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