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