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