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