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