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