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