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