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