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