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