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