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