Whamcloud - gitweb
LU-16231 misc: fix stats snapshot_time to use wallclock
[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                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2866                 if (verbose & ~VERBOSE_POOL)
2867                         llapi_printf(LLAPI_MSG_NORMAL, "%s%spool:          ",
2868                                      space, prefix);
2869                 llapi_printf(LLAPI_MSG_NORMAL, "%s", pool_name);
2870                 if (!yaml && is_dir)
2871                         separator = " ";
2872                 else
2873                         separator = "\n";
2874         }
2875
2876         if (strlen(separator) != 0)
2877                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
2878 }
2879
2880 void lov_dump_user_lmm_v1v3(struct lov_user_md *lum, char *pool_name,
2881                             struct lov_user_ost_data_v1 *objects,
2882                             char *path, int obdindex, int depth,
2883                             enum llapi_layout_verbose verbose,
2884                             enum lov_dump_flags flags)
2885 {
2886         bool is_dir = flags & LDF_IS_DIR;
2887         bool indent = flags & LDF_INDENT;
2888         bool skip_objs = flags & LDF_SKIP_OBJS;
2889         bool yaml = flags & LDF_YAML;
2890         bool obdstripe = obdindex == OBD_NOT_FOUND;
2891         int i;
2892
2893         if (!obdstripe && !skip_objs) {
2894                 for (i = 0; !is_dir && i < lum->lmm_stripe_count; i++) {
2895                         if (obdindex == objects[i].l_ost_idx) {
2896                                 obdstripe = true;
2897                                 break;
2898                         }
2899                 }
2900         }
2901
2902         if (!obdstripe)
2903                 return;
2904
2905         lov_dump_user_lmm_header(lum, path, objects, verbose, depth, pool_name,
2906                                  flags);
2907
2908         if (!is_dir && !skip_objs && (verbose & VERBOSE_OBJID) &&
2909             !(lum->lmm_pattern & LOV_PATTERN_F_RELEASED ||
2910               lov_pattern(lum->lmm_pattern) == LOV_PATTERN_MDT)) {
2911                 char *space = "      - ";
2912
2913                 if (indent)
2914                         llapi_printf(LLAPI_MSG_NORMAL,
2915                                      "%6slmm_objects:\n", " ");
2916                 else if (yaml)
2917                         llapi_printf(LLAPI_MSG_NORMAL, "lmm_objects:\n");
2918                 else
2919                         llapi_printf(LLAPI_MSG_NORMAL,
2920                                 "\tobdidx\t\t objid\t\t objid\t\t group\n");
2921
2922                 for (i = 0; i < lum->lmm_stripe_count; i++) {
2923                         int idx = objects[i].l_ost_idx;
2924                         long long oid = ostid_id(&objects[i].l_ost_oi);
2925                         long long gr = ostid_seq(&objects[i].l_ost_oi);
2926
2927                         if (obdindex != OBD_NOT_FOUND && obdindex != idx)
2928                                 continue;
2929
2930                         if (yaml) {
2931                                 struct lu_fid fid = { 0 };
2932
2933                                 ostid_to_fid(&fid, &objects[i].l_ost_oi, idx);
2934                                 llapi_printf(LLAPI_MSG_NORMAL,
2935                                     "%sl_ost_idx: %d\n", space, idx);
2936                                 llapi_printf(LLAPI_MSG_NORMAL,
2937                                     "%8sl_fid:     "DFID_NOBRACE"\n",
2938                                     " ", PFID(&fid));
2939                         } else if (indent) {
2940                                 struct lu_fid fid = { 0 };
2941
2942                                 ostid_to_fid(&fid, &objects[i].l_ost_oi, idx);
2943                                 llapi_printf(LLAPI_MSG_NORMAL,
2944                                     "%s%d: { l_ost_idx: %d, l_fid: "DFID" }\n",
2945                                     space, i, idx, PFID(&fid));
2946                         } else {
2947                                 char fmt[48];
2948
2949                                 sprintf(fmt, "%s%s%s\n",
2950                                         "\t%6u\t%14llu\t%#13llx\t",
2951                                         (fid_seq_is_rsvd(gr) ||
2952                                          fid_seq_is_mdt0(gr)) ?
2953                                          "%14llu" : "%#14llx", "%s");
2954                                 llapi_printf(LLAPI_MSG_NORMAL, fmt, idx, oid,
2955                                              oid, gr,
2956                                              obdindex == idx ? " *" : "");
2957                         }
2958                 }
2959         }
2960         llapi_printf(LLAPI_MSG_NORMAL, "\n");
2961 }
2962
2963 void lmv_dump_user_lmm(struct lmv_user_md *lum, char *pool_name,
2964                        char *path, int obdindex, int depth,
2965                        enum llapi_layout_verbose verbose,
2966                        enum lov_dump_flags flags)
2967 {
2968         struct lmv_user_mds_data *objects = lum->lum_objects;
2969         char *prefix = lum->lum_magic == LMV_USER_MAGIC ? "(Default)" : "";
2970         char *separator = "";
2971         bool yaml = flags & LDF_YAML;
2972         bool obdstripe = false;
2973         int i;
2974
2975         if (obdindex != OBD_NOT_FOUND) {
2976                 if (lum->lum_stripe_count == 0) {
2977                         if (obdindex == lum->lum_stripe_offset)
2978                                 obdstripe = true;
2979                 } else {
2980                         for (i = 0; i < lum->lum_stripe_count; i++) {
2981                                 if (obdindex == objects[i].lum_mds) {
2982                                         llapi_printf(LLAPI_MSG_NORMAL,
2983                                                      "%s%s\n", prefix,
2984                                                      path);
2985                                         obdstripe = true;
2986                                         break;
2987                                 }
2988                         }
2989                 }
2990         } else {
2991                 obdstripe = true;
2992         }
2993
2994         if (!obdstripe)
2995                 return;
2996
2997         /* show all information default */
2998         if (!verbose) {
2999                 if (lum->lum_magic == LMV_USER_MAGIC)
3000                         verbose = VERBOSE_POOL | VERBOSE_STRIPE_COUNT |
3001                                   VERBOSE_STRIPE_OFFSET | VERBOSE_HASH_TYPE;
3002                 else
3003                         verbose = VERBOSE_OBJID;
3004         }
3005
3006         if (depth && path && ((verbose != VERBOSE_OBJID)))
3007                 llapi_printf(LLAPI_MSG_NORMAL, "%s%s\n", prefix, path);
3008
3009         if (verbose & VERBOSE_STRIPE_COUNT) {
3010                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3011                 if (verbose & ~VERBOSE_STRIPE_COUNT)
3012                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_stripe_count: ");
3013                 llapi_printf(LLAPI_MSG_NORMAL, "%d",
3014                              (int)lum->lum_stripe_count);
3015                 if ((verbose & VERBOSE_STRIPE_OFFSET) && !yaml)
3016                         separator = " ";
3017                 else
3018                         separator = "\n";
3019         }
3020
3021         if (verbose & VERBOSE_STRIPE_OFFSET) {
3022                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3023                 if (verbose & ~VERBOSE_STRIPE_OFFSET)
3024                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_stripe_offset: ");
3025                 llapi_printf(LLAPI_MSG_NORMAL, "%d",
3026                              (int)lum->lum_stripe_offset);
3027                 if (verbose & VERBOSE_HASH_TYPE && !yaml)
3028                         separator = " ";
3029                 else
3030                         separator = "\n";
3031         }
3032
3033         if (verbose & VERBOSE_HASH_TYPE) {
3034                 unsigned int type = lum->lum_hash_type & LMV_HASH_TYPE_MASK;
3035                 unsigned int flags = lum->lum_hash_type & ~LMV_HASH_TYPE_MASK;
3036
3037                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3038                 if (verbose & ~VERBOSE_HASH_TYPE)
3039                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_hash_type: ");
3040                 if (type < LMV_HASH_TYPE_MAX)
3041                         llapi_printf(LLAPI_MSG_NORMAL, "%s",
3042                                      mdt_hash_name[type]);
3043                 else
3044                         llapi_printf(LLAPI_MSG_NORMAL, "%#x", type);
3045
3046                 if (flags & LMV_HASH_FLAG_MIGRATION)
3047                         llapi_printf(LLAPI_MSG_NORMAL, ",migrating");
3048                 if (flags & LMV_HASH_FLAG_BAD_TYPE)
3049                         llapi_printf(LLAPI_MSG_NORMAL, ",bad_type");
3050                 if (flags & LMV_HASH_FLAG_LOST_LMV)
3051                         llapi_printf(LLAPI_MSG_NORMAL, ",lost_lmv");
3052                 if (flags & LMV_HASH_FLAG_FIXED)
3053                         llapi_printf(LLAPI_MSG_NORMAL, ",fixed");
3054                 if (flags & ~LMV_HASH_FLAG_KNOWN)
3055                         llapi_printf(LLAPI_MSG_NORMAL, ",unknown_%04x",
3056                                      flags & ~LMV_HASH_FLAG_KNOWN);
3057
3058                 if (verbose & VERBOSE_HASH_TYPE && !yaml)
3059                         separator = " ";
3060                 else
3061                         separator = "\n";
3062         }
3063
3064         if ((verbose & VERBOSE_INHERIT) && lum->lum_magic == LMV_USER_MAGIC) {
3065                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3066                 if (verbose & ~VERBOSE_INHERIT)
3067                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_max_inherit: ");
3068                 if (lum->lum_max_inherit == LMV_INHERIT_UNLIMITED)
3069                         llapi_printf(LLAPI_MSG_NORMAL, "-1");
3070                 else if (lum->lum_max_inherit == LMV_INHERIT_NONE)
3071                         llapi_printf(LLAPI_MSG_NORMAL, "0");
3072                 else
3073                         llapi_printf(LLAPI_MSG_NORMAL, "%hhu",
3074                                      lum->lum_max_inherit);
3075                 if (verbose & VERBOSE_INHERIT && !yaml)
3076                         separator = " ";
3077                 else
3078                         separator = "\n";
3079         }
3080
3081         if ((verbose & VERBOSE_INHERIT_RR) &&
3082             lum->lum_magic == LMV_USER_MAGIC &&
3083             lum->lum_stripe_offset == LMV_OFFSET_DEFAULT) {
3084                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3085                 if (verbose & ~VERBOSE_INHERIT_RR)
3086                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_max_inherit_rr: ");
3087                 if (lum->lum_max_inherit_rr == LMV_INHERIT_RR_UNLIMITED)
3088                         llapi_printf(LLAPI_MSG_NORMAL, "-1");
3089                 else if (lum->lum_max_inherit_rr == LMV_INHERIT_RR_NONE)
3090                         llapi_printf(LLAPI_MSG_NORMAL, "0");
3091                 else
3092                         llapi_printf(LLAPI_MSG_NORMAL, "%hhu",
3093                                      lum->lum_max_inherit_rr);
3094                 if (verbose & VERBOSE_INHERIT_RR && !yaml)
3095                         separator = " ";
3096                 else
3097                         separator = "\n";
3098         }
3099
3100         separator = "\n";
3101
3102         if (verbose & VERBOSE_OBJID && lum->lum_magic != LMV_USER_MAGIC) {
3103                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3104                 if (lum->lum_stripe_count > 0)
3105                         llapi_printf(LLAPI_MSG_NORMAL,
3106                                      "mdtidx\t\t FID[seq:oid:ver]\n");
3107                 for (i = 0; i < lum->lum_stripe_count; i++) {
3108                         int idx = objects[i].lum_mds;
3109                         struct lu_fid *fid = &objects[i].lum_fid;
3110
3111                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
3112                                 llapi_printf(LLAPI_MSG_NORMAL,
3113                                              "%6u\t\t "DFID"\t\t%s\n",
3114                                             idx, PFID(fid),
3115                                             obdindex == idx ? " *" : "");
3116                 }
3117         }
3118
3119         if ((verbose & VERBOSE_POOL) && pool_name != NULL &&
3120              pool_name[0] != '\0') {
3121                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3122                 if (verbose & ~VERBOSE_POOL)
3123                         llapi_printf(LLAPI_MSG_NORMAL, "%slmv_pool:           ",
3124                                      prefix);
3125                 llapi_printf(LLAPI_MSG_NORMAL, "%s%c ", pool_name, ' ');
3126                 separator = "\n";
3127         }
3128
3129         if (!(verbose & VERBOSE_OBJID) || lum->lum_magic == LMV_USER_MAGIC)
3130                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
3131 }
3132
3133 static void lov_dump_comp_v1_header(struct find_param *param, char *path,
3134                                     enum lov_dump_flags flags)
3135 {
3136         struct lov_comp_md_v1 *comp_v1 = (void *)&param->fp_lmd->lmd_lmm;
3137         int depth = param->fp_max_depth;
3138         enum llapi_layout_verbose verbose = param->fp_verbose;
3139         bool yaml = flags & LDF_YAML;
3140
3141         if (depth && path && ((verbose != VERBOSE_OBJID) ||
3142                               !(flags & LDF_IS_DIR)) && !yaml)
3143                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
3144
3145         if (verbose & VERBOSE_DETAIL) {
3146                 llapi_printf(LLAPI_MSG_NORMAL, "composite_header:\n");
3147                 llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_magic:         0x%08X\n",
3148                              " ", comp_v1->lcm_magic);
3149                 llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_size:          %u\n",
3150                              " ", comp_v1->lcm_size);
3151                 if (flags & LDF_IS_DIR)
3152                         llapi_printf(LLAPI_MSG_NORMAL,
3153                                      "%2slcm_flags:         %s\n", " ",
3154                                      comp_v1->lcm_mirror_count > 0 ?
3155                                                         "mirrored" : "");
3156                 else
3157                         llapi_printf(LLAPI_MSG_NORMAL,
3158                                      "%2slcm_flags:         %s\n", " ",
3159                                 llapi_layout_flags_string(comp_v1->lcm_flags));
3160         }
3161
3162         if (verbose & VERBOSE_GENERATION) {
3163                 if (verbose & ~VERBOSE_GENERATION)
3164                         llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_layout_gen:    ",
3165                                      " ");
3166                 llapi_printf(LLAPI_MSG_NORMAL, "%u\n", comp_v1->lcm_layout_gen);
3167         }
3168
3169         if (verbose & VERBOSE_MIRROR_COUNT) {
3170                 if (verbose & ~VERBOSE_MIRROR_COUNT)
3171                         llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_mirror_count:  ",
3172                                      " ");
3173                 llapi_printf(LLAPI_MSG_NORMAL, "%u\n",
3174                              comp_v1->lcm_magic == LOV_USER_MAGIC_COMP_V1 ?
3175                              comp_v1->lcm_mirror_count + 1 : 1);
3176         }
3177
3178         if (verbose & VERBOSE_COMP_COUNT) {
3179                 if (verbose & ~VERBOSE_COMP_COUNT)
3180                         llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_entry_count:   ",
3181                                      " ");
3182                 llapi_printf(LLAPI_MSG_NORMAL, "%u\n",
3183                              comp_v1->lcm_magic == LOV_USER_MAGIC_COMP_V1 ?
3184                              comp_v1->lcm_entry_count : 0);
3185         }
3186
3187         if (verbose & VERBOSE_DETAIL && !yaml)
3188                 llapi_printf(LLAPI_MSG_NORMAL, "components:\n");
3189 }
3190
3191 static void lcme_flags2str(__u32 comp_flags)
3192 {
3193         bool found = false;
3194         int i = 0;
3195
3196         if (!comp_flags) {
3197                 llapi_printf(LLAPI_MSG_NORMAL, "0");
3198                 return;
3199         }
3200         for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
3201                 if (comp_flags & comp_flags_table[i].cfn_flag) {
3202                         if (found)
3203                                 llapi_printf(LLAPI_MSG_NORMAL, ",");
3204                         llapi_printf(LLAPI_MSG_NORMAL, "%s",
3205                                      comp_flags_table[i].cfn_name);
3206                         comp_flags &= ~comp_flags_table[i].cfn_flag;
3207                         found = true;
3208                 }
3209         }
3210         if (comp_flags) {
3211                 if (found)
3212                         llapi_printf(LLAPI_MSG_NORMAL, ",");
3213                 llapi_printf(LLAPI_MSG_NORMAL, "%#x", comp_flags);
3214         }
3215 }
3216
3217 static void lov_dump_comp_v1_entry(struct find_param *param,
3218                                    enum lov_dump_flags flags, int index)
3219 {
3220         struct lov_comp_md_v1 *comp_v1 = (void *)&param->fp_lmd->lmd_lmm;
3221         struct lov_comp_md_entry_v1 *entry;
3222         char *separator = "";
3223         enum llapi_layout_verbose verbose = param->fp_verbose;
3224         bool yaml = flags & LDF_YAML;
3225
3226         entry = &comp_v1->lcm_entries[index];
3227
3228         if (yaml)
3229                 llapi_printf(LLAPI_MSG_NORMAL, "%2scomponent%d:\n", " ", index);
3230
3231         if (verbose & VERBOSE_COMP_ID) {
3232                 if (verbose & VERBOSE_DETAIL && !yaml)
3233                         llapi_printf(LLAPI_MSG_NORMAL,
3234                                      "%slcme_id:             ", "  - ");
3235                 else if (verbose & ~VERBOSE_COMP_ID)
3236                         llapi_printf(LLAPI_MSG_NORMAL,
3237                                      "%4slcme_id:             ", " ");
3238                 if (entry->lcme_id != LCME_ID_INVAL)
3239                         llapi_printf(LLAPI_MSG_NORMAL, "%u", entry->lcme_id);
3240                 else
3241                         llapi_printf(LLAPI_MSG_NORMAL, "N/A");
3242                 separator = "\n";
3243         }
3244
3245         if (verbose & VERBOSE_MIRROR_ID) {
3246                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3247                 if (verbose & ~VERBOSE_MIRROR_ID)
3248                         llapi_printf(LLAPI_MSG_NORMAL,
3249                                      "%4slcme_mirror_id:      ", " ");
3250                 if (entry->lcme_id != LCME_ID_INVAL)
3251                         llapi_printf(LLAPI_MSG_NORMAL, "%u",
3252                                      mirror_id_of(entry->lcme_id));
3253                 else
3254                         llapi_printf(LLAPI_MSG_NORMAL, "N/A");
3255                 separator = "\n";
3256         }
3257
3258         if (verbose & VERBOSE_COMP_FLAGS) {
3259                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3260                 if (verbose & ~VERBOSE_COMP_FLAGS)
3261                         llapi_printf(LLAPI_MSG_NORMAL,
3262                                      "%4slcme_flags:          ", " ");
3263                 lcme_flags2str(entry->lcme_flags);
3264                 separator = "\n";
3265         }
3266         /* print snapshot timestamp if its a nosync comp */
3267         if ((verbose & VERBOSE_COMP_FLAGS) &&
3268             (entry->lcme_flags & LCME_FL_NOSYNC)) {
3269                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3270                 if (verbose & ~VERBOSE_COMP_FLAGS)
3271                         llapi_printf(LLAPI_MSG_NORMAL,
3272                                      "%4slcme_timestamp:      ", " ");
3273                 if (yaml) {
3274                         llapi_printf(LLAPI_MSG_NORMAL, "%llu",
3275                                      (unsigned long long)entry->lcme_timestamp);
3276                 } else {
3277                         time_t stamp = entry->lcme_timestamp;
3278                         char *date_str = asctime(localtime(&stamp));
3279
3280                         date_str[strlen(date_str) - 1] = '\0';
3281                         llapi_printf(LLAPI_MSG_NORMAL, "'%s'", date_str);
3282                 }
3283
3284                 separator = "\n";
3285         }
3286
3287         if (verbose & VERBOSE_COMP_START) {
3288                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3289                 if (verbose & ~VERBOSE_COMP_START)
3290                         llapi_printf(LLAPI_MSG_NORMAL,
3291                                      "%4slcme_extent.e_start: ", " ");
3292                 llapi_printf(LLAPI_MSG_NORMAL, "%llu",
3293                              (unsigned long long)entry->lcme_extent.e_start);
3294                 separator = "\n";
3295         }
3296
3297         if (verbose & VERBOSE_COMP_END) {
3298                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3299                 if (verbose & ~VERBOSE_COMP_END)
3300                         llapi_printf(LLAPI_MSG_NORMAL,
3301                                      "%4slcme_extent.e_end:   ", " ");
3302                 if (entry->lcme_extent.e_end == LUSTRE_EOF)
3303                         llapi_printf(LLAPI_MSG_NORMAL, "%s", "EOF");
3304                 else
3305                         llapi_printf(LLAPI_MSG_NORMAL, "%llu",
3306                                      (unsigned long long)entry->lcme_extent.e_end);
3307                 separator = "\n";
3308         }
3309
3310         if (yaml) {
3311                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3312                 llapi_printf(LLAPI_MSG_NORMAL, "%4ssub_layout:\n", " ");
3313         } else if (verbose & VERBOSE_DETAIL) {
3314                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3315                 llapi_printf(LLAPI_MSG_NORMAL, "%4slcme_offset:         %u\n",
3316                              " ", entry->lcme_offset);
3317                 llapi_printf(LLAPI_MSG_NORMAL, "%4slcme_size:           %u\n",
3318                              " ", entry->lcme_size);
3319                 llapi_printf(LLAPI_MSG_NORMAL, "%4ssub_layout:\n", " ");
3320         } else {
3321                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3322         }
3323 }
3324
3325 /*
3326  * Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
3327  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
3328  *
3329  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
3330  * The table below gives the answers for the specified parameters (value and
3331  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
3332  * --------------------------------------
3333  * 1 | file > limit; sign > 0 | -1 / -1 |
3334  * 2 | file = limit; sign > 0 | -1 / -1 |
3335  * 3 | file < limit; sign > 0 |  ? /  1 |
3336  * 4 | file > limit; sign = 0 | -1 / -1 |
3337  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
3338  * 6 | file < limit; sign = 0 |  ? / -1 |
3339  * 7 | file > limit; sign < 0 |  1 /  1 |
3340  * 8 | file = limit; sign < 0 |  ? / -1 |
3341  * 9 | file < limit; sign < 0 |  ? / -1 |
3342  * --------------------------------------
3343  * Note: 5th actually means that the value is within the interval
3344  * (limit - margin, limit].
3345  */
3346 static int find_value_cmp(unsigned long long file, unsigned long long limit,
3347                           int sign, int negopt, unsigned long long margin,
3348                           bool mds)
3349 {
3350         int ret = -1;
3351
3352         if (sign > 0) {
3353                 /* Drop the fraction of margin (of days or size). */
3354                 if (file + margin <= limit)
3355                         ret = mds ? 0 : 1;
3356         } else if (sign == 0) {
3357                 if (file <= limit && file + margin > limit)
3358                         ret = mds ? 0 : 1;
3359                 else if (file + margin <= limit)
3360                         ret = mds ? 0 : -1;
3361         } else if (sign < 0) {
3362                 if (file > limit)
3363                         ret = 1;
3364                 else if (mds)
3365                         ret = 0;
3366         }
3367
3368         return negopt ? ~ret + 1 : ret;
3369 }
3370
3371 static inline struct lov_user_md *
3372 lov_comp_entry(struct lov_comp_md_v1 *comp_v1, int ent_idx)
3373 {
3374         return (struct lov_user_md *)((char *)comp_v1 +
3375                         comp_v1->lcm_entries[ent_idx].lcme_offset);
3376 }
3377
3378 static inline struct lov_user_ost_data_v1 *
3379 lov_v1v3_objects(struct lov_user_md *v1)
3380 {
3381         if (v1->lmm_magic == LOV_USER_MAGIC_V3)
3382                 return ((struct lov_user_md_v3 *)v1)->lmm_objects;
3383         else
3384                 return v1->lmm_objects;
3385 }
3386
3387 static inline void
3388 lov_v1v3_pool_name(struct lov_user_md *v1, char *pool_name)
3389 {
3390         if (v1->lmm_magic == LOV_USER_MAGIC_V3)
3391                 snprintf(pool_name, LOV_MAXPOOLNAME + 1, "%s",
3392                          ((struct lov_user_md_v3 *)v1)->lmm_pool_name);
3393         else
3394                 pool_name[0] = '\0';
3395 }
3396
3397 static inline bool
3398 print_last_init_comp(struct find_param *param)
3399 {
3400         /* print all component info */
3401         if ((param->fp_verbose & VERBOSE_DEFAULT) == VERBOSE_DEFAULT)
3402                 return false;
3403
3404         /* print specific component info */
3405         if (param->fp_check_comp_id || param->fp_check_comp_flags ||
3406             param->fp_check_comp_start || param->fp_check_comp_end ||
3407             param->fp_check_mirror_id || param->fp_check_mirror_index)
3408                 return false;
3409
3410         return true;
3411 }
3412
3413 static int find_comp_end_cmp(unsigned long long end, struct find_param *param)
3414 {
3415         int match;
3416
3417         if (param->fp_comp_end == LUSTRE_EOF) {
3418                 if (param->fp_comp_end_sign == 0) /* equal to EOF */
3419                         match = end == LUSTRE_EOF ? 1 : -1;
3420                 else if (param->fp_comp_end_sign > 0) /* at most EOF */
3421                         match = end == LUSTRE_EOF ? -1 : 1;
3422                 else /* at least EOF */
3423                         match = -1;
3424                 if (param->fp_exclude_comp_end)
3425                         match = ~match + 1;
3426         } else {
3427                 unsigned long long margin;
3428
3429                 margin = end == LUSTRE_EOF ? 0 : param->fp_comp_end_units;
3430                 match = find_value_cmp(end, param->fp_comp_end,
3431                                        param->fp_comp_end_sign,
3432                                        param->fp_exclude_comp_end, margin, 0);
3433         }
3434
3435         return match;
3436 }
3437
3438 /**
3439  * An example of "getstripe -v" for a two components PFL file:
3440  *
3441  * composite_header:
3442  * lcm_magic:       0x0BD60BD0
3443  * lcm_size:        264
3444  * lcm_flags:       0
3445  * lcm_layout_gen:  2
3446  * lcm_entry_count: 2
3447  * components:
3448  * - lcme_id:             1
3449  *   lcme_flags:          0x10
3450  *   lcme_extent.e_start: 0
3451  *   lcme_extent.e_end:   1048576
3452  *   lcme_offset:         128
3453  *   lcme_size:           56
3454  *   sub_layout:
3455  *     lmm_magic:         0x0BD10BD0
3456  *     lmm_seq:           0x200000401
3457  *     lmm_object_id:     0x1
3458  *     lmm_fid:           [0x200000401:0x1:0x0]
3459  *     lmm_stripe_count:  1
3460  *     lmm_stripe_size:   1048576
3461  *     lmm_pattern:       raid0
3462  *     lmm_layout_gen:    0
3463  *     lmm_stripe_offset: 0
3464  *     lmm_objects:
3465  *     - 0: { l_ost_idx: 0, l_fid: [0x100000000:0x2:0x0] }
3466  *
3467  * - lcme_id:             2
3468  *   lcme_flags:          0x10
3469  *   lcme_extent.e_start: 1048576
3470  *   lcme_extent.e_end:   EOF
3471  *   lcme_offset:         184
3472  *   lcme_size:           80
3473  *     sub_layout:
3474  *     lmm_magic:         0x0BD10BD0
3475  *     lmm_seq:           0x200000401
3476  *     lmm_object_id:     0x1
3477  *     lmm_fid:           [0x200000401:0x1:0x0]
3478  *     lmm_stripe_count:  2
3479  *     lmm_stripe_size:   1048576
3480  *     lmm_pattern:       raid0
3481  *     lmm_layout_gen:    0
3482  *     lmm_stripe_offset: 1
3483  *     lmm_objects:
3484  *     - 0: { l_ost_idx: 1, l_fid: [0x100010000:0x2:0x0] }
3485  *     - 1: { l_ost_idx: 0, l_fid: [0x100000000:0x3:0x0] }
3486  */
3487 static void lov_dump_comp_v1(struct find_param *param, char *path,
3488                              enum lov_dump_flags flags)
3489 {
3490         struct lov_comp_md_entry_v1 *entry;
3491         struct lov_user_ost_data_v1 *objects;
3492         struct lov_comp_md_v1 *comp_v1 = (void *)&param->fp_lmd->lmd_lmm;
3493         struct lov_user_md_v1 *v1;
3494         char pool_name[LOV_MAXPOOLNAME + 1];
3495         int obdindex = param->fp_obd_index;
3496         int i, j, match, ext;
3497         bool obdstripe = false;
3498         __u16 mirror_index = 0;
3499         __u16 mirror_id = 0;
3500
3501         if (obdindex != OBD_NOT_FOUND) {
3502                 for (i = 0; !(flags & LDF_IS_DIR) && !obdstripe &&
3503                             i < comp_v1->lcm_entry_count; i++) {
3504                         if (!(comp_v1->lcm_entries[i].lcme_flags &
3505                               LCME_FL_INIT))
3506                                 continue;
3507
3508                         v1 = lov_comp_entry(comp_v1, i);
3509                         objects = lov_v1v3_objects(v1);
3510
3511                         for (j = 0; j < v1->lmm_stripe_count; j++) {
3512                                 if (obdindex == objects[j].l_ost_idx) {
3513                                         obdstripe = true;
3514                                         break;
3515                                 }
3516                         }
3517                 }
3518         } else {
3519                 obdstripe = true;
3520         }
3521
3522         if (!obdstripe)
3523                 return;
3524
3525         lov_dump_comp_v1_header(param, path, flags);
3526
3527         flags |= LDF_INDENT;
3528
3529         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
3530                 entry = &comp_v1->lcm_entries[i];
3531
3532                 if (param->fp_check_comp_flags) {
3533                         if (((param->fp_comp_flags & entry->lcme_flags) !=
3534                              param->fp_comp_flags) ||
3535                             (param->fp_comp_neg_flags & entry->lcme_flags))
3536                                 continue;
3537                 }
3538
3539                 if (param->fp_check_comp_id &&
3540                     param->fp_comp_id != entry->lcme_id)
3541                         continue;
3542
3543                 if (param->fp_check_comp_start) {
3544                         match = find_value_cmp(entry->lcme_extent.e_start,
3545                                                param->fp_comp_start,
3546                                                param->fp_comp_start_sign,
3547                                                0,
3548                                                param->fp_comp_start_units, 0);
3549                         if (match == -1)
3550                                 continue;
3551                 }
3552
3553                 if (param->fp_check_comp_end) {
3554                         match = find_comp_end_cmp(entry->lcme_extent.e_end,
3555                                                   param);
3556                         if (match == -1)
3557                                 continue;
3558                 }
3559
3560                 if (param->fp_check_mirror_index) {
3561                         if (mirror_id != mirror_id_of(entry->lcme_id)) {
3562                                 mirror_index++;
3563                                 mirror_id = mirror_id_of(entry->lcme_id);
3564                         }
3565
3566                         match = find_value_cmp(mirror_index,
3567                                                param->fp_mirror_index,
3568                                                param->fp_mirror_index_sign,
3569                                                param->fp_exclude_mirror_index,
3570                                                1, 0);
3571                         if (match == -1)
3572                                 continue;
3573                 } else if (param->fp_check_mirror_id) {
3574                         if (mirror_id != mirror_id_of(entry->lcme_id))
3575                                 mirror_id = mirror_id_of(entry->lcme_id);
3576
3577                         match = find_value_cmp(mirror_id,
3578                                                param->fp_mirror_id,
3579                                                param->fp_mirror_id_sign,
3580                                                param->fp_exclude_mirror_id,
3581                                                1, 0);
3582                         if (match == -1)
3583                                 continue;
3584                 }
3585
3586                 if (print_last_init_comp(param)) {
3587                         /**
3588                          * if part of stripe info is needed, we'd print only
3589                          * the last instantiated component info.
3590                          */
3591                         if (entry->lcme_flags & LCME_FL_INIT)
3592                                 continue;
3593
3594                         if (param->fp_verbose & VERBOSE_EXT_SIZE) {
3595                                 if (entry->lcme_flags & LCME_FL_EXTENSION)
3596                                         /* moved back below */
3597                                         i++;
3598                                 else
3599                                         continue;
3600                         }
3601                         break;
3602                 }
3603
3604                 if (entry->lcme_flags & LCME_FL_INIT) {
3605                         if (obdindex != OBD_NOT_FOUND) {
3606                                 flags |= LDF_SKIP_OBJS;
3607                                 v1 = lov_comp_entry(comp_v1, i);
3608                                 objects = lov_v1v3_objects(v1);
3609
3610                                 for (j = 0; j < v1->lmm_stripe_count; j++) {
3611                                         if (obdindex == objects[j].l_ost_idx) {
3612                                                 flags &= ~LDF_SKIP_OBJS;
3613                                                 break;
3614                                         }
3615                                 }
3616                         } else {
3617                                 flags &= ~LDF_SKIP_OBJS;
3618                         }
3619                 } else {
3620                         flags |= LDF_SKIP_OBJS;
3621                 }
3622
3623                 if (obdindex != OBD_NOT_FOUND && (flags & LDF_SKIP_OBJS))
3624                         continue;
3625                 lov_dump_comp_v1_entry(param, flags, i);
3626
3627                 v1 = lov_comp_entry(comp_v1, i);
3628                 objects = lov_v1v3_objects(v1);
3629                 lov_v1v3_pool_name(v1, pool_name);
3630
3631                 ext = entry->lcme_flags & LCME_FL_EXTENSION ? LDF_EXTENSION : 0;
3632                 lov_dump_user_lmm_v1v3(v1, pool_name, objects, path, obdindex,
3633                                        param->fp_max_depth, param->fp_verbose,
3634                                        flags | ext);
3635         }
3636         if (print_last_init_comp(param)) {
3637                 /**
3638                  * directory layout contains only layout template, print the
3639                  * last component.
3640                  */
3641                 if (i == 0)
3642                         i = comp_v1->lcm_entry_count - 1;
3643                 else
3644                         i--;
3645                 flags &= ~LDF_SKIP_OBJS;
3646
3647                 lov_dump_comp_v1_entry(param, flags, i);
3648
3649                 v1 = lov_comp_entry(comp_v1, i);
3650                 objects = lov_v1v3_objects(v1);
3651                 lov_v1v3_pool_name(v1, pool_name);
3652
3653                 entry = &comp_v1->lcm_entries[i];
3654                 ext = entry->lcme_flags & LCME_FL_EXTENSION ? LDF_EXTENSION : 0;
3655                 lov_dump_user_lmm_v1v3(v1, pool_name, objects, path, obdindex,
3656                                        param->fp_max_depth, param->fp_verbose,
3657                                        flags | ext);
3658         }
3659 }
3660
3661 #define VERBOSE_COMP_OPTS       (VERBOSE_COMP_COUNT | VERBOSE_COMP_ID | \
3662                                  VERBOSE_COMP_START | VERBOSE_COMP_END | \
3663                                  VERBOSE_COMP_FLAGS)
3664
3665 static inline bool has_any_comp_options(struct find_param *param)
3666 {
3667         enum llapi_layout_verbose verbose = param->fp_verbose;
3668
3669         if (param->fp_check_comp_id || param->fp_check_comp_count ||
3670             param->fp_check_comp_start || param->fp_check_comp_end ||
3671             param->fp_check_comp_flags)
3672                 return true;
3673
3674         /* show full layout information, not component specific */
3675         if ((verbose & ~VERBOSE_DETAIL) == VERBOSE_DEFAULT)
3676                 return false;
3677
3678         return verbose & VERBOSE_COMP_OPTS;
3679 }
3680
3681 struct lov_user_mds_data *lov_forge_comp_v1(struct lov_user_mds_data *orig,
3682                                             bool is_dir)
3683 {
3684         struct lov_user_md *lum = &orig->lmd_lmm;
3685         struct lov_user_mds_data *new;
3686         struct lov_comp_md_v1 *comp_v1;
3687         struct lov_comp_md_entry_v1 *ent;
3688         int lum_off = sizeof(*comp_v1) + sizeof(*ent);
3689         int lum_size = lov_user_md_size(is_dir ? 0 : lum->lmm_stripe_count,
3690                                         lum->lmm_magic);
3691
3692         new = malloc(offsetof(typeof(*new), lmd_lmm) + lum_off + lum_size);
3693         if (new == NULL) {
3694                 llapi_printf(LLAPI_MSG_NORMAL, "out of memory\n");
3695                 return new;
3696         }
3697
3698         memcpy(new, orig, sizeof(new->lmd_stx) + sizeof(new->lmd_flags)
3699                + sizeof(new->lmd_lmmsize));
3700
3701         comp_v1 = (struct lov_comp_md_v1 *)&new->lmd_lmm;
3702         comp_v1->lcm_magic = lum->lmm_magic;
3703         comp_v1->lcm_size = lum_off + lum_size;
3704         comp_v1->lcm_layout_gen = is_dir ? 0 : lum->lmm_layout_gen;
3705         comp_v1->lcm_flags = 0;
3706         comp_v1->lcm_entry_count = 1;
3707
3708         ent = &comp_v1->lcm_entries[0];
3709         ent->lcme_id = 0;
3710         ent->lcme_flags = is_dir ? 0 : LCME_FL_INIT;
3711         ent->lcme_extent.e_start = 0;
3712         ent->lcme_extent.e_end = LUSTRE_EOF;
3713         ent->lcme_offset = lum_off;
3714         ent->lcme_size = lum_size;
3715
3716         memcpy((char *)comp_v1 + lum_off, lum, lum_size);
3717
3718         return new;
3719 }
3720
3721 static void lov_dump_plain_user_lmm(struct find_param *param, char *path,
3722                                     enum lov_dump_flags flags)
3723 {
3724         __u32 magic = *(__u32 *)&param->fp_lmd->lmd_lmm;
3725
3726         if (has_any_comp_options(param)) {
3727                 struct lov_user_mds_data *new_lmd, *orig_lmd;
3728
3729                 orig_lmd = param->fp_lmd;
3730                 new_lmd = lov_forge_comp_v1(orig_lmd, flags & LDF_IS_DIR);
3731                 if (new_lmd != NULL) {
3732                         param->fp_lmd = new_lmd;
3733                         lov_dump_comp_v1(param, path, flags);
3734                         param->fp_lmd = orig_lmd;
3735                         free(new_lmd);
3736                 }
3737                 return;
3738         }
3739
3740         if (magic == LOV_USER_MAGIC_V1) {
3741                 lov_dump_user_lmm_v1v3(&param->fp_lmd->lmd_lmm, NULL,
3742                                        param->fp_lmd->lmd_lmm.lmm_objects,
3743                                        path, param->fp_obd_index,
3744                                        param->fp_max_depth, param->fp_verbose,
3745                                        flags);
3746         } else {
3747                 char pool_name[LOV_MAXPOOLNAME + 1];
3748                 struct lov_user_ost_data_v1 *objects;
3749                 struct lov_user_md_v3 *lmmv3 = (void *)&param->fp_lmd->lmd_lmm;
3750
3751                 snprintf(pool_name, sizeof(pool_name), "%s",
3752                          lmmv3->lmm_pool_name);
3753                 objects = lmmv3->lmm_objects;
3754                 lov_dump_user_lmm_v1v3(&param->fp_lmd->lmd_lmm, pool_name,
3755                                        objects, path, param->fp_obd_index,
3756                                        param->fp_max_depth, param->fp_verbose,
3757                                        flags);
3758         }
3759 }
3760
3761 static uint32_t check_foreign_type(uint32_t foreign_type)
3762 {
3763         uint32_t i;
3764
3765         for (i = 0; i < LU_FOREIGN_TYPE_UNKNOWN; i++) {
3766                 if (lu_foreign_types[i].lft_name == NULL)
3767                         break;
3768                 if (foreign_type == lu_foreign_types[i].lft_type)
3769                         return i;
3770         }
3771
3772         return LU_FOREIGN_TYPE_UNKNOWN;
3773 }
3774
3775 static void lov_dump_foreign_lmm(struct find_param *param, char *path,
3776                                  enum lov_dump_flags flags)
3777 {
3778         struct lov_foreign_md *lfm = (void *)&param->fp_lmd->lmd_lmm;
3779         bool yaml = flags & LDF_YAML;
3780
3781         if (!yaml && param->fp_depth && path)
3782                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
3783
3784         if (param->fp_verbose & VERBOSE_DETAIL) {
3785                 uint32_t type = check_foreign_type(lfm->lfm_type);
3786
3787                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_magic:         0x%08X\n",
3788                              lfm->lfm_magic);
3789                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_length:          %u\n",
3790                              lfm->lfm_length);
3791                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_type:          0x%08X",
3792                              lfm->lfm_type);
3793                 if (type < LU_FOREIGN_TYPE_UNKNOWN)
3794                         llapi_printf(LLAPI_MSG_NORMAL, " (%s)\n",
3795                                      lu_foreign_types[type].lft_name);
3796                 else
3797                         llapi_printf(LLAPI_MSG_NORMAL, " (unknown)\n");
3798
3799                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_flags:          0x%08X\n",
3800                              lfm->lfm_flags);
3801         }
3802         llapi_printf(LLAPI_MSG_NORMAL, "lfm_value:     '%.*s'\n",
3803                      lfm->lfm_length, lfm->lfm_value);
3804         llapi_printf(LLAPI_MSG_NORMAL, "\n");
3805 }
3806
3807 static void lmv_dump_foreign_lmm(struct find_param *param, char *path,
3808                                     enum lov_dump_flags flags)
3809 {
3810         struct lmv_foreign_md *lfm = (struct lmv_foreign_md *)param->fp_lmv_md;
3811         bool yaml = flags & LDF_YAML;
3812
3813         if (!yaml && param->fp_depth && path)
3814                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
3815
3816         if (param->fp_verbose & VERBOSE_DETAIL) {
3817                 uint32_t type = check_foreign_type(lfm->lfm_type);
3818
3819                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_magic:         0x%08X\n",
3820                              lfm->lfm_magic);
3821                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_length:          %u\n",
3822                              lfm->lfm_length);
3823                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_type:          0x%08X",
3824                              lfm->lfm_type);
3825                 if (type < LU_FOREIGN_TYPE_UNKNOWN)
3826                         llapi_printf(LLAPI_MSG_NORMAL, " (%s)\n",
3827                                      lu_foreign_types[type].lft_name);
3828                 else
3829                         llapi_printf(LLAPI_MSG_NORMAL, " (unknown)\n");
3830
3831                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_flags:          0x%08X\n",
3832                              lfm->lfm_flags);
3833         }
3834         llapi_printf(LLAPI_MSG_NORMAL, "lfm_value:     '%.*s'\n",
3835                      lfm->lfm_length, lfm->lfm_value);
3836         llapi_printf(LLAPI_MSG_NORMAL, "\n");
3837 }
3838
3839 static void llapi_lov_dump_user_lmm(struct find_param *param, char *path,
3840                                     enum lov_dump_flags flags)
3841 {
3842         __u32 magic;
3843
3844         if (param->fp_get_lmv || param->fp_get_default_lmv)
3845                 magic = (__u32)param->fp_lmv_md->lum_magic;
3846         else
3847                 magic = *(__u32 *)&param->fp_lmd->lmd_lmm; /* lum->lmm_magic */
3848
3849         if (param->fp_raw)
3850                 flags |= LDF_IS_RAW;
3851         if (param->fp_yaml)
3852                 flags |= LDF_YAML;
3853
3854         switch (magic) {
3855         case LOV_USER_MAGIC_V1:
3856         case LOV_USER_MAGIC_V3:
3857         case LOV_USER_MAGIC_SPECIFIC:
3858                 lov_dump_plain_user_lmm(param, path, flags);
3859                 break;
3860         case LOV_USER_MAGIC_FOREIGN:
3861                 lov_dump_foreign_lmm(param, path, flags);
3862                 break;
3863         case LMV_MAGIC_V1:
3864         case LMV_USER_MAGIC: {
3865                 char pool_name[LOV_MAXPOOLNAME + 1];
3866                 struct lmv_user_md *lum;
3867
3868                 lum = (struct lmv_user_md *)param->fp_lmv_md;
3869                 snprintf(pool_name, sizeof(pool_name), "%s",
3870                          lum->lum_pool_name);
3871                 lmv_dump_user_lmm(lum, pool_name, path, param->fp_obd_index,
3872                                   param->fp_max_depth, param->fp_verbose,
3873                                   flags);
3874                 break;
3875         }
3876         case LOV_USER_MAGIC_COMP_V1:
3877                 lov_dump_comp_v1(param, path, flags);
3878                 break;
3879         case LMV_MAGIC_FOREIGN:
3880                 lmv_dump_foreign_lmm(param, path, flags);
3881                 break;
3882         default:
3883                 llapi_printf(LLAPI_MSG_NORMAL,
3884                              "unknown lmm_magic:  %#x (expecting one of %#x %#x %#x %#x)\n",
3885                              *(__u32 *)&param->fp_lmd->lmd_lmm,
3886                              LOV_USER_MAGIC_V1, LOV_USER_MAGIC_V3,
3887                              LMV_USER_MAGIC, LMV_MAGIC_V1);
3888                 return;
3889         }
3890 }
3891
3892 static int llapi_file_get_stripe1(const char *path, struct lov_user_md *lum)
3893 {
3894         const char *fname;
3895         char *dname;
3896         int fd, rc = 0;
3897
3898         fname = strrchr(path, '/');
3899
3900         /* It should be a file (or other non-directory) */
3901         if (fname == NULL) {
3902                 dname = (char *)malloc(2);
3903                 if (dname == NULL)
3904                         return -ENOMEM;
3905                 strcpy(dname, ".");
3906                 fname = (char *)path;
3907         } else {
3908                 dname = (char *)malloc(fname - path + 1);
3909                 if (dname == NULL)
3910                         return -ENOMEM;
3911                 strncpy(dname, path, fname - path);
3912                 dname[fname - path] = '\0';
3913                 fname++;
3914         }
3915
3916         fd = open(dname, O_RDONLY | O_NONBLOCK);
3917         if (fd == -1) {
3918                 rc = -errno;
3919                 goto out_free;
3920         }
3921
3922         strcpy((char *)lum, fname);
3923         if (ioctl(fd, IOC_MDC_GETFILESTRIPE, (void *)lum) == -1)
3924                 rc = -errno;
3925
3926         if (close(fd) == -1 && rc == 0)
3927                 rc = -errno;
3928
3929 out_free:
3930         free(dname);
3931         return rc;
3932 }
3933
3934 int llapi_file_get_stripe(const char *path, struct lov_user_md *lum)
3935 {
3936         char *canon_path = NULL;
3937         int rc, rc2;
3938
3939         rc = llapi_file_get_stripe1(path, lum);
3940         if (!(rc == -ENOTTY || rc == -ENODATA))
3941                 goto out;
3942
3943         /* Handle failure due to symlinks by dereferencing path manually. */
3944         canon_path = canonicalize_file_name(path);
3945         if (canon_path == NULL)
3946                 goto out; /* Keep original rc. */
3947
3948         rc2 = llapi_file_get_stripe1(canon_path, lum);
3949         if (rc2 < 0)
3950                 goto out; /* Keep original rc. */
3951
3952         rc = 0;
3953 out:
3954         free(canon_path);
3955
3956         return rc;
3957 }
3958
3959 int llapi_file_lookup(int dirfd, const char *name)
3960 {
3961         struct obd_ioctl_data data = { 0 };
3962         char rawbuf[8192];
3963         char *buf = rawbuf;
3964         int rc;
3965
3966         if (dirfd < 0 || name == NULL)
3967                 return -EINVAL;
3968
3969         data.ioc_version = OBD_IOCTL_VERSION;
3970         data.ioc_len = sizeof(data);
3971         data.ioc_inlbuf1 = (char *)name;
3972         data.ioc_inllen1 = strlen(name) + 1;
3973
3974         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
3975         if (rc) {
3976                 llapi_error(LLAPI_MSG_ERROR, rc,
3977                             "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
3978                             name, rc);
3979                 return rc;
3980         }
3981
3982         rc = ioctl(dirfd, IOC_MDC_LOOKUP, buf);
3983         if (rc < 0)
3984                 rc = -errno;
3985         return rc;
3986 }
3987
3988 /*
3989  * Check if the file time matches all the given criteria (e.g. --atime +/-N).
3990  * Return -1 or 1 if file timestamp does not or does match the given criteria
3991  * correspondingly. Return 0 if the MDS time is being checked and there are
3992  * attributes on OSTs and it is not yet clear if the timespamp matches.
3993  *
3994  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
3995  * updated timestamps.
3996  */
3997 static int find_time_check(struct find_param *param, int mds)
3998 {
3999         struct lov_user_mds_data *lmd = param->fp_lmd;
4000         int rc = 1;
4001         int rc2;
4002
4003         /* Check if file is accepted. */
4004         if (param->fp_atime) {
4005                 rc2 = find_value_cmp(lmd->lmd_stx.stx_atime.tv_sec,
4006                                      param->fp_atime, param->fp_asign,
4007                                      param->fp_exclude_atime,
4008                                      param->fp_time_margin, mds);
4009                 if (rc2 < 0)
4010                         return rc2;
4011                 rc = rc2;
4012         }
4013
4014         if (param->fp_mtime) {
4015                 rc2 = find_value_cmp(lmd->lmd_stx.stx_mtime.tv_sec,
4016                                      param->fp_mtime, param->fp_msign,
4017                                      param->fp_exclude_mtime,
4018                                      param->fp_time_margin, mds);
4019                 if (rc2 < 0)
4020                         return rc2;
4021
4022                 /*
4023                  * If the previous check matches, but this one is not yet clear,
4024                  * we should return 0 to do an RPC on OSTs.
4025                  */
4026                 if (rc == 1)
4027                         rc = rc2;
4028         }
4029
4030         if (param->fp_ctime) {
4031                 rc2 = find_value_cmp(lmd->lmd_stx.stx_ctime.tv_sec,
4032                                      param->fp_ctime, param->fp_csign,
4033                                      param->fp_exclude_ctime,
4034                                      param->fp_time_margin, mds);
4035                 if (rc2 < 0)
4036                         return rc2;
4037
4038                 /*
4039                  * If the previous check matches, but this one is not yet clear,
4040                  * we should return 0 to do an RPC on OSTs.
4041                  */
4042                 if (rc == 1)
4043                         rc = rc2;
4044         }
4045
4046         return rc;
4047 }
4048
4049 static int find_newerxy_check(struct find_param *param, int mds, bool from_mdt)
4050 {
4051         struct lov_user_mds_data *lmd = param->fp_lmd;
4052         int i;
4053         int rc = 1;
4054         int rc2;
4055
4056         for (i = 0; i < 2; i++) {
4057                 /* Check if file is accepted. */
4058                 if (param->fp_newery[NEWERXY_ATIME][i]) {
4059                         rc2 = find_value_cmp(lmd->lmd_stx.stx_atime.tv_sec,
4060                                              param->fp_newery[NEWERXY_ATIME][i],
4061                                              -1, i, 0, mds);
4062                         if (rc2 < 0)
4063                                 return rc2;
4064                         rc = rc2;
4065                 }
4066
4067                 if (param->fp_newery[NEWERXY_MTIME][i]) {
4068                         rc2 = find_value_cmp(lmd->lmd_stx.stx_mtime.tv_sec,
4069                                              param->fp_newery[NEWERXY_MTIME][i],
4070                                              -1, i, 0, mds);
4071                         if (rc2 < 0)
4072                                 return rc2;
4073
4074                         /*
4075                          * If the previous check matches, but this one is not
4076                          * yet clear, we should return 0 to do an RPC on OSTs.
4077                          */
4078                         if (rc == 1)
4079                                 rc = rc2;
4080                 }
4081
4082                 if (param->fp_newery[NEWERXY_CTIME][i]) {
4083                         rc2 = find_value_cmp(lmd->lmd_stx.stx_ctime.tv_sec,
4084                                              param->fp_newery[NEWERXY_CTIME][i],
4085                                              -1, i, 0, mds);
4086                         if (rc2 < 0)
4087                                 return rc2;
4088
4089                         /*
4090                          * If the previous check matches, but this one is not
4091                          * yet clear, we should return 0 to do an RPC on OSTs.
4092                          */
4093                         if (rc == 1)
4094                                 rc = rc2;
4095                 }
4096
4097                 /*
4098                  * File birth time (btime) can get from MDT directly.
4099                  * if @from_mdt is true, it means the input file attributs are
4100                  * obtained directly from MDT.
4101                  * Thus, if @from_mdt is false, we should skip the following
4102                  * btime check.
4103                  */
4104                 if (!from_mdt)
4105                         continue;
4106
4107                 if (param->fp_newery[NEWERXY_BTIME][i]) {
4108                         if (!(lmd->lmd_stx.stx_mask & STATX_BTIME))
4109                                 return -EOPNOTSUPP;
4110
4111                         rc2 = find_value_cmp(lmd->lmd_stx.stx_btime.tv_sec,
4112                                              param->fp_newery[NEWERXY_BTIME][i],
4113                                              -1, i, 0, 0);
4114                         if (rc2 < 0)
4115                                 return rc2;
4116                 }
4117         }
4118
4119         return rc;
4120 }
4121
4122 /**
4123  * Check whether the stripes matches the indexes user provided
4124  *       1   : matched
4125  *       0   : Unmatched
4126  */
4127 static int check_obd_match(struct find_param *param)
4128 {
4129         struct lov_user_ost_data_v1 *objects;
4130         struct lov_comp_md_v1 *comp_v1 = NULL;
4131         struct lov_user_mds_data *lmd = param->fp_lmd;
4132         struct lov_user_md_v1 *v1 = &lmd->lmd_lmm;
4133         int i, j, k, count = 1;
4134
4135         if (param->fp_obd_uuid && param->fp_obd_index == OBD_NOT_FOUND)
4136                 return 0;
4137
4138         if (!S_ISREG(lmd->lmd_stx.stx_mode))
4139                 return 0;
4140
4141         /* exclude foreign */
4142         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4143                 return param->fp_exclude_obd;
4144
4145         /*
4146          * Only those files should be accepted, which have a
4147          * stripe on the specified OST.
4148          */
4149         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4150                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4151                 count = comp_v1->lcm_entry_count;
4152         }
4153
4154         for (i = 0; i < count; i++) {
4155                 if (comp_v1)
4156                         v1 = lov_comp_entry(comp_v1, i);
4157
4158                 objects = lov_v1v3_objects(v1);
4159
4160                 for (j = 0; j < v1->lmm_stripe_count; j++) {
4161                         if (comp_v1 && !(comp_v1->lcm_entries[i].lcme_flags &
4162                                          LCME_FL_INIT))
4163                                 continue;
4164                         for (k = 0; k < param->fp_num_obds; k++) {
4165                                 if (param->fp_obd_indexes[k] ==
4166                                     objects[j].l_ost_idx)
4167                                         return !param->fp_exclude_obd;
4168                         }
4169                 }
4170         }
4171
4172         return param->fp_exclude_obd;
4173 }
4174
4175 static int check_mdt_match(struct find_param *param)
4176 {
4177         int i;
4178
4179         if (param->fp_mdt_uuid && param->fp_mdt_index == OBD_NOT_FOUND)
4180                 return 0;
4181
4182         /* FIXME: For striped dir, we should get stripe information and check */
4183         for (i = 0; i < param->fp_num_mdts; i++) {
4184                 if (param->fp_mdt_indexes[i] == param->fp_file_mdt_index)
4185                         return !param->fp_exclude_mdt;
4186         }
4187
4188         if (param->fp_exclude_mdt)
4189                 return 1;
4190
4191         return 0;
4192 }
4193
4194 /**
4195  * Check whether the obd is active or not, if it is
4196  * not active, just print the object affected by this
4197  * failed target
4198  **/
4199 static void print_failed_tgt(struct find_param *param, char *path, int type)
4200 {
4201         struct obd_statfs stat_buf;
4202         struct obd_uuid uuid_buf;
4203         int tgt_nr, i, *indexes;
4204         int ret = 0;
4205
4206         if (type != LL_STATFS_LOV && type != LL_STATFS_LMV) {
4207                 llapi_error(LLAPI_MSG_NORMAL, ret, "%s: wrong statfs type(%d)",
4208                             __func__, type);
4209                 return;
4210         }
4211
4212         tgt_nr = (type == LL_STATFS_LOV) ? param->fp_obd_index :
4213                  param->fp_mdt_index;
4214         indexes = (type == LL_STATFS_LOV) ? param->fp_obd_indexes :
4215                   param->fp_mdt_indexes;
4216
4217         for (i = 0; i < tgt_nr; i++) {
4218                 memset(&stat_buf, 0, sizeof(struct obd_statfs));
4219                 memset(&uuid_buf, 0, sizeof(struct obd_uuid));
4220
4221                 ret = llapi_obd_statfs(path, type, indexes[i], &stat_buf,
4222                                        &uuid_buf);
4223                 if (ret)
4224                         llapi_error(LLAPI_MSG_NORMAL, ret,
4225                                     "%s: obd_uuid: %s failed",
4226                                     __func__, param->fp_obd_uuid->uuid);
4227         }
4228 }
4229
4230 static int find_check_stripe_size(struct find_param *param)
4231 {
4232         struct lov_comp_md_v1 *comp_v1 = NULL;
4233         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4234         __u32 stripe_size = 0;
4235         int ret, i, count = 1;
4236
4237         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4238                 return param->fp_exclude_stripe_size ? 1 : -1;
4239
4240         ret = param->fp_exclude_stripe_size ? 1 : -1;
4241         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4242                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4243                 count = comp_v1->lcm_entry_count;
4244         }
4245
4246         for (i = 0; i < count; i++) {
4247                 struct lov_comp_md_entry_v1 *ent;
4248
4249                 if (comp_v1) {
4250                         v1 = lov_comp_entry(comp_v1, i);
4251
4252                         ent = &comp_v1->lcm_entries[i];
4253                         if (ent->lcme_flags & LCME_FL_EXTENSION)
4254                                 continue;
4255                         if (!(ent->lcme_flags & LCME_FL_INIT))
4256                                 continue;
4257                 }
4258                 stripe_size = v1->lmm_stripe_size;
4259         }
4260
4261         ret = find_value_cmp(stripe_size, param->fp_stripe_size,
4262                              param->fp_stripe_size_sign,
4263                              param->fp_exclude_stripe_size,
4264                              param->fp_stripe_size_units, 0);
4265
4266         return ret;
4267 }
4268
4269 static int find_check_ext_size(struct find_param *param)
4270 {
4271         struct lov_comp_md_v1 *comp_v1;
4272         struct lov_user_md_v1 *v1;
4273         int ret, i;
4274
4275         ret = param->fp_exclude_ext_size ? 1 : -1;
4276         comp_v1 = (struct lov_comp_md_v1 *)&param->fp_lmd->lmd_lmm;
4277         if (comp_v1->lcm_magic != LOV_USER_MAGIC_COMP_V1)
4278                 return ret;
4279
4280         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
4281                 struct lov_comp_md_entry_v1 *ent;
4282
4283                 v1 = lov_comp_entry(comp_v1, i);
4284
4285                 ent = &comp_v1->lcm_entries[i];
4286                 if (!(ent->lcme_flags & LCME_FL_EXTENSION))
4287                         continue;
4288
4289                 ret = find_value_cmp(v1->lmm_stripe_size, param->fp_ext_size,
4290                                      param->fp_ext_size_sign,
4291                                      param->fp_exclude_ext_size,
4292                                      param->fp_ext_size_units, 0);
4293                 /* If any ext_size matches */
4294                 if (ret != -1)
4295                         break;
4296         }
4297
4298         return ret;
4299 }
4300
4301 static __u32 find_get_stripe_count(struct find_param *param)
4302 {
4303         struct lov_comp_md_v1 *comp_v1 = NULL;
4304         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4305         int i, count = 1;
4306         __u32 stripe_count = 0;
4307
4308         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4309                 return 0;
4310
4311         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4312                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4313                 count = comp_v1->lcm_entry_count;
4314         }
4315
4316         for (i = 0; i < count; i++) {
4317                 if (comp_v1) {
4318                         struct lov_comp_md_entry_v1 *ent;
4319
4320                         v1 = lov_comp_entry(comp_v1, i);
4321
4322                         ent = &comp_v1->lcm_entries[i];
4323                         if (!(ent->lcme_flags & LCME_FL_INIT))
4324                                 continue;
4325
4326                         if (ent->lcme_flags & LCME_FL_EXTENSION)
4327                                 continue;
4328                 }
4329                 stripe_count = v1->lmm_stripe_count;
4330         }
4331
4332         return stripe_count;
4333 }
4334
4335 #define LOV_PATTERN_INVALID     0xFFFFFFFF
4336
4337 static int find_check_layout(struct find_param *param)
4338 {
4339         struct lov_comp_md_v1 *comp_v1 = NULL;
4340         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4341         int i, count = 1;
4342         bool found = false, valid = false;
4343
4344         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4345                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4346                 count = comp_v1->lcm_entry_count;
4347         }
4348
4349         for (i = 0; i < count; i++) {
4350                 if (comp_v1)
4351                         v1 = lov_comp_entry(comp_v1, i);
4352
4353                 /* foreign file have a special magic but no pattern field */
4354                 if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4355                         continue;
4356
4357                 if (v1->lmm_pattern == LOV_PATTERN_INVALID)
4358                         continue;
4359
4360                 valid = true;
4361                 if (v1->lmm_pattern & param->fp_layout) {
4362                         found = true;
4363                         break;
4364                 }
4365         }
4366
4367         if (!valid)
4368                 return -1;
4369
4370         if ((found && !param->fp_exclude_layout) ||
4371             (!found && param->fp_exclude_layout))
4372                 return 1;
4373
4374         return -1;
4375 }
4376
4377 /*
4378  * if no type specified, check/exclude all foreign
4379  * if type specified, check all foreign&type and exclude !foreign + foreign&type
4380  */
4381 static int find_check_foreign(struct find_param *param)
4382 {
4383         if (S_ISREG(param->fp_lmd->lmd_stx.stx_mode)) {
4384                 struct lov_foreign_md *lfm;
4385
4386                 lfm = (void *)&param->fp_lmd->lmd_lmm;
4387                 if (lfm->lfm_magic != LOV_USER_MAGIC_FOREIGN) {
4388                         if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN)
4389                                 return param->fp_exclude_foreign ? 1 : -1;
4390                         return -1;
4391                 }
4392
4393                 if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN ||
4394                     lfm->lfm_type == param->fp_foreign_type)
4395                         return param->fp_exclude_foreign ? -1 : 1;
4396                 return param->fp_exclude_foreign ? 1 : -1;
4397         }
4398
4399         if (S_ISDIR(param->fp_lmd->lmd_stx.stx_mode)) {
4400                 struct lmv_foreign_md *lfm;
4401
4402                 lfm = (void *)param->fp_lmv_md;
4403                 if (lmv_is_foreign(lfm->lfm_magic)) {
4404                         if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN)
4405                                 return param->fp_exclude_foreign ? 1 : -1;
4406                         return -1;
4407                 }
4408
4409                 if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN ||
4410                     lfm->lfm_type == param->fp_foreign_type)
4411                         return param->fp_exclude_foreign ? -1 : 1;
4412                 return param->fp_exclude_foreign ? 1 : -1;
4413         }
4414         return -1;
4415 }
4416
4417 static int find_check_pool(struct find_param *param)
4418 {
4419         struct lov_comp_md_v1 *comp_v1 = NULL;
4420         struct lov_user_md_v3 *v3 = (void *)&param->fp_lmd->lmd_lmm;
4421         int i, count = 1;
4422         bool found = false;
4423
4424         if (v3->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4425                 comp_v1 = (struct lov_comp_md_v1 *)v3;
4426                 count = comp_v1->lcm_entry_count;
4427                 /* empty requested pool is taken as no pool search */
4428                 if (count == 0 && param->fp_poolname[0] == '\0') {
4429                         found = true;
4430                         goto found;
4431                 }
4432         }
4433
4434         for (i = 0; i < count; i++) {
4435                 if (comp_v1 != NULL) {
4436                         if (!(comp_v1->lcm_entries[i].lcme_flags &
4437                               LCME_FL_INIT))
4438                                 continue;
4439
4440                         v3 = (void *)lov_comp_entry(comp_v1, i);
4441                 }
4442
4443                 if (v3->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4444                         continue;
4445
4446                 if (((v3->lmm_magic == LOV_USER_MAGIC_V1) &&
4447                      (param->fp_poolname[0] == '\0')) ||
4448                     ((v3->lmm_magic == LOV_USER_MAGIC_V3) &&
4449                      (strncmp(v3->lmm_pool_name,
4450                               param->fp_poolname, LOV_MAXPOOLNAME) == 0)) ||
4451                     ((v3->lmm_magic == LOV_USER_MAGIC_V3) &&
4452                      (strcmp(param->fp_poolname, "*") == 0))) {
4453                         found = true;
4454                         break;
4455                 }
4456         }
4457
4458 found:
4459         if ((found && !param->fp_exclude_pool) ||
4460             (!found && param->fp_exclude_pool))
4461                 return 1;
4462
4463         return -1;
4464 }
4465
4466 static int find_check_comp_options(struct find_param *param)
4467 {
4468         struct lov_comp_md_v1 *comp_v1, *forged_v1 = NULL;
4469         struct lov_user_mds_data *lmd = param->fp_lmd;
4470         struct lov_user_md_v1 *v1 = &lmd->lmd_lmm;
4471         struct lov_comp_md_entry_v1 *entry;
4472         int i, ret = 0;
4473
4474         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4475                 return -1;
4476
4477         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4478                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4479         } else {
4480                 forged_v1 = malloc(sizeof(*forged_v1) + sizeof(*entry));
4481                 if (forged_v1 == NULL)
4482                         return -1;
4483                 comp_v1 = forged_v1;
4484                 comp_v1->lcm_entry_count = 1;
4485                 entry = &comp_v1->lcm_entries[0];
4486                 entry->lcme_flags = S_ISDIR(lmd->lmd_stx.stx_mode) ?
4487                                     0 : LCME_FL_INIT;
4488                 entry->lcme_extent.e_start = 0;
4489                 entry->lcme_extent.e_end = LUSTRE_EOF;
4490         }
4491
4492         /* invalid case, don't match for any kind of search. */
4493         if (comp_v1->lcm_entry_count == 0) {
4494                 ret = -1;
4495                 goto out;
4496         }
4497
4498         if (param->fp_check_comp_count) {
4499                 ret = find_value_cmp(forged_v1 ? 0 : comp_v1->lcm_entry_count,
4500                                      param->fp_comp_count,
4501                                      param->fp_comp_count_sign,
4502                                      param->fp_exclude_comp_count, 1, 0);
4503                 if (ret == -1)
4504                         goto out;
4505         }
4506
4507         ret = 1;
4508         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
4509                 entry = &comp_v1->lcm_entries[i];
4510
4511                 if (param->fp_check_comp_flags) {
4512                         ret = 1;
4513                         if (((param->fp_comp_flags & entry->lcme_flags) !=
4514                              param->fp_comp_flags) ||
4515                             (param->fp_comp_neg_flags & entry->lcme_flags)) {
4516                                 ret = -1;
4517                                 continue;
4518                         }
4519                 }
4520
4521                 if (param->fp_check_comp_start) {
4522                         ret = find_value_cmp(entry->lcme_extent.e_start,
4523                                              param->fp_comp_start,
4524                                              param->fp_comp_start_sign,
4525                                              param->fp_exclude_comp_start,
4526                                              param->fp_comp_start_units, 0);
4527                         if (ret == -1)
4528                                 continue;
4529                 }
4530
4531                 if (param->fp_check_comp_end) {
4532                         ret = find_comp_end_cmp(entry->lcme_extent.e_end,
4533                                                 param);
4534                         if (ret == -1)
4535                                 continue;
4536                 }
4537
4538                 /* the component matches all criteria */
4539                 break;
4540         }
4541 out:
4542         if (forged_v1)
4543                 free(forged_v1);
4544         return ret;
4545 }
4546
4547 static int find_check_mirror_options(struct find_param *param)
4548 {
4549         struct lov_comp_md_v1 *comp_v1;
4550         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4551         int ret = 0;
4552
4553         if (v1->lmm_magic != LOV_USER_MAGIC_COMP_V1)
4554                 return -1;
4555
4556         comp_v1 = (struct lov_comp_md_v1 *)v1;
4557
4558         if (param->fp_check_mirror_count) {
4559                 ret = find_value_cmp(comp_v1->lcm_mirror_count + 1,
4560                                      param->fp_mirror_count,
4561                                      param->fp_mirror_count_sign,
4562                                      param->fp_exclude_mirror_count, 1, 0);
4563                 if (ret == -1)
4564                         return ret;
4565         }
4566
4567         if (param->fp_check_mirror_state) {
4568                 ret = 1;
4569                 __u16 file_state = comp_v1->lcm_flags & LCM_FL_FLR_MASK;
4570
4571                 if ((param->fp_mirror_state != 0 &&
4572                     file_state != param->fp_mirror_state) ||
4573                     file_state == param->fp_mirror_neg_state)
4574                         return -1;
4575         }
4576
4577         return ret;
4578 }
4579
4580 static bool find_check_lmm_info(struct find_param *param)
4581 {
4582         return param->fp_check_pool || param->fp_check_stripe_count ||
4583                param->fp_check_stripe_size || param->fp_check_layout ||
4584                param->fp_check_comp_count || param->fp_check_comp_end ||
4585                param->fp_check_comp_start || param->fp_check_comp_flags ||
4586                param->fp_check_mirror_count || param->fp_check_foreign ||
4587                param->fp_check_mirror_state || param->fp_check_ext_size ||
4588                param->fp_check_projid;
4589 }
4590
4591 /*
4592  * Interpret backslash escape sequences and write output into buffer.
4593  * Anything written to the buffer will be null terminated.
4594  *
4595  * @param[in]   seq     String being parsed for escape sequence. The leading
4596  *                      '\' character is not included in this string (only the
4597  *                      characters after it)
4598  * @param[out]  buffer  Location where interpreted escape sequence is written
4599  * @param[in]   size    Size of the available buffer. (Needs to be large enough
4600  *                      to handle escape sequence output plus null terminator.)
4601  * @param[out]  wrote   Number of bytes written to the buffer.
4602  * @return              Number of characters from input string processed
4603  *                      as part of the escape sequence (0 for an unrecognized
4604  *                      escape sequence)
4605  */
4606 int printf_format_escape(char *seq, char *buffer, size_t size, int *wrote)
4607 {
4608         *wrote = 0;
4609         /* For now, only handle single char escape sequences: \n, \t, \\ */
4610         if (size < 2)
4611                 return 0;
4612
4613         switch (*seq) {
4614         case 'n':
4615                 *buffer = '\n';
4616                 break;
4617         case 't':
4618                 *buffer = '\t';
4619                 break;
4620         case '\\':
4621                 *buffer = '\\';
4622                 break;
4623         default:
4624                 return 0;
4625         }
4626
4627         *wrote = 1;
4628         return 1;
4629 }
4630
4631 /*
4632  * Interpret formats for timestamps (%a, %A@, etc)
4633  *
4634  * @param[in]   seq     String being parsed for timestamp format.  The leading
4635  *                      '%' character is not included in this string
4636  * @param[out]  buffer  Location where timestamp info is written
4637  * @param[in]   size    Size of the available buffer.
4638  * @param[out]  wrote   Number of bytes written to the buffer.
4639  * @return              Number of characters from input string processed
4640  *                      as part of the format (0 for an unknown format)
4641  */
4642
4643 int printf_format_timestamp(char *seq, char *buffer, size_t size, int *wrote,
4644                             struct find_param *param)
4645 {
4646         struct statx_timestamp ts = { 0, 0 };
4647         struct tm *tm;
4648         time_t t;
4649         int rc = 0;
4650         char *fmt = "%c";  /* Print in ctime format by default */
4651         *wrote = 0;
4652
4653         switch (*seq) {
4654         case 'a':
4655                 ts = param->fp_lmd->lmd_stx.stx_atime;
4656                 rc = 1;
4657                 break;
4658         case 'A':
4659                 if (*(seq + 1) == '@') {
4660                         ts = param->fp_lmd->lmd_stx.stx_atime;
4661                         fmt = "%s";
4662                         rc = 2;
4663                 }
4664                 break;
4665         case 'c':
4666                 ts = param->fp_lmd->lmd_stx.stx_ctime;
4667                 rc = 1;
4668                 break;
4669         case 'C':
4670                 if (*(seq + 1) == '@') {
4671                         ts = param->fp_lmd->lmd_stx.stx_ctime;
4672                         fmt = "%s";
4673                         rc = 2;
4674                 }
4675                 break;
4676         case 't':
4677                 ts = param->fp_lmd->lmd_stx.stx_mtime;
4678                 rc = 1;
4679                 break;
4680         case 'T':
4681                 if (*(seq + 1) == '@') {
4682                         ts = param->fp_lmd->lmd_stx.stx_mtime;
4683                         fmt = "%s";
4684                         rc = 2;
4685                 }
4686                 break;
4687         case 'w':
4688                 ts = param->fp_lmd->lmd_stx.stx_btime;
4689                 rc = 1;
4690                 break;
4691         case 'W':
4692                 if (*(seq + 1) == '@') {
4693                         ts = param->fp_lmd->lmd_stx.stx_btime;
4694                         fmt = "%s";
4695                         rc = 2;
4696                 }
4697                 break;
4698         default:
4699                 rc = 0;
4700         }
4701
4702         if (rc) {
4703                 /* Found valid format, print to buffer */
4704                 t = ts.tv_sec;
4705                 tm = localtime(&t);
4706                 *wrote = strftime(buffer, size, fmt, tm);
4707         }
4708
4709         return rc;
4710 }
4711
4712 /*
4713  * Print all ost indices associated with a file layout using a commma separated
4714  * list.  For a file with mutliple components, the list of indices for each
4715  * component will be enclosed in brackets.
4716  *
4717  * @param[out]  buffer  Location where OST indices are written
4718  * @param[in]   size    Size of the available buffer.
4719  * @pararm[in]  layout  Pointer to layout structure for the file
4720  * @return              Number of bytes written to output buffer
4721  */
4722 static int printf_format_ost_indices(char *buffer, size_t size,
4723                                 struct llapi_layout *layout)
4724 {
4725         uint64_t count, idx, i;
4726         int err, bytes, wrote = 0;
4727
4728         /* Make sure to start at the first component */
4729         err = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
4730         if (err) {
4731                 llapi_error(LLAPI_MSG_ERROR, err,
4732                             "error: layout component iteration failed\n");
4733                 goto format_done;
4734         }
4735         while (1) {
4736                 err = llapi_layout_stripe_count_get(layout, &count);
4737                 if (err) {
4738                         llapi_error(LLAPI_MSG_ERROR, err,
4739                                     "error: cannot get stripe_count\n");
4740                         goto format_done;
4741                 }
4742
4743                 bytes = snprintf(buffer, (size - wrote), "%s", "[");
4744                 wrote += bytes;
4745                 if (wrote >= size)
4746                         goto format_done;
4747                 buffer += bytes;
4748                 for (i = 0; i < count; i++) {
4749                         err = llapi_layout_ost_index_get(layout, i, &idx);
4750                         if (err) {
4751                                 llapi_error(LLAPI_MSG_ERROR, err,
4752                                             "error: cannot get OST index\n");
4753                                 bytes = snprintf(buffer, (size - wrote),
4754                                                  "%c,", '?');
4755                         } else {
4756                                 bytes = snprintf(buffer, (size - wrote),
4757                                                  "%"PRIu64",", idx);
4758                         }
4759                         wrote += bytes;
4760                         if (wrote >= size)
4761                                 goto format_done;
4762                         buffer += bytes;
4763                 }
4764                 /* Overwrite last comma with closing bracket */
4765                 *(buffer - 1) = ']';
4766
4767                 err = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
4768                 if (err == 0)           /* next component is found */
4769                         continue;
4770                 if (err < 0)
4771                         llapi_error(LLAPI_MSG_ERROR, err,
4772                                     "error: layout component iteration failed\n");
4773                 /* At this point, either got error or reached last component */
4774                 break;
4775         }
4776
4777 format_done:
4778         if (wrote >= size)
4779                 wrote = (size - 1);
4780         return wrote;
4781 }
4782
4783 /*
4784  * Parse Lustre-specific format sequences of the form %L{x}.
4785  *
4786  * @param[in]   seq     String being parsed for format sequence.  The leading
4787  *                      '%' character is not included in this string
4788  * @param[out]  buffer  Location where interpreted format info is written
4789  * @param[in]   size    Size of the available buffer.
4790  * @param[out]  wrote   Number of bytes written to the buffer.
4791  * @param[in]   param   The find_param structure associated with the file/dir
4792  * @param[in]   path    Pathname of the current file/dir being handled
4793  * @param[in]   projid  Project ID associated with the current file/dir
4794  * @param[in]   d       File descriptor for the directory (or -1 for a
4795  *                      non-directory file)
4796  * @return              Number of characters from input string processed
4797  *                      as part of the format (0 for an unknown format)
4798  */
4799 int printf_format_lustre(char *seq, char *buffer, size_t size, int *wrote,
4800                          struct find_param *param, char *path, int projid,
4801                          int d)
4802 {
4803         struct lmv_user_md *lum;
4804         struct lmv_user_mds_data *objects;
4805         struct llapi_layout *layout = NULL;
4806         struct lu_fid fid;
4807         unsigned int hash_type;
4808         uint64_t str_cnt, str_size, idx;
4809         char pool_name[LOV_MAXPOOLNAME + 1] = { '\0' };
4810         int err, bytes, i;
4811         int rc = 2;     /* all current valid sequences are 2 chars */
4812         *wrote = 0;
4813
4814         /* Sanity check.  Formats always look like %L{X} */
4815         if (*seq++ != 'L') {
4816                 rc = 0;
4817                 goto format_done;
4818         }
4819
4820         /*
4821          * Some formats like %LF or %LP are handled the same for both files
4822          * and dirs, so handle all of those here.
4823          */
4824         switch (*seq) {
4825         case 'F':
4826                 err = llapi_path2fid(path, &fid);
4827                 if (err) {
4828                         llapi_error(LLAPI_MSG_ERROR, err,
4829                                     "error: cannot get fid\n");
4830                         goto format_done;
4831                 }
4832                 *wrote = snprintf(buffer, size, DFID_NOBRACE, PFID(&fid));
4833                 goto format_done;
4834         case 'P':
4835                 *wrote = snprintf(buffer, size, "%d", projid);
4836                 goto format_done;
4837         }
4838
4839         /* Other formats for files/dirs need to be handled differently */
4840         if (d == -1) {          /* file */
4841                 //layout = llapi_layout_get_by_xattr(&param->fp_lmd->lmd_lmm,
4842                 //                                 param->fp_lum_size, 0);
4843                 layout = llapi_layout_get_by_path(path, 0);
4844                 if (layout == NULL) {
4845                         llapi_error(LLAPI_MSG_ERROR, errno,
4846                                     "error: cannot get file layout\n");
4847                         goto format_done;
4848                 }
4849
4850                 /*
4851                  * Set the layout pointer to the last init component
4852                  * since that is the component used for most of these
4853                  * formats. (This also works for non-composite files)
4854                  */
4855                 err = llapi_layout_get_last_init_comp(layout);
4856                 if (err) {
4857                         llapi_error(LLAPI_MSG_ERROR, err,
4858                                     "error: cannot get last initialized compomnent\n");
4859                         goto format_done;
4860                 }
4861
4862                 switch (*seq) {
4863                 case 'c':       /* stripe count */
4864                         err = llapi_layout_stripe_count_get(layout, &str_cnt);
4865                         if (err) {
4866                                 llapi_error(LLAPI_MSG_ERROR, err,
4867                                             "error: cannot get stripe_count\n");
4868                                 goto format_done;
4869                         }
4870                         *wrote = snprintf(buffer, size, "%"PRIu64, str_cnt);
4871                         break;
4872                 case 'h':       /* hash info */
4873                         /* Not applicable to files.  Skip it. */
4874                         break;
4875                 case 'i':       /* starting index */
4876                         err = llapi_layout_ost_index_get(layout, 0, &idx);
4877                         if (err) {
4878                                 llapi_error(LLAPI_MSG_ERROR, err,
4879                                             "error: cannot get OST index of last initialized component\n");
4880                                 goto format_done;
4881                         }
4882                         *wrote = snprintf(buffer, size, "%"PRIu64, idx);
4883                         break;
4884                 case 'o':       /* list of object indices */
4885                         *wrote = printf_format_ost_indices(buffer, size, layout);
4886                         break;
4887                 case 'p':       /* pool name */
4888                         err = llapi_layout_pool_name_get(layout, pool_name,
4889                                                          sizeof(pool_name));
4890                         if (err) {
4891                                 llapi_error(LLAPI_MSG_ERROR, rc,
4892                                             "error: cannot get pool name\n");
4893                                 goto format_done;
4894                         }
4895                         *wrote = snprintf(buffer, size, "%s", pool_name);
4896                         break;
4897                 case 'S':       /* stripe size */
4898                         err = llapi_layout_stripe_size_get(layout, &str_size);
4899                         if (err) {
4900                                 llapi_error(LLAPI_MSG_ERROR, rc,
4901                                             "error: cannot get stripe_size\n");
4902                                 goto format_done;
4903                         }
4904                         *wrote = snprintf(buffer, size, "%"PRIu64, str_size);
4905                         break;
4906                 default:
4907                         rc = 0;
4908                         break;
4909                 }
4910         } else {                /* directory */
4911                 lum = (struct lmv_user_md *)param->fp_lmv_md;
4912                 objects = lum->lum_objects;
4913
4914                 switch (*seq) {
4915                 case 'c':       /* stripe count */
4916                         *wrote = snprintf(buffer, size, "%d",
4917                                           (int)lum->lum_stripe_count);
4918                         break;
4919                 case 'h':       /* hash info */
4920                         hash_type = lum->lum_hash_type & LMV_HASH_TYPE_MASK;
4921                         if (hash_type < LMV_HASH_TYPE_MAX)
4922                                 *wrote = snprintf(buffer, size, "%s",
4923                                                   mdt_hash_name[hash_type]);
4924                         else
4925                                 *wrote = snprintf(buffer, size, "%#x",
4926                                                   hash_type);
4927                         break;
4928                 case 'i':       /* starting index */
4929                         *wrote = snprintf(buffer, size, "%d",
4930                                           lum->lum_stripe_offset);
4931                         break;
4932                 case 'o':       /* list of object indices */
4933                         str_cnt = (int) lum->lum_stripe_count;
4934                         *wrote = snprintf(buffer, size, "%s", "[");
4935                         if (*wrote >= size)
4936                                 goto format_done;
4937                         buffer += *wrote;
4938                         for (i = 0; i < str_cnt; i++) {
4939                                 bytes = snprintf(buffer, (size - *wrote),
4940                                                  "%d,", objects[i].lum_mds);
4941                                 *wrote += bytes;
4942                                 if (*wrote >= size)
4943                                         goto format_done;
4944                                 buffer += bytes;
4945                         }
4946                         if (str_cnt == 0) {
4947                                 /* Use lum_offset as the only list entry */
4948                                 bytes = snprintf(buffer, (size - *wrote),
4949                                                 "%d]", lum->lum_stripe_offset);
4950                                 *wrote += bytes;
4951                         } else {
4952                                 /* Overwrite last comma with closing bracket */
4953                                 *(buffer - 1) = ']';
4954                         }
4955                         break;
4956                 case 'p':       /* pool name */
4957                         *wrote = snprintf(buffer, size, "%s",
4958                                           lum->lum_pool_name);
4959                         break;
4960                 case 'S':       /* stripe size */
4961                         /* This has no meaning for directories.  Skip it. */
4962                         break;
4963                 default:
4964                         rc = 0;
4965                         break;
4966                 }
4967         }
4968
4969 format_done:
4970         if (layout != NULL)
4971                 llapi_layout_free(layout);
4972
4973         if (*wrote >= size)
4974                 /* output of snprintf was truncated */
4975                 *wrote = size - 1;
4976
4977         return rc;
4978 }
4979
4980 /*
4981  * Interpret format specifiers beginning with '%'.
4982  *
4983  * @param[in]   seq     String being parsed for format specifier.  The leading
4984  *                      '%' character is not included in this string
4985  * @param[out]  buffer  Location where formatted info is written
4986  * @param[in]   size    Size of the available buffer.
4987  * @param[out]  wrote   Number of bytes written to the buffer.
4988  * @param[in]   param   The find_param structure associated with the file/dir
4989  * @param[in]   path    Pathname of the current file/dir being handled
4990  * @param[in]   projid  Project ID associated with the current file/dir
4991  * @param[in]   d       File descriptor for the directory (or -1 for a
4992  *                      non-directory file)
4993  * @return              Number of characters from input string processed
4994  *                      as part of the format (0 for an unknown format)
4995  */
4996 int printf_format_directive(char *seq, char *buffer, size_t size, int *wrote,
4997                          struct find_param *param, char *path, int projid,
4998                          int d)
4999 {
5000         __u16 mode = param->fp_lmd->lmd_stx.stx_mode;
5001         uint64_t blocks = param->fp_lmd->lmd_stx.stx_blocks;
5002         int rc = 1;  /* most specifiers are single character */
5003
5004         *wrote = 0;
5005
5006         switch (*seq) {
5007         case 'a': case 'A':
5008         case 'c': case 'C':
5009         case 't': case 'T':
5010         case 'w': case 'W':     /* timestamps */
5011                 rc = printf_format_timestamp(seq, buffer, size, wrote, param);
5012                 break;
5013         case 'b':       /* file size (in 512B blocks) */
5014                 *wrote = snprintf(buffer, size, "%"PRIu64, blocks);
5015                 break;
5016         case 'G':       /* GID of owner */
5017                 *wrote = snprintf(buffer, size, "%u",
5018                                    param->fp_lmd->lmd_stx.stx_gid);
5019                 break;
5020         case 'k':       /* file size (in 1K blocks) */
5021                 *wrote = snprintf(buffer, size, "%"PRIu64, (blocks + 1)/2);
5022                 break;
5023         case 'L':       /* Lustre-specific formats */
5024                 rc = printf_format_lustre(seq, buffer, size, wrote, param,
5025                                           path, projid, d);
5026                 break;
5027         case 'm':       /* file mode in octal */
5028                 *wrote = snprintf(buffer, size, "%#o", (mode & (~S_IFMT)));
5029                 break;
5030         case 'p':       /* Path name of file */
5031                 *wrote = snprintf(buffer, size, "%s", path);
5032                 break;
5033         case 's':       /* file size (in bytes) */
5034                 *wrote = snprintf(buffer, size, "%"PRIu64,
5035                                    (uint64_t) param->fp_lmd->lmd_stx.stx_size);
5036                 break;
5037         case 'U':       /* UID of owner */
5038                 *wrote = snprintf(buffer, size, "%u",
5039                                    param->fp_lmd->lmd_stx.stx_uid);
5040                 break;
5041         case 'y':       /* file type */
5042                 if (S_ISREG(mode))
5043                         *buffer = 'f';
5044                 else if (S_ISDIR(mode))
5045                         *buffer = 'd';
5046                 else if (S_ISLNK(mode))
5047                         *buffer = 'l';
5048                 else if (S_ISBLK(mode))
5049                         *buffer = 'b';
5050                 else if (S_ISCHR(mode))
5051                         *buffer = 'c';
5052                 else if (S_ISFIFO(mode))
5053                         *buffer = 'p';
5054                 else if (S_ISSOCK(mode))
5055                         *buffer = 's';
5056                 else
5057                         *buffer = '?';
5058                 *wrote = 1;
5059                 break;
5060         case '%':
5061                 *buffer = '%';
5062                 *wrote = 1;
5063                 break;
5064         default:        /* invalid format specifier */
5065                 rc = 0;
5066                 break;
5067         }
5068
5069         if (*wrote >= size)
5070                 /* output of snprintf was truncated */
5071                 *wrote = size - 1;
5072
5073         return rc;
5074 }
5075
5076 /*
5077  * Parse user-supplied string for the -printf option and interpret any
5078  * '%' format specifiers or '\' escape sequences.
5079  *
5080  * @param[in]   param   The find_param struct containing the -printf string
5081  *                      as well as info about the current file/dir that mathced
5082  *                      the lfs find search criteria
5083  * @param[in]   path    Path name for current file/dir
5084  * @param[in]   projid  Project ID associated with current file/dir
5085  * @param[in]   d       File descriptor for current directory (or -1 for a
5086  *                      non-directory file)
5087  */
5088 void printf_format_string(struct find_param *param, char *path,
5089                            int projid, int d)
5090 {
5091         char output[FORMATTED_BUF_LEN];
5092         char *fmt_char = param->fp_format_printf_str;
5093         char *buff = output;
5094         size_t buff_size;
5095         int rc, written;
5096
5097         buff = output;
5098         *buff = '\0';
5099         buff_size = FORMATTED_BUF_LEN;
5100
5101         /* Always leave one free byte in buffer for trailing NUL */
5102         while (*fmt_char && (buff_size > 1)) {
5103                 rc = 0;
5104                 written = 0;
5105                 if (*fmt_char == '%') {
5106                         rc = printf_format_directive(fmt_char + 1, buff,
5107                                                   buff_size, &written, param,
5108                                                   path, projid, d);
5109                 } else if (*fmt_char == '\\')
5110                         rc = printf_format_escape(fmt_char + 1, buff,
5111                                                   buff_size, &written);
5112
5113                 if (rc > 0) {
5114                         /* Either a '\' escape or '%' format was processed.
5115                          * Increment pointers accordingly.
5116                          */
5117                         fmt_char += (rc + 1);
5118                         buff += written;
5119                         buff_size -= written;
5120                 } else {
5121                         /* Regular char or invalid escape/format.
5122                          * Either way, copy current character.
5123                          */
5124                         *buff++ = *fmt_char++;
5125                         buff_size--;
5126                 }
5127         }
5128
5129         /* Terminate output buffer and print */
5130         *buff = '\0';
5131         llapi_printf(LLAPI_MSG_NORMAL, "%s", output);
5132 }
5133
5134 /*
5135  * Get file/directory project id.
5136  * by the open fd resides on.
5137  * Return 0 and project id on success, or -ve errno.
5138  */
5139 static int fget_projid(int fd, int *projid)
5140 {
5141         struct fsxattr fsx;
5142         int rc;
5143
5144         rc = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
5145         if (rc)
5146                 return -errno;
5147
5148         *projid = fsx.fsx_projid;
5149         return 0;
5150 }
5151
5152 /*
5153  * Check that the file's permissions in *st matches the one in find_param
5154  */
5155 static int check_file_permissions(const struct find_param *param,
5156                         mode_t mode)
5157 {
5158         int decision = 0;
5159
5160         mode &= 07777;
5161
5162         switch (param->fp_perm_sign) {
5163         case LFS_FIND_PERM_EXACT:
5164                 decision = (mode == param->fp_perm);
5165                 break;
5166         case LFS_FIND_PERM_ALL:
5167                 decision = ((mode & param->fp_perm) == param->fp_perm);
5168                 break;
5169         case LFS_FIND_PERM_ANY:
5170                 decision = ((mode & param->fp_perm) != 0);
5171                 break;
5172         }
5173
5174         if ((param->fp_exclude_perm && decision)
5175                 || (!param->fp_exclude_perm && !decision))
5176                 return -1;
5177         else
5178                 return 1;
5179 }
5180
5181 static int cb_find_init(char *path, int p, int *dp,
5182                         void *data, struct dirent64 *de)
5183 {
5184         struct find_param *param = (struct find_param *)data;
5185         struct lov_user_mds_data *lmd = param->fp_lmd;
5186         int d = dp == NULL ? -1 : *dp;
5187         int decision = 1; /* 1 is accepted; -1 is rejected. */
5188         int lustre_fs = 1;
5189         int checked_type = 0;
5190         int ret = 0;
5191         __u32 stripe_count = 0;
5192         __u64 flags;
5193         int fd = -2;
5194         int projid = 0;
5195         bool gather_all = false;
5196
5197         if (p == -1 && d == -1)
5198                 return -EINVAL;
5199
5200         /* Reset this value between invocations */
5201         param->fp_get_lmv = 0;
5202
5203         /* Gather all file/dir info, not just what's needed for search params */
5204         if (param->fp_format_printf_str)
5205                 gather_all = true;
5206
5207         /* If a regular expression is presented, make the initial decision */
5208         if (param->fp_pattern != NULL) {
5209                 char *fname = strrchr(path, '/');
5210
5211                 fname = (fname == NULL ? path : fname + 1);
5212                 ret = fnmatch(param->fp_pattern, fname, 0);
5213                 if ((ret == FNM_NOMATCH && !param->fp_exclude_pattern) ||
5214                     (ret == 0 && param->fp_exclude_pattern))
5215                         goto decided;
5216         }
5217
5218         /* See if we can check the file type from the dirent. */
5219         if (de != NULL && de->d_type != DT_UNKNOWN) {
5220                 if (param->fp_type != 0) {
5221                         checked_type = 1;
5222
5223                         if (DTTOIF(de->d_type) == param->fp_type) {
5224                                 if (param->fp_exclude_type)
5225                                         goto decided;
5226                         } else {
5227                                 if (!param->fp_exclude_type)
5228                                         goto decided;
5229                         }
5230                 }
5231                 if ((param->fp_check_mdt_count || param->fp_hash_type ||
5232                      param->fp_check_hash_flag) && de->d_type != DT_DIR)
5233                         goto decided;
5234         }
5235
5236         ret = 0;
5237
5238         /*
5239          * Request MDS for the stat info if some of these parameters need
5240          * to be compared.
5241          */
5242         if (param->fp_obd_uuid || param->fp_mdt_uuid ||
5243             param->fp_check_uid || param->fp_check_gid ||
5244             param->fp_newerxy || param->fp_btime ||
5245             param->fp_atime || param->fp_mtime || param->fp_ctime ||
5246             param->fp_check_size || param->fp_check_blocks ||
5247             find_check_lmm_info(param) ||
5248             param->fp_check_mdt_count || param->fp_hash_type ||
5249             param->fp_check_hash_flag || param->fp_perm_sign ||
5250             gather_all)
5251                 decision = 0;
5252
5253         if (param->fp_type != 0 && checked_type == 0)
5254                 decision = 0;
5255
5256         if (decision == 0) {
5257                 if (d != -1 &&
5258                     (param->fp_check_mdt_count || param->fp_hash_type ||
5259                      param->fp_check_hash_flag || param->fp_check_foreign ||
5260                      gather_all)) {
5261                         param->fp_get_lmv = 1;
5262                         ret = cb_get_dirstripe(path, &d, param);
5263                         if (ret != 0) {
5264                                 if (errno == ENODATA) {
5265                                         /* Fill in struct for unstriped dir */
5266                                         ret = 0;
5267                                         param->fp_lmv_md->lum_magic = LMV_MAGIC_V1;
5268                                         /* Use 0 until we find actual offset */
5269                                         param->fp_lmv_md->lum_stripe_offset = 0;
5270                                         param->fp_lmv_md->lum_stripe_count = 0;
5271                                         param->fp_lmv_md->lum_hash_type = 0;
5272
5273                                         if (param->fp_check_foreign) {
5274                                                 if (param->fp_exclude_foreign)
5275                                                         goto print;
5276                                                 goto decided;
5277                                         }
5278                                 } else {
5279                                         return ret;
5280                                 }
5281                         }
5282
5283                         if (param->fp_check_mdt_count) {
5284                                 if (lmv_is_foreign(param->fp_lmv_md->lum_magic))
5285                                         goto decided;
5286
5287                                 decision = find_value_cmp(param->fp_lmv_md->lum_stripe_count,
5288                                                           param->fp_mdt_count,
5289                                                           param->fp_mdt_count_sign,
5290                                                           param->fp_exclude_mdt_count, 1, 0);
5291                                 if (decision == -1)
5292                                         goto decided;
5293                         }
5294
5295                         if (param->fp_hash_type) {
5296                                 __u32 found;
5297                                 __u32 type = param->fp_lmv_md->lum_hash_type &
5298                                         LMV_HASH_TYPE_MASK;
5299
5300                                 if (lmv_is_foreign(param->fp_lmv_md->lum_magic))
5301                                         goto decided;
5302
5303                                 found = (1 << type) & param->fp_hash_type;
5304                                 if ((found && param->fp_exclude_hash_type) ||
5305                                     (!found && !param->fp_exclude_hash_type))
5306                                         goto decided;
5307                         }
5308
5309                         if (param->fp_check_hash_flag) {
5310                                 __u32 flags = param->fp_lmv_md->lum_hash_type &
5311                                         ~LMV_HASH_TYPE_MASK;
5312
5313                                 if (lmv_is_foreign(param->fp_lmv_md->lum_magic))
5314                                         goto decided;
5315
5316                                 if (!(flags & param->fp_hash_inflags) ||
5317                                     (flags & param->fp_hash_exflags))
5318                                         goto decided;
5319                         }
5320                 }
5321
5322                 param->fp_lmd->lmd_lmm.lmm_magic = 0;
5323                 ret = get_lmd_info_fd(path, p, d, param->fp_lmd,
5324                                       param->fp_lum_size, GET_LMD_INFO);
5325                 if (ret == 0 && param->fp_lmd->lmd_lmm.lmm_magic == 0 &&
5326                     find_check_lmm_info(param)) {
5327                         struct lov_user_md *lmm = &param->fp_lmd->lmd_lmm;
5328
5329                         /*
5330                          * We need to "fake" the "use the default" values
5331                          * since the lmm struct is zeroed out at this point.
5332                          */
5333                         lmm->lmm_magic = LOV_USER_MAGIC_V1;
5334                         lmm->lmm_pattern = LOV_PATTERN_DEFAULT;
5335                         if (!param->fp_raw)
5336                                 ostid_set_seq(&lmm->lmm_oi,
5337                                               FID_SEQ_LOV_DEFAULT);
5338                         lmm->lmm_stripe_size = 0;
5339                         lmm->lmm_stripe_count = 0;
5340                         lmm->lmm_stripe_offset = -1;
5341                 }
5342                 if (ret == 0 && (param->fp_mdt_uuid != NULL || gather_all)) {
5343                         if (d != -1) {
5344                                 ret = llapi_file_fget_mdtidx(d,
5345                                                      &param->fp_file_mdt_index);
5346                                 /*
5347                                  *  Make sure lum_stripe_offset matches
5348                                  *  mdt_index even for unstriped directories.
5349                                  */
5350                                 if (ret == 0 && param->fp_get_lmv)
5351                                         param->fp_lmv_md->lum_stripe_offset =
5352                                                 param->fp_file_mdt_index;
5353                         } else if (S_ISREG(lmd->lmd_stx.stx_mode)) {
5354                                 /*
5355                                  * FIXME: we could get the MDT index from the
5356                                  * file's FID in lmd->lmd_lmm.lmm_oi without
5357                                  * opening the file, once we are sure that
5358                                  * LFSCK2 (2.6) has fixed up pre-2.0 LOV EAs.
5359                                  * That would still be an ioctl() to map the
5360                                  * FID to the MDT, but not an open RPC.
5361                                  */
5362                                 fd = open(path, O_RDONLY);
5363                                 if (fd > 0) {
5364                                         ret = llapi_file_fget_mdtidx(fd,
5365                                                      &param->fp_file_mdt_index);
5366                                 } else {
5367                                         ret = -errno;
5368                                 }
5369                         } else {
5370                                 /*
5371                                  * For a special file, we assume it resides on
5372                                  * the same MDT as the parent directory.
5373                                  */
5374                                 ret = llapi_file_fget_mdtidx(p,
5375                                                      &param->fp_file_mdt_index);
5376                         }
5377                 }
5378                 if (ret != 0) {
5379                         if (ret == -ENOTTY)
5380                                 lustre_fs = 0;
5381                         if (ret == -ENOENT)
5382                                 goto decided;
5383
5384                         goto out;
5385                 } else {
5386                         stripe_count = find_get_stripe_count(param);
5387                 }
5388         }
5389
5390         /* Check the file permissions from the stat info */
5391         if (param->fp_perm_sign) {
5392                 decision = check_file_permissions(param, lmd->lmd_stx.stx_mode);
5393                 if (decision == -1)
5394                         goto decided;
5395         }
5396
5397         if (param->fp_type && !checked_type) {
5398                 if ((param->fp_check_mdt_count || param->fp_check_hash_flag ||
5399                      param->fp_hash_type) && !S_ISDIR(lmd->lmd_stx.stx_mode))
5400                         goto decided;
5401
5402                 if ((lmd->lmd_stx.stx_mode & S_IFMT) == param->fp_type) {
5403                         if (param->fp_exclude_type)
5404                                 goto decided;
5405                 } else {
5406                         if (!param->fp_exclude_type)
5407                                 goto decided;
5408                 }
5409         }
5410
5411         /* Prepare odb. */
5412         if (param->fp_obd_uuid || param->fp_mdt_uuid) {
5413                 if (lustre_fs && param->fp_got_uuids &&
5414                     param->fp_dev != makedev(lmd->lmd_stx.stx_dev_major,
5415                                              lmd->lmd_stx.stx_dev_minor)) {
5416                         /* A lustre/lustre mount point is crossed. */
5417                         param->fp_got_uuids = 0;
5418                         param->fp_obds_printed = 0;
5419                         param->fp_mdt_index = OBD_NOT_FOUND;
5420                         param->fp_obd_index = OBD_NOT_FOUND;
5421                 }
5422
5423                 if (lustre_fs && !param->fp_got_uuids) {
5424                         ret = setup_target_indexes((d != -1) ? d : p, path,
5425                                                    param);
5426                         if (ret)
5427                                 goto out;
5428
5429                         param->fp_dev = makedev(lmd->lmd_stx.stx_dev_major,
5430                                                 lmd->lmd_stx.stx_dev_minor);
5431                 } else if (!lustre_fs && param->fp_got_uuids) {
5432                         /* A lustre/non-lustre mount point is crossed. */
5433                         param->fp_got_uuids = 0;
5434                         param->fp_mdt_index = OBD_NOT_FOUND;
5435                         param->fp_obd_index = OBD_NOT_FOUND;
5436                 }
5437         }
5438
5439         if (param->fp_check_foreign) {
5440                 decision = find_check_foreign(param);
5441                 if (decision == -1)
5442                         goto decided;
5443         }
5444
5445         if (param->fp_check_stripe_size) {
5446                 decision = find_check_stripe_size(param);
5447                 if (decision == -1)
5448                         goto decided;
5449         }
5450
5451         if (param->fp_check_ext_size) {
5452                 decision = find_check_ext_size(param);
5453                 if (decision == -1)
5454                         goto decided;
5455         }
5456
5457         if (param->fp_check_stripe_count) {
5458                 decision = find_value_cmp(stripe_count, param->fp_stripe_count,
5459                                           param->fp_stripe_count_sign,
5460                                           param->fp_exclude_stripe_count, 1, 0);
5461                 if (decision == -1)
5462                         goto decided;
5463         }
5464
5465         if (param->fp_check_layout) {
5466                 decision = find_check_layout(param);
5467                 if (decision == -1)
5468                         goto decided;
5469         }
5470
5471         /* If an OBD UUID is specified but none matches, skip this file. */
5472         if ((param->fp_obd_uuid && param->fp_obd_index == OBD_NOT_FOUND) ||
5473             (param->fp_mdt_uuid && param->fp_mdt_index == OBD_NOT_FOUND))
5474                 goto decided;
5475
5476         /*
5477          * If an OST or MDT UUID is given, and some OST matches,
5478          * check it here.
5479          */
5480         if (param->fp_obd_index != OBD_NOT_FOUND ||
5481             param->fp_mdt_index != OBD_NOT_FOUND) {
5482                 if (param->fp_obd_uuid) {
5483                         if (check_obd_match(param)) {
5484                                 /*
5485                                  * If no mdtuuid is given, we are done.
5486                                  * Otherwise, fall through to the mdtuuid
5487                                  * check below.
5488                                  */
5489                                 if (!param->fp_mdt_uuid)
5490                                         goto obd_matches;
5491                         } else {
5492                                 goto decided;
5493                         }
5494                 }
5495
5496                 if (param->fp_mdt_uuid) {
5497                         if (check_mdt_match(param))
5498                                 goto obd_matches;
5499                         goto decided;
5500                 }
5501         }
5502
5503 obd_matches:
5504         if (param->fp_check_uid) {
5505                 if (lmd->lmd_stx.stx_uid == param->fp_uid) {
5506                         if (param->fp_exclude_uid)
5507                                 goto decided;
5508                 } else {
5509                         if (!param->fp_exclude_uid)
5510                                 goto decided;
5511                 }
5512         }
5513
5514         if (param->fp_check_gid) {
5515                 if (lmd->lmd_stx.stx_gid == param->fp_gid) {
5516                         if (param->fp_exclude_gid)
5517                                 goto decided;
5518                 } else {
5519                         if (!param->fp_exclude_gid)
5520                                 goto decided;
5521                 }
5522         }
5523
5524         if (param->fp_check_projid || gather_all) {
5525                 int projid = 0;
5526
5527                 if (fd == -2)
5528                         fd = open(path, O_RDONLY);
5529
5530                 if (fd > 0)
5531                         ret = fget_projid(fd, &projid);
5532                 else
5533                         ret = -errno;
5534                 if (ret)
5535                         goto out;
5536                 if (projid == param->fp_projid) {
5537                         if (param->fp_exclude_projid)
5538                                 goto decided;
5539                 } else {
5540                         if (!param->fp_exclude_projid)
5541                                 goto decided;
5542                 }
5543         }
5544
5545         if (param->fp_check_pool) {
5546                 decision = find_check_pool(param);
5547                 if (decision == -1)
5548                         goto decided;
5549         }
5550
5551         if (param->fp_check_comp_count || param->fp_check_comp_flags ||
5552             param->fp_check_comp_start || param->fp_check_comp_end) {
5553                 decision = find_check_comp_options(param);
5554                 if (decision == -1)
5555                         goto decided;
5556         }
5557
5558         if (param->fp_check_mirror_count || param->fp_check_mirror_state) {
5559                 decision = find_check_mirror_options(param);
5560                 if (decision == -1)
5561                         goto decided;
5562         }
5563
5564         /* Check the time on mds. */
5565         decision = 1;
5566         if (param->fp_atime || param->fp_mtime || param->fp_ctime) {
5567                 int for_mds;
5568
5569                 for_mds = lustre_fs ?
5570                           (S_ISREG(lmd->lmd_stx.stx_mode) && stripe_count) : 0;
5571                 decision = find_time_check(param, for_mds);
5572                 if (decision == -1)
5573                         goto decided;
5574         }
5575
5576         if (param->fp_btime) {
5577                 if (!(lmd->lmd_stx.stx_mask & STATX_BTIME)) {
5578                         ret = -EOPNOTSUPP;
5579                         goto out;
5580                 }
5581
5582                 decision = find_value_cmp(lmd->lmd_stx.stx_btime.tv_sec,
5583                                           param->fp_btime, param->fp_bsign,
5584                                           param->fp_exclude_btime,
5585                                           param->fp_time_margin, 0);
5586                 if (decision == -1)
5587                         goto decided;
5588         }
5589
5590         if (param->fp_newerxy) {
5591                 int for_mds;
5592
5593                 for_mds = lustre_fs ?
5594                           (S_ISREG(lmd->lmd_stx.stx_mode) && stripe_count) : 0;
5595                 decision = find_newerxy_check(param, for_mds, true);
5596                 if (decision == -1)
5597                         goto decided;
5598                 if (decision < 0) {
5599                         ret = decision;
5600                         goto out;
5601                 }
5602         }
5603
5604         flags = param->fp_lmd->lmd_flags;
5605         if (param->fp_check_size &&
5606             ((S_ISREG(lmd->lmd_stx.stx_mode) && stripe_count) ||
5607               S_ISDIR(lmd->lmd_stx.stx_mode)) &&
5608             !(flags & OBD_MD_FLSIZE ||
5609               (param->fp_lazy && flags & OBD_MD_FLLAZYSIZE)))
5610                 decision = 0;
5611
5612         if (param->fp_check_blocks &&
5613             ((S_ISREG(lmd->lmd_stx.stx_mode) && stripe_count) ||
5614               S_ISDIR(lmd->lmd_stx.stx_mode)) &&
5615             !(flags & OBD_MD_FLBLOCKS ||
5616               (param->fp_lazy && flags & OBD_MD_FLLAZYBLOCKS)))
5617                 decision = 0;
5618
5619         /*
5620          * If file still fits the request, ask ost for updated info.
5621          * The regular stat is almost of the same speed as some new
5622          * 'glimpse-size-ioctl'.
5623          */
5624         if (!decision || gather_all) {
5625                 lstat_t st;
5626
5627                 /*
5628                  * For regular files with the stripe the decision may have not
5629                  * been taken yet if *time or size is to be checked.
5630                  */
5631                 if (param->fp_obd_index != OBD_NOT_FOUND)
5632                         print_failed_tgt(param, path, LL_STATFS_LOV);
5633
5634                 if (param->fp_mdt_index != OBD_NOT_FOUND)
5635                         print_failed_tgt(param, path, LL_STATFS_LMV);
5636
5637                 if (d != -1)
5638                         ret = fstat_f(d, &st);
5639                 else if (de != NULL)
5640                         ret = fstatat_f(p, de->d_name, &st,
5641                                         AT_SYMLINK_NOFOLLOW);
5642                 else
5643                         ret = lstat_f(path, &st);
5644
5645                 if (ret) {
5646                         if (errno == ENOENT) {
5647                                 llapi_error(LLAPI_MSG_ERROR, -ENOENT,
5648                                             "warning: %s: %s does not exist",
5649                                             __func__, path);
5650                                 goto decided;
5651                         } else {
5652                                 ret = -errno;
5653                                 llapi_error(LLAPI_MSG_ERROR, ret,
5654                                             "%s: stat on %s failed",
5655                                             __func__, path);
5656                                 goto out;
5657                         }
5658                 }
5659
5660                 convert_lmd_statx(param->fp_lmd, &st, true);
5661                 /* Check the time on osc. */
5662                 decision = find_time_check(param, 0);
5663                 if (decision == -1)
5664                         goto decided;
5665
5666                 if (param->fp_newerxy) {
5667                         decision = find_newerxy_check(param, 0, false);
5668                         if (decision == -1)
5669                                 goto decided;
5670                         if (decision < 0) {
5671                                 ret = decision;
5672                                 goto out;
5673                         }
5674                 }
5675         }
5676
5677         if (param->fp_check_size) {
5678                 decision = find_value_cmp(lmd->lmd_stx.stx_size,
5679                                           param->fp_size,
5680                                           param->fp_size_sign,
5681                                           param->fp_exclude_size,
5682                                           param->fp_size_units, 0);
5683                 if (decision == -1)
5684                         goto decided;
5685         }
5686
5687         if (param->fp_check_blocks) { /* convert st_blocks to bytes */
5688                 decision = find_value_cmp(lmd->lmd_stx.stx_blocks * 512,
5689                                           param->fp_blocks,
5690                                           param->fp_blocks_sign,
5691                                           param->fp_exclude_blocks,
5692                                           param->fp_blocks_units, 0);
5693                 if (decision == -1)
5694                         goto decided;
5695         }
5696
5697 print:
5698         if (param->fp_format_printf_str)
5699                 printf_format_string(param, path, projid, d);
5700         else
5701                 llapi_printf(LLAPI_MSG_NORMAL, "%s%c", path,
5702                              param->fp_zero_end ? '\0' : '\n');
5703
5704 decided:
5705         ret = 0;
5706         /* Do not get down anymore? */
5707         if (param->fp_depth == param->fp_max_depth) {
5708                 ret = 1;
5709                 goto out;
5710         }
5711         param->fp_depth++;
5712 out:
5713         if (fd > 0)
5714                 close(fd);
5715         return ret;
5716 }
5717
5718 static int cb_migrate_mdt_init(char *path, int p, int *dp,
5719                                void *param_data, struct dirent64 *de)
5720 {
5721         struct find_param *param = (struct find_param *)param_data;
5722         struct lmv_user_md *lmu = param->fp_lmv_md;
5723         int tmp_p = p;
5724         char raw[MAX_IOC_BUFLEN] = {'\0'};
5725         char *rawbuf = raw;
5726         struct obd_ioctl_data data = { 0 };
5727         int ret;
5728         char *path_copy;
5729         char *filename;
5730         bool retry = false;
5731
5732         if (p == -1 && dp == NULL)
5733                 return -EINVAL;
5734
5735         if (!lmu)
5736                 return -EINVAL;
5737
5738         if (dp != NULL && *dp != -1)
5739                 close(*dp);
5740
5741         if (p == -1) {
5742                 tmp_p = open_parent(path);
5743                 if (tmp_p == -1) {
5744                         *dp = -1;
5745                         ret = -errno;
5746                         llapi_error(LLAPI_MSG_ERROR, ret,
5747                                     "can not open %s", path);
5748                         return ret;
5749                 }
5750         }
5751
5752         path_copy = strdup(path);
5753         filename = basename(path_copy);
5754
5755         data.ioc_inlbuf1 = (char *)filename;
5756         data.ioc_inllen1 = strlen(filename) + 1;
5757         data.ioc_inlbuf2 = (char *)lmu;
5758         data.ioc_inllen2 = lmv_user_md_size(lmu->lum_stripe_count,
5759                                             lmu->lum_magic);
5760         /* reach bottom? */
5761         if (param->fp_depth == param->fp_max_depth)
5762                 data.ioc_type = MDS_MIGRATE_NSONLY;
5763         ret = llapi_ioctl_pack(&data, &rawbuf, sizeof(raw));
5764         if (ret != 0) {
5765                 llapi_error(LLAPI_MSG_ERROR, ret,
5766                             "%s: error packing ioctl data", __func__);
5767                 goto out;
5768         }
5769
5770 migrate:
5771         ret = ioctl(tmp_p, LL_IOC_MIGRATE, rawbuf);
5772         if (ret != 0) {
5773                 if (errno == EBUSY && !retry) {
5774                         /*
5775                          * because migrate may not be able to lock all involved
5776                          * objects in order, for some of them it try lock, while
5777                          * there may be conflicting COS locks and cause migrate
5778                          * fail with EBUSY, hope a sync() could cause
5779                          * transaction commit and release these COS locks.
5780                          */
5781                         sync();
5782                         retry = true;
5783                         goto migrate;
5784                 } else if (errno == EALREADY) {
5785                         if (param->fp_verbose & VERBOSE_DETAIL)
5786                                 llapi_printf(LLAPI_MSG_NORMAL,
5787                                              "%s migrated to MDT%d already\n",
5788                                              path, lmu->lum_stripe_offset);
5789                         ret = 0;
5790                 } else {
5791                         ret = -errno;
5792                         llapi_error(LLAPI_MSG_ERROR, ret, "%s migrate failed",
5793                                     path);
5794                         goto out;
5795                 }
5796         } else if (param->fp_verbose & VERBOSE_DETAIL) {
5797                 llapi_printf(LLAPI_MSG_NORMAL,
5798                              "migrate %s to MDT%d stripe count %d\n",
5799                              path, lmu->lum_stripe_offset,
5800                              lmu->lum_stripe_count);
5801         }
5802
5803 out:
5804         /* Do not get down anymore? */
5805         if (param->fp_depth == param->fp_max_depth)
5806                 ret = 1;
5807         else
5808                 param->fp_depth++;
5809
5810         if (dp != NULL) {
5811                 /*
5812                  * If the directory is being migration, we need
5813                  * close the directory after migration,
5814                  * so the old directory cache will be cleanup
5815                  * on the client side, and re-open to get the
5816                  * new directory handle
5817                  */
5818                 *dp = open(path, O_RDONLY|O_NDELAY|O_DIRECTORY);
5819                 if (*dp == -1) {
5820                         ret = -errno;
5821                         llapi_error(LLAPI_MSG_ERROR, ret,
5822                                     "%s: Failed to open '%s'", __func__, path);
5823                 }
5824         }
5825
5826         if (p == -1)
5827                 close(tmp_p);
5828
5829         free(path_copy);
5830
5831         return ret;
5832 }
5833
5834 /* dir migration finished, shrink its stripes */
5835 static int cb_migrate_mdt_fini(char *path, int p, int *dp, void *data,
5836                                struct dirent64 *de)
5837 {
5838         struct find_param *param = data;
5839         struct lmv_user_md *lmu = param->fp_lmv_md;
5840         int lmulen = lmv_user_md_size(lmu->lum_stripe_count, lmu->lum_magic);
5841         int ret = 0;
5842
5843         if (de && de->d_type != DT_DIR)
5844                 goto out;
5845
5846         if (*dp != -1) {
5847                 /*
5848                  * close it before setxattr because the latter may destroy the
5849                  * original object, and cause close fail.
5850                  */
5851                 ret = close(*dp);
5852                 *dp = -1;
5853                 if (ret)
5854                         goto out;
5855         }
5856
5857         ret = setxattr(path, XATTR_NAME_LMV, lmu, lmulen, 0);
5858         if (ret == -EALREADY)
5859                 ret = 0;
5860 out:
5861         cb_common_fini(path, p, dp, data, de);
5862         return ret;
5863 }
5864
5865 int llapi_migrate_mdt(char *path, struct find_param *param)
5866 {
5867         param->fp_stop_on_error = 1;
5868         return param_callback(path, cb_migrate_mdt_init, cb_migrate_mdt_fini,
5869                               param);
5870 }
5871
5872 int llapi_mv(char *path, struct find_param *param)
5873 {
5874 #if LUSTRE_VERSION_CODE > OBD_OCD_VERSION(2, 9, 59, 0)
5875         static bool printed;
5876
5877         if (!printed) {
5878                 llapi_error(LLAPI_MSG_ERROR, -ESTALE,
5879                           "%s() is deprecated, use llapi_migrate_mdt() instead",
5880                           __func__);
5881                 printed = true;
5882         }
5883 #endif
5884         return llapi_migrate_mdt(path, param);
5885 }
5886
5887 /*
5888  * Check string for escape sequences and print a message to stdout
5889  * if any invalid escapes are found.
5890  *
5891  * @param[in]   c       Pointer to character immediately following the
5892  *                      '\' character indicating the start of an escape
5893  *                      sequence.
5894  * @return              Number of characters examined in the escape sequence
5895  *                      (regardless of whether the sequence is valid or not).
5896  */
5897 int validate_printf_esc(char *c)
5898 {
5899         char *valid_esc = "nt\\";
5900
5901         if (*c == '\0') {
5902                  /* backslash at end of string */
5903                 llapi_err_noerrno(LLAPI_MSG_WARN,
5904                         "warning: '\\' at end of -printf format string\n");
5905                 return 0;
5906         }
5907
5908         if (!strchr(valid_esc, *c))
5909                 /* Invalid escape character */
5910                 llapi_err_noerrno(LLAPI_MSG_WARN,
5911                         "warning: unrecognized escape: '\\%c'\n", *c);
5912
5913         return 1;
5914 }
5915
5916 /*
5917  * Check string for format directives and print a message to stdout
5918  * if any invalid directives are found.
5919  *
5920  * @param[in]   c       Pointer to character immediately following the
5921  *                      '%' character indicating the start of a format
5922  *                      directive.
5923  * @return              Number of characters examined in the format directive
5924  *                      (regardless of whether the directive is valid or not).
5925  */
5926 int validate_printf_fmt(char *c)
5927 {
5928         char *valid_fmt_single = "abcGkmpstUwy%";
5929         char *valid_fmt_double = "ACTW";
5930         char *valid_fmt_lustre = "cFhioPpS";
5931         char curr = *c, next;
5932
5933         if (curr == '\0') {
5934                 llapi_err_noerrno(LLAPI_MSG_WARN,
5935                         "warning: '%%' at end of -printf format string\n");
5936                 return 0;
5937         }
5938
5939         next = *(c + 1);
5940         if ((next == '\0') || (next == '%') || (next == '\\'))
5941                 /* Treat as single char format directive */
5942                 goto check_single;
5943
5944         /* Check format directives with multiple characters */
5945         if (strchr(valid_fmt_double, curr)) {
5946                 /* For now, only valid formats are followed by '@' char */
5947                 if (next != '@')
5948                         llapi_err_noerrno(LLAPI_MSG_WARN,
5949                                 "warning: unrecognized format directive: '%%%c%c'\n",
5950                                 curr, next);
5951                 return 2;
5952         }
5953
5954         /* Lustre formats always start with 'L' */
5955         if (curr == 'L') {
5956                 if (!strchr(valid_fmt_lustre, next))
5957                         llapi_err_noerrno(LLAPI_MSG_WARN,
5958                                 "warning: unrecognized format directive: '%%%c%c'\n",
5959                                 curr, next);
5960                 return 2;
5961         }
5962
5963 check_single:
5964
5965         if (!strchr(valid_fmt_single, curr))
5966                 llapi_err_noerrno(LLAPI_MSG_WARN,
5967                         "warning: unrecognized format directive: '%%%c'\n", curr);
5968         return 1;
5969 }
5970
5971 /*
5972  * Validate the user-supplied string for the -printf option and report
5973  * any invalid backslash escape sequences or format directives.
5974  *
5975  * @param[in]   param   Structure containing info about invocation of lfs find
5976  * @return              None
5977  */
5978 void validate_printf_str(struct find_param *param)
5979 {
5980         char *c = param->fp_format_printf_str;
5981         int ret = 0;
5982
5983         while (*c) {
5984                 switch (*c) {
5985                 case '%':
5986                         ret = validate_printf_fmt(++c);
5987                         c += ret;
5988                         break;
5989                 case '\\':
5990                         ret = validate_printf_esc(++c);
5991                         c += ret;
5992                         break;
5993                 default:
5994                         c++;
5995                         break;
5996                 }
5997         }
5998 }
5999
6000 int llapi_find(char *path, struct find_param *param)
6001 {
6002         if (param->fp_format_printf_str)
6003                 validate_printf_str(param);
6004         return param_callback(path, cb_find_init, cb_common_fini, param);
6005 }
6006
6007 /*
6008  * Get MDT number that the file/directory inode referenced
6009  * by the open fd resides on.
6010  * Return 0 and mdtidx on success, or -ve errno.
6011  */
6012 int llapi_file_fget_mdtidx(int fd, int *mdtidx)
6013 {
6014         if (ioctl(fd, LL_IOC_GET_MDTIDX, mdtidx) < 0)
6015                 return -errno;
6016         return 0;
6017 }
6018
6019 static int cb_get_mdt_index(char *path, int p, int *dp, void *data,
6020                             struct dirent64 *de)
6021 {
6022         struct find_param *param = (struct find_param *)data;
6023         int d = dp == NULL ? -1 : *dp;
6024         int ret;
6025         int mdtidx;
6026
6027         if (p == -1 && d == -1)
6028                 return -EINVAL;
6029
6030         if (d != -1) {
6031                 ret = llapi_file_fget_mdtidx(d, &mdtidx);
6032         } else /* if (p != -1) */ {
6033                 int fd;
6034
6035                 fd = open(path, O_RDONLY | O_NOCTTY);
6036                 if (fd > 0) {
6037                         ret = llapi_file_fget_mdtidx(fd, &mdtidx);
6038                         close(fd);
6039                 } else {
6040                         ret = -errno;
6041                 }
6042         }
6043
6044         if (ret != 0) {
6045                 if (ret == -ENODATA) {
6046                         if (!param->fp_obd_uuid)
6047                                 llapi_printf(LLAPI_MSG_NORMAL,
6048                                              "'%s' has no stripe info\n", path);
6049                         goto out;
6050                 } else if (ret == -ENOENT) {
6051                         llapi_error(LLAPI_MSG_WARN, ret,
6052                                     "warning: %s: '%s' does not exist",
6053                                     __func__, path);
6054                         goto out;
6055                 } else if (ret == -ENOTTY) {
6056                         llapi_error(LLAPI_MSG_ERROR, ret,
6057                                     "%s: '%s' not on a Lustre fs",
6058                                     __func__, path);
6059                 } else {
6060                         llapi_error(LLAPI_MSG_ERROR, ret,
6061                                     "error: %s: '%s' failed get_mdtidx",
6062                                     __func__, path);
6063                 }
6064                 return ret;
6065         }
6066
6067         if (param->fp_quiet || !(param->fp_verbose & VERBOSE_DETAIL))
6068                 llapi_printf(LLAPI_MSG_NORMAL, "%d\n", mdtidx);
6069         else
6070                 llapi_printf(LLAPI_MSG_NORMAL, "%s\nmdt_index:\t%d\n",
6071                              path, mdtidx);
6072
6073 out:
6074         /* Do not go down anymore? */
6075         if (param->fp_depth == param->fp_max_depth)
6076                 return 1;
6077
6078         param->fp_depth++;
6079
6080         return 0;
6081 }
6082
6083 static int cb_getstripe(char *path, int p, int *dp, void *data,
6084                         struct dirent64 *de)
6085 {
6086         struct find_param *param = (struct find_param *)data;
6087         int d = dp == NULL ? -1 : *dp;
6088         int ret = 0;
6089
6090         if (p == -1 && d == -1)
6091                 return -EINVAL;
6092
6093         if (param->fp_obd_uuid) {
6094                 param->fp_quiet = 1;
6095                 ret = setup_obd_uuid(d != -1 ? d : p, path, param);
6096                 if (ret)
6097                         return ret;
6098         }
6099
6100         if (d != -1 && (param->fp_get_lmv || param->fp_get_default_lmv))
6101                 ret = cb_get_dirstripe(path, &d, param);
6102         else if (d != -1 ||
6103                  (p != -1 && !param->fp_get_lmv && !param->fp_get_default_lmv))
6104                 ret = get_lmd_info_fd(path, p, d, &param->fp_lmd->lmd_lmm,
6105                                       param->fp_lum_size, GET_LMD_STRIPE);
6106         else if (d == -1 && (param->fp_get_lmv || param->fp_get_default_lmv)) {
6107                 /* in case of a dangling or valid faked symlink dir, opendir()
6108                  * should have return either EINVAL or ENOENT, so let's try
6109                  * to get LMV just in case, and by opening it as a file but
6110                  * with O_NOFOLLOW ...
6111                  */
6112                 int fd = open(path, O_RDONLY | O_NOFOLLOW);
6113
6114                 if (fd == -1)
6115                         return 0;
6116                 ret = cb_get_dirstripe(path, &fd, param);
6117                 if (ret == 0)
6118                         llapi_lov_dump_user_lmm(param, path, LDF_IS_DIR);
6119                 close(fd);
6120                 return 0;
6121         } else
6122                 return 0;
6123
6124         if (ret) {
6125                 if (errno == ENODATA && d != -1) {
6126                         /*
6127                          * We need to "fake" the "use the default" values
6128                          * since the lmm struct is zeroed out at this point.
6129                          * The magic needs to be set in order to satisfy
6130                          * a check later on in the code path.
6131                          * The object_seq needs to be set for the "(Default)"
6132                          * prefix to be displayed.
6133                          */
6134                         if (param->fp_get_default_lmv) {
6135                                 struct lmv_user_md *lum = param->fp_lmv_md;
6136
6137                                 lum->lum_magic = LMV_USER_MAGIC;
6138                                 lum->lum_stripe_count = 0;
6139                                 lum->lum_stripe_offset = LMV_OFFSET_DEFAULT;
6140                                 goto dump;
6141                         } else if (param->fp_get_lmv) {
6142                                 struct lmv_user_md *lum = param->fp_lmv_md;
6143                                 int mdtidx;
6144
6145                                 ret = llapi_file_fget_mdtidx(d, &mdtidx);
6146                                 if (ret != 0)
6147                                         goto err_out;
6148                                 lum->lum_magic = LMV_MAGIC_V1;
6149                                 lum->lum_stripe_count = 0;
6150                                 lum->lum_stripe_offset = mdtidx;
6151                                 goto dump;
6152                         } else {
6153                                 struct lov_user_md *lmm =
6154                                         &param->fp_lmd->lmd_lmm;
6155
6156                                 lmm->lmm_magic = LOV_USER_MAGIC_V1;
6157                                 if (!param->fp_raw)
6158                                         ostid_set_seq(&lmm->lmm_oi,
6159                                                       FID_SEQ_LOV_DEFAULT);
6160                                 lmm->lmm_stripe_count = 0;
6161                                 lmm->lmm_stripe_size = 0;
6162                                 lmm->lmm_stripe_offset = -1;
6163                                 goto dump;
6164                         }
6165                 } else if (errno == ENODATA && p != -1) {
6166                         if (!param->fp_obd_uuid && !param->fp_mdt_uuid)
6167                                 llapi_printf(LLAPI_MSG_NORMAL,
6168                                              "%s has no stripe info\n", path);
6169                         goto out;
6170                 } else if (errno == ENOENT) {
6171                         llapi_error(LLAPI_MSG_WARN, -ENOENT,
6172                                     "warning: %s: %s does not exist",
6173                                     __func__, path);
6174                         goto out;
6175                 } else if (errno == ENOTTY) {
6176                         ret = -errno;
6177                         llapi_error(LLAPI_MSG_ERROR, ret,
6178                                     "%s: '%s' not on a Lustre fs?",
6179                                     __func__, path);
6180                 } else {
6181                         ret = -errno;
6182 err_out:
6183                         llapi_error(LLAPI_MSG_ERROR, ret,
6184                                     "error: %s: %s failed for %s",
6185                                      __func__, d != -1 ?
6186                                                "LL_IOC_LOV_GETSTRIPE" :
6187                                                "IOC_MDC_GETFILESTRIPE", path);
6188                 }
6189
6190                 return ret;
6191         }
6192
6193 dump:
6194         if (!(param->fp_verbose & VERBOSE_MDTINDEX))
6195                 llapi_lov_dump_user_lmm(param, path, d != -1 ? LDF_IS_DIR : 0);
6196
6197 out:
6198         /* Do not get down anymore? */
6199         if (param->fp_depth == param->fp_max_depth)
6200                 return 1;
6201
6202         param->fp_depth++;
6203
6204         return 0;
6205 }
6206
6207 int llapi_getstripe(char *path, struct find_param *param)
6208 {
6209         return param_callback(path, (param->fp_verbose & VERBOSE_MDTINDEX) ?
6210                               cb_get_mdt_index : cb_getstripe,
6211                               cb_common_fini, param);
6212 }
6213
6214 int llapi_obd_fstatfs(int fd, __u32 type, __u32 index,
6215                       struct obd_statfs *stat_buf, struct obd_uuid *uuid_buf)
6216 {
6217         char raw[MAX_IOC_BUFLEN] = {'\0'};
6218         char *rawbuf = raw;
6219         struct obd_ioctl_data data = { 0 };
6220         int rc = 0;
6221
6222         data.ioc_inlbuf1 = (char *)&type;
6223         data.ioc_inllen1 = sizeof(__u32);
6224         data.ioc_inlbuf2 = (char *)&index;
6225         data.ioc_inllen2 = sizeof(__u32);
6226         data.ioc_pbuf1 = (char *)stat_buf;
6227         data.ioc_plen1 = sizeof(struct obd_statfs);
6228         data.ioc_pbuf2 = (char *)uuid_buf;
6229         data.ioc_plen2 = sizeof(struct obd_uuid);
6230
6231         rc = llapi_ioctl_pack(&data, &rawbuf, sizeof(raw));
6232         if (rc != 0) {
6233                 llapi_error(LLAPI_MSG_ERROR, rc,
6234                             "%s: error packing ioctl data", __func__);
6235                 return rc;
6236         }
6237
6238         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
6239
6240         return rc < 0 ? -errno : 0;
6241 }
6242
6243 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
6244                      struct obd_statfs *stat_buf, struct obd_uuid *uuid_buf)
6245 {
6246         int fd;
6247         int rc;
6248
6249         fd = open(path, O_RDONLY);
6250         if (fd < 0) {
6251                 rc = -errno;
6252                 llapi_error(LLAPI_MSG_ERROR, rc, "error: %s: opening '%s'",
6253                             __func__, path);
6254                 /*
6255                  * If we can't even open a file on the filesystem (e.g. with
6256                  * -ESHUTDOWN), force caller to exit or it will loop forever.
6257                  */
6258                 return -ENODEV;
6259         }
6260
6261         rc = llapi_obd_fstatfs(fd, type, index, stat_buf, uuid_buf);
6262
6263         close(fd);
6264
6265         return rc;
6266 }
6267
6268 #define MAX_STRING_SIZE 128
6269
6270 int llapi_ping(char *obd_type, char *obd_name)
6271 {
6272         int flags = O_RDONLY;
6273         char buf[1] = { 0 };
6274         glob_t path;
6275         int rc, fd;
6276
6277         rc = cfs_get_param_paths(&path, "%s/%s/ping",
6278                                 obd_type, obd_name);
6279         if (rc != 0)
6280                 return -errno;
6281 retry_open:
6282         fd = open(path.gl_pathv[0], flags);
6283         if (fd < 0) {
6284                 if (errno == EACCES && flags == O_RDONLY) {
6285                         flags = O_WRONLY;
6286                         goto retry_open;
6287                 }
6288                 rc = -errno;
6289                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s",
6290                             path.gl_pathv[0]);
6291                 goto failed;
6292         }
6293
6294         if (flags == O_RDONLY)
6295                 rc = read(fd, buf, sizeof(buf));
6296         else
6297                 rc = write(fd, buf, sizeof(buf));
6298         if (rc < 0)
6299                 rc = -errno;
6300         close(fd);
6301
6302         if (rc == 1)
6303                 rc = 0;
6304 failed:
6305         cfs_free_param_data(&path);
6306         return rc;
6307 }
6308
6309 int llapi_target_iterate(int type_num, char **obd_type,
6310                          void *args, llapi_cb_t cb)
6311 {
6312         int i, rc = 0;
6313         glob_t param;
6314         FILE *fp;
6315
6316         for (i = 0; i < type_num; i++) {
6317                 int j;
6318
6319                 rc = cfs_get_param_paths(&param, "%s/*/uuid", obd_type[i]);
6320                 if (rc != 0)
6321                         continue;
6322
6323                 for (j = 0; j < param.gl_pathc; j++) {
6324                         char obd_uuid[UUID_MAX + 1];
6325                         char *obd_name;
6326                         char *ptr;
6327
6328                         fp = fopen(param.gl_pathv[j], "r");
6329                         if (fp == NULL) {
6330                                 rc = -errno;
6331                                 llapi_error(LLAPI_MSG_ERROR, rc,
6332                                             "error: opening '%s'",
6333                                             param.gl_pathv[j]);
6334                                 goto free_path;
6335                         }
6336
6337                         if (fgets(obd_uuid, sizeof(obd_uuid), fp) == NULL) {
6338                                 rc = -errno;
6339                                 llapi_error(LLAPI_MSG_ERROR, rc,
6340                                             "error: reading '%s'",
6341                                             param.gl_pathv[j]);
6342                                 goto free_path;
6343                         }
6344
6345                         /* Extract the obd_name from the sysfs path.
6346                          * 'topsysfs'/fs/lustre/'obd_type'/'obd_name'.
6347                          */
6348                         obd_name = strstr(param.gl_pathv[j], "/fs/lustre/");
6349                         if (!obd_name) {
6350                                 rc = -EINVAL;
6351                                 goto free_path;
6352                         }
6353
6354                         /* skip /fs/lustre/'obd_type'/ */
6355                         obd_name += strlen(obd_type[i]) + 12;
6356                         /* chop off after obd_name */
6357                         ptr = strrchr(obd_name, '/');
6358                         if (ptr)
6359                                 *ptr = '\0';
6360
6361                         cb(obd_type[i], obd_name, obd_uuid, args);
6362
6363                         fclose(fp);
6364                         fp = NULL;
6365                 }
6366         }
6367 free_path:
6368         if (fp)
6369                 fclose(fp);
6370         cfs_free_param_data(&param);
6371         return rc;
6372 }
6373
6374 struct check_target_filter {
6375         char *nid;
6376         char *instance;
6377 };
6378
6379 static void do_target_check(char *obd_type_name, char *obd_name,
6380                             char *obd_uuid, void *args)
6381 {
6382         int rc;
6383         struct check_target_filter *filter = args;
6384
6385         if (filter != NULL) {
6386                 /* check nid if obd type is mgc */
6387                 if (strcmp(obd_type_name, "mgc") == 0) {
6388                         if (strcmp(obd_name + 3, filter->nid) != 0)
6389                                 return;
6390                 }
6391                 /* check instance for other types of device (osc/mdc) */
6392                 else if (strstr(obd_name, filter->instance) == NULL)
6393                         return;
6394         }
6395
6396         rc = llapi_ping(obd_type_name, obd_name);
6397         if (rc == ENOTCONN)
6398                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
6399         else if (rc)
6400                 llapi_error(LLAPI_MSG_ERROR, rc, "error: check '%s'", obd_name);
6401         else
6402                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
6403 }
6404
6405 int llapi_target_check(int type_num, char **obd_type, char *dir)
6406 {
6407         char nid[MAX_LINE_LEN], instance[MAX_INSTANCE_LEN];
6408         struct check_target_filter filter = {NULL, NULL};
6409         int rc;
6410
6411         if (dir == NULL || dir[0] == '\0')
6412                 return llapi_target_iterate(type_num, obd_type, NULL,
6413                                             do_target_check);
6414
6415         rc = get_root_path(WANT_NID | WANT_ERROR, NULL, NULL, dir, -1, NULL,
6416                            nid);
6417         if (rc) {
6418                 llapi_error(LLAPI_MSG_ERROR, rc,
6419                             "cannot get nid of path '%s'", dir);
6420                 return rc;
6421         }
6422         filter.nid = nid;
6423
6424         rc = llapi_get_instance(dir, instance, ARRAY_SIZE(instance));
6425         if (rc)
6426                 return rc;
6427         filter.instance = instance;
6428
6429         return llapi_target_iterate(type_num, obd_type, &filter,
6430                                     do_target_check);
6431 }
6432
6433 #undef MAX_STRING_SIZE
6434
6435 /* Is this a lustre fs? */
6436 int llapi_is_lustre_mnttype(const char *type)
6437 {
6438         return strcmp(type, "lustre") == 0 || strcmp(type, "lustre_tgt") == 0;
6439 }
6440
6441 /* Is this a lustre client fs? */
6442 int llapi_is_lustre_mnt(struct mntent *mnt)
6443 {
6444         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
6445                 strstr(mnt->mnt_fsname, ":/") != NULL);
6446 }
6447
6448 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
6449 {
6450         char fsname[PATH_MAX + 1];
6451         int root;
6452         int rc;
6453
6454         rc = llapi_search_fsname(mnt, fsname);
6455         if (rc)
6456                 return rc;
6457
6458         root = open(mnt, O_RDONLY | O_DIRECTORY);
6459         if (root < 0) {
6460                 rc = -errno;
6461                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot open '%s'", mnt);
6462                 return rc;
6463         }
6464
6465         rc = ioctl(root, OBD_IOC_QUOTACTL, qctl);
6466         if (rc < 0)
6467                 rc = -errno;
6468         if (rc == -ENOENT && LUSTRE_Q_CMD_IS_POOL(qctl->qc_cmd))
6469                 llapi_error(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO, rc,
6470                             "Cannot find pool '%s'", qctl->qc_poolname);
6471
6472         close(root);
6473         return rc;
6474 }
6475
6476 int llapi_get_connect_flags(const char *mnt, __u64 *flags)
6477 {
6478         int root;
6479         int rc;
6480
6481         root = open(mnt, O_RDONLY | O_DIRECTORY);
6482         if (root < 0) {
6483                 rc = -errno;
6484                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
6485                 return rc;
6486         }
6487
6488         rc = ioctl(root, LL_IOC_GET_CONNECT_FLAGS, flags);
6489         if (rc < 0) {
6490                 rc = -errno;
6491                 llapi_error(LLAPI_MSG_ERROR, rc,
6492                         "ioctl on %s for getting connect flags failed", mnt);
6493         }
6494         close(root);
6495         return rc;
6496 }
6497
6498 /**
6499  * Flush cached pages from all clients.
6500  *
6501  * \param fd    File descriptor
6502  * \retval 0    success
6503  * \retval < 0  error
6504  */
6505 int llapi_file_flush(int fd)
6506 {
6507         __u64 dv;
6508
6509         return llapi_get_data_version(fd, &dv, LL_DV_WR_FLUSH);
6510 }
6511