Whamcloud - gitweb
LU-12624 obdclass: lu_tgt_descs cleanup
[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         return get_root_path(WANT_PATH, (char *)fsname, NULL, pathname, -1);
1458 }
1459
1460 int llapi_getname(const char *path, char *buf, size_t size)
1461 {
1462         struct obd_uuid uuid_buf;
1463         char *uuid = uuid_buf.uuid;
1464         char *cfg_instance;
1465         int rc, len, fsname_len;
1466
1467         memset(&uuid_buf, 0, sizeof(uuid_buf));
1468         rc = llapi_file_get_lov_uuid(path, &uuid_buf);
1469         if (rc)
1470                 return rc;
1471
1472         /*
1473          * We want to turn testfs-clilov-ffff88002738bc00 into
1474          * testfs-ffff88002738bc00 in a portable way that doesn't depend
1475          * on what is after "-clilov-" as it may change in the future.
1476          * Unfortunately, the "fsname" part may contain a dash, so we
1477          * can't just skip to the first dash, and the "instance" may be a
1478          * UUID in the future, so we can't necessarily go to the last dash.
1479          */
1480         cfg_instance = strstr(uuid, "-clilov-");
1481         if (!cfg_instance)
1482                 return -EINVAL;
1483
1484         fsname_len = cfg_instance - uuid;
1485         cfg_instance += strlen("-clilov-");
1486         len = snprintf(buf, size, "%.*s-%s", fsname_len, uuid, cfg_instance);
1487
1488         if (len >= size)
1489                 rc = -ENAMETOOLONG;
1490
1491         return rc;
1492 }
1493
1494 /**
1495  * Get the list of pool members.
1496  * \param poolname    string of format \<fsname\>.\<poolname\>
1497  * \param members     caller-allocated array of char*
1498  * \param list_size   size of the members array
1499  * \param buffer      caller-allocated buffer for storing OST names
1500  * \param buffer_size size of the buffer
1501  *
1502  * \return number of members retrieved for this pool
1503  * \retval -error failure
1504  */
1505 int llapi_get_poolmembers(const char *poolname, char **members,
1506                           int list_size, char *buffer, int buffer_size)
1507 {
1508         char fsname[PATH_MAX];
1509         char *pool, *tmp;
1510         glob_t pathname;
1511         char buf[PATH_MAX];
1512         FILE *fd;
1513         int rc = 0;
1514         int nb_entries = 0;
1515         int used = 0;
1516
1517         /* name is FSNAME.POOLNAME */
1518         if (strlen(poolname) >= sizeof(fsname))
1519                 return -EOVERFLOW;
1520
1521         snprintf(fsname, sizeof(fsname), "%s", poolname);
1522         pool = strchr(fsname, '.');
1523         if (pool == NULL)
1524                 return -EINVAL;
1525
1526         *pool = '\0';
1527         pool++;
1528
1529         rc = poolpath(&pathname, fsname, NULL);
1530         if (rc != 0) {
1531                 llapi_error(LLAPI_MSG_ERROR, rc,
1532                             "Lustre filesystem '%s' not found",
1533                             fsname);
1534                 return rc;
1535         }
1536
1537         llapi_printf(LLAPI_MSG_NORMAL, "Pool: %s.%s\n", fsname, pool);
1538         rc = snprintf(buf, sizeof(buf), "%s/%s", pathname.gl_pathv[0], pool);
1539         cfs_free_param_data(&pathname);
1540         if (rc >= sizeof(buf))
1541                 return -EOVERFLOW;
1542         fd = fopen(buf, "r");
1543         if (fd == NULL) {
1544                 rc = -errno;
1545                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot open %s", buf);
1546                 return rc;
1547         }
1548
1549         rc = 0;
1550         while (fgets(buf, sizeof(buf), fd) != NULL) {
1551                 if (nb_entries >= list_size) {
1552                         rc = -EOVERFLOW;
1553                         break;
1554                 }
1555                 buf[sizeof(buf) - 1] = '\0';
1556                 /* remove '\n' */
1557                 tmp = strchr(buf, '\n');
1558                 if (tmp != NULL)
1559                         *tmp='\0';
1560                 if (used + strlen(buf) + 1 > buffer_size) {
1561                         rc = -EOVERFLOW;
1562                         break;
1563                 }
1564
1565                 strcpy(buffer + used, buf);
1566                 members[nb_entries] = buffer + used;
1567                 used += strlen(buf) + 1;
1568                 nb_entries++;
1569                 rc = nb_entries;
1570         }
1571
1572         fclose(fd);
1573         return rc;
1574 }
1575
1576 /**
1577  * Get the list of pools in a filesystem.
1578  * \param name        filesystem name or path
1579  * \param poollist    caller-allocated array of char*
1580  * \param list_size   size of the poollist array
1581  * \param buffer      caller-allocated buffer for storing pool names
1582  * \param buffer_size size of the buffer
1583  *
1584  * \return number of pools retrieved for this filesystem
1585  * \retval -error failure
1586  */
1587 int llapi_get_poollist(const char *name, char **poollist, int list_size,
1588                        char *buffer, int buffer_size)
1589 {
1590         glob_t pathname;
1591         char *fsname;
1592         char *ptr;
1593         DIR *dir;
1594         struct dirent *pool;
1595         int rc = 0;
1596         unsigned int nb_entries = 0;
1597         unsigned int used = 0;
1598         unsigned int i;
1599
1600         /* initialize output array */
1601         for (i = 0; i < list_size; i++)
1602                 poollist[i] = NULL;
1603
1604         /* is name a pathname ? */
1605         ptr = strchr(name, '/');
1606         if (ptr != NULL) {
1607                 char fsname_buf[MAXNAMLEN];
1608
1609                 /* We will need fsname for printing later */
1610                 rc = llapi_getname(name, fsname_buf, sizeof(fsname_buf));
1611                 if (rc)
1612                         return rc;
1613
1614                 ptr = strrchr(fsname_buf, '-');
1615                 if (ptr)
1616                         *ptr = '\0';
1617
1618                 fsname = strdup(fsname_buf);
1619                 if (!fsname)
1620                         return -ENOMEM;
1621         } else {
1622                 /* name is FSNAME */
1623                 fsname = strdup(name);
1624                 if (!fsname)
1625                         return -ENOMEM;
1626         }
1627
1628         rc = poolpath(&pathname, fsname, NULL);
1629         if (rc != 0) {
1630                 llapi_error(LLAPI_MSG_ERROR, rc,
1631                             "Lustre filesystem '%s' not found", name);
1632                 goto free_path;
1633         }
1634
1635         dir = opendir(pathname.gl_pathv[0]);
1636         if (dir == NULL) {
1637                 rc = -errno;
1638                 llapi_error(LLAPI_MSG_ERROR, rc,
1639                             "Could not open pool list for '%s'",
1640                             name);
1641                 goto free_path;
1642         }
1643
1644         do {
1645                 errno = 0;
1646                 pool = readdir(dir);
1647                 if (pool == NULL) {
1648                         rc = -errno;
1649                         goto free_dir;
1650                 }
1651
1652                 /* ignore . and .. */
1653                 if (!strcmp(pool->d_name, ".") || !strcmp(pool->d_name, ".."))
1654                         continue;
1655
1656                 /* check output bounds */
1657                 if (nb_entries >= list_size) {
1658                         rc = -EOVERFLOW;
1659                         goto free_dir_no_msg;
1660                 }
1661
1662                 /* +2 for '.' and final '\0' */
1663                 if (used + strlen(pool->d_name) + strlen(fsname) + 2
1664                     > buffer_size) {
1665                         rc = -EOVERFLOW;
1666                         goto free_dir_no_msg;
1667                 }
1668
1669                 sprintf(buffer + used, "%s.%s", fsname, pool->d_name);
1670                 poollist[nb_entries] = buffer + used;
1671                 used += strlen(pool->d_name) + strlen(fsname) + 2;
1672                 nb_entries++;
1673         } while (1);
1674
1675 free_dir:
1676         if (rc)
1677                 llapi_error(LLAPI_MSG_ERROR, rc,
1678                             "Error reading pool list for '%s'", name);
1679         else
1680                 llapi_printf(LLAPI_MSG_NORMAL, "Pools from %s:\n", fsname);
1681
1682 free_dir_no_msg:
1683         closedir(dir);
1684 free_path:
1685         cfs_free_param_data(&pathname);
1686         if (fsname)
1687                 free(fsname);
1688         return rc != 0 ? rc : nb_entries;
1689 }
1690
1691 /* wrapper for lfs.c and obd.c */
1692 int llapi_poollist(const char *name)
1693 {
1694         /* list of pool names (assume that pool count is smaller
1695            than OST count) */
1696         char **list, *buffer = NULL, *fsname = (char *)name;
1697         char *poolname = NULL, *tmp = NULL, data[16];
1698         enum param_filter type = FILTER_BY_PATH;
1699         int obdcount, bufsize, rc, nb, i;
1700
1701         if (name == NULL)
1702                 return -EINVAL;
1703
1704         if (name[0] != '/') {
1705                 fsname = strdup(name);
1706                 if (fsname == NULL)
1707                         return -ENOMEM;
1708
1709                 poolname = strchr(fsname, '.');
1710                 if (poolname)
1711                         *poolname = '\0';
1712                 type = FILTER_BY_FS_NAME;
1713         }
1714
1715         rc = get_lustre_param_value("lov", fsname, type, "numobd",
1716                                     data, sizeof(data));
1717         if (rc < 0)
1718                 goto err;
1719         obdcount = atoi(data);
1720
1721         /* Allocate space for each fsname-OST0000_UUID, 1 per OST,
1722          * and also an array to store the pointers for all that
1723          * allocated space. */
1724 retry_get_pools:
1725         bufsize = sizeof(struct obd_uuid) * obdcount;
1726         buffer = realloc(tmp, bufsize + sizeof(*list) * obdcount);
1727         if (buffer == NULL) {
1728                 rc = -ENOMEM;
1729                 goto err;
1730         }
1731         list = (char **) (buffer + bufsize);
1732
1733         if (!poolname) {
1734                 /* name is a path or fsname */
1735                 nb = llapi_get_poollist(name, list, obdcount,
1736                                         buffer, bufsize);
1737         } else {
1738                 /* name is a pool name (<fsname>.<poolname>) */
1739                 nb = llapi_get_poolmembers(name, list, obdcount,
1740                                            buffer, bufsize);
1741         }
1742
1743         if (nb == -EOVERFLOW) {
1744                 obdcount *= 2;
1745                 tmp = buffer;
1746                 goto retry_get_pools;
1747         }
1748
1749         for (i = 0; i < nb; i++)
1750                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", list[i]);
1751         rc = (nb < 0 ? nb : 0);
1752 err:
1753         if (buffer)
1754                 free(buffer);
1755         if (fsname != NULL && type == FILTER_BY_FS_NAME)
1756                 free(fsname);
1757         return rc;
1758 }
1759
1760 typedef int (semantic_func_t)(char *path, DIR *parent, DIR **d,
1761                               void *data, struct dirent64 *de);
1762
1763 #define OBD_NOT_FOUND           (-1)
1764
1765 static void find_param_fini(struct find_param *param)
1766 {
1767         if (param->fp_migrate)
1768                 return;
1769
1770         if (param->fp_obd_indexes) {
1771                 free(param->fp_obd_indexes);
1772                 param->fp_obd_indexes = NULL;
1773         }
1774
1775         if (param->fp_lmd) {
1776                 free(param->fp_lmd);
1777                 param->fp_lmd = NULL;
1778         }
1779
1780         if (param->fp_lmv_md) {
1781                 free(param->fp_lmv_md);
1782                 param->fp_lmv_md = NULL;
1783         }
1784 }
1785
1786 static int common_param_init(struct find_param *param, char *path)
1787 {
1788         int lum_size = get_mds_md_size(path);
1789
1790         if (lum_size < 0)
1791                 return lum_size;
1792
1793         /* migrate has fp_lmv_md initialized outside */
1794         if (param->fp_migrate)
1795                 return 0;
1796
1797         if (lum_size < PATH_MAX + 1)
1798                 lum_size = PATH_MAX + 1;
1799
1800         param->fp_lum_size = lum_size;
1801         param->fp_lmd = calloc(1, offsetof(typeof(*param->fp_lmd), lmd_lmm) +
1802                                lum_size);
1803         if (param->fp_lmd == NULL) {
1804                 llapi_error(LLAPI_MSG_ERROR, -ENOMEM,
1805                             "error: allocate %zu bytes for layout failed",
1806                             sizeof(lstat_t) + param->fp_lum_size);
1807                 return -ENOMEM;
1808         }
1809
1810         param->fp_lmv_stripe_count = 256;
1811         param->fp_lmv_md = calloc(1,
1812                                   lmv_user_md_size(param->fp_lmv_stripe_count,
1813                                                    LMV_USER_MAGIC_SPECIFIC));
1814         if (param->fp_lmv_md == NULL) {
1815                 llapi_error(LLAPI_MSG_ERROR, -ENOMEM,
1816                             "error: allocation of %d bytes for ioctl",
1817                             lmv_user_md_size(param->fp_lmv_stripe_count,
1818                                              LMV_USER_MAGIC_SPECIFIC));
1819                 find_param_fini(param);
1820                 return -ENOMEM;
1821         }
1822
1823         param->fp_got_uuids = 0;
1824         param->fp_obd_indexes = NULL;
1825         param->fp_obd_index = OBD_NOT_FOUND;
1826         param->fp_mdt_index = OBD_NOT_FOUND;
1827         return 0;
1828 }
1829
1830 static int cb_common_fini(char *path, DIR *parent, DIR **dirp, void *data,
1831                           struct dirent64 *de)
1832 {
1833         struct find_param *param = data;
1834         param->fp_depth--;
1835
1836         return 0;
1837 }
1838
1839 /* set errno upon failure */
1840 static DIR *opendir_parent(const char *path)
1841 {
1842         char *path_copy;
1843         char *parent_path;
1844         DIR *parent;
1845
1846         path_copy = strdup(path);
1847         if (path_copy == NULL)
1848                 return NULL;
1849
1850         parent_path = dirname(path_copy);
1851         parent = opendir(parent_path);
1852         free(path_copy);
1853
1854         return parent;
1855 }
1856
1857 static int cb_get_dirstripe(char *path, DIR *d, struct find_param *param)
1858 {
1859         int ret;
1860
1861 again:
1862         param->fp_lmv_md->lum_stripe_count = param->fp_lmv_stripe_count;
1863         if (param->fp_get_default_lmv)
1864                 param->fp_lmv_md->lum_magic = LMV_USER_MAGIC;
1865         else
1866                 param->fp_lmv_md->lum_magic = LMV_MAGIC_V1;
1867
1868         ret = ioctl(dirfd(d), LL_IOC_LMV_GETSTRIPE, param->fp_lmv_md);
1869         if (errno == E2BIG && ret != 0) {
1870                 int stripe_count;
1871                 int lmv_size;
1872
1873                 /* if foreign LMV case, fake stripes number */
1874                 if (param->fp_lmv_md->lum_magic == LMV_MAGIC_FOREIGN) {
1875                         struct lmv_foreign_md *lfm;
1876
1877                         lfm = (struct lmv_foreign_md *)param->fp_lmv_md;
1878                         if (lfm->lfm_length < XATTR_SIZE_MAX -
1879                             offsetof(typeof(*lfm), lfm_value)) {
1880                                 uint32_t size = lfm->lfm_length +
1881                                              offsetof(typeof(*lfm), lfm_value);
1882
1883                                 stripe_count = lmv_foreign_to_md_stripes(size);
1884                         } else {
1885                                 llapi_error(LLAPI_MSG_ERROR, -EINVAL,
1886                                             "error: invalid %d foreign size "
1887                                             "returned from ioctl",
1888                                             lfm->lfm_length);
1889                                 return -EINVAL;
1890                         }
1891                 } else {
1892                         stripe_count = param->fp_lmv_md->lum_stripe_count;
1893                 }
1894                 if (stripe_count <= param->fp_lmv_stripe_count)
1895                         return ret;
1896
1897                 free(param->fp_lmv_md);
1898                 param->fp_lmv_stripe_count = stripe_count;
1899                 lmv_size = lmv_user_md_size(stripe_count,
1900                                             LMV_USER_MAGIC_SPECIFIC);
1901                 param->fp_lmv_md = malloc(lmv_size);
1902                 if (param->fp_lmv_md == NULL) {
1903                         llapi_error(LLAPI_MSG_ERROR, -ENOMEM,
1904                                     "error: allocation of %d bytes for ioctl",
1905                                     lmv_user_md_size(param->fp_lmv_stripe_count,
1906                                                      LMV_USER_MAGIC_SPECIFIC));
1907                         return -ENOMEM;
1908                 }
1909                 goto again;
1910         }
1911         return ret;
1912 }
1913
1914 static void convert_lmd_statx(struct lov_user_mds_data *lmd_v2, lstat_t *st,
1915                               bool strict)
1916 {
1917         memset(&lmd_v2->lmd_stx, 0, sizeof(lmd_v2->lmd_stx));
1918         lmd_v2->lmd_stx.stx_blksize = st->st_blksize;
1919         lmd_v2->lmd_stx.stx_nlink = st->st_nlink;
1920         lmd_v2->lmd_stx.stx_uid = st->st_uid;
1921         lmd_v2->lmd_stx.stx_gid = st->st_gid;
1922         lmd_v2->lmd_stx.stx_mode = st->st_mode;
1923         lmd_v2->lmd_stx.stx_ino = st->st_ino;
1924         lmd_v2->lmd_stx.stx_size = st->st_size;
1925         lmd_v2->lmd_stx.stx_blocks = st->st_blocks;
1926         lmd_v2->lmd_stx.stx_atime.tv_sec = st->st_atime;
1927         lmd_v2->lmd_stx.stx_ctime.tv_sec = st->st_ctime;
1928         lmd_v2->lmd_stx.stx_mtime.tv_sec = st->st_mtime;
1929         lmd_v2->lmd_stx.stx_rdev_major = major(st->st_rdev);
1930         lmd_v2->lmd_stx.stx_rdev_minor = minor(st->st_rdev);
1931         lmd_v2->lmd_stx.stx_dev_major = major(st->st_dev);
1932         lmd_v2->lmd_stx.stx_dev_minor = minor(st->st_dev);
1933         lmd_v2->lmd_stx.stx_mask |= STATX_BASIC_STATS;
1934
1935         lmd_v2->lmd_flags = 0;
1936         if (strict) {
1937                 lmd_v2->lmd_flags |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
1938         } else {
1939                 lmd_v2->lmd_stx.stx_mask &= ~(STATX_SIZE | STATX_BLOCKS);
1940                 if (lmd_v2->lmd_stx.stx_size)
1941                         lmd_v2->lmd_flags |= OBD_MD_FLLAZYSIZE;
1942                 if (lmd_v2->lmd_stx.stx_blocks)
1943                         lmd_v2->lmd_flags |= OBD_MD_FLLAZYBLOCKS;
1944         }
1945         lmd_v2->lmd_flags |= OBD_MD_FLATIME | OBD_MD_FLMTIME | OBD_MD_FLCTIME |
1946                              OBD_MD_FLBLKSZ | OBD_MD_FLMODE | OBD_MD_FLTYPE |
1947                              OBD_MD_FLUID | OBD_MD_FLGID | OBD_MD_FLNLINK |
1948                              OBD_MD_FLRDEV;
1949
1950 }
1951
1952 static int convert_lmdbuf_v1v2(void *lmdbuf, int lmdlen)
1953 {
1954         struct lov_user_mds_data_v1 *lmd_v1 = lmdbuf;
1955         struct lov_user_mds_data *lmd_v2 = lmdbuf;
1956         lstat_t st;
1957         int size;
1958
1959         size = lov_comp_md_size((struct lov_comp_md_v1 *)&lmd_v1->lmd_lmm);
1960         if (size < 0)
1961                 return size;
1962
1963         if (lmdlen < sizeof(lmd_v1->lmd_st) + size)
1964                 return -EOVERFLOW;
1965
1966         st = lmd_v1->lmd_st;
1967         memmove(&lmd_v2->lmd_lmm, &lmd_v1->lmd_lmm,
1968                 lmdlen - (&lmd_v2->lmd_lmm - &lmd_v1->lmd_lmm));
1969         convert_lmd_statx(lmd_v2, &st, false);
1970         lmd_v2->lmd_lmmsize = 0;
1971         lmd_v2->lmd_padding = 0;
1972
1973         return 0;
1974 }
1975
1976 int get_lmd_info_fd(const char *path, int parent_fd, int dir_fd,
1977                     void *lmdbuf, int lmdlen, enum get_lmd_info_type type)
1978 {
1979         struct lov_user_mds_data *lmd = lmdbuf;
1980         static bool use_old_ioctl;
1981         unsigned long cmd;
1982         int ret = 0;
1983
1984         if (parent_fd < 0 && dir_fd < 0)
1985                 return -EINVAL;
1986         if (type != GET_LMD_INFO && type != GET_LMD_STRIPE)
1987                 return -EINVAL;
1988
1989         if (dir_fd >= 0) {
1990                 /* LL_IOC_MDC_GETINFO operates on the current directory inode
1991                  * and returns struct lov_user_mds_data, while
1992                  * LL_IOC_LOV_GETSTRIPE returns only struct lov_user_md.
1993                  */
1994                 if (type == GET_LMD_INFO)
1995                         cmd = use_old_ioctl ? LL_IOC_MDC_GETINFO_OLD :
1996                                               LL_IOC_MDC_GETINFO;
1997                 else
1998                         cmd = LL_IOC_LOV_GETSTRIPE;
1999
2000 retry_getinfo:
2001                 ret = ioctl(dir_fd, cmd, lmdbuf);
2002                 if (ret < 0 && errno == ENOTTY && cmd == LL_IOC_MDC_GETINFO) {
2003                         cmd = LL_IOC_MDC_GETINFO_OLD;
2004                         use_old_ioctl = true;
2005                         goto retry_getinfo;
2006                 }
2007
2008                 if (cmd == LL_IOC_MDC_GETINFO_OLD && !ret)
2009                         ret = convert_lmdbuf_v1v2(lmdbuf, lmdlen);
2010         } else if (parent_fd >= 0) {
2011                 const char *fname = strrchr(path, '/');
2012
2013                 /* IOC_MDC_GETFILEINFO takes as input the filename (relative to
2014                  * the parent directory) and returns struct lov_user_mds_data,
2015                  * while IOC_MDC_GETFILESTRIPE returns only struct lov_user_md.
2016                  *
2017                  * This avoids opening, locking, and closing each file on the
2018                  * client if that is not needed. Multiple of these ioctl() can
2019                  * be done on the parent dir with a single open for all
2020                  * files in that directory, and it also doesn't pollute the
2021                  * client dcache with millions of dentries when traversing
2022                  * a large filesystem.
2023                  */
2024                 fname = (fname == NULL ? path : fname + 1);
2025
2026                 ret = snprintf(lmdbuf, lmdlen, "%s", fname);
2027                 if (ret < 0)
2028                         errno = -ret;
2029                 else if (ret >= lmdlen || ret++ == 0)
2030                         errno = EINVAL;
2031                 else {
2032                         if (type == GET_LMD_INFO)
2033                                 cmd = use_old_ioctl ? IOC_MDC_GETFILEINFO_OLD :
2034                                                       IOC_MDC_GETFILEINFO;
2035                         else
2036                                 cmd = IOC_MDC_GETFILESTRIPE;
2037
2038 retry_getfileinfo:
2039                         ret = ioctl(parent_fd, cmd, lmdbuf);
2040                         if (ret < 0 && errno == ENOTTY &&
2041                             cmd == IOC_MDC_GETFILEINFO) {
2042                                 cmd = IOC_MDC_GETFILEINFO_OLD;
2043                                 use_old_ioctl = true;
2044                                 goto retry_getfileinfo;
2045                         }
2046
2047                         if (cmd == IOC_MDC_GETFILEINFO_OLD && !ret)
2048                                 ret = convert_lmdbuf_v1v2(lmdbuf, lmdlen);
2049                 }
2050         }
2051
2052         if (ret && type == GET_LMD_INFO) {
2053                 if (errno == ENOTTY) {
2054                         lstat_t st;
2055
2056                         /* ioctl is not supported, it is not a lustre fs.
2057                          * Do the regular lstat(2) instead.
2058                          */
2059                         ret = lstat_f(path, &st);
2060                         if (ret) {
2061                                 ret = -errno;
2062                                 llapi_error(LLAPI_MSG_ERROR, ret,
2063                                             "error: %s: lstat failed for %s",
2064                                             __func__, path);
2065                         }
2066
2067                         convert_lmd_statx(lmd, &st, true);
2068                         /* It may be wrong to set use_old_ioctl with true as
2069                          * the file is not a lustre fs. So reset it with false
2070                          * directly here.
2071                          */
2072                         use_old_ioctl = false;
2073                 } else if (errno == ENOENT) {
2074                         ret = -errno;
2075                         llapi_error(LLAPI_MSG_WARN, ret,
2076                                     "warning: %s does not exist", path);
2077                 } else if (errno != EISDIR && errno != ENODATA) {
2078                         ret = -errno;
2079                         llapi_error(LLAPI_MSG_ERROR, ret,
2080                                     "%s ioctl failed for %s.",
2081                                     dir_fd >= 0 ? "LL_IOC_MDC_GETINFO" :
2082                                     "IOC_MDC_GETFILEINFO", path);
2083                 }
2084         }
2085
2086         return ret;
2087 }
2088
2089 static int get_lmd_info(char *path, DIR *parent, DIR *dir, void *lmdbuf,
2090                         int lmdlen, enum get_lmd_info_type type)
2091 {
2092         int parent_fd = -1;
2093         int dir_fd = -1;
2094
2095         if (parent)
2096                 parent_fd = dirfd(parent);
2097         if (dir)
2098                 dir_fd = dirfd(dir);
2099
2100         return get_lmd_info_fd(path, parent_fd, dir_fd, lmdbuf, lmdlen, type);
2101 }
2102
2103 static int llapi_semantic_traverse(char *path, int size, DIR *parent,
2104                                    semantic_func_t sem_init,
2105                                    semantic_func_t sem_fini, void *data,
2106                                    struct dirent64 *de)
2107 {
2108         struct find_param *param = (struct find_param *)data;
2109         struct dirent64 *dent;
2110         int len, ret;
2111         DIR *d, *p = NULL;
2112
2113         ret = 0;
2114         len = strlen(path);
2115
2116         d = opendir(path);
2117         if (!d && errno != ENOTDIR) {
2118                 ret = -errno;
2119                 llapi_error(LLAPI_MSG_ERROR, ret, "%s: Failed to open '%s'",
2120                             __func__, path);
2121                 return ret;
2122         } else if (!d && !parent) {
2123                 /* ENOTDIR. Open the parent dir. */
2124                 p = opendir_parent(path);
2125                 if (!p) {
2126                         ret = -errno;
2127                         goto out;
2128                 }
2129         }
2130
2131         if (sem_init && (ret = sem_init(path, parent ?: p, &d, data, de)))
2132                 goto err;
2133
2134         if (d == NULL)
2135                 goto out;
2136
2137         while ((dent = readdir64(d)) != NULL) {
2138                 int rc;
2139
2140                 if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
2141                         continue;
2142
2143                 path[len] = 0;
2144                 if ((len + dent->d_reclen + 2) > size) {
2145                         llapi_err_noerrno(LLAPI_MSG_ERROR,
2146                                           "error: %s: string buffer too small",
2147                                           __func__);
2148                         break;
2149                 }
2150                 strcat(path, "/");
2151                 strcat(path, dent->d_name);
2152
2153                 if (dent->d_type == DT_UNKNOWN) {
2154                         lstatx_t *stx = &param->fp_lmd->lmd_stx;
2155
2156                         rc = get_lmd_info(path, d, NULL, param->fp_lmd,
2157                                           param->fp_lum_size, GET_LMD_INFO);
2158                         if (rc == 0)
2159                                 dent->d_type = IFTODT(stx->stx_mode);
2160                         else if (ret == 0)
2161                                 ret = rc;
2162
2163                         if (rc == -ENOENT)
2164                                 continue;
2165                 }
2166                 switch (dent->d_type) {
2167                 case DT_UNKNOWN:
2168                         llapi_err_noerrno(LLAPI_MSG_ERROR,
2169                                           "error: %s: '%s' is UNKNOWN type %d",
2170                                           __func__, dent->d_name, dent->d_type);
2171                         break;
2172                 case DT_DIR:
2173                         rc = llapi_semantic_traverse(path, size, d, sem_init,
2174                                                       sem_fini, data, dent);
2175                         if (rc != 0 && ret == 0)
2176                                 ret = rc;
2177                         break;
2178                 default:
2179                         rc = 0;
2180                         if (sem_init) {
2181                                 rc = sem_init(path, d, NULL, data, dent);
2182                                 if (rc < 0 && ret == 0) {
2183                                         ret = rc;
2184                                         break;
2185                                 }
2186                         }
2187                         if (sem_fini && rc == 0)
2188                                 sem_fini(path, d, NULL, data, dent);
2189                 }
2190         }
2191
2192 out:
2193         path[len] = 0;
2194
2195         if (sem_fini)
2196                 sem_fini(path, parent, &d, data, de);
2197 err:
2198         if (d)
2199                 closedir(d);
2200         if (p)
2201                 closedir(p);
2202         return ret;
2203 }
2204
2205 static int param_callback(char *path, semantic_func_t sem_init,
2206                           semantic_func_t sem_fini, struct find_param *param)
2207 {
2208         int ret, len = strlen(path);
2209         char *buf;
2210
2211         if (len > PATH_MAX) {
2212                 ret = -EINVAL;
2213                 llapi_error(LLAPI_MSG_ERROR, ret,
2214                             "Path name '%s' is too long", path);
2215                 return ret;
2216         }
2217
2218         buf = (char *)malloc(PATH_MAX + 1);
2219         if (!buf)
2220                 return -ENOMEM;
2221
2222         snprintf(buf, PATH_MAX + 1, "%s", path);
2223         ret = common_param_init(param, buf);
2224         if (ret)
2225                 goto out;
2226
2227         param->fp_depth = 0;
2228
2229         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, sem_init,
2230                                       sem_fini, param, NULL);
2231 out:
2232         find_param_fini(param);
2233         free(buf);
2234         return ret < 0 ? ret : 0;
2235 }
2236
2237 int llapi_file_fget_lov_uuid(int fd, struct obd_uuid *lov_name)
2238 {
2239         int rc = ioctl(fd, OBD_IOC_GETNAME, lov_name);
2240
2241         if (rc) {
2242                 rc = -errno;
2243                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot get lov name");
2244         }
2245         return rc;
2246 }
2247
2248 int llapi_file_fget_lmv_uuid(int fd, struct obd_uuid *lov_name)
2249 {
2250         int rc = ioctl(fd, OBD_IOC_GETMDNAME, lov_name);
2251         if (rc) {
2252                 rc = -errno;
2253                 llapi_error(LLAPI_MSG_ERROR, rc, "error: can't get lmv name.");
2254         }
2255         return rc;
2256 }
2257
2258 int llapi_file_get_lov_uuid(const char *path, struct obd_uuid *lov_uuid)
2259 {
2260         int fd, rc;
2261
2262         fd = open(path, O_RDONLY | O_NONBLOCK);
2263         if (fd < 0) {
2264                 rc = -errno;
2265                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot open '%s'", path);
2266                 return rc;
2267         }
2268
2269         rc = llapi_file_fget_lov_uuid(fd, lov_uuid);
2270
2271         close(fd);
2272         return rc;
2273 }
2274
2275 int llapi_file_get_lmv_uuid(const char *path, struct obd_uuid *lov_uuid)
2276 {
2277         int fd, rc;
2278
2279         fd = open(path, O_RDONLY | O_NONBLOCK);
2280         if (fd < 0) {
2281                 rc = -errno;
2282                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s", path);
2283                 return rc;
2284         }
2285
2286         rc = llapi_file_fget_lmv_uuid(fd, lov_uuid);
2287
2288         close(fd);
2289         return rc;
2290 }
2291
2292 enum tgt_type {
2293         LOV_TYPE = 1,
2294         LMV_TYPE
2295 };
2296
2297 /*
2298  * If uuidp is NULL, return the number of available obd uuids.
2299  * If uuidp is non-NULL, then it will return the uuids of the obds. If
2300  * there are more OSTs than allocated to uuidp, then an error is returned with
2301  * the ost_count set to number of available obd uuids.
2302  */
2303 static int llapi_get_target_uuids(int fd, struct obd_uuid *uuidp,
2304                                   int *ost_count, enum tgt_type type)
2305 {
2306         char buf[PATH_MAX], format[32];
2307         int rc = 0, index = 0;
2308         struct obd_uuid name;
2309         glob_t param;
2310         FILE *fp;
2311
2312         /* Get the lov name */
2313         if (type == LOV_TYPE)
2314                 rc = llapi_file_fget_lov_uuid(fd, &name);
2315         else
2316                 rc = llapi_file_fget_lmv_uuid(fd, &name);
2317         if (rc != 0)
2318                 return rc;
2319
2320         /* Now get the ost uuids */
2321         rc = get_lustre_param_path(type == LOV_TYPE ? "lov" : "lmv", name.uuid,
2322                                    FILTER_BY_EXACT, "target_obd", &param);
2323         if (rc != 0)
2324                 return -ENOENT;
2325
2326         fp = fopen(param.gl_pathv[0], "r");
2327         if (fp == NULL) {
2328                 rc = -errno;
2329                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening '%s'",
2330                             param.gl_pathv[0]);
2331                 goto free_param;
2332         }
2333
2334         snprintf(format, sizeof(format),
2335                  "%%d: %%%zus", sizeof(uuidp[0].uuid) - 1);
2336         while (fgets(buf, sizeof(buf), fp) != NULL) {
2337                 if (uuidp && (index < *ost_count)) {
2338                         if (sscanf(buf, format, &index, uuidp[index].uuid) < 2)
2339                                 break;
2340                 }
2341                 index++;
2342         }
2343
2344         fclose(fp);
2345
2346         if (uuidp && (index > *ost_count))
2347                 rc = -EOVERFLOW;
2348
2349         *ost_count = index;
2350 free_param:
2351         cfs_free_param_data(&param);
2352         return rc;
2353 }
2354
2355 int llapi_lov_get_uuids(int fd, struct obd_uuid *uuidp, int *ost_count)
2356 {
2357         return llapi_get_target_uuids(fd, uuidp, ost_count, LOV_TYPE);
2358 }
2359
2360 int llapi_get_obd_count(char *mnt, int *count, int is_mdt)
2361 {
2362         int root;
2363         int rc;
2364
2365         root = open(mnt, O_RDONLY | O_DIRECTORY);
2366         if (root < 0) {
2367                 rc = -errno;
2368                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
2369                 return rc;
2370         }
2371
2372         *count = is_mdt;
2373         rc = ioctl(root, LL_IOC_GETOBDCOUNT, count);
2374         if (rc < 0)
2375                 rc = -errno;
2376
2377         close(root);
2378         return rc;
2379 }
2380
2381 /* Check if user specified value matches a real uuid.  Ignore _UUID,
2382  * -osc-4ba41334, other trailing gunk in comparison.
2383  * @param real_uuid ends in "_UUID"
2384  * @param search_uuid may or may not end in "_UUID"
2385  */
2386 int llapi_uuid_match(char *real_uuid, char *search_uuid)
2387 {
2388         int cmplen = strlen(real_uuid);
2389         int searchlen = strlen(search_uuid);
2390
2391         if (cmplen > 5 && strcmp(real_uuid + cmplen - 5, "_UUID") == 0)
2392                 cmplen -= 5;
2393         if (searchlen > 5 && strcmp(search_uuid + searchlen - 5, "_UUID") == 0)
2394                 searchlen -= 5;
2395
2396         /* The UUIDs may legitimately be different lengths, if
2397          * the system was upgraded from an older version. */
2398         if (cmplen != searchlen)
2399                 return 0;
2400
2401         return (strncmp(search_uuid, real_uuid, cmplen) == 0);
2402 }
2403
2404 /* Here, param->fp_obd_uuid points to a single obduuid, the index of which is
2405  * returned in param->fp_obd_index */
2406 static int setup_obd_uuid(int fd, char *dname, struct find_param *param)
2407 {
2408         struct obd_uuid obd_uuid;
2409         char buf[PATH_MAX];
2410         glob_t param_data;
2411         char format[32];
2412         int rc = 0;
2413         FILE *fp;
2414
2415         if (param->fp_got_uuids)
2416                 return rc;
2417
2418         /* Get the lov/lmv name */
2419         if (param->fp_get_lmv)
2420                 rc = llapi_file_fget_lmv_uuid(fd, &obd_uuid);
2421         else
2422                 rc = llapi_file_fget_lov_uuid(fd, &obd_uuid);
2423         if (rc) {
2424                 if (rc != -ENOTTY) {
2425                         llapi_error(LLAPI_MSG_ERROR, rc,
2426                                     "error: can't get %s name: %s",
2427                                     param->fp_get_lmv ? "lmv" : "lov",
2428                                     dname);
2429                 } else {
2430                         rc = 0;
2431                 }
2432                 return rc;
2433         }
2434
2435         param->fp_got_uuids = 1;
2436
2437         /* Now get the ost uuids */
2438         rc = get_lustre_param_path(param->fp_get_lmv ? "lmv" : "lov",
2439                                    obd_uuid.uuid, FILTER_BY_EXACT,
2440                                    "target_obd", &param_data);
2441         if (rc != 0)
2442                 return -ENOENT;
2443
2444         fp = fopen(param_data.gl_pathv[0], "r");
2445         if (fp == NULL) {
2446                 rc = -errno;
2447                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening '%s'",
2448                             param_data.gl_pathv[0]);
2449                 goto free_param;
2450         }
2451
2452         if (!param->fp_obd_uuid && !param->fp_quiet && !param->fp_obds_printed)
2453                 llapi_printf(LLAPI_MSG_NORMAL, "%s:\n",
2454                              param->fp_get_lmv ? "MDTS" : "OBDS");
2455
2456         snprintf(format, sizeof(format),
2457                  "%%d: %%%zus", sizeof(obd_uuid.uuid) - 1);
2458         while (fgets(buf, sizeof(buf), fp) != NULL) {
2459                 int index;
2460
2461                 if (sscanf(buf, format, &index, obd_uuid.uuid) < 2)
2462                         break;
2463
2464                 if (param->fp_obd_uuid) {
2465                         if (llapi_uuid_match(obd_uuid.uuid,
2466                                              param->fp_obd_uuid->uuid)) {
2467                                 param->fp_obd_index = index;
2468                                 break;
2469                         }
2470                 } else if (!param->fp_quiet && !param->fp_obds_printed) {
2471                         /* Print everything */
2472                         llapi_printf(LLAPI_MSG_NORMAL, "%s", buf);
2473                 }
2474         }
2475         param->fp_obds_printed = 1;
2476
2477         fclose(fp);
2478
2479         if (param->fp_obd_uuid && (param->fp_obd_index == OBD_NOT_FOUND)) {
2480                 llapi_err_noerrno(LLAPI_MSG_ERROR,
2481                                   "error: %s: unknown obduuid: %s",
2482                                   __func__, param->fp_obd_uuid->uuid);
2483                 rc = -EINVAL;
2484         }
2485 free_param:
2486         cfs_free_param_data(&param_data);
2487         return rc;
2488 }
2489
2490 /* In this case, param->fp_obd_uuid will be an array of obduuids and
2491  * obd index for all these obduuids will be returned in
2492  * param->fp_obd_indexes */
2493 static int setup_indexes(DIR *dir, char *path, struct obd_uuid *obduuids,
2494                          int num_obds, int **obdindexes, int *obdindex,
2495                          enum tgt_type type)
2496 {
2497         int ret, obdcount, obd_valid = 0, obdnum;
2498         long i;
2499         struct obd_uuid *uuids = NULL;
2500         char buf[16];
2501         int *indexes;
2502
2503         if (type == LOV_TYPE)
2504                 ret = get_param_lov(path, "numobd", buf, sizeof(buf));
2505         else
2506                 ret = get_param_lmv(path, "numobd", buf, sizeof(buf));
2507         if (ret != 0)
2508                 return ret;
2509
2510         obdcount = atoi(buf);
2511         uuids = malloc(obdcount * sizeof(struct obd_uuid));
2512         if (uuids == NULL)
2513                 return -ENOMEM;
2514
2515 retry_get_uuids:
2516         ret = llapi_get_target_uuids(dirfd(dir), uuids, &obdcount, type);
2517         if (ret) {
2518                 if (ret == -EOVERFLOW) {
2519                         struct obd_uuid *uuids_temp;
2520
2521                         uuids_temp = realloc(uuids, obdcount *
2522                                              sizeof(struct obd_uuid));
2523                         if (uuids_temp != NULL) {
2524                                 uuids = uuids_temp;
2525                                 goto retry_get_uuids;
2526                         }
2527                         ret = -ENOMEM;
2528                 }
2529
2530                 llapi_error(LLAPI_MSG_ERROR, ret, "cannot get ost uuid");
2531                 goto out_free;
2532         }
2533
2534         indexes = malloc(num_obds * sizeof(*obdindex));
2535         if (indexes == NULL) {
2536                 ret = -ENOMEM;
2537                 goto out_free;
2538         }
2539
2540         for (obdnum = 0; obdnum < num_obds; obdnum++) {
2541                 char *end = NULL;
2542
2543                 /* The user may have specified a simple index */
2544                 i = strtol(obduuids[obdnum].uuid, &end, 0);
2545                 if (end && *end == '\0' && i < obdcount) {
2546                         indexes[obdnum] = i;
2547                         obd_valid++;
2548                 } else {
2549                         for (i = 0; i < obdcount; i++) {
2550                                 if (llapi_uuid_match(uuids[i].uuid,
2551                                                      obduuids[obdnum].uuid)) {
2552                                         indexes[obdnum] = i;
2553                                         obd_valid++;
2554                                         break;
2555                                 }
2556                         }
2557                 }
2558                 if (i >= obdcount) {
2559                         indexes[obdnum] = OBD_NOT_FOUND;
2560                         llapi_err_noerrno(LLAPI_MSG_ERROR,
2561                                           "invalid obduuid '%s'",
2562                                           obduuids[obdnum].uuid);
2563                         ret = -EINVAL;
2564                 }
2565         }
2566
2567         if (obd_valid == 0)
2568                 *obdindex = OBD_NOT_FOUND;
2569         else
2570                 *obdindex = obd_valid;
2571
2572         *obdindexes = indexes;
2573 out_free:
2574         if (uuids)
2575                 free(uuids);
2576
2577         return ret;
2578 }
2579
2580 static int setup_target_indexes(DIR *dir, char *path, struct find_param *param)
2581 {
2582         int ret = 0;
2583
2584         if (param->fp_mdt_uuid) {
2585                 ret = setup_indexes(dir, path, param->fp_mdt_uuid,
2586                                     param->fp_num_mdts,
2587                                     &param->fp_mdt_indexes,
2588                                     &param->fp_mdt_index, LMV_TYPE);
2589                 if (ret)
2590                         return ret;
2591         }
2592
2593         if (param->fp_obd_uuid) {
2594                 ret = setup_indexes(dir, path, param->fp_obd_uuid,
2595                                     param->fp_num_obds,
2596                                     &param->fp_obd_indexes,
2597                                     &param->fp_obd_index, LOV_TYPE);
2598                 if (ret)
2599                         return ret;
2600         }
2601
2602         param->fp_got_uuids = 1;
2603
2604         return ret;
2605 }
2606
2607 int llapi_ostlist(char *path, struct find_param *param)
2608 {
2609         int fd;
2610         int ret;
2611
2612         fd = open(path, O_RDONLY | O_DIRECTORY);
2613         if (fd < 0)
2614                 return -errno;
2615
2616         ret = setup_obd_uuid(fd, path, param);
2617         close(fd);
2618
2619         return ret;
2620 }
2621
2622 /*
2623  * Tries to determine the default stripe attributes for a given filesystem. The
2624  * filesystem to check should be specified by fsname, or will be determined
2625  * using pathname.
2626  */
2627 static int sattr_get_defaults(const char *const fsname,
2628                               unsigned int *scount,
2629                               unsigned int *ssize,
2630                               unsigned int *soffset)
2631 {
2632         char val[PATH_MAX];
2633         int rc;
2634
2635         if (scount) {
2636                 rc = get_lustre_param_value("lov", fsname, FILTER_BY_FS_NAME,
2637                                             "stripecount", val, sizeof(val));
2638                 if (rc != 0)
2639                         return rc;
2640                 *scount = atoi(val);
2641         }
2642
2643         if (ssize) {
2644                 rc = get_lustre_param_value("lov", fsname, FILTER_BY_FS_NAME,
2645                                             "stripesize", val, sizeof(val));
2646                 if (rc != 0)
2647                         return rc;
2648                 *ssize = atoi(val);
2649         }
2650
2651         if (soffset) {
2652                 rc = get_lustre_param_value("lov", fsname, FILTER_BY_FS_NAME,
2653                                             "stripeoffset", val, sizeof(val));
2654                 if (rc != 0)
2655                         return rc;
2656                 *soffset = atoi(val);
2657         }
2658
2659         return 0;
2660 }
2661
2662 /*
2663  * Tries to gather the default stripe attributes for a given filesystem. If
2664  * the attributes can be determined, they are cached for easy retreival the
2665  * next time they are needed. Only a single filesystem's attributes are
2666  * cached at a time.
2667  */
2668 int sattr_cache_get_defaults(const char *const fsname,
2669                              const char *const pathname, unsigned int *scount,
2670                              unsigned int *ssize, unsigned int *soffset)
2671 {
2672         static struct {
2673                 char fsname[PATH_MAX + 1];
2674                 unsigned int stripecount;
2675                 unsigned int stripesize;
2676                 unsigned int stripeoffset;
2677         } cache = {
2678                 .fsname = {'\0'}
2679         };
2680
2681         int rc;
2682         char fsname_buf[PATH_MAX + 1];
2683         unsigned int tmp[3];
2684
2685         if (fsname == NULL) {
2686                 rc = llapi_search_fsname(pathname, fsname_buf);
2687                 if (rc)
2688                         return rc;
2689         } else {
2690                 snprintf(fsname_buf, sizeof(fsname_buf), "%s", fsname);
2691         }
2692
2693         if (strncmp(fsname_buf, cache.fsname, sizeof(fsname_buf) - 1) != 0) {
2694                 /*
2695                  * Ensure all 3 sattrs (count, size, and offset) are
2696                  * successfully retrieved and stored in tmp before writing to
2697                  * cache.
2698                  */
2699                 rc = sattr_get_defaults(fsname_buf, &tmp[0], &tmp[1], &tmp[2]);
2700                 if (rc != 0)
2701                         return rc;
2702
2703                 cache.stripecount = tmp[0];
2704                 cache.stripesize = tmp[1];
2705                 cache.stripeoffset = tmp[2];
2706                 snprintf(cache.fsname, sizeof(cache.fsname), "%s", fsname_buf);
2707         }
2708
2709         if (scount)
2710                 *scount = cache.stripecount;
2711         if (ssize)
2712                 *ssize = cache.stripesize;
2713         if (soffset)
2714                 *soffset = cache.stripeoffset;
2715
2716         return 0;
2717 }
2718
2719 static char *layout2name(__u32 layout_pattern)
2720 {
2721         if (layout_pattern & LOV_PATTERN_F_RELEASED)
2722                 return "released";
2723         else if (layout_pattern == LOV_PATTERN_MDT)
2724                 return "mdt";
2725         else if (layout_pattern == LOV_PATTERN_RAID0)
2726                 return "raid0";
2727         else if (layout_pattern ==
2728                         (LOV_PATTERN_RAID0 | LOV_PATTERN_OVERSTRIPING))
2729                 return "raid0,overstriped";
2730         else
2731                 return "unknown";
2732 }
2733
2734 enum lov_dump_flags {
2735         LDF_IS_DIR      = 0x0001,
2736         LDF_IS_RAW      = 0x0002,
2737         LDF_INDENT      = 0x0004,
2738         LDF_SKIP_OBJS   = 0x0008,
2739         LDF_YAML        = 0x0010,
2740         LDF_EXTENSION   = 0x0020,
2741 };
2742
2743 static void lov_dump_user_lmm_header(struct lov_user_md *lum, char *path,
2744                                      struct lov_user_ost_data_v1 *objects,
2745                                      enum llapi_layout_verbose verbose,
2746                                      int depth, char *pool_name,
2747                                      enum lov_dump_flags flags)
2748 {
2749         bool is_dir = flags & LDF_IS_DIR;
2750         bool is_raw = flags & LDF_IS_RAW;
2751         bool indent = flags & LDF_INDENT;
2752         bool yaml = flags & LDF_YAML;
2753         bool skip_objs = flags & LDF_SKIP_OBJS;
2754         bool extension = flags & LDF_EXTENSION;
2755         char *prefix = is_dir ? "" : "lmm_";
2756         char *separator = "";
2757         char *space = indent ? "      " : "";
2758         int rc;
2759
2760         if (is_dir && lmm_oi_seq(&lum->lmm_oi) == FID_SEQ_LOV_DEFAULT) {
2761                 lmm_oi_set_seq(&lum->lmm_oi, 0);
2762                 if (!indent && (verbose & VERBOSE_DETAIL))
2763                         llapi_printf(LLAPI_MSG_NORMAL, "%s(Default) ", space);
2764         }
2765
2766         if (!yaml && !indent && depth && path &&
2767             ((verbose != VERBOSE_OBJID) || !is_dir))
2768                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
2769
2770         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
2771                 llapi_printf(LLAPI_MSG_NORMAL, "%s%smagic:         0x%08X\n",
2772                              space, prefix, lum->lmm_magic);
2773                 llapi_printf(LLAPI_MSG_NORMAL, "%s%sseq:           %#jx\n",
2774                              space, prefix,
2775                              (uintmax_t)lmm_oi_seq(&lum->lmm_oi));
2776                 llapi_printf(LLAPI_MSG_NORMAL, "%s%sobject_id:     %#jx\n",
2777                              space, prefix,
2778                              (uintmax_t)lmm_oi_id(&lum->lmm_oi));
2779         }
2780         if ((verbose & (VERBOSE_DETAIL | VERBOSE_DFID)) && !is_dir) {
2781                 __u64 seq;
2782                 __u32 oid;
2783                 __u32 ver;
2784
2785                 if (verbose & ~VERBOSE_DFID)
2786                         llapi_printf(LLAPI_MSG_NORMAL, "%slmm_fid:           ",
2787                                      space);
2788                 /* This needs a bit of hand-holding since old 1.x lmm_oi
2789                  * have { oi.oi_id = mds_inum, oi.oi_seq = 0 } and 2.x lmm_oi
2790                  * have { oi.oi_id = mds_oid, oi.oi_seq = mds_seq } instead of
2791                  * a real FID.  Ideally the 2.x code would have stored this
2792                  * like a FID with { oi_id = mds_seq, oi_seq = mds_oid } so the
2793                  * ostid union lu_fid { f_seq = mds_seq, f_oid = mds_oid }
2794                  * worked properly (especially since IGIF FIDs use mds_inum as
2795                  * the FID SEQ), but unfortunately that didn't happen.
2796                  *
2797                  * Print it to look like an IGIF FID, even though the fields
2798                  * are reversed on disk, so that it makes sense to userspace.
2799                  *
2800                  * Don't use ostid_id() and ostid_seq(), since they assume the
2801                  * oi_fid fields are in the right order.  This is why there are
2802                  * separate lmm_oi_seq() and lmm_oi_id() routines for this.
2803                  *
2804                  * For newer layout types hopefully this will be a real FID. */
2805                 seq = lmm_oi_seq(&lum->lmm_oi) == 0 ?
2806                         lmm_oi_id(&lum->lmm_oi) : lmm_oi_seq(&lum->lmm_oi);
2807                 oid = lmm_oi_seq(&lum->lmm_oi) == 0 ?
2808                         0 : (__u32)lmm_oi_id(&lum->lmm_oi);
2809                 ver = (__u32)(lmm_oi_id(&lum->lmm_oi) >> 32);
2810                 if (yaml)
2811                         llapi_printf(LLAPI_MSG_NORMAL, DFID_NOBRACE"\n",
2812                                      (unsigned long long)seq, oid, ver);
2813                 else
2814                         llapi_printf(LLAPI_MSG_NORMAL, DFID"\n",
2815                                      (unsigned long long)seq, oid, ver);
2816         }
2817
2818         if (verbose & VERBOSE_STRIPE_COUNT) {
2819                 if (verbose & ~VERBOSE_STRIPE_COUNT)
2820                         llapi_printf(LLAPI_MSG_NORMAL, "%s%sstripe_count:  ",
2821                                      space, prefix);
2822                 if (is_dir) {
2823                         if (!is_raw && lum->lmm_stripe_count == 0 &&
2824                             lov_pattern(lum->lmm_pattern) != LOV_PATTERN_MDT) {
2825                                 unsigned int scount;
2826                                 rc = sattr_cache_get_defaults(NULL, path,
2827                                                               &scount, NULL,
2828                                                               NULL);
2829                                 if (rc == 0)
2830                                         llapi_printf(LLAPI_MSG_NORMAL, "%d",
2831                                                      scount);
2832                                 else
2833                                         llapi_error(LLAPI_MSG_ERROR, rc,
2834                                                     "Cannot determine default"
2835                                                     " stripe count.");
2836                         } else {
2837                                 llapi_printf(LLAPI_MSG_NORMAL, "%d",
2838                                              extension ? 0 :
2839                                              (__s16)lum->lmm_stripe_count);
2840                         }
2841                 } else {
2842                         llapi_printf(LLAPI_MSG_NORMAL, "%hd",
2843                                      extension ? 0 :
2844                                      (__s16)lum->lmm_stripe_count);
2845                 }
2846                 if (!yaml && is_dir)
2847                         separator = " ";
2848                 else
2849                         separator = "\n";
2850         }
2851
2852         if (((verbose & VERBOSE_STRIPE_SIZE) && !extension) ||
2853             ((verbose & VERBOSE_EXT_SIZE) && extension)) {
2854                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2855                 if (verbose & ~VERBOSE_EXT_SIZE && extension)
2856                         llapi_printf(LLAPI_MSG_NORMAL, "%s%sextension_size: ",
2857                                      space, prefix);
2858                 if (verbose & ~VERBOSE_STRIPE_SIZE && !extension)
2859                         llapi_printf(LLAPI_MSG_NORMAL, "%s%sstripe_size:   ",
2860                                      space, prefix);
2861                 if (is_dir && !is_raw && lum->lmm_stripe_size == 0) {
2862                         unsigned int ssize;
2863                         rc = sattr_cache_get_defaults(NULL, path, NULL, &ssize,
2864                                                       NULL);
2865                         if (rc == 0)
2866                                 llapi_printf(LLAPI_MSG_NORMAL, "%u", ssize);
2867                         else
2868                                 llapi_error(LLAPI_MSG_ERROR, rc,
2869                                             "Cannot determine default"
2870                                             " stripe size.");
2871                 } else {
2872                         /* Extension size is in KiB */
2873                         llapi_printf(LLAPI_MSG_NORMAL, "%llu",
2874                                      extension ?
2875                                      (unsigned long long)(lum->lmm_stripe_size * SEL_UNIT_SIZE) :
2876                                      (unsigned long long)lum->lmm_stripe_size);
2877                 }
2878                 if (!yaml && is_dir)
2879                         separator = " ";
2880                 else
2881                         separator = "\n";
2882         }
2883
2884         if ((verbose & VERBOSE_PATTERN)) {
2885                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2886                 if (verbose & ~VERBOSE_PATTERN)
2887                         llapi_printf(LLAPI_MSG_NORMAL, "%s%spattern:       ",
2888                                      space, prefix);
2889                 if (lov_pattern_supported(lum->lmm_pattern))
2890                         llapi_printf(LLAPI_MSG_NORMAL, "%s",
2891                                      layout2name(lum->lmm_pattern));
2892                 else
2893                         llapi_printf(LLAPI_MSG_NORMAL, "%x", lum->lmm_pattern);
2894                 separator = (!yaml && is_dir) ? " " : "\n";
2895         }
2896
2897         if ((verbose & VERBOSE_GENERATION) && !is_dir) {
2898                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2899                 if (verbose & ~VERBOSE_GENERATION)
2900                         llapi_printf(LLAPI_MSG_NORMAL, "%s%slayout_gen:    ",
2901                                      space, prefix);
2902                 llapi_printf(LLAPI_MSG_NORMAL, "%u",
2903                              skip_objs ? 0 : (int)lum->lmm_layout_gen);
2904                 separator = "\n";
2905         }
2906
2907         if (verbose & VERBOSE_STRIPE_OFFSET) {
2908                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2909                 if (verbose & ~VERBOSE_STRIPE_OFFSET)
2910                         llapi_printf(LLAPI_MSG_NORMAL, "%s%sstripe_offset: ",
2911                                      space, prefix);
2912                 if (is_dir || skip_objs)
2913                         llapi_printf(LLAPI_MSG_NORMAL, "%d",
2914                                      lum->lmm_stripe_offset ==
2915                                      (typeof(lum->lmm_stripe_offset))(-1) ? -1 :
2916                                      lum->lmm_stripe_offset);
2917                 else if (lov_pattern(lum->lmm_pattern) == LOV_PATTERN_MDT)
2918                         llapi_printf(LLAPI_MSG_NORMAL, "0");
2919                 else
2920                         llapi_printf(LLAPI_MSG_NORMAL, "%u",
2921                                      objects[0].l_ost_idx);
2922                 if (!yaml && is_dir)
2923                         separator = " ";
2924                 else
2925                         separator = "\n";
2926         }
2927
2928         if ((verbose & VERBOSE_POOL) && pool_name && (pool_name[0] != '\0')) {
2929                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2930                 if (verbose & ~VERBOSE_POOL)
2931                         llapi_printf(LLAPI_MSG_NORMAL, "%s%spool:          ",
2932                                      space, prefix);
2933                 llapi_printf(LLAPI_MSG_NORMAL, "%s", pool_name);
2934                 if (!yaml && is_dir)
2935                         separator = " ";
2936                 else
2937                         separator = "\n";
2938         }
2939
2940         if (strlen(separator) != 0)
2941                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
2942 }
2943
2944 void lov_dump_user_lmm_v1v3(struct lov_user_md *lum, char *pool_name,
2945                             struct lov_user_ost_data_v1 *objects,
2946                             char *path, int obdindex, int depth,
2947                             enum llapi_layout_verbose verbose,
2948                             enum lov_dump_flags flags)
2949 {
2950         bool is_dir = flags & LDF_IS_DIR;
2951         bool indent = flags & LDF_INDENT;
2952         bool skip_objs = flags & LDF_SKIP_OBJS;
2953         bool yaml = flags & LDF_YAML;
2954         bool obdstripe = obdindex == OBD_NOT_FOUND;
2955         int i;
2956
2957         if (!obdstripe && !skip_objs) {
2958                 for (i = 0; !is_dir && i < lum->lmm_stripe_count; i++) {
2959                         if (obdindex == objects[i].l_ost_idx) {
2960                                 obdstripe = true;
2961                                 break;
2962                         }
2963                 }
2964         }
2965
2966         if (!obdstripe)
2967                 return;
2968
2969         lov_dump_user_lmm_header(lum, path, objects, verbose, depth, pool_name,
2970                                  flags);
2971
2972         if (!is_dir && !skip_objs && (verbose & VERBOSE_OBJID) &&
2973             !(lum->lmm_pattern & LOV_PATTERN_F_RELEASED ||
2974               lov_pattern(lum->lmm_pattern) == LOV_PATTERN_MDT)) {
2975                 char *space = "      - ";
2976
2977                 if (indent)
2978                         llapi_printf(LLAPI_MSG_NORMAL,
2979                                      "%6slmm_objects:\n", " ");
2980                 else if (yaml)
2981                         llapi_printf(LLAPI_MSG_NORMAL, "lmm_objects:\n");
2982                 else
2983                         llapi_printf(LLAPI_MSG_NORMAL,
2984                                 "\tobdidx\t\t objid\t\t objid\t\t group\n");
2985
2986                 for (i = 0; i < lum->lmm_stripe_count; i++) {
2987                         int idx = objects[i].l_ost_idx;
2988                         long long oid = ostid_id(&objects[i].l_ost_oi);
2989                         long long gr = ostid_seq(&objects[i].l_ost_oi);
2990
2991                         if (obdindex != OBD_NOT_FOUND && obdindex != idx)
2992                                 continue;
2993
2994                         if (yaml) {
2995                                 struct lu_fid fid = { 0 };
2996
2997                                 ostid_to_fid(&fid, &objects[i].l_ost_oi, idx);
2998                                 llapi_printf(LLAPI_MSG_NORMAL,
2999                                     "%sl_ost_idx: %d\n", space, idx);
3000                                 llapi_printf(LLAPI_MSG_NORMAL,
3001                                     "%8sl_fid:     "DFID_NOBRACE"\n",
3002                                     " ", PFID(&fid));
3003                         } else if (indent) {
3004                                 struct lu_fid fid = { 0 };
3005
3006                                 ostid_to_fid(&fid, &objects[i].l_ost_oi, idx);
3007                                 llapi_printf(LLAPI_MSG_NORMAL,
3008                                     "%s%d: { l_ost_idx: %d, l_fid: "DFID" }\n",
3009                                     space, i, idx, PFID(&fid));
3010                         } else {
3011                                 char fmt[48];
3012                                 sprintf(fmt, "%s%s%s\n",
3013                                         "\t%6u\t%14llu\t%#13llx\t",
3014                                         (fid_seq_is_rsvd(gr) ||
3015                                          fid_seq_is_mdt0(gr)) ?
3016                                          "%14llu" : "%#14llx", "%s");
3017                                 llapi_printf(LLAPI_MSG_NORMAL, fmt, idx, oid,
3018                                              oid, gr,
3019                                              obdindex == idx ? " *" : "");
3020                         }
3021                 }
3022         }
3023         llapi_printf(LLAPI_MSG_NORMAL, "\n");
3024 }
3025
3026 void lmv_dump_user_lmm(struct lmv_user_md *lum, char *pool_name,
3027                        char *path, int obdindex, int depth,
3028                        enum llapi_layout_verbose verbose,
3029                        enum lov_dump_flags flags)
3030 {
3031         struct lmv_user_mds_data *objects = lum->lum_objects;
3032         char *prefix = lum->lum_magic == LMV_USER_MAGIC ? "(Default)" : "";
3033         char *separator = "";
3034         bool yaml = flags & LDF_YAML;
3035         bool obdstripe = false;
3036         int i;
3037
3038         if (obdindex != OBD_NOT_FOUND) {
3039                 if (lum->lum_stripe_count == 0) {
3040                         if (obdindex == lum->lum_stripe_offset)
3041                                 obdstripe = true;
3042                 } else {
3043                         for (i = 0; i < lum->lum_stripe_count; i++) {
3044                                 if (obdindex == objects[i].lum_mds) {
3045                                         llapi_printf(LLAPI_MSG_NORMAL,
3046                                                      "%s%s\n", prefix,
3047                                                      path);
3048                                         obdstripe = true;
3049                                         break;
3050                                 }
3051                         }
3052                 }
3053         } else {
3054                 obdstripe = true;
3055         }
3056
3057         if (!obdstripe)
3058                 return;
3059
3060         /* show all information default */
3061         if (!verbose) {
3062                 if (lum->lum_magic == LMV_USER_MAGIC)
3063                         verbose = VERBOSE_POOL | VERBOSE_STRIPE_COUNT |
3064                                   VERBOSE_STRIPE_OFFSET | VERBOSE_HASH_TYPE;
3065                 else
3066                         verbose = VERBOSE_OBJID;
3067         }
3068
3069         if (depth && path && ((verbose != VERBOSE_OBJID)))
3070                 llapi_printf(LLAPI_MSG_NORMAL, "%s%s\n", prefix, path);
3071
3072         if (verbose & VERBOSE_STRIPE_COUNT) {
3073                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3074                 if (verbose & ~VERBOSE_STRIPE_COUNT)
3075                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_stripe_count: ");
3076                 llapi_printf(LLAPI_MSG_NORMAL, "%u",
3077                              (int)lum->lum_stripe_count);
3078                 if ((verbose & VERBOSE_STRIPE_OFFSET) && !yaml)
3079                         separator = " ";
3080                 else
3081                         separator = "\n";
3082         }
3083
3084         if (verbose & VERBOSE_STRIPE_OFFSET) {
3085                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3086                 if (verbose & ~VERBOSE_STRIPE_OFFSET)
3087                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_stripe_offset: ");
3088                 llapi_printf(LLAPI_MSG_NORMAL, "%d",
3089                              (int)lum->lum_stripe_offset);
3090                 if (verbose & VERBOSE_HASH_TYPE && !yaml)
3091                         separator = " ";
3092                 else
3093                         separator = "\n";
3094         }
3095
3096         if (verbose & VERBOSE_HASH_TYPE) {
3097                 unsigned int type = lum->lum_hash_type & LMV_HASH_TYPE_MASK;
3098                 unsigned int flags = lum->lum_hash_type & ~LMV_HASH_TYPE_MASK;
3099
3100                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3101                 if (verbose & ~VERBOSE_HASH_TYPE)
3102                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_hash_type: ");
3103                 if (type < LMV_HASH_TYPE_MAX)
3104                         llapi_printf(LLAPI_MSG_NORMAL, "%s",
3105                                      mdt_hash_name[type]);
3106                 else
3107                         llapi_printf(LLAPI_MSG_NORMAL, "%#x", type);
3108
3109                 if (flags & LMV_HASH_FLAG_SPACE)
3110                         llapi_printf(LLAPI_MSG_NORMAL, ",space");
3111                 if (flags & LMV_HASH_FLAG_MIGRATION)
3112                         llapi_printf(LLAPI_MSG_NORMAL, ",migrating");
3113                 if (flags & LMV_HASH_FLAG_BAD_TYPE)
3114                         llapi_printf(LLAPI_MSG_NORMAL, ",bad_type");
3115                 if (flags & LMV_HASH_FLAG_LOST_LMV)
3116                         llapi_printf(LLAPI_MSG_NORMAL, ",lost_lmv");
3117                 separator = "\n";
3118
3119         }
3120
3121         if (verbose & VERBOSE_OBJID && lum->lum_magic != LMV_USER_MAGIC) {
3122                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3123                 if (lum->lum_stripe_count > 0)
3124                         llapi_printf(LLAPI_MSG_NORMAL,
3125                                      "mdtidx\t\t FID[seq:oid:ver]\n");
3126                 for (i = 0; i < lum->lum_stripe_count; i++) {
3127                         int idx = objects[i].lum_mds;
3128                         struct lu_fid *fid = &objects[i].lum_fid;
3129                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
3130                                 llapi_printf(LLAPI_MSG_NORMAL,
3131                                              "%6u\t\t "DFID"\t\t%s\n",
3132                                             idx, PFID(fid),
3133                                             obdindex == idx ? " *" : "");
3134                 }
3135
3136         }
3137
3138         if ((verbose & VERBOSE_POOL) && pool_name != NULL &&
3139              pool_name[0] != '\0') {
3140                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3141                 if (verbose & ~VERBOSE_POOL)
3142                         llapi_printf(LLAPI_MSG_NORMAL, "%slmv_pool:           ",
3143                                      prefix);
3144                 llapi_printf(LLAPI_MSG_NORMAL, "%s%c ", pool_name, ' ');
3145                 separator = "\n";
3146         }
3147
3148         if (!(verbose & VERBOSE_OBJID) || lum->lum_magic == LMV_USER_MAGIC)
3149                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
3150 }
3151
3152 static void lov_dump_comp_v1_header(struct find_param *param, char *path,
3153                                     enum lov_dump_flags flags)
3154 {
3155         struct lov_comp_md_v1 *comp_v1 = (void *)&param->fp_lmd->lmd_lmm;
3156         int depth = param->fp_max_depth;
3157         enum llapi_layout_verbose verbose = param->fp_verbose;
3158         bool yaml = flags & LDF_YAML;
3159
3160         if (depth && path && ((verbose != VERBOSE_OBJID) ||
3161                               !(flags & LDF_IS_DIR)) && !yaml)
3162                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
3163
3164         if (verbose & VERBOSE_DETAIL) {
3165                 llapi_printf(LLAPI_MSG_NORMAL, "composite_header:\n");
3166                 llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_magic:         0x%08X\n",
3167                              " ", comp_v1->lcm_magic);
3168                 llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_size:          %u\n",
3169                              " ", comp_v1->lcm_size);
3170                 if (flags & LDF_IS_DIR)
3171                         llapi_printf(LLAPI_MSG_NORMAL,
3172                                      "%2slcm_flags:         %s\n", " ",
3173                                      comp_v1->lcm_mirror_count > 0 ?
3174                                                         "mirrored" : "");
3175                 else
3176                         llapi_printf(LLAPI_MSG_NORMAL,
3177                                      "%2slcm_flags:         %s\n", " ",
3178                                 llapi_layout_flags_string(comp_v1->lcm_flags));
3179         }
3180
3181         if (verbose & VERBOSE_GENERATION) {
3182                 if (verbose & ~VERBOSE_GENERATION)
3183                         llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_layout_gen:    ",
3184                                      " ");
3185                 llapi_printf(LLAPI_MSG_NORMAL, "%u\n", comp_v1->lcm_layout_gen);
3186         }
3187
3188         if (verbose & VERBOSE_MIRROR_COUNT) {
3189                 if (verbose & ~VERBOSE_MIRROR_COUNT)
3190                         llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_mirror_count:  ",
3191                                      " ");
3192                 llapi_printf(LLAPI_MSG_NORMAL, "%u\n",
3193                              comp_v1->lcm_magic == LOV_USER_MAGIC_COMP_V1 ?
3194                              comp_v1->lcm_mirror_count + 1 : 1);
3195         }
3196
3197         if (verbose & VERBOSE_COMP_COUNT) {
3198                 if (verbose & ~VERBOSE_COMP_COUNT)
3199                         llapi_printf(LLAPI_MSG_NORMAL, "%2slcm_entry_count:   ",
3200                                      " ");
3201                 llapi_printf(LLAPI_MSG_NORMAL, "%u\n",
3202                              comp_v1->lcm_magic == LOV_USER_MAGIC_COMP_V1 ?
3203                              comp_v1->lcm_entry_count : 0);
3204         }
3205
3206         if (verbose & VERBOSE_DETAIL && !yaml)
3207                 llapi_printf(LLAPI_MSG_NORMAL, "components:\n");
3208 }
3209
3210 static void lcme_flags2str(__u32 comp_flags)
3211 {
3212         bool found = false;
3213         int i = 0;
3214
3215         if (!comp_flags) {
3216                 llapi_printf(LLAPI_MSG_NORMAL, "0");
3217                 return;
3218         }
3219         for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
3220                 if (comp_flags & comp_flags_table[i].cfn_flag) {
3221                         if (found)
3222                                 llapi_printf(LLAPI_MSG_NORMAL, ",");
3223                         llapi_printf(LLAPI_MSG_NORMAL, "%s",
3224                                      comp_flags_table[i].cfn_name);
3225                         comp_flags &= ~comp_flags_table[i].cfn_flag;
3226                         found = true;
3227                 }
3228         }
3229         if (comp_flags) {
3230                 if (found)
3231                         llapi_printf(LLAPI_MSG_NORMAL, ",");
3232                 llapi_printf(LLAPI_MSG_NORMAL, "%#x", comp_flags);
3233         }
3234 }
3235
3236 static void lov_dump_comp_v1_entry(struct find_param *param,
3237                                    enum lov_dump_flags flags, int index)
3238 {
3239         struct lov_comp_md_v1 *comp_v1 = (void *)&param->fp_lmd->lmd_lmm;
3240         struct lov_comp_md_entry_v1 *entry;
3241         char *separator = "";
3242         enum llapi_layout_verbose verbose = param->fp_verbose;
3243         bool yaml = flags & LDF_YAML;
3244
3245         entry = &comp_v1->lcm_entries[index];
3246
3247         if (yaml)
3248                 llapi_printf(LLAPI_MSG_NORMAL, "%2scomponent%d:\n", " ", index);
3249
3250         if (verbose & VERBOSE_COMP_ID) {
3251                 if (verbose & VERBOSE_DETAIL && !yaml)
3252                         llapi_printf(LLAPI_MSG_NORMAL,
3253                                      "%slcme_id:             ", "  - ");
3254                 else if (verbose & ~VERBOSE_COMP_ID)
3255                         llapi_printf(LLAPI_MSG_NORMAL,
3256                                      "%4slcme_id:             ", " ");
3257                 if (entry->lcme_id != LCME_ID_INVAL)
3258                         llapi_printf(LLAPI_MSG_NORMAL, "%u", entry->lcme_id);
3259                 else
3260                         llapi_printf(LLAPI_MSG_NORMAL, "N/A");
3261                 separator = "\n";
3262         }
3263
3264         if (verbose & VERBOSE_MIRROR_ID) {
3265                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3266                 if (verbose & ~VERBOSE_MIRROR_ID)
3267                         llapi_printf(LLAPI_MSG_NORMAL,
3268                                      "%4slcme_mirror_id:      ", " ");
3269                 if (entry->lcme_id != LCME_ID_INVAL)
3270                         llapi_printf(LLAPI_MSG_NORMAL, "%u",
3271                                      mirror_id_of(entry->lcme_id));
3272                 else
3273                         llapi_printf(LLAPI_MSG_NORMAL, "N/A");
3274                 separator = "\n";
3275         }
3276
3277         if (verbose & VERBOSE_COMP_FLAGS) {
3278                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3279                 if (verbose & ~VERBOSE_COMP_FLAGS)
3280                         llapi_printf(LLAPI_MSG_NORMAL,
3281                                      "%4slcme_flags:          ", " ");
3282                 lcme_flags2str(entry->lcme_flags);
3283                 separator = "\n";
3284         }
3285         /* print snapshot timestamp if its a nosync comp */
3286         if ((verbose & VERBOSE_COMP_FLAGS) &&
3287             (entry->lcme_flags & LCME_FL_NOSYNC)) {
3288                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3289                 if (verbose & ~VERBOSE_COMP_FLAGS)
3290                         llapi_printf(LLAPI_MSG_NORMAL,
3291                                      "%4slcme_timestamp:      ", " ");
3292                 if (yaml) {
3293                         llapi_printf(LLAPI_MSG_NORMAL, "%llu",
3294                                      (unsigned long long)entry->lcme_timestamp);
3295                 } else {
3296                         time_t stamp = entry->lcme_timestamp;
3297                         char *date_str = asctime(localtime(&stamp));
3298
3299                         date_str[strlen(date_str) - 1] = '\0';
3300                         llapi_printf(LLAPI_MSG_NORMAL, "'%s'", date_str);
3301                 }
3302
3303                 separator = "\n";
3304         }
3305
3306         if (verbose & VERBOSE_COMP_START) {
3307                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3308                 if (verbose & ~VERBOSE_COMP_START)
3309                         llapi_printf(LLAPI_MSG_NORMAL,
3310                                      "%4slcme_extent.e_start: ", " ");
3311                 llapi_printf(LLAPI_MSG_NORMAL, "%llu",
3312                              (unsigned long long)entry->lcme_extent.e_start);
3313                 separator = "\n";
3314         }
3315
3316         if (verbose & VERBOSE_COMP_END) {
3317                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3318                 if (verbose & ~VERBOSE_COMP_END)
3319                         llapi_printf(LLAPI_MSG_NORMAL,
3320                                      "%4slcme_extent.e_end:   ", " ");
3321                 if (entry->lcme_extent.e_end == LUSTRE_EOF)
3322                         llapi_printf(LLAPI_MSG_NORMAL, "%s", "EOF");
3323                 else
3324                         llapi_printf(LLAPI_MSG_NORMAL, "%llu",
3325                                      (unsigned long long)entry->lcme_extent.e_end);
3326                 separator = "\n";
3327         }
3328
3329         if (yaml) {
3330                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3331                 llapi_printf(LLAPI_MSG_NORMAL, "%4ssub_layout:\n", " ");
3332         } else if (verbose & VERBOSE_DETAIL) {
3333                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3334                 llapi_printf(LLAPI_MSG_NORMAL, "%4slcme_offset:         %u\n",
3335                              " ", entry->lcme_offset);
3336                 llapi_printf(LLAPI_MSG_NORMAL, "%4slcme_size:           %u\n",
3337                              " ", entry->lcme_size);
3338                 llapi_printf(LLAPI_MSG_NORMAL, "%4ssub_layout:\n", " ");
3339         } else {
3340                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
3341         }
3342 }
3343
3344 /* Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
3345  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
3346  *
3347  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
3348  * The table below gives the answers for the specified parameters (value and
3349  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
3350  * --------------------------------------
3351  * 1 | file > limit; sign > 0 | -1 / -1 |
3352  * 2 | file = limit; sign > 0 | -1 / -1 |
3353  * 3 | file < limit; sign > 0 |  ? /  1 |
3354  * 4 | file > limit; sign = 0 | -1 / -1 |
3355  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
3356  * 6 | file < limit; sign = 0 |  ? / -1 |
3357  * 7 | file > limit; sign < 0 |  1 /  1 |
3358  * 8 | file = limit; sign < 0 |  ? / -1 |
3359  * 9 | file < limit; sign < 0 |  ? / -1 |
3360  * --------------------------------------
3361  * Note: 5th actually means that the value is within the interval
3362  * (limit - margin, limit]. */
3363 static int find_value_cmp(unsigned long long file, unsigned long long limit,
3364                           int sign, int negopt, unsigned long long margin,
3365                           bool mds)
3366 {
3367         int ret = -1;
3368
3369         if (sign > 0) {
3370                 /* Drop the fraction of margin (of days or size). */
3371                 if (file + margin <= limit)
3372                         ret = mds ? 0 : 1;
3373         } else if (sign == 0) {
3374                 if (file <= limit && file + margin > limit)
3375                         ret = mds ? 0 : 1;
3376                 else if (file + margin <= limit)
3377                         ret = mds ? 0 : -1;
3378         } else if (sign < 0) {
3379                 if (file > limit)
3380                         ret = 1;
3381                 else if (mds)
3382                         ret = 0;
3383         }
3384
3385         return negopt ? ~ret + 1 : ret;
3386 }
3387
3388 static inline struct lov_user_md *
3389 lov_comp_entry(struct lov_comp_md_v1 *comp_v1, int ent_idx)
3390 {
3391         return (struct lov_user_md *)((char *)comp_v1 +
3392                         comp_v1->lcm_entries[ent_idx].lcme_offset);
3393 }
3394
3395 static inline struct lov_user_ost_data_v1 *
3396 lov_v1v3_objects(struct lov_user_md *v1)
3397 {
3398         if (v1->lmm_magic == LOV_USER_MAGIC_V3)
3399                 return ((struct lov_user_md_v3 *)v1)->lmm_objects;
3400         else
3401                 return v1->lmm_objects;
3402 }
3403
3404 static inline void
3405 lov_v1v3_pool_name(struct lov_user_md *v1, char *pool_name)
3406 {
3407         if (v1->lmm_magic == LOV_USER_MAGIC_V3)
3408                 snprintf(pool_name, LOV_MAXPOOLNAME, "%s",
3409                          ((struct lov_user_md_v3 *)v1)->lmm_pool_name);
3410         else
3411                 pool_name[0] = '\0';
3412 }
3413
3414 static inline bool
3415 print_last_init_comp(struct find_param *param)
3416 {
3417         /* print all component info */
3418         if ((param->fp_verbose & VERBOSE_DEFAULT) == VERBOSE_DEFAULT)
3419                 return false;
3420
3421         /* print specific component info */
3422         if (param->fp_check_comp_id || param->fp_check_comp_flags ||
3423             param->fp_check_comp_start || param->fp_check_comp_end ||
3424             param->fp_check_mirror_id || param->fp_check_mirror_index)
3425                 return false;
3426
3427         return true;
3428 }
3429
3430 static int find_comp_end_cmp(unsigned long long end, struct find_param *param)
3431 {
3432         int match;
3433
3434         if (param->fp_comp_end == LUSTRE_EOF) {
3435                 if (param->fp_comp_end_sign == 0) /* equal to EOF */
3436                         match = end == LUSTRE_EOF ? 1 : -1;
3437                 else if (param->fp_comp_end_sign > 0) /* at most EOF */
3438                         match = end == LUSTRE_EOF ? -1 : 1;
3439                 else /* at least EOF */
3440                         match = -1;
3441                 if (param->fp_exclude_comp_end)
3442                         match = ~match + 1;
3443         } else {
3444                 unsigned long long margin;
3445
3446                 margin = end == LUSTRE_EOF ? 0 : param->fp_comp_end_units;
3447                 match = find_value_cmp(end, param->fp_comp_end,
3448                                        param->fp_comp_end_sign,
3449                                        param->fp_exclude_comp_end, margin, 0);
3450         }
3451
3452         return match;
3453 }
3454
3455 /**
3456  * An example of "getstripe -v" for a two components PFL file:
3457  *
3458  * composite_header:
3459  * lcm_magic:       0x0BD60BD0
3460  * lcm_size:        264
3461  * lcm_flags:       0
3462  * lcm_layout_gen:  2
3463  * lcm_entry_count: 2
3464  * components:
3465  * - lcme_id:             1
3466  *   lcme_flags:          0x10
3467  *   lcme_extent.e_start: 0
3468  *   lcme_extent.e_end:   1048576
3469  *   lcme_offset:         128
3470  *   lcme_size:           56
3471  *   sub_layout:
3472  *     lmm_magic:         0x0BD10BD0
3473  *     lmm_seq:           0x200000401
3474  *     lmm_object_id:     0x1
3475  *     lmm_fid:           [0x200000401:0x1:0x0]
3476  *     lmm_stripe_count:  1
3477  *     lmm_stripe_size:   1048576
3478  *     lmm_pattern:       raid0
3479  *     lmm_layout_gen:    0
3480  *     lmm_stripe_offset: 0
3481  *     lmm_objects:
3482  *     - 0: { l_ost_idx: 0, l_fid: [0x100000000:0x2:0x0] }
3483  *
3484  * - lcme_id:             2
3485  *   lcme_flags:          0x10
3486  *   lcme_extent.e_start: 1048576
3487  *   lcme_extent.e_end:   EOF
3488  *   lcme_offset:         184
3489  *   lcme_size:           80
3490  *     sub_layout:
3491  *     lmm_magic:         0x0BD10BD0
3492  *     lmm_seq:           0x200000401
3493  *     lmm_object_id:     0x1
3494  *     lmm_fid:           [0x200000401:0x1:0x0]
3495  *     lmm_stripe_count:  2
3496  *     lmm_stripe_size:   1048576
3497  *     lmm_pattern:       raid0
3498  *     lmm_layout_gen:    0
3499  *     lmm_stripe_offset: 1
3500  *     lmm_objects:
3501  *     - 0: { l_ost_idx: 1, l_fid: [0x100010000:0x2:0x0] }
3502  *     - 1: { l_ost_idx: 0, l_fid: [0x100000000:0x3:0x0] }
3503  */
3504 static void lov_dump_comp_v1(struct find_param *param, char *path,
3505                              enum lov_dump_flags flags)
3506 {
3507         struct lov_comp_md_entry_v1 *entry;
3508         struct lov_user_ost_data_v1 *objects;
3509         struct lov_comp_md_v1 *comp_v1 = (void *)&param->fp_lmd->lmd_lmm;
3510         struct lov_user_md_v1 *v1;
3511         char pool_name[LOV_MAXPOOLNAME + 1];
3512         int obdindex = param->fp_obd_index;
3513         int i, j, match, ext;
3514         bool obdstripe = false;
3515         __u16 mirror_index = 0;
3516         __u16 mirror_id = 0;
3517
3518         if (obdindex != OBD_NOT_FOUND) {
3519                 for (i = 0; !(flags & LDF_IS_DIR) && !obdstripe &&
3520                             i < comp_v1->lcm_entry_count; i++) {
3521                         if (!(comp_v1->lcm_entries[i].lcme_flags &
3522                               LCME_FL_INIT))
3523                                 continue;
3524
3525                         v1 = lov_comp_entry(comp_v1, i);
3526                         objects = lov_v1v3_objects(v1);
3527
3528                         for (j = 0; j < v1->lmm_stripe_count; j++) {
3529                                 if (obdindex == objects[j].l_ost_idx) {
3530                                         obdstripe = true;
3531                                         break;
3532                                 }
3533                         }
3534                 }
3535         } else {
3536                 obdstripe = true;
3537         }
3538
3539         if (!obdstripe)
3540                 return;
3541
3542         lov_dump_comp_v1_header(param, path, flags);
3543
3544         flags |= LDF_INDENT;
3545
3546         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
3547                 entry = &comp_v1->lcm_entries[i];
3548
3549                 if (param->fp_check_comp_flags) {
3550                         if (((param->fp_comp_flags & entry->lcme_flags) !=
3551                              param->fp_comp_flags) ||
3552                             (param->fp_comp_neg_flags & entry->lcme_flags))
3553                                 continue;
3554                 }
3555
3556                 if (param->fp_check_comp_id &&
3557                     param->fp_comp_id != entry->lcme_id)
3558                         continue;
3559
3560                 if (param->fp_check_comp_start) {
3561                         match = find_value_cmp(entry->lcme_extent.e_start,
3562                                                param->fp_comp_start,
3563                                                param->fp_comp_start_sign,
3564                                                0,
3565                                                param->fp_comp_start_units, 0);
3566                         if (match == -1)
3567                                 continue;
3568                 }
3569
3570                 if (param->fp_check_comp_end) {
3571                         match = find_comp_end_cmp(entry->lcme_extent.e_end,
3572                                                   param);
3573                         if (match == -1)
3574                                 continue;
3575                 }
3576
3577                 if (param->fp_check_mirror_index) {
3578                         if (mirror_id != mirror_id_of(entry->lcme_id)) {
3579                                 mirror_index++;
3580                                 mirror_id = mirror_id_of(entry->lcme_id);
3581                         }
3582
3583                         match = find_value_cmp(mirror_index,
3584                                                param->fp_mirror_index,
3585                                                param->fp_mirror_index_sign,
3586                                                param->fp_exclude_mirror_index,
3587                                                1, 0);
3588                         if (match == -1)
3589                                 continue;
3590                 } else if (param->fp_check_mirror_id) {
3591                         if (mirror_id != mirror_id_of(entry->lcme_id))
3592                                 mirror_id = mirror_id_of(entry->lcme_id);
3593
3594                         match = find_value_cmp(mirror_id,
3595                                                param->fp_mirror_id,
3596                                                param->fp_mirror_id_sign,
3597                                                param->fp_exclude_mirror_id,
3598                                                1, 0);
3599                         if (match == -1)
3600                                 continue;
3601                 }
3602
3603                 if (print_last_init_comp(param)) {
3604                         /**
3605                          * if part of stripe info is needed, we'd print only
3606                          * the last instantiated component info.
3607                          */
3608                         if (entry->lcme_flags & LCME_FL_INIT)
3609                                 continue;
3610
3611                         if (param->fp_verbose & VERBOSE_EXT_SIZE) {
3612                                 if (entry->lcme_flags & LCME_FL_EXTENSION)
3613                                         /* moved back below */
3614                                         i++;
3615                                 else
3616                                         continue;
3617                         }
3618                         break;
3619                 }
3620
3621                 if (entry->lcme_flags & LCME_FL_INIT) {
3622                         if (obdindex != OBD_NOT_FOUND) {
3623                                 flags |= LDF_SKIP_OBJS;
3624                                 v1 = lov_comp_entry(comp_v1, i);
3625                                 objects = lov_v1v3_objects(v1);
3626
3627                                 for (j = 0; j < v1->lmm_stripe_count; j++) {
3628                                         if (obdindex == objects[j].l_ost_idx) {
3629                                                 flags &= ~LDF_SKIP_OBJS;
3630                                                 break;
3631                                         }
3632                                 }
3633                         } else {
3634                                 flags &= ~LDF_SKIP_OBJS;
3635                         }
3636                 } else {
3637                         flags |= LDF_SKIP_OBJS;
3638                 }
3639
3640                 if (obdindex != OBD_NOT_FOUND && (flags & LDF_SKIP_OBJS))
3641                         continue;
3642                 lov_dump_comp_v1_entry(param, flags, i);
3643
3644                 v1 = lov_comp_entry(comp_v1, i);
3645                 objects = lov_v1v3_objects(v1);
3646                 lov_v1v3_pool_name(v1, pool_name);
3647
3648                 ext = entry->lcme_flags & LCME_FL_EXTENSION ? LDF_EXTENSION : 0;
3649                 lov_dump_user_lmm_v1v3(v1, pool_name, objects, path, obdindex,
3650                                        param->fp_max_depth, param->fp_verbose,
3651                                        flags | ext);
3652         }
3653         if (print_last_init_comp(param)) {
3654                 /**
3655                  * directory layout contains only layout template, print the
3656                  * last component.
3657                  */
3658                 if (i == 0)
3659                         i = comp_v1->lcm_entry_count - 1;
3660                 else
3661                         i--;
3662                 flags &= ~LDF_SKIP_OBJS;
3663
3664                 lov_dump_comp_v1_entry(param, flags, i);
3665
3666                 v1 = lov_comp_entry(comp_v1, i);
3667                 objects = lov_v1v3_objects(v1);
3668                 lov_v1v3_pool_name(v1, pool_name);
3669
3670                 entry = &comp_v1->lcm_entries[i];
3671                 ext = entry->lcme_flags & LCME_FL_EXTENSION ? LDF_EXTENSION : 0;
3672                 lov_dump_user_lmm_v1v3(v1, pool_name, objects, path, obdindex,
3673                                        param->fp_max_depth, param->fp_verbose,
3674                                        flags | ext);
3675         }
3676 }
3677
3678 #define VERBOSE_COMP_OPTS       (VERBOSE_COMP_COUNT | VERBOSE_COMP_ID | \
3679                                  VERBOSE_COMP_START | VERBOSE_COMP_END | \
3680                                  VERBOSE_COMP_FLAGS)
3681
3682 static inline bool has_any_comp_options(struct find_param *param)
3683 {
3684         enum llapi_layout_verbose verbose = param->fp_verbose;
3685
3686         if (param->fp_check_comp_id || param->fp_check_comp_count ||
3687             param->fp_check_comp_start || param->fp_check_comp_end ||
3688             param->fp_check_comp_flags)
3689                 return true;
3690
3691         /* show full layout information, not component specific */
3692         if ((verbose & ~VERBOSE_DETAIL) == VERBOSE_DEFAULT)
3693                 return false;
3694
3695         return verbose & VERBOSE_COMP_OPTS;
3696 }
3697
3698 struct lov_user_mds_data *lov_forge_comp_v1(struct lov_user_mds_data *orig,
3699                                             bool is_dir)
3700 {
3701         struct lov_user_md *lum = &orig->lmd_lmm;
3702         struct lov_user_mds_data *new;
3703         struct lov_comp_md_v1 *comp_v1;
3704         struct lov_comp_md_entry_v1 *ent;
3705         int lum_off = sizeof(*comp_v1) + sizeof(*ent);
3706         int lum_size = lov_user_md_size(is_dir ? 0 : lum->lmm_stripe_count,
3707                                         lum->lmm_magic);
3708
3709         new = malloc(offsetof(typeof(*new), lmd_lmm) + lum_off + lum_size);
3710         if (new == NULL) {
3711                 llapi_printf(LLAPI_MSG_NORMAL, "out of memory\n");
3712                 return new;
3713         }
3714
3715         memcpy(new, orig, sizeof(new->lmd_stx) + sizeof(new->lmd_flags)
3716                + sizeof(new->lmd_lmmsize));
3717
3718         comp_v1 = (struct lov_comp_md_v1 *)&new->lmd_lmm;
3719         comp_v1->lcm_magic = lum->lmm_magic;
3720         comp_v1->lcm_size = lum_off + lum_size;
3721         comp_v1->lcm_layout_gen = is_dir ? 0 : lum->lmm_layout_gen;
3722         comp_v1->lcm_flags = 0;
3723         comp_v1->lcm_entry_count = 1;
3724
3725         ent = &comp_v1->lcm_entries[0];
3726         ent->lcme_id = 0;
3727         ent->lcme_flags = is_dir ? 0 : LCME_FL_INIT;
3728         ent->lcme_extent.e_start = 0;
3729         ent->lcme_extent.e_end = LUSTRE_EOF;
3730         ent->lcme_offset = lum_off;
3731         ent->lcme_size = lum_size;
3732
3733         memcpy((char *)comp_v1 + lum_off, lum, lum_size);
3734
3735         return new;
3736 }
3737
3738 static void lov_dump_plain_user_lmm(struct find_param *param, char *path,
3739                                     enum lov_dump_flags flags)
3740 {
3741         __u32 magic = *(__u32 *)&param->fp_lmd->lmd_lmm;
3742
3743         if (has_any_comp_options(param)) {
3744                 struct lov_user_mds_data *new_lmd, *orig_lmd;
3745
3746                 orig_lmd = param->fp_lmd;
3747                 new_lmd = lov_forge_comp_v1(orig_lmd, flags & LDF_IS_DIR);
3748                 if (new_lmd != NULL) {
3749                         param->fp_lmd = new_lmd;
3750                         lov_dump_comp_v1(param, path, flags);
3751                         param->fp_lmd = orig_lmd;
3752                         free(new_lmd);
3753                 }
3754                 return;
3755         }
3756
3757         if (magic == LOV_USER_MAGIC_V1) {
3758                 lov_dump_user_lmm_v1v3(&param->fp_lmd->lmd_lmm, NULL,
3759                                        param->fp_lmd->lmd_lmm.lmm_objects,
3760                                        path, param->fp_obd_index,
3761                                        param->fp_max_depth, param->fp_verbose,
3762                                        flags);
3763         } else {
3764                 char pool_name[LOV_MAXPOOLNAME + 1];
3765                 struct lov_user_ost_data_v1 *objects;
3766                 struct lov_user_md_v3 *lmmv3 = (void *)&param->fp_lmd->lmd_lmm;
3767
3768                 snprintf(pool_name, sizeof(pool_name), "%s",
3769                          lmmv3->lmm_pool_name);
3770                 objects = lmmv3->lmm_objects;
3771                 lov_dump_user_lmm_v1v3(&param->fp_lmd->lmd_lmm, pool_name,
3772                                        objects, path, param->fp_obd_index,
3773                                        param->fp_max_depth, param->fp_verbose,
3774                                        flags);
3775         }
3776 }
3777
3778 static uint32_t check_foreign_type(uint32_t foreign_type)
3779 {
3780         uint32_t i;
3781
3782         for (i = 0; i < LU_FOREIGN_TYPE_UNKNOWN; i++) {
3783                 if (lu_foreign_types[i].lft_name == NULL)
3784                         break;
3785                 if (foreign_type == lu_foreign_types[i].lft_type)
3786                         return i;
3787         }
3788
3789         return LU_FOREIGN_TYPE_UNKNOWN;
3790 }
3791
3792 static void lov_dump_foreign_lmm(struct find_param *param, char *path,
3793                                  enum lov_dump_flags flags)
3794 {
3795         struct lov_foreign_md *lfm = (void *)&param->fp_lmd->lmd_lmm;
3796         bool yaml = flags & LDF_YAML;
3797
3798         if (!yaml && param->fp_depth && path)
3799                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
3800
3801         if (param->fp_verbose & VERBOSE_DETAIL) {
3802                 uint32_t type = check_foreign_type(lfm->lfm_type);
3803
3804                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_magic:         0x%08X\n",
3805                              lfm->lfm_magic);
3806                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_length:          %u\n",
3807                              lfm->lfm_length);
3808                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_type:          0x%08X",
3809                              lfm->lfm_type);
3810                 if (type < LU_FOREIGN_TYPE_UNKNOWN)
3811                         llapi_printf(LLAPI_MSG_NORMAL, " (%s)\n",
3812                                      lu_foreign_types[type].lft_name);
3813                 else
3814                         llapi_printf(LLAPI_MSG_NORMAL, " (unknown)\n");
3815
3816                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_flags:          0x%08X\n",
3817                              lfm->lfm_flags);
3818         }
3819         llapi_printf(LLAPI_MSG_NORMAL, "lfm_value:     '%.*s'\n",
3820                      lfm->lfm_length, lfm->lfm_value);
3821         llapi_printf(LLAPI_MSG_NORMAL, "\n");
3822 }
3823
3824 static void lmv_dump_foreign_lmm(struct find_param *param, char *path,
3825                                     enum lov_dump_flags flags)
3826 {
3827         struct lmv_foreign_md *lfm = (struct lmv_foreign_md *)param->fp_lmv_md;
3828         bool yaml = flags & LDF_YAML;
3829
3830         if (!yaml && param->fp_depth && path)
3831                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
3832
3833         if (param->fp_verbose & VERBOSE_DETAIL) {
3834                 uint32_t type = check_foreign_type(lfm->lfm_type);
3835
3836                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_magic:         0x%08X\n",
3837                              lfm->lfm_magic);
3838                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_length:          %u\n",
3839                              lfm->lfm_length);
3840                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_type:          0x%08X",
3841                              lfm->lfm_type);
3842                 if (type < LU_FOREIGN_TYPE_UNKNOWN)
3843                         llapi_printf(LLAPI_MSG_NORMAL, " (%s)\n",
3844                                      lu_foreign_types[type].lft_name);
3845                 else
3846                         llapi_printf(LLAPI_MSG_NORMAL, " (unknown)\n");
3847
3848                 llapi_printf(LLAPI_MSG_NORMAL, "lfm_flags:          0x%08X\n",
3849                              lfm->lfm_flags);
3850         }
3851         llapi_printf(LLAPI_MSG_NORMAL, "lfm_value:     '%.*s'\n",
3852                      lfm->lfm_length, lfm->lfm_value);
3853         llapi_printf(LLAPI_MSG_NORMAL, "\n");
3854 }
3855
3856 static void llapi_lov_dump_user_lmm(struct find_param *param, char *path,
3857                                     enum lov_dump_flags flags)
3858 {
3859         __u32 magic;
3860
3861         if (param->fp_get_lmv || param->fp_get_default_lmv)
3862                 magic = (__u32)param->fp_lmv_md->lum_magic;
3863         else
3864                 magic = *(__u32 *)&param->fp_lmd->lmd_lmm; /* lum->lmm_magic */
3865
3866         if (param->fp_raw)
3867                 flags |= LDF_IS_RAW;
3868         if (param->fp_yaml)
3869                 flags |= LDF_YAML;
3870
3871         switch (magic) {
3872         case LOV_USER_MAGIC_V1:
3873         case LOV_USER_MAGIC_V3:
3874         case LOV_USER_MAGIC_SPECIFIC:
3875                 lov_dump_plain_user_lmm(param, path, flags);
3876                 break;
3877         case LOV_USER_MAGIC_FOREIGN:
3878                 lov_dump_foreign_lmm(param, path, flags);
3879                 break;
3880         case LMV_MAGIC_V1:
3881         case LMV_USER_MAGIC: {
3882                 char pool_name[LOV_MAXPOOLNAME + 1];
3883                 struct lmv_user_md *lum;
3884
3885                 lum = (struct lmv_user_md *)param->fp_lmv_md;
3886                 snprintf(pool_name, sizeof(pool_name), "%s",
3887                          lum->lum_pool_name);
3888                 lmv_dump_user_lmm(lum, pool_name, path, param->fp_obd_index,
3889                                   param->fp_max_depth, param->fp_verbose,
3890                                   flags);
3891                 break;
3892         }
3893         case LOV_USER_MAGIC_COMP_V1:
3894                 lov_dump_comp_v1(param, path, flags);
3895                 break;
3896         case LMV_MAGIC_FOREIGN:
3897                 lmv_dump_foreign_lmm(param, path, flags);
3898                 break;
3899         default:
3900                 llapi_printf(LLAPI_MSG_NORMAL, "unknown lmm_magic:  %#x "
3901                              "(expecting one of %#x %#x %#x %#x)\n",
3902                              *(__u32 *)&param->fp_lmd->lmd_lmm,
3903                              LOV_USER_MAGIC_V1, LOV_USER_MAGIC_V3,
3904                              LMV_USER_MAGIC, LMV_MAGIC_V1);
3905                 return;
3906         }
3907 }
3908
3909 int llapi_file_get_stripe(const char *path, struct lov_user_md *lum)
3910 {
3911         const char *fname;
3912         char *dname;
3913         int fd, rc = 0;
3914
3915         fname = strrchr(path, '/');
3916
3917         /* It should be a file (or other non-directory) */
3918         if (fname == NULL) {
3919                 dname = (char *)malloc(2);
3920                 if (dname == NULL)
3921                         return -ENOMEM;
3922                 strcpy(dname, ".");
3923                 fname = (char *)path;
3924         } else {
3925                 dname = (char *)malloc(fname - path + 1);
3926                 if (dname == NULL)
3927                         return -ENOMEM;
3928                 strncpy(dname, path, fname - path);
3929                 dname[fname - path] = '\0';
3930                 fname++;
3931         }
3932
3933         fd = open(dname, O_RDONLY | O_NONBLOCK);
3934         if (fd == -1) {
3935                 rc = -errno;
3936                 goto out_free;
3937         }
3938
3939         strcpy((char *)lum, fname);
3940         if (ioctl(fd, IOC_MDC_GETFILESTRIPE, (void *)lum) == -1)
3941                 rc = -errno;
3942
3943         if (close(fd) == -1 && rc == 0)
3944                 rc = -errno;
3945
3946 out_free:
3947         free(dname);
3948         return rc;
3949 }
3950
3951 int llapi_file_lookup(int dirfd, const char *name)
3952 {
3953         struct obd_ioctl_data data = { 0 };
3954         char rawbuf[8192];
3955         char *buf = rawbuf;
3956         int rc;
3957
3958         if (dirfd < 0 || name == NULL)
3959                 return -EINVAL;
3960
3961         data.ioc_version = OBD_IOCTL_VERSION;
3962         data.ioc_len = sizeof(data);
3963         data.ioc_inlbuf1 = (char *)name;
3964         data.ioc_inllen1 = strlen(name) + 1;
3965
3966         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
3967         if (rc) {
3968                 llapi_error(LLAPI_MSG_ERROR, rc,
3969                             "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
3970                             name, rc);
3971                 return rc;
3972         }
3973
3974         rc = ioctl(dirfd, IOC_MDC_LOOKUP, buf);
3975         if (rc < 0)
3976                 rc = -errno;
3977         return rc;
3978 }
3979
3980 /* Check if the file time matches all the given criteria (e.g. --atime +/-N).
3981  * Return -1 or 1 if file timestamp does not or does match the given criteria
3982  * correspondingly. Return 0 if the MDS time is being checked and there are
3983  * attributes on OSTs and it is not yet clear if the timespamp matches.
3984  *
3985  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
3986  * updated timestamps. */
3987 static int find_time_check(lstatx_t *stx, struct find_param *param, int mds)
3988 {
3989         int rc = 1;
3990         int rc2;
3991
3992         /* Check if file is accepted. */
3993         if (param->fp_atime) {
3994                 rc2 = find_value_cmp(stx->stx_atime.tv_sec, param->fp_atime,
3995                                      param->fp_asign, param->fp_exclude_atime,
3996                                      param->fp_time_margin, mds);
3997                 if (rc2 < 0)
3998                         return rc2;
3999                 rc = rc2;
4000         }
4001
4002         if (param->fp_mtime) {
4003                 rc2 = find_value_cmp(stx->stx_mtime.tv_sec, param->fp_mtime,
4004                                      param->fp_msign, param->fp_exclude_mtime,
4005                                      param->fp_time_margin, mds);
4006                 if (rc2 < 0)
4007                         return rc2;
4008
4009                 /* If the previous check matches, but this one is not yet clear,
4010                  * we should return 0 to do an RPC on OSTs. */
4011                 if (rc == 1)
4012                         rc = rc2;
4013         }
4014
4015         if (param->fp_ctime) {
4016                 rc2 = find_value_cmp(stx->stx_ctime.tv_sec, param->fp_ctime,
4017                                      param->fp_csign, param->fp_exclude_ctime,
4018                                      param->fp_time_margin, mds);
4019                 if (rc2 < 0)
4020                         return rc2;
4021
4022                 /* If the previous check matches, but this one is not yet clear,
4023                  * we should return 0 to do an RPC on OSTs. */
4024                 if (rc == 1)
4025                         rc = rc2;
4026         }
4027
4028         return rc;
4029 }
4030
4031 /**
4032  * Check whether the stripes matches the indexes user provided
4033  *       1   : matched
4034  *       0   : Unmatched
4035  */
4036 static int check_obd_match(struct find_param *param)
4037 {
4038         struct lov_user_ost_data_v1 *objects;
4039         struct lov_comp_md_v1 *comp_v1 = NULL;
4040         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4041         lstatx_t *stx = &param->fp_lmd->lmd_stx;
4042         int i, j, k, count = 1;
4043
4044         if (param->fp_obd_uuid && param->fp_obd_index == OBD_NOT_FOUND)
4045                 return 0;
4046
4047         if (!S_ISREG(stx->stx_mode))
4048                 return 0;
4049
4050         /* exclude foreign */
4051         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4052                 return param->fp_exclude_obd;
4053
4054         /* Only those files should be accepted, which have a
4055          * stripe on the specified OST. */
4056         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4057                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4058                 count = comp_v1->lcm_entry_count;
4059         }
4060
4061         for (i = 0; i < count; i++) {
4062                 if (comp_v1)
4063                         v1 = lov_comp_entry(comp_v1, i);
4064
4065                 objects = lov_v1v3_objects(v1);
4066
4067                 for (j = 0; j < v1->lmm_stripe_count; j++) {
4068                         if (comp_v1 && !(comp_v1->lcm_entries[i].lcme_flags &
4069                                          LCME_FL_INIT))
4070                                 continue;
4071                         for (k = 0; k < param->fp_num_obds; k++) {
4072                                 if (param->fp_obd_indexes[k] ==
4073                                     objects[j].l_ost_idx)
4074                                         return !param->fp_exclude_obd;
4075                         }
4076                 }
4077         }
4078
4079         return param->fp_exclude_obd;
4080 }
4081
4082 static int check_mdt_match(struct find_param *param)
4083 {
4084         int i;
4085
4086         if (param->fp_mdt_uuid && param->fp_mdt_index == OBD_NOT_FOUND)
4087                 return 0;
4088
4089         /* FIXME: For striped dir, we should get stripe information and check */
4090         for (i = 0; i < param->fp_num_mdts; i++) {
4091                 if (param->fp_mdt_indexes[i] == param->fp_file_mdt_index)
4092                         return !param->fp_exclude_mdt;
4093         }
4094
4095         if (param->fp_exclude_mdt)
4096                 return 1;
4097
4098         return 0;
4099 }
4100
4101 /**
4102  * Check whether the obd is active or not, if it is
4103  * not active, just print the object affected by this
4104  * failed target
4105  **/
4106 static int print_failed_tgt(struct find_param *param, char *path, int type)
4107 {
4108         struct obd_statfs stat_buf;
4109         struct obd_uuid uuid_buf;
4110         int ret;
4111
4112         if (type != LL_STATFS_LOV && type != LL_STATFS_LMV)
4113                 return -EINVAL;
4114
4115         memset(&stat_buf, 0, sizeof(struct obd_statfs));
4116         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
4117         ret = llapi_obd_statfs(path, type,
4118                                param->fp_obd_index, &stat_buf,
4119                                &uuid_buf);
4120         if (ret) {
4121                 llapi_printf(LLAPI_MSG_NORMAL,
4122                              "obd_uuid: %s failed %s ",
4123                              param->fp_obd_uuid->uuid,
4124                              strerror(errno));
4125         }
4126
4127         return ret;
4128 }
4129
4130 static int find_check_stripe_size(struct find_param *param)
4131 {
4132         struct lov_comp_md_v1 *comp_v1 = NULL;
4133         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4134         __u32 stripe_size = 0;
4135         int ret, i, count = 1;
4136
4137         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4138                 return param->fp_exclude_stripe_size ? 1 : -1;
4139
4140         ret = param->fp_exclude_stripe_size ? 1 : -1;
4141         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4142                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4143                 count = comp_v1->lcm_entry_count;
4144         }
4145
4146         for (i = 0; i < count; i++) {
4147                 struct lov_comp_md_entry_v1 *ent;
4148
4149                 if (comp_v1) {
4150                         v1 = lov_comp_entry(comp_v1, i);
4151
4152                         ent = &comp_v1->lcm_entries[i];
4153                         if (ent->lcme_flags & LCME_FL_EXTENSION)
4154                                 continue;
4155                         if (!(ent->lcme_flags & LCME_FL_INIT))
4156                                 continue;
4157                 }
4158                 stripe_size = v1->lmm_stripe_size;
4159         }
4160
4161         ret = find_value_cmp(stripe_size, param->fp_stripe_size,
4162                              param->fp_stripe_size_sign,
4163                              param->fp_exclude_stripe_size,
4164                              param->fp_stripe_size_units, 0);
4165
4166         return ret;
4167 }
4168
4169 static int find_check_ext_size(struct find_param *param)
4170 {
4171         struct lov_comp_md_v1 *comp_v1;
4172         struct lov_user_md_v1 *v1;
4173         int ret, i;
4174
4175         ret = param->fp_exclude_ext_size ? 1 : -1;
4176         comp_v1 = (struct lov_comp_md_v1 *)&param->fp_lmd->lmd_lmm;
4177         if (comp_v1->lcm_magic != LOV_USER_MAGIC_COMP_V1)
4178                 return ret;
4179
4180         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
4181                 struct lov_comp_md_entry_v1 *ent;
4182
4183                 v1 = lov_comp_entry(comp_v1, i);
4184
4185                 ent = &comp_v1->lcm_entries[i];
4186                 if (!(ent->lcme_flags & LCME_FL_EXTENSION))
4187                         continue;
4188
4189                 ret = find_value_cmp(v1->lmm_stripe_size, param->fp_ext_size,
4190                                      param->fp_ext_size_sign,
4191                                      param->fp_exclude_ext_size,
4192                                      param->fp_ext_size_units, 0);
4193                 /* If any ext_size matches */
4194                 if (ret != -1)
4195                         break;
4196         }
4197
4198         return ret;
4199 }
4200
4201 static __u32 find_get_stripe_count(struct find_param *param)
4202 {
4203         struct lov_comp_md_v1 *comp_v1 = NULL;
4204         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4205         int i, count = 1;
4206         __u32 stripe_count = 0;
4207
4208         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4209                 return 0;
4210
4211         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4212                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4213                 count = comp_v1->lcm_entry_count;
4214         }
4215
4216         for (i = 0; i < count; i++) {
4217                 if (comp_v1) {
4218                         struct lov_comp_md_entry_v1 *ent;
4219
4220                         v1 = lov_comp_entry(comp_v1, i);
4221
4222                         ent = &comp_v1->lcm_entries[i];
4223                         if (!(ent->lcme_flags & LCME_FL_INIT))
4224                                 continue;
4225
4226                         if (ent->lcme_flags & LCME_FL_EXTENSION)
4227                                 continue;
4228                 }
4229                 stripe_count = v1->lmm_stripe_count;
4230         }
4231
4232         return stripe_count;
4233 }
4234
4235 #define LOV_PATTERN_INVALID     0xFFFFFFFF
4236
4237 static int find_check_layout(struct find_param *param)
4238 {
4239         struct lov_comp_md_v1 *comp_v1 = NULL;
4240         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4241         int i, count = 1;
4242         bool found = false, valid = false;
4243
4244         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4245                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4246                 count = comp_v1->lcm_entry_count;
4247         }
4248
4249         for (i = 0; i < count; i++) {
4250                 if (comp_v1)
4251                         v1 = lov_comp_entry(comp_v1, i);
4252
4253                 /* foreign file have a special magic but no pattern field */
4254                 if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4255                         continue;
4256
4257                 if (v1->lmm_pattern == LOV_PATTERN_INVALID)
4258                         continue;
4259
4260                 valid = true;
4261                 if (v1->lmm_pattern & param->fp_layout) {
4262                         found = true;
4263                         break;
4264                 }
4265         }
4266
4267         if (!valid)
4268                 return -1;
4269
4270         if ((found && !param->fp_exclude_layout) ||
4271             (!found && param->fp_exclude_layout))
4272                 return 1;
4273
4274         return -1;
4275 }
4276
4277 /* if no type specified, check/exclude all foreign
4278  * if type specified, check all foreign&type and exclude !foreign + foreign&type
4279  */
4280 static int find_check_foreign(struct find_param *param)
4281 {
4282         if (S_ISREG(param->fp_lmd->lmd_stx.stx_mode)) {
4283                 struct lov_foreign_md *lfm;
4284
4285                 lfm = (void *)&param->fp_lmd->lmd_lmm;
4286                 if (lfm->lfm_magic != LOV_USER_MAGIC_FOREIGN) {
4287                         if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN)
4288                                 return param->fp_exclude_foreign ? 1 : -1;
4289                         return -1;
4290                 } else {
4291                         if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN ||
4292                             lfm->lfm_type == param->fp_foreign_type)
4293                                 return param->fp_exclude_foreign ? -1 : 1;
4294                         return param->fp_exclude_foreign ? 1 : -1;
4295                 }
4296         }
4297
4298         if (S_ISDIR(param->fp_lmd->lmd_stx.stx_mode)) {
4299                 struct lmv_foreign_md *lfm;
4300
4301                 lfm = (void *)param->fp_lmv_md;
4302                 if (lfm->lfm_magic != LMV_MAGIC_FOREIGN) {
4303                         if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN)
4304                                 return param->fp_exclude_foreign ? 1 : -1;
4305                         return -1;
4306                 } else {
4307                         if (param->fp_foreign_type == LU_FOREIGN_TYPE_UNKNOWN ||
4308                             lfm->lfm_type == param->fp_foreign_type)
4309                                 return param->fp_exclude_foreign ? -1 : 1;
4310                         return param->fp_exclude_foreign ? 1 : -1;
4311                 }
4312         }
4313         return -1;
4314 }
4315
4316 static int find_check_pool(struct find_param *param)
4317 {
4318         struct lov_comp_md_v1 *comp_v1 = NULL;
4319         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4320         struct lov_user_md_v3 *v3 = (void *)v1;
4321         int i, count = 1;
4322         bool found = false;
4323
4324         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4325                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4326                 count = comp_v1->lcm_entry_count;
4327                 /* empty requested pool is taken as no pool search */
4328                 if (count == 0 && param->fp_poolname[0] == '\0')
4329                         found = true;
4330         }
4331
4332         for (i = 0; i < count; i++) {
4333                 if (comp_v1 != NULL)
4334                         v1 = lov_comp_entry(comp_v1, i);
4335
4336                 if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4337                         continue;
4338
4339                 if (((v1->lmm_magic == LOV_USER_MAGIC_V1) &&
4340                      (param->fp_poolname[0] == '\0')) ||
4341                     ((v1->lmm_magic == LOV_USER_MAGIC_V3) &&
4342                      (strncmp(v3->lmm_pool_name,
4343                               param->fp_poolname, LOV_MAXPOOLNAME) == 0)) ||
4344                     ((v1->lmm_magic == LOV_USER_MAGIC_V3) &&
4345                      (strcmp(param->fp_poolname, "*") == 0))) {
4346                         found = true;
4347                         break;
4348                 }
4349         }
4350
4351         if ((found && !param->fp_exclude_pool) ||
4352             (!found && param->fp_exclude_pool))
4353                 return 1;
4354
4355         return -1;
4356 }
4357
4358 static int find_check_comp_options(struct find_param *param)
4359 {
4360         lstatx_t *stx = &param->fp_lmd->lmd_stx;
4361         struct lov_comp_md_v1 *comp_v1, *forged_v1 = NULL;
4362         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4363         struct lov_comp_md_entry_v1 *entry;
4364         int i, ret = 0;
4365
4366         if (v1->lmm_magic == LOV_USER_MAGIC_FOREIGN)
4367                 return -1;
4368
4369         if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1) {
4370                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4371         } else {
4372                 forged_v1 = malloc(sizeof(*forged_v1) + sizeof(*entry));
4373                 if (forged_v1 == NULL)
4374                         return -1;
4375                 comp_v1 = forged_v1;
4376                 comp_v1->lcm_entry_count = 1;
4377                 entry = &comp_v1->lcm_entries[0];
4378                 entry->lcme_flags = S_ISDIR(stx->stx_mode) ? 0 : LCME_FL_INIT;
4379                 entry->lcme_extent.e_start = 0;
4380                 entry->lcme_extent.e_end = LUSTRE_EOF;
4381         }
4382
4383         /* invalid case, don't match for any kind of search. */
4384         if (comp_v1->lcm_entry_count == 0) {
4385                 ret = -1;
4386                 goto out;
4387         }
4388
4389         if (param->fp_check_comp_count) {
4390                 ret = find_value_cmp(forged_v1 ? 0 : comp_v1->lcm_entry_count,
4391                                      param->fp_comp_count,
4392                                      param->fp_comp_count_sign,
4393                                      param->fp_exclude_comp_count, 1, 0);
4394                 if (ret == -1)
4395                         goto out;
4396         }
4397
4398         ret = 1;
4399         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
4400                 entry = &comp_v1->lcm_entries[i];
4401
4402                 if (param->fp_check_comp_flags) {
4403                         ret = 1;
4404                         if (((param->fp_comp_flags & entry->lcme_flags) !=
4405                              param->fp_comp_flags) ||
4406                             (param->fp_comp_neg_flags & entry->lcme_flags)) {
4407                                 ret = -1;
4408                                 continue;
4409                         }
4410                 }
4411
4412                 if (param->fp_check_comp_start) {
4413                         ret = find_value_cmp(entry->lcme_extent.e_start,
4414                                              param->fp_comp_start,
4415                                              param->fp_comp_start_sign,
4416                                              param->fp_exclude_comp_start,
4417                                              param->fp_comp_start_units, 0);
4418                         if (ret == -1)
4419                                 continue;
4420                 }
4421
4422                 if (param->fp_check_comp_end) {
4423                         ret = find_comp_end_cmp(entry->lcme_extent.e_end,
4424                                                 param);
4425                         if (ret == -1)
4426                                 continue;
4427                 }
4428
4429                 /* the component matches all criteria */
4430                 break;
4431         }
4432 out:
4433         if (forged_v1)
4434                 free(forged_v1);
4435         return ret;
4436 }
4437
4438 static int find_check_mirror_options(struct find_param *param)
4439 {
4440         struct lov_comp_md_v1 *comp_v1;
4441         struct lov_user_md_v1 *v1 = &param->fp_lmd->lmd_lmm;
4442         int ret = 0;
4443
4444         if (v1->lmm_magic != LOV_USER_MAGIC_COMP_V1)
4445                 return -1;
4446
4447         comp_v1 = (struct lov_comp_md_v1 *)v1;
4448
4449         if (param->fp_check_mirror_count) {
4450                 ret = find_value_cmp(comp_v1->lcm_mirror_count + 1,
4451                                      param->fp_mirror_count,
4452                                      param->fp_mirror_count_sign,
4453                                      param->fp_exclude_mirror_count, 1, 0);
4454                 if (ret == -1)
4455                         return ret;
4456         }
4457
4458         if (param->fp_check_mirror_state) {
4459                 ret = 1;
4460                 __u16 file_state = comp_v1->lcm_flags & LCM_FL_FLR_MASK;
4461
4462                 if ((param->fp_mirror_state != 0 &&
4463                     file_state != param->fp_mirror_state) ||
4464                     file_state == param->fp_mirror_neg_state)
4465                         return -1;
4466         }
4467
4468         return ret;
4469 }
4470
4471 static bool find_check_lmm_info(struct find_param *param)
4472 {
4473         return param->fp_check_pool || param->fp_check_stripe_count ||
4474                param->fp_check_stripe_size || param->fp_check_layout ||
4475                param->fp_check_comp_count || param->fp_check_comp_end ||
4476                param->fp_check_comp_start || param->fp_check_comp_flags ||
4477                param->fp_check_mirror_count || param->fp_check_foreign ||
4478                param->fp_check_mirror_state || param->fp_check_ext_size ||
4479                param->fp_check_projid;
4480 }
4481
4482 /*
4483  * Get file/directory project id.
4484  * by the open fd resides on.
4485  * Return 0 and project id on success, or -ve errno.
4486  */
4487 static int fget_projid(int fd, int *projid)
4488 {
4489         struct fsxattr fsx;
4490         int rc;
4491
4492         rc = ioctl(fd, LL_IOC_FSGETXATTR, &fsx);
4493         if (rc)
4494                 return -errno;
4495
4496         *projid = fsx.fsx_projid;
4497         return 0;
4498 }
4499
4500 static int cb_find_init(char *path, DIR *parent, DIR **dirp,
4501                         void *data, struct dirent64 *de)
4502 {
4503         struct find_param *param = (struct find_param *)data;
4504         DIR *dir = dirp == NULL ? NULL : *dirp;
4505         int decision = 1; /* 1 is accepted; -1 is rejected. */
4506         lstatx_t *stx = &param->fp_lmd->lmd_stx;
4507         int lustre_fs = 1;
4508         int checked_type = 0;
4509         int ret = 0;
4510         __u32 stripe_count = 0;
4511         __u64 flags;
4512         int fd = -2;
4513
4514         if (parent == NULL && dir == NULL)
4515                 return -EINVAL;
4516
4517         /* If a regular expression is presented, make the initial decision */
4518         if (param->fp_pattern != NULL) {
4519                 char *fname = strrchr(path, '/');
4520                 fname = (fname == NULL ? path : fname + 1);
4521                 ret = fnmatch(param->fp_pattern, fname, 0);
4522                 if ((ret == FNM_NOMATCH && !param->fp_exclude_pattern) ||
4523                     (ret == 0 && param->fp_exclude_pattern))
4524                         goto decided;
4525         }
4526
4527         /* See if we can check the file type from the dirent. */
4528         if (param->fp_type != 0 && de != NULL && de->d_type != DT_UNKNOWN) {
4529                 checked_type = 1;
4530
4531                 if (DTTOIF(de->d_type) == param->fp_type) {
4532                         if (param->fp_exclude_type)
4533                                 goto decided;
4534                 } else {
4535                         if (!param->fp_exclude_type)
4536                                 goto decided;
4537                 }
4538         }
4539
4540         ret = 0;
4541
4542         /* Request MDS for the stat info if some of these parameters need
4543          * to be compared. */
4544         if (param->fp_obd_uuid || param->fp_mdt_uuid ||
4545             param->fp_check_uid || param->fp_check_gid ||
4546             param->fp_atime || param->fp_mtime || param->fp_ctime ||
4547             param->fp_check_size || param->fp_check_blocks ||
4548             find_check_lmm_info(param) ||
4549             param->fp_check_mdt_count || param->fp_check_hash_type)
4550                 decision = 0;
4551
4552         if (param->fp_type != 0 && checked_type == 0)
4553                 decision = 0;
4554
4555         if (decision == 0) {
4556                 if (dir && (param->fp_check_mdt_count ||
4557                     param->fp_check_hash_type || param->fp_check_foreign)) {
4558                         param->fp_get_lmv = 1;
4559                         ret = cb_get_dirstripe(path, dir, param);
4560                         if (ret != 0) {
4561                                 /* XXX this works to decide for foreign
4562                                  * criterion only
4563                                  */
4564                                 if (errno == ENODATA &&
4565                                     param->fp_check_foreign) {
4566                                         if (param->fp_exclude_foreign)
4567                                                 goto foreign;
4568                                         goto decided;
4569                                 }
4570                                 return ret;
4571                         }
4572                 }
4573
4574                 param->fp_lmd->lmd_lmm.lmm_magic = 0;
4575                 ret = get_lmd_info(path, parent, dir, param->fp_lmd,
4576                                    param->fp_lum_size, GET_LMD_INFO);
4577                 if (ret == 0 && param->fp_lmd->lmd_lmm.lmm_magic == 0 &&
4578                     find_check_lmm_info(param)) {
4579                         struct lov_user_md *lmm = &param->fp_lmd->lmd_lmm;
4580
4581                         /* We need to "fake" the "use the default" values
4582                          * since the lmm struct is zeroed out at this point. */
4583                         lmm->lmm_magic = LOV_USER_MAGIC_V1;
4584                         lmm->lmm_pattern = LOV_PATTERN_DEFAULT;
4585                         if (!param->fp_raw)
4586                                 ostid_set_seq(&lmm->lmm_oi,
4587                                               FID_SEQ_LOV_DEFAULT);
4588                         lmm->lmm_stripe_size = 0;
4589                         lmm->lmm_stripe_count = 0;
4590                         lmm->lmm_stripe_offset = -1;
4591                 }
4592                 if (ret == 0 && param->fp_mdt_uuid != NULL) {
4593                         if (dir != NULL) {
4594                                 ret = llapi_file_fget_mdtidx(dirfd(dir),
4595                                                      &param->fp_file_mdt_index);
4596                         } else if (S_ISREG(stx->stx_mode)) {
4597                                 /* FIXME: we could get the MDT index from the
4598                                  * file's FID in lmd->lmd_lmm.lmm_oi without
4599                                  * opening the file, once we are sure that
4600                                  * LFSCK2 (2.6) has fixed up pre-2.0 LOV EAs.
4601                                  * That would still be an ioctl() to map the
4602                                  * FID to the MDT, but not an open RPC. */
4603                                 fd = open(path, O_RDONLY);
4604                                 if (fd > 0) {
4605                                         ret = llapi_file_fget_mdtidx(fd,
4606                                                      &param->fp_file_mdt_index);
4607                                 } else {
4608                                         ret = -errno;
4609                                 }
4610                         } else {
4611                                 /* For a special file, we assume it resides on
4612                                  * the same MDT as the parent directory. */
4613                                 ret = llapi_file_fget_mdtidx(dirfd(parent),
4614                                                      &param->fp_file_mdt_index);
4615                         }
4616                 }
4617                 if (ret != 0) {
4618                         if (ret == -ENOTTY)
4619                                 lustre_fs = 0;
4620                         if (ret == -ENOENT)
4621                                 goto decided;
4622
4623                         goto out;
4624                 } else {
4625                         stripe_count = find_get_stripe_count(param);
4626                 }
4627         }
4628
4629         if (param->fp_type && !checked_type) {
4630                 if ((stx->stx_mode & S_IFMT) == param->fp_type) {
4631                         if (param->fp_exclude_type)
4632                                 goto decided;
4633                 } else {
4634                         if (!param->fp_exclude_type)
4635                                 goto decided;
4636                 }
4637         }
4638
4639         /* Prepare odb. */
4640         if (param->fp_obd_uuid || param->fp_mdt_uuid) {
4641                 if (lustre_fs && param->fp_got_uuids &&
4642                     param->fp_dev != makedev(stx->stx_dev_major,
4643                                              stx->stx_dev_minor)) {
4644                         /* A lustre/lustre mount point is crossed. */
4645                         param->fp_got_uuids = 0;
4646                         param->fp_obds_printed = 0;
4647                         param->fp_mdt_index = OBD_NOT_FOUND;
4648                         param->fp_obd_index = OBD_NOT_FOUND;
4649                 }
4650
4651                 if (lustre_fs && !param->fp_got_uuids) {
4652                         ret = setup_target_indexes(dir ? dir : parent, path,
4653                                                    param);
4654                         if (ret)
4655                                 goto out;
4656
4657                         param->fp_dev = makedev(stx->stx_dev_major,
4658                                                 stx->stx_dev_minor);
4659                 } else if (!lustre_fs && param->fp_got_uuids) {
4660                         /* A lustre/non-lustre mount point is crossed. */
4661                         param->fp_got_uuids = 0;
4662                         param->fp_mdt_index = OBD_NOT_FOUND;
4663                         param->fp_obd_index = OBD_NOT_FOUND;
4664                 }
4665         }
4666
4667         if (param->fp_check_foreign) {
4668                 decision = find_check_foreign(param);
4669                 if (decision == -1)
4670                         goto decided;
4671         }
4672
4673         if (param->fp_check_stripe_size) {
4674                 decision = find_check_stripe_size(param);
4675                 if (decision == -1)
4676                         goto decided;
4677         }
4678
4679         if (param->fp_check_ext_size) {
4680                 decision = find_check_ext_size(param);
4681                 if (decision == -1)
4682                         goto decided;
4683         }
4684
4685         if (param->fp_check_stripe_count) {
4686                 decision = find_value_cmp(stripe_count, param->fp_stripe_count,
4687                                           param->fp_stripe_count_sign,
4688                                           param->fp_exclude_stripe_count, 1, 0);
4689                 if (decision == -1)
4690                         goto decided;
4691         }
4692
4693         if (param->fp_check_mdt_count) {
4694                 if (param->fp_lmv_md->lum_magic == LMV_MAGIC_FOREIGN) {
4695                         decision = -1;
4696                         goto decided;
4697                 }
4698
4699                 decision = find_value_cmp(
4700                                 param->fp_lmv_md->lum_stripe_count,
4701                                 param->fp_mdt_count,
4702                                 param->fp_mdt_count_sign,
4703                                 param->fp_exclude_mdt_count, 1, 0);
4704                 if (decision == -1)
4705                         goto decided;
4706         }
4707
4708         if (param->fp_check_layout) {
4709                 decision = find_check_layout(param);
4710                 if (decision == -1)
4711                         goto decided;
4712         }
4713
4714         if (param->fp_check_hash_type) {
4715                 __u32 found;
4716
4717                 if (param->fp_lmv_md->lum_magic == LMV_MAGIC_FOREIGN) {
4718                         decision = -1;
4719                         goto decided;
4720                 }
4721
4722                 found = param->fp_lmv_md->lum_hash_type & param->fp_hash_type;
4723                 if ((found && param->fp_exclude_hash_type) ||
4724                     (!found && !param->fp_exclude_hash_type)) {
4725                         decision = -1;
4726                         goto decided;
4727                 }
4728         }
4729
4730         /* If an OBD UUID is specified but none matches, skip this file. */
4731         if ((param->fp_obd_uuid && param->fp_obd_index == OBD_NOT_FOUND) ||
4732             (param->fp_mdt_uuid && param->fp_mdt_index == OBD_NOT_FOUND))
4733                 goto decided;
4734
4735         /* If an OST or MDT UUID is given, and some OST matches,
4736          * check it here. */
4737         if (param->fp_obd_index != OBD_NOT_FOUND ||
4738             param->fp_mdt_index != OBD_NOT_FOUND) {
4739                 if (param->fp_obd_uuid) {
4740                         if (check_obd_match(param)) {
4741                                 /* If no mdtuuid is given, we are done.
4742                                  * Otherwise, fall through to the mdtuuid
4743                                  * check below. */
4744                                 if (!param->fp_mdt_uuid)
4745                                         goto obd_matches;
4746                         } else {
4747                                 goto decided;
4748                         }
4749                 }
4750
4751                 if (param->fp_mdt_uuid) {
4752                         if (check_mdt_match(param))
4753                                 goto obd_matches;
4754                         goto decided;
4755                 }
4756         }
4757
4758 obd_matches:
4759         if (param->fp_check_uid) {
4760                 if (stx->stx_uid == param->fp_uid) {
4761                         if (param->fp_exclude_uid)
4762                                 goto decided;
4763                 } else {
4764                         if (!param->fp_exclude_uid)
4765                                 goto decided;
4766                 }
4767         }
4768
4769         if (param->fp_check_gid) {
4770                 if (stx->stx_gid == param->fp_gid) {
4771                         if (param->fp_exclude_gid)
4772                                 goto decided;
4773                 } else {
4774                         if (!param->fp_exclude_gid)
4775                                 goto decided;
4776                 }
4777         }
4778
4779         if (param->fp_check_projid) {
4780                 int projid = 0;
4781
4782                 if (fd == -2)
4783                         fd = open(path, O_RDONLY);
4784
4785                 if (fd > 0)
4786                         ret = fget_projid(fd, &projid);
4787                 else
4788                         ret = -errno;
4789                 if (ret)
4790                         goto out;
4791                 if (projid == param->fp_projid) {
4792                         if (param->fp_exclude_projid)
4793                                 goto decided;
4794                 } else {
4795                         if (!param->fp_exclude_projid)
4796                                 goto decided;
4797                 }
4798         }
4799
4800         if (param->fp_check_pool) {
4801                 decision = find_check_pool(param);
4802                 if (decision == -1)
4803                         goto decided;
4804         }
4805
4806         if (param->fp_check_comp_count || param->fp_check_comp_flags ||
4807             param->fp_check_comp_start || param->fp_check_comp_end) {
4808                 decision = find_check_comp_options(param);
4809                 if (decision == -1)
4810                         goto decided;
4811         }
4812
4813         if (param->fp_check_mirror_count || param->fp_check_mirror_state) {
4814                 decision = find_check_mirror_options(param);
4815                 if (decision == -1)
4816                         goto decided;
4817         }
4818
4819         /* Check the time on mds. */
4820         decision = 1;
4821         if (param->fp_atime || param->fp_mtime || param->fp_ctime) {
4822                 int for_mds;
4823
4824                 for_mds = lustre_fs ?
4825                         (S_ISREG(stx->stx_mode) && stripe_count) : 0;
4826                 decision = find_time_check(stx, param, for_mds);
4827                 if (decision == -1)
4828                         goto decided;
4829         }
4830
4831         flags = param->fp_lmd->lmd_flags;
4832         if (param->fp_check_size &&
4833             ((S_ISREG(stx->stx_mode) && stripe_count) ||
4834               S_ISDIR(stx->stx_mode)) &&
4835             !(flags & OBD_MD_FLSIZE ||
4836               (param->fp_lazy && flags & OBD_MD_FLLAZYSIZE)))
4837                 decision = 0;
4838
4839         if (param->fp_check_blocks &&
4840             ((S_ISREG(stx->stx_mode) && stripe_count) ||
4841               S_ISDIR(stx->stx_mode)) &&
4842             !(flags & OBD_MD_FLBLOCKS ||
4843               (param->fp_lazy && flags & OBD_MD_FLLAZYBLOCKS)))
4844                 decision = 0;
4845
4846         /* If file still fits the request, ask ost for updated info.
4847          * The regular stat is almost of the same speed as some new
4848          * 'glimpse-size-ioctl'.
4849          */
4850         if (!decision) {
4851                 lstat_t st;
4852
4853                 /* For regular files with the stripe the decision may have not
4854                  * been taken yet if *time or size is to be checked. */
4855                 if (param->fp_obd_index != OBD_NOT_FOUND)
4856                         print_failed_tgt(param, path, LL_STATFS_LOV);
4857
4858                 if (param->fp_mdt_index != OBD_NOT_FOUND)
4859                         print_failed_tgt(param, path, LL_STATFS_LMV);
4860
4861                 if (dir != NULL)
4862                         ret = fstat_f(dirfd(dir), &st);
4863                 else if (de != NULL)
4864                         ret = fstatat_f(dirfd(parent), de->d_name, &st,
4865                                         AT_SYMLINK_NOFOLLOW);
4866                 else
4867                         ret = lstat_f(path, &st);
4868
4869                 if (ret) {
4870                         if (errno == ENOENT) {
4871                                 llapi_error(LLAPI_MSG_ERROR, -ENOENT,
4872                                             "warning: %s: %s does not exist",
4873                                             __func__, path);
4874                                 goto decided;
4875                         } else {
4876                                 ret = -errno;
4877                                 llapi_error(LLAPI_MSG_ERROR, ret,
4878                                             "%s: stat on %s failed",
4879                                             __func__, path);
4880                                 goto out;
4881                         }
4882                 }
4883
4884                 convert_lmd_statx(param->fp_lmd, &st, true);
4885                 /* Check the time on osc. */
4886                 decision = find_time_check(stx, param, 0);
4887                 if (decision == -1)
4888                         goto decided;
4889         }
4890
4891         if (param->fp_check_size) {
4892                 decision = find_value_cmp(stx->stx_size, param->fp_size,
4893                                           param->fp_size_sign,
4894                                           param->fp_exclude_size,
4895                                           param->fp_size_units, 0);
4896                 if (decision == -1)
4897                         goto decided;
4898         }
4899
4900         if (param->fp_check_blocks) { /* convert st_blocks to bytes */
4901                 decision = find_value_cmp(stx->stx_blocks * 512,
4902                                           param->fp_blocks,
4903                                           param->fp_blocks_sign,
4904                                           param->fp_exclude_blocks,
4905                                           param->fp_blocks_units, 0);
4906                 if (decision == -1)
4907                         goto decided;
4908         }
4909
4910 foreign:
4911         llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
4912         if (param->fp_zero_end)
4913                 llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
4914         else
4915                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
4916
4917 decided:
4918         ret = 0;
4919         /* Do not get down anymore? */
4920         if (param->fp_depth == param->fp_max_depth) {
4921                 ret = 1;
4922                 goto out;
4923         }
4924         param->fp_depth++;
4925 out:
4926         if (fd > 0)
4927                 close(fd);
4928         return ret;
4929 }
4930
4931 static int cb_migrate_mdt_init(char *path, DIR *parent, DIR **dirp,
4932                                void *param_data, struct dirent64 *de)
4933 {
4934         struct find_param *param = (struct find_param *)param_data;
4935         struct lmv_user_md *lmu = param->fp_lmv_md;
4936         DIR *tmp_parent = parent;
4937         char raw[MAX_IOC_BUFLEN] = {'\0'};
4938         char *rawbuf = raw;
4939         struct obd_ioctl_data data = { 0 };
4940         int fd;
4941         int ret;
4942         char *path_copy;
4943         char *filename;
4944         bool retry = false;
4945
4946         if (parent == NULL && dirp == NULL)
4947                 return -EINVAL;
4948
4949         if (!lmu)
4950                 return -EINVAL;
4951
4952         if (dirp != NULL)
4953                 closedir(*dirp);
4954
4955         if (parent == NULL) {
4956                 tmp_parent = opendir_parent(path);
4957                 if (tmp_parent == NULL) {
4958                         *dirp = NULL;
4959                         ret = -errno;
4960                         llapi_error(LLAPI_MSG_ERROR, ret,
4961                                     "can not open %s", path);
4962                         return ret;
4963                 }
4964         }
4965
4966         fd = dirfd(tmp_parent);
4967
4968         path_copy = strdup(path);
4969         filename = basename(path_copy);
4970
4971         data.ioc_inlbuf1 = (char *)filename;
4972         data.ioc_inllen1 = strlen(filename) + 1;
4973         data.ioc_inlbuf2 = (char *)lmu;
4974         data.ioc_inllen2 = lmv_user_md_size(lmu->lum_stripe_count,
4975                                             lmu->lum_magic);
4976         ret = llapi_ioctl_pack(&data, &rawbuf, sizeof(raw));
4977         if (ret != 0) {
4978                 llapi_error(LLAPI_MSG_ERROR, ret,
4979                             "llapi_obd_statfs: error packing ioctl data");
4980                 goto out;
4981         }
4982
4983 migrate:
4984         ret = ioctl(fd, LL_IOC_MIGRATE, rawbuf);
4985         if (ret != 0) {
4986                 if (errno == EBUSY && !retry) {
4987                         /* because migrate may not be able to lock all involved
4988                          * objects in order, for some of them it try lock, while
4989                          * there may be conflicting COS locks and cause migrate
4990                          * fail with EBUSY, hope a sync() could cause
4991                          * transaction commit and release these COS locks. */
4992                         sync();
4993                         retry = true;
4994                         goto migrate;
4995                 } else if (errno == EALREADY) {
4996                         if (param->fp_verbose & VERBOSE_DETAIL)
4997                                 llapi_printf(LLAPI_MSG_NORMAL,
4998                                              "%s was migrated to MDT%d already\n",
4999                                              path, lmu->lum_stripe_offset);
5000                         ret = 0;
5001                 } else {
5002                         ret = -errno;
5003                         llapi_error(LLAPI_MSG_ERROR, ret,
5004                                     "%s migrate failed: %s (%d)\n",
5005                                     path, strerror(-ret), ret);
5006                         goto out;
5007                 }
5008         } else if (param->fp_verbose & VERBOSE_DETAIL) {
5009                 llapi_printf(LLAPI_MSG_NORMAL,
5010                              "migrate %s to MDT%d stripe count %d\n",
5011                              path, lmu->lum_stripe_offset,
5012                              lmu->lum_stripe_count);
5013         }
5014
5015 out:
5016         if (dirp != NULL) {
5017                 /* If the directory is being migration, we need
5018                  * close the directory after migration,
5019                  * so the old directory cache will be cleanup
5020                  * on the client side, and re-open to get the
5021                  * new directory handle */
5022                 *dirp = opendir(path);
5023                 if (*dirp == NULL) {
5024                         ret = -errno;
5025                         llapi_error(LLAPI_MSG_ERROR, ret,
5026                                     "%s: Failed to open '%s'", __func__, path);
5027                 }
5028         }
5029
5030         if (parent == NULL)
5031                 closedir(tmp_parent);
5032
5033         free(path_copy);
5034
5035         return ret;
5036 }
5037
5038 /* dir migration finished, shrink its stripes */
5039 static int cb_migrate_mdt_fini(char *path, DIR *parent, DIR **dirp, void *data,
5040                                struct dirent64 *de)
5041 {
5042         struct find_param *param = data;
5043         struct lmv_user_md *lmu = param->fp_lmv_md;
5044         int lmulen = lmv_user_md_size(lmu->lum_stripe_count, lmu->lum_magic);
5045         int ret = 0;
5046
5047         if (de && de->d_type != DT_DIR)
5048                 goto out;
5049
5050         if (*dirp) {
5051                 /*
5052                  * close it before setxattr because the latter may destroy the
5053                  * original object, and cause close fail.
5054                  */
5055                 ret = closedir(*dirp);
5056                 *dirp = NULL;
5057                 if (ret)
5058                         goto out;
5059         }
5060
5061         ret = setxattr(path, XATTR_NAME_LMV, lmu, lmulen, 0);
5062         if (ret == -EALREADY)
5063                 ret = 0;
5064 out:
5065         cb_common_fini(path, parent, dirp, data, de);
5066         return ret;
5067 }
5068
5069 int llapi_migrate_mdt(char *path, struct find_param *param)
5070 {
5071         return param_callback(path, cb_migrate_mdt_init, cb_migrate_mdt_fini,
5072                               param);
5073 }
5074
5075 int llapi_mv(char *path, struct find_param *param)
5076 {
5077 #if LUSTRE_VERSION_CODE > OBD_OCD_VERSION(2, 9, 59, 0)
5078         static bool printed;
5079
5080         if (!printed) {
5081                 llapi_error(LLAPI_MSG_ERROR, -ESTALE,
5082                             "llapi_mv() is deprecated, use llapi_migrate_mdt()\n");
5083                 printed = true;
5084         }
5085 #endif
5086         return llapi_migrate_mdt(path, param);
5087 }
5088
5089 int llapi_find(char *path, struct find_param *param)
5090 {
5091         return param_callback(path, cb_find_init, cb_common_fini, param);
5092 }
5093
5094 /*
5095  * Get MDT number that the file/directory inode referenced
5096  * by the open fd resides on.
5097  * Return 0 and mdtidx on success, or -ve errno.
5098  */
5099 int llapi_file_fget_mdtidx(int fd, int *mdtidx)
5100 {
5101         if (ioctl(fd, LL_IOC_GET_MDTIDX, mdtidx) < 0)
5102                 return -errno;
5103         return 0;
5104 }
5105
5106 static int cb_get_mdt_index(char *path, DIR *parent, DIR **dirp, void *data,
5107                             struct dirent64 *de)
5108 {
5109         struct find_param *param = (struct find_param *)data;
5110         DIR *d = dirp == NULL ? NULL : *dirp;
5111         int ret;
5112         int mdtidx;
5113
5114         if (parent == NULL && d == NULL)
5115                 return -EINVAL;
5116
5117         if (d != NULL) {
5118                 ret = llapi_file_fget_mdtidx(dirfd(d), &mdtidx);
5119         } else /* if (parent) */ {
5120                 int fd;
5121
5122                 fd = open(path, O_RDONLY | O_NOCTTY);
5123                 if (fd > 0) {
5124                         ret = llapi_file_fget_mdtidx(fd, &mdtidx);
5125                         close(fd);
5126                 } else {
5127                         ret = -errno;
5128                 }
5129         }
5130
5131         if (ret != 0) {
5132                 if (ret == -ENODATA) {
5133                         if (!param->fp_obd_uuid)
5134                                 llapi_printf(LLAPI_MSG_NORMAL,
5135                                              "'%s' has no stripe info\n", path);
5136                         goto out;
5137                 } else if (ret == -ENOENT) {
5138                         llapi_error(LLAPI_MSG_WARN, ret,
5139                                     "warning: %s: '%s' does not exist",
5140                                     __func__, path);
5141                         goto out;
5142                 } else if (ret == -ENOTTY) {
5143                         llapi_error(LLAPI_MSG_ERROR, ret,
5144                                     "%s: '%s' not on a Lustre fs",
5145                                     __func__, path);
5146                 } else {
5147                         llapi_error(LLAPI_MSG_ERROR, ret,
5148                                     "error: %s: '%s' failed get_mdtidx",
5149                                     __func__, path);
5150                 }
5151                 return ret;
5152         }
5153
5154         if (param->fp_quiet || !(param->fp_verbose & VERBOSE_DETAIL))
5155                 llapi_printf(LLAPI_MSG_NORMAL, "%d\n", mdtidx);
5156         else
5157                 llapi_printf(LLAPI_MSG_NORMAL, "%s\nmdt_index:\t%d\n",
5158                              path, mdtidx);
5159
5160 out:
5161         /* Do not go down anymore? */
5162         if (param->fp_depth == param->fp_max_depth)
5163                 return 1;
5164
5165         param->fp_depth++;
5166
5167         return 0;
5168 }
5169
5170 static int cb_getstripe(char *path, DIR *parent, DIR **dirp, void *data,
5171                         struct dirent64 *de)
5172 {
5173         struct find_param *param = (struct find_param *)data;
5174         DIR *d = dirp == NULL ? NULL : *dirp;
5175         int ret = 0;
5176
5177         if (parent == NULL && d == NULL)
5178                 return -EINVAL;
5179
5180         if (param->fp_obd_uuid) {
5181                 param->fp_quiet = 1;
5182                 ret = setup_obd_uuid(d ? dirfd(d) : dirfd(parent), path, param);
5183                 if (ret)
5184                         return ret;
5185         }
5186
5187         if (d && (param->fp_get_lmv || param->fp_get_default_lmv))
5188                 ret = cb_get_dirstripe(path, d, param);
5189         else if (d ||
5190                  (parent && !param->fp_get_lmv && !param->fp_get_default_lmv))
5191                 ret = get_lmd_info(path, parent, d, &param->fp_lmd->lmd_lmm,
5192                                    param->fp_lum_size, GET_LMD_STRIPE);
5193         else
5194                 return 0;
5195
5196         if (ret) {
5197                 if (errno == ENODATA && d != NULL) {
5198                         /* We need to "fake" the "use the default" values
5199                          * since the lmm struct is zeroed out at this point.
5200                          * The magic needs to be set in order to satisfy
5201                          * a check later on in the code path.
5202                          * The object_seq needs to be set for the "(Default)"
5203                          * prefix to be displayed. */
5204                         if (param->fp_get_default_lmv) {
5205                                 struct lmv_user_md *lum = param->fp_lmv_md;
5206
5207                                 lum->lum_magic = LMV_USER_MAGIC;
5208                                 lum->lum_stripe_count = 0;
5209                                 lum->lum_stripe_offset = -1;
5210                                 goto dump;
5211                         } else if (param->fp_get_lmv) {
5212                                 struct lmv_user_md *lum = param->fp_lmv_md;
5213                                 int mdtidx;
5214
5215                                 ret = llapi_file_fget_mdtidx(dirfd(d), &mdtidx);
5216                                 if (ret != 0)
5217                                         goto err_out;
5218                                 lum->lum_magic = LMV_MAGIC_V1;
5219                                 lum->lum_stripe_count = 0;
5220                                 lum->lum_stripe_offset = mdtidx;
5221                                 goto dump;
5222                         } else {
5223                                 struct lov_user_md *lmm =
5224                                         &param->fp_lmd->lmd_lmm;
5225
5226                                 lmm->lmm_magic = LOV_USER_MAGIC_V1;
5227                                 if (!param->fp_raw)
5228                                         ostid_set_seq(&lmm->lmm_oi,
5229                                                       FID_SEQ_LOV_DEFAULT);
5230                                 lmm->lmm_stripe_count = 0;
5231                                 lmm->lmm_stripe_size = 0;
5232                                 lmm->lmm_stripe_offset = -1;
5233                                 goto dump;
5234                         }
5235                 } else if (errno == ENODATA && parent != NULL) {
5236                         if (!param->fp_obd_uuid && !param->fp_mdt_uuid)
5237                                 llapi_printf(LLAPI_MSG_NORMAL,
5238                                              "%s has no stripe info\n", path);
5239                         goto out;
5240                 } else if (errno == ENOENT) {
5241                         llapi_error(LLAPI_MSG_WARN, -ENOENT,
5242                                     "warning: %s: %s does not exist",
5243                                     __func__, path);
5244                         goto out;
5245                 } else if (errno == ENOTTY) {
5246                         ret = -errno;
5247                         llapi_error(LLAPI_MSG_ERROR, ret,
5248                                     "%s: '%s' not on a Lustre fs?",
5249                                     __func__, path);
5250                 } else {
5251                         ret = -errno;
5252 err_out:
5253                         llapi_error(LLAPI_MSG_ERROR, ret,
5254                                     "error: %s: %s failed for %s",
5255                                      __func__, d ? "LL_IOC_LOV_GETSTRIPE" :
5256                                     "IOC_MDC_GETFILESTRIPE", path);
5257                 }
5258
5259                 return ret;
5260         }
5261
5262 dump:
5263         if (!(param->fp_verbose & VERBOSE_MDTINDEX))
5264                 llapi_lov_dump_user_lmm(param, path, d ? LDF_IS_DIR : 0);
5265
5266 out:
5267         /* Do not get down anymore? */
5268         if (param->fp_depth == param->fp_max_depth)
5269                 return 1;
5270
5271         param->fp_depth++;
5272
5273         return 0;
5274 }
5275
5276 int llapi_getstripe(char *path, struct find_param *param)
5277 {
5278         return param_callback(path, (param->fp_verbose & VERBOSE_MDTINDEX) ?
5279                               cb_get_mdt_index : cb_getstripe,
5280                               cb_common_fini, param);
5281 }
5282
5283 int llapi_obd_fstatfs(int fd, __u32 type, __u32 index,
5284                       struct obd_statfs *stat_buf, struct obd_uuid *uuid_buf)
5285 {
5286         char raw[MAX_IOC_BUFLEN] = {'\0'};
5287         char *rawbuf = raw;
5288         struct obd_ioctl_data data = { 0 };
5289         int rc = 0;
5290
5291         data.ioc_inlbuf1 = (char *)&type;
5292         data.ioc_inllen1 = sizeof(__u32);
5293         data.ioc_inlbuf2 = (char *)&index;
5294         data.ioc_inllen2 = sizeof(__u32);
5295         data.ioc_pbuf1 = (char *)stat_buf;
5296         data.ioc_plen1 = sizeof(struct obd_statfs);
5297         data.ioc_pbuf2 = (char *)uuid_buf;
5298         data.ioc_plen2 = sizeof(struct obd_uuid);
5299
5300         rc = llapi_ioctl_pack(&data, &rawbuf, sizeof(raw));
5301         if (rc != 0) {
5302                 llapi_error(LLAPI_MSG_ERROR, rc,
5303                             "llapi_obd_statfs: error packing ioctl data");
5304                 return rc;
5305         }
5306
5307         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
5308
5309         return rc < 0 ? -errno : 0;
5310 }
5311
5312 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
5313                      struct obd_statfs *stat_buf, struct obd_uuid *uuid_buf)
5314 {
5315         int fd;
5316         int rc;
5317
5318         fd = open(path, O_RDONLY);
5319         if (fd < 0) {
5320                 rc = -errno;
5321                 llapi_error(LLAPI_MSG_ERROR, rc, "error: %s: opening '%s'",
5322                             __func__, path);
5323                 /* If we can't even open a file on the filesystem (e.g. with
5324                  * -ESHUTDOWN), force caller to exit or it will loop forever. */
5325                 return -ENODEV;
5326         }
5327
5328         rc = llapi_obd_fstatfs(fd, type, index, stat_buf, uuid_buf);
5329
5330         close(fd);
5331
5332         return rc;
5333 }
5334
5335 #define MAX_STRING_SIZE 128
5336
5337 int llapi_ping(char *obd_type, char *obd_name)
5338 {
5339         int flags = O_RDONLY;
5340         char buf[1] = { 0 };
5341         glob_t path;
5342         int rc, fd;
5343
5344         rc = cfs_get_param_paths(&path, "%s/%s/ping",
5345                                 obd_type, obd_name);
5346         if (rc != 0)
5347                 return -errno;
5348 retry_open:
5349         fd = open(path.gl_pathv[0], flags);
5350         if (fd < 0) {
5351                 if (errno == EACCES && flags == O_RDONLY) {
5352                         flags = O_WRONLY;
5353                         goto retry_open;
5354                 }
5355                 rc = -errno;
5356                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s",
5357                             path.gl_pathv[0]);
5358                 goto failed;
5359         }
5360
5361         if (flags == O_RDONLY)
5362                 rc = read(fd, buf, sizeof(buf));
5363         else
5364                 rc = write(fd, buf, sizeof(buf));
5365         if (rc < 0)
5366                 rc = -errno;
5367         close(fd);
5368
5369         if (rc == 1)
5370                 rc = 0;
5371 failed:
5372         cfs_free_param_data(&path);
5373         return rc;
5374 }
5375
5376 int llapi_target_iterate(int type_num, char **obd_type,
5377                          void *args, llapi_cb_t cb)
5378 {
5379         int i, rc = 0;
5380         glob_t param;
5381         FILE *fp;
5382
5383         for (i = 0; i < type_num; i++) {
5384                 int j;
5385
5386                 rc = cfs_get_param_paths(&param, "%s/*/uuid", obd_type[i]);
5387                 if (rc != 0)
5388                         continue;
5389
5390                 for (j = 0; j < param.gl_pathc; j++) {
5391                         char obd_uuid[UUID_MAX + 1];
5392                         char *obd_name;
5393                         char *ptr;
5394
5395                         fp = fopen(param.gl_pathv[j], "r");
5396                         if (fp == NULL) {
5397                                 rc = -errno;
5398                                 llapi_error(LLAPI_MSG_ERROR, rc,
5399                                             "error: opening '%s'",
5400                                             param.gl_pathv[j]);
5401                                 goto free_path;
5402                         }
5403
5404                         if (fgets(obd_uuid, sizeof(obd_uuid), fp) == NULL) {
5405                                 rc = -errno;
5406                                 llapi_error(LLAPI_MSG_ERROR, rc,
5407                                             "error: reading '%s'",
5408                                             param.gl_pathv[j]);
5409                                 goto free_path;
5410                         }
5411
5412                         /* Extract the obd_name from the sysfs path.
5413                          * 'topsysfs'/fs/lustre/'obd_type'/'obd_name'.
5414                          */
5415                         obd_name = strstr(param.gl_pathv[j], "/fs/lustre/");
5416                         if (!obd_name) {
5417                                 rc = -EINVAL;
5418                                 goto free_path;
5419                         }
5420
5421                         /* skip /fs/lustre/'obd_type'/ */
5422                         obd_name += strlen(obd_type[i]) + 12;
5423                         /* chop off after obd_name */
5424                         ptr = strrchr(obd_name, '/');
5425                         if (ptr)
5426                                 *ptr = '\0';
5427
5428                         cb(obd_type[i], obd_name, obd_uuid, args);
5429
5430                         fclose(fp);
5431                         fp = NULL;
5432                 }
5433         }
5434 free_path:
5435         if (fp)
5436                 fclose(fp);
5437         cfs_free_param_data(&param);
5438         return rc;
5439 }
5440
5441 static void do_target_check(char *obd_type_name, char *obd_name,
5442                             char *obd_uuid, void *args)
5443 {
5444         int rc;
5445
5446         rc = llapi_ping(obd_type_name, obd_name);
5447         if (rc == ENOTCONN) {
5448                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
5449         } else if (rc) {
5450                 llapi_error(LLAPI_MSG_ERROR, rc, "error: check '%s'", obd_name);
5451         } else {
5452                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
5453         }
5454 }
5455
5456 int llapi_target_check(int type_num, char **obd_type, char *dir)
5457 {
5458         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
5459 }
5460
5461 #undef MAX_STRING_SIZE
5462
5463 /* Is this a lustre fs? */
5464 int llapi_is_lustre_mnttype(const char *type)
5465 {
5466         return strcmp(type, "lustre") == 0 || strcmp(type, "lustre_tgt") == 0;
5467 }
5468
5469 /* Is this a lustre client fs? */
5470 int llapi_is_lustre_mnt(struct mntent *mnt)
5471 {
5472         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
5473                 strstr(mnt->mnt_fsname, ":/") != NULL);
5474 }
5475
5476 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
5477 {
5478         char fsname[PATH_MAX + 1];
5479         int root;
5480         int rc;
5481
5482         rc = llapi_search_fsname(mnt, fsname);
5483         if (rc)
5484                 return rc;
5485
5486         root = open(mnt, O_RDONLY | O_DIRECTORY);
5487         if (root < 0) {
5488                 rc = -errno;
5489                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot open '%s'", mnt);
5490                 return rc;
5491         }
5492
5493         rc = ioctl(root, OBD_IOC_QUOTACTL, qctl);
5494         if (rc < 0)
5495                 rc = -errno;
5496
5497         close(root);
5498         return rc;
5499 }
5500
5501 /* Print mdtname 'name' into 'buf' using 'format'.  Add -MDT0000 if needed.
5502  * format must have %s%s, buf must be > 16
5503  * Eg: if name = "lustre-MDT0000", "lustre", or "lustre-MDT0000_UUID"
5504  *     then buf = "lustre-MDT0000"
5505  */
5506 static int get_mdtname(char *name, char *format, char *buf)
5507 {
5508         char suffix[]="-MDT0000";
5509         int len = strlen(name);
5510
5511         if ((len > 5) && (strncmp(name + len - 5, "_UUID", 5) == 0)) {
5512                 name[len - 5] = '\0';
5513                 len -= 5;
5514         }
5515
5516         if (len > 8) {
5517                 if ((len <= 16) && strncmp(name + len - 8, "-MDT", 4) == 0) {
5518                         suffix[0] = '\0';
5519                 } else {
5520                         /* Not enough room to add suffix */
5521                         llapi_err_noerrno(LLAPI_MSG_ERROR,
5522                                           "Invalid MDT name |%s|", name);
5523                         return -EINVAL;
5524                 }
5525         }
5526
5527         return sprintf(buf, format, name, suffix);
5528 }
5529
5530 /** ioctl on filsystem root, with mdtindex sent as data
5531  * \param mdtname path, fsname, or mdtname (lutre-MDT0004)
5532  * \param mdtidxp pointer to integer within data to be filled in with the
5533  *    mdt index (0 if no mdt is specified).  NULL won't be filled.
5534  */
5535 int root_ioctl(const char *mdtname, int opc, void *data, int *mdtidxp,
5536                int want_error)
5537 {
5538         char fsname[20];
5539         char *ptr;
5540         int fd, rc;
5541         long index;
5542
5543         /* Take path, fsname, or MDTname.  Assume MDT0000 in the former cases.
5544          Open root and parse mdt index. */
5545         if (mdtname[0] == '/') {
5546                 index = 0;
5547                 rc = get_root_path(WANT_FD | want_error, NULL, &fd,
5548                                    (char *)mdtname, -1);
5549         } else {
5550                 if (get_mdtname((char *)mdtname, "%s%s", fsname) < 0)
5551                         return -EINVAL;
5552                 ptr = fsname + strlen(fsname) - 8;
5553                 *ptr = '\0';
5554                 index = strtol(ptr + 4, NULL, 16);
5555                 rc = get_root_path(WANT_FD | want_error, fsname, &fd, NULL, -1);
5556         }
5557         if (rc < 0) {
5558                 if (want_error)
5559                         llapi_err_noerrno(LLAPI_MSG_ERROR,
5560                                           "Can't open %s: %d\n", mdtname, rc);
5561                 return rc;
5562         }
5563
5564         if (mdtidxp)
5565                 *mdtidxp = index;
5566
5567         rc = ioctl(fd, opc, data);
5568         if (rc == -1)
5569                 rc = -errno;
5570         else
5571                 rc = 0;
5572         close(fd);
5573         return rc;
5574 }
5575
5576 int llapi_fid2path(const char *device, const char *fidstr, char *buf,
5577                    int buflen, long long *recno, int *linkno)
5578 {
5579         const char *fidstr_orig = fidstr;
5580         struct lu_fid fid;
5581         struct getinfo_fid2path *gf;
5582         char *a;
5583         char *b;
5584         int rc;
5585
5586         while (*fidstr == '[')
5587                 fidstr++;
5588
5589         sscanf(fidstr, SFID, RFID(&fid));
5590         if (!fid_is_sane(&fid)) {
5591                 llapi_err_noerrno(LLAPI_MSG_ERROR,
5592                                   "bad FID format '%s', should be [seq:oid:ver]"
5593                                   " (e.g. "DFID")\n", fidstr_orig,
5594                                   (unsigned long long)FID_SEQ_NORMAL, 2, 0);
5595                 return -EINVAL;
5596         }
5597
5598         gf = malloc(sizeof(*gf) + buflen);
5599         if (gf == NULL)
5600                 return -ENOMEM;
5601
5602         gf->gf_fid = fid;
5603         gf->gf_recno = *recno;
5604         gf->gf_linkno = *linkno;
5605         gf->gf_pathlen = buflen;
5606
5607         /* Take path or fsname */
5608         rc = root_ioctl(device, OBD_IOC_FID2PATH, gf, NULL, 0);
5609         if (rc)
5610                 goto out_free;
5611
5612         b = buf;
5613         /* strip out instances of // */
5614         for (a = gf->gf_u.gf_path; *a != '\0'; a++) {
5615                 if ((*a == '/') && (*(a + 1) == '/'))
5616                         continue;
5617                 *b = *a;
5618                 b++;
5619         }
5620         *b = '\0';
5621
5622         if (buf[0] == '\0') { /* ROOT path */
5623                 buf[0] = '/';
5624                 buf[1] = '\0';
5625         }
5626
5627         *recno = gf->gf_recno;
5628         *linkno = gf->gf_linkno;
5629
5630 out_free:
5631         free(gf);
5632         return rc;
5633 }
5634
5635 static int fid_from_lma(const char *path, int fd, struct lu_fid *fid)
5636 {
5637         char                     buf[512];
5638         struct lustre_mdt_attrs *lma;
5639         int                      rc;
5640
5641         if (path == NULL)
5642                 rc = fgetxattr(fd, XATTR_NAME_LMA, buf, sizeof(buf));
5643         else
5644                 rc = lgetxattr(path, XATTR_NAME_LMA, buf, sizeof(buf));
5645         if (rc < 0)
5646                 return -errno;
5647         lma = (struct lustre_mdt_attrs *)buf;
5648         fid_le_to_cpu(fid, &lma->lma_self_fid);
5649         return 0;
5650 }
5651
5652 int llapi_get_mdt_index_by_fid(int fd, const struct lu_fid *fid,
5653                                int *mdt_index)
5654 {
5655         int     rc;
5656
5657         rc = ioctl(fd, LL_IOC_FID2MDTIDX, fid);
5658         if (rc < 0)
5659                 return -errno;
5660
5661         *mdt_index = rc;
5662
5663         return rc;
5664 }
5665
5666 int llapi_fd2fid(int fd, struct lu_fid *fid)
5667 {
5668         int rc;
5669
5670         memset(fid, 0, sizeof(*fid));
5671
5672         rc = ioctl(fd, LL_IOC_PATH2FID, fid) < 0 ? -errno : 0;
5673         if (rc == -EINVAL || rc == -ENOTTY)
5674                 rc = fid_from_lma(NULL, fd, fid);
5675
5676         return rc;
5677 }
5678
5679 int llapi_path2fid(const char *path, struct lu_fid *fid)
5680 {
5681         int fd, rc;
5682
5683         memset(fid, 0, sizeof(*fid));
5684         fd = open(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
5685         if (fd < 0) {
5686                 if (errno == ELOOP || errno == ENXIO)
5687                         return fid_from_lma(path, -1, fid);
5688                 return -errno;
5689         }
5690
5691         rc = llapi_fd2fid(fd, fid);
5692         if (rc == -EINVAL || rc == -ENOTTY)
5693                 rc = fid_from_lma(path, -1, fid);
5694
5695         close(fd);
5696         return rc;
5697 }
5698
5699 int llapi_fd2parent(int fd, unsigned int linkno, struct lu_fid *parent_fid,
5700                     char *name, size_t name_size)
5701 {
5702         struct getparent        *gp;
5703         int                      rc;
5704
5705         gp = malloc(sizeof(*gp) + name_size);
5706         if (gp == NULL)
5707                 return -ENOMEM;
5708
5709         gp->gp_linkno = linkno;
5710         gp->gp_name_size = name_size;
5711
5712         rc = ioctl(fd, LL_IOC_GETPARENT, gp);
5713         if (rc < 0) {
5714                 rc = -errno;
5715                 goto err_free;
5716         }
5717
5718         *parent_fid = gp->gp_fid;
5719
5720         strncpy(name, gp->gp_name, name_size);
5721         name[name_size - 1] = '\0';
5722
5723 err_free:
5724         free(gp);
5725         return rc;
5726 }
5727
5728 int llapi_path2parent(const char *path, unsigned int linkno,
5729                       struct lu_fid *parent_fid, char *name, size_t name_size)
5730 {
5731         int     fd;
5732         int     rc;
5733
5734         fd = open(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
5735         if (fd < 0)
5736                 return -errno;
5737
5738         rc = llapi_fd2parent(fd, linkno, parent_fid, name, name_size);
5739         close(fd);
5740         return rc;
5741 }
5742
5743 int llapi_get_connect_flags(const char *mnt, __u64 *flags)
5744 {
5745         int root;
5746         int rc;
5747
5748         root = open(mnt, O_RDONLY | O_DIRECTORY);
5749         if (root < 0) {
5750                 rc = -errno;
5751                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
5752                 return rc;
5753         }
5754
5755         rc = ioctl(root, LL_IOC_GET_CONNECT_FLAGS, flags);
5756         if (rc < 0) {
5757                 rc = -errno;
5758                 llapi_error(LLAPI_MSG_ERROR, rc,
5759                         "ioctl on %s for getting connect flags failed", mnt);
5760         }
5761         close(root);
5762         return rc;
5763 }
5764
5765 /**
5766  * Get a 64-bit value representing the version of file data pointed by fd.
5767  *
5768  * Each write or truncate, flushed on OST, will change this value. You can use
5769  * this value to verify if file data was modified. This only checks the file
5770  * data, not metadata.
5771  *
5772  * \param  flags  0: no flush pages, usually used it the process has already
5773  *                  taken locks;
5774  *                LL_DV_RD_FLUSH: OSTs will take LCK_PR to flush dirty pages
5775  *                  from clients;
5776  *                LL_DV_WR_FLUSH: OSTs will take LCK_PW to flush all caching
5777  *                  pages from clients.
5778  *
5779  * \retval 0 on success.
5780  * \retval -errno on error.
5781  */
5782 int llapi_get_data_version(int fd, __u64 *data_version, __u64 flags)
5783 {
5784         int rc;
5785         struct ioc_data_version idv;
5786
5787         idv.idv_flags = (__u32)flags;
5788
5789         rc = ioctl(fd, LL_IOC_DATA_VERSION, &idv);
5790         if (rc)
5791                 rc = -errno;
5792         else
5793                 *data_version = idv.idv_version;
5794
5795         return rc;
5796 }
5797
5798 /**
5799  * Flush cached pages from all clients.
5800  *
5801  * \param fd    File descriptor
5802  * \retval 0    success
5803  * \retval < 0  error
5804  */
5805 int llapi_file_flush(int fd)
5806 {
5807         __u64 dv;
5808
5809         return llapi_get_data_version(fd, &dv, LL_DV_WR_FLUSH);
5810 }
5811
5812 /*
5813  * Fetch layout version from OST objects. Layout version on OST objects are
5814  * only set when the file is a mirrored file AND after the file has been
5815  * written at least once.
5816  *
5817  * It actually fetches the least layout version from the objects.
5818  */
5819 int llapi_get_ost_layout_version(int fd, __u32 *layout_version)
5820 {
5821         int rc;
5822         struct ioc_data_version idv = { 0 };
5823
5824         rc = ioctl(fd, LL_IOC_DATA_VERSION, &idv);
5825         if (rc)
5826                 rc = -errno;
5827         else
5828                 *layout_version = idv.idv_layout_version;
5829
5830         return rc;
5831 }
5832
5833 /*
5834  * Create a file without any name and open it for read/write
5835  *
5836  * - file is created as if it were a standard file in the given \a directory
5837  * - file does not appear in \a directory and mtime does not change because
5838  *   the filename is handled specially by the Lustre MDS.
5839  * - file is destroyed at final close
5840  *
5841  * \param[in]   directory       directory from which to inherit layout/MDT idx
5842  * \param[in]   mdt_idx         MDT index on which the file is created,
5843  *                              \a idx == -1 means no specific MDT is requested
5844  * \param[in]   mode            standard open(2) mode
5845  * \param[in]   stripe_param    stripe parameters. May be NULL.
5846  *
5847  * \retval      a file descriptor on success.
5848  * \retval      -errno on error.
5849  */
5850 int llapi_create_volatile_param(const char *directory, int mdt_idx,
5851                                 int open_flags, mode_t mode,
5852                                 const struct llapi_stripe_param *stripe_param)
5853 {
5854         char file_path[PATH_MAX];
5855         int saved_errno = errno;
5856         int fd;
5857         unsigned int rnumber;
5858         int rc;
5859
5860         do {
5861                 rnumber = random();
5862                 if (mdt_idx == -1)
5863                         rc = snprintf(file_path, sizeof(file_path),
5864                                       "%s/" LUSTRE_VOLATILE_HDR "::%.4X",
5865                                       directory, rnumber);
5866                 else
5867                         rc = snprintf(file_path, sizeof(file_path),
5868                                       "%s/" LUSTRE_VOLATILE_HDR ":%.4X:%.4X",
5869                                       directory, mdt_idx, rnumber);
5870
5871                 if (rc < 0 || rc >= sizeof(file_path))
5872                         return -ENAMETOOLONG;
5873
5874                 /*
5875                  * Either open O_WRONLY or O_RDWR, creating RDONLY
5876                  * is non-sensical here
5877                  */
5878                 if ((open_flags & O_ACCMODE) == O_RDONLY)
5879                         open_flags = O_RDWR | (open_flags & ~O_ACCMODE);
5880
5881                 open_flags |= O_CREAT | O_EXCL | O_NOFOLLOW;
5882
5883                 if (stripe_param != NULL) {
5884                         fd = llapi_file_open_param(file_path, open_flags,
5885                                                    mode, stripe_param);
5886                         if (fd < 0)
5887                                 rc = fd;
5888                 } else {
5889                         fd = open(file_path, open_flags, mode);
5890                         if (fd < 0)
5891                                 rc = -errno;
5892                 }
5893         } while (fd < 0 && rc == -EEXIST);
5894
5895         if (fd < 0) {
5896                 llapi_error(LLAPI_MSG_ERROR, rc,
5897                             "Cannot create volatile file '%s' in '%s'",
5898                             file_path + strlen(directory) + 1 +
5899                             LUSTRE_VOLATILE_HDR_LEN,
5900                             directory);
5901                 return rc;
5902         }
5903
5904         /*
5905          * Unlink file in case this wasn't a Lustre filesystem and the magic
5906          * volatile filename wasn't handled as intended. The effect is the
5907          * same. If volatile open was supported then we expect unlink() to
5908          * return -ENOENT.
5909          */
5910         (void)unlink(file_path);
5911
5912         /*
5913          * Since we are returning successfully we restore errno (and
5914          * mask out possible EEXIST from open() and ENOENT from unlink().
5915          */
5916         errno = saved_errno;
5917
5918         return fd;
5919 }
5920
5921 /*
5922  * Create a file without any name open it for read/write
5923  *
5924  * - file is created as if it were a standard file in the given \a directory
5925  * - file does not appear in \a directory and mtime does not change because
5926  *   the filename is handled specially by the Lustre MDS.
5927  * - file is removed at final close
5928  * - file modes are rw------- since it doesn't make sense to have a read-only
5929  *   or write-only file that cannot be opened again.
5930  * - if user wants another mode it must use fchmod() on the open file, no
5931  *   security problems arise because it cannot be opened by another process.
5932  *
5933  * \param[in]   directory       directory from which to inherit layout/MDT idx
5934  * \param[in]   idx             MDT index on which the file is created,
5935  *                              \a idx == -1 means no specific MDT is requested
5936  * \param[in]   open_flags      standard open(2) flags
5937  *
5938  * \retval      a file descriptor on success.
5939  * \retval      -errno on error.
5940  */
5941 int llapi_create_volatile_idx(const char *directory, int mdt_idx,
5942                               int open_flags)
5943 {
5944         return llapi_create_volatile_param(directory, mdt_idx, open_flags,
5945                                            S_IRUSR | S_IWUSR, NULL);
5946 }
5947
5948 /**
5949  * Swap the layouts between 2 file descriptors
5950  * the 2 files must be open for writing
5951  * first fd received the ioctl, second fd is passed as arg
5952  * this is assymetric but avoid use of root path for ioctl
5953  */
5954 int llapi_fswap_layouts_grouplock(int fd1, int fd2, __u64 dv1, __u64 dv2,
5955                                   int gid, __u64 flags)
5956 {
5957         struct lustre_swap_layouts      lsl;
5958         struct stat                     st1;
5959         struct stat                     st2;
5960         int                             rc;
5961
5962         if (flags & (SWAP_LAYOUTS_KEEP_ATIME | SWAP_LAYOUTS_KEEP_MTIME)) {
5963                 rc = fstat(fd1, &st1);
5964                 if (rc < 0)
5965                         return -errno;
5966
5967                 rc = fstat(fd2, &st2);
5968                 if (rc < 0)
5969                         return -errno;
5970         }
5971         lsl.sl_fd = fd2;
5972         lsl.sl_flags = flags;
5973         lsl.sl_gid = gid;
5974         lsl.sl_dv1 = dv1;
5975         lsl.sl_dv2 = dv2;
5976         rc = ioctl(fd1, LL_IOC_LOV_SWAP_LAYOUTS, &lsl);
5977         if (rc < 0)
5978                 return -errno;
5979
5980         if (flags & (SWAP_LAYOUTS_KEEP_ATIME | SWAP_LAYOUTS_KEEP_MTIME)) {
5981                 struct timeval  tv1[2];
5982                 struct timeval  tv2[2];
5983
5984                 memset(tv1, 0, sizeof(tv1));
5985                 memset(tv2, 0, sizeof(tv2));
5986
5987                 if (flags & SWAP_LAYOUTS_KEEP_ATIME) {
5988                         tv1[0].tv_sec = st1.st_atime;
5989                         tv2[0].tv_sec = st2.st_atime;
5990                 } else {
5991                         tv1[0].tv_sec = st2.st_atime;
5992                         tv2[0].tv_sec = st1.st_atime;
5993                 }
5994
5995                 if (flags & SWAP_LAYOUTS_KEEP_MTIME) {
5996                         tv1[1].tv_sec = st1.st_mtime;
5997                         tv2[1].tv_sec = st2.st_mtime;
5998                 } else {
5999                         tv1[1].tv_sec = st2.st_mtime;
6000                         tv2[1].tv_sec = st1.st_mtime;
6001                 }
6002
6003                 rc = futimes(fd1, tv1);
6004                 if (rc < 0)
6005                         return -errno;
6006
6007                 rc = futimes(fd2, tv2);
6008                 if (rc < 0)
6009                         return -errno;
6010         }
6011
6012         return 0;
6013 }
6014
6015 int llapi_fswap_layouts(int fd1, int fd2, __u64 dv1, __u64 dv2, __u64 flags)
6016 {
6017         int     rc;
6018         int     grp_id;
6019
6020         do
6021                 grp_id = random();
6022         while (grp_id == 0);
6023
6024         rc = llapi_fswap_layouts_grouplock(fd1, fd2, dv1, dv2, grp_id, flags);
6025         if (rc < 0)
6026                 return rc;
6027
6028         return 0;
6029 }
6030
6031 /**
6032  * Swap the layouts between 2 files
6033  * the 2 files are open in write
6034  */
6035 int llapi_swap_layouts(const char *path1, const char *path2,
6036                        __u64 dv1, __u64 dv2, __u64 flags)
6037 {
6038         int     fd1, fd2, rc;
6039
6040         fd1 = open(path1, O_WRONLY | O_LOV_DELAY_CREATE);
6041         if (fd1 < 0) {
6042                 rc = -errno;
6043                 llapi_error(LLAPI_MSG_ERROR, rc,
6044                             "error: cannot open '%s' for write", path1);
6045                 goto out;
6046         }
6047
6048         fd2 = open(path2, O_WRONLY | O_LOV_DELAY_CREATE);
6049         if (fd2 < 0) {
6050                 rc = -errno;
6051                 llapi_error(LLAPI_MSG_ERROR, rc,
6052                             "error: cannot open '%s' for write", path2);
6053                 goto out_close;
6054         }
6055
6056         rc = llapi_fswap_layouts(fd1, fd2, dv1, dv2, flags);
6057         if (rc < 0)
6058                 llapi_error(LLAPI_MSG_ERROR, rc,
6059                             "error: cannot swap layout between '%s' and '%s'",
6060                             path1, path2);
6061
6062         close(fd2);
6063 out_close:
6064         close(fd1);
6065 out:
6066         return rc;
6067 }
6068
6069 /**
6070  * Attempt to open a file with Lustre file identifier \a fid
6071  * and return an open file descriptor.
6072  *
6073  * \param[in] lustre_dir        path within Lustre filesystem containing \a fid
6074  * \param[in] fid               Lustre file identifier of file to open
6075  * \param[in] flags             open() flags
6076  *
6077  * \retval                      non-negative file descriptor on successful open
6078  * \retval                      -1 if an error occurred
6079  */
6080 int llapi_open_by_fid(const char *lustre_dir, const struct lu_fid *fid,
6081                       int flags)
6082 {
6083         char mntdir[PATH_MAX];
6084         char path[PATH_MAX + 64];
6085         int rc;
6086
6087         rc = llapi_search_mounts(lustre_dir, 0, mntdir, NULL);
6088         if (rc != 0)
6089                 return -1;
6090
6091         snprintf(path, sizeof(path), "%s/.lustre/fid/"DFID, mntdir, PFID(fid));
6092         return open(path, flags);
6093 }
6094
6095 /**
6096  * Take group lock.
6097  *
6098  * \param fd   File to lock.
6099  * \param gid  Group Identifier.
6100  *
6101  * \retval 0 on success.
6102  * \retval -errno on failure.
6103  */
6104 int llapi_group_lock(int fd, int gid)
6105 {
6106         int rc;
6107
6108         rc = ioctl(fd, LL_IOC_GROUP_LOCK, gid);
6109         if (rc < 0) {
6110                 rc = -errno;
6111                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot get group lock");
6112         }
6113         return rc;
6114 }
6115
6116 /**
6117  * Put group lock.
6118  *
6119  * \param fd   File to unlock.
6120  * \param gid  Group Identifier.
6121  *
6122  * \retval 0 on success.
6123  * \retval -errno on failure.
6124  */
6125 int llapi_group_unlock(int fd, int gid)
6126 {
6127         int rc;
6128
6129         rc = ioctl(fd, LL_IOC_GROUP_UNLOCK, gid);
6130         if (rc < 0) {
6131                 rc = -errno;
6132                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot put group lock");
6133         }
6134         return rc;
6135 }