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