Whamcloud - gitweb
LU-14459 mdt: support fixed directory layout
[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                 if (flags & LMV_HASH_FLAG_FIXED)
3323                         llapi_printf(LLAPI_MSG_NORMAL, ",fixed");
3324                 if (flags & ~LMV_HASH_FLAG_KNOWN)
3325                         llapi_printf(LLAPI_MSG_NORMAL, ",unknown_%04x",
3326                                      flags & ~LMV_HASH_FLAG_KNOWN);
3327
3328                 if (verbose & VERBOSE_HASH_TYPE && !yaml)
3329                         separator = " ";
3330                 else
3331                         separator = "\n";
3332         }
3333
3334         if ((verbose & VERBOSE_INHERIT) && lum->lum_magic == LMV_USER_MAGIC) {
3335                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3336                 if (verbose & ~VERBOSE_INHERIT)
3337                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_max_inherit: ");
3338                 if (lum->lum_max_inherit == LMV_INHERIT_UNLIMITED)
3339                         llapi_printf(LLAPI_MSG_NORMAL, "-1");
3340                 else if (lum->lum_max_inherit == LMV_INHERIT_NONE)
3341                         llapi_printf(LLAPI_MSG_NORMAL, "0");
3342                 else
3343                         llapi_printf(LLAPI_MSG_NORMAL, "%hhu",
3344                                      lum->lum_max_inherit);
3345                 if (verbose & VERBOSE_INHERIT && !yaml)
3346                         separator = " ";
3347                 else
3348                         separator = "\n";
3349         }
3350
3351         if ((verbose & VERBOSE_INHERIT_RR) &&
3352             lum->lum_magic == LMV_USER_MAGIC &&
3353             lum->lum_stripe_offset == LMV_OFFSET_DEFAULT) {
3354                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3355                 if (verbose & ~VERBOSE_INHERIT_RR)
3356                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_max_inherit_rr: ");
3357                 if (lum->lum_max_inherit_rr == LMV_INHERIT_RR_UNLIMITED)
3358                         llapi_printf(LLAPI_MSG_NORMAL, "-1");
3359                 else if (lum->lum_max_inherit_rr == LMV_INHERIT_RR_NONE)
3360                         llapi_printf(LLAPI_MSG_NORMAL, "0");
3361                 else
3362                         llapi_printf(LLAPI_MSG_NORMAL, "%hhu",
3363                                      lum->lum_max_inherit_rr);
3364                 if (verbose & VERBOSE_INHERIT_RR && !yaml)
3365                         separator = " ";
3366                 else
3367                         separator = "\n";
3368         }
3369
3370         separator = "\n";
3371
3372         if (verbose & VERBOSE_OBJID && lum->lum_magic != LMV_USER_MAGIC) {
3373                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3374                 if (lum->lum_stripe_count > 0)
3375                         llapi_printf(LLAPI_MSG_NORMAL,
3376                                      "mdtidx\t\t FID[seq:oid:ver]\n");
3377                 for (i = 0; i < lum->lum_stripe_count; i++) {
3378                         int idx = objects[i].lum_mds;
3379                         struct lu_fid *fid = &objects[i].lum_fid;
3380
3381                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
3382                                 llapi_printf(LLAPI_MSG_NORMAL,
3383                                              "%6u\t\t "DFID"\t\t%s\n",
3384                                             idx, PFID(fid),
3385                                             obdindex == idx ? " *" : "");
3386                 }
3387         }
3388
3389         if ((verbose & VERBOSE_POOL) && pool_name != NULL &&
3390              pool_name[0] != '\0') {
3391                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3392                 if (verbose & ~VERBOSE_POOL)
3393                         llapi_printf(LLAPI_MSG_NORMAL, "%slmv_pool:           ",
3394                                      prefix);
3395                 llapi_printf(LLAPI_MSG_NORMAL, "%s%c ", pool_name, ' ');
3396                 separator = "\n";
3397         }
3398
3399         if (!(verbose & VERBOSE_OBJID) || lum->lum_magic == LMV_USER_MAGIC)
3400                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
3401 }
3402
3403 static void lov_dump_comp_v1_header(struct find_param *param, char *path,
3404                                     enum lov_dump_flags flags)
3405 {
3406         struct lov_comp_md_v1 *comp_v1 = (void *)&param->fp_lmd->lmd_lmm;
3407         int depth = param->fp_max_depth;
3408         enum llapi_layout_verbose verbose = param->fp_verbose;
3409         bool yaml = flags & LDF_YAML;
3410
3411         if (depth && path && ((verbose != VERBOSE_OBJID) ||
3412                               !(flags & LDF_IS_DIR)) && !yaml)
3413                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
3414
3415         if (verbose & VERBOSE_DETAIL) {
3416                 llapi_printf(LLAPI_MSG_NORMAL, "composite_header:\n");
3417                 llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_magic:         0x%08X\n",
3418                              " ", comp_v1->lcm_magic);
3419                 llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_size:          %u\n",
3420                              " ", comp_v1->lcm_size);
3421                 if (flags & LDF_IS_DIR)
3422                         llapi_printf(LLAPI_MSG_NORMAL,
3423                                      "%2slcm_flags:         %s\n", " ",
3424                                      comp_v1->lcm_mirror_count > 0 ?
3425                                                         "mirrored" : "");
3426                 else
3427                         llapi_printf(LLAPI_MSG_NORMAL,
3428                                      "%2slcm_flags:         %s\n", " ",
3429                                 llapi_layout_flags_string(comp_v1->lcm_flags));
3430         }
3431
3432         if (verbose & VERBOSE_GENERATION) {
3433                 if (verbose & ~VERBOSE_GENERATION)
3434                         llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_layout_gen:    ",
3435                                      " ");
3436                 llapi_printf(LLAPI_MSG_NORMAL, "%u\n", comp_v1->lcm_layout_gen);
3437         }
3438
3439         if (verbose & VERBOSE_MIRROR_COUNT) {
3440                 if (verbose & ~VERBOSE_MIRROR_COUNT)
3441                         llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_mirror_count:  ",
3442                                      " ");
3443                 llapi_printf(LLAPI_MSG_NORMAL, "%u\n",
3444                              comp_v1->lcm_magic == LOV_USER_MAGIC_COMP_V1 ?
3445                              comp_v1->lcm_mirror_count + 1 : 1);
3446         }
3447
3448         if (verbose & VERBOSE_COMP_COUNT) {
3449                 if (verbose & ~VERBOSE_COMP_COUNT)
3450                         llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_entry_count:   ",
3451                                      " ");
3452                 llapi_printf(LLAPI_MSG_NORMAL, "%u\n",
3453                              comp_v1->lcm_magic == LOV_USER_MAGIC_COMP_V1 ?
3454                              comp_v1->lcm_entry_count : 0);
3455         }
3456
3457         if (verbose & VERBOSE_DETAIL && !yaml)
3458                 llapi_printf(LLAPI_MSG_NORMAL, "components:\n");
3459 }
3460
3461 static void lcme_flags2str(__u32 comp_flags)
3462 {
3463         bool found = false;
3464         int i = 0;
3465
3466         if (!comp_flags) {
3467                 llapi_printf(LLAPI_MSG_NORMAL, "0");
3468                 return;
3469         }
3470         for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
3471                 if (comp_flags & comp_flags_table[i].cfn_flag) {
3472                         if (found)
3473                                 llapi_printf(LLAPI_MSG_NORMAL, ",");
3474                         llapi_printf(LLAPI_MSG_NORMAL, "%s",
3475                                      comp_flags_table[i].cfn_name);
3476                         comp_flags &= ~comp_flags_table[i].cfn_flag;
3477                         found = true;
3478                 }
3479         }
3480         if (comp_flags) {
3481                 if (found)
3482                         llapi_printf(LLAPI_MSG_NORMAL, ",");
3483                 llapi_printf(LLAPI_MSG_NORMAL, "%#x", comp_flags);
3484         }
3485 }
3486
3487 static void lov_dump_comp_v1_entry(struct find_param *param,
3488                                    enum lov_dump_flags flags, int index)
3489 {
3490         struct lov_comp_md_v1 *comp_v1 = (void *)&param->fp_lmd->lmd_lmm;
3491         struct lov_comp_md_entry_v1 *entry;
3492         char *separator = "";
3493         enum llapi_layout_verbose verbose = param->fp_verbose;
3494         bool yaml = flags & LDF_YAML;
3495
3496         entry = &comp_v1->lcm_entries[index];
3497
3498         if (yaml)
3499                 llapi_printf(LLAPI_MSG_NORMAL, "%2scomponent%d:\n", " ", index);
3500
3501         if (verbose & VERBOSE_COMP_ID) {
3502                 if (verbose & VERBOSE_DETAIL && !yaml)
3503                         llapi_printf(LLAPI_MSG_NORMAL,
3504                                      "%slcme_id:             ", "  - ");
3505                 else if (verbose & ~VERBOSE_COMP_ID)
3506                         llapi_printf(LLAPI_MSG_NORMAL,
3507                                      "%4slcme_id:             ", " ");
3508                 if (entry->lcme_id != LCME_ID_INVAL)
3509                         llapi_printf(LLAPI_MSG_NORMAL, "%u", entry->lcme_id);
3510                 else
3511                         llapi_printf(LLAPI_MSG_NORMAL, "N/A");
3512                 separator = "\n";
3513         }
3514
3515         if (verbose & VERBOSE_MIRROR_ID) {
3516                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3517                 if (verbose & ~VERBOSE_MIRROR_ID)
3518                         llapi_printf(LLAPI_MSG_NORMAL,
3519                                      "%4slcme_mirror_id:      ", " ");
3520                 if (entry->lcme_id != LCME_ID_INVAL)
3521                         llapi_printf(LLAPI_MSG_NORMAL, "%u",
3522                                      mirror_id_of(entry->lcme_id));
3523                 else
3524                         llapi_printf(LLAPI_MSG_NORMAL, "N/A");
3525                 separator = "\n";
3526         }
3527
3528         if (verbose & VERBOSE_COMP_FLAGS) {
3529                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3530                 if (verbose & ~VERBOSE_COMP_FLAGS)
3531                         llapi_printf(LLAPI_MSG_NORMAL,
3532                                      "%4slcme_flags:          ", " ");
3533                 lcme_flags2str(entry->lcme_flags);
3534                 separator = "\n";
3535         }
3536         /* print snapshot timestamp if its a nosync comp */
3537         if ((verbose & VERBOSE_COMP_FLAGS) &&
3538             (entry->lcme_flags & LCME_FL_NOSYNC)) {
3539                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3540                 if (verbose & ~VERBOSE_COMP_FLAGS)
3541                         llapi_printf(LLAPI_MSG_NORMAL,
3542                                      "%4slcme_timestamp:      ", " ");
3543                 if (yaml) {
3544                         llapi_printf(LLAPI_MSG_NORMAL, "%llu",
3545                                      (unsigned long long)entry->lcme_timestamp);
3546                 } else {
3547                         time_t stamp = entry->lcme_timestamp;
3548                         char *date_str = asctime(localtime(&stamp));
3549
3550                         date_str[strlen(date_str) - 1] = '\0';
3551                         llapi_printf(LLAPI_MSG_NORMAL, "'%s'", date_str);
3552                 }
3553
3554                 separator = "\n";
3555         }
3556
3557         if (verbose & VERBOSE_COMP_START) {
3558                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3559                 if (verbose & ~VERBOSE_COMP_START)
3560                         llapi_printf(LLAPI_MSG_NORMAL,
3561                                      "%4slcme_extent.e_start: ", " ");
3562                 llapi_printf(LLAPI_MSG_NORMAL, "%llu",
3563                              (unsigned long long)entry->lcme_extent.e_start);
3564                 separator = "\n";
3565         }
3566
3567         if (verbose & VERBOSE_COMP_END) {
3568                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3569                 if (verbose & ~VERBOSE_COMP_END)
3570                         llapi_printf(LLAPI_MSG_NORMAL,
3571                                      "%4slcme_extent.e_end:   ", " ");
3572                 if (entry->lcme_extent.e_end == LUSTRE_EOF)
3573                         llapi_printf(LLAPI_MSG_NORMAL, "%s", "EOF");
3574                 else
3575                         llapi_printf(LLAPI_MSG_NORMAL, "%llu",
3576                                      (unsigned long long)entry->lcme_extent.e_end);
3577                 separator = "\n";
3578         }
3579
3580         if (yaml) {
3581                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3582                 llapi_printf(LLAPI_MSG_NORMAL, "%4ssub_layout:\n", " ");
3583         } else if (verbose & VERBOSE_DETAIL) {
3584                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3585                 llapi_printf(LLAPI_MSG_NORMAL, "%4slcme_offset:         %u\n",
3586                              " ", entry->lcme_offset);
3587                 llapi_printf(LLAPI_MSG_NORMAL, "%4slcme_size:           %u\n",
3588                              " ", entry->lcme_size);
3589                 llapi_printf(LLAPI_MSG_NORMAL, "%4ssub_layout:\n", " ");
3590         } else {
3591                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3592         }
3593 }
3594
3595 /*
3596  * Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
3597  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
3598  *
3599  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
3600  * The table below gives the answers for the specified parameters (value and
3601  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
3602  * --------------------------------------
3603  * 1 | file > limit; sign > 0 | -1 / -1 |
3604  * 2 | file = limit; sign > 0 | -1 / -1 |
3605  * 3 | file < limit; sign > 0 |  ? /  1 |
3606  * 4 | file > limit; sign = 0 | -1 / -1 |
3607  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
3608  * 6 | file < limit; sign = 0 |  ? / -1 |
3609  * 7 | file > limit; sign < 0 |  1 /  1 |
3610  * 8 | file = limit; sign < 0 |  ? / -1 |
3611  * 9 | file < limit; sign < 0 |  ? / -1 |
3612  * --------------------------------------
3613  * Note: 5th actually means that the value is within the interval
3614  * (limit - margin, limit].
3615  */
3616 static int find_value_cmp(unsigned long long file, unsigned long long limit,
3617                           int sign, int negopt, unsigned long long margin,
3618                           bool mds)
3619 {
3620         int ret = -1;
3621
3622         if (sign > 0) {
3623                 /* Drop the fraction of margin (of days or size). */
3624                 if (file + margin <= limit)
3625                         ret = mds ? 0 : 1;
3626         } else if (sign == 0) {
3627                 if (file <= limit && file + margin > limit)
3628                         ret = mds ? 0 : 1;
3629                 else if (file + margin <= limit)
3630                         ret = mds ? 0 : -1;
3631         } else if (sign < 0) {
3632                 if (file > limit)
3633                         ret = 1;
3634                 else if (mds)
3635                         ret = 0;
3636         }
3637
3638         return negopt ? ~ret + 1 : ret;
3639 }
3640
3641 static inline struct lov_user_md *
3642 lov_comp_entry(struct lov_comp_md_v1 *comp_v1, int ent_idx)
3643 {
3644         return (struct lov_user_md *)((char *)comp_v1 +
3645                         comp_v1->lcm_entries[ent_idx].lcme_offset);
3646 }
3647
3648 static inline struct lov_user_ost_data_v1 *
3649 lov_v1v3_objects(struct lov_user_md *v1)
3650 {
3651         if (v1->lmm_magic == LOV_USER_MAGIC_V3)
3652                 return ((struct lov_user_md_v3 *)v1)->lmm_objects;
3653         else
3654                 return v1->lmm_objects;
3655 }
3656
3657 static inline void
3658 lov_v1v3_pool_name(struct lov_user_md *v1, char *pool_name)
3659 {
3660         if (v1->lmm_magic == LOV_USER_MAGIC_V3)
3661                 snprintf(pool_name, LOV_MAXPOOLNAME, "%s",
3662                          ((struct lov_user_md_v3 *)v1)->lmm_pool_name);
3663         else
3664                 pool_name[0] = '\0';
3665 }
3666
3667 static inline bool
3668 print_last_init_comp(struct find_param *param)
3669 {
3670         /* print all component info */
3671         if ((param->fp_verbose & VERBOSE_DEFAULT) == VERBOSE_DEFAULT)
3672                 return false;
3673
3674         /* print specific component info */
3675         if (param->fp_check_comp_id || param->fp_check_comp_flags ||
3676             param->fp_check_comp_start || param->fp_check_comp_end ||
3677             param->fp_check_mirror_id || param->fp_check_mirror_index)
3678                 return false;
3679
3680         return true;
3681 }
3682
3683 static int find_comp_end_cmp(unsigned long long end, struct find_param *param)
3684 {
3685         int match;
3686
3687         if (param->fp_comp_end == LUSTRE_EOF) {
3688                 if (param->fp_comp_end_sign == 0) /* equal to EOF */
3689                         match = end == LUSTRE_EOF ? 1 : -1;
3690                 else if (param->fp_comp_end_sign > 0) /* at most EOF */
3691                         match = end == LUSTRE_EOF ? -1 : 1;
3692                 else /* at least EOF */
3693                         match = -1;
3694                 if (param->fp_exclude_comp_end)
3695                         match = ~match + 1;
3696         } else {
3697                 unsigned long long margin;
3698
3699                 margin = end == LUSTRE_EOF ? 0 : param->fp_comp_end_units;
3700                 match = find_value_cmp(end, param->fp_comp_end,
3701                                        param->fp_comp_end_sign,
3702                                        param->fp_exclude_comp_end, margin, 0);
3703         }
3704
3705         return match;
3706 }
3707
3708 /**
3709  * An example of "getstripe -v" for a two components PFL file:
3710  *
3711  * composite_header:
3712  * lcm_magic:       0x0BD60BD0
3713  * lcm_size:        264
3714  * lcm_flags:       0
3715  * lcm_layout_gen:  2
3716  * lcm_entry_count: 2
3717  * components:
3718  * - lcme_id:             1
3719  *   lcme_flags:          0x10
3720  *   lcme_extent.e_start: 0
3721  *   lcme_extent.e_end:   1048576
3722  *   lcme_offset:         128
3723  *   lcme_size:           56
3724  *   sub_layout:
3725  *     lmm_magic:         0x0BD10BD0
3726  *     lmm_seq:           0x200000401
3727  *     lmm_object_id:     0x1
3728  *     lmm_fid:           [0x200000401:0x1:0x0]
3729  *     lmm_stripe_count:  1
3730  *     lmm_stripe_size:   1048576
3731  *     lmm_pattern:       raid0
3732  *     lmm_layout_gen:    0
3733  *     lmm_stripe_offset: 0
3734  *     lmm_objects:
3735  *     - 0: { l_ost_idx: 0, l_fid: [0x100000000:0x2:0x0] }
3736  *
3737  * - lcme_id:             2
3738  *   lcme_flags:          0x10
3739  *   lcme_extent.e_start: 1048576
3740  *   lcme_extent.e_end:   EOF
3741  *   lcme_offset:         184
3742  *   lcme_size:           80
3743  *     sub_layout:
3744  *     lmm_magic:         0x0BD10BD0
3745  *     lmm_seq:           0x200000401
3746  *     lmm_object_id:     0x1
3747  *     lmm_fid:           [0x200000401:0x1:0x0]
3748  *     lmm_stripe_count:  2
3749  *     lmm_stripe_size:   1048576
3750  *     lmm_pattern:       raid0
3751  *     lmm_layout_gen:    0
3752  *     lmm_stripe_offset: 1
3753  *     lmm_objects:
3754  *     - 0: { l_ost_idx: 1, l_fid: [0x100010000:0x2:0x0] }
3755  *     - 1: { l_ost_idx: 0, l_fid: [0x100000000:0x3:0x0] }
3756  */
3757 static void lov_dump_comp_v1(struct find_param *param, char *path,
3758                              enum lov_dump_flags flags)
3759 {
3760         struct lov_comp_md_entry_v1 *entry;
3761         struct lov_user_ost_data_v1 *objects;
3762         struct lov_comp_md_v1 *comp_v1 = (void *)&param->fp_lmd->lmd_lmm;
3763         struct lov_user_md_v1 *v1;
3764         char pool_name[LOV_MAXPOOLNAME + 1];
3765         int obdindex = param->fp_obd_index;
3766         int i, j, match, ext;
3767         bool obdstripe = false;
3768         __u16 mirror_index = 0;
3769         __u16 mirror_id = 0;
3770
3771         if (obdindex != OBD_NOT_FOUND) {
3772                 for (i = 0; !(flags & LDF_IS_DIR) && !obdstripe &&
3773                             i < comp_v1->lcm_entry_count; i++) {
3774                         if (!(comp_v1->lcm_entries[i].lcme_flags &
3775                               LCME_FL_INIT))
3776                                 continue;
3777
3778                         v1 = lov_comp_entry(comp_v1, i);
3779                         objects = lov_v1v3_objects(v1);
3780
3781                         for (j = 0; j < v1->lmm_stripe_count; j++) {
3782                                 if (obdindex == objects[j].l_ost_idx) {
3783                                         obdstripe = true;
3784                                         break;
3785                                 }
3786                         }
3787                 }
3788         } else {
3789                 obdstripe = true;
3790         }
3791
3792         if (!obdstripe)
3793                 return;
3794
3795         lov_dump_comp_v1_header(param, path, flags);
3796
3797         flags |= LDF_INDENT;
3798
3799         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
3800                 entry = &comp_v1->lcm_entries[i];
3801
3802                 if (param->fp_check_comp_flags) {
3803                         if (((param->fp_comp_flags & entry->lcme_flags) !=
3804                              param->fp_comp_flags) ||
3805                             (param->fp_comp_neg_flags & entry->lcme_flags))
3806                                 continue;
3807                 }
3808
3809                 if (param->fp_check_comp_id &&
3810                     param->fp_comp_id != entry->lcme_id)
3811                         continue;
3812
3813                 if (param->fp_check_comp_start) {
3814                         match = find_value_cmp(entry->lcme_extent.e_start,
3815                                                param->fp_comp_start,
3816                                                param->fp_comp_start_sign,
3817                                                0,
3818                                                param->fp_comp_start_units, 0);
3819                         if (match == -1)
3820                                 continue;
3821                 }
3822
3823                 if (param->fp_check_comp_end) {
3824                         match = find_comp_end_cmp(entry->lcme_extent.e_end,
3825                                                   param);
3826                         if (match == -1)
3827                                 continue;
3828                 }
3829
3830                 if (param->fp_check_mirror_index) {
3831                         if (mirror_id != mirror_id_of(entry->lcme_id)) {
3832                                 mirror_index++;
3833                                 mirror_id = mirror_id_of(entry->lcme_id);
3834                         }
3835
3836                         match = find_value_cmp(mirror_index,
3837                                                param->fp_mirror_index,
3838                                                param->fp_mirror_index_sign,
3839                                                param->fp_exclude_mirror_index,
3840                                                1, 0);
3841                         if (match == -1)
3842                                 continue;
3843                 } else if (param->fp_check_mirror_id) {
3844                         if (mirror_id != mirror_id_of(entry->lcme_id))
3845                                 mirror_id = mirror_id_of(entry->lcme_id);
3846
3847                         match = find_value_cmp(mirror_id,
3848                                                param->fp_mirror_id,
3849                                                param->fp_mirror_id_sign,
3850                                                param->fp_exclude_mirror_id,
3851                                                1, 0);
3852                         if (match == -1)
3853                                 continue;
3854                 }
3855
3856                 if (print_last_init_comp(param)) {
3857                         /**
3858                          * if part of stripe info is needed, we'd print only
3859                          * the last instantiated component info.
3860                          */
3861                         if (entry->lcme_flags & LCME_FL_INIT)
3862                                 continue;
3863
3864                         if (param->fp_verbose & VERBOSE_EXT_SIZE) {
3865                                 if (entry->lcme_flags & LCME_FL_EXTENSION)
3866                                         /* moved back below */
3867                                         i++;
3868                                 else
3869                                         continue;
3870                         }
3871                         break;
3872                 }
3873
3874                 if (entry->lcme_flags & LCME_FL_INIT) {
3875                         if (obdindex != OBD_NOT_FOUND) {
3876                                 flags |= LDF_SKIP_OBJS;
3877                                 v1 = lov_comp_entry(comp_v1, i);
3878                                 objects = lov_v1v3_objects(v1);
3879
3880                                 for (j = 0; j < v1->lmm_stripe_count; j++) {
3881                                         if (obdindex == objects[j].l_ost_idx) {
3882                                                 flags &= ~LDF_SKIP_OBJS;
3883                                                 break;
3884                                         }
3885                                 }
3886                         } else {
3887                                 flags &= ~LDF_SKIP_OBJS;
3888                         }
3889                 } else {
3890                         flags |= LDF_SKIP_OBJS;
3891                 }
3892
3893                 if (obdindex != OBD_NOT_FOUND && (flags & LDF_SKIP_OBJS))
3894                         continue;
3895                 lov_dump_comp_v1_entry(param, flags, i);
3896
3897                 v1 = lov_comp_entry(comp_v1, i);
3898                 objects = lov_v1v3_objects(v1);
3899                 lov_v1v3_pool_name(v1, pool_name);
3900
3901                 ext = entry->lcme_flags & LCME_FL_EXTENSION ? LDF_EXTENSION : 0;
3902                 lov_dump_user_lmm_v1v3(v1, pool_name, objects, path, obdindex,
3903                                        param->fp_max_depth, param->fp_verbose,
3904                                        flags | ext);
3905         }
3906         if (print_last_init_comp(param)) {
3907                 /**
3908                  * directory layout contains only layout template, print the
3909                  * last component.
3910                  */
3911                 if (i == 0)
3912                         i = comp_v1->lcm_entry_count - 1;
3913                 else
3914                         i--;
3915                 flags &= ~LDF_SKIP_OBJS;
3916
3917                 lov_dump_comp_v1_entry(param, flags, i);
3918
3919                 v1 = lov_comp_entry(comp_v1, i);
3920                 objects = lov_v1v3_objects(v1);
3921                 lov_v1v3_pool_name(v1, pool_name);
3922
3923                 entry = &comp_v1->lcm_entries[i];
3924                 ext = entry->lcme_flags & LCME_FL_EXTENSION ? LDF_EXTENSION : 0;
3925                 lov_dump_user_lmm_v1v3(v1, pool_name, objects, path, obdindex,
3926                                        param->fp_max_depth, param->fp_verbose,
3927                                        flags | ext);
3928         }
3929 }
3930
3931 #define VERBOSE_COMP_OPTS       (VERBOSE_COMP_COUNT | VERBOSE_COMP_ID | \
3932                                  VERBOSE_COMP_START | VERBOSE_COMP_END | \
3933                                  VERBOSE_COMP_FLAGS)
3934
3935 static inline bool has_any_comp_options(struct find_param *param)
3936 {
3937         enum llapi_layout_verbose verbose = param->fp_verbose;
3938
3939         if (param->fp_check_comp_id || param->fp_check_comp_count ||
3940             param->fp_check_comp_start || param->fp_check_comp_end ||
3941             param->fp_check_comp_flags)
3942                 return true;
3943
3944         /* show full layout information, not component specific */
3945         if ((verbose & ~VERBOSE_DETAIL) == VERBOSE_DEFAULT)
3946                 return false;
3947
3948         return verbose & VERBOSE_COMP_OPTS;
3949 }
3950
3951 struct lov_user_mds_data *lov_forge_comp_v1(struct lov_user_mds_data *orig,
3952                                             bool is_dir)
3953 {
3954         struct lov_user_md *lum = &orig->lmd_lmm;
3955         struct lov_user_mds_data *new;
3956         struct lov_comp_md_v1 *comp_v1;
3957         struct lov_comp_md_entry_v1 *ent;
3958         int lum_off = sizeof(*comp_v1) + sizeof(*ent);
3959         int lum_size = lov_user_md_size(is_dir ? 0 : lum->lmm_stripe_count,
3960                                         lum->lmm_magic);
3961
3962         new = malloc(offsetof(typeof(*new), lmd_lmm) + lum_off + lum_size);
3963         if (new == NULL) {
3964                 llapi_printf(LLAPI_MSG_NORMAL, "out of memory\n");
3965                 return new;
3966         }
3967
3968         memcpy(new, orig, sizeof(new->lmd_stx) + sizeof(new->lmd_flags)
3969                + sizeof(new->lmd_lmmsize));
3970
3971         comp_v1 = (struct lov_comp_md_v1 *)&new->lmd_lmm;
3972         comp_v1->lcm_magic = lum->lmm_magic;
3973         comp_v1->lcm_size = lum_off + lum_size;
3974         comp_v1->lcm_layout_gen = is_dir ? 0 : lum->lmm_layout_gen;
3975         comp_v1->lcm_flags = 0;
3976         comp_v1->lcm_entry_count = 1;
3977
3978         ent = &comp_v1->lcm_entries[0];
3979         ent->lcme_id = 0;
3980         ent->lcme_flags = is_dir ? 0 : LCME_FL_INIT;
3981         ent->lcme_extent.e_start = 0;
3982         ent->lcme_extent.e_end = LUSTRE_EOF;
3983         ent->lcme_offset = lum_off;
3984         ent->lcme_size = lum_size;
3985
3986         memcpy((char *)comp_v1 + lum_off, lum, lum_size);
3987
3988         return new;
3989 }
3990
3991 static void lov_dump_plain_user_lmm(struct find_param *param, char *path,
3992                                     enum lov_dump_flags flags)
3993 {
3994         __u32 magic = *(__u32 *)&param->fp_lmd->lmd_lmm;
3995
3996         if (has_any_comp_options(param)) {
3997                 struct lov_user_mds_data *new_lmd, *orig_lmd;
3998
3999                 orig_lmd = param->fp_lmd;
4000                 new_lmd = lov_forge_comp_v1(orig_lmd, flags & LDF_IS_DIR);
4001                 if (new_lmd != NULL) {
4002                         param->fp_lmd = new_lmd;
4003                         lov_dump_comp_v1(param, path, flags);
4004                         param->fp_lmd = orig_lmd;
4005                         free(new_lmd);
4006                 }
4007                 return;
4008         }
4009
4010         if (magic == LOV_USER_MAGIC_V1) {
4011                 lov_dump_user_lmm_v1v3(&param->fp_lmd->lmd_lmm, NULL,
4012                                        param->fp_lmd->lmd_lmm.lmm_objects,
4013                                        path, param->fp_obd_index,
4014                                        param->fp_max_depth, param->fp_verbose,
4015                                        flags);
4016         } else {
4017                 char pool_name[LOV_MAXPOOLNAME + 1];
4018                 struct lov_user_ost_data_v1 *objects;
4019                 struct lov_user_md_v3 *lmmv3 = (void *)&param->fp_lmd->lmd_lmm;
4020
4021                 snprintf(pool_name, sizeof(pool_name), "%s",
4022                          lmmv3->lmm_pool_name);
4023                 objects = lmmv3->lmm_objects;
4024                 lov_dump_user_lmm_v1v3(&param->fp_lmd->lmd_lmm, pool_name,
4025                                        objects, path, param->fp_obd_index,
4026                                        param->fp_max_depth, param->fp_verbose,
4027                                        flags);
4028         }
4029 }
4030
4031 static uint32_t check_foreign_type(uint32_t foreign_type)
4032 {
4033         uint32_t i;
4034
4035         for (i = 0; i < LU_FOREIGN_TYPE_UNKNOWN; i++) {
4036                 if (lu_foreign_types[i].lft_name == NULL)
4037                         break;
4038                 if (foreign_type == lu_foreign_types[i].lft_type)
4039                         return i;
4040         }
4041
4042         return LU_FOREIGN_TYPE_UNKNOWN;
4043 }
4044
4045 static void lov_dump_foreign_lmm(struct find_param *param, char *path,
4046                                  enum lov_dump_flags flags)
4047 {
4048         struct lov_foreign_md *lfm = (void *)&param->fp_lmd->lmd_lmm;
4049         bool yaml = flags & LDF_YAML;
4050
4051         if (!yaml && param->fp_depth && path)
4052                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
4053
4054         if (param->fp_verbose & VERBOSE_DETAIL) {
4055                 uint32_t type = check_foreign_type(lfm->lfm_type);
4056
4057                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_magic:         0x%08X\n",
4058                              lfm->lfm_magic);
4059                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_length:          %u\n",
4060                              lfm->lfm_length);
4061                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_type:          0x%08X",
4062                              lfm->lfm_type);
4063                 if (type < LU_FOREIGN_TYPE_UNKNOWN)
4064                         llapi_printf(LLAPI_MSG_NORMAL, " (%s)\n",
4065                                      lu_foreign_types[type].lft_name);
4066                 else
4067                         llapi_printf(LLAPI_MSG_NORMAL, " (unknown)\n");
4068
4069                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_flags:          0x%08X\n",
4070                              lfm->lfm_flags);
4071         }
4072         llapi_printf(LLAPI_MSG_NORMAL, "lfm_value:     '%.*s'\n",
4073                      lfm->lfm_length, lfm->lfm_value);
4074         llapi_printf(LLAPI_MSG_NORMAL, "\n");
4075 }
4076
4077 static void lmv_dump_foreign_lmm(struct find_param *param, char *path,
4078                                     enum lov_dump_flags flags)
4079 {
4080         struct lmv_foreign_md *lfm = (struct lmv_foreign_md *)param->fp_lmv_md;
4081         bool yaml = flags & LDF_YAML;
4082
4083         if (!yaml && param->fp_depth && path)
4084                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
4085
4086         if (param->fp_verbose & VERBOSE_DETAIL) {
4087                 uint32_t type = check_foreign_type(lfm->lfm_type);
4088
4089                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_magic:         0x%08X\n",
4090                              lfm->lfm_magic);
4091                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_length:          %u\n",
4092                              lfm->lfm_length);
4093                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_type:          0x%08X",
4094                              lfm->lfm_type);
4095                 if (type < LU_FOREIGN_TYPE_UNKNOWN)
4096                         llapi_printf(LLAPI_MSG_NORMAL, " (%s)\n",
4097                                      lu_foreign_types[type].lft_name);
4098                 else
4099                         llapi_printf(LLAPI_MSG_NORMAL, " (unknown)\n");
4100
4101                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_flags:          0x%08X\n",
4102                              lfm->lfm_flags);
4103         }
4104         llapi_printf(LLAPI_MSG_NORMAL, "lfm_value:     '%.*s'\n",
4105                      lfm->lfm_length, lfm->lfm_value);
4106         llapi_printf(LLAPI_MSG_NORMAL, "\n");
4107 }
4108
4109 static void llapi_lov_dump_user_lmm(struct find_param *param, char *path,
4110                                     enum lov_dump_flags flags)
4111 {
4112         __u32 magic;
4113
4114         if (param->fp_get_lmv || param->fp_get_default_lmv)
4115                 magic = (__u32)param->fp_lmv_md->lum_magic;
4116         else
4117                 magic = *(__u32 *)&param->fp_lmd->lmd_lmm; /* lum->lmm_magic */
4118
4119         if (param->fp_raw)
4120                 flags |= LDF_IS_RAW;
4121         if (param->fp_yaml)
4122                 flags |= LDF_YAML;
4123
4124         switch (magic) {
4125         case LOV_USER_MAGIC_V1:
4126         case LOV_USER_MAGIC_V3:
4127         case LOV_USER_MAGIC_SPECIFIC:
4128                 lov_dump_plain_user_lmm(param, path, flags);
4129                 break;
4130         case LOV_USER_MAGIC_FOREIGN:
4131                 lov_dump_foreign_lmm(param, path, flags);
4132                 break;
4133         case LMV_MAGIC_V1:
4134         case LMV_USER_MAGIC: {
4135                 char pool_name[LOV_MAXPOOLNAME + 1];
4136                 struct lmv_user_md *lum;
4137
4138                 lum = (struct lmv_user_md *)param->fp_lmv_md;
4139                 snprintf(pool_name, sizeof(pool_name), "%s",
4140                          lum->lum_pool_name);
4141                 lmv_dump_user_lmm(lum, pool_name, path, param->fp_obd_index,
4142                                   param->fp_max_depth, param->fp_verbose,
4143                                   flags);
4144                 break;
4145         }
4146         case LOV_USER_MAGIC_COMP_V1:
4147                 lov_dump_comp_v1(param, path, flags);
4148                 break;
4149         case LMV_MAGIC_FOREIGN:
4150                 lmv_dump_foreign_lmm(param, path, flags);
4151                 break;
4152         default:
4153                 llapi_printf(LLAPI_MSG_NORMAL,
4154                              "unknown lmm_magic:  %#x (expecting one of %#x %#x %#x %#x)\n",
4155                              *(__u32 *)&param->fp_lmd->lmd_lmm,
4156                              LOV_USER_MAGIC_V1, LOV_USER_MAGIC_V3,
4157                              LMV_USER_MAGIC, LMV_MAGIC_V1);
4158                 return;
4159         }
4160 }
4161
4162 static int llapi_file_get_stripe1(const char *path, struct lov_user_md *lum)
4163 {
4164         const char *fname;
4165         char *dname;
4166         int fd, rc = 0;
4167
4168         fname = strrchr(path, '/');
4169
4170         /* It should be a file (or other non-directory) */
4171         if (fname == NULL) {
4172                 dname = (char *)malloc(2);
4173                 if (dname == NULL)
4174                         return -ENOMEM;
4175                 strcpy(dname, ".");
4176                 fname = (char *)path;
4177         } else {
4178                 dname = (char *)malloc(fname - path + 1);
4179                 if (dname == NULL)
4180                         return -ENOMEM;
4181                 strncpy(dname, path, fname - path);
4182                 dname[fname - path] = '\0';
4183                 fname++;
4184         }
4185
4186         fd = open(dname, O_RDONLY | O_NONBLOCK);
4187         if (fd == -1) {
4188                 rc = -errno;
4189                 goto out_free;
4190         }
4191
4192         strcpy((char *)lum, fname);
4193         if (ioctl(fd, IOC_MDC_GETFILESTRIPE, (void *)lum) == -1)
4194                 rc = -errno;
4195
4196         if (close(fd) == -1 && rc == 0)
4197                 rc = -errno;
4198
4199 out_free:
4200         free(dname);
4201         return rc;
4202 }
4203
4204 int llapi_file_get_stripe(const char *path, struct lov_user_md *lum)
4205 {
4206         char *canon_path = NULL;
4207         int rc, rc2;
4208
4209         rc = llapi_file_get_stripe1(path, lum);
4210         if (!(rc == -ENOTTY || rc == -ENODATA))
4211                 goto out;
4212
4213         /* Handle failure due to symlinks by dereferencing path manually. */
4214         canon_path = canonicalize_file_name(path);
4215         if (canon_path == NULL)
4216                 goto out; /* Keep original rc. */
4217
4218         rc2 = llapi_file_get_stripe1(canon_path, lum);
4219         if (rc2 < 0)
4220                 goto out; /* Keep original rc. */
4221
4222         rc = 0;
4223 out:
4224         free(canon_path);
4225
4226         return rc;
4227 }
4228
4229 int llapi_file_lookup(int dirfd, const char *name)
4230 {
4231         struct obd_ioctl_data data = { 0 };
4232         char rawbuf[8192];
4233         char *buf = rawbuf;
4234         int rc;
4235
4236         if (dirfd < 0 || name == NULL)
4237                 return -EINVAL;
4238
4239         data.ioc_version = OBD_IOCTL_VERSION;
4240         data.ioc_len = sizeof(data);
4241         data.ioc_inlbuf1 = (char *)name;
4242         data.ioc_inllen1 = strlen(name) + 1;
4243
4244         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
4245         if (rc) {
4246                 llapi_error(LLAPI_MSG_ERROR, rc,
4247                             "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
4248                             name, rc);
4249                 return rc;
4250         }
4251
4252         rc = ioctl(dirfd, IOC_MDC_LOOKUP, buf);
4253         if (rc < 0)
4254                 rc = -errno;
4255         return rc;
4256 }
4257
4258 /*
4259  * Check if the file time matches all the given criteria (e.g. --atime +/-N).
4260  * Return -1 or 1 if file timestamp does not or does match the given criteria
4261  * correspondingly. Return 0 if the MDS time is being checked and there are
4262  * attributes on OSTs and it is not yet clear if the timespamp matches.
4263  *
4264  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
4265  * updated timestamps.
4266  */
4267 static int find_time_check(struct find_param *param, int mds)
4268 {
4269         struct lov_user_mds_data *lmd = param->fp_lmd;
4270         int rc = 1;
4271         int rc2;
4272
4273         /* Check if file is accepted. */
4274         if (param->fp_atime) {
4275                 rc2 = find_value_cmp(lmd->lmd_stx.stx_atime.tv_sec,
4276                                      param->fp_atime, param->fp_asign,
4277                                      param->fp_exclude_atime,
4278                                      param->fp_time_margin, mds);
4279                 if (rc2 < 0)
4280                         return rc2;
4281                 rc = rc2;
4282         }
4283
4284         if (param->fp_mtime) {
4285                 rc2 = find_value_cmp(lmd->lmd_stx.stx_mtime.tv_sec,
4286                                      param->fp_mtime, param->fp_msign,
4287                                      param->fp_exclude_mtime,
4288                                      param->fp_time_margin, mds);
4289                 if (rc2 < 0)
4290                         return rc2;
4291
4292                 /*
4293                  * If the previous check matches, but this one is not yet clear,
4294                  * we should return 0 to do an RPC on OSTs.
4295                  */
4296                 if (rc == 1)
4297                         rc = rc2;
4298         }
4299
4300         if (param->fp_ctime) {
4301                 rc2 = find_value_cmp(lmd->lmd_stx.stx_ctime.tv_sec,
4302                                      param->fp_ctime, param->fp_csign,
4303                                      param->fp_exclude_ctime,
4304                                      param->fp_time_margin, mds);
4305                 if (rc2 < 0)
4306                         return rc2;
4307
4308                 /*
4309                  * If the previous check matches, but this one is not yet clear,
4310                  * we should return 0 to do an RPC on OSTs.
4311                  */
4312                 if (rc == 1)
4313                         rc = rc2;
4314         }
4315
4316         return rc;
4317 }
4318
4319 static int find_newerxy_check(struct find_param *param, int mds, bool from_mdt)
4320 {
4321         struct lov_user_mds_data *lmd = param->fp_lmd;
4322         int i;
4323         int rc = 1;
4324         int rc2;
4325
4326         for (i = 0; i < 2; i++) {
4327                 /* Check if file is accepted. */
4328                 if (param->fp_newery[NEWERXY_ATIME][i]) {
4329                         rc2 = find_value_cmp(lmd->lmd_stx.stx_atime.tv_sec,
4330                                              param->fp_newery[NEWERXY_ATIME][i],
4331                                              -1, i, 0, mds);
4332                         if (rc2 < 0)
4333                                 return rc2;
4334                         rc = rc2;
4335                 }
4336
4337                 if (param->fp_newery[NEWERXY_MTIME][i]) {
4338                         rc2 = find_value_cmp(lmd->lmd_stx.stx_mtime.tv_sec,
4339                                              param->fp_newery[NEWERXY_MTIME][i],
4340                                              -1, i, 0, mds);
4341                         if (rc2 < 0)
4342                                 return rc2;
4343
4344                         /*
4345                          * If the previous check matches, but this one is not
4346                          * yet clear, we should return 0 to do an RPC on OSTs.
4347                          */
4348                         if (rc == 1)
4349                                 rc = rc2;
4350                 }
4351
4352                 if (param->fp_newery[NEWERXY_CTIME][i]) {
4353                         rc2 = find_value_cmp(lmd->lmd_stx.stx_ctime.tv_sec,
4354                                              param->fp_newery[NEWERXY_CTIME][i],
4355                                              -1, i, 0, mds);
4356                         if (rc2 < 0)
4357                                 return rc2;
4358
4359                         /*
4360                          * If the previous check matches, but this one is not
4361                          * yet clear, we should return 0 to do an RPC on OSTs.
4362                          */
4363                         if (rc == 1)
4364                                 rc = rc2;
4365                 }
4366
4367                 /*
4368                  * File birth time (btime) can get from MDT directly.
4369                  * if @from_mdt is true, it means the input file attributs are
4370                  * obtained directly from MDT.
4371                  * Thus, if @from_mdt is false, we should skip the following
4372                  * btime check.
4373                  */
4374                 if (!from_mdt)
4375                         continue;
4376
4377                 if (param->fp_newery[NEWERXY_BTIME][i]) {
4378                         if (!(lmd->lmd_stx.stx_mask & STATX_BTIME))
4379                                 return -EOPNOTSUPP;
4380
4381                         rc2 = find_value_cmp(lmd->lmd_stx.stx_btime.tv_sec,
4382                                              param->fp_newery[NEWERXY_BTIME][i],
4383                                              -1, i, 0, 0);
4384                         if (rc2 < 0)
4385                                 return rc2;
4386                 }
4387         }
4388
4389         return rc;
4390 }
4391
4392 /**
4393  * Check whether the stripes matches the indexes user provided
4394  *       1   : matched
4395  *       0   : Unmatched
4396  */
4397 static int check_obd_match(struct find_param *param)
4398 {
4399         struct lov_user_ost_data_v1 *objects;
4400         struct lov_comp_md_v1 *comp_v1 = NULL;
4401         struct lov_user_mds_data *lmd = param->fp_lmd;
4402         struct lov_user_md_v1 *v1 = &lmd->lmd_lmm;
4403         int i, j, k, count = 1;
4404
4405         if (param->fp_obd_uuid && param->fp_obd_index == OBD_NOT_FOUND)
4406                 return 0;
4407
4408         if (!S_ISREG(lmd->lmd_stx.stx_mode))
4409                 return 0;
4410
4411         /* exclude foreign */
4412         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4413                 return param->fp_exclude_obd;
4414
4415         /*
4416          * Only those files should be accepted, which have a
4417          * stripe on the specified OST.
4418          */
4419         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4420                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4421                 count = comp_v1->lcm_entry_count;
4422         }
4423
4424         for (i = 0; i < count; i++) {
4425                 if (comp_v1)
4426                         v1 = lov_comp_entry(comp_v1, i);
4427
4428                 objects = lov_v1v3_objects(v1);
4429
4430                 for (j = 0; j < v1->lmm_stripe_count; j++) {
4431                         if (comp_v1 && !(comp_v1->lcm_entries[i].lcme_flags &
4432                                          LCME_FL_INIT))
4433                                 continue;
4434                         for (k = 0; k < param->fp_num_obds; k++) {
4435                                 if (param->fp_obd_indexes[k] ==
4436                                     objects[j].l_ost_idx)
4437                                         return !param->fp_exclude_obd;
4438                         }
4439                 }
4440         }
4441
4442         return param->fp_exclude_obd;
4443 }
4444
4445 static int check_mdt_match(struct find_param *param)
4446 {
4447         int i;
4448
4449         if (param->fp_mdt_uuid && param->fp_mdt_index == OBD_NOT_FOUND)
4450                 return 0;
4451
4452         /* FIXME: For striped dir, we should get stripe information and check */
4453         for (i = 0; i < param->fp_num_mdts; i++) {
4454                 if (param->fp_mdt_indexes[i] == param->fp_file_mdt_index)
4455                         return !param->fp_exclude_mdt;
4456         }
4457
4458         if (param->fp_exclude_mdt)
4459                 return 1;
4460
4461         return 0;
4462 }
4463
4464 /**
4465  * Check whether the obd is active or not, if it is
4466  * not active, just print the object affected by this
4467  * failed target
4468  **/
4469 static void print_failed_tgt(struct find_param *param, char *path, int type)
4470 {
4471         struct obd_statfs stat_buf;
4472         struct obd_uuid uuid_buf;
4473         int tgt_nr, i, *indexes;
4474         int ret = 0;
4475
4476         if (type != LL_STATFS_LOV && type != LL_STATFS_LMV) {
4477                 llapi_error(LLAPI_MSG_NORMAL, ret, "%s: wrong statfs type(%d)",
4478                             __func__, type);
4479                 return;
4480         }
4481
4482         tgt_nr = (type == LL_STATFS_LOV) ? param->fp_obd_index :
4483                  param->fp_mdt_index;
4484         indexes = (type == LL_STATFS_LOV) ? param->fp_obd_indexes :
4485                   param->fp_mdt_indexes;
4486
4487         for (i = 0; i < tgt_nr; i++) {
4488                 memset(&stat_buf, 0, sizeof(struct obd_statfs));
4489                 memset(&uuid_buf, 0, sizeof(struct obd_uuid));
4490
4491                 ret = llapi_obd_statfs(path, type, indexes[i], &stat_buf,
4492                                        &uuid_buf);
4493                 if (ret)
4494                         llapi_error(LLAPI_MSG_NORMAL, ret,
4495                                     "%s: obd_uuid: %s failed",
4496                                     __func__, param->fp_obd_uuid->uuid);
4497         }
4498 }
4499
4500 static int find_check_stripe_size(struct find_param *param)
4501 {
4502         struct lov_comp_md_v1 *comp_v1 = NULL;
4503         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4504         __u32 stripe_size = 0;
4505         int ret, i, count = 1;
4506
4507         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4508                 return param->fp_exclude_stripe_size ? 1 : -1;
4509
4510         ret = param->fp_exclude_stripe_size ? 1 : -1;
4511         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4512                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4513                 count = comp_v1->lcm_entry_count;
4514         }
4515
4516         for (i = 0; i < count; i++) {
4517                 struct lov_comp_md_entry_v1 *ent;
4518
4519                 if (comp_v1) {
4520                         v1 = lov_comp_entry(comp_v1, i);
4521
4522                         ent = &comp_v1->lcm_entries[i];
4523                         if (ent->lcme_flags & LCME_FL_EXTENSION)
4524                                 continue;
4525                         if (!(ent->lcme_flags & LCME_FL_INIT))
4526                                 continue;
4527                 }
4528                 stripe_size = v1->lmm_stripe_size;
4529         }
4530
4531         ret = find_value_cmp(stripe_size, param->fp_stripe_size,
4532                              param->fp_stripe_size_sign,
4533                              param->fp_exclude_stripe_size,
4534                              param->fp_stripe_size_units, 0);
4535
4536         return ret;
4537 }
4538
4539 static int find_check_ext_size(struct find_param *param)
4540 {
4541         struct lov_comp_md_v1 *comp_v1;
4542         struct lov_user_md_v1 *v1;
4543         int ret, i;
4544
4545         ret = param->fp_exclude_ext_size ? 1 : -1;
4546         comp_v1 = (struct lov_comp_md_v1 *)&param->fp_lmd->lmd_lmm;
4547         if (comp_v1->lcm_magic != LOV_USER_MAGIC_COMP_V1)
4548                 return ret;
4549
4550         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
4551                 struct lov_comp_md_entry_v1 *ent;
4552
4553                 v1 = lov_comp_entry(comp_v1, i);
4554
4555                 ent = &comp_v1->lcm_entries[i];
4556                 if (!(ent->lcme_flags & LCME_FL_EXTENSION))
4557                         continue;
4558
4559                 ret = find_value_cmp(v1->lmm_stripe_size, param->fp_ext_size,
4560                                      param->fp_ext_size_sign,
4561                                      param->fp_exclude_ext_size,
4562                                      param->fp_ext_size_units, 0);
4563                 /* If any ext_size matches */
4564                 if (ret != -1)
4565                         break;
4566         }
4567
4568         return ret;
4569 }
4570
4571 static __u32 find_get_stripe_count(struct find_param *param)
4572 {
4573         struct lov_comp_md_v1 *comp_v1 = NULL;
4574         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4575         int i, count = 1;
4576         __u32 stripe_count = 0;
4577
4578         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4579                 return 0;
4580
4581         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4582                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4583                 count = comp_v1->lcm_entry_count;
4584         }
4585
4586         for (i = 0; i < count; i++) {
4587                 if (comp_v1) {
4588                         struct lov_comp_md_entry_v1 *ent;
4589
4590                         v1 = lov_comp_entry(comp_v1, i);
4591
4592                         ent = &comp_v1->lcm_entries[i];
4593                         if (!(ent->lcme_flags & LCME_FL_INIT))
4594                                 continue;
4595
4596                         if (ent->lcme_flags & LCME_FL_EXTENSION)
4597                                 continue;
4598                 }
4599                 stripe_count = v1->lmm_stripe_count;
4600         }
4601
4602         return stripe_count;
4603 }
4604
4605 #define LOV_PATTERN_INVALID     0xFFFFFFFF
4606
4607 static int find_check_layout(struct find_param *param)
4608 {
4609         struct lov_comp_md_v1 *comp_v1 = NULL;
4610         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4611         int i, count = 1;
4612         bool found = false, valid = false;
4613
4614         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4615                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4616                 count = comp_v1->lcm_entry_count;
4617         }
4618
4619         for (i = 0; i < count; i++) {
4620                 if (comp_v1)
4621                         v1 = lov_comp_entry(comp_v1, i);
4622
4623                 /* foreign file have a special magic but no pattern field */
4624                 if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4625                         continue;
4626
4627                 if (v1->lmm_pattern == LOV_PATTERN_INVALID)
4628                         continue;
4629
4630                 valid = true;
4631                 if (v1->lmm_pattern & param->fp_layout) {
4632                         found = true;
4633                         break;
4634                 }
4635         }
4636
4637         if (!valid)
4638                 return -1;
4639
4640         if ((found && !param->fp_exclude_layout) ||
4641             (!found && param->fp_exclude_layout))
4642                 return 1;
4643
4644         return -1;
4645 }
4646
4647 /*
4648  * if no type specified, check/exclude all foreign
4649  * if type specified, check all foreign&type and exclude !foreign + foreign&type
4650  */
4651 static int find_check_foreign(struct find_param *param)
4652 {
4653         if (S_ISREG(param->fp_lmd->lmd_stx.stx_mode)) {
4654                 struct lov_foreign_md *lfm;
4655
4656                 lfm = (void *)&param->fp_lmd->lmd_lmm;
4657                 if (lfm->lfm_magic != LOV_USER_MAGIC_FOREIGN) {
4658                         if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN)
4659                                 return param->fp_exclude_foreign ? 1 : -1;
4660                         return -1;
4661                 }
4662
4663                 if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN ||
4664                     lfm->lfm_type == param->fp_foreign_type)
4665                         return param->fp_exclude_foreign ? -1 : 1;
4666                 return param->fp_exclude_foreign ? 1 : -1;
4667         }
4668
4669         if (S_ISDIR(param->fp_lmd->lmd_stx.stx_mode)) {
4670                 struct lmv_foreign_md *lfm;
4671
4672                 lfm = (void *)param->fp_lmv_md;
4673                 if (lmv_is_foreign(lfm->lfm_magic)) {
4674                         if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN)
4675                                 return param->fp_exclude_foreign ? 1 : -1;
4676                         return -1;
4677                 }
4678
4679                 if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN ||
4680                     lfm->lfm_type == param->fp_foreign_type)
4681                         return param->fp_exclude_foreign ? -1 : 1;
4682                 return param->fp_exclude_foreign ? 1 : -1;
4683         }
4684         return -1;
4685 }
4686
4687 static int find_check_pool(struct find_param *param)
4688 {
4689         struct lov_comp_md_v1 *comp_v1 = NULL;
4690         struct lov_user_md_v3 *v3 = (void *)&param->fp_lmd->lmd_lmm;
4691         int i, count = 1;
4692         bool found = false;
4693
4694         if (v3->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4695                 comp_v1 = (struct lov_comp_md_v1 *)v3;
4696                 count = comp_v1->lcm_entry_count;
4697                 /* empty requested pool is taken as no pool search */
4698                 if (count == 0 && param->fp_poolname[0] == '\0') {
4699                         found = true;
4700                         goto found;
4701                 }
4702         }
4703
4704         for (i = 0; i < count; i++) {
4705                 if (comp_v1 != NULL) {
4706                         if (!(comp_v1->lcm_entries[i].lcme_flags &
4707                               LCME_FL_INIT))
4708                                 continue;
4709
4710                         v3 = (void *)lov_comp_entry(comp_v1, i);
4711                 }
4712
4713                 if (v3->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4714                         continue;
4715
4716                 if (((v3->lmm_magic == LOV_USER_MAGIC_V1) &&
4717                      (param->fp_poolname[0] == '\0')) ||
4718                     ((v3->lmm_magic == LOV_USER_MAGIC_V3) &&
4719                      (strncmp(v3->lmm_pool_name,
4720                               param->fp_poolname, LOV_MAXPOOLNAME) == 0)) ||
4721                     ((v3->lmm_magic == LOV_USER_MAGIC_V3) &&
4722                      (strcmp(param->fp_poolname, "*") == 0))) {
4723                         found = true;
4724                         break;
4725                 }
4726         }
4727
4728 found:
4729         if ((found && !param->fp_exclude_pool) ||
4730             (!found && param->fp_exclude_pool))
4731                 return 1;
4732
4733         return -1;
4734 }
4735
4736 static int find_check_comp_options(struct find_param *param)
4737 {
4738         struct lov_comp_md_v1 *comp_v1, *forged_v1 = NULL;
4739         struct lov_user_mds_data *lmd = param->fp_lmd;
4740         struct lov_user_md_v1 *v1 = &lmd->lmd_lmm;
4741         struct lov_comp_md_entry_v1 *entry;
4742         int i, ret = 0;
4743
4744         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4745                 return -1;
4746
4747         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4748                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4749         } else {
4750                 forged_v1 = malloc(sizeof(*forged_v1) + sizeof(*entry));
4751                 if (forged_v1 == NULL)
4752                         return -1;
4753                 comp_v1 = forged_v1;
4754                 comp_v1->lcm_entry_count = 1;
4755                 entry = &comp_v1->lcm_entries[0];
4756                 entry->lcme_flags = S_ISDIR(lmd->lmd_stx.stx_mode) ?
4757                                     0 : LCME_FL_INIT;
4758                 entry->lcme_extent.e_start = 0;
4759                 entry->lcme_extent.e_end = LUSTRE_EOF;
4760         }
4761
4762         /* invalid case, don't match for any kind of search. */
4763         if (comp_v1->lcm_entry_count == 0) {
4764                 ret = -1;
4765                 goto out;
4766         }
4767
4768         if (param->fp_check_comp_count) {
4769                 ret = find_value_cmp(forged_v1 ? 0 : comp_v1->lcm_entry_count,
4770                                      param->fp_comp_count,
4771                                      param->fp_comp_count_sign,
4772                                      param->fp_exclude_comp_count, 1, 0);
4773                 if (ret == -1)
4774                         goto out;
4775         }
4776
4777         ret = 1;
4778         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
4779                 entry = &comp_v1->lcm_entries[i];
4780
4781                 if (param->fp_check_comp_flags) {
4782                         ret = 1;
4783                         if (((param->fp_comp_flags & entry->lcme_flags) !=
4784                              param->fp_comp_flags) ||
4785                             (param->fp_comp_neg_flags & entry->lcme_flags)) {
4786                                 ret = -1;
4787                                 continue;
4788                         }
4789                 }
4790
4791                 if (param->fp_check_comp_start) {
4792                         ret = find_value_cmp(entry->lcme_extent.e_start,
4793                                              param->fp_comp_start,
4794                                              param->fp_comp_start_sign,
4795                                              param->fp_exclude_comp_start,
4796                                              param->fp_comp_start_units, 0);
4797                         if (ret == -1)
4798                                 continue;
4799                 }
4800
4801                 if (param->fp_check_comp_end) {
4802                         ret = find_comp_end_cmp(entry->lcme_extent.e_end,
4803                                                 param);
4804                         if (ret == -1)
4805                                 continue;
4806                 }
4807
4808                 /* the component matches all criteria */
4809                 break;
4810         }
4811 out:
4812         if (forged_v1)
4813                 free(forged_v1);
4814         return ret;
4815 }
4816
4817 static int find_check_mirror_options(struct find_param *param)
4818 {
4819         struct lov_comp_md_v1 *comp_v1;
4820         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4821         int ret = 0;
4822
4823         if (v1->lmm_magic != LOV_USER_MAGIC_COMP_V1)
4824                 return -1;
4825
4826         comp_v1 = (struct lov_comp_md_v1 *)v1;
4827
4828         if (param->fp_check_mirror_count) {
4829                 ret = find_value_cmp(comp_v1->lcm_mirror_count + 1,
4830                                      param->fp_mirror_count,
4831                                      param->fp_mirror_count_sign,
4832                                      param->fp_exclude_mirror_count, 1, 0);
4833                 if (ret == -1)
4834                         return ret;
4835         }
4836
4837         if (param->fp_check_mirror_state) {
4838                 ret = 1;
4839                 __u16 file_state = comp_v1->lcm_flags & LCM_FL_FLR_MASK;
4840
4841                 if ((param->fp_mirror_state != 0 &&
4842                     file_state != param->fp_mirror_state) ||
4843                     file_state == param->fp_mirror_neg_state)
4844                         return -1;
4845         }
4846
4847         return ret;
4848 }
4849
4850 static bool find_check_lmm_info(struct find_param *param)
4851 {
4852         return param->fp_check_pool || param->fp_check_stripe_count ||
4853                param->fp_check_stripe_size || param->fp_check_layout ||
4854                param->fp_check_comp_count || param->fp_check_comp_end ||
4855                param->fp_check_comp_start || param->fp_check_comp_flags ||
4856                param->fp_check_mirror_count || param->fp_check_foreign ||
4857                param->fp_check_mirror_state || param->fp_check_ext_size ||
4858                param->fp_check_projid;
4859 }
4860
4861 /*
4862  * Get file/directory project id.
4863  * by the open fd resides on.
4864  * Return 0 and project id on success, or -ve errno.
4865  */
4866 static int fget_projid(int fd, int *projid)
4867 {
4868         struct fsxattr fsx;
4869         int rc;
4870
4871         rc = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
4872         if (rc)
4873                 return -errno;
4874
4875         *projid = fsx.fsx_projid;
4876         return 0;
4877 }
4878
4879 /*
4880  * Check that the file's permissions in *st matches the one in find_param
4881  */
4882 static int check_file_permissions(const struct find_param *param,
4883                         const lstat_t *st)
4884 {
4885         const mode_t st_mode = st->st_mode & 07777;
4886         int decision = 0;
4887
4888         switch (param->fp_perm_sign) {
4889         case LFS_FIND_PERM_EXACT:
4890                 decision = (st_mode == param->fp_perm);
4891                 break;
4892         case LFS_FIND_PERM_ALL:
4893                 decision = ((st_mode & param->fp_perm) == param->fp_perm);
4894                 break;
4895         case LFS_FIND_PERM_ANY:
4896                 decision = ((st_mode & param->fp_perm) != 0);
4897                 break;
4898         }
4899
4900         if ((param->fp_exclude_perm && decision)
4901                 || (!param->fp_exclude_perm && !decision))
4902                 return -1;
4903         else
4904                 return 1;
4905 }
4906
4907 static int cb_find_init(char *path, int p, int *dp,
4908                         void *data, struct dirent64 *de)
4909 {
4910         struct find_param *param = (struct find_param *)data;
4911         struct lov_user_mds_data *lmd = param->fp_lmd;
4912         int d = dp == NULL ? -1 : *dp;
4913         int decision = 1; /* 1 is accepted; -1 is rejected. */
4914         int lustre_fs = 1;
4915         int checked_type = 0;
4916         int ret = 0;
4917         __u32 stripe_count = 0;
4918         __u64 flags;
4919         int fd = -2;
4920
4921         if (p == -1 && d == -1)
4922                 return -EINVAL;
4923
4924         /* If a regular expression is presented, make the initial decision */
4925         if (param->fp_pattern != NULL) {
4926                 char *fname = strrchr(path, '/');
4927
4928                 fname = (fname == NULL ? path : fname + 1);
4929                 ret = fnmatch(param->fp_pattern, fname, 0);
4930                 if ((ret == FNM_NOMATCH && !param->fp_exclude_pattern) ||
4931                     (ret == 0 && param->fp_exclude_pattern))
4932                         goto decided;
4933         }
4934
4935         /* See if we can check the file type from the dirent. */
4936         if (de != NULL && de->d_type != DT_UNKNOWN) {
4937                 if (param->fp_type != 0) {
4938                         checked_type = 1;
4939
4940                         if (DTTOIF(de->d_type) == param->fp_type) {
4941                                 if (param->fp_exclude_type)
4942                                         goto decided;
4943                         } else {
4944                                 if (!param->fp_exclude_type)
4945                                         goto decided;
4946                         }
4947                 }
4948                 if ((param->fp_check_mdt_count || param->fp_hash_type ||
4949                      param->fp_check_hash_flag) && de->d_type != DT_DIR)
4950                         goto decided;
4951         }
4952
4953         ret = 0;
4954
4955         /*
4956          * Request MDS for the stat info if some of these parameters need
4957          * to be compared.
4958          */
4959         if (param->fp_obd_uuid || param->fp_mdt_uuid ||
4960             param->fp_check_uid || param->fp_check_gid ||
4961             param->fp_newerxy || param->fp_btime ||
4962             param->fp_atime || param->fp_mtime || param->fp_ctime ||
4963             param->fp_check_size || param->fp_check_blocks ||
4964             find_check_lmm_info(param) ||
4965             param->fp_check_mdt_count || param->fp_hash_type ||
4966             param->fp_check_hash_flag || param->fp_perm_sign)
4967                 decision = 0;
4968
4969         if (param->fp_type != 0 && checked_type == 0)
4970                 decision = 0;
4971
4972         if (decision == 0) {
4973                 if (d != -1 &&
4974                     (param->fp_check_mdt_count || param->fp_hash_type ||
4975                      param->fp_check_hash_flag || param->fp_check_foreign)) {
4976                         param->fp_get_lmv = 1;
4977                         ret = cb_get_dirstripe(path, &d, param);
4978                         if (ret != 0) {
4979                                 if (errno == ENODATA) {
4980                                         ret = 0;
4981                                         if (param->fp_check_mdt_count ||
4982                                             param->fp_hash_type ||
4983                                             param->fp_check_hash_flag) {
4984                                                 param->fp_lmv_md->lum_stripe_count = 0;
4985                                                 param->fp_lmv_md->lum_hash_type = 0;
4986                                         }
4987                                         if (param->fp_check_foreign) {
4988                                                 if (param->fp_exclude_foreign)
4989                                                         goto print;
4990                                                 goto decided;
4991                                         }
4992                                 } else {
4993                                         return ret;
4994                                 }
4995                         }
4996
4997                         if (param->fp_check_mdt_count) {
4998                                 if (lmv_is_foreign(param->fp_lmv_md->lum_magic))
4999                                         goto decided;
5000
5001                                 decision = find_value_cmp(param->fp_lmv_md->lum_stripe_count,
5002                                                           param->fp_mdt_count,
5003                                                           param->fp_mdt_count_sign,
5004                                                           param->fp_exclude_mdt_count, 1, 0);
5005                                 if (decision == -1)
5006                                         goto decided;
5007                         }
5008
5009                         if (param->fp_hash_type) {
5010                                 __u32 found;
5011                                 __u32 type = param->fp_lmv_md->lum_hash_type &
5012                                         LMV_HASH_TYPE_MASK;
5013
5014                                 if (lmv_is_foreign(param->fp_lmv_md->lum_magic))
5015                                         goto decided;
5016
5017                                 found = (1 << type) & param->fp_hash_type;
5018                                 if ((found && param->fp_exclude_hash_type) ||
5019                                     (!found && !param->fp_exclude_hash_type))
5020                                         goto decided;
5021                         }
5022
5023                         if (param->fp_check_hash_flag) {
5024                                 __u32 flags = param->fp_lmv_md->lum_hash_type &
5025                                         ~LMV_HASH_TYPE_MASK;
5026
5027                                 if (lmv_is_foreign(param->fp_lmv_md->lum_magic))
5028                                         goto decided;
5029
5030                                 if (!(flags & param->fp_hash_inflags) ||
5031                                     (flags & param->fp_hash_exflags))
5032                                         goto decided;
5033                         }
5034                 }
5035
5036                 param->fp_lmd->lmd_lmm.lmm_magic = 0;
5037                 ret = get_lmd_info_fd(path, p, d, param->fp_lmd,
5038                                       param->fp_lum_size, GET_LMD_INFO);
5039                 if (ret == 0 && param->fp_lmd->lmd_lmm.lmm_magic == 0 &&
5040                     find_check_lmm_info(param)) {
5041                         struct lov_user_md *lmm = &param->fp_lmd->lmd_lmm;
5042
5043                         /*
5044                          * We need to "fake" the "use the default" values
5045                          * since the lmm struct is zeroed out at this point.
5046                          */
5047                         lmm->lmm_magic = LOV_USER_MAGIC_V1;
5048                         lmm->lmm_pattern = LOV_PATTERN_DEFAULT;
5049                         if (!param->fp_raw)
5050                                 ostid_set_seq(&lmm->lmm_oi,
5051                                               FID_SEQ_LOV_DEFAULT);
5052                         lmm->lmm_stripe_size = 0;
5053                         lmm->lmm_stripe_count = 0;
5054                         lmm->lmm_stripe_offset = -1;
5055                 }
5056                 if (ret == 0 && param->fp_mdt_uuid != NULL) {
5057                         if (d != -1) {
5058                                 ret = llapi_file_fget_mdtidx(d,
5059                                                      &param->fp_file_mdt_index);
5060                         } else if (S_ISREG(lmd->lmd_stx.stx_mode)) {
5061                                 /*
5062                                  * FIXME: we could get the MDT index from the
5063                                  * file's FID in lmd->lmd_lmm.lmm_oi without
5064                                  * opening the file, once we are sure that
5065                                  * LFSCK2 (2.6) has fixed up pre-2.0 LOV EAs.
5066                                  * That would still be an ioctl() to map the
5067                                  * FID to the MDT, but not an open RPC.
5068                                  */
5069                                 fd = open(path, O_RDONLY);
5070                                 if (fd > 0) {
5071                                         ret = llapi_file_fget_mdtidx(fd,
5072                                                      &param->fp_file_mdt_index);
5073                                 } else {
5074                                         ret = -errno;
5075                                 }
5076                         } else {
5077                                 /*
5078                                  * For a special file, we assume it resides on
5079                                  * the same MDT as the parent directory.
5080                                  */
5081                                 ret = llapi_file_fget_mdtidx(p,
5082                                                      &param->fp_file_mdt_index);
5083                         }
5084                 }
5085                 if (ret != 0) {
5086                         if (ret == -ENOTTY)
5087                                 lustre_fs = 0;
5088                         if (ret == -ENOENT)
5089                                 goto decided;
5090
5091                         goto out;
5092                 } else {
5093                         stripe_count = find_get_stripe_count(param);
5094                 }
5095         }
5096
5097         if (param->fp_type && !checked_type) {
5098                 if ((param->fp_check_mdt_count || param->fp_check_hash_flag ||
5099                      param->fp_hash_type) && !S_ISDIR(lmd->lmd_stx.stx_mode))
5100                         goto decided;
5101
5102                 if ((lmd->lmd_stx.stx_mode & S_IFMT) == param->fp_type) {
5103                         if (param->fp_exclude_type)
5104                                 goto decided;
5105                 } else {
5106                         if (!param->fp_exclude_type)
5107                                 goto decided;
5108                 }
5109         }
5110
5111         /* Prepare odb. */
5112         if (param->fp_obd_uuid || param->fp_mdt_uuid) {
5113                 if (lustre_fs && param->fp_got_uuids &&
5114                     param->fp_dev != makedev(lmd->lmd_stx.stx_dev_major,
5115                                              lmd->lmd_stx.stx_dev_minor)) {
5116                         /* A lustre/lustre mount point is crossed. */
5117                         param->fp_got_uuids = 0;
5118                         param->fp_obds_printed = 0;
5119                         param->fp_mdt_index = OBD_NOT_FOUND;
5120                         param->fp_obd_index = OBD_NOT_FOUND;
5121                 }
5122
5123                 if (lustre_fs && !param->fp_got_uuids) {
5124                         ret = setup_target_indexes((d != -1) ? d : p, path,
5125                                                    param);
5126                         if (ret)
5127                                 goto out;
5128
5129                         param->fp_dev = makedev(lmd->lmd_stx.stx_dev_major,
5130                                                 lmd->lmd_stx.stx_dev_minor);
5131                 } else if (!lustre_fs && param->fp_got_uuids) {
5132                         /* A lustre/non-lustre mount point is crossed. */
5133                         param->fp_got_uuids = 0;
5134                         param->fp_mdt_index = OBD_NOT_FOUND;
5135                         param->fp_obd_index = OBD_NOT_FOUND;
5136                 }
5137         }
5138
5139         if (param->fp_check_foreign) {
5140                 decision = find_check_foreign(param);
5141                 if (decision == -1)
5142                         goto decided;
5143         }
5144
5145         if (param->fp_check_stripe_size) {
5146                 decision = find_check_stripe_size(param);
5147                 if (decision == -1)
5148                         goto decided;
5149         }
5150
5151         if (param->fp_check_ext_size) {
5152                 decision = find_check_ext_size(param);
5153                 if (decision == -1)
5154                         goto decided;
5155         }
5156
5157         if (param->fp_check_stripe_count) {
5158                 decision = find_value_cmp(stripe_count, param->fp_stripe_count,
5159                                           param->fp_stripe_count_sign,
5160                                           param->fp_exclude_stripe_count, 1, 0);
5161                 if (decision == -1)
5162                         goto decided;
5163         }
5164
5165         if (param->fp_check_layout) {
5166                 decision = find_check_layout(param);
5167                 if (decision == -1)
5168                         goto decided;
5169         }
5170
5171         /* If an OBD UUID is specified but none matches, skip this file. */
5172         if ((param->fp_obd_uuid && param->fp_obd_index == OBD_NOT_FOUND) ||
5173             (param->fp_mdt_uuid && param->fp_mdt_index == OBD_NOT_FOUND))
5174                 goto decided;
5175
5176         /*
5177          * If an OST or MDT UUID is given, and some OST matches,
5178          * check it here.
5179          */
5180         if (param->fp_obd_index != OBD_NOT_FOUND ||
5181             param->fp_mdt_index != OBD_NOT_FOUND) {
5182                 if (param->fp_obd_uuid) {
5183                         if (check_obd_match(param)) {
5184                                 /*
5185                                  * If no mdtuuid is given, we are done.
5186                                  * Otherwise, fall through to the mdtuuid
5187                                  * check below.
5188                                  */
5189                                 if (!param->fp_mdt_uuid)
5190                                         goto obd_matches;
5191                         } else {
5192                                 goto decided;
5193                         }
5194                 }
5195
5196                 if (param->fp_mdt_uuid) {
5197                         if (check_mdt_match(param))
5198                                 goto obd_matches;
5199                         goto decided;
5200                 }
5201         }
5202
5203 obd_matches:
5204         if (param->fp_check_uid) {
5205                 if (lmd->lmd_stx.stx_uid == param->fp_uid) {
5206                         if (param->fp_exclude_uid)
5207                                 goto decided;
5208                 } else {
5209                         if (!param->fp_exclude_uid)
5210                                 goto decided;
5211                 }
5212         }
5213
5214         if (param->fp_check_gid) {
5215                 if (lmd->lmd_stx.stx_gid == param->fp_gid) {
5216                         if (param->fp_exclude_gid)
5217                                 goto decided;
5218                 } else {
5219                         if (!param->fp_exclude_gid)
5220                                 goto decided;
5221                 }
5222         }
5223
5224         if (param->fp_check_projid) {
5225                 int projid = 0;
5226
5227                 if (fd == -2)
5228                         fd = open(path, O_RDONLY);
5229
5230                 if (fd > 0)
5231                         ret = fget_projid(fd, &projid);
5232                 else
5233                         ret = -errno;
5234                 if (ret)
5235                         goto out;
5236                 if (projid == param->fp_projid) {
5237                         if (param->fp_exclude_projid)
5238                                 goto decided;
5239                 } else {
5240                         if (!param->fp_exclude_projid)
5241                                 goto decided;
5242                 }
5243         }
5244
5245         if (param->fp_check_pool) {
5246                 decision = find_check_pool(param);
5247                 if (decision == -1)
5248                         goto decided;
5249         }
5250
5251         if (param->fp_check_comp_count || param->fp_check_comp_flags ||
5252             param->fp_check_comp_start || param->fp_check_comp_end) {
5253                 decision = find_check_comp_options(param);
5254                 if (decision == -1)
5255                         goto decided;
5256         }
5257
5258         if (param->fp_check_mirror_count || param->fp_check_mirror_state) {
5259                 decision = find_check_mirror_options(param);
5260                 if (decision == -1)
5261                         goto decided;
5262         }
5263
5264         /* Check the time on mds. */
5265         decision = 1;
5266         if (param->fp_atime || param->fp_mtime || param->fp_ctime) {
5267                 int for_mds;
5268
5269                 for_mds = lustre_fs ?
5270                           (S_ISREG(lmd->lmd_stx.stx_mode) && stripe_count) : 0;
5271                 decision = find_time_check(param, for_mds);
5272                 if (decision == -1)
5273                         goto decided;
5274         }
5275
5276         if (param->fp_btime) {
5277                 if (!(lmd->lmd_stx.stx_mask & STATX_BTIME)) {
5278                         ret = -EOPNOTSUPP;
5279                         goto out;
5280                 }
5281
5282                 decision = find_value_cmp(lmd->lmd_stx.stx_btime.tv_sec,
5283                                           param->fp_btime, param->fp_bsign,
5284                                           param->fp_exclude_btime,
5285                                           param->fp_time_margin, 0);
5286                 if (decision == -1)
5287                         goto decided;
5288         }
5289
5290         if (param->fp_newerxy) {
5291                 int for_mds;
5292
5293                 for_mds = lustre_fs ?
5294                           (S_ISREG(lmd->lmd_stx.stx_mode) && stripe_count) : 0;
5295                 decision = find_newerxy_check(param, for_mds, true);
5296                 if (decision == -1)
5297                         goto decided;
5298                 if (decision < 0) {
5299                         ret = decision;
5300                         goto out;
5301                 }
5302         }
5303
5304         flags = param->fp_lmd->lmd_flags;
5305         if (param->fp_check_size &&
5306             ((S_ISREG(lmd->lmd_stx.stx_mode) && stripe_count) ||
5307               S_ISDIR(lmd->lmd_stx.stx_mode)) &&
5308             !(flags & OBD_MD_FLSIZE ||
5309               (param->fp_lazy && flags & OBD_MD_FLLAZYSIZE)))
5310                 decision = 0;
5311
5312         if (param->fp_check_blocks &&
5313             ((S_ISREG(lmd->lmd_stx.stx_mode) && stripe_count) ||
5314               S_ISDIR(lmd->lmd_stx.stx_mode)) &&
5315             !(flags & OBD_MD_FLBLOCKS ||
5316               (param->fp_lazy && flags & OBD_MD_FLLAZYBLOCKS)))
5317                 decision = 0;
5318
5319         if (param->fp_perm_sign)
5320                 decision = 0;
5321
5322         /*
5323          * If file still fits the request, ask ost for updated info.
5324          * The regular stat is almost of the same speed as some new
5325          * 'glimpse-size-ioctl'.
5326          */
5327         if (!decision) {
5328                 lstat_t st;
5329
5330                 /*
5331                  * For regular files with the stripe the decision may have not
5332                  * been taken yet if *time or size is to be checked.
5333                  */
5334                 if (param->fp_obd_index != OBD_NOT_FOUND)
5335                         print_failed_tgt(param, path, LL_STATFS_LOV);
5336
5337                 if (param->fp_mdt_index != OBD_NOT_FOUND)
5338                         print_failed_tgt(param, path, LL_STATFS_LMV);
5339
5340                 if (d != -1)
5341                         ret = fstat_f(d, &st);
5342                 else if (de != NULL)
5343                         ret = fstatat_f(p, de->d_name, &st,
5344                                         AT_SYMLINK_NOFOLLOW);
5345                 else
5346                         ret = lstat_f(path, &st);
5347
5348                 if (ret) {
5349                         if (errno == ENOENT) {
5350                                 llapi_error(LLAPI_MSG_ERROR, -ENOENT,
5351                                             "warning: %s: %s does not exist",
5352                                             __func__, path);
5353                                 goto decided;
5354                         } else {
5355                                 ret = -errno;
5356                                 llapi_error(LLAPI_MSG_ERROR, ret,
5357                                             "%s: stat on %s failed",
5358                                             __func__, path);
5359                                 goto out;
5360                         }
5361                 }
5362
5363                 convert_lmd_statx(param->fp_lmd, &st, true);
5364                 /* Check the time on osc. */
5365                 decision = find_time_check(param, 0);
5366                 if (decision == -1)
5367                         goto decided;
5368
5369                 if (param->fp_newerxy) {
5370                         decision = find_newerxy_check(param, 0, false);
5371                         if (decision == -1)
5372                                 goto decided;
5373                         if (decision < 0) {
5374                                 ret = decision;
5375                                 goto out;
5376                         }
5377                 }
5378
5379                 /* Check the file permissions from the stat info */
5380                 if (param->fp_perm_sign) {
5381                         decision = check_file_permissions(param, &st);
5382                         if (decision == -1)
5383                                 goto decided;
5384                 }
5385         }
5386
5387         if (param->fp_check_size) {
5388                 decision = find_value_cmp(lmd->lmd_stx.stx_size,
5389                                           param->fp_size,
5390                                           param->fp_size_sign,
5391                                           param->fp_exclude_size,
5392                                           param->fp_size_units, 0);
5393                 if (decision == -1)
5394                         goto decided;
5395         }
5396
5397         if (param->fp_check_blocks) { /* convert st_blocks to bytes */
5398                 decision = find_value_cmp(lmd->lmd_stx.stx_blocks * 512,
5399                                           param->fp_blocks,
5400                                           param->fp_blocks_sign,
5401                                           param->fp_exclude_blocks,
5402                                           param->fp_blocks_units, 0);
5403                 if (decision == -1)
5404                         goto decided;
5405         }
5406
5407 print:
5408         llapi_printf(LLAPI_MSG_NORMAL, "%s%c", path,
5409                      param->fp_zero_end ? '\0' : '\n');
5410
5411 decided:
5412         ret = 0;
5413         /* Do not get down anymore? */
5414         if (param->fp_depth == param->fp_max_depth) {
5415                 ret = 1;
5416                 goto out;
5417         }
5418         param->fp_depth++;
5419 out:
5420         if (fd > 0)
5421                 close(fd);
5422         return ret;
5423 }
5424
5425 static int cb_migrate_mdt_init(char *path, int p, int *dp,
5426                                void *param_data, struct dirent64 *de)
5427 {
5428         struct find_param *param = (struct find_param *)param_data;
5429         struct lmv_user_md *lmu = param->fp_lmv_md;
5430         int tmp_p = p;
5431         char raw[MAX_IOC_BUFLEN] = {'\0'};
5432         char *rawbuf = raw;
5433         struct obd_ioctl_data data = { 0 };
5434         int ret;
5435         char *path_copy;
5436         char *filename;
5437         bool retry = false;
5438
5439         if (p == -1 && dp == NULL)
5440                 return -EINVAL;
5441
5442         if (!lmu)
5443                 return -EINVAL;
5444
5445         if (dp != NULL && *dp != -1)
5446                 close(*dp);
5447
5448         if (p == -1) {
5449                 tmp_p = open_parent(path);
5450                 if (tmp_p == -1) {
5451                         *dp = -1;
5452                         ret = -errno;
5453                         llapi_error(LLAPI_MSG_ERROR, ret,
5454                                     "can not open %s", path);
5455                         return ret;
5456                 }
5457         }
5458
5459         path_copy = strdup(path);
5460         filename = basename(path_copy);
5461
5462         data.ioc_inlbuf1 = (char *)filename;
5463         data.ioc_inllen1 = strlen(filename) + 1;
5464         data.ioc_inlbuf2 = (char *)lmu;
5465         data.ioc_inllen2 = lmv_user_md_size(lmu->lum_stripe_count,
5466                                             lmu->lum_magic);
5467         ret = llapi_ioctl_pack(&data, &rawbuf, sizeof(raw));
5468         if (ret != 0) {
5469                 llapi_error(LLAPI_MSG_ERROR, ret,
5470                             "%s: error packing ioctl data", __func__);
5471                 goto out;
5472         }
5473
5474 migrate:
5475         ret = ioctl(tmp_p, LL_IOC_MIGRATE, rawbuf);
5476         if (ret != 0) {
5477                 if (errno == EBUSY && !retry) {
5478                         /*
5479                          * because migrate may not be able to lock all involved
5480                          * objects in order, for some of them it try lock, while
5481                          * there may be conflicting COS locks and cause migrate
5482                          * fail with EBUSY, hope a sync() could cause
5483                          * transaction commit and release these COS locks.
5484                          */
5485                         sync();
5486                         retry = true;
5487                         goto migrate;
5488                 } else if (errno == EALREADY) {
5489                         if (param->fp_verbose & VERBOSE_DETAIL)
5490                                 llapi_printf(LLAPI_MSG_NORMAL,
5491                                              "%s migrated to MDT%d already\n",
5492                                              path, lmu->lum_stripe_offset);
5493                         ret = 0;
5494                 } else {
5495                         ret = -errno;
5496                         llapi_error(LLAPI_MSG_ERROR, ret, "%s migrate failed",
5497                                     path);
5498                         goto out;
5499                 }
5500         } else if (param->fp_verbose & VERBOSE_DETAIL) {
5501                 llapi_printf(LLAPI_MSG_NORMAL,
5502                              "migrate %s to MDT%d stripe count %d\n",
5503                              path, lmu->lum_stripe_offset,
5504                              lmu->lum_stripe_count);
5505         }
5506
5507 out:
5508         if (dp != NULL) {
5509                 /*
5510                  * If the directory is being migration, we need
5511                  * close the directory after migration,
5512                  * so the old directory cache will be cleanup
5513                  * on the client side, and re-open to get the
5514                  * new directory handle
5515                  */
5516                 *dp = open(path, O_RDONLY|O_NDELAY|O_DIRECTORY);
5517                 if (*dp == -1) {
5518                         ret = -errno;
5519                         llapi_error(LLAPI_MSG_ERROR, ret,
5520                                     "%s: Failed to open '%s'", __func__, path);
5521                 }
5522         }
5523
5524         if (p == -1)
5525                 close(tmp_p);
5526
5527         free(path_copy);
5528
5529         return ret;
5530 }
5531
5532 /* dir migration finished, shrink its stripes */
5533 static int cb_migrate_mdt_fini(char *path, int p, int *dp, void *data,
5534                                struct dirent64 *de)
5535 {
5536         struct find_param *param = data;
5537         struct lmv_user_md *lmu = param->fp_lmv_md;
5538         int lmulen = lmv_user_md_size(lmu->lum_stripe_count, lmu->lum_magic);
5539         int ret = 0;
5540
5541         if (de && de->d_type != DT_DIR)
5542                 goto out;
5543
5544         if (*dp != -1) {
5545                 /*
5546                  * close it before setxattr because the latter may destroy the
5547                  * original object, and cause close fail.
5548                  */
5549                 ret = close(*dp);
5550                 *dp = -1;
5551                 if (ret)
5552                         goto out;
5553         }
5554
5555         ret = setxattr(path, XATTR_NAME_LMV, lmu, lmulen, 0);
5556         if (ret == -EALREADY)
5557                 ret = 0;
5558 out:
5559         cb_common_fini(path, p, dp, data, de);
5560         return ret;
5561 }
5562
5563 int llapi_migrate_mdt(char *path, struct find_param *param)
5564 {
5565         return param_callback(path, cb_migrate_mdt_init, cb_migrate_mdt_fini,
5566                               param);
5567 }
5568
5569 int llapi_mv(char *path, struct find_param *param)
5570 {
5571 #if LUSTRE_VERSION_CODE > OBD_OCD_VERSION(2, 9, 59, 0)
5572         static bool printed;
5573
5574         if (!printed) {
5575                 llapi_error(LLAPI_MSG_ERROR, -ESTALE,
5576                           "%s() is deprecated, use llapi_migrate_mdt() instead",
5577                           __func__);
5578                 printed = true;
5579         }
5580 #endif
5581         return llapi_migrate_mdt(path, param);
5582 }
5583
5584 int llapi_find(char *path, struct find_param *param)
5585 {
5586         return param_callback(path, cb_find_init, cb_common_fini, param);
5587 }
5588
5589 /*
5590  * Get MDT number that the file/directory inode referenced
5591  * by the open fd resides on.
5592  * Return 0 and mdtidx on success, or -ve errno.
5593  */
5594 int llapi_file_fget_mdtidx(int fd, int *mdtidx)
5595 {
5596         if (ioctl(fd, LL_IOC_GET_MDTIDX, mdtidx) < 0)
5597                 return -errno;
5598         return 0;
5599 }
5600
5601 static int cb_get_mdt_index(char *path, int p, int *dp, void *data,
5602                             struct dirent64 *de)
5603 {
5604         struct find_param *param = (struct find_param *)data;
5605         int d = dp == NULL ? -1 : *dp;
5606         int ret;
5607         int mdtidx;
5608
5609         if (p == -1 && d == -1)
5610                 return -EINVAL;
5611
5612         if (d != -1) {
5613                 ret = llapi_file_fget_mdtidx(d, &mdtidx);
5614         } else /* if (p != -1) */ {
5615                 int fd;
5616
5617                 fd = open(path, O_RDONLY | O_NOCTTY);
5618                 if (fd > 0) {
5619                         ret = llapi_file_fget_mdtidx(fd, &mdtidx);
5620                         close(fd);
5621                 } else {
5622                         ret = -errno;
5623                 }
5624         }
5625
5626         if (ret != 0) {
5627                 if (ret == -ENODATA) {
5628                         if (!param->fp_obd_uuid)
5629                                 llapi_printf(LLAPI_MSG_NORMAL,
5630                                              "'%s' has no stripe info\n", path);
5631                         goto out;
5632                 } else if (ret == -ENOENT) {
5633                         llapi_error(LLAPI_MSG_WARN, ret,
5634                                     "warning: %s: '%s' does not exist",
5635                                     __func__, path);
5636                         goto out;
5637                 } else if (ret == -ENOTTY) {
5638                         llapi_error(LLAPI_MSG_ERROR, ret,
5639                                     "%s: '%s' not on a Lustre fs",
5640                                     __func__, path);
5641                 } else {
5642                         llapi_error(LLAPI_MSG_ERROR, ret,
5643                                     "error: %s: '%s' failed get_mdtidx",
5644                                     __func__, path);
5645                 }
5646                 return ret;
5647         }
5648
5649         if (param->fp_quiet || !(param->fp_verbose & VERBOSE_DETAIL))
5650                 llapi_printf(LLAPI_MSG_NORMAL, "%d\n", mdtidx);
5651         else
5652                 llapi_printf(LLAPI_MSG_NORMAL, "%s\nmdt_index:\t%d\n",
5653                              path, mdtidx);
5654
5655 out:
5656         /* Do not go down anymore? */
5657         if (param->fp_depth == param->fp_max_depth)
5658                 return 1;
5659
5660         param->fp_depth++;
5661
5662         return 0;
5663 }
5664
5665 static int cb_getstripe(char *path, int p, int *dp, void *data,
5666                         struct dirent64 *de)
5667 {
5668         struct find_param *param = (struct find_param *)data;
5669         int d = dp == NULL ? -1 : *dp;
5670         int ret = 0;
5671
5672         if (p == -1 && d == -1)
5673                 return -EINVAL;
5674
5675         if (param->fp_obd_uuid) {
5676                 param->fp_quiet = 1;
5677                 ret = setup_obd_uuid(d != -1 ? d : p, path, param);
5678                 if (ret)
5679                         return ret;
5680         }
5681
5682         if (d != -1 && (param->fp_get_lmv || param->fp_get_default_lmv))
5683                 ret = cb_get_dirstripe(path, &d, param);
5684         else if (d != -1 ||
5685                  (p != -1 && !param->fp_get_lmv && !param->fp_get_default_lmv))
5686                 ret = get_lmd_info_fd(path, p, d, &param->fp_lmd->lmd_lmm,
5687                                       param->fp_lum_size, GET_LMD_STRIPE);
5688         else if (d == -1 && (param->fp_get_lmv || param->fp_get_default_lmv)) {
5689                 /* in case of a dangling or valid faked symlink dir, opendir()
5690                  * should have return either EINVAL or ENOENT, so let's try
5691                  * to get LMV just in case, and by opening it as a file but
5692                  * with O_NOFOLLOW ...
5693                  */
5694                 int fd = open(path, O_RDONLY | O_NOFOLLOW);
5695
5696                 if (fd == -1)
5697                         return 0;
5698                 ret = cb_get_dirstripe(path, &fd, param);
5699                 if (ret == 0)
5700                         llapi_lov_dump_user_lmm(param, path, LDF_IS_DIR);
5701                 close(fd);
5702                 return 0;
5703         } else
5704                 return 0;
5705
5706         if (ret) {
5707                 if (errno == ENODATA && d != -1) {
5708                         /*
5709                          * We need to "fake" the "use the default" values
5710                          * since the lmm struct is zeroed out at this point.
5711                          * The magic needs to be set in order to satisfy
5712                          * a check later on in the code path.
5713                          * The object_seq needs to be set for the "(Default)"
5714                          * prefix to be displayed.
5715                          */
5716                         if (param->fp_get_default_lmv) {
5717                                 struct lmv_user_md *lum = param->fp_lmv_md;
5718
5719                                 lum->lum_magic = LMV_USER_MAGIC;
5720                                 lum->lum_stripe_count = 0;
5721                                 lum->lum_stripe_offset = LMV_OFFSET_DEFAULT;
5722                                 goto dump;
5723                         } else if (param->fp_get_lmv) {
5724                                 struct lmv_user_md *lum = param->fp_lmv_md;
5725                                 int mdtidx;
5726
5727                                 ret = llapi_file_fget_mdtidx(d, &mdtidx);
5728                                 if (ret != 0)
5729                                         goto err_out;
5730                                 lum->lum_magic = LMV_MAGIC_V1;
5731                                 lum->lum_stripe_count = 0;
5732                                 lum->lum_stripe_offset = mdtidx;
5733                                 goto dump;
5734                         } else {
5735                                 struct lov_user_md *lmm =
5736                                         &param->fp_lmd->lmd_lmm;
5737
5738                                 lmm->lmm_magic = LOV_USER_MAGIC_V1;
5739                                 if (!param->fp_raw)
5740                                         ostid_set_seq(&lmm->lmm_oi,
5741                                                       FID_SEQ_LOV_DEFAULT);
5742                                 lmm->lmm_stripe_count = 0;
5743                                 lmm->lmm_stripe_size = 0;
5744                                 lmm->lmm_stripe_offset = -1;
5745                                 goto dump;
5746                         }
5747                 } else if (errno == ENODATA && p != -1) {
5748                         if (!param->fp_obd_uuid && !param->fp_mdt_uuid)
5749                                 llapi_printf(LLAPI_MSG_NORMAL,
5750                                              "%s has no stripe info\n", path);
5751                         goto out;
5752                 } else if (errno == ENOENT) {
5753                         llapi_error(LLAPI_MSG_WARN, -ENOENT,
5754                                     "warning: %s: %s does not exist",
5755                                     __func__, path);
5756                         goto out;
5757                 } else if (errno == ENOTTY) {
5758                         ret = -errno;
5759                         llapi_error(LLAPI_MSG_ERROR, ret,
5760                                     "%s: '%s' not on a Lustre fs?",
5761                                     __func__, path);
5762                 } else {
5763                         ret = -errno;
5764 err_out:
5765                         llapi_error(LLAPI_MSG_ERROR, ret,
5766                                     "error: %s: %s failed for %s",
5767                                      __func__, d != -1 ?
5768                                                "LL_IOC_LOV_GETSTRIPE" :
5769                                                "IOC_MDC_GETFILESTRIPE", path);
5770                 }
5771
5772                 return ret;
5773         }
5774
5775 dump:
5776         if (!(param->fp_verbose & VERBOSE_MDTINDEX))
5777                 llapi_lov_dump_user_lmm(param, path, d != -1 ? LDF_IS_DIR : 0);
5778
5779 out:
5780         /* Do not get down anymore? */
5781         if (param->fp_depth == param->fp_max_depth)
5782                 return 1;
5783
5784         param->fp_depth++;
5785
5786         return 0;
5787 }
5788
5789 int llapi_getstripe(char *path, struct find_param *param)
5790 {
5791         return param_callback(path, (param->fp_verbose & VERBOSE_MDTINDEX) ?
5792                               cb_get_mdt_index : cb_getstripe,
5793                               cb_common_fini, param);
5794 }
5795
5796 int llapi_obd_fstatfs(int fd, __u32 type, __u32 index,
5797                       struct obd_statfs *stat_buf, struct obd_uuid *uuid_buf)
5798 {
5799         char raw[MAX_IOC_BUFLEN] = {'\0'};
5800         char *rawbuf = raw;
5801         struct obd_ioctl_data data = { 0 };
5802         int rc = 0;
5803
5804         data.ioc_inlbuf1 = (char *)&type;
5805         data.ioc_inllen1 = sizeof(__u32);
5806         data.ioc_inlbuf2 = (char *)&index;
5807         data.ioc_inllen2 = sizeof(__u32);
5808         data.ioc_pbuf1 = (char *)stat_buf;
5809         data.ioc_plen1 = sizeof(struct obd_statfs);
5810         data.ioc_pbuf2 = (char *)uuid_buf;
5811         data.ioc_plen2 = sizeof(struct obd_uuid);
5812
5813         rc = llapi_ioctl_pack(&data, &rawbuf, sizeof(raw));
5814         if (rc != 0) {
5815                 llapi_error(LLAPI_MSG_ERROR, rc,
5816                             "%s: error packing ioctl data", __func__);
5817                 return rc;
5818         }
5819
5820         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
5821
5822         return rc < 0 ? -errno : 0;
5823 }
5824
5825 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
5826                      struct obd_statfs *stat_buf, struct obd_uuid *uuid_buf)
5827 {
5828         int fd;
5829         int rc;
5830
5831         fd = open(path, O_RDONLY);
5832         if (fd < 0) {
5833                 rc = -errno;
5834                 llapi_error(LLAPI_MSG_ERROR, rc, "error: %s: opening '%s'",
5835                             __func__, path);
5836                 /*
5837                  * If we can't even open a file on the filesystem (e.g. with
5838                  * -ESHUTDOWN), force caller to exit or it will loop forever.
5839                  */
5840                 return -ENODEV;
5841         }
5842
5843         rc = llapi_obd_fstatfs(fd, type, index, stat_buf, uuid_buf);
5844
5845         close(fd);
5846
5847         return rc;
5848 }
5849
5850 #define MAX_STRING_SIZE 128
5851
5852 int llapi_ping(char *obd_type, char *obd_name)
5853 {
5854         int flags = O_RDONLY;
5855         char buf[1] = { 0 };
5856         glob_t path;
5857         int rc, fd;
5858
5859         rc = cfs_get_param_paths(&path, "%s/%s/ping",
5860                                 obd_type, obd_name);
5861         if (rc != 0)
5862                 return -errno;
5863 retry_open:
5864         fd = open(path.gl_pathv[0], flags);
5865         if (fd < 0) {
5866                 if (errno == EACCES && flags == O_RDONLY) {
5867                         flags = O_WRONLY;
5868                         goto retry_open;
5869                 }
5870                 rc = -errno;
5871                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s",
5872                             path.gl_pathv[0]);
5873                 goto failed;
5874         }
5875
5876         if (flags == O_RDONLY)
5877                 rc = read(fd, buf, sizeof(buf));
5878         else
5879                 rc = write(fd, buf, sizeof(buf));
5880         if (rc < 0)
5881                 rc = -errno;
5882         close(fd);
5883
5884         if (rc == 1)
5885                 rc = 0;
5886 failed:
5887         cfs_free_param_data(&path);
5888         return rc;
5889 }
5890
5891 int llapi_target_iterate(int type_num, char **obd_type,
5892                          void *args, llapi_cb_t cb)
5893 {
5894         int i, rc = 0;
5895         glob_t param;
5896         FILE *fp;
5897
5898         for (i = 0; i < type_num; i++) {
5899                 int j;
5900
5901                 rc = cfs_get_param_paths(&param, "%s/*/uuid", obd_type[i]);
5902                 if (rc != 0)
5903                         continue;
5904
5905                 for (j = 0; j < param.gl_pathc; j++) {
5906                         char obd_uuid[UUID_MAX + 1];
5907                         char *obd_name;
5908                         char *ptr;
5909
5910                         fp = fopen(param.gl_pathv[j], "r");
5911                         if (fp == NULL) {
5912                                 rc = -errno;
5913                                 llapi_error(LLAPI_MSG_ERROR, rc,
5914                                             "error: opening '%s'",
5915                                             param.gl_pathv[j]);
5916                                 goto free_path;
5917                         }
5918
5919                         if (fgets(obd_uuid, sizeof(obd_uuid), fp) == NULL) {
5920                                 rc = -errno;
5921                                 llapi_error(LLAPI_MSG_ERROR, rc,
5922                                             "error: reading '%s'",
5923                                             param.gl_pathv[j]);
5924                                 goto free_path;
5925                         }
5926
5927                         /* Extract the obd_name from the sysfs path.
5928                          * 'topsysfs'/fs/lustre/'obd_type'/'obd_name'.
5929                          */
5930                         obd_name = strstr(param.gl_pathv[j], "/fs/lustre/");
5931                         if (!obd_name) {
5932                                 rc = -EINVAL;
5933                                 goto free_path;
5934                         }
5935
5936                         /* skip /fs/lustre/'obd_type'/ */
5937                         obd_name += strlen(obd_type[i]) + 12;
5938                         /* chop off after obd_name */
5939                         ptr = strrchr(obd_name, '/');
5940                         if (ptr)
5941                                 *ptr = '\0';
5942
5943                         cb(obd_type[i], obd_name, obd_uuid, args);
5944
5945                         fclose(fp);
5946                         fp = NULL;
5947                 }
5948         }
5949 free_path:
5950         if (fp)
5951                 fclose(fp);
5952         cfs_free_param_data(&param);
5953         return rc;
5954 }
5955
5956 static void do_target_check(char *obd_type_name, char *obd_name,
5957                             char *obd_uuid, void *args)
5958 {
5959         int rc;
5960
5961         rc = llapi_ping(obd_type_name, obd_name);
5962         if (rc == ENOTCONN)
5963                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
5964         else if (rc)
5965                 llapi_error(LLAPI_MSG_ERROR, rc, "error: check '%s'", obd_name);
5966         else
5967                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
5968 }
5969
5970 int llapi_target_check(int type_num, char **obd_type, char *dir)
5971 {
5972         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
5973 }
5974
5975 #undef MAX_STRING_SIZE
5976
5977 /* Is this a lustre fs? */
5978 int llapi_is_lustre_mnttype(const char *type)
5979 {
5980         return strcmp(type, "lustre") == 0 || strcmp(type, "lustre_tgt") == 0;
5981 }
5982
5983 /* Is this a lustre client fs? */
5984 int llapi_is_lustre_mnt(struct mntent *mnt)
5985 {
5986         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
5987                 strstr(mnt->mnt_fsname, ":/") != NULL);
5988 }
5989
5990 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
5991 {
5992         char fsname[PATH_MAX + 1];
5993         int root;
5994         int rc;
5995
5996         rc = llapi_search_fsname(mnt, fsname);
5997         if (rc)
5998                 return rc;
5999
6000         root = open(mnt, O_RDONLY | O_DIRECTORY);
6001         if (root < 0) {
6002                 rc = -errno;
6003                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot open '%s'", mnt);
6004                 return rc;
6005         }
6006
6007         rc = ioctl(root, OBD_IOC_QUOTACTL, qctl);
6008         if (rc < 0)
6009                 rc = -errno;
6010         if (rc == -ENOENT && LUSTRE_Q_CMD_IS_POOL(qctl->qc_cmd))
6011                 llapi_error(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO, rc,
6012                             "Cannot find pool '%s'", qctl->qc_poolname);
6013
6014         close(root);
6015         return rc;
6016 }
6017
6018 int llapi_get_connect_flags(const char *mnt, __u64 *flags)
6019 {
6020         int root;
6021         int rc;
6022
6023         root = open(mnt, O_RDONLY | O_DIRECTORY);
6024         if (root < 0) {
6025                 rc = -errno;
6026                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
6027                 return rc;
6028         }
6029
6030         rc = ioctl(root, LL_IOC_GET_CONNECT_FLAGS, flags);
6031         if (rc < 0) {
6032                 rc = -errno;
6033                 llapi_error(LLAPI_MSG_ERROR, rc,
6034                         "ioctl on %s for getting connect flags failed", mnt);
6035         }
6036         close(root);
6037         return rc;
6038 }
6039
6040 /**
6041  * Flush cached pages from all clients.
6042  *
6043  * \param fd    File descriptor
6044  * \retval 0    success
6045  * \retval < 0  error
6046  */
6047 int llapi_file_flush(int fd)
6048 {
6049         __u64 dv;
6050
6051         return llapi_get_data_version(fd, &dv, LL_DV_WR_FLUSH);
6052 }
6053