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