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