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