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