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