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