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