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