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