Whamcloud - gitweb
LU-3888 utils: print lmm_fid as part of getstripe
[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, *ptr_end;
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 = strchr(mnt.mnt_fsname, '/');
877                 while (ptr && *ptr == '/')
878                         ptr++;
879                 /* thanks to the call to llapi_is_lustre_mnt() above,
880                  * we are sure that mnt.mnt_fsname contains ":/",
881                  * so ptr should never be NULL */
882                 if (ptr == NULL)
883                         continue;
884                 ptr_end = ptr;
885                 while (*ptr_end != '/' && *ptr_end != '\0')
886                         ptr_end++;
887
888                 /* Check the fsname for a match, if given */
889                 if (!(want & WANT_FSNAME) && fsname != NULL &&
890                     (strlen(fsname) > 0) &&
891                     (strncmp(ptr, fsname, ptr_end - ptr) != 0))
892                         continue;
893
894                 /* If the path isn't set return the first one we find */
895                 if (path == NULL || strlen(path) == 0) {
896                         strncpy(mntdir, mnt.mnt_dir, strlen(mnt.mnt_dir));
897                         mntdir[strlen(mnt.mnt_dir)] = '\0';
898                         if ((want & WANT_FSNAME) && fsname != NULL) {
899                                 strncpy(fsname, ptr, ptr_end - ptr);
900                                 fsname[ptr_end - ptr] = '\0';
901                         }
902                         rc = 0;
903                         break;
904                 /* Otherwise find the longest matching path */
905                 } else if ((strlen(path) >= mntlen) && (mntlen >= len) &&
906                            (strncmp(mnt.mnt_dir, path, mntlen) == 0)) {
907                         strncpy(mntdir, mnt.mnt_dir, strlen(mnt.mnt_dir));
908                         mntdir[strlen(mnt.mnt_dir)] = '\0';
909                         len = mntlen;
910                         if ((want & WANT_FSNAME) && fsname != NULL) {
911                                 strncpy(fsname, ptr, ptr_end - ptr);
912                                 fsname[ptr_end - ptr] = '\0';
913                         }
914                         rc = 0;
915                 }
916         }
917         endmntent(fp);
918
919         /* Found it */
920         if (rc == 0) {
921                 if ((want & WANT_PATH) && path != NULL) {
922                         strncpy(path, mntdir, strlen(mntdir));
923                         path[strlen(mntdir)] = '\0';
924                 }
925                 if (want & WANT_FD) {
926                         fd = open(mntdir, O_RDONLY | O_DIRECTORY | O_NONBLOCK);
927                         if (fd < 0) {
928                                 rc = -errno;
929                                 llapi_error(LLAPI_MSG_ERROR, rc,
930                                             "error opening '%s'", mntdir);
931
932                         } else {
933                                 *outfd = fd;
934                         }
935                 }
936         } else if (want & WANT_ERROR)
937                 llapi_err_noerrno(LLAPI_MSG_ERROR,
938                                   "can't find fs root for '%s': %d",
939                                   (want & WANT_PATH) ? fsname : path, rc);
940         return rc;
941 }
942
943 /*
944  * search lustre mounts
945  *
946  * Calling this function will return to the user the mount point, mntdir, and
947  * the file system name, fsname, if the user passed a buffer to this routine.
948  *
949  * The user inputs are pathname and index. If the pathname is supplied then
950  * the value of the index will be ignored. The pathname will return data if
951  * the pathname is located on a lustre mount. Index is used to pick which
952  * mount point you want in the case of multiple mounted lustre file systems.
953  * See function lfs_osts in lfs.c for an example of the index use.
954  */
955 int llapi_search_mounts(const char *pathname, int index, char *mntdir,
956                         char *fsname)
957 {
958         int want = WANT_PATH, idx = -1;
959
960         if (!pathname || pathname[0] == '\0') {
961                 want |= WANT_INDEX;
962                 idx = index;
963         } else
964                 strcpy(mntdir, pathname);
965
966         if (fsname)
967                 want |= WANT_FSNAME;
968         return get_root_path(want, fsname, NULL, mntdir, idx);
969 }
970
971 /* Given a path, find the corresponding Lustre fsname */
972 int llapi_search_fsname(const char *pathname, char *fsname)
973 {
974         char *path;
975         int rc;
976
977         path = realpath(pathname, NULL);
978         if (path == NULL) {
979                 char buf[PATH_MAX], *ptr;
980
981                 buf[0] = '\0';
982                 if (pathname[0] != '/') {
983                         /* Need an absolute path, but realpath() only works for
984                          * pathnames that actually exist.  We go through the
985                          * extra hurdle of dirname(getcwd() + pathname) in
986                          * case the relative pathname contains ".." in it. */
987                         if (getcwd(buf, sizeof(buf) - 2) == NULL)
988                                 return -errno;
989                         rc = strlcat(buf, "/", sizeof(buf));
990                         if (rc >= sizeof(buf))
991                                 return -E2BIG;
992                 }
993                 rc = strlcat(buf, pathname, sizeof(buf));
994                 if (rc >= sizeof(buf))
995                         return -E2BIG;
996                 path = realpath(buf, NULL);
997                 if (path == NULL) {
998                         ptr = strrchr(buf, '/');
999                         if (ptr == NULL)
1000                                 return -ENOENT;
1001                         *ptr = '\0';
1002                         path = realpath(buf, NULL);
1003                         if (path == NULL) {
1004                                 rc = -errno;
1005                                 llapi_error(LLAPI_MSG_ERROR, rc,
1006                                             "pathname '%s' cannot expand",
1007                                             pathname);
1008                                 return rc;
1009                         }
1010                 }
1011         }
1012         rc = get_root_path(WANT_FSNAME | WANT_ERROR, fsname, NULL, path, -1);
1013         free(path);
1014         return rc;
1015 }
1016
1017 int llapi_search_rootpath(char *pathname, const char *fsname)
1018 {
1019         return get_root_path(WANT_PATH, (char *)fsname, NULL, pathname, -1);
1020 }
1021
1022 int llapi_getname(const char *path, char *buf, size_t size)
1023 {
1024         struct obd_uuid uuid_buf;
1025         char *uuid = uuid_buf.uuid;
1026         int rc, nr;
1027
1028         memset(&uuid_buf, 0, sizeof(uuid_buf));
1029         rc = llapi_file_get_lov_uuid(path, &uuid_buf);
1030         if (rc)
1031                 return rc;
1032
1033         /* We want to turn lustre-clilov-ffff88002738bc00 into
1034          * lustre-ffff88002738bc00. */
1035
1036         nr = snprintf(buf, size, "%.*s-%s",
1037                       (int) (strlen(uuid) - 24), uuid,
1038                       uuid + strlen(uuid) - 16);
1039
1040         if (nr >= size)
1041                 rc = -ENAMETOOLONG;
1042
1043         return rc;
1044 }
1045
1046 /**
1047  * Get the list of pool members.
1048  * \param poolname    string of format \<fsname\>.\<poolname\>
1049  * \param members     caller-allocated array of char*
1050  * \param list_size   size of the members array
1051  * \param buffer      caller-allocated buffer for storing OST names
1052  * \param buffer_size size of the buffer
1053  *
1054  * \return number of members retrieved for this pool
1055  * \retval -error failure
1056  */
1057 int llapi_get_poolmembers(const char *poolname, char **members,
1058                           int list_size, char *buffer, int buffer_size)
1059 {
1060         char fsname[PATH_MAX];
1061         char *pool, *tmp;
1062         glob_t pathname;
1063         char buf[PATH_MAX];
1064         FILE *fd;
1065         int rc = 0;
1066         int nb_entries = 0;
1067         int used = 0;
1068
1069         /* name is FSNAME.POOLNAME */
1070         if (strlen(poolname) >= sizeof(fsname))
1071                 return -EOVERFLOW;
1072         strlcpy(fsname, poolname, sizeof(fsname));
1073         pool = strchr(fsname, '.');
1074         if (pool == NULL)
1075                 return -EINVAL;
1076
1077         *pool = '\0';
1078         pool++;
1079
1080         rc = poolpath(&pathname, fsname, NULL);
1081         if (rc != 0) {
1082                 llapi_error(LLAPI_MSG_ERROR, rc,
1083                             "Lustre filesystem '%s' not found",
1084                             fsname);
1085                 return rc;
1086         }
1087
1088         llapi_printf(LLAPI_MSG_NORMAL, "Pool: %s.%s\n", fsname, pool);
1089         rc = snprintf(buf, sizeof(buf), "%s/%s", pathname.gl_pathv[0], pool);
1090         cfs_free_param_data(&pathname);
1091         if (rc >= sizeof(buf))
1092                 return -EOVERFLOW;
1093         fd = fopen(buf, "r");
1094         if (fd == NULL) {
1095                 rc = -errno;
1096                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot open %s", buf);
1097                 return rc;
1098         }
1099
1100         rc = 0;
1101         while (fgets(buf, sizeof(buf), fd) != NULL) {
1102                 if (nb_entries >= list_size) {
1103                         rc = -EOVERFLOW;
1104                         break;
1105                 }
1106                 buf[sizeof(buf) - 1] = '\0';
1107                 /* remove '\n' */
1108                 tmp = strchr(buf, '\n');
1109                 if (tmp != NULL)
1110                         *tmp='\0';
1111                 if (used + strlen(buf) + 1 > buffer_size) {
1112                         rc = -EOVERFLOW;
1113                         break;
1114                 }
1115
1116                 strcpy(buffer + used, buf);
1117                 members[nb_entries] = buffer + used;
1118                 used += strlen(buf) + 1;
1119                 nb_entries++;
1120                 rc = nb_entries;
1121         }
1122
1123         fclose(fd);
1124         return rc;
1125 }
1126
1127 /**
1128  * Get the list of pools in a filesystem.
1129  * \param name        filesystem name or path
1130  * \param poollist    caller-allocated array of char*
1131  * \param list_size   size of the poollist array
1132  * \param buffer      caller-allocated buffer for storing pool names
1133  * \param buffer_size size of the buffer
1134  *
1135  * \return number of pools retrieved for this filesystem
1136  * \retval -error failure
1137  */
1138 int llapi_get_poollist(const char *name, char **poollist, int list_size,
1139                        char *buffer, int buffer_size)
1140 {
1141         char rname[PATH_MAX];
1142         glob_t pathname;
1143         char *fsname;
1144         char *ptr;
1145         DIR *dir;
1146         struct dirent pool;
1147         struct dirent *cookie = NULL;
1148         int rc = 0;
1149         unsigned int nb_entries = 0;
1150         unsigned int used = 0;
1151         unsigned int i;
1152
1153         /* initialize output array */
1154         for (i = 0; i < list_size; i++)
1155                 poollist[i] = NULL;
1156
1157         /* is name a pathname ? */
1158         ptr = strchr(name, '/');
1159         if (ptr != NULL) {
1160                 /* only absolute pathname is supported */
1161                 if (*name != '/')
1162                         return -EINVAL;
1163
1164                 if (!realpath(name, rname)) {
1165                         rc = -errno;
1166                         llapi_error(LLAPI_MSG_ERROR, rc, "invalid path '%s'",
1167                                     name);
1168                         return rc;
1169                 }
1170
1171                 fsname = strdup(rname);
1172                 if (!fsname)
1173                         return -ENOMEM;
1174
1175                 rc = poolpath(&pathname, NULL, rname);
1176         } else {
1177                 /* name is FSNAME */
1178                 fsname = strdup(name);
1179                 if (!fsname)
1180                         return -ENOMEM;
1181                 rc = poolpath(&pathname, fsname, NULL);
1182         }
1183         if (rc != 0) {
1184                 llapi_error(LLAPI_MSG_ERROR, rc,
1185                             "Lustre filesystem '%s' not found", name);
1186                 goto free_path;
1187         }
1188
1189         llapi_printf(LLAPI_MSG_NORMAL, "Pools from %s:\n", fsname);
1190         dir = opendir(pathname.gl_pathv[0]);
1191         if (dir == NULL) {
1192                 rc = -errno;
1193                 llapi_error(LLAPI_MSG_ERROR, rc,
1194                             "Could not open pool list for '%s'",
1195                             name);
1196                 goto free_path;
1197         }
1198
1199         while(1) {
1200                 rc = readdir_r(dir, &pool, &cookie);
1201                 if (rc != 0) {
1202                         rc = -errno;
1203                         llapi_error(LLAPI_MSG_ERROR, rc,
1204                                     "Error reading pool list for '%s'", name);
1205                         goto free_path;
1206                 } else if ((rc == 0) && (cookie == NULL)) {
1207                         /* end of directory */
1208                         break;
1209                 }
1210
1211                 /* ignore . and .. */
1212                 if (!strcmp(pool.d_name, ".") || !strcmp(pool.d_name, ".."))
1213                         continue;
1214
1215                 /* check output bounds */
1216                 if (nb_entries >= list_size) {
1217                         rc = -EOVERFLOW;
1218                         goto free_dir;
1219                 }
1220
1221                 /* +2 for '.' and final '\0' */
1222                 if (used + strlen(pool.d_name) + strlen(fsname) + 2
1223                     > buffer_size) {
1224                         rc = -EOVERFLOW;
1225                         goto free_dir;
1226                 }
1227
1228                 sprintf(buffer + used, "%s.%s", fsname, pool.d_name);
1229                 poollist[nb_entries] = buffer + used;
1230                 used += strlen(pool.d_name) + strlen(fsname) + 2;
1231                 nb_entries++;
1232         }
1233
1234 free_dir:
1235         closedir(dir);
1236 free_path:
1237         cfs_free_param_data(&pathname);
1238         if (fsname)
1239                 free(fsname);
1240         return rc != 0 ? rc : nb_entries;
1241 }
1242
1243 /* wrapper for lfs.c and obd.c */
1244 int llapi_poollist(const char *name)
1245 {
1246         /* list of pool names (assume that pool count is smaller
1247            than OST count) */
1248         char **list, *buffer = NULL, *fsname = (char *)name;
1249         char *poolname = NULL, *tmp = NULL, data[16];
1250         enum param_filter type = FILTER_BY_PATH;
1251         int obdcount, bufsize, rc, nb, i;
1252
1253         if (name == NULL)
1254                 return -EINVAL;
1255
1256         if (name[0] != '/') {
1257                 fsname = strdup(name);
1258                 if (fsname == NULL)
1259                         return -ENOMEM;
1260
1261                 poolname = strchr(fsname, '.');
1262                 if (poolname)
1263                         *poolname = '\0';
1264                 type = FILTER_BY_FS_NAME;
1265         }
1266
1267         rc = get_lustre_param_value("lov", fsname, type, "numobd",
1268                                     data, sizeof(data));
1269         if (rc < 0)
1270                 goto err;
1271         obdcount = atoi(data);
1272
1273         /* Allocate space for each fsname-OST0000_UUID, 1 per OST,
1274          * and also an array to store the pointers for all that
1275          * allocated space. */
1276 retry_get_pools:
1277         bufsize = sizeof(struct obd_uuid) * obdcount;
1278         buffer = realloc(tmp, bufsize + sizeof(*list) * obdcount);
1279         if (buffer == NULL) {
1280                 rc = -ENOMEM;
1281                 goto err;
1282         }
1283         list = (char **) (buffer + bufsize);
1284
1285         if (!poolname) {
1286                 /* name is a path or fsname */
1287                 nb = llapi_get_poollist(name, list, obdcount,
1288                                         buffer, bufsize);
1289         } else {
1290                 /* name is a pool name (<fsname>.<poolname>) */
1291                 nb = llapi_get_poolmembers(name, list, obdcount,
1292                                            buffer, bufsize);
1293         }
1294
1295         if (nb == -EOVERFLOW) {
1296                 obdcount *= 2;
1297                 tmp = buffer;
1298                 goto retry_get_pools;
1299         }
1300
1301         for (i = 0; i < nb; i++)
1302                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", list[i]);
1303         rc = (nb < 0 ? nb : 0);
1304 err:
1305         if (buffer)
1306                 free(buffer);
1307         if (fsname != NULL && type == FILTER_BY_FS_NAME)
1308                 free(fsname);
1309         return rc;
1310 }
1311
1312 typedef int (semantic_func_t)(char *path, DIR *parent, DIR **d,
1313                               void *data, struct dirent64 *de);
1314
1315 #define OBD_NOT_FOUND           (-1)
1316
1317 static int common_param_init(struct find_param *param, char *path)
1318 {
1319         int lum_size = get_mds_md_size(path);
1320
1321         if (lum_size < PATH_MAX + 1)
1322                 lum_size = PATH_MAX + 1;
1323
1324         param->fp_lum_size = lum_size;
1325         param->fp_lmd = calloc(1, sizeof(lstat_t) + param->fp_lum_size);
1326         if (param->fp_lmd == NULL) {
1327                 llapi_error(LLAPI_MSG_ERROR, -ENOMEM,
1328                             "error: allocation of %zu bytes for ioctl",
1329                             sizeof(lstat_t) + param->fp_lum_size);
1330                 return -ENOMEM;
1331         }
1332
1333         param->fp_lmv_stripe_count = 256;
1334         param->fp_lmv_md = calloc(1,
1335                                   lmv_user_md_size(param->fp_lmv_stripe_count,
1336                                                    LMV_MAGIC_V1));
1337         if (param->fp_lmv_md == NULL) {
1338                 llapi_error(LLAPI_MSG_ERROR, -ENOMEM,
1339                             "error: allocation of %d bytes for ioctl",
1340                             lmv_user_md_size(param->fp_lmv_stripe_count,
1341                                              LMV_MAGIC_V1));
1342                 return -ENOMEM;
1343         }
1344
1345         param->fp_got_uuids = 0;
1346         param->fp_obd_indexes = NULL;
1347         param->fp_obd_index = OBD_NOT_FOUND;
1348         if (!param->fp_migrate)
1349                 param->fp_mdt_index = OBD_NOT_FOUND;
1350         return 0;
1351 }
1352
1353 static void find_param_fini(struct find_param *param)
1354 {
1355         if (param->fp_obd_indexes)
1356                 free(param->fp_obd_indexes);
1357
1358         if (param->fp_lmd)
1359                 free(param->fp_lmd);
1360
1361         if (param->fp_lmv_md)
1362                 free(param->fp_lmv_md);
1363 }
1364
1365 static int cb_common_fini(char *path, DIR *parent, DIR **dirp, void *data,
1366                           struct dirent64 *de)
1367 {
1368         struct find_param *param = data;
1369         param->fp_depth--;
1370
1371         return 0;
1372 }
1373
1374 /* set errno upon failure */
1375 static DIR *opendir_parent(const char *path)
1376 {
1377         char *path_copy;
1378         char *parent_path;
1379         DIR *parent;
1380
1381         path_copy = strdup(path);
1382         if (path_copy == NULL)
1383                 return NULL;
1384
1385         parent_path = dirname(path_copy);
1386         parent = opendir(parent_path);
1387         free(path_copy);
1388
1389         return parent;
1390 }
1391
1392 static int cb_get_dirstripe(char *path, DIR *d, struct find_param *param)
1393 {
1394         int ret;
1395
1396 again:
1397         param->fp_lmv_md->lum_stripe_count = param->fp_lmv_stripe_count;
1398         if (param->fp_get_default_lmv)
1399                 param->fp_lmv_md->lum_magic = LMV_USER_MAGIC;
1400         else
1401                 param->fp_lmv_md->lum_magic = LMV_MAGIC_V1;
1402
1403         ret = ioctl(dirfd(d), LL_IOC_LMV_GETSTRIPE, param->fp_lmv_md);
1404         if (errno == E2BIG && ret != 0) {
1405                 int stripe_count;
1406                 int lmv_size;
1407
1408                 stripe_count = (__u32)param->fp_lmv_md->lum_stripe_count;
1409                 if (stripe_count <= param->fp_lmv_stripe_count)
1410                         return ret;
1411
1412                 free(param->fp_lmv_md);
1413                 param->fp_lmv_stripe_count = stripe_count;
1414                 lmv_size = lmv_user_md_size(stripe_count, LMV_MAGIC_V1);
1415                 param->fp_lmv_md = malloc(lmv_size);
1416                 if (param->fp_lmv_md == NULL) {
1417                         llapi_error(LLAPI_MSG_ERROR, -ENOMEM,
1418                                     "error: allocation of %d bytes for ioctl",
1419                                     lmv_user_md_size(param->fp_lmv_stripe_count,
1420                                                      LMV_MAGIC_V1));
1421                         return -ENOMEM;
1422                 }
1423                 goto again;
1424         }
1425         return ret;
1426 }
1427
1428 static int get_lmd_info(char *path, DIR *parent, DIR *dir,
1429                  struct lov_user_mds_data *lmd, int lumlen)
1430 {
1431         lstat_t *st = &lmd->lmd_st;
1432         int ret = 0;
1433
1434         if (parent == NULL && dir == NULL)
1435                 return -EINVAL;
1436
1437         if (dir) {
1438                 ret = ioctl(dirfd(dir), LL_IOC_MDC_GETINFO, (void *)lmd);
1439         } else if (parent) {
1440                 char *fname = strrchr(path, '/');
1441
1442                 /* To avoid opening, locking, and closing each file on the
1443                  * client if that is not needed. The GETFILEINFO ioctl can
1444                  * be done on the patent dir with a single open for all
1445                  * files in that directory, and it also doesn't pollute the
1446                  * client dcache with millions of dentries when traversing
1447                  * a large filesystem.  */
1448                 fname = (fname == NULL ? path : fname + 1);
1449                 /* retrieve needed file info */
1450                 strlcpy((char *)lmd, fname, lumlen);
1451                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO, (void *)lmd);
1452         }
1453
1454         if (ret) {
1455                 if (errno == ENOTTY) {
1456                         /* ioctl is not supported, it is not a lustre fs.
1457                          * Do the regular lstat(2) instead. */
1458                         ret = lstat_f(path, st);
1459                         if (ret) {
1460                                 ret = -errno;
1461                                 llapi_error(LLAPI_MSG_ERROR, ret,
1462                                             "error: %s: lstat failed for %s",
1463                                             __func__, path);
1464                         }
1465                 } else if (errno == ENOENT) {
1466                         ret = -errno;
1467                         llapi_error(LLAPI_MSG_WARN, ret,
1468                                     "warning: %s: %s does not exist",
1469                                     __func__, path);
1470                 } else if (errno != EISDIR) {
1471                         ret = -errno;
1472                         llapi_error(LLAPI_MSG_ERROR, ret,
1473                                     "%s ioctl failed for %s.",
1474                                     dir ? "LL_IOC_MDC_GETINFO" :
1475                                     "IOC_MDC_GETFILEINFO", path);
1476                 } else {
1477                         ret = -errno;
1478                         llapi_error(LLAPI_MSG_ERROR, ret,
1479                                  "error: %s: IOC_MDC_GETFILEINFO failed for %s",
1480                                    __func__, path);
1481                 }
1482         }
1483         return ret;
1484 }
1485
1486 static int llapi_semantic_traverse(char *path, int size, DIR *parent,
1487                                    semantic_func_t sem_init,
1488                                    semantic_func_t sem_fini, void *data,
1489                                    struct dirent64 *de)
1490 {
1491         struct find_param *param = (struct find_param *)data;
1492         struct dirent64 *dent;
1493         int len, ret;
1494         DIR *d, *p = NULL;
1495
1496         ret = 0;
1497         len = strlen(path);
1498
1499         d = opendir(path);
1500         if (!d && errno != ENOTDIR) {
1501                 ret = -errno;
1502                 llapi_error(LLAPI_MSG_ERROR, ret, "%s: Failed to open '%s'",
1503                             __func__, path);
1504                 return ret;
1505         } else if (!d && !parent) {
1506                 /* ENOTDIR. Open the parent dir. */
1507                 p = opendir_parent(path);
1508                 if (!p) {
1509                         ret = -errno;
1510                         goto out;
1511                 }
1512         }
1513
1514         if (sem_init && (ret = sem_init(path, parent ?: p, &d, data, de)))
1515                 goto err;
1516
1517         if (d == NULL)
1518                 goto out;
1519
1520         while ((dent = readdir64(d)) != NULL) {
1521                 int rc;
1522
1523                 if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
1524                         continue;
1525
1526                 /* Don't traverse .lustre directory */
1527                 if (!(strcmp(dent->d_name, dot_lustre_name)))
1528                         continue;
1529
1530                 path[len] = 0;
1531                 if ((len + dent->d_reclen + 2) > size) {
1532                         llapi_err_noerrno(LLAPI_MSG_ERROR,
1533                                           "error: %s: string buffer is too small",
1534                                           __func__);
1535                         break;
1536                 }
1537                 strcat(path, "/");
1538                 strcat(path, dent->d_name);
1539
1540                 if (dent->d_type == DT_UNKNOWN) {
1541                         lstat_t *st = &param->fp_lmd->lmd_st;
1542
1543                         rc = get_lmd_info(path, d, NULL, param->fp_lmd,
1544                                            param->fp_lum_size);
1545                         if (rc == 0)
1546                                 dent->d_type = IFTODT(st->st_mode);
1547                         else if (ret == 0)
1548                                 ret = rc;
1549
1550                         if (rc == -ENOENT)
1551                                 continue;
1552                 }
1553                 switch (dent->d_type) {
1554                 case DT_UNKNOWN:
1555                         llapi_err_noerrno(LLAPI_MSG_ERROR,
1556                                           "error: %s: '%s' is UNKNOWN type %d",
1557                                           __func__, dent->d_name, dent->d_type);
1558                         break;
1559                 case DT_DIR:
1560                         rc = llapi_semantic_traverse(path, size, d, sem_init,
1561                                                       sem_fini, data, dent);
1562                         if (rc != 0 && ret == 0)
1563                                 ret = rc;
1564                         break;
1565                 default:
1566                         rc = 0;
1567                         if (sem_init) {
1568                                 rc = sem_init(path, d, NULL, data, dent);
1569                                 if (rc < 0 && ret == 0)
1570                                         ret = rc;
1571                         }
1572                         if (sem_fini && rc == 0)
1573                                 sem_fini(path, d, NULL, data, dent);
1574                 }
1575         }
1576
1577 out:
1578         path[len] = 0;
1579
1580         if (sem_fini)
1581                 sem_fini(path, parent, &d, data, de);
1582 err:
1583         if (d)
1584                 closedir(d);
1585         if (p)
1586                 closedir(p);
1587         return ret;
1588 }
1589
1590 static int param_callback(char *path, semantic_func_t sem_init,
1591                           semantic_func_t sem_fini, struct find_param *param)
1592 {
1593         int ret, len = strlen(path);
1594         char *buf;
1595
1596         if (len > PATH_MAX) {
1597                 ret = -EINVAL;
1598                 llapi_error(LLAPI_MSG_ERROR, ret,
1599                             "Path name '%s' is too long", path);
1600                 return ret;
1601         }
1602
1603         buf = (char *)malloc(PATH_MAX + 1);
1604         if (!buf)
1605                 return -ENOMEM;
1606
1607         strlcpy(buf, path, PATH_MAX + 1);
1608         ret = common_param_init(param, buf);
1609         if (ret)
1610                 goto out;
1611
1612         param->fp_depth = 0;
1613
1614         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, sem_init,
1615                                       sem_fini, param, NULL);
1616 out:
1617         find_param_fini(param);
1618         free(buf);
1619         return ret < 0 ? ret : 0;
1620 }
1621
1622 int llapi_file_fget_lov_uuid(int fd, struct obd_uuid *lov_name)
1623 {
1624         int rc = ioctl(fd, OBD_IOC_GETNAME, lov_name);
1625         if (rc) {
1626                 rc = -errno;
1627                 llapi_error(LLAPI_MSG_ERROR, rc, "error: can't get lov name.");
1628         }
1629         return rc;
1630 }
1631
1632 int llapi_file_fget_lmv_uuid(int fd, struct obd_uuid *lov_name)
1633 {
1634         int rc = ioctl(fd, OBD_IOC_GETMDNAME, lov_name);
1635         if (rc) {
1636                 rc = -errno;
1637                 llapi_error(LLAPI_MSG_ERROR, rc, "error: can't get lmv name.");
1638         }
1639         return rc;
1640 }
1641
1642 int llapi_file_get_lov_uuid(const char *path, struct obd_uuid *lov_uuid)
1643 {
1644         int fd, rc;
1645
1646         fd = open(path, O_RDONLY | O_NONBLOCK);
1647         if (fd < 0) {
1648                 rc = -errno;
1649                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s", path);
1650                 return rc;
1651         }
1652
1653         rc = llapi_file_fget_lov_uuid(fd, lov_uuid);
1654
1655         close(fd);
1656         return rc;
1657 }
1658
1659 int llapi_file_get_lmv_uuid(const char *path, struct obd_uuid *lov_uuid)
1660 {
1661         int fd, rc;
1662
1663         fd = open(path, O_RDONLY | O_NONBLOCK);
1664         if (fd < 0) {
1665                 rc = -errno;
1666                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s", path);
1667                 return rc;
1668         }
1669
1670         rc = llapi_file_fget_lmv_uuid(fd, lov_uuid);
1671
1672         close(fd);
1673         return rc;
1674 }
1675
1676 enum tgt_type {
1677         LOV_TYPE = 1,
1678         LMV_TYPE
1679 };
1680
1681 /*
1682  * If uuidp is NULL, return the number of available obd uuids.
1683  * If uuidp is non-NULL, then it will return the uuids of the obds. If
1684  * there are more OSTs than allocated to uuidp, then an error is returned with
1685  * the ost_count set to number of available obd uuids.
1686  */
1687 static int llapi_get_target_uuids(int fd, struct obd_uuid *uuidp,
1688                                   int *ost_count, enum tgt_type type)
1689 {
1690         char buf[PATH_MAX], format[32];
1691         int rc = 0, index = 0;
1692         struct obd_uuid name;
1693         glob_t param;
1694         FILE *fp;
1695
1696         /* Get the lov name */
1697         if (type == LOV_TYPE)
1698                 rc = llapi_file_fget_lov_uuid(fd, &name);
1699         else
1700                 rc = llapi_file_fget_lmv_uuid(fd, &name);
1701         if (rc != 0)
1702                 return rc;
1703
1704         /* Now get the ost uuids */
1705         rc = get_lustre_param_path(type == LOV_TYPE ? "lov" : "lmv", name.uuid,
1706                                    FILTER_BY_EXACT, "target_obd", &param);
1707         if (rc != 0)
1708                 return -ENOENT;
1709
1710         fp = fopen(param.gl_pathv[0], "r");
1711         if (fp == NULL) {
1712                 rc = -errno;
1713                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening '%s'",
1714                             param.gl_pathv[0]);
1715                 goto free_param;
1716         }
1717
1718         snprintf(format, sizeof(format),
1719                  "%%d: %%%zus", sizeof(uuidp[0].uuid) - 1);
1720         while (fgets(buf, sizeof(buf), fp) != NULL) {
1721                 if (uuidp && (index < *ost_count)) {
1722                         if (sscanf(buf, format, &index, uuidp[index].uuid) < 2)
1723                                 break;
1724                 }
1725                 index++;
1726         }
1727
1728         fclose(fp);
1729
1730         if (uuidp && (index > *ost_count))
1731                 rc = -EOVERFLOW;
1732
1733         *ost_count = index;
1734 free_param:
1735         cfs_free_param_data(&param);
1736         return rc;
1737 }
1738
1739 int llapi_lov_get_uuids(int fd, struct obd_uuid *uuidp, int *ost_count)
1740 {
1741         return llapi_get_target_uuids(fd, uuidp, ost_count, LOV_TYPE);
1742 }
1743
1744 int llapi_get_obd_count(char *mnt, int *count, int is_mdt)
1745 {
1746         DIR *root;
1747         int rc;
1748
1749         root = opendir(mnt);
1750         if (!root) {
1751                 rc = -errno;
1752                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
1753                 return rc;
1754         }
1755
1756         *count = is_mdt;
1757         rc = ioctl(dirfd(root), LL_IOC_GETOBDCOUNT, count);
1758         if (rc < 0)
1759                 rc = -errno;
1760
1761         closedir(root);
1762         return rc;
1763 }
1764
1765 /* Check if user specified value matches a real uuid.  Ignore _UUID,
1766  * -osc-4ba41334, other trailing gunk in comparison.
1767  * @param real_uuid ends in "_UUID"
1768  * @param search_uuid may or may not end in "_UUID"
1769  */
1770 int llapi_uuid_match(char *real_uuid, char *search_uuid)
1771 {
1772         int cmplen = strlen(real_uuid);
1773         int searchlen = strlen(search_uuid);
1774
1775         if (cmplen > 5 && strcmp(real_uuid + cmplen - 5, "_UUID") == 0)
1776                 cmplen -= 5;
1777         if (searchlen > 5 && strcmp(search_uuid + searchlen - 5, "_UUID") == 0)
1778                 searchlen -= 5;
1779
1780         /* The UUIDs may legitimately be different lengths, if
1781          * the system was upgraded from an older version. */
1782         if (cmplen != searchlen)
1783                 return 0;
1784
1785         return (strncmp(search_uuid, real_uuid, cmplen) == 0);
1786 }
1787
1788 /* Here, param->fp_obd_uuid points to a single obduuid, the index of which is
1789  * returned in param->fp_obd_index */
1790 static int setup_obd_uuid(DIR *dir, char *dname, struct find_param *param)
1791 {
1792         struct obd_uuid obd_uuid;
1793         char buf[PATH_MAX];
1794         glob_t param_data;
1795         char format[32];
1796         int rc = 0;
1797         FILE *fp;
1798
1799         if (param->fp_got_uuids)
1800                 return rc;
1801
1802         /* Get the lov/lmv name */
1803         if (param->fp_get_lmv)
1804                 rc = llapi_file_fget_lmv_uuid(dirfd(dir), &obd_uuid);
1805         else
1806                 rc = llapi_file_fget_lov_uuid(dirfd(dir), &obd_uuid);
1807         if (rc) {
1808                 if (rc != -ENOTTY) {
1809                         llapi_error(LLAPI_MSG_ERROR, rc,
1810                                     "error: can't get %s name: %s",
1811                                     param->fp_get_lmv ? "lmv" : "lov",
1812                                     dname);
1813                 } else {
1814                         rc = 0;
1815                 }
1816                 return rc;
1817         }
1818
1819         param->fp_got_uuids = 1;
1820
1821         /* Now get the ost uuids */
1822         rc = get_lustre_param_path(param->fp_get_lmv ? "lmv" : "lov",
1823                                    obd_uuid.uuid, FILTER_BY_EXACT,
1824                                    "target_obd", &param_data);
1825         if (rc != 0)
1826                 return -ENOENT;
1827
1828         fp = fopen(param_data.gl_pathv[0], "r");
1829         if (fp == NULL) {
1830                 rc = -errno;
1831                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening '%s'",
1832                             param_data.gl_pathv[0]);
1833                 goto free_param;
1834         }
1835
1836         if (!param->fp_obd_uuid && !param->fp_quiet && !param->fp_obds_printed)
1837                 llapi_printf(LLAPI_MSG_NORMAL, "%s:\n",
1838                              param->fp_get_lmv ? "MDTS" : "OBDS");
1839
1840         snprintf(format, sizeof(format),
1841                  "%%d: %%%zus", sizeof(obd_uuid.uuid) - 1);
1842         while (fgets(buf, sizeof(buf), fp) != NULL) {
1843                 int index;
1844
1845                 if (sscanf(buf, format, &index, obd_uuid.uuid) < 2)
1846                         break;
1847
1848                 if (param->fp_obd_uuid) {
1849                         if (llapi_uuid_match(obd_uuid.uuid,
1850                                              param->fp_obd_uuid->uuid)) {
1851                                 param->fp_obd_index = index;
1852                                 break;
1853                         }
1854                 } else if (!param->fp_quiet && !param->fp_obds_printed) {
1855                         /* Print everything */
1856                         llapi_printf(LLAPI_MSG_NORMAL, "%s", buf);
1857                 }
1858         }
1859         param->fp_obds_printed = 1;
1860
1861         fclose(fp);
1862
1863         if (param->fp_obd_uuid && (param->fp_obd_index == OBD_NOT_FOUND)) {
1864                 llapi_err_noerrno(LLAPI_MSG_ERROR,
1865                                   "error: %s: unknown obduuid: %s",
1866                                   __func__, param->fp_obd_uuid->uuid);
1867                 rc = -EINVAL;
1868         }
1869 free_param:
1870         cfs_free_param_data(&param_data);
1871         return rc;
1872 }
1873
1874 /* In this case, param->fp_obd_uuid will be an array of obduuids and
1875  * obd index for all these obduuids will be returned in
1876  * param->fp_obd_indexes */
1877 static int setup_indexes(DIR *dir, char *path, struct obd_uuid *obduuids,
1878                          int num_obds, int **obdindexes, int *obdindex,
1879                          enum tgt_type type)
1880 {
1881         int ret, obdcount, obd_valid = 0, obdnum;
1882         long i;
1883         struct obd_uuid *uuids = NULL;
1884         char buf[16];
1885         int *indexes;
1886
1887         if (type == LOV_TYPE)
1888                 ret = get_param_lov(path, "numobd", buf, sizeof(buf));
1889         else
1890                 ret = get_param_lmv(path, "numobd", buf, sizeof(buf));
1891         if (ret != 0)
1892                 return ret;
1893
1894         obdcount = atoi(buf);
1895         uuids = malloc(obdcount * sizeof(struct obd_uuid));
1896         if (uuids == NULL)
1897                 return -ENOMEM;
1898
1899 retry_get_uuids:
1900         ret = llapi_get_target_uuids(dirfd(dir), uuids, &obdcount, type);
1901         if (ret) {
1902                 if (ret == -EOVERFLOW) {
1903                         struct obd_uuid *uuids_temp;
1904
1905                         uuids_temp = realloc(uuids, obdcount *
1906                                              sizeof(struct obd_uuid));
1907                         if (uuids_temp != NULL) {
1908                                 uuids = uuids_temp;
1909                                 goto retry_get_uuids;
1910                         }
1911                         ret = -ENOMEM;
1912                 }
1913
1914                 llapi_error(LLAPI_MSG_ERROR, ret, "get ost uuid failed");
1915                 goto out_free;
1916         }
1917
1918         indexes = malloc(num_obds * sizeof(*obdindex));
1919         if (indexes == NULL) {
1920                 ret = -ENOMEM;
1921                 goto out_free;
1922         }
1923
1924         for (obdnum = 0; obdnum < num_obds; obdnum++) {
1925                 char *end = NULL;
1926
1927                 /* The user may have specified a simple index */
1928                 i = strtol(obduuids[obdnum].uuid, &end, 0);
1929                 if (end && *end == '\0' && i < obdcount) {
1930                         indexes[obdnum] = i;
1931                         obd_valid++;
1932                 } else {
1933                         for (i = 0; i < obdcount; i++) {
1934                                 if (llapi_uuid_match(uuids[i].uuid,
1935                                                      obduuids[obdnum].uuid)) {
1936                                         indexes[obdnum] = i;
1937                                         obd_valid++;
1938                                         break;
1939                                 }
1940                         }
1941                 }
1942                 if (i >= obdcount) {
1943                         indexes[obdnum] = OBD_NOT_FOUND;
1944                         llapi_err_noerrno(LLAPI_MSG_ERROR,
1945                                           "error: %s: unknown obduuid: %s",
1946                                           __func__, obduuids[obdnum].uuid);
1947                         ret = -EINVAL;
1948                 }
1949         }
1950
1951         if (obd_valid == 0)
1952                 *obdindex = OBD_NOT_FOUND;
1953         else
1954                 *obdindex = obd_valid;
1955
1956         *obdindexes = indexes;
1957 out_free:
1958         if (uuids)
1959                 free(uuids);
1960
1961         return ret;
1962 }
1963
1964 static int setup_target_indexes(DIR *dir, char *path, struct find_param *param)
1965 {
1966         int ret = 0;
1967
1968         if (param->fp_mdt_uuid) {
1969                 ret = setup_indexes(dir, path, param->fp_mdt_uuid,
1970                                     param->fp_num_mdts,
1971                                     &param->fp_mdt_indexes,
1972                                     &param->fp_mdt_index, LMV_TYPE);
1973                 if (ret)
1974                         return ret;
1975         }
1976
1977         if (param->fp_obd_uuid) {
1978                 ret = setup_indexes(dir, path, param->fp_obd_uuid,
1979                                     param->fp_num_obds,
1980                                     &param->fp_obd_indexes,
1981                                     &param->fp_obd_index, LOV_TYPE);
1982                 if (ret)
1983                         return ret;
1984         }
1985
1986         param->fp_got_uuids = 1;
1987
1988         return ret;
1989 }
1990
1991 int llapi_ostlist(char *path, struct find_param *param)
1992 {
1993         DIR *dir;
1994         int ret;
1995
1996         dir = opendir(path);
1997         if (dir == NULL)
1998                 return -errno;
1999
2000         ret = setup_obd_uuid(dir, path, param);
2001         closedir(dir);
2002
2003         return ret;
2004 }
2005
2006 /*
2007  * Tries to determine the default stripe attributes for a given filesystem. The
2008  * filesystem to check should be specified by fsname, or will be determined
2009  * using pathname.
2010  */
2011 static int sattr_get_defaults(const char *const fsname,
2012                               unsigned int *scount,
2013                               unsigned int *ssize,
2014                               unsigned int *soffset)
2015 {
2016         char val[PATH_MAX];
2017         int rc;
2018
2019         if (scount) {
2020                 rc = get_lustre_param_value("lov", fsname, FILTER_BY_FS_NAME,
2021                                             "stripecount", val, sizeof(val));
2022                 if (rc != 0)
2023                         return rc;
2024                 *scount = atoi(val);
2025         }
2026
2027         if (ssize) {
2028                 rc = get_lustre_param_value("lov", fsname, FILTER_BY_FS_NAME,
2029                                             "stripesize", val, sizeof(val));
2030                 if (rc != 0)
2031                         return rc;
2032                 *ssize = atoi(val);
2033         }
2034
2035         if (soffset) {
2036                 rc = get_lustre_param_value("lov", fsname, FILTER_BY_FS_NAME,
2037                                             "stripeoffset", val, sizeof(val));
2038                 if (rc != 0)
2039                         return rc;
2040                 *soffset = atoi(val);
2041         }
2042
2043         return 0;
2044 }
2045
2046 /*
2047  * Tries to gather the default stripe attributes for a given filesystem. If
2048  * the attributes can be determined, they are cached for easy retreival the
2049  * next time they are needed. Only a single filesystem's attributes are
2050  * cached at a time.
2051  */
2052 static int sattr_cache_get_defaults(const char *const fsname,
2053                                     const char *const pathname,
2054                                     unsigned int *scount,
2055                                     unsigned int *ssize,
2056                                     unsigned int *soffset)
2057 {
2058         static struct {
2059                 char fsname[PATH_MAX + 1];
2060                 unsigned int stripecount;
2061                 unsigned int stripesize;
2062                 unsigned int stripeoffset;
2063         } cache = {
2064                 .fsname = {'\0'}
2065         };
2066
2067         int rc;
2068         char fsname_buf[PATH_MAX + 1];
2069         unsigned int tmp[3];
2070
2071         if (fsname == NULL) {
2072                 rc = llapi_search_fsname(pathname, fsname_buf);
2073                 if (rc)
2074                         return rc;
2075         } else {
2076                 strlcpy(fsname_buf, fsname, sizeof(fsname_buf));
2077         }
2078
2079         if (strncmp(fsname_buf, cache.fsname, sizeof(fsname_buf) - 1) != 0) {
2080                 /*
2081                  * Ensure all 3 sattrs (count, size, and offset) are
2082                  * successfully retrieved and stored in tmp before writing to
2083                  * cache.
2084                  */
2085                 rc = sattr_get_defaults(fsname_buf, &tmp[0], &tmp[1], &tmp[2]);
2086                 if (rc != 0)
2087                         return rc;
2088
2089                 cache.stripecount = tmp[0];
2090                 cache.stripesize = tmp[1];
2091                 cache.stripeoffset = tmp[2];
2092                 strlcpy(cache.fsname, fsname_buf, sizeof(cache.fsname));
2093         }
2094
2095         if (scount)
2096                 *scount = cache.stripecount;
2097         if (ssize)
2098                 *ssize = cache.stripesize;
2099         if (soffset)
2100                 *soffset = cache.stripeoffset;
2101
2102         return 0;
2103 }
2104
2105 static void lov_dump_user_lmm_header(struct lov_user_md *lum, char *path,
2106                                      struct lov_user_ost_data_v1 *objects,
2107                                      int is_dir, int verbose, int depth,
2108                                      int raw, char *pool_name)
2109 {
2110         char *prefix = is_dir ? "" : "lmm_";
2111         char *separator = "";
2112         int rc;
2113
2114         if (is_dir && lmm_oi_seq(&lum->lmm_oi) == FID_SEQ_LOV_DEFAULT) {
2115                 lmm_oi_set_seq(&lum->lmm_oi, 0);
2116                 if (verbose & VERBOSE_DETAIL)
2117                         llapi_printf(LLAPI_MSG_NORMAL, "(Default) ");
2118         }
2119
2120         if (depth && path && ((verbose != VERBOSE_OBJID) || !is_dir))
2121                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
2122
2123         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
2124                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_magic:          0x%08X\n",
2125                              lum->lmm_magic);
2126                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_seq:            %#jx\n",
2127                              (uintmax_t)lmm_oi_seq(&lum->lmm_oi));
2128                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_id:      %#jx\n",
2129                              (uintmax_t)lmm_oi_id(&lum->lmm_oi));
2130         }
2131         if ((verbose & (VERBOSE_DETAIL | VERBOSE_DFID)) && !is_dir) {
2132                 if (verbose & ~VERBOSE_DFID)
2133                         llapi_printf(LLAPI_MSG_NORMAL, "lmm_fid:            ");
2134                 /* This needs a bit of hand-holding since old 1.x lmm_oi
2135                  * have { oi.oi_id = mds_inum, oi.oi_seq = 0 } and 2.x lmm_oi
2136                  * have { oi.oi_id = mds_oid, oi.oi_seq = mds_seq } instead of
2137                  * a real FID.  Ideally the 2.x code would have stored this
2138                  * like a FID with { oi_id = mds_seq, oi_seq = mds_oid } so the
2139                  * ostid union lu_fid { f_seq = mds_seq, f_oid = mds_oid }
2140                  * worked properly (especially since IGIF FIDs use mds_inum as
2141                  * the FID SEQ), but unfortunately that didn't happen.
2142                  *
2143                  * Print it to look like an IGIF FID, even though the fields
2144                  * are reversed on disk, so that it makes sense to userspace.
2145                  *
2146                  * Don't use ostid_id() and ostid_seq(), since they assume the
2147                  * oi_fid fields are in the right order.  This is why there are
2148                  * separate lmm_oi_seq() and lmm_oi_id() routines for this.
2149                  *
2150                  * For newer layout types hopefully this will be a real FID. */
2151                 llapi_printf(LLAPI_MSG_NORMAL, DFID"\n",
2152                              lmm_oi_seq(&lum->lmm_oi) == 0 ?
2153                                 lmm_oi_id(&lum->lmm_oi) :
2154                                 lmm_oi_seq(&lum->lmm_oi),
2155                              lmm_oi_seq(&lum->lmm_oi) == 0 ?
2156                                 0 : (__u32)lmm_oi_id(&lum->lmm_oi),
2157                              (__u32)(lmm_oi_id(&lum->lmm_oi) >> 32));
2158         }
2159
2160         if (verbose & VERBOSE_COUNT) {
2161                 if (verbose & ~VERBOSE_COUNT)
2162                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_count:   ",
2163                                      prefix);
2164                 if (is_dir) {
2165                         if (!raw && lum->lmm_stripe_count == 0) {
2166                                 unsigned int scount;
2167                                 rc = sattr_cache_get_defaults(NULL, path,
2168                                                               &scount, NULL,
2169                                                               NULL);
2170                                 if (rc == 0)
2171                                         llapi_printf(LLAPI_MSG_NORMAL, "%d",
2172                                                      scount);
2173                                 else
2174                                         llapi_error(LLAPI_MSG_ERROR, rc,
2175                                                     "Cannot determine default"
2176                                                     " stripe count.");
2177                         } else {
2178                                 llapi_printf(LLAPI_MSG_NORMAL, "%d",
2179                                              lum->lmm_stripe_count ==
2180                                              (typeof(lum->lmm_stripe_count))(-1)
2181                                              ? -1 : lum->lmm_stripe_count);
2182                         }
2183                 } else {
2184                         llapi_printf(LLAPI_MSG_NORMAL, "%hd",
2185                                      (__s16)lum->lmm_stripe_count);
2186                 }
2187                 separator = is_dir ? " " : "\n";
2188         }
2189
2190         if (verbose & VERBOSE_SIZE) {
2191                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2192                 if (verbose & ~VERBOSE_SIZE)
2193                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_size:    ",
2194                                      prefix);
2195                 if (is_dir && !raw && lum->lmm_stripe_size == 0) {
2196                         unsigned int ssize;
2197                         rc = sattr_cache_get_defaults(NULL, path, NULL, &ssize,
2198                                                       NULL);
2199                         if (rc == 0)
2200                                 llapi_printf(LLAPI_MSG_NORMAL, "%u", ssize);
2201                         else
2202                                 llapi_error(LLAPI_MSG_ERROR, rc,
2203                                             "Cannot determine default"
2204                                             " stripe size.");
2205                 } else {
2206                         llapi_printf(LLAPI_MSG_NORMAL, "%u",
2207                                      lum->lmm_stripe_size);
2208                 }
2209                 separator = is_dir ? " " : "\n";
2210         }
2211
2212         if ((verbose & VERBOSE_LAYOUT) && !is_dir) {
2213                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2214                 if (verbose & ~VERBOSE_LAYOUT)
2215                         llapi_printf(LLAPI_MSG_NORMAL, "%spattern:        ",
2216                                      prefix);
2217                 llapi_printf(LLAPI_MSG_NORMAL, "%.x", lum->lmm_pattern);
2218                 separator = "\n";
2219         }
2220
2221         if ((verbose & VERBOSE_GENERATION) && !is_dir) {
2222                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2223                 if (verbose & ~VERBOSE_GENERATION)
2224                         llapi_printf(LLAPI_MSG_NORMAL, "%slayout_gen:     ",
2225                                      prefix);
2226                 llapi_printf(LLAPI_MSG_NORMAL, "%u",
2227                              (int)lum->lmm_layout_gen);
2228                 separator = "\n";
2229         }
2230
2231         if (verbose & VERBOSE_OFFSET) {
2232                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2233                 if (verbose & ~VERBOSE_OFFSET)
2234                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_offset:  ",
2235                                      prefix);
2236                 if (is_dir)
2237                         llapi_printf(LLAPI_MSG_NORMAL, "%d",
2238                                      lum->lmm_stripe_offset ==
2239                                      (typeof(lum->lmm_stripe_offset))(-1) ? -1 :
2240                                      lum->lmm_stripe_offset);
2241                 else
2242                         llapi_printf(LLAPI_MSG_NORMAL, "%u",
2243                                      objects[0].l_ost_idx);
2244                 separator = is_dir ? " " : "\n";
2245         }
2246
2247         if ((verbose & VERBOSE_POOL) && (pool_name != NULL)) {
2248                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2249                 if (verbose & ~VERBOSE_POOL)
2250                         llapi_printf(LLAPI_MSG_NORMAL, "%spool:           ",
2251                                      prefix);
2252                 llapi_printf(LLAPI_MSG_NORMAL, "%s", pool_name);
2253         }
2254
2255         if (!is_dir || (is_dir && (verbose != VERBOSE_OBJID)))
2256                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
2257 }
2258
2259 void lov_dump_user_lmm_v1v3(struct lov_user_md *lum, char *pool_name,
2260                             struct lov_user_ost_data_v1 *objects,
2261                             char *path, int is_dir, int obdindex,
2262                             int depth, int header, int raw)
2263 {
2264         int i, obdstripe = (obdindex != OBD_NOT_FOUND) ? 0 : 1;
2265
2266         if (!obdstripe) {
2267                 for (i = 0; !is_dir && i < lum->lmm_stripe_count; i++) {
2268                         if (obdindex == objects[i].l_ost_idx) {
2269                                 obdstripe = 1;
2270                                 break;
2271                         }
2272                 }
2273         }
2274
2275         if (obdstripe == 1)
2276                 lov_dump_user_lmm_header(lum, path, objects, is_dir, header,
2277                                          depth, raw, pool_name);
2278
2279         if (!is_dir && (header & VERBOSE_OBJID) &&
2280             !(lum->lmm_pattern & LOV_PATTERN_F_RELEASED)) {
2281                 if (obdstripe == 1)
2282                         llapi_printf(LLAPI_MSG_NORMAL,
2283                                    "\tobdidx\t\t objid\t\t objid\t\t group\n");
2284
2285                 for (i = 0; i < lum->lmm_stripe_count; i++) {
2286                         int idx = objects[i].l_ost_idx;
2287                         long long oid = ostid_id(&objects[i].l_ost_oi);
2288                         long long gr = ostid_seq(&objects[i].l_ost_oi);
2289                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx)) {
2290                                 char fmt[48];
2291                                 sprintf(fmt, "%s%s%s\n",
2292                                         "\t%6u\t%14llu\t%#13llx\t",
2293                                         (fid_seq_is_rsvd(gr) ||
2294                                          fid_seq_is_mdt0(gr)) ?
2295                                          "%14llu" : "%#14llx", "%s");
2296                                 llapi_printf(LLAPI_MSG_NORMAL, fmt, idx, oid,
2297                                              oid, gr,
2298                                              obdindex == idx ? " *" : "");
2299                         }
2300
2301                 }
2302                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
2303         }
2304 }
2305
2306 void lmv_dump_user_lmm(struct lmv_user_md *lum, char *pool_name,
2307                        char *path, int obdindex, int depth, int verbose)
2308 {
2309         struct lmv_user_mds_data *objects = lum->lum_objects;
2310         char *prefix = lum->lum_magic == LMV_USER_MAGIC ? "(Default)" : "";
2311         int i, obdstripe = 0;
2312         char *separator = "";
2313
2314         if (obdindex != OBD_NOT_FOUND) {
2315                 if (lum->lum_stripe_count == 0) {
2316                         if (obdindex == lum->lum_stripe_offset)
2317                                 obdstripe = 1;
2318                 } else {
2319                         for (i = 0; i < lum->lum_stripe_count; i++) {
2320                                 if (obdindex == objects[i].lum_mds) {
2321                                         llapi_printf(LLAPI_MSG_NORMAL,
2322                                                      "%s%s\n", prefix,
2323                                                      path);
2324                                         obdstripe = 1;
2325                                         break;
2326                                 }
2327                         }
2328                 }
2329         } else {
2330                 obdstripe = 1;
2331         }
2332
2333         if (!obdstripe)
2334                 return;
2335
2336         /* show all information default */
2337         if (!verbose) {
2338                 if (lum->lum_magic == LMV_USER_MAGIC)
2339                         verbose = VERBOSE_POOL | VERBOSE_COUNT | VERBOSE_OFFSET;
2340                 else
2341                         verbose = VERBOSE_OBJID;
2342         }
2343
2344         if (depth && path && ((verbose != VERBOSE_OBJID)))
2345                 llapi_printf(LLAPI_MSG_NORMAL, "%s%s\n", prefix, path);
2346
2347         if (verbose & VERBOSE_COUNT) {
2348                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2349                 if (verbose & ~VERBOSE_COUNT)
2350                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_stripe_count: ");
2351                 llapi_printf(LLAPI_MSG_NORMAL, "%u",
2352                              (int)lum->lum_stripe_count);
2353                 if (verbose & VERBOSE_OFFSET)
2354                         separator = " ";
2355                 else
2356                         separator = "\n";
2357         }
2358
2359         if (verbose & VERBOSE_OFFSET) {
2360                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2361                 if (verbose & ~VERBOSE_OFFSET)
2362                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_stripe_offset: ");
2363                 llapi_printf(LLAPI_MSG_NORMAL, "%d",
2364                              (int)lum->lum_stripe_offset);
2365                 separator = "\n";
2366         }
2367
2368         if (verbose & VERBOSE_OBJID && lum->lum_magic != LMV_USER_MAGIC) {
2369                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2370                 if (obdstripe == 1 && lum->lum_stripe_count > 0)
2371                         llapi_printf(LLAPI_MSG_NORMAL,
2372                                      "mdtidx\t\t FID[seq:oid:ver]\n");
2373                 for (i = 0; i < lum->lum_stripe_count; i++) {
2374                         int idx = objects[i].lum_mds;
2375                         struct lu_fid *fid = &objects[i].lum_fid;
2376                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
2377                                 llapi_printf(LLAPI_MSG_NORMAL,
2378                                              "%6u\t\t "DFID"\t\t%s\n",
2379                                             idx, PFID(fid),
2380                                             obdindex == idx ? " *" : "");
2381                 }
2382
2383         }
2384
2385         if ((verbose & VERBOSE_POOL) && pool_name != NULL &&
2386              pool_name[0] != '\0') {
2387                 llapi_printf(LLAPI_MSG_NORMAL, "%s", separator);
2388                 if (verbose & ~VERBOSE_POOL)
2389                         llapi_printf(LLAPI_MSG_NORMAL, "%slmv_pool:           ",
2390                                      prefix);
2391                 llapi_printf(LLAPI_MSG_NORMAL, "%s%c ", pool_name, ' ');
2392                 separator = "\n";
2393         }
2394
2395         if (!(verbose & VERBOSE_OBJID) || lum->lum_magic == LMV_USER_MAGIC)
2396                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
2397 }
2398
2399 void llapi_lov_dump_user_lmm(struct find_param *param, char *path, int is_dir)
2400 {
2401         __u32 magic;
2402
2403         if (param->fp_get_lmv || param->fp_get_default_lmv)
2404                 magic = (__u32)param->fp_lmv_md->lum_magic;
2405         else
2406                 magic = *(__u32 *)&param->fp_lmd->lmd_lmm; /* lum->lmm_magic */
2407
2408         switch (magic) {
2409         case LOV_USER_MAGIC_V1:
2410                 lov_dump_user_lmm_v1v3(&param->fp_lmd->lmd_lmm, NULL,
2411                                        param->fp_lmd->lmd_lmm.lmm_objects,
2412                                        path, is_dir,
2413                                        param->fp_obd_index, param->fp_max_depth,
2414                                        param->fp_verbose, param->fp_raw);
2415                 break;
2416         case LOV_USER_MAGIC_V3: {
2417                 char pool_name[LOV_MAXPOOLNAME + 1];
2418                 struct lov_user_ost_data_v1 *objects;
2419                 struct lov_user_md_v3 *lmmv3 = (void *)&param->fp_lmd->lmd_lmm;
2420
2421                 strlcpy(pool_name, lmmv3->lmm_pool_name, sizeof(pool_name));
2422                 objects = lmmv3->lmm_objects;
2423                 lov_dump_user_lmm_v1v3(&param->fp_lmd->lmd_lmm,
2424                                        pool_name[0] == '\0' ? NULL : pool_name,
2425                                        objects, path, is_dir,
2426                                        param->fp_obd_index, param->fp_max_depth,
2427                                        param->fp_verbose, param->fp_raw);
2428                 break;
2429         }
2430         case LMV_MAGIC_V1:
2431         case LMV_USER_MAGIC: {
2432                 char pool_name[LOV_MAXPOOLNAME + 1];
2433                 struct lmv_user_md *lum;
2434
2435                 lum = (struct lmv_user_md *)param->fp_lmv_md;
2436                 strlcpy(pool_name, lum->lum_pool_name, sizeof(pool_name));
2437                 lmv_dump_user_lmm(lum,
2438                                   pool_name[0] == '\0' ? NULL : pool_name,
2439                                   path, param->fp_obd_index,
2440                                   param->fp_max_depth, param->fp_verbose);
2441                 break;
2442         }
2443         default:
2444                 llapi_printf(LLAPI_MSG_NORMAL, "unknown lmm_magic:  %#x "
2445                              "(expecting one of %#x %#x %#x %#x)\n",
2446                              *(__u32 *)&param->fp_lmd->lmd_lmm,
2447                              LOV_USER_MAGIC_V1, LOV_USER_MAGIC_V3,
2448                              LMV_USER_MAGIC, LMV_MAGIC_V1);
2449                 return;
2450         }
2451 }
2452
2453 int llapi_file_get_stripe(const char *path, struct lov_user_md *lum)
2454 {
2455         const char *fname;
2456         char *dname;
2457         int fd, rc = 0;
2458
2459         fname = strrchr(path, '/');
2460
2461         /* It should be a file (or other non-directory) */
2462         if (fname == NULL) {
2463                 dname = (char *)malloc(2);
2464                 if (dname == NULL)
2465                         return -ENOMEM;
2466                 strcpy(dname, ".");
2467                 fname = (char *)path;
2468         } else {
2469                 dname = (char *)malloc(fname - path + 1);
2470                 if (dname == NULL)
2471                         return -ENOMEM;
2472                 strncpy(dname, path, fname - path);
2473                 dname[fname - path] = '\0';
2474                 fname++;
2475         }
2476
2477         fd = open(dname, O_RDONLY | O_NONBLOCK);
2478         if (fd == -1) {
2479                 rc = -errno;
2480                 free(dname);
2481                 return rc;
2482         }
2483
2484         strcpy((char *)lum, fname);
2485         if (ioctl(fd, IOC_MDC_GETFILESTRIPE, (void *)lum) == -1)
2486                 rc = -errno;
2487
2488         if (close(fd) == -1 && rc == 0)
2489                 rc = -errno;
2490
2491         free(dname);
2492         return rc;
2493 }
2494
2495 int llapi_file_lookup(int dirfd, const char *name)
2496 {
2497         struct obd_ioctl_data data = { 0 };
2498         char rawbuf[8192];
2499         char *buf = rawbuf;
2500         int rc;
2501
2502         if (dirfd < 0 || name == NULL)
2503                 return -EINVAL;
2504
2505         data.ioc_version = OBD_IOCTL_VERSION;
2506         data.ioc_len = sizeof(data);
2507         data.ioc_inlbuf1 = (char *)name;
2508         data.ioc_inllen1 = strlen(name) + 1;
2509
2510         rc = obd_ioctl_pack(&data, &buf, sizeof(rawbuf));
2511         if (rc) {
2512                 llapi_error(LLAPI_MSG_ERROR, rc,
2513                             "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
2514                             name, rc);
2515                 return rc;
2516         }
2517
2518         rc = ioctl(dirfd, IOC_MDC_LOOKUP, buf);
2519         if (rc < 0)
2520                 rc = -errno;
2521         return rc;
2522 }
2523
2524 /* Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
2525  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
2526  *
2527  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
2528  * The table below gives the answers for the specified parameters (value and
2529  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
2530  * --------------------------------------
2531  * 1 | file > limit; sign > 0 | -1 / -1 |
2532  * 2 | file = limit; sign > 0 | -1 / -1 |
2533  * 3 | file < limit; sign > 0 |  ? /  1 |
2534  * 4 | file > limit; sign = 0 | -1 / -1 |
2535  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
2536  * 6 | file < limit; sign = 0 |  ? / -1 |
2537  * 7 | file > limit; sign < 0 |  1 /  1 |
2538  * 8 | file = limit; sign < 0 |  ? / -1 |
2539  * 9 | file < limit; sign < 0 |  ? / -1 |
2540  * --------------------------------------
2541  * Note: 5th actually means that the value is within the interval
2542  * (limit - margin, limit]. */
2543 static int find_value_cmp(unsigned long long file, unsigned long long limit,
2544                           int sign, int negopt, unsigned long long margin,
2545                           int mds)
2546 {
2547         int ret = -1;
2548
2549         if (sign > 0) {
2550                 /* Drop the fraction of margin (of days). */
2551                 if (file + margin <= limit)
2552                         ret = mds ? 0 : 1;
2553         } else if (sign == 0) {
2554                 if (file <= limit && file + margin > limit)
2555                         ret = mds ? 0 : 1;
2556                 else if (file + margin <= limit)
2557                         ret = mds ? 0 : -1;
2558         } else if (sign < 0) {
2559                 if (file > limit)
2560                         ret = 1;
2561                 else if (mds)
2562                         ret = 0;
2563         }
2564
2565         return negopt ? ~ret + 1 : ret;
2566 }
2567
2568 /* Check if the file time matches all the given criteria (e.g. --atime +/-N).
2569  * Return -1 or 1 if file timestamp does not or does match the given criteria
2570  * correspondingly. Return 0 if the MDS time is being checked and there are
2571  * attributes on OSTs and it is not yet clear if the timespamp matches.
2572  *
2573  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
2574  * updated timestamps. */
2575 static int find_time_check(lstat_t *st, struct find_param *param, int mds)
2576 {
2577         int rc = 1;
2578         int rc2;
2579
2580         /* Check if file is accepted. */
2581         if (param->fp_atime) {
2582                 rc2 = find_value_cmp(st->st_atime, param->fp_atime,
2583                                      param->fp_asign, param->fp_exclude_atime,
2584                                      24 * 60 * 60, mds);
2585                 if (rc2 < 0)
2586                         return rc2;
2587                 rc = rc2;
2588         }
2589
2590         if (param->fp_mtime) {
2591                 rc2 = find_value_cmp(st->st_mtime, param->fp_mtime,
2592                                      param->fp_msign, param->fp_exclude_mtime,
2593                                      24 * 60 * 60, mds);
2594                 if (rc2 < 0)
2595                         return rc2;
2596
2597                 /* If the previous check matches, but this one is not yet clear,
2598                  * we should return 0 to do an RPC on OSTs. */
2599                 if (rc == 1)
2600                         rc = rc2;
2601         }
2602
2603         if (param->fp_ctime) {
2604                 rc2 = find_value_cmp(st->st_ctime, param->fp_ctime,
2605                                      param->fp_csign, param->fp_exclude_ctime,
2606                                      24 * 60 * 60, mds);
2607                 if (rc2 < 0)
2608                         return rc2;
2609
2610                 /* If the previous check matches, but this one is not yet clear,
2611                  * we should return 0 to do an RPC on OSTs. */
2612                 if (rc == 1)
2613                         rc = rc2;
2614         }
2615
2616         return rc;
2617 }
2618
2619 /**
2620  * Check whether the stripes matches the indexes user provided
2621  *       1   : matched
2622  *       0   : Unmatched
2623  */
2624 static int check_obd_match(struct find_param *param)
2625 {
2626         lstat_t *st = &param->fp_lmd->lmd_st;
2627         struct lov_user_ost_data_v1 *lmm_objects;
2628         int i, j;
2629
2630         if (param->fp_obd_uuid && param->fp_obd_index == OBD_NOT_FOUND)
2631                 return 0;
2632
2633         if (!S_ISREG(st->st_mode))
2634                 return 0;
2635
2636         /* Only those files should be accepted, which have a
2637          * stripe on the specified OST. */
2638         if (!param->fp_lmd->lmd_lmm.lmm_stripe_count)
2639                 return 0;
2640
2641         if (param->fp_lmd->lmd_lmm.lmm_magic ==
2642             LOV_USER_MAGIC_V3) {
2643                 struct lov_user_md_v3 *lmmv3 = (void *)&param->fp_lmd->lmd_lmm;
2644
2645                 lmm_objects = lmmv3->lmm_objects;
2646         } else if (param->fp_lmd->lmd_lmm.lmm_magic ==  LOV_USER_MAGIC_V1) {
2647                 lmm_objects = param->fp_lmd->lmd_lmm.lmm_objects;
2648         } else {
2649                 llapi_err_noerrno(LLAPI_MSG_ERROR, "%s:Unknown magic: 0x%08X\n",
2650                                   __func__, param->fp_lmd->lmd_lmm.lmm_magic);
2651                 return -EINVAL;
2652         }
2653
2654         for (i = 0; i < param->fp_lmd->lmd_lmm.lmm_stripe_count; i++) {
2655                 for (j = 0; j < param->fp_num_obds; j++) {
2656                         if (param->fp_obd_indexes[j] ==
2657                             lmm_objects[i].l_ost_idx) {
2658                                 if (param->fp_exclude_obd)
2659                                         return 0;
2660                                 return 1;
2661                         }
2662                 }
2663         }
2664
2665         if (param->fp_exclude_obd)
2666                 return 1;
2667
2668         return 0;
2669 }
2670
2671 static int check_mdt_match(struct find_param *param)
2672 {
2673         int i;
2674
2675         if (param->fp_mdt_uuid && param->fp_mdt_index == OBD_NOT_FOUND)
2676                 return 0;
2677
2678         /* FIXME: For striped dir, we should get stripe information and check */
2679         for (i = 0; i < param->fp_num_mdts; i++) {
2680                 if (param->fp_mdt_indexes[i] == param->fp_file_mdt_index)
2681                         return !param->fp_exclude_mdt;
2682         }
2683
2684         if (param->fp_exclude_mdt)
2685                 return 1;
2686
2687         return 0;
2688 }
2689
2690 /**
2691  * Check whether the obd is active or not, if it is
2692  * not active, just print the object affected by this
2693  * failed target
2694  **/
2695 static int print_failed_tgt(struct find_param *param, char *path, int type)
2696 {
2697         struct obd_statfs stat_buf;
2698         struct obd_uuid uuid_buf;
2699         int ret;
2700
2701         LASSERT(type == LL_STATFS_LOV || type == LL_STATFS_LMV);
2702
2703         memset(&stat_buf, 0, sizeof(struct obd_statfs));
2704         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
2705         ret = llapi_obd_statfs(path, type,
2706                                param->fp_obd_index, &stat_buf,
2707                                &uuid_buf);
2708         if (ret) {
2709                 llapi_printf(LLAPI_MSG_NORMAL,
2710                              "obd_uuid: %s failed %s ",
2711                              param->fp_obd_uuid->uuid,
2712                              strerror(errno));
2713         }
2714
2715         return ret;
2716 }
2717
2718 static int cb_find_init(char *path, DIR *parent, DIR **dirp,
2719                         void *data, struct dirent64 *de)
2720 {
2721         struct find_param *param = (struct find_param *)data;
2722         DIR *dir = dirp == NULL ? NULL : *dirp;
2723         int decision = 1; /* 1 is accepted; -1 is rejected. */
2724         lstat_t *st = &param->fp_lmd->lmd_st;
2725         int lustre_fs = 1;
2726         int checked_type = 0;
2727         int ret = 0;
2728
2729         LASSERT(parent != NULL || dir != NULL);
2730
2731         param->fp_lmd->lmd_lmm.lmm_stripe_count = 0;
2732
2733         /* If a regular expression is presented, make the initial decision */
2734         if (param->fp_pattern != NULL) {
2735                 char *fname = strrchr(path, '/');
2736                 fname = (fname == NULL ? path : fname + 1);
2737                 ret = fnmatch(param->fp_pattern, fname, 0);
2738                 if ((ret == FNM_NOMATCH && !param->fp_exclude_pattern) ||
2739                     (ret == 0 && param->fp_exclude_pattern))
2740                         goto decided;
2741         }
2742
2743         /* See if we can check the file type from the dirent. */
2744         if (param->fp_type != 0 && de != NULL && de->d_type != DT_UNKNOWN) {
2745                 checked_type = 1;
2746
2747                 if (DTTOIF(de->d_type) == param->fp_type) {
2748                         if (param->fp_exclude_type)
2749                                 goto decided;
2750                 } else {
2751                         if (!param->fp_exclude_type)
2752                                 goto decided;
2753                 }
2754         }
2755
2756         ret = 0;
2757
2758         /* Request MDS for the stat info if some of these parameters need
2759          * to be compared. */
2760         if (param->fp_obd_uuid || param->fp_mdt_uuid ||
2761             param->fp_check_uid || param->fp_check_gid ||
2762             param->fp_atime || param->fp_mtime || param->fp_ctime ||
2763             param->fp_check_pool || param->fp_check_size ||
2764             param->fp_check_stripe_count || param->fp_check_stripe_size ||
2765             param->fp_check_layout)
2766                 decision = 0;
2767
2768         if (param->fp_type != 0 && checked_type == 0)
2769                 decision = 0;
2770
2771         if (decision == 0) {
2772                 ret = get_lmd_info(path, parent, dir, param->fp_lmd,
2773                                    param->fp_lum_size);
2774                 if (ret == 0 && param->fp_lmd->lmd_lmm.lmm_magic == 0 &&
2775                     (param->fp_check_pool || param->fp_check_stripe_count ||
2776                      param->fp_check_stripe_size || param->fp_check_layout)) {
2777                         struct lov_user_md *lmm = &param->fp_lmd->lmd_lmm;
2778
2779                         /* We need to "fake" the "use the default" values
2780                          * since the lmm struct is zeroed out at this point. */
2781                         lmm->lmm_magic = LOV_USER_MAGIC_V1;
2782                         lmm->lmm_pattern = 0xFFFFFFFF;
2783                         if (!param->fp_raw)
2784                                 ostid_set_seq(&lmm->lmm_oi,
2785                                               FID_SEQ_LOV_DEFAULT);
2786                         lmm->lmm_stripe_size = 0;
2787                         lmm->lmm_stripe_count = 0;
2788                         lmm->lmm_stripe_offset = -1;
2789                 }
2790                 if (ret == 0 && param->fp_mdt_uuid != NULL) {
2791                         if (dir != NULL) {
2792                                 ret = llapi_file_fget_mdtidx(dirfd(dir),
2793                                                      &param->fp_file_mdt_index);
2794                         } else if (S_ISREG(st->st_mode)) {
2795                                 int fd;
2796
2797                                 /* FIXME: we could get the MDT index from the
2798                                  * file's FID in lmd->lmd_lmm.lmm_oi without
2799                                  * opening the file, once we are sure that
2800                                  * LFSCK2 (2.6) has fixed up pre-2.0 LOV EAs.
2801                                  * That would still be an ioctl() to map the
2802                                  * FID to the MDT, but not an open RPC. */
2803                                 fd = open(path, O_RDONLY);
2804                                 if (fd > 0) {
2805                                         ret = llapi_file_fget_mdtidx(fd,
2806                                                      &param->fp_file_mdt_index);
2807                                         close(fd);
2808                                 } else {
2809                                         ret = -errno;
2810                                 }
2811                         } else {
2812                                 /* For a special file, we assume it resides on
2813                                  * the same MDT as the parent directory. */
2814                                 ret = llapi_file_fget_mdtidx(dirfd(parent),
2815                                                      &param->fp_file_mdt_index);
2816                         }
2817                 }
2818                 if (ret != 0) {
2819                         if (ret == -ENOTTY)
2820                                 lustre_fs = 0;
2821                         if (ret == -ENOENT)
2822                                 goto decided;
2823
2824                         return ret;
2825                 }
2826         }
2827
2828         if (param->fp_type && !checked_type) {
2829                 if ((st->st_mode & S_IFMT) == param->fp_type) {
2830                         if (param->fp_exclude_type)
2831                                 goto decided;
2832                 } else {
2833                         if (!param->fp_exclude_type)
2834                                 goto decided;
2835                 }
2836         }
2837
2838         /* Prepare odb. */
2839         if (param->fp_obd_uuid || param->fp_mdt_uuid) {
2840                 if (lustre_fs && param->fp_got_uuids &&
2841                     param->fp_dev != st->st_dev) {
2842                         /* A lustre/lustre mount point is crossed. */
2843                         param->fp_got_uuids = 0;
2844                         param->fp_obds_printed = 0;
2845                         param->fp_mdt_index = OBD_NOT_FOUND;
2846                         param->fp_obd_index = OBD_NOT_FOUND;
2847                 }
2848
2849                 if (lustre_fs && !param->fp_got_uuids) {
2850                         ret = setup_target_indexes(dir ? dir : parent, path,
2851                                                    param);
2852                         if (ret)
2853                                 return ret;
2854
2855                         param->fp_dev = st->st_dev;
2856                 } else if (!lustre_fs && param->fp_got_uuids) {
2857                         /* A lustre/non-lustre mount point is crossed. */
2858                         param->fp_got_uuids = 0;
2859                         param->fp_mdt_index = OBD_NOT_FOUND;
2860                         param->fp_obd_index = OBD_NOT_FOUND;
2861                 }
2862         }
2863
2864         if (param->fp_check_stripe_size) {
2865                 decision = find_value_cmp(
2866                                 param->fp_lmd->lmd_lmm.lmm_stripe_size,
2867                                 param->fp_stripe_size,
2868                                 param->fp_stripe_size_sign,
2869                                 param->fp_exclude_stripe_size,
2870                                 param->fp_stripe_size_units, 0);
2871                 if (decision == -1)
2872                         goto decided;
2873         }
2874
2875         if (param->fp_check_stripe_count) {
2876                 decision = find_value_cmp(
2877                                 param->fp_lmd->lmd_lmm.lmm_stripe_count,
2878                                 param->fp_stripe_count,
2879                                 param->fp_stripe_count_sign,
2880                                 param->fp_exclude_stripe_count, 1, 0);
2881                 if (decision == -1)
2882                         goto decided;
2883         }
2884
2885         if (param->fp_check_layout) {
2886                 __u32 found;
2887
2888                 found = (param->fp_lmd->lmd_lmm.lmm_pattern & param->fp_layout);
2889                 if ((param->fp_lmd->lmd_lmm.lmm_pattern == 0xFFFFFFFF) ||
2890                     (found && param->fp_exclude_layout) ||
2891                     (!found && !param->fp_exclude_layout)) {
2892                         decision = -1;
2893                         goto decided;
2894                 }
2895         }
2896
2897         /* If an OBD UUID is specified but none matches, skip this file. */
2898         if ((param->fp_obd_uuid && param->fp_obd_index == OBD_NOT_FOUND) ||
2899             (param->fp_mdt_uuid && param->fp_mdt_index == OBD_NOT_FOUND))
2900                 goto decided;
2901
2902         /* If an OST or MDT UUID is given, and some OST matches,
2903          * check it here. */
2904         if (param->fp_obd_index != OBD_NOT_FOUND ||
2905             param->fp_mdt_index != OBD_NOT_FOUND) {
2906                 if (param->fp_obd_uuid) {
2907                         if (check_obd_match(param)) {
2908                                 /* If no mdtuuid is given, we are done.
2909                                  * Otherwise, fall through to the mdtuuid
2910                                  * check below. */
2911                                 if (!param->fp_mdt_uuid)
2912                                         goto obd_matches;
2913                         } else {
2914                                 goto decided;
2915                         }
2916                 }
2917
2918                 if (param->fp_mdt_uuid) {
2919                         if (check_mdt_match(param))
2920                                 goto obd_matches;
2921                         goto decided;
2922                 }
2923         }
2924
2925 obd_matches:
2926         if (param->fp_check_uid) {
2927                 if (st->st_uid == param->fp_uid) {
2928                         if (param->fp_exclude_uid)
2929                                 goto decided;
2930                 } else {
2931                         if (!param->fp_exclude_uid)
2932                                 goto decided;
2933                 }
2934         }
2935
2936         if (param->fp_check_gid) {
2937                 if (st->st_gid == param->fp_gid) {
2938                         if (param->fp_exclude_gid)
2939                                 goto decided;
2940                 } else {
2941                         if (!param->fp_exclude_gid)
2942                                 goto decided;
2943                 }
2944         }
2945
2946         if (param->fp_check_pool) {
2947                 struct lov_user_md_v3 *lmmv3 = (void *)&param->fp_lmd->lmd_lmm;
2948
2949                 /* empty requested pool is taken as no pool search => V1 */
2950                 if (((param->fp_lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V1) &&
2951                      (param->fp_poolname[0] == '\0')) ||
2952                     ((param->fp_lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
2953                      (strncmp(lmmv3->lmm_pool_name,
2954                               param->fp_poolname, LOV_MAXPOOLNAME) == 0)) ||
2955                     ((param->fp_lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
2956                      (strcmp(param->fp_poolname, "*") == 0))) {
2957                         if (param->fp_exclude_pool)
2958                                 goto decided;
2959                 } else {
2960                         if (!param->fp_exclude_pool)
2961                                 goto decided;
2962                 }
2963         }
2964
2965         /* Check the time on mds. */
2966         decision = 1;
2967         if (param->fp_atime || param->fp_mtime || param->fp_ctime) {
2968                 int for_mds;
2969
2970                 for_mds = lustre_fs ? (S_ISREG(st->st_mode) &&
2971                                        param->fp_lmd->lmd_lmm.lmm_stripe_count)
2972                         : 0;
2973                 decision = find_time_check(st, param, for_mds);
2974                 if (decision == -1)
2975                         goto decided;
2976         }
2977
2978         /* If file still fits the request, ask ost for updated info.
2979            The regular stat is almost of the same speed as some new
2980            'glimpse-size-ioctl'. */
2981
2982         if (param->fp_check_size && S_ISREG(st->st_mode) &&
2983             param->fp_lmd->lmd_lmm.lmm_stripe_count)
2984                 decision = 0;
2985
2986         if (param->fp_check_size && S_ISDIR(st->st_mode))
2987                 decision = 0;
2988
2989         if (!decision) {
2990                 /* For regular files with the stripe the decision may have not
2991                  * been taken yet if *time or size is to be checked. */
2992                 if (param->fp_obd_index != OBD_NOT_FOUND)
2993                         print_failed_tgt(param, path, LL_STATFS_LOV);
2994
2995                 if (param->fp_mdt_index != OBD_NOT_FOUND)
2996                         print_failed_tgt(param, path, LL_STATFS_LMV);
2997
2998                 if (dir != NULL)
2999                         ret = fstat_f(dirfd(dir), st);
3000                 else if (de != NULL)
3001                         ret = fstatat_f(dirfd(parent), de->d_name, st,
3002                                         AT_SYMLINK_NOFOLLOW);
3003                 else
3004                         ret = lstat_f(path, st);
3005
3006                 if (ret) {
3007                         if (errno == ENOENT) {
3008                                 llapi_error(LLAPI_MSG_ERROR, -ENOENT,
3009                                             "warning: %s: %s does not exist",
3010                                             __func__, path);
3011                                 goto decided;
3012                         } else {
3013                                 ret = -errno;
3014                                 llapi_error(LLAPI_MSG_ERROR, ret,
3015                                             "%s: IOC_LOV_GETINFO on %s failed",
3016                                             __func__, path);
3017                                 return ret;
3018                         }
3019                 }
3020
3021                 /* Check the time on osc. */
3022                 decision = find_time_check(st, param, 0);
3023                 if (decision == -1)
3024                         goto decided;
3025         }
3026
3027         if (param->fp_check_size)
3028                 decision = find_value_cmp(st->st_size, param->fp_size,
3029                                           param->fp_size_sign,
3030                                           param->fp_exclude_size,
3031                                           param->fp_size_units, 0);
3032
3033         if (decision != -1) {
3034                 llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
3035                 if (param->fp_zero_end)
3036                         llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
3037                 else
3038                         llapi_printf(LLAPI_MSG_NORMAL, "\n");
3039         }
3040
3041 decided:
3042         /* Do not get down anymore? */
3043         if (param->fp_depth == param->fp_max_depth)
3044                 return 1;
3045
3046         param->fp_depth++;
3047
3048         return 0;
3049 }
3050
3051 static int cb_migrate_mdt_init(char *path, DIR *parent, DIR **dirp,
3052                                void *param_data, struct dirent64 *de)
3053 {
3054         struct find_param       *param = (struct find_param *)param_data;
3055         DIR                     *tmp_parent = parent;
3056         char                    raw[OBD_MAX_IOCTL_BUFFER] = {'\0'};
3057         char                    *rawbuf = raw;
3058         struct obd_ioctl_data   data = { 0 };
3059         int                     fd;
3060         int                     ret;
3061         char                    *path_copy;
3062         char                    *filename;
3063         bool                    retry = false;
3064
3065         LASSERT(parent != NULL || dirp != NULL);
3066         if (dirp != NULL)
3067                 closedir(*dirp);
3068
3069         if (parent == NULL) {
3070                 tmp_parent = opendir_parent(path);
3071                 if (tmp_parent == NULL) {
3072                         *dirp = NULL;
3073                         ret = -errno;
3074                         llapi_error(LLAPI_MSG_ERROR, ret,
3075                                     "can not open %s", path);
3076                         return ret;
3077                 }
3078         }
3079
3080         fd = dirfd(tmp_parent);
3081
3082         path_copy = strdup(path);
3083         filename = basename(path_copy);
3084         data.ioc_inlbuf1 = (char *)filename;
3085         data.ioc_inllen1 = strlen(filename) + 1;
3086         data.ioc_inlbuf2 = (char *)&param->fp_mdt_index;
3087         data.ioc_inllen2 = sizeof(param->fp_mdt_index);
3088         ret = obd_ioctl_pack(&data, &rawbuf, sizeof(raw));
3089         if (ret != 0) {
3090                 llapi_error(LLAPI_MSG_ERROR, ret,
3091                             "llapi_obd_statfs: error packing ioctl data");
3092                 goto out;
3093         }
3094
3095 migrate:
3096         ret = ioctl(fd, LL_IOC_MIGRATE, rawbuf);
3097         if (ret != 0) {
3098                 if (errno == EBUSY && !retry) {
3099                         /* because migrate may not be able to lock all involved
3100                          * objects in order, for some of them it try lock, while
3101                          * there may be conflicting COS locks and cause migrate
3102                          * fail with EBUSY, hope a sync() could cause
3103                          * transaction commit and release these COS locks. */
3104                         sync();
3105                         retry = true;
3106                         goto migrate;
3107                 }
3108                 ret = -errno;
3109                 fprintf(stderr, "%s migrate failed: %s (%d)\n",
3110                         path, strerror(-ret), ret);
3111                 goto out;
3112         } else if (param->fp_verbose & VERBOSE_DETAIL) {
3113                 fprintf(stdout, "migrate %s to MDT%d\n",
3114                         path, param->fp_mdt_index);
3115         }
3116
3117 out:
3118         if (dirp != NULL) {
3119                 /* If the directory is being migration, we need
3120                  * close the directory after migration,
3121                  * so the old directory cache will be cleanup
3122                  * on the client side, and re-open to get the
3123                  * new directory handle */
3124                 *dirp = opendir(path);
3125                 if (*dirp == NULL) {
3126                         ret = -errno;
3127                         llapi_error(LLAPI_MSG_ERROR, ret,
3128                                     "%s: Failed to open '%s'", __func__, path);
3129                 }
3130         }
3131
3132         if (parent == NULL)
3133                 closedir(tmp_parent);
3134
3135         free(path_copy);
3136
3137         return ret;
3138 }
3139
3140 int llapi_migrate_mdt(char *path, struct find_param *param)
3141 {
3142         return param_callback(path, cb_migrate_mdt_init, cb_common_fini, param);
3143 }
3144
3145 int llapi_mv(char *path, struct find_param *param)
3146 {
3147 #if LUSTRE_VERSION_CODE > OBD_OCD_VERSION(2, 9, 53, 0)
3148         static bool printed;
3149
3150         if (!printed) {
3151                 llapi_error(LLAPI_MSG_ERROR, -ESTALE,
3152                             "llapi_mv() is deprecated, use llapi_migrate_mdt()\n");
3153                 printed = true;
3154         }
3155 #endif
3156         return llapi_migrate_mdt(path, param);
3157 }
3158
3159 int llapi_find(char *path, struct find_param *param)
3160 {
3161         return param_callback(path, cb_find_init, cb_common_fini, param);
3162 }
3163
3164 /*
3165  * Get MDT number that the file/directory inode referenced
3166  * by the open fd resides on.
3167  * Return 0 and mdtidx on success, or -ve errno.
3168  */
3169 int llapi_file_fget_mdtidx(int fd, int *mdtidx)
3170 {
3171         if (ioctl(fd, LL_IOC_GET_MDTIDX, mdtidx) < 0)
3172                 return -errno;
3173         return 0;
3174 }
3175
3176 static int cb_get_mdt_index(char *path, DIR *parent, DIR **dirp, void *data,
3177                             struct dirent64 *de)
3178 {
3179         struct find_param *param = (struct find_param *)data;
3180         DIR *d = dirp == NULL ? NULL : *dirp;
3181         int ret;
3182         int mdtidx;
3183
3184         LASSERT(parent != NULL || d != NULL);
3185
3186         if (d != NULL) {
3187                 ret = llapi_file_fget_mdtidx(dirfd(d), &mdtidx);
3188         } else /* if (parent) */ {
3189                 int fd;
3190
3191                 fd = open(path, O_RDONLY | O_NOCTTY);
3192                 if (fd > 0) {
3193                         ret = llapi_file_fget_mdtidx(fd, &mdtidx);
3194                         close(fd);
3195                 } else {
3196                         ret = -errno;
3197                 }
3198         }
3199
3200         if (ret != 0) {
3201                 if (ret == -ENODATA) {
3202                         if (!param->fp_obd_uuid)
3203                                 llapi_printf(LLAPI_MSG_NORMAL,
3204                                              "'%s' has no stripe info\n", path);
3205                         goto out;
3206                 } else if (ret == -ENOENT) {
3207                         llapi_error(LLAPI_MSG_WARN, ret,
3208                                     "warning: %s: '%s' does not exist",
3209                                     __func__, path);
3210                         goto out;
3211                 } else if (ret == -ENOTTY) {
3212                         llapi_error(LLAPI_MSG_ERROR, ret,
3213                                     "%s: '%s' not on a Lustre fs",
3214                                     __func__, path);
3215                 } else {
3216                         llapi_error(LLAPI_MSG_ERROR, ret,
3217                                     "error: %s: '%s' failed get_mdtidx",
3218                                     __func__, path);
3219                 }
3220                 return ret;
3221         }
3222
3223         if (param->fp_quiet || !(param->fp_verbose & VERBOSE_DETAIL))
3224                 llapi_printf(LLAPI_MSG_NORMAL, "%d\n", mdtidx);
3225         else
3226                 llapi_printf(LLAPI_MSG_NORMAL, "%s\nmdt_index:\t%d\n",
3227                              path, mdtidx);
3228
3229 out:
3230         /* Do not go down anymore? */
3231         if (param->fp_depth == param->fp_max_depth)
3232                 return 1;
3233
3234         param->fp_depth++;
3235
3236         return 0;
3237 }
3238
3239 static int cb_getstripe(char *path, DIR *parent, DIR **dirp, void *data,
3240                         struct dirent64 *de)
3241 {
3242         struct find_param *param = (struct find_param *)data;
3243         DIR *d = dirp == NULL ? NULL : *dirp;
3244         int ret = 0;
3245
3246         LASSERT(parent != NULL || d != NULL);
3247
3248         if (param->fp_obd_uuid) {
3249                 param->fp_quiet = 1;
3250                 ret = setup_obd_uuid(d ? d : parent, path, param);
3251                 if (ret)
3252                         return ret;
3253         }
3254
3255         if (d) {
3256                 if (param->fp_get_lmv || param->fp_get_default_lmv) {
3257                         ret = cb_get_dirstripe(path, d, param);
3258                 } else {
3259                         ret = ioctl(dirfd(d), LL_IOC_LOV_GETSTRIPE,
3260                                      (void *)&param->fp_lmd->lmd_lmm);
3261                 }
3262
3263         } else if (parent && !param->fp_get_lmv && !param->fp_get_default_lmv) {
3264                 char *fname = strrchr(path, '/');
3265                 fname = (fname == NULL ? path : fname + 1);
3266
3267                 strlcpy((char *)&param->fp_lmd->lmd_lmm, fname,
3268                         param->fp_lum_size);
3269
3270                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILESTRIPE,
3271                             (void *)&param->fp_lmd->lmd_lmm);
3272         } else {
3273                 return 0;
3274         }
3275
3276         if (ret) {
3277                 if (errno == ENODATA && d != NULL) {
3278                         /* We need to "fake" the "use the default" values
3279                          * since the lmm struct is zeroed out at this point.
3280                          * The magic needs to be set in order to satisfy
3281                          * a check later on in the code path.
3282                          * The object_seq needs to be set for the "(Default)"
3283                          * prefix to be displayed. */
3284                         if (param->fp_get_default_lmv) {
3285                                 struct lmv_user_md *lum = param->fp_lmv_md;
3286
3287                                 lum->lum_magic = LMV_USER_MAGIC;
3288                                 lum->lum_stripe_count = 0;
3289                                 lum->lum_stripe_offset = -1;
3290                                 goto dump;
3291                         } else if (param->fp_get_lmv) {
3292                                 struct lmv_user_md *lum = param->fp_lmv_md;
3293                                 int mdtidx;
3294
3295                                 ret = llapi_file_fget_mdtidx(dirfd(d), &mdtidx);
3296                                 if (ret != 0)
3297                                         goto err_out;
3298                                 lum->lum_magic = LMV_MAGIC_V1;
3299                                 lum->lum_stripe_count = 0;
3300                                 lum->lum_stripe_offset = mdtidx;
3301                                 goto dump;
3302                         } else {
3303                                 struct lov_user_md *lmm =
3304                                         &param->fp_lmd->lmd_lmm;
3305
3306                                 lmm->lmm_magic = LOV_USER_MAGIC_V1;
3307                                 if (!param->fp_raw)
3308                                         ostid_set_seq(&lmm->lmm_oi,
3309                                                       FID_SEQ_LOV_DEFAULT);
3310                                 lmm->lmm_stripe_count = 0;
3311                                 lmm->lmm_stripe_size = 0;
3312                                 lmm->lmm_stripe_offset = -1;
3313                                 goto dump;
3314                         }
3315                 } else if (errno == ENODATA && parent != NULL) {
3316                         if (!param->fp_obd_uuid && !param->fp_mdt_uuid)
3317                                 llapi_printf(LLAPI_MSG_NORMAL,
3318                                              "%s has no stripe info\n", path);
3319                         goto out;
3320                 } else if (errno == ENOENT) {
3321                         llapi_error(LLAPI_MSG_WARN, -ENOENT,
3322                                     "warning: %s: %s does not exist",
3323                                     __func__, path);
3324                         goto out;
3325                 } else if (errno == ENOTTY) {
3326                         ret = -errno;
3327                         llapi_error(LLAPI_MSG_ERROR, ret,
3328                                     "%s: '%s' not on a Lustre fs?",
3329                                     __func__, path);
3330                 } else {
3331                         ret = -errno;
3332 err_out:
3333                         llapi_error(LLAPI_MSG_ERROR, ret,
3334                                     "error: %s: %s failed for %s",
3335                                      __func__, d ? "LL_IOC_LOV_GETSTRIPE" :
3336                                     "IOC_MDC_GETFILESTRIPE", path);
3337                 }
3338
3339                 return ret;
3340         }
3341
3342 dump:
3343         if (!(param->fp_verbose & VERBOSE_MDTINDEX))
3344                 llapi_lov_dump_user_lmm(param, path, d ? 1 : 0);
3345
3346 out:
3347         /* Do not get down anymore? */
3348         if (param->fp_depth == param->fp_max_depth)
3349                 return 1;
3350
3351         param->fp_depth++;
3352
3353         return 0;
3354 }
3355
3356 int llapi_getstripe(char *path, struct find_param *param)
3357 {
3358         return param_callback(path, (param->fp_verbose & VERBOSE_MDTINDEX) ?
3359                               cb_get_mdt_index : cb_getstripe,
3360                               cb_common_fini, param);
3361 }
3362
3363 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
3364                      struct obd_statfs *stat_buf,
3365                      struct obd_uuid *uuid_buf)
3366 {
3367         int fd;
3368         char raw[OBD_MAX_IOCTL_BUFFER] = {'\0'};
3369         char *rawbuf = raw;
3370         struct obd_ioctl_data data = { 0 };
3371         int rc = 0;
3372
3373         data.ioc_inlbuf1 = (char *)&type;
3374         data.ioc_inllen1 = sizeof(__u32);
3375         data.ioc_inlbuf2 = (char *)&index;
3376         data.ioc_inllen2 = sizeof(__u32);
3377         data.ioc_pbuf1 = (char *)stat_buf;
3378         data.ioc_plen1 = sizeof(struct obd_statfs);
3379         data.ioc_pbuf2 = (char *)uuid_buf;
3380         data.ioc_plen2 = sizeof(struct obd_uuid);
3381
3382         rc = obd_ioctl_pack(&data, &rawbuf, sizeof(raw));
3383         if (rc != 0) {
3384                 llapi_error(LLAPI_MSG_ERROR, rc,
3385                             "llapi_obd_statfs: error packing ioctl data");
3386                 return rc;
3387         }
3388
3389         fd = open(path, O_RDONLY);
3390         if (errno == EISDIR)
3391                 fd = open(path, O_DIRECTORY | O_RDONLY);
3392
3393         if (fd < 0) {
3394                 rc = errno ? -errno : -EBADF;
3395                 llapi_error(LLAPI_MSG_ERROR, rc, "error: %s: opening '%s'",
3396                             __func__, path);
3397                 /* If we can't even open a file on the filesystem (e.g. with
3398                  * -ESHUTDOWN), force caller to exit or it will loop forever. */
3399                 return -ENODEV;
3400         }
3401         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
3402         if (rc)
3403                 rc = errno ? -errno : -EINVAL;
3404
3405         close(fd);
3406         return rc;
3407 }
3408
3409 #define MAX_STRING_SIZE 128
3410
3411 int llapi_ping(char *obd_type, char *obd_name)
3412 {
3413         glob_t path;
3414         char buf[1];
3415         int rc, fd;
3416
3417         rc = cfs_get_param_paths(&path, "%s/%s/ping",
3418                                 obd_type, obd_name);
3419         if (rc != 0)
3420                 return -errno;
3421
3422         fd = open(path.gl_pathv[0], O_WRONLY);
3423         if (fd < 0) {
3424                 rc = -errno;
3425                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s",
3426                             path.gl_pathv[0]);
3427                 goto failed;
3428         }
3429
3430         /* The purpose is to send a byte as a ping, whatever this byte is. */
3431         /* coverity[uninit_use_in_call] */
3432         rc = write(fd, buf, 1);
3433         if (rc < 0)
3434                 rc = -errno;
3435         close(fd);
3436
3437         if (rc == 1)
3438                 rc = 0;
3439 failed:
3440         cfs_free_param_data(&path);
3441         return rc;
3442 }
3443
3444 int llapi_target_iterate(int type_num, char **obd_type,
3445                          void *args, llapi_cb_t cb)
3446 {
3447         char buf[MAX_STRING_SIZE];
3448         int i, rc = 0;
3449         glob_t param;
3450         FILE *fp;
3451
3452         rc = cfs_get_param_paths(&param, "devices");
3453         if (rc != 0)
3454                 return -ENOENT;
3455
3456         fp = fopen(param.gl_pathv[0], "r");
3457         if (fp == NULL) {
3458                 rc = -errno;
3459                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening '%s'",
3460                             param.gl_pathv[0]);
3461                 goto free_path;
3462         }
3463
3464         while (fgets(buf, sizeof(buf), fp) != NULL) {
3465                 char *obd_type_name = NULL;
3466                 char *obd_name = NULL;
3467                 char *obd_uuid = NULL;
3468                 char *bufp = buf;
3469                 struct obd_statfs osfs_buffer;
3470
3471                 while(bufp[0] == ' ')
3472                         ++bufp;
3473
3474                 for(i = 0; i < 3; i++) {
3475                         obd_type_name = strsep(&bufp, " ");
3476                 }
3477                 obd_name = strsep(&bufp, " ");
3478                 obd_uuid = strsep(&bufp, " ");
3479
3480                 memset(&osfs_buffer, 0, sizeof (osfs_buffer));
3481
3482                 for (i = 0; i < type_num; i++) {
3483                         if (strcmp(obd_type_name, obd_type[i]) != 0)
3484                                 continue;
3485
3486                         cb(obd_type_name, obd_name, obd_uuid, args);
3487                 }
3488         }
3489         fclose(fp);
3490 free_path:
3491         cfs_free_param_data(&param);
3492         return 0;
3493 }
3494
3495 static void do_target_check(char *obd_type_name, char *obd_name,
3496                             char *obd_uuid, void *args)
3497 {
3498         int rc;
3499
3500         rc = llapi_ping(obd_type_name, obd_name);
3501         if (rc == ENOTCONN) {
3502                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
3503         } else if (rc) {
3504                 llapi_error(LLAPI_MSG_ERROR, rc, "error: check '%s'", obd_name);
3505         } else {
3506                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
3507         }
3508 }
3509
3510 int llapi_target_check(int type_num, char **obd_type, char *dir)
3511 {
3512         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
3513 }
3514
3515 #undef MAX_STRING_SIZE
3516
3517 /* Is this a lustre fs? */
3518 int llapi_is_lustre_mnttype(const char *type)
3519 {
3520         return (strcmp(type, "lustre") == 0 || strcmp(type,"lustre_lite") == 0);
3521 }
3522
3523 /* Is this a lustre client fs? */
3524 int llapi_is_lustre_mnt(struct mntent *mnt)
3525 {
3526         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
3527                 strstr(mnt->mnt_fsname, ":/") != NULL);
3528 }
3529
3530 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
3531 {
3532         DIR *root;
3533         int rc;
3534
3535         root = opendir(mnt);
3536         if (!root) {
3537                 rc = -errno;
3538                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
3539                 return rc;
3540         }
3541
3542         rc = ioctl(dirfd(root), OBD_IOC_QUOTACTL, qctl);
3543         if (rc < 0)
3544                 rc = -errno;
3545
3546         closedir(root);
3547         return rc;
3548 }
3549
3550 /* Print mdtname 'name' into 'buf' using 'format'.  Add -MDT0000 if needed.
3551  * format must have %s%s, buf must be > 16
3552  * Eg: if name = "lustre-MDT0000", "lustre", or "lustre-MDT0000_UUID"
3553  *     then buf = "lustre-MDT0000"
3554  */
3555 static int get_mdtname(char *name, char *format, char *buf)
3556 {
3557         char suffix[]="-MDT0000";
3558         int len = strlen(name);
3559
3560         if ((len > 5) && (strncmp(name + len - 5, "_UUID", 5) == 0)) {
3561                 name[len - 5] = '\0';
3562                 len -= 5;
3563         }
3564
3565         if (len > 8) {
3566                 if ((len <= 16) && strncmp(name + len - 8, "-MDT", 4) == 0) {
3567                         suffix[0] = '\0';
3568                 } else {
3569                         /* Not enough room to add suffix */
3570                         llapi_err_noerrno(LLAPI_MSG_ERROR,
3571                                           "MDT name too long |%s|", name);
3572                         return -EINVAL;
3573                 }
3574         }
3575
3576         return sprintf(buf, format, name, suffix);
3577 }
3578
3579 /** ioctl on filsystem root, with mdtindex sent as data
3580  * \param mdtname path, fsname, or mdtname (lutre-MDT0004)
3581  * \param mdtidxp pointer to integer within data to be filled in with the
3582  *    mdt index (0 if no mdt is specified).  NULL won't be filled.
3583  */
3584 int root_ioctl(const char *mdtname, int opc, void *data, int *mdtidxp,
3585                int want_error)
3586 {
3587         char fsname[20];
3588         char *ptr;
3589         int fd, rc;
3590         long index;
3591
3592         /* Take path, fsname, or MDTname.  Assume MDT0000 in the former cases.
3593          Open root and parse mdt index. */
3594         if (mdtname[0] == '/') {
3595                 index = 0;
3596                 rc = get_root_path(WANT_FD | want_error, NULL, &fd,
3597                                    (char *)mdtname, -1);
3598         } else {
3599                 if (get_mdtname((char *)mdtname, "%s%s", fsname) < 0)
3600                         return -EINVAL;
3601                 ptr = fsname + strlen(fsname) - 8;
3602                 *ptr = '\0';
3603                 index = strtol(ptr + 4, NULL, 10);
3604                 rc = get_root_path(WANT_FD | want_error, fsname, &fd, NULL, -1);
3605         }
3606         if (rc < 0) {
3607                 if (want_error)
3608                         llapi_err_noerrno(LLAPI_MSG_ERROR,
3609                                           "Can't open %s: %d\n", mdtname, rc);
3610                 return rc;
3611         }
3612
3613         if (mdtidxp)
3614                 *mdtidxp = index;
3615
3616         rc = ioctl(fd, opc, data);
3617         if (rc == -1)
3618                 rc = -errno;
3619         else
3620                 rc = 0;
3621         close(fd);
3622         return rc;
3623 }
3624
3625 /****** Changelog API ********/
3626
3627 static int changelog_ioctl(const char *mdtname, int opc, int id,
3628                            long long recno, int flags)
3629 {
3630         struct ioc_changelog data;
3631         int *idx;
3632
3633         data.icc_id = id;
3634         data.icc_recno = recno;
3635         data.icc_flags = flags;
3636         idx = (int *)(&data.icc_mdtindex);
3637
3638         return root_ioctl(mdtname, opc, &data, idx, WANT_ERROR);
3639 }
3640
3641 #define CHANGELOG_PRIV_MAGIC 0xCA8E1080
3642 struct changelog_private {
3643         int                             magic;
3644         enum changelog_send_flag        flags;
3645         struct lustre_kernelcomm        kuc;
3646 };
3647
3648 /** Start reading from a changelog
3649  * @param priv Opaque private control structure
3650  * @param flags Start flags (e.g. CHANGELOG_FLAG_BLOCK)
3651  * @param device Report changes recorded on this MDT
3652  * @param startrec Report changes beginning with this record number
3653  * (just call llapi_changelog_fini when done; don't need an endrec)
3654  */
3655 int llapi_changelog_start(void **priv, enum changelog_send_flag flags,
3656                           const char *device, long long startrec)
3657 {
3658         struct changelog_private        *cp;
3659         static bool                      warned;
3660         int                              rc;
3661
3662         /* Set up the receiver control struct */
3663         cp = calloc(1, sizeof(*cp));
3664         if (cp == NULL)
3665                 return -ENOMEM;
3666
3667         cp->magic = CHANGELOG_PRIV_MAGIC;
3668         cp->flags = flags;
3669
3670         /* Set up the receiver */
3671         rc = libcfs_ukuc_start(&cp->kuc, 0 /* no group registration */, 0);
3672         if (rc < 0)
3673                 goto out_free;
3674
3675         *priv = cp;
3676
3677         /* CHANGELOG_FLAG_JOBID will eventually become mandatory. Display a
3678          * warning if it's missing. */
3679         if (!(flags & CHANGELOG_FLAG_JOBID) && !warned) {
3680                 llapi_err_noerrno(LLAPI_MSG_WARN, "warning: %s() called "
3681                                   "w/o CHANGELOG_FLAG_JOBID", __func__);
3682                 warned = true;
3683         }
3684
3685         /* Tell the kernel to start sending */
3686         rc = changelog_ioctl(device, OBD_IOC_CHANGELOG_SEND, cp->kuc.lk_wfd,
3687                              startrec, flags);
3688         /* Only the kernel reference keeps the write side open */
3689         close(cp->kuc.lk_wfd);
3690         cp->kuc.lk_wfd = LK_NOFD;
3691         if (rc < 0) {
3692                 /* frees and clears priv */
3693                 llapi_changelog_fini(priv);
3694                 return rc;
3695         }
3696
3697         return 0;
3698
3699 out_free:
3700         free(cp);
3701         return rc;
3702 }
3703
3704 /** Finish reading from a changelog */
3705 int llapi_changelog_fini(void **priv)
3706 {
3707         struct changelog_private *cp = (struct changelog_private *)*priv;
3708
3709         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
3710                 return -EINVAL;
3711
3712         libcfs_ukuc_stop(&cp->kuc);
3713         free(cp);
3714         *priv = NULL;
3715         return 0;
3716 }
3717
3718 /**
3719  * Convert all records to a same format according to the caller's wishes.
3720  * Default is CLF_VERSION | CLF_RENAME.
3721  * Add CLF_JOBID if explicitely requested.
3722  *
3723  * \param rec  The record to remap. It is expected to be big enough to
3724  *             properly handle the final format.
3725  * \return 1 if anything changed. 0 otherwise.
3726  */
3727 /** Read the next changelog entry
3728  * @param priv Opaque private control structure
3729  * @param rech Changelog record handle; record will be allocated here
3730  * @return 0 valid message received; rec is set
3731  *         <0 error code
3732  *         1 EOF
3733  */
3734 #define DEFAULT_RECORD_FMT      (CLF_VERSION | CLF_RENAME)
3735 int llapi_changelog_recv(void *priv, struct changelog_rec **rech)
3736 {
3737         struct changelog_private        *cp = (struct changelog_private *)priv;
3738         struct kuc_hdr                  *kuch;
3739         enum changelog_rec_flags         rec_fmt = DEFAULT_RECORD_FMT;
3740         int                              rc = 0;
3741
3742         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
3743                 return -EINVAL;
3744         if (rech == NULL)
3745                 return -EINVAL;
3746         kuch = malloc(KUC_CHANGELOG_MSG_MAXSIZE);
3747         if (kuch == NULL)
3748                 return -ENOMEM;
3749
3750         if (cp->flags & CHANGELOG_FLAG_JOBID)
3751                 rec_fmt |= CLF_JOBID;
3752
3753 repeat:
3754         rc = libcfs_ukuc_msg_get(&cp->kuc, (char *)kuch,
3755                                  KUC_CHANGELOG_MSG_MAXSIZE,
3756                                  KUC_TRANSPORT_CHANGELOG);
3757         if (rc < 0)
3758                 goto out_free;
3759
3760         if ((kuch->kuc_transport != KUC_TRANSPORT_CHANGELOG) ||
3761             ((kuch->kuc_msgtype != CL_RECORD) &&
3762              (kuch->kuc_msgtype != CL_EOF))) {
3763                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3764                                   "Unknown changelog message type %d:%d\n",
3765                                   kuch->kuc_transport, kuch->kuc_msgtype);
3766                 rc = -EPROTO;
3767                 goto out_free;
3768         }
3769
3770         if (kuch->kuc_msgtype == CL_EOF) {
3771                 if (cp->flags & CHANGELOG_FLAG_FOLLOW) {
3772                         /* Ignore EOFs */
3773                         goto repeat;
3774                 } else {
3775                         rc = 1;
3776                         goto out_free;
3777                 }
3778         }
3779
3780         /* Our message is a changelog_rec.  Use pointer math to skip
3781          * kuch_hdr and point directly to the message payload. */
3782         *rech = (struct changelog_rec *)(kuch + 1);
3783         changelog_remap_rec(*rech, rec_fmt);
3784
3785         return 0;
3786
3787 out_free:
3788         *rech = NULL;
3789         free(kuch);
3790         return rc;
3791 }
3792
3793 /** Release the changelog record when done with it. */
3794 int llapi_changelog_free(struct changelog_rec **rech)
3795 {
3796         if (*rech) {
3797                 /* We allocated memory starting at the kuc_hdr, but passed
3798                  * the consumer a pointer to the payload.
3799                  * Use pointer math to get back to the header.
3800                  */
3801                 struct kuc_hdr *kuch = (struct kuc_hdr *)*rech - 1;
3802                 free(kuch);
3803         }
3804         *rech = NULL;
3805         return 0;
3806 }
3807
3808 int llapi_changelog_clear(const char *mdtname, const char *idstr,
3809                           long long endrec)
3810 {
3811         long id;
3812
3813         if (endrec < 0) {
3814                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3815                                   "can't purge negative records\n");
3816                 return -EINVAL;
3817         }
3818
3819         id = strtol(idstr + strlen(CHANGELOG_USER_PREFIX), NULL, 10);
3820         if ((id == 0) || (strncmp(idstr, CHANGELOG_USER_PREFIX,
3821                                   strlen(CHANGELOG_USER_PREFIX)) != 0)) {
3822                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3823                                   "expecting id of the form '"
3824                                   CHANGELOG_USER_PREFIX
3825                                   "<num>'; got '%s'\n", idstr);
3826                 return -EINVAL;
3827         }
3828
3829         return changelog_ioctl(mdtname, OBD_IOC_CHANGELOG_CLEAR, id, endrec, 0);
3830 }
3831
3832 int llapi_fid2path(const char *device, const char *fidstr, char *buf,
3833                    int buflen, long long *recno, int *linkno)
3834 {
3835         const char *fidstr_orig = fidstr;
3836         struct lu_fid fid;
3837         struct getinfo_fid2path *gf;
3838         int rc;
3839
3840         while (*fidstr == '[')
3841                 fidstr++;
3842
3843         sscanf(fidstr, SFID, RFID(&fid));
3844         if (!fid_is_sane(&fid)) {
3845                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3846                                   "bad FID format '%s', should be [seq:oid:ver]"
3847                                   " (e.g. "DFID")\n", fidstr_orig,
3848                                   (unsigned long long)FID_SEQ_NORMAL, 2, 0);
3849                 return -EINVAL;
3850         }
3851
3852         gf = malloc(sizeof(*gf) + buflen);
3853         if (gf == NULL)
3854                 return -ENOMEM;
3855
3856         gf->gf_fid = fid;
3857         gf->gf_recno = *recno;
3858         gf->gf_linkno = *linkno;
3859         gf->gf_pathlen = buflen;
3860
3861         /* Take path or fsname */
3862         rc = root_ioctl(device, OBD_IOC_FID2PATH, gf, NULL, 0);
3863         if (rc)
3864                 goto out_free;
3865
3866         memcpy(buf, gf->gf_u.gf_path, gf->gf_pathlen);
3867         if (buf[0] == '\0') { /* ROOT path */
3868                 buf[0] = '/';
3869                 buf[1] = '\0';
3870         }
3871         *recno = gf->gf_recno;
3872         *linkno = gf->gf_linkno;
3873
3874 out_free:
3875         free(gf);
3876         return rc;
3877 }
3878
3879 static int fid_from_lma(const char *path, const int fd, lustre_fid *fid)
3880 {
3881         char                     buf[512];
3882         struct lustre_mdt_attrs *lma;
3883         int                      rc;
3884
3885         if (path == NULL)
3886                 rc = fgetxattr(fd, XATTR_NAME_LMA, buf, sizeof(buf));
3887         else
3888                 rc = lgetxattr(path, XATTR_NAME_LMA, buf, sizeof(buf));
3889         if (rc < 0)
3890                 return -errno;
3891         lma = (struct lustre_mdt_attrs *)buf;
3892         fid_le_to_cpu(fid, &lma->lma_self_fid);
3893         return 0;
3894 }
3895
3896 int llapi_get_mdt_index_by_fid(int fd, const lustre_fid *fid,
3897                                int *mdt_index)
3898 {
3899         int     rc;
3900
3901         rc = ioctl(fd, LL_IOC_FID2MDTIDX, fid);
3902         if (rc < 0)
3903                 return -errno;
3904
3905         *mdt_index = rc;
3906
3907         return rc;
3908 }
3909
3910 int llapi_fd2fid(const int fd, lustre_fid *fid)
3911 {
3912         int rc;
3913
3914         memset(fid, 0, sizeof(*fid));
3915
3916         rc = ioctl(fd, LL_IOC_PATH2FID, fid) < 0 ? -errno : 0;
3917         if (rc == -EINVAL || rc == -ENOTTY)
3918                 rc = fid_from_lma(NULL, fd, fid);
3919
3920         return rc;
3921 }
3922
3923 int llapi_path2fid(const char *path, lustre_fid *fid)
3924 {
3925         int fd, rc;
3926
3927         memset(fid, 0, sizeof(*fid));
3928         fd = open(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
3929         if (fd < 0) {
3930                 if (errno == ELOOP || errno == ENXIO)
3931                         return fid_from_lma(path, -1, fid);
3932                 return -errno;
3933         }
3934
3935         rc = llapi_fd2fid(fd, fid);
3936         if (rc == -EINVAL || rc == -ENOTTY)
3937                 rc = fid_from_lma(path, -1, fid);
3938
3939         close(fd);
3940         return rc;
3941 }
3942
3943 int llapi_fd2parent(int fd, unsigned int linkno, lustre_fid *parent_fid,
3944                     char *name, size_t name_size)
3945 {
3946         struct getparent        *gp;
3947         int                      rc;
3948
3949         gp = malloc(sizeof(*gp) + name_size);
3950         if (gp == NULL)
3951                 return -ENOMEM;
3952
3953         gp->gp_linkno = linkno;
3954         gp->gp_name_size = name_size;
3955
3956         rc = ioctl(fd, LL_IOC_GETPARENT, gp);
3957         if (rc < 0) {
3958                 rc = -errno;
3959                 goto err_free;
3960         }
3961
3962         *parent_fid = gp->gp_fid;
3963
3964         strncpy(name, gp->gp_name, name_size);
3965         name[name_size - 1] = '\0';
3966
3967 err_free:
3968         free(gp);
3969         return rc;
3970 }
3971
3972 int llapi_path2parent(const char *path, unsigned int linkno,
3973                       lustre_fid *parent_fid, char *name, size_t name_size)
3974 {
3975         int     fd;
3976         int     rc;
3977
3978         fd = open(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
3979         if (fd < 0)
3980                 return -errno;
3981
3982         rc = llapi_fd2parent(fd, linkno, parent_fid, name, name_size);
3983         close(fd);
3984         return rc;
3985 }
3986
3987 int llapi_get_connect_flags(const char *mnt, __u64 *flags)
3988 {
3989         DIR *root;
3990         int rc;
3991
3992         root = opendir(mnt);
3993         if (!root) {
3994                 rc = -errno;
3995                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
3996                 return rc;
3997         }
3998
3999         rc = ioctl(dirfd(root), LL_IOC_GET_CONNECT_FLAGS, flags);
4000         if (rc < 0) {
4001                 rc = -errno;
4002                 llapi_error(LLAPI_MSG_ERROR, rc,
4003                             "ioctl on %s for getting connect flags failed", mnt);
4004         }
4005         closedir(root);
4006         return rc;
4007 }
4008
4009 /**
4010  * Get a 64-bit value representing the version of file data pointed by fd.
4011  *
4012  * Each write or truncate, flushed on OST, will change this value. You can use
4013  * this value to verify if file data was modified. This only checks the file
4014  * data, not metadata.
4015  *
4016  * \param  flags  0: no flush pages, usually used it the process has already
4017  *                  taken locks;
4018  *                LL_DV_RD_FLUSH: OSTs will take LCK_PR to flush dirty pages
4019  *                  from clients;
4020  *                LL_DV_WR_FLUSH: OSTs will take LCK_PW to flush all caching
4021  *                  pages from clients.
4022  *
4023  * \retval 0 on success.
4024  * \retval -errno on error.
4025  */
4026 int llapi_get_data_version(int fd, __u64 *data_version, __u64 flags)
4027 {
4028         int rc;
4029         struct ioc_data_version idv;
4030
4031         idv.idv_flags = flags;
4032
4033         rc = ioctl(fd, LL_IOC_DATA_VERSION, &idv);
4034         if (rc)
4035                 rc = -errno;
4036         else
4037                 *data_version = idv.idv_version;
4038
4039         return rc;
4040 }
4041
4042 /*
4043  * Create a file without any name open it for read/write
4044  *
4045  * - file is created as if it were a standard file in the given \a directory
4046  * - file does not appear in \a directory and mtime does not change because
4047  *   the filename is handled specially by the Lustre MDS.
4048  * - file is removed at final close
4049  * - file modes are rw------- since it doesn't make sense to have a read-only
4050  *   or write-only file that cannot be opened again.
4051  * - if user wants another mode it must use fchmod() on the open file, no
4052  *   security problems arise because it cannot be opened by another process.
4053  *
4054  * \param[in]   directory       directory from which to inherit layout/MDT idx
4055  * \param[in]   idx             MDT index on which the file is created,
4056  *                              \a idx == -1 means no specific MDT is requested
4057  * \param[in]   open_flags      standard open(2) flags
4058  *
4059  * \retval      0 on success.
4060  * \retval      -errno on error.
4061  */
4062 int llapi_create_volatile_idx(char *directory, int idx, int open_flags)
4063 {
4064         char    file_path[PATH_MAX];
4065         char    filename[PATH_MAX];
4066         int     saved_errno = errno;
4067         int     fd;
4068         int     rnumber;
4069         int     rc;
4070
4071         do {
4072                 rnumber = random();
4073                 if (idx == -1)
4074                         snprintf(filename, sizeof(filename),
4075                                  LUSTRE_VOLATILE_HDR"::%.4X", rnumber);
4076                 else
4077                         snprintf(filename, sizeof(filename),
4078                                  LUSTRE_VOLATILE_HDR":%.4X:%.4X", idx, rnumber);
4079
4080                 rc = snprintf(file_path, sizeof(file_path),
4081                               "%s/%s", directory, filename);
4082                 if (rc >= sizeof(file_path))
4083                         return -E2BIG;
4084
4085                 fd = open(file_path,
4086                           O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | open_flags,
4087                           S_IRUSR | S_IWUSR);
4088         } while (fd < 0 && errno == EEXIST);
4089
4090         if (fd < 0) {
4091                 llapi_error(LLAPI_MSG_ERROR, errno,
4092                             "Cannot create volatile file '%s' in '%s'",
4093                             filename + LUSTRE_VOLATILE_HDR_LEN,
4094                             directory);
4095                 return -errno;
4096         }
4097
4098         /* Unlink file in case this wasn't a Lustre filesystem and the
4099          * magic volatile filename wasn't handled as intended. The
4100          * effect is the same. If volatile open was supported then we
4101          * expect unlink() to return -ENOENT. */
4102         (void)unlink(file_path);
4103
4104         /* Since we are returning successfully we restore errno (and
4105          * mask out possible EEXIST from open() and ENOENT from
4106          * unlink(). */
4107         errno = saved_errno;
4108
4109         return fd;
4110 }
4111
4112 /**
4113  * Swap the layouts between 2 file descriptors
4114  * the 2 files must be open for writing
4115  * first fd received the ioctl, second fd is passed as arg
4116  * this is assymetric but avoid use of root path for ioctl
4117  */
4118 int llapi_fswap_layouts_grouplock(int fd1, int fd2, __u64 dv1, __u64 dv2,
4119                                   int gid, __u64 flags)
4120 {
4121         struct lustre_swap_layouts      lsl;
4122         struct stat                     st1;
4123         struct stat                     st2;
4124         int                             rc;
4125
4126         if (flags & (SWAP_LAYOUTS_KEEP_ATIME | SWAP_LAYOUTS_KEEP_MTIME)) {
4127                 rc = fstat(fd1, &st1);
4128                 if (rc < 0)
4129                         return -errno;
4130
4131                 rc = fstat(fd2, &st2);
4132                 if (rc < 0)
4133                         return -errno;
4134         }
4135         lsl.sl_fd = fd2;
4136         lsl.sl_flags = flags;
4137         lsl.sl_gid = gid;
4138         lsl.sl_dv1 = dv1;
4139         lsl.sl_dv2 = dv2;
4140         rc = ioctl(fd1, LL_IOC_LOV_SWAP_LAYOUTS, &lsl);
4141         if (rc < 0)
4142                 return -errno;
4143
4144         if (flags & (SWAP_LAYOUTS_KEEP_ATIME | SWAP_LAYOUTS_KEEP_MTIME)) {
4145                 struct timeval  tv1[2];
4146                 struct timeval  tv2[2];
4147
4148                 memset(tv1, 0, sizeof(tv1));
4149                 memset(tv2, 0, sizeof(tv2));
4150
4151                 if (flags & SWAP_LAYOUTS_KEEP_ATIME) {
4152                         tv1[0].tv_sec = st1.st_atime;
4153                         tv2[0].tv_sec = st2.st_atime;
4154                 } else {
4155                         tv1[0].tv_sec = st2.st_atime;
4156                         tv2[0].tv_sec = st1.st_atime;
4157                 }
4158
4159                 if (flags & SWAP_LAYOUTS_KEEP_MTIME) {
4160                         tv1[1].tv_sec = st1.st_mtime;
4161                         tv2[1].tv_sec = st2.st_mtime;
4162                 } else {
4163                         tv1[1].tv_sec = st2.st_mtime;
4164                         tv2[1].tv_sec = st1.st_mtime;
4165                 }
4166
4167                 rc = futimes(fd1, tv1);
4168                 if (rc < 0)
4169                         return -errno;
4170
4171                 rc = futimes(fd2, tv2);
4172                 if (rc < 0)
4173                         return -errno;
4174         }
4175
4176         return 0;
4177 }
4178
4179 int llapi_fswap_layouts(int fd1, int fd2, __u64 dv1, __u64 dv2, __u64 flags)
4180 {
4181         int     rc;
4182         int     grp_id;
4183
4184         do
4185                 grp_id = random();
4186         while (grp_id == 0);
4187
4188         rc = llapi_fswap_layouts_grouplock(fd1, fd2, dv1, dv2, grp_id, flags);
4189         if (rc < 0)
4190                 return rc;
4191
4192         return 0;
4193 }
4194
4195 /**
4196  * Swap the layouts between 2 files
4197  * the 2 files are open in write
4198  */
4199 int llapi_swap_layouts(const char *path1, const char *path2,
4200                        __u64 dv1, __u64 dv2, __u64 flags)
4201 {
4202         int     fd1, fd2, rc;
4203
4204         fd1 = open(path1, O_WRONLY | O_LOV_DELAY_CREATE);
4205         if (fd1 < 0) {
4206                 rc = -errno;
4207                 llapi_error(LLAPI_MSG_ERROR, rc,
4208                             "error: cannot open '%s' for write", path1);
4209                 goto out;
4210         }
4211
4212         fd2 = open(path2, O_WRONLY | O_LOV_DELAY_CREATE);
4213         if (fd2 < 0) {
4214                 rc = -errno;
4215                 llapi_error(LLAPI_MSG_ERROR, rc,
4216                             "error: cannot open '%s' for write", path2);
4217                 goto out_close;
4218         }
4219
4220         rc = llapi_fswap_layouts(fd1, fd2, dv1, dv2, flags);
4221         if (rc < 0)
4222                 llapi_error(LLAPI_MSG_ERROR, rc,
4223                             "error: cannot swap layout between '%s' and '%s'",
4224                             path1, path2);
4225
4226         close(fd2);
4227 out_close:
4228         close(fd1);
4229 out:
4230         return rc;
4231 }
4232
4233 /**
4234  * Attempt to open a file with Lustre file identifier \a fid
4235  * and return an open file descriptor.
4236  *
4237  * \param[in] lustre_dir        path within Lustre filesystem containing \a fid
4238  * \param[in] fid               Lustre file identifier of file to open
4239  * \param[in] flags             open() flags
4240  *
4241  * \retval                      non-negative file descriptor on successful open
4242  * \retval                      -1 if an error occurred
4243  */
4244 int llapi_open_by_fid(const char *lustre_dir, const lustre_fid *fid, int flags)
4245 {
4246         char mntdir[PATH_MAX];
4247         char path[PATH_MAX];
4248         int rc;
4249
4250         rc = llapi_search_mounts(lustre_dir, 0, mntdir, NULL);
4251         if (rc != 0)
4252                 return -1;
4253
4254         snprintf(path, sizeof(path), "%s/.lustre/fid/"DFID, mntdir, PFID(fid));
4255         return open(path, flags);
4256 }
4257
4258 /**
4259  * Take group lock.
4260  *
4261  * \param fd   File to lock.
4262  * \param gid  Group Identifier.
4263  *
4264  * \retval 0 on success.
4265  * \retval -errno on failure.
4266  */
4267 int llapi_group_lock(int fd, int gid)
4268 {
4269         int rc;
4270
4271         rc = ioctl(fd, LL_IOC_GROUP_LOCK, gid);
4272         if (rc < 0) {
4273                 rc = -errno;
4274                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot get group lock");
4275         }
4276         return rc;
4277 }
4278
4279 /**
4280  * Put group lock.
4281  *
4282  * \param fd   File to unlock.
4283  * \param gid  Group Identifier.
4284  *
4285  * \retval 0 on success.
4286  * \retval -errno on failure.
4287  */
4288 int llapi_group_unlock(int fd, int gid)
4289 {
4290         int rc;
4291
4292         rc = ioctl(fd, LL_IOC_GROUP_UNLOCK, gid);
4293         if (rc < 0) {
4294                 rc = -errno;
4295                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot put group lock");
4296         }
4297         return rc;
4298 }