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