Whamcloud - gitweb
59d02deb01396cbcc20761623c7616878acde2d1
[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.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/utils/liblustreapi.c
33  *
34  * Author: Peter J. Braam <braam@clusterfs.com>
35  * Author: Phil Schwan <phil@clusterfs.com>
36  * Author: Robert Read <rread@clusterfs.com>
37  */
38
39 /* for O_DIRECTORY */
40 #ifndef _GNU_SOURCE
41 #define _GNU_SOURCE
42 #endif
43
44 #include <ctype.h>
45 #include <mntent.h>
46 #include <stdlib.h>
47 #include <stdio.h>
48 #include <string.h>
49 #include <stddef.h>
50 #include <sys/ioctl.h>
51 #include <unistd.h>
52 #include <fcntl.h>
53 #include <errno.h>
54 #include <dirent.h>
55 #include <stdarg.h>
56 #include <sys/stat.h>
57 #include <sys/statfs.h>
58 #include <sys/syscall.h>
59 #include <sys/time.h>
60 #include <sys/types.h>
61 #include <sys/xattr.h>
62 #include <time.h>
63 #include <fnmatch.h>
64 #include <libgen.h> /* for dirname() */
65 #ifdef HAVE_LINUX_UNISTD_H
66 #include <linux/unistd.h>
67 #else
68 #include <unistd.h>
69 #endif
70 #include <poll.h>
71 #include <time.h>
72 #include <inttypes.h>
73
74 #include <libcfs/util/ioctl.h>
75 #include <libcfs/util/param.h>
76 #include <libcfs/util/string.h>
77 #include <linux/lnet/lnetctl.h>
78 #include <lustre/lustreapi.h>
79 #include <linux/lustre/lustre_ostid.h>
80 #include <linux/lustre/lustre_ioctl.h>
81 #include "lustreapi_internal.h"
82
83 static int llapi_msg_level = LLAPI_MSG_MAX;
84 const char *liblustreapi_cmd;
85
86 char *mdt_hash_name[] = { "none",
87                           LMV_HASH_NAME_ALL_CHARS,
88                           LMV_HASH_NAME_FNV_1A_64,
89 };
90
91 struct lustre_foreign_type lu_foreign_types[] = {
92         {.lft_type = LU_FOREIGN_TYPE_NONE, .lft_name = "none"},
93         {.lft_type = LU_FOREIGN_TYPE_DAOS, .lft_name = "daos"},
94         /* must be the last element */
95         {.lft_type = LU_FOREIGN_TYPE_UNKNOWN, .lft_name = NULL}
96         /* array max dimension must be <= UINT32_MAX */
97 };
98
99 void llapi_msg_set_level(int level)
100 {
101         /* ensure level is in the good range */
102         if (level < LLAPI_MSG_OFF)
103                 llapi_msg_level = LLAPI_MSG_OFF;
104         else if (level > LLAPI_MSG_MAX)
105                 llapi_msg_level = LLAPI_MSG_MAX;
106         else
107                 llapi_msg_level = level;
108 }
109
110 int llapi_msg_get_level(void)
111 {
112         return llapi_msg_level;
113 }
114
115 void llapi_set_command_name(const char *cmd)
116 {
117         liblustreapi_cmd = cmd;
118 }
119
120 void llapi_clear_command_name(void)
121 {
122         liblustreapi_cmd = NULL;
123 }
124
125 static void error_callback_default(enum llapi_message_level level, int err,
126                                    const char *fmt, va_list ap)
127 {
128         if (liblustreapi_cmd != NULL)
129                 fprintf(stderr, "%s %s: ", program_invocation_short_name,
130                         liblustreapi_cmd);
131         else
132                 fprintf(stderr, "%s: ", program_invocation_short_name);
133         vfprintf(stderr, fmt, ap);
134         if (level & LLAPI_MSG_NO_ERRNO)
135                 fprintf(stderr, "\n");
136         else
137                 fprintf(stderr, ": %s (%d)\n", strerror(err), err);
138 }
139
140 static void info_callback_default(enum llapi_message_level level, int err,
141                                   const char *fmt, va_list ap)
142 {
143         if (err != 0) {
144                 if (liblustreapi_cmd != NULL) {
145                         fprintf(stdout, "%s %s: ",
146                                 program_invocation_short_name,
147                                 liblustreapi_cmd);
148                 } else {
149                         fprintf(stdout, "%s: ", program_invocation_short_name);
150                 }
151         }
152         vfprintf(stdout, fmt, ap);
153 }
154
155 static llapi_log_callback_t llapi_error_callback = error_callback_default;
156 static llapi_log_callback_t llapi_info_callback = info_callback_default;
157
158
159 /* llapi_error will preserve errno */
160 void llapi_error(enum llapi_message_level level, int err, const char *fmt, ...)
161 {
162         va_list  args;
163         int      tmp_errno = errno;
164
165         if ((level & LLAPI_MSG_MASK) > llapi_msg_level)
166                 return;
167
168         va_start(args, fmt);
169         llapi_error_callback(level, abs(err), fmt, args);
170         va_end(args);
171         errno = tmp_errno;
172 }
173
174 /* llapi_printf will preserve errno */
175 void llapi_printf(enum llapi_message_level level, const char *fmt, ...)
176 {
177         va_list  args;
178         int      tmp_errno = errno;
179
180         if ((level & LLAPI_MSG_MASK) > llapi_msg_level)
181                 return;
182
183         va_start(args, fmt);
184         llapi_info_callback(level, 0, fmt, args);
185         va_end(args);
186         errno = tmp_errno;
187 }
188
189 /**
190  * Set a custom error logging function. Passing in NULL will reset the logging
191  * callback to its default value.
192  *
193  * This function returns the value of the old callback.
194  */
195 llapi_log_callback_t llapi_error_callback_set(llapi_log_callback_t cb)
196 {
197         llapi_log_callback_t    old = llapi_error_callback;
198
199         if (cb != NULL)
200                 llapi_error_callback = cb;
201         else
202                 llapi_error_callback = error_callback_default;
203
204         return old;
205 }
206
207 /**
208  * Set a custom info logging function. Passing in NULL will reset the logging
209  * callback to its default value.
210  *
211  * This function returns the value of the old callback.
212  */
213 llapi_log_callback_t llapi_info_callback_set(llapi_log_callback_t cb)
214 {
215         llapi_log_callback_t    old = llapi_info_callback;
216
217         if (cb != NULL)
218                 llapi_info_callback = cb;
219         else
220                 llapi_info_callback = info_callback_default;
221
222         return old;
223 }
224
225 /**
226  * size_units is to be initialized (or zeroed) by caller.
227  */
228 int llapi_parse_size(const char *optarg, unsigned long long *size,
229                      unsigned long long *size_units, int bytes_spec)
230 {
231         char *end;
232         char *argbuf = (char *)optarg;
233         unsigned long long frac = 0, frac_d = 1;
234
235         if (strncmp(optarg, "-", 1) == 0)
236                 return -1;
237
238         if (*size_units == 0)
239                 *size_units = 1;
240
241         *size = strtoull(argbuf, &end, 0);
242         if (end != NULL && *end == '.') {
243                 int i;
244
245                 argbuf = end + 1;
246                 frac = strtoull(argbuf, &end, 10);
247                 /* count decimal places */
248                 for (i = 0; i < (end - argbuf); i++)
249                         frac_d *= 10;
250         }
251
252         if (*end != '\0') {
253                 if ((*end == 'b') && *(end + 1) == '\0' &&
254                     (*size & (~0ULL << (64 - 9))) == 0 &&
255                     !bytes_spec) {
256                         *size_units = 1 << 9;
257                 } else if ((*end == 'b') &&
258                            *(end + 1) == '\0' &&
259                            bytes_spec) {
260                         *size_units = 1;
261                 } else if ((*end == 'k' || *end == 'K') &&
262                            *(end + 1) == '\0' &&
263                            (*size & (~0ULL << (64 - 10))) == 0) {
264                         *size_units = 1 << 10;
265                 } else if ((*end == 'm' || *end == 'M') &&
266                            *(end + 1) == '\0' &&
267                            (*size & (~0ULL << (64 - 20))) == 0) {
268                         *size_units = 1 << 20;
269                 } else if ((*end == 'g' || *end == 'G') &&
270                            *(end + 1) == '\0' &&
271                            (*size & (~0ULL << (64 - 30))) == 0) {
272                         *size_units = 1 << 30;
273                 } else if ((*end == 't' || *end == 'T') &&
274                            *(end + 1) == '\0' &&
275                            (*size & (~0ULL << (64 - 40))) == 0) {
276                         *size_units = 1ULL << 40;
277                 } else if ((*end == 'p' || *end == 'P') &&
278                            *(end + 1) == '\0' &&
279                            (*size & (~0ULL << (64 - 50))) == 0) {
280                         *size_units = 1ULL << 50;
281                 } else if ((*end == 'e' || *end == 'E') &&
282                            *(end + 1) == '\0' &&
283                            (*size & (~0ULL << (64 - 60))) == 0) {
284                         *size_units = 1ULL << 60;
285                 } else {
286                         return -1;
287                 }
288         }
289         *size = *size * *size_units + frac * *size_units / frac_d;
290
291         return 0;
292 }
293
294 int llapi_ioctl_pack(struct obd_ioctl_data *data, char **pbuf, int max_len)
295 {
296         struct obd_ioctl_data *overlay;
297         char *ptr;
298
299         data->ioc_len = obd_ioctl_packlen(data);
300         data->ioc_version = OBD_IOCTL_VERSION;
301
302         if (*pbuf != NULL && data->ioc_len > max_len) {
303                 llapi_error(LLAPI_MSG_ERROR, -EINVAL,
304                             "pbuf = %p, ioc_len = %u, max_len = %d\n",
305                             *pbuf, data->ioc_len, max_len);
306                 return -EINVAL;
307         }
308
309         if (*pbuf == NULL)
310                 *pbuf = malloc(data->ioc_len);
311
312         if (*pbuf == NULL)
313                 return -ENOMEM;
314
315         overlay = (struct obd_ioctl_data *)*pbuf;
316         memcpy(*pbuf, data, sizeof(*data));
317
318         ptr = overlay->ioc_bulk;
319         if (data->ioc_inlbuf1) {
320                 memcpy(ptr, data->ioc_inlbuf1, data->ioc_inllen1);
321                 ptr += __ALIGN_KERNEL(data->ioc_inllen1, 8);
322         }
323
324         if (data->ioc_inlbuf2) {
325                 memcpy(ptr, data->ioc_inlbuf2, data->ioc_inllen2);
326                 ptr += __ALIGN_KERNEL(data->ioc_inllen2, 8);
327         }
328
329         if (data->ioc_inlbuf3) {
330                 memcpy(ptr, data->ioc_inlbuf3, data->ioc_inllen3);
331                 ptr += __ALIGN_KERNEL(data->ioc_inllen3, 8);
332         }
333
334         if (data->ioc_inlbuf4) {
335                 memcpy(ptr, data->ioc_inlbuf4, data->ioc_inllen4);
336                 ptr += __ALIGN_KERNEL(data->ioc_inllen4, 8);
337         }
338
339         return 0;
340 }
341
342 int llapi_ioctl_unpack(struct obd_ioctl_data *data, char *pbuf, int max_len)
343 {
344         struct obd_ioctl_data *overlay;
345         char *ptr;
346
347         if (pbuf == NULL)
348                 return 1;
349
350         overlay = (struct obd_ioctl_data *)pbuf;
351
352         /* Preserve the caller's buffer pointers */
353         overlay->ioc_inlbuf1 = data->ioc_inlbuf1;
354         overlay->ioc_inlbuf2 = data->ioc_inlbuf2;
355         overlay->ioc_inlbuf3 = data->ioc_inlbuf3;
356         overlay->ioc_inlbuf4 = data->ioc_inlbuf4;
357
358         memcpy(data, pbuf, sizeof(*data));
359
360         ptr = overlay->ioc_bulk;
361         if (data->ioc_inlbuf1) {
362                 memcpy(data->ioc_inlbuf1, ptr, data->ioc_inllen1);
363                 ptr += __ALIGN_KERNEL(data->ioc_inllen1, 8);
364         }
365
366         if (data->ioc_inlbuf2) {
367                 memcpy(data->ioc_inlbuf2, ptr, data->ioc_inllen2);
368                 ptr += __ALIGN_KERNEL(data->ioc_inllen2, 8);
369         }
370
371         if (data->ioc_inlbuf3) {
372                 memcpy(data->ioc_inlbuf3, ptr, data->ioc_inllen3);
373                 ptr += __ALIGN_KERNEL(data->ioc_inllen3, 8);
374         }
375
376         if (data->ioc_inlbuf4) {
377                 memcpy(data->ioc_inlbuf4, ptr, data->ioc_inllen4);
378                 ptr += __ALIGN_KERNEL(data->ioc_inllen4, 8);
379         }
380
381         return 0;
382 }
383
384 /* XXX: llapi_xxx() functions return negative values upon failure */
385
386 int llapi_stripe_limit_check(unsigned long long stripe_size, int stripe_offset,
387                                 int stripe_count, int stripe_pattern)
388 {
389         static int page_size;
390         int rc = 0;
391
392         if (page_size == 0) {
393                 /* 64 KB is the largest common page size (on ia64/PPC/ARM),
394                  * but check the local page size just in case. The page_size
395                  * will not change for the lifetime of this process at least.
396                  */
397                 page_size = LOV_MIN_STRIPE_SIZE;
398                 if (getpagesize() > page_size) {
399                         page_size = getpagesize();
400                         llapi_err_noerrno(LLAPI_MSG_WARN,
401                                           "warning: page size (%u) larger than expected (%u)",
402                                           page_size, LOV_MIN_STRIPE_SIZE);
403                 }
404         }
405         if (!llapi_stripe_size_is_aligned(stripe_size)) {
406                 rc = -EINVAL;
407                 llapi_error(LLAPI_MSG_ERROR, rc, "error: bad stripe_size %llu, "
408                                 "must be an even multiple of %d bytes",
409                                 (unsigned long long)stripe_size, page_size);
410                 goto out;
411         }
412         if (!llapi_stripe_index_is_valid(stripe_offset)) {
413                 rc = -EINVAL;
414                 llapi_error(LLAPI_MSG_ERROR, rc, "error: bad stripe offset %d",
415                                 stripe_offset);
416                 goto out;
417         }
418         if (!llapi_stripe_count_is_valid(stripe_count)) {
419                 rc = -EINVAL;
420                 llapi_error(LLAPI_MSG_ERROR, rc, "error: bad stripe count %d",
421                                 stripe_count);
422                 goto out;
423         }
424         if (llapi_stripe_size_is_too_big(stripe_size)) {
425                 rc = -EINVAL;
426                 llapi_error(LLAPI_MSG_ERROR, rc,
427                             "error: stripe size '%llu' over 4GB limit",
428                             (unsigned long long)stripe_size);
429                 goto out;
430         }
431
432 out:
433         errno = -rc;
434         return rc;
435 }
436
437 int llapi_dir_stripe_limit_check(int stripe_offset, int stripe_count,
438                                  int hash_type)
439 {
440         int rc;
441
442         if (!llapi_dir_stripe_index_is_valid(stripe_offset)) {
443                 rc = -EINVAL;
444                 llapi_error(LLAPI_MSG_ERROR, rc, "error: bad stripe offset %d",
445                                 stripe_offset);
446                 return rc;
447         }
448         if (!llapi_dir_stripe_count_is_valid(stripe_count)) {
449                 rc = -EINVAL;
450                 llapi_error(LLAPI_MSG_ERROR, rc, "error: bad stripe count %d",
451                                 stripe_count);
452                 return rc;
453         }
454
455         if (!llapi_dir_hash_type_is_valid(hash_type)) {
456                 rc = -EINVAL;
457                 llapi_error(LLAPI_MSG_ERROR, rc, "error: bad hash type %d",
458                                 hash_type);
459                 return rc;
460         }
461         return 0;
462 }
463
464 /*
465  * Trim a trailing newline from a string, if it exists.
466  */
467 int llapi_chomp_string(char *buf)
468 {
469         if (!buf || !*buf)
470                 return 0;
471
472         while (buf[1])
473                 buf++;
474
475         if (*buf != '\n')
476                 return 0;
477
478         *buf = '\0';
479         return '\n';
480 }
481
482 /*
483  * Wrapper to grab parameter settings for lov.*-clilov-*.* values
484  */
485 static int get_param_lov(const char *path, const char *param,
486                          char *buf, size_t buf_size)
487 {
488         struct obd_uuid uuid;
489         int rc;
490
491         rc = llapi_file_get_lov_uuid(path, &uuid);
492         if (rc != 0)
493                 return rc;
494
495         return get_lustre_param_value("lov", uuid.uuid, FILTER_BY_EXACT, param,
496                                       buf, buf_size);
497 }
498
499 /*
500  * Wrapper to grab parameter settings for lmv.*-clilov-*.* values
501  */
502 static int get_param_lmv(const char *path, const char *param,
503                          char *buf, size_t buf_size)
504 {
505         struct obd_uuid uuid;
506         int rc;
507
508         rc = llapi_file_get_lmv_uuid(path, &uuid);
509         if (rc != 0)
510                 return rc;
511
512         return get_lustre_param_value("lmv", uuid.uuid, FILTER_BY_EXACT, param,
513                                buf, buf_size);
514 }
515
516 static int get_mds_md_size(const char *path)
517 {
518         char buf[PATH_MAX], inst[PATH_MAX];
519         int md_size = lov_user_md_size(LOV_MAX_STRIPE_COUNT, LOV_USER_MAGIC_V3);
520         int rc;
521
522         rc = llapi_getname(path, inst, sizeof(inst));
523         if (rc != 0)
524                 return rc;
525
526         /* Get the max ea size from llite parameters. */
527         rc = get_lustre_param_value("llite", inst, FILTER_BY_EXACT,
528                                     "max_easize", buf, sizeof(buf));
529         if (rc != 0)
530                 return rc;
531
532         rc = atoi(buf);
533
534         return rc > 0 ? rc : md_size;
535 }
536
537 int llapi_get_agent_uuid(char *path, char *buf, size_t bufsize)
538 {
539         return get_param_lmv(path, "uuid", buf, bufsize);
540 }
541
542 /**
543  * Open a Lustre file.
544  *
545  * \param name     the name of the file to be opened
546  * \param flags    access mode, see flags in open(2)
547  * \param mode     permission of the file if it is created, see mode in open(2)
548  * \param param    stripe pattern of the newly created file
549  *
550  * \retval         file descriptor of opened file
551  * \retval         negative errno on failure
552  */
553 int llapi_file_open_param(const char *name, int flags, mode_t mode,
554                           const struct llapi_stripe_param *param)
555 {
556         char fsname[MAX_OBD_NAME + 1] = { 0 };
557         char *pool_name = param->lsp_pool;
558         struct lov_user_md *lum = NULL;
559         size_t lum_size = sizeof(*lum);
560         int fd, rc;
561
562         /* Make sure we are on a Lustre file system */
563         rc = llapi_search_fsname(name, fsname);
564         if (rc) {
565                 llapi_error(LLAPI_MSG_ERROR, rc,
566                             "'%s' is not on a Lustre filesystem",
567                             name);
568                 return rc;
569         }
570
571         /* Check if the stripe pattern is sane. */
572         rc = llapi_stripe_limit_check(param->lsp_stripe_size,
573                                       param->lsp_stripe_offset,
574                                       param->lsp_stripe_count,
575                                       param->lsp_stripe_pattern);
576         if (rc != 0)
577                 return rc;
578
579         /* Make sure we have a good pool */
580         if (pool_name != NULL) {
581                 /* in case user gives the full pool name <fsname>.<poolname>,
582                  * strip the fsname */
583                 char *ptr = strchr(pool_name, '.');
584                 if (ptr != NULL) {
585                         *ptr = '\0';
586                         if (strcmp(pool_name, fsname) != 0) {
587                                 *ptr = '.';
588                                 llapi_err_noerrno(LLAPI_MSG_ERROR,
589                                         "Pool '%s' is not on filesystem '%s'",
590                                         pool_name, fsname);
591                                 return -EINVAL;
592                         }
593                         pool_name = ptr + 1;
594                 }
595
596                 /* Make sure the pool exists and is non-empty */
597                 rc = llapi_search_ost(fsname, pool_name, NULL);
598                 if (rc < 1) {
599                         char *err = rc == 0 ? "has no OSTs" : "does not exist";
600
601                         llapi_err_noerrno(LLAPI_MSG_ERROR, "pool '%s.%s' %s",
602                                           fsname, pool_name, err);
603                         return -EINVAL;
604                 }
605
606                 lum_size = sizeof(struct lov_user_md_v3);
607         }
608
609         /* sanity check of target list */
610         if (param->lsp_is_specific) {
611                 char ostname[MAX_OBD_NAME + 64];
612                 bool found = false;
613                 int i;
614
615                 for (i = 0; i < param->lsp_stripe_count; i++) {
616                         snprintf(ostname, sizeof(ostname), "%s-OST%04x_UUID",
617                                  fsname, param->lsp_osts[i]);
618                         rc = llapi_search_ost(fsname, pool_name, ostname);
619                         if (rc <= 0) {
620                                 if (rc == 0)
621                                         rc = -ENODEV;
622
623                                 llapi_error(LLAPI_MSG_ERROR, rc,
624                                             "%s: cannot find OST %s in %s",
625                                             __func__, ostname,
626                                             pool_name != NULL ?
627                                             "pool" : "system");
628                                 return rc;
629                         }
630
631                         /* Make sure stripe offset is in OST list. */
632                         if (param->lsp_osts[i] == param->lsp_stripe_offset)
633                                 found = true;
634                 }
635                 if (!found) {
636                         llapi_error(LLAPI_MSG_ERROR, -EINVAL,
637                                     "%s: stripe offset '%d' is not in the "
638                                     "target list",
639                                     __func__, param->lsp_stripe_offset);
640                         return -EINVAL;
641                 }
642
643                 lum_size = lov_user_md_size(param->lsp_stripe_count,
644                                             LOV_USER_MAGIC_SPECIFIC);
645         }
646
647         lum = calloc(1, lum_size);
648         if (lum == NULL)
649                 return -ENOMEM;
650
651 retry_open:
652         fd = open(name, flags | O_LOV_DELAY_CREATE, mode);
653         if (fd < 0) {
654                 if (errno == EISDIR && !(flags & O_DIRECTORY)) {
655                         flags = O_DIRECTORY | O_RDONLY;
656                         goto retry_open;
657                 }
658         }
659
660         if (fd < 0) {
661                 rc = -errno;
662                 llapi_error(LLAPI_MSG_ERROR, rc, "unable to open '%s'", name);
663                 free(lum);
664                 return rc;
665         }
666
667         /*  Initialize IOCTL striping pattern structure */
668         lum->lmm_magic = LOV_USER_MAGIC_V1;
669         lum->lmm_pattern = param->lsp_stripe_pattern;
670         lum->lmm_stripe_size = param->lsp_stripe_size;
671         lum->lmm_stripe_count = param->lsp_stripe_count;
672         lum->lmm_stripe_offset = param->lsp_stripe_offset;
673         if (pool_name != NULL) {
674                 struct lov_user_md_v3 *lumv3 = (void *)lum;
675
676                 lumv3->lmm_magic = LOV_USER_MAGIC_V3;
677                 strncpy(lumv3->lmm_pool_name, pool_name, LOV_MAXPOOLNAME);
678         }
679         if (param->lsp_is_specific) {
680                 struct lov_user_md_v3 *lumv3 = (void *)lum;
681                 int i;
682
683                 lumv3->lmm_magic = LOV_USER_MAGIC_SPECIFIC;
684                 if (pool_name == NULL) {
685                         /* LOV_USER_MAGIC_SPECIFIC uses v3 format plus specified
686                          * OST list, therefore if pool is not specified we have
687                          * to pack a null pool name for placeholder. */
688                         memset(lumv3->lmm_pool_name, 0, LOV_MAXPOOLNAME);
689                 }
690
691                 for (i = 0; i < param->lsp_stripe_count; i++)
692                         lumv3->lmm_objects[i].l_ost_idx = param->lsp_osts[i];
693         }
694
695         if (ioctl(fd, LL_IOC_LOV_SETSTRIPE, lum) != 0) {
696                 char *errmsg = "stripe already set";
697
698                 rc = -errno;
699                 if (errno != EEXIST && errno != EALREADY)
700                         errmsg = strerror(errno);
701
702                 llapi_err_noerrno(LLAPI_MSG_ERROR,
703                                   "setstripe error for '%s': %s", name, errmsg);
704
705                 close(fd);
706                 fd = rc;
707         }
708
709         free(lum);
710
711         return fd;
712 }
713
714 int llapi_file_open_pool(const char *name, int flags, int mode,
715                          unsigned long long stripe_size, int stripe_offset,
716                          int stripe_count, int stripe_pattern, char *pool_name)
717 {
718         const struct llapi_stripe_param param = {
719                 .lsp_stripe_size = stripe_size,
720                 .lsp_stripe_count = stripe_count,
721                 .lsp_stripe_pattern = stripe_pattern,
722                 .lsp_stripe_offset = stripe_offset,
723                 .lsp_pool = pool_name
724         };
725         return llapi_file_open_param(name, flags, mode, &param);
726 }
727
728 int llapi_file_open(const char *name, int flags, int mode,
729                     unsigned long long stripe_size, int stripe_offset,
730                     int stripe_count, int stripe_pattern)
731 {
732         return llapi_file_open_pool(name, flags, mode, stripe_size,
733                                     stripe_offset, stripe_count,
734                                     stripe_pattern, NULL);
735 }
736
737 int llapi_file_create_foreign(const char *name, mode_t mode, __u32 type,
738                               __u32 flags, char *foreign_lov)
739 {
740         size_t len;
741         struct lov_foreign_md *lfm;
742         int fd, rc;
743
744         if (foreign_lov == NULL) {
745                 rc = -EINVAL;
746                 llapi_error(LLAPI_MSG_ERROR, rc,
747                             "foreign LOV EA content must be provided");
748                 goto out_err;
749         }
750
751         len = strlen(foreign_lov);
752         if (len > XATTR_SIZE_MAX - offsetof(struct lov_foreign_md, lfm_value) ||
753             len <= 0) {
754                 rc = -EINVAL;
755                 llapi_error(LLAPI_MSG_ERROR, rc,
756                             "foreign LOV EA size %zu (must be 0 < len < %zu)",
757                             len, XATTR_SIZE_MAX -
758                             offsetof(struct lov_foreign_md, lfm_value));
759                 goto out_err;
760         }
761
762         lfm = malloc(len + offsetof(struct lov_foreign_md, lfm_value));
763         if (lfm == NULL) {
764                 rc = -ENOMEM;
765                 llapi_error(LLAPI_MSG_ERROR, rc,
766                             "failed to allocate lov_foreign_md");
767                 goto out_err;
768         }
769
770         fd = open(name, O_WRONLY|O_CREAT|O_LOV_DELAY_CREATE, mode);
771         if (fd == -1) {
772                 fd = -errno;
773                 llapi_error(LLAPI_MSG_ERROR, fd, "open '%s' failed", name);
774                 goto out_free;
775         }
776
777         lfm->lfm_magic = LOV_USER_MAGIC_FOREIGN;
778         lfm->lfm_length = len;
779         lfm->lfm_type = type;
780         lfm->lfm_flags = flags;
781         memcpy(lfm->lfm_value, foreign_lov, len);
782
783         if (ioctl(fd, LL_IOC_LOV_SETSTRIPE, lfm) != 0) {
784                 char *errmsg = "stripe already set";
785
786                 rc = -errno;
787                 if (errno == ENOTTY)
788                         errmsg = "not on a Lustre filesystem";
789                 else if (errno == EEXIST || errno == EALREADY)
790                         errmsg = "stripe already set";
791                 else
792                         errmsg = strerror(errno);
793
794                 llapi_err_noerrno(LLAPI_MSG_ERROR,
795                                   "setstripe error for '%s': %s", name, errmsg);
796
797                 close(fd);
798                 fd = rc;
799         }
800
801 out_free:
802         free(lfm);
803
804         return fd;
805
806 out_err:
807         errno = -rc;
808         return rc;
809 }
810
811 int llapi_file_create(const char *name, unsigned long long stripe_size,
812                       int stripe_offset, int stripe_count, int stripe_pattern)
813 {
814         int fd;
815
816         fd = llapi_file_open_pool(name, O_CREAT | O_WRONLY, 0644, stripe_size,
817                                   stripe_offset, stripe_count, stripe_pattern,
818                                   NULL);
819         if (fd < 0)
820                 return fd;
821
822         close(fd);
823         return 0;
824 }
825
826 int llapi_file_create_pool(const char *name, unsigned long long stripe_size,
827                            int stripe_offset, int stripe_count,
828                            int stripe_pattern, char *pool_name)
829 {
830         int fd;
831
832         fd = llapi_file_open_pool(name, O_CREAT | O_WRONLY, 0644, stripe_size,
833                                   stripe_offset, stripe_count, stripe_pattern,
834                                   pool_name);
835         if (fd < 0)
836                 return fd;
837
838         close(fd);
839         return 0;
840 }
841
842 static int verify_dir_param(const char *name,
843                             const struct llapi_stripe_param *param)
844 {
845         char fsname[MAX_OBD_NAME + 1] = { 0 };
846         char *pool_name = param->lsp_pool;
847         int rc;
848
849         /* Make sure we are on a Lustre file system */
850         rc = llapi_search_fsname(name, fsname);
851         if (rc) {
852                 llapi_error(LLAPI_MSG_ERROR, rc,
853                             "'%s' is not on a Lustre filesystem",
854                             name);
855                 return rc;
856         }
857
858         /* Check if the stripe pattern is sane. */
859         rc = llapi_dir_stripe_limit_check(param->lsp_stripe_offset,
860                                           param->lsp_stripe_count,
861                                           param->lsp_stripe_pattern);
862         if (rc != 0)
863                 return rc;
864
865         /* Make sure we have a good pool */
866         if (pool_name != NULL) {
867                 /* in case user gives the full pool name <fsname>.<poolname>,
868                  * strip the fsname */
869                 char *ptr = strchr(pool_name, '.');
870
871                 if (ptr != NULL) {
872                         *ptr = '\0';
873                         if (strcmp(pool_name, fsname) != 0) {
874                                 *ptr = '.';
875                                 llapi_err_noerrno(LLAPI_MSG_ERROR,
876                                         "Pool '%s' is not on filesystem '%s'",
877                                         pool_name, fsname);
878                                 return -EINVAL;
879                         }
880                         pool_name = ptr + 1;
881                 }
882
883                 /* Make sure the pool exists and is non-empty */
884                 rc = llapi_search_tgt(fsname, pool_name, NULL, true);
885                 if (rc < 1) {
886                         char *err = rc == 0 ? "has no OSTs" : "does not exist";
887
888                         llapi_err_noerrno(LLAPI_MSG_ERROR, "pool '%s.%s' %s",
889                                           fsname, pool_name, err);
890                         return -EINVAL;
891                 }
892         }
893
894         /* sanity check of target list */
895         if (param->lsp_is_specific) {
896                 char mdtname[MAX_OBD_NAME + 64];
897                 bool found = false;
898                 int i;
899
900                 for (i = 0; i < param->lsp_stripe_count; i++) {
901                         snprintf(mdtname, sizeof(mdtname), "%s-MDT%04x_UUID",
902                                  fsname, param->lsp_tgts[i]);
903                         rc = llapi_search_tgt(fsname, pool_name, mdtname, true);
904                         if (rc <= 0) {
905                                 if (rc == 0)
906                                         rc = -ENODEV;
907
908                                 llapi_error(LLAPI_MSG_ERROR, rc,
909                                             "%s: cannot find MDT %s in %s",
910                                             __func__, mdtname,
911                                             pool_name != NULL ?
912                                             "pool" : "system");
913                                 return rc;
914                         }
915
916                         /* Make sure stripe offset is in MDT list. */
917                         if (param->lsp_tgts[i] == param->lsp_stripe_offset)
918                                 found = true;
919                 }
920                 if (!found) {
921                         llapi_error(LLAPI_MSG_ERROR, -EINVAL,
922                                     "%s: stripe offset '%d' is not in the "
923                                     "target list",
924                                     __func__, param->lsp_stripe_offset);
925                         return -EINVAL;
926                 }
927         }
928
929         return 0;
930 }
931
932 static inline void param2lmu(struct lmv_user_md *lmu,
933                              const struct llapi_stripe_param *param)
934 {
935         lmu->lum_magic = param->lsp_is_specific ? LMV_USER_MAGIC_SPECIFIC :
936                                                   LMV_USER_MAGIC;
937         lmu->lum_stripe_count = param->lsp_stripe_count;
938         lmu->lum_stripe_offset = param->lsp_stripe_offset;
939         lmu->lum_hash_type = param->lsp_stripe_pattern;
940         if (param->lsp_pool != NULL)
941                 strncpy(lmu->lum_pool_name, param->lsp_pool, LOV_MAXPOOLNAME);
942         if (param->lsp_is_specific) {
943                 int i;
944
945                 for (i = 0; i < param->lsp_stripe_count; i++)
946                         lmu->lum_objects[i].lum_mds = param->lsp_tgts[i];
947         }
948 }
949
950 int llapi_dir_set_default_lmv(const char *name,
951                               const struct llapi_stripe_param *param)
952 {
953         struct lmv_user_md lmu = { 0 };
954         int fd;
955         int rc = 0;
956
957         rc = verify_dir_param(name, param);
958         if (rc)
959                 return rc;
960
961         /* TODO: default lmv doesn't support specific targets yet */
962         if (param->lsp_is_specific)
963                 return -EINVAL;
964
965         param2lmu(&lmu, param);
966
967         fd = open(name, O_DIRECTORY | O_RDONLY);
968         if (fd < 0) {
969                 rc = -errno;
970                 llapi_error(LLAPI_MSG_ERROR, rc, "unable to open '%s'", name);
971                 return rc;
972         }
973
974         rc = ioctl(fd, LL_IOC_LMV_SET_DEFAULT_STRIPE, &lmu);
975         if (rc < 0) {
976                 char *errmsg = "stripe already set";
977                 rc = -errno;
978                 if (errno != EEXIST && errno != EALREADY)
979                         errmsg = strerror(errno);
980
981                 llapi_err_noerrno(LLAPI_MSG_ERROR,
982                                   "default dirstripe error on '%s': %s",
983                                   name, errmsg);
984         }
985         close(fd);
986         return rc;
987 }
988
989 int llapi_dir_set_default_lmv_stripe(const char *name, int stripe_offset,
990                                      int stripe_count, int stripe_pattern,
991                                      const char *pool_name)
992 {
993         const struct llapi_stripe_param param = {
994                 .lsp_stripe_count = stripe_count,
995                 .lsp_stripe_offset = stripe_offset,
996                 .lsp_stripe_pattern = stripe_pattern,
997                 .lsp_pool = (char *)pool_name
998         };
999
1000         return llapi_dir_set_default_lmv(name, &param);
1001 }
1002
1003 /**
1004  * Create a Lustre directory.
1005  *
1006  * \param name     the name of the directory to be created
1007  * \param mode     permission of the file if it is created, see mode in open(2)
1008  * \param param    stripe pattern of the newly created directory
1009  *
1010  * \retval         0 on success
1011  * \retval         negative errno on failure
1012  */
1013 int llapi_dir_create(const char *name, mode_t mode,
1014                      const struct llapi_stripe_param *param)
1015 {
1016         struct lmv_user_md *lmu = NULL;
1017         size_t lmu_size;
1018         struct obd_ioctl_data data = { 0 };
1019         char rawbuf[8192];
1020         char *buf = rawbuf;
1021         char *dirpath = NULL;
1022         char *namepath = NULL;
1023         char *dir;
1024         char *filename;
1025         int fd, rc;
1026
1027         rc = verify_dir_param(name, param);
1028         if (rc)
1029                 return rc;
1030
1031         lmu_size = lmv_user_md_size(param->lsp_stripe_count,
1032                                     param->lsp_is_specific ?
1033                                          LMV_USER_MAGIC_SPECIFIC :
1034                                          LMV_USER_MAGIC);
1035
1036         lmu = calloc(1, lmu_size);
1037         if (lmu == NULL)
1038                 return -ENOMEM;
1039
1040         dirpath = strdup(name);
1041         if (!dirpath) {
1042                 free(lmu);
1043                 return -ENOMEM;
1044         }
1045
1046         namepath = strdup(name);
1047         if (!namepath) {
1048                 free(dirpath);
1049                 free(lmu);
1050                 return -ENOMEM;
1051         }
1052
1053         param2lmu(lmu, param);
1054
1055         filename = basename(namepath);
1056         dir = dirname(dirpath);
1057
1058         data.ioc_inlbuf1 = (char *)filename;
1059         data.ioc_inllen1 = strlen(filename) + 1;
1060         data.ioc_inlbuf2 = (char *)lmu;
1061         data.ioc_inllen2 = lmu_size;
1062         data.ioc_type = mode;
1063         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
1064         if (rc) {
1065                 llapi_error(LLAPI_MSG_ERROR, rc,
1066                             "error: LL_IOC_LMV_SETSTRIPE pack failed '%s'.",
1067                             name);
1068                 goto out;
1069         }
1070
1071         fd = open(dir, O_DIRECTORY | O_RDONLY);
1072         if (fd < 0) {
1073                 rc = -errno;
1074                 llapi_error(LLAPI_MSG_ERROR, rc, "unable to open '%s'", name);
1075                 goto out;
1076         }
1077
1078         if (ioctl(fd, LL_IOC_LMV_SETSTRIPE, buf)) {
1079                 char *errmsg = "stripe already set";
1080
1081                 rc = -errno;
1082                 if (errno != EEXIST && errno != EALREADY)
1083                         errmsg = strerror(errno);
1084
1085                 llapi_err_noerrno(LLAPI_MSG_ERROR,
1086                                   "dirstripe error on '%s': %s", name, errmsg);
1087         }
1088         close(fd);
1089 out:
1090         free(namepath);
1091         free(dirpath);
1092         free(lmu);
1093         return rc;
1094 }
1095
1096 /**
1097  * Create a foreign directory.
1098  *
1099  * \param name     the name of the directory to be created
1100  * \param mode     permission of the file if it is created, see mode in open(2)
1101  * \param type     foreign type to be set in LMV EA
1102  * \param flags    foreign flags to be set in LMV EA
1103  * \param value    foreign pattern to be set in LMV EA
1104  *
1105  * \retval         0 on success
1106  * \retval         negative errno on failure
1107  */
1108 int llapi_dir_create_foreign(const char *name, mode_t mode, __u32 type,
1109                              __u32 flags, const char *value)
1110 {
1111         struct lmv_foreign_md *lfm = NULL;
1112         size_t lfm_size, len;
1113         struct obd_ioctl_data data = { 0 };
1114         char rawbuf[8192];
1115         char *buf = rawbuf;
1116         char *dirpath = NULL;
1117         char *namepath = NULL;
1118         char *dir;
1119         char *filename;
1120         int fd, rc;
1121
1122         len = strlen(value);
1123         if (len > XATTR_SIZE_MAX - offsetof(struct lmv_foreign_md, lfm_value) ||
1124             len <= 0) {
1125                 rc = -EINVAL;
1126                 llapi_error(LLAPI_MSG_ERROR, rc, "invalid LOV EA length %zu "
1127                         "(must be 0 < len < %zu)\n", len,
1128                         XATTR_SIZE_MAX -
1129                         offsetof(struct lmv_foreign_md, lfm_value));
1130                 return rc;
1131         }
1132         lfm_size = len + offsetof(struct lmv_foreign_md, lfm_value);
1133         lfm = calloc(1, lfm_size);
1134         if (lfm == NULL)
1135                 return -ENOMEM;
1136
1137         dirpath = strdup(name);
1138         if (!dirpath) {
1139                 free(lfm);
1140                 return -ENOMEM;
1141         }
1142
1143         namepath = strdup(name);
1144         if (!namepath) {
1145                 free(dirpath);
1146                 free(lfm);
1147                 return -ENOMEM;
1148         }
1149
1150         lfm->lfm_magic = LMV_MAGIC_FOREIGN;
1151         lfm->lfm_length = len;
1152         lfm->lfm_type = type;
1153         lfm->lfm_flags = flags;
1154         memcpy(lfm->lfm_value, value, len);
1155
1156         filename = basename(namepath);
1157         dir = dirname(dirpath);
1158
1159         data.ioc_inlbuf1 = (char *)filename;
1160         data.ioc_inllen1 = strlen(filename) + 1;
1161         data.ioc_inlbuf2 = (char *)lfm;
1162         data.ioc_inllen2 = lfm_size;
1163         data.ioc_type = mode;
1164         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
1165         if (rc) {
1166                 llapi_error(LLAPI_MSG_ERROR, rc,
1167                             "error: LL_IOC_LMV_SETSTRIPE pack failed '%s'.",
1168                             name);
1169                 goto out;
1170         }
1171
1172         fd = open(dir, O_DIRECTORY | O_RDONLY);
1173         if (fd < 0) {
1174                 rc = -errno;
1175                 llapi_error(LLAPI_MSG_ERROR, rc, "unable to open '%s'", name);
1176                 goto out;
1177         }
1178
1179         if (ioctl(fd, LL_IOC_LMV_SETSTRIPE, buf)) {
1180                 char *errmsg = "stripe already set";
1181
1182                 rc = -errno;
1183                 if (errno != EEXIST && errno != EALREADY)
1184                         errmsg = strerror(errno);
1185
1186                 llapi_err_noerrno(LLAPI_MSG_ERROR,
1187                                   "dirstripe error on '%s': %s", name, errmsg);
1188         }
1189         close(fd);
1190 out:
1191         free(namepath);
1192         free(dirpath);
1193         free(lfm);
1194         return rc;
1195 }
1196
1197 int llapi_dir_create_pool(const char *name, int mode, int stripe_offset,
1198                           int stripe_count, int stripe_pattern,
1199                           const char *pool_name)
1200 {
1201         const struct llapi_stripe_param param = {
1202                 .lsp_stripe_count = stripe_count,
1203                 .lsp_stripe_offset = stripe_offset,
1204                 .lsp_stripe_pattern = stripe_pattern,
1205                 .lsp_pool = (char *)pool_name
1206         };
1207
1208         return llapi_dir_create(name, mode, &param);
1209 }
1210
1211 int llapi_direntry_remove(char *dname)
1212 {
1213         char *dirpath = NULL;
1214         char *namepath = NULL;
1215         char *dir;
1216         char *filename;
1217         int fd = -1;
1218         int rc = 0;
1219
1220         dirpath = strdup(dname);
1221         namepath = strdup(dname);
1222         if (!dirpath || !namepath)
1223                 return -ENOMEM;
1224
1225         filename = basename(namepath);
1226
1227         dir = dirname(dirpath);
1228
1229         fd = open(dir, O_DIRECTORY | O_RDONLY);
1230         if (fd < 0) {
1231                 rc = -errno;
1232                 llapi_error(LLAPI_MSG_ERROR, rc, "unable to open '%s'",
1233                             filename);
1234                 goto out;
1235         }
1236
1237         if (ioctl(fd, LL_IOC_REMOVE_ENTRY, filename)) {
1238                 char *errmsg = strerror(errno);
1239                 llapi_err_noerrno(LLAPI_MSG_ERROR,
1240                                   "error on ioctl %#jx for '%s' (%d): %s",
1241                                   (uintmax_t)LL_IOC_LMV_SETSTRIPE, filename,
1242                                   fd, errmsg);
1243         }
1244 out:
1245         free(dirpath);
1246         free(namepath);
1247         if (fd != -1)
1248                 close(fd);
1249         return rc;
1250 }
1251
1252 /*
1253  * Find the fsname, the full path, and/or an open fd.
1254  * Either the fsname or path must not be NULL
1255  */
1256 int get_root_path(int want, char *fsname, int *outfd, char *path, int index)
1257 {
1258         struct mntent mnt;
1259         char buf[PATH_MAX], mntdir[PATH_MAX];
1260         char *ptr, *ptr_end;
1261         FILE *fp;
1262         int idx = 0, len = 0, mntlen, fd;
1263         int rc = -ENODEV;
1264
1265         /* get the mount point */
1266         fp = setmntent(PROC_MOUNTS, "r");
1267         if (fp == NULL) {
1268                 rc = -EIO;
1269                 llapi_error(LLAPI_MSG_ERROR, rc,
1270                             "cannot retrieve filesystem mount point");
1271                 return rc;
1272         }
1273         while (1) {
1274                 if (getmntent_r(fp, &mnt, buf, sizeof(buf)) == NULL)
1275                         break;
1276
1277                 if (!llapi_is_lustre_mnt(&mnt))
1278                         continue;
1279
1280                 if ((want & WANT_INDEX) && (idx++ != index))
1281                         continue;
1282
1283                 mntlen = strlen(mnt.mnt_dir);
1284                 ptr = strchr(mnt.mnt_fsname, '/');
1285                 while (ptr && *ptr == '/')
1286                         ptr++;
1287                 /* thanks to the call to llapi_is_lustre_mnt() above,
1288                  * we are sure that mnt.mnt_fsname contains ":/",
1289                  * so ptr should never be NULL */
1290                 if (ptr == NULL)
1291                         continue;
1292                 ptr_end = ptr;
1293                 while (*ptr_end != '/' && *ptr_end != '\0')
1294                         ptr_end++;
1295
1296                 /* Check the fsname for a match, if given */
1297                 if (!(want & WANT_FSNAME) && fsname != NULL &&
1298                     (strlen(fsname) > 0) &&
1299                     (strncmp(ptr, fsname, ptr_end - ptr) != 0))
1300                         continue;
1301
1302                 /* If the path isn't set return the first one we find */
1303                 if (path == NULL || strlen(path) == 0) {
1304                         strncpy(mntdir, mnt.mnt_dir, sizeof(mntdir) - 1);
1305                         mntdir[sizeof(mntdir) - 1] = '\0';
1306                         if ((want & WANT_FSNAME) && fsname != NULL) {
1307                                 strncpy(fsname, ptr, ptr_end - ptr);
1308                                 fsname[ptr_end - ptr] = '\0';
1309                         }
1310                         rc = 0;
1311                         break;
1312                 /* Otherwise find the longest matching path */
1313                 } else if ((strlen(path) >= mntlen) && (mntlen >= len) &&
1314                            (strncmp(mnt.mnt_dir, path, mntlen) == 0)) {
1315                         strncpy(mntdir, mnt.mnt_dir, sizeof(mntdir) - 1);
1316                         mntdir[sizeof(mntdir) - 1] = '\0';
1317                         len = mntlen;
1318                         if ((want & WANT_FSNAME) && fsname != NULL) {
1319                                 strncpy(fsname, ptr, ptr_end - ptr);
1320                                 fsname[ptr_end - ptr] = '\0';
1321                         }
1322                         rc = 0;
1323                 }
1324         }
1325         endmntent(fp);
1326
1327         /* Found it */
1328         if (rc == 0) {
1329                 if ((want & WANT_PATH) && path != NULL) {
1330                         strncpy(path, mntdir, PATH_MAX);
1331                         path[strlen(mntdir)] = '\0';
1332                 }
1333                 if (want & WANT_FD) {
1334                         fd = open(mntdir, O_RDONLY | O_DIRECTORY | O_NONBLOCK);
1335                         if (fd < 0) {
1336                                 rc = -errno;
1337                                 llapi_error(LLAPI_MSG_ERROR, rc,
1338                                             "cannot open '%s': %s", mntdir,
1339                                             strerror(-rc));
1340
1341                         } else {
1342                                 *outfd = fd;
1343                         }
1344                 }
1345         } else if (want & WANT_ERROR)
1346                 llapi_err_noerrno(LLAPI_MSG_ERROR,
1347                                   "'%s' not on a mounted Lustre filesystem",
1348                                   (want & WANT_PATH) ? fsname : path);
1349         return rc;
1350 }
1351
1352 /*
1353  * search lustre mounts
1354  *
1355  * Calling this function will return to the user the mount point, mntdir, and
1356  * the file system name, fsname, if the user passed a buffer to this routine.
1357  *
1358  * The user inputs are pathname and index. If the pathname is supplied then
1359  * the value of the index will be ignored. The pathname will return data if
1360  * the pathname is located on a lustre mount. Index is used to pick which
1361  * mount point you want in the case of multiple mounted lustre file systems.
1362  * See function lfs_osts in lfs.c for an example of the index use.
1363  */
1364 int llapi_search_mounts(const char *pathname, int index, char *mntdir,
1365                         char *fsname)
1366 {
1367         int want = WANT_PATH, idx = -1;
1368
1369         if (!pathname || pathname[0] == '\0') {
1370                 want |= WANT_INDEX;
1371                 idx = index;
1372         } else
1373                 strcpy(mntdir, pathname);
1374
1375         if (fsname)
1376                 want |= WANT_FSNAME;
1377         return get_root_path(want, fsname, NULL, mntdir, idx);
1378 }
1379
1380 /* Given a path, find the corresponding Lustre fsname */
1381 int llapi_search_fsname(const char *pathname, char *fsname)
1382 {
1383         char *path;
1384         int rc;
1385
1386         path = realpath(pathname, NULL);
1387         if (path == NULL) {
1388                 char tmp[PATH_MAX - 1];
1389                 char buf[PATH_MAX];
1390                 char *ptr;
1391
1392                 tmp[0] = '\0';
1393                 buf[0] = '\0';
1394                 if (pathname[0] != '/') {
1395                         /* Need an absolute path, but realpath() only works for
1396                          * pathnames that actually exist.  We go through the
1397                          * extra hurdle of dirname(getcwd() + pathname) in
1398                          * case the relative pathname contains ".." in it. */
1399                         char realpath[PATH_MAX - 1];
1400
1401                         if (getcwd(realpath, sizeof(realpath) - 2) == NULL) {
1402                                 rc = -errno;
1403                                 llapi_error(LLAPI_MSG_ERROR, rc,
1404                                             "cannot get current working directory");
1405                                 return rc;
1406                         }
1407
1408                         rc = snprintf(tmp, sizeof(tmp), "%s/", realpath);
1409                         if (rc >= sizeof(tmp)) {
1410                                 rc = -E2BIG;
1411                                 llapi_error(LLAPI_MSG_ERROR, rc,
1412                                             "invalid parent path '%s'",
1413                                             tmp);
1414                                 return rc;
1415                         }
1416                 }
1417
1418                 rc = snprintf(buf, sizeof(buf), "%s%s", tmp, pathname);
1419                 if (rc >= sizeof(buf)) {
1420                         rc = -E2BIG;
1421                         llapi_error(LLAPI_MSG_ERROR, rc,
1422                                     "invalid path '%s'", pathname);
1423                         return rc;
1424                 }
1425                 path = realpath(buf, NULL);
1426                 if (path == NULL) {
1427                         ptr = strrchr(buf, '/');
1428                         if (ptr == NULL) {
1429                                 llapi_error(LLAPI_MSG_ERROR |
1430                                             LLAPI_MSG_NO_ERRNO, 0,
1431                                             "cannot resolve path '%s'",
1432                                             buf);
1433                                 return -ENOENT;
1434                         }
1435                         *ptr = '\0';
1436                         path = realpath(buf, NULL);
1437                         if (path == NULL) {
1438                                 rc = -errno;
1439                                 llapi_error(LLAPI_MSG_ERROR, rc,
1440                                             "cannot resolve path '%s'",
1441                                              pathname);
1442                                 return rc;
1443                         }
1444                 }
1445         }
1446         rc = get_root_path(WANT_FSNAME | WANT_ERROR, fsname, NULL, path, -1);
1447         free(path);
1448         return rc;
1449 }
1450
1451 int llapi_search_rootpath(char *pathname, const char *fsname)
1452 {
1453         return get_root_path(WANT_PATH, (char *)fsname, NULL, pathname, -1);
1454 }
1455
1456 int llapi_getname(const char *path, char *buf, size_t size)
1457 {
1458         struct obd_uuid uuid_buf;
1459         char *uuid = uuid_buf.uuid;
1460         char *cfg_instance;
1461         int rc, len, fsname_len;
1462
1463         memset(&uuid_buf, 0, sizeof(uuid_buf));
1464         rc = llapi_file_get_lov_uuid(path, &uuid_buf);
1465         if (rc)
1466                 return rc;
1467
1468         /*
1469          * We want to turn testfs-clilov-ffff88002738bc00 into
1470          * testfs-ffff88002738bc00 in a portable way that doesn't depend
1471          * on what is after "-clilov-" as it may change in the future.
1472          * Unfortunately, the "fsname" part may contain a dash, so we
1473          * can't just skip to the first dash, and the "instance" may be a
1474          * UUID in the future, so we can't necessarily go to the last dash.
1475          */
1476         cfg_instance = strstr(uuid, "-clilov-");
1477         if (!cfg_instance)
1478                 return -EINVAL;
1479
1480         fsname_len = cfg_instance - uuid;
1481         cfg_instance += strlen("-clilov-");
1482         len = snprintf(buf, size, "%.*s-%s", fsname_len, uuid, cfg_instance);
1483
1484         if (len >= size)
1485                 rc = -ENAMETOOLONG;
1486
1487         return rc;
1488 }
1489
1490 /**
1491  * Get the list of pool members.
1492  * \param poolname    string of format \<fsname\>.\<poolname\>
1493  * \param members     caller-allocated array of char*
1494  * \param list_size   size of the members array
1495  * \param buffer      caller-allocated buffer for storing OST names
1496  * \param buffer_size size of the buffer
1497  *
1498  * \return number of members retrieved for this pool
1499  * \retval -error failure
1500  */
1501 int llapi_get_poolmembers(const char *poolname, char **members,
1502                           int list_size, char *buffer, int buffer_size)
1503 {
1504         char fsname[PATH_MAX];
1505         char *pool, *tmp;
1506         glob_t pathname;
1507         char buf[PATH_MAX];
1508         FILE *fd;
1509         int rc = 0;
1510         int nb_entries = 0;
1511         int used = 0;
1512
1513         /* name is FSNAME.POOLNAME */
1514         if (strlen(poolname) >= sizeof(fsname))
1515                 return -EOVERFLOW;
1516
1517         snprintf(fsname, sizeof(fsname), "%s", poolname);
1518         pool = strchr(fsname, '.');
1519         if (pool == NULL)
1520                 return -EINVAL;
1521
1522         *pool = '\0';
1523         pool++;
1524
1525         rc = poolpath(&pathname, fsname, NULL);
1526         if (rc != 0) {
1527                 llapi_error(LLAPI_MSG_ERROR, rc,
1528                             "Lustre filesystem '%s' not found",
1529                             fsname);
1530                 return rc;
1531         }
1532
1533         llapi_printf(LLAPI_MSG_NORMAL, "Pool: %s.%s\n", fsname, pool);
1534         rc = snprintf(buf, sizeof(buf), "%s/%s", pathname.gl_pathv[0], pool);
1535         cfs_free_param_data(&pathname);
1536         if (rc >= sizeof(buf))
1537                 return -EOVERFLOW;
1538         fd = fopen(buf, "r");
1539         if (fd == NULL) {
1540                 rc = -errno;
1541                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot open %s", buf);
1542                 return rc;
1543         }
1544
1545         rc = 0;
1546         while (fgets(buf, sizeof(buf), fd) != NULL) {
1547                 if (nb_entries >= list_size) {
1548                         rc = -EOVERFLOW;
1549                         break;
1550                 }
1551                 buf[sizeof(buf) - 1] = '\0';
1552                 /* remove '\n' */
1553                 tmp = strchr(buf, '\n');
1554                 if (tmp != NULL)
1555                         *tmp='\0';
1556                 if (used + strlen(buf) + 1 > buffer_size) {
1557                         rc = -EOVERFLOW;
1558                         break;
1559                 }
1560
1561                 strcpy(buffer + used, buf);
1562                 members[nb_entries] = buffer + used;
1563                 used += strlen(buf) + 1;
1564                 nb_entries++;
1565                 rc = nb_entries;
1566         }
1567
1568         fclose(fd);
1569         return rc;
1570 }
1571
1572 /**
1573  * Get the list of pools in a filesystem.
1574  * \param name        filesystem name or path
1575  * \param poollist    caller-allocated array of char*
1576  * \param list_size   size of the poollist array
1577  * \param buffer      caller-allocated buffer for storing pool names
1578  * \param buffer_size size of the buffer
1579  *
1580  * \return number of pools retrieved for this filesystem
1581  * \retval -error failure
1582  */
1583 int llapi_get_poollist(const char *name, char **poollist, int list_size,
1584                        char *buffer, int buffer_size)
1585 {
1586         glob_t pathname;
1587         char *fsname;
1588         char *ptr;
1589         DIR *dir;
1590         struct dirent *pool;
1591         int rc = 0;
1592         unsigned int nb_entries = 0;
1593         unsigned int used = 0;
1594         unsigned int i;
1595
1596         /* initialize output array */
1597         for (i = 0; i < list_size; i++)
1598                 poollist[i] = NULL;
1599
1600         /* is name a pathname ? */
1601         ptr = strchr(name, '/');
1602         if (ptr != NULL) {
1603                 char fsname_buf[MAXNAMLEN];
1604
1605                 /* We will need fsname for printing later */
1606                 rc = llapi_getname(name, fsname_buf, sizeof(fsname_buf));
1607                 if (rc)
1608                         return rc;
1609
1610                 ptr = strrchr(fsname_buf, '-');
1611                 if (ptr)
1612                         *ptr = '\0';
1613
1614                 fsname = strdup(fsname_buf);
1615                 if (!fsname)
1616                         return -ENOMEM;
1617         } else {
1618                 /* name is FSNAME */
1619                 fsname = strdup(name);
1620                 if (!fsname)
1621                         return -ENOMEM;
1622         }
1623
1624         rc = poolpath(&pathname, fsname, NULL);
1625         if (rc != 0) {
1626                 llapi_error(LLAPI_MSG_ERROR, rc,
1627                             "Lustre filesystem '%s' not found", name);
1628                 goto free_path;
1629         }
1630
1631         dir = opendir(pathname.gl_pathv[0]);
1632         if (dir == NULL) {
1633                 rc = -errno;
1634                 llapi_error(LLAPI_MSG_ERROR, rc,
1635                             "Could not open pool list for '%s'",
1636                             name);
1637                 goto free_path;
1638         }
1639
1640         do {
1641                 errno = 0;
1642                 pool = readdir(dir);
1643                 if (pool == NULL) {
1644                         rc = -errno;
1645                         goto free_dir;
1646                 }
1647
1648                 /* ignore . and .. */
1649                 if (!strcmp(pool->d_name, ".") || !strcmp(pool->d_name, ".."))
1650                         continue;
1651
1652                 /* check output bounds */
1653                 if (nb_entries >= list_size) {
1654                         rc = -EOVERFLOW;
1655                         goto free_dir_no_msg;
1656                 }
1657
1658                 /* +2 for '.' and final '\0' */
1659                 if (used + strlen(pool->d_name) + strlen(fsname) + 2
1660                     > buffer_size) {
1661                         rc = -EOVERFLOW;
1662                         goto free_dir_no_msg;
1663                 }
1664
1665                 sprintf(buffer + used, "%s.%s", fsname, pool->d_name);
1666                 poollist[nb_entries] = buffer + used;
1667                 used += strlen(pool->d_name) + strlen(fsname) + 2;
1668                 nb_entries++;
1669         } while (1);
1670
1671 free_dir:
1672         if (rc)
1673                 llapi_error(LLAPI_MSG_ERROR, rc,
1674                             "Error reading pool list for '%s'", name);
1675         else
1676                 llapi_printf(LLAPI_MSG_NORMAL, "Pools from %s:\n", fsname);
1677
1678 free_dir_no_msg:
1679         closedir(dir);
1680 free_path:
1681         cfs_free_param_data(&pathname);
1682         if (fsname)
1683                 free(fsname);
1684         return rc != 0 ? rc : nb_entries;
1685 }
1686
1687 /* wrapper for lfs.c and obd.c */
1688 int llapi_poollist(const char *name)
1689 {
1690         /* list of pool names (assume that pool count is smaller
1691            than OST count) */
1692         char **list, *buffer = NULL, *fsname = (char *)name;
1693         char *poolname = NULL, *tmp = NULL, data[16];
1694         enum param_filter type = FILTER_BY_PATH;
1695         int obdcount, bufsize, rc, nb, i;
1696
1697         if (name == NULL)
1698                 return -EINVAL;
1699
1700         if (name[0] != '/') {
1701                 fsname = strdup(name);
1702                 if (fsname == NULL)
1703                         return -ENOMEM;
1704
1705                 poolname = strchr(fsname, '.');
1706                 if (poolname)
1707                         *poolname = '\0';
1708                 type = FILTER_BY_FS_NAME;
1709         }
1710
1711         rc = get_lustre_param_value("lov", fsname, type, "numobd",
1712                                     data, sizeof(data));
1713         if (rc < 0)
1714                 goto err;
1715         obdcount = atoi(data);
1716
1717         /* Allocate space for each fsname-OST0000_UUID, 1 per OST,
1718          * and also an array to store the pointers for all that
1719          * allocated space. */
1720 retry_get_pools:
1721         bufsize = sizeof(struct obd_uuid) * obdcount;
1722         buffer = realloc(tmp, bufsize + sizeof(*list) * obdcount);
1723         if (buffer == NULL) {
1724                 rc = -ENOMEM;
1725                 goto err;
1726         }
1727         list = (char **) (buffer + bufsize);
1728
1729         if (!poolname) {
1730                 /* name is a path or fsname */
1731                 nb = llapi_get_poollist(name, list, obdcount,
1732                                         buffer, bufsize);
1733         } else {
1734                 /* name is a pool name (<fsname>.<poolname>) */
1735                 nb = llapi_get_poolmembers(name, list, obdcount,
1736                                            buffer, bufsize);
1737         }
1738
1739         if (nb == -EOVERFLOW) {
1740                 obdcount *= 2;
1741                 tmp = buffer;
1742                 goto retry_get_pools;
1743         }
1744
1745         for (i = 0; i < nb; i++)
1746                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", list[i]);
1747         rc = (nb < 0 ? nb : 0);
1748 err:
1749         if (buffer)
1750                 free(buffer);
1751         if (fsname != NULL && type == FILTER_BY_FS_NAME)
1752                 free(fsname);
1753         return rc;
1754 }
1755
1756 typedef int (semantic_func_t)(char *path, DIR *parent, DIR **d,
1757                               void *data, struct dirent64 *de);
1758
1759 #define OBD_NOT_FOUND           (-1)
1760
1761 static void find_param_fini(struct find_param *param)
1762 {
1763         if (param->fp_migrate)
1764                 return;
1765
1766         if (param->fp_obd_indexes) {
1767                 free(param->fp_obd_indexes);
1768                 param->fp_obd_indexes = NULL;
1769         }
1770
1771         if (param->fp_lmd) {
1772                 free(param->fp_lmd);
1773                 param->fp_lmd = NULL;
1774         }
1775
1776         if (param->fp_lmv_md) {
1777                 free(param->fp_lmv_md);
1778                 param->fp_lmv_md = NULL;
1779         }
1780 }
1781
1782 static int common_param_init(struct find_param *param, char *path)
1783 {
1784         int lum_size = get_mds_md_size(path);
1785
1786         if (lum_size < 0)
1787                 return lum_size;
1788
1789         /* migrate has fp_lmv_md initialized outside */
1790         if (param->fp_migrate)
1791                 return 0;
1792
1793         if (lum_size < PATH_MAX + 1)
1794                 lum_size = PATH_MAX + 1;
1795
1796         param->fp_lum_size = lum_size;
1797         param->fp_lmd = calloc(1, sizeof(lstat_t) + lum_size);
1798         if (param->fp_lmd == NULL) {
1799                 llapi_error(LLAPI_MSG_ERROR, -ENOMEM,
1800                             "error: allocation of %zu bytes for ioctl",
1801                             sizeof(lstat_t) + param->fp_lum_size);
1802                 return -ENOMEM;
1803         }
1804
1805         param->fp_lmv_stripe_count = 256;
1806         param->fp_lmv_md = calloc(1,
1807                                   lmv_user_md_size(param->fp_lmv_stripe_count,
1808                                                    LMV_USER_MAGIC_SPECIFIC));
1809         if (param->fp_lmv_md == NULL) {
1810                 llapi_error(LLAPI_MSG_ERROR, -ENOMEM,
1811                             "error: allocation of %d bytes for ioctl",
1812                             lmv_user_md_size(param->fp_lmv_stripe_count,
1813                                              LMV_USER_MAGIC_SPECIFIC));
1814                 find_param_fini(param);
1815                 return -ENOMEM;
1816         }
1817
1818         param->fp_got_uuids = 0;
1819         param->fp_obd_indexes = NULL;
1820         param->fp_obd_index = OBD_NOT_FOUND;
1821         param->fp_mdt_index = OBD_NOT_FOUND;
1822         return 0;
1823 }
1824
1825 static int cb_common_fini(char *path, DIR *parent, DIR **dirp, void *data,
1826                           struct dirent64 *de)
1827 {
1828         struct find_param *param = data;
1829         param->fp_depth--;
1830
1831         return 0;
1832 }
1833
1834 /* set errno upon failure */
1835 static DIR *opendir_parent(const char *path)
1836 {
1837         char *path_copy;
1838         char *parent_path;
1839         DIR *parent;
1840
1841         path_copy = strdup(path);
1842         if (path_copy == NULL)
1843                 return NULL;
1844
1845         parent_path = dirname(path_copy);
1846         parent = opendir(parent_path);
1847         free(path_copy);
1848
1849         return parent;
1850 }
1851
1852 static int cb_get_dirstripe(char *path, DIR *d, struct find_param *param)
1853 {
1854         int ret;
1855
1856 again:
1857         param->fp_lmv_md->lum_stripe_count = param->fp_lmv_stripe_count;
1858         if (param->fp_get_default_lmv)
1859                 param->fp_lmv_md->lum_magic = LMV_USER_MAGIC;
1860         else
1861                 param->fp_lmv_md->lum_magic = LMV_MAGIC_V1;
1862
1863         ret = ioctl(dirfd(d), LL_IOC_LMV_GETSTRIPE, param->fp_lmv_md);
1864         if (errno == E2BIG && ret != 0) {
1865                 int stripe_count;
1866                 int lmv_size;
1867
1868                 /* if foreign LMV case, fake stripes number */
1869                 if (param->fp_lmv_md->lum_magic == LMV_MAGIC_FOREIGN) {
1870                         struct lmv_foreign_md *lfm;
1871
1872                         lfm = (struct lmv_foreign_md *)param->fp_lmv_md;
1873                         if (lfm->lfm_length < XATTR_SIZE_MAX -
1874                             offsetof(typeof(*lfm), lfm_value)) {
1875                                 uint32_t size = lfm->lfm_length +
1876                                              offsetof(typeof(*lfm), lfm_value);
1877
1878                                 stripe_count = lmv_foreign_to_md_stripes(size);
1879                         } else {
1880                                 llapi_error(LLAPI_MSG_ERROR, -EINVAL,
1881                                             "error: invalid %d foreign size "
1882                                             "returned from ioctl",
1883                                             lfm->lfm_length);
1884                                 return -EINVAL;
1885                         }
1886                 } else {
1887                         stripe_count = param->fp_lmv_md->lum_stripe_count;
1888                 }
1889                 if (stripe_count <= param->fp_lmv_stripe_count)
1890                         return ret;
1891
1892                 free(param->fp_lmv_md);
1893                 param->fp_lmv_stripe_count = stripe_count;
1894                 lmv_size = lmv_user_md_size(stripe_count,
1895                                             LMV_USER_MAGIC_SPECIFIC);
1896                 param->fp_lmv_md = malloc(lmv_size);
1897                 if (param->fp_lmv_md == NULL) {
1898                         llapi_error(LLAPI_MSG_ERROR, -ENOMEM,
1899                                     "error: allocation of %d bytes for ioctl",
1900                                     lmv_user_md_size(param->fp_lmv_stripe_count,
1901                                                      LMV_USER_MAGIC_SPECIFIC));
1902                         return -ENOMEM;
1903                 }
1904                 goto again;
1905         }
1906         return ret;
1907 }
1908
1909 int get_lmd_info_fd(char *path, int parent_fd, int dir_fd,
1910                     void *lmdbuf, int lmdlen, enum get_lmd_info_type type)
1911 {
1912         struct lov_user_mds_data *lmd = lmdbuf;
1913         lstat_t *st = &lmd->lmd_st;
1914         int ret = 0;
1915
1916         if (parent_fd < 0 && dir_fd < 0)
1917                 return -EINVAL;
1918         if (type != GET_LMD_INFO && type != GET_LMD_STRIPE)
1919                 return -EINVAL;
1920
1921         if (dir_fd >= 0) {
1922                 /* LL_IOC_MDC_GETINFO operates on the current directory inode
1923                  * and returns struct lov_user_mds_data, while
1924                  * LL_IOC_LOV_GETSTRIPE returns only struct lov_user_md.
1925                  */
1926                 ret = ioctl(dir_fd, type == GET_LMD_INFO ? LL_IOC_MDC_GETINFO :
1927                                                            LL_IOC_LOV_GETSTRIPE,
1928                             lmdbuf);
1929         } else if (parent_fd >= 0) {
1930                 char *fname = strrchr(path, '/');
1931
1932                 /* IOC_MDC_GETFILEINFO takes as input the filename (relative to
1933                  * the parent directory) and returns struct lov_user_mds_data,
1934                  * while IOC_MDC_GETFILESTRIPE returns only struct lov_user_md.
1935                  *
1936                  * This avoids opening, locking, and closing each file on the
1937                  * client if that is not needed. Multiple of these ioctl() can
1938                  * be done on the parent dir with a single open for all
1939                  * files in that directory, and it also doesn't pollute the
1940                  * client dcache with millions of dentries when traversing
1941                  * a large filesystem.
1942                  */
1943                 fname = (fname == NULL ? path : fname + 1);
1944
1945                 ret = snprintf(lmdbuf, lmdlen, "%s", fname);
1946                 if (ret < 0)
1947                         errno = -ret;
1948                 else if (ret >= lmdlen || ret++ == 0)
1949                         errno = EINVAL;
1950                 else
1951                         ret = ioctl(parent_fd, type == GET_LMD_INFO ?
1952                                                 IOC_MDC_GETFILEINFO :
1953                                                 IOC_MDC_GETFILESTRIPE, lmdbuf);
1954         }
1955
1956         if (ret && type == GET_LMD_INFO) {
1957                 if (errno == ENOTTY) {
1958                         /* ioctl is not supported, it is not a lustre fs.
1959                          * Do the regular lstat(2) instead.
1960                          */
1961                         ret = lstat_f(path, st);
1962                         if (ret) {
1963                                 ret = -errno;
1964                                 llapi_error(LLAPI_MSG_ERROR, ret,
1965                                             "error: %s: lstat failed for %s",
1966                                             __func__, path);
1967                         }
1968                 } else if (errno == ENOENT) {
1969                         ret = -errno;
1970                         llapi_error(LLAPI_MSG_WARN, ret,
1971                                     "warning: %s does not exist", path);
1972                 } else if (errno != EISDIR && errno != ENODATA) {
1973                         ret = -errno;
1974                         llapi_error(LLAPI_MSG_ERROR, ret,
1975                                     "%s ioctl failed for %s.",
1976                                     dir_fd >= 0 ? "LL_IOC_MDC_GETINFO" :
1977                                     "IOC_MDC_GETFILEINFO", path);
1978                 }
1979         }
1980
1981         return ret;
1982 }
1983
1984 static int get_lmd_info(char *path, DIR *parent, DIR *dir, void *lmdbuf,
1985                         int lmdlen, enum get_lmd_info_type type)
1986 {
1987         int parent_fd = -1;
1988         int dir_fd = -1;
1989
1990         if (parent)
1991                 parent_fd = dirfd(parent);
1992         if (dir)
1993                 dir_fd = dirfd(dir);
1994
1995         return get_lmd_info_fd(path, parent_fd, dir_fd, lmdbuf, lmdlen, type);
1996 }
1997
1998 static int llapi_semantic_traverse(char *path, int size, DIR *parent,
1999                                    semantic_func_t sem_init,
2000                                    semantic_func_t sem_fini, void *data,
2001                                    struct dirent64 *de)
2002 {
2003         struct find_param *param = (struct find_param *)data;
2004         struct dirent64 *dent;
2005         int len, ret;
2006         DIR *d, *p = NULL;
2007
2008         ret = 0;
2009         len = strlen(path);
2010
2011         d = opendir(path);
2012         if (!d && errno != ENOTDIR) {
2013                 ret = -errno;
2014                 llapi_error(LLAPI_MSG_ERROR, ret, "%s: Failed to open '%s'",
2015                             __func__, path);
2016                 return ret;
2017         } else if (!d && !parent) {
2018                 /* ENOTDIR. Open the parent dir. */
2019                 p = opendir_parent(path);
2020                 if (!p) {
2021                         ret = -errno;
2022                         goto out;
2023                 }
2024         }
2025
2026         if (sem_init && (ret = sem_init(path, parent ?: p, &d, data, de)))
2027                 goto err;
2028
2029         if (d == NULL)
2030                 goto out;
2031
2032         while ((dent = readdir64(d)) != NULL) {
2033                 int rc;
2034
2035                 if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
2036                         continue;
2037
2038                 path[len] = 0;
2039                 if ((len + dent->d_reclen + 2) > size) {
2040                         llapi_err_noerrno(LLAPI_MSG_ERROR,
2041                                           "error: %s: string buffer too small",
2042                                           __func__);
2043                         break;
2044                 }
2045                 strcat(path, "/");
2046                 strcat(path, dent->d_name);
2047
2048                 if (dent->d_type == DT_UNKNOWN) {
2049                         lstat_t *st = &param->fp_lmd->lmd_st;
2050
2051                         rc = get_lmd_info(path, d, NULL, param->fp_lmd,
2052                                           param->fp_lum_size, GET_LMD_INFO);
2053                         if (rc == 0)
2054                                 dent->d_type = IFTODT(st->st_mode);
2055                         else if (ret == 0)
2056                                 ret = rc;
2057
2058                         if (rc == -ENOENT)
2059                                 continue;
2060                 }
2061                 switch (dent->d_type) {
2062                 case DT_UNKNOWN:
2063                         llapi_err_noerrno(LLAPI_MSG_ERROR,
2064                                           "error: %s: '%s' is UNKNOWN type %d",
2065                                           __func__, dent->d_name, dent->d_type);
2066                         break;
2067                 case DT_DIR:
2068                         rc = llapi_semantic_traverse(path, size, d, sem_init,
2069                                                       sem_fini, data, dent);
2070                         if (rc != 0 && ret == 0)
2071                                 ret = rc;
2072                         break;
2073                 default:
2074                         rc = 0;
2075                         if (sem_init) {
2076                                 rc = sem_init(path, d, NULL, data, dent);
2077                                 if (rc < 0 && ret == 0) {
2078                                         ret = rc;
2079                                         break;
2080                                 }
2081                         }
2082                         if (sem_fini && rc == 0)
2083                                 sem_fini(path, d, NULL, data, dent);
2084                 }
2085         }
2086
2087 out:
2088         path[len] = 0;
2089
2090         if (sem_fini)
2091                 sem_fini(path, parent, &d, data, de);
2092 err:
2093         if (d)
2094                 closedir(d);
2095         if (p)
2096                 closedir(p);
2097         return ret;
2098 }
2099
2100 static int param_callback(char *path, semantic_func_t sem_init,
2101                           semantic_func_t sem_fini, struct find_param *param)
2102 {
2103         int ret, len = strlen(path);
2104         char *buf;
2105
2106         if (len > PATH_MAX) {
2107                 ret = -EINVAL;
2108                 llapi_error(LLAPI_MSG_ERROR, ret,
2109                             "Path name '%s' is too long", path);
2110                 return ret;
2111         }
2112
2113         buf = (char *)malloc(PATH_MAX + 1);
2114         if (!buf)
2115                 return -ENOMEM;
2116
2117         snprintf(buf, PATH_MAX + 1, "%s", path);
2118         ret = common_param_init(param, buf);
2119         if (ret)
2120                 goto out;
2121
2122         param->fp_depth = 0;
2123
2124         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, sem_init,
2125                                       sem_fini, param, NULL);
2126 out:
2127         find_param_fini(param);
2128         free(buf);
2129         return ret < 0 ? ret : 0;
2130 }
2131
2132 int llapi_file_fget_lov_uuid(int fd, struct obd_uuid *lov_name)
2133 {
2134         int rc = ioctl(fd, OBD_IOC_GETNAME, lov_name);
2135
2136         if (rc) {
2137                 rc = -errno;
2138                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot get lov name");
2139         }
2140         return rc;
2141 }
2142
2143 int llapi_file_fget_lmv_uuid(int fd, struct obd_uuid *lov_name)
2144 {
2145         int rc = ioctl(fd, OBD_IOC_GETMDNAME, lov_name);
2146         if (rc) {
2147                 rc = -errno;
2148                 llapi_error(LLAPI_MSG_ERROR, rc, "error: can't get lmv name.");
2149         }
2150         return rc;
2151 }
2152
2153 int llapi_file_get_lov_uuid(const char *path, struct obd_uuid *lov_uuid)
2154 {
2155         int fd, rc;
2156
2157         fd = open(path, O_RDONLY | O_NONBLOCK);
2158         if (fd < 0) {
2159                 rc = -errno;
2160                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot open '%s'", path);
2161                 return rc;
2162         }
2163
2164         rc = llapi_file_fget_lov_uuid(fd, lov_uuid);
2165
2166         close(fd);
2167         return rc;
2168 }
2169
2170 int llapi_file_get_lmv_uuid(const char *path, struct obd_uuid *lov_uuid)
2171 {
2172         int fd, rc;
2173
2174         fd = open(path, O_RDONLY | O_NONBLOCK);
2175         if (fd < 0) {
2176                 rc = -errno;
2177                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s", path);
2178                 return rc;
2179         }
2180
2181         rc = llapi_file_fget_lmv_uuid(fd, lov_uuid);
2182
2183         close(fd);
2184         return rc;
2185 }
2186
2187 enum tgt_type {
2188         LOV_TYPE = 1,
2189         LMV_TYPE
2190 };
2191
2192 /*
2193  * If uuidp is NULL, return the number of available obd uuids.
2194  * If uuidp is non-NULL, then it will return the uuids of the obds. If
2195  * there are more OSTs than allocated to uuidp, then an error is returned with
2196  * the ost_count set to number of available obd uuids.
2197  */
2198 static int llapi_get_target_uuids(int fd, struct obd_uuid *uuidp,
2199                                   int *ost_count, enum tgt_type type)
2200 {
2201         char buf[PATH_MAX], format[32];
2202         int rc = 0, index = 0;
2203         struct obd_uuid name;
2204         glob_t param;
2205         FILE *fp;
2206
2207         /* Get the lov name */
2208         if (type == LOV_TYPE)
2209                 rc = llapi_file_fget_lov_uuid(fd, &name);
2210         else
2211                 rc = llapi_file_fget_lmv_uuid(fd, &name);
2212         if (rc != 0)
2213                 return rc;
2214
2215         /* Now get the ost uuids */
2216         rc = get_lustre_param_path(type == LOV_TYPE ? "lov" : "lmv", name.uuid,
2217                                    FILTER_BY_EXACT, "target_obd", &param);
2218         if (rc != 0)
2219                 return -ENOENT;
2220
2221         fp = fopen(param.gl_pathv[0], "r");
2222         if (fp == NULL) {
2223                 rc = -errno;
2224                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening '%s'",
2225                             param.gl_pathv[0]);
2226                 goto free_param;
2227         }
2228
2229         snprintf(format, sizeof(format),
2230                  "%%d: %%%zus", sizeof(uuidp[0].uuid) - 1);
2231         while (fgets(buf, sizeof(buf), fp) != NULL) {
2232                 if (uuidp && (index < *ost_count)) {
2233                         if (sscanf(buf, format, &index, uuidp[index].uuid) < 2)
2234                                 break;
2235                 }
2236                 index++;
2237         }
2238
2239         fclose(fp);
2240
2241         if (uuidp && (index > *ost_count))
2242                 rc = -EOVERFLOW;
2243
2244         *ost_count = index;
2245 free_param:
2246         cfs_free_param_data(&param);
2247         return rc;
2248 }
2249
2250 int llapi_lov_get_uuids(int fd, struct obd_uuid *uuidp, int *ost_count)
2251 {
2252         return llapi_get_target_uuids(fd, uuidp, ost_count, LOV_TYPE);
2253 }
2254
2255 int llapi_get_obd_count(char *mnt, int *count, int is_mdt)
2256 {
2257         int root;
2258         int rc;
2259
2260         root = open(mnt, O_RDONLY | O_DIRECTORY);
2261         if (root < 0) {
2262                 rc = -errno;
2263                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
2264                 return rc;
2265         }
2266
2267         *count = is_mdt;
2268         rc = ioctl(root, LL_IOC_GETOBDCOUNT, count);
2269         if (rc < 0)
2270                 rc = -errno;
2271
2272         close(root);
2273         return rc;
2274 }
2275
2276 /* Check if user specified value matches a real uuid.  Ignore _UUID,
2277  * -osc-4ba41334, other trailing gunk in comparison.
2278  * @param real_uuid ends in "_UUID"
2279  * @param search_uuid may or may not end in "_UUID"
2280  */
2281 int llapi_uuid_match(char *real_uuid, char *search_uuid)
2282 {
2283         int cmplen = strlen(real_uuid);
2284         int searchlen = strlen(search_uuid);
2285
2286         if (cmplen > 5 && strcmp(real_uuid + cmplen - 5, "_UUID") == 0)
2287                 cmplen -= 5;
2288         if (searchlen > 5 && strcmp(search_uuid + searchlen - 5, "_UUID") == 0)
2289                 searchlen -= 5;
2290
2291         /* The UUIDs may legitimately be different lengths, if
2292          * the system was upgraded from an older version. */
2293         if (cmplen != searchlen)
2294                 return 0;
2295
2296         return (strncmp(search_uuid, real_uuid, cmplen) == 0);
2297 }
2298
2299 /* Here, param->fp_obd_uuid points to a single obduuid, the index of which is
2300  * returned in param->fp_obd_index */
2301 static int setup_obd_uuid(int fd, char *dname, struct find_param *param)
2302 {
2303         struct obd_uuid obd_uuid;
2304         char buf[PATH_MAX];
2305         glob_t param_data;
2306         char format[32];
2307         int rc = 0;
2308         FILE *fp;
2309
2310         if (param->fp_got_uuids)
2311                 return rc;
2312
2313         /* Get the lov/lmv name */
2314         if (param->fp_get_lmv)
2315                 rc = llapi_file_fget_lmv_uuid(fd, &obd_uuid);
2316         else
2317                 rc = llapi_file_fget_lov_uuid(fd, &obd_uuid);
2318         if (rc) {
2319                 if (rc != -ENOTTY) {
2320                         llapi_error(LLAPI_MSG_ERROR, rc,
2321                                     "error: can't get %s name: %s",
2322                                     param->fp_get_lmv ? "lmv" : "lov",
2323                                     dname);
2324                 } else {
2325                         rc = 0;
2326                 }
2327                 return rc;
2328         }
2329
2330         param->fp_got_uuids = 1;
2331
2332         /* Now get the ost uuids */
2333         rc = get_lustre_param_path(param->fp_get_lmv ? "lmv" : "lov",
2334                                    obd_uuid.uuid, FILTER_BY_EXACT,
2335                                    "target_obd", &param_data);
2336         if (rc != 0)
2337                 return -ENOENT;
2338
2339         fp = fopen(param_data.gl_pathv[0], "r");
2340         if (fp == NULL) {
2341                 rc = -errno;
2342                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening '%s'",
2343                             param_data.gl_pathv[0]);
2344                 goto free_param;
2345         }
2346
2347         if (!param->fp_obd_uuid && !param->fp_quiet && !param->fp_obds_printed)
2348                 llapi_printf(LLAPI_MSG_NORMAL, "%s:\n",
2349                              param->fp_get_lmv ? "MDTS" : "OBDS");
2350
2351         snprintf(format, sizeof(format),
2352                  "%%d: %%%zus", sizeof(obd_uuid.uuid) - 1);
2353         while (fgets(buf, sizeof(buf), fp) != NULL) {
2354                 int index;
2355
2356                 if (sscanf(buf, format, &index, obd_uuid.uuid) < 2)
2357                         break;
2358
2359                 if (param->fp_obd_uuid) {
2360                         if (llapi_uuid_match(obd_uuid.uuid,
2361                                              param->fp_obd_uuid->uuid)) {
2362                                 param->fp_obd_index = index;
2363                                 break;
2364                         }
2365                 } else if (!param->fp_quiet && !param->fp_obds_printed) {
2366                         /* Print everything */
2367                         llapi_printf(LLAPI_MSG_NORMAL, "%s", buf);
2368                 }
2369         }
2370         param->fp_obds_printed = 1;
2371
2372         fclose(fp);
2373
2374         if (param->fp_obd_uuid && (param->fp_obd_index == OBD_NOT_FOUND)) {
2375                 llapi_err_noerrno(LLAPI_MSG_ERROR,
2376                                   "error: %s: unknown obduuid: %s",
2377                                   __func__, param->fp_obd_uuid->uuid);
2378                 rc = -EINVAL;
2379         }
2380 free_param:
2381         cfs_free_param_data(&param_data);
2382         return rc;
2383 }
2384
2385 /* In this case, param->fp_obd_uuid will be an array of obduuids and
2386  * obd index for all these obduuids will be returned in
2387  * param->fp_obd_indexes */
2388 static int setup_indexes(DIR *dir, char *path, struct obd_uuid *obduuids,
2389                          int num_obds, int **obdindexes, int *obdindex,
2390                          enum tgt_type type)
2391 {
2392         int ret, obdcount, obd_valid = 0, obdnum;
2393         long i;
2394         struct obd_uuid *uuids = NULL;
2395         char buf[16];
2396         int *indexes;
2397
2398         if (type == LOV_TYPE)
2399                 ret = get_param_lov(path, "numobd", buf, sizeof(buf));
2400         else
2401                 ret = get_param_lmv(path, "numobd", buf, sizeof(buf));
2402         if (ret != 0)
2403                 return ret;
2404
2405         obdcount = atoi(buf);
2406         uuids = malloc(obdcount * sizeof(struct obd_uuid));
2407         if (uuids == NULL)
2408                 return -ENOMEM;
2409
2410 retry_get_uuids:
2411         ret = llapi_get_target_uuids(dirfd(dir), uuids, &obdcount, type);
2412         if (ret) {
2413                 if (ret == -EOVERFLOW) {
2414                         struct obd_uuid *uuids_temp;
2415
2416                         uuids_temp = realloc(uuids, obdcount *
2417                                              sizeof(struct obd_uuid));
2418                         if (uuids_temp != NULL) {
2419                                 uuids = uuids_temp;
2420                                 goto retry_get_uuids;
2421                         }
2422                         ret = -ENOMEM;
2423                 }
2424
2425                 llapi_error(LLAPI_MSG_ERROR, ret, "cannot get ost uuid");
2426                 goto out_free;
2427         }
2428
2429         indexes = malloc(num_obds * sizeof(*obdindex));
2430         if (indexes == NULL) {
2431                 ret = -ENOMEM;
2432                 goto out_free;
2433         }
2434
2435         for (obdnum = 0; obdnum < num_obds; obdnum++) {
2436                 char *end = NULL;
2437
2438                 /* The user may have specified a simple index */
2439                 i = strtol(obduuids[obdnum].uuid, &end, 0);
2440                 if (end && *end == '\0' && i < obdcount) {
2441                         indexes[obdnum] = i;
2442                         obd_valid++;
2443                 } else {
2444                         for (i = 0; i < obdcount; i++) {
2445                                 if (llapi_uuid_match(uuids[i].uuid,
2446                                                      obduuids[obdnum].uuid)) {
2447                                         indexes[obdnum] = i;
2448                                         obd_valid++;
2449                                         break;
2450                                 }
2451                         }
2452                 }
2453                 if (i >= obdcount) {
2454                         indexes[obdnum] = OBD_NOT_FOUND;
2455                         llapi_err_noerrno(LLAPI_MSG_ERROR,
2456                                           "invalid obduuid '%s'",
2457                                           obduuids[obdnum].uuid);
2458                         ret = -EINVAL;
2459                 }
2460         }
2461
2462         if (obd_valid == 0)
2463                 *obdindex = OBD_NOT_FOUND;
2464         else
2465                 *obdindex = obd_valid;
2466
2467         *obdindexes = indexes;
2468 out_free:
2469         if (uuids)
2470                 free(uuids);
2471
2472         return ret;
2473 }
2474
2475 static int setup_target_indexes(DIR *dir, char *path, struct find_param *param)
2476 {
2477         int ret = 0;
2478
2479         if (param->fp_mdt_uuid) {
2480                 ret = setup_indexes(dir, path, param->fp_mdt_uuid,
2481                                     param->fp_num_mdts,
2482                                     &param->fp_mdt_indexes,
2483                                     &param->fp_mdt_index, LMV_TYPE);
2484                 if (ret)
2485                         return ret;
2486         }
2487
2488         if (param->fp_obd_uuid) {
2489                 ret = setup_indexes(dir, path, param->fp_obd_uuid,
2490                                     param->fp_num_obds,
2491                                     &param->fp_obd_indexes,
2492                                     &param->fp_obd_index, LOV_TYPE);
2493                 if (ret)
2494                         return ret;
2495         }
2496
2497         param->fp_got_uuids = 1;
2498
2499         return ret;
2500 }
2501
2502 int llapi_ostlist(char *path, struct find_param *param)
2503 {
2504         int fd;
2505         int ret;
2506
2507         fd = open(path, O_RDONLY | O_DIRECTORY);
2508         if (fd < 0)
2509                 return -errno;
2510
2511         ret = setup_obd_uuid(fd, path, param);
2512         close(fd);
2513
2514         return ret;
2515 }
2516
2517 /*
2518  * Tries to determine the default stripe attributes for a given filesystem. The
2519  * filesystem to check should be specified by fsname, or will be determined
2520  * using pathname.
2521  */
2522 static int sattr_get_defaults(const char *const fsname,
2523                               unsigned int *scount,
2524                               unsigned int *ssize,
2525                               unsigned int *soffset)
2526 {
2527         char val[PATH_MAX];
2528         int rc;
2529
2530         if (scount) {
2531                 rc = get_lustre_param_value("lov", fsname, FILTER_BY_FS_NAME,
2532                                             "stripecount", val, sizeof(val));
2533                 if (rc != 0)
2534                         return rc;
2535                 *scount = atoi(val);
2536         }
2537
2538         if (ssize) {
2539                 rc = get_lustre_param_value("lov", fsname, FILTER_BY_FS_NAME,
2540                                             "stripesize", val, sizeof(val));
2541                 if (rc != 0)
2542                         return rc;
2543                 *ssize = atoi(val);
2544         }
2545
2546         if (soffset) {
2547                 rc = get_lustre_param_value("lov", fsname, FILTER_BY_FS_NAME,
2548                                             "stripeoffset", val, sizeof(val));
2549                 if (rc != 0)
2550                         return rc;
2551                 *soffset = atoi(val);
2552         }
2553
2554         return 0;
2555 }
2556
2557 /*
2558  * Tries to gather the default stripe attributes for a given filesystem. If
2559  * the attributes can be determined, they are cached for easy retreival the
2560  * next time they are needed. Only a single filesystem's attributes are
2561  * cached at a time.
2562  */
2563 int sattr_cache_get_defaults(const char *const fsname,
2564                              const char *const pathname, unsigned int *scount,
2565                              unsigned int *ssize, unsigned int *soffset)
2566 {
2567         static struct {
2568                 char fsname[PATH_MAX + 1];
2569                 unsigned int stripecount;
2570                 unsigned int stripesize;
2571                 unsigned int stripeoffset;
2572         } cache = {
2573                 .fsname = {'\0'}
2574         };
2575
2576         int rc;
2577         char fsname_buf[PATH_MAX + 1];
2578         unsigned int tmp[3];
2579
2580         if (fsname == NULL) {
2581                 rc = llapi_search_fsname(pathname, fsname_buf);
2582                 if (rc)
2583                         return rc;
2584         } else {
2585                 snprintf(fsname_buf, sizeof(fsname_buf), "%s", fsname);
2586         }
2587
2588         if (strncmp(fsname_buf, cache.fsname, sizeof(fsname_buf) - 1) != 0) {
2589                 /*
2590                  * Ensure all 3 sattrs (count, size, and offset) are
2591                  * successfully retrieved and stored in tmp before writing to
2592                  * cache.
2593                  */
2594                 rc = sattr_get_defaults(fsname_buf, &tmp[0], &tmp[1], &tmp[2]);
2595                 if (rc != 0)
2596                         return rc;
2597
2598                 cache.stripecount = tmp[0];
2599                 cache.stripesize = tmp[1];
2600                 cache.stripeoffset = tmp[2];
2601                 snprintf(cache.fsname, sizeof(cache.fsname), "%s", fsname_buf);
2602         }
2603
2604         if (scount)
2605                 *scount = cache.stripecount;
2606         if (ssize)
2607                 *ssize = cache.stripesize;
2608         if (soffset)
2609                 *soffset = cache.stripeoffset;
2610
2611         return 0;
2612 }
2613
2614 static char *layout2name(__u32 layout_pattern)
2615 {
2616         if (layout_pattern & LOV_PATTERN_F_RELEASED)
2617                 return "released";
2618         else if (layout_pattern == LOV_PATTERN_MDT)
2619                 return "mdt";
2620         else if (layout_pattern == LOV_PATTERN_RAID0)
2621                 return "raid0";
2622         else if (layout_pattern ==
2623                         (LOV_PATTERN_RAID0 | LOV_PATTERN_OVERSTRIPING))
2624                 return "raid0,overstriped";
2625         else
2626                 return "unknown";
2627 }
2628
2629 enum lov_dump_flags {
2630         LDF_IS_DIR      = 0x0001,
2631         LDF_IS_RAW      = 0x0002,
2632         LDF_INDENT      = 0x0004,
2633         LDF_SKIP_OBJS   = 0x0008,
2634         LDF_YAML        = 0x0010,
2635         LDF_EXTENSION   = 0x0020,
2636 };
2637
2638 static void lov_dump_user_lmm_header(struct lov_user_md *lum, char *path,
2639                                      struct lov_user_ost_data_v1 *objects,
2640                                      enum llapi_layout_verbose verbose,
2641                                      int depth, char *pool_name,
2642                                      enum lov_dump_flags flags)
2643 {
2644         bool is_dir = flags & LDF_IS_DIR;
2645         bool is_raw = flags & LDF_IS_RAW;
2646         bool indent = flags & LDF_INDENT;
2647         bool yaml = flags & LDF_YAML;
2648         bool skip_objs = flags & LDF_SKIP_OBJS;
2649         bool extension = flags & LDF_EXTENSION;
2650         char *prefix = is_dir ? "" : "lmm_";
2651         char *separator = "";
2652         char *space = indent ? "      " : "";
2653         int rc;
2654
2655         if (is_dir && lmm_oi_seq(&lum->lmm_oi) == FID_SEQ_LOV_DEFAULT) {
2656                 lmm_oi_set_seq(&lum->lmm_oi, 0);
2657                 if (!indent && (verbose & VERBOSE_DETAIL))
2658                         llapi_printf(LLAPI_MSG_NORMAL, "%s(Default) ", space);
2659         }
2660
2661         if (!yaml && !indent && depth && path &&
2662             ((verbose != VERBOSE_OBJID) || !is_dir))
2663                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
2664
2665         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
2666                 llapi_printf(LLAPI_MSG_NORMAL, "%s%smagic:         0x%08X\n",
2667                              space, prefix, lum->lmm_magic);
2668                 llapi_printf(LLAPI_MSG_NORMAL, "%s%sseq:           %#jx\n",
2669                              space, prefix,
2670                              (uintmax_t)lmm_oi_seq(&lum->lmm_oi));
2671                 llapi_printf(LLAPI_MSG_NORMAL, "%s%sobject_id:     %#jx\n",
2672                              space, prefix,
2673                              (uintmax_t)lmm_oi_id(&lum->lmm_oi));
2674         }
2675         if ((verbose & (VERBOSE_DETAIL | VERBOSE_DFID)) && !is_dir) {
2676                 __u64 seq;
2677                 __u32 oid;
2678                 __u32 ver;
2679
2680                 if (verbose & ~VERBOSE_DFID)
2681                         llapi_printf(LLAPI_MSG_NORMAL, "%slmm_fid:           ",
2682                                      space);
2683                 /* This needs a bit of hand-holding since old 1.x lmm_oi
2684                  * have { oi.oi_id = mds_inum, oi.oi_seq = 0 } and 2.x lmm_oi
2685                  * have { oi.oi_id = mds_oid, oi.oi_seq = mds_seq } instead of
2686                  * a real FID.  Ideally the 2.x code would have stored this
2687                  * like a FID with { oi_id = mds_seq, oi_seq = mds_oid } so the
2688                  * ostid union lu_fid { f_seq = mds_seq, f_oid = mds_oid }
2689                  * worked properly (especially since IGIF FIDs use mds_inum as
2690                  * the FID SEQ), but unfortunately that didn't happen.
2691                  *
2692                  * Print it to look like an IGIF FID, even though the fields
2693                  * are reversed on disk, so that it makes sense to userspace.
2694                  *
2695                  * Don't use ostid_id() and ostid_seq(), since they assume the
2696                  * oi_fid fields are in the right order.  This is why there are
2697                  * separate lmm_oi_seq() and lmm_oi_id() routines for this.
2698                  *
2699                  * For newer layout types hopefully this will be a real FID. */
2700                 seq = lmm_oi_seq(&lum->lmm_oi) == 0 ?
2701                         lmm_oi_id(&lum->lmm_oi) : lmm_oi_seq(&lum->lmm_oi);
2702                 oid = lmm_oi_seq(&lum->lmm_oi) == 0 ?
2703                         0 : (__u32)lmm_oi_id(&lum->lmm_oi);
2704                 ver = (__u32)(lmm_oi_id(&lum->lmm_oi) >> 32);
2705                 if (yaml)
2706                         llapi_printf(LLAPI_MSG_NORMAL, DFID_NOBRACE"\n",
2707                                      (unsigned long long)seq, oid, ver);
2708                 else
2709                         llapi_printf(LLAPI_MSG_NORMAL, DFID"\n",
2710                                      (unsigned long long)seq, oid, ver);
2711         }
2712
2713         if (verbose & VERBOSE_STRIPE_COUNT) {
2714                 if (verbose & ~VERBOSE_STRIPE_COUNT)
2715                         llapi_printf(LLAPI_MSG_NORMAL, "%s%sstripe_count:  ",
2716                                      space, prefix);
2717                 if (is_dir) {
2718                         if (!is_raw && lum->lmm_stripe_count == 0 &&
2719                             lov_pattern(lum->lmm_pattern) != LOV_PATTERN_MDT) {
2720                                 unsigned int scount;
2721                                 rc = sattr_cache_get_defaults(NULL, path,
2722                                                               &scount, NULL,
2723                                                               NULL);
2724                                 if (rc == 0)
2725                                         llapi_printf(LLAPI_MSG_NORMAL, "%d",
2726                                                      scount);
2727                                 else
2728                                         llapi_error(LLAPI_MSG_ERROR, rc,
2729                                                     "Cannot determine default"
2730                                                     " stripe count.");
2731                         } else {
2732                                 llapi_printf(LLAPI_MSG_NORMAL, "%d",
2733                                              extension ? 0 :
2734                                              (__s16)lum->lmm_stripe_count);
2735                         }
2736                 } else {
2737                         llapi_printf(LLAPI_MSG_NORMAL, "%hd",
2738                                      extension ? 0 :
2739                                      (__s16)lum->lmm_stripe_count);
2740                 }
2741                 if (!yaml && is_dir)
2742                         separator = " ";
2743                 else
2744                         separator = "\n";
2745         }
2746
2747         if (((verbose & VERBOSE_STRIPE_SIZE) && !extension) ||
2748             ((verbose & VERBOSE_EXT_SIZE) && extension)) {
2749                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2750                 if (verbose & ~VERBOSE_EXT_SIZE && extension)
2751                         llapi_printf(LLAPI_MSG_NORMAL, "%s%sextension_size: ",
2752                                      space, prefix);
2753                 if (verbose & ~VERBOSE_STRIPE_SIZE && !extension)
2754                         llapi_printf(LLAPI_MSG_NORMAL, "%s%sstripe_size:   ",
2755                                      space, prefix);
2756                 if (is_dir && !is_raw && lum->lmm_stripe_size == 0) {
2757                         unsigned int ssize;
2758                         rc = sattr_cache_get_defaults(NULL, path, NULL, &ssize,
2759                                                       NULL);
2760                         if (rc == 0)
2761                                 llapi_printf(LLAPI_MSG_NORMAL, "%u", ssize);
2762                         else
2763                                 llapi_error(LLAPI_MSG_ERROR, rc,
2764                                             "Cannot determine default"
2765                                             " stripe size.");
2766                 } else {
2767                         /* Extension size is in KiB */
2768                         llapi_printf(LLAPI_MSG_NORMAL, "%llu",
2769                                      extension ?
2770                                      (unsigned long long)(lum->lmm_stripe_size * SEL_UNIT_SIZE) :
2771                                      (unsigned long long)lum->lmm_stripe_size);
2772                 }
2773                 if (!yaml && is_dir)
2774                         separator = " ";
2775                 else
2776                         separator = "\n";
2777         }
2778
2779         if ((verbose & VERBOSE_PATTERN)) {
2780                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2781                 if (verbose & ~VERBOSE_PATTERN)
2782                         llapi_printf(LLAPI_MSG_NORMAL, "%s%spattern:       ",
2783                                      space, prefix);
2784                 if (lov_pattern_supported(lum->lmm_pattern))
2785                         llapi_printf(LLAPI_MSG_NORMAL, "%s",
2786                                      layout2name(lum->lmm_pattern));
2787                 else
2788                         llapi_printf(LLAPI_MSG_NORMAL, "%x", lum->lmm_pattern);
2789                 separator = (!yaml && is_dir) ? " " : "\n";
2790         }
2791
2792         if ((verbose & VERBOSE_GENERATION) && !is_dir) {
2793                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2794                 if (verbose & ~VERBOSE_GENERATION)
2795                         llapi_printf(LLAPI_MSG_NORMAL, "%s%slayout_gen:    ",
2796                                      space, prefix);
2797                 llapi_printf(LLAPI_MSG_NORMAL, "%u",
2798                              skip_objs ? 0 : (int)lum->lmm_layout_gen);
2799                 separator = "\n";
2800         }
2801
2802         if (verbose & VERBOSE_STRIPE_OFFSET) {
2803                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2804                 if (verbose & ~VERBOSE_STRIPE_OFFSET)
2805                         llapi_printf(LLAPI_MSG_NORMAL, "%s%sstripe_offset: ",
2806                                      space, prefix);
2807                 if (is_dir || skip_objs)
2808                         llapi_printf(LLAPI_MSG_NORMAL, "%d",
2809                                      lum->lmm_stripe_offset ==
2810                                      (typeof(lum->lmm_stripe_offset))(-1) ? -1 :
2811                                      lum->lmm_stripe_offset);
2812                 else if (lov_pattern(lum->lmm_pattern) == LOV_PATTERN_MDT)
2813                         llapi_printf(LLAPI_MSG_NORMAL, "0");
2814                 else
2815                         llapi_printf(LLAPI_MSG_NORMAL, "%u",
2816                                      objects[0].l_ost_idx);
2817                 if (!yaml && is_dir)
2818                         separator = " ";
2819                 else
2820                         separator = "\n";
2821         }
2822
2823         if ((verbose & VERBOSE_POOL) && pool_name && (pool_name[0] != '\0')) {
2824                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2825                 if (verbose & ~VERBOSE_POOL)
2826                         llapi_printf(LLAPI_MSG_NORMAL, "%s%spool:          ",
2827                                      space, prefix);
2828                 llapi_printf(LLAPI_MSG_NORMAL, "%s", pool_name);
2829                 if (!yaml && is_dir)
2830                         separator = " ";
2831                 else
2832                         separator = "\n";
2833         }
2834
2835         if (strlen(separator) != 0)
2836                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
2837 }
2838
2839 void lov_dump_user_lmm_v1v3(struct lov_user_md *lum, char *pool_name,
2840                             struct lov_user_ost_data_v1 *objects,
2841                             char *path, int obdindex, int depth,
2842                             enum llapi_layout_verbose verbose,
2843                             enum lov_dump_flags flags)
2844 {
2845         bool is_dir = flags & LDF_IS_DIR;
2846         bool indent = flags & LDF_INDENT;
2847         bool skip_objs = flags & LDF_SKIP_OBJS;
2848         bool yaml = flags & LDF_YAML;
2849         bool obdstripe = obdindex == OBD_NOT_FOUND;
2850         int i;
2851
2852         if (!obdstripe && !skip_objs) {
2853                 for (i = 0; !is_dir && i < lum->lmm_stripe_count; i++) {
2854                         if (obdindex == objects[i].l_ost_idx) {
2855                                 obdstripe = true;
2856                                 break;
2857                         }
2858                 }
2859         }
2860
2861         if (!obdstripe)
2862                 return;
2863
2864         lov_dump_user_lmm_header(lum, path, objects, verbose, depth, pool_name,
2865                                  flags);
2866
2867         if (!is_dir && !skip_objs && (verbose & VERBOSE_OBJID) &&
2868             !(lum->lmm_pattern & LOV_PATTERN_F_RELEASED ||
2869               lov_pattern(lum->lmm_pattern) == LOV_PATTERN_MDT)) {
2870                 char *space = "      - ";
2871
2872                 if (indent)
2873                         llapi_printf(LLAPI_MSG_NORMAL,
2874                                      "%6slmm_objects:\n", " ");
2875                 else if (yaml)
2876                         llapi_printf(LLAPI_MSG_NORMAL, "lmm_objects:\n");
2877                 else
2878                         llapi_printf(LLAPI_MSG_NORMAL,
2879                                 "\tobdidx\t\t objid\t\t objid\t\t group\n");
2880
2881                 for (i = 0; i < lum->lmm_stripe_count; i++) {
2882                         int idx = objects[i].l_ost_idx;
2883                         long long oid = ostid_id(&objects[i].l_ost_oi);
2884                         long long gr = ostid_seq(&objects[i].l_ost_oi);
2885
2886                         if (obdindex != OBD_NOT_FOUND && obdindex != idx)
2887                                 continue;
2888
2889                         if (yaml) {
2890                                 struct lu_fid fid = { 0 };
2891
2892                                 ostid_to_fid(&fid, &objects[i].l_ost_oi, idx);
2893                                 llapi_printf(LLAPI_MSG_NORMAL,
2894                                     "%sl_ost_idx: %d\n", space, idx);
2895                                 llapi_printf(LLAPI_MSG_NORMAL,
2896                                     "%8sl_fid:     "DFID_NOBRACE"\n",
2897                                     " ", PFID(&fid));
2898                         } else if (indent) {
2899                                 struct lu_fid fid = { 0 };
2900
2901                                 ostid_to_fid(&fid, &objects[i].l_ost_oi, idx);
2902                                 llapi_printf(LLAPI_MSG_NORMAL,
2903                                     "%s%d: { l_ost_idx: %d, l_fid: "DFID" }\n",
2904                                     space, i, idx, PFID(&fid));
2905                         } else {
2906                                 char fmt[48];
2907                                 sprintf(fmt, "%s%s%s\n",
2908                                         "\t%6u\t%14llu\t%#13llx\t",
2909                                         (fid_seq_is_rsvd(gr) ||
2910                                          fid_seq_is_mdt0(gr)) ?
2911                                          "%14llu" : "%#14llx", "%s");
2912                                 llapi_printf(LLAPI_MSG_NORMAL, fmt, idx, oid,
2913                                              oid, gr,
2914                                              obdindex == idx ? " *" : "");
2915                         }
2916                 }
2917         }
2918         llapi_printf(LLAPI_MSG_NORMAL, "\n");
2919 }
2920
2921 void lmv_dump_user_lmm(struct lmv_user_md *lum, char *pool_name,
2922                        char *path, int obdindex, int depth,
2923                        enum llapi_layout_verbose verbose,
2924                        enum lov_dump_flags flags)
2925 {
2926         struct lmv_user_mds_data *objects = lum->lum_objects;
2927         char *prefix = lum->lum_magic == LMV_USER_MAGIC ? "(Default)" : "";
2928         char *separator = "";
2929         bool yaml = flags & LDF_YAML;
2930         bool obdstripe = false;
2931         int i;
2932
2933         if (obdindex != OBD_NOT_FOUND) {
2934                 if (lum->lum_stripe_count == 0) {
2935                         if (obdindex == lum->lum_stripe_offset)
2936                                 obdstripe = true;
2937                 } else {
2938                         for (i = 0; i < lum->lum_stripe_count; i++) {
2939                                 if (obdindex == objects[i].lum_mds) {
2940                                         llapi_printf(LLAPI_MSG_NORMAL,
2941                                                      "%s%s\n", prefix,
2942                                                      path);
2943                                         obdstripe = true;
2944                                         break;
2945                                 }
2946                         }
2947                 }
2948         } else {
2949                 obdstripe = true;
2950         }
2951
2952         if (!obdstripe)
2953                 return;
2954
2955         /* show all information default */
2956         if (!verbose) {
2957                 if (lum->lum_magic == LMV_USER_MAGIC)
2958                         verbose = VERBOSE_POOL | VERBOSE_STRIPE_COUNT |
2959                                   VERBOSE_STRIPE_OFFSET | VERBOSE_HASH_TYPE;
2960                 else
2961                         verbose = VERBOSE_OBJID;
2962         }
2963
2964         if (depth && path && ((verbose != VERBOSE_OBJID)))
2965                 llapi_printf(LLAPI_MSG_NORMAL, "%s%s\n", prefix, path);
2966
2967         if (verbose & VERBOSE_STRIPE_COUNT) {
2968                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2969                 if (verbose & ~VERBOSE_STRIPE_COUNT)
2970                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_stripe_count: ");
2971                 llapi_printf(LLAPI_MSG_NORMAL, "%u",
2972                              (int)lum->lum_stripe_count);
2973                 if ((verbose & VERBOSE_STRIPE_OFFSET) && !yaml)
2974                         separator = " ";
2975                 else
2976                         separator = "\n";
2977         }
2978
2979         if (verbose & VERBOSE_STRIPE_OFFSET) {
2980                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2981                 if (verbose & ~VERBOSE_STRIPE_OFFSET)
2982                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_stripe_offset: ");
2983                 llapi_printf(LLAPI_MSG_NORMAL, "%d",
2984                              (int)lum->lum_stripe_offset);
2985                 if (verbose & VERBOSE_HASH_TYPE && !yaml)
2986                         separator = " ";
2987                 else
2988                         separator = "\n";
2989         }
2990
2991         if (verbose & VERBOSE_HASH_TYPE) {
2992                 unsigned int type = lum->lum_hash_type & LMV_HASH_TYPE_MASK;
2993                 unsigned int flags = lum->lum_hash_type & ~LMV_HASH_TYPE_MASK;
2994
2995                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2996                 if (verbose & ~VERBOSE_HASH_TYPE)
2997                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_hash_type: ");
2998                 if (type < LMV_HASH_TYPE_MAX)
2999                         llapi_printf(LLAPI_MSG_NORMAL, "%s",
3000                                      mdt_hash_name[type]);
3001                 else
3002                         llapi_printf(LLAPI_MSG_NORMAL, "%#x", type);
3003
3004                 if (flags & LMV_HASH_FLAG_SPACE)
3005                         llapi_printf(LLAPI_MSG_NORMAL, ",space");
3006                 if (flags & LMV_HASH_FLAG_MIGRATION)
3007                         llapi_printf(LLAPI_MSG_NORMAL, ",migrating");
3008                 if (flags & LMV_HASH_FLAG_BAD_TYPE)
3009                         llapi_printf(LLAPI_MSG_NORMAL, ",bad_type");
3010                 if (flags & LMV_HASH_FLAG_LOST_LMV)
3011                         llapi_printf(LLAPI_MSG_NORMAL, ",lost_lmv");
3012                 separator = "\n";
3013
3014         }
3015
3016         if (verbose & VERBOSE_OBJID && lum->lum_magic != LMV_USER_MAGIC) {
3017                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3018                 if (lum->lum_stripe_count > 0)
3019                         llapi_printf(LLAPI_MSG_NORMAL,
3020                                      "mdtidx\t\t FID[seq:oid:ver]\n");
3021                 for (i = 0; i < lum->lum_stripe_count; i++) {
3022                         int idx = objects[i].lum_mds;
3023                         struct lu_fid *fid = &objects[i].lum_fid;
3024                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
3025                                 llapi_printf(LLAPI_MSG_NORMAL,
3026                                              "%6u\t\t "DFID"\t\t%s\n",
3027                                             idx, PFID(fid),
3028                                             obdindex == idx ? " *" : "");
3029                 }
3030
3031         }
3032
3033         if ((verbose & VERBOSE_POOL) && pool_name != NULL &&
3034              pool_name[0] != '\0') {
3035                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3036                 if (verbose & ~VERBOSE_POOL)
3037                         llapi_printf(LLAPI_MSG_NORMAL, "%slmv_pool:           ",
3038                                      prefix);
3039                 llapi_printf(LLAPI_MSG_NORMAL, "%s%c ", pool_name, ' ');
3040                 separator = "\n";
3041         }
3042
3043         if (!(verbose & VERBOSE_OBJID) || lum->lum_magic == LMV_USER_MAGIC)
3044                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
3045 }
3046
3047 static void lov_dump_comp_v1_header(struct find_param *param, char *path,
3048                                     enum lov_dump_flags flags)
3049 {
3050         struct lov_comp_md_v1 *comp_v1 = (void *)&param->fp_lmd->lmd_lmm;
3051         int depth = param->fp_max_depth;
3052         enum llapi_layout_verbose verbose = param->fp_verbose;
3053         bool yaml = flags & LDF_YAML;
3054
3055         if (depth && path && ((verbose != VERBOSE_OBJID) ||
3056                               !(flags & LDF_IS_DIR)) && !yaml)
3057                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
3058
3059         if (verbose & VERBOSE_DETAIL) {
3060                 llapi_printf(LLAPI_MSG_NORMAL, "composite_header:\n");
3061                 llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_magic:         0x%08X\n",
3062                              " ", comp_v1->lcm_magic);
3063                 llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_size:          %u\n",
3064                              " ", comp_v1->lcm_size);
3065                 if (flags & LDF_IS_DIR)
3066                         llapi_printf(LLAPI_MSG_NORMAL,
3067                                      "%2slcm_flags:         %s\n", " ",
3068                                      comp_v1->lcm_mirror_count > 0 ?
3069                                                         "mirrored" : "");
3070                 else
3071                         llapi_printf(LLAPI_MSG_NORMAL,
3072                                      "%2slcm_flags:         %s\n", " ",
3073                                 llapi_layout_flags_string(comp_v1->lcm_flags));
3074         }
3075
3076         if (verbose & VERBOSE_GENERATION) {
3077                 if (verbose & ~VERBOSE_GENERATION)
3078                         llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_layout_gen:    ",
3079                                      " ");
3080                 llapi_printf(LLAPI_MSG_NORMAL, "%u\n", comp_v1->lcm_layout_gen);
3081         }
3082
3083         if (verbose & VERBOSE_MIRROR_COUNT) {
3084                 if (verbose & ~VERBOSE_MIRROR_COUNT)
3085                         llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_mirror_count:  ",
3086                                      " ");
3087                 llapi_printf(LLAPI_MSG_NORMAL, "%u\n",
3088                              comp_v1->lcm_magic == LOV_USER_MAGIC_COMP_V1 ?
3089                              comp_v1->lcm_mirror_count + 1 : 1);
3090         }
3091
3092         if (verbose & VERBOSE_COMP_COUNT) {
3093                 if (verbose & ~VERBOSE_COMP_COUNT)
3094                         llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_entry_count:   ",
3095                                      " ");
3096                 llapi_printf(LLAPI_MSG_NORMAL, "%u\n",
3097                              comp_v1->lcm_magic == LOV_USER_MAGIC_COMP_V1 ?
3098                              comp_v1->lcm_entry_count : 0);
3099         }
3100
3101         if (verbose & VERBOSE_DETAIL && !yaml)
3102                 llapi_printf(LLAPI_MSG_NORMAL, "components:\n");
3103 }
3104
3105 static void lcme_flags2str(__u32 comp_flags)
3106 {
3107         bool found = false;
3108         int i = 0;
3109
3110         if (!comp_flags) {
3111                 llapi_printf(LLAPI_MSG_NORMAL, "0");
3112                 return;
3113         }
3114         for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
3115                 if (comp_flags & comp_flags_table[i].cfn_flag) {
3116                         if (found)
3117                                 llapi_printf(LLAPI_MSG_NORMAL, ",");
3118                         llapi_printf(LLAPI_MSG_NORMAL, "%s",
3119                                      comp_flags_table[i].cfn_name);
3120                         comp_flags &= ~comp_flags_table[i].cfn_flag;
3121                         found = true;
3122                 }
3123         }
3124         if (comp_flags) {
3125                 if (found)
3126                         llapi_printf(LLAPI_MSG_NORMAL, ",");
3127                 llapi_printf(LLAPI_MSG_NORMAL, "%#x", comp_flags);
3128         }
3129 }
3130
3131 static void lov_dump_comp_v1_entry(struct find_param *param,
3132                                    enum lov_dump_flags flags, int index)
3133 {
3134         struct lov_comp_md_v1 *comp_v1 = (void *)&param->fp_lmd->lmd_lmm;
3135         struct lov_comp_md_entry_v1 *entry;
3136         char *separator = "";
3137         enum llapi_layout_verbose verbose = param->fp_verbose;
3138         bool yaml = flags & LDF_YAML;
3139
3140         entry = &comp_v1->lcm_entries[index];
3141
3142         if (yaml)
3143                 llapi_printf(LLAPI_MSG_NORMAL, "%2scomponent%d:\n", " ", index);
3144
3145         if (verbose & VERBOSE_COMP_ID) {
3146                 if (verbose & VERBOSE_DETAIL && !yaml)
3147                         llapi_printf(LLAPI_MSG_NORMAL,
3148                                      "%slcme_id:             ", "  - ");
3149                 else if (verbose & ~VERBOSE_COMP_ID)
3150                         llapi_printf(LLAPI_MSG_NORMAL,
3151                                      "%4slcme_id:             ", " ");
3152                 if (entry->lcme_id != LCME_ID_INVAL)
3153                         llapi_printf(LLAPI_MSG_NORMAL, "%u", entry->lcme_id);
3154                 else
3155                         llapi_printf(LLAPI_MSG_NORMAL, "N/A");
3156                 separator = "\n";
3157         }
3158
3159         if (verbose & VERBOSE_MIRROR_ID) {
3160                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3161                 if (verbose & ~VERBOSE_MIRROR_ID)
3162                         llapi_printf(LLAPI_MSG_NORMAL,
3163                                      "%4slcme_mirror_id:      ", " ");
3164                 if (entry->lcme_id != LCME_ID_INVAL)
3165                         llapi_printf(LLAPI_MSG_NORMAL, "%u",
3166                                      mirror_id_of(entry->lcme_id));
3167                 else
3168                         llapi_printf(LLAPI_MSG_NORMAL, "N/A");
3169                 separator = "\n";
3170         }
3171
3172         if (verbose & VERBOSE_COMP_FLAGS) {
3173                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3174                 if (verbose & ~VERBOSE_COMP_FLAGS)
3175                         llapi_printf(LLAPI_MSG_NORMAL,
3176                                      "%4slcme_flags:          ", " ");
3177                 lcme_flags2str(entry->lcme_flags);
3178                 separator = "\n";
3179         }
3180         /* print snapshot timestamp if its a nosync comp */
3181         if ((verbose & VERBOSE_COMP_FLAGS) &&
3182             (entry->lcme_flags & LCME_FL_NOSYNC)) {
3183                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3184                 if (verbose & ~VERBOSE_COMP_FLAGS)
3185                         llapi_printf(LLAPI_MSG_NORMAL,
3186                                      "%4slcme_timestamp:      ", " ");
3187                 if (yaml) {
3188                         llapi_printf(LLAPI_MSG_NORMAL, "%llu",
3189                                      (unsigned long long)entry->lcme_timestamp);
3190                 } else {
3191                         time_t stamp = entry->lcme_timestamp;
3192                         char *date_str = asctime(localtime(&stamp));
3193
3194                         date_str[strlen(date_str) - 1] = '\0';
3195                         llapi_printf(LLAPI_MSG_NORMAL, "'%s'", date_str);
3196                 }
3197
3198                 separator = "\n";
3199         }
3200
3201         if (verbose & VERBOSE_COMP_START) {
3202                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3203                 if (verbose & ~VERBOSE_COMP_START)
3204                         llapi_printf(LLAPI_MSG_NORMAL,
3205                                      "%4slcme_extent.e_start: ", " ");
3206                 llapi_printf(LLAPI_MSG_NORMAL, "%llu",
3207                              (unsigned long long)entry->lcme_extent.e_start);
3208                 separator = "\n";
3209         }
3210
3211         if (verbose & VERBOSE_COMP_END) {
3212                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3213                 if (verbose & ~VERBOSE_COMP_END)
3214                         llapi_printf(LLAPI_MSG_NORMAL,
3215                                      "%4slcme_extent.e_end:   ", " ");
3216                 if (entry->lcme_extent.e_end == LUSTRE_EOF)
3217                         llapi_printf(LLAPI_MSG_NORMAL, "%s", "EOF");
3218                 else
3219                         llapi_printf(LLAPI_MSG_NORMAL, "%llu",
3220                                      (unsigned long long)entry->lcme_extent.e_end);
3221                 separator = "\n";
3222         }
3223
3224         if (yaml) {
3225                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3226                 llapi_printf(LLAPI_MSG_NORMAL, "%4ssub_layout:\n", " ");
3227         } else if (verbose & VERBOSE_DETAIL) {
3228                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3229                 llapi_printf(LLAPI_MSG_NORMAL, "%4slcme_offset:         %u\n",
3230                              " ", entry->lcme_offset);
3231                 llapi_printf(LLAPI_MSG_NORMAL, "%4slcme_size:           %u\n",
3232                              " ", entry->lcme_size);
3233                 llapi_printf(LLAPI_MSG_NORMAL, "%4ssub_layout:\n", " ");
3234         } else {
3235                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3236         }
3237 }
3238
3239 /* Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
3240  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
3241  *
3242  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
3243  * The table below gives the answers for the specified parameters (value and
3244  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
3245  * --------------------------------------
3246  * 1 | file > limit; sign > 0 | -1 / -1 |
3247  * 2 | file = limit; sign > 0 | -1 / -1 |
3248  * 3 | file < limit; sign > 0 |  ? /  1 |
3249  * 4 | file > limit; sign = 0 | -1 / -1 |
3250  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
3251  * 6 | file < limit; sign = 0 |  ? / -1 |
3252  * 7 | file > limit; sign < 0 |  1 /  1 |
3253  * 8 | file = limit; sign < 0 |  ? / -1 |
3254  * 9 | file < limit; sign < 0 |  ? / -1 |
3255  * --------------------------------------
3256  * Note: 5th actually means that the value is within the interval
3257  * (limit - margin, limit]. */
3258 static int find_value_cmp(unsigned long long file, unsigned long long limit,
3259                           int sign, int negopt, unsigned long long margin,
3260                           bool mds)
3261 {
3262         int ret = -1;
3263
3264         if (sign > 0) {
3265                 /* Drop the fraction of margin (of days or size). */
3266                 if (file + margin <= limit)
3267                         ret = mds ? 0 : 1;
3268         } else if (sign == 0) {
3269                 if (file <= limit && file + margin > limit)
3270                         ret = mds ? 0 : 1;
3271                 else if (file + margin <= limit)
3272                         ret = mds ? 0 : -1;
3273         } else if (sign < 0) {
3274                 if (file > limit)
3275                         ret = 1;
3276                 else if (mds)
3277                         ret = 0;
3278         }
3279
3280         return negopt ? ~ret + 1 : ret;
3281 }
3282
3283 static inline struct lov_user_md *
3284 lov_comp_entry(struct lov_comp_md_v1 *comp_v1, int ent_idx)
3285 {
3286         return (struct lov_user_md *)((char *)comp_v1 +
3287                         comp_v1->lcm_entries[ent_idx].lcme_offset);
3288 }
3289
3290 static inline struct lov_user_ost_data_v1 *
3291 lov_v1v3_objects(struct lov_user_md *v1)
3292 {
3293         if (v1->lmm_magic == LOV_USER_MAGIC_V3)
3294                 return ((struct lov_user_md_v3 *)v1)->lmm_objects;
3295         else
3296                 return v1->lmm_objects;
3297 }
3298
3299 static inline void
3300 lov_v1v3_pool_name(struct lov_user_md *v1, char *pool_name)
3301 {
3302         if (v1->lmm_magic == LOV_USER_MAGIC_V3)
3303                 snprintf(pool_name, LOV_MAXPOOLNAME, "%s",
3304                          ((struct lov_user_md_v3 *)v1)->lmm_pool_name);
3305         else
3306                 pool_name[0] = '\0';
3307 }
3308
3309 static inline bool
3310 print_last_init_comp(struct find_param *param)
3311 {
3312         /* print all component info */
3313         if ((param->fp_verbose & VERBOSE_DEFAULT) == VERBOSE_DEFAULT)
3314                 return false;
3315
3316         /* print specific component info */
3317         if (param->fp_check_comp_id || param->fp_check_comp_flags ||
3318             param->fp_check_comp_start || param->fp_check_comp_end ||
3319             param->fp_check_mirror_id || param->fp_check_mirror_index)
3320                 return false;
3321
3322         return true;
3323 }
3324
3325 static int find_comp_end_cmp(unsigned long long end, struct find_param *param)
3326 {
3327         int match;
3328
3329         if (param->fp_comp_end == LUSTRE_EOF) {
3330                 if (param->fp_comp_end_sign == 0) /* equal to EOF */
3331                         match = end == LUSTRE_EOF ? 1 : -1;
3332                 else if (param->fp_comp_end_sign > 0) /* at most EOF */
3333                         match = end == LUSTRE_EOF ? -1 : 1;
3334                 else /* at least EOF */
3335                         match = -1;
3336                 if (param->fp_exclude_comp_end)
3337                         match = ~match + 1;
3338         } else {
3339                 unsigned long long margin;
3340
3341                 margin = end == LUSTRE_EOF ? 0 : param->fp_comp_end_units;
3342                 match = find_value_cmp(end, param->fp_comp_end,
3343                                        param->fp_comp_end_sign,
3344                                        param->fp_exclude_comp_end, margin, 0);
3345         }
3346
3347         return match;
3348 }
3349
3350 /**
3351  * An example of "getstripe -v" for a two components PFL file:
3352  *
3353  * composite_header:
3354  * lcm_magic:       0x0BD60BD0
3355  * lcm_size:        264
3356  * lcm_flags:       0
3357  * lcm_layout_gen:  2
3358  * lcm_entry_count: 2
3359  * components:
3360  * - lcme_id:             1
3361  *   lcme_flags:          0x10
3362  *   lcme_extent.e_start: 0
3363  *   lcme_extent.e_end:   1048576
3364  *   lcme_offset:         128
3365  *   lcme_size:           56
3366  *   sub_layout:
3367  *     lmm_magic:         0x0BD10BD0
3368  *     lmm_seq:           0x200000401
3369  *     lmm_object_id:     0x1
3370  *     lmm_fid:           [0x200000401:0x1:0x0]
3371  *     lmm_stripe_count:  1
3372  *     lmm_stripe_size:   1048576
3373  *     lmm_pattern:       raid0
3374  *     lmm_layout_gen:    0
3375  *     lmm_stripe_offset: 0
3376  *     lmm_objects:
3377  *     - 0: { l_ost_idx: 0, l_fid: [0x100000000:0x2:0x0] }
3378  *
3379  * - lcme_id:             2
3380  *   lcme_flags:          0x10
3381  *   lcme_extent.e_start: 1048576
3382  *   lcme_extent.e_end:   EOF
3383  *   lcme_offset:         184
3384  *   lcme_size:           80
3385  *     sub_layout:
3386  *     lmm_magic:         0x0BD10BD0
3387  *     lmm_seq:           0x200000401
3388  *     lmm_object_id:     0x1
3389  *     lmm_fid:           [0x200000401:0x1:0x0]
3390  *     lmm_stripe_count:  2
3391  *     lmm_stripe_size:   1048576
3392  *     lmm_pattern:       raid0
3393  *     lmm_layout_gen:    0
3394  *     lmm_stripe_offset: 1
3395  *     lmm_objects:
3396  *     - 0: { l_ost_idx: 1, l_fid: [0x100010000:0x2:0x0] }
3397  *     - 1: { l_ost_idx: 0, l_fid: [0x100000000:0x3:0x0] }
3398  */
3399 static void lov_dump_comp_v1(struct find_param *param, char *path,
3400                              enum lov_dump_flags flags)
3401 {
3402         struct lov_comp_md_entry_v1 *entry;
3403         struct lov_user_ost_data_v1 *objects;
3404         struct lov_comp_md_v1 *comp_v1 = (void *)&param->fp_lmd->lmd_lmm;
3405         struct lov_user_md_v1 *v1;
3406         char pool_name[LOV_MAXPOOLNAME + 1];
3407         int obdindex = param->fp_obd_index;
3408         int i, j, match, ext;
3409         bool obdstripe = false;
3410         __u16 mirror_index = 0;
3411         __u16 mirror_id = 0;
3412
3413         if (obdindex != OBD_NOT_FOUND) {
3414                 for (i = 0; !(flags & LDF_IS_DIR) && !obdstripe &&
3415                             i < comp_v1->lcm_entry_count; i++) {
3416                         if (!(comp_v1->lcm_entries[i].lcme_flags &
3417                               LCME_FL_INIT))
3418                                 continue;
3419
3420                         v1 = lov_comp_entry(comp_v1, i);
3421                         objects = lov_v1v3_objects(v1);
3422
3423                         for (j = 0; j < v1->lmm_stripe_count; j++) {
3424                                 if (obdindex == objects[j].l_ost_idx) {
3425                                         obdstripe = true;
3426                                         break;
3427                                 }
3428                         }
3429                 }
3430         } else {
3431                 obdstripe = true;
3432         }
3433
3434         if (!obdstripe)
3435                 return;
3436
3437         lov_dump_comp_v1_header(param, path, flags);
3438
3439         flags |= LDF_INDENT;
3440
3441         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
3442                 entry = &comp_v1->lcm_entries[i];
3443
3444                 if (param->fp_check_comp_flags) {
3445                         if (((param->fp_comp_flags & entry->lcme_flags) !=
3446                              param->fp_comp_flags) ||
3447                             (param->fp_comp_neg_flags & entry->lcme_flags))
3448                                 continue;
3449                 }
3450
3451                 if (param->fp_check_comp_id &&
3452                     param->fp_comp_id != entry->lcme_id)
3453                         continue;
3454
3455                 if (param->fp_check_comp_start) {
3456                         match = find_value_cmp(entry->lcme_extent.e_start,
3457                                                param->fp_comp_start,
3458                                                param->fp_comp_start_sign,
3459                                                0,
3460                                                param->fp_comp_start_units, 0);
3461                         if (match == -1)
3462                                 continue;
3463                 }
3464
3465                 if (param->fp_check_comp_end) {
3466                         match = find_comp_end_cmp(entry->lcme_extent.e_end,
3467                                                   param);
3468                         if (match == -1)
3469                                 continue;
3470                 }
3471
3472                 if (param->fp_check_mirror_index) {
3473                         if (mirror_id != mirror_id_of(entry->lcme_id)) {
3474                                 mirror_index++;
3475                                 mirror_id = mirror_id_of(entry->lcme_id);
3476                         }
3477
3478                         match = find_value_cmp(mirror_index,
3479                                                param->fp_mirror_index,
3480                                                param->fp_mirror_index_sign,
3481                                                param->fp_exclude_mirror_index,
3482                                                1, 0);
3483                         if (match == -1)
3484                                 continue;
3485                 } else if (param->fp_check_mirror_id) {
3486                         if (mirror_id != mirror_id_of(entry->lcme_id))
3487                                 mirror_id = mirror_id_of(entry->lcme_id);
3488
3489                         match = find_value_cmp(mirror_id,
3490                                                param->fp_mirror_id,
3491                                                param->fp_mirror_id_sign,
3492                                                param->fp_exclude_mirror_id,
3493                                                1, 0);
3494                         if (match == -1)
3495                                 continue;
3496                 }
3497
3498                 if (print_last_init_comp(param)) {
3499                         /**
3500                          * if part of stripe info is needed, we'd print only
3501                          * the last instantiated component info.
3502                          */
3503                         if (entry->lcme_flags & LCME_FL_INIT)
3504                                 continue;
3505
3506                         if (param->fp_verbose & VERBOSE_EXT_SIZE) {
3507                                 if (entry->lcme_flags & LCME_FL_EXTENSION)
3508                                         /* moved back below */
3509                                         i++;
3510                                 else
3511                                         continue;
3512                         }
3513                         break;
3514                 }
3515
3516                 if (entry->lcme_flags & LCME_FL_INIT) {
3517                         if (obdindex != OBD_NOT_FOUND) {
3518                                 flags |= LDF_SKIP_OBJS;
3519                                 v1 = lov_comp_entry(comp_v1, i);
3520                                 objects = lov_v1v3_objects(v1);
3521
3522                                 for (j = 0; j < v1->lmm_stripe_count; j++) {
3523                                         if (obdindex == objects[j].l_ost_idx) {
3524                                                 flags &= ~LDF_SKIP_OBJS;
3525                                                 break;
3526                                         }
3527                                 }
3528                         } else {
3529                                 flags &= ~LDF_SKIP_OBJS;
3530                         }
3531                 } else {
3532                         flags |= LDF_SKIP_OBJS;
3533                 }
3534
3535                 if (obdindex != OBD_NOT_FOUND && (flags & LDF_SKIP_OBJS))
3536                         continue;
3537                 lov_dump_comp_v1_entry(param, flags, i);
3538
3539                 v1 = lov_comp_entry(comp_v1, i);
3540                 objects = lov_v1v3_objects(v1);
3541                 lov_v1v3_pool_name(v1, pool_name);
3542
3543                 ext = entry->lcme_flags & LCME_FL_EXTENSION ? LDF_EXTENSION : 0;
3544                 lov_dump_user_lmm_v1v3(v1, pool_name, objects, path, obdindex,
3545                                        param->fp_max_depth, param->fp_verbose,
3546                                        flags | ext);
3547         }
3548         if (print_last_init_comp(param)) {
3549                 /**
3550                  * directory layout contains only layout template, print the
3551                  * last component.
3552                  */
3553                 if (i == 0)
3554                         i = comp_v1->lcm_entry_count - 1;
3555                 else
3556                         i--;
3557                 flags &= ~LDF_SKIP_OBJS;
3558
3559                 lov_dump_comp_v1_entry(param, flags, i);
3560
3561                 v1 = lov_comp_entry(comp_v1, i);
3562                 objects = lov_v1v3_objects(v1);
3563                 lov_v1v3_pool_name(v1, pool_name);
3564
3565                 entry = &comp_v1->lcm_entries[i];
3566                 ext = entry->lcme_flags & LCME_FL_EXTENSION ? LDF_EXTENSION : 0;
3567                 lov_dump_user_lmm_v1v3(v1, pool_name, objects, path, obdindex,
3568                                        param->fp_max_depth, param->fp_verbose,
3569                                        flags | ext);
3570         }
3571 }
3572
3573 #define VERBOSE_COMP_OPTS       (VERBOSE_COMP_COUNT | VERBOSE_COMP_ID | \
3574                                  VERBOSE_COMP_START | VERBOSE_COMP_END | \
3575                                  VERBOSE_COMP_FLAGS)
3576
3577 static inline bool has_any_comp_options(struct find_param *param)
3578 {
3579         enum llapi_layout_verbose verbose = param->fp_verbose;
3580
3581         if (param->fp_check_comp_id || param->fp_check_comp_count ||
3582             param->fp_check_comp_start || param->fp_check_comp_end ||
3583             param->fp_check_comp_flags)
3584                 return true;
3585
3586         /* show full layout information, not component specific */
3587         if ((verbose & ~VERBOSE_DETAIL) == VERBOSE_DEFAULT)
3588                 return false;
3589
3590         return verbose & VERBOSE_COMP_OPTS;
3591 }
3592
3593 struct lov_user_mds_data *lov_forge_comp_v1(struct lov_user_mds_data *orig,
3594                                             bool is_dir)
3595 {
3596         struct lov_user_md *lum = &orig->lmd_lmm;
3597         struct lov_user_mds_data *new;
3598         struct lov_comp_md_v1 *comp_v1;
3599         struct lov_comp_md_entry_v1 *ent;
3600         int lum_off = sizeof(*comp_v1) + sizeof(*ent);
3601         int lum_size = lov_user_md_size(is_dir ? 0 : lum->lmm_stripe_count,
3602                                         lum->lmm_magic);
3603
3604         new = malloc(sizeof(lstat_t) + lum_off + lum_size);
3605         if (new == NULL) {
3606                 llapi_printf(LLAPI_MSG_NORMAL, "out of memory\n");
3607                 return new;
3608         }
3609
3610         memcpy(new, orig, sizeof(lstat_t));
3611
3612         comp_v1 = (struct lov_comp_md_v1 *)&new->lmd_lmm;
3613         comp_v1->lcm_magic = lum->lmm_magic;
3614         comp_v1->lcm_size = lum_off + lum_size;
3615         comp_v1->lcm_layout_gen = is_dir ? 0 : lum->lmm_layout_gen;
3616         comp_v1->lcm_flags = 0;
3617         comp_v1->lcm_entry_count = 1;
3618
3619         ent = &comp_v1->lcm_entries[0];
3620         ent->lcme_id = 0;
3621         ent->lcme_flags = is_dir ? 0 : LCME_FL_INIT;
3622         ent->lcme_extent.e_start = 0;
3623         ent->lcme_extent.e_end = LUSTRE_EOF;
3624         ent->lcme_offset = lum_off;
3625         ent->lcme_size = lum_size;
3626
3627         memcpy((char *)comp_v1 + lum_off, lum, lum_size);
3628
3629         return new;
3630 }
3631
3632 static void lov_dump_plain_user_lmm(struct find_param *param, char *path,
3633                                     enum lov_dump_flags flags)
3634 {
3635         __u32 magic = *(__u32 *)&param->fp_lmd->lmd_lmm;
3636
3637         if (has_any_comp_options(param)) {
3638                 struct lov_user_mds_data *new_lmd, *orig_lmd;
3639
3640                 orig_lmd = param->fp_lmd;
3641                 new_lmd = lov_forge_comp_v1(orig_lmd, flags & LDF_IS_DIR);
3642                 if (new_lmd != NULL) {
3643                         param->fp_lmd = new_lmd;
3644                         lov_dump_comp_v1(param, path, flags);
3645                         param->fp_lmd = orig_lmd;
3646                         free(new_lmd);
3647                 }
3648                 return;
3649         }
3650
3651         if (magic == LOV_USER_MAGIC_V1) {
3652                 lov_dump_user_lmm_v1v3(&param->fp_lmd->lmd_lmm, NULL,
3653                                        param->fp_lmd->lmd_lmm.lmm_objects,
3654                                        path, param->fp_obd_index,
3655                                        param->fp_max_depth, param->fp_verbose,
3656                                        flags);
3657         } else {
3658                 char pool_name[LOV_MAXPOOLNAME + 1];
3659                 struct lov_user_ost_data_v1 *objects;
3660                 struct lov_user_md_v3 *lmmv3 = (void *)&param->fp_lmd->lmd_lmm;
3661
3662                 snprintf(pool_name, sizeof(pool_name), "%s",
3663                          lmmv3->lmm_pool_name);
3664                 objects = lmmv3->lmm_objects;
3665                 lov_dump_user_lmm_v1v3(&param->fp_lmd->lmd_lmm, pool_name,
3666                                        objects, path, param->fp_obd_index,
3667                                        param->fp_max_depth, param->fp_verbose,
3668                                        flags);
3669         }
3670 }
3671
3672 static uint32_t check_foreign_type(uint32_t foreign_type)
3673 {
3674         uint32_t i;
3675
3676         for (i = 0; i < LU_FOREIGN_TYPE_UNKNOWN; i++) {
3677                 if (lu_foreign_types[i].lft_name == NULL)
3678                         break;
3679                 if (foreign_type == lu_foreign_types[i].lft_type)
3680                         return i;
3681         }
3682
3683         return LU_FOREIGN_TYPE_UNKNOWN;
3684 }
3685
3686 static void lov_dump_foreign_lmm(struct find_param *param, char *path,
3687                                  enum lov_dump_flags flags)
3688 {
3689         struct lov_foreign_md *lfm = (void *)&param->fp_lmd->lmd_lmm;
3690         bool yaml = flags & LDF_YAML;
3691
3692         if (!yaml && param->fp_depth && path)
3693                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
3694
3695         if (param->fp_verbose & VERBOSE_DETAIL) {
3696                 uint32_t type = check_foreign_type(lfm->lfm_type);
3697
3698                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_magic:         0x%08X\n",
3699                              lfm->lfm_magic);
3700                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_length:          %u\n",
3701                              lfm->lfm_length);
3702                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_type:          0x%08X",
3703                              lfm->lfm_type);
3704                 if (type < LU_FOREIGN_TYPE_UNKNOWN)
3705                         llapi_printf(LLAPI_MSG_NORMAL, " (%s)\n",
3706                                      lu_foreign_types[type].lft_name);
3707                 else
3708                         llapi_printf(LLAPI_MSG_NORMAL, " (unknown)\n");
3709
3710                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_flags:          0x%08X\n",
3711                              lfm->lfm_flags);
3712         }
3713         llapi_printf(LLAPI_MSG_NORMAL, "lfm_value:     '%.*s'\n",
3714                      lfm->lfm_length, lfm->lfm_value);
3715         llapi_printf(LLAPI_MSG_NORMAL, "\n");
3716 }
3717
3718 static void lmv_dump_foreign_lmm(struct find_param *param, char *path,
3719                                     enum lov_dump_flags flags)
3720 {
3721         struct lmv_foreign_md *lfm = (struct lmv_foreign_md *)param->fp_lmv_md;
3722         bool yaml = flags & LDF_YAML;
3723
3724         if (!yaml && param->fp_depth && path)
3725                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
3726
3727         if (param->fp_verbose & VERBOSE_DETAIL) {
3728                 uint32_t type = check_foreign_type(lfm->lfm_type);
3729
3730                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_magic:         0x%08X\n",
3731                              lfm->lfm_magic);
3732                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_length:          %u\n",
3733                              lfm->lfm_length);
3734                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_type:          0x%08X",
3735                              lfm->lfm_type);
3736                 if (type < LU_FOREIGN_TYPE_UNKNOWN)
3737                         llapi_printf(LLAPI_MSG_NORMAL, " (%s)\n",
3738                                      lu_foreign_types[type].lft_name);
3739                 else
3740                         llapi_printf(LLAPI_MSG_NORMAL, " (unknown)\n");
3741
3742                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_flags:          0x%08X\n",
3743                              lfm->lfm_flags);
3744         }
3745         llapi_printf(LLAPI_MSG_NORMAL, "lfm_value:     '%.*s'\n",
3746                      lfm->lfm_length, lfm->lfm_value);
3747         llapi_printf(LLAPI_MSG_NORMAL, "\n");
3748 }
3749
3750 static void llapi_lov_dump_user_lmm(struct find_param *param, char *path,
3751                                     enum lov_dump_flags flags)
3752 {
3753         __u32 magic;
3754
3755         if (param->fp_get_lmv || param->fp_get_default_lmv)
3756                 magic = (__u32)param->fp_lmv_md->lum_magic;
3757         else
3758                 magic = *(__u32 *)&param->fp_lmd->lmd_lmm; /* lum->lmm_magic */
3759
3760         if (param->fp_raw)
3761                 flags |= LDF_IS_RAW;
3762         if (param->fp_yaml)
3763                 flags |= LDF_YAML;
3764
3765         switch (magic) {
3766         case LOV_USER_MAGIC_V1:
3767         case LOV_USER_MAGIC_V3:
3768         case LOV_USER_MAGIC_SPECIFIC:
3769                 lov_dump_plain_user_lmm(param, path, flags);
3770                 break;
3771         case LOV_USER_MAGIC_FOREIGN:
3772                 lov_dump_foreign_lmm(param, path, flags);
3773                 break;
3774         case LMV_MAGIC_V1:
3775         case LMV_USER_MAGIC: {
3776                 char pool_name[LOV_MAXPOOLNAME + 1];
3777                 struct lmv_user_md *lum;
3778
3779                 lum = (struct lmv_user_md *)param->fp_lmv_md;
3780                 snprintf(pool_name, sizeof(pool_name), "%s",
3781                          lum->lum_pool_name);
3782                 lmv_dump_user_lmm(lum, pool_name, path, param->fp_obd_index,
3783                                   param->fp_max_depth, param->fp_verbose,
3784                                   flags);
3785                 break;
3786         }
3787         case LOV_USER_MAGIC_COMP_V1:
3788                 lov_dump_comp_v1(param, path, flags);
3789                 break;
3790         case LMV_MAGIC_FOREIGN:
3791                 lmv_dump_foreign_lmm(param, path, flags);
3792                 break;
3793         default:
3794                 llapi_printf(LLAPI_MSG_NORMAL, "unknown lmm_magic:  %#x "
3795                              "(expecting one of %#x %#x %#x %#x)\n",
3796                              *(__u32 *)&param->fp_lmd->lmd_lmm,
3797                              LOV_USER_MAGIC_V1, LOV_USER_MAGIC_V3,
3798                              LMV_USER_MAGIC, LMV_MAGIC_V1);
3799                 return;
3800         }
3801 }
3802
3803 int llapi_file_get_stripe(const char *path, struct lov_user_md *lum)
3804 {
3805         const char *fname;
3806         char *dname;
3807         int fd, rc = 0;
3808
3809         fname = strrchr(path, '/');
3810
3811         /* It should be a file (or other non-directory) */
3812         if (fname == NULL) {
3813                 dname = (char *)malloc(2);
3814                 if (dname == NULL)
3815                         return -ENOMEM;
3816                 strcpy(dname, ".");
3817                 fname = (char *)path;
3818         } else {
3819                 dname = (char *)malloc(fname - path + 1);
3820                 if (dname == NULL)
3821                         return -ENOMEM;
3822                 strncpy(dname, path, fname - path);
3823                 dname[fname - path] = '\0';
3824                 fname++;
3825         }
3826
3827         fd = open(dname, O_RDONLY | O_NONBLOCK);
3828         if (fd == -1) {
3829                 rc = -errno;
3830                 goto out_free;
3831         }
3832
3833         strcpy((char *)lum, fname);
3834         if (ioctl(fd, IOC_MDC_GETFILESTRIPE, (void *)lum) == -1)
3835                 rc = -errno;
3836
3837         if (close(fd) == -1 && rc == 0)
3838                 rc = -errno;
3839
3840 out_free:
3841         free(dname);
3842         return rc;
3843 }
3844
3845 int llapi_file_lookup(int dirfd, const char *name)
3846 {
3847         struct obd_ioctl_data data = { 0 };
3848         char rawbuf[8192];
3849         char *buf = rawbuf;
3850         int rc;
3851
3852         if (dirfd < 0 || name == NULL)
3853                 return -EINVAL;
3854
3855         data.ioc_version = OBD_IOCTL_VERSION;
3856         data.ioc_len = sizeof(data);
3857         data.ioc_inlbuf1 = (char *)name;
3858         data.ioc_inllen1 = strlen(name) + 1;
3859
3860         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
3861         if (rc) {
3862                 llapi_error(LLAPI_MSG_ERROR, rc,
3863                             "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
3864                             name, rc);
3865                 return rc;
3866         }
3867
3868         rc = ioctl(dirfd, IOC_MDC_LOOKUP, buf);
3869         if (rc < 0)
3870                 rc = -errno;
3871         return rc;
3872 }
3873
3874 /* Check if the file time matches all the given criteria (e.g. --atime +/-N).
3875  * Return -1 or 1 if file timestamp does not or does match the given criteria
3876  * correspondingly. Return 0 if the MDS time is being checked and there are
3877  * attributes on OSTs and it is not yet clear if the timespamp matches.
3878  *
3879  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
3880  * updated timestamps. */
3881 static int find_time_check(lstat_t *st, struct find_param *param, int mds)
3882 {
3883         int rc = 1;
3884         int rc2;
3885
3886         /* Check if file is accepted. */
3887         if (param->fp_atime) {
3888                 rc2 = find_value_cmp(st->st_atime, param->fp_atime,
3889                                      param->fp_asign, param->fp_exclude_atime,
3890                                      param->fp_time_margin, mds);
3891                 if (rc2 < 0)
3892                         return rc2;
3893                 rc = rc2;
3894         }
3895
3896         if (param->fp_mtime) {
3897                 rc2 = find_value_cmp(st->st_mtime, param->fp_mtime,
3898                                      param->fp_msign, param->fp_exclude_mtime,
3899                                      param->fp_time_margin, mds);
3900                 if (rc2 < 0)
3901                         return rc2;
3902
3903                 /* If the previous check matches, but this one is not yet clear,
3904                  * we should return 0 to do an RPC on OSTs. */
3905                 if (rc == 1)
3906                         rc = rc2;
3907         }
3908
3909         if (param->fp_ctime) {
3910                 rc2 = find_value_cmp(st->st_ctime, param->fp_ctime,
3911                                      param->fp_csign, param->fp_exclude_ctime,
3912                                      param->fp_time_margin, mds);
3913                 if (rc2 < 0)
3914                         return rc2;
3915
3916                 /* If the previous check matches, but this one is not yet clear,
3917                  * we should return 0 to do an RPC on OSTs. */
3918                 if (rc == 1)
3919                         rc = rc2;
3920         }
3921
3922         return rc;
3923 }
3924
3925 /**
3926  * Check whether the stripes matches the indexes user provided
3927  *       1   : matched
3928  *       0   : Unmatched
3929  */
3930 static int check_obd_match(struct find_param *param)
3931 {
3932         struct lov_user_ost_data_v1 *objects;
3933         struct lov_comp_md_v1 *comp_v1 = NULL;
3934         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
3935         lstat_t *st = &param->fp_lmd->lmd_st;
3936         int i, j, k, count = 1;
3937
3938         if (param->fp_obd_uuid && param->fp_obd_index == OBD_NOT_FOUND)
3939                 return 0;
3940
3941         if (!S_ISREG(st->st_mode))
3942                 return 0;
3943
3944         /* exclude foreign */
3945         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
3946                 return param->fp_exclude_obd;
3947
3948         /* Only those files should be accepted, which have a
3949          * stripe on the specified OST. */
3950         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
3951                 comp_v1 = (struct lov_comp_md_v1 *)v1;
3952                 count = comp_v1->lcm_entry_count;
3953         }
3954
3955         for (i = 0; i < count; i++) {
3956                 if (comp_v1)
3957                         v1 = lov_comp_entry(comp_v1, i);
3958
3959                 objects = lov_v1v3_objects(v1);
3960
3961                 for (j = 0; j < v1->lmm_stripe_count; j++) {
3962                         if (comp_v1 && !(comp_v1->lcm_entries[i].lcme_flags &
3963                                          LCME_FL_INIT))
3964                                 continue;
3965                         for (k = 0; k < param->fp_num_obds; k++) {
3966                                 if (param->fp_obd_indexes[k] ==
3967                                     objects[j].l_ost_idx)
3968                                         return !param->fp_exclude_obd;
3969                         }
3970                 }
3971         }
3972
3973         return param->fp_exclude_obd;
3974 }
3975
3976 static int check_mdt_match(struct find_param *param)
3977 {
3978         int i;
3979
3980         if (param->fp_mdt_uuid && param->fp_mdt_index == OBD_NOT_FOUND)
3981                 return 0;
3982
3983         /* FIXME: For striped dir, we should get stripe information and check */
3984         for (i = 0; i < param->fp_num_mdts; i++) {
3985                 if (param->fp_mdt_indexes[i] == param->fp_file_mdt_index)
3986                         return !param->fp_exclude_mdt;
3987         }
3988
3989         if (param->fp_exclude_mdt)
3990                 return 1;
3991
3992         return 0;
3993 }
3994
3995 /**
3996  * Check whether the obd is active or not, if it is
3997  * not active, just print the object affected by this
3998  * failed target
3999  **/
4000 static int print_failed_tgt(struct find_param *param, char *path, int type)
4001 {
4002         struct obd_statfs stat_buf;
4003         struct obd_uuid uuid_buf;
4004         int ret;
4005
4006         if (type != LL_STATFS_LOV && type != LL_STATFS_LMV)
4007                 return -EINVAL;
4008
4009         memset(&stat_buf, 0, sizeof(struct obd_statfs));
4010         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
4011         ret = llapi_obd_statfs(path, type,
4012                                param->fp_obd_index, &stat_buf,
4013                                &uuid_buf);
4014         if (ret) {
4015                 llapi_printf(LLAPI_MSG_NORMAL,
4016                              "obd_uuid: %s failed %s ",
4017                              param->fp_obd_uuid->uuid,
4018                              strerror(errno));
4019         }
4020
4021         return ret;
4022 }
4023
4024 static int find_check_stripe_size(struct find_param *param)
4025 {
4026         struct lov_comp_md_v1 *comp_v1 = NULL;
4027         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4028         __u32 stripe_size = 0;
4029         int ret, i, count = 1;
4030
4031         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4032                 return param->fp_exclude_stripe_size ? 1 : -1;
4033
4034         ret = param->fp_exclude_stripe_size ? 1 : -1;
4035         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4036                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4037                 count = comp_v1->lcm_entry_count;
4038         }
4039
4040         for (i = 0; i < count; i++) {
4041                 struct lov_comp_md_entry_v1 *ent;
4042
4043                 if (comp_v1) {
4044                         v1 = lov_comp_entry(comp_v1, i);
4045
4046                         ent = &comp_v1->lcm_entries[i];
4047                         if (ent->lcme_flags & LCME_FL_EXTENSION)
4048                                 continue;
4049                         if (!(ent->lcme_flags & LCME_FL_INIT))
4050                                 continue;
4051                 }
4052                 stripe_size = v1->lmm_stripe_size;
4053         }
4054
4055         ret = find_value_cmp(stripe_size, param->fp_stripe_size,
4056                              param->fp_stripe_size_sign,
4057                              param->fp_exclude_stripe_size,
4058                              param->fp_stripe_size_units, 0);
4059
4060         return ret;
4061 }
4062
4063 static int find_check_ext_size(struct find_param *param)
4064 {
4065         struct lov_comp_md_v1 *comp_v1;
4066         struct lov_user_md_v1 *v1;
4067         int ret, i;
4068
4069         ret = param->fp_exclude_ext_size ? 1 : -1;
4070         comp_v1 = (struct lov_comp_md_v1 *)&param->fp_lmd->lmd_lmm;
4071         if (comp_v1->lcm_magic != LOV_USER_MAGIC_COMP_V1)
4072                 return ret;
4073
4074         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
4075                 struct lov_comp_md_entry_v1 *ent;
4076
4077                 v1 = lov_comp_entry(comp_v1, i);
4078
4079                 ent = &comp_v1->lcm_entries[i];
4080                 if (!(ent->lcme_flags & LCME_FL_EXTENSION))
4081                         continue;
4082
4083                 ret = find_value_cmp(v1->lmm_stripe_size, param->fp_ext_size,
4084                                      param->fp_ext_size_sign,
4085                                      param->fp_exclude_ext_size,
4086                                      param->fp_ext_size_units, 0);
4087                 /* If any ext_size matches */
4088                 if (ret != -1)
4089                         break;
4090         }
4091
4092         return ret;
4093 }
4094
4095 static __u32 find_get_stripe_count(struct find_param *param)
4096 {
4097         struct lov_comp_md_v1 *comp_v1 = NULL;
4098         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4099         int i, count = 1;
4100         __u32 stripe_count = 0;
4101
4102         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4103                 return 0;
4104
4105         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4106                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4107                 count = comp_v1->lcm_entry_count;
4108         }
4109
4110         for (i = 0; i < count; i++) {
4111                 if (comp_v1) {
4112                         struct lov_comp_md_entry_v1 *ent;
4113
4114                         v1 = lov_comp_entry(comp_v1, i);
4115
4116                         ent = &comp_v1->lcm_entries[i];
4117                         if (!(ent->lcme_flags & LCME_FL_INIT))
4118                                 continue;
4119
4120                         if (ent->lcme_flags & LCME_FL_EXTENSION)
4121                                 continue;
4122                 }
4123                 stripe_count = v1->lmm_stripe_count;
4124         }
4125
4126         return stripe_count;
4127 }
4128
4129 #define LOV_PATTERN_INVALID     0xFFFFFFFF
4130
4131 static int find_check_layout(struct find_param *param)
4132 {
4133         struct lov_comp_md_v1 *comp_v1 = NULL;
4134         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4135         int i, count = 1;
4136         bool found = false, valid = false;
4137
4138         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4139                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4140                 count = comp_v1->lcm_entry_count;
4141         }
4142
4143         for (i = 0; i < count; i++) {
4144                 if (comp_v1)
4145                         v1 = lov_comp_entry(comp_v1, i);
4146
4147                 /* foreign file have a special magic but no pattern field */
4148                 if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4149                         continue;
4150
4151                 if (v1->lmm_pattern == LOV_PATTERN_INVALID)
4152                         continue;
4153
4154                 valid = true;
4155                 if (v1->lmm_pattern & param->fp_layout) {
4156                         found = true;
4157                         break;
4158                 }
4159         }
4160
4161         if (!valid)
4162                 return -1;
4163
4164         if ((found && !param->fp_exclude_layout) ||
4165             (!found && param->fp_exclude_layout))
4166                 return 1;
4167
4168         return -1;
4169 }
4170
4171 /* if no type specified, check/exclude all foreign
4172  * if type specified, check all foreign&type and exclude !foreign + foreign&type
4173  */
4174 static int find_check_foreign(struct find_param *param)
4175 {
4176         if (S_ISREG(param->fp_lmd->lmd_st.st_mode)) {
4177                 struct lov_foreign_md *lfm;
4178
4179                 lfm = (void *)&param->fp_lmd->lmd_lmm;
4180                 if (lfm->lfm_magic != LOV_USER_MAGIC_FOREIGN) {
4181                         if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN)
4182                                 return param->fp_exclude_foreign ? 1 : -1;
4183                         return -1;
4184                 } else {
4185                         if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN ||
4186                             lfm->lfm_type == param->fp_foreign_type)
4187                                 return param->fp_exclude_foreign ? -1 : 1;
4188                         return param->fp_exclude_foreign ? 1 : -1;
4189                 }
4190         }
4191
4192         if (S_ISDIR(param->fp_lmd->lmd_st.st_mode)) {
4193                 struct lmv_foreign_md *lfm;
4194
4195                 lfm = (void *)param->fp_lmv_md;
4196                 if (lfm->lfm_magic != LMV_MAGIC_FOREIGN) {
4197                         if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN)
4198                                 return param->fp_exclude_foreign ? 1 : -1;
4199                         return -1;
4200                 } else {
4201                         if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN ||
4202                             lfm->lfm_type == param->fp_foreign_type)
4203                                 return param->fp_exclude_foreign ? -1 : 1;
4204                         return param->fp_exclude_foreign ? 1 : -1;
4205                 }
4206         }
4207         return -1;
4208 }
4209
4210 static int find_check_pool(struct find_param *param)
4211 {
4212         struct lov_comp_md_v1 *comp_v1 = NULL;
4213         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4214         struct lov_user_md_v3 *v3 = (void *)v1;
4215         int i, count = 1;
4216         bool found = false;
4217
4218         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4219                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4220                 count = comp_v1->lcm_entry_count;
4221                 /* empty requested pool is taken as no pool search */
4222                 if (count == 0 && param->fp_poolname[0] == '\0')
4223                         found = true;
4224         }
4225
4226         for (i = 0; i < count; i++) {
4227                 if (comp_v1 != NULL)
4228                         v1 = lov_comp_entry(comp_v1, i);
4229
4230                 if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4231                         continue;
4232
4233                 if (((v1->lmm_magic == LOV_USER_MAGIC_V1) &&
4234                      (param->fp_poolname[0] == '\0')) ||
4235                     ((v1->lmm_magic == LOV_USER_MAGIC_V3) &&
4236                      (strncmp(v3->lmm_pool_name,
4237                               param->fp_poolname, LOV_MAXPOOLNAME) == 0)) ||
4238                     ((v1->lmm_magic == LOV_USER_MAGIC_V3) &&
4239                      (strcmp(param->fp_poolname, "*") == 0))) {
4240                         found = true;
4241                         break;
4242                 }
4243         }
4244
4245         if ((found && !param->fp_exclude_pool) ||
4246             (!found && param->fp_exclude_pool))
4247                 return 1;
4248
4249         return -1;
4250 }
4251
4252 static int find_check_comp_options(struct find_param *param)
4253 {
4254         lstat_t *st = &param->fp_lmd->lmd_st;
4255         struct lov_comp_md_v1 *comp_v1, *forged_v1 = NULL;
4256         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4257         struct lov_comp_md_entry_v1 *entry;
4258         int i, ret = 0;
4259
4260         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4261                 return -1;
4262
4263         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4264                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4265         } else {
4266                 forged_v1 = malloc(sizeof(*forged_v1) + sizeof(*entry));
4267                 if (forged_v1 == NULL)
4268                         return -1;
4269                 comp_v1 = forged_v1;
4270                 comp_v1->lcm_entry_count = 1;
4271                 entry = &comp_v1->lcm_entries[0];
4272                 entry->lcme_flags = S_ISDIR(st->st_mode) ? 0 : LCME_FL_INIT;
4273                 entry->lcme_extent.e_start = 0;
4274                 entry->lcme_extent.e_end = LUSTRE_EOF;
4275         }
4276
4277         /* invalid case, don't match for any kind of search. */
4278         if (comp_v1->lcm_entry_count == 0) {
4279                 ret = -1;
4280                 goto out;
4281         }
4282
4283         if (param->fp_check_comp_count) {
4284                 ret = find_value_cmp(forged_v1 ? 0 : comp_v1->lcm_entry_count,
4285                                      param->fp_comp_count,
4286                                      param->fp_comp_count_sign,
4287                                      param->fp_exclude_comp_count, 1, 0);
4288                 if (ret == -1)
4289                         goto out;
4290         }
4291
4292         ret = 1;
4293         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
4294                 entry = &comp_v1->lcm_entries[i];
4295
4296                 if (param->fp_check_comp_flags) {
4297                         ret = 1;
4298                         if (((param->fp_comp_flags & entry->lcme_flags) !=
4299                              param->fp_comp_flags) ||
4300                             (param->fp_comp_neg_flags & entry->lcme_flags)) {
4301                                 ret = -1;
4302                                 continue;
4303                         }
4304                 }
4305
4306                 if (param->fp_check_comp_start) {
4307                         ret = find_value_cmp(entry->lcme_extent.e_start,
4308                                              param->fp_comp_start,
4309                                              param->fp_comp_start_sign,
4310                                              param->fp_exclude_comp_start,
4311                                              param->fp_comp_start_units, 0);
4312                         if (ret == -1)
4313                                 continue;
4314                 }
4315
4316                 if (param->fp_check_comp_end) {
4317                         ret = find_comp_end_cmp(entry->lcme_extent.e_end,
4318                                                 param);
4319                         if (ret == -1)
4320                                 continue;
4321                 }
4322
4323                 /* the component matches all criteria */
4324                 break;
4325         }
4326 out:
4327         if (forged_v1)
4328                 free(forged_v1);
4329         return ret;
4330 }
4331
4332 static int find_check_mirror_options(struct find_param *param)
4333 {
4334         struct lov_comp_md_v1 *comp_v1;
4335         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4336         int ret = 0;
4337
4338         if (v1->lmm_magic != LOV_USER_MAGIC_COMP_V1)
4339                 return -1;
4340
4341         comp_v1 = (struct lov_comp_md_v1 *)v1;
4342
4343         if (param->fp_check_mirror_count) {
4344                 ret = find_value_cmp(comp_v1->lcm_mirror_count + 1,
4345                                      param->fp_mirror_count,
4346                                      param->fp_mirror_count_sign,
4347                                      param->fp_exclude_mirror_count, 1, 0);
4348                 if (ret == -1)
4349                         return ret;
4350         }
4351
4352         if (param->fp_check_mirror_state) {
4353                 ret = 1;
4354                 __u16 file_state = comp_v1->lcm_flags & LCM_FL_FLR_MASK;
4355
4356                 if ((param->fp_mirror_state != 0 &&
4357                     file_state != param->fp_mirror_state) ||
4358                     file_state == param->fp_mirror_neg_state)
4359                         return -1;
4360         }
4361
4362         return ret;
4363 }
4364
4365 static bool find_check_lmm_info(struct find_param *param)
4366 {
4367         return param->fp_check_pool || param->fp_check_stripe_count ||
4368                param->fp_check_stripe_size || param->fp_check_layout ||
4369                param->fp_check_comp_count || param->fp_check_comp_end ||
4370                param->fp_check_comp_start || param->fp_check_comp_flags ||
4371                param->fp_check_mirror_count || param->fp_check_foreign ||
4372                param->fp_check_mirror_state || param->fp_check_ext_size ||
4373                param->fp_check_projid;
4374 }
4375
4376 /*
4377  * Get file/directory project id.
4378  * by the open fd resides on.
4379  * Return 0 and project id on success, or -ve errno.
4380  */
4381 static int fget_projid(int fd, int *projid)
4382 {
4383         struct fsxattr fsx;
4384         int rc;
4385
4386         rc = ioctl(fd, LL_IOC_FSGETXATTR, &fsx);
4387         if (rc)
4388                 return -errno;
4389
4390         *projid = fsx.fsx_projid;
4391         return 0;
4392 }
4393
4394 static int cb_find_init(char *path, DIR *parent, DIR **dirp,
4395                         void *data, struct dirent64 *de)
4396 {
4397         struct find_param *param = (struct find_param *)data;
4398         DIR *dir = dirp == NULL ? NULL : *dirp;
4399         int decision = 1; /* 1 is accepted; -1 is rejected. */
4400         lstat_t *st = &param->fp_lmd->lmd_st;
4401         int lustre_fs = 1;
4402         int checked_type = 0;
4403         int ret = 0;
4404         __u32 stripe_count = 0;
4405         int fd = -2;
4406
4407         if (parent == NULL && dir == NULL)
4408                 return -EINVAL;
4409
4410         /* If a regular expression is presented, make the initial decision */
4411         if (param->fp_pattern != NULL) {
4412                 char *fname = strrchr(path, '/');
4413                 fname = (fname == NULL ? path : fname + 1);
4414                 ret = fnmatch(param->fp_pattern, fname, 0);
4415                 if ((ret == FNM_NOMATCH && !param->fp_exclude_pattern) ||
4416                     (ret == 0 && param->fp_exclude_pattern))
4417                         goto decided;
4418         }
4419
4420         /* See if we can check the file type from the dirent. */
4421         if (param->fp_type != 0 && de != NULL && de->d_type != DT_UNKNOWN) {
4422                 checked_type = 1;
4423
4424                 if (DTTOIF(de->d_type) == param->fp_type) {
4425                         if (param->fp_exclude_type)
4426                                 goto decided;
4427                 } else {
4428                         if (!param->fp_exclude_type)
4429                                 goto decided;
4430                 }
4431         }
4432
4433         ret = 0;
4434
4435         /* Request MDS for the stat info if some of these parameters need
4436          * to be compared. */
4437         if (param->fp_obd_uuid || param->fp_mdt_uuid ||
4438             param->fp_check_uid || param->fp_check_gid ||
4439             param->fp_atime || param->fp_mtime || param->fp_ctime ||
4440             param->fp_check_size || param->fp_check_blocks ||
4441             find_check_lmm_info(param) ||
4442             param->fp_check_mdt_count || param->fp_check_hash_type)
4443                 decision = 0;
4444
4445         if (param->fp_type != 0 && checked_type == 0)
4446                 decision = 0;
4447
4448         if (decision == 0) {
4449                 if (dir && (param->fp_check_mdt_count ||
4450                     param->fp_check_hash_type || param->fp_check_foreign)) {
4451                         param->fp_get_lmv = 1;
4452                         ret = cb_get_dirstripe(path, dir, param);
4453                         if (ret != 0) {
4454                                 /* XXX this works to decide for foreign
4455                                  * criterion only
4456                                  */
4457                                 if (errno == ENODATA &&
4458                                     param->fp_check_foreign) {
4459                                         if (param->fp_exclude_foreign)
4460                                                 goto foreign;
4461                                         goto decided;
4462                                 }
4463                                 return ret;
4464                         }
4465                 }
4466
4467                 param->fp_lmd->lmd_lmm.lmm_magic = 0;
4468                 ret = get_lmd_info(path, parent, dir, param->fp_lmd,
4469                                    param->fp_lum_size, GET_LMD_INFO);
4470                 if (ret == 0 && param->fp_lmd->lmd_lmm.lmm_magic == 0 &&
4471                     find_check_lmm_info(param)) {
4472                         struct lov_user_md *lmm = &param->fp_lmd->lmd_lmm;
4473
4474                         /* We need to "fake" the "use the default" values
4475                          * since the lmm struct is zeroed out at this point. */
4476                         lmm->lmm_magic = LOV_USER_MAGIC_V1;
4477                         lmm->lmm_pattern = LOV_PATTERN_DEFAULT;
4478                         if (!param->fp_raw)
4479                                 ostid_set_seq(&lmm->lmm_oi,
4480                                               FID_SEQ_LOV_DEFAULT);
4481                         lmm->lmm_stripe_size = 0;
4482                         lmm->lmm_stripe_count = 0;
4483                         lmm->lmm_stripe_offset = -1;
4484                 }
4485                 if (ret == 0 && param->fp_mdt_uuid != NULL) {
4486                         if (dir != NULL) {
4487                                 ret = llapi_file_fget_mdtidx(dirfd(dir),
4488                                                      &param->fp_file_mdt_index);
4489                         } else if (S_ISREG(st->st_mode)) {
4490                                 /* FIXME: we could get the MDT index from the
4491                                  * file's FID in lmd->lmd_lmm.lmm_oi without
4492                                  * opening the file, once we are sure that
4493                                  * LFSCK2 (2.6) has fixed up pre-2.0 LOV EAs.
4494                                  * That would still be an ioctl() to map the
4495                                  * FID to the MDT, but not an open RPC. */
4496                                 fd = open(path, O_RDONLY);
4497                                 if (fd > 0) {
4498                                         ret = llapi_file_fget_mdtidx(fd,
4499                                                      &param->fp_file_mdt_index);
4500                                 } else {
4501                                         ret = -errno;
4502                                 }
4503                         } else {
4504                                 /* For a special file, we assume it resides on
4505                                  * the same MDT as the parent directory. */
4506                                 ret = llapi_file_fget_mdtidx(dirfd(parent),
4507                                                      &param->fp_file_mdt_index);
4508                         }
4509                 }
4510                 if (ret != 0) {
4511                         if (ret == -ENOTTY)
4512                                 lustre_fs = 0;
4513                         if (ret == -ENOENT)
4514                                 goto decided;
4515
4516                         goto out;
4517                 } else {
4518                         stripe_count = find_get_stripe_count(param);
4519                 }
4520         }
4521
4522         if (param->fp_type && !checked_type) {
4523                 if ((st->st_mode & S_IFMT) == param->fp_type) {
4524                         if (param->fp_exclude_type)
4525                                 goto decided;
4526                 } else {
4527                         if (!param->fp_exclude_type)
4528                                 goto decided;
4529                 }
4530         }
4531
4532         /* Prepare odb. */
4533         if (param->fp_obd_uuid || param->fp_mdt_uuid) {
4534                 if (lustre_fs && param->fp_got_uuids &&
4535                     param->fp_dev != st->st_dev) {
4536                         /* A lustre/lustre mount point is crossed. */
4537                         param->fp_got_uuids = 0;
4538                         param->fp_obds_printed = 0;
4539                         param->fp_mdt_index = OBD_NOT_FOUND;
4540                         param->fp_obd_index = OBD_NOT_FOUND;
4541                 }
4542
4543                 if (lustre_fs && !param->fp_got_uuids) {
4544                         ret = setup_target_indexes(dir ? dir : parent, path,
4545                                                    param);
4546                         if (ret)
4547                                 goto out;
4548
4549                         param->fp_dev = st->st_dev;
4550                 } else if (!lustre_fs && param->fp_got_uuids) {
4551                         /* A lustre/non-lustre mount point is crossed. */
4552                         param->fp_got_uuids = 0;
4553                         param->fp_mdt_index = OBD_NOT_FOUND;
4554                         param->fp_obd_index = OBD_NOT_FOUND;
4555                 }
4556         }
4557
4558         if (param->fp_check_foreign) {
4559                 decision = find_check_foreign(param);
4560                 if (decision == -1)
4561                         goto decided;
4562         }
4563
4564         if (param->fp_check_stripe_size) {
4565                 decision = find_check_stripe_size(param);
4566                 if (decision == -1)
4567                         goto decided;
4568         }
4569
4570         if (param->fp_check_ext_size) {
4571                 decision = find_check_ext_size(param);
4572                 if (decision == -1)
4573                         goto decided;
4574         }
4575
4576         if (param->fp_check_stripe_count) {
4577                 decision = find_value_cmp(stripe_count, param->fp_stripe_count,
4578                                           param->fp_stripe_count_sign,
4579                                           param->fp_exclude_stripe_count, 1, 0);
4580                 if (decision == -1)
4581                         goto decided;
4582         }
4583
4584         if (param->fp_check_mdt_count) {
4585                 if (param->fp_lmv_md->lum_magic == LMV_MAGIC_FOREIGN) {
4586                         decision = -1;
4587                         goto decided;
4588                 }
4589
4590                 decision = find_value_cmp(
4591                                 param->fp_lmv_md->lum_stripe_count,
4592                                 param->fp_mdt_count,
4593                                 param->fp_mdt_count_sign,
4594                                 param->fp_exclude_mdt_count, 1, 0);
4595                 if (decision == -1)
4596                         goto decided;
4597         }
4598
4599         if (param->fp_check_layout) {
4600                 decision = find_check_layout(param);
4601                 if (decision == -1)
4602                         goto decided;
4603         }
4604
4605         if (param->fp_check_hash_type) {
4606                 __u32 found;
4607
4608                 if (param->fp_lmv_md->lum_magic == LMV_MAGIC_FOREIGN) {
4609                         decision = -1;
4610                         goto decided;
4611                 }
4612
4613                 found = param->fp_lmv_md->lum_hash_type & param->fp_hash_type;
4614                 if ((found && param->fp_exclude_hash_type) ||
4615                     (!found && !param->fp_exclude_hash_type)) {
4616                         decision = -1;
4617                         goto decided;
4618                 }
4619         }
4620
4621         /* If an OBD UUID is specified but none matches, skip this file. */
4622         if ((param->fp_obd_uuid && param->fp_obd_index == OBD_NOT_FOUND) ||
4623             (param->fp_mdt_uuid && param->fp_mdt_index == OBD_NOT_FOUND))
4624                 goto decided;
4625
4626         /* If an OST or MDT UUID is given, and some OST matches,
4627          * check it here. */
4628         if (param->fp_obd_index != OBD_NOT_FOUND ||
4629             param->fp_mdt_index != OBD_NOT_FOUND) {
4630                 if (param->fp_obd_uuid) {
4631                         if (check_obd_match(param)) {
4632                                 /* If no mdtuuid is given, we are done.
4633                                  * Otherwise, fall through to the mdtuuid
4634                                  * check below. */
4635                                 if (!param->fp_mdt_uuid)
4636                                         goto obd_matches;
4637                         } else {
4638                                 goto decided;
4639                         }
4640                 }
4641
4642                 if (param->fp_mdt_uuid) {
4643                         if (check_mdt_match(param))
4644                                 goto obd_matches;
4645                         goto decided;
4646                 }
4647         }
4648
4649 obd_matches:
4650         if (param->fp_check_uid) {
4651                 if (st->st_uid == param->fp_uid) {
4652                         if (param->fp_exclude_uid)
4653                                 goto decided;
4654                 } else {
4655                         if (!param->fp_exclude_uid)
4656                                 goto decided;
4657                 }
4658         }
4659
4660         if (param->fp_check_gid) {
4661                 if (st->st_gid == param->fp_gid) {
4662                         if (param->fp_exclude_gid)
4663                                 goto decided;
4664                 } else {
4665                         if (!param->fp_exclude_gid)
4666                                 goto decided;
4667                 }
4668         }
4669
4670         if (param->fp_check_projid) {
4671                 int projid = 0;
4672
4673                 if (fd == -2)
4674                         fd = open(path, O_RDONLY);
4675
4676                 if (fd > 0)
4677                         ret = fget_projid(fd, &projid);
4678                 else
4679                         ret = -errno;
4680                 if (ret)
4681                         goto out;
4682                 if (projid == param->fp_projid) {
4683                         if (param->fp_exclude_projid)
4684                                 goto decided;
4685                 } else {
4686                         if (!param->fp_exclude_projid)
4687                                 goto decided;
4688                 }
4689         }
4690
4691         if (param->fp_check_pool) {
4692                 decision = find_check_pool(param);
4693                 if (decision == -1)
4694                         goto decided;
4695         }
4696
4697         if (param->fp_check_comp_count || param->fp_check_comp_flags ||
4698             param->fp_check_comp_start || param->fp_check_comp_end) {
4699                 decision = find_check_comp_options(param);
4700                 if (decision == -1)
4701                         goto decided;
4702         }
4703
4704         if (param->fp_check_mirror_count || param->fp_check_mirror_state) {
4705                 decision = find_check_mirror_options(param);
4706                 if (decision == -1)
4707                         goto decided;
4708         }
4709
4710         /* Check the time on mds. */
4711         decision = 1;
4712         if (param->fp_atime || param->fp_mtime || param->fp_ctime) {
4713                 int for_mds;
4714
4715                 for_mds = lustre_fs ?
4716                         (S_ISREG(st->st_mode) && stripe_count) : 0;
4717                 decision = find_time_check(st, param, for_mds);
4718                 if (decision == -1)
4719                         goto decided;
4720         }
4721
4722         /* If file still fits the request, ask ost for updated info.
4723            The regular stat is almost of the same speed as some new
4724            'glimpse-size-ioctl'. */
4725
4726         if ((param->fp_check_size || param->fp_check_blocks) &&
4727             ((S_ISREG(st->st_mode) && stripe_count) || S_ISDIR(st->st_mode)))
4728                 decision = 0;
4729
4730         if (!decision) {
4731                 /* For regular files with the stripe the decision may have not
4732                  * been taken yet if *time or size is to be checked. */
4733                 if (param->fp_obd_index != OBD_NOT_FOUND)
4734                         print_failed_tgt(param, path, LL_STATFS_LOV);
4735
4736                 if (param->fp_mdt_index != OBD_NOT_FOUND)
4737                         print_failed_tgt(param, path, LL_STATFS_LMV);
4738
4739                 if (dir != NULL)
4740                         ret = fstat_f(dirfd(dir), st);
4741                 else if (de != NULL)
4742                         ret = fstatat_f(dirfd(parent), de->d_name, st,
4743                                         AT_SYMLINK_NOFOLLOW);
4744                 else
4745                         ret = lstat_f(path, st);
4746
4747                 if (ret) {
4748                         if (errno == ENOENT) {
4749                                 llapi_error(LLAPI_MSG_ERROR, -ENOENT,
4750                                             "warning: %s: %s does not exist",
4751                                             __func__, path);
4752                                 goto decided;
4753                         } else {
4754                                 ret = -errno;
4755                                 llapi_error(LLAPI_MSG_ERROR, ret,
4756                                             "%s: IOC_LOV_GETINFO on %s failed",
4757                                             __func__, path);
4758                                 goto out;
4759                         }
4760                 }
4761
4762                 /* Check the time on osc. */
4763                 decision = find_time_check(st, param, 0);
4764                 if (decision == -1)
4765                         goto decided;
4766         }
4767
4768         if (param->fp_check_size) {
4769                 decision = find_value_cmp(st->st_size, param->fp_size,
4770                                           param->fp_size_sign,
4771                                           param->fp_exclude_size,
4772                                           param->fp_size_units, 0);
4773                 if (decision == -1)
4774                         goto decided;
4775         }
4776
4777         if (param->fp_check_blocks) { /* convert st_blocks to bytes */
4778                 decision = find_value_cmp(st->st_blocks * 512, param->fp_blocks,
4779                                           param->fp_blocks_sign,
4780                                           param->fp_exclude_blocks,
4781                                           param->fp_blocks_units, 0);
4782                 if (decision == -1)
4783                         goto decided;
4784         }
4785
4786 foreign:
4787         llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
4788         if (param->fp_zero_end)
4789                 llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
4790         else
4791                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
4792
4793 decided:
4794         ret = 0;
4795         /* Do not get down anymore? */
4796         if (param->fp_depth == param->fp_max_depth) {
4797                 ret = 1;
4798                 goto out;
4799         }
4800         param->fp_depth++;
4801 out:
4802         if (fd > 0)
4803                 close(fd);
4804         return ret;
4805 }
4806
4807 static int cb_migrate_mdt_init(char *path, DIR *parent, DIR **dirp,
4808                                void *param_data, struct dirent64 *de)
4809 {
4810         struct find_param *param = (struct find_param *)param_data;
4811         struct lmv_user_md *lmu = param->fp_lmv_md;
4812         DIR *tmp_parent = parent;
4813         char raw[MAX_IOC_BUFLEN] = {'\0'};
4814         char *rawbuf = raw;
4815         struct obd_ioctl_data data = { 0 };
4816         int fd;
4817         int ret;
4818         char *path_copy;
4819         char *filename;
4820         bool retry = false;
4821
4822         if (parent == NULL && dirp == NULL)
4823                 return -EINVAL;
4824
4825         if (!lmu)
4826                 return -EINVAL;
4827
4828         if (dirp != NULL)
4829                 closedir(*dirp);
4830
4831         if (parent == NULL) {
4832                 tmp_parent = opendir_parent(path);
4833                 if (tmp_parent == NULL) {
4834                         *dirp = NULL;
4835                         ret = -errno;
4836                         llapi_error(LLAPI_MSG_ERROR, ret,
4837                                     "can not open %s", path);
4838                         return ret;
4839                 }
4840         }
4841
4842         fd = dirfd(tmp_parent);
4843
4844         path_copy = strdup(path);
4845         filename = basename(path_copy);
4846
4847         data.ioc_inlbuf1 = (char *)filename;
4848         data.ioc_inllen1 = strlen(filename) + 1;
4849         data.ioc_inlbuf2 = (char *)lmu;
4850         data.ioc_inllen2 = lmv_user_md_size(lmu->lum_stripe_count,
4851                                             lmu->lum_magic);
4852         ret = llapi_ioctl_pack(&data, &rawbuf, sizeof(raw));
4853         if (ret != 0) {
4854                 llapi_error(LLAPI_MSG_ERROR, ret,
4855                             "llapi_obd_statfs: error packing ioctl data");
4856                 goto out;
4857         }
4858
4859 migrate:
4860         ret = ioctl(fd, LL_IOC_MIGRATE, rawbuf);
4861         if (ret != 0) {
4862                 if (errno == EBUSY && !retry) {
4863                         /* because migrate may not be able to lock all involved
4864                          * objects in order, for some of them it try lock, while
4865                          * there may be conflicting COS locks and cause migrate
4866                          * fail with EBUSY, hope a sync() could cause
4867                          * transaction commit and release these COS locks. */
4868                         sync();
4869                         retry = true;
4870                         goto migrate;
4871                 } else if (errno == EALREADY) {
4872                         if (param->fp_verbose & VERBOSE_DETAIL)
4873                                 llapi_printf(LLAPI_MSG_NORMAL,
4874                                              "%s was migrated to MDT%d already\n",
4875                                              path, lmu->lum_stripe_offset);
4876                         ret = 0;
4877                 } else {
4878                         ret = -errno;
4879                         llapi_error(LLAPI_MSG_ERROR, ret,
4880                                     "%s migrate failed: %s (%d)\n",
4881                                     path, strerror(-ret), ret);
4882                         goto out;
4883                 }
4884         } else if (param->fp_verbose & VERBOSE_DETAIL) {
4885                 llapi_printf(LLAPI_MSG_NORMAL,
4886                              "migrate %s to MDT%d stripe count %d\n",
4887                              path, lmu->lum_stripe_offset,
4888                              lmu->lum_stripe_count);
4889         }
4890
4891 out:
4892         if (dirp != NULL) {
4893                 /* If the directory is being migration, we need
4894                  * close the directory after migration,
4895                  * so the old directory cache will be cleanup
4896                  * on the client side, and re-open to get the
4897                  * new directory handle */
4898                 *dirp = opendir(path);
4899                 if (*dirp == NULL) {
4900                         ret = -errno;
4901                         llapi_error(LLAPI_MSG_ERROR, ret,
4902                                     "%s: Failed to open '%s'", __func__, path);
4903                 }
4904         }
4905
4906         if (parent == NULL)
4907                 closedir(tmp_parent);
4908
4909         free(path_copy);
4910
4911         return ret;
4912 }
4913
4914 /* dir migration finished, shrink its stripes */
4915 static int cb_migrate_mdt_fini(char *path, DIR *parent, DIR **dirp, void *data,
4916                                struct dirent64 *de)
4917 {
4918         struct find_param *param = data;
4919         struct lmv_user_md *lmu = param->fp_lmv_md;
4920         int lmulen = lmv_user_md_size(lmu->lum_stripe_count, lmu->lum_magic);
4921         int ret = 0;
4922
4923         if (de && de->d_type != DT_DIR)
4924                 goto out;
4925
4926         if (*dirp) {
4927                 /*
4928                  * close it before setxattr because the latter may destroy the
4929                  * original object, and cause close fail.
4930                  */
4931                 ret = closedir(*dirp);
4932                 *dirp = NULL;
4933                 if (ret)
4934                         goto out;
4935         }
4936
4937         ret = setxattr(path, XATTR_NAME_LMV, lmu, lmulen, 0);
4938         if (ret == -EALREADY)
4939                 ret = 0;
4940 out:
4941         cb_common_fini(path, parent, dirp, data, de);
4942         return ret;
4943 }
4944
4945 int llapi_migrate_mdt(char *path, struct find_param *param)
4946 {
4947         return param_callback(path, cb_migrate_mdt_init, cb_migrate_mdt_fini,
4948                               param);
4949 }
4950
4951 int llapi_mv(char *path, struct find_param *param)
4952 {
4953 #if LUSTRE_VERSION_CODE > OBD_OCD_VERSION(2, 9, 59, 0)
4954         static bool printed;
4955
4956         if (!printed) {
4957                 llapi_error(LLAPI_MSG_ERROR, -ESTALE,
4958                             "llapi_mv() is deprecated, use llapi_migrate_mdt()\n");
4959                 printed = true;
4960         }
4961 #endif
4962         return llapi_migrate_mdt(path, param);
4963 }
4964
4965 int llapi_find(char *path, struct find_param *param)
4966 {
4967         return param_callback(path, cb_find_init, cb_common_fini, param);
4968 }
4969
4970 /*
4971  * Get MDT number that the file/directory inode referenced
4972  * by the open fd resides on.
4973  * Return 0 and mdtidx on success, or -ve errno.
4974  */
4975 int llapi_file_fget_mdtidx(int fd, int *mdtidx)
4976 {
4977         if (ioctl(fd, LL_IOC_GET_MDTIDX, mdtidx) < 0)
4978                 return -errno;
4979         return 0;
4980 }
4981
4982 static int cb_get_mdt_index(char *path, DIR *parent, DIR **dirp, void *data,
4983                             struct dirent64 *de)
4984 {
4985         struct find_param *param = (struct find_param *)data;
4986         DIR *d = dirp == NULL ? NULL : *dirp;
4987         int ret;
4988         int mdtidx;
4989
4990         if (parent == NULL && d == NULL)
4991                 return -EINVAL;
4992
4993         if (d != NULL) {
4994                 ret = llapi_file_fget_mdtidx(dirfd(d), &mdtidx);
4995         } else /* if (parent) */ {
4996                 int fd;
4997
4998                 fd = open(path, O_RDONLY | O_NOCTTY);
4999                 if (fd > 0) {
5000                         ret = llapi_file_fget_mdtidx(fd, &mdtidx);
5001                         close(fd);
5002                 } else {
5003                         ret = -errno;
5004                 }
5005         }
5006
5007         if (ret != 0) {
5008                 if (ret == -ENODATA) {
5009                         if (!param->fp_obd_uuid)
5010                                 llapi_printf(LLAPI_MSG_NORMAL,
5011                                              "'%s' has no stripe info\n", path);
5012                         goto out;
5013                 } else if (ret == -ENOENT) {
5014                         llapi_error(LLAPI_MSG_WARN, ret,
5015                                     "warning: %s: '%s' does not exist",
5016                                     __func__, path);
5017                         goto out;
5018                 } else if (ret == -ENOTTY) {
5019                         llapi_error(LLAPI_MSG_ERROR, ret,
5020                                     "%s: '%s' not on a Lustre fs",
5021                                     __func__, path);
5022                 } else {
5023                         llapi_error(LLAPI_MSG_ERROR, ret,
5024                                     "error: %s: '%s' failed get_mdtidx",
5025                                     __func__, path);
5026                 }
5027                 return ret;
5028         }
5029
5030         if (param->fp_quiet || !(param->fp_verbose & VERBOSE_DETAIL))
5031                 llapi_printf(LLAPI_MSG_NORMAL, "%d\n", mdtidx);
5032         else
5033                 llapi_printf(LLAPI_MSG_NORMAL, "%s\nmdt_index:\t%d\n",
5034                              path, mdtidx);
5035
5036 out:
5037         /* Do not go down anymore? */
5038         if (param->fp_depth == param->fp_max_depth)
5039                 return 1;
5040
5041         param->fp_depth++;
5042
5043         return 0;
5044 }
5045
5046 static int cb_getstripe(char *path, DIR *parent, DIR **dirp, void *data,
5047                         struct dirent64 *de)
5048 {
5049         struct find_param *param = (struct find_param *)data;
5050         DIR *d = dirp == NULL ? NULL : *dirp;
5051         int ret = 0;
5052
5053         if (parent == NULL && d == NULL)
5054                 return -EINVAL;
5055
5056         if (param->fp_obd_uuid) {
5057                 param->fp_quiet = 1;
5058                 ret = setup_obd_uuid(d ? dirfd(d) : dirfd(parent), path, param);
5059                 if (ret)
5060                         return ret;
5061         }
5062
5063         if (d && (param->fp_get_lmv || param->fp_get_default_lmv))
5064                 ret = cb_get_dirstripe(path, d, param);
5065         else if (d ||
5066                  (parent && !param->fp_get_lmv && !param->fp_get_default_lmv))
5067                 ret = get_lmd_info(path, parent, d, &param->fp_lmd->lmd_lmm,
5068                                    param->fp_lum_size, GET_LMD_STRIPE);
5069         else
5070                 return 0;
5071
5072         if (ret) {
5073                 if (errno == ENODATA && d != NULL) {
5074                         /* We need to "fake" the "use the default" values
5075                          * since the lmm struct is zeroed out at this point.
5076                          * The magic needs to be set in order to satisfy
5077                          * a check later on in the code path.
5078                          * The object_seq needs to be set for the "(Default)"
5079                          * prefix to be displayed. */
5080                         if (param->fp_get_default_lmv) {
5081                                 struct lmv_user_md *lum = param->fp_lmv_md;
5082
5083                                 lum->lum_magic = LMV_USER_MAGIC;
5084                                 lum->lum_stripe_count = 0;
5085                                 lum->lum_stripe_offset = -1;
5086                                 goto dump;
5087                         } else if (param->fp_get_lmv) {
5088                                 struct lmv_user_md *lum = param->fp_lmv_md;
5089                                 int mdtidx;
5090
5091                                 ret = llapi_file_fget_mdtidx(dirfd(d), &mdtidx);
5092                                 if (ret != 0)
5093                                         goto err_out;
5094                                 lum->lum_magic = LMV_MAGIC_V1;
5095                                 lum->lum_stripe_count = 0;
5096                                 lum->lum_stripe_offset = mdtidx;
5097                                 goto dump;
5098                         } else {
5099                                 struct lov_user_md *lmm =
5100                                         &param->fp_lmd->lmd_lmm;
5101
5102                                 lmm->lmm_magic = LOV_USER_MAGIC_V1;
5103                                 if (!param->fp_raw)
5104                                         ostid_set_seq(&lmm->lmm_oi,
5105                                                       FID_SEQ_LOV_DEFAULT);
5106                                 lmm->lmm_stripe_count = 0;
5107                                 lmm->lmm_stripe_size = 0;
5108                                 lmm->lmm_stripe_offset = -1;
5109                                 goto dump;
5110                         }
5111                 } else if (errno == ENODATA && parent != NULL) {
5112                         if (!param->fp_obd_uuid && !param->fp_mdt_uuid)
5113                                 llapi_printf(LLAPI_MSG_NORMAL,
5114                                              "%s has no stripe info\n", path);
5115                         goto out;
5116                 } else if (errno == ENOENT) {
5117                         llapi_error(LLAPI_MSG_WARN, -ENOENT,
5118                                     "warning: %s: %s does not exist",
5119                                     __func__, path);
5120                         goto out;
5121                 } else if (errno == ENOTTY) {
5122                         ret = -errno;
5123                         llapi_error(LLAPI_MSG_ERROR, ret,
5124                                     "%s: '%s' not on a Lustre fs?",
5125                                     __func__, path);
5126                 } else {
5127                         ret = -errno;
5128 err_out:
5129                         llapi_error(LLAPI_MSG_ERROR, ret,
5130                                     "error: %s: %s failed for %s",
5131                                      __func__, d ? "LL_IOC_LOV_GETSTRIPE" :
5132                                     "IOC_MDC_GETFILESTRIPE", path);
5133                 }
5134
5135                 return ret;
5136         }
5137
5138 dump:
5139         if (!(param->fp_verbose & VERBOSE_MDTINDEX))
5140                 llapi_lov_dump_user_lmm(param, path, d ? LDF_IS_DIR : 0);
5141
5142 out:
5143         /* Do not get down anymore? */
5144         if (param->fp_depth == param->fp_max_depth)
5145                 return 1;
5146
5147         param->fp_depth++;
5148
5149         return 0;
5150 }
5151
5152 int llapi_getstripe(char *path, struct find_param *param)
5153 {
5154         return param_callback(path, (param->fp_verbose & VERBOSE_MDTINDEX) ?
5155                               cb_get_mdt_index : cb_getstripe,
5156                               cb_common_fini, param);
5157 }
5158
5159 int llapi_obd_fstatfs(int fd, __u32 type, __u32 index,
5160                       struct obd_statfs *stat_buf, struct obd_uuid *uuid_buf)
5161 {
5162         char raw[MAX_IOC_BUFLEN] = {'\0'};
5163         char *rawbuf = raw;
5164         struct obd_ioctl_data data = { 0 };
5165         int rc = 0;
5166
5167         data.ioc_inlbuf1 = (char *)&type;
5168         data.ioc_inllen1 = sizeof(__u32);
5169         data.ioc_inlbuf2 = (char *)&index;
5170         data.ioc_inllen2 = sizeof(__u32);
5171         data.ioc_pbuf1 = (char *)stat_buf;
5172         data.ioc_plen1 = sizeof(struct obd_statfs);
5173         data.ioc_pbuf2 = (char *)uuid_buf;
5174         data.ioc_plen2 = sizeof(struct obd_uuid);
5175
5176         rc = llapi_ioctl_pack(&data, &rawbuf, sizeof(raw));
5177         if (rc != 0) {
5178                 llapi_error(LLAPI_MSG_ERROR, rc,
5179                             "llapi_obd_statfs: error packing ioctl data");
5180                 return rc;
5181         }
5182
5183         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
5184
5185         return rc < 0 ? -errno : 0;
5186 }
5187
5188 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
5189                      struct obd_statfs *stat_buf, struct obd_uuid *uuid_buf)
5190 {
5191         int fd;
5192         int rc;
5193
5194         fd = open(path, O_RDONLY);
5195         if (fd < 0) {
5196                 rc = -errno;
5197                 llapi_error(LLAPI_MSG_ERROR, rc, "error: %s: opening '%s'",
5198                             __func__, path);
5199                 /* If we can't even open a file on the filesystem (e.g. with
5200                  * -ESHUTDOWN), force caller to exit or it will loop forever. */
5201                 return -ENODEV;
5202         }
5203
5204         rc = llapi_obd_fstatfs(fd, type, index, stat_buf, uuid_buf);
5205
5206         close(fd);
5207
5208         return rc;
5209 }
5210
5211 #define MAX_STRING_SIZE 128
5212
5213 int llapi_ping(char *obd_type, char *obd_name)
5214 {
5215         int flags = O_RDONLY;
5216         char buf[1] = { 0 };
5217         glob_t path;
5218         int rc, fd;
5219
5220         rc = cfs_get_param_paths(&path, "%s/%s/ping",
5221                                 obd_type, obd_name);
5222         if (rc != 0)
5223                 return -errno;
5224 retry_open:
5225         fd = open(path.gl_pathv[0], flags);
5226         if (fd < 0) {
5227                 if (errno == EACCES && flags == O_RDONLY) {
5228                         flags = O_WRONLY;
5229                         goto retry_open;
5230                 }
5231                 rc = -errno;
5232                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s",
5233                             path.gl_pathv[0]);
5234                 goto failed;
5235         }
5236
5237         if (flags == O_RDONLY)
5238                 rc = read(fd, buf, sizeof(buf));
5239         else
5240                 rc = write(fd, buf, sizeof(buf));
5241         if (rc < 0)
5242                 rc = -errno;
5243         close(fd);
5244
5245         if (rc == 1)
5246                 rc = 0;
5247 failed:
5248         cfs_free_param_data(&path);
5249         return rc;
5250 }
5251
5252 int llapi_target_iterate(int type_num, char **obd_type,
5253                          void *args, llapi_cb_t cb)
5254 {
5255         int i, rc = 0;
5256         glob_t param;
5257         FILE *fp;
5258
5259         for (i = 0; i < type_num; i++) {
5260                 int j;
5261
5262                 rc = cfs_get_param_paths(&param, "%s/*/uuid", obd_type[i]);
5263                 if (rc != 0)
5264                         continue;
5265
5266                 for (j = 0; j < param.gl_pathc; j++) {
5267                         char obd_uuid[UUID_MAX + 1];
5268                         char *obd_name;
5269                         char *ptr;
5270
5271                         fp = fopen(param.gl_pathv[j], "r");
5272                         if (fp == NULL) {
5273                                 rc = -errno;
5274                                 llapi_error(LLAPI_MSG_ERROR, rc,
5275                                             "error: opening '%s'",
5276                                             param.gl_pathv[j]);
5277                                 goto free_path;
5278                         }
5279
5280                         if (fgets(obd_uuid, sizeof(obd_uuid), fp) == NULL) {
5281                                 rc = -errno;
5282                                 llapi_error(LLAPI_MSG_ERROR, rc,
5283                                             "error: reading '%s'",
5284                                             param.gl_pathv[j]);
5285                                 goto free_path;
5286                         }
5287
5288                         /* Extract the obd_name from the sysfs path.
5289                          * 'topsysfs'/fs/lustre/'obd_type'/'obd_name'.
5290                          */
5291                         obd_name = strstr(param.gl_pathv[j], "/fs/lustre/");
5292                         if (!obd_name) {
5293                                 rc = -EINVAL;
5294                                 goto free_path;
5295                         }
5296
5297                         /* skip /fs/lustre/'obd_type'/ */
5298                         obd_name += strlen(obd_type[i]) + 12;
5299                         /* chop off after obd_name */
5300                         ptr = strrchr(obd_name, '/');
5301                         if (ptr)
5302                                 *ptr = '\0';
5303
5304                         cb(obd_type[i], obd_name, obd_uuid, args);
5305
5306                         fclose(fp);
5307                         fp = NULL;
5308                 }
5309         }
5310 free_path:
5311         if (fp)
5312                 fclose(fp);
5313         cfs_free_param_data(&param);
5314         return rc;
5315 }
5316
5317 static void do_target_check(char *obd_type_name, char *obd_name,
5318                             char *obd_uuid, void *args)
5319 {
5320         int rc;
5321
5322         rc = llapi_ping(obd_type_name, obd_name);
5323         if (rc == ENOTCONN) {
5324                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
5325         } else if (rc) {
5326                 llapi_error(LLAPI_MSG_ERROR, rc, "error: check '%s'", obd_name);
5327         } else {
5328                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
5329         }
5330 }
5331
5332 int llapi_target_check(int type_num, char **obd_type, char *dir)
5333 {
5334         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
5335 }
5336
5337 #undef MAX_STRING_SIZE
5338
5339 /* Is this a lustre fs? */
5340 int llapi_is_lustre_mnttype(const char *type)
5341 {
5342         return (strcmp(type, "lustre") == 0 || strcmp(type,"lustre_lite") == 0);
5343 }
5344
5345 /* Is this a lustre client fs? */
5346 int llapi_is_lustre_mnt(struct mntent *mnt)
5347 {
5348         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
5349                 strstr(mnt->mnt_fsname, ":/") != NULL);
5350 }
5351
5352 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
5353 {
5354         char fsname[PATH_MAX + 1];
5355         int root;
5356         int rc;
5357
5358         rc = llapi_search_fsname(mnt, fsname);
5359         if (rc)
5360                 return rc;
5361
5362         root = open(mnt, O_RDONLY | O_DIRECTORY);
5363         if (root < 0) {
5364                 rc = -errno;
5365                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot open '%s'", mnt);
5366                 return rc;
5367         }
5368
5369         rc = ioctl(root, OBD_IOC_QUOTACTL, qctl);
5370         if (rc < 0)
5371                 rc = -errno;
5372
5373         close(root);
5374         return rc;
5375 }
5376
5377 /* Print mdtname 'name' into 'buf' using 'format'.  Add -MDT0000 if needed.
5378  * format must have %s%s, buf must be > 16
5379  * Eg: if name = "lustre-MDT0000", "lustre", or "lustre-MDT0000_UUID"
5380  *     then buf = "lustre-MDT0000"
5381  */
5382 static int get_mdtname(char *name, char *format, char *buf)
5383 {
5384         char suffix[]="-MDT0000";
5385         int len = strlen(name);
5386
5387         if ((len > 5) && (strncmp(name + len - 5, "_UUID", 5) == 0)) {
5388                 name[len - 5] = '\0';
5389                 len -= 5;
5390         }
5391
5392         if (len > 8) {
5393                 if ((len <= 16) && strncmp(name + len - 8, "-MDT", 4) == 0) {
5394                         suffix[0] = '\0';
5395                 } else {
5396                         /* Not enough room to add suffix */
5397                         llapi_err_noerrno(LLAPI_MSG_ERROR,
5398                                           "Invalid MDT name |%s|", name);
5399                         return -EINVAL;
5400                 }
5401         }
5402
5403         return sprintf(buf, format, name, suffix);
5404 }
5405
5406 /** ioctl on filsystem root, with mdtindex sent as data
5407  * \param mdtname path, fsname, or mdtname (lutre-MDT0004)
5408  * \param mdtidxp pointer to integer within data to be filled in with the
5409  *    mdt index (0 if no mdt is specified).  NULL won't be filled.
5410  */
5411 int root_ioctl(const char *mdtname, int opc, void *data, int *mdtidxp,
5412                int want_error)
5413 {
5414         char fsname[20];
5415         char *ptr;
5416         int fd, rc;
5417         long index;
5418
5419         /* Take path, fsname, or MDTname.  Assume MDT0000 in the former cases.
5420          Open root and parse mdt index. */
5421         if (mdtname[0] == '/') {
5422                 index = 0;
5423                 rc = get_root_path(WANT_FD | want_error, NULL, &fd,
5424                                    (char *)mdtname, -1);
5425         } else {
5426                 if (get_mdtname((char *)mdtname, "%s%s", fsname) < 0)
5427                         return -EINVAL;
5428                 ptr = fsname + strlen(fsname) - 8;
5429                 *ptr = '\0';
5430                 index = strtol(ptr + 4, NULL, 16);
5431                 rc = get_root_path(WANT_FD | want_error, fsname, &fd, NULL, -1);
5432         }
5433         if (rc < 0) {
5434                 if (want_error)
5435                         llapi_err_noerrno(LLAPI_MSG_ERROR,
5436                                           "Can't open %s: %d\n", mdtname, rc);
5437                 return rc;
5438         }
5439
5440         if (mdtidxp)
5441                 *mdtidxp = index;
5442
5443         rc = ioctl(fd, opc, data);
5444         if (rc == -1)
5445                 rc = -errno;
5446         else
5447                 rc = 0;
5448         close(fd);
5449         return rc;
5450 }
5451
5452 int llapi_fid2path(const char *device, const char *fidstr, char *buf,
5453                    int buflen, long long *recno, int *linkno)
5454 {
5455         const char *fidstr_orig = fidstr;
5456         struct lu_fid fid;
5457         struct getinfo_fid2path *gf;
5458         char *a;
5459         char *b;
5460         int rc;
5461
5462         while (*fidstr == '[')
5463                 fidstr++;
5464
5465         sscanf(fidstr, SFID, RFID(&fid));
5466         if (!fid_is_sane(&fid)) {
5467                 llapi_err_noerrno(LLAPI_MSG_ERROR,
5468                                   "bad FID format '%s', should be [seq:oid:ver]"
5469                                   " (e.g. "DFID")\n", fidstr_orig,
5470                                   (unsigned long long)FID_SEQ_NORMAL, 2, 0);
5471                 return -EINVAL;
5472         }
5473
5474         gf = malloc(sizeof(*gf) + buflen);
5475         if (gf == NULL)
5476                 return -ENOMEM;
5477
5478         gf->gf_fid = fid;
5479         gf->gf_recno = *recno;
5480         gf->gf_linkno = *linkno;
5481         gf->gf_pathlen = buflen;
5482
5483         /* Take path or fsname */
5484         rc = root_ioctl(device, OBD_IOC_FID2PATH, gf, NULL, 0);
5485         if (rc)
5486                 goto out_free;
5487
5488         b = buf;
5489         /* strip out instances of // */
5490         for (a = gf->gf_u.gf_path; *a != '\0'; a++) {
5491                 if ((*a == '/') && (*(a + 1) == '/'))
5492                         continue;
5493                 *b = *a;
5494                 b++;
5495         }
5496         *b = '\0';
5497
5498         if (buf[0] == '\0') { /* ROOT path */
5499                 buf[0] = '/';
5500                 buf[1] = '\0';
5501         }
5502
5503         *recno = gf->gf_recno;
5504         *linkno = gf->gf_linkno;
5505
5506 out_free:
5507         free(gf);
5508         return rc;
5509 }
5510
5511 static int fid_from_lma(const char *path, int fd, struct lu_fid *fid)
5512 {
5513         char                     buf[512];
5514         struct lustre_mdt_attrs *lma;
5515         int                      rc;
5516
5517         if (path == NULL)
5518                 rc = fgetxattr(fd, XATTR_NAME_LMA, buf, sizeof(buf));
5519         else
5520                 rc = lgetxattr(path, XATTR_NAME_LMA, buf, sizeof(buf));
5521         if (rc < 0)
5522                 return -errno;
5523         lma = (struct lustre_mdt_attrs *)buf;
5524         fid_le_to_cpu(fid, &lma->lma_self_fid);
5525         return 0;
5526 }
5527
5528 int llapi_get_mdt_index_by_fid(int fd, const struct lu_fid *fid,
5529                                int *mdt_index)
5530 {
5531         int     rc;
5532
5533         rc = ioctl(fd, LL_IOC_FID2MDTIDX, fid);
5534         if (rc < 0)
5535                 return -errno;
5536
5537         *mdt_index = rc;
5538
5539         return rc;
5540 }
5541
5542 int llapi_fd2fid(int fd, struct lu_fid *fid)
5543 {
5544         int rc;
5545
5546         memset(fid, 0, sizeof(*fid));
5547
5548         rc = ioctl(fd, LL_IOC_PATH2FID, fid) < 0 ? -errno : 0;
5549         if (rc == -EINVAL || rc == -ENOTTY)
5550                 rc = fid_from_lma(NULL, fd, fid);
5551
5552         return rc;
5553 }
5554
5555 int llapi_path2fid(const char *path, struct lu_fid *fid)
5556 {
5557         int fd, rc;
5558
5559         memset(fid, 0, sizeof(*fid));
5560         fd = open(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
5561         if (fd < 0) {
5562                 if (errno == ELOOP || errno == ENXIO)
5563                         return fid_from_lma(path, -1, fid);
5564                 return -errno;
5565         }
5566
5567         rc = llapi_fd2fid(fd, fid);
5568         if (rc == -EINVAL || rc == -ENOTTY)
5569                 rc = fid_from_lma(path, -1, fid);
5570
5571         close(fd);
5572         return rc;
5573 }
5574
5575 int llapi_fd2parent(int fd, unsigned int linkno, struct lu_fid *parent_fid,
5576                     char *name, size_t name_size)
5577 {
5578         struct getparent        *gp;
5579         int                      rc;
5580
5581         gp = malloc(sizeof(*gp) + name_size);
5582         if (gp == NULL)
5583                 return -ENOMEM;
5584
5585         gp->gp_linkno = linkno;
5586         gp->gp_name_size = name_size;
5587
5588         rc = ioctl(fd, LL_IOC_GETPARENT, gp);
5589         if (rc < 0) {
5590                 rc = -errno;
5591                 goto err_free;
5592         }
5593
5594         *parent_fid = gp->gp_fid;
5595
5596         strncpy(name, gp->gp_name, name_size);
5597         name[name_size - 1] = '\0';
5598
5599 err_free:
5600         free(gp);
5601         return rc;
5602 }
5603
5604 int llapi_path2parent(const char *path, unsigned int linkno,
5605                       struct lu_fid *parent_fid, char *name, size_t name_size)
5606 {
5607         int     fd;
5608         int     rc;
5609
5610         fd = open(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
5611         if (fd < 0)
5612                 return -errno;
5613
5614         rc = llapi_fd2parent(fd, linkno, parent_fid, name, name_size);
5615         close(fd);
5616         return rc;
5617 }
5618
5619 int llapi_get_connect_flags(const char *mnt, __u64 *flags)
5620 {
5621         int root;
5622         int rc;
5623
5624         root = open(mnt, O_RDONLY | O_DIRECTORY);
5625         if (root < 0) {
5626                 rc = -errno;
5627                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
5628                 return rc;
5629         }
5630
5631         rc = ioctl(root, LL_IOC_GET_CONNECT_FLAGS, flags);
5632         if (rc < 0) {
5633                 rc = -errno;
5634                 llapi_error(LLAPI_MSG_ERROR, rc,
5635                         "ioctl on %s for getting connect flags failed", mnt);
5636         }
5637         close(root);
5638         return rc;
5639 }
5640
5641 /**
5642  * Get a 64-bit value representing the version of file data pointed by fd.
5643  *
5644  * Each write or truncate, flushed on OST, will change this value. You can use
5645  * this value to verify if file data was modified. This only checks the file
5646  * data, not metadata.
5647  *
5648  * \param  flags  0: no flush pages, usually used it the process has already
5649  *                  taken locks;
5650  *                LL_DV_RD_FLUSH: OSTs will take LCK_PR to flush dirty pages
5651  *                  from clients;
5652  *                LL_DV_WR_FLUSH: OSTs will take LCK_PW to flush all caching
5653  *                  pages from clients.
5654  *
5655  * \retval 0 on success.
5656  * \retval -errno on error.
5657  */
5658 int llapi_get_data_version(int fd, __u64 *data_version, __u64 flags)
5659 {
5660         int rc;
5661         struct ioc_data_version idv;
5662
5663         idv.idv_flags = (__u32)flags;
5664
5665         rc = ioctl(fd, LL_IOC_DATA_VERSION, &idv);
5666         if (rc)
5667                 rc = -errno;
5668         else
5669                 *data_version = idv.idv_version;
5670
5671         return rc;
5672 }
5673
5674 /**
5675  * Flush cached pages from all clients.
5676  *
5677  * \param fd    File descriptor
5678  * \retval 0    success
5679  * \retval < 0  error
5680  */
5681 int llapi_file_flush(int fd)
5682 {
5683         __u64 dv;
5684
5685         return llapi_get_data_version(fd, &dv, LL_DV_WR_FLUSH);
5686 }
5687
5688 /*
5689  * Fetch layout version from OST objects. Layout version on OST objects are
5690  * only set when the file is a mirrored file AND after the file has been
5691  * written at least once.
5692  *
5693  * It actually fetches the least layout version from the objects.
5694  */
5695 int llapi_get_ost_layout_version(int fd, __u32 *layout_version)
5696 {
5697         int rc;
5698         struct ioc_data_version idv = { 0 };
5699
5700         rc = ioctl(fd, LL_IOC_DATA_VERSION, &idv);
5701         if (rc)
5702                 rc = -errno;
5703         else
5704                 *layout_version = idv.idv_layout_version;
5705
5706         return rc;
5707 }
5708
5709 /*
5710  * Create a file without any name and open it for read/write
5711  *
5712  * - file is created as if it were a standard file in the given \a directory
5713  * - file does not appear in \a directory and mtime does not change because
5714  *   the filename is handled specially by the Lustre MDS.
5715  * - file is destroyed at final close
5716  *
5717  * \param[in]   directory       directory from which to inherit layout/MDT idx
5718  * \param[in]   mdt_idx         MDT index on which the file is created,
5719  *                              \a idx == -1 means no specific MDT is requested
5720  * \param[in]   mode            standard open(2) mode
5721  * \param[in]   stripe_param    stripe parameters. May be NULL.
5722  *
5723  * \retval      a file descriptor on success.
5724  * \retval      -errno on error.
5725  */
5726 int llapi_create_volatile_param(const char *directory, int mdt_idx,
5727                                 int open_flags, mode_t mode,
5728                                 const struct llapi_stripe_param *stripe_param)
5729 {
5730         char file_path[PATH_MAX];
5731         int saved_errno = errno;
5732         int fd;
5733         unsigned int rnumber;
5734         int rc;
5735
5736         do {
5737                 rnumber = random();
5738                 if (mdt_idx == -1)
5739                         rc = snprintf(file_path, sizeof(file_path),
5740                                       "%s/" LUSTRE_VOLATILE_HDR "::%.4X",
5741                                       directory, rnumber);
5742                 else
5743                         rc = snprintf(file_path, sizeof(file_path),
5744                                       "%s/" LUSTRE_VOLATILE_HDR ":%.4X:%.4X",
5745                                       directory, mdt_idx, rnumber);
5746
5747                 if (rc < 0 || rc >= sizeof(file_path))
5748                         return -ENAMETOOLONG;
5749
5750                 /*
5751                  * Either open O_WRONLY or O_RDWR, creating RDONLY
5752                  * is non-sensical here
5753                  */
5754                 if ((open_flags & O_ACCMODE) == O_RDONLY)
5755                         open_flags = O_RDWR | (open_flags & ~O_ACCMODE);
5756
5757                 open_flags |= O_CREAT | O_EXCL | O_NOFOLLOW;
5758
5759                 if (stripe_param != NULL) {
5760                         fd = llapi_file_open_param(file_path, open_flags,
5761                                                    mode, stripe_param);
5762                         if (fd < 0)
5763                                 rc = fd;
5764                 } else {
5765                         fd = open(file_path, open_flags, mode);
5766                         if (fd < 0)
5767                                 rc = -errno;
5768                 }
5769         } while (fd < 0 && rc == -EEXIST);
5770
5771         if (fd < 0) {
5772                 llapi_error(LLAPI_MSG_ERROR, rc,
5773                             "Cannot create volatile file '%s' in '%s'",
5774                             file_path + strlen(directory) + 1 +
5775                             LUSTRE_VOLATILE_HDR_LEN,
5776                             directory);
5777                 return rc;
5778         }
5779
5780         /*
5781          * Unlink file in case this wasn't a Lustre filesystem and the magic
5782          * volatile filename wasn't handled as intended. The effect is the
5783          * same. If volatile open was supported then we expect unlink() to
5784          * return -ENOENT.
5785          */
5786         (void)unlink(file_path);
5787
5788         /*
5789          * Since we are returning successfully we restore errno (and
5790          * mask out possible EEXIST from open() and ENOENT from unlink().
5791          */
5792         errno = saved_errno;
5793
5794         return fd;
5795 }
5796
5797 /*
5798  * Create a file without any name open it for read/write
5799  *
5800  * - file is created as if it were a standard file in the given \a directory
5801  * - file does not appear in \a directory and mtime does not change because
5802  *   the filename is handled specially by the Lustre MDS.
5803  * - file is removed at final close
5804  * - file modes are rw------- since it doesn't make sense to have a read-only
5805  *   or write-only file that cannot be opened again.
5806  * - if user wants another mode it must use fchmod() on the open file, no
5807  *   security problems arise because it cannot be opened by another process.
5808  *
5809  * \param[in]   directory       directory from which to inherit layout/MDT idx
5810  * \param[in]   idx             MDT index on which the file is created,
5811  *                              \a idx == -1 means no specific MDT is requested
5812  * \param[in]   open_flags      standard open(2) flags
5813  *
5814  * \retval      a file descriptor on success.
5815  * \retval      -errno on error.
5816  */
5817 int llapi_create_volatile_idx(const char *directory, int mdt_idx,
5818                               int open_flags)
5819 {
5820         return llapi_create_volatile_param(directory, mdt_idx, open_flags,
5821                                            S_IRUSR | S_IWUSR, NULL);
5822 }
5823
5824 /**
5825  * Swap the layouts between 2 file descriptors
5826  * the 2 files must be open for writing
5827  * first fd received the ioctl, second fd is passed as arg
5828  * this is assymetric but avoid use of root path for ioctl
5829  */
5830 int llapi_fswap_layouts_grouplock(int fd1, int fd2, __u64 dv1, __u64 dv2,
5831                                   int gid, __u64 flags)
5832 {
5833         struct lustre_swap_layouts      lsl;
5834         struct stat                     st1;
5835         struct stat                     st2;
5836         int                             rc;
5837
5838         if (flags & (SWAP_LAYOUTS_KEEP_ATIME | SWAP_LAYOUTS_KEEP_MTIME)) {
5839                 rc = fstat(fd1, &st1);
5840                 if (rc < 0)
5841                         return -errno;
5842
5843                 rc = fstat(fd2, &st2);
5844                 if (rc < 0)
5845                         return -errno;
5846         }
5847         lsl.sl_fd = fd2;
5848         lsl.sl_flags = flags;
5849         lsl.sl_gid = gid;
5850         lsl.sl_dv1 = dv1;
5851         lsl.sl_dv2 = dv2;
5852         rc = ioctl(fd1, LL_IOC_LOV_SWAP_LAYOUTS, &lsl);
5853         if (rc < 0)
5854                 return -errno;
5855
5856         if (flags & (SWAP_LAYOUTS_KEEP_ATIME | SWAP_LAYOUTS_KEEP_MTIME)) {
5857                 struct timeval  tv1[2];
5858                 struct timeval  tv2[2];
5859
5860                 memset(tv1, 0, sizeof(tv1));
5861                 memset(tv2, 0, sizeof(tv2));
5862
5863                 if (flags & SWAP_LAYOUTS_KEEP_ATIME) {
5864                         tv1[0].tv_sec = st1.st_atime;
5865                         tv2[0].tv_sec = st2.st_atime;
5866                 } else {
5867                         tv1[0].tv_sec = st2.st_atime;
5868                         tv2[0].tv_sec = st1.st_atime;
5869                 }
5870
5871                 if (flags & SWAP_LAYOUTS_KEEP_MTIME) {
5872                         tv1[1].tv_sec = st1.st_mtime;
5873                         tv2[1].tv_sec = st2.st_mtime;
5874                 } else {
5875                         tv1[1].tv_sec = st2.st_mtime;
5876                         tv2[1].tv_sec = st1.st_mtime;
5877                 }
5878
5879                 rc = futimes(fd1, tv1);
5880                 if (rc < 0)
5881                         return -errno;
5882
5883                 rc = futimes(fd2, tv2);
5884                 if (rc < 0)
5885                         return -errno;
5886         }
5887
5888         return 0;
5889 }
5890
5891 int llapi_fswap_layouts(int fd1, int fd2, __u64 dv1, __u64 dv2, __u64 flags)
5892 {
5893         int     rc;
5894         int     grp_id;
5895
5896         do
5897                 grp_id = random();
5898         while (grp_id == 0);
5899
5900         rc = llapi_fswap_layouts_grouplock(fd1, fd2, dv1, dv2, grp_id, flags);
5901         if (rc < 0)
5902                 return rc;
5903
5904         return 0;
5905 }
5906
5907 /**
5908  * Swap the layouts between 2 files
5909  * the 2 files are open in write
5910  */
5911 int llapi_swap_layouts(const char *path1, const char *path2,
5912                        __u64 dv1, __u64 dv2, __u64 flags)
5913 {
5914         int     fd1, fd2, rc;
5915
5916         fd1 = open(path1, O_WRONLY | O_LOV_DELAY_CREATE);
5917         if (fd1 < 0) {
5918                 rc = -errno;
5919                 llapi_error(LLAPI_MSG_ERROR, rc,
5920                             "error: cannot open '%s' for write", path1);
5921                 goto out;
5922         }
5923
5924         fd2 = open(path2, O_WRONLY | O_LOV_DELAY_CREATE);
5925         if (fd2 < 0) {
5926                 rc = -errno;
5927                 llapi_error(LLAPI_MSG_ERROR, rc,
5928                             "error: cannot open '%s' for write", path2);
5929                 goto out_close;
5930         }
5931
5932         rc = llapi_fswap_layouts(fd1, fd2, dv1, dv2, flags);
5933         if (rc < 0)
5934                 llapi_error(LLAPI_MSG_ERROR, rc,
5935                             "error: cannot swap layout between '%s' and '%s'",
5936                             path1, path2);
5937
5938         close(fd2);
5939 out_close:
5940         close(fd1);
5941 out:
5942         return rc;
5943 }
5944
5945 /**
5946  * Attempt to open a file with Lustre file identifier \a fid
5947  * and return an open file descriptor.
5948  *
5949  * \param[in] lustre_dir        path within Lustre filesystem containing \a fid
5950  * \param[in] fid               Lustre file identifier of file to open
5951  * \param[in] flags             open() flags
5952  *
5953  * \retval                      non-negative file descriptor on successful open
5954  * \retval                      -1 if an error occurred
5955  */
5956 int llapi_open_by_fid(const char *lustre_dir, const struct lu_fid *fid,
5957                       int flags)
5958 {
5959         char mntdir[PATH_MAX];
5960         char path[PATH_MAX + 64];
5961         int rc;
5962
5963         rc = llapi_search_mounts(lustre_dir, 0, mntdir, NULL);
5964         if (rc != 0)
5965                 return -1;
5966
5967         snprintf(path, sizeof(path), "%s/.lustre/fid/"DFID, mntdir, PFID(fid));
5968         return open(path, flags);
5969 }
5970
5971 /**
5972  * Take group lock.
5973  *
5974  * \param fd   File to lock.
5975  * \param gid  Group Identifier.
5976  *
5977  * \retval 0 on success.
5978  * \retval -errno on failure.
5979  */
5980 int llapi_group_lock(int fd, int gid)
5981 {
5982         int rc;
5983
5984         rc = ioctl(fd, LL_IOC_GROUP_LOCK, gid);
5985         if (rc < 0) {
5986                 rc = -errno;
5987                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot get group lock");
5988         }
5989         return rc;
5990 }
5991
5992 /**
5993  * Put group lock.
5994  *
5995  * \param fd   File to unlock.
5996  * \param gid  Group Identifier.
5997  *
5998  * \retval 0 on success.
5999  * \retval -errno on failure.
6000  */
6001 int llapi_group_unlock(int fd, int gid)
6002 {
6003         int rc;
6004
6005         rc = ioctl(fd, LL_IOC_GROUP_UNLOCK, gid);
6006         if (rc < 0) {
6007                 rc = -errno;
6008                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot put group lock");
6009         }
6010         return rc;
6011 }