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