Whamcloud - gitweb
b=13698 llapi_get_version
[fs/lustre-release.git] / lustre / utils / liblustreapi.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
30  * Use is subject to license terms.
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 <ctype.h>
59 #include <sys/stat.h>
60 #include <sys/types.h>
61 #include <sys/syscall.h>
62 #include <sys/param.h>
63 #include <fnmatch.h>
64 #include <glob.h>
65 #ifdef HAVE_ASM_TYPES_H
66 #include <asm/types.h>
67 #endif
68 #ifdef HAVE_LINUX_UNISTD_H
69 #include <linux/unistd.h>
70 #else
71 #include <unistd.h>
72 #endif
73
74 #include <liblustre.h>
75 #include <lnet/lnetctl.h>
76 #include <obd.h>
77 #include <lustre_lib.h>
78 #include <lustre/liblustreapi.h>
79 #include <obd_lov.h>
80
81 static unsigned llapi_dir_filetype_table[] = {
82         [DT_UNKNOWN]= 0,
83         [DT_FIFO]= S_IFIFO,
84         [DT_CHR] = S_IFCHR,
85         [DT_DIR] = S_IFDIR,
86         [DT_BLK] = S_IFBLK,
87         [DT_REG] = S_IFREG,
88         [DT_LNK] = S_IFLNK,
89         [DT_SOCK]= S_IFSOCK,
90 #if defined(DT_DOOR) && defined(S_IFDOOR)
91         [DT_DOOR]= S_IFDOOR,
92 #endif
93 };
94
95 #if defined(DT_DOOR) && defined(S_IFDOOR)
96 static const int DT_MAX = DT_DOOR;
97 #else
98 static const int DT_MAX = DT_SOCK;
99 #endif
100
101 static unsigned llapi_filetype_dir_table[] = {
102         [0]= DT_UNKNOWN,
103         [S_IFIFO]= DT_FIFO,
104         [S_IFCHR] = DT_CHR,
105         [S_IFDIR] = DT_DIR,
106         [S_IFBLK] = DT_BLK,
107         [S_IFREG] = DT_REG,
108         [S_IFLNK] = DT_LNK,
109         [S_IFSOCK]= DT_SOCK,
110 #if defined(DT_DOOR) && defined(S_IFDOOR)
111         [S_IFDOOR]= DT_DOOR,
112 #endif
113 };
114
115 #if defined(DT_DOOR) && defined(S_IFDOOR)
116 static const int S_IFMAX = DT_DOOR;
117 #else
118 static const int S_IFMAX = DT_SOCK;
119 #endif
120
121 /* liblustreapi message level */
122 static int llapi_msg_level = LLAPI_MSG_MAX;
123
124 void llapi_msg_set_level(int level)
125 {
126         /* ensure level is in the good range */
127         if (level < LLAPI_MSG_OFF)
128                 llapi_msg_level = LLAPI_MSG_OFF;
129         else if (level > LLAPI_MSG_MAX)
130                 llapi_msg_level = LLAPI_MSG_MAX;
131         else
132                 llapi_msg_level = level;
133 }
134
135 void llapi_err(int level, char *fmt, ...)
136 {
137         va_list args;
138         int tmp_errno = abs(errno);
139
140         if ((level & LLAPI_MSG_MASK) > llapi_msg_level)
141                 return;
142
143         va_start(args, fmt);
144         vfprintf(stderr, fmt, args);
145         va_end(args);
146
147         if (level & LLAPI_MSG_NO_ERRNO)
148                 fprintf(stderr, "\n");
149         else
150                 fprintf(stderr, ": %s (%d)\n", strerror(tmp_errno), tmp_errno);
151 }
152
153 #define llapi_err_noerrno(level, fmt, a...)                             \
154         llapi_err((level) | LLAPI_MSG_NO_ERRNO, fmt, ## a)
155
156 void llapi_printf(int level, char *fmt, ...)
157 {
158         va_list args;
159
160         if ((level & LLAPI_MSG_MASK) > llapi_msg_level)
161                 return;
162
163         va_start(args, fmt);
164         vfprintf(stdout, fmt, args);
165         va_end(args);
166 }
167
168 /* size_units is unchanged if no specifier used */
169 int parse_size(char *optarg, unsigned long long *size,
170                unsigned long long *size_units, int bytes_spec)
171 {
172         char *end;
173
174         *size = strtoull(optarg, &end, 0);
175
176         if (*end != '\0') {
177                 if ((*end == 'b') && *(end+1) == '\0' &&
178                     (*size & (~0ULL << (64 - 9))) == 0 &&
179                     !bytes_spec) {
180                         *size <<= 9;
181                         *size_units = 1 << 9;
182                 } else if ((*end == 'b') && *(end+1) == '\0' &&
183                            bytes_spec) {
184                         *size_units = 1;
185                 } else if ((*end == 'k' || *end == 'K') &&
186                            *(end+1) == '\0' && (*size &
187                            (~0ULL << (64 - 10))) == 0) {
188                         *size <<= 10;
189                         *size_units = 1 << 10;
190                 } else if ((*end == 'm' || *end == 'M') &&
191                            *(end+1) == '\0' && (*size &
192                            (~0ULL << (64 - 20))) == 0) {
193                         *size <<= 20;
194                         *size_units = 1 << 20;
195                 } else if ((*end == 'g' || *end == 'G') &&
196                            *(end+1) == '\0' && (*size &
197                            (~0ULL << (64 - 30))) == 0) {
198                         *size <<= 30;
199                         *size_units = 1 << 30;
200                 } else if ((*end == 't' || *end == 'T') &&
201                            *(end+1) == '\0' && (*size &
202                            (~0ULL << (64 - 40))) == 0) {
203                         *size <<= 40;
204                         *size_units = 1ULL << 40;
205                 } else if ((*end == 'p' || *end == 'P') &&
206                            *(end+1) == '\0' && (*size &
207                            (~0ULL << (64 - 50))) == 0) {
208                         *size <<= 50;
209                         *size_units = 1ULL << 50;
210                 } else if ((*end == 'e' || *end == 'E') &&
211                            *(end+1) == '\0' && (*size &
212                            (~0ULL << (64 - 60))) == 0) {
213                         *size <<= 60;
214                         *size_units = 1ULL << 60;
215                 } else {
216                         return -1;
217                 }
218         }
219
220         return 0;
221 }
222
223 int llapi_stripe_limit_check(unsigned long long stripe_size, int stripe_offset,
224                              int stripe_count, int stripe_pattern)
225 {
226         int page_size;
227
228         /* 64 KB is the largest common page size I'm aware of (on ia64), but
229          * check the local page size just in case. */
230         page_size = LOV_MIN_STRIPE_SIZE;
231         if (getpagesize() > page_size) {
232                 page_size = getpagesize();
233                 llapi_err_noerrno(LLAPI_MSG_WARN,
234                                   "warning: your page size (%u) is "
235                                   "larger than expected (%u)", page_size,
236                                   LOV_MIN_STRIPE_SIZE);
237         }
238         if (stripe_size < 0 || (stripe_size & (LOV_MIN_STRIPE_SIZE - 1))) {
239                 errno = -EINVAL;
240                 llapi_err(LLAPI_MSG_ERROR, "error: bad stripe_size %lu, "
241                           "must be an even multiple of %d bytes",
242                           stripe_size, page_size);
243                 return errno;
244         }
245         if (stripe_offset < -1 || stripe_offset > MAX_OBD_DEVICES) {
246                 errno = -EINVAL;
247                 llapi_err(LLAPI_MSG_ERROR, "error: bad stripe offset %d",
248                           stripe_offset);
249                 return errno;
250         }
251         if (stripe_count < -1 || stripe_count > LOV_MAX_STRIPE_COUNT) {
252                 errno = -EINVAL;
253                 llapi_err(LLAPI_MSG_ERROR, "error: bad stripe count %d",
254                           stripe_count);
255                 return errno;
256         }
257         if (stripe_size >= (1ULL << 32)) {
258                 errno = -EINVAL;
259                 llapi_err(LLAPI_MSG_ERROR, "warning: stripe size larger than 4G"
260                           " is not currently supported and would wrap");
261                 return errno;
262         }
263         return 0;
264 }
265
266 static int find_target_obdpath(char *fsname, char *path)
267 {
268         glob_t glob_info;
269         char pattern[PATH_MAX + 1];
270         int rc;
271
272         snprintf(pattern, PATH_MAX,
273                  "/proc/fs/lustre/lov/%s-*/target_obd",
274                  fsname);
275         rc = glob(pattern, GLOB_BRACE, NULL, &glob_info);
276         if (rc == GLOB_NOMATCH)
277                 return -ENODEV;
278         else if (rc)
279                 return -EINVAL;
280
281         strcpy(path, glob_info.gl_pathv[0]);
282         globfree(&glob_info);
283         return 0;
284 }
285
286 static int find_poolpath(char *fsname, char *poolname, char *poolpath)
287 {
288         glob_t glob_info;
289         char pattern[PATH_MAX + 1];
290         int rc;
291
292         snprintf(pattern, PATH_MAX,
293                  "/proc/fs/lustre/lov/%s-*/pools/%s",
294                  fsname, poolname);
295         rc = glob(pattern, GLOB_BRACE, NULL, &glob_info);
296         /* If no pools, make sure the lov is available */
297         if ((rc == GLOB_NOMATCH) &&
298             (find_target_obdpath(fsname, poolpath) == -ENODEV))
299                 return -ENODEV;
300         if (rc)
301                 return -EINVAL;
302
303         strcpy(poolpath, glob_info.gl_pathv[0]);
304         globfree(&glob_info);
305         return 0;
306 }
307
308 /*
309  * if pool is NULL, search ostname in target_obd
310  * if pool is not NULL:
311  *  if pool not found returns errno < 0
312  *  if ostname is NULL, returns 1 if pool is not empty and 0 if pool empty
313  *  if ostname is not NULL, returns 1 if OST is in pool and 0 if not
314  */
315 int llapi_search_ost(char *fsname, char *poolname, char *ostname)
316 {
317         FILE *fd;
318         char buffer[PATH_MAX + 1];
319         int len = 0, rc;
320
321         if (ostname != NULL)
322                 len = strlen(ostname);
323
324         if (poolname == NULL)
325                 rc = find_target_obdpath(fsname, buffer);
326         else
327                 rc = find_poolpath(fsname, poolname, buffer);
328         if (rc)
329                 return rc;
330
331         if ((fd = fopen(buffer, "r")) == NULL)
332                 return -EINVAL;
333
334         while (fgets(buffer, sizeof(buffer), fd) != NULL) {
335                 if (poolname == NULL) {
336                         char *ptr;
337                         /* Search for an ostname in the list of OSTs
338                          Line format is IDX: fsname-OSTxxxx_UUID STATUS */
339                         ptr = strchr(buffer, ' ');
340                         if ((ptr != NULL) &&
341                             (strncmp(ptr + 1, ostname, len) == 0)) {
342                                 fclose(fd);
343                                 return 1;
344                         }
345                 } else {
346                         /* Search for an ostname in a pool,
347                          (or an existing non-empty pool if no ostname) */
348                         if ((ostname == NULL) ||
349                             (strncmp(buffer, ostname, len) == 0)) {
350                                 fclose(fd);
351                                 return 1;
352                         }
353                 }
354         }
355         fclose(fd);
356         return 0;
357 }
358
359 int llapi_file_open_pool(const char *name, int flags, int mode,
360                          unsigned long long stripe_size, int stripe_offset,
361                          int stripe_count, int stripe_pattern, char *pool_name)
362 {
363         struct lov_user_md_v3 lum = { 0 };
364         int fd, rc = 0;
365         int isdir = 0;
366
367         /* Make sure we have a good pool */
368         if (pool_name != NULL) {
369                 char fsname[MAX_OBD_NAME + 1], *ptr;
370
371                 if (llapi_search_fsname(name, fsname)) {
372                     llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
373                               "'%s' is not on a Lustre filesystem", name);
374                     return -EINVAL;
375                 }
376
377                 /* in case user gives the full pool name <fsname>.<poolname>,
378                  * strip the fsname */
379                 ptr = strchr(pool_name, '.');
380                 if (ptr != NULL) {
381                         *ptr = '\0';
382                         if (strcmp(pool_name, fsname) != 0) {
383                                 *ptr = '.';
384                                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
385                                    "Pool '%s' is not on filesystem '%s'",
386                                    pool_name, fsname);
387                                 return -EINVAL;
388                         }
389                         pool_name = ptr + 1;
390                 }
391
392                 /* Make sure the pool exists and is non-empty */
393                 if ((rc = llapi_search_ost(fsname, pool_name, NULL)) < 1) {
394                         llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
395                                   "pool '%s.%s' %s", fsname, pool_name,
396                                   rc == 0 ? "has no OSTs" : "does not exist");
397                         return -EINVAL;
398                 }
399         }
400
401         fd = open(name, flags | O_LOV_DELAY_CREATE, mode);
402         if (fd < 0 && errno == EISDIR) {
403                 fd = open(name, O_DIRECTORY | O_RDONLY);
404                 isdir++;
405         }
406
407         if (fd < 0) {
408                 rc = -errno;
409                 llapi_err(LLAPI_MSG_ERROR, "unable to open '%s'", name);
410                 return rc;
411         }
412
413         if ((rc = llapi_stripe_limit_check(stripe_size, stripe_offset,
414                                            stripe_count, stripe_pattern)) != 0){
415                 errno = rc;
416                 goto out;
417         }
418
419         /*  Initialize IOCTL striping pattern structure */
420         lum.lmm_magic = LOV_USER_MAGIC_V3;
421         lum.lmm_pattern = stripe_pattern;
422         lum.lmm_stripe_size = stripe_size;
423         lum.lmm_stripe_count = stripe_count;
424         lum.lmm_stripe_offset = stripe_offset;
425         if (pool_name != NULL) {
426                 strncpy(lum.lmm_pool_name, pool_name, LOV_MAXPOOLNAME);
427         } else {
428                 /* If no pool is specified at all, use V1 request */
429                 lum.lmm_magic = LOV_USER_MAGIC_V1;
430         }
431
432         if (ioctl(fd, LL_IOC_LOV_SETSTRIPE, &lum)) {
433                 char *errmsg = "stripe already set";
434                 rc = -errno;
435                 if (errno != EEXIST && errno != EALREADY)
436                         errmsg = strerror(errno);
437
438                 llapi_err_noerrno(LLAPI_MSG_ERROR,
439                                   "error on ioctl "LPX64" for '%s' (%d): %s",
440                                   (__u64)LL_IOC_LOV_SETSTRIPE, name, fd,errmsg);
441         }
442 out:
443         if (rc) {
444                 close(fd);
445                 fd = rc;
446         }
447
448         return fd;
449 }
450
451 int llapi_file_open(const char *name, int flags, int mode,
452                     unsigned long long stripe_size, int stripe_offset,
453                     int stripe_count, int stripe_pattern)
454 {
455         return llapi_file_open_pool(name, flags, mode, stripe_size,
456                                     stripe_offset, stripe_count,
457                                     stripe_pattern, NULL);
458 }
459
460 int llapi_file_create(const char *name, unsigned long long stripe_size,
461                       int stripe_offset, int stripe_count, int stripe_pattern)
462 {
463         int fd;
464
465         fd = llapi_file_open_pool(name, O_CREAT | O_WRONLY, 0644, stripe_size,
466                                   stripe_offset, stripe_count, stripe_pattern,
467                                   NULL);
468         if (fd < 0)
469                 return fd;
470
471         close(fd);
472         return 0;
473 }
474
475 int llapi_file_create_pool(const char *name, unsigned long long stripe_size,
476                            int stripe_offset, int stripe_count,
477                            int stripe_pattern, char *pool_name)
478 {
479         int fd;
480
481         fd = llapi_file_open_pool(name, O_CREAT | O_WRONLY, 0644, stripe_size,
482                                   stripe_offset, stripe_count, stripe_pattern,
483                                   pool_name);
484         if (fd < 0)
485                 return fd;
486
487         close(fd);
488         return 0;
489 }
490
491 /*
492  * Find the fsname, the full path, and/or an open fd.
493  * Either the fsname or path must not be NULL
494  */
495 #define WANT_PATH   0x1
496 #define WANT_FSNAME 0x2
497 #define WANT_FD     0x4
498 #define WANT_INDEX  0x8
499 #define WANT_ERROR  0x10
500 static int get_root_path(int want, char *fsname, int *outfd, char *path,
501                          int index)
502 {
503         struct mntent mnt;
504         char buf[PATH_MAX], mntdir[PATH_MAX];
505         char *ptr;
506         FILE *fp;
507         int idx = 0, len = 0, mntlen, fd;
508         int rc = -ENODEV;
509
510         /* get the mount point */
511         fp = setmntent(MOUNTED, "r");
512         if (fp == NULL) {
513                  llapi_err(LLAPI_MSG_ERROR,
514                            "setmntent(%s) failed: %s:", MOUNTED,
515                            strerror (errno));
516                  return -EIO;
517         }
518         while (1) {
519                 if (getmntent_r(fp, &mnt, buf, sizeof(buf)) == NULL)
520                         break;
521
522                 if (!llapi_is_lustre_mnt(&mnt))
523                         continue;
524
525                 if ((want & WANT_INDEX) && (idx++ != index))
526                         continue;
527
528                 mntlen = strlen(mnt.mnt_dir);
529                 ptr = strrchr(mnt.mnt_fsname, '/');
530                 if (!ptr && !len) {
531                         rc = -EINVAL;
532                         break;
533                 }
534                 ptr++;
535
536                 /* Check the fsname for a match, if given */
537                 if (!(want & WANT_FSNAME) && fsname != NULL &&
538                     (strlen(fsname) > 0) && (strcmp(ptr, fsname) != 0))
539                         continue;
540
541                 /* If the path isn't set return the first one we find */
542                 if (path == NULL || strlen(path) == 0) {
543                         strcpy(mntdir, mnt.mnt_dir);
544                         if ((want & WANT_FSNAME) && fsname != NULL)
545                                 strcpy(fsname, ptr);
546                         rc = 0;
547                         break;
548                 /* Otherwise find the longest matching path */
549                 } else if ((strlen(path) >= mntlen) && (mntlen >= len) &&
550                            (strncmp(mnt.mnt_dir, path, mntlen) == 0)) {
551                         strcpy(mntdir, mnt.mnt_dir);
552                         len = mntlen;
553                         if ((want & WANT_FSNAME) && fsname != NULL)
554                                 strcpy(fsname, ptr);
555                         rc = 0;
556                 }
557         }
558         endmntent(fp);
559
560         /* Found it */
561         if (rc == 0) {
562                 if ((want & WANT_PATH) && path != NULL)
563                         strcpy(path, mntdir);
564                 if (want & WANT_FD) {
565                         fd = open(mntdir, O_RDONLY | O_DIRECTORY | O_NONBLOCK);
566                         if (fd < 0) {
567                                 perror("open");
568                                 rc = -errno;
569                         } else {
570                                 *outfd = fd;
571                         }
572                 }
573         } else if (want & WANT_ERROR)
574                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
575                           "can't find fs root for '%s': %d",
576                           (want & WANT_PATH) ? fsname : path, rc);
577         return rc;
578 }
579
580 /*
581  * search lustre mounts
582  *
583  * Calling this function will return to the user the mount point, mntdir, and
584  * the file system name, fsname, if the user passed a buffer to this routine.
585  *
586  * The user inputs are pathname and index. If the pathname is supplied then
587  * the value of the index will be ignored. The pathname will return data if
588  * the pathname is located on a lustre mount. Index is used to pick which
589  * mount point you want in the case of multiple mounted lustre file systems.
590  * See function lfs_osts in lfs.c for a example of the index use.
591  */
592 int llapi_search_mounts(const char *pathname, int index, char *mntdir,
593                         char *fsname)
594 {
595         int want = WANT_PATH, idx = -1;
596
597         if (!pathname || pathname[0] == '\0') {
598                 want |= WANT_INDEX;
599                 idx = index;
600         } else
601                 strcpy(mntdir, pathname);
602
603         if (fsname)
604                 want |= WANT_FSNAME;
605         return get_root_path(want, fsname, NULL, mntdir, idx);
606 }
607
608 int llapi_search_fsname(const char *pathname, char *fsname)
609 {
610         char *path = (char*)pathname, buf[PATH_MAX + 1];
611
612         if (pathname[0] != '/') { /* Need a absolute path */
613                 memset(buf, '\0', sizeof(buf));
614                 if (realpath(pathname, buf) == NULL) {
615                         llapi_err(LLAPI_MSG_ERROR, "pathname '%s' cannot expand",
616                                   pathname);
617                         return -EINVAL;
618                 }
619                 path = buf;
620         }
621         return get_root_path(WANT_FSNAME | WANT_ERROR, fsname, NULL,
622                              path, -1);
623 }
624
625 /* return the first file matching this pattern */
626 static int first_match(char *pattern, char *buffer)
627 {
628         glob_t glob_info;
629
630         if (glob(pattern, GLOB_BRACE, NULL, &glob_info))
631                 return -ENOENT;
632
633         if (glob_info.gl_pathc < 1) {
634                 globfree(&glob_info);
635                 return -ENOENT;
636         }
637
638         strcpy(buffer, glob_info.gl_pathv[0]);
639
640         globfree(&glob_info);
641         return 0;
642 }
643
644 /*
645  * find the pool directory path under /proc
646  * (can be also used to test if a fsname is known)
647  */
648 static int poolpath(char *fsname, char *pathname, char *pool_pathname)
649 {
650         int rc = 0;
651         char pattern[PATH_MAX + 1];
652         char buffer[PATH_MAX];
653
654         if (fsname == NULL) {
655                 rc = llapi_search_fsname(pathname, buffer);
656                 if (rc != 0)
657                         return rc;
658                 fsname = buffer;
659                 strcpy(pathname, fsname);
660         }
661
662         snprintf(pattern, PATH_MAX, "/proc/fs/lustre/lov/%s-*/pools", fsname);
663         rc = first_match(pattern, buffer);
664         if (rc)
665                 return rc;
666
667         /* in fsname test mode, pool_pathname is NULL */
668         if (pool_pathname != NULL)
669                 strcpy(pool_pathname, buffer);
670
671         return 0;
672 }
673
674 /**
675  * Get the list of pool members.
676  * \param poolname    string of format \<fsname\>.\<poolname\>
677  * \param members     caller-allocated array of char*
678  * \param list_size   size of the members array
679  * \param buffer      caller-allocated buffer for storing OST names
680  * \param buffer_size size of the buffer
681  *
682  * \return number of members retrieved for this pool
683  * \retval -error failure
684  */
685 int llapi_get_poolmembers(const char *poolname, char **members,
686                           int list_size, char *buffer, int buffer_size)
687 {
688         char fsname[PATH_MAX + 1];
689         char *pool, *tmp;
690         char pathname[PATH_MAX + 1];
691         char path[PATH_MAX + 1];
692         char buf[1024];
693         FILE *fd;
694         int rc = 0;
695         int nb_entries = 0;
696         int used = 0;
697
698         /* name is FSNAME.POOLNAME */
699         if (strlen(poolname) > PATH_MAX)
700                 return -EOVERFLOW;
701         strcpy(fsname, poolname);
702         pool = strchr(fsname, '.');
703         if (pool == NULL)
704                 return -EINVAL;
705
706         *pool = '\0';
707         pool++;
708
709         rc = poolpath(fsname, NULL, pathname);
710         if (rc != 0) {
711                 errno = -rc;
712                 llapi_err(LLAPI_MSG_ERROR, "Lustre filesystem '%s' not found",
713                           fsname);
714                 return rc;
715         }
716
717         llapi_printf(LLAPI_MSG_NORMAL, "Pool: %s.%s\n", fsname, pool);
718         sprintf(path, "%s/%s", pathname, pool);
719         if ((fd = fopen(path, "r")) == NULL) {
720                 llapi_err(LLAPI_MSG_ERROR, "Cannot open %s", path);
721                 return -EINVAL;
722         }
723
724         rc = 0;
725         while (fgets(buf, sizeof(buf), fd) != NULL) {
726                 if (nb_entries >= list_size) {
727                         rc = -EOVERFLOW;
728                         break;
729                 }
730                 /* remove '\n' */
731                 if ((tmp = strchr(buf, '\n')) != NULL)
732                         *tmp='\0';
733                 if (used + strlen(buf) + 1 > buffer_size) {
734                         rc = -EOVERFLOW;
735                         break;
736                 }
737
738                 strcpy(buffer + used, buf);
739                 members[nb_entries] = buffer + used;
740                 used += strlen(buf) + 1;
741                 nb_entries++;
742                 rc = nb_entries;
743         }
744
745         fclose(fd);
746         return rc;
747 }
748
749 /**
750  * Get the list of pools in a filesystem.
751  * \param name        filesystem name or path
752  * \param poollist    caller-allocated array of char*
753  * \param list_size   size of the poollist array
754  * \param buffer      caller-allocated buffer for storing pool names
755  * \param buffer_size size of the buffer
756  *
757  * \return number of pools retrieved for this filesystem
758  * \retval -error failure
759  */
760 int llapi_get_poollist(const char *name, char **poollist, int list_size,
761                        char *buffer, int buffer_size)
762 {
763         char fsname[PATH_MAX + 1], rname[PATH_MAX + 1], pathname[PATH_MAX + 1];
764         char *ptr;
765         DIR *dir;
766         struct dirent pool;
767         struct dirent *cookie = NULL;
768         int rc = 0;
769         unsigned int nb_entries = 0;
770         unsigned int used = 0;
771         unsigned int i;
772
773         /* initilize output array */
774         for (i = 0; i < list_size; i++)
775                 poollist[i] = NULL;
776
777         /* is name a pathname ? */
778         ptr = strchr(name, '/');
779         if (ptr != NULL) {
780                 /* only absolute pathname is supported */
781                 if (*name != '/')
782                         return -EINVAL;
783                 if (!realpath(name, rname)) {
784                         rc = -errno;
785                         llapi_err(LLAPI_MSG_ERROR, "invalid path '%s'", name);
786                         return rc;
787                 }
788
789                 rc = poolpath(NULL, rname, pathname);
790                 if (rc != 0) {
791                         errno = -rc;
792                         llapi_err(LLAPI_MSG_ERROR, "'%s' is not"
793                                   " a Lustre filesystem", name);
794                         return rc;
795                 }
796                 strcpy(fsname, rname);
797         } else {
798                 /* name is FSNAME */
799                 strcpy(fsname, name);
800                 rc = poolpath(fsname, NULL, pathname);
801         }
802         if (rc != 0) {
803                 errno = -rc;
804                 llapi_err(LLAPI_MSG_ERROR, "Lustre filesystem '%s' not found",
805                           name);
806                 return rc;
807         }
808
809         llapi_printf(LLAPI_MSG_NORMAL, "Pools from %s:\n", fsname);
810         if ((dir = opendir(pathname)) == NULL) {
811                 llapi_err(LLAPI_MSG_ERROR, "Could not open pool list for '%s'",
812                           name);
813                 return -errno;
814         }
815
816         while(1) {
817                 rc = readdir_r(dir, &pool, &cookie);
818
819                 if (rc != 0) {
820                         llapi_err(LLAPI_MSG_ERROR,
821                                   "Error reading pool list for '%s'", name);
822                         return -errno;
823                 } else if ((rc == 0) && (cookie == NULL))
824                         /* end of directory */
825                         break;
826
827                 /* ignore . and .. */
828                 if (!strcmp(pool.d_name, ".") || !strcmp(pool.d_name, ".."))
829                         continue;
830
831                 /* check output bounds */
832                 if (nb_entries >= list_size)
833                         return -EOVERFLOW;
834
835                 /* +2 for '.' and final '\0' */
836                 if (used + strlen(pool.d_name) + strlen(fsname) + 2
837                     > buffer_size)
838                         return -EOVERFLOW;
839
840                 sprintf(buffer + used, "%s.%s", fsname, pool.d_name);
841                 poollist[nb_entries] = buffer + used;
842                 used += strlen(pool.d_name) + strlen(fsname) + 2;
843                 nb_entries++;
844         }
845
846         closedir(dir);
847         return nb_entries;
848 }
849
850 /* wrapper for lfs.c and obd.c */
851 int llapi_poollist(const char *name)
852 {
853         /* list of pool names (assume that pool count is smaller
854            than OST count) */
855         char *list[FIND_MAX_OSTS];
856         char *buffer;
857         /* fsname-OST0000_UUID < 32 char, 1 per OST */
858         int bufsize = FIND_MAX_OSTS * 32;
859         int i, nb;
860
861         buffer = malloc(bufsize);
862         if (buffer == NULL)
863                 return -ENOMEM;
864
865         if ((name[0] == '/') || (strchr(name, '.') == NULL))
866                 /* name is a path or fsname */
867                 nb = llapi_get_poollist(name, list, FIND_MAX_OSTS, buffer,
868                                         bufsize);
869         else
870                 /* name is a pool name (<fsname>.<poolname>) */
871                 nb = llapi_get_poolmembers(name, list, FIND_MAX_OSTS, buffer,
872                                            bufsize);
873
874         for (i = 0; i < nb; i++)
875                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", list[i]);
876
877         free(buffer);
878         return (nb < 0 ? nb : 0);
879 }
880
881 typedef int (semantic_func_t)(char *path, DIR *parent, DIR *d,
882                               void *data, struct dirent64 *de);
883
884 #define MAX_LOV_UUID_COUNT      max(LOV_MAX_STRIPE_COUNT, 1000)
885 #define OBD_NOT_FOUND           (-1)
886
887 static int common_param_init(struct find_param *param)
888 {
889         param->lumlen = lov_mds_md_size(MAX_LOV_UUID_COUNT, LOV_MAGIC_V3);
890         if ((param->lmd = malloc(sizeof(lstat_t) + param->lumlen)) == NULL) {
891                 llapi_err(LLAPI_MSG_ERROR,
892                           "error: allocation of %d bytes for ioctl",
893                           sizeof(lstat_t) + param->lumlen);
894                 return -ENOMEM;
895         }
896
897         param->got_uuids = 0;
898         param->obdindexes = NULL;
899         param->obdindex = OBD_NOT_FOUND;
900         return 0;
901 }
902
903 static void find_param_fini(struct find_param *param)
904 {
905         if (param->obdindexes)
906                 free(param->obdindexes);
907
908         if (param->lmd)
909                 free(param->lmd);
910 }
911
912 static int cb_common_fini(char *path, DIR *parent, DIR *d, void *data,
913                           struct dirent64 *de)
914 {
915         struct find_param *param = (struct find_param *)data;
916         param->depth--;
917         return 0;
918 }
919
920 static DIR *opendir_parent(char *path)
921 {
922         DIR *parent;
923         char *fname;
924         char c;
925
926         fname = strrchr(path, '/');
927         if (fname == NULL)
928                 return opendir(".");
929
930         c = fname[1];
931         fname[1] = '\0';
932         parent = opendir(path);
933         fname[1] = c;
934         return parent;
935 }
936
937 int llapi_mds_getfileinfo(char *path, DIR *parent,
938                           struct lov_user_mds_data *lmd)
939 {
940         lstat_t *st = &lmd->lmd_st;
941         char *fname = strrchr(path, '/');
942         int ret = 0;
943
944         if (parent == NULL)
945                 return -EINVAL;
946
947         fname = (fname == NULL ? path : fname + 1);
948         /* retrieve needed file info */
949         strncpy((char *)lmd, fname, lov_mds_md_size(MAX_LOV_UUID_COUNT,
950                 LOV_MAGIC));
951         ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO, (void *)lmd);
952
953         if (ret) {
954                 if (errno == ENOTTY) {
955                         /* ioctl is not supported, it is not a lustre fs.
956                          * Do the regular lstat(2) instead. */
957                         ret = lstat_f(path, st);
958                         if (ret) {
959                                 llapi_err(LLAPI_MSG_ERROR,
960                                           "error: %s: lstat failed for %s",
961                                           __func__, path);
962                                 return ret;
963                         }
964                 } else if (errno == ENOENT) {
965                         llapi_err(LLAPI_MSG_WARN,
966                                   "warning: %s: %s does not exist",
967                                   __func__, path);
968                         return -ENOENT;
969                 } else {
970                         llapi_err(LLAPI_MSG_ERROR,
971                                  "error: %s: IOC_MDC_GETFILEINFO failed for %s",
972                                  __func__, path);
973                         return ret;
974                 }
975         }
976
977         return 0;
978 }
979
980 static int llapi_semantic_traverse(char *path, int size, DIR *parent,
981                                    semantic_func_t sem_init,
982                                    semantic_func_t sem_fini, void *data,
983                                    struct dirent64 *de)
984 {
985         struct dirent64 *dent;
986         int len, ret;
987         DIR *d, *p = NULL;
988
989         ret = 0;
990         len = strlen(path);
991
992         d = opendir(path);
993         if (!d && errno != ENOTDIR) {
994                 llapi_err(LLAPI_MSG_ERROR, "%s: Failed to open '%s'",
995                           __func__, path);
996                 return -EINVAL;
997         } else if (!d && !parent) {
998                 /* ENOTDIR. Open the parent dir. */
999                 p = opendir_parent(path);
1000                 if (!p)
1001                         GOTO(out, ret = -EINVAL);
1002         }
1003
1004         if (sem_init && (ret = sem_init(path, parent ?: p, d, data, de)))
1005                 goto err;
1006
1007         if (!d)
1008                 GOTO(out, ret = 0);
1009
1010         while ((dent = readdir64(d)) != NULL) {
1011                 ((struct find_param *)data)->have_fileinfo = 0;
1012
1013                 if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
1014                         continue;
1015
1016                 path[len] = 0;
1017                 if ((len + dent->d_reclen + 2) > size) {
1018                         llapi_err(LLAPI_MSG_ERROR,
1019                                   "error: %s: string buffer is too small",
1020                                   __func__);
1021                         break;
1022                 }
1023
1024                 if (path[len-1] != '/')
1025                         strcat(path, "/");
1026                 strcat(path, dent->d_name);
1027
1028                 if (dent->d_type == DT_UNKNOWN) {
1029                         lstat_t *st = &((struct find_param *)data)->lmd->lmd_st;
1030
1031                         ret = llapi_mds_getfileinfo(path, d,
1032                                              ((struct find_param *)data)->lmd);
1033                         if (ret == 0) {
1034                                 ((struct find_param *)data)->have_fileinfo = 1;
1035                                 dent->d_type =
1036                                         llapi_filetype_dir_table[st->st_mode &
1037                                                                  S_IFMT];
1038                         }
1039                         if (ret == -ENOENT)
1040                                 continue;
1041                 }
1042
1043                 switch (dent->d_type) {
1044                 case DT_UNKNOWN:
1045                         llapi_err(LLAPI_MSG_ERROR,
1046                                   "error: %s: '%s' is UNKNOWN type %d",
1047                                   __func__, dent->d_name, dent->d_type);
1048                         break;
1049                 case DT_DIR:
1050                         ret = llapi_semantic_traverse(path, size, d, sem_init,
1051                                                       sem_fini, data, dent);
1052                         if (ret < 0)
1053                                 goto out;
1054                         break;
1055                 default:
1056                         ret = 0;
1057                         if (sem_init) {
1058                                 ret = sem_init(path, d, NULL, data, dent);
1059                                 if (ret < 0)
1060                                         goto out;
1061                         }
1062                         if (sem_fini && ret == 0)
1063                                 sem_fini(path, d, NULL, data, dent);
1064                 }
1065         }
1066
1067 out:
1068         path[len] = 0;
1069
1070         if (sem_fini)
1071                 sem_fini(path, parent, d, data, de);
1072 err:
1073         if (d)
1074                 closedir(d);
1075         if (p)
1076                 closedir(p);
1077         return ret;
1078 }
1079
1080 static int param_callback(char *path, semantic_func_t sem_init,
1081                           semantic_func_t sem_fini, struct find_param *param)
1082 {
1083         int ret, len = strlen(path);
1084         char *buf;
1085
1086         if (len > PATH_MAX) {
1087                 llapi_err(LLAPI_MSG_ERROR, "Path name '%s' is too long", path);
1088                 return -EINVAL;
1089         }
1090
1091         buf = (char *)malloc(PATH_MAX + 1);
1092         if (!buf)
1093                 return -ENOMEM;
1094
1095         ret = common_param_init(param);
1096         if (ret)
1097                 goto out;
1098         param->depth = 0;
1099
1100         strncpy(buf, path, PATH_MAX + 1);
1101         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, sem_init,
1102                                       sem_fini, param, NULL);
1103 out:
1104         find_param_fini(param);
1105         free(buf);
1106         return ret < 0 ? ret : 0;
1107 }
1108
1109 int llapi_file_fget_lov_uuid(int fd, struct obd_uuid *lov_name)
1110 {
1111         int rc = ioctl(fd, OBD_IOC_GETNAME, lov_name);
1112         if (rc) {
1113                 rc = errno;
1114                 llapi_err(LLAPI_MSG_ERROR, "error: can't get lov name.");
1115         }
1116         return rc;
1117 }
1118
1119 int llapi_file_get_lov_uuid(const char *path, struct obd_uuid *lov_uuid)
1120 {
1121         int fd, rc;
1122
1123         fd = open(path, O_RDONLY);
1124         if (fd < 0) {
1125                 rc = errno;
1126                 llapi_err(LLAPI_MSG_ERROR, "error opening %s", path);
1127                 return rc;
1128         }
1129
1130         rc = llapi_file_fget_lov_uuid(fd, lov_uuid);
1131
1132         close(fd);
1133
1134         return rc;
1135 }
1136
1137 /*
1138  * If uuidp is NULL, return the number of available obd uuids.
1139  * If uuidp is non-NULL, then it will return the uuids of the obds. If
1140  * there are more OSTs then allocated to uuidp, then an error is returned with
1141  * the ost_count set to number of available obd uuids.
1142  */
1143 int llapi_lov_get_uuids(int fd, struct obd_uuid *uuidp, int *ost_count)
1144 {
1145         struct obd_uuid lov_name;
1146         char buf[1024];
1147         FILE *fp;
1148         int rc = 0, index = 0;
1149
1150         /* Get the lov name */
1151         rc = llapi_file_fget_lov_uuid(fd, &lov_name);
1152         if (rc)
1153                 return rc;
1154
1155         /* Now get the ost uuids from /proc */
1156         snprintf(buf, sizeof(buf), "/proc/fs/lustre/lov/%s/target_obd",
1157                  lov_name.uuid);
1158         fp = fopen(buf, "r");
1159         if (fp == NULL) {
1160                 rc = errno;
1161                 llapi_err(LLAPI_MSG_ERROR, "error: opening '%s'", buf);
1162                 return rc;
1163         }
1164
1165         while (fgets(buf, sizeof(buf), fp) != NULL) {
1166                 if (uuidp && (index < *ost_count)) {
1167                         if (sscanf(buf, "%d: %s", &index, uuidp[index].uuid) <2)
1168                                 break;
1169                 }
1170                 index++;
1171         }
1172
1173         fclose(fp);
1174
1175         if (uuidp && (index >= *ost_count))
1176                 return -EOVERFLOW;
1177
1178         *ost_count = index;
1179         return rc;
1180 }
1181
1182 /* Check if user specified value matches a real uuid.  Ignore _UUID,
1183  * -osc-4ba41334, other trailing gunk in comparison.
1184  * @param real_uuid ends in "_UUID"
1185  * @param search_uuid may or may not end in "_UUID"
1186  */
1187 int llapi_uuid_match(char *real_uuid, char *search_uuid)
1188 {
1189         int cmplen = strlen(real_uuid);
1190         int searchlen = strlen(search_uuid);
1191
1192         if (cmplen > 5 && strcmp(real_uuid + cmplen - 5, "_UUID") == 0)
1193                 cmplen -= 5;
1194         if (searchlen > 5 && strcmp(search_uuid + searchlen - 5, "_UUID") == 0)
1195                 searchlen -= 5;
1196
1197         /* The UUIDs may legitimately be different lengths, if
1198          * the system was upgraded from an older version. */
1199         if (cmplen != searchlen)
1200                 return 0;
1201
1202         return (strncmp(search_uuid, real_uuid, cmplen) == 0);
1203 }
1204
1205 /* Here, param->obduuid points to a single obduuid, the index of which is
1206  * returned in param->obdindex */
1207 static int setup_obd_uuid(DIR *dir, char *dname, struct find_param *param)
1208 {
1209         struct obd_uuid lov_uuid;
1210         char uuid[sizeof(struct obd_uuid)];
1211         char buf[1024];
1212         FILE *fp;
1213         int rc = 0, index;
1214
1215         if (param->got_uuids)
1216                 return rc;
1217
1218         /* Get the lov name */
1219         rc = llapi_file_fget_lov_uuid(dirfd(dir), &lov_uuid);
1220         if (rc) {
1221                 if (errno != ENOTTY) {
1222                         rc = errno;
1223                         llapi_err(LLAPI_MSG_ERROR,
1224                                   "error: can't get lov name: %s", dname);
1225                 } else {
1226                         rc = 0;
1227                 }
1228                 return rc;
1229         }
1230
1231         param->got_uuids = 1;
1232
1233         /* Now get the ost uuids from /proc */
1234         snprintf(buf, sizeof(buf), "/proc/fs/lustre/lov/%s/target_obd",
1235                  lov_uuid.uuid);
1236         fp = fopen(buf, "r");
1237         if (fp == NULL) {
1238                 rc = errno;
1239                 llapi_err(LLAPI_MSG_ERROR, "error: opening '%s'", buf);
1240                 return rc;
1241         }
1242
1243         if (!param->obduuid && !param->quiet && !param->obds_printed)
1244                 llapi_printf(LLAPI_MSG_NORMAL, "OBDS:\n");
1245
1246         while (fgets(buf, sizeof(buf), fp) != NULL) {
1247                 if (sscanf(buf, "%d: %s", &index, uuid) < 2)
1248                         break;
1249
1250                 if (param->obduuid) {
1251                         if (llapi_uuid_match(uuid, param->obduuid->uuid)) {
1252                                 param->obdindex = index;
1253                                 break;
1254                         }
1255                 } else if (!param->quiet && !param->obds_printed) {
1256                         /* Print everything */
1257                         llapi_printf(LLAPI_MSG_NORMAL, "%s", buf);
1258                 }
1259         }
1260         param->obds_printed = 1;
1261
1262         fclose(fp);
1263
1264         if (param->obduuid && (param->obdindex == OBD_NOT_FOUND)) {
1265                 llapi_err_noerrno(LLAPI_MSG_ERROR,
1266                                   "error: %s: unknown obduuid: %s",
1267                                   __FUNCTION__, param->obduuid->uuid);
1268                 rc = -EINVAL;
1269         }
1270
1271         return (rc);
1272 }
1273
1274 /* In this case, param->obduuid will be an array of obduuids and
1275  * obd index for all these obduuids will be returned in
1276  * param->obdindexes */
1277 static int setup_obd_indexes(DIR *dir, struct find_param *param)
1278 {
1279         struct obd_uuid *uuids = NULL;
1280         int obdcount = INIT_ALLOC_NUM_OSTS;
1281         int ret, obd_valid = 0, obdnum, i;
1282
1283         uuids = (struct obd_uuid *)malloc(INIT_ALLOC_NUM_OSTS *
1284                                           sizeof(struct obd_uuid));
1285         if (uuids == NULL)
1286                 return -ENOMEM;
1287
1288 retry_get_uuids:
1289         ret = llapi_lov_get_uuids(dirfd(dir), uuids,
1290                                   &obdcount);
1291         if (ret) {
1292                 struct obd_uuid *uuids_temp;
1293
1294                 if (ret == -EOVERFLOW) {
1295                         uuids_temp = realloc(uuids, obdcount *
1296                                              sizeof(struct obd_uuid));
1297                         if (uuids_temp != NULL)
1298                                 goto retry_get_uuids;
1299                         else
1300                                 ret = -ENOMEM;
1301                 }
1302
1303                 llapi_err(LLAPI_MSG_ERROR, "get ost uuid failed");
1304                 return ret;
1305         }
1306
1307         param->obdindexes = malloc(param->num_obds * sizeof(param->obdindex));
1308         if (param->obdindexes == NULL)
1309                 return -ENOMEM;
1310
1311         for (obdnum = 0; obdnum < param->num_obds; obdnum++) {
1312                 for (i = 0; i < obdcount; i++) {
1313                         if (llapi_uuid_match(uuids[i].uuid,
1314                                              param->obduuid[obdnum].uuid)) {
1315                                 param->obdindexes[obdnum] = i;
1316                                 obd_valid++;
1317                                 break;
1318                         }
1319                 }
1320                 if (i >= obdcount) {
1321                         param->obdindexes[obdnum] = OBD_NOT_FOUND;
1322                         llapi_err_noerrno(LLAPI_MSG_ERROR,
1323                                           "error: %s: unknown obduuid: %s",
1324                                           __FUNCTION__,
1325                                           param->obduuid[obdnum].uuid);
1326                         ret = -EINVAL;
1327                 }
1328         }
1329
1330         if (obd_valid == 0)
1331                 param->obdindex = OBD_NOT_FOUND;
1332         else
1333                 param->obdindex = obd_valid;
1334
1335         param->got_uuids = 1;
1336
1337         return ret;
1338 }
1339
1340
1341 int llapi_ostlist(char *path, struct find_param *param)
1342 {
1343         DIR *dir;
1344         int ret;
1345
1346         dir = opendir(path);
1347         if (dir == NULL)
1348                 return -errno;
1349
1350         ret = setup_obd_uuid(dir, path, param);
1351         closedir(dir);
1352
1353         return ret;
1354 }
1355
1356 static void lov_dump_user_lmm_header(struct lov_user_md *lum, char *path,
1357                                      int is_dir, int verbose, int depth,
1358                                      char *pool_name)
1359 {
1360         char *prefix = is_dir ? "" : "lmm_";
1361         char nl = is_dir ? ' ' : '\n';
1362
1363         if (is_dir && lum->lmm_object_gr == LOV_OBJECT_GROUP_DEFAULT) {
1364                 lum->lmm_object_gr = LOV_OBJECT_GROUP_CLEAR;
1365                 if (verbose & VERBOSE_DETAIL)
1366                         llapi_printf(LLAPI_MSG_NORMAL, "(Default) ");
1367         }
1368
1369         if (depth && path && ((verbose != VERBOSE_OBJID) || !is_dir))
1370                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
1371
1372         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
1373                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_magic:          0x%08X\n",
1374                              lum->lmm_magic);
1375                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_gr:      "LPX64"\n",
1376                              lum->lmm_object_gr);
1377                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_id:      "LPX64"\n",
1378                              lum->lmm_object_id);
1379         }
1380
1381         if (verbose & VERBOSE_COUNT) {
1382                 if (verbose & ~VERBOSE_COUNT)
1383                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_count:   ",
1384                                      prefix);
1385                 if (is_dir) 
1386                         llapi_printf(LLAPI_MSG_NORMAL, "%d%c",
1387                                      lum->lmm_stripe_count ==
1388                                      (typeof(lum->lmm_stripe_count))(-1) ? -1 :
1389                                      lum->lmm_stripe_count, nl);
1390                 else
1391                         llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
1392                                      (int)lum->lmm_stripe_count, nl);
1393         }
1394
1395         if (verbose & VERBOSE_SIZE) {
1396                 if (verbose & ~VERBOSE_SIZE)
1397                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_size:    ",
1398                                      prefix);
1399                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c", lum->lmm_stripe_size,
1400                              nl);
1401         }
1402
1403         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
1404                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_stripe_pattern: %x%c",
1405                              lum->lmm_pattern, nl);
1406         }
1407
1408         if (verbose & VERBOSE_OFFSET) {
1409                 if (verbose & ~VERBOSE_OFFSET)
1410                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_offset:  ",
1411                                      prefix);
1412                 if (is_dir) 
1413                         llapi_printf(LLAPI_MSG_NORMAL, "%d%c",
1414                                      lum->lmm_stripe_offset ==
1415                                      (typeof(lum->lmm_stripe_offset))(-1) ? -1 :
1416                                      lum->lmm_stripe_offset, nl);
1417                 else
1418                         llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
1419                                      lum->lmm_objects[0].l_ost_idx, nl);
1420         }
1421
1422         if ((verbose & VERBOSE_POOL) && (pool_name != NULL)) {
1423                 llapi_printf(LLAPI_MSG_NORMAL, "pool: %s", pool_name);
1424                 is_dir = 1;
1425         }
1426
1427         if (is_dir && (verbose != VERBOSE_OBJID))
1428                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1429 }
1430
1431 static void lov_dump_user_lmm_join(struct lov_user_md_v1 *lum, int is_dir,
1432                                    int obdstripe, int obdindex, int header)
1433 {
1434         struct lov_user_md_join *lumj = (struct lov_user_md_join *)lum;
1435         int i;
1436
1437         if (header && (obdstripe == 1))
1438                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_extent_count:   %x\n",
1439                              lumj->lmm_extent_count);
1440
1441         if (!is_dir && (header & VERBOSE_OBJID)) {
1442                 unsigned long long start = -1, end = 0;
1443
1444                 if (obdstripe == 1)
1445                         llapi_printf(LLAPI_MSG_NORMAL,
1446                                      "joined\tobdidx\t\t objid\t\tobjid\t\t "
1447                                      "group\t\tstart\t\tend\n");
1448                 for (i = 0; i < lumj->lmm_stripe_count; i++) {
1449                         int idx = lumj->lmm_objects[i].l_ost_idx;
1450                         long long oid = lumj->lmm_objects[i].l_object_id;
1451                         long long gr = lumj->lmm_objects[i].l_object_gr;
1452                         if (obdindex == OBD_NOT_FOUND || obdindex == idx)
1453                                 llapi_printf(LLAPI_MSG_NORMAL,
1454                                              "\t%6u\t%14llu\t%#13llx\t%14llu%s",
1455                                              idx, oid, oid, gr,
1456                                              obdindex == idx ? " *" : "");
1457                         if (start != lumj->lmm_objects[i].l_extent_start ||
1458                             end != lumj->lmm_objects[i].l_extent_end) {
1459                                 start = lumj->lmm_objects[i].l_extent_start;
1460                                 llapi_printf(LLAPI_MSG_NORMAL,"\t%14llu",start);
1461                                 end = lumj->lmm_objects[i].l_extent_end;
1462                                 if (end == (unsigned long long)-1)
1463                                         llapi_printf(LLAPI_MSG_NORMAL,
1464                                                      "\t\tEOF\n");
1465                                 else
1466                                         llapi_printf(LLAPI_MSG_NORMAL,
1467                                                      "\t\t%llu\n", end);
1468                         } else {
1469                                 llapi_printf(LLAPI_MSG_NORMAL, "\t\t\t\t\n");
1470                         }
1471                 }
1472                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1473         }
1474 }
1475
1476 static void lov_dump_user_lmm_v1v3(struct lov_user_md *lum,
1477                                    struct lov_user_ost_data_v1 *objects,
1478                                    int is_dir, int obdstripe,
1479                                    int obdindex,int header)
1480 {
1481         int i;
1482
1483         if (!is_dir && (header & VERBOSE_OBJID)) {
1484                 if (obdstripe == 1)
1485                         llapi_printf(LLAPI_MSG_NORMAL,
1486                                      "\tobdidx\t\t objid\t\tobjid\t\t group\n");
1487
1488                 for (i = 0; i < lum->lmm_stripe_count; i++) {
1489                         int idx = objects[i].l_ost_idx;
1490                         long long oid = objects[i].l_object_id;
1491                         long long gr = objects[i].l_object_gr;
1492                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
1493                                 llapi_printf(LLAPI_MSG_NORMAL,
1494                                            "\t%6u\t%14llu\t%#13llx\t%14llu%s\n",
1495                                            idx, oid, oid, gr,
1496                                            obdindex == idx ? " *" : "");
1497                 }
1498                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1499         }
1500 }
1501
1502 void llapi_lov_dump_user_lmm(struct find_param *param,
1503                              char *path, int is_dir)
1504 {
1505         int i, obdstripe = (param->obdindex != OBD_NOT_FOUND) ? 0 : 1;
1506         struct lov_user_md *lum = &param->lmd->lmd_lmm;
1507
1508         if (!obdstripe) {
1509                 for (i = 0; !is_dir && i < lum->lmm_stripe_count; i++) {
1510                         if (param->obdindex == lum->lmm_objects[i].l_ost_idx) {
1511                                 obdstripe = 1;
1512                                 break;
1513                         }
1514                 }
1515         }
1516
1517         switch(*(__u32 *)&param->lmd->lmd_lmm) { /* lum->lmm_magic */
1518         case LOV_USER_MAGIC_V1:
1519                 if (param->verbose && (obdstripe == 1))
1520                         lov_dump_user_lmm_header(lum, path, is_dir,
1521                                                  param->verbose,
1522                                                  param->maxdepth,
1523                                                  NULL);
1524                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm,
1525                                        param->lmd->lmd_lmm.lmm_objects,
1526                                        is_dir, obdstripe,
1527                                        param->obdindex,
1528                                        param->verbose);
1529                 break;
1530         case LOV_USER_MAGIC_JOIN:
1531                 if (param->verbose && (obdstripe == 1))
1532                         lov_dump_user_lmm_header(lum, path, is_dir,
1533                                                  param->verbose,
1534                                                  param->maxdepth,
1535                                                  NULL);
1536                 lov_dump_user_lmm_join(&param->lmd->lmd_lmm, is_dir,
1537                                        obdstripe, param->obdindex,
1538                                        param->verbose);
1539                 break;
1540         case LOV_USER_MAGIC_V3: {
1541                 char pool_name[LOV_MAXPOOLNAME + 1];
1542                 struct lov_user_ost_data_v1 *objects;
1543                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
1544
1545                 strncpy(pool_name, lmmv3->lmm_pool_name, LOV_MAXPOOLNAME);
1546                 pool_name[LOV_MAXPOOLNAME] = '\0';
1547                 objects = lmmv3->lmm_objects;
1548                 if (param->verbose && (obdstripe == 1))
1549                         lov_dump_user_lmm_header(lum, path, is_dir,
1550                                                  param->verbose,
1551                                                  param->maxdepth,
1552                                                  pool_name);
1553                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, objects, is_dir,
1554                                        obdstripe, param->obdindex,
1555                                        param->verbose);
1556                 break;
1557         }
1558         default:
1559                 llapi_printf(LLAPI_MSG_NORMAL, "unknown lmm_magic:  %#x "
1560                              "(expecting one of %#x %#x %#x)\n",
1561                              param->lmd->lmd_lmm.lmm_magic,
1562                              LOV_USER_MAGIC_V1, LOV_USER_MAGIC_JOIN,
1563                              LOV_USER_MAGIC_V3);
1564                 return;
1565         }
1566 }
1567
1568 int llapi_file_get_stripe(const char *path, struct lov_user_md *lum)
1569 {
1570         const char *fname;
1571         char *dname;
1572         int fd, rc = 0;
1573
1574         fname = strrchr(path, '/');
1575         if (strlen(fname) + 1 < sizeof(struct lov_user_md))
1576                 return ENAMETOOLONG;
1577
1578         /* It should be a file (or other non-directory) */
1579         if (fname == NULL) {
1580                 dname = (char *)malloc(2);
1581                 if (dname == NULL)
1582                         return ENOMEM;
1583                 strcpy(dname, ".");
1584                 fname = (char *)path;
1585         } else {
1586                 dname = (char *)malloc(fname - path + 1);
1587                 if (dname == NULL)
1588                         return ENOMEM;
1589                 strncpy(dname, path, fname - path);
1590                 dname[fname - path] = '\0';
1591                 fname++;
1592         }
1593
1594         if ((fd = open(dname, O_RDONLY)) == -1) {
1595                 rc = errno;
1596                 free(dname);
1597                 return rc;
1598         }
1599
1600         strcpy((char *)lum, fname);
1601         if (ioctl(fd, IOC_MDC_GETFILESTRIPE, (void *)lum) == -1)
1602                 rc = errno;
1603
1604         if (close(fd) == -1 && rc == 0)
1605                 rc = errno;
1606
1607         free(dname);
1608
1609         return rc;
1610 }
1611
1612 int llapi_file_lookup(int dirfd, const char *name)
1613 {
1614         struct obd_ioctl_data data = { 0 };
1615         char rawbuf[8192];
1616         char *buf = rawbuf;
1617         int rc;
1618
1619         if (dirfd < 0 || name == NULL)
1620                 return -EINVAL;
1621
1622         data.ioc_version = OBD_IOCTL_VERSION;
1623         data.ioc_len = sizeof(data);
1624         data.ioc_inlbuf1 = (char *)name;
1625         data.ioc_inllen1 = strlen(name) + 1;
1626
1627         rc = obd_ioctl_pack(&data, &buf, sizeof(rawbuf));
1628         if (rc) {
1629                 llapi_err(LLAPI_MSG_ERROR,
1630                           "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
1631                           name, rc);
1632                 return rc;
1633         }
1634
1635         return ioctl(dirfd, IOC_MDC_LOOKUP, buf);
1636 }
1637
1638 /* Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
1639  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
1640  *
1641  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
1642  * The table below gives the answers for the specified parameters (value and
1643  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
1644  * --------------------------------------
1645  * 1 | file > limit; sign > 0 | -1 / -1 |
1646  * 2 | file = limit; sign > 0 |  ? /  1 |
1647  * 3 | file < limit; sign > 0 |  ? /  1 |
1648  * 4 | file > limit; sign = 0 | -1 / -1 |
1649  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
1650  * 6 | file < limit; sign = 0 |  ? / -1 |
1651  * 7 | file > limit; sign < 0 |  1 /  1 |
1652  * 8 | file = limit; sign < 0 |  ? / -1 |
1653  * 9 | file < limit; sign < 0 |  ? / -1 |
1654  * --------------------------------------
1655  * Note: 5th actually means that the value is within the interval
1656  * (limit - margin, limit]. */
1657 static int find_value_cmp(unsigned int file, unsigned int limit, int sign,
1658                           int negopt, unsigned long long margin, int mds)
1659 {
1660         int ret = -1;
1661
1662         if (sign > 0) {
1663                 if (file <= limit)
1664                         ret = mds ? 0 : 1;
1665         } else if (sign == 0) {
1666                 if (file <= limit && file + margin >= limit)
1667                         ret = mds ? 0 : 1;
1668                 else if (file + margin <= limit)
1669                         ret = mds ? 0 : -1;
1670         } else if (sign < 0) {
1671                 if (file >= limit)
1672                         ret = 1;
1673                 else if (mds)
1674                         ret = 0;
1675         }
1676
1677         return negopt ? ~ret + 1 : ret;
1678 }
1679
1680 /* Check if the file time matches all the given criteria (e.g. --atime +/-N).
1681  * Return -1 or 1 if file timestamp does not or does match the given criteria
1682  * correspondingly. Return 0 if the MDS time is being checked and there are
1683  * attributes on OSTs and it is not yet clear if the timespamp matches.
1684  *
1685  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
1686  * updated timestamps. */
1687 static int find_time_check(lstat_t *st, struct find_param *param, int mds)
1688 {
1689         int ret;
1690         int rc = 0;
1691
1692         /* Check if file is accepted. */
1693         if (param->atime) {
1694                 ret = find_value_cmp(st->st_atime, param->atime,
1695                                      param->asign, param->exclude_atime,
1696                                      24 * 60 * 60, mds);
1697                 if (ret < 0)
1698                         return ret;
1699                 rc = ret;
1700         }
1701
1702         if (param->mtime) {
1703                 ret = find_value_cmp(st->st_mtime, param->mtime,
1704                                      param->msign, param->exclude_mtime,
1705                                      24 * 60 * 60, mds);
1706                 if (ret < 0)
1707                         return ret;
1708
1709                 /* If the previous check matches, but this one is not yet clear,
1710                  * we should return 0 to do an RPC on OSTs. */
1711                 if (rc == 1)
1712                         rc = ret;
1713         }
1714
1715         if (param->ctime) {
1716                 ret = find_value_cmp(st->st_ctime, param->ctime,
1717                                      param->csign, param->exclude_ctime,
1718                                      24 * 60 * 60, mds);
1719                 if (ret < 0)
1720                         return ret;
1721
1722                 /* If the previous check matches, but this one is not yet clear,
1723                  * we should return 0 to do an RPC on OSTs. */
1724                 if (rc == 1)
1725                         rc = ret;
1726         }
1727
1728         return rc;
1729 }
1730
1731 static int cb_find_init(char *path, DIR *parent, DIR *dir,
1732                         void *data, struct dirent64 *de)
1733 {
1734         struct find_param *param = (struct find_param *)data;
1735         struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
1736         int decision = 1; /* 1 is accepted; -1 is rejected. */
1737         lstat_t *st = &param->lmd->lmd_st;
1738         int lustre_fs = 1;
1739         int checked_type = 0;
1740         int ret = 0;
1741
1742         LASSERT(parent != NULL || dir != NULL);
1743
1744         param->lmd->lmd_lmm.lmm_stripe_count = 0;
1745
1746         /* If a regular expression is presented, make the initial decision */
1747         if (param->pattern != NULL) {
1748                 char *fname = strrchr(path, '/');
1749                 fname = (fname == NULL ? path : fname + 1);
1750                 ret = fnmatch(param->pattern, fname, 0);
1751                 if ((ret == FNM_NOMATCH && !param->exclude_pattern) ||
1752                     (ret == 0 && param->exclude_pattern))
1753                         goto decided;
1754         }
1755
1756         /* See if we can check the file type from the dirent. */
1757         if (param->type && de != NULL && de->d_type != DT_UNKNOWN &&
1758             de->d_type <= DT_MAX) {
1759                 checked_type = 1;
1760                 if (llapi_dir_filetype_table[de->d_type] == param->type) {
1761                         if (param->exclude_type)
1762                                 goto decided;
1763                 } else {
1764                         if (!param->exclude_type)
1765                                 goto decided;
1766                 }
1767         }
1768
1769
1770         /* If a time or OST should be checked, the decision is not taken yet. */
1771         if (param->atime || param->ctime || param->mtime || param->obduuid ||
1772             param->size_check)
1773                 decision = 0;
1774
1775         ret = 0;
1776         /* Request MDS for the stat info. */
1777         if (param->have_fileinfo == 0) {
1778                 if (dir) {
1779                         /* retrieve needed file info */
1780                         ret = ioctl(dirfd(dir), LL_IOC_MDC_GETINFO,
1781                                     (void *)param->lmd);
1782                 } else {
1783                         char *fname = strrchr(path, '/');
1784                         fname = (fname == NULL ? path : fname + 1);
1785
1786                         /* retrieve needed file info */
1787                         strncpy((char *)param->lmd, fname, param->lumlen);
1788                         ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
1789                                    (void *)param->lmd);
1790                 }
1791         }
1792
1793         if (ret) {
1794                 if (errno == ENOTTY) {
1795                         /* ioctl is not supported, it is not a lustre fs.
1796                          * Do the regular lstat(2) instead. */
1797                         lustre_fs = 0;
1798                         ret = lstat_f(path, st);
1799                         if (ret) {
1800                                 llapi_err(LLAPI_MSG_ERROR,
1801                                           "error: %s: lstat failed for %s",
1802                                           __func__, path);
1803                                 return ret;
1804                         }
1805                 } else if (errno == ENOENT) {
1806                         llapi_err(LLAPI_MSG_WARN,
1807                                   "warning: %s: %s does not exist",
1808                                   __func__, path);
1809                         goto decided;
1810                 } else {
1811                         llapi_err(LLAPI_MSG_ERROR,"error: %s: %s failed for %s",
1812                                   __func__, dir ? "LL_IOC_MDC_GETINFO" :
1813                                   "IOC_MDC_GETFILEINFO", path);
1814                         return ret;
1815                 }
1816         }
1817
1818         if (param->check_uid) {
1819                 if (st->st_uid == param->uid) {
1820                         if (param->exclude_uid)
1821                                 goto decided;
1822                 } else {
1823                         if (!param->exclude_uid)
1824                                 goto decided;
1825                 }
1826         }
1827
1828         if (param->check_gid) {
1829                 if (st->st_gid == param->gid) {
1830                         if (param->exclude_gid)
1831                                 goto decided;
1832                 } else {
1833                         if (!param->exclude_gid)
1834                                 goto decided;
1835                 }
1836         }
1837
1838         if (param->check_pool) {
1839                 /* empty requested pool is taken as no pool search => V1 */
1840                 if ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V1 &&
1841                      param->poolname[0] == '\0') ||
1842                     (param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3 &&
1843                      (strncmp(lmmv3->lmm_pool_name, param->poolname,
1844                               LOV_MAXPOOLNAME) == 0 ||
1845                       strcmp(param->poolname, "*") == 0))) {
1846                         if (param->exclude_pool)
1847                                 goto decided;
1848                 } else {
1849                         if (!param->exclude_pool)
1850                                 goto decided;
1851                 }
1852         }
1853
1854         /* Check the time on mds. */
1855         if (!decision) {
1856                 int for_mds;
1857
1858                 for_mds = lustre_fs ? (S_ISREG(st->st_mode) &&
1859                                        param->lmd->lmd_lmm.lmm_stripe_count)
1860                                     : 0;
1861                 decision = find_time_check(st, param, for_mds);
1862                 if (decision == -1)
1863                         goto decided;
1864         }
1865
1866         if (param->type && !checked_type) {
1867                 if ((st->st_mode & S_IFMT) == param->type) {
1868                         if (param->exclude_type)
1869                                 goto decided;
1870                 } else {
1871                         if (!param->exclude_type)
1872                                 goto decided;
1873                 }
1874         }
1875
1876         /* Prepare odb. */
1877         if (param->obduuid) {
1878                 if (lustre_fs && param->got_uuids &&
1879                     param->st_dev != st->st_dev) {
1880                         /* A lustre/lustre mount point is crossed. */
1881                         param->got_uuids = 0;
1882                         param->obds_printed = 0;
1883                         param->obdindex = OBD_NOT_FOUND;
1884                 }
1885
1886                 if (lustre_fs && !param->got_uuids) {
1887                         ret = setup_obd_indexes(dir ? dir : parent, param);
1888                         if (ret)
1889                                 return ret;
1890
1891                         param->st_dev = st->st_dev;
1892                 } else if (!lustre_fs && param->got_uuids) {
1893                         /* A lustre/non-lustre mount point is crossed. */
1894                         param->got_uuids = 0;
1895                         param->obdindex = OBD_NOT_FOUND;
1896                 }
1897         }
1898
1899         /* If an OBD UUID is specified but no one matches, skip this file. */
1900         if (param->obduuid && param->obdindex == OBD_NOT_FOUND)
1901                 goto decided;
1902
1903         /* If a OST UUID is given, and some OST matches, check it here. */
1904         if (param->obdindex != OBD_NOT_FOUND) {
1905                 if (!S_ISREG(st->st_mode))
1906                         goto decided;
1907
1908                 /* Only those files should be accepted, which have a
1909                  * stripe on the specified OST. */
1910                 if (!param->lmd->lmd_lmm.lmm_stripe_count) {
1911                         goto decided;
1912                 } else {
1913                         int i, j;
1914                         struct lov_user_ost_data_v1 *lmm_objects;
1915
1916                         if (param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3)
1917                                 lmm_objects = lmmv3->lmm_objects;
1918                         else
1919                                 lmm_objects = param->lmd->lmd_lmm.lmm_objects;
1920
1921                         for (i = 0;
1922                              i < param->lmd->lmd_lmm.lmm_stripe_count; i++) {
1923                                 for (j = 0; j < param->num_obds; j++) {
1924                                         if (param->obdindexes[j] ==
1925                                             lmm_objects[i].l_ost_idx) {
1926                                                 if (param->exclude_obd)
1927                                                         goto decided;
1928                                                 goto obd_matches;
1929                                         }
1930                                 }
1931                         }
1932
1933                         if (i == param->lmd->lmd_lmm.lmm_stripe_count) {
1934                                 if (param->exclude_obd)
1935                                         goto obd_matches;
1936                                 goto decided;
1937                         }
1938                 }
1939         }
1940
1941 obd_matches:
1942
1943         /* If file still fits the request, ask osd for updated info.
1944            The regulat stat is almost of the same speed as some new
1945            'glimpse-size-ioctl'. */
1946         if (!decision && S_ISREG(st->st_mode) &&
1947             param->lmd->lmd_lmm.lmm_stripe_count &&
1948             (param->size_check ||param->atime ||param->mtime ||param->ctime)) {
1949                 if (dir) {
1950                         ret = ioctl(dirfd(dir), IOC_LOV_GETINFO,
1951                                     (void *)param->lmd);
1952                 } else if (parent) {
1953                         ret = ioctl(dirfd(parent), IOC_LOV_GETINFO,
1954                                     (void *)param->lmd);
1955                 }
1956
1957                 if (ret) {
1958                         if (errno == ENOENT) {
1959                                 llapi_err(LLAPI_MSG_ERROR,
1960                                           "warning: %s: %s does not exist",
1961                                           __func__, path);
1962                                 goto decided;
1963                         } else {
1964                                 llapi_err(LLAPI_MSG_ERROR,
1965                                           "%s: IOC_LOV_GETINFO on %s failed",
1966                                           __func__, path);
1967                                 return ret;
1968                         }
1969                 }
1970
1971                 /* Check the time on osc. */
1972                 decision = find_time_check(st, param, 0);
1973                 if (decision == -1)
1974                         goto decided;
1975         }
1976
1977         if (param->size_check) {
1978                 decision = find_value_cmp(st->st_size, param->size,
1979                                           param->size_sign, param->exclude_size,
1980                                           param->size_units, 0);
1981         }
1982
1983         if (decision != -1) {
1984                 llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
1985                 if (param->zeroend)
1986                         llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
1987                 else
1988                         llapi_printf(LLAPI_MSG_NORMAL, "\n");
1989         }
1990
1991 decided:
1992         /* Do not get down anymore? */
1993         if (param->depth == param->maxdepth)
1994                 return 1;
1995
1996         param->depth++;
1997         return 0;
1998 }
1999
2000 int llapi_find(char *path, struct find_param *param)
2001 {
2002         return param_callback(path, cb_find_init, cb_common_fini, param);
2003 }
2004
2005 static int cb_getstripe(char *path, DIR *parent, DIR *d, void *data,
2006                         struct dirent64 *de)
2007 {
2008         struct find_param *param = (struct find_param *)data;
2009         int ret = 0;
2010
2011         LASSERT(parent != NULL || d != NULL);
2012
2013         if (param->obduuid) {
2014                 param->quiet = 1;
2015                 ret = setup_obd_uuid(d ? d : parent, path, param);
2016                 if (ret)
2017                         return ret;
2018         }
2019
2020         if (d) {
2021                 ret = ioctl(dirfd(d), LL_IOC_LOV_GETSTRIPE,
2022                             (void *)&param->lmd->lmd_lmm);
2023         } else if (parent) {
2024                 char *fname = strrchr(path, '/');
2025                 fname = (fname == NULL ? path : fname + 1);
2026
2027                 strncpy((char *)&param->lmd->lmd_lmm, fname, param->lumlen);
2028                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILESTRIPE,
2029                             (void *)&param->lmd->lmd_lmm);
2030         }
2031
2032         if (ret) {
2033                 if (errno == ENODATA) {
2034                         if (!param->obduuid)
2035                                 llapi_printf(LLAPI_MSG_NORMAL,
2036                                              "%s has no stripe info\n", path);
2037                         goto out;
2038                 } else if (errno == ENOTTY) {
2039                         llapi_err(LLAPI_MSG_ERROR,
2040                                   "%s: '%s' not on a Lustre fs?",
2041                                   __func__, path);
2042                 } else if (errno == ENOENT) {
2043                         llapi_err(LLAPI_MSG_WARN,
2044                                   "warning: %s: %s does not exist",
2045                                   __func__, path);
2046                         goto out;
2047                 } else {
2048                         llapi_err(LLAPI_MSG_ERROR,
2049                                   "error: %s: %s failed for %s",
2050                                    __func__, d ? "LL_IOC_LOV_GETSTRIPE" :
2051                                   "IOC_MDC_GETFILESTRIPE", path);
2052                 }
2053
2054                 return ret;
2055         }
2056
2057         llapi_lov_dump_user_lmm(param, path, d ? 1 : 0);
2058 out:
2059         /* Do not get down anymore? */
2060         if (param->depth == param->maxdepth)
2061                 return 1;
2062
2063         param->depth++;
2064         return 0;
2065 }
2066
2067 int llapi_getstripe(char *path, struct find_param *param)
2068 {
2069         return param_callback(path, cb_getstripe, cb_common_fini, param);
2070 }
2071
2072 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
2073                      struct obd_statfs *stat_buf,
2074                      struct obd_uuid *uuid_buf)
2075 {
2076         int fd;
2077         char raw[OBD_MAX_IOCTL_BUFFER] = {'\0'};
2078         char *rawbuf = raw;
2079         struct obd_ioctl_data data = { 0 };
2080         int rc = 0;
2081
2082         data.ioc_inlbuf1 = (char *)&type;
2083         data.ioc_inllen1 = sizeof(__u32);
2084         data.ioc_inlbuf2 = (char *)&index;
2085         data.ioc_inllen2 = sizeof(__u32);
2086         data.ioc_pbuf1 = (char *)stat_buf;
2087         data.ioc_plen1 = sizeof(struct obd_statfs);
2088         data.ioc_pbuf2 = (char *)uuid_buf;
2089         data.ioc_plen2 = sizeof(struct obd_uuid);
2090
2091         if ((rc = obd_ioctl_pack(&data, &rawbuf, sizeof(raw))) != 0) {
2092                 llapi_err(LLAPI_MSG_ERROR,
2093                           "llapi_obd_statfs: error packing ioctl data");
2094                 return rc;
2095         }
2096
2097         fd = open(path, O_RDONLY);
2098         if (errno == EISDIR)
2099                 fd = open(path, O_DIRECTORY | O_RDONLY);
2100
2101         if (fd < 0) {
2102                 rc = errno ? -errno : -EBADF;
2103                 llapi_err(LLAPI_MSG_ERROR, "error: %s: opening '%s'",
2104                           __func__, path);
2105                 return rc;
2106         }
2107         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
2108         if (rc)
2109                 rc = errno ? -errno : -EINVAL;
2110
2111         close(fd);
2112         return rc;
2113 }
2114
2115 #define MAX_STRING_SIZE 128
2116 #define DEVICES_LIST "/proc/fs/lustre/devices"
2117
2118 int llapi_ping(char *obd_type, char *obd_name)
2119 {
2120         char path[MAX_STRING_SIZE];
2121         char buf[1];
2122         int rc, fd;
2123
2124         snprintf(path, MAX_STRING_SIZE, "/proc/fs/lustre/%s/%s/ping",
2125                  obd_type, obd_name);
2126
2127         fd = open(path, O_WRONLY);
2128         if (fd < 0) {
2129                 rc = errno;
2130                 llapi_err(LLAPI_MSG_ERROR, "error opening %s", path);
2131                 return rc;
2132         }
2133
2134         rc = write(fd, buf, 1);
2135         close(fd);
2136
2137         if (rc == 1)
2138                 return 0;
2139         return rc;
2140 }
2141
2142 int llapi_target_iterate(int type_num, char **obd_type,void *args,llapi_cb_t cb)
2143 {
2144         char buf[MAX_STRING_SIZE];
2145         FILE *fp = fopen(DEVICES_LIST, "r");
2146         int i, rc = 0;
2147
2148         if (fp == NULL) {
2149                 rc = errno;
2150                 llapi_err(LLAPI_MSG_ERROR, "error: opening "DEVICES_LIST);
2151                 return rc;
2152         }
2153
2154         while (fgets(buf, sizeof(buf), fp) != NULL) {
2155                 char *obd_type_name = NULL;
2156                 char *obd_name = NULL;
2157                 char *obd_uuid = NULL;
2158                 char rawbuf[OBD_MAX_IOCTL_BUFFER];
2159                 char *bufl = rawbuf;
2160                 char *bufp = buf;
2161                 struct obd_ioctl_data datal = { 0, };
2162                 struct obd_statfs osfs_buffer;
2163
2164                 while(bufp[0] == ' ')
2165                         ++bufp;
2166
2167                 for(i = 0; i < 3; i++) {
2168                         obd_type_name = strsep(&bufp, " ");
2169                 }
2170                 obd_name = strsep(&bufp, " ");
2171                 obd_uuid = strsep(&bufp, " ");
2172
2173                 memset(&osfs_buffer, 0, sizeof (osfs_buffer));
2174
2175                 memset(bufl, 0, sizeof(rawbuf));
2176                 datal.ioc_pbuf1 = (char *)&osfs_buffer;
2177                 datal.ioc_plen1 = sizeof(osfs_buffer);
2178
2179                 for (i = 0; i < type_num; i++) {
2180                         if (strcmp(obd_type_name, obd_type[i]) != 0)
2181                                 continue;
2182
2183                         cb(obd_type_name, obd_name, obd_uuid, args);
2184                 }
2185         }
2186         fclose(fp);
2187         return rc;
2188 }
2189
2190 static void do_target_check(char *obd_type_name, char *obd_name,
2191                             char *obd_uuid, void *args)
2192 {
2193         int rc;
2194
2195         rc = llapi_ping(obd_type_name, obd_name);
2196         if (rc == ENOTCONN) {
2197                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
2198         } else if (rc) {
2199                 llapi_err(LLAPI_MSG_ERROR, "error: check '%s'", obd_name);
2200         } else {
2201                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
2202         }
2203 }
2204
2205 int llapi_target_check(int type_num, char **obd_type, char *dir)
2206 {
2207         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
2208 }
2209
2210 #undef MAX_STRING_SIZE
2211
2212 int llapi_catinfo(char *dir, char *keyword, char *node_name)
2213 {
2214         char raw[OBD_MAX_IOCTL_BUFFER];
2215         char out[LLOG_CHUNK_SIZE];
2216         char *buf = raw;
2217         struct obd_ioctl_data data = { 0 };
2218         char key[30];
2219         DIR *root;
2220         int rc;
2221
2222         sprintf(key, "%s", keyword);
2223         memset(raw, 0, sizeof(raw));
2224         memset(out, 0, sizeof(out));
2225         data.ioc_inlbuf1 = key;
2226         data.ioc_inllen1 = strlen(key) + 1;
2227         if (node_name) {
2228                 data.ioc_inlbuf2 = node_name;
2229                 data.ioc_inllen2 = strlen(node_name) + 1;
2230         }
2231         data.ioc_pbuf1 = out;
2232         data.ioc_plen1 = sizeof(out);
2233         rc = obd_ioctl_pack(&data, &buf, sizeof(raw));
2234         if (rc)
2235                 return rc;
2236
2237         root = opendir(dir);
2238         if (root == NULL) {
2239                 rc = errno;
2240                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", dir);
2241                 return rc;
2242         }
2243
2244         rc = ioctl(dirfd(root), OBD_IOC_LLOG_CATINFO, buf);
2245         if (rc)
2246                 llapi_err(LLAPI_MSG_ERROR, "ioctl OBD_IOC_CATINFO failed");
2247         else
2248                 llapi_printf(LLAPI_MSG_NORMAL, "%s", data.ioc_pbuf1);
2249
2250         closedir(root);
2251         return rc;
2252 }
2253
2254 /* Is this a lustre fs? */
2255 int llapi_is_lustre_mnttype(const char *type)
2256 {
2257         return (strcmp(type, "lustre") == 0 || strcmp(type,"lustre_lite") == 0);
2258 }
2259
2260 /* Is this a lustre client fs? */
2261 int llapi_is_lustre_mnt(struct mntent *mnt)
2262 {
2263         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
2264                 strstr(mnt->mnt_fsname, ":/") != NULL);
2265 }
2266
2267 int llapi_quotacheck(char *mnt, int check_type)
2268 {
2269         DIR *root;
2270         int rc;
2271
2272         root = opendir(mnt);
2273         if (!root) {
2274                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2275                 return -1;
2276         }
2277
2278         rc = ioctl(dirfd(root), LL_IOC_QUOTACHECK, check_type);
2279
2280         closedir(root);
2281         return rc;
2282 }
2283
2284 int llapi_poll_quotacheck(char *mnt, struct if_quotacheck *qchk)
2285 {
2286         DIR *root;
2287         int poll_intvl = 2;
2288         int rc;
2289
2290         root = opendir(mnt);
2291         if (!root) {
2292                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2293                 return -1;
2294         }
2295
2296         while (1) {
2297                 rc = ioctl(dirfd(root), LL_IOC_POLL_QUOTACHECK, qchk);
2298                 if (!rc)
2299                         break;
2300                 sleep(poll_intvl);
2301                 if (poll_intvl < 30)
2302                         poll_intvl *= 2;
2303         }
2304
2305         closedir(root);
2306         return rc;
2307 }
2308
2309 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
2310 {
2311         DIR *root;
2312         int rc;
2313
2314         root = opendir(mnt);
2315         if (!root) {
2316                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2317                 return -1;
2318         }
2319
2320         rc = ioctl(dirfd(root), LL_IOC_QUOTACTL, qctl);
2321
2322         closedir(root);
2323         return rc;
2324 }
2325
2326 static int cb_quotachown(char *path, DIR *parent, DIR *d, void *data,
2327                          struct dirent64 *de)
2328 {
2329         struct find_param *param = (struct find_param *)data;
2330         lstat_t *st;
2331         int rc;
2332
2333         LASSERT(parent != NULL || d != NULL);
2334
2335         if (d) {
2336                 rc = ioctl(dirfd(d), LL_IOC_MDC_GETINFO,
2337                            (void *)param->lmd);
2338         } else if (parent) {
2339                 char *fname = strrchr(path, '/');
2340                 fname = (fname == NULL ? path : fname + 1);
2341
2342                 strncpy((char *)param->lmd, fname, param->lumlen);
2343                 rc = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
2344                            (void *)param->lmd);
2345         } else {
2346                 return 0;
2347         }
2348
2349         if (rc) {
2350                 if (errno == ENODATA) {
2351                         if (!param->obduuid && !param->quiet)
2352                                 llapi_err(LLAPI_MSG_ERROR,
2353                                           "%s has no stripe info", path);
2354                         rc = 0;
2355                 } else if (errno == ENOENT) {
2356                         llapi_err(LLAPI_MSG_ERROR,
2357                                   "warning: %s: %s does not exist",
2358                                   __func__, path);
2359                         rc = 0;
2360                 } else if (errno != EISDIR) {
2361                         rc = errno;
2362                         llapi_err(LLAPI_MSG_ERROR, "%s ioctl failed for %s.",
2363                                   d ? "LL_IOC_MDC_GETINFO" :
2364                                   "IOC_MDC_GETFILEINFO", path);
2365                 }
2366                 return rc;
2367         }
2368
2369         st = &param->lmd->lmd_st;
2370
2371         /* libc chown() will do extra check, and if the real owner is
2372          * the same as the ones to set, it won't fall into kernel, so
2373          * invoke syscall directly. */
2374         rc = syscall(SYS_chown, path, -1, -1);
2375         if (rc)
2376                 llapi_err(LLAPI_MSG_ERROR, "error: chown %s", path);
2377
2378         rc = chmod(path, st->st_mode);
2379         if (rc)
2380                 llapi_err(LLAPI_MSG_ERROR, "error: chmod %s (%hu)",
2381                           path, st->st_mode);
2382
2383         return rc;
2384 }
2385
2386 int llapi_quotachown(char *path, int flag)
2387 {
2388         struct find_param param;
2389         
2390         memset(&param, 0, sizeof(param));
2391         param.recursive = 1;
2392         param.verbose = 0;
2393         param.quiet = 1;
2394
2395         return param_callback(path, cb_quotachown, NULL, &param);
2396 }
2397
2398 int llapi_path2fid(const char *path, lustre_fid *fid)
2399 {
2400         int fd, rc;
2401
2402         fd = open(path, O_RDONLY);
2403         if (fd < 0)
2404                 return -errno;
2405
2406         rc = ioctl(fd, LL_IOC_PATH2FID, fid);
2407
2408         close(fd);
2409         return rc;
2410 }
2411
2412 int llapi_get_connect_flags(const char *mnt, __u64 *flags)
2413 {
2414         DIR *root;
2415         int rc;
2416
2417         root = opendir(mnt);
2418         if (!root) {
2419                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2420                 return -1;
2421         }
2422
2423         rc = ioctl(dirfd(root), LL_IOC_GET_CONNECT_FLAGS, flags);
2424         closedir(root);
2425         if (rc < 0)
2426                 llapi_err(LLAPI_MSG_ERROR,
2427                           "ioctl on %s for getting connect flags failed", mnt);
2428         return rc;
2429 }
2430
2431 int llapi_get_version(char *buffer, int buffer_size,
2432                       char **version)
2433 {
2434         int rc;
2435         int fd;
2436         struct obd_ioctl_data *data = (struct obd_ioctl_data *)buffer;
2437
2438         fd = open(OBD_DEV_PATH, O_RDONLY);
2439         if (fd == -1)
2440                 return -errno;
2441
2442         memset(buffer, 0, buffer_size);
2443         data->ioc_version = OBD_IOCTL_VERSION;
2444         data->ioc_inllen1 = buffer_size - size_round(sizeof(*data));
2445         data->ioc_inlbuf1 = buffer + size_round(sizeof(*data));
2446         data->ioc_len = obd_ioctl_packlen(data);
2447
2448         rc = ioctl(fd, OBD_GET_VERSION, buffer);
2449         if (rc == -1) {
2450                 rc = errno;
2451                 close(fd);
2452                 return -rc;
2453         }
2454         close(fd);
2455         *version = data->ioc_bulk;
2456         return 0;
2457 }