Whamcloud - gitweb
LU-11213 uapi: change "space" hash type to hash flag
[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 };
2633
2634 static void lov_dump_user_lmm_header(struct lov_user_md *lum, char *path,
2635                                      struct lov_user_ost_data_v1 *objects,
2636                                      enum llapi_layout_verbose verbose,
2637                                      int depth, char *pool_name,
2638                                      enum lov_dump_flags flags)
2639 {
2640         bool is_dir = flags & LDF_IS_DIR;
2641         bool is_raw = flags & LDF_IS_RAW;
2642         bool indent = flags & LDF_INDENT;
2643         bool yaml = flags & LDF_YAML;
2644         bool skip_objs = flags & LDF_SKIP_OBJS;
2645         char *prefix = is_dir ? "" : "lmm_";
2646         char *separator = "";
2647         char *space = indent ? "      " : "";
2648         int rc;
2649
2650         if (is_dir && lmm_oi_seq(&lum->lmm_oi) == FID_SEQ_LOV_DEFAULT) {
2651                 lmm_oi_set_seq(&lum->lmm_oi, 0);
2652                 if (!indent && (verbose & VERBOSE_DETAIL))
2653                         llapi_printf(LLAPI_MSG_NORMAL, "%s(Default) ", space);
2654         }
2655
2656         if (!yaml && !indent && depth && path &&
2657             ((verbose != VERBOSE_OBJID) || !is_dir))
2658                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
2659
2660         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
2661                 llapi_printf(LLAPI_MSG_NORMAL, "%s%smagic:         0x%08X\n",
2662                              space, prefix, lum->lmm_magic);
2663                 llapi_printf(LLAPI_MSG_NORMAL, "%s%sseq:           %#jx\n",
2664                              space, prefix,
2665                              (uintmax_t)lmm_oi_seq(&lum->lmm_oi));
2666                 llapi_printf(LLAPI_MSG_NORMAL, "%s%sobject_id:     %#jx\n",
2667                              space, prefix,
2668                              (uintmax_t)lmm_oi_id(&lum->lmm_oi));
2669         }
2670         if ((verbose & (VERBOSE_DETAIL | VERBOSE_DFID)) && !is_dir) {
2671                 __u64 seq;
2672                 __u32 oid;
2673                 __u32 ver;
2674
2675                 if (verbose & ~VERBOSE_DFID)
2676                         llapi_printf(LLAPI_MSG_NORMAL, "%slmm_fid:           ",
2677                                      space);
2678                 /* This needs a bit of hand-holding since old 1.x lmm_oi
2679                  * have { oi.oi_id = mds_inum, oi.oi_seq = 0 } and 2.x lmm_oi
2680                  * have { oi.oi_id = mds_oid, oi.oi_seq = mds_seq } instead of
2681                  * a real FID.  Ideally the 2.x code would have stored this
2682                  * like a FID with { oi_id = mds_seq, oi_seq = mds_oid } so the
2683                  * ostid union lu_fid { f_seq = mds_seq, f_oid = mds_oid }
2684                  * worked properly (especially since IGIF FIDs use mds_inum as
2685                  * the FID SEQ), but unfortunately that didn't happen.
2686                  *
2687                  * Print it to look like an IGIF FID, even though the fields
2688                  * are reversed on disk, so that it makes sense to userspace.
2689                  *
2690                  * Don't use ostid_id() and ostid_seq(), since they assume the
2691                  * oi_fid fields are in the right order.  This is why there are
2692                  * separate lmm_oi_seq() and lmm_oi_id() routines for this.
2693                  *
2694                  * For newer layout types hopefully this will be a real FID. */
2695                 seq = lmm_oi_seq(&lum->lmm_oi) == 0 ?
2696                         lmm_oi_id(&lum->lmm_oi) : lmm_oi_seq(&lum->lmm_oi);
2697                 oid = lmm_oi_seq(&lum->lmm_oi) == 0 ?
2698                         0 : (__u32)lmm_oi_id(&lum->lmm_oi);
2699                 ver = (__u32)(lmm_oi_id(&lum->lmm_oi) >> 32);
2700                 if (yaml)
2701                         llapi_printf(LLAPI_MSG_NORMAL, DFID_NOBRACE"\n",
2702                                      seq, oid, ver);
2703                 else
2704                         llapi_printf(LLAPI_MSG_NORMAL, DFID"\n",
2705                                      seq, oid, ver);
2706         }
2707
2708         if (verbose & VERBOSE_STRIPE_COUNT) {
2709                 if (verbose & ~VERBOSE_STRIPE_COUNT)
2710                         llapi_printf(LLAPI_MSG_NORMAL, "%s%sstripe_count:  ",
2711                                      space, prefix);
2712                 if (is_dir) {
2713                         if (!is_raw && lum->lmm_stripe_count == 0 &&
2714                             lov_pattern(lum->lmm_pattern) != LOV_PATTERN_MDT) {
2715                                 unsigned int scount;
2716                                 rc = sattr_cache_get_defaults(NULL, path,
2717                                                               &scount, NULL,
2718                                                               NULL);
2719                                 if (rc == 0)
2720                                         llapi_printf(LLAPI_MSG_NORMAL, "%d",
2721                                                      scount);
2722                                 else
2723                                         llapi_error(LLAPI_MSG_ERROR, rc,
2724                                                     "Cannot determine default"
2725                                                     " stripe count.");
2726                         } else {
2727                                 llapi_printf(LLAPI_MSG_NORMAL, "%d",
2728                                              lum->lmm_stripe_count ==
2729                                              (typeof(lum->lmm_stripe_count))(-1)
2730                                              ? -1 : lum->lmm_stripe_count);
2731                         }
2732                 } else {
2733                         llapi_printf(LLAPI_MSG_NORMAL, "%hd",
2734                                      (__s16)lum->lmm_stripe_count);
2735                 }
2736                 if (!yaml && is_dir)
2737                         separator = " ";
2738                 else
2739                         separator = "\n";
2740         }
2741
2742         if (verbose & VERBOSE_STRIPE_SIZE) {
2743                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2744                 if (verbose & ~VERBOSE_STRIPE_SIZE)
2745                         llapi_printf(LLAPI_MSG_NORMAL, "%s%sstripe_size:   ",
2746                                      space, prefix);
2747                 if (is_dir && !is_raw && lum->lmm_stripe_size == 0) {
2748                         unsigned int ssize;
2749                         rc = sattr_cache_get_defaults(NULL, path, NULL, &ssize,
2750                                                       NULL);
2751                         if (rc == 0)
2752                                 llapi_printf(LLAPI_MSG_NORMAL, "%u", ssize);
2753                         else
2754                                 llapi_error(LLAPI_MSG_ERROR, rc,
2755                                             "Cannot determine default"
2756                                             " stripe size.");
2757                 } else {
2758                         llapi_printf(LLAPI_MSG_NORMAL, "%u",
2759                                      lum->lmm_stripe_size);
2760                 }
2761                 if (!yaml && is_dir)
2762                         separator = " ";
2763                 else
2764                         separator = "\n";
2765         }
2766
2767         if ((verbose & VERBOSE_PATTERN)) {
2768                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2769                 if (verbose & ~VERBOSE_PATTERN)
2770                         llapi_printf(LLAPI_MSG_NORMAL, "%s%spattern:       ",
2771                                      space, prefix);
2772                 if (lov_pattern_supported(lum->lmm_pattern))
2773                         llapi_printf(LLAPI_MSG_NORMAL, "%s",
2774                                      layout2name(lum->lmm_pattern));
2775                 else
2776                         llapi_printf(LLAPI_MSG_NORMAL, "%x", lum->lmm_pattern);
2777                 separator = (!yaml && is_dir) ? " " : "\n";
2778         }
2779
2780         if ((verbose & VERBOSE_GENERATION) && !is_dir) {
2781                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2782                 if (verbose & ~VERBOSE_GENERATION)
2783                         llapi_printf(LLAPI_MSG_NORMAL, "%s%slayout_gen:    ",
2784                                      space, prefix);
2785                 llapi_printf(LLAPI_MSG_NORMAL, "%u",
2786                              skip_objs ? 0 : (int)lum->lmm_layout_gen);
2787                 separator = "\n";
2788         }
2789
2790         if (verbose & VERBOSE_STRIPE_OFFSET) {
2791                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2792                 if (verbose & ~VERBOSE_STRIPE_OFFSET)
2793                         llapi_printf(LLAPI_MSG_NORMAL, "%s%sstripe_offset: ",
2794                                      space, prefix);
2795                 if (is_dir || skip_objs)
2796                         llapi_printf(LLAPI_MSG_NORMAL, "%d",
2797                                      lum->lmm_stripe_offset ==
2798                                      (typeof(lum->lmm_stripe_offset))(-1) ? -1 :
2799                                      lum->lmm_stripe_offset);
2800                 else if (lov_pattern(lum->lmm_pattern) == LOV_PATTERN_MDT)
2801                         llapi_printf(LLAPI_MSG_NORMAL, "0");
2802                 else
2803                         llapi_printf(LLAPI_MSG_NORMAL, "%u",
2804                                      objects[0].l_ost_idx);
2805                 if (!yaml && is_dir)
2806                         separator = " ";
2807                 else
2808                         separator = "\n";
2809         }
2810
2811         if ((verbose & VERBOSE_POOL) && pool_name && (pool_name[0] != '\0')) {
2812                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2813                 if (verbose & ~VERBOSE_POOL)
2814                         llapi_printf(LLAPI_MSG_NORMAL, "%s%spool:          ",
2815                                      space, prefix);
2816                 llapi_printf(LLAPI_MSG_NORMAL, "%s", pool_name);
2817                 if (!yaml && is_dir)
2818                         separator = " ";
2819                 else
2820                         separator = "\n";
2821         }
2822
2823         if (strlen(separator) != 0)
2824                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
2825 }
2826
2827 void lov_dump_user_lmm_v1v3(struct lov_user_md *lum, char *pool_name,
2828                             struct lov_user_ost_data_v1 *objects,
2829                             char *path, int obdindex, int depth,
2830                             enum llapi_layout_verbose verbose,
2831                             enum lov_dump_flags flags)
2832 {
2833         bool is_dir = flags & LDF_IS_DIR;
2834         bool indent = flags & LDF_INDENT;
2835         bool skip_objs = flags & LDF_SKIP_OBJS;
2836         bool yaml = flags & LDF_YAML;
2837         bool obdstripe = obdindex == OBD_NOT_FOUND;
2838         int i;
2839
2840         if (!obdstripe && !skip_objs) {
2841                 for (i = 0; !is_dir && i < lum->lmm_stripe_count; i++) {
2842                         if (obdindex == objects[i].l_ost_idx) {
2843                                 obdstripe = true;
2844                                 break;
2845                         }
2846                 }
2847         }
2848
2849         if (!obdstripe)
2850                 return;
2851
2852         lov_dump_user_lmm_header(lum, path, objects, verbose, depth, pool_name,
2853                                  flags);
2854
2855         if (!is_dir && !skip_objs && (verbose & VERBOSE_OBJID) &&
2856             !(lum->lmm_pattern & LOV_PATTERN_F_RELEASED ||
2857               lov_pattern(lum->lmm_pattern) == LOV_PATTERN_MDT)) {
2858                 char *space = "      - ";
2859
2860                 if (indent)
2861                         llapi_printf(LLAPI_MSG_NORMAL,
2862                                      "%6slmm_objects:\n", " ");
2863                 else if (yaml)
2864                         llapi_printf(LLAPI_MSG_NORMAL, "lmm_objects:\n");
2865                 else
2866                         llapi_printf(LLAPI_MSG_NORMAL,
2867                                 "\tobdidx\t\t objid\t\t objid\t\t group\n");
2868
2869                 for (i = 0; i < lum->lmm_stripe_count; i++) {
2870                         int idx = objects[i].l_ost_idx;
2871                         long long oid = ostid_id(&objects[i].l_ost_oi);
2872                         long long gr = ostid_seq(&objects[i].l_ost_oi);
2873
2874                         if (obdindex != OBD_NOT_FOUND && obdindex != idx)
2875                                 continue;
2876
2877                         if (yaml) {
2878                                 struct lu_fid fid = { 0 };
2879
2880                                 ostid_to_fid(&fid, &objects[i].l_ost_oi, idx);
2881                                 llapi_printf(LLAPI_MSG_NORMAL,
2882                                     "%sl_ost_idx: %d\n", space, idx);
2883                                 llapi_printf(LLAPI_MSG_NORMAL,
2884                                     "%8sl_fid:     "DFID_NOBRACE"\n",
2885                                     " ", PFID(&fid));
2886                         } else if (indent) {
2887                                 struct lu_fid fid = { 0 };
2888
2889                                 ostid_to_fid(&fid, &objects[i].l_ost_oi, idx);
2890                                 llapi_printf(LLAPI_MSG_NORMAL,
2891                                     "%s%d: { l_ost_idx: %d, l_fid: "DFID" }\n",
2892                                     space, i, idx, PFID(&fid));
2893                         } else {
2894                                 char fmt[48];
2895                                 sprintf(fmt, "%s%s%s\n",
2896                                         "\t%6u\t%14llu\t%#13llx\t",
2897                                         (fid_seq_is_rsvd(gr) ||
2898                                          fid_seq_is_mdt0(gr)) ?
2899                                          "%14llu" : "%#14llx", "%s");
2900                                 llapi_printf(LLAPI_MSG_NORMAL, fmt, idx, oid,
2901                                              oid, gr,
2902                                              obdindex == idx ? " *" : "");
2903                         }
2904                 }
2905         }
2906         llapi_printf(LLAPI_MSG_NORMAL, "\n");
2907 }
2908
2909 void lmv_dump_user_lmm(struct lmv_user_md *lum, char *pool_name,
2910                        char *path, int obdindex, int depth,
2911                        enum llapi_layout_verbose verbose,
2912                        enum lov_dump_flags flags)
2913 {
2914         struct lmv_user_mds_data *objects = lum->lum_objects;
2915         char *prefix = lum->lum_magic == LMV_USER_MAGIC ? "(Default)" : "";
2916         char *separator = "";
2917         bool yaml = flags & LDF_YAML;
2918         bool obdstripe = false;
2919         int i;
2920
2921         if (obdindex != OBD_NOT_FOUND) {
2922                 if (lum->lum_stripe_count == 0) {
2923                         if (obdindex == lum->lum_stripe_offset)
2924                                 obdstripe = true;
2925                 } else {
2926                         for (i = 0; i < lum->lum_stripe_count; i++) {
2927                                 if (obdindex == objects[i].lum_mds) {
2928                                         llapi_printf(LLAPI_MSG_NORMAL,
2929                                                      "%s%s\n", prefix,
2930                                                      path);
2931                                         obdstripe = true;
2932                                         break;
2933                                 }
2934                         }
2935                 }
2936         } else {
2937                 obdstripe = true;
2938         }
2939
2940         if (!obdstripe)
2941                 return;
2942
2943         /* show all information default */
2944         if (!verbose) {
2945                 if (lum->lum_magic == LMV_USER_MAGIC)
2946                         verbose = VERBOSE_POOL | VERBOSE_STRIPE_COUNT |
2947                                   VERBOSE_STRIPE_OFFSET | VERBOSE_HASH_TYPE;
2948                 else
2949                         verbose = VERBOSE_OBJID;
2950         }
2951
2952         if (depth && path && ((verbose != VERBOSE_OBJID)))
2953                 llapi_printf(LLAPI_MSG_NORMAL, "%s%s\n", prefix, path);
2954
2955         if (verbose & VERBOSE_STRIPE_COUNT) {
2956                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2957                 if (verbose & ~VERBOSE_STRIPE_COUNT)
2958                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_stripe_count: ");
2959                 llapi_printf(LLAPI_MSG_NORMAL, "%u",
2960                              (int)lum->lum_stripe_count);
2961                 if ((verbose & VERBOSE_STRIPE_OFFSET) && !yaml)
2962                         separator = " ";
2963                 else
2964                         separator = "\n";
2965         }
2966
2967         if (verbose & VERBOSE_STRIPE_OFFSET) {
2968                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2969                 if (verbose & ~VERBOSE_STRIPE_OFFSET)
2970                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_stripe_offset: ");
2971                 llapi_printf(LLAPI_MSG_NORMAL, "%d",
2972                              (int)lum->lum_stripe_offset);
2973                 if (verbose & VERBOSE_HASH_TYPE && !yaml)
2974                         separator = " ";
2975                 else
2976                         separator = "\n";
2977         }
2978
2979         if (verbose & VERBOSE_HASH_TYPE) {
2980                 unsigned int type = lum->lum_hash_type & LMV_HASH_TYPE_MASK;
2981                 unsigned int flags = lum->lum_hash_type & ~LMV_HASH_TYPE_MASK;
2982
2983                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2984                 if (verbose & ~VERBOSE_HASH_TYPE)
2985                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_hash_type: ");
2986                 if (type < LMV_HASH_TYPE_MAX)
2987                         llapi_printf(LLAPI_MSG_NORMAL, "%s",
2988                                      mdt_hash_name[type]);
2989                 else
2990                         llapi_printf(LLAPI_MSG_NORMAL, "%#x", type);
2991
2992                 if (flags & LMV_HASH_FLAG_SPACE)
2993                         llapi_printf(LLAPI_MSG_NORMAL, ",space");
2994                 if (flags & LMV_HASH_FLAG_MIGRATION)
2995                         llapi_printf(LLAPI_MSG_NORMAL, ",migrating");
2996                 if (flags & LMV_HASH_FLAG_BAD_TYPE)
2997                         llapi_printf(LLAPI_MSG_NORMAL, ",bad_type");
2998                 if (flags & LMV_HASH_FLAG_LOST_LMV)
2999                         llapi_printf(LLAPI_MSG_NORMAL, ",lost_lmv");
3000                 separator = "\n";
3001
3002         }
3003
3004         if (verbose & VERBOSE_OBJID && lum->lum_magic != LMV_USER_MAGIC) {
3005                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3006                 if (lum->lum_stripe_count > 0)
3007                         llapi_printf(LLAPI_MSG_NORMAL,
3008                                      "mdtidx\t\t FID[seq:oid:ver]\n");
3009                 for (i = 0; i < lum->lum_stripe_count; i++) {
3010                         int idx = objects[i].lum_mds;
3011                         struct lu_fid *fid = &objects[i].lum_fid;
3012                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
3013                                 llapi_printf(LLAPI_MSG_NORMAL,
3014                                              "%6u\t\t "DFID"\t\t%s\n",
3015                                             idx, PFID(fid),
3016                                             obdindex == idx ? " *" : "");
3017                 }
3018
3019         }
3020
3021         if ((verbose & VERBOSE_POOL) && pool_name != NULL &&
3022              pool_name[0] != '\0') {
3023                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3024                 if (verbose & ~VERBOSE_POOL)
3025                         llapi_printf(LLAPI_MSG_NORMAL, "%slmv_pool:           ",
3026                                      prefix);
3027                 llapi_printf(LLAPI_MSG_NORMAL, "%s%c ", pool_name, ' ');
3028                 separator = "\n";
3029         }
3030
3031         if (!(verbose & VERBOSE_OBJID) || lum->lum_magic == LMV_USER_MAGIC)
3032                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
3033 }
3034
3035 static void lov_dump_comp_v1_header(struct find_param *param, char *path,
3036                                     enum lov_dump_flags flags)
3037 {
3038         struct lov_comp_md_v1 *comp_v1 = (void *)&param->fp_lmd->lmd_lmm;
3039         int depth = param->fp_max_depth;
3040         enum llapi_layout_verbose verbose = param->fp_verbose;
3041         bool yaml = flags & LDF_YAML;
3042
3043         if (depth && path && ((verbose != VERBOSE_OBJID) ||
3044                               !(flags & LDF_IS_DIR)) && !yaml)
3045                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
3046
3047         if (verbose & VERBOSE_DETAIL) {
3048                 llapi_printf(LLAPI_MSG_NORMAL, "composite_header:\n");
3049                 llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_magic:         0x%08X\n",
3050                              " ", comp_v1->lcm_magic);
3051                 llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_size:          %u\n",
3052                              " ", comp_v1->lcm_size);
3053                 if (flags & LDF_IS_DIR)
3054                         llapi_printf(LLAPI_MSG_NORMAL,
3055                                      "%2slcm_flags:         %s\n", " ",
3056                                      comp_v1->lcm_mirror_count > 0 ?
3057                                                         "mirrored" : "");
3058                 else
3059                         llapi_printf(LLAPI_MSG_NORMAL,
3060                                      "%2slcm_flags:         %s\n", " ",
3061                                 llapi_layout_flags_string(comp_v1->lcm_flags));
3062         }
3063
3064         if (verbose & VERBOSE_GENERATION) {
3065                 if (verbose & ~VERBOSE_GENERATION)
3066                         llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_layout_gen:    ",
3067                                      " ");
3068                 llapi_printf(LLAPI_MSG_NORMAL, "%u\n", comp_v1->lcm_layout_gen);
3069         }
3070
3071         if (verbose & VERBOSE_MIRROR_COUNT) {
3072                 if (verbose & ~VERBOSE_MIRROR_COUNT)
3073                         llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_mirror_count:  ",
3074                                      " ");
3075                 llapi_printf(LLAPI_MSG_NORMAL, "%u\n",
3076                              comp_v1->lcm_magic == LOV_USER_MAGIC_COMP_V1 ?
3077                              comp_v1->lcm_mirror_count + 1 : 1);
3078         }
3079
3080         if (verbose & VERBOSE_COMP_COUNT) {
3081                 if (verbose & ~VERBOSE_COMP_COUNT)
3082                         llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_entry_count:   ",
3083                                      " ");
3084                 llapi_printf(LLAPI_MSG_NORMAL, "%u\n",
3085                              comp_v1->lcm_magic == LOV_USER_MAGIC_COMP_V1 ?
3086                              comp_v1->lcm_entry_count : 0);
3087         }
3088
3089         if (verbose & VERBOSE_DETAIL && !yaml)
3090                 llapi_printf(LLAPI_MSG_NORMAL, "components:\n");
3091 }
3092
3093 static void lcme_flags2str(__u32 comp_flags)
3094 {
3095         bool found = false;
3096         int i = 0;
3097
3098         if (!comp_flags) {
3099                 llapi_printf(LLAPI_MSG_NORMAL, "0");
3100                 return;
3101         }
3102         for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
3103                 if (comp_flags & comp_flags_table[i].cfn_flag) {
3104                         if (found)
3105                                 llapi_printf(LLAPI_MSG_NORMAL, ",");
3106                         llapi_printf(LLAPI_MSG_NORMAL, "%s",
3107                                      comp_flags_table[i].cfn_name);
3108                         comp_flags &= ~comp_flags_table[i].cfn_flag;
3109                         found = true;
3110                 }
3111         }
3112         if (comp_flags) {
3113                 if (found)
3114                         llapi_printf(LLAPI_MSG_NORMAL, ",");
3115                 llapi_printf(LLAPI_MSG_NORMAL, "%#x", comp_flags);
3116         }
3117 }
3118
3119 static void lov_dump_comp_v1_entry(struct find_param *param,
3120                                    enum lov_dump_flags flags, int index)
3121 {
3122         struct lov_comp_md_v1 *comp_v1 = (void *)&param->fp_lmd->lmd_lmm;
3123         struct lov_comp_md_entry_v1 *entry;
3124         char *separator = "";
3125         enum llapi_layout_verbose verbose = param->fp_verbose;
3126         bool yaml = flags & LDF_YAML;
3127
3128         entry = &comp_v1->lcm_entries[index];
3129
3130         if (yaml)
3131                 llapi_printf(LLAPI_MSG_NORMAL, "%2scomponent%d:\n", " ", index);
3132
3133         if (verbose & VERBOSE_COMP_ID) {
3134                 if (verbose & VERBOSE_DETAIL && !yaml)
3135                         llapi_printf(LLAPI_MSG_NORMAL,
3136                                      "%slcme_id:             ", "  - ");
3137                 else if (verbose & ~VERBOSE_COMP_ID)
3138                         llapi_printf(LLAPI_MSG_NORMAL,
3139                                      "%4slcme_id:             ", " ");
3140                 if (entry->lcme_id != LCME_ID_INVAL)
3141                         llapi_printf(LLAPI_MSG_NORMAL, "%u", entry->lcme_id);
3142                 else
3143                         llapi_printf(LLAPI_MSG_NORMAL, "N/A");
3144                 separator = "\n";
3145         }
3146
3147         if (verbose & VERBOSE_MIRROR_ID) {
3148                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3149                 if (verbose & ~VERBOSE_MIRROR_ID)
3150                         llapi_printf(LLAPI_MSG_NORMAL,
3151                                      "%4slcme_mirror_id:      ", " ");
3152                 if (entry->lcme_id != LCME_ID_INVAL)
3153                         llapi_printf(LLAPI_MSG_NORMAL, "%u",
3154                                      mirror_id_of(entry->lcme_id));
3155                 else
3156                         llapi_printf(LLAPI_MSG_NORMAL, "N/A");
3157                 separator = "\n";
3158         }
3159
3160         if (verbose & VERBOSE_COMP_FLAGS) {
3161                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3162                 if (verbose & ~VERBOSE_COMP_FLAGS)
3163                         llapi_printf(LLAPI_MSG_NORMAL,
3164                                      "%4slcme_flags:          ", " ");
3165                 lcme_flags2str(entry->lcme_flags);
3166                 separator = "\n";
3167         }
3168         /* print snapshot timestamp if its a nosync comp */
3169         if ((verbose & VERBOSE_COMP_FLAGS) &&
3170             (entry->lcme_flags & LCME_FL_NOSYNC)) {
3171                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3172                 if (verbose & ~VERBOSE_COMP_FLAGS)
3173                         llapi_printf(LLAPI_MSG_NORMAL,
3174                                      "%4slcme_timestamp:      ", " ");
3175                 if (yaml) {
3176                         llapi_printf(LLAPI_MSG_NORMAL, "%llu",
3177                                                         entry->lcme_timestamp);
3178                 } else {
3179                         time_t stamp = entry->lcme_timestamp;
3180                         char *date_str = asctime(localtime(&stamp));
3181
3182                         date_str[strlen(date_str) - 1] = '\0';
3183                         llapi_printf(LLAPI_MSG_NORMAL, "'%s'", date_str);
3184                 }
3185
3186                 separator = "\n";
3187         }
3188
3189         if (verbose & VERBOSE_COMP_START) {
3190                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3191                 if (verbose & ~VERBOSE_COMP_START)
3192                         llapi_printf(LLAPI_MSG_NORMAL,
3193                                      "%4slcme_extent.e_start: ", " ");
3194                 llapi_printf(LLAPI_MSG_NORMAL, "%llu",
3195                              entry->lcme_extent.e_start);
3196                 separator = "\n";
3197         }
3198
3199         if (verbose & VERBOSE_COMP_END) {
3200                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3201                 if (verbose & ~VERBOSE_COMP_END)
3202                         llapi_printf(LLAPI_MSG_NORMAL,
3203                                      "%4slcme_extent.e_end:   ", " ");
3204                 if (entry->lcme_extent.e_end == LUSTRE_EOF)
3205                         llapi_printf(LLAPI_MSG_NORMAL, "%s", "EOF");
3206                 else
3207                         llapi_printf(LLAPI_MSG_NORMAL, "%llu",
3208                                         entry->lcme_extent.e_end);
3209                 separator = "\n";
3210         }
3211
3212         if (yaml) {
3213                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3214                 llapi_printf(LLAPI_MSG_NORMAL, "%4ssub_layout:\n", " ");
3215         } else if (verbose & VERBOSE_DETAIL) {
3216                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3217                 llapi_printf(LLAPI_MSG_NORMAL, "%4slcme_offset:         %u\n",
3218                              " ", entry->lcme_offset);
3219                 llapi_printf(LLAPI_MSG_NORMAL, "%4slcme_size:           %u\n",
3220                              " ", entry->lcme_size);
3221                 llapi_printf(LLAPI_MSG_NORMAL, "%4ssub_layout:\n", " ");
3222         } else {
3223                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3224         }
3225 }
3226
3227 /* Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
3228  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
3229  *
3230  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
3231  * The table below gives the answers for the specified parameters (value and
3232  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
3233  * --------------------------------------
3234  * 1 | file > limit; sign > 0 | -1 / -1 |
3235  * 2 | file = limit; sign > 0 | -1 / -1 |
3236  * 3 | file < limit; sign > 0 |  ? /  1 |
3237  * 4 | file > limit; sign = 0 | -1 / -1 |
3238  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
3239  * 6 | file < limit; sign = 0 |  ? / -1 |
3240  * 7 | file > limit; sign < 0 |  1 /  1 |
3241  * 8 | file = limit; sign < 0 |  ? / -1 |
3242  * 9 | file < limit; sign < 0 |  ? / -1 |
3243  * --------------------------------------
3244  * Note: 5th actually means that the value is within the interval
3245  * (limit - margin, limit]. */
3246 static int find_value_cmp(unsigned long long file, unsigned long long limit,
3247                           int sign, int negopt, unsigned long long margin,
3248                           bool mds)
3249 {
3250         int ret = -1;
3251
3252         if (sign > 0) {
3253                 /* Drop the fraction of margin (of days or size). */
3254                 if (file + margin <= limit)
3255                         ret = mds ? 0 : 1;
3256         } else if (sign == 0) {
3257                 if (file <= limit && file + margin > limit)
3258                         ret = mds ? 0 : 1;
3259                 else if (file + margin <= limit)
3260                         ret = mds ? 0 : -1;
3261         } else if (sign < 0) {
3262                 if (file > limit)
3263                         ret = 1;
3264                 else if (mds)
3265                         ret = 0;
3266         }
3267
3268         return negopt ? ~ret + 1 : ret;
3269 }
3270
3271 static inline struct lov_user_md *
3272 lov_comp_entry(struct lov_comp_md_v1 *comp_v1, int ent_idx)
3273 {
3274         return (struct lov_user_md *)((char *)comp_v1 +
3275                         comp_v1->lcm_entries[ent_idx].lcme_offset);
3276 }
3277
3278 static inline struct lov_user_ost_data_v1 *
3279 lov_v1v3_objects(struct lov_user_md *v1)
3280 {
3281         if (v1->lmm_magic == LOV_USER_MAGIC_V3)
3282                 return ((struct lov_user_md_v3 *)v1)->lmm_objects;
3283         else
3284                 return v1->lmm_objects;
3285 }
3286
3287 static inline void
3288 lov_v1v3_pool_name(struct lov_user_md *v1, char *pool_name)
3289 {
3290         if (v1->lmm_magic == LOV_USER_MAGIC_V3)
3291                 snprintf(pool_name, LOV_MAXPOOLNAME, "%s",
3292                          ((struct lov_user_md_v3 *)v1)->lmm_pool_name);
3293         else
3294                 pool_name[0] = '\0';
3295 }
3296
3297 static inline bool
3298 print_last_init_comp(struct find_param *param)
3299 {
3300         /* print all component info */
3301         if ((param->fp_verbose & VERBOSE_DEFAULT) == VERBOSE_DEFAULT)
3302                 return false;
3303
3304         /* print specific component info */
3305         if (param->fp_check_comp_id || param->fp_check_comp_flags ||
3306             param->fp_check_comp_start || param->fp_check_comp_end ||
3307             param->fp_check_mirror_id || param->fp_check_mirror_index)
3308                 return false;
3309
3310         return true;
3311 }
3312
3313 static int find_comp_end_cmp(unsigned long long end, struct find_param *param)
3314 {
3315         int match;
3316
3317         if (param->fp_comp_end == LUSTRE_EOF) {
3318                 if (param->fp_comp_end_sign == 0) /* equal to EOF */
3319                         match = end == LUSTRE_EOF ? 1 : -1;
3320                 else if (param->fp_comp_end_sign > 0) /* at most EOF */
3321                         match = end == LUSTRE_EOF ? -1 : 1;
3322                 else /* at least EOF */
3323                         match = -1;
3324                 if (param->fp_exclude_comp_end)
3325                         match = ~match + 1;
3326         } else {
3327                 unsigned long long margin;
3328
3329                 margin = end == LUSTRE_EOF ? 0 : param->fp_comp_end_units;
3330                 match = find_value_cmp(end, param->fp_comp_end,
3331                                        param->fp_comp_end_sign,
3332                                        param->fp_exclude_comp_end, margin, 0);
3333         }
3334
3335         return match;
3336 }
3337
3338 /**
3339  * An example of "getstripe -v" for a two components PFL file:
3340  *
3341  * composite_header:
3342  * lcm_magic:       0x0BD60BD0
3343  * lcm_size:        264
3344  * lcm_flags:       0
3345  * lcm_layout_gen:  2
3346  * lcm_entry_count: 2
3347  * components:
3348  * - lcme_id:             1
3349  *   lcme_flags:          0x10
3350  *   lcme_extent.e_start: 0
3351  *   lcme_extent.e_end:   1048576
3352  *   lcme_offset:         128
3353  *   lcme_size:           56
3354  *   sub_layout:
3355  *     lmm_magic:         0x0BD10BD0
3356  *     lmm_seq:           0x200000401
3357  *     lmm_object_id:     0x1
3358  *     lmm_fid:           [0x200000401:0x1:0x0]
3359  *     lmm_stripe_count:  1
3360  *     lmm_stripe_size:   1048576
3361  *     lmm_pattern:       raid0
3362  *     lmm_layout_gen:    0
3363  *     lmm_stripe_offset: 0
3364  *     lmm_objects:
3365  *     - 0: { l_ost_idx: 0, l_fid: [0x100000000:0x2:0x0] }
3366  *
3367  * - lcme_id:             2
3368  *   lcme_flags:          0x10
3369  *   lcme_extent.e_start: 1048576
3370  *   lcme_extent.e_end:   EOF
3371  *   lcme_offset:         184
3372  *   lcme_size:           80
3373  *     sub_layout:
3374  *     lmm_magic:         0x0BD10BD0
3375  *     lmm_seq:           0x200000401
3376  *     lmm_object_id:     0x1
3377  *     lmm_fid:           [0x200000401:0x1:0x0]
3378  *     lmm_stripe_count:  2
3379  *     lmm_stripe_size:   1048576
3380  *     lmm_pattern:       raid0
3381  *     lmm_layout_gen:    0
3382  *     lmm_stripe_offset: 1
3383  *     lmm_objects:
3384  *     - 0: { l_ost_idx: 1, l_fid: [0x100010000:0x2:0x0] }
3385  *     - 1: { l_ost_idx: 0, l_fid: [0x100000000:0x3:0x0] }
3386  */
3387 static void lov_dump_comp_v1(struct find_param *param, char *path,
3388                              enum lov_dump_flags flags)
3389 {
3390         struct lov_comp_md_entry_v1 *entry;
3391         struct lov_user_ost_data_v1 *objects;
3392         struct lov_comp_md_v1 *comp_v1 = (void *)&param->fp_lmd->lmd_lmm;
3393         struct lov_user_md_v1 *v1;
3394         char pool_name[LOV_MAXPOOLNAME + 1];
3395         int obdindex = param->fp_obd_index;
3396         int i, j, match;
3397         bool obdstripe = false;
3398         __u16 mirror_index = 0;
3399         __u16 mirror_id = 0;
3400
3401         if (obdindex != OBD_NOT_FOUND) {
3402                 for (i = 0; !(flags & LDF_IS_DIR) && !obdstripe &&
3403                             i < comp_v1->lcm_entry_count; i++) {
3404                         if (!(comp_v1->lcm_entries[i].lcme_flags &
3405                               LCME_FL_INIT))
3406                                 continue;
3407
3408                         v1 = lov_comp_entry(comp_v1, i);
3409                         objects = lov_v1v3_objects(v1);
3410
3411                         for (j = 0; j < v1->lmm_stripe_count; j++) {
3412                                 if (obdindex == objects[j].l_ost_idx) {
3413                                         obdstripe = true;
3414                                         break;
3415                                 }
3416                         }
3417                 }
3418         } else {
3419                 obdstripe = true;
3420         }
3421
3422         if (!obdstripe)
3423                 return;
3424
3425         lov_dump_comp_v1_header(param, path, flags);
3426
3427         flags |= LDF_INDENT;
3428
3429         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
3430                 entry = &comp_v1->lcm_entries[i];
3431
3432                 if (param->fp_check_comp_flags) {
3433                         if (((param->fp_comp_flags & entry->lcme_flags) !=
3434                              param->fp_comp_flags) ||
3435                             (param->fp_comp_neg_flags & entry->lcme_flags))
3436                                 continue;
3437                 }
3438
3439                 if (param->fp_check_comp_id &&
3440                     param->fp_comp_id != entry->lcme_id)
3441                         continue;
3442
3443                 if (param->fp_check_comp_start) {
3444                         match = find_value_cmp(entry->lcme_extent.e_start,
3445                                                param->fp_comp_start,
3446                                                param->fp_comp_start_sign,
3447                                                0,
3448                                                param->fp_comp_start_units, 0);
3449                         if (match == -1)
3450                                 continue;
3451                 }
3452
3453                 if (param->fp_check_comp_end) {
3454                         match = find_comp_end_cmp(entry->lcme_extent.e_end,
3455                                                   param);
3456                         if (match == -1)
3457                                 continue;
3458                 }
3459
3460                 if (param->fp_check_mirror_index) {
3461                         if (mirror_id != mirror_id_of(entry->lcme_id)) {
3462                                 mirror_index++;
3463                                 mirror_id = mirror_id_of(entry->lcme_id);
3464                         }
3465
3466                         match = find_value_cmp(mirror_index,
3467                                                param->fp_mirror_index,
3468                                                param->fp_mirror_index_sign,
3469                                                param->fp_exclude_mirror_index,
3470                                                1, 0);
3471                         if (match == -1)
3472                                 continue;
3473                 } else if (param->fp_check_mirror_id) {
3474                         if (mirror_id != mirror_id_of(entry->lcme_id))
3475                                 mirror_id = mirror_id_of(entry->lcme_id);
3476
3477                         match = find_value_cmp(mirror_id,
3478                                                param->fp_mirror_id,
3479                                                param->fp_mirror_id_sign,
3480                                                param->fp_exclude_mirror_id,
3481                                                1, 0);
3482                         if (match == -1)
3483                                 continue;
3484                 }
3485
3486                 if (print_last_init_comp(param)) {
3487                         /**
3488                          * if part of stripe info is needed, we'd print only
3489                          * the last instantiated component info.
3490                          */
3491                         if (entry->lcme_flags & LCME_FL_INIT)
3492                                 continue;
3493                         else
3494                                 break;
3495                 }
3496
3497                 if (entry->lcme_flags & LCME_FL_INIT) {
3498                         if (obdindex != OBD_NOT_FOUND) {
3499                                 flags |= LDF_SKIP_OBJS;
3500                                 v1 = lov_comp_entry(comp_v1, i);
3501                                 objects = lov_v1v3_objects(v1);
3502
3503                                 for (j = 0; j < v1->lmm_stripe_count; j++) {
3504                                         if (obdindex == objects[j].l_ost_idx) {
3505                                                 flags &= ~LDF_SKIP_OBJS;
3506                                                 break;
3507                                         }
3508                                 }
3509                         } else {
3510                                 flags &= ~LDF_SKIP_OBJS;
3511                         }
3512                 } else {
3513                         flags |= LDF_SKIP_OBJS;
3514                 }
3515
3516                 if (obdindex != OBD_NOT_FOUND && (flags & LDF_SKIP_OBJS))
3517                         continue;
3518                 lov_dump_comp_v1_entry(param, flags, i);
3519
3520                 v1 = lov_comp_entry(comp_v1, i);
3521                 objects = lov_v1v3_objects(v1);
3522                 lov_v1v3_pool_name(v1, pool_name);
3523
3524                 lov_dump_user_lmm_v1v3(v1, pool_name, objects, path, obdindex,
3525                                        param->fp_max_depth, param->fp_verbose,
3526                                        flags);
3527         }
3528         if (print_last_init_comp(param)) {
3529                 /**
3530                  * directory layout contains only layout template, print the
3531                  * last component.
3532                  */
3533                 if (i == 0)
3534                         i = comp_v1->lcm_entry_count - 1;
3535                 else
3536                         i--;
3537                 flags &= ~LDF_SKIP_OBJS;
3538
3539                 lov_dump_comp_v1_entry(param, flags, i);
3540
3541                 v1 = lov_comp_entry(comp_v1, i);
3542                 objects = lov_v1v3_objects(v1);
3543                 lov_v1v3_pool_name(v1, pool_name);
3544
3545                 lov_dump_user_lmm_v1v3(v1, pool_name, objects, path, obdindex,
3546                                        param->fp_max_depth, param->fp_verbose,
3547                                        flags);
3548         }
3549 }
3550
3551 #define VERBOSE_COMP_OPTS       (VERBOSE_COMP_COUNT | VERBOSE_COMP_ID | \
3552                                  VERBOSE_COMP_START | VERBOSE_COMP_END | \
3553                                  VERBOSE_COMP_FLAGS)
3554
3555 static inline bool has_any_comp_options(struct find_param *param)
3556 {
3557         enum llapi_layout_verbose verbose = param->fp_verbose;
3558
3559         if (param->fp_check_comp_id || param->fp_check_comp_count ||
3560             param->fp_check_comp_start || param->fp_check_comp_end ||
3561             param->fp_check_comp_flags)
3562                 return true;
3563
3564         /* show full layout information, not component specific */
3565         if ((verbose & ~VERBOSE_DETAIL) == VERBOSE_DEFAULT)
3566                 return false;
3567
3568         return verbose & VERBOSE_COMP_OPTS;
3569 }
3570
3571 struct lov_user_mds_data *lov_forge_comp_v1(struct lov_user_mds_data *orig,
3572                                             bool is_dir)
3573 {
3574         struct lov_user_md *lum = &orig->lmd_lmm;
3575         struct lov_user_mds_data *new;
3576         struct lov_comp_md_v1 *comp_v1;
3577         struct lov_comp_md_entry_v1 *ent;
3578         int lum_off = sizeof(*comp_v1) + sizeof(*ent);
3579         int lum_size = lov_user_md_size(is_dir ? 0 : lum->lmm_stripe_count,
3580                                         lum->lmm_magic);
3581
3582         new = malloc(sizeof(lstat_t) + lum_off + lum_size);
3583         if (new == NULL) {
3584                 llapi_printf(LLAPI_MSG_NORMAL, "out of memory\n");
3585                 return new;
3586         }
3587
3588         memcpy(new, orig, sizeof(lstat_t));
3589
3590         comp_v1 = (struct lov_comp_md_v1 *)&new->lmd_lmm;
3591         comp_v1->lcm_magic = lum->lmm_magic;
3592         comp_v1->lcm_size = lum_off + lum_size;
3593         comp_v1->lcm_layout_gen = is_dir ? 0 : lum->lmm_layout_gen;
3594         comp_v1->lcm_flags = 0;
3595         comp_v1->lcm_entry_count = 1;
3596
3597         ent = &comp_v1->lcm_entries[0];
3598         ent->lcme_id = 0;
3599         ent->lcme_flags = is_dir ? 0 : LCME_FL_INIT;
3600         ent->lcme_extent.e_start = 0;
3601         ent->lcme_extent.e_end = LUSTRE_EOF;
3602         ent->lcme_offset = lum_off;
3603         ent->lcme_size = lum_size;
3604
3605         memcpy((char *)comp_v1 + lum_off, lum, lum_size);
3606
3607         return new;
3608 }
3609
3610 static void lov_dump_plain_user_lmm(struct find_param *param, char *path,
3611                                     enum lov_dump_flags flags)
3612 {
3613         __u32 magic = *(__u32 *)&param->fp_lmd->lmd_lmm;
3614
3615         if (has_any_comp_options(param)) {
3616                 struct lov_user_mds_data *new_lmd, *orig_lmd;
3617
3618                 orig_lmd = param->fp_lmd;
3619                 new_lmd = lov_forge_comp_v1(orig_lmd, flags & LDF_IS_DIR);
3620                 if (new_lmd != NULL) {
3621                         param->fp_lmd = new_lmd;
3622                         lov_dump_comp_v1(param, path, flags);
3623                         param->fp_lmd = orig_lmd;
3624                         free(new_lmd);
3625                 }
3626                 return;
3627         }
3628
3629         if (magic == LOV_USER_MAGIC_V1) {
3630                 lov_dump_user_lmm_v1v3(&param->fp_lmd->lmd_lmm, NULL,
3631                                        param->fp_lmd->lmd_lmm.lmm_objects,
3632                                        path, param->fp_obd_index,
3633                                        param->fp_max_depth, param->fp_verbose,
3634                                        flags);
3635         } else {
3636                 char pool_name[LOV_MAXPOOLNAME + 1];
3637                 struct lov_user_ost_data_v1 *objects;
3638                 struct lov_user_md_v3 *lmmv3 = (void *)&param->fp_lmd->lmd_lmm;
3639
3640                 snprintf(pool_name, sizeof(pool_name), "%s",
3641                          lmmv3->lmm_pool_name);
3642                 objects = lmmv3->lmm_objects;
3643                 lov_dump_user_lmm_v1v3(&param->fp_lmd->lmd_lmm, pool_name,
3644                                        objects, path, param->fp_obd_index,
3645                                        param->fp_max_depth, param->fp_verbose,
3646                                        flags);
3647         }
3648 }
3649
3650 static uint32_t check_foreign_type(uint32_t foreign_type)
3651 {
3652         uint32_t i;
3653
3654         for (i = 0; i < LU_FOREIGN_TYPE_UNKNOWN; i++) {
3655                 if (lu_foreign_types[i].lft_name == NULL)
3656                         break;
3657                 if (foreign_type == lu_foreign_types[i].lft_type)
3658                         return i;
3659         }
3660
3661         return LU_FOREIGN_TYPE_UNKNOWN;
3662 }
3663
3664 static void lov_dump_foreign_lmm(struct find_param *param, char *path,
3665                                  enum lov_dump_flags flags)
3666 {
3667         struct lov_foreign_md *lfm = (void *)&param->fp_lmd->lmd_lmm;
3668         bool yaml = flags & LDF_YAML;
3669
3670         if (!yaml && param->fp_depth && path)
3671                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
3672
3673         if (param->fp_verbose & VERBOSE_DETAIL) {
3674                 uint32_t type = check_foreign_type(lfm->lfm_type);
3675
3676                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_magic:         0x%08X\n",
3677                              lfm->lfm_magic);
3678                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_length:          %u\n",
3679                              lfm->lfm_length);
3680                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_type:          0x%08X",
3681                              lfm->lfm_type);
3682                 if (type < LU_FOREIGN_TYPE_UNKNOWN)
3683                         llapi_printf(LLAPI_MSG_NORMAL, " (%s)\n",
3684                                      lu_foreign_types[type].lft_name);
3685                 else
3686                         llapi_printf(LLAPI_MSG_NORMAL, " (unknown)\n");
3687
3688                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_flags:          0x%08X\n",
3689                              lfm->lfm_flags);
3690         }
3691         llapi_printf(LLAPI_MSG_NORMAL, "lfm_value:     '%.*s'\n",
3692                      lfm->lfm_length, lfm->lfm_value);
3693         llapi_printf(LLAPI_MSG_NORMAL, "\n");
3694 }
3695
3696 static void lmv_dump_foreign_lmm(struct find_param *param, char *path,
3697                                     enum lov_dump_flags flags)
3698 {
3699         struct lmv_foreign_md *lfm = (struct lmv_foreign_md *)param->fp_lmv_md;
3700         bool yaml = flags & LDF_YAML;
3701
3702         if (!yaml && param->fp_depth && path)
3703                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
3704
3705         if (param->fp_verbose & VERBOSE_DETAIL) {
3706                 uint32_t type = check_foreign_type(lfm->lfm_type);
3707
3708                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_magic:         0x%08X\n",
3709                              lfm->lfm_magic);
3710                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_length:          %u\n",
3711                              lfm->lfm_length);
3712                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_type:          0x%08X",
3713                              lfm->lfm_type);
3714                 if (type < LU_FOREIGN_TYPE_UNKNOWN)
3715                         llapi_printf(LLAPI_MSG_NORMAL, " (%s)\n",
3716                                      lu_foreign_types[type].lft_name);
3717                 else
3718                         llapi_printf(LLAPI_MSG_NORMAL, " (unknown)\n");
3719
3720                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_flags:          0x%08X\n",
3721                              lfm->lfm_flags);
3722         }
3723         llapi_printf(LLAPI_MSG_NORMAL, "lfm_value:     '%.*s'\n",
3724                      lfm->lfm_length, lfm->lfm_value);
3725         llapi_printf(LLAPI_MSG_NORMAL, "\n");
3726 }
3727
3728 static void llapi_lov_dump_user_lmm(struct find_param *param, char *path,
3729                                     enum lov_dump_flags flags)
3730 {
3731         __u32 magic;
3732
3733         if (param->fp_get_lmv || param->fp_get_default_lmv)
3734                 magic = (__u32)param->fp_lmv_md->lum_magic;
3735         else
3736                 magic = *(__u32 *)&param->fp_lmd->lmd_lmm; /* lum->lmm_magic */
3737
3738         if (param->fp_raw)
3739                 flags |= LDF_IS_RAW;
3740         if (param->fp_yaml)
3741                 flags |= LDF_YAML;
3742
3743         switch (magic) {
3744         case LOV_USER_MAGIC_V1:
3745         case LOV_USER_MAGIC_V3:
3746         case LOV_USER_MAGIC_SPECIFIC:
3747                 lov_dump_plain_user_lmm(param, path, flags);
3748                 break;
3749         case LOV_USER_MAGIC_FOREIGN:
3750                 lov_dump_foreign_lmm(param, path, flags);
3751                 break;
3752         case LMV_MAGIC_V1:
3753         case LMV_USER_MAGIC: {
3754                 char pool_name[LOV_MAXPOOLNAME + 1];
3755                 struct lmv_user_md *lum;
3756
3757                 lum = (struct lmv_user_md *)param->fp_lmv_md;
3758                 snprintf(pool_name, sizeof(pool_name), "%s",
3759                          lum->lum_pool_name);
3760                 lmv_dump_user_lmm(lum, pool_name, path, param->fp_obd_index,
3761                                   param->fp_max_depth, param->fp_verbose,
3762                                   flags);
3763                 break;
3764         }
3765         case LOV_USER_MAGIC_COMP_V1:
3766                 lov_dump_comp_v1(param, path, flags);
3767                 break;
3768         case LMV_MAGIC_FOREIGN:
3769                 lmv_dump_foreign_lmm(param, path, flags);
3770                 break;
3771         default:
3772                 llapi_printf(LLAPI_MSG_NORMAL, "unknown lmm_magic:  %#x "
3773                              "(expecting one of %#x %#x %#x %#x)\n",
3774                              *(__u32 *)&param->fp_lmd->lmd_lmm,
3775                              LOV_USER_MAGIC_V1, LOV_USER_MAGIC_V3,
3776                              LMV_USER_MAGIC, LMV_MAGIC_V1);
3777                 return;
3778         }
3779 }
3780
3781 int llapi_file_get_stripe(const char *path, struct lov_user_md *lum)
3782 {
3783         const char *fname;
3784         char *dname;
3785         int fd, rc = 0;
3786
3787         fname = strrchr(path, '/');
3788
3789         /* It should be a file (or other non-directory) */
3790         if (fname == NULL) {
3791                 dname = (char *)malloc(2);
3792                 if (dname == NULL)
3793                         return -ENOMEM;
3794                 strcpy(dname, ".");
3795                 fname = (char *)path;
3796         } else {
3797                 dname = (char *)malloc(fname - path + 1);
3798                 if (dname == NULL)
3799                         return -ENOMEM;
3800                 strncpy(dname, path, fname - path);
3801                 dname[fname - path] = '\0';
3802                 fname++;
3803         }
3804
3805         fd = open(dname, O_RDONLY | O_NONBLOCK);
3806         if (fd == -1) {
3807                 rc = -errno;
3808                 goto out_free;
3809         }
3810
3811         strcpy((char *)lum, fname);
3812         if (ioctl(fd, IOC_MDC_GETFILESTRIPE, (void *)lum) == -1)
3813                 rc = -errno;
3814
3815         if (close(fd) == -1 && rc == 0)
3816                 rc = -errno;
3817
3818 out_free:
3819         free(dname);
3820         return rc;
3821 }
3822
3823 int llapi_file_lookup(int dirfd, const char *name)
3824 {
3825         struct obd_ioctl_data data = { 0 };
3826         char rawbuf[8192];
3827         char *buf = rawbuf;
3828         int rc;
3829
3830         if (dirfd < 0 || name == NULL)
3831                 return -EINVAL;
3832
3833         data.ioc_version = OBD_IOCTL_VERSION;
3834         data.ioc_len = sizeof(data);
3835         data.ioc_inlbuf1 = (char *)name;
3836         data.ioc_inllen1 = strlen(name) + 1;
3837
3838         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
3839         if (rc) {
3840                 llapi_error(LLAPI_MSG_ERROR, rc,
3841                             "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
3842                             name, rc);
3843                 return rc;
3844         }
3845
3846         rc = ioctl(dirfd, IOC_MDC_LOOKUP, buf);
3847         if (rc < 0)
3848                 rc = -errno;
3849         return rc;
3850 }
3851
3852 /* Check if the file time matches all the given criteria (e.g. --atime +/-N).
3853  * Return -1 or 1 if file timestamp does not or does match the given criteria
3854  * correspondingly. Return 0 if the MDS time is being checked and there are
3855  * attributes on OSTs and it is not yet clear if the timespamp matches.
3856  *
3857  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
3858  * updated timestamps. */
3859 static int find_time_check(lstat_t *st, struct find_param *param, int mds)
3860 {
3861         int rc = 1;
3862         int rc2;
3863
3864         /* Check if file is accepted. */
3865         if (param->fp_atime) {
3866                 rc2 = find_value_cmp(st->st_atime, param->fp_atime,
3867                                      param->fp_asign, param->fp_exclude_atime,
3868                                      param->fp_time_margin, mds);
3869                 if (rc2 < 0)
3870                         return rc2;
3871                 rc = rc2;
3872         }
3873
3874         if (param->fp_mtime) {
3875                 rc2 = find_value_cmp(st->st_mtime, param->fp_mtime,
3876                                      param->fp_msign, param->fp_exclude_mtime,
3877                                      param->fp_time_margin, mds);
3878                 if (rc2 < 0)
3879                         return rc2;
3880
3881                 /* If the previous check matches, but this one is not yet clear,
3882                  * we should return 0 to do an RPC on OSTs. */
3883                 if (rc == 1)
3884                         rc = rc2;
3885         }
3886
3887         if (param->fp_ctime) {
3888                 rc2 = find_value_cmp(st->st_ctime, param->fp_ctime,
3889                                      param->fp_csign, param->fp_exclude_ctime,
3890                                      param->fp_time_margin, mds);
3891                 if (rc2 < 0)
3892                         return rc2;
3893
3894                 /* If the previous check matches, but this one is not yet clear,
3895                  * we should return 0 to do an RPC on OSTs. */
3896                 if (rc == 1)
3897                         rc = rc2;
3898         }
3899
3900         return rc;
3901 }
3902
3903 /**
3904  * Check whether the stripes matches the indexes user provided
3905  *       1   : matched
3906  *       0   : Unmatched
3907  */
3908 static int check_obd_match(struct find_param *param)
3909 {
3910         struct lov_user_ost_data_v1 *objects;
3911         struct lov_comp_md_v1 *comp_v1 = NULL;
3912         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
3913         lstat_t *st = &param->fp_lmd->lmd_st;
3914         int i, j, k, count = 1;
3915
3916         if (param->fp_obd_uuid && param->fp_obd_index == OBD_NOT_FOUND)
3917                 return 0;
3918
3919         if (!S_ISREG(st->st_mode))
3920                 return 0;
3921
3922         /* exclude foreign */
3923         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
3924                 return param->fp_exclude_obd;
3925
3926         /* Only those files should be accepted, which have a
3927          * stripe on the specified OST. */
3928         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
3929                 comp_v1 = (struct lov_comp_md_v1 *)v1;
3930                 count = comp_v1->lcm_entry_count;
3931         }
3932
3933         for (i = 0; i < count; i++) {
3934                 if (comp_v1)
3935                         v1 = lov_comp_entry(comp_v1, i);
3936
3937                 objects = lov_v1v3_objects(v1);
3938
3939                 for (j = 0; j < v1->lmm_stripe_count; j++) {
3940                         if (comp_v1 && !(comp_v1->lcm_entries[i].lcme_flags &
3941                                          LCME_FL_INIT))
3942                                 continue;
3943                         for (k = 0; k < param->fp_num_obds; k++) {
3944                                 if (param->fp_obd_indexes[k] ==
3945                                     objects[j].l_ost_idx)
3946                                         return !param->fp_exclude_obd;
3947                         }
3948                 }
3949         }
3950
3951         return param->fp_exclude_obd;
3952 }
3953
3954 static int check_mdt_match(struct find_param *param)
3955 {
3956         int i;
3957
3958         if (param->fp_mdt_uuid && param->fp_mdt_index == OBD_NOT_FOUND)
3959                 return 0;
3960
3961         /* FIXME: For striped dir, we should get stripe information and check */
3962         for (i = 0; i < param->fp_num_mdts; i++) {
3963                 if (param->fp_mdt_indexes[i] == param->fp_file_mdt_index)
3964                         return !param->fp_exclude_mdt;
3965         }
3966
3967         if (param->fp_exclude_mdt)
3968                 return 1;
3969
3970         return 0;
3971 }
3972
3973 /**
3974  * Check whether the obd is active or not, if it is
3975  * not active, just print the object affected by this
3976  * failed target
3977  **/
3978 static int print_failed_tgt(struct find_param *param, char *path, int type)
3979 {
3980         struct obd_statfs stat_buf;
3981         struct obd_uuid uuid_buf;
3982         int ret;
3983
3984         if (type != LL_STATFS_LOV && type != LL_STATFS_LMV)
3985                 return -EINVAL;
3986
3987         memset(&stat_buf, 0, sizeof(struct obd_statfs));
3988         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
3989         ret = llapi_obd_statfs(path, type,
3990                                param->fp_obd_index, &stat_buf,
3991                                &uuid_buf);
3992         if (ret) {
3993                 llapi_printf(LLAPI_MSG_NORMAL,
3994                              "obd_uuid: %s failed %s ",
3995                              param->fp_obd_uuid->uuid,
3996                              strerror(errno));
3997         }
3998
3999         return ret;
4000 }
4001
4002 static int find_check_stripe_size(struct find_param *param)
4003 {
4004         struct lov_comp_md_v1 *comp_v1 = NULL;
4005         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4006         int ret, i, count = 1;
4007
4008         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4009                 return param->fp_exclude_stripe_size ? 1 : -1;
4010
4011         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4012                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4013                 count = comp_v1->lcm_entry_count;
4014                 ret = param->fp_exclude_stripe_size ? 1 : -1;
4015         }
4016
4017         for (i = 0; i < count; i++) {
4018                 if (comp_v1)
4019                         v1 = lov_comp_entry(comp_v1, i);
4020
4021                 ret = find_value_cmp(v1->lmm_stripe_size, param->fp_stripe_size,
4022                                      param->fp_stripe_size_sign,
4023                                      param->fp_exclude_stripe_size,
4024                                      param->fp_stripe_size_units, 0);
4025                 /* If any stripe_size matches */
4026                 if (ret != -1)
4027                         break;
4028         }
4029
4030         return ret;
4031 }
4032
4033 static __u32 find_get_stripe_count(struct find_param *param)
4034 {
4035         struct lov_comp_md_v1 *comp_v1 = NULL;
4036         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4037         int i, count = 1;
4038         __u32 stripe_count = 0;
4039
4040         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4041                 return 0;
4042
4043         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4044                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4045                 count = comp_v1->lcm_entry_count;
4046         }
4047
4048         for (i = 0; i < count; i++) {
4049                 if (comp_v1)
4050                         v1 = lov_comp_entry(comp_v1, i);
4051                 stripe_count += v1->lmm_stripe_count;
4052         }
4053
4054         return stripe_count;
4055 }
4056
4057 #define LOV_PATTERN_INVALID     0xFFFFFFFF
4058
4059 static int find_check_layout(struct find_param *param)
4060 {
4061         struct lov_comp_md_v1 *comp_v1 = NULL;
4062         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4063         int i, count = 1;
4064         bool found = false, valid = false;
4065
4066         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4067                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4068                 count = comp_v1->lcm_entry_count;
4069         }
4070
4071         for (i = 0; i < count; i++) {
4072                 if (comp_v1)
4073                         v1 = lov_comp_entry(comp_v1, i);
4074
4075                 /* foreign file have a special magic but no pattern field */
4076                 if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4077                         continue;
4078
4079                 if (v1->lmm_pattern == LOV_PATTERN_INVALID)
4080                         continue;
4081
4082                 valid = true;
4083                 if (v1->lmm_pattern & param->fp_layout) {
4084                         found = true;
4085                         break;
4086                 }
4087         }
4088
4089         if (!valid)
4090                 return -1;
4091
4092         if ((found && !param->fp_exclude_layout) ||
4093             (!found && param->fp_exclude_layout))
4094                 return 1;
4095
4096         return -1;
4097 }
4098
4099 /* if no type specified, check/exclude all foreign
4100  * if type specified, check all foreign&type and exclude !foreign + foreign&type
4101  */
4102 static int find_check_foreign(struct find_param *param)
4103 {
4104         if (S_ISREG(param->fp_lmd->lmd_st.st_mode)) {
4105                 struct lov_foreign_md *lfm;
4106
4107                 lfm = (void *)&param->fp_lmd->lmd_lmm;
4108                 if (lfm->lfm_magic != LOV_USER_MAGIC_FOREIGN) {
4109                         if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN)
4110                                 return param->fp_exclude_foreign ? 1 : -1;
4111                         return -1;
4112                 } else {
4113                         if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN ||
4114                             lfm->lfm_type == param->fp_foreign_type)
4115                                 return param->fp_exclude_foreign ? -1 : 1;
4116                         return param->fp_exclude_foreign ? 1 : -1;
4117                 }
4118         }
4119
4120         if (S_ISDIR(param->fp_lmd->lmd_st.st_mode)) {
4121                 struct lmv_foreign_md *lfm;
4122
4123                 lfm = (void *)param->fp_lmv_md;
4124                 if (lfm->lfm_magic != LMV_MAGIC_FOREIGN) {
4125                         if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN)
4126                                 return param->fp_exclude_foreign ? 1 : -1;
4127                         return -1;
4128                 } else {
4129                         if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN ||
4130                             lfm->lfm_type == param->fp_foreign_type)
4131                                 return param->fp_exclude_foreign ? -1 : 1;
4132                         return param->fp_exclude_foreign ? 1 : -1;
4133                 }
4134         }
4135         return -1;
4136 }
4137
4138 static int find_check_pool(struct find_param *param)
4139 {
4140         struct lov_comp_md_v1 *comp_v1 = NULL;
4141         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4142         struct lov_user_md_v3 *v3 = (void *)v1;
4143         int i, count = 1;
4144         bool found = false;
4145
4146         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4147                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4148                 count = comp_v1->lcm_entry_count;
4149                 /* empty requested pool is taken as no pool search */
4150                 if (count == 0 && param->fp_poolname[0] == '\0')
4151                         found = true;
4152         }
4153
4154         for (i = 0; i < count; i++) {
4155                 if (comp_v1 != NULL)
4156                         v1 = lov_comp_entry(comp_v1, i);
4157
4158                 if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4159                         continue;
4160
4161                 if (((v1->lmm_magic == LOV_USER_MAGIC_V1) &&
4162                      (param->fp_poolname[0] == '\0')) ||
4163                     ((v1->lmm_magic == LOV_USER_MAGIC_V3) &&
4164                      (strncmp(v3->lmm_pool_name,
4165                               param->fp_poolname, LOV_MAXPOOLNAME) == 0)) ||
4166                     ((v1->lmm_magic == LOV_USER_MAGIC_V3) &&
4167                      (strcmp(param->fp_poolname, "*") == 0))) {
4168                         found = true;
4169                         break;
4170                 }
4171         }
4172
4173         if ((found && !param->fp_exclude_pool) ||
4174             (!found && param->fp_exclude_pool))
4175                 return 1;
4176
4177         return -1;
4178 }
4179
4180 static int find_check_comp_options(struct find_param *param)
4181 {
4182         lstat_t *st = &param->fp_lmd->lmd_st;
4183         struct lov_comp_md_v1 *comp_v1, *forged_v1 = NULL;
4184         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4185         struct lov_comp_md_entry_v1 *entry;
4186         int i, ret = 0;
4187
4188         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4189                 return -1;
4190
4191         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4192                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4193         } else {
4194                 forged_v1 = malloc(sizeof(*forged_v1) + sizeof(*entry));
4195                 if (forged_v1 == NULL)
4196                         return -1;
4197                 comp_v1 = forged_v1;
4198                 comp_v1->lcm_entry_count = 1;
4199                 entry = &comp_v1->lcm_entries[0];
4200                 entry->lcme_flags = S_ISDIR(st->st_mode) ? 0 : LCME_FL_INIT;
4201                 entry->lcme_extent.e_start = 0;
4202                 entry->lcme_extent.e_end = LUSTRE_EOF;
4203         }
4204
4205         /* invalid case, don't match for any kind of search. */
4206         if (comp_v1->lcm_entry_count == 0) {
4207                 ret = -1;
4208                 goto out;
4209         }
4210
4211         if (param->fp_check_comp_count) {
4212                 ret = find_value_cmp(forged_v1 ? 0 : comp_v1->lcm_entry_count,
4213                                      param->fp_comp_count,
4214                                      param->fp_comp_count_sign,
4215                                      param->fp_exclude_comp_count, 1, 0);
4216                 if (ret == -1)
4217                         goto out;
4218         }
4219
4220         ret = 1;
4221         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
4222                 entry = &comp_v1->lcm_entries[i];
4223
4224                 if (param->fp_check_comp_flags) {
4225                         ret = 1;
4226                         if (((param->fp_comp_flags & entry->lcme_flags) !=
4227                              param->fp_comp_flags) ||
4228                             (param->fp_comp_neg_flags & entry->lcme_flags)) {
4229                                 ret = -1;
4230                                 continue;
4231                         }
4232                 }
4233
4234                 if (param->fp_check_comp_start) {
4235                         ret = find_value_cmp(entry->lcme_extent.e_start,
4236                                              param->fp_comp_start,
4237                                              param->fp_comp_start_sign,
4238                                              param->fp_exclude_comp_start,
4239                                              param->fp_comp_start_units, 0);
4240                         if (ret == -1)
4241                                 continue;
4242                 }
4243
4244                 if (param->fp_check_comp_end) {
4245                         ret = find_comp_end_cmp(entry->lcme_extent.e_end,
4246                                                 param);
4247                         if (ret == -1)
4248                                 continue;
4249                 }
4250
4251                 /* the component matches all criteria */
4252                 break;
4253         }
4254 out:
4255         if (forged_v1)
4256                 free(forged_v1);
4257         return ret;
4258 }
4259
4260 static int find_check_mirror_options(struct find_param *param)
4261 {
4262         struct lov_comp_md_v1 *comp_v1;
4263         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4264         int ret = 0;
4265
4266         if (v1->lmm_magic != LOV_USER_MAGIC_COMP_V1)
4267                 return -1;
4268
4269         comp_v1 = (struct lov_comp_md_v1 *)v1;
4270
4271         if (param->fp_check_mirror_count) {
4272                 ret = find_value_cmp(comp_v1->lcm_mirror_count + 1,
4273                                      param->fp_mirror_count,
4274                                      param->fp_mirror_count_sign,
4275                                      param->fp_exclude_mirror_count, 1, 0);
4276                 if (ret == -1)
4277                         return ret;
4278         }
4279
4280         if (param->fp_check_mirror_state) {
4281                 ret = 1;
4282                 __u16 file_state = comp_v1->lcm_flags & LCM_FL_FLR_MASK;
4283
4284                 if ((param->fp_mirror_state != 0 &&
4285                     file_state != param->fp_mirror_state) ||
4286                     file_state == param->fp_mirror_neg_state)
4287                         return -1;
4288         }
4289
4290         return ret;
4291 }
4292
4293 static bool find_check_lmm_info(struct find_param *param)
4294 {
4295         return param->fp_check_pool || param->fp_check_stripe_count ||
4296                param->fp_check_stripe_size || param->fp_check_layout ||
4297                param->fp_check_comp_count || param->fp_check_comp_end ||
4298                param->fp_check_comp_start || param->fp_check_comp_flags ||
4299                param->fp_check_mirror_count || param->fp_check_foreign ||
4300                param->fp_check_mirror_state ||
4301                param->fp_check_projid;
4302 }
4303
4304 /*
4305  * Get file/directory project id.
4306  * by the open fd resides on.
4307  * Return 0 and project id on success, or -ve errno.
4308  */
4309 static int fget_projid(int fd, int *projid)
4310 {
4311         struct fsxattr fsx;
4312         int rc;
4313
4314         rc = ioctl(fd, LL_IOC_FSGETXATTR, &fsx);
4315         if (rc)
4316                 return -errno;
4317
4318         *projid = fsx.fsx_projid;
4319         return 0;
4320 }
4321
4322 static int cb_find_init(char *path, DIR *parent, DIR **dirp,
4323                         void *data, struct dirent64 *de)
4324 {
4325         struct find_param *param = (struct find_param *)data;
4326         DIR *dir = dirp == NULL ? NULL : *dirp;
4327         int decision = 1; /* 1 is accepted; -1 is rejected. */
4328         lstat_t *st = &param->fp_lmd->lmd_st;
4329         int lustre_fs = 1;
4330         int checked_type = 0;
4331         int ret = 0;
4332         __u32 stripe_count = 0;
4333         int fd = -2;
4334
4335         if (parent == NULL && dir == NULL)
4336                 return -EINVAL;
4337
4338         /* If a regular expression is presented, make the initial decision */
4339         if (param->fp_pattern != NULL) {
4340                 char *fname = strrchr(path, '/');
4341                 fname = (fname == NULL ? path : fname + 1);
4342                 ret = fnmatch(param->fp_pattern, fname, 0);
4343                 if ((ret == FNM_NOMATCH && !param->fp_exclude_pattern) ||
4344                     (ret == 0 && param->fp_exclude_pattern))
4345                         goto decided;
4346         }
4347
4348         /* See if we can check the file type from the dirent. */
4349         if (param->fp_type != 0 && de != NULL && de->d_type != DT_UNKNOWN) {
4350                 checked_type = 1;
4351
4352                 if (DTTOIF(de->d_type) == param->fp_type) {
4353                         if (param->fp_exclude_type)
4354                                 goto decided;
4355                 } else {
4356                         if (!param->fp_exclude_type)
4357                                 goto decided;
4358                 }
4359         }
4360
4361         ret = 0;
4362
4363         /* Request MDS for the stat info if some of these parameters need
4364          * to be compared. */
4365         if (param->fp_obd_uuid || param->fp_mdt_uuid ||
4366             param->fp_check_uid || param->fp_check_gid ||
4367             param->fp_atime || param->fp_mtime || param->fp_ctime ||
4368             param->fp_check_size || param->fp_check_blocks ||
4369             find_check_lmm_info(param) ||
4370             param->fp_check_mdt_count || param->fp_check_hash_type)
4371                 decision = 0;
4372
4373         if (param->fp_type != 0 && checked_type == 0)
4374                 decision = 0;
4375
4376         if (decision == 0) {
4377                 if (dir && (param->fp_check_mdt_count ||
4378                     param->fp_check_hash_type || param->fp_check_foreign)) {
4379                         param->fp_get_lmv = 1;
4380                         ret = cb_get_dirstripe(path, dir, param);
4381                         if (ret != 0) {
4382                                 /* XXX this works to decide for foreign
4383                                  * criterion only
4384                                  */
4385                                 if (errno == ENODATA &&
4386                                     param->fp_check_foreign) {
4387                                         if (param->fp_exclude_foreign)
4388                                                 goto foreign;
4389                                         goto decided;
4390                                 }
4391                                 return ret;
4392                         }
4393                 }
4394
4395                 param->fp_lmd->lmd_lmm.lmm_magic = 0;
4396                 ret = get_lmd_info(path, parent, dir, param->fp_lmd,
4397                                    param->fp_lum_size, GET_LMD_INFO);
4398                 if (ret == 0 && param->fp_lmd->lmd_lmm.lmm_magic == 0 &&
4399                     find_check_lmm_info(param)) {
4400                         struct lov_user_md *lmm = &param->fp_lmd->lmd_lmm;
4401
4402                         /* We need to "fake" the "use the default" values
4403                          * since the lmm struct is zeroed out at this point. */
4404                         lmm->lmm_magic = LOV_USER_MAGIC_V1;
4405                         lmm->lmm_pattern = LOV_PATTERN_DEFAULT;
4406                         if (!param->fp_raw)
4407                                 ostid_set_seq(&lmm->lmm_oi,
4408                                               FID_SEQ_LOV_DEFAULT);
4409                         lmm->lmm_stripe_size = 0;
4410                         lmm->lmm_stripe_count = 0;
4411                         lmm->lmm_stripe_offset = -1;
4412                 }
4413                 if (ret == 0 && param->fp_mdt_uuid != NULL) {
4414                         if (dir != NULL) {
4415                                 ret = llapi_file_fget_mdtidx(dirfd(dir),
4416                                                      &param->fp_file_mdt_index);
4417                         } else if (S_ISREG(st->st_mode)) {
4418                                 /* FIXME: we could get the MDT index from the
4419                                  * file's FID in lmd->lmd_lmm.lmm_oi without
4420                                  * opening the file, once we are sure that
4421                                  * LFSCK2 (2.6) has fixed up pre-2.0 LOV EAs.
4422                                  * That would still be an ioctl() to map the
4423                                  * FID to the MDT, but not an open RPC. */
4424                                 fd = open(path, O_RDONLY);
4425                                 if (fd > 0) {
4426                                         ret = llapi_file_fget_mdtidx(fd,
4427                                                      &param->fp_file_mdt_index);
4428                                 } else {
4429                                         ret = -errno;
4430                                 }
4431                         } else {
4432                                 /* For a special file, we assume it resides on
4433                                  * the same MDT as the parent directory. */
4434                                 ret = llapi_file_fget_mdtidx(dirfd(parent),
4435                                                      &param->fp_file_mdt_index);
4436                         }
4437                 }
4438                 if (ret != 0) {
4439                         if (ret == -ENOTTY)
4440                                 lustre_fs = 0;
4441                         if (ret == -ENOENT)
4442                                 goto decided;
4443
4444                         goto out;
4445                 } else {
4446                         stripe_count = find_get_stripe_count(param);
4447                 }
4448         }
4449
4450         if (param->fp_type && !checked_type) {
4451                 if ((st->st_mode & S_IFMT) == param->fp_type) {
4452                         if (param->fp_exclude_type)
4453                                 goto decided;
4454                 } else {
4455                         if (!param->fp_exclude_type)
4456                                 goto decided;
4457                 }
4458         }
4459
4460         /* Prepare odb. */
4461         if (param->fp_obd_uuid || param->fp_mdt_uuid) {
4462                 if (lustre_fs && param->fp_got_uuids &&
4463                     param->fp_dev != st->st_dev) {
4464                         /* A lustre/lustre mount point is crossed. */
4465                         param->fp_got_uuids = 0;
4466                         param->fp_obds_printed = 0;
4467                         param->fp_mdt_index = OBD_NOT_FOUND;
4468                         param->fp_obd_index = OBD_NOT_FOUND;
4469                 }
4470
4471                 if (lustre_fs && !param->fp_got_uuids) {
4472                         ret = setup_target_indexes(dir ? dir : parent, path,
4473                                                    param);
4474                         if (ret)
4475                                 goto out;
4476
4477                         param->fp_dev = st->st_dev;
4478                 } else if (!lustre_fs && param->fp_got_uuids) {
4479                         /* A lustre/non-lustre mount point is crossed. */
4480                         param->fp_got_uuids = 0;
4481                         param->fp_mdt_index = OBD_NOT_FOUND;
4482                         param->fp_obd_index = OBD_NOT_FOUND;
4483                 }
4484         }
4485
4486         if (param->fp_check_foreign) {
4487                 decision = find_check_foreign(param);
4488                 if (decision == -1)
4489                         goto decided;
4490         }
4491
4492         if (param->fp_check_stripe_size) {
4493                 decision = find_check_stripe_size(param);
4494                 if (decision == -1)
4495                         goto decided;
4496         }
4497
4498         if (param->fp_check_stripe_count) {
4499                 decision = find_value_cmp(stripe_count, param->fp_stripe_count,
4500                                           param->fp_stripe_count_sign,
4501                                           param->fp_exclude_stripe_count, 1, 0);
4502                 if (decision == -1)
4503                         goto decided;
4504         }
4505
4506         if (param->fp_check_mdt_count) {
4507                 if (param->fp_lmv_md->lum_magic == LMV_MAGIC_FOREIGN) {
4508                         decision = -1;
4509                         goto decided;
4510                 }
4511
4512                 decision = find_value_cmp(
4513                                 param->fp_lmv_md->lum_stripe_count,
4514                                 param->fp_mdt_count,
4515                                 param->fp_mdt_count_sign,
4516                                 param->fp_exclude_mdt_count, 1, 0);
4517                 if (decision == -1)
4518                         goto decided;
4519         }
4520
4521         if (param->fp_check_layout) {
4522                 decision = find_check_layout(param);
4523                 if (decision == -1)
4524                         goto decided;
4525         }
4526
4527         if (param->fp_check_hash_type) {
4528                 __u32 found;
4529
4530                 if (param->fp_lmv_md->lum_magic == LMV_MAGIC_FOREIGN) {
4531                         decision = -1;
4532                         goto decided;
4533                 }
4534
4535                 found = param->fp_lmv_md->lum_hash_type & param->fp_hash_type;
4536                 if ((found && param->fp_exclude_hash_type) ||
4537                     (!found && !param->fp_exclude_hash_type)) {
4538                         decision = -1;
4539                         goto decided;
4540                 }
4541         }
4542
4543         /* If an OBD UUID is specified but none matches, skip this file. */
4544         if ((param->fp_obd_uuid && param->fp_obd_index == OBD_NOT_FOUND) ||
4545             (param->fp_mdt_uuid && param->fp_mdt_index == OBD_NOT_FOUND))
4546                 goto decided;
4547
4548         /* If an OST or MDT UUID is given, and some OST matches,
4549          * check it here. */
4550         if (param->fp_obd_index != OBD_NOT_FOUND ||
4551             param->fp_mdt_index != OBD_NOT_FOUND) {
4552                 if (param->fp_obd_uuid) {
4553                         if (check_obd_match(param)) {
4554                                 /* If no mdtuuid is given, we are done.
4555                                  * Otherwise, fall through to the mdtuuid
4556                                  * check below. */
4557                                 if (!param->fp_mdt_uuid)
4558                                         goto obd_matches;
4559                         } else {
4560                                 goto decided;
4561                         }
4562                 }
4563
4564                 if (param->fp_mdt_uuid) {
4565                         if (check_mdt_match(param))
4566                                 goto obd_matches;
4567                         goto decided;
4568                 }
4569         }
4570
4571 obd_matches:
4572         if (param->fp_check_uid) {
4573                 if (st->st_uid == param->fp_uid) {
4574                         if (param->fp_exclude_uid)
4575                                 goto decided;
4576                 } else {
4577                         if (!param->fp_exclude_uid)
4578                                 goto decided;
4579                 }
4580         }
4581
4582         if (param->fp_check_gid) {
4583                 if (st->st_gid == param->fp_gid) {
4584                         if (param->fp_exclude_gid)
4585                                 goto decided;
4586                 } else {
4587                         if (!param->fp_exclude_gid)
4588                                 goto decided;
4589                 }
4590         }
4591
4592         if (param->fp_check_projid) {
4593                 int projid = 0;
4594
4595                 if (fd == -2)
4596                         fd = open(path, O_RDONLY);
4597
4598                 if (fd > 0)
4599                         ret = fget_projid(fd, &projid);
4600                 else
4601                         ret = -errno;
4602                 if (ret)
4603                         goto out;
4604                 if (projid == param->fp_projid) {
4605                         if (param->fp_exclude_projid)
4606                                 goto decided;
4607                 } else {
4608                         if (!param->fp_exclude_projid)
4609                                 goto decided;
4610                 }
4611         }
4612
4613         if (param->fp_check_pool) {
4614                 decision = find_check_pool(param);
4615                 if (decision == -1)
4616                         goto decided;
4617         }
4618
4619         if (param->fp_check_comp_count || param->fp_check_comp_flags ||
4620             param->fp_check_comp_start || param->fp_check_comp_end) {
4621                 decision = find_check_comp_options(param);
4622                 if (decision == -1)
4623                         goto decided;
4624         }
4625
4626         if (param->fp_check_mirror_count || param->fp_check_mirror_state) {
4627                 decision = find_check_mirror_options(param);
4628                 if (decision == -1)
4629                         goto decided;
4630         }
4631
4632         /* Check the time on mds. */
4633         decision = 1;
4634         if (param->fp_atime || param->fp_mtime || param->fp_ctime) {
4635                 int for_mds;
4636
4637                 for_mds = lustre_fs ?
4638                         (S_ISREG(st->st_mode) && stripe_count) : 0;
4639                 decision = find_time_check(st, param, for_mds);
4640                 if (decision == -1)
4641                         goto decided;
4642         }
4643
4644         /* If file still fits the request, ask ost for updated info.
4645            The regular stat is almost of the same speed as some new
4646            'glimpse-size-ioctl'. */
4647
4648         if ((param->fp_check_size || param->fp_check_blocks) &&
4649             ((S_ISREG(st->st_mode) && stripe_count) || S_ISDIR(st->st_mode)))
4650                 decision = 0;
4651
4652         if (!decision) {
4653                 /* For regular files with the stripe the decision may have not
4654                  * been taken yet if *time or size is to be checked. */
4655                 if (param->fp_obd_index != OBD_NOT_FOUND)
4656                         print_failed_tgt(param, path, LL_STATFS_LOV);
4657
4658                 if (param->fp_mdt_index != OBD_NOT_FOUND)
4659                         print_failed_tgt(param, path, LL_STATFS_LMV);
4660
4661                 if (dir != NULL)
4662                         ret = fstat_f(dirfd(dir), st);
4663                 else if (de != NULL)
4664                         ret = fstatat_f(dirfd(parent), de->d_name, st,
4665                                         AT_SYMLINK_NOFOLLOW);
4666                 else
4667                         ret = lstat_f(path, st);
4668
4669                 if (ret) {
4670                         if (errno == ENOENT) {
4671                                 llapi_error(LLAPI_MSG_ERROR, -ENOENT,
4672                                             "warning: %s: %s does not exist",
4673                                             __func__, path);
4674                                 goto decided;
4675                         } else {
4676                                 ret = -errno;
4677                                 llapi_error(LLAPI_MSG_ERROR, ret,
4678                                             "%s: IOC_LOV_GETINFO on %s failed",
4679                                             __func__, path);
4680                                 goto out;
4681                         }
4682                 }
4683
4684                 /* Check the time on osc. */
4685                 decision = find_time_check(st, param, 0);
4686                 if (decision == -1)
4687                         goto decided;
4688         }
4689
4690         if (param->fp_check_size) {
4691                 decision = find_value_cmp(st->st_size, param->fp_size,
4692                                           param->fp_size_sign,
4693                                           param->fp_exclude_size,
4694                                           param->fp_size_units, 0);
4695                 if (decision == -1)
4696                         goto decided;
4697         }
4698
4699         if (param->fp_check_blocks) { /* convert st_blocks to bytes */
4700                 decision = find_value_cmp(st->st_blocks * 512, param->fp_blocks,
4701                                           param->fp_blocks_sign,
4702                                           param->fp_exclude_blocks,
4703                                           param->fp_blocks_units, 0);
4704                 if (decision == -1)
4705                         goto decided;
4706         }
4707
4708 foreign:
4709         llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
4710         if (param->fp_zero_end)
4711                 llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
4712         else
4713                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
4714
4715 decided:
4716         ret = 0;
4717         /* Do not get down anymore? */
4718         if (param->fp_depth == param->fp_max_depth) {
4719                 ret = 1;
4720                 goto out;
4721         }
4722         param->fp_depth++;
4723 out:
4724         if (fd > 0)
4725                 close(fd);
4726         return ret;
4727 }
4728
4729 static int cb_migrate_mdt_init(char *path, DIR *parent, DIR **dirp,
4730                                void *param_data, struct dirent64 *de)
4731 {
4732         struct find_param *param = (struct find_param *)param_data;
4733         struct lmv_user_md *lmu = param->fp_lmv_md;
4734         DIR *tmp_parent = parent;
4735         char raw[MAX_IOC_BUFLEN] = {'\0'};
4736         char *rawbuf = raw;
4737         struct obd_ioctl_data data = { 0 };
4738         int fd;
4739         int ret;
4740         char *path_copy;
4741         char *filename;
4742         bool retry = false;
4743
4744         if (parent == NULL && dirp == NULL)
4745                 return -EINVAL;
4746
4747         if (!lmu)
4748                 return -EINVAL;
4749
4750         if (dirp != NULL)
4751                 closedir(*dirp);
4752
4753         if (parent == NULL) {
4754                 tmp_parent = opendir_parent(path);
4755                 if (tmp_parent == NULL) {
4756                         *dirp = NULL;
4757                         ret = -errno;
4758                         llapi_error(LLAPI_MSG_ERROR, ret,
4759                                     "can not open %s", path);
4760                         return ret;
4761                 }
4762         }
4763
4764         fd = dirfd(tmp_parent);
4765
4766         path_copy = strdup(path);
4767         filename = basename(path_copy);
4768
4769         data.ioc_inlbuf1 = (char *)filename;
4770         data.ioc_inllen1 = strlen(filename) + 1;
4771         data.ioc_inlbuf2 = (char *)lmu;
4772         data.ioc_inllen2 = lmv_user_md_size(lmu->lum_stripe_count,
4773                                             lmu->lum_magic);
4774         ret = llapi_ioctl_pack(&data, &rawbuf, sizeof(raw));
4775         if (ret != 0) {
4776                 llapi_error(LLAPI_MSG_ERROR, ret,
4777                             "llapi_obd_statfs: error packing ioctl data");
4778                 goto out;
4779         }
4780
4781 migrate:
4782         ret = ioctl(fd, LL_IOC_MIGRATE, rawbuf);
4783         if (ret != 0) {
4784                 if (errno == EBUSY && !retry) {
4785                         /* because migrate may not be able to lock all involved
4786                          * objects in order, for some of them it try lock, while
4787                          * there may be conflicting COS locks and cause migrate
4788                          * fail with EBUSY, hope a sync() could cause
4789                          * transaction commit and release these COS locks. */
4790                         sync();
4791                         retry = true;
4792                         goto migrate;
4793                 } else if (errno == EALREADY) {
4794                         if (param->fp_verbose & VERBOSE_DETAIL)
4795                                 llapi_printf(LLAPI_MSG_NORMAL,
4796                                              "%s was migrated to MDT%d already\n",
4797                                              path, lmu->lum_stripe_offset);
4798                         ret = 0;
4799                 } else {
4800                         ret = -errno;
4801                         llapi_error(LLAPI_MSG_ERROR, ret,
4802                                     "%s migrate failed: %s (%d)\n",
4803                                     path, strerror(-ret), ret);
4804                         goto out;
4805                 }
4806         } else if (param->fp_verbose & VERBOSE_DETAIL) {
4807                 llapi_printf(LLAPI_MSG_NORMAL,
4808                              "migrate %s to MDT%d stripe count %d\n",
4809                              path, lmu->lum_stripe_offset,
4810                              lmu->lum_stripe_count);
4811         }
4812
4813 out:
4814         if (dirp != NULL) {
4815                 /* If the directory is being migration, we need
4816                  * close the directory after migration,
4817                  * so the old directory cache will be cleanup
4818                  * on the client side, and re-open to get the
4819                  * new directory handle */
4820                 *dirp = opendir(path);
4821                 if (*dirp == NULL) {
4822                         ret = -errno;
4823                         llapi_error(LLAPI_MSG_ERROR, ret,
4824                                     "%s: Failed to open '%s'", __func__, path);
4825                 }
4826         }
4827
4828         if (parent == NULL)
4829                 closedir(tmp_parent);
4830
4831         free(path_copy);
4832
4833         return ret;
4834 }
4835
4836 /* dir migration finished, shrink its stripes */
4837 static int cb_migrate_mdt_fini(char *path, DIR *parent, DIR **dirp, void *data,
4838                                struct dirent64 *de)
4839 {
4840         struct find_param *param = data;
4841         struct lmv_user_md *lmu = param->fp_lmv_md;
4842         int lmulen = lmv_user_md_size(lmu->lum_stripe_count, lmu->lum_magic);
4843         int ret = 0;
4844
4845         if (de && de->d_type != DT_DIR)
4846                 goto out;
4847
4848         if (*dirp) {
4849                 /*
4850                  * close it before setxattr because the latter may destroy the
4851                  * original object, and cause close fail.
4852                  */
4853                 ret = closedir(*dirp);
4854                 *dirp = NULL;
4855                 if (ret)
4856                         goto out;
4857         }
4858
4859         ret = setxattr(path, XATTR_NAME_LMV, lmu, lmulen, 0);
4860         if (ret == -EALREADY)
4861                 ret = 0;
4862 out:
4863         cb_common_fini(path, parent, dirp, data, de);
4864         return ret;
4865 }
4866
4867 int llapi_migrate_mdt(char *path, struct find_param *param)
4868 {
4869         return param_callback(path, cb_migrate_mdt_init, cb_migrate_mdt_fini,
4870                               param);
4871 }
4872
4873 int llapi_mv(char *path, struct find_param *param)
4874 {
4875 #if LUSTRE_VERSION_CODE > OBD_OCD_VERSION(2, 9, 59, 0)
4876         static bool printed;
4877
4878         if (!printed) {
4879                 llapi_error(LLAPI_MSG_ERROR, -ESTALE,
4880                             "llapi_mv() is deprecated, use llapi_migrate_mdt()\n");
4881                 printed = true;
4882         }
4883 #endif
4884         return llapi_migrate_mdt(path, param);
4885 }
4886
4887 int llapi_find(char *path, struct find_param *param)
4888 {
4889         return param_callback(path, cb_find_init, cb_common_fini, param);
4890 }
4891
4892 /*
4893  * Get MDT number that the file/directory inode referenced
4894  * by the open fd resides on.
4895  * Return 0 and mdtidx on success, or -ve errno.
4896  */
4897 int llapi_file_fget_mdtidx(int fd, int *mdtidx)
4898 {
4899         if (ioctl(fd, LL_IOC_GET_MDTIDX, mdtidx) < 0)
4900                 return -errno;
4901         return 0;
4902 }
4903
4904 static int cb_get_mdt_index(char *path, DIR *parent, DIR **dirp, void *data,
4905                             struct dirent64 *de)
4906 {
4907         struct find_param *param = (struct find_param *)data;
4908         DIR *d = dirp == NULL ? NULL : *dirp;
4909         int ret;
4910         int mdtidx;
4911
4912         if (parent == NULL && d == NULL)
4913                 return -EINVAL;
4914
4915         if (d != NULL) {
4916                 ret = llapi_file_fget_mdtidx(dirfd(d), &mdtidx);
4917         } else /* if (parent) */ {
4918                 int fd;
4919
4920                 fd = open(path, O_RDONLY | O_NOCTTY);
4921                 if (fd > 0) {
4922                         ret = llapi_file_fget_mdtidx(fd, &mdtidx);
4923                         close(fd);
4924                 } else {
4925                         ret = -errno;
4926                 }
4927         }
4928
4929         if (ret != 0) {
4930                 if (ret == -ENODATA) {
4931                         if (!param->fp_obd_uuid)
4932                                 llapi_printf(LLAPI_MSG_NORMAL,
4933                                              "'%s' has no stripe info\n", path);
4934                         goto out;
4935                 } else if (ret == -ENOENT) {
4936                         llapi_error(LLAPI_MSG_WARN, ret,
4937                                     "warning: %s: '%s' does not exist",
4938                                     __func__, path);
4939                         goto out;
4940                 } else if (ret == -ENOTTY) {
4941                         llapi_error(LLAPI_MSG_ERROR, ret,
4942                                     "%s: '%s' not on a Lustre fs",
4943                                     __func__, path);
4944                 } else {
4945                         llapi_error(LLAPI_MSG_ERROR, ret,
4946                                     "error: %s: '%s' failed get_mdtidx",
4947                                     __func__, path);
4948                 }
4949                 return ret;
4950         }
4951
4952         if (param->fp_quiet || !(param->fp_verbose & VERBOSE_DETAIL))
4953                 llapi_printf(LLAPI_MSG_NORMAL, "%d\n", mdtidx);
4954         else
4955                 llapi_printf(LLAPI_MSG_NORMAL, "%s\nmdt_index:\t%d\n",
4956                              path, mdtidx);
4957
4958 out:
4959         /* Do not go down anymore? */
4960         if (param->fp_depth == param->fp_max_depth)
4961                 return 1;
4962
4963         param->fp_depth++;
4964
4965         return 0;
4966 }
4967
4968 static int cb_getstripe(char *path, DIR *parent, DIR **dirp, void *data,
4969                         struct dirent64 *de)
4970 {
4971         struct find_param *param = (struct find_param *)data;
4972         DIR *d = dirp == NULL ? NULL : *dirp;
4973         int ret = 0;
4974
4975         if (parent == NULL && d == NULL)
4976                 return -EINVAL;
4977
4978         if (param->fp_obd_uuid) {
4979                 param->fp_quiet = 1;
4980                 ret = setup_obd_uuid(d ? dirfd(d) : dirfd(parent), path, param);
4981                 if (ret)
4982                         return ret;
4983         }
4984
4985         if (d && (param->fp_get_lmv || param->fp_get_default_lmv))
4986                 ret = cb_get_dirstripe(path, d, param);
4987         else if (d ||
4988                  (parent && !param->fp_get_lmv && !param->fp_get_default_lmv))
4989                 ret = get_lmd_info(path, parent, d, &param->fp_lmd->lmd_lmm,
4990                                    param->fp_lum_size, GET_LMD_STRIPE);
4991         else
4992                 return 0;
4993
4994         if (ret) {
4995                 if (errno == ENODATA && d != NULL) {
4996                         /* We need to "fake" the "use the default" values
4997                          * since the lmm struct is zeroed out at this point.
4998                          * The magic needs to be set in order to satisfy
4999                          * a check later on in the code path.
5000                          * The object_seq needs to be set for the "(Default)"
5001                          * prefix to be displayed. */
5002                         if (param->fp_get_default_lmv) {
5003                                 struct lmv_user_md *lum = param->fp_lmv_md;
5004
5005                                 lum->lum_magic = LMV_USER_MAGIC;
5006                                 lum->lum_stripe_count = 0;
5007                                 lum->lum_stripe_offset = -1;
5008                                 goto dump;
5009                         } else if (param->fp_get_lmv) {
5010                                 struct lmv_user_md *lum = param->fp_lmv_md;
5011                                 int mdtidx;
5012
5013                                 ret = llapi_file_fget_mdtidx(dirfd(d), &mdtidx);
5014                                 if (ret != 0)
5015                                         goto err_out;
5016                                 lum->lum_magic = LMV_MAGIC_V1;
5017                                 lum->lum_stripe_count = 0;
5018                                 lum->lum_stripe_offset = mdtidx;
5019                                 goto dump;
5020                         } else {
5021                                 struct lov_user_md *lmm =
5022                                         &param->fp_lmd->lmd_lmm;
5023
5024                                 lmm->lmm_magic = LOV_USER_MAGIC_V1;
5025                                 if (!param->fp_raw)
5026                                         ostid_set_seq(&lmm->lmm_oi,
5027                                                       FID_SEQ_LOV_DEFAULT);
5028                                 lmm->lmm_stripe_count = 0;
5029                                 lmm->lmm_stripe_size = 0;
5030                                 lmm->lmm_stripe_offset = -1;
5031                                 goto dump;
5032                         }
5033                 } else if (errno == ENODATA && parent != NULL) {
5034                         if (!param->fp_obd_uuid && !param->fp_mdt_uuid)
5035                                 llapi_printf(LLAPI_MSG_NORMAL,
5036                                              "%s has no stripe info\n", path);
5037                         goto out;
5038                 } else if (errno == ENOENT) {
5039                         llapi_error(LLAPI_MSG_WARN, -ENOENT,
5040                                     "warning: %s: %s does not exist",
5041                                     __func__, path);
5042                         goto out;
5043                 } else if (errno == ENOTTY) {
5044                         ret = -errno;
5045                         llapi_error(LLAPI_MSG_ERROR, ret,
5046                                     "%s: '%s' not on a Lustre fs?",
5047                                     __func__, path);
5048                 } else {
5049                         ret = -errno;
5050 err_out:
5051                         llapi_error(LLAPI_MSG_ERROR, ret,
5052                                     "error: %s: %s failed for %s",
5053                                      __func__, d ? "LL_IOC_LOV_GETSTRIPE" :
5054                                     "IOC_MDC_GETFILESTRIPE", path);
5055                 }
5056
5057                 return ret;
5058         }
5059
5060 dump:
5061         if (!(param->fp_verbose & VERBOSE_MDTINDEX))
5062                 llapi_lov_dump_user_lmm(param, path, d ? LDF_IS_DIR : 0);
5063
5064 out:
5065         /* Do not get down anymore? */
5066         if (param->fp_depth == param->fp_max_depth)
5067                 return 1;
5068
5069         param->fp_depth++;
5070
5071         return 0;
5072 }
5073
5074 int llapi_getstripe(char *path, struct find_param *param)
5075 {
5076         return param_callback(path, (param->fp_verbose & VERBOSE_MDTINDEX) ?
5077                               cb_get_mdt_index : cb_getstripe,
5078                               cb_common_fini, param);
5079 }
5080
5081 int llapi_obd_fstatfs(int fd, __u32 type, __u32 index,
5082                       struct obd_statfs *stat_buf, struct obd_uuid *uuid_buf)
5083 {
5084         char raw[MAX_IOC_BUFLEN] = {'\0'};
5085         char *rawbuf = raw;
5086         struct obd_ioctl_data data = { 0 };
5087         int rc = 0;
5088
5089         data.ioc_inlbuf1 = (char *)&type;
5090         data.ioc_inllen1 = sizeof(__u32);
5091         data.ioc_inlbuf2 = (char *)&index;
5092         data.ioc_inllen2 = sizeof(__u32);
5093         data.ioc_pbuf1 = (char *)stat_buf;
5094         data.ioc_plen1 = sizeof(struct obd_statfs);
5095         data.ioc_pbuf2 = (char *)uuid_buf;
5096         data.ioc_plen2 = sizeof(struct obd_uuid);
5097
5098         rc = llapi_ioctl_pack(&data, &rawbuf, sizeof(raw));
5099         if (rc != 0) {
5100                 llapi_error(LLAPI_MSG_ERROR, rc,
5101                             "llapi_obd_statfs: error packing ioctl data");
5102                 return rc;
5103         }
5104
5105         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
5106
5107         return rc < 0 ? -errno : 0;
5108 }
5109
5110 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
5111                      struct obd_statfs *stat_buf, struct obd_uuid *uuid_buf)
5112 {
5113         int fd;
5114         int rc;
5115
5116         fd = open(path, O_RDONLY);
5117         if (fd < 0) {
5118                 rc = -errno;
5119                 llapi_error(LLAPI_MSG_ERROR, rc, "error: %s: opening '%s'",
5120                             __func__, path);
5121                 /* If we can't even open a file on the filesystem (e.g. with
5122                  * -ESHUTDOWN), force caller to exit or it will loop forever. */
5123                 return -ENODEV;
5124         }
5125
5126         rc = llapi_obd_fstatfs(fd, type, index, stat_buf, uuid_buf);
5127
5128         close(fd);
5129
5130         return rc;
5131 }
5132
5133 #define MAX_STRING_SIZE 128
5134
5135 int llapi_ping(char *obd_type, char *obd_name)
5136 {
5137         int flags = O_RDONLY;
5138         char buf[1] = { 0 };
5139         glob_t path;
5140         int rc, fd;
5141
5142         rc = cfs_get_param_paths(&path, "%s/%s/ping",
5143                                 obd_type, obd_name);
5144         if (rc != 0)
5145                 return -errno;
5146 retry_open:
5147         fd = open(path.gl_pathv[0], flags);
5148         if (fd < 0) {
5149                 if (errno == EACCES && flags == O_RDONLY) {
5150                         flags = O_WRONLY;
5151                         goto retry_open;
5152                 }
5153                 rc = -errno;
5154                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s",
5155                             path.gl_pathv[0]);
5156                 goto failed;
5157         }
5158
5159         if (flags == O_RDONLY)
5160                 rc = read(fd, buf, sizeof(buf));
5161         else
5162                 rc = write(fd, buf, sizeof(buf));
5163         if (rc < 0)
5164                 rc = -errno;
5165         close(fd);
5166
5167         if (rc == 1)
5168                 rc = 0;
5169 failed:
5170         cfs_free_param_data(&path);
5171         return rc;
5172 }
5173
5174 int llapi_target_iterate(int type_num, char **obd_type,
5175                          void *args, llapi_cb_t cb)
5176 {
5177         int i, rc = 0;
5178         glob_t param;
5179         FILE *fp;
5180
5181         for (i = 0; i < type_num; i++) {
5182                 int j;
5183
5184                 rc = cfs_get_param_paths(&param, "%s/*/uuid", obd_type[i]);
5185                 if (rc != 0)
5186                         continue;
5187
5188                 for (j = 0; j < param.gl_pathc; j++) {
5189                         char obd_uuid[UUID_MAX + 1];
5190                         char *obd_name;
5191                         char *ptr;
5192
5193                         fp = fopen(param.gl_pathv[j], "r");
5194                         if (fp == NULL) {
5195                                 rc = -errno;
5196                                 llapi_error(LLAPI_MSG_ERROR, rc,
5197                                             "error: opening '%s'",
5198                                             param.gl_pathv[j]);
5199                                 goto free_path;
5200                         }
5201
5202                         if (fgets(obd_uuid, sizeof(obd_uuid), fp) == NULL) {
5203                                 rc = -errno;
5204                                 llapi_error(LLAPI_MSG_ERROR, rc,
5205                                             "error: reading '%s'",
5206                                             param.gl_pathv[j]);
5207                                 goto free_path;
5208                         }
5209
5210                         /* Extract the obd_name from the sysfs path.
5211                          * 'topsysfs'/fs/lustre/'obd_type'/'obd_name'.
5212                          */
5213                         obd_name = strstr(param.gl_pathv[j], "/fs/lustre/");
5214                         if (!obd_name) {
5215                                 rc = -EINVAL;
5216                                 goto free_path;
5217                         }
5218
5219                         /* skip /fs/lustre/'obd_type'/ */
5220                         obd_name += strlen(obd_type[i]) + 12;
5221                         /* chop off after obd_name */
5222                         ptr = strrchr(obd_name, '/');
5223                         if (ptr)
5224                                 *ptr = '\0';
5225
5226                         cb(obd_type[i], obd_name, obd_uuid, args);
5227
5228                         fclose(fp);
5229                         fp = NULL;
5230                 }
5231         }
5232 free_path:
5233         if (fp)
5234                 fclose(fp);
5235         cfs_free_param_data(&param);
5236         return rc;
5237 }
5238
5239 static void do_target_check(char *obd_type_name, char *obd_name,
5240                             char *obd_uuid, void *args)
5241 {
5242         int rc;
5243
5244         rc = llapi_ping(obd_type_name, obd_name);
5245         if (rc == ENOTCONN) {
5246                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
5247         } else if (rc) {
5248                 llapi_error(LLAPI_MSG_ERROR, rc, "error: check '%s'", obd_name);
5249         } else {
5250                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
5251         }
5252 }
5253
5254 int llapi_target_check(int type_num, char **obd_type, char *dir)
5255 {
5256         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
5257 }
5258
5259 #undef MAX_STRING_SIZE
5260
5261 /* Is this a lustre fs? */
5262 int llapi_is_lustre_mnttype(const char *type)
5263 {
5264         return (strcmp(type, "lustre") == 0 || strcmp(type,"lustre_lite") == 0);
5265 }
5266
5267 /* Is this a lustre client fs? */
5268 int llapi_is_lustre_mnt(struct mntent *mnt)
5269 {
5270         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
5271                 strstr(mnt->mnt_fsname, ":/") != NULL);
5272 }
5273
5274 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
5275 {
5276         char fsname[PATH_MAX + 1];
5277         int root;
5278         int rc;
5279
5280         rc = llapi_search_fsname(mnt, fsname);
5281         if (rc)
5282                 return rc;
5283
5284         root = open(mnt, O_RDONLY | O_DIRECTORY);
5285         if (root < 0) {
5286                 rc = -errno;
5287                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot open '%s'", mnt);
5288                 return rc;
5289         }
5290
5291         rc = ioctl(root, OBD_IOC_QUOTACTL, qctl);
5292         if (rc < 0)
5293                 rc = -errno;
5294
5295         close(root);
5296         return rc;
5297 }
5298
5299 /* Print mdtname 'name' into 'buf' using 'format'.  Add -MDT0000 if needed.
5300  * format must have %s%s, buf must be > 16
5301  * Eg: if name = "lustre-MDT0000", "lustre", or "lustre-MDT0000_UUID"
5302  *     then buf = "lustre-MDT0000"
5303  */
5304 static int get_mdtname(char *name, char *format, char *buf)
5305 {
5306         char suffix[]="-MDT0000";
5307         int len = strlen(name);
5308
5309         if ((len > 5) && (strncmp(name + len - 5, "_UUID", 5) == 0)) {
5310                 name[len - 5] = '\0';
5311                 len -= 5;
5312         }
5313
5314         if (len > 8) {
5315                 if ((len <= 16) && strncmp(name + len - 8, "-MDT", 4) == 0) {
5316                         suffix[0] = '\0';
5317                 } else {
5318                         /* Not enough room to add suffix */
5319                         llapi_err_noerrno(LLAPI_MSG_ERROR,
5320                                           "Invalid MDT name |%s|", name);
5321                         return -EINVAL;
5322                 }
5323         }
5324
5325         return sprintf(buf, format, name, suffix);
5326 }
5327
5328 /** ioctl on filsystem root, with mdtindex sent as data
5329  * \param mdtname path, fsname, or mdtname (lutre-MDT0004)
5330  * \param mdtidxp pointer to integer within data to be filled in with the
5331  *    mdt index (0 if no mdt is specified).  NULL won't be filled.
5332  */
5333 int root_ioctl(const char *mdtname, int opc, void *data, int *mdtidxp,
5334                int want_error)
5335 {
5336         char fsname[20];
5337         char *ptr;
5338         int fd, rc;
5339         long index;
5340
5341         /* Take path, fsname, or MDTname.  Assume MDT0000 in the former cases.
5342          Open root and parse mdt index. */
5343         if (mdtname[0] == '/') {
5344                 index = 0;
5345                 rc = get_root_path(WANT_FD | want_error, NULL, &fd,
5346                                    (char *)mdtname, -1);
5347         } else {
5348                 if (get_mdtname((char *)mdtname, "%s%s", fsname) < 0)
5349                         return -EINVAL;
5350                 ptr = fsname + strlen(fsname) - 8;
5351                 *ptr = '\0';
5352                 index = strtol(ptr + 4, NULL, 16);
5353                 rc = get_root_path(WANT_FD | want_error, fsname, &fd, NULL, -1);
5354         }
5355         if (rc < 0) {
5356                 if (want_error)
5357                         llapi_err_noerrno(LLAPI_MSG_ERROR,
5358                                           "Can't open %s: %d\n", mdtname, rc);
5359                 return rc;
5360         }
5361
5362         if (mdtidxp)
5363                 *mdtidxp = index;
5364
5365         rc = ioctl(fd, opc, data);
5366         if (rc == -1)
5367                 rc = -errno;
5368         else
5369                 rc = 0;
5370         close(fd);
5371         return rc;
5372 }
5373
5374 int llapi_fid2path(const char *device, const char *fidstr, char *buf,
5375                    int buflen, long long *recno, int *linkno)
5376 {
5377         const char *fidstr_orig = fidstr;
5378         struct lu_fid fid;
5379         struct getinfo_fid2path *gf;
5380         char *a;
5381         char *b;
5382         int rc;
5383
5384         while (*fidstr == '[')
5385                 fidstr++;
5386
5387         sscanf(fidstr, SFID, RFID(&fid));
5388         if (!fid_is_sane(&fid)) {
5389                 llapi_err_noerrno(LLAPI_MSG_ERROR,
5390                                   "bad FID format '%s', should be [seq:oid:ver]"
5391                                   " (e.g. "DFID")\n", fidstr_orig,
5392                                   (unsigned long long)FID_SEQ_NORMAL, 2, 0);
5393                 return -EINVAL;
5394         }
5395
5396         gf = malloc(sizeof(*gf) + buflen);
5397         if (gf == NULL)
5398                 return -ENOMEM;
5399
5400         gf->gf_fid = fid;
5401         gf->gf_recno = *recno;
5402         gf->gf_linkno = *linkno;
5403         gf->gf_pathlen = buflen;
5404
5405         /* Take path or fsname */
5406         rc = root_ioctl(device, OBD_IOC_FID2PATH, gf, NULL, 0);
5407         if (rc)
5408                 goto out_free;
5409
5410         b = buf;
5411         /* strip out instances of // */
5412         for (a = gf->gf_u.gf_path; *a != '\0'; a++) {
5413                 if ((*a == '/') && (*(a + 1) == '/'))
5414                         continue;
5415                 *b = *a;
5416                 b++;
5417         }
5418         *b = '\0';
5419
5420         if (buf[0] == '\0') { /* ROOT path */
5421                 buf[0] = '/';
5422                 buf[1] = '\0';
5423         }
5424
5425         *recno = gf->gf_recno;
5426         *linkno = gf->gf_linkno;
5427
5428 out_free:
5429         free(gf);
5430         return rc;
5431 }
5432
5433 static int fid_from_lma(const char *path, int fd, struct lu_fid *fid)
5434 {
5435         char                     buf[512];
5436         struct lustre_mdt_attrs *lma;
5437         int                      rc;
5438
5439         if (path == NULL)
5440                 rc = fgetxattr(fd, XATTR_NAME_LMA, buf, sizeof(buf));
5441         else
5442                 rc = lgetxattr(path, XATTR_NAME_LMA, buf, sizeof(buf));
5443         if (rc < 0)
5444                 return -errno;
5445         lma = (struct lustre_mdt_attrs *)buf;
5446         fid_le_to_cpu(fid, &lma->lma_self_fid);
5447         return 0;
5448 }
5449
5450 int llapi_get_mdt_index_by_fid(int fd, const struct lu_fid *fid,
5451                                int *mdt_index)
5452 {
5453         int     rc;
5454
5455         rc = ioctl(fd, LL_IOC_FID2MDTIDX, fid);
5456         if (rc < 0)
5457                 return -errno;
5458
5459         *mdt_index = rc;
5460
5461         return rc;
5462 }
5463
5464 int llapi_fd2fid(int fd, struct lu_fid *fid)
5465 {
5466         int rc;
5467
5468         memset(fid, 0, sizeof(*fid));
5469
5470         rc = ioctl(fd, LL_IOC_PATH2FID, fid) < 0 ? -errno : 0;
5471         if (rc == -EINVAL || rc == -ENOTTY)
5472                 rc = fid_from_lma(NULL, fd, fid);
5473
5474         return rc;
5475 }
5476
5477 int llapi_path2fid(const char *path, struct lu_fid *fid)
5478 {
5479         int fd, rc;
5480
5481         memset(fid, 0, sizeof(*fid));
5482         fd = open(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
5483         if (fd < 0) {
5484                 if (errno == ELOOP || errno == ENXIO)
5485                         return fid_from_lma(path, -1, fid);
5486                 return -errno;
5487         }
5488
5489         rc = llapi_fd2fid(fd, fid);
5490         if (rc == -EINVAL || rc == -ENOTTY)
5491                 rc = fid_from_lma(path, -1, fid);
5492
5493         close(fd);
5494         return rc;
5495 }
5496
5497 int llapi_fd2parent(int fd, unsigned int linkno, struct lu_fid *parent_fid,
5498                     char *name, size_t name_size)
5499 {
5500         struct getparent        *gp;
5501         int                      rc;
5502
5503         gp = malloc(sizeof(*gp) + name_size);
5504         if (gp == NULL)
5505                 return -ENOMEM;
5506
5507         gp->gp_linkno = linkno;
5508         gp->gp_name_size = name_size;
5509
5510         rc = ioctl(fd, LL_IOC_GETPARENT, gp);
5511         if (rc < 0) {
5512                 rc = -errno;
5513                 goto err_free;
5514         }
5515
5516         *parent_fid = gp->gp_fid;
5517
5518         strncpy(name, gp->gp_name, name_size);
5519         name[name_size - 1] = '\0';
5520
5521 err_free:
5522         free(gp);
5523         return rc;
5524 }
5525
5526 int llapi_path2parent(const char *path, unsigned int linkno,
5527                       struct lu_fid *parent_fid, char *name, size_t name_size)
5528 {
5529         int     fd;
5530         int     rc;
5531
5532         fd = open(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
5533         if (fd < 0)
5534                 return -errno;
5535
5536         rc = llapi_fd2parent(fd, linkno, parent_fid, name, name_size);
5537         close(fd);
5538         return rc;
5539 }
5540
5541 int llapi_get_connect_flags(const char *mnt, __u64 *flags)
5542 {
5543         int root;
5544         int rc;
5545
5546         root = open(mnt, O_RDONLY | O_DIRECTORY);
5547         if (root < 0) {
5548                 rc = -errno;
5549                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
5550                 return rc;
5551         }
5552
5553         rc = ioctl(root, LL_IOC_GET_CONNECT_FLAGS, flags);
5554         if (rc < 0) {
5555                 rc = -errno;
5556                 llapi_error(LLAPI_MSG_ERROR, rc,
5557                         "ioctl on %s for getting connect flags failed", mnt);
5558         }
5559         close(root);
5560         return rc;
5561 }
5562
5563 /**
5564  * Get a 64-bit value representing the version of file data pointed by fd.
5565  *
5566  * Each write or truncate, flushed on OST, will change this value. You can use
5567  * this value to verify if file data was modified. This only checks the file
5568  * data, not metadata.
5569  *
5570  * \param  flags  0: no flush pages, usually used it the process has already
5571  *                  taken locks;
5572  *                LL_DV_RD_FLUSH: OSTs will take LCK_PR to flush dirty pages
5573  *                  from clients;
5574  *                LL_DV_WR_FLUSH: OSTs will take LCK_PW to flush all caching
5575  *                  pages from clients.
5576  *
5577  * \retval 0 on success.
5578  * \retval -errno on error.
5579  */
5580 int llapi_get_data_version(int fd, __u64 *data_version, __u64 flags)
5581 {
5582         int rc;
5583         struct ioc_data_version idv;
5584
5585         idv.idv_flags = (__u32)flags;
5586
5587         rc = ioctl(fd, LL_IOC_DATA_VERSION, &idv);
5588         if (rc)
5589                 rc = -errno;
5590         else
5591                 *data_version = idv.idv_version;
5592
5593         return rc;
5594 }
5595
5596 /**
5597  * Flush cached pages from all clients.
5598  *
5599  * \param fd    File descriptor
5600  * \retval 0    success
5601  * \retval < 0  error
5602  */
5603 int llapi_file_flush(int fd)
5604 {
5605         __u64 dv;
5606
5607         return llapi_get_data_version(fd, &dv, LL_DV_WR_FLUSH);
5608 }
5609
5610 /*
5611  * Fetch layout version from OST objects. Layout version on OST objects are
5612  * only set when the file is a mirrored file AND after the file has been
5613  * written at least once.
5614  *
5615  * It actually fetches the least layout version from the objects.
5616  */
5617 int llapi_get_ost_layout_version(int fd, __u32 *layout_version)
5618 {
5619         int rc;
5620         struct ioc_data_version idv = { 0 };
5621
5622         rc = ioctl(fd, LL_IOC_DATA_VERSION, &idv);
5623         if (rc)
5624                 rc = -errno;
5625         else
5626                 *layout_version = idv.idv_layout_version;
5627
5628         return rc;
5629 }
5630
5631 /*
5632  * Create a file without any name and open it for read/write
5633  *
5634  * - file is created as if it were a standard file in the given \a directory
5635  * - file does not appear in \a directory and mtime does not change because
5636  *   the filename is handled specially by the Lustre MDS.
5637  * - file is destroyed at final close
5638  *
5639  * \param[in]   directory       directory from which to inherit layout/MDT idx
5640  * \param[in]   mdt_idx         MDT index on which the file is created,
5641  *                              \a idx == -1 means no specific MDT is requested
5642  * \param[in]   mode            standard open(2) mode
5643  * \param[in]   stripe_param    stripe parameters. May be NULL.
5644  *
5645  * \retval      a file descriptor on success.
5646  * \retval      -errno on error.
5647  */
5648 int llapi_create_volatile_param(const char *directory, int mdt_idx,
5649                                 int open_flags, mode_t mode,
5650                                 const struct llapi_stripe_param *stripe_param)
5651 {
5652         char file_path[PATH_MAX];
5653         int saved_errno = errno;
5654         int fd;
5655         unsigned int rnumber;
5656         int rc;
5657
5658         do {
5659                 rnumber = random();
5660                 if (mdt_idx == -1)
5661                         rc = snprintf(file_path, sizeof(file_path),
5662                                       "%s/" LUSTRE_VOLATILE_HDR "::%.4X",
5663                                       directory, rnumber);
5664                 else
5665                         rc = snprintf(file_path, sizeof(file_path),
5666                                       "%s/" LUSTRE_VOLATILE_HDR ":%.4X:%.4X",
5667                                       directory, mdt_idx, rnumber);
5668
5669                 if (rc < 0 || rc >= sizeof(file_path))
5670                         return -ENAMETOOLONG;
5671
5672                 /*
5673                  * Either open O_WRONLY or O_RDWR, creating RDONLY
5674                  * is non-sensical here
5675                  */
5676                 if ((open_flags & O_ACCMODE) == O_RDONLY)
5677                         open_flags = O_RDWR | (open_flags & ~O_ACCMODE);
5678
5679                 open_flags |= O_CREAT | O_EXCL | O_NOFOLLOW;
5680
5681                 if (stripe_param != NULL) {
5682                         fd = llapi_file_open_param(file_path, open_flags,
5683                                                    mode, stripe_param);
5684                         if (fd < 0)
5685                                 rc = fd;
5686                 } else {
5687                         fd = open(file_path, open_flags, mode);
5688                         if (fd < 0)
5689                                 rc = -errno;
5690                 }
5691         } while (fd < 0 && rc == -EEXIST);
5692
5693         if (fd < 0) {
5694                 llapi_error(LLAPI_MSG_ERROR, rc,
5695                             "Cannot create volatile file '%s' in '%s'",
5696                             file_path + strlen(directory) + 1 +
5697                             LUSTRE_VOLATILE_HDR_LEN,
5698                             directory);
5699                 return rc;
5700         }
5701
5702         /*
5703          * Unlink file in case this wasn't a Lustre filesystem and the magic
5704          * volatile filename wasn't handled as intended. The effect is the
5705          * same. If volatile open was supported then we expect unlink() to
5706          * return -ENOENT.
5707          */
5708         (void)unlink(file_path);
5709
5710         /*
5711          * Since we are returning successfully we restore errno (and
5712          * mask out possible EEXIST from open() and ENOENT from unlink().
5713          */
5714         errno = saved_errno;
5715
5716         return fd;
5717 }
5718
5719 /*
5720  * Create a file without any name open it for read/write
5721  *
5722  * - file is created as if it were a standard file in the given \a directory
5723  * - file does not appear in \a directory and mtime does not change because
5724  *   the filename is handled specially by the Lustre MDS.
5725  * - file is removed at final close
5726  * - file modes are rw------- since it doesn't make sense to have a read-only
5727  *   or write-only file that cannot be opened again.
5728  * - if user wants another mode it must use fchmod() on the open file, no
5729  *   security problems arise because it cannot be opened by another process.
5730  *
5731  * \param[in]   directory       directory from which to inherit layout/MDT idx
5732  * \param[in]   idx             MDT index on which the file is created,
5733  *                              \a idx == -1 means no specific MDT is requested
5734  * \param[in]   open_flags      standard open(2) flags
5735  *
5736  * \retval      a file descriptor on success.
5737  * \retval      -errno on error.
5738  */
5739 int llapi_create_volatile_idx(const char *directory, int mdt_idx,
5740                               int open_flags)
5741 {
5742         return llapi_create_volatile_param(directory, mdt_idx, open_flags,
5743                                            S_IRUSR | S_IWUSR, NULL);
5744 }
5745
5746 /**
5747  * Swap the layouts between 2 file descriptors
5748  * the 2 files must be open for writing
5749  * first fd received the ioctl, second fd is passed as arg
5750  * this is assymetric but avoid use of root path for ioctl
5751  */
5752 int llapi_fswap_layouts_grouplock(int fd1, int fd2, __u64 dv1, __u64 dv2,
5753                                   int gid, __u64 flags)
5754 {
5755         struct lustre_swap_layouts      lsl;
5756         struct stat                     st1;
5757         struct stat                     st2;
5758         int                             rc;
5759
5760         if (flags & (SWAP_LAYOUTS_KEEP_ATIME | SWAP_LAYOUTS_KEEP_MTIME)) {
5761                 rc = fstat(fd1, &st1);
5762                 if (rc < 0)
5763                         return -errno;
5764
5765                 rc = fstat(fd2, &st2);
5766                 if (rc < 0)
5767                         return -errno;
5768         }
5769         lsl.sl_fd = fd2;
5770         lsl.sl_flags = flags;
5771         lsl.sl_gid = gid;
5772         lsl.sl_dv1 = dv1;
5773         lsl.sl_dv2 = dv2;
5774         rc = ioctl(fd1, LL_IOC_LOV_SWAP_LAYOUTS, &lsl);
5775         if (rc < 0)
5776                 return -errno;
5777
5778         if (flags & (SWAP_LAYOUTS_KEEP_ATIME | SWAP_LAYOUTS_KEEP_MTIME)) {
5779                 struct timeval  tv1[2];
5780                 struct timeval  tv2[2];
5781
5782                 memset(tv1, 0, sizeof(tv1));
5783                 memset(tv2, 0, sizeof(tv2));
5784
5785                 if (flags & SWAP_LAYOUTS_KEEP_ATIME) {
5786                         tv1[0].tv_sec = st1.st_atime;
5787                         tv2[0].tv_sec = st2.st_atime;
5788                 } else {
5789                         tv1[0].tv_sec = st2.st_atime;
5790                         tv2[0].tv_sec = st1.st_atime;
5791                 }
5792
5793                 if (flags & SWAP_LAYOUTS_KEEP_MTIME) {
5794                         tv1[1].tv_sec = st1.st_mtime;
5795                         tv2[1].tv_sec = st2.st_mtime;
5796                 } else {
5797                         tv1[1].tv_sec = st2.st_mtime;
5798                         tv2[1].tv_sec = st1.st_mtime;
5799                 }
5800
5801                 rc = futimes(fd1, tv1);
5802                 if (rc < 0)
5803                         return -errno;
5804
5805                 rc = futimes(fd2, tv2);
5806                 if (rc < 0)
5807                         return -errno;
5808         }
5809
5810         return 0;
5811 }
5812
5813 int llapi_fswap_layouts(int fd1, int fd2, __u64 dv1, __u64 dv2, __u64 flags)
5814 {
5815         int     rc;
5816         int     grp_id;
5817
5818         do
5819                 grp_id = random();
5820         while (grp_id == 0);
5821
5822         rc = llapi_fswap_layouts_grouplock(fd1, fd2, dv1, dv2, grp_id, flags);
5823         if (rc < 0)
5824                 return rc;
5825
5826         return 0;
5827 }
5828
5829 /**
5830  * Swap the layouts between 2 files
5831  * the 2 files are open in write
5832  */
5833 int llapi_swap_layouts(const char *path1, const char *path2,
5834                        __u64 dv1, __u64 dv2, __u64 flags)
5835 {
5836         int     fd1, fd2, rc;
5837
5838         fd1 = open(path1, O_WRONLY | O_LOV_DELAY_CREATE);
5839         if (fd1 < 0) {
5840                 rc = -errno;
5841                 llapi_error(LLAPI_MSG_ERROR, rc,
5842                             "error: cannot open '%s' for write", path1);
5843                 goto out;
5844         }
5845
5846         fd2 = open(path2, O_WRONLY | O_LOV_DELAY_CREATE);
5847         if (fd2 < 0) {
5848                 rc = -errno;
5849                 llapi_error(LLAPI_MSG_ERROR, rc,
5850                             "error: cannot open '%s' for write", path2);
5851                 goto out_close;
5852         }
5853
5854         rc = llapi_fswap_layouts(fd1, fd2, dv1, dv2, flags);
5855         if (rc < 0)
5856                 llapi_error(LLAPI_MSG_ERROR, rc,
5857                             "error: cannot swap layout between '%s' and '%s'",
5858                             path1, path2);
5859
5860         close(fd2);
5861 out_close:
5862         close(fd1);
5863 out:
5864         return rc;
5865 }
5866
5867 /**
5868  * Attempt to open a file with Lustre file identifier \a fid
5869  * and return an open file descriptor.
5870  *
5871  * \param[in] lustre_dir        path within Lustre filesystem containing \a fid
5872  * \param[in] fid               Lustre file identifier of file to open
5873  * \param[in] flags             open() flags
5874  *
5875  * \retval                      non-negative file descriptor on successful open
5876  * \retval                      -1 if an error occurred
5877  */
5878 int llapi_open_by_fid(const char *lustre_dir, const struct lu_fid *fid,
5879                       int flags)
5880 {
5881         char mntdir[PATH_MAX];
5882         char path[PATH_MAX + 64];
5883         int rc;
5884
5885         rc = llapi_search_mounts(lustre_dir, 0, mntdir, NULL);
5886         if (rc != 0)
5887                 return -1;
5888
5889         snprintf(path, sizeof(path), "%s/.lustre/fid/"DFID, mntdir, PFID(fid));
5890         return open(path, flags);
5891 }
5892
5893 /**
5894  * Take group lock.
5895  *
5896  * \param fd   File to lock.
5897  * \param gid  Group Identifier.
5898  *
5899  * \retval 0 on success.
5900  * \retval -errno on failure.
5901  */
5902 int llapi_group_lock(int fd, int gid)
5903 {
5904         int rc;
5905
5906         rc = ioctl(fd, LL_IOC_GROUP_LOCK, gid);
5907         if (rc < 0) {
5908                 rc = -errno;
5909                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot get group lock");
5910         }
5911         return rc;
5912 }
5913
5914 /**
5915  * Put group lock.
5916  *
5917  * \param fd   File to unlock.
5918  * \param gid  Group Identifier.
5919  *
5920  * \retval 0 on success.
5921  * \retval -errno on failure.
5922  */
5923 int llapi_group_unlock(int fd, int gid)
5924 {
5925         int rc;
5926
5927         rc = ioctl(fd, LL_IOC_GROUP_UNLOCK, gid);
5928         if (rc < 0) {
5929                 rc = -errno;
5930                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot put group lock");
5931         }
5932         return rc;
5933 }