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