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