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