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