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