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