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