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