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