Whamcloud - gitweb
1532078ed5f9e9f003627ef4ed7c96ea41d42ffa
[fs/lustre-release.git] / lustre / utils / liblustreapi.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/utils/liblustreapi.c
37  *
38  * Author: Peter J. Braam <braam@clusterfs.com>
39  * Author: Phil Schwan <phil@clusterfs.com>
40  * Author: Robert Read <rread@clusterfs.com>
41  */
42
43 /* for O_DIRECTORY */
44 #ifndef _GNU_SOURCE
45 #define _GNU_SOURCE
46 #endif
47
48 #include <stdlib.h>
49 #include <stdio.h>
50 #include <string.h>
51 #include <stddef.h>
52 #include <sys/ioctl.h>
53 #include <unistd.h>
54 #include <fcntl.h>
55 #include <errno.h>
56 #include <dirent.h>
57 #include <stdarg.h>
58 #include <sys/stat.h>
59 #include <sys/types.h>
60 #include <sys/syscall.h>
61 #include <fnmatch.h>
62 #include <glob.h>
63 #ifdef HAVE_LINUX_UNISTD_H
64 #include <linux/unistd.h>
65 #else
66 #include <unistd.h>
67 #endif
68 #include <poll.h>
69
70 #include <liblustre.h>
71 #include <lnet/lnetctl.h>
72 #include <obd.h>
73 #include <lustre_lib.h>
74 #include <obd_lov.h>
75 #include <lustre/liblustreapi.h>
76
77 static unsigned llapi_dir_filetype_table[] = {
78         [DT_UNKNOWN]= 0,
79         [DT_FIFO]= S_IFIFO,
80         [DT_CHR] = S_IFCHR,
81         [DT_DIR] = S_IFDIR,
82         [DT_BLK] = S_IFBLK,
83         [DT_REG] = S_IFREG,
84         [DT_LNK] = S_IFLNK,
85         [DT_SOCK]= S_IFSOCK,
86 #if defined(DT_DOOR) && defined(S_IFDOOR)
87         [DT_DOOR]= S_IFDOOR,
88 #endif
89 };
90
91 #if defined(DT_DOOR) && defined(S_IFDOOR)
92 static const int DT_MAX = DT_DOOR;
93 #else
94 static const int DT_MAX = DT_SOCK;
95 #endif
96
97 static unsigned llapi_filetype_dir_table[] = {
98         [0]= DT_UNKNOWN,
99         [S_IFIFO]= DT_FIFO,
100         [S_IFCHR] = DT_CHR,
101         [S_IFDIR] = DT_DIR,
102         [S_IFBLK] = DT_BLK,
103         [S_IFREG] = DT_REG,
104         [S_IFLNK] = DT_LNK,
105         [S_IFSOCK]= DT_SOCK,
106 #if defined(DT_DOOR) && defined(S_IFDOOR)
107         [S_IFDOOR]= DT_DOOR,
108 #endif
109 };
110
111 #if defined(DT_DOOR) && defined(S_IFDOOR)
112 static const int S_IFMAX = DT_DOOR;
113 #else
114 static const int S_IFMAX = DT_SOCK;
115 #endif
116
117 /* liblustreapi message level */
118 static int llapi_msg_level = LLAPI_MSG_MAX;
119
120 void llapi_msg_set_level(int level)
121 {
122         /* ensure level is in the good range */
123         if (level < LLAPI_MSG_OFF)
124                 llapi_msg_level = LLAPI_MSG_OFF;
125         else if (level > LLAPI_MSG_MAX)
126                 llapi_msg_level = LLAPI_MSG_MAX;
127         else
128                 llapi_msg_level = level;
129 }
130
131 void llapi_err(int level, char *fmt, ...)
132 {
133         va_list args;
134         int tmp_errno = abs(errno);
135
136         if ((level & LLAPI_MSG_MASK) > llapi_msg_level)
137                 return;
138
139         va_start(args, fmt);
140         vfprintf(stderr, fmt, args);
141         va_end(args);
142
143         if (level & LLAPI_MSG_NO_ERRNO)
144                 fprintf(stderr, "\n");
145         else
146                 fprintf(stderr, ": %s (%d)\n", strerror(tmp_errno), tmp_errno);
147 }
148
149 #define llapi_err_noerrno(level, fmt, a...)                             \
150         llapi_err((level) | LLAPI_MSG_NO_ERRNO, fmt, ## a)
151
152 void llapi_printf(int level, char *fmt, ...)
153 {
154         va_list args;
155
156         if ((level & LLAPI_MSG_MASK) > llapi_msg_level)
157                 return;
158
159         va_start(args, fmt);
160         vfprintf(stdout, fmt, args);
161         va_end(args);
162 }
163
164 /**
165  * size_units is unchanged if no specifier used
166  */
167 int parse_size(char *optarg, unsigned long long *size,
168                unsigned long long *size_units, int bytes_spec)
169 {
170         char *end;
171
172         *size = strtoull(optarg, &end, 0);
173
174         if (*end != '\0') {
175                 if ((*end == 'b') && *(end+1) == '\0' &&
176                     (*size & (~0ULL << (64 - 9))) == 0 &&
177                     !bytes_spec) {
178                         *size <<= 9;
179                         *size_units = 1 << 9;
180                 } else if ((*end == 'b') && *(end+1) == '\0' &&
181                            bytes_spec) {
182                         *size_units = 1;
183                 } else if ((*end == 'k' || *end == 'K') &&
184                            *(end+1) == '\0' && (*size &
185                            (~0ULL << (64 - 10))) == 0) {
186                         *size <<= 10;
187                         *size_units = 1 << 10;
188                 } else if ((*end == 'm' || *end == 'M') &&
189                            *(end+1) == '\0' && (*size &
190                            (~0ULL << (64 - 20))) == 0) {
191                         *size <<= 20;
192                         *size_units = 1 << 20;
193                 } else if ((*end == 'g' || *end == 'G') &&
194                            *(end+1) == '\0' && (*size &
195                            (~0ULL << (64 - 30))) == 0) {
196                         *size <<= 30;
197                         *size_units = 1 << 30;
198                 } else if ((*end == 't' || *end == 'T') &&
199                            *(end+1) == '\0' && (*size &
200                            (~0ULL << (64 - 40))) == 0) {
201                         *size <<= 40;
202                         *size_units = 1ULL << 40;
203                 } else if ((*end == 'p' || *end == 'P') &&
204                            *(end+1) == '\0' && (*size &
205                            (~0ULL << (64 - 50))) == 0) {
206                         *size <<= 50;
207                         *size_units = 1ULL << 50;
208                 } else if ((*end == 'e' || *end == 'E') &&
209                            *(end+1) == '\0' && (*size &
210                            (~0ULL << (64 - 60))) == 0) {
211                         *size <<= 60;
212                         *size_units = 1ULL << 60;
213                 } else {
214                         return -1;
215                 }
216         }
217
218         return 0;
219 }
220
221 int llapi_stripe_limit_check(unsigned long long stripe_size, int stripe_offset,
222                              int stripe_count, int stripe_pattern)
223 {
224         int page_size;
225
226         /* 64 KB is the largest common page size I'm aware of (on ia64), but
227          * check the local page size just in case. */
228         page_size = LOV_MIN_STRIPE_SIZE;
229         if (getpagesize() > page_size) {
230                 page_size = getpagesize();
231                 llapi_err_noerrno(LLAPI_MSG_WARN,
232                                   "warning: your page size (%u) is "
233                                   "larger than expected (%u)", page_size,
234                                   LOV_MIN_STRIPE_SIZE);
235         }
236         if (stripe_size < 0 || (stripe_size & (LOV_MIN_STRIPE_SIZE - 1))) {
237                 llapi_err(LLAPI_MSG_ERROR, "error: bad stripe_size %lu, "
238                           "must be an even multiple of %d bytes",
239                           stripe_size, page_size);
240                 return -EINVAL;
241         }
242         if (stripe_offset < -1 || stripe_offset > MAX_OBD_DEVICES) {
243                 errno = -EINVAL;
244                 llapi_err(LLAPI_MSG_ERROR, "error: bad stripe offset %d",
245                           stripe_offset);
246                 return -EINVAL;
247         }
248         if (stripe_count < -1 || stripe_count > LOV_MAX_STRIPE_COUNT) {
249                 errno = -EINVAL;
250                 llapi_err(LLAPI_MSG_ERROR, "error: bad stripe count %d",
251                           stripe_count);
252                 return -EINVAL;
253         }
254         if (stripe_size >= (1ULL << 32)){
255                 errno = -EINVAL;
256                 llapi_err(LLAPI_MSG_ERROR, "warning: stripe size larger than 4G"
257                           " is not currently supported and would wrap");
258                 return -EINVAL;
259         }
260         return 0;
261 }
262
263 static int poolpath(char *fsname, char *pathname, char *pool_pathname);
264
265 int llapi_file_open_pool(const char *name, int flags, int mode,
266                          unsigned long long stripe_size, int stripe_offset,
267                          int stripe_count, int stripe_pattern, char *pool_name)
268 {
269         struct lov_user_md_v3 lum = { 0 };
270         int fd, rc = 0;
271         int isdir = 0;
272         char fsname[MAX_OBD_NAME + 1], *ptr;
273
274         fd = open(name, flags | O_LOV_DELAY_CREATE, mode);
275         if (fd < 0 && errno == EISDIR) {
276                 fd = open(name, O_DIRECTORY | O_RDONLY);
277                 isdir++;
278         }
279
280         if (fd < 0) {
281                 rc = -errno;
282                 llapi_err(LLAPI_MSG_ERROR, "unable to open '%s'", name);
283                 return rc;
284         }
285
286         if ((rc = llapi_stripe_limit_check(stripe_size, stripe_offset,
287                                            stripe_count, stripe_pattern)) != 0){
288                 errno = rc;
289                 goto out;
290         }
291
292         /*  Initialize IOCTL striping pattern structure */
293         lum.lmm_magic = LOV_USER_MAGIC_V3;
294         lum.lmm_pattern = stripe_pattern;
295         lum.lmm_stripe_size = stripe_size;
296         lum.lmm_stripe_count = stripe_count;
297         lum.lmm_stripe_offset = stripe_offset;
298
299         /* in case user give the full pool name <fsname>.<poolname>, skip
300          * the fsname */
301         if (pool_name != NULL) {
302                 ptr = strchr(pool_name, '.');
303                 if (ptr != NULL) {
304                         strncpy(fsname, pool_name, ptr - pool_name);
305                         *ptr = '\0';
306                         /* if fsname matches a filesystem skip it
307                          * if not keep the poolname as is */
308                         if (poolpath(fsname, NULL, NULL) == 0)
309                                 pool_name = ptr + 1;
310                 }
311                 strncpy(lum.lmm_pool_name, pool_name, LOV_MAXPOOLNAME);
312         } else {
313                 /* If no pool is specified at all, use V1 request */
314                 lum.lmm_magic = LOV_USER_MAGIC_V1;
315         }
316
317         if (ioctl(fd, LL_IOC_LOV_SETSTRIPE, &lum)) {
318                 char *errmsg = "stripe already set";
319                 rc = -errno;
320                 if (errno != EEXIST && errno != EALREADY)
321                         errmsg = strerror(errno);
322
323                 llapi_err_noerrno(LLAPI_MSG_ERROR,
324                                   "error on ioctl "LPX64" for '%s' (%d): %s",
325                                   (__u64)LL_IOC_LOV_SETSTRIPE, name, fd,errmsg);
326         }
327 out:
328         if (rc) {
329                 close(fd);
330                 fd = rc;
331         }
332
333         return fd;
334 }
335
336 int llapi_file_open(const char *name, int flags, int mode,
337                     unsigned long long stripe_size, int stripe_offset,
338                     int stripe_count, int stripe_pattern)
339 {
340         return llapi_file_open_pool(name, flags, mode, stripe_size,
341                                     stripe_offset, stripe_count,
342                                     stripe_pattern, NULL);
343 }
344
345 int llapi_file_create(const char *name, unsigned long long stripe_size,
346                       int stripe_offset, int stripe_count, int stripe_pattern)
347 {
348         int fd;
349
350         fd = llapi_file_open_pool(name, O_CREAT | O_WRONLY, 0644, stripe_size,
351                                   stripe_offset, stripe_count, stripe_pattern,
352                                   NULL);
353         if (fd < 0)
354                 return fd;
355
356         close(fd);
357         return 0;
358 }
359
360 int llapi_file_create_pool(const char *name, unsigned long long stripe_size,
361                            int stripe_offset, int stripe_count,
362                            int stripe_pattern, char *pool_name)
363 {
364         int fd;
365
366         fd = llapi_file_open_pool(name, O_CREAT | O_WRONLY, 0644, stripe_size,
367                                   stripe_offset, stripe_count, stripe_pattern,
368                                   pool_name);
369         if (fd < 0)
370                 return fd;
371
372         close(fd);
373         return 0;
374 }
375
376 /*
377  * Find the fsname, the full path, and/or an open fd.
378  * Either the fsname or path must not be NULL
379  */
380 #define WANT_PATH   0x1
381 #define WANT_FSNAME 0x2
382 #define WANT_FD     0x4
383 #define WANT_INDEX  0x8
384 #define WANT_ERROR  0x10
385 static int get_root_path(int want, char *fsname, int *outfd, char *path,
386                          int index)
387 {
388         struct mntent mnt;
389         char buf[PATH_MAX], mntdir[PATH_MAX];
390         char *name = NULL, *ptr;
391         FILE *fp;
392         int idx = 0, len = 0, mntlen, fd;
393         int rc = -ENODEV;
394
395         /* get the mount point */
396         fp = setmntent(MOUNTED, "r");
397         if (fp == NULL) {
398                  llapi_err(LLAPI_MSG_ERROR,
399                            "setmntent(%s) failed: %s:", MOUNTED,
400                            strerror (errno));
401                  return -EIO;
402         }
403         while (1) {
404                 if (getmntent_r(fp, &mnt, buf, sizeof(buf)) == NULL)
405                         break;
406
407                 if (!llapi_is_lustre_mnt(&mnt))
408                         continue;
409
410                 mntlen = strlen(mnt.mnt_dir);
411                 ptr = strrchr(mnt.mnt_fsname, '/');
412                 if (!ptr && !len) {
413                         rc = -EINVAL;
414                         break;
415                 }
416                 ptr++;
417
418                 if ((want & WANT_INDEX) && (idx++ != index))
419                         continue; 
420
421                 /* Check the fsname for a match */
422                 if (!(want & WANT_FSNAME) && fsname != NULL &&
423                     (strlen(fsname) > 0) && (strcmp(ptr, fsname) != 0))
424                         continue;
425
426                 /* If the path isn't set return the first one we find */
427                 if (path == NULL || strlen(path) == 0) {
428                         strcpy(mntdir, mnt.mnt_dir);
429                         name = ptr;
430                         rc = 0;
431                         break;
432                 /* Otherwise find the longest matching path */
433                 } else if ((strlen(path) >= mntlen) && (mntlen >= len) &&
434                            (strncmp(mnt.mnt_dir, path, mntlen) == 0)) { 
435                         strcpy(mntdir, mnt.mnt_dir);
436                         mntlen = len;
437                         name = ptr;
438                         rc = 0;
439                 }
440         }
441         endmntent(fp);
442
443         /* Found it */
444         if (rc == 0) {
445                 if ((want & WANT_FSNAME) && fsname != NULL)
446                         strcpy(fsname, name);
447                 if ((want & WANT_PATH) && path != NULL)
448                         strcpy(path, mntdir);
449                 if (want & WANT_FD) {
450                         fd = open(mntdir, O_RDONLY | O_DIRECTORY | O_NONBLOCK);
451                         if (fd < 0) {
452                                 perror("open");
453                                 rc = -errno;
454                         } else {
455                                 *outfd = fd;
456                         }
457                 }
458         } else if (want & WANT_ERROR)
459                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
460                           "can't find fs root for '%s': %d",
461                           (want & WANT_PATH) ? fsname : path, rc);
462         return rc;
463 }
464
465 /*
466  * search lustre mounts
467  *
468  * Calling this function will return to the user the mount point, mntdir, and
469  * the file system name, fsname, if the user passed a buffer to this routine.
470  *
471  * The user inputs are pathname and index. If the pathname is supplied then
472  * the value of the index will be ignored. The pathname will return data if
473  * the pathname is located on a lustre mount. Index is used to pick which
474  * mount point you want in the case of multiple mounted lustre file systems.
475  * See function lfs_osts in lfs.c for a example of the index use.
476  */
477 int llapi_search_mounts(const char *pathname, int index, char *mntdir,
478                         char *fsname)
479 {
480         int want = WANT_PATH, idx = -1;
481
482         if (!pathname) {
483                 want |= WANT_INDEX;
484                 idx = index;
485         } else
486                 strcpy(mntdir, pathname);
487
488         if (fsname)
489                 want |= WANT_FSNAME;
490         return get_root_path(want, fsname, NULL, mntdir, idx);
491 }
492
493 int llapi_search_fsname(const char *pathname, char *fsname)
494 {
495         return get_root_path(WANT_FSNAME | WANT_ERROR, fsname, NULL,
496                              (char *)pathname, -1);
497 }
498
499 /* return the first file matching this pattern */
500 static int first_match(char *pattern, char *buffer)
501 {
502         glob_t glob_info;
503
504         if (glob(pattern, GLOB_BRACE, NULL, &glob_info))
505                 return -ENOENT;
506
507         if (glob_info.gl_pathc < 1) {
508                 globfree(&glob_info);
509                 return -ENOENT;
510         }
511
512         strcpy(buffer, glob_info.gl_pathv[0]);
513
514         globfree(&glob_info);
515         return 0;
516 }
517
518 /*
519  * find the pool directory path under /proc
520  * (can be also used to test if a fsname is known)
521  */
522 static int poolpath(char *fsname, char *pathname, char *pool_pathname)
523 {
524         int rc = 0;
525         char pattern[PATH_MAX + 1];
526         char buffer[PATH_MAX];
527
528         if (fsname == NULL) {
529                 rc = llapi_search_fsname(pathname, buffer);
530                 if (rc != 0)
531                         return rc;
532                 fsname = buffer;
533                 strcpy(pathname, fsname);
534         }
535
536         snprintf(pattern, PATH_MAX, "/proc/fs/lustre/lov/%s-*/pools", fsname);
537         rc = first_match(pattern, buffer);
538         if (rc)
539                 return rc;
540
541         /* in fsname test mode, pool_pathname is NULL */
542         if (pool_pathname != NULL)
543                 strcpy(pool_pathname, buffer);
544
545         return 0;
546 }
547
548 /**
549  * Get the list of pool members.
550  * \param poolname    string of format <fsname>.<poolname>
551  * \param members     caller-allocated array of char*
552  * \param list_size   size of the members array
553  * \param buffer      caller-allocated buffer for storing OST names
554  * \param buffer_size size of the buffer
555  *
556  * \return number of members retrieved for this pool
557  * \retval -error failure
558  */
559 int llapi_get_poolmembers(const char *poolname, char **members,
560                           int list_size, char *buffer, int buffer_size)
561 {
562         char fsname[PATH_MAX + 1];
563         char *pool, *tmp;
564         char pathname[PATH_MAX + 1];
565         char path[PATH_MAX + 1];
566         char buf[1024];
567         FILE *fd;
568         int rc = 0;
569         int nb_entries = 0;
570         int used = 0;
571
572         /* name is FSNAME.POOLNAME */
573         if (strlen(poolname) > PATH_MAX)
574                 return -EOVERFLOW;
575         strcpy(fsname, poolname);
576         pool = strchr(fsname, '.');
577         if (pool == NULL)
578                 return -EINVAL;
579
580         *pool = '\0';
581         pool++;
582
583         rc = poolpath(fsname, NULL, pathname);
584         if (rc != 0) {
585                 errno = -rc;
586                 llapi_err(LLAPI_MSG_ERROR, "Lustre filesystem '%s' not found",
587                           fsname);
588                 return rc;
589         }
590
591         llapi_printf(LLAPI_MSG_NORMAL, "Pool: %s.%s\n", fsname, pool);
592         sprintf(path, "%s/%s", pathname, pool);
593         if ((fd = fopen(path, "r")) == NULL) {
594                 llapi_err(LLAPI_MSG_ERROR, "Cannot open %s", path);
595                 return -EINVAL;
596         }
597
598         rc = 0;
599         while (fgets(buf, sizeof(buf), fd) != NULL) {
600                 if (nb_entries >= list_size) {
601                         rc = -EOVERFLOW;
602                         break;
603                 }
604                 /* remove '\n' */
605                 if ((tmp = strchr(buf, '\n')) != NULL)
606                         *tmp='\0';
607                 if (used + strlen(buf) + 1 > buffer_size) {
608                         rc = -EOVERFLOW;
609                         break;
610                 }
611
612                 strcpy(buffer + used, buf);
613                 members[nb_entries] = buffer + used;
614                 used += strlen(buf) + 1;
615                 nb_entries++;
616                 rc = nb_entries;
617         }
618
619         fclose(fd);
620         return rc;
621 }
622
623 /**
624  * Get the list of pools in a filesystem.
625  * \param name        filesystem name or path
626  * \param poollist    caller-allocated array of char*
627  * \param list_size   size of the poollist array
628  * \param buffer      caller-allocated buffer for storing pool names
629  * \param buffer_size size of the buffer
630  *
631  * \return number of pools retrieved for this filesystem
632  * \retval -error failure
633  */
634 int llapi_get_poollist(const char *name, char **poollist, int list_size,
635                        char *buffer, int buffer_size)
636 {
637         char fsname[PATH_MAX + 1], rname[PATH_MAX + 1], pathname[PATH_MAX + 1];
638         char *ptr;
639         DIR *dir;
640         struct dirent pool;
641         struct dirent *cookie = NULL;
642         int rc = 0;
643         unsigned int nb_entries = 0;
644         unsigned int used = 0;
645         unsigned int i;
646
647         /* initilize output array */
648         for (i = 0; i < list_size; i++)
649                 poollist[i] = NULL;
650
651         /* is name a pathname ? */
652         ptr = strchr(name, '/');
653         if (ptr != NULL) {
654                 /* only absolute pathname is supported */
655                 if (*name != '/')
656                         return -EINVAL;
657                 if (!realpath(name, rname)) {
658                         rc = -errno;
659                         llapi_err(LLAPI_MSG_ERROR, "invalid path '%s'", name);
660                         return rc;
661                 }
662
663                 rc = poolpath(NULL, rname, pathname);
664                 if (rc != 0) {
665                         errno = -rc;
666                         llapi_err(LLAPI_MSG_ERROR, "'%s' is not"
667                                   " a Lustre filesystem", name);
668                         return rc;
669                 }
670                 strcpy(fsname, rname);
671         } else {
672                 /* name is FSNAME */
673                 strcpy(fsname, name);
674                 rc = poolpath(fsname, NULL, pathname);
675         }
676         if (rc != 0) {
677                 errno = -rc;
678                 llapi_err(LLAPI_MSG_ERROR, "Lustre filesystem '%s' not found",
679                           name);
680                 return rc;
681         }
682
683         llapi_printf(LLAPI_MSG_NORMAL, "Pools from %s:\n", fsname);
684         if ((dir = opendir(pathname)) == NULL) {
685                 llapi_err(LLAPI_MSG_ERROR, "Could not open pool list for '%s'",
686                           name);
687                 return -errno;
688         }
689
690         while(1) {
691                 rc = readdir_r(dir, &pool, &cookie);
692
693                 if (rc != 0) {
694                         llapi_err(LLAPI_MSG_ERROR,
695                                   "Error reading pool list for '%s'", name);
696                         return -errno;
697                 } else if ((rc == 0) && (cookie == NULL))
698                         /* end of directory */
699                         break;
700
701                 /* ignore . and .. */
702                 if (!strcmp(pool.d_name, ".") || !strcmp(pool.d_name, ".."))
703                         continue;
704
705                 /* check output bounds */
706                 if (nb_entries >= list_size)
707                         return -EOVERFLOW;
708
709                 /* +2 for '.' and final '\0' */
710                 if (used + strlen(pool.d_name) + strlen(fsname) + 2
711                     > buffer_size)
712                         return -EOVERFLOW;
713
714                 sprintf(buffer + used, "%s.%s", fsname, pool.d_name);
715                 poollist[nb_entries] = buffer + used;
716                 used += strlen(pool.d_name) + strlen(fsname) + 2;
717                 nb_entries++;
718         }
719
720         closedir(dir);
721         return nb_entries;
722 }
723
724 /* wrapper for lfs.c and obd.c */
725 int llapi_poollist(const char *name)
726 {
727         /* list of pool names (assume that pool count is smaller
728            than OST count) */
729         char *list[FIND_MAX_OSTS];
730         char *buffer;
731         /* fsname-OST0000_UUID < 32 char, 1 per OST */
732         int bufsize = FIND_MAX_OSTS * 32;
733         int i, nb;
734
735         buffer = malloc(bufsize);
736         if (buffer == NULL)
737                 return -ENOMEM;
738
739         if ((name[0] == '/') || (strchr(name, '.') == NULL))
740                 /* name is a path or fsname */
741                 nb = llapi_get_poollist(name, list, FIND_MAX_OSTS, buffer,
742                                         bufsize);
743         else
744                 /* name is a pool name (<fsname>.<poolname>) */
745                 nb = llapi_get_poolmembers(name, list, FIND_MAX_OSTS, buffer,
746                                            bufsize);
747
748         for (i = 0; i < nb; i++)
749                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", list[i]);
750
751         free(buffer);
752         return (nb < 0 ? nb : 0);
753 }
754
755
756 typedef int (semantic_func_t)(char *path, DIR *parent, DIR *d,
757                               void *data, cfs_dirent_t *de);
758
759 #define MAX_LOV_UUID_COUNT      max(LOV_MAX_STRIPE_COUNT, 1000)
760 #define OBD_NOT_FOUND           (-1)
761
762 static int common_param_init(struct find_param *param)
763 {
764         param->lumlen = lov_mds_md_size(MAX_LOV_UUID_COUNT, LOV_MAGIC_V3);
765         if ((param->lmd = malloc(sizeof(lstat_t) + param->lumlen)) == NULL) {
766                 llapi_err(LLAPI_MSG_ERROR,
767                           "error: allocation of %d bytes for ioctl",
768                           sizeof(lstat_t) + param->lumlen);
769                 return -ENOMEM;
770         }
771
772         param->got_uuids = 0;
773         param->obdindexes = NULL;
774         param->obdindex = OBD_NOT_FOUND;
775         return 0;
776 }
777
778 static void find_param_fini(struct find_param *param)
779 {
780         if (param->obdindexes)
781                 free(param->obdindexes);
782
783         if (param->lmd)
784                 free(param->lmd);
785 }
786
787 int llapi_file_fget_lov_uuid(int fd, struct obd_uuid *lov_name)
788 {
789         int rc = ioctl(fd, OBD_IOC_GETNAME, lov_name);
790         if (rc) {
791                 rc = errno;
792                 llapi_err(LLAPI_MSG_ERROR, "error: can't get lov name.");
793         }
794         return rc;
795 }
796
797 int llapi_file_get_lov_uuid(const char *path, struct obd_uuid *lov_uuid)
798 {
799         int fd, rc;
800
801         fd = open(path, O_RDONLY);
802         if (fd < 0) {
803                 rc = errno;
804                 llapi_err(LLAPI_MSG_ERROR, "error opening %s", path);
805                 return rc;
806         }
807
808         rc = llapi_file_fget_lov_uuid(fd, lov_uuid);
809
810         close(fd);
811
812         return rc;
813 }
814
815 /*
816  * If uuidp is NULL, return the number of available obd uuids.
817  * If uuidp is non-NULL, then it will return the uuids of the obds. If
818  * there are more OSTs then allocated to uuidp, then an error is returned with
819  * the ost_count set to number of available obd uuids.
820  */
821 int llapi_lov_get_uuids(int fd, struct obd_uuid *uuidp, int *ost_count)
822 {
823         struct obd_uuid lov_name;
824         char buf[1024];
825         FILE *fp;
826         int rc = 0, index = 0;
827
828         /* Get the lov name */
829         rc = llapi_file_fget_lov_uuid(fd, &lov_name);
830         if (rc)
831                 return rc;
832
833         /* Now get the ost uuids from /proc */
834         snprintf(buf, sizeof(buf), "/proc/fs/lustre/lov/%s/target_obd",
835                  lov_name.uuid);
836         fp = fopen(buf, "r");
837         if (fp == NULL) {
838                 rc = errno;
839                 llapi_err(LLAPI_MSG_ERROR, "error: opening '%s'", buf);
840                 return rc;
841         }
842
843         while (fgets(buf, sizeof(buf), fp) != NULL) {
844                 if (uuidp && (index < *ost_count)) {
845                         if (sscanf(buf, "%d: %s", &index, uuidp[index].uuid) <2)
846                                 break;
847                 }
848                 index++;
849         }
850
851         fclose(fp);
852
853         if (uuidp && (index >= *ost_count))
854                 return -EOVERFLOW;
855
856         *ost_count = index;
857         return rc;
858 }
859
860 int llapi_get_obd_count(char *mnt, int *count, int is_mdt)
861 {
862         DIR *root;
863         int rc;
864
865         root = opendir(mnt);
866         if (!root) {
867                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
868                 return -1;
869         }
870
871         *count = is_mdt;
872         rc = ioctl(dirfd(root), LL_IOC_GETOBDCOUNT, count);
873
874         closedir(root);
875         return rc;
876 }
877
878 /* Here, param->obduuid points to a single obduuid, the index of which is
879  * returned in param->obdindex */
880 static int setup_obd_uuid(DIR *dir, char *dname, struct find_param *param)
881 {
882         struct obd_uuid lov_uuid;
883         char uuid[sizeof(struct obd_uuid)];
884         char buf[1024];
885         FILE *fp;
886         int rc = 0, index;
887
888         /* Get the lov name */
889         rc = llapi_file_fget_lov_uuid(dirfd(dir), &lov_uuid);
890         if (rc) {
891                 if (errno != ENOTTY) {
892                         rc = errno;
893                         llapi_err(LLAPI_MSG_ERROR,
894                                   "error: can't get lov name: %s", dname);
895                 } else {
896                         rc = 0;
897                 }
898                 return rc;
899         }
900
901         param->got_uuids = 1;
902
903         /* Now get the ost uuids from /proc */
904         snprintf(buf, sizeof(buf), "/proc/fs/lustre/lov/%s/target_obd",
905                  lov_uuid.uuid);
906         fp = fopen(buf, "r");
907         if (fp == NULL) {
908                 rc = errno;
909                 llapi_err(LLAPI_MSG_ERROR, "error: opening '%s'", buf);
910                 return rc;
911         }
912
913         if (!param->obduuid && !param->quiet && !param->obds_printed)
914                 llapi_printf(LLAPI_MSG_NORMAL, "OBDS:\n");
915
916         while (fgets(buf, sizeof(buf), fp) != NULL) {
917                 if (sscanf(buf, "%d: %s", &index, uuid) < 2)
918                         break;
919
920                 if (param->obduuid) {
921                         if (strncmp(param->obduuid->uuid, uuid,
922                                     sizeof(uuid)) == 0) {
923                                 param->obdindex = index;
924                                 break;
925                         }
926                 } else if (!param->quiet && !param->obds_printed) {
927                         /* Print everything */
928                         llapi_printf(LLAPI_MSG_NORMAL, "%s", buf);
929                 }
930         }
931         param->obds_printed = 1;
932
933         fclose(fp);
934
935         if (!param->quiet && param->obduuid &&
936             (param->obdindex == OBD_NOT_FOUND)) {
937                 llapi_err_noerrno(LLAPI_MSG_ERROR,
938                                   "error: %s: unknown obduuid: %s",
939                                   __FUNCTION__, param->obduuid->uuid);
940                 //rc = EINVAL;
941         }
942
943         return (rc);
944 }
945
946 /* In this case, param->obduuid will be an array of obduuids and
947  * obd index for all these obduuids will be returned in
948  * param->obdindexes */
949 static int setup_obd_indexes(DIR *dir, struct find_param *param)
950 {
951         struct obd_uuid *uuids = NULL;
952         int obdcount = INIT_ALLOC_NUM_OSTS;
953         int ret, obd_valid = 0, obdnum, i;
954
955         uuids = (struct obd_uuid *)malloc(INIT_ALLOC_NUM_OSTS *
956                                           sizeof(struct obd_uuid));
957         if (uuids == NULL)
958                 return -ENOMEM;
959
960 retry_get_uuids:
961         ret = llapi_lov_get_uuids(dirfd(dir), uuids,
962                                   &obdcount);
963         if (ret) {
964                 struct obd_uuid *uuids_temp;
965
966                 if (ret == -EOVERFLOW) {
967                         uuids_temp = realloc(uuids, obdcount *
968                                              sizeof(struct obd_uuid));
969                         if (uuids_temp != NULL)
970                                 goto retry_get_uuids;
971                         else
972                                 ret = -ENOMEM;
973                 }
974
975                 llapi_err(LLAPI_MSG_ERROR, "get ost uuid failed");
976                 return ret;
977         }
978
979         param->obdindexes = malloc(param->num_obds * sizeof(param->obdindex));
980         if (param->obdindexes == NULL)
981                 return -ENOMEM;
982
983         for (obdnum = 0; obdnum < param->num_obds; obdnum++) {
984                 for (i = 0; i <= obdcount; i++) {
985                         if (strcmp((char *)&param->obduuid[obdnum].uuid,
986                                    (char *)&uuids[i]) == 0) {
987                                 param->obdindexes[obdnum] = i;
988                                 obd_valid++;
989                                 break;
990                         }
991                 }
992                 if (i == obdcount)
993                         param->obdindexes[obdnum] = OBD_NOT_FOUND;
994         }
995
996         if (obd_valid == 0)
997                 param->obdindex = OBD_NOT_FOUND;
998         else
999                 param->obdindex = obd_valid;
1000
1001         param->got_uuids = 1;
1002
1003         return 0;
1004 }
1005
1006 static void lov_dump_user_lmm_header(struct lov_user_md *lum, char *path,
1007                                      int is_dir, int verbose, int quiet,
1008                                      char *pool_name)
1009 {
1010         char *prefix = is_dir ? "" : "lmm_";
1011         char nl = is_dir ? ' ' : '\n';
1012
1013         if (verbose && path)
1014                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
1015
1016         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
1017                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_magic:          0x%08X\n",
1018                              lum->lmm_magic);
1019                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_gr:      "LPX64"\n",
1020                              lum->lmm_object_gr);
1021                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_id:      "LPX64"\n",
1022                              lum->lmm_object_id);
1023         }
1024
1025         if (verbose & VERBOSE_COUNT) {
1026                 if (!quiet)
1027                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_count:   ",
1028                                      prefix);
1029                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
1030                              (int)lum->lmm_stripe_count, nl);
1031         }
1032
1033         if (verbose & VERBOSE_SIZE) {
1034                 if (!quiet)
1035                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_size:    ",
1036                                      prefix);
1037                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c", lum->lmm_stripe_size,
1038                              nl);
1039         }
1040
1041         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
1042                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_stripe_pattern: %x%c",
1043                              lum->lmm_pattern, nl);
1044         }
1045
1046         if (verbose & VERBOSE_OFFSET) {
1047                 if (!quiet)
1048                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_offset:   ",
1049                                      prefix);
1050                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
1051                              lum->lmm_objects[0].l_ost_idx, nl);
1052         }
1053
1054         if ((verbose & VERBOSE_POOL) && (pool_name != NULL))
1055                 llapi_printf(LLAPI_MSG_NORMAL, "pool: %s%c", pool_name, nl);
1056
1057         if (is_dir)
1058                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1059 }
1060
1061 void lov_dump_user_lmm_v1v3(struct lov_user_md *lum, char *pool_name,
1062                             struct lov_user_ost_data_v1 *objects,
1063                             char *path, int is_dir,
1064                             int obdindex, int quiet, int header, int body)
1065 {
1066         int i, obdstripe = 0;
1067
1068         if (obdindex != OBD_NOT_FOUND) {
1069                 for (i = 0; !is_dir && i < lum->lmm_stripe_count; i++) {
1070                         if (obdindex == objects[i].l_ost_idx) {
1071                                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
1072                                 obdstripe = 1;
1073                                 break;
1074                         }
1075                 }
1076         } else {
1077                 if (!quiet)
1078                         llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
1079                 obdstripe = 1;
1080         }
1081
1082         /* if it's a directory */
1083         if (is_dir) {
1084                 if (obdstripe == 1) {
1085                         if (lum->lmm_object_gr == LOV_OBJECT_GROUP_DEFAULT) {
1086                                 llapi_printf(LLAPI_MSG_NORMAL, "(Default) ");
1087                                 lum->lmm_object_gr = LOV_OBJECT_GROUP_CLEAR;
1088                         }
1089                         /* maintain original behavior */
1090                         if (!header)
1091                                 header |= VERBOSE_ALL;
1092                         lov_dump_user_lmm_header(lum, path, is_dir, header,
1093                                                  quiet, pool_name);
1094                 }
1095                 return;
1096         }
1097
1098         if (header && (obdstripe == 1))
1099                 lov_dump_user_lmm_header(lum, NULL, is_dir, header, quiet,
1100                                          pool_name);
1101
1102         if (body) {
1103                 if ((!quiet) && (obdstripe == 1))
1104                         llapi_printf(LLAPI_MSG_NORMAL,
1105                                      "\tobdidx\t\t objid\t\tobjid\t\t group\n");
1106
1107                 for (i = 0; i < lum->lmm_stripe_count; i++) {
1108                         int idx = objects[i].l_ost_idx;
1109                         long long oid = objects[i].l_object_id;
1110                         long long gr = objects[i].l_object_gr;
1111                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
1112                                 llapi_printf(LLAPI_MSG_NORMAL,
1113                                            "\t%6u\t%14llu\t%#13llx\t%14llu%s\n",
1114                                            idx, oid, oid, gr,
1115                                            obdindex == idx ? " *" : "");
1116                 }
1117                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1118         }
1119 }
1120
1121 void lov_dump_user_lmm_join(struct lov_user_md_v1 *lum, char *path,
1122                             int is_dir, int obdindex, int quiet,
1123                             int header, int body)
1124 {
1125         struct lov_user_md_join *lumj = (struct lov_user_md_join *)lum;
1126         int i, obdstripe = 0;
1127
1128         if (obdindex != OBD_NOT_FOUND) {
1129                 for (i = 0; i < lumj->lmm_stripe_count; i++) {
1130                         if (obdindex == lumj->lmm_objects[i].l_ost_idx) {
1131                                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
1132                                 obdstripe = 1;
1133                                 break;
1134                         }
1135                 }
1136         } else {
1137                 if (!quiet)
1138                         llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
1139                 obdstripe = 1;
1140         }
1141
1142         if (header && obdstripe == 1) {
1143                 lov_dump_user_lmm_header(lum, NULL, 0, header, quiet, NULL);
1144
1145                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_extent_count:   %x\n",
1146                              lumj->lmm_extent_count);
1147         }
1148
1149         if (body) {
1150                 unsigned long long start = -1, end = 0;
1151                 if (!quiet && obdstripe == 1)
1152                         llapi_printf(LLAPI_MSG_NORMAL,
1153                                      "joined\tobdidx\t\t objid\t\tobjid\t\t "
1154                                      "group\t\tstart\t\tend\n");
1155                 for (i = 0; i < lumj->lmm_stripe_count; i++) {
1156                         int idx = lumj->lmm_objects[i].l_ost_idx;
1157                         long long oid = lumj->lmm_objects[i].l_object_id;
1158                         long long gr = lumj->lmm_objects[i].l_object_gr;
1159                         if (obdindex == OBD_NOT_FOUND || obdindex == idx)
1160                                 llapi_printf(LLAPI_MSG_NORMAL,
1161                                              "\t%6u\t%14llu\t%#13llx\t%14llu%s",
1162                                              idx, oid, oid, gr,
1163                                              obdindex == idx ? " *" : "");
1164                         if (start != lumj->lmm_objects[i].l_extent_start ||
1165                             end != lumj->lmm_objects[i].l_extent_end) {
1166                                 start = lumj->lmm_objects[i].l_extent_start;
1167                                 llapi_printf(LLAPI_MSG_NORMAL,"\t%14llu",start);
1168                                 end = lumj->lmm_objects[i].l_extent_end;
1169                                 if (end == (unsigned long long)-1)
1170                                         llapi_printf(LLAPI_MSG_NORMAL,
1171                                                      "\t\tEOF\n");
1172                                 else
1173                                         llapi_printf(LLAPI_MSG_NORMAL,
1174                                                      "\t\t%llu\n", end);
1175                         } else {
1176                                 llapi_printf(LLAPI_MSG_NORMAL, "\t\t\t\t\n");
1177                         }
1178                 }
1179                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1180         }
1181 }
1182
1183 void llapi_lov_dump_user_lmm(struct find_param *param,
1184                              char *path, int is_dir)
1185 {
1186         switch(*(__u32 *)&param->lmd->lmd_lmm) { /* lum->lmm_magic */
1187         case LOV_USER_MAGIC_V1:
1188                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, NULL,
1189                                        param->lmd->lmd_lmm.lmm_objects,
1190                                        path, is_dir,
1191                                        param->obdindex, param->quiet,
1192                                        param->verbose,
1193                                        (param->verbose || !param->obduuid));
1194                 break;
1195         case LOV_USER_MAGIC_JOIN:
1196                 lov_dump_user_lmm_join(&param->lmd->lmd_lmm, path, is_dir,
1197                                        param->obdindex, param->quiet,
1198                                        param->verbose,
1199                                        (param->verbose || !param->obduuid));
1200                 break;
1201         case LOV_USER_MAGIC_V3: {
1202                 char pool_name[LOV_MAXPOOLNAME + 1];
1203                 struct lov_user_ost_data_v1 *objects;
1204                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
1205
1206                 strncpy(pool_name, lmmv3->lmm_pool_name, LOV_MAXPOOLNAME);
1207                 pool_name[LOV_MAXPOOLNAME] = '\0';
1208                 objects = lmmv3->lmm_objects;
1209                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, pool_name,
1210                                        objects, path, is_dir,
1211                                        param->obdindex, param->quiet,
1212                                        param->verbose,
1213                                        (param->verbose || !param->obduuid));
1214                 break;
1215         }
1216         default:
1217                 llapi_printf(LLAPI_MSG_NORMAL, "unknown lmm_magic:  %#x "
1218                              "(expecting one of %#x %#x %#x)\n",
1219                              *(__u32 *)&param->lmd->lmd_lmm,
1220                              LOV_USER_MAGIC_V1, LOV_USER_MAGIC_JOIN,
1221                              LOV_USER_MAGIC_V3);
1222                 return;
1223         }
1224 }
1225
1226 int llapi_file_get_stripe(const char *path, struct lov_user_md *lum)
1227 {
1228         const char *fname;
1229         char *dname;
1230         int fd, rc = 0;
1231
1232         fname = strrchr(path, '/');
1233
1234         /* It should be a file (or other non-directory) */
1235         if (fname == NULL) {
1236                 dname = (char *)malloc(2);
1237                 if (dname == NULL)
1238                         return ENOMEM;
1239                 strcpy(dname, ".");
1240                 fname = (char *)path;
1241         } else {
1242                 dname = (char *)malloc(fname - path + 1);
1243                 if (dname == NULL)
1244                         return ENOMEM;
1245                 strncpy(dname, path, fname - path);
1246                 dname[fname - path] = '\0';
1247                 fname++;
1248         }
1249
1250         if ((fd = open(dname, O_RDONLY)) == -1) {
1251                 rc = errno;
1252                 free(dname);
1253                 return rc;
1254         }
1255
1256         strcpy((char *)lum, fname);
1257         if (ioctl(fd, IOC_MDC_GETFILESTRIPE, (void *)lum) == -1)
1258                 rc = errno;
1259
1260         if (close(fd) == -1 && rc == 0)
1261                 rc = errno;
1262
1263         free(dname);
1264
1265         return rc;
1266 }
1267
1268 int llapi_file_lookup(int dirfd, const char *name)
1269 {
1270         struct obd_ioctl_data data = { 0 };
1271         char rawbuf[8192];
1272         char *buf = rawbuf;
1273         int rc;
1274
1275         if (dirfd < 0 || name == NULL)
1276                 return -EINVAL;
1277
1278         data.ioc_version = OBD_IOCTL_VERSION;
1279         data.ioc_len = sizeof(data);
1280         data.ioc_inlbuf1 = (char *)name;
1281         data.ioc_inllen1 = strlen(name) + 1;
1282
1283         rc = obd_ioctl_pack(&data, &buf, sizeof(rawbuf));
1284         if (rc) {
1285                 llapi_err(LLAPI_MSG_ERROR,
1286                           "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
1287                           name, rc);
1288                 return rc;
1289         }
1290
1291         return ioctl(dirfd, IOC_MDC_LOOKUP, buf);
1292 }
1293
1294 int llapi_mds_getfileinfo(char *path, DIR *parent,
1295                           struct lov_user_mds_data *lmd)
1296 {
1297         lstat_t *st = &lmd->lmd_st;
1298         char *fname = strrchr(path, '/');
1299         int ret = 0;
1300
1301         if (parent == NULL)
1302                 return -EINVAL;
1303
1304         fname = (fname == NULL ? path : fname + 1);
1305         /* retrieve needed file info */
1306         strncpy((char *)lmd, fname,
1307                 lov_mds_md_size(MAX_LOV_UUID_COUNT, LOV_MAGIC));
1308         ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO, (void *)lmd);
1309
1310         if (ret) {
1311                 if (errno == ENOTTY) {
1312                         /* ioctl is not supported, it is not a lustre fs.
1313                          * Do the regular lstat(2) instead. */
1314                         ret = lstat_f(path, st);
1315                         if (ret) {
1316                                 llapi_err(LLAPI_MSG_ERROR,
1317                                           "error: %s: lstat failed for %s",
1318                                           __FUNCTION__, path);
1319                                 return ret;
1320                         }
1321                 } else if (errno == ENOENT) {
1322                         llapi_err(LLAPI_MSG_WARN,
1323                                   "warning: %s: %s does not exist",
1324                                   __FUNCTION__, path);
1325                         return -ENOENT;
1326                 } else {
1327                         llapi_err(LLAPI_MSG_ERROR,
1328                                  "error: %s: IOC_MDC_GETFILEINFO failed for %s",
1329                                  __FUNCTION__, path);
1330                         return ret;
1331                 }
1332         }
1333
1334         return 0;
1335 }
1336
1337 static DIR *opendir_parent(char *path)
1338 {
1339         DIR *parent;
1340         char *fname;
1341         char c;
1342
1343         fname = strrchr(path, '/');
1344         if (fname == NULL)
1345                 return opendir(".");
1346
1347         c = fname[1];
1348         fname[1] = '\0';
1349         parent = opendir(path);
1350         fname[1] = c;
1351         return parent;
1352 }
1353
1354 static int llapi_semantic_traverse(char *path, int size, DIR *parent,
1355                                    semantic_func_t sem_init,
1356                                    semantic_func_t sem_fini, void *data,
1357                                    cfs_dirent_t *de)
1358 {
1359         cfs_dirent_t *dent;
1360         int len, ret;
1361         DIR *d, *p = NULL;
1362
1363         ret = 0;
1364         len = strlen(path);
1365
1366         d = opendir(path);
1367         if (!d && errno != ENOTDIR) {
1368                 llapi_err(LLAPI_MSG_ERROR, "%s: Failed to open '%s'",
1369                           __FUNCTION__, path);
1370                 return -EINVAL;
1371         } else if (!d && !parent) {
1372                 /* ENOTDIR. Open the parent dir. */
1373                 p = opendir_parent(path);
1374                 if (!p)
1375                         GOTO(out, ret = -EINVAL);
1376         }
1377
1378         if (sem_init && (ret = sem_init(path, parent ?: p, d, data, de)))
1379                 goto err;
1380
1381         if (!d)
1382                 GOTO(out, ret = 0);
1383
1384         while ((dent = readdir64(d)) != NULL) {
1385                 ((struct find_param *)data)->have_fileinfo = 0;
1386
1387                 if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
1388                         continue;
1389
1390                 /* Don't traverse .lustre directory */
1391                 if (!(strcmp(dent->d_name, dot_lustre_name)))
1392                         continue;
1393
1394                 path[len] = 0;
1395                 if ((len + dent->d_reclen + 2) > size) {
1396                         llapi_err(LLAPI_MSG_ERROR,
1397                                   "error: %s: string buffer is too small",
1398                                   __FUNCTION__);
1399                         break;
1400                 }
1401                 strcat(path, "/");
1402                 strcat(path, dent->d_name);
1403
1404                 if (dent->d_type == DT_UNKNOWN) {
1405                         lstat_t *st = &((struct find_param *)data)->lmd->lmd_st;
1406
1407                         ret = llapi_mds_getfileinfo(path, d,
1408                                              ((struct find_param *)data)->lmd);
1409                         if (ret == 0) {
1410                                 ((struct find_param *)data)->have_fileinfo = 1;
1411                                 dent->d_type =
1412                                         llapi_filetype_dir_table[st->st_mode &
1413                                                                  S_IFMT];
1414                         }
1415                         if (ret == -ENOENT)
1416                                 continue;
1417                 }
1418
1419                 switch (dent->d_type) {
1420                 case DT_UNKNOWN:
1421                         llapi_err(LLAPI_MSG_ERROR,
1422                                   "error: %s: '%s' is UNKNOWN type %d",
1423                                   __FUNCTION__, dent->d_name, dent->d_type);
1424                         break;
1425                 case DT_DIR:
1426                         ret = llapi_semantic_traverse(path, size, d, sem_init,
1427                                                       sem_fini, data, dent);
1428                         if (ret < 0)
1429                                 goto out;
1430                         break;
1431                 default:
1432                         ret = 0;
1433                         if (sem_init) {
1434                                 ret = sem_init(path, d, NULL, data, dent);
1435                                 if (ret < 0)
1436                                         goto out;
1437                         }
1438                         if (sem_fini && ret == 0)
1439                                 sem_fini(path, d, NULL, data, dent);
1440                 }
1441         }
1442
1443 out:
1444         path[len] = 0;
1445
1446         if (sem_fini)
1447                 sem_fini(path, parent, d, data, de);
1448 err:
1449         if (d)
1450                 closedir(d);
1451         if (p)
1452                 closedir(p);
1453         return ret;
1454 }
1455
1456 /* Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
1457  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
1458  *
1459  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
1460  * The table below gives the answers for the specified parameters (value and
1461  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
1462  * --------------------------------------
1463  * 1 | file > limit; sign > 0 | -1 / -1 |
1464  * 2 | file = limit; sign > 0 |  ? /  1 |
1465  * 3 | file < limit; sign > 0 |  ? /  1 |
1466  * 4 | file > limit; sign = 0 | -1 / -1 |
1467  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
1468  * 6 | file < limit; sign = 0 |  ? / -1 |
1469  * 7 | file > limit; sign < 0 |  1 /  1 |
1470  * 8 | file = limit; sign < 0 |  ? / -1 |
1471  * 9 | file < limit; sign < 0 |  ? / -1 |
1472  * --------------------------------------
1473  * Note: 5th actually means that the value is within the interval
1474  * (limit - margin, limit]. */
1475 static int find_value_cmp(unsigned int file, unsigned int limit, int sign,
1476                           unsigned long long margin, int mds)
1477 {
1478         if (sign > 0) {
1479                 if (file < limit)
1480                         return mds ? 0 : 1;
1481         }
1482
1483         if (sign == 0) {
1484                 if (file <= limit && file + margin > limit)
1485                         return mds ? 0 : 1;
1486                 if (file + margin <= limit)
1487                         return mds ? 0 : -1;
1488         }
1489
1490         if (sign < 0) {
1491                 if (file > limit)
1492                         return 1;
1493                 if (mds)
1494                         return 0;
1495         }
1496
1497         return -1;
1498 }
1499
1500 /* Check if the file time matches all the given criteria (e.g. --atime +/-N).
1501  * Return -1 or 1 if file timestamp does not or does match the given criteria
1502  * correspondingly. Return 0 if the MDS time is being checked and there are
1503  * attributes on OSTs and it is not yet clear if the timespamp matches.
1504  *
1505  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
1506  * updated timestamps. */
1507 static int find_time_check(lstat_t *st, struct find_param *param, int mds)
1508 {
1509         int ret;
1510         int rc = 0;
1511
1512         /* Check if file is accepted. */
1513         if (param->atime) {
1514                 ret = find_value_cmp(st->st_atime, param->atime,
1515                                      param->asign, 24 * 60 * 60, mds);
1516                 if (ret < 0)
1517                         return ret;
1518                 rc = ret;
1519         }
1520
1521         if (param->mtime) {
1522                 ret = find_value_cmp(st->st_mtime, param->mtime,
1523                                      param->msign, 24 * 60 * 60, mds);
1524                 if (ret < 0)
1525                         return ret;
1526
1527                 /* If the previous check matches, but this one is not yet clear,
1528                  * we should return 0 to do an RPC on OSTs. */
1529                 if (rc == 1)
1530                         rc = ret;
1531         }
1532
1533         if (param->ctime) {
1534                 ret = find_value_cmp(st->st_ctime, param->ctime,
1535                                      param->csign, 24 * 60 * 60, mds);
1536                 if (ret < 0)
1537                         return ret;
1538
1539                 /* If the previous check matches, but this one is not yet clear,
1540                  * we should return 0 to do an RPC on OSTs. */
1541                 if (rc == 1)
1542                         rc = ret;
1543         }
1544
1545         return rc;
1546 }
1547
1548 static int cb_find_init(char *path, DIR *parent, DIR *dir,
1549                         void *data, cfs_dirent_t *de)
1550 {
1551         struct find_param *param = (struct find_param *)data;
1552         int decision = 1; /* 1 is accepted; -1 is rejected. */
1553         lstat_t *st = &param->lmd->lmd_st;
1554         int lustre_fs = 1;
1555         int checked_type = 0;
1556         int ret = 0;
1557
1558         LASSERT(parent != NULL || dir != NULL);
1559
1560         param->lmd->lmd_lmm.lmm_stripe_count = 0;
1561
1562         /* If a regular expression is presented, make the initial decision */
1563         if (param->pattern != NULL) {
1564                 char *fname = strrchr(path, '/');
1565                 fname = (fname == NULL ? path : fname + 1);
1566                 ret = fnmatch(param->pattern, fname, 0);
1567                 if ((ret == FNM_NOMATCH && !param->exclude_pattern) ||
1568                     (ret == 0 && param->exclude_pattern))
1569                         goto decided;
1570         }
1571
1572         /* See if we can check the file type from the dirent. */
1573         if (param->type && de != NULL && de->d_type != DT_UNKNOWN &&
1574             de->d_type < DT_MAX) {
1575                 checked_type = 1;
1576                 if (llapi_dir_filetype_table[de->d_type] == param->type) {
1577                         if (param->exclude_type)
1578                                 goto decided;
1579                 } else {
1580                         if (!param->exclude_type)
1581                                 goto decided;
1582                 }
1583         }
1584
1585
1586         /* If a time or OST should be checked, the decision is not taken yet. */
1587         if (param->atime || param->ctime || param->mtime || param->obduuid ||
1588             param->size)
1589                 decision = 0;
1590
1591         ret = 0;
1592         /* Request MDS for the stat info. */
1593         if (param->have_fileinfo == 0) {
1594                 if (dir) {
1595                         /* retrieve needed file info */
1596                         ret = ioctl(dirfd(dir), LL_IOC_MDC_GETINFO,
1597                                     (void *)param->lmd);
1598                 } else {
1599                         char *fname = strrchr(path, '/');
1600                         fname = (fname == NULL ? path : fname + 1);
1601
1602                         /* retrieve needed file info */
1603                         strncpy((char *)param->lmd, fname, param->lumlen);
1604                         ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
1605                                    (void *)param->lmd);
1606                 }
1607         }
1608
1609         if (ret) {
1610                 if (errno == ENOTTY) {
1611                         /* ioctl is not supported, it is not a lustre fs.
1612                          * Do the regular lstat(2) instead. */
1613                         lustre_fs = 0;
1614                         ret = lstat_f(path, st);
1615                         if (ret) {
1616                                 llapi_err(LLAPI_MSG_ERROR,
1617                                           "error: %s: lstat failed for %s",
1618                                           __FUNCTION__, path);
1619                                 return ret;
1620                         }
1621                 } else if (errno == ENOENT) {
1622                         llapi_err(LLAPI_MSG_WARN,
1623                                   "warning: %s: %s does not exist",
1624                                   __FUNCTION__, path);
1625                         goto decided;
1626                 } else {
1627                         llapi_err(LLAPI_MSG_ERROR,"error: %s: %s failed for %s",
1628                                   __FUNCTION__, dir ? "LL_IOC_MDC_GETINFO" :
1629                                   "IOC_MDC_GETFILEINFO", path);
1630                         return ret;
1631                 }
1632         }
1633
1634         if (param->type && !checked_type) {
1635                 if ((st->st_mode & S_IFMT) == param->type) {
1636                         if (param->exclude_type)
1637                                 goto decided;
1638                 } else {
1639                         if (!param->exclude_type)
1640                                 goto decided;
1641                 }
1642         }
1643
1644         /* Prepare odb. */
1645         if (param->obduuid) {
1646                 if (lustre_fs && param->got_uuids &&
1647                     param->st_dev != st->st_dev) {
1648                         /* A lustre/lustre mount point is crossed. */
1649                         param->got_uuids = 0;
1650                         param->obds_printed = 0;
1651                         param->obdindex = OBD_NOT_FOUND;
1652                 }
1653
1654                 if (lustre_fs && !param->got_uuids) {
1655                         ret = setup_obd_indexes(dir ? dir : parent, param);
1656                         if (ret)
1657                                 return ret;
1658
1659                         param->st_dev = st->st_dev;
1660                 } else if (!lustre_fs && param->got_uuids) {
1661                         /* A lustre/non-lustre mount point is crossed. */
1662                         param->got_uuids = 0;
1663                         param->obdindex = OBD_NOT_FOUND;
1664                 }
1665         }
1666
1667         /* If an OBD UUID is specified but no one matches, skip this file. */
1668         if (param->obduuid && param->obdindex == OBD_NOT_FOUND)
1669                 goto decided;
1670
1671         /* If a OST UUID is given, and some OST matches, check it here. */
1672         if (param->obdindex != OBD_NOT_FOUND) {
1673                 if (!S_ISREG(st->st_mode))
1674                         goto decided;
1675
1676                 /* Only those files should be accepted, which have a
1677                  * stripe on the specified OST. */
1678                 if (!param->lmd->lmd_lmm.lmm_stripe_count) {
1679                         goto decided;
1680                 } else {
1681                         int i, j;
1682                         struct lov_user_ost_data_v1 *lmm_objects;
1683
1684                         if (param->lmd->lmd_lmm.lmm_magic ==
1685                             LOV_USER_MAGIC_V3) {
1686                                 struct lov_user_md_v3 *lmmv3 =
1687                                         (void *)&param->lmd->lmd_lmm;
1688
1689                                 lmm_objects = lmmv3->lmm_objects;
1690                         } else {
1691                                 lmm_objects = param->lmd->lmd_lmm.lmm_objects;
1692                         }
1693
1694                         for (i = 0;
1695                              i < param->lmd->lmd_lmm.lmm_stripe_count; i++) {
1696                                 for (j = 0; j < param->num_obds; j++) {
1697                                         if (param->obdindexes[j] ==
1698                                             lmm_objects[i].l_ost_idx)
1699                                                 goto obd_matches;
1700                                 }
1701                         }
1702
1703                         if (i == param->lmd->lmd_lmm.lmm_stripe_count)
1704                                 goto decided;
1705                 }
1706         }
1707
1708         if (param->check_uid) {
1709                 if (st->st_uid == param->uid) {
1710                         if (param->exclude_uid)
1711                                 goto decided;
1712                 } else {
1713                         if (!param->exclude_uid)
1714                                 goto decided;
1715                 }
1716         }
1717
1718         if (param->check_gid) {
1719                 if (st->st_gid == param->gid) {
1720                         if (param->exclude_gid)
1721                                 goto decided;
1722                 } else {
1723                         if (!param->exclude_gid)
1724                                 goto decided;
1725                 }
1726         }
1727
1728         if (param->check_pool) {
1729                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
1730
1731                 /* empty requested pool is taken as no pool search => V1 */
1732                 if (((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V1) &&
1733                      (param->poolname[0] == '\0')) ||
1734                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
1735                      (strncmp(lmmv3->lmm_pool_name,
1736                               param->poolname, LOV_MAXPOOLNAME) == 0)) ||
1737                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
1738                      (strcmp(param->poolname, "*") == 0))) {
1739                         if (param->exclude_pool)
1740                                 goto decided;
1741                 } else {
1742                         if (!param->exclude_pool)
1743                                 goto decided;
1744                 }
1745         }
1746
1747         /* Check the time on mds. */
1748         if (!decision) {
1749                 int for_mds;
1750
1751                 for_mds = lustre_fs ? (S_ISREG(st->st_mode) &&
1752                                        param->lmd->lmd_lmm.lmm_stripe_count)
1753                                     : 0;
1754                 decision = find_time_check(st, param, for_mds);
1755         }
1756
1757 obd_matches:
1758         /* If file still fits the request, ask ost for updated info.
1759            The regular stat is almost of the same speed as some new
1760            'glimpse-size-ioctl'. */
1761         if (!decision && S_ISREG(st->st_mode) &&
1762             (param->lmd->lmd_lmm.lmm_stripe_count || param->size)) {
1763                 if (param->obdindex != OBD_NOT_FOUND) {
1764                         /* Check whether the obd is active or not, if it is
1765                          * not active, just print the object affected by this
1766                          * failed ost
1767                          * */
1768                         struct obd_statfs stat_buf;
1769                         struct obd_uuid uuid_buf;
1770
1771                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
1772                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1773                         ret = llapi_obd_statfs(path, LL_STATFS_LOV,
1774                                                param->obdindex, &stat_buf,
1775                                                &uuid_buf);
1776                         if (ret) {
1777                                 if (ret == -ENODATA || ret == -ENODEV
1778                                     || ret == -EIO)
1779                                         errno = EIO;
1780                                 llapi_printf(LLAPI_MSG_NORMAL,
1781                                              "obd_uuid: %s failed %s ",
1782                                              param->obduuid->uuid,
1783                                              strerror(errno));
1784                                 goto print_path;
1785                         }
1786                 }
1787                 if (dir) {
1788                         ret = ioctl(dirfd(dir), IOC_LOV_GETINFO,
1789                                     (void *)param->lmd);
1790                 } else if (parent) {
1791                         ret = ioctl(dirfd(parent), IOC_LOV_GETINFO,
1792                                     (void *)param->lmd);
1793                 }
1794
1795                 if (ret) {
1796                         if (errno == ENOENT) {
1797                                 llapi_err(LLAPI_MSG_ERROR,
1798                                           "warning: %s: %s does not exist",
1799                                           __FUNCTION__, path);
1800                                 goto decided;
1801                         } else {
1802                                 llapi_err(LLAPI_MSG_ERROR,
1803                                           "%s: IOC_LOV_GETINFO on %s failed",
1804                                           __FUNCTION__, path);
1805                                 return ret;
1806                         }
1807                 }
1808
1809                 /* Check the time on osc. */
1810                 decision = find_time_check(st, param, 0);
1811                 if (decision == -1)
1812                         goto decided;
1813         }
1814
1815         if (param->size)
1816                 decision = find_value_cmp(st->st_size, param->size,
1817                                           param->size_sign, param->size_units,
1818                                           0);
1819
1820 print_path:
1821         if (decision != -1) {
1822                 llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
1823                 if (param->zeroend)
1824                         llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
1825                 else
1826                         llapi_printf(LLAPI_MSG_NORMAL, "\n");
1827         }
1828
1829 decided:
1830         /* Do not get down anymore? */
1831         if (param->depth == param->maxdepth)
1832                 return 1;
1833
1834         param->depth++;
1835         return 0;
1836 }
1837
1838 static int cb_common_fini(char *path, DIR *parent, DIR *d, void *data,
1839                           cfs_dirent_t *de)
1840 {
1841         struct find_param *param = (struct find_param *)data;
1842         param->depth--;
1843         return 0;
1844 }
1845
1846 int llapi_find(char *path, struct find_param *param)
1847 {
1848         char *buf;
1849         int ret, len = strlen(path);
1850
1851         if (len > PATH_MAX) {
1852                 llapi_err(LLAPI_MSG_ERROR, "%s: Path name '%s' is too long",
1853                           __FUNCTION__, path);
1854                 return -EINVAL;
1855         }
1856
1857         buf = (char *)malloc(PATH_MAX + 1);
1858         if (!buf)
1859                 return -ENOMEM;
1860
1861         ret = common_param_init(param);
1862         if (ret) {
1863                 free(buf);
1864                 return ret;
1865         }
1866
1867         param->depth = 0;
1868
1869         strncpy(buf, path, PATH_MAX + 1);
1870         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, cb_find_init,
1871                                       cb_common_fini, param, NULL);
1872
1873         find_param_fini(param);
1874         free(buf);
1875         return ret < 0 ? ret : 0;
1876 }
1877
1878 static int cb_getstripe(char *path, DIR *parent, DIR *d, void *data,
1879                         cfs_dirent_t *de)
1880 {
1881         struct find_param *param = (struct find_param *)data;
1882         int ret = 0;
1883
1884         LASSERT(parent != NULL || d != NULL);
1885
1886         /* Prepare odb. */
1887         if (!param->got_uuids) {
1888                 ret = setup_obd_uuid(d ? d : parent, path, param);
1889                 if (ret)
1890                         return ret;
1891         }
1892
1893         if (d) {
1894                 ret = ioctl(dirfd(d), LL_IOC_LOV_GETSTRIPE,
1895                             (void *)&param->lmd->lmd_lmm);
1896         } else if (parent) {
1897                 char *fname = strrchr(path, '/');
1898                 fname = (fname == NULL ? path : fname + 1);
1899
1900                 strncpy((char *)&param->lmd->lmd_lmm, fname, param->lumlen);
1901                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILESTRIPE,
1902                             (void *)&param->lmd->lmd_lmm);
1903         }
1904
1905         if (ret) {
1906                 if (errno == ENODATA) {
1907                         if (!param->obduuid && !param->quiet)
1908                                 llapi_printf(LLAPI_MSG_NORMAL,
1909                                              "%s has no stripe info\n", path);
1910                         goto out;
1911                 } else if (errno == ENOTTY) {
1912                         llapi_err(LLAPI_MSG_ERROR,
1913                                   "%s: '%s' not on a Lustre fs?",
1914                                   __FUNCTION__, path);
1915                 } else if (errno == ENOENT) {
1916                         llapi_err(LLAPI_MSG_WARN,
1917                                   "warning: %s: %s does not exist",
1918                                   __FUNCTION__, path);
1919                         goto out;
1920                 } else {
1921                         llapi_err(LLAPI_MSG_ERROR,
1922                                   "error: %s: %s failed for %s",
1923                                    __FUNCTION__, d ? "LL_IOC_LOV_GETSTRIPE" :
1924                                   "IOC_MDC_GETFILESTRIPE", path);
1925                 }
1926
1927                 return ret;
1928         }
1929
1930         llapi_lov_dump_user_lmm(param, path, d ? 1 : 0);
1931 out:
1932         /* Do not get down anymore? */
1933         if (param->depth == param->maxdepth)
1934                 return 1;
1935
1936         param->depth++;
1937         return 0;
1938 }
1939
1940 int llapi_getstripe(char *path, struct find_param *param)
1941 {
1942         char *buf;
1943         int ret = 0, len = strlen(path);
1944
1945         if (len > PATH_MAX) {
1946                 llapi_err(LLAPI_MSG_ERROR,
1947                           "%s: Path name '%s' is too long",
1948                           __FUNCTION__, path);
1949                 return -EINVAL;
1950         }
1951
1952         buf = (char *)malloc(PATH_MAX + 1);
1953         if (!buf)
1954                 return -ENOMEM;
1955
1956         ret = common_param_init(param);
1957         if (ret) {
1958                 free(buf);
1959                 return ret;
1960         }
1961
1962         param->depth = 0;
1963
1964         strncpy(buf, path, PATH_MAX + 1);
1965         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, cb_getstripe,
1966                                       cb_common_fini, param, NULL);
1967         find_param_fini(param);
1968         free(buf);
1969         return ret < 0 ? ret : 0;
1970 }
1971
1972 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
1973                      struct obd_statfs *stat_buf,
1974                      struct obd_uuid *uuid_buf)
1975 {
1976         int fd;
1977         char raw[OBD_MAX_IOCTL_BUFFER] = {'\0'};
1978         char *rawbuf = raw;
1979         struct obd_ioctl_data data = { 0 };
1980         int rc = 0;
1981
1982         data.ioc_inlbuf1 = (char *)&type;
1983         data.ioc_inllen1 = sizeof(__u32);
1984         data.ioc_inlbuf2 = (char *)&index;
1985         data.ioc_inllen2 = sizeof(__u32);
1986         data.ioc_pbuf1 = (char *)stat_buf;
1987         data.ioc_plen1 = sizeof(struct obd_statfs);
1988         data.ioc_pbuf2 = (char *)uuid_buf;
1989         data.ioc_plen2 = sizeof(struct obd_uuid);
1990
1991         if ((rc = obd_ioctl_pack(&data, &rawbuf, sizeof(raw))) != 0) {
1992                 llapi_err(LLAPI_MSG_ERROR,
1993                           "llapi_obd_statfs: error packing ioctl data");
1994                 return rc;
1995         }
1996
1997         fd = open(path, O_RDONLY);
1998         if (errno == EISDIR)
1999                 fd = open(path, O_DIRECTORY | O_RDONLY);
2000
2001         if (fd < 0) {
2002                 rc = errno ? -errno : -EBADF;
2003                 llapi_err(LLAPI_MSG_ERROR, "error: %s: opening '%s'",
2004                           __FUNCTION__, path);
2005                 return rc;
2006         }
2007         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
2008         if (rc)
2009                 rc = errno ? -errno : -EINVAL;
2010
2011         close(fd);
2012         return rc;
2013 }
2014
2015 #define MAX_STRING_SIZE 128
2016 #define DEVICES_LIST "/proc/fs/lustre/devices"
2017
2018 int llapi_ping(char *obd_type, char *obd_name)
2019 {
2020         char path[MAX_STRING_SIZE];
2021         char buf[1];
2022         int rc, fd;
2023
2024         snprintf(path, MAX_STRING_SIZE, "/proc/fs/lustre/%s/%s/ping",
2025                  obd_type, obd_name);
2026
2027         fd = open(path, O_WRONLY);
2028         if (fd < 0) {
2029                 rc = errno;
2030                 llapi_err(LLAPI_MSG_ERROR, "error opening %s", path);
2031                 return rc;
2032         }
2033
2034         rc = write(fd, buf, 1);
2035         close(fd);
2036
2037         if (rc == 1)
2038                 return 0;
2039         return rc;
2040 }
2041
2042 int llapi_target_iterate(int type_num, char **obd_type,void *args,llapi_cb_t cb)
2043 {
2044         char buf[MAX_STRING_SIZE];
2045         FILE *fp = fopen(DEVICES_LIST, "r");
2046         int i, rc = 0;
2047
2048         if (fp == NULL) {
2049                 rc = errno;
2050                 llapi_err(LLAPI_MSG_ERROR, "error: opening "DEVICES_LIST);
2051                 return rc;
2052         }
2053
2054         while (fgets(buf, sizeof(buf), fp) != NULL) {
2055                 char *obd_type_name = NULL;
2056                 char *obd_name = NULL;
2057                 char *obd_uuid = NULL;
2058                 char *bufp = buf;
2059                 struct obd_ioctl_data datal = { 0, };
2060                 struct obd_statfs osfs_buffer;
2061
2062                 while(bufp[0] == ' ')
2063                         ++bufp;
2064
2065                 for(i = 0; i < 3; i++) {
2066                         obd_type_name = strsep(&bufp, " ");
2067                 }
2068                 obd_name = strsep(&bufp, " ");
2069                 obd_uuid = strsep(&bufp, " ");
2070
2071                 memset(&osfs_buffer, 0, sizeof (osfs_buffer));
2072
2073                 datal.ioc_pbuf1 = (char *)&osfs_buffer;
2074                 datal.ioc_plen1 = sizeof(osfs_buffer);
2075
2076                 for (i = 0; i < type_num; i++) {
2077                         if (strcmp(obd_type_name, obd_type[i]) != 0)
2078                                 continue;
2079
2080                         cb(obd_type_name, obd_name, obd_uuid, args);
2081                 }
2082         }
2083         fclose(fp);
2084         return rc;
2085 }
2086
2087 static void do_target_check(char *obd_type_name, char *obd_name,
2088                             char *obd_uuid, void *args)
2089 {
2090         int rc;
2091
2092         rc = llapi_ping(obd_type_name, obd_name);
2093         if (rc == ENOTCONN) {
2094                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
2095         } else if (rc) {
2096                 llapi_err(LLAPI_MSG_ERROR, "error: check '%s'", obd_name);
2097         } else {
2098                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
2099         }
2100 }
2101
2102 int llapi_target_check(int type_num, char **obd_type, char *dir)
2103 {
2104         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
2105 }
2106
2107 #undef MAX_STRING_SIZE
2108
2109 int llapi_catinfo(char *dir, char *keyword, char *node_name)
2110 {
2111         char raw[OBD_MAX_IOCTL_BUFFER];
2112         char out[LLOG_CHUNK_SIZE];
2113         char *buf = raw;
2114         struct obd_ioctl_data data = { 0 };
2115         char key[30];
2116         DIR *root;
2117         int rc;
2118
2119         sprintf(key, "%s", keyword);
2120         memset(raw, 0, sizeof(raw));
2121         memset(out, 0, sizeof(out));
2122         data.ioc_inlbuf1 = key;
2123         data.ioc_inllen1 = strlen(key) + 1;
2124         if (node_name) {
2125                 data.ioc_inlbuf2 = node_name;
2126                 data.ioc_inllen2 = strlen(node_name) + 1;
2127         }
2128         data.ioc_pbuf1 = out;
2129         data.ioc_plen1 = sizeof(out);
2130         rc = obd_ioctl_pack(&data, &buf, sizeof(raw));
2131         if (rc)
2132                 return rc;
2133
2134         root = opendir(dir);
2135         if (root == NULL) {
2136                 rc = errno;
2137                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", dir);
2138                 return rc;
2139         }
2140
2141         rc = ioctl(dirfd(root), OBD_IOC_LLOG_CATINFO, buf);
2142         if (rc)
2143                 llapi_err(LLAPI_MSG_ERROR, "ioctl OBD_IOC_CATINFO failed");
2144         else
2145                 llapi_printf(LLAPI_MSG_NORMAL, "%s", data.ioc_pbuf1);
2146
2147         closedir(root);
2148         return rc;
2149 }
2150
2151 /* Is this a lustre fs? */
2152 int llapi_is_lustre_mnttype(const char *type)
2153 {
2154         return (strcmp(type, "lustre") == 0 || strcmp(type,"lustre_lite") == 0);
2155 }
2156
2157 /* Is this a lustre client fs? */
2158 int llapi_is_lustre_mnt(struct mntent *mnt)
2159 {
2160         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
2161                 strstr(mnt->mnt_fsname, ":/") != NULL);
2162 }
2163
2164 int llapi_quotacheck(char *mnt, int check_type)
2165 {
2166         DIR *root;
2167         int rc;
2168
2169         root = opendir(mnt);
2170         if (!root) {
2171                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2172                 return -1;
2173         }
2174
2175         rc = ioctl(dirfd(root), LL_IOC_QUOTACHECK, check_type);
2176
2177         closedir(root);
2178         return rc;
2179 }
2180
2181 int llapi_poll_quotacheck(char *mnt, struct if_quotacheck *qchk)
2182 {
2183         DIR *root;
2184         int poll_intvl = 2;
2185         int rc;
2186
2187         root = opendir(mnt);
2188         if (!root) {
2189                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2190                 return -1;
2191         }
2192
2193         while (1) {
2194                 rc = ioctl(dirfd(root), LL_IOC_POLL_QUOTACHECK, qchk);
2195                 if (!rc)
2196                         break;
2197                 sleep(poll_intvl);
2198                 if (poll_intvl < 30)
2199                         poll_intvl *= 2;
2200         }
2201
2202         closedir(root);
2203         return rc;
2204 }
2205
2206 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
2207 {
2208         DIR *root;
2209         int rc;
2210
2211         root = opendir(mnt);
2212         if (!root) {
2213                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2214                 return -1;
2215         }
2216
2217         rc = ioctl(dirfd(root), LL_IOC_QUOTACTL, qctl);
2218
2219         closedir(root);
2220         return rc;
2221 }
2222
2223 static int cb_quotachown(char *path, DIR *parent, DIR *d, void *data,
2224                          cfs_dirent_t *de)
2225 {
2226         struct find_param *param = (struct find_param *)data;
2227         lstat_t *st;
2228         int rc;
2229
2230         LASSERT(parent != NULL || d != NULL);
2231
2232         if (d) {
2233                 rc = ioctl(dirfd(d), LL_IOC_MDC_GETINFO,
2234                            (void *)param->lmd);
2235         } else if (parent) {
2236                 char *fname = strrchr(path, '/');
2237                 fname = (fname == NULL ? path : fname + 1);
2238
2239                 strncpy((char *)param->lmd, fname, param->lumlen);
2240                 rc = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
2241                            (void *)param->lmd);
2242         } else {
2243                 return 0;
2244         }
2245
2246         if (rc) {
2247                 if (errno == ENODATA) {
2248                         if (!param->obduuid && !param->quiet)
2249                                 llapi_err(LLAPI_MSG_ERROR,
2250                                           "%s has no stripe info", path);
2251                         rc = 0;
2252                 } else if (errno == ENOENT) {
2253                         llapi_err(LLAPI_MSG_ERROR,
2254                                   "warning: %s: %s does not exist",
2255                                   __FUNCTION__, path);
2256                         rc = 0;
2257                 } else if (errno != EISDIR) {
2258                         rc = errno;
2259                         llapi_err(LLAPI_MSG_ERROR, "%s ioctl failed for %s.",
2260                                   d ? "LL_IOC_MDC_GETINFO" :
2261                                   "IOC_MDC_GETFILEINFO", path);
2262                 }
2263                 return rc;
2264         }
2265
2266         st = &param->lmd->lmd_st;
2267
2268         /* libc chown() will do extra check, and if the real owner is
2269          * the same as the ones to set, it won't fall into kernel, so
2270          * invoke syscall directly. */
2271         rc = syscall(SYS_chown, path, -1, -1);
2272         if (rc)
2273                 llapi_err(LLAPI_MSG_ERROR,"error: chown %s (%u,%u)", path);
2274
2275         rc = chmod(path, st->st_mode);
2276         if (rc)
2277                 llapi_err(LLAPI_MSG_ERROR, "error: chmod %s (%hu)",
2278                           path, st->st_mode);
2279
2280         return rc;
2281 }
2282
2283 int llapi_quotachown(char *path, int flag)
2284 {
2285         struct find_param param;
2286         char *buf;
2287         int ret = 0, len = strlen(path);
2288
2289         if (len > PATH_MAX) {
2290                 llapi_err(LLAPI_MSG_ERROR, "%s: Path name '%s' is too long",
2291                           __FUNCTION__, path);
2292                 return -EINVAL;
2293         }
2294
2295         buf = (char *)malloc(PATH_MAX + 1);
2296         if (!buf)
2297                 return -ENOMEM;
2298
2299         memset(&param, 0, sizeof(param));
2300         param.recursive = 1;
2301         param.verbose = 0;
2302         param.quiet = 1;
2303
2304         ret = common_param_init(&param);
2305         if (ret)
2306                 goto out;
2307
2308         strncpy(buf, path, PATH_MAX + 1);
2309         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, cb_quotachown,
2310                                       NULL, &param, NULL);
2311 out:
2312         find_param_fini(&param);
2313         free(buf);
2314         return ret;
2315 }
2316
2317 #include <pwd.h>
2318 #include <grp.h>
2319 #include <mntent.h>
2320 #include <sys/wait.h>
2321 #include <errno.h>
2322 #include <ctype.h>
2323
2324 static int rmtacl_notify(int ops)
2325 {
2326         FILE *fp;
2327         struct mntent *mnt;
2328         int found = 0, fd, rc;
2329
2330         fp = setmntent(MOUNTED, "r");
2331         if (fp == NULL) {
2332                 perror("setmntent");
2333                 return -1;
2334         }
2335
2336         while (1) {
2337                 mnt = getmntent(fp);
2338                 if (!mnt)
2339                         break;
2340
2341                 if (!llapi_is_lustre_mnt(mnt))
2342                         continue;
2343
2344                 fd = open(mnt->mnt_dir, O_RDONLY | O_DIRECTORY);
2345                 if (fd < 0) {
2346                         perror("open");
2347                         return -1;
2348                 }
2349
2350                 rc = ioctl(fd, LL_IOC_RMTACL, ops);
2351                 if (rc < 0) {
2352                         perror("ioctl");
2353                 return -1;
2354                 }
2355
2356                 found++;
2357         }
2358         endmntent(fp);
2359         return found;
2360 }
2361
2362 static char *next_token(char *p, int div)
2363 {
2364         if (p == NULL)
2365                 return NULL;
2366
2367         if (div)
2368                 while (*p && *p != ':' && !isspace(*p))
2369                         p++;
2370         else
2371                 while (*p == ':' || isspace(*p))
2372                         p++;
2373
2374         return *p ? p : NULL;
2375 }
2376
2377 static int rmtacl_name2id(char *name, int is_user)
2378 {
2379         if (is_user) {
2380                 struct passwd *pw;
2381
2382                 if ((pw = getpwnam(name)) == NULL)
2383                         return INVALID_ID;
2384                 else
2385                         return (int)(pw->pw_uid);
2386         } else {
2387                 struct group *gr;
2388
2389                 if ((gr = getgrnam(name)) == NULL)
2390                         return INVALID_ID;
2391                 else
2392                         return (int)(gr->gr_gid);
2393         }
2394 }
2395
2396 static int isodigit(int c)
2397 {
2398         return (c >= '0' && c <= '7') ? 1 : 0;
2399 }
2400
2401 /*
2402  * Whether the name is just digits string (uid/gid) already or not.
2403  * Return value:
2404  * 1: str is id
2405  * 0: str is not id
2406  */
2407 static int str_is_id(char *str)
2408 {
2409         if (str == NULL)
2410                 return 0;
2411
2412         if (*str == '0') {
2413                 str++;
2414                 if (*str == 'x' || *str == 'X') { /* for Hex. */
2415                         if (!isxdigit(*(++str)))
2416                                 return 0;
2417
2418                         while (isxdigit(*(++str)));
2419                 } else if (isodigit(*str)) { /* for Oct. */
2420                         while (isodigit(*(++str)));
2421                 }
2422         } else if (isdigit(*str)) { /* for Dec. */
2423                 while (isdigit(*(++str)));
2424         }
2425
2426         return (*str == 0) ? 1 : 0;
2427 }
2428
2429 typedef struct {
2430         char *name;
2431         int   length;
2432         int   is_user;
2433         int   next_token;
2434 } rmtacl_name_t;
2435
2436 #define RMTACL_OPTNAME(name) name, sizeof(name) - 1
2437
2438 static rmtacl_name_t rmtacl_namelist[] = {
2439         { RMTACL_OPTNAME("user:"),            1,      0 },
2440         { RMTACL_OPTNAME("group:"),           0,      0 },
2441         { RMTACL_OPTNAME("default:user:"),    1,      0 },
2442         { RMTACL_OPTNAME("default:group:"),   0,      0 },
2443         /* for --tabular option */
2444         { RMTACL_OPTNAME("user"),             1,      1 },
2445         { RMTACL_OPTNAME("group"),            0,      1 },
2446         { 0 }
2447 };
2448
2449 static int rgetfacl_output(char *str)
2450 {
2451         char *start = NULL, *end = NULL;
2452         int is_user = 0, n, id;
2453         char c;
2454         rmtacl_name_t *rn;
2455
2456         if (str == NULL)
2457                 return -1;
2458
2459         for (rn = rmtacl_namelist; rn->name; rn++) {
2460                 if(strncmp(str, rn->name, rn->length) == 0) {
2461                         if (!rn->next_token)
2462                                 start = str + rn->length;
2463                         else
2464                                 start = next_token(str + rn->length, 0);
2465                         is_user = rn->is_user;
2466                         break;
2467                 }
2468         }
2469
2470         end = next_token(start, 1);
2471         if (end == NULL || start == end) {
2472                 n = printf("%s", str);
2473                 return n;
2474         }
2475
2476         c = *end;
2477         *end = 0;
2478         id = rmtacl_name2id(start, is_user);
2479         if (id == INVALID_ID) {
2480                 if (str_is_id(start)) {
2481                         *end = c;
2482                         n = printf("%s", str);
2483                 } else
2484                         return -1;
2485         } else if ((id == NOBODY_UID && is_user) ||
2486                    (id == NOBODY_GID && !is_user)) {
2487                 *end = c;
2488                 n = printf("%s", str);
2489         } else {
2490                 *end = c;
2491                 *start = 0;
2492                 n = printf("%s%d%s", str, id, end);
2493         }
2494         return n;
2495 }
2496
2497 static int child_status(int status)
2498 {
2499         return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
2500 }
2501
2502 static int do_rmtacl(int argc, char *argv[], int ops, int (output_func)(char *))
2503 {
2504         pid_t pid = 0;
2505         int fd[2], status;
2506         FILE *fp;
2507         char buf[PIPE_BUF];
2508
2509         if (output_func) {
2510                 if (pipe(fd) < 0) {
2511                         perror("pipe");
2512                         return -1;
2513                 }
2514
2515                 if ((pid = fork()) < 0) {
2516                         perror("fork");
2517                         close(fd[0]);
2518                         close(fd[1]);
2519                         return -1;
2520                 } else if (!pid) {
2521                         /* child process redirects its output. */
2522                         close(fd[0]);
2523                         close(1);
2524                         if (dup2(fd[1], 1) < 0) {
2525                                 perror("dup2");
2526                                 close(fd[1]);
2527                                 return -1;
2528                         }
2529                 } else {
2530                         close(fd[1]);
2531                 }
2532         }
2533
2534         if (!pid) {
2535                 status = rmtacl_notify(ops);
2536                 if (status < 0)
2537                         return -1;
2538
2539                 exit(execvp(argv[0], argv));
2540         }
2541
2542         /* the following is parent process */
2543         if ((fp = fdopen(fd[0], "r")) == NULL) {
2544                 perror("fdopen");
2545                 kill(pid, SIGKILL);
2546                 close(fd[0]);
2547                 return -1;
2548         }
2549
2550         while (fgets(buf, PIPE_BUF, fp) != NULL) {
2551                 if (output_func(buf) < 0)
2552                         fprintf(stderr, "WARNING: unexpected error!\n[%s]\n",
2553                                 buf);
2554         }
2555         fclose(fp);
2556         close(fd[0]);
2557
2558         if (waitpid(pid, &status, 0) < 0) {
2559                 perror("waitpid");
2560                 return -1;
2561         }
2562
2563         return child_status(status);
2564 }
2565
2566 int llapi_lsetfacl(int argc, char *argv[])
2567 {
2568         return do_rmtacl(argc, argv, RMT_LSETFACL, NULL);
2569 }
2570
2571 int llapi_lgetfacl(int argc, char *argv[])
2572 {
2573         return do_rmtacl(argc, argv, RMT_LGETFACL, NULL);
2574 }
2575
2576 int llapi_rsetfacl(int argc, char *argv[])
2577 {
2578         return do_rmtacl(argc, argv, RMT_RSETFACL, NULL);
2579 }
2580
2581 int llapi_rgetfacl(int argc, char *argv[])
2582 {
2583         return do_rmtacl(argc, argv, RMT_RGETFACL, rgetfacl_output);
2584 }
2585
2586 int llapi_cp(int argc, char *argv[])
2587 {
2588         int rc;
2589
2590         rc = rmtacl_notify(RMT_RSETFACL);
2591         if (rc < 0)
2592                 return -1;
2593
2594         exit(execvp(argv[0], argv));
2595 }
2596
2597 int llapi_ls(int argc, char *argv[])
2598 {
2599         int rc;
2600
2601         rc = rmtacl_notify(RMT_LGETFACL);
2602         if (rc < 0)
2603                 return -1;
2604
2605         exit(execvp(argv[0], argv));
2606 }
2607
2608 /* Print mdtname 'name' into 'buf' using 'format'.  Add -MDT0000 if needed.
2609  * format must have %s%s, buf must be > 16
2610  */
2611 static int get_mdtname(char *name, char *format, char *buf)
2612 {
2613         char suffix[]="-MDT0000";
2614         int len = strlen(name);
2615
2616         if ((len > 5) && (strncmp(name + len - 5, "_UUID", 5) == 0)) {
2617                 name[len - 5] = '\0';
2618                 len -= 5;
2619         }
2620
2621         if (len > 8) {
2622                 if ((len <= 16) && strncmp(name + len - 8, "-MDT", 4) == 0) {
2623                         suffix[0] = '\0';
2624                 } else {
2625                         /* Not enough room to add suffix */
2626                         llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2627                                   "MDT name too long |%s|", name);
2628                         return -EINVAL;
2629                 }
2630         }
2631
2632         return sprintf(buf, format, name, suffix);
2633 }
2634
2635 /****** Changelog API ********/
2636 #define CHANGELOG_PRIV_MAGIC 0xCA8E1080
2637 struct changelog_private {
2638         int magic;
2639         int fd;
2640         int flags;
2641 };
2642
2643 /** Start reading from a changelog
2644  * @param priv Opaque private control structure
2645  * @param flags Start flags (e.g. follow)
2646  * @param device Report changes recorded on this MDT
2647  * @param startrec Report changes beginning with this record number
2648  */
2649 int llapi_changelog_start(void **priv, int flags, const char *device,
2650                           long long startrec)
2651 {
2652         struct changelog_private *cp;
2653         char path[256];
2654         char mdtname[20];
2655         int rc, fd;
2656
2657         if (device[0] == '/')
2658                 rc = llapi_search_fsname(device, mdtname);
2659         else
2660                 strncpy(mdtname, device, sizeof(mdtname));
2661
2662         /* Use either the mdd changelog (preferred) or a client mdc changelog */
2663         if (get_mdtname(mdtname,
2664                         "/proc/fs/lustre/md[cd]/%s%s{,-mdc-*}/changelog",
2665                         path) < 0)
2666                 return -EINVAL;
2667         rc = first_match(path, path);
2668         if (rc)
2669                 return rc;
2670
2671         if ((fd = open(path, O_RDONLY)) < 0) {
2672                 llapi_err(LLAPI_MSG_ERROR, "error: can't open |%s|\n", path);
2673                 return -errno;
2674         }
2675
2676         rc = lseek(fd, (off_t)startrec, SEEK_SET);
2677         if (rc < 0) {
2678                 llapi_err(LLAPI_MSG_ERROR, "can't seek rc=%d\n", rc);
2679                 return -errno;
2680         }
2681
2682         cp = malloc(sizeof(*cp));
2683         if (cp == NULL) {
2684                 close(fd);
2685                 return -ENOMEM;
2686         }
2687
2688         cp->magic = CHANGELOG_PRIV_MAGIC;
2689         cp->fd = fd;
2690         cp->flags = flags;
2691         *priv = cp;
2692
2693         return 0;
2694 }
2695
2696 /** Finish reading from a changelog */
2697 int llapi_changelog_fini(void **priv)
2698 {
2699         struct changelog_private *cp = (struct changelog_private *)*priv;
2700
2701         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
2702                 return -EINVAL;
2703
2704         close(cp->fd);
2705         free(cp);
2706         *priv = NULL;
2707         return 0;
2708 }
2709
2710 static int pollwait(int fd) {
2711         struct pollfd pfds[1];
2712         int rc;
2713
2714         pfds[0].fd = fd;
2715         pfds[0].events = POLLIN;
2716         rc = poll(pfds, 1, -1);
2717         return rc < 0 ? -errno : rc;
2718 }
2719
2720 /** Read the next changelog entry
2721  * @param priv Opaque private control structure
2722  * @param rech Changelog record handle; record will be allocated here
2723  * @return 0 valid message received; rec is set
2724  *         <0 error code
2725  *         1 EOF
2726  */
2727 int llapi_changelog_recv(void *priv, struct changelog_rec **rech)
2728 {
2729         struct changelog_private *cp = (struct changelog_private *)priv;
2730         struct changelog_rec rec, *recp;
2731         int rc = 0;
2732
2733         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
2734                 return -EINVAL;
2735         if (rech == NULL)
2736                 return -EINVAL;
2737
2738 readrec:
2739         /* Read in the rec to get the namelen */
2740         rc = read(cp->fd, &rec, sizeof(rec));
2741         if (rc < 0)
2742                 return -errno;
2743         if (rc == 0) {
2744                 if (cp->flags && CHANGELOG_FLAG_FOLLOW) {
2745                         rc = pollwait(cp->fd);
2746                         if (rc < 0)
2747                                 return rc;
2748                         goto readrec;
2749                 }
2750                 return 1;
2751         }
2752
2753         recp = malloc(sizeof(rec) + rec.cr_namelen);
2754         if (recp == NULL)
2755                 return -ENOMEM;
2756         memcpy(recp, &rec, sizeof(rec));
2757         rc = read(cp->fd, recp->cr_name, rec.cr_namelen);
2758         if (rc < 0) {
2759                 free(recp);
2760                 llapi_err(LLAPI_MSG_ERROR, "Can't read entire filename");
2761                 return -errno;
2762         }
2763
2764         *rech = recp;
2765         return 0;
2766 }
2767
2768 /** Release the changelog record when done with it. */
2769 int llapi_changelog_free(struct changelog_rec **rech)
2770 {
2771         if (*rech)
2772                 free(*rech);
2773         *rech = NULL;
2774         return 0;
2775 }
2776
2777 int llapi_changelog_clear(const char *mdtname, const char *idstr,
2778                           long long endrec)
2779 {
2780         struct ioc_changelog_clear data;
2781         char fsname[17];
2782         char *ptr;
2783         int id, fd, index, rc;
2784
2785         if (endrec < 0) {
2786                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2787                           "can't purge negative records\n");
2788                 return -EINVAL;
2789         }
2790
2791         id = strtol(idstr + strlen(CHANGELOG_USER_PREFIX), NULL, 10);
2792         if ((id == 0) || (strncmp(idstr, CHANGELOG_USER_PREFIX,
2793                                   strlen(CHANGELOG_USER_PREFIX)) != 0)) {
2794                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2795                           "expecting id of the form '"CHANGELOG_USER_PREFIX
2796                           "<num>'; got '%s'\n", idstr);
2797                 return -EINVAL;
2798         }
2799
2800         /* Take path, fsname, or MDTNAME.  Assume MDT0000 in the former cases */
2801         if (mdtname[0] == '/') {
2802                 index = 0;
2803                 fd = open(mdtname, O_RDONLY | O_DIRECTORY | O_NONBLOCK);
2804                 rc = fd < 0 ? -errno : 0;
2805         } else {
2806                 if (get_mdtname((char *)mdtname, "%s%s", fsname) < 0)
2807                         return -EINVAL;
2808                 ptr = fsname + strlen(fsname) - 8;
2809                 *ptr = '\0';
2810                 index = strtol(ptr + 4, NULL, 10);
2811                 rc = get_root_path(WANT_FD | WANT_ERROR, fsname, &fd, NULL, -1);
2812         }
2813         if (rc < 0) {
2814                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2815                           "Can't open %s: %d\n", mdtname, rc);
2816                 return rc;
2817         }
2818
2819         data.icc_mdtindex = index;
2820         data.icc_id = id;
2821         data.icc_recno = endrec;
2822         rc = ioctl(fd, OBD_IOC_CHANGELOG_CLEAR, &data);
2823         if (rc)
2824                 llapi_err(LLAPI_MSG_ERROR, "ioctl err %d", rc);
2825
2826         close(fd);
2827         return rc;
2828 }
2829
2830 int llapi_fid2path(const char *device, const char *fidstr, char *buf,
2831                    int buflen, long long *recno, int *linkno)
2832 {
2833         char path[PATH_MAX];
2834         struct lu_fid fid;
2835         struct getinfo_fid2path *gf;
2836         int fd, rc;
2837
2838         while (*fidstr == '[')
2839                 fidstr++;
2840
2841         sscanf(fidstr, SFID, RFID(&fid));
2842         if (!fid_is_sane(&fid)) {
2843                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2844                           "bad FID format [%s], should be "DFID"\n",
2845                           fidstr, (__u64)1, 2, 0);
2846                 return -EINVAL;
2847         }
2848
2849         /* Take path or fsname */
2850         if (device[0] == '/') {
2851                 strcpy(path, device);
2852         } else {
2853                 rc = get_root_path(WANT_PATH | WANT_ERROR, (char *)device,
2854                                    NULL, path, -1);
2855                 if (rc < 0)
2856                         return rc;
2857         }
2858         sprintf(path, "%s/%s/fid/%s", path, dot_lustre_name, fidstr);
2859         fd = open(path, O_RDONLY | O_NONBLOCK);
2860         if (fd < 0)
2861                 return -errno;
2862
2863         gf = malloc(sizeof(*gf) + buflen);
2864         gf->gf_fid = fid;
2865         gf->gf_recno = *recno;
2866         gf->gf_linkno = *linkno;
2867         gf->gf_pathlen = buflen;
2868         rc = ioctl(fd, OBD_IOC_FID2PATH, gf);
2869         if (rc) {
2870                 llapi_err(LLAPI_MSG_ERROR, "ioctl err %d", rc);
2871         } else {
2872                 memcpy(buf, gf->gf_path, gf->gf_pathlen);
2873                 *recno = gf->gf_recno;
2874                 *linkno = gf->gf_linkno;
2875         }
2876
2877         free(gf);
2878         close(fd);
2879         return rc;
2880 }
2881
2882 int llapi_path2fid(const char *path, lustre_fid *fid)
2883 {
2884         int fd, rc;
2885
2886         fd = open(path, O_RDONLY);
2887         if (fd < 0)
2888                 return -errno;
2889
2890         rc = ioctl(fd, LL_IOC_PATH2FID, fid);
2891
2892         close(fd);
2893         return rc;
2894 }
2895
2896 /****** HSM Copytool API ********/
2897 #define CT_PRIV_MAGIC 0xC0BE2001
2898 struct copytool_private {
2899         int magic;
2900         lustre_netlink lnl;
2901         int archive_num_count;
2902         int archive_nums[0];
2903 };
2904
2905 #include <libcfs/libcfs.h>
2906
2907 /** Register a copytool
2908  * @param priv Opaque private control structure
2909  * @param flags Open flags, currently unused (e.g. O_NONBLOCK)
2910  * @param archive_nums Which archive numbers this copytool is responsible for
2911  */
2912 int llapi_copytool_start(void **priv, int flags, int archive_num_count,
2913                          int *archive_nums)
2914 {
2915         struct copytool_private *ct;
2916         int rc;
2917
2918         if (archive_num_count > 0 && archive_nums == NULL) {
2919                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2920                           "NULL archive numbers");
2921                 return -EINVAL;
2922         }
2923
2924         ct = malloc(sizeof(*ct) +
2925                     archive_num_count * sizeof(ct->archive_nums[0]));
2926         if (ct == NULL)
2927                 return -ENOMEM;
2928
2929         ct->magic = CT_PRIV_MAGIC;
2930         ct->archive_num_count = archive_num_count;
2931         if (ct->archive_num_count > 0)
2932                 memcpy(ct->archive_nums, archive_nums, archive_num_count *
2933                        sizeof(ct->archive_nums[0]));
2934
2935         rc = libcfs_ulnl_start(&ct->lnl, LNL_GRP_HSM);
2936         if (rc < 0)
2937                 goto out_err;
2938
2939         *priv = ct;
2940         return 0;
2941
2942 out_err:
2943         free(ct);
2944         return rc;
2945 }
2946
2947 /** Deregister a copytool */
2948 int llapi_copytool_fini(void **priv)
2949 {
2950         struct copytool_private *ct = (struct copytool_private *)*priv;
2951
2952         if (!ct || (ct->magic != CT_PRIV_MAGIC))
2953                 return -EINVAL;
2954
2955         libcfs_ulnl_stop(&ct->lnl);
2956         free(ct);
2957         *priv = NULL;
2958         return 0;
2959 }
2960
2961 /** Wait for the next hsm_action_list
2962  * @param priv Opaque private control structure
2963  * @param halh Action list handle, will be allocated here
2964  * @param msgsize Number of bytes in the message, will be set here
2965  * @return 0 valid message received; halh and msgsize are set
2966  *         <0 error code
2967  */
2968 int llapi_copytool_recv(void *priv, struct hsm_action_list **halh, int *msgsize)
2969 {
2970         struct copytool_private *ct = (struct copytool_private *)priv;
2971         struct lnl_hdr *lnlh;
2972         struct hsm_action_list *hal;
2973         int rc = 0;
2974
2975         if (!ct || (ct->magic != CT_PRIV_MAGIC))
2976                 return -EINVAL;
2977         if (halh == NULL || msgsize == NULL)
2978                 return -EINVAL;
2979
2980         rc = libcfs_ulnl_msg_get(&ct->lnl, HAL_MAXSIZE,
2981                                  LNL_TRANSPORT_HSM, &lnlh);
2982         if (rc < 0)
2983                 return rc;
2984
2985         /* Handle generic messages */
2986         if (lnlh->lnl_transport == LNL_TRANSPORT_GENERIC &&
2987             lnlh->lnl_msgtype == LNL_MSG_SHUTDOWN) {
2988                 rc = -ESHUTDOWN;
2989                 goto out_free;
2990         }
2991
2992         if (lnlh->lnl_transport != LNL_TRANSPORT_HSM ||
2993             lnlh->lnl_msgtype != HMT_ACTION_LIST) {
2994                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2995                           "Unknown HSM message type %d:%d\n",
2996                           lnlh->lnl_transport, lnlh->lnl_msgtype);
2997                 rc = -EPROTO;
2998                 goto out_free;
2999         }
3000
3001         /* Our message is an hsm_action_list */
3002
3003         hal = (struct hsm_action_list *)(lnlh + 1);
3004
3005         /* Check that we have registered for this archive # */
3006         for (rc = 0; rc < ct->archive_num_count; rc++) {
3007                 if (hal->hal_archive_num == ct->archive_nums[rc])
3008                         break;
3009         }
3010         if (rc >= ct->archive_num_count) {
3011                 CDEBUG(D_INFO, "This copytool does not service archive #%d, "
3012                        "ignoring this request.\n", hal->hal_archive_num);
3013                 rc = 0;
3014                 goto out_free;
3015         }
3016
3017         *halh = hal;
3018         *msgsize = lnlh->lnl_msglen - sizeof(*lnlh);
3019         return 0;
3020
3021 out_free:
3022         libcfs_ulnl_msg_free(&lnlh);
3023         *halh = NULL;
3024         *msgsize = 0;
3025         return rc;
3026 }
3027
3028 /** Release the action list when done with it. */
3029 int llapi_copytool_free(struct hsm_action_list **hal)
3030 {
3031         if (*hal) {
3032                 struct lnl_hdr *lnlh = (struct lnl_hdr *)*hal - 1;
3033                 libcfs_ulnl_msg_free(&lnlh);
3034         }
3035         *hal = NULL;
3036         return 0;
3037 }
3038
3039
3040