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