Whamcloud - gitweb
LU-1270 utils: properly initialize traverse param
[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         param->mdtindex = OBD_NOT_FOUND;
1137         return 0;
1138 }
1139
1140 static void find_param_fini(struct find_param *param)
1141 {
1142         if (param->obdindexes)
1143                 free(param->obdindexes);
1144
1145         if (param->lmd)
1146                 free(param->lmd);
1147 }
1148
1149 static int cb_common_fini(char *path, DIR *parent, DIR *d, void *data,
1150                           cfs_dirent_t *de)
1151 {
1152         struct find_param *param = (struct find_param *)data;
1153         param->depth--;
1154         return 0;
1155 }
1156
1157 /* set errno upon failure */
1158 static DIR *opendir_parent(char *path)
1159 {
1160         DIR *parent;
1161         char *fname;
1162         char c;
1163
1164         fname = strrchr(path, '/');
1165         if (fname == NULL)
1166                 return opendir(".");
1167
1168         c = fname[1];
1169         fname[1] = '\0';
1170         parent = opendir(path);
1171         fname[1] = c;
1172         return parent;
1173 }
1174
1175 static int get_lmd_info(char *path, DIR *parent, DIR *dir,
1176                  struct lov_user_mds_data *lmd, int lumlen)
1177 {
1178         lstat_t *st = &lmd->lmd_st;
1179         int ret = 0;
1180
1181         if (parent == NULL && dir == NULL)
1182                 return -EINVAL;
1183
1184         if (dir) {
1185                 ret = ioctl(dirfd(dir), LL_IOC_MDC_GETINFO, (void *)lmd);
1186         } else if (parent) {
1187                 char *fname = strrchr(path, '/');
1188
1189                 fname = (fname == NULL ? path : fname + 1);
1190                 /* retrieve needed file info */
1191                 strncpy((char *)lmd, fname, lumlen);
1192                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO, (void *)lmd);
1193         } else {
1194                 return ret;
1195         }
1196
1197         if (ret) {
1198                 if (errno == ENOTTY) {
1199                         /* ioctl is not supported, it is not a lustre fs.
1200                          * Do the regular lstat(2) instead. */
1201                         ret = lstat_f(path, st);
1202                         if (ret) {
1203                                 ret = -errno;
1204                                 llapi_error(LLAPI_MSG_ERROR, ret,
1205                                             "error: %s: lstat failed for %s",
1206                                             __func__, path);
1207                         }
1208                 } else if (errno == ENOENT) {
1209                         ret = -errno;
1210                         llapi_error(LLAPI_MSG_WARN, ret,
1211                                     "warning: %s: %s does not exist",
1212                                     __func__, path);
1213                 } else if (errno != EISDIR) {
1214                         ret = -errno;
1215                         llapi_error(LLAPI_MSG_ERROR, ret,
1216                                     "%s ioctl failed for %s.",
1217                                     dir ? "LL_IOC_MDC_GETINFO" :
1218                                     "IOC_MDC_GETFILEINFO", path);
1219                 } else {
1220                         ret = -errno;
1221                         llapi_error(LLAPI_MSG_ERROR, ret,
1222                                    "error: %s: IOC_MDC_GETFILEINFO failed for %s",
1223                                    __func__, path);
1224                 }
1225         }
1226         return ret;
1227 }
1228
1229 int llapi_mds_getfileinfo(char *path, DIR *parent,
1230                           struct lov_user_mds_data *lmd)
1231 {
1232         int lumlen = get_mds_md_size(path);
1233
1234         return get_lmd_info(path, parent, NULL, lmd, lumlen);
1235 }
1236
1237 static int llapi_semantic_traverse(char *path, int size, DIR *parent,
1238                                    semantic_func_t sem_init,
1239                                    semantic_func_t sem_fini, void *data,
1240                                    cfs_dirent_t *de)
1241 {
1242         cfs_dirent_t *dent;
1243         int len, ret;
1244         DIR *d, *p = NULL;
1245
1246         ret = 0;
1247         len = strlen(path);
1248
1249         d = opendir(path);
1250         if (!d && errno != ENOTDIR) {
1251                 ret = -errno;
1252                 llapi_error(LLAPI_MSG_ERROR, ret, "%s: Failed to open '%s'",
1253                             __func__, path);
1254                 return ret;
1255         } else if (!d && !parent) {
1256                 /* ENOTDIR. Open the parent dir. */
1257                 p = opendir_parent(path);
1258                 if (!p)
1259                         GOTO(out, ret = -errno);
1260         }
1261
1262         if (sem_init && (ret = sem_init(path, parent ?: p, d, data, de)))
1263                 goto err;
1264
1265         if (!d)
1266                 GOTO(out, ret = 0);
1267
1268         while ((dent = readdir64(d)) != NULL) {
1269                 ((struct find_param *)data)->have_fileinfo = 0;
1270
1271                 if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
1272                         continue;
1273
1274                 /* Don't traverse .lustre directory */
1275                 if (!(strcmp(dent->d_name, dot_lustre_name)))
1276                         continue;
1277
1278                 path[len] = 0;
1279                 if ((len + dent->d_reclen + 2) > size) {
1280                         llapi_err_noerrno(LLAPI_MSG_ERROR,
1281                                           "error: %s: string buffer is too small",
1282                                           __func__);
1283                         break;
1284                 }
1285                 strcat(path, "/");
1286                 strcat(path, dent->d_name);
1287
1288                 if (dent->d_type == DT_UNKNOWN) {
1289                         lstat_t *st = &((struct find_param *)data)->lmd->lmd_st;
1290
1291                         ret = llapi_mds_getfileinfo(path, d,
1292                                              ((struct find_param *)data)->lmd);
1293                         if (ret == 0) {
1294                                 ((struct find_param *)data)->have_fileinfo = 1;
1295                                 dent->d_type =
1296                                         llapi_filetype_dir_table[st->st_mode &
1297                                                                  S_IFMT];
1298                         }
1299                         if (ret == -ENOENT)
1300                                 continue;
1301                 }
1302
1303                 switch (dent->d_type) {
1304                 case DT_UNKNOWN:
1305                         llapi_err_noerrno(LLAPI_MSG_ERROR,
1306                                           "error: %s: '%s' is UNKNOWN type %d",
1307                                           __func__, dent->d_name, dent->d_type);
1308                         break;
1309                 case DT_DIR:
1310                         ret = llapi_semantic_traverse(path, size, d, sem_init,
1311                                                       sem_fini, data, dent);
1312                         if (ret < 0)
1313                                 goto out;
1314                         break;
1315                 default:
1316                         ret = 0;
1317                         if (sem_init) {
1318                                 ret = sem_init(path, d, NULL, data, dent);
1319                                 if (ret < 0)
1320                                         goto out;
1321                         }
1322                         if (sem_fini && ret == 0)
1323                                 sem_fini(path, d, NULL, data, dent);
1324                 }
1325         }
1326
1327 out:
1328         path[len] = 0;
1329
1330         if (sem_fini)
1331                 sem_fini(path, parent, d, data, de);
1332 err:
1333         if (d)
1334                 closedir(d);
1335         if (p)
1336                 closedir(p);
1337         return ret;
1338 }
1339
1340 static int param_callback(char *path, semantic_func_t sem_init,
1341                           semantic_func_t sem_fini, struct find_param *param)
1342 {
1343         int ret, len = strlen(path);
1344         char *buf;
1345
1346         if (len > PATH_MAX) {
1347                 ret = -EINVAL;
1348                 llapi_error(LLAPI_MSG_ERROR, ret,
1349                             "Path name '%s' is too long", path);
1350                 return ret;
1351         }
1352
1353         buf = (char *)malloc(PATH_MAX + 1);
1354         if (!buf)
1355                 return -ENOMEM;
1356
1357         strncpy(buf, path, PATH_MAX + 1);
1358         ret = common_param_init(param, buf);
1359         if (ret)
1360                 goto out;
1361         param->depth = 0;
1362
1363         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, sem_init,
1364                                       sem_fini, param, NULL);
1365 out:
1366         find_param_fini(param);
1367         free(buf);
1368         return ret < 0 ? ret : 0;
1369 }
1370
1371 int llapi_file_fget_lov_uuid(int fd, struct obd_uuid *lov_name)
1372 {
1373         int rc = ioctl(fd, OBD_IOC_GETNAME, lov_name);
1374         if (rc) {
1375                 rc = -errno;
1376                 llapi_error(LLAPI_MSG_ERROR, rc, "error: can't get lov name.");
1377         }
1378         return rc;
1379 }
1380
1381 int llapi_file_fget_lmv_uuid(int fd, struct obd_uuid *lov_name)
1382 {
1383         int rc = ioctl(fd, OBD_IOC_GETMDNAME, lov_name);
1384         if (rc) {
1385                 rc = -errno;
1386                 llapi_error(LLAPI_MSG_ERROR, rc, "error: can't get lmv name.");
1387         }
1388         return rc;
1389 }
1390
1391 int llapi_file_get_lov_uuid(const char *path, struct obd_uuid *lov_uuid)
1392 {
1393         int fd, rc;
1394
1395         fd = open(path, O_RDONLY);
1396         if (fd < 0) {
1397                 rc = -errno;
1398                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s", path);
1399                 return rc;
1400         }
1401
1402         rc = llapi_file_fget_lov_uuid(fd, lov_uuid);
1403
1404         close(fd);
1405         return rc;
1406 }
1407
1408 enum tgt_type {
1409         LOV_TYPE = 1,
1410         LMV_TYPE
1411 };
1412 /*
1413  * If uuidp is NULL, return the number of available obd uuids.
1414  * If uuidp is non-NULL, then it will return the uuids of the obds. If
1415  * there are more OSTs then allocated to uuidp, then an error is returned with
1416  * the ost_count set to number of available obd uuids.
1417  */
1418 static int llapi_get_target_uuids(int fd, struct obd_uuid *uuidp,
1419                                   int *ost_count, enum tgt_type type)
1420 {
1421         struct obd_uuid name;
1422         char buf[1024];
1423         FILE *fp;
1424         int rc = 0, index = 0;
1425
1426         /* Get the lov name */
1427         if (type == LOV_TYPE) {
1428                 rc = llapi_file_fget_lov_uuid(fd, &name);
1429                 if (rc)
1430                         return rc;
1431         } else {
1432                 rc = llapi_file_fget_lmv_uuid(fd, &name);
1433                 if (rc)
1434                         return rc;
1435         }
1436
1437         /* Now get the ost uuids from /proc */
1438         snprintf(buf, sizeof(buf), "/proc/fs/lustre/%s/%s/target_obd",
1439                  type == LOV_TYPE ? "lov" : "lmv", name.uuid);
1440         fp = fopen(buf, "r");
1441         if (fp == NULL) {
1442                 rc = -errno;
1443                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening '%s'", buf);
1444                 return rc;
1445         }
1446
1447         while (fgets(buf, sizeof(buf), fp) != NULL) {
1448                 if (uuidp && (index < *ost_count)) {
1449                         if (sscanf(buf, "%d: %s", &index, uuidp[index].uuid) <2)
1450                                 break;
1451                 }
1452                 index++;
1453         }
1454
1455         fclose(fp);
1456
1457         if (uuidp && (index > *ost_count))
1458                 rc = -EOVERFLOW;
1459
1460         *ost_count = index;
1461         return rc;
1462 }
1463
1464 int llapi_lov_get_uuids(int fd, struct obd_uuid *uuidp, int *ost_count)
1465 {
1466         return llapi_get_target_uuids(fd, uuidp, ost_count, LOV_TYPE);
1467 }
1468
1469 int llapi_get_obd_count(char *mnt, int *count, int is_mdt)
1470 {
1471         DIR *root;
1472         int rc;
1473
1474         root = opendir(mnt);
1475         if (!root) {
1476                 rc = -errno;
1477                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
1478                 return rc;
1479         }
1480
1481         *count = is_mdt;
1482         rc = ioctl(dirfd(root), LL_IOC_GETOBDCOUNT, count);
1483         if (rc < 0)
1484                 rc = -errno;
1485
1486         closedir(root);
1487         return rc;
1488 }
1489
1490 /* Check if user specified value matches a real uuid.  Ignore _UUID,
1491  * -osc-4ba41334, other trailing gunk in comparison.
1492  * @param real_uuid ends in "_UUID"
1493  * @param search_uuid may or may not end in "_UUID"
1494  */
1495 int llapi_uuid_match(char *real_uuid, char *search_uuid)
1496 {
1497         int cmplen = strlen(real_uuid);
1498         int searchlen = strlen(search_uuid);
1499
1500         if (cmplen > 5 && strcmp(real_uuid + cmplen - 5, "_UUID") == 0)
1501                 cmplen -= 5;
1502         if (searchlen > 5 && strcmp(search_uuid + searchlen - 5, "_UUID") == 0)
1503                 searchlen -= 5;
1504
1505         /* The UUIDs may legitimately be different lengths, if
1506          * the system was upgraded from an older version. */
1507         if (cmplen != searchlen)
1508                 return 0;
1509
1510         return (strncmp(search_uuid, real_uuid, cmplen) == 0);
1511 }
1512
1513 /* Here, param->obduuid points to a single obduuid, the index of which is
1514  * returned in param->obdindex */
1515 static int setup_obd_uuid(DIR *dir, char *dname, struct find_param *param)
1516 {
1517         struct obd_uuid obd_uuid;
1518         char uuid[sizeof(struct obd_uuid)];
1519         char buf[1024];
1520         FILE *fp;
1521         int rc = 0, index;
1522
1523         if (param->got_uuids)
1524                 return rc;
1525
1526         /* Get the lov/lmv name */
1527         if (param->get_lmv)
1528                 rc = llapi_file_fget_lmv_uuid(dirfd(dir), &obd_uuid);
1529         else
1530                 rc = llapi_file_fget_lov_uuid(dirfd(dir), &obd_uuid);
1531         if (rc) {
1532                 if (rc != -ENOTTY) {
1533                         llapi_error(LLAPI_MSG_ERROR, rc,
1534                                     "error: can't get lov name: %s", dname);
1535                 } else {
1536                         rc = 0;
1537                 }
1538                 return rc;
1539         }
1540
1541         param->got_uuids = 1;
1542
1543         /* Now get the ost uuids from /proc */
1544         snprintf(buf, sizeof(buf), "/proc/fs/lustre/%s/%s/target_obd",
1545                  param->get_lmv ? "lmv" : "lov", obd_uuid.uuid);
1546         fp = fopen(buf, "r");
1547         if (fp == NULL) {
1548                 rc = -errno;
1549                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening '%s'", buf);
1550                 return rc;
1551         }
1552
1553         if (!param->obduuid && !param->quiet && !param->obds_printed)
1554                 llapi_printf(LLAPI_MSG_NORMAL, "%s:\n",
1555                              param->get_lmv ? "MDTS" : "OBDS:");
1556
1557         while (fgets(buf, sizeof(buf), fp) != NULL) {
1558                 if (sscanf(buf, "%d: %s", &index, uuid) < 2)
1559                         break;
1560
1561                 if (param->obduuid) {
1562                         if (llapi_uuid_match(uuid, param->obduuid->uuid)) {
1563                                 param->obdindex = index;
1564                                 break;
1565                         }
1566                 } else if (!param->quiet && !param->obds_printed) {
1567                         /* Print everything */
1568                         llapi_printf(LLAPI_MSG_NORMAL, "%s", buf);
1569                 }
1570         }
1571         param->obds_printed = 1;
1572
1573         fclose(fp);
1574
1575         if (param->obduuid && (param->obdindex == OBD_NOT_FOUND)) {
1576                 llapi_err_noerrno(LLAPI_MSG_ERROR,
1577                                   "error: %s: unknown obduuid: %s",
1578                                   __func__, param->obduuid->uuid);
1579                 rc = -EINVAL;
1580         }
1581
1582         return (rc);
1583 }
1584
1585 /* In this case, param->obduuid will be an array of obduuids and
1586  * obd index for all these obduuids will be returned in
1587  * param->obdindexes */
1588 static int setup_indexes(DIR *dir, char *path, struct obd_uuid *obduuids,
1589                          int num_obds, int **obdindexes, int *obdindex,
1590                          enum tgt_type type)
1591 {
1592         int ret, obdcount, obd_valid = 0, obdnum, i;
1593         struct obd_uuid *uuids = NULL;
1594         char buf[16];
1595         int *indexes;
1596
1597         ret = get_param_obdvar(NULL, path, type == LOV_TYPE ? "lov" : "lmv",
1598                                "numobd", buf, sizeof(buf));
1599         if (ret)
1600                 return ret;
1601
1602         obdcount = atoi(buf);
1603         uuids = (struct obd_uuid *)malloc(obdcount *
1604                                           sizeof(struct obd_uuid));
1605         if (uuids == NULL)
1606                 return -ENOMEM;
1607
1608 retry_get_uuids:
1609         ret = llapi_get_target_uuids(dirfd(dir), uuids, &obdcount, type);
1610         if (ret) {
1611                 struct obd_uuid *uuids_temp;
1612
1613                 if (ret == -EOVERFLOW) {
1614                         uuids_temp = realloc(uuids, obdcount *
1615                                              sizeof(struct obd_uuid));
1616                         if (uuids_temp != NULL) {
1617                                 uuids = uuids_temp;
1618                                 goto retry_get_uuids;
1619                         }
1620                         else
1621                                 ret = -ENOMEM;
1622                 }
1623
1624                 llapi_error(LLAPI_MSG_ERROR, ret, "get ost uuid failed");
1625                 goto out_free;
1626         }
1627
1628         indexes = malloc(num_obds * sizeof(*obdindex));
1629         if (indexes == NULL) {
1630                 ret = -ENOMEM;
1631                 goto out_free;
1632         }
1633
1634         for (obdnum = 0; obdnum < num_obds; obdnum++) {
1635                 char *end = NULL;
1636
1637                 /* The user may have specified a simple index */
1638                 i = strtol(obduuids[obdnum].uuid, &end, 0);
1639                 if (end && *end == '\0' && i < obdcount) {
1640                         indexes[obdnum] = i;
1641                         obd_valid++;
1642                 } else {
1643                         for (i = 0; i < obdcount; i++) {
1644                                 if (llapi_uuid_match(uuids[i].uuid,
1645                                                      obduuids[obdnum].uuid)) {
1646                                         indexes[obdnum] = i;
1647                                         obd_valid++;
1648                                         break;
1649                                 }
1650                         }
1651                 }
1652                 if (i >= obdcount) {
1653                         indexes[obdnum] = OBD_NOT_FOUND;
1654                         llapi_err_noerrno(LLAPI_MSG_ERROR,
1655                                           "error: %s: unknown obduuid: %s",
1656                                           __func__, obduuids[obdnum].uuid);
1657                         ret = -EINVAL;
1658                 }
1659         }
1660
1661         if (obd_valid == 0)
1662                 *obdindex = OBD_NOT_FOUND;
1663         else
1664                 *obdindex = obd_valid;
1665
1666         *obdindexes = indexes;
1667 out_free:
1668         if (uuids)
1669                 free(uuids);
1670
1671         return ret;
1672 }
1673
1674 static int setup_target_indexes(DIR *dir, char *path, struct find_param *param)
1675 {
1676         int ret = 0;
1677
1678         if (param->mdtuuid) {
1679                 ret = setup_indexes(dir, path, param->mdtuuid, param->num_mdts,
1680                               &param->mdtindexes, &param->mdtindex, LMV_TYPE);
1681                 if (ret)
1682                         return ret;
1683         }
1684         if (param->obduuid) {
1685                 ret = setup_indexes(dir, path, param->obduuid, param->num_obds,
1686                               &param->obdindexes, &param->obdindex, LOV_TYPE);
1687                 if (ret)
1688                         return ret;
1689         }
1690         param->got_uuids = 1;
1691         return ret;
1692 }
1693
1694 int llapi_ostlist(char *path, struct find_param *param)
1695 {
1696         DIR *dir;
1697         int ret;
1698
1699         dir = opendir(path);
1700         if (dir == NULL)
1701                 return -errno;
1702
1703         ret = setup_obd_uuid(dir, path, param);
1704         closedir(dir);
1705
1706         return ret;
1707 }
1708
1709 /*
1710  * Given a filesystem name, or a pathname of a file on a lustre filesystem,
1711  * tries to determine the path to the filesystem's clilov directory under /proc
1712  *
1713  * fsname is limited to MTI_NAME_MAXLEN in lustre_idl.h
1714  * The NUL terminator is compensated by the additional "%s" bytes. */
1715 #define LOV_LEN (sizeof("/proc/fs/lustre/lov/%s-clilov-*") + MTI_NAME_MAXLEN)
1716 static int clilovpath(const char *fsname, const char *const pathname,
1717                       char *clilovpath)
1718 {
1719         int rc;
1720         char pattern[LOV_LEN];
1721         char buffer[PATH_MAX + 1];
1722
1723         if (fsname == NULL) {
1724                 rc = llapi_search_fsname(pathname, buffer);
1725                 if (rc != 0)
1726                         return rc;
1727                 fsname = buffer;
1728         }
1729
1730         snprintf(pattern, sizeof(pattern), "/proc/fs/lustre/lov/%s-clilov-*",
1731                  fsname);
1732
1733         rc = first_match(pattern, buffer);
1734         if (rc != 0)
1735                 return rc;
1736
1737         strncpy(clilovpath, buffer, sizeof(buffer));
1738
1739         return 0;
1740 }
1741
1742 /*
1743  * Given the path to a stripe attribute proc file, tries to open and
1744  * read the attribute and return the value using the attr parameter
1745  */
1746 static int sattr_read_attr(const char *const fpath,
1747                            unsigned int *attr)
1748 {
1749
1750         FILE *f;
1751         char line[PATH_MAX + 1];
1752         int rc = 0;
1753
1754         f = fopen(fpath, "r");
1755         if (f == NULL) {
1756                 rc = -errno;
1757                 llapi_error(LLAPI_MSG_ERROR, rc, "Cannot open '%s'", fpath);
1758                 return rc;
1759         }
1760
1761         if (fgets(line, sizeof(line), f) != NULL) {
1762                 *attr = atoi(line);
1763         } else {
1764                 llapi_error(LLAPI_MSG_ERROR, errno, "Cannot read from '%s'", fpath);
1765                 rc = 1;
1766         }
1767
1768         fclose(f);
1769         return rc;
1770 }
1771
1772 /*
1773  * Tries to determine the default stripe attributes for a given filesystem. The
1774  * filesystem to check should be specified by fsname, or will be determined
1775  * using pathname.
1776  */
1777 static int sattr_get_defaults(const char *const fsname,
1778                               const char *const pathname,
1779                               unsigned int *scount,
1780                               unsigned int *ssize,
1781                               unsigned int *soffset)
1782 {
1783         int rc;
1784         char dpath[PATH_MAX + 1];
1785         char fpath[PATH_MAX + 1];
1786
1787         rc = clilovpath(fsname, pathname, dpath);
1788         if (rc != 0)
1789                 return rc;
1790
1791         if (scount) {
1792                 snprintf(fpath, PATH_MAX, "%s/stripecount", dpath);
1793                 rc = sattr_read_attr(fpath, scount);
1794                 if (rc != 0)
1795                         return rc;
1796         }
1797
1798         if (ssize) {
1799                 snprintf(fpath, PATH_MAX, "%s/stripesize", dpath);
1800                 rc = sattr_read_attr(fpath, ssize);
1801                 if (rc != 0)
1802                         return rc;
1803         }
1804
1805         if (soffset) {
1806                 snprintf(fpath, PATH_MAX, "%s/stripeoffset", dpath);
1807                 rc = sattr_read_attr(fpath, soffset);
1808                 if (rc != 0)
1809                         return rc;
1810         }
1811
1812         return 0;
1813 }
1814
1815 /*
1816  * Tries to gather the default stripe attributes for a given filesystem. If
1817  * the attributes can be determined, they are cached for easy retreival the
1818  * next time they are needed. Only a single filesystem's attributes are
1819  * cached at a time.
1820  */
1821 static int sattr_cache_get_defaults(const char *const fsname,
1822                                     const char *const pathname,
1823                                     unsigned int *scount,
1824                                     unsigned int *ssize,
1825                                     unsigned int *soffset)
1826 {
1827         static struct {
1828                 char fsname[PATH_MAX + 1];
1829                 unsigned int stripecount;
1830                 unsigned int stripesize;
1831                 unsigned int stripeoffset;
1832         } cache = {
1833                 .fsname = {'\0'}
1834         };
1835
1836         int rc;
1837         char fsname_buf[PATH_MAX + 1];
1838         unsigned int tmp[3];
1839
1840         if (fsname == NULL) {
1841                 rc = llapi_search_fsname(pathname, fsname_buf);
1842                 if (rc)
1843                         return rc;
1844         } else {
1845                 strncpy(fsname_buf, fsname, PATH_MAX);
1846         }
1847
1848         if (strncmp(fsname_buf, cache.fsname, PATH_MAX) != 0) {
1849                 /*
1850                  * Ensure all 3 sattrs (count, size, and offset) are
1851                  * successfully retrieved and stored in tmp before writing to
1852                  * cache.
1853                  */
1854                 rc = sattr_get_defaults(fsname_buf, NULL, &tmp[0], &tmp[1],
1855                                         &tmp[2]);
1856                 if (rc != 0)
1857                         return rc;
1858
1859                 cache.stripecount = tmp[0];
1860                 cache.stripesize = tmp[1];
1861                 cache.stripeoffset = tmp[2];
1862                 strncpy(cache.fsname, fsname_buf, PATH_MAX);
1863         }
1864
1865         if (scount)
1866                 *scount = cache.stripecount;
1867         if (ssize)
1868                 *ssize = cache.stripesize;
1869         if (soffset)
1870                 *soffset = cache.stripeoffset;
1871
1872         return 0;
1873 }
1874
1875 static void lov_dump_user_lmm_header(struct lov_user_md *lum, char *path,
1876                                      struct lov_user_ost_data_v1 *objects,
1877                                      int is_dir, int verbose, int depth,
1878                                      int raw, char *pool_name)
1879 {
1880         char *prefix = is_dir ? "" : "lmm_";
1881         char nl = is_dir ? ' ' : '\n';
1882         int rc;
1883
1884         if (is_dir && lum->lmm_object_seq == FID_SEQ_LOV_DEFAULT) {
1885                 lum->lmm_object_seq = FID_SEQ_OST_MDT0;
1886                 if (verbose & VERBOSE_DETAIL)
1887                         llapi_printf(LLAPI_MSG_NORMAL, "(Default) ");
1888         }
1889
1890         if (depth && path && ((verbose != VERBOSE_OBJID) || !is_dir))
1891                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
1892
1893         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
1894                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_magic:          0x%08X\n",
1895                              lum->lmm_magic);
1896                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_seq:            "LPX64"\n",
1897                              lum->lmm_object_seq);
1898                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_id:      "LPX64"\n",
1899                              lum->lmm_object_id);
1900         }
1901
1902         if (verbose & VERBOSE_COUNT) {
1903                 if (verbose & ~VERBOSE_COUNT)
1904                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_count:   ",
1905                                      prefix);
1906                 if (is_dir) {
1907                         if (!raw && lum->lmm_stripe_count == 0) {
1908                                 unsigned int scount;
1909                                 rc = sattr_cache_get_defaults(NULL, path,
1910                                                               &scount, NULL,
1911                                                               NULL);
1912                                 if (rc == 0)
1913                                         llapi_printf(LLAPI_MSG_NORMAL, "%d%c",
1914                                                      scount, nl);
1915                                 else
1916                                         llapi_error(LLAPI_MSG_ERROR, rc,
1917                                                     "Cannot determine default"
1918                                                     " stripe count.");
1919                         } else {
1920                                 llapi_printf(LLAPI_MSG_NORMAL, "%d%c",
1921                                              lum->lmm_stripe_count ==
1922                                              (typeof(lum->lmm_stripe_count))(-1)
1923                                              ? -1 : lum->lmm_stripe_count, nl);
1924                         }
1925                 } else {
1926                         llapi_printf(LLAPI_MSG_NORMAL, "%hd%c",
1927                                      (__s16)lum->lmm_stripe_count, nl);
1928                 }
1929         }
1930
1931         if (verbose & VERBOSE_SIZE) {
1932                 if (verbose & ~VERBOSE_SIZE)
1933                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_size:    ",
1934                                      prefix);
1935                 if (is_dir && !raw && lum->lmm_stripe_size == 0) {
1936                         unsigned int ssize;
1937                         rc = sattr_cache_get_defaults(NULL, path, NULL, &ssize,
1938                                                       NULL);
1939                         if (rc == 0)
1940                                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c", ssize,
1941                                              nl);
1942                         else
1943                                 llapi_error(LLAPI_MSG_ERROR, rc,
1944                                             "Cannot determine default"
1945                                             " stripe size.");
1946                 } else {
1947                         llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
1948                                      lum->lmm_stripe_size, nl);
1949                 }
1950         }
1951
1952         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
1953                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_stripe_pattern: %x%c",
1954                              lum->lmm_pattern, nl);
1955         }
1956
1957         if ((verbose & VERBOSE_GENERATION) && !is_dir) {
1958                 if (verbose & ~VERBOSE_GENERATION)
1959                         llapi_printf(LLAPI_MSG_NORMAL, "%slayout_gen:     ",
1960                                      prefix);
1961                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
1962                              (int)lum->u.lum_layout_gen, nl);
1963         }
1964
1965         if (verbose & VERBOSE_OFFSET) {
1966                 if (verbose & ~VERBOSE_OFFSET)
1967                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_offset:  ",
1968                                      prefix);
1969                 if (is_dir)
1970                         llapi_printf(LLAPI_MSG_NORMAL, "%d%c",
1971                                      lum->lmm_stripe_offset ==
1972                                      (typeof(lum->lmm_stripe_offset))(-1) ? -1 :
1973                                      lum->lmm_stripe_offset, nl);
1974                 else
1975                         llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
1976                                      objects[0].l_ost_idx, nl);
1977         }
1978
1979         if ((verbose & VERBOSE_POOL) && (pool_name != NULL)) {
1980                 if (verbose & ~VERBOSE_POOL)
1981                         llapi_printf(LLAPI_MSG_NORMAL, "%spool:           ",
1982                                      prefix);
1983                 llapi_printf(LLAPI_MSG_NORMAL, "%s%c", pool_name, nl);
1984         }
1985
1986         if (is_dir && (verbose != VERBOSE_OBJID))
1987                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1988 }
1989
1990 void lov_dump_user_lmm_v1v3(struct lov_user_md *lum, char *pool_name,
1991                             struct lov_user_ost_data_v1 *objects,
1992                             char *path, int is_dir, int obdindex,
1993                             int depth, int header, int raw)
1994 {
1995         int i, obdstripe = (obdindex != OBD_NOT_FOUND) ? 0 : 1;
1996
1997         if (!obdstripe) {
1998                 for (i = 0; !is_dir && i < lum->lmm_stripe_count; i++) {
1999                         if (obdindex == objects[i].l_ost_idx) {
2000                                 obdstripe = 1;
2001                                 break;
2002                         }
2003                 }
2004         }
2005
2006         if (obdstripe == 1)
2007                 lov_dump_user_lmm_header(lum, path, objects, is_dir, header,
2008                                          depth, raw, pool_name);
2009
2010         if (!is_dir && (header & VERBOSE_OBJID)) {
2011                 if (obdstripe == 1)
2012                         llapi_printf(LLAPI_MSG_NORMAL,
2013                                      "\tobdidx\t\t objid\t\tobjid\t\t group\n");
2014
2015                 for (i = 0; i < lum->lmm_stripe_count; i++) {
2016                         int idx = objects[i].l_ost_idx;
2017                         long long oid = objects[i].l_object_id;
2018                         long long gr = objects[i].l_object_seq;
2019                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
2020                                 llapi_printf(LLAPI_MSG_NORMAL,
2021                                            "\t%6u\t%14llu\t%#13llx\t%14llu%s\n",
2022                                            idx, oid, oid, gr,
2023                                            obdindex == idx ? " *" : "");
2024                 }
2025                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
2026         }
2027 }
2028
2029 void llapi_lov_dump_user_lmm(struct find_param *param,
2030                              char *path, int is_dir)
2031 {
2032         switch(*(__u32 *)&param->lmd->lmd_lmm) { /* lum->lmm_magic */
2033         case LOV_USER_MAGIC_V1:
2034                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, NULL,
2035                                        param->lmd->lmd_lmm.lmm_objects,
2036                                        path, is_dir,
2037                                        param->obdindex, param->maxdepth,
2038                                        param->verbose, param->raw);
2039                 break;
2040         case LOV_USER_MAGIC_V3: {
2041                 char pool_name[LOV_MAXPOOLNAME + 1];
2042                 struct lov_user_ost_data_v1 *objects;
2043                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
2044
2045                 strncpy(pool_name, lmmv3->lmm_pool_name, LOV_MAXPOOLNAME);
2046                 pool_name[LOV_MAXPOOLNAME] = '\0';
2047                 objects = lmmv3->lmm_objects;
2048                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, pool_name,
2049                                        objects, path, is_dir,
2050                                        param->obdindex, param->maxdepth,
2051                                        param->verbose, param->raw);
2052                 break;
2053         }
2054         default:
2055                 llapi_printf(LLAPI_MSG_NORMAL, "unknown lmm_magic:  %#x "
2056                              "(expecting one of %#x %#x %#x)\n",
2057                              *(__u32 *)&param->lmd->lmd_lmm,
2058                              LOV_USER_MAGIC_V1, LOV_USER_MAGIC_V3);
2059                 return;
2060         }
2061 }
2062
2063 int llapi_file_get_stripe(const char *path, struct lov_user_md *lum)
2064 {
2065         const char *fname;
2066         char *dname;
2067         int fd, rc = 0;
2068
2069         fname = strrchr(path, '/');
2070
2071         /* It should be a file (or other non-directory) */
2072         if (fname == NULL) {
2073                 dname = (char *)malloc(2);
2074                 if (dname == NULL)
2075                         return -ENOMEM;
2076                 strcpy(dname, ".");
2077                 fname = (char *)path;
2078         } else {
2079                 dname = (char *)malloc(fname - path + 1);
2080                 if (dname == NULL)
2081                         return -ENOMEM;
2082                 strncpy(dname, path, fname - path);
2083                 dname[fname - path] = '\0';
2084                 fname++;
2085         }
2086
2087         fd = open(dname, O_RDONLY);
2088         if (fd == -1) {
2089                 rc = -errno;
2090                 free(dname);
2091                 return rc;
2092         }
2093
2094         strcpy((char *)lum, fname);
2095         if (ioctl(fd, IOC_MDC_GETFILESTRIPE, (void *)lum) == -1)
2096                 rc = -errno;
2097
2098         if (close(fd) == -1 && rc == 0)
2099                 rc = -errno;
2100
2101         free(dname);
2102         return rc;
2103 }
2104
2105 int llapi_file_lookup(int dirfd, const char *name)
2106 {
2107         struct obd_ioctl_data data = { 0 };
2108         char rawbuf[8192];
2109         char *buf = rawbuf;
2110         int rc;
2111
2112         if (dirfd < 0 || name == NULL)
2113                 return -EINVAL;
2114
2115         data.ioc_version = OBD_IOCTL_VERSION;
2116         data.ioc_len = sizeof(data);
2117         data.ioc_inlbuf1 = (char *)name;
2118         data.ioc_inllen1 = strlen(name) + 1;
2119
2120         rc = obd_ioctl_pack(&data, &buf, sizeof(rawbuf));
2121         if (rc) {
2122                 llapi_error(LLAPI_MSG_ERROR, rc,
2123                             "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
2124                             name, rc);
2125                 return rc;
2126         }
2127
2128         rc = ioctl(dirfd, IOC_MDC_LOOKUP, buf);
2129         if (rc < 0)
2130                 rc = -errno;
2131         return rc;
2132 }
2133
2134 /* Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
2135  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
2136  *
2137  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
2138  * The table below gives the answers for the specified parameters (value and
2139  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
2140  * --------------------------------------
2141  * 1 | file > limit; sign > 0 | -1 / -1 |
2142  * 2 | file = limit; sign > 0 | -1 / -1 |
2143  * 3 | file < limit; sign > 0 |  ? /  1 |
2144  * 4 | file > limit; sign = 0 | -1 / -1 |
2145  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
2146  * 6 | file < limit; sign = 0 |  ? / -1 |
2147  * 7 | file > limit; sign < 0 |  1 /  1 |
2148  * 8 | file = limit; sign < 0 |  ? / -1 |
2149  * 9 | file < limit; sign < 0 |  ? / -1 |
2150  * --------------------------------------
2151  * Note: 5th actually means that the value is within the interval
2152  * (limit - margin, limit]. */
2153 static int find_value_cmp(unsigned long long file, unsigned long long limit,
2154                           int sign, int negopt, unsigned long long margin,
2155                           int mds)
2156 {
2157         int ret = -1;
2158
2159         if (sign > 0) {
2160                 /* Drop the fraction of margin (of days). */
2161                 if (file + margin <= limit)
2162                         ret = mds ? 0 : 1;
2163         } else if (sign == 0) {
2164                 if (file <= limit && file + margin > limit)
2165                         ret = mds ? 0 : 1;
2166                 else if (file + margin <= limit)
2167                         ret = mds ? 0 : -1;
2168         } else if (sign < 0) {
2169                 if (file > limit)
2170                         ret = 1;
2171                 else if (mds)
2172                         ret = 0;
2173         }
2174
2175         return negopt ? ~ret + 1 : ret;
2176 }
2177
2178 /* Check if the file time matches all the given criteria (e.g. --atime +/-N).
2179  * Return -1 or 1 if file timestamp does not or does match the given criteria
2180  * correspondingly. Return 0 if the MDS time is being checked and there are
2181  * attributes on OSTs and it is not yet clear if the timespamp matches.
2182  *
2183  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
2184  * updated timestamps. */
2185 static int find_time_check(lstat_t *st, struct find_param *param, int mds)
2186 {
2187         int ret;
2188         int rc = 1;
2189
2190         /* Check if file is accepted. */
2191         if (param->atime) {
2192                 ret = find_value_cmp(st->st_atime, param->atime,
2193                                      param->asign, param->exclude_atime,
2194                                      24 * 60 * 60, mds);
2195                 if (ret < 0)
2196                         return ret;
2197                 rc = ret;
2198         }
2199
2200         if (param->mtime) {
2201                 ret = find_value_cmp(st->st_mtime, param->mtime,
2202                                      param->msign, param->exclude_mtime,
2203                                      24 * 60 * 60, mds);
2204                 if (ret < 0)
2205                         return ret;
2206
2207                 /* If the previous check matches, but this one is not yet clear,
2208                  * we should return 0 to do an RPC on OSTs. */
2209                 if (rc == 1)
2210                         rc = ret;
2211         }
2212
2213         if (param->ctime) {
2214                 ret = find_value_cmp(st->st_ctime, param->ctime,
2215                                      param->csign, param->exclude_ctime,
2216                                      24 * 60 * 60, mds);
2217                 if (ret < 0)
2218                         return ret;
2219
2220                 /* If the previous check matches, but this one is not yet clear,
2221                  * we should return 0 to do an RPC on OSTs. */
2222                 if (rc == 1)
2223                         rc = ret;
2224         }
2225
2226         return rc;
2227 }
2228
2229 /**
2230  * Check whether the stripes matches the indexes user provided
2231  *       1   : matched
2232  *       0   : Unmatched
2233  */
2234 static int check_obd_match(struct find_param *param)
2235 {
2236         lstat_t *st = &param->lmd->lmd_st;
2237         struct lov_user_ost_data_v1 *lmm_objects;
2238         int i, j;
2239
2240         if (param->obduuid && param->obdindex == OBD_NOT_FOUND)
2241                 return 0;
2242
2243         if (!S_ISREG(st->st_mode))
2244                 return 0;
2245
2246         /* Only those files should be accepted, which have a
2247          * stripe on the specified OST. */
2248         if (!param->lmd->lmd_lmm.lmm_stripe_count)
2249                 return 0;
2250
2251         if (param->lmd->lmd_lmm.lmm_magic ==
2252             LOV_USER_MAGIC_V3) {
2253                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
2254
2255                 lmm_objects = lmmv3->lmm_objects;
2256         } else if (param->lmd->lmd_lmm.lmm_magic ==  LOV_USER_MAGIC_V1) {
2257                 lmm_objects = param->lmd->lmd_lmm.lmm_objects;
2258         } else {
2259                 llapi_err_noerrno(LLAPI_MSG_ERROR, "%s:Unknown magic: 0x%08X\n",
2260                                   __func__, param->lmd->lmd_lmm.lmm_magic);
2261                 return -EINVAL;
2262         }
2263
2264         for (i = 0; i < param->lmd->lmd_lmm.lmm_stripe_count; i++) {
2265                 for (j = 0; j < param->num_obds; j++) {
2266                         if (param->obdindexes[j] ==
2267                             lmm_objects[i].l_ost_idx) {
2268                                 if (param->exclude_obd)
2269                                         return 0;
2270                                 return 1;
2271                         }
2272                 }
2273         }
2274
2275         if (param->exclude_obd)
2276                 return 1;
2277         return 0;
2278 }
2279
2280 static int check_mdt_match(struct find_param *param)
2281 {
2282         int i;
2283
2284         if (param->mdtuuid && param->mdtindex == OBD_NOT_FOUND)
2285                 return 0;
2286
2287         /* FIXME: For striped dir, we should get stripe information and check */
2288         for (i = 0; i < param->num_mdts; i++) {
2289                 if (param->mdtindexes[i] == param->file_mdtindex)
2290                         if (param->exclude_mdt)
2291                                 return 0;
2292                         return 1;
2293         }
2294
2295         if (param->exclude_mdt)
2296                 return 1;
2297         return 0;
2298 }
2299
2300 /**
2301  * Check whether the obd is active or not, if it is
2302  * not active, just print the object affected by this
2303  * failed target
2304  **/
2305 static int print_failed_tgt(struct find_param *param, char *path, int type)
2306 {
2307         struct obd_statfs stat_buf;
2308         struct obd_uuid uuid_buf;
2309         int ret;
2310
2311         LASSERT(type == LL_STATFS_LOV || type == LL_STATFS_LMV);
2312
2313         memset(&stat_buf, 0, sizeof(struct obd_statfs));
2314         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
2315         ret = llapi_obd_statfs(path, type,
2316                                param->obdindex, &stat_buf,
2317                                &uuid_buf);
2318         if (ret) {
2319                 llapi_printf(LLAPI_MSG_NORMAL,
2320                              "obd_uuid: %s failed %s ",
2321                              param->obduuid->uuid,
2322                              strerror(errno));
2323         }
2324         return ret;
2325 }
2326
2327 static int cb_find_init(char *path, DIR *parent, DIR *dir,
2328                         void *data, cfs_dirent_t *de)
2329 {
2330         struct find_param *param = (struct find_param *)data;
2331         int decision = 1; /* 1 is accepted; -1 is rejected. */
2332         lstat_t *st = &param->lmd->lmd_st;
2333         int lustre_fs = 1;
2334         int checked_type = 0;
2335         int ret = 0;
2336
2337         LASSERT(parent != NULL || dir != NULL);
2338
2339         if (param->have_fileinfo == 0)
2340                 param->lmd->lmd_lmm.lmm_stripe_count = 0;
2341
2342         /* If a regular expression is presented, make the initial decision */
2343         if (param->pattern != NULL) {
2344                 char *fname = strrchr(path, '/');
2345                 fname = (fname == NULL ? path : fname + 1);
2346                 ret = fnmatch(param->pattern, fname, 0);
2347                 if ((ret == FNM_NOMATCH && !param->exclude_pattern) ||
2348                     (ret == 0 && param->exclude_pattern))
2349                         goto decided;
2350         }
2351
2352         /* See if we can check the file type from the dirent. */
2353         if (param->type && de != NULL && de->d_type != DT_UNKNOWN &&
2354             de->d_type < DT_MAX) {
2355                 checked_type = 1;
2356                 if (llapi_dir_filetype_table[de->d_type] == param->type) {
2357                         if (param->exclude_type)
2358                                 goto decided;
2359                 } else {
2360                         if (!param->exclude_type)
2361                                 goto decided;
2362                 }
2363         }
2364
2365         ret = 0;
2366
2367         /* Request MDS for the stat info if some of these parameters need
2368          * to be compared. */
2369         if (param->obduuid    || param->mdtuuid || param->check_uid ||
2370             param->check_gid || param->check_pool || param->atime   ||
2371             param->ctime     || param->mtime || param->check_size ||
2372             param->check_stripecount || param->check_stripesize)
2373                 decision = 0;
2374
2375         if (param->type && checked_type == 0)
2376                 decision = 0;
2377
2378         if (param->have_fileinfo == 0 && decision == 0) {
2379                 ret = get_lmd_info(path, parent, dir, param->lmd,
2380                                    param->lumlen);
2381                 if (ret == 0) {
2382                         if (dir) {
2383                                 ret = llapi_file_fget_mdtidx(dirfd(dir),
2384                                                      &param->file_mdtindex);
2385                         } else {
2386                                 int fd;
2387                                 lstat_t tmp_st;
2388
2389                                 ret = lstat_f(path, &tmp_st);
2390                                 if (ret) {
2391                                         ret = -errno;
2392                                         llapi_error(LLAPI_MSG_ERROR, ret,
2393                                                     "error: %s: lstat failed"
2394                                                     "for %s", __func__, path);
2395                                         return ret;
2396                                 }
2397                                 if (S_ISREG(tmp_st.st_mode)) {
2398                                         fd = open(path, O_RDONLY);
2399                                         if (fd > 0) {
2400                                                 ret = llapi_file_fget_mdtidx(fd,
2401                                                          &param->file_mdtindex);
2402                                                 close(fd);
2403                                         } else {
2404                                                 ret = fd;
2405                                         }
2406                                 } else {
2407                                         /* For special inode, it assumes to
2408                                          * reside on the same MDT with the
2409                                          * parent */
2410                                         fd = dirfd(parent);
2411                                         ret = llapi_file_fget_mdtidx(fd,
2412                                                         &param->file_mdtindex);
2413                                 }
2414                         }
2415                 }
2416                 if (ret) {
2417                         if (ret == -ENOTTY)
2418                                 lustre_fs = 0;
2419                         if (ret == -ENOENT)
2420                                 goto decided;
2421                         return ret;
2422                 }
2423         }
2424
2425         if (param->type && !checked_type) {
2426                 if ((st->st_mode & S_IFMT) == param->type) {
2427                         if (param->exclude_type)
2428                                 goto decided;
2429                 } else {
2430                         if (!param->exclude_type)
2431                                 goto decided;
2432                 }
2433         }
2434
2435         /* Prepare odb. */
2436         if (param->obduuid || param->mdtuuid) {
2437                 if (lustre_fs && param->got_uuids &&
2438                     param->st_dev != st->st_dev) {
2439                         /* A lustre/lustre mount point is crossed. */
2440                         param->got_uuids = 0;
2441                         param->obds_printed = 0;
2442                         param->obdindex = param->mdtindex = OBD_NOT_FOUND;
2443                 }
2444
2445                 if (lustre_fs && !param->got_uuids) {
2446                         ret = setup_target_indexes(dir ? dir : parent, path,
2447                                                    param);
2448                         if (ret)
2449                                 return ret;
2450
2451                         param->st_dev = st->st_dev;
2452                 } else if (!lustre_fs && param->got_uuids) {
2453                         /* A lustre/non-lustre mount point is crossed. */
2454                         param->got_uuids = 0;
2455                         param->obdindex = param->mdtindex = OBD_NOT_FOUND;
2456                 }
2457         }
2458
2459         if (param->check_stripesize) {
2460                 decision = find_value_cmp(param->lmd->lmd_lmm.lmm_stripe_size,
2461                                           param->stripesize,
2462                                           param->stripesize_sign,
2463                                           param->exclude_stripesize,
2464                                           param->stripesize_units, 0);
2465                 if (decision == -1)
2466                         goto decided;
2467         }
2468
2469         if (param->check_stripecount) {
2470                 decision = find_value_cmp(param->lmd->lmd_lmm.lmm_stripe_count,
2471                                           param->stripecount,
2472                                           param->stripecount_sign,
2473                                           param->exclude_stripecount, 1, 0);
2474                 if (decision == -1)
2475                         goto decided;
2476         }
2477
2478         /* If an OBD UUID is specified but none matches, skip this file. */
2479         if ((param->obduuid && param->obdindex == OBD_NOT_FOUND) ||
2480             (param->mdtuuid && param->mdtindex == OBD_NOT_FOUND))
2481                 goto decided;
2482
2483         /* If a OST or MDT UUID is given, and some OST matches,
2484          * check it here. */
2485         if (param->obdindex != OBD_NOT_FOUND ||
2486             param->mdtindex != OBD_NOT_FOUND) {
2487                 if (param->obduuid) {
2488                         if (check_obd_match(param)) {
2489                                 /* If no mdtuuid is given, we are done.
2490                                  * Otherwise, fall through to the mdtuuid
2491                                  * check below. */
2492                                 if (!param->mdtuuid)
2493                                         goto obd_matches;
2494                         } else {
2495                                 goto decided;
2496                         }
2497                 }
2498                 if (param->mdtuuid) {
2499                         if (check_mdt_match(param))
2500                                 goto obd_matches;
2501                         goto decided;
2502                 }
2503         }
2504 obd_matches:
2505         if (param->check_uid) {
2506                 if (st->st_uid == param->uid) {
2507                         if (param->exclude_uid)
2508                                 goto decided;
2509                 } else {
2510                         if (!param->exclude_uid)
2511                                 goto decided;
2512                 }
2513         }
2514
2515         if (param->check_gid) {
2516                 if (st->st_gid == param->gid) {
2517                         if (param->exclude_gid)
2518                                 goto decided;
2519                 } else {
2520                         if (!param->exclude_gid)
2521                                 goto decided;
2522                 }
2523         }
2524
2525         if (param->check_pool) {
2526                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
2527
2528                 /* empty requested pool is taken as no pool search => V1 */
2529                 if (((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V1) &&
2530                      (param->poolname[0] == '\0')) ||
2531                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
2532                      (strncmp(lmmv3->lmm_pool_name,
2533                               param->poolname, LOV_MAXPOOLNAME) == 0)) ||
2534                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
2535                      (strcmp(param->poolname, "*") == 0))) {
2536                         if (param->exclude_pool)
2537                                 goto decided;
2538                 } else {
2539                         if (!param->exclude_pool)
2540                                 goto decided;
2541                 }
2542         }
2543
2544         /* Check the time on mds. */
2545         decision = 1;
2546         if (param->atime || param->ctime || param->mtime) {
2547                 int for_mds;
2548
2549                 for_mds = lustre_fs ? (S_ISREG(st->st_mode) &&
2550                                        param->lmd->lmd_lmm.lmm_stripe_count)
2551                                     : 0;
2552                 decision = find_time_check(st, param, for_mds);
2553                 if (decision == -1)
2554                         goto decided;
2555         }
2556
2557         /* If file still fits the request, ask ost for updated info.
2558            The regular stat is almost of the same speed as some new
2559            'glimpse-size-ioctl'. */
2560
2561         if (param->check_size && S_ISREG(st->st_mode) &&
2562             param->lmd->lmd_lmm.lmm_stripe_count)
2563                 decision = 0;
2564
2565         while (!decision) {
2566                 /* For regular files with the stripe the decision may have not
2567                  * been taken yet if *time or size is to be checked. */
2568                 LASSERT((S_ISREG(st->st_mode) &&
2569                         param->lmd->lmd_lmm.lmm_stripe_count) ||
2570                         param->mdtindex != OBD_NOT_FOUND);
2571
2572                 if (param->obdindex != OBD_NOT_FOUND)
2573                         print_failed_tgt(param, path, LL_STATFS_LOV);
2574
2575                 if (param->mdtindex != OBD_NOT_FOUND)
2576                         print_failed_tgt(param, path, LL_STATFS_LMV);
2577
2578                 if (dir) {
2579                         ret = ioctl(dirfd(dir), IOC_LOV_GETINFO,
2580                                     (void *)param->lmd);
2581                 } else if (parent) {
2582                         ret = ioctl(dirfd(parent), IOC_LOV_GETINFO,
2583                                     (void *)param->lmd);
2584                 }
2585
2586                 if (ret) {
2587                         if (errno == ENOENT) {
2588                                 llapi_error(LLAPI_MSG_ERROR, -ENOENT,
2589                                             "warning: %s: %s does not exist",
2590                                             __func__, path);
2591                                 goto decided;
2592                         } else {
2593                                 ret = -errno;
2594                                 llapi_error(LLAPI_MSG_ERROR, ret,
2595                                             "%s: IOC_LOV_GETINFO on %s failed",
2596                                             __func__, path);
2597                                 return ret;
2598                         }
2599                 }
2600
2601                 /* Check the time on osc. */
2602                 decision = find_time_check(st, param, 0);
2603                 if (decision == -1)
2604                         goto decided;
2605
2606                 break;
2607         }
2608
2609         if (param->check_size)
2610                 decision = find_value_cmp(st->st_size, param->size,
2611                                           param->size_sign, param->exclude_size,
2612                                           param->size_units, 0);
2613
2614         if (decision != -1) {
2615                 llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
2616                 if (param->zeroend)
2617                         llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
2618                 else
2619                         llapi_printf(LLAPI_MSG_NORMAL, "\n");
2620         }
2621
2622 decided:
2623         /* Do not get down anymore? */
2624         if (param->depth == param->maxdepth)
2625                 return 1;
2626
2627         param->depth++;
2628         return 0;
2629 }
2630
2631 int llapi_find(char *path, struct find_param *param)
2632 {
2633         return param_callback(path, cb_find_init, cb_common_fini, param);
2634 }
2635
2636 /*
2637  * Get MDT number that the file/directory inode referenced
2638  * by the open fd resides on.
2639  * Return 0 and mdtidx on success, or -ve errno.
2640  */
2641 int llapi_file_fget_mdtidx(int fd, int *mdtidx)
2642 {
2643         if (ioctl(fd, LL_IOC_GET_MDTIDX, mdtidx) < 0)
2644                 return -errno;
2645         return 0;
2646 }
2647
2648 static int cb_get_mdt_index(char *path, DIR *parent, DIR *d, void *data,
2649                             cfs_dirent_t *de)
2650 {
2651         struct find_param *param = (struct find_param *)data;
2652         int ret = 0;
2653         int mdtidx;
2654
2655         LASSERT(parent != NULL || d != NULL);
2656
2657         if (d) {
2658                 ret = llapi_file_fget_mdtidx(dirfd(d), &mdtidx);
2659         } else if (parent) {
2660                 int fd;
2661
2662                 fd = open(path, O_RDONLY);
2663                 if (fd > 0) {
2664                         ret = llapi_file_fget_mdtidx(fd, &mdtidx);
2665                         close(fd);
2666                 } else {
2667                         ret = -errno;
2668                 }
2669         }
2670
2671         if (ret) {
2672                 if (ret == -ENODATA) {
2673                         if (!param->obduuid)
2674                                 llapi_printf(LLAPI_MSG_NORMAL,
2675                                              "%s has no stripe info\n", path);
2676                         goto out;
2677                 } else if (ret == -ENOENT) {
2678                         llapi_error(LLAPI_MSG_WARN, ret,
2679                                     "warning: %s: %s does not exist",
2680                                     __func__, path);
2681                         goto out;
2682                 } else if (ret == -ENOTTY) {
2683                         llapi_error(LLAPI_MSG_ERROR, ret,
2684                                     "%s: '%s' not on a Lustre fs?",
2685                                     __func__, path);
2686                 } else {
2687                         llapi_error(LLAPI_MSG_ERROR, ret,
2688                                     "error: %s: LL_IOC_GET_MDTIDX failed for %s",
2689                                     __func__, path);
2690                 }
2691                 return ret;
2692         }
2693
2694         /* The 'LASSERT(parent != NULL || d != NULL);' guarantees
2695          * that either 'd' or 'parent' is not null.
2696          * So in all cases llapi_file_fget_mdtidx() is called,
2697          * thus initializing 'mdtidx'. */
2698         if (param->quiet || !(param->verbose & VERBOSE_DETAIL))
2699                 /* coverity[uninit_use_in_call] */
2700                 llapi_printf(LLAPI_MSG_NORMAL, "%d\n", mdtidx);
2701         else
2702                 /* coverity[uninit_use_in_call] */
2703                 llapi_printf(LLAPI_MSG_NORMAL, "%s\nmdt_index:\t%d\n",
2704                              path, mdtidx);
2705
2706 out:
2707         /* Do not get down anymore? */
2708         if (param->depth == param->maxdepth)
2709                 return 1;
2710
2711         param->depth++;
2712         return 0;
2713 }
2714
2715 static int cb_getstripe(char *path, DIR *parent, DIR *d, void *data,
2716                         cfs_dirent_t *de)
2717 {
2718         struct find_param *param = (struct find_param *)data;
2719         int ret = 0;
2720
2721         LASSERT(parent != NULL || d != NULL);
2722
2723         if (param->obduuid) {
2724                 param->quiet = 1;
2725                 ret = setup_obd_uuid(d ? d : parent, path, param);
2726                 if (ret)
2727                         return ret;
2728         }
2729
2730         if (d) {
2731                 ret = ioctl(dirfd(d), LL_IOC_LOV_GETSTRIPE,
2732                             (void *)&param->lmd->lmd_lmm);
2733         } else if (parent) {
2734                 char *fname = strrchr(path, '/');
2735                 fname = (fname == NULL ? path : fname + 1);
2736
2737                 strncpy((char *)&param->lmd->lmd_lmm, fname, param->lumlen);
2738
2739                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILESTRIPE,
2740                             (void *)&param->lmd->lmd_lmm);
2741         }
2742
2743         if (ret) {
2744                 if (errno == ENODATA && d != NULL) {
2745                         /* We need to "fake" the "use the default" values
2746                          * since the lmm struct is zeroed out at this point.
2747                          * The magic needs to be set in order to satisfy
2748                          * a check later on in the code path.
2749                          * The object_seq needs to be set for the "(Default)"
2750                          * prefix to be displayed. */
2751                         struct lov_user_md *lmm = &param->lmd->lmd_lmm;
2752                         lmm->lmm_magic = LOV_MAGIC_V1;
2753                         if (!param->raw)
2754                                 lmm->lmm_object_seq = FID_SEQ_LOV_DEFAULT;
2755                         lmm->lmm_stripe_count = 0;
2756                         lmm->lmm_stripe_size = 0;
2757                         lmm->lmm_stripe_offset = -1;
2758                         goto dump;
2759
2760                 } else if (errno == ENODATA && parent != NULL) {
2761                         if (!param->obduuid)
2762                                 llapi_printf(LLAPI_MSG_NORMAL,
2763                                              "%s has no stripe info\n", path);
2764                         goto out;
2765                 } else if (errno == ENOENT) {
2766                         llapi_error(LLAPI_MSG_WARN, -ENOENT,
2767                                     "warning: %s: %s does not exist",
2768                                     __func__, path);
2769                         goto out;
2770                 } else if (errno == ENOTTY) {
2771                         ret = -errno;
2772                         llapi_error(LLAPI_MSG_ERROR, ret,
2773                                     "%s: '%s' not on a Lustre fs?",
2774                                     __func__, path);
2775                 } else {
2776                         ret = -errno;
2777                         llapi_error(LLAPI_MSG_ERROR, ret,
2778                                     "error: %s: %s failed for %s",
2779                                      __func__, d ? "LL_IOC_LOV_GETSTRIPE" :
2780                                     "IOC_MDC_GETFILESTRIPE", path);
2781                 }
2782
2783                 return ret;
2784         }
2785
2786 dump:
2787         if (!(param->verbose & VERBOSE_MDTINDEX))
2788                 llapi_lov_dump_user_lmm(param, path, d ? 1 : 0);
2789
2790 out:
2791         /* Do not get down anymore? */
2792         if (param->depth == param->maxdepth)
2793                 return 1;
2794
2795         param->depth++;
2796         return 0;
2797 }
2798
2799 int llapi_getstripe(char *path, struct find_param *param)
2800 {
2801         return param_callback(path, (param->verbose & VERBOSE_MDTINDEX) ?
2802                               cb_get_mdt_index : cb_getstripe,
2803                               cb_common_fini, param);
2804 }
2805
2806 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
2807                      struct obd_statfs *stat_buf,
2808                      struct obd_uuid *uuid_buf)
2809 {
2810         int fd;
2811         char raw[OBD_MAX_IOCTL_BUFFER] = {'\0'};
2812         char *rawbuf = raw;
2813         struct obd_ioctl_data data = { 0 };
2814         int rc = 0;
2815
2816         data.ioc_inlbuf1 = (char *)&type;
2817         data.ioc_inllen1 = sizeof(__u32);
2818         data.ioc_inlbuf2 = (char *)&index;
2819         data.ioc_inllen2 = sizeof(__u32);
2820         data.ioc_pbuf1 = (char *)stat_buf;
2821         data.ioc_plen1 = sizeof(struct obd_statfs);
2822         data.ioc_pbuf2 = (char *)uuid_buf;
2823         data.ioc_plen2 = sizeof(struct obd_uuid);
2824
2825         rc = obd_ioctl_pack(&data, &rawbuf, sizeof(raw));
2826         if (rc != 0) {
2827                 llapi_error(LLAPI_MSG_ERROR, rc,
2828                             "llapi_obd_statfs: error packing ioctl data");
2829                 return rc;
2830         }
2831
2832         fd = open(path, O_RDONLY);
2833         if (errno == EISDIR)
2834                 fd = open(path, O_DIRECTORY | O_RDONLY);
2835
2836         if (fd < 0) {
2837                 rc = errno ? -errno : -EBADF;
2838                 llapi_error(LLAPI_MSG_ERROR, rc, "error: %s: opening '%s'",
2839                             __func__, path);
2840                 return rc;
2841         }
2842         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
2843         if (rc)
2844                 rc = errno ? -errno : -EINVAL;
2845
2846         close(fd);
2847         return rc;
2848 }
2849
2850 #define MAX_STRING_SIZE 128
2851
2852 int llapi_ping(char *obd_type, char *obd_name)
2853 {
2854         char path[MAX_STRING_SIZE];
2855         char buf[1];
2856         int rc, fd;
2857
2858         snprintf(path, MAX_STRING_SIZE, "/proc/fs/lustre/%s/%s/ping",
2859                  obd_type, obd_name);
2860
2861         fd = open(path, O_WRONLY);
2862         if (fd < 0) {
2863                 rc = -errno;
2864                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s", path);
2865                 return rc;
2866         }
2867
2868         /* The purpose is to send a byte as a ping, whatever this byte is. */
2869         /* coverity[uninit_use_in_call] */
2870         rc = write(fd, buf, 1);
2871         if (rc < 0)
2872                 rc = -errno;
2873         close(fd);
2874
2875         if (rc == 1)
2876                 return 0;
2877         return rc;
2878 }
2879
2880 int llapi_target_iterate(int type_num, char **obd_type,
2881                          void *args, llapi_cb_t cb)
2882 {
2883         char buf[MAX_STRING_SIZE];
2884         FILE *fp = fopen(DEVICES_LIST, "r");
2885         int i, rc = 0;
2886
2887         if (fp == NULL) {
2888                 rc = -errno;
2889                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening "DEVICES_LIST);
2890                 return rc;
2891         }
2892
2893         while (fgets(buf, sizeof(buf), fp) != NULL) {
2894                 char *obd_type_name = NULL;
2895                 char *obd_name = NULL;
2896                 char *obd_uuid = NULL;
2897                 char *bufp = buf;
2898                 struct obd_statfs osfs_buffer;
2899
2900                 while(bufp[0] == ' ')
2901                         ++bufp;
2902
2903                 for(i = 0; i < 3; i++) {
2904                         obd_type_name = strsep(&bufp, " ");
2905                 }
2906                 obd_name = strsep(&bufp, " ");
2907                 obd_uuid = strsep(&bufp, " ");
2908
2909                 memset(&osfs_buffer, 0, sizeof (osfs_buffer));
2910
2911                 for (i = 0; i < type_num; i++) {
2912                         if (strcmp(obd_type_name, obd_type[i]) != 0)
2913                                 continue;
2914
2915                         cb(obd_type_name, obd_name, obd_uuid, args);
2916                 }
2917         }
2918         fclose(fp);
2919         return 0;
2920 }
2921
2922 static void do_target_check(char *obd_type_name, char *obd_name,
2923                             char *obd_uuid, void *args)
2924 {
2925         int rc;
2926
2927         rc = llapi_ping(obd_type_name, obd_name);
2928         if (rc == ENOTCONN) {
2929                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
2930         } else if (rc) {
2931                 llapi_error(LLAPI_MSG_ERROR, rc, "error: check '%s'", obd_name);
2932         } else {
2933                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
2934         }
2935 }
2936
2937 int llapi_target_check(int type_num, char **obd_type, char *dir)
2938 {
2939         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
2940 }
2941
2942 #undef MAX_STRING_SIZE
2943
2944 /* Is this a lustre fs? */
2945 int llapi_is_lustre_mnttype(const char *type)
2946 {
2947         return (strcmp(type, "lustre") == 0 || strcmp(type,"lustre_lite") == 0);
2948 }
2949
2950 /* Is this a lustre client fs? */
2951 int llapi_is_lustre_mnt(struct mntent *mnt)
2952 {
2953         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
2954                 strstr(mnt->mnt_fsname, ":/") != NULL);
2955 }
2956
2957 int llapi_quotacheck(char *mnt, int check_type)
2958 {
2959         DIR *root;
2960         int rc;
2961
2962         root = opendir(mnt);
2963         if (!root) {
2964                 rc = -errno;
2965                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
2966                 return rc;
2967         }
2968
2969         rc = ioctl(dirfd(root), LL_IOC_QUOTACHECK, check_type);
2970         if (rc < 0)
2971                 rc = -errno;
2972
2973         closedir(root);
2974         return rc;
2975 }
2976
2977 int llapi_poll_quotacheck(char *mnt, struct if_quotacheck *qchk)
2978 {
2979         DIR *root;
2980         int poll_intvl = 2;
2981         int rc;
2982
2983         root = opendir(mnt);
2984         if (!root) {
2985                 rc = -errno;
2986                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
2987                 return rc;
2988         }
2989
2990         while (1) {
2991                 rc = ioctl(dirfd(root), LL_IOC_POLL_QUOTACHECK, qchk);
2992                 if (!rc)
2993                         break;
2994                 sleep(poll_intvl);
2995                 if (poll_intvl < 30)
2996                         poll_intvl *= 2;
2997         }
2998
2999         closedir(root);
3000         return 0;
3001 }
3002
3003 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
3004 {
3005         DIR *root;
3006         int rc;
3007
3008         root = opendir(mnt);
3009         if (!root) {
3010                 rc = -errno;
3011                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
3012                 return rc;
3013         }
3014
3015         rc = ioctl(dirfd(root), LL_IOC_QUOTACTL, qctl);
3016         if (rc < 0)
3017                 rc = -errno;
3018
3019         closedir(root);
3020         return rc;
3021 }
3022
3023 static int cb_quotachown(char *path, DIR *parent, DIR *d, void *data,
3024                          cfs_dirent_t *de)
3025 {
3026         struct find_param *param = (struct find_param *)data;
3027         lstat_t *st;
3028         int rc;
3029
3030         LASSERT(parent != NULL || d != NULL);
3031
3032         rc = get_lmd_info(path, parent, d, param->lmd, param->lumlen);
3033         if (rc) {
3034                 if (rc == -ENODATA) {
3035                         if (!param->obduuid && !param->quiet)
3036                                 llapi_error(LLAPI_MSG_ERROR, -ENODATA,
3037                                           "%s has no stripe info", path);
3038                         rc = 0;
3039                 } else if (rc == -ENOENT) {
3040                         rc = 0;
3041                 }
3042                 return rc;
3043         }
3044
3045         st = &param->lmd->lmd_st;
3046
3047         /* libc chown() will do extra check, and if the real owner is
3048          * the same as the ones to set, it won't fall into kernel, so
3049          * invoke syscall directly. */
3050         rc = syscall(SYS_chown, path, -1, -1);
3051         if (rc)
3052                 llapi_error(LLAPI_MSG_ERROR, errno,
3053                             "error: chown %s", path);
3054
3055         rc = chmod(path, st->st_mode);
3056         if (rc) {
3057                 rc = -errno;
3058                 llapi_error(LLAPI_MSG_ERROR, rc, "error: chmod %s (%hu)",
3059                             path, st->st_mode);
3060         }
3061
3062         return rc;
3063 }
3064
3065 int llapi_quotachown(char *path, int flag)
3066 {
3067         struct find_param param;
3068
3069         memset(&param, 0, sizeof(param));
3070         param.recursive = 1;
3071         param.verbose = 0;
3072         param.quiet = 1;
3073
3074         return param_callback(path, cb_quotachown, NULL, &param);
3075 }
3076
3077 #include <pwd.h>
3078 #include <grp.h>
3079 #include <mntent.h>
3080 #include <sys/wait.h>
3081 #include <errno.h>
3082 #include <ctype.h>
3083
3084 static int rmtacl_notify(int ops)
3085 {
3086         FILE *fp;
3087         struct mntent *mnt;
3088         int found = 0, fd = 0, rc = 0;
3089
3090         fp = setmntent(MOUNTED, "r");
3091         if (fp == NULL) {
3092                 rc = -errno;
3093                 llapi_error(LLAPI_MSG_ERROR, rc,
3094                             "error setmntent(%s)", MOUNTED);
3095                 return rc;
3096         }
3097
3098         while (1) {
3099                 mnt = getmntent(fp);
3100                 if (!mnt)
3101                         break;
3102
3103                 if (!llapi_is_lustre_mnt(mnt))
3104                         continue;
3105
3106                 fd = open(mnt->mnt_dir, O_RDONLY | O_DIRECTORY);
3107                 if (fd < 0) {
3108                         rc = -errno;
3109                         llapi_error(LLAPI_MSG_ERROR, rc,
3110                                     "Can't open '%s'\n", mnt->mnt_dir);
3111                         goto out;
3112                 }
3113
3114                 rc = ioctl(fd, LL_IOC_RMTACL, ops);
3115                 close(fd);
3116                 if (rc < 0) {
3117                         rc = -errno;
3118                         llapi_error(LLAPI_MSG_ERROR, rc, "ioctl %d\n", fd);
3119                         goto out;
3120                 }
3121
3122                 found++;
3123         }
3124
3125 out:
3126         endmntent(fp);
3127         return ((rc != 0) ? rc : found);
3128 }
3129
3130 static char *next_token(char *p, int div)
3131 {
3132         if (p == NULL)
3133                 return NULL;
3134
3135         if (div)
3136                 while (*p && *p != ':' && !isspace(*p))
3137                         p++;
3138         else
3139                 while (*p == ':' || isspace(*p))
3140                         p++;
3141
3142         return *p ? p : NULL;
3143 }
3144
3145 static int rmtacl_name2id(char *name, int is_user)
3146 {
3147         if (is_user) {
3148                 struct passwd *pw;
3149
3150                 pw = getpwnam(name);
3151                 if (pw == NULL)
3152                         return INVALID_ID;
3153                 else
3154                         return (int)(pw->pw_uid);
3155         } else {
3156                 struct group *gr;
3157
3158                 gr = getgrnam(name);
3159                 if (gr == NULL)
3160                         return INVALID_ID;
3161                 else
3162                         return (int)(gr->gr_gid);
3163         }
3164 }
3165
3166 static int isodigit(int c)
3167 {
3168         return (c >= '0' && c <= '7') ? 1 : 0;
3169 }
3170
3171 /*
3172  * Whether the name is just digits string (uid/gid) already or not.
3173  * Return value:
3174  * 1: str is id
3175  * 0: str is not id
3176  */
3177 static int str_is_id(char *str)
3178 {
3179         if (str == NULL)
3180                 return 0;
3181
3182         if (*str == '0') {
3183                 str++;
3184                 if (*str == 'x' || *str == 'X') { /* for Hex. */
3185                         if (!isxdigit(*(++str)))
3186                                 return 0;
3187
3188                         while (isxdigit(*(++str)));
3189                 } else if (isodigit(*str)) { /* for Oct. */
3190                         while (isodigit(*(++str)));
3191                 }
3192         } else if (isdigit(*str)) { /* for Dec. */
3193                 while (isdigit(*(++str)));
3194         }
3195
3196         return (*str == 0) ? 1 : 0;
3197 }
3198
3199 typedef struct {
3200         char *name;
3201         int   length;
3202         int   is_user;
3203         int   next_token;
3204 } rmtacl_name_t;
3205
3206 #define RMTACL_OPTNAME(name) name, sizeof(name) - 1
3207
3208 static rmtacl_name_t rmtacl_namelist[] = {
3209         { RMTACL_OPTNAME("user:"),            1,      0 },
3210         { RMTACL_OPTNAME("group:"),           0,      0 },
3211         { RMTACL_OPTNAME("default:user:"),    1,      0 },
3212         { RMTACL_OPTNAME("default:group:"),   0,      0 },
3213         /* for --tabular option */
3214         { RMTACL_OPTNAME("user"),             1,      1 },
3215         { RMTACL_OPTNAME("group"),            0,      1 },
3216         { 0 }
3217 };
3218
3219 static int rgetfacl_output(char *str)
3220 {
3221         char *start = NULL, *end = NULL;
3222         int is_user = 0, n, id;
3223         char c;
3224         rmtacl_name_t *rn;
3225
3226         if (str == NULL)
3227                 return -1;
3228
3229         for (rn = rmtacl_namelist; rn->name; rn++) {
3230                 if(strncmp(str, rn->name, rn->length) == 0) {
3231                         if (!rn->next_token)
3232                                 start = str + rn->length;
3233                         else
3234                                 start = next_token(str + rn->length, 0);
3235                         is_user = rn->is_user;
3236                         break;
3237                 }
3238         }
3239
3240         end = next_token(start, 1);
3241         if (end == NULL || start == end) {
3242                 n = printf("%s", str);
3243                 return n;
3244         }
3245
3246         c = *end;
3247         *end = 0;
3248         id = rmtacl_name2id(start, is_user);
3249         if (id == INVALID_ID) {
3250                 if (str_is_id(start)) {
3251                         *end = c;
3252                         n = printf("%s", str);
3253                 } else
3254                         return -1;
3255         } else if ((id == NOBODY_UID && is_user) ||
3256                    (id == NOBODY_GID && !is_user)) {
3257                 *end = c;
3258                 n = printf("%s", str);
3259         } else {
3260                 *end = c;
3261                 *start = 0;
3262                 n = printf("%s%d%s", str, id, end);
3263         }
3264         return n;
3265 }
3266
3267 static int child_status(int status)
3268 {
3269         return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
3270 }
3271
3272 static int do_rmtacl(int argc, char *argv[], int ops, int (output_func)(char *))
3273 {
3274         pid_t pid = 0;
3275         int fd[2], status, rc;
3276         FILE *fp;
3277         char buf[PIPE_BUF];
3278
3279         if (output_func) {
3280                 if (pipe(fd) < 0) {
3281                         rc = -errno;
3282                         llapi_error(LLAPI_MSG_ERROR, rc, "Can't create pipe\n");
3283                         return rc;
3284                 }
3285
3286                 pid = fork();
3287                 if (pid < 0) {
3288                         rc = -errno;
3289                         llapi_error(LLAPI_MSG_ERROR, rc, "Can't fork\n");
3290                         close(fd[0]);
3291                         close(fd[1]);
3292                         return rc;
3293                 } else if (!pid) {
3294                         /* child process redirects its output. */
3295                         close(fd[0]);
3296                         close(1);
3297                         if (dup2(fd[1], 1) < 0) {
3298                                 rc = -errno;
3299                                 llapi_error(LLAPI_MSG_ERROR, rc,
3300                                             "Can't dup2 %d\n", fd[1]);
3301                                 close(fd[1]);
3302                                 return rc;
3303                         }
3304                 } else {
3305                         close(fd[1]);
3306                 }
3307         }
3308
3309         if (!pid) {
3310                 status = rmtacl_notify(ops);
3311                 if (status < 0)
3312                         return -errno;
3313
3314                 exit(execvp(argv[0], argv));
3315         }
3316
3317         /* the following is parent process */
3318         fp = fdopen(fd[0], "r");
3319         if (fp == NULL) {
3320                 rc = -errno;
3321                 llapi_error(LLAPI_MSG_ERROR, rc, "fdopen %d failed\n", fd[0]);
3322                 kill(pid, SIGKILL);
3323                 close(fd[0]);
3324                 return rc;
3325         }
3326
3327         while (fgets(buf, PIPE_BUF, fp) != NULL) {
3328                 if (output_func(buf) < 0)
3329                         fprintf(stderr, "WARNING: unexpected error!\n[%s]\n",
3330                                 buf);
3331         }
3332         fclose(fp);
3333         close(fd[0]);
3334
3335         if (waitpid(pid, &status, 0) < 0) {
3336                 rc = -errno;
3337                 llapi_error(LLAPI_MSG_ERROR, rc, "waitpid %d failed\n", pid);
3338                 return rc;
3339         }
3340
3341         return child_status(status);
3342 }
3343
3344 int llapi_lsetfacl(int argc, char *argv[])
3345 {
3346         return do_rmtacl(argc, argv, RMT_LSETFACL, NULL);
3347 }
3348
3349 int llapi_lgetfacl(int argc, char *argv[])
3350 {
3351         return do_rmtacl(argc, argv, RMT_LGETFACL, NULL);
3352 }
3353
3354 int llapi_rsetfacl(int argc, char *argv[])
3355 {
3356         return do_rmtacl(argc, argv, RMT_RSETFACL, NULL);
3357 }
3358
3359 int llapi_rgetfacl(int argc, char *argv[])
3360 {
3361         return do_rmtacl(argc, argv, RMT_RGETFACL, rgetfacl_output);
3362 }
3363
3364 int llapi_cp(int argc, char *argv[])
3365 {
3366         int rc;
3367
3368         rc = rmtacl_notify(RMT_RSETFACL);
3369         if (rc < 0)
3370                 return rc;
3371
3372         exit(execvp(argv[0], argv));
3373 }
3374
3375 int llapi_ls(int argc, char *argv[])
3376 {
3377         int rc;
3378
3379         rc = rmtacl_notify(RMT_LGETFACL);
3380         if (rc < 0)
3381                 return rc;
3382
3383         exit(execvp(argv[0], argv));
3384 }
3385
3386 /* Print mdtname 'name' into 'buf' using 'format'.  Add -MDT0000 if needed.
3387  * format must have %s%s, buf must be > 16
3388  * Eg: if name = "lustre-MDT0000", "lustre", or "lustre-MDT0000_UUID"
3389  *     then buf = "lustre-MDT0000"
3390  */
3391 static int get_mdtname(char *name, char *format, char *buf)
3392 {
3393         char suffix[]="-MDT0000";
3394         int len = strlen(name);
3395
3396         if ((len > 5) && (strncmp(name + len - 5, "_UUID", 5) == 0)) {
3397                 name[len - 5] = '\0';
3398                 len -= 5;
3399         }
3400
3401         if (len > 8) {
3402                 if ((len <= 16) && strncmp(name + len - 8, "-MDT", 4) == 0) {
3403                         suffix[0] = '\0';
3404                 } else {
3405                         /* Not enough room to add suffix */
3406                         llapi_err_noerrno(LLAPI_MSG_ERROR,
3407                                           "MDT name too long |%s|", name);
3408                         return -EINVAL;
3409                 }
3410         }
3411
3412         return sprintf(buf, format, name, suffix);
3413 }
3414
3415 /** ioctl on filsystem root, with mdtindex sent as data
3416  * \param mdtname path, fsname, or mdtname (lutre-MDT0004)
3417  * \param mdtidxp pointer to integer within data to be filled in with the
3418  *    mdt index (0 if no mdt is specified).  NULL won't be filled.
3419  */
3420 static int root_ioctl(const char *mdtname, int opc, void *data, int *mdtidxp,
3421                       int want_error)
3422 {
3423         char fsname[20];
3424         char *ptr;
3425         int fd, index, rc;
3426
3427         /* Take path, fsname, or MDTname.  Assume MDT0000 in the former cases.
3428          Open root and parse mdt index. */
3429         if (mdtname[0] == '/') {
3430                 index = 0;
3431                 rc = get_root_path(WANT_FD | want_error, NULL, &fd,
3432                                    (char *)mdtname, -1);
3433         } else {
3434                 if (get_mdtname((char *)mdtname, "%s%s", fsname) < 0)
3435                         return -EINVAL;
3436                 ptr = fsname + strlen(fsname) - 8;
3437                 *ptr = '\0';
3438                 index = strtol(ptr + 4, NULL, 10);
3439                 rc = get_root_path(WANT_FD | want_error, fsname, &fd, NULL, -1);
3440         }
3441         if (rc < 0) {
3442                 if (want_error)
3443                         llapi_err_noerrno(LLAPI_MSG_ERROR,
3444                                           "Can't open %s: %d\n", mdtname, rc);
3445                 return rc;
3446         }
3447
3448         if (mdtidxp)
3449                 *mdtidxp = index;
3450
3451         rc = ioctl(fd, opc, data);
3452         if (rc == -1)
3453                 rc = -errno;
3454         else
3455                 rc = 0;
3456         if (rc && want_error)
3457                 llapi_error(LLAPI_MSG_ERROR, rc, "ioctl %d err %d", opc, rc);
3458
3459         close(fd);
3460         return rc;
3461 }
3462
3463 /****** Changelog API ********/
3464
3465 static int changelog_ioctl(const char *mdtname, int opc, int id,
3466                            long long recno, int flags)
3467 {
3468         struct ioc_changelog data;
3469         int *idx;
3470
3471         data.icc_id = id;
3472         data.icc_recno = recno;
3473         data.icc_flags = flags;
3474         idx = (int *)(&data.icc_mdtindex);
3475
3476         return root_ioctl(mdtname, opc, &data, idx, WANT_ERROR);
3477 }
3478
3479 #define CHANGELOG_PRIV_MAGIC 0xCA8E1080
3480 struct changelog_private {
3481         int magic;
3482         int flags;
3483         lustre_kernelcomm kuc;
3484 };
3485
3486 /** Start reading from a changelog
3487  * @param priv Opaque private control structure
3488  * @param flags Start flags (e.g. CHANGELOG_FLAG_BLOCK)
3489  * @param device Report changes recorded on this MDT
3490  * @param startrec Report changes beginning with this record number
3491  * (just call llapi_changelog_fini when done; don't need an endrec)
3492  */
3493 int llapi_changelog_start(void **priv, int flags, const char *device,
3494                           long long startrec)
3495 {
3496         struct changelog_private *cp;
3497         int rc;
3498
3499         /* Set up the receiver control struct */
3500         cp = calloc(1, sizeof(*cp));
3501         if (cp == NULL)
3502                 return -ENOMEM;
3503
3504         cp->magic = CHANGELOG_PRIV_MAGIC;
3505         cp->flags = flags;
3506
3507         /* Set up the receiver */
3508         rc = libcfs_ukuc_start(&cp->kuc, 0 /* no group registration */);
3509         if (rc < 0)
3510                 goto out_free;
3511
3512         *priv = cp;
3513
3514         /* Tell the kernel to start sending */
3515         rc = changelog_ioctl(device, OBD_IOC_CHANGELOG_SEND, cp->kuc.lk_wfd,
3516                              startrec, flags);
3517         /* Only the kernel reference keeps the write side open */
3518         close(cp->kuc.lk_wfd);
3519         cp->kuc.lk_wfd = 0;
3520         if (rc < 0) {
3521                 /* frees and clears priv */
3522                 llapi_changelog_fini(priv);
3523                 return rc;
3524         }
3525
3526         return 0;
3527
3528 out_free:
3529         free(cp);
3530         return rc;
3531 }
3532
3533 /** Finish reading from a changelog */
3534 int llapi_changelog_fini(void **priv)
3535 {
3536         struct changelog_private *cp = (struct changelog_private *)*priv;
3537
3538         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
3539                 return -EINVAL;
3540
3541         libcfs_ukuc_stop(&cp->kuc);
3542         free(cp);
3543         *priv = NULL;
3544         return 0;
3545 }
3546
3547 /** Convert a changelog_rec to changelog_ext_rec, in this way client can treat
3548  *  all records in the format of changelog_ext_rec, this can make record
3549  *  analysis simpler.
3550  */
3551 static inline int changelog_extend_rec(struct changelog_ext_rec *ext)
3552 {
3553         if (!CHANGELOG_REC_EXTENDED(ext)) {
3554                 struct changelog_rec *rec = (struct changelog_rec *)ext;
3555
3556                 memmove(ext->cr_name, rec->cr_name, rec->cr_namelen);
3557                 fid_zero(&ext->cr_sfid);
3558                 fid_zero(&ext->cr_spfid);
3559                 return 1;
3560         }
3561
3562         return 0;
3563 }
3564
3565 /** Read the next changelog entry
3566  * @param priv Opaque private control structure
3567  * @param rech Changelog record handle; record will be allocated here
3568  * @return 0 valid message received; rec is set
3569  *         <0 error code
3570  *         1 EOF
3571  */
3572 int llapi_changelog_recv(void *priv, struct changelog_ext_rec **rech)
3573 {
3574         struct changelog_private *cp = (struct changelog_private *)priv;
3575         struct kuc_hdr *kuch;
3576         int rc = 0;
3577
3578         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
3579                 return -EINVAL;
3580         if (rech == NULL)
3581                 return -EINVAL;
3582         kuch = malloc(CR_MAXSIZE + sizeof(*kuch));
3583         if (kuch == NULL)
3584                 return -ENOMEM;
3585
3586 repeat:
3587         rc = libcfs_ukuc_msg_get(&cp->kuc, (char *)kuch,
3588                                  CR_MAXSIZE + sizeof(*kuch),
3589                                  KUC_TRANSPORT_CHANGELOG);
3590         if (rc < 0)
3591                 goto out_free;
3592
3593         if ((kuch->kuc_transport != KUC_TRANSPORT_CHANGELOG) ||
3594             ((kuch->kuc_msgtype != CL_RECORD) &&
3595              (kuch->kuc_msgtype != CL_EOF))) {
3596                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3597                                   "Unknown changelog message type %d:%d\n",
3598                                   kuch->kuc_transport, kuch->kuc_msgtype);
3599                 rc = -EPROTO;
3600                 goto out_free;
3601         }
3602
3603         if (kuch->kuc_msgtype == CL_EOF) {
3604                 if (cp->flags & CHANGELOG_FLAG_FOLLOW) {
3605                         /* Ignore EOFs */
3606                         goto repeat;
3607                 } else {
3608                         rc = 1;
3609                         goto out_free;
3610                 }
3611         }
3612
3613         /* Our message is a changelog_ext_rec.  Use pointer math to skip
3614          * kuch_hdr and point directly to the message payload.
3615          */
3616         *rech = (struct changelog_ext_rec *)(kuch + 1);
3617         changelog_extend_rec(*rech);
3618
3619         return 0;
3620
3621 out_free:
3622         *rech = NULL;
3623         free(kuch);
3624         return rc;
3625 }
3626
3627 /** Release the changelog record when done with it. */
3628 int llapi_changelog_free(struct changelog_ext_rec **rech)
3629 {
3630         if (*rech) {
3631                 /* We allocated memory starting at the kuc_hdr, but passed
3632                  * the consumer a pointer to the payload.
3633                  * Use pointer math to get back to the header.
3634                  */
3635                 struct kuc_hdr *kuch = (struct kuc_hdr *)*rech - 1;
3636                 free(kuch);
3637         }
3638         *rech = NULL;
3639         return 0;
3640 }
3641
3642 int llapi_changelog_clear(const char *mdtname, const char *idstr,
3643                           long long endrec)
3644 {
3645         int id;
3646
3647         if (endrec < 0) {
3648                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3649                                   "can't purge negative records\n");
3650                 return -EINVAL;
3651         }
3652
3653         id = strtol(idstr + strlen(CHANGELOG_USER_PREFIX), NULL, 10);
3654         if ((id == 0) || (strncmp(idstr, CHANGELOG_USER_PREFIX,
3655                                   strlen(CHANGELOG_USER_PREFIX)) != 0)) {
3656                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3657                                   "expecting id of the form '"
3658                                   CHANGELOG_USER_PREFIX
3659                                   "<num>'; got '%s'\n", idstr);
3660                 return -EINVAL;
3661         }
3662
3663         return changelog_ioctl(mdtname, OBD_IOC_CHANGELOG_CLEAR, id, endrec, 0);
3664 }
3665
3666 int llapi_fid2path(const char *device, const char *fidstr, char *buf,
3667                    int buflen, long long *recno, int *linkno)
3668 {
3669         struct lu_fid fid;
3670         struct getinfo_fid2path *gf;
3671         int rc;
3672
3673         while (*fidstr == '[')
3674                 fidstr++;
3675
3676         sscanf(fidstr, SFID, RFID(&fid));
3677         if (!fid_is_sane(&fid)) {
3678                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3679                                   "bad FID format [%s], should be "DFID"\n",
3680                                   fidstr, (__u64)1, 2, 0);
3681                 return -EINVAL;
3682         }
3683
3684         gf = malloc(sizeof(*gf) + buflen);
3685         if (gf == NULL)
3686                 return -ENOMEM;
3687         gf->gf_fid = fid;
3688         gf->gf_recno = *recno;
3689         gf->gf_linkno = *linkno;
3690         gf->gf_pathlen = buflen;
3691
3692         /* Take path or fsname */
3693         rc = root_ioctl(device, OBD_IOC_FID2PATH, gf, NULL, 0);
3694         if (rc) {
3695                 if (rc != -ENOENT)
3696                         llapi_error(LLAPI_MSG_ERROR, rc, "ioctl err %d", rc);
3697         } else {
3698                 memcpy(buf, gf->gf_path, gf->gf_pathlen);
3699                 *recno = gf->gf_recno;
3700                 *linkno = gf->gf_linkno;
3701         }
3702
3703         free(gf);
3704         return rc;
3705 }
3706
3707 static int path2fid_from_lma(const char *path, lustre_fid *fid)
3708 {
3709         char buf[512];
3710         struct lustre_mdt_attrs *lma;
3711         int rc;
3712
3713         rc = lgetxattr(path, XATTR_NAME_LMA, buf, sizeof(buf));
3714         if (rc < 0)
3715                 return -errno;
3716         lma = (struct lustre_mdt_attrs *)buf;
3717         fid_le_to_cpu(fid, &lma->lma_self_fid);
3718         return 0;
3719 }
3720
3721 int llapi_path2fid(const char *path, lustre_fid *fid)
3722 {
3723         int fd, rc;
3724
3725         memset(fid, 0, sizeof(*fid));
3726         fd = open(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
3727         if (fd < 0) {
3728                 if (errno == ELOOP || errno == ENXIO)
3729                         return path2fid_from_lma(path, fid);
3730                 return -errno;
3731         }
3732
3733         rc = ioctl(fd, LL_IOC_PATH2FID, fid) < 0 ? -errno : 0;
3734         if (rc == -EINVAL || rc == -ENOTTY)
3735                 rc = path2fid_from_lma(path, fid);
3736
3737         close(fd);
3738         return rc;
3739 }
3740
3741 /****** HSM Copytool API ********/
3742 #define CT_PRIV_MAGIC 0xC0BE2001
3743 struct copytool_private {
3744         int magic;
3745         char *fsname;
3746         lustre_kernelcomm kuc;
3747         __u32 archives;
3748 };
3749
3750 #include <libcfs/libcfs.h>
3751
3752 /** Register a copytool
3753  * @param[out] priv Opaque private control structure
3754  * @param fsname Lustre filesystem
3755  * @param flags Open flags, currently unused (e.g. O_NONBLOCK)
3756  * @param archive_count
3757  * @param archives Which archive numbers this copytool is responsible for
3758  */
3759 int llapi_copytool_start(void **priv, char *fsname, int flags,
3760                          int archive_count, int *archives)
3761 {
3762         struct copytool_private *ct;
3763         int rc;
3764
3765         if (archive_count > 0 && archives == NULL) {
3766                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3767                                   "NULL archive numbers");
3768                 return -EINVAL;
3769         }
3770
3771         ct = calloc(1, sizeof(*ct));
3772         if (ct == NULL)
3773                 return -ENOMEM;
3774
3775         ct->fsname = malloc(strlen(fsname) + 1);
3776         if (ct->fsname == NULL) {
3777                 rc = -ENOMEM;
3778                 goto out_err;
3779         }
3780         strcpy(ct->fsname, fsname);
3781         ct->magic = CT_PRIV_MAGIC;
3782         ct->archives = 0;
3783         for (rc = 0; rc < archive_count; rc++) {
3784                 if (archives[rc] > sizeof(ct->archives)) {
3785                         llapi_err_noerrno(LLAPI_MSG_ERROR,
3786                                           "Maximum of %d archives supported",
3787                                           sizeof(ct->archives));
3788                         goto out_err;
3789                 }
3790                 ct->archives |= 1 << archives[rc];
3791         }
3792         /* special case: if no archives specified, default to archive #0. */
3793         if (ct->archives == 0)
3794                 ct->archives = 1;
3795
3796         rc = libcfs_ukuc_start(&ct->kuc, KUC_GRP_HSM);
3797         if (rc < 0)
3798                 goto out_err;
3799
3800         /* Storing archive(s) in lk_data; see mdc_ioc_hsm_ct_start */
3801         ct->kuc.lk_data = ct->archives;
3802         rc = root_ioctl(ct->fsname, LL_IOC_HSM_CT_START, &(ct->kuc), NULL,
3803                         WANT_ERROR);
3804         /* Only the kernel reference keeps the write side open */
3805         close(ct->kuc.lk_wfd);
3806         ct->kuc.lk_wfd = 0;
3807         if (rc < 0)
3808                 goto out_err;
3809
3810         *priv = ct;
3811         return 0;
3812
3813 out_err:
3814         if (ct->fsname)
3815                 free(ct->fsname);
3816         free(ct);
3817         return rc;
3818 }
3819
3820 /** Deregister a copytool */
3821 int llapi_copytool_fini(void **priv)
3822 {
3823         struct copytool_private *ct = (struct copytool_private *)*priv;
3824
3825         if (!ct || (ct->magic != CT_PRIV_MAGIC))
3826                 return -EINVAL;
3827
3828         /* Tell the kernel to stop sending us messages */
3829         ct->kuc.lk_flags = LK_FLG_STOP;
3830         root_ioctl(ct->fsname, LL_IOC_HSM_CT_START, &(ct->kuc), NULL, 0);
3831
3832         /* Shut down the kernelcomms */
3833         libcfs_ukuc_stop(&ct->kuc);
3834
3835         free(ct->fsname);
3836         free(ct);
3837         *priv = NULL;
3838         return 0;
3839 }
3840
3841 /** Wait for the next hsm_action_list
3842  * @param priv Opaque private control structure
3843  * @param halh Action list handle, will be allocated here
3844  * @param msgsize Number of bytes in the message, will be set here
3845  * @return 0 valid message received; halh and msgsize are set
3846  *         <0 error code
3847  */
3848 int llapi_copytool_recv(void *priv, struct hsm_action_list **halh, int *msgsize)
3849 {
3850         struct copytool_private *ct = (struct copytool_private *)priv;
3851         struct kuc_hdr *kuch;
3852         struct hsm_action_list *hal;
3853         int rc = 0;
3854
3855         if (!ct || (ct->magic != CT_PRIV_MAGIC))
3856                 return -EINVAL;
3857         if (halh == NULL || msgsize == NULL)
3858                 return -EINVAL;
3859
3860         kuch = malloc(HAL_MAXSIZE + sizeof(*kuch));
3861         if (kuch == NULL)
3862                 return -ENOMEM;
3863
3864         rc = libcfs_ukuc_msg_get(&ct->kuc, (char *)kuch,
3865                                  HAL_MAXSIZE + sizeof(*kuch),
3866                                  KUC_TRANSPORT_HSM);
3867         if (rc < 0)
3868                 goto out_free;
3869
3870         /* Handle generic messages */
3871         if (kuch->kuc_transport == KUC_TRANSPORT_GENERIC &&
3872             kuch->kuc_msgtype == KUC_MSG_SHUTDOWN) {
3873                 rc = -ESHUTDOWN;
3874                 goto out_free;
3875         }
3876
3877         if (kuch->kuc_transport != KUC_TRANSPORT_HSM ||
3878             kuch->kuc_msgtype != HMT_ACTION_LIST) {
3879                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3880                                   "Unknown HSM message type %d:%d\n",
3881                                   kuch->kuc_transport, kuch->kuc_msgtype);
3882                 rc = -EPROTO;
3883                 goto out_free;
3884         }
3885
3886         /* Our message is a hsm_action_list.  Use pointer math to skip
3887          * kuch_hdr and point directly to the message payload.
3888          */
3889         hal = (struct hsm_action_list *)(kuch + 1);
3890
3891         /* Check that we have registered for this archive # */
3892         if (((1 << hal->hal_archive_num) & ct->archives) == 0) {
3893                     llapi_err_noerrno(LLAPI_MSG_INFO,
3894                              "Ignoring request for archive #%d (bitmask %#x)\n",
3895                              hal->hal_archive_num, ct->archives);
3896                 rc = 0;
3897                 goto out_free;
3898         }
3899
3900         *halh = hal;
3901         *msgsize = kuch->kuc_msglen - sizeof(*kuch);
3902         return 0;
3903
3904 out_free:
3905         *halh = NULL;
3906         *msgsize = 0;
3907         free(kuch);
3908         return rc;
3909 }
3910
3911 /** Release the action list when done with it. */
3912 int llapi_copytool_free(struct hsm_action_list **hal)
3913 {
3914         /* Reuse the llapi_changelog_free function */
3915         return llapi_changelog_free((struct changelog_ext_rec **)hal);
3916 }
3917
3918 int llapi_get_connect_flags(const char *mnt, __u64 *flags)
3919 {
3920         DIR *root;
3921         int rc;
3922
3923         root = opendir(mnt);
3924         if (!root) {
3925                 rc = -errno;
3926                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
3927                 return rc;
3928         }
3929
3930         rc = ioctl(dirfd(root), LL_IOC_GET_CONNECT_FLAGS, flags);
3931         if (rc < 0) {
3932                 rc = -errno;
3933                 llapi_error(LLAPI_MSG_ERROR, rc,
3934                             "ioctl on %s for getting connect flags failed", mnt);
3935         }
3936         closedir(root);
3937         return rc;
3938 }
3939
3940 int llapi_get_version(char *buffer, int buffer_size,
3941                       char **version)
3942 {
3943         int rc;
3944         int fd;
3945         struct obd_ioctl_data *data = (struct obd_ioctl_data *)buffer;
3946
3947         fd = open(OBD_DEV_PATH, O_RDONLY);
3948         if (fd == -1)
3949                 return -errno;
3950
3951         memset(buffer, 0, buffer_size);
3952         data->ioc_version = OBD_IOCTL_VERSION;
3953         data->ioc_inllen1 = buffer_size - cfs_size_round(sizeof(*data));
3954         data->ioc_inlbuf1 = buffer + cfs_size_round(sizeof(*data));
3955         data->ioc_len = obd_ioctl_packlen(data);
3956
3957         rc = ioctl(fd, OBD_GET_VERSION, buffer);
3958         if (rc == -1) {
3959                 rc = -errno;
3960                 close(fd);
3961                 return rc;
3962         }
3963         close(fd);
3964         *version = data->ioc_bulk;
3965         return 0;
3966 }
3967
3968 /**
3969  * Get a 64-bit value representing the version of file data pointed by fd.
3970  *
3971  * Each write or truncate, flushed on OST, will change this value. You can use
3972  * this value to verify if file data was modified. This only checks the file
3973  * data, not metadata.
3974  *
3975  * \param  flags  If set to LL_DV_NOFLUSH, the data version will be read
3976  *                directly from OST without regard to possible dirty cache on
3977  *                client nodes.
3978  *
3979  * \retval 0 on success.
3980  * \retval -errno on error.
3981  */
3982 int llapi_get_data_version(int fd, __u64 *data_version, __u64 flags)
3983 {
3984         int rc;
3985         struct ioc_data_version idv;
3986
3987         idv.idv_flags = flags;
3988
3989         rc = ioctl(fd, LL_IOC_DATA_VERSION, &idv);
3990         if (rc)
3991                 rc = -errno;
3992         else
3993                 *data_version = idv.idv_version;
3994
3995         return rc;
3996 }