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