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