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