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