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