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