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