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