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