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