Whamcloud - gitweb
2d29c35247f29df9de3c0d6c5b996f5ea1b73479
[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 int llapi_file_get_stripe(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_lookup(int dirfd, const char *name)
4097 {
4098         struct obd_ioctl_data data = { 0 };
4099         char rawbuf[8192];
4100         char *buf = rawbuf;
4101         int rc;
4102
4103         if (dirfd < 0 || name == NULL)
4104                 return -EINVAL;
4105
4106         data.ioc_version = OBD_IOCTL_VERSION;
4107         data.ioc_len = sizeof(data);
4108         data.ioc_inlbuf1 = (char *)name;
4109         data.ioc_inllen1 = strlen(name) + 1;
4110
4111         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
4112         if (rc) {
4113                 llapi_error(LLAPI_MSG_ERROR, rc,
4114                             "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
4115                             name, rc);
4116                 return rc;
4117         }
4118
4119         rc = ioctl(dirfd, IOC_MDC_LOOKUP, buf);
4120         if (rc < 0)
4121                 rc = -errno;
4122         return rc;
4123 }
4124
4125 /*
4126  * Check if the file time matches all the given criteria (e.g. --atime +/-N).
4127  * Return -1 or 1 if file timestamp does not or does match the given criteria
4128  * correspondingly. Return 0 if the MDS time is being checked and there are
4129  * attributes on OSTs and it is not yet clear if the timespamp matches.
4130  *
4131  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
4132  * updated timestamps.
4133  */
4134 static int find_time_check(struct find_param *param, int mds)
4135 {
4136         struct lov_user_mds_data *lmd = param->fp_lmd;
4137         int rc = 1;
4138         int rc2;
4139
4140         /* Check if file is accepted. */
4141         if (param->fp_atime) {
4142                 rc2 = find_value_cmp(lmd->lmd_stx.stx_atime.tv_sec,
4143                                      param->fp_atime, param->fp_asign,
4144                                      param->fp_exclude_atime,
4145                                      param->fp_time_margin, mds);
4146                 if (rc2 < 0)
4147                         return rc2;
4148                 rc = rc2;
4149         }
4150
4151         if (param->fp_mtime) {
4152                 rc2 = find_value_cmp(lmd->lmd_stx.stx_mtime.tv_sec,
4153                                      param->fp_mtime, param->fp_msign,
4154                                      param->fp_exclude_mtime,
4155                                      param->fp_time_margin, mds);
4156                 if (rc2 < 0)
4157                         return rc2;
4158
4159                 /*
4160                  * If the previous check matches, but this one is not yet clear,
4161                  * we should return 0 to do an RPC on OSTs.
4162                  */
4163                 if (rc == 1)
4164                         rc = rc2;
4165         }
4166
4167         if (param->fp_ctime) {
4168                 rc2 = find_value_cmp(lmd->lmd_stx.stx_ctime.tv_sec,
4169                                      param->fp_ctime, param->fp_csign,
4170                                      param->fp_exclude_ctime,
4171                                      param->fp_time_margin, mds);
4172                 if (rc2 < 0)
4173                         return rc2;
4174
4175                 /*
4176                  * If the previous check matches, but this one is not yet clear,
4177                  * we should return 0 to do an RPC on OSTs.
4178                  */
4179                 if (rc == 1)
4180                         rc = rc2;
4181         }
4182
4183         return rc;
4184 }
4185
4186 static int find_newerxy_check(struct find_param *param, int mds, bool from_mdt)
4187 {
4188         struct lov_user_mds_data *lmd = param->fp_lmd;
4189         int i;
4190         int rc = 1;
4191         int rc2;
4192
4193         for (i = 0; i < 2; i++) {
4194                 /* Check if file is accepted. */
4195                 if (param->fp_newery[NEWERXY_ATIME][i]) {
4196                         rc2 = find_value_cmp(lmd->lmd_stx.stx_atime.tv_sec,
4197                                              param->fp_newery[NEWERXY_ATIME][i],
4198                                              -1, i, 0, mds);
4199                         if (rc2 < 0)
4200                                 return rc2;
4201                         rc = rc2;
4202                 }
4203
4204                 if (param->fp_newery[NEWERXY_MTIME][i]) {
4205                         rc2 = find_value_cmp(lmd->lmd_stx.stx_mtime.tv_sec,
4206                                              param->fp_newery[NEWERXY_MTIME][i],
4207                                              -1, i, 0, mds);
4208                         if (rc2 < 0)
4209                                 return rc2;
4210
4211                         /*
4212                          * If the previous check matches, but this one is not
4213                          * yet clear, we should return 0 to do an RPC on OSTs.
4214                          */
4215                         if (rc == 1)
4216                                 rc = rc2;
4217                 }
4218
4219                 if (param->fp_newery[NEWERXY_CTIME][i]) {
4220                         rc2 = find_value_cmp(lmd->lmd_stx.stx_ctime.tv_sec,
4221                                              param->fp_newery[NEWERXY_CTIME][i],
4222                                              -1, i, 0, mds);
4223                         if (rc2 < 0)
4224                                 return rc2;
4225
4226                         /*
4227                          * If the previous check matches, but this one is not
4228                          * yet clear, we should return 0 to do an RPC on OSTs.
4229                          */
4230                         if (rc == 1)
4231                                 rc = rc2;
4232                 }
4233
4234                 /*
4235                  * File birth time (btime) can get from MDT directly.
4236                  * if @from_mdt is true, it means the input file attributs are
4237                  * obtained directly from MDT.
4238                  * Thus, if @from_mdt is false, we should skip the following
4239                  * btime check.
4240                  */
4241                 if (!from_mdt)
4242                         continue;
4243
4244                 if (param->fp_newery[NEWERXY_BTIME][i]) {
4245                         if (!(lmd->lmd_stx.stx_mask & STATX_BTIME))
4246                                 return -EOPNOTSUPP;
4247
4248                         rc2 = find_value_cmp(lmd->lmd_stx.stx_btime.tv_sec,
4249                                              param->fp_newery[NEWERXY_BTIME][i],
4250                                              -1, i, 0, 0);
4251                         if (rc2 < 0)
4252                                 return rc2;
4253                 }
4254         }
4255
4256         return rc;
4257 }
4258
4259 /**
4260  * Check whether the stripes matches the indexes user provided
4261  *       1   : matched
4262  *       0   : Unmatched
4263  */
4264 static int check_obd_match(struct find_param *param)
4265 {
4266         struct lov_user_ost_data_v1 *objects;
4267         struct lov_comp_md_v1 *comp_v1 = NULL;
4268         struct lov_user_mds_data *lmd = param->fp_lmd;
4269         struct lov_user_md_v1 *v1 = &lmd->lmd_lmm;
4270         int i, j, k, count = 1;
4271
4272         if (param->fp_obd_uuid && param->fp_obd_index == OBD_NOT_FOUND)
4273                 return 0;
4274
4275         if (!S_ISREG(lmd->lmd_stx.stx_mode))
4276                 return 0;
4277
4278         /* exclude foreign */
4279         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4280                 return param->fp_exclude_obd;
4281
4282         /*
4283          * Only those files should be accepted, which have a
4284          * stripe on the specified OST.
4285          */
4286         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4287                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4288                 count = comp_v1->lcm_entry_count;
4289         }
4290
4291         for (i = 0; i < count; i++) {
4292                 if (comp_v1)
4293                         v1 = lov_comp_entry(comp_v1, i);
4294
4295                 objects = lov_v1v3_objects(v1);
4296
4297                 for (j = 0; j < v1->lmm_stripe_count; j++) {
4298                         if (comp_v1 && !(comp_v1->lcm_entries[i].lcme_flags &
4299                                          LCME_FL_INIT))
4300                                 continue;
4301                         for (k = 0; k < param->fp_num_obds; k++) {
4302                                 if (param->fp_obd_indexes[k] ==
4303                                     objects[j].l_ost_idx)
4304                                         return !param->fp_exclude_obd;
4305                         }
4306                 }
4307         }
4308
4309         return param->fp_exclude_obd;
4310 }
4311
4312 static int check_mdt_match(struct find_param *param)
4313 {
4314         int i;
4315
4316         if (param->fp_mdt_uuid && param->fp_mdt_index == OBD_NOT_FOUND)
4317                 return 0;
4318
4319         /* FIXME: For striped dir, we should get stripe information and check */
4320         for (i = 0; i < param->fp_num_mdts; i++) {
4321                 if (param->fp_mdt_indexes[i] == param->fp_file_mdt_index)
4322                         return !param->fp_exclude_mdt;
4323         }
4324
4325         if (param->fp_exclude_mdt)
4326                 return 1;
4327
4328         return 0;
4329 }
4330
4331 /**
4332  * Check whether the obd is active or not, if it is
4333  * not active, just print the object affected by this
4334  * failed target
4335  **/
4336 static void print_failed_tgt(struct find_param *param, char *path, int type)
4337 {
4338         struct obd_statfs stat_buf;
4339         struct obd_uuid uuid_buf;
4340         int tgt_nr, i, *indexes;
4341         int ret = 0;
4342
4343         if (type != LL_STATFS_LOV && type != LL_STATFS_LMV) {
4344                 llapi_error(LLAPI_MSG_NORMAL, ret, "%s: wrong statfs type(%d)",
4345                             __func__, type);
4346                 return;
4347         }
4348
4349         tgt_nr = (type == LL_STATFS_LOV) ? param->fp_obd_index :
4350                  param->fp_mdt_index;
4351         indexes = (type == LL_STATFS_LOV) ? param->fp_obd_indexes :
4352                   param->fp_mdt_indexes;
4353
4354         for (i = 0; i < tgt_nr; i++) {
4355                 memset(&stat_buf, 0, sizeof(struct obd_statfs));
4356                 memset(&uuid_buf, 0, sizeof(struct obd_uuid));
4357
4358                 ret = llapi_obd_statfs(path, type, indexes[i], &stat_buf,
4359                                        &uuid_buf);
4360                 if (ret)
4361                         llapi_error(LLAPI_MSG_NORMAL, ret,
4362                                     "%s: obd_uuid: %s failed",
4363                                     __func__, param->fp_obd_uuid->uuid);
4364         }
4365 }
4366
4367 static int find_check_stripe_size(struct find_param *param)
4368 {
4369         struct lov_comp_md_v1 *comp_v1 = NULL;
4370         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4371         __u32 stripe_size = 0;
4372         int ret, i, count = 1;
4373
4374         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4375                 return param->fp_exclude_stripe_size ? 1 : -1;
4376
4377         ret = param->fp_exclude_stripe_size ? 1 : -1;
4378         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4379                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4380                 count = comp_v1->lcm_entry_count;
4381         }
4382
4383         for (i = 0; i < count; i++) {
4384                 struct lov_comp_md_entry_v1 *ent;
4385
4386                 if (comp_v1) {
4387                         v1 = lov_comp_entry(comp_v1, i);
4388
4389                         ent = &comp_v1->lcm_entries[i];
4390                         if (ent->lcme_flags & LCME_FL_EXTENSION)
4391                                 continue;
4392                         if (!(ent->lcme_flags & LCME_FL_INIT))
4393                                 continue;
4394                 }
4395                 stripe_size = v1->lmm_stripe_size;
4396         }
4397
4398         ret = find_value_cmp(stripe_size, param->fp_stripe_size,
4399                              param->fp_stripe_size_sign,
4400                              param->fp_exclude_stripe_size,
4401                              param->fp_stripe_size_units, 0);
4402
4403         return ret;
4404 }
4405
4406 static int find_check_ext_size(struct find_param *param)
4407 {
4408         struct lov_comp_md_v1 *comp_v1;
4409         struct lov_user_md_v1 *v1;
4410         int ret, i;
4411
4412         ret = param->fp_exclude_ext_size ? 1 : -1;
4413         comp_v1 = (struct lov_comp_md_v1 *)&param->fp_lmd->lmd_lmm;
4414         if (comp_v1->lcm_magic != LOV_USER_MAGIC_COMP_V1)
4415                 return ret;
4416
4417         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
4418                 struct lov_comp_md_entry_v1 *ent;
4419
4420                 v1 = lov_comp_entry(comp_v1, i);
4421
4422                 ent = &comp_v1->lcm_entries[i];
4423                 if (!(ent->lcme_flags & LCME_FL_EXTENSION))
4424                         continue;
4425
4426                 ret = find_value_cmp(v1->lmm_stripe_size, param->fp_ext_size,
4427                                      param->fp_ext_size_sign,
4428                                      param->fp_exclude_ext_size,
4429                                      param->fp_ext_size_units, 0);
4430                 /* If any ext_size matches */
4431                 if (ret != -1)
4432                         break;
4433         }
4434
4435         return ret;
4436 }
4437
4438 static __u32 find_get_stripe_count(struct find_param *param)
4439 {
4440         struct lov_comp_md_v1 *comp_v1 = NULL;
4441         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4442         int i, count = 1;
4443         __u32 stripe_count = 0;
4444
4445         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4446                 return 0;
4447
4448         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4449                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4450                 count = comp_v1->lcm_entry_count;
4451         }
4452
4453         for (i = 0; i < count; i++) {
4454                 if (comp_v1) {
4455                         struct lov_comp_md_entry_v1 *ent;
4456
4457                         v1 = lov_comp_entry(comp_v1, i);
4458
4459                         ent = &comp_v1->lcm_entries[i];
4460                         if (!(ent->lcme_flags & LCME_FL_INIT))
4461                                 continue;
4462
4463                         if (ent->lcme_flags & LCME_FL_EXTENSION)
4464                                 continue;
4465                 }
4466                 stripe_count = v1->lmm_stripe_count;
4467         }
4468
4469         return stripe_count;
4470 }
4471
4472 #define LOV_PATTERN_INVALID     0xFFFFFFFF
4473
4474 static int find_check_layout(struct find_param *param)
4475 {
4476         struct lov_comp_md_v1 *comp_v1 = NULL;
4477         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4478         int i, count = 1;
4479         bool found = false, valid = false;
4480
4481         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4482                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4483                 count = comp_v1->lcm_entry_count;
4484         }
4485
4486         for (i = 0; i < count; i++) {
4487                 if (comp_v1)
4488                         v1 = lov_comp_entry(comp_v1, i);
4489
4490                 /* foreign file have a special magic but no pattern field */
4491                 if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4492                         continue;
4493
4494                 if (v1->lmm_pattern == LOV_PATTERN_INVALID)
4495                         continue;
4496
4497                 valid = true;
4498                 if (v1->lmm_pattern & param->fp_layout) {
4499                         found = true;
4500                         break;
4501                 }
4502         }
4503
4504         if (!valid)
4505                 return -1;
4506
4507         if ((found && !param->fp_exclude_layout) ||
4508             (!found && param->fp_exclude_layout))
4509                 return 1;
4510
4511         return -1;
4512 }
4513
4514 /*
4515  * if no type specified, check/exclude all foreign
4516  * if type specified, check all foreign&type and exclude !foreign + foreign&type
4517  */
4518 static int find_check_foreign(struct find_param *param)
4519 {
4520         if (S_ISREG(param->fp_lmd->lmd_stx.stx_mode)) {
4521                 struct lov_foreign_md *lfm;
4522
4523                 lfm = (void *)&param->fp_lmd->lmd_lmm;
4524                 if (lfm->lfm_magic != LOV_USER_MAGIC_FOREIGN) {
4525                         if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN)
4526                                 return param->fp_exclude_foreign ? 1 : -1;
4527                         return -1;
4528                 }
4529
4530                 if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN ||
4531                     lfm->lfm_type == param->fp_foreign_type)
4532                         return param->fp_exclude_foreign ? -1 : 1;
4533                 return param->fp_exclude_foreign ? 1 : -1;
4534         }
4535
4536         if (S_ISDIR(param->fp_lmd->lmd_stx.stx_mode)) {
4537                 struct lmv_foreign_md *lfm;
4538
4539                 lfm = (void *)param->fp_lmv_md;
4540                 if (lfm->lfm_magic != LMV_MAGIC_FOREIGN) {
4541                         if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN)
4542                                 return param->fp_exclude_foreign ? 1 : -1;
4543                         return -1;
4544                 }
4545
4546                 if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN ||
4547                     lfm->lfm_type == param->fp_foreign_type)
4548                         return param->fp_exclude_foreign ? -1 : 1;
4549                 return param->fp_exclude_foreign ? 1 : -1;
4550         }
4551         return -1;
4552 }
4553
4554 static int find_check_pool(struct find_param *param)
4555 {
4556         struct lov_comp_md_v1 *comp_v1 = NULL;
4557         struct lov_user_md_v3 *v3 = (void *)&param->fp_lmd->lmd_lmm;
4558         int i, count = 1;
4559         bool found = false;
4560
4561         if (v3->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4562                 comp_v1 = (struct lov_comp_md_v1 *)v3;
4563                 count = comp_v1->lcm_entry_count;
4564                 /* empty requested pool is taken as no pool search */
4565                 if (count == 0 && param->fp_poolname[0] == '\0') {
4566                         found = true;
4567                         goto found;
4568                 }
4569         }
4570
4571         for (i = 0; i < count; i++) {
4572                 if (comp_v1 != NULL) {
4573                         if (!(comp_v1->lcm_entries[i].lcme_flags &
4574                               LCME_FL_INIT))
4575                                 continue;
4576
4577                         v3 = (void *)lov_comp_entry(comp_v1, i);
4578                 }
4579
4580                 if (v3->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4581                         continue;
4582
4583                 if (((v3->lmm_magic == LOV_USER_MAGIC_V1) &&
4584                      (param->fp_poolname[0] == '\0')) ||
4585                     ((v3->lmm_magic == LOV_USER_MAGIC_V3) &&
4586                      (strncmp(v3->lmm_pool_name,
4587                               param->fp_poolname, LOV_MAXPOOLNAME) == 0)) ||
4588                     ((v3->lmm_magic == LOV_USER_MAGIC_V3) &&
4589                      (strcmp(param->fp_poolname, "*") == 0))) {
4590                         found = true;
4591                         break;
4592                 }
4593         }
4594
4595 found:
4596         if ((found && !param->fp_exclude_pool) ||
4597             (!found && param->fp_exclude_pool))
4598                 return 1;
4599
4600         return -1;
4601 }
4602
4603 static int find_check_comp_options(struct find_param *param)
4604 {
4605         struct lov_comp_md_v1 *comp_v1, *forged_v1 = NULL;
4606         struct lov_user_mds_data *lmd = param->fp_lmd;
4607         struct lov_user_md_v1 *v1 = &lmd->lmd_lmm;
4608         struct lov_comp_md_entry_v1 *entry;
4609         int i, ret = 0;
4610
4611         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4612                 return -1;
4613
4614         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4615                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4616         } else {
4617                 forged_v1 = malloc(sizeof(*forged_v1) + sizeof(*entry));
4618                 if (forged_v1 == NULL)
4619                         return -1;
4620                 comp_v1 = forged_v1;
4621                 comp_v1->lcm_entry_count = 1;
4622                 entry = &comp_v1->lcm_entries[0];
4623                 entry->lcme_flags = S_ISDIR(lmd->lmd_stx.stx_mode) ?
4624                                     0 : LCME_FL_INIT;
4625                 entry->lcme_extent.e_start = 0;
4626                 entry->lcme_extent.e_end = LUSTRE_EOF;
4627         }
4628
4629         /* invalid case, don't match for any kind of search. */
4630         if (comp_v1->lcm_entry_count == 0) {
4631                 ret = -1;
4632                 goto out;
4633         }
4634
4635         if (param->fp_check_comp_count) {
4636                 ret = find_value_cmp(forged_v1 ? 0 : comp_v1->lcm_entry_count,
4637                                      param->fp_comp_count,
4638                                      param->fp_comp_count_sign,
4639                                      param->fp_exclude_comp_count, 1, 0);
4640                 if (ret == -1)
4641                         goto out;
4642         }
4643
4644         ret = 1;
4645         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
4646                 entry = &comp_v1->lcm_entries[i];
4647
4648                 if (param->fp_check_comp_flags) {
4649                         ret = 1;
4650                         if (((param->fp_comp_flags & entry->lcme_flags) !=
4651                              param->fp_comp_flags) ||
4652                             (param->fp_comp_neg_flags & entry->lcme_flags)) {
4653                                 ret = -1;
4654                                 continue;
4655                         }
4656                 }
4657
4658                 if (param->fp_check_comp_start) {
4659                         ret = find_value_cmp(entry->lcme_extent.e_start,
4660                                              param->fp_comp_start,
4661                                              param->fp_comp_start_sign,
4662                                              param->fp_exclude_comp_start,
4663                                              param->fp_comp_start_units, 0);
4664                         if (ret == -1)
4665                                 continue;
4666                 }
4667
4668                 if (param->fp_check_comp_end) {
4669                         ret = find_comp_end_cmp(entry->lcme_extent.e_end,
4670                                                 param);
4671                         if (ret == -1)
4672                                 continue;
4673                 }
4674
4675                 /* the component matches all criteria */
4676                 break;
4677         }
4678 out:
4679         if (forged_v1)
4680                 free(forged_v1);
4681         return ret;
4682 }
4683
4684 static int find_check_mirror_options(struct find_param *param)
4685 {
4686         struct lov_comp_md_v1 *comp_v1;
4687         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4688         int ret = 0;
4689
4690         if (v1->lmm_magic != LOV_USER_MAGIC_COMP_V1)
4691                 return -1;
4692
4693         comp_v1 = (struct lov_comp_md_v1 *)v1;
4694
4695         if (param->fp_check_mirror_count) {
4696                 ret = find_value_cmp(comp_v1->lcm_mirror_count + 1,
4697                                      param->fp_mirror_count,
4698                                      param->fp_mirror_count_sign,
4699                                      param->fp_exclude_mirror_count, 1, 0);
4700                 if (ret == -1)
4701                         return ret;
4702         }
4703
4704         if (param->fp_check_mirror_state) {
4705                 ret = 1;
4706                 __u16 file_state = comp_v1->lcm_flags & LCM_FL_FLR_MASK;
4707
4708                 if ((param->fp_mirror_state != 0 &&
4709                     file_state != param->fp_mirror_state) ||
4710                     file_state == param->fp_mirror_neg_state)
4711                         return -1;
4712         }
4713
4714         return ret;
4715 }
4716
4717 static bool find_check_lmm_info(struct find_param *param)
4718 {
4719         return param->fp_check_pool || param->fp_check_stripe_count ||
4720                param->fp_check_stripe_size || param->fp_check_layout ||
4721                param->fp_check_comp_count || param->fp_check_comp_end ||
4722                param->fp_check_comp_start || param->fp_check_comp_flags ||
4723                param->fp_check_mirror_count || param->fp_check_foreign ||
4724                param->fp_check_mirror_state || param->fp_check_ext_size ||
4725                param->fp_check_projid;
4726 }
4727
4728 /*
4729  * Get file/directory project id.
4730  * by the open fd resides on.
4731  * Return 0 and project id on success, or -ve errno.
4732  */
4733 static int fget_projid(int fd, int *projid)
4734 {
4735         struct fsxattr fsx;
4736         int rc;
4737
4738         rc = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
4739         if (rc)
4740                 return -errno;
4741
4742         *projid = fsx.fsx_projid;
4743         return 0;
4744 }
4745
4746 static int cb_find_init(char *path, int p, int *dp,
4747                         void *data, struct dirent64 *de)
4748 {
4749         struct find_param *param = (struct find_param *)data;
4750         struct lov_user_mds_data *lmd = param->fp_lmd;
4751         int d = dp == NULL ? -1 : *dp;
4752         int decision = 1; /* 1 is accepted; -1 is rejected. */
4753         int lustre_fs = 1;
4754         int checked_type = 0;
4755         int ret = 0;
4756         __u32 stripe_count = 0;
4757         __u64 flags;
4758         int fd = -2;
4759
4760         if (p == -1 && d == -1)
4761                 return -EINVAL;
4762
4763         /* If a regular expression is presented, make the initial decision */
4764         if (param->fp_pattern != NULL) {
4765                 char *fname = strrchr(path, '/');
4766
4767                 fname = (fname == NULL ? path : fname + 1);
4768                 ret = fnmatch(param->fp_pattern, fname, 0);
4769                 if ((ret == FNM_NOMATCH && !param->fp_exclude_pattern) ||
4770                     (ret == 0 && param->fp_exclude_pattern))
4771                         goto decided;
4772         }
4773
4774         /* See if we can check the file type from the dirent. */
4775         if (param->fp_type != 0 && de != NULL && de->d_type != DT_UNKNOWN) {
4776                 checked_type = 1;
4777
4778                 if (DTTOIF(de->d_type) == param->fp_type) {
4779                         if (param->fp_exclude_type)
4780                                 goto decided;
4781                 } else {
4782                         if (!param->fp_exclude_type)
4783                                 goto decided;
4784                 }
4785         }
4786
4787         ret = 0;
4788
4789         /*
4790          * Request MDS for the stat info if some of these parameters need
4791          * to be compared.
4792          */
4793         if (param->fp_obd_uuid || param->fp_mdt_uuid ||
4794             param->fp_check_uid || param->fp_check_gid ||
4795             param->fp_newerxy || param->fp_btime ||
4796             param->fp_atime || param->fp_mtime || param->fp_ctime ||
4797             param->fp_check_size || param->fp_check_blocks ||
4798             find_check_lmm_info(param) ||
4799             param->fp_check_mdt_count || param->fp_hash_type ||
4800             param->fp_check_hash_flag)
4801                 decision = 0;
4802
4803         if (param->fp_type != 0 && checked_type == 0)
4804                 decision = 0;
4805
4806         if (decision == 0) {
4807                 if (d != -1 && (param->fp_check_mdt_count ||
4808                     param->fp_hash_type || param->fp_check_foreign ||
4809                     param->fp_check_hash_flag)) {
4810                         param->fp_get_lmv = 1;
4811                         ret = cb_get_dirstripe(path, &d, param);
4812                         if (ret != 0) {
4813                                 /*
4814                                  * XXX this works to decide for foreign
4815                                  * criterion only
4816                                  */
4817                                 if (errno == ENODATA &&
4818                                     param->fp_check_foreign) {
4819                                         if (param->fp_exclude_foreign)
4820                                                 goto foreign;
4821                                         goto decided;
4822                                 }
4823                                 return ret;
4824                         }
4825                 }
4826
4827                 param->fp_lmd->lmd_lmm.lmm_magic = 0;
4828                 ret = get_lmd_info_fd(path, p, d, param->fp_lmd,
4829                                       param->fp_lum_size, GET_LMD_INFO);
4830                 if (ret == 0 && param->fp_lmd->lmd_lmm.lmm_magic == 0 &&
4831                     find_check_lmm_info(param)) {
4832                         struct lov_user_md *lmm = &param->fp_lmd->lmd_lmm;
4833
4834                         /*
4835                          * We need to "fake" the "use the default" values
4836                          * since the lmm struct is zeroed out at this point.
4837                          */
4838                         lmm->lmm_magic = LOV_USER_MAGIC_V1;
4839                         lmm->lmm_pattern = LOV_PATTERN_DEFAULT;
4840                         if (!param->fp_raw)
4841                                 ostid_set_seq(&lmm->lmm_oi,
4842                                               FID_SEQ_LOV_DEFAULT);
4843                         lmm->lmm_stripe_size = 0;
4844                         lmm->lmm_stripe_count = 0;
4845                         lmm->lmm_stripe_offset = -1;
4846                 }
4847                 if (ret == 0 && param->fp_mdt_uuid != NULL) {
4848                         if (d != -1) {
4849                                 ret = llapi_file_fget_mdtidx(d,
4850                                                      &param->fp_file_mdt_index);
4851                         } else if (S_ISREG(lmd->lmd_stx.stx_mode)) {
4852                                 /*
4853                                  * FIXME: we could get the MDT index from the
4854                                  * file's FID in lmd->lmd_lmm.lmm_oi without
4855                                  * opening the file, once we are sure that
4856                                  * LFSCK2 (2.6) has fixed up pre-2.0 LOV EAs.
4857                                  * That would still be an ioctl() to map the
4858                                  * FID to the MDT, but not an open RPC.
4859                                  */
4860                                 fd = open(path, O_RDONLY);
4861                                 if (fd > 0) {
4862                                         ret = llapi_file_fget_mdtidx(fd,
4863                                                      &param->fp_file_mdt_index);
4864                                 } else {
4865                                         ret = -errno;
4866                                 }
4867                         } else {
4868                                 /*
4869                                  * For a special file, we assume it resides on
4870                                  * the same MDT as the parent directory.
4871                                  */
4872                                 ret = llapi_file_fget_mdtidx(p,
4873                                                      &param->fp_file_mdt_index);
4874                         }
4875                 }
4876                 if (ret != 0) {
4877                         if (ret == -ENOTTY)
4878                                 lustre_fs = 0;
4879                         if (ret == -ENOENT)
4880                                 goto decided;
4881
4882                         goto out;
4883                 } else {
4884                         stripe_count = find_get_stripe_count(param);
4885                 }
4886         }
4887
4888         if (param->fp_type && !checked_type) {
4889                 if ((lmd->lmd_stx.stx_mode & S_IFMT) == param->fp_type) {
4890                         if (param->fp_exclude_type)
4891                                 goto decided;
4892                 } else {
4893                         if (!param->fp_exclude_type)
4894                                 goto decided;
4895                 }
4896         }
4897
4898         /* Prepare odb. */
4899         if (param->fp_obd_uuid || param->fp_mdt_uuid) {
4900                 if (lustre_fs && param->fp_got_uuids &&
4901                     param->fp_dev != makedev(lmd->lmd_stx.stx_dev_major,
4902                                              lmd->lmd_stx.stx_dev_minor)) {
4903                         /* A lustre/lustre mount point is crossed. */
4904                         param->fp_got_uuids = 0;
4905                         param->fp_obds_printed = 0;
4906                         param->fp_mdt_index = OBD_NOT_FOUND;
4907                         param->fp_obd_index = OBD_NOT_FOUND;
4908                 }
4909
4910                 if (lustre_fs && !param->fp_got_uuids) {
4911                         ret = setup_target_indexes((d != -1) ? d : p, path,
4912                                                    param);
4913                         if (ret)
4914                                 goto out;
4915
4916                         param->fp_dev = makedev(lmd->lmd_stx.stx_dev_major,
4917                                                 lmd->lmd_stx.stx_dev_minor);
4918                 } else if (!lustre_fs && param->fp_got_uuids) {
4919                         /* A lustre/non-lustre mount point is crossed. */
4920                         param->fp_got_uuids = 0;
4921                         param->fp_mdt_index = OBD_NOT_FOUND;
4922                         param->fp_obd_index = OBD_NOT_FOUND;
4923                 }
4924         }
4925
4926         if (param->fp_check_foreign) {
4927                 decision = find_check_foreign(param);
4928                 if (decision == -1)
4929                         goto decided;
4930         }
4931
4932         if (param->fp_check_stripe_size) {
4933                 decision = find_check_stripe_size(param);
4934                 if (decision == -1)
4935                         goto decided;
4936         }
4937
4938         if (param->fp_check_ext_size) {
4939                 decision = find_check_ext_size(param);
4940                 if (decision == -1)
4941                         goto decided;
4942         }
4943
4944         if (param->fp_check_stripe_count) {
4945                 decision = find_value_cmp(stripe_count, param->fp_stripe_count,
4946                                           param->fp_stripe_count_sign,
4947                                           param->fp_exclude_stripe_count, 1, 0);
4948                 if (decision == -1)
4949                         goto decided;
4950         }
4951
4952         if (param->fp_check_mdt_count) {
4953                 if (param->fp_lmv_md->lum_magic == LMV_MAGIC_FOREIGN) {
4954                         decision = -1;
4955                         goto decided;
4956                 }
4957
4958                 decision = find_value_cmp(
4959                                 param->fp_lmv_md->lum_stripe_count,
4960                                 param->fp_mdt_count,
4961                                 param->fp_mdt_count_sign,
4962                                 param->fp_exclude_mdt_count, 1, 0);
4963                 if (decision == -1)
4964                         goto decided;
4965         }
4966
4967         if (param->fp_check_layout) {
4968                 decision = find_check_layout(param);
4969                 if (decision == -1)
4970                         goto decided;
4971         }
4972
4973         if (param->fp_hash_type) {
4974                 __u32 found;
4975                 __u32 type = param->fp_lmv_md->lum_hash_type &
4976                              LMV_HASH_TYPE_MASK;
4977
4978                 if (param->fp_lmv_md->lum_magic == LMV_MAGIC_FOREIGN) {
4979                         decision = -1;
4980                         goto decided;
4981                 }
4982
4983                 found = (1 << type) & param->fp_hash_type;
4984                 if ((found && param->fp_exclude_hash_type) ||
4985                     (!found && !param->fp_exclude_hash_type)) {
4986                         decision = -1;
4987                         goto decided;
4988                 }
4989         }
4990
4991         if (param->fp_check_hash_flag) {
4992                 __u32 flags = param->fp_lmv_md->lum_hash_type &
4993                               ~LMV_HASH_TYPE_MASK;
4994
4995                 if (param->fp_lmv_md->lum_magic == LMV_MAGIC_FOREIGN) {
4996                         decision = -1;
4997                         goto decided;
4998                 }
4999
5000                 if (!(flags & param->fp_hash_inflags) ||
5001                      (flags & param->fp_hash_exflags)) {
5002                         decision = -1;
5003                         goto decided;
5004                 }
5005         }
5006
5007         /* If an OBD UUID is specified but none matches, skip this file. */
5008         if ((param->fp_obd_uuid && param->fp_obd_index == OBD_NOT_FOUND) ||
5009             (param->fp_mdt_uuid && param->fp_mdt_index == OBD_NOT_FOUND))
5010                 goto decided;
5011
5012         /*
5013          * If an OST or MDT UUID is given, and some OST matches,
5014          * check it here.
5015          */
5016         if (param->fp_obd_index != OBD_NOT_FOUND ||
5017             param->fp_mdt_index != OBD_NOT_FOUND) {
5018                 if (param->fp_obd_uuid) {
5019                         if (check_obd_match(param)) {
5020                                 /*
5021                                  * If no mdtuuid is given, we are done.
5022                                  * Otherwise, fall through to the mdtuuid
5023                                  * check below.
5024                                  */
5025                                 if (!param->fp_mdt_uuid)
5026                                         goto obd_matches;
5027                         } else {
5028                                 goto decided;
5029                         }
5030                 }
5031
5032                 if (param->fp_mdt_uuid) {
5033                         if (check_mdt_match(param))
5034                                 goto obd_matches;
5035                         goto decided;
5036                 }
5037         }
5038
5039 obd_matches:
5040         if (param->fp_check_uid) {
5041                 if (lmd->lmd_stx.stx_uid == param->fp_uid) {
5042                         if (param->fp_exclude_uid)
5043                                 goto decided;
5044                 } else {
5045                         if (!param->fp_exclude_uid)
5046                                 goto decided;
5047                 }
5048         }
5049
5050         if (param->fp_check_gid) {
5051                 if (lmd->lmd_stx.stx_gid == param->fp_gid) {
5052                         if (param->fp_exclude_gid)
5053                                 goto decided;
5054                 } else {
5055                         if (!param->fp_exclude_gid)
5056                                 goto decided;
5057                 }
5058         }
5059
5060         if (param->fp_check_projid) {
5061                 int projid = 0;
5062
5063                 if (fd == -2)
5064                         fd = open(path, O_RDONLY);
5065
5066                 if (fd > 0)
5067                         ret = fget_projid(fd, &projid);
5068                 else
5069                         ret = -errno;
5070                 if (ret)
5071                         goto out;
5072                 if (projid == param->fp_projid) {
5073                         if (param->fp_exclude_projid)
5074                                 goto decided;
5075                 } else {
5076                         if (!param->fp_exclude_projid)
5077                                 goto decided;
5078                 }
5079         }
5080
5081         if (param->fp_check_pool) {
5082                 decision = find_check_pool(param);
5083                 if (decision == -1)
5084                         goto decided;
5085         }
5086
5087         if (param->fp_check_comp_count || param->fp_check_comp_flags ||
5088             param->fp_check_comp_start || param->fp_check_comp_end) {
5089                 decision = find_check_comp_options(param);
5090                 if (decision == -1)
5091                         goto decided;
5092         }
5093
5094         if (param->fp_check_mirror_count || param->fp_check_mirror_state) {
5095                 decision = find_check_mirror_options(param);
5096                 if (decision == -1)
5097                         goto decided;
5098         }
5099
5100         /* Check the time on mds. */
5101         decision = 1;
5102         if (param->fp_atime || param->fp_mtime || param->fp_ctime) {
5103                 int for_mds;
5104
5105                 for_mds = lustre_fs ?
5106                           (S_ISREG(lmd->lmd_stx.stx_mode) && stripe_count) : 0;
5107                 decision = find_time_check(param, for_mds);
5108                 if (decision == -1)
5109                         goto decided;
5110         }
5111
5112         if (param->fp_btime) {
5113                 if (!(lmd->lmd_stx.stx_mask & STATX_BTIME)) {
5114                         ret = -EOPNOTSUPP;
5115                         goto out;
5116                 }
5117
5118                 decision = find_value_cmp(lmd->lmd_stx.stx_btime.tv_sec,
5119                                           param->fp_btime, param->fp_bsign,
5120                                           param->fp_exclude_btime,
5121                                           param->fp_time_margin, 0);
5122                 if (decision == -1)
5123                         goto decided;
5124         }
5125
5126         if (param->fp_newerxy) {
5127                 int for_mds;
5128
5129                 for_mds = lustre_fs ?
5130                           (S_ISREG(lmd->lmd_stx.stx_mode) && stripe_count) : 0;
5131                 decision = find_newerxy_check(param, for_mds, true);
5132                 if (decision == -1)
5133                         goto decided;
5134                 if (decision < 0) {
5135                         ret = decision;
5136                         goto out;
5137                 }
5138         }
5139
5140         flags = param->fp_lmd->lmd_flags;
5141         if (param->fp_check_size &&
5142             ((S_ISREG(lmd->lmd_stx.stx_mode) && stripe_count) ||
5143               S_ISDIR(lmd->lmd_stx.stx_mode)) &&
5144             !(flags & OBD_MD_FLSIZE ||
5145               (param->fp_lazy && flags & OBD_MD_FLLAZYSIZE)))
5146                 decision = 0;
5147
5148         if (param->fp_check_blocks &&
5149             ((S_ISREG(lmd->lmd_stx.stx_mode) && stripe_count) ||
5150               S_ISDIR(lmd->lmd_stx.stx_mode)) &&
5151             !(flags & OBD_MD_FLBLOCKS ||
5152               (param->fp_lazy && flags & OBD_MD_FLLAZYBLOCKS)))
5153                 decision = 0;
5154
5155         /*
5156          * If file still fits the request, ask ost for updated info.
5157          * The regular stat is almost of the same speed as some new
5158          * 'glimpse-size-ioctl'.
5159          */
5160         if (!decision) {
5161                 lstat_t st;
5162
5163                 /*
5164                  * For regular files with the stripe the decision may have not
5165                  * been taken yet if *time or size is to be checked.
5166                  */
5167                 if (param->fp_obd_index != OBD_NOT_FOUND)
5168                         print_failed_tgt(param, path, LL_STATFS_LOV);
5169
5170                 if (param->fp_mdt_index != OBD_NOT_FOUND)
5171                         print_failed_tgt(param, path, LL_STATFS_LMV);
5172
5173                 if (d != -1)
5174                         ret = fstat_f(d, &st);
5175                 else if (de != NULL)
5176                         ret = fstatat_f(p, de->d_name, &st,
5177                                         AT_SYMLINK_NOFOLLOW);
5178                 else
5179                         ret = lstat_f(path, &st);
5180
5181                 if (ret) {
5182                         if (errno == ENOENT) {
5183                                 llapi_error(LLAPI_MSG_ERROR, -ENOENT,
5184                                             "warning: %s: %s does not exist",
5185                                             __func__, path);
5186                                 goto decided;
5187                         } else {
5188                                 ret = -errno;
5189                                 llapi_error(LLAPI_MSG_ERROR, ret,
5190                                             "%s: stat on %s failed",
5191                                             __func__, path);
5192                                 goto out;
5193                         }
5194                 }
5195
5196                 convert_lmd_statx(param->fp_lmd, &st, true);
5197                 /* Check the time on osc. */
5198                 decision = find_time_check(param, 0);
5199                 if (decision == -1)
5200                         goto decided;
5201
5202                 if (param->fp_newerxy) {
5203                         decision = find_newerxy_check(param, 0, false);
5204                         if (decision == -1)
5205                                 goto decided;
5206                         if (decision < 0) {
5207                                 ret = decision;
5208                                 goto out;
5209                         }
5210                 }
5211         }
5212
5213         if (param->fp_check_size) {
5214                 decision = find_value_cmp(lmd->lmd_stx.stx_size,
5215                                           param->fp_size,
5216                                           param->fp_size_sign,
5217                                           param->fp_exclude_size,
5218                                           param->fp_size_units, 0);
5219                 if (decision == -1)
5220                         goto decided;
5221         }
5222
5223         if (param->fp_check_blocks) { /* convert st_blocks to bytes */
5224                 decision = find_value_cmp(lmd->lmd_stx.stx_blocks * 512,
5225                                           param->fp_blocks,
5226                                           param->fp_blocks_sign,
5227                                           param->fp_exclude_blocks,
5228                                           param->fp_blocks_units, 0);
5229                 if (decision == -1)
5230                         goto decided;
5231         }
5232
5233 foreign:
5234         llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
5235         if (param->fp_zero_end)
5236                 llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
5237         else
5238                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
5239
5240 decided:
5241         ret = 0;
5242         /* Do not get down anymore? */
5243         if (param->fp_depth == param->fp_max_depth) {
5244                 ret = 1;
5245                 goto out;
5246         }
5247         param->fp_depth++;
5248 out:
5249         if (fd > 0)
5250                 close(fd);
5251         return ret;
5252 }
5253
5254 static int cb_migrate_mdt_init(char *path, int p, int *dp,
5255                                void *param_data, struct dirent64 *de)
5256 {
5257         struct find_param *param = (struct find_param *)param_data;
5258         struct lmv_user_md *lmu = param->fp_lmv_md;
5259         int tmp_p = p;
5260         char raw[MAX_IOC_BUFLEN] = {'\0'};
5261         char *rawbuf = raw;
5262         struct obd_ioctl_data data = { 0 };
5263         int ret;
5264         char *path_copy;
5265         char *filename;
5266         bool retry = false;
5267
5268         if (p == -1 && dp == NULL)
5269                 return -EINVAL;
5270
5271         if (!lmu)
5272                 return -EINVAL;
5273
5274         if (dp != NULL && *dp != -1)
5275                 close(*dp);
5276
5277         if (p == -1) {
5278                 tmp_p = open_parent(path);
5279                 if (tmp_p == -1) {
5280                         *dp = -1;
5281                         ret = -errno;
5282                         llapi_error(LLAPI_MSG_ERROR, ret,
5283                                     "can not open %s", path);
5284                         return ret;
5285                 }
5286         }
5287
5288         path_copy = strdup(path);
5289         filename = basename(path_copy);
5290
5291         data.ioc_inlbuf1 = (char *)filename;
5292         data.ioc_inllen1 = strlen(filename) + 1;
5293         data.ioc_inlbuf2 = (char *)lmu;
5294         data.ioc_inllen2 = lmv_user_md_size(lmu->lum_stripe_count,
5295                                             lmu->lum_magic);
5296         ret = llapi_ioctl_pack(&data, &rawbuf, sizeof(raw));
5297         if (ret != 0) {
5298                 llapi_error(LLAPI_MSG_ERROR, ret,
5299                             "%s: error packing ioctl data", __func__);
5300                 goto out;
5301         }
5302
5303 migrate:
5304         ret = ioctl(tmp_p, LL_IOC_MIGRATE, rawbuf);
5305         if (ret != 0) {
5306                 if (errno == EBUSY && !retry) {
5307                         /*
5308                          * because migrate may not be able to lock all involved
5309                          * objects in order, for some of them it try lock, while
5310                          * there may be conflicting COS locks and cause migrate
5311                          * fail with EBUSY, hope a sync() could cause
5312                          * transaction commit and release these COS locks.
5313                          */
5314                         sync();
5315                         retry = true;
5316                         goto migrate;
5317                 } else if (errno == EALREADY) {
5318                         if (param->fp_verbose & VERBOSE_DETAIL)
5319                                 llapi_printf(LLAPI_MSG_NORMAL,
5320                                              "%s migrated to MDT%d already\n",
5321                                              path, lmu->lum_stripe_offset);
5322                         ret = 0;
5323                 } else {
5324                         ret = -errno;
5325                         llapi_error(LLAPI_MSG_ERROR, ret, "%s migrate failed",
5326                                     path);
5327                         goto out;
5328                 }
5329         } else if (param->fp_verbose & VERBOSE_DETAIL) {
5330                 llapi_printf(LLAPI_MSG_NORMAL,
5331                              "migrate %s to MDT%d stripe count %d\n",
5332                              path, lmu->lum_stripe_offset,
5333                              lmu->lum_stripe_count);
5334         }
5335
5336 out:
5337         if (dp != NULL) {
5338                 /*
5339                  * If the directory is being migration, we need
5340                  * close the directory after migration,
5341                  * so the old directory cache will be cleanup
5342                  * on the client side, and re-open to get the
5343                  * new directory handle
5344                  */
5345                 *dp = open(path, O_RDONLY|O_NDELAY|O_DIRECTORY);
5346                 if (*dp == -1) {
5347                         ret = -errno;
5348                         llapi_error(LLAPI_MSG_ERROR, ret,
5349                                     "%s: Failed to open '%s'", __func__, path);
5350                 }
5351         }
5352
5353         if (p == -1)
5354                 close(tmp_p);
5355
5356         free(path_copy);
5357
5358         return ret;
5359 }
5360
5361 /* dir migration finished, shrink its stripes */
5362 static int cb_migrate_mdt_fini(char *path, int p, int *dp, void *data,
5363                                struct dirent64 *de)
5364 {
5365         struct find_param *param = data;
5366         struct lmv_user_md *lmu = param->fp_lmv_md;
5367         int lmulen = lmv_user_md_size(lmu->lum_stripe_count, lmu->lum_magic);
5368         int ret = 0;
5369
5370         if (de && de->d_type != DT_DIR)
5371                 goto out;
5372
5373         if (*dp != -1) {
5374                 /*
5375                  * close it before setxattr because the latter may destroy the
5376                  * original object, and cause close fail.
5377                  */
5378                 ret = close(*dp);
5379                 *dp = -1;
5380                 if (ret)
5381                         goto out;
5382         }
5383
5384         ret = setxattr(path, XATTR_NAME_LMV, lmu, lmulen, 0);
5385         if (ret == -EALREADY)
5386                 ret = 0;
5387 out:
5388         cb_common_fini(path, p, dp, data, de);
5389         return ret;
5390 }
5391
5392 int llapi_migrate_mdt(char *path, struct find_param *param)
5393 {
5394         return param_callback(path, cb_migrate_mdt_init, cb_migrate_mdt_fini,
5395                               param);
5396 }
5397
5398 int llapi_mv(char *path, struct find_param *param)
5399 {
5400 #if LUSTRE_VERSION_CODE > OBD_OCD_VERSION(2, 9, 59, 0)
5401         static bool printed;
5402
5403         if (!printed) {
5404                 llapi_error(LLAPI_MSG_ERROR, -ESTALE,
5405                           "%s() is deprecated, use llapi_migrate_mdt() instead",
5406                           __func__);
5407                 printed = true;
5408         }
5409 #endif
5410         return llapi_migrate_mdt(path, param);
5411 }
5412
5413 int llapi_find(char *path, struct find_param *param)
5414 {
5415         return param_callback(path, cb_find_init, cb_common_fini, param);
5416 }
5417
5418 /*
5419  * Get MDT number that the file/directory inode referenced
5420  * by the open fd resides on.
5421  * Return 0 and mdtidx on success, or -ve errno.
5422  */
5423 int llapi_file_fget_mdtidx(int fd, int *mdtidx)
5424 {
5425         if (ioctl(fd, LL_IOC_GET_MDTIDX, mdtidx) < 0)
5426                 return -errno;
5427         return 0;
5428 }
5429
5430 static int cb_get_mdt_index(char *path, int p, int *dp, void *data,
5431                             struct dirent64 *de)
5432 {
5433         struct find_param *param = (struct find_param *)data;
5434         int d = dp == NULL ? -1 : *dp;
5435         int ret;
5436         int mdtidx;
5437
5438         if (p == -1 && d == -1)
5439                 return -EINVAL;
5440
5441         if (d != -1) {
5442                 ret = llapi_file_fget_mdtidx(d, &mdtidx);
5443         } else /* if (p != -1) */ {
5444                 int fd;
5445
5446                 fd = open(path, O_RDONLY | O_NOCTTY);
5447                 if (fd > 0) {
5448                         ret = llapi_file_fget_mdtidx(fd, &mdtidx);
5449                         close(fd);
5450                 } else {
5451                         ret = -errno;
5452                 }
5453         }
5454
5455         if (ret != 0) {
5456                 if (ret == -ENODATA) {
5457                         if (!param->fp_obd_uuid)
5458                                 llapi_printf(LLAPI_MSG_NORMAL,
5459                                              "'%s' has no stripe info\n", path);
5460                         goto out;
5461                 } else if (ret == -ENOENT) {
5462                         llapi_error(LLAPI_MSG_WARN, ret,
5463                                     "warning: %s: '%s' does not exist",
5464                                     __func__, path);
5465                         goto out;
5466                 } else if (ret == -ENOTTY) {
5467                         llapi_error(LLAPI_MSG_ERROR, ret,
5468                                     "%s: '%s' not on a Lustre fs",
5469                                     __func__, path);
5470                 } else {
5471                         llapi_error(LLAPI_MSG_ERROR, ret,
5472                                     "error: %s: '%s' failed get_mdtidx",
5473                                     __func__, path);
5474                 }
5475                 return ret;
5476         }
5477
5478         if (param->fp_quiet || !(param->fp_verbose & VERBOSE_DETAIL))
5479                 llapi_printf(LLAPI_MSG_NORMAL, "%d\n", mdtidx);
5480         else
5481                 llapi_printf(LLAPI_MSG_NORMAL, "%s\nmdt_index:\t%d\n",
5482                              path, mdtidx);
5483
5484 out:
5485         /* Do not go down anymore? */
5486         if (param->fp_depth == param->fp_max_depth)
5487                 return 1;
5488
5489         param->fp_depth++;
5490
5491         return 0;
5492 }
5493
5494 static int cb_getstripe(char *path, int p, int *dp, void *data,
5495                         struct dirent64 *de)
5496 {
5497         struct find_param *param = (struct find_param *)data;
5498         int d = dp == NULL ? -1 : *dp;
5499         int ret = 0;
5500
5501         if (p == -1 && d == -1)
5502                 return -EINVAL;
5503
5504         if (param->fp_obd_uuid) {
5505                 param->fp_quiet = 1;
5506                 ret = setup_obd_uuid(d != -1 ? d : p, path, param);
5507                 if (ret)
5508                         return ret;
5509         }
5510
5511         if (d != -1 && (param->fp_get_lmv || param->fp_get_default_lmv))
5512                 ret = cb_get_dirstripe(path, &d, param);
5513         else if (d != -1 ||
5514                  (p != -1 && !param->fp_get_lmv && !param->fp_get_default_lmv))
5515                 ret = get_lmd_info_fd(path, p, d, &param->fp_lmd->lmd_lmm,
5516                                       param->fp_lum_size, GET_LMD_STRIPE);
5517         else if (d == -1 && (param->fp_get_lmv || param->fp_get_default_lmv)) {
5518                 /* in case of a dangling or valid faked symlink dir, opendir()
5519                  * should have return either EINVAL or ENOENT, so let's try
5520                  * to get LMV just in case, and by opening it as a file but
5521                  * with O_NOFOLLOW ...
5522                  */
5523                 int fd = open(path, O_RDONLY | O_NOFOLLOW);
5524
5525                 if (fd == -1)
5526                         return 0;
5527                 ret = cb_get_dirstripe(path, &fd, param);
5528                 if (ret == 0)
5529                         llapi_lov_dump_user_lmm(param, path, LDF_IS_DIR);
5530                 close(fd);
5531                 return 0;
5532         } else
5533                 return 0;
5534
5535         if (ret) {
5536                 if (errno == ENODATA && d != -1) {
5537                         /*
5538                          * We need to "fake" the "use the default" values
5539                          * since the lmm struct is zeroed out at this point.
5540                          * The magic needs to be set in order to satisfy
5541                          * a check later on in the code path.
5542                          * The object_seq needs to be set for the "(Default)"
5543                          * prefix to be displayed.
5544                          */
5545                         if (param->fp_get_default_lmv) {
5546                                 struct lmv_user_md *lum = param->fp_lmv_md;
5547
5548                                 lum->lum_magic = LMV_USER_MAGIC;
5549                                 lum->lum_stripe_count = 0;
5550                                 lum->lum_stripe_offset = LMV_OFFSET_DEFAULT;
5551                                 goto dump;
5552                         } else if (param->fp_get_lmv) {
5553                                 struct lmv_user_md *lum = param->fp_lmv_md;
5554                                 int mdtidx;
5555
5556                                 ret = llapi_file_fget_mdtidx(d, &mdtidx);
5557                                 if (ret != 0)
5558                                         goto err_out;
5559                                 lum->lum_magic = LMV_MAGIC_V1;
5560                                 lum->lum_stripe_count = 0;
5561                                 lum->lum_stripe_offset = mdtidx;
5562                                 goto dump;
5563                         } else {
5564                                 struct lov_user_md *lmm =
5565                                         &param->fp_lmd->lmd_lmm;
5566
5567                                 lmm->lmm_magic = LOV_USER_MAGIC_V1;
5568                                 if (!param->fp_raw)
5569                                         ostid_set_seq(&lmm->lmm_oi,
5570                                                       FID_SEQ_LOV_DEFAULT);
5571                                 lmm->lmm_stripe_count = 0;
5572                                 lmm->lmm_stripe_size = 0;
5573                                 lmm->lmm_stripe_offset = -1;
5574                                 goto dump;
5575                         }
5576                 } else if (errno == ENODATA && p != -1) {
5577                         if (!param->fp_obd_uuid && !param->fp_mdt_uuid)
5578                                 llapi_printf(LLAPI_MSG_NORMAL,
5579                                              "%s has no stripe info\n", path);
5580                         goto out;
5581                 } else if (errno == ENOENT) {
5582                         llapi_error(LLAPI_MSG_WARN, -ENOENT,
5583                                     "warning: %s: %s does not exist",
5584                                     __func__, path);
5585                         goto out;
5586                 } else if (errno == ENOTTY) {
5587                         ret = -errno;
5588                         llapi_error(LLAPI_MSG_ERROR, ret,
5589                                     "%s: '%s' not on a Lustre fs?",
5590                                     __func__, path);
5591                 } else {
5592                         ret = -errno;
5593 err_out:
5594                         llapi_error(LLAPI_MSG_ERROR, ret,
5595                                     "error: %s: %s failed for %s",
5596                                      __func__, d != -1 ?
5597                                                "LL_IOC_LOV_GETSTRIPE" :
5598                                                "IOC_MDC_GETFILESTRIPE", path);
5599                 }
5600
5601                 return ret;
5602         }
5603
5604 dump:
5605         if (!(param->fp_verbose & VERBOSE_MDTINDEX))
5606                 llapi_lov_dump_user_lmm(param, path, d != -1 ? LDF_IS_DIR : 0);
5607
5608 out:
5609         /* Do not get down anymore? */
5610         if (param->fp_depth == param->fp_max_depth)
5611                 return 1;
5612
5613         param->fp_depth++;
5614
5615         return 0;
5616 }
5617
5618 int llapi_getstripe(char *path, struct find_param *param)
5619 {
5620         return param_callback(path, (param->fp_verbose & VERBOSE_MDTINDEX) ?
5621                               cb_get_mdt_index : cb_getstripe,
5622                               cb_common_fini, param);
5623 }
5624
5625 int llapi_obd_fstatfs(int fd, __u32 type, __u32 index,
5626                       struct obd_statfs *stat_buf, struct obd_uuid *uuid_buf)
5627 {
5628         char raw[MAX_IOC_BUFLEN] = {'\0'};
5629         char *rawbuf = raw;
5630         struct obd_ioctl_data data = { 0 };
5631         int rc = 0;
5632
5633         data.ioc_inlbuf1 = (char *)&type;
5634         data.ioc_inllen1 = sizeof(__u32);
5635         data.ioc_inlbuf2 = (char *)&index;
5636         data.ioc_inllen2 = sizeof(__u32);
5637         data.ioc_pbuf1 = (char *)stat_buf;
5638         data.ioc_plen1 = sizeof(struct obd_statfs);
5639         data.ioc_pbuf2 = (char *)uuid_buf;
5640         data.ioc_plen2 = sizeof(struct obd_uuid);
5641
5642         rc = llapi_ioctl_pack(&data, &rawbuf, sizeof(raw));
5643         if (rc != 0) {
5644                 llapi_error(LLAPI_MSG_ERROR, rc,
5645                             "%s: error packing ioctl data", __func__);
5646                 return rc;
5647         }
5648
5649         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
5650
5651         return rc < 0 ? -errno : 0;
5652 }
5653
5654 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
5655                      struct obd_statfs *stat_buf, struct obd_uuid *uuid_buf)
5656 {
5657         int fd;
5658         int rc;
5659
5660         fd = open(path, O_RDONLY);
5661         if (fd < 0) {
5662                 rc = -errno;
5663                 llapi_error(LLAPI_MSG_ERROR, rc, "error: %s: opening '%s'",
5664                             __func__, path);
5665                 /*
5666                  * If we can't even open a file on the filesystem (e.g. with
5667                  * -ESHUTDOWN), force caller to exit or it will loop forever.
5668                  */
5669                 return -ENODEV;
5670         }
5671
5672         rc = llapi_obd_fstatfs(fd, type, index, stat_buf, uuid_buf);
5673
5674         close(fd);
5675
5676         return rc;
5677 }
5678
5679 #define MAX_STRING_SIZE 128
5680
5681 int llapi_ping(char *obd_type, char *obd_name)
5682 {
5683         int flags = O_RDONLY;
5684         char buf[1] = { 0 };
5685         glob_t path;
5686         int rc, fd;
5687
5688         rc = cfs_get_param_paths(&path, "%s/%s/ping",
5689                                 obd_type, obd_name);
5690         if (rc != 0)
5691                 return -errno;
5692 retry_open:
5693         fd = open(path.gl_pathv[0], flags);
5694         if (fd < 0) {
5695                 if (errno == EACCES && flags == O_RDONLY) {
5696                         flags = O_WRONLY;
5697                         goto retry_open;
5698                 }
5699                 rc = -errno;
5700                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s",
5701                             path.gl_pathv[0]);
5702                 goto failed;
5703         }
5704
5705         if (flags == O_RDONLY)
5706                 rc = read(fd, buf, sizeof(buf));
5707         else
5708                 rc = write(fd, buf, sizeof(buf));
5709         if (rc < 0)
5710                 rc = -errno;
5711         close(fd);
5712
5713         if (rc == 1)
5714                 rc = 0;
5715 failed:
5716         cfs_free_param_data(&path);
5717         return rc;
5718 }
5719
5720 int llapi_target_iterate(int type_num, char **obd_type,
5721                          void *args, llapi_cb_t cb)
5722 {
5723         int i, rc = 0;
5724         glob_t param;
5725         FILE *fp;
5726
5727         for (i = 0; i < type_num; i++) {
5728                 int j;
5729
5730                 rc = cfs_get_param_paths(&param, "%s/*/uuid", obd_type[i]);
5731                 if (rc != 0)
5732                         continue;
5733
5734                 for (j = 0; j < param.gl_pathc; j++) {
5735                         char obd_uuid[UUID_MAX + 1];
5736                         char *obd_name;
5737                         char *ptr;
5738
5739                         fp = fopen(param.gl_pathv[j], "r");
5740                         if (fp == NULL) {
5741                                 rc = -errno;
5742                                 llapi_error(LLAPI_MSG_ERROR, rc,
5743                                             "error: opening '%s'",
5744                                             param.gl_pathv[j]);
5745                                 goto free_path;
5746                         }
5747
5748                         if (fgets(obd_uuid, sizeof(obd_uuid), fp) == NULL) {
5749                                 rc = -errno;
5750                                 llapi_error(LLAPI_MSG_ERROR, rc,
5751                                             "error: reading '%s'",
5752                                             param.gl_pathv[j]);
5753                                 goto free_path;
5754                         }
5755
5756                         /* Extract the obd_name from the sysfs path.
5757                          * 'topsysfs'/fs/lustre/'obd_type'/'obd_name'.
5758                          */
5759                         obd_name = strstr(param.gl_pathv[j], "/fs/lustre/");
5760                         if (!obd_name) {
5761                                 rc = -EINVAL;
5762                                 goto free_path;
5763                         }
5764
5765                         /* skip /fs/lustre/'obd_type'/ */
5766                         obd_name += strlen(obd_type[i]) + 12;
5767                         /* chop off after obd_name */
5768                         ptr = strrchr(obd_name, '/');
5769                         if (ptr)
5770                                 *ptr = '\0';
5771
5772                         cb(obd_type[i], obd_name, obd_uuid, args);
5773
5774                         fclose(fp);
5775                         fp = NULL;
5776                 }
5777         }
5778 free_path:
5779         if (fp)
5780                 fclose(fp);
5781         cfs_free_param_data(&param);
5782         return rc;
5783 }
5784
5785 static void do_target_check(char *obd_type_name, char *obd_name,
5786                             char *obd_uuid, void *args)
5787 {
5788         int rc;
5789
5790         rc = llapi_ping(obd_type_name, obd_name);
5791         if (rc == ENOTCONN)
5792                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
5793         else if (rc)
5794                 llapi_error(LLAPI_MSG_ERROR, rc, "error: check '%s'", obd_name);
5795         else
5796                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
5797 }
5798
5799 int llapi_target_check(int type_num, char **obd_type, char *dir)
5800 {
5801         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
5802 }
5803
5804 #undef MAX_STRING_SIZE
5805
5806 /* Is this a lustre fs? */
5807 int llapi_is_lustre_mnttype(const char *type)
5808 {
5809         return strcmp(type, "lustre") == 0 || strcmp(type, "lustre_tgt") == 0;
5810 }
5811
5812 /* Is this a lustre client fs? */
5813 int llapi_is_lustre_mnt(struct mntent *mnt)
5814 {
5815         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
5816                 strstr(mnt->mnt_fsname, ":/") != NULL);
5817 }
5818
5819 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
5820 {
5821         char fsname[PATH_MAX + 1];
5822         int root;
5823         int rc;
5824
5825         rc = llapi_search_fsname(mnt, fsname);
5826         if (rc)
5827                 return rc;
5828
5829         root = open(mnt, O_RDONLY | O_DIRECTORY);
5830         if (root < 0) {
5831                 rc = -errno;
5832                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot open '%s'", mnt);
5833                 return rc;
5834         }
5835
5836         rc = ioctl(root, OBD_IOC_QUOTACTL, qctl);
5837         if (rc < 0)
5838                 rc = -errno;
5839         if (rc == -ENOENT && LUSTRE_Q_CMD_IS_POOL(qctl->qc_cmd))
5840                 llapi_error(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO, rc,
5841                             "Cannot find pool '%s'", qctl->qc_poolname);
5842
5843         close(root);
5844         return rc;
5845 }
5846
5847 int llapi_get_connect_flags(const char *mnt, __u64 *flags)
5848 {
5849         int root;
5850         int rc;
5851
5852         root = open(mnt, O_RDONLY | O_DIRECTORY);
5853         if (root < 0) {
5854                 rc = -errno;
5855                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
5856                 return rc;
5857         }
5858
5859         rc = ioctl(root, LL_IOC_GET_CONNECT_FLAGS, flags);
5860         if (rc < 0) {
5861                 rc = -errno;
5862                 llapi_error(LLAPI_MSG_ERROR, rc,
5863                         "ioctl on %s for getting connect flags failed", mnt);
5864         }
5865         close(root);
5866         return rc;
5867 }
5868
5869 /**
5870  * Flush cached pages from all clients.
5871  *
5872  * \param fd    File descriptor
5873  * \retval 0    success
5874  * \retval < 0  error
5875  */
5876 int llapi_file_flush(int fd)
5877 {
5878         __u64 dv;
5879
5880         return llapi_get_data_version(fd, &dv, LL_DV_WR_FLUSH);
5881 }
5882