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