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