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