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