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