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