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