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