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