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