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