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