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