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