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