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