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