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