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