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