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