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