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