Whamcloud - gitweb
LU-387 mmp.sh test_9 failed
[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;
611         int rc;
612
613         path = realpath(pathname, NULL);
614         if (path == NULL) {
615                 char buf[PATH_MAX + 1], *ptr;
616
617                 buf[0] = 0;
618                 if (pathname[0] != '/') {
619                         /* Need an absolute path, but realpath() only works for
620                          * pathnames that actually exist.  We go through the
621                          * extra hurdle of dirname(getcwd() + pathname) in
622                          * case the relative pathname contains ".." in it. */
623                         if (getcwd(buf, sizeof(buf) - 1) == NULL)
624                                 return -errno;
625                         strcat(buf, "/");
626                 }
627                 strncat(buf, pathname, sizeof(buf) - strlen(buf));
628                 path = realpath(buf, NULL);
629                 if (path == NULL) {
630                         ptr = strrchr(buf, '/');
631                         if (ptr == NULL)
632                                 return -ENOENT;
633                         *ptr = '\0';
634                         path = realpath(buf, NULL);
635                         if (path == NULL) {
636                                 llapi_err(LLAPI_MSG_ERROR,
637                                           "pathname '%s' cannot expand",
638                                           pathname);
639                                 return -errno;
640                         }
641                 }
642         }
643         rc = get_root_path(WANT_FSNAME | WANT_ERROR, fsname, NULL, path, -1);
644         free(path);
645         return rc;
646 }
647
648 /* return the first file matching this pattern */
649 static int first_match(char *pattern, char *buffer)
650 {
651         glob_t glob_info;
652
653         if (glob(pattern, GLOB_BRACE, NULL, &glob_info))
654                 return -ENOENT;
655
656         if (glob_info.gl_pathc < 1) {
657                 globfree(&glob_info);
658                 return -ENOENT;
659         }
660
661         strcpy(buffer, glob_info.gl_pathv[0]);
662
663         globfree(&glob_info);
664         return 0;
665 }
666
667 /*
668  * find the pool directory path under /proc
669  * (can be also used to test if a fsname is known)
670  */
671 static int poolpath(char *fsname, char *pathname, char *pool_pathname)
672 {
673         int rc = 0;
674         char pattern[PATH_MAX + 1];
675         char buffer[PATH_MAX];
676
677         if (fsname == NULL) {
678                 rc = llapi_search_fsname(pathname, buffer);
679                 if (rc != 0)
680                         return rc;
681                 fsname = buffer;
682                 strcpy(pathname, fsname);
683         }
684
685         snprintf(pattern, PATH_MAX, "/proc/fs/lustre/lov/%s-*/pools", fsname);
686         rc = first_match(pattern, buffer);
687         if (rc)
688                 return rc;
689
690         /* in fsname test mode, pool_pathname is NULL */
691         if (pool_pathname != NULL)
692                 strcpy(pool_pathname, buffer);
693
694         return 0;
695 }
696
697 /**
698  * Get the list of pool members.
699  * \param poolname    string of format \<fsname\>.\<poolname\>
700  * \param members     caller-allocated array of char*
701  * \param list_size   size of the members array
702  * \param buffer      caller-allocated buffer for storing OST names
703  * \param buffer_size size of the buffer
704  *
705  * \return number of members retrieved for this pool
706  * \retval -error failure
707  */
708 int llapi_get_poolmembers(const char *poolname, char **members,
709                           int list_size, char *buffer, int buffer_size)
710 {
711         char fsname[PATH_MAX + 1];
712         char *pool, *tmp;
713         char pathname[PATH_MAX + 1];
714         char path[PATH_MAX + 1];
715         char buf[1024];
716         FILE *fd;
717         int rc = 0;
718         int nb_entries = 0;
719         int used = 0;
720
721         /* name is FSNAME.POOLNAME */
722         if (strlen(poolname) > PATH_MAX)
723                 return -EOVERFLOW;
724         strcpy(fsname, poolname);
725         pool = strchr(fsname, '.');
726         if (pool == NULL)
727                 return -EINVAL;
728
729         *pool = '\0';
730         pool++;
731
732         rc = poolpath(fsname, NULL, pathname);
733         if (rc != 0) {
734                 errno = -rc;
735                 llapi_err(LLAPI_MSG_ERROR, "Lustre filesystem '%s' not found",
736                           fsname);
737                 return rc;
738         }
739
740         llapi_printf(LLAPI_MSG_NORMAL, "Pool: %s.%s\n", fsname, pool);
741         sprintf(path, "%s/%s", pathname, pool);
742         if ((fd = fopen(path, "r")) == NULL) {
743                 llapi_err(LLAPI_MSG_ERROR, "Cannot open %s", path);
744                 return -EINVAL;
745         }
746
747         rc = 0;
748         while (fgets(buf, sizeof(buf), fd) != NULL) {
749                 if (nb_entries >= list_size) {
750                         rc = -EOVERFLOW;
751                         break;
752                 }
753                 /* remove '\n' */
754                 if ((tmp = strchr(buf, '\n')) != NULL)
755                         *tmp='\0';
756                 if (used + strlen(buf) + 1 > buffer_size) {
757                         rc = -EOVERFLOW;
758                         break;
759                 }
760
761                 strcpy(buffer + used, buf);
762                 members[nb_entries] = buffer + used;
763                 used += strlen(buf) + 1;
764                 nb_entries++;
765                 rc = nb_entries;
766         }
767
768         fclose(fd);
769         return rc;
770 }
771
772 /**
773  * Get the list of pools in a filesystem.
774  * \param name        filesystem name or path
775  * \param poollist    caller-allocated array of char*
776  * \param list_size   size of the poollist array
777  * \param buffer      caller-allocated buffer for storing pool names
778  * \param buffer_size size of the buffer
779  *
780  * \return number of pools retrieved for this filesystem
781  * \retval -error failure
782  */
783 int llapi_get_poollist(const char *name, char **poollist, int list_size,
784                        char *buffer, int buffer_size)
785 {
786         char fsname[PATH_MAX + 1], rname[PATH_MAX + 1], pathname[PATH_MAX + 1];
787         char *ptr;
788         DIR *dir;
789         struct dirent pool;
790         struct dirent *cookie = NULL;
791         int rc = 0;
792         unsigned int nb_entries = 0;
793         unsigned int used = 0;
794         unsigned int i;
795
796         /* initilize output array */
797         for (i = 0; i < list_size; i++)
798                 poollist[i] = NULL;
799
800         /* is name a pathname ? */
801         ptr = strchr(name, '/');
802         if (ptr != NULL) {
803                 /* only absolute pathname is supported */
804                 if (*name != '/')
805                         return -EINVAL;
806                 if (!realpath(name, rname)) {
807                         rc = -errno;
808                         llapi_err(LLAPI_MSG_ERROR, "invalid path '%s'", name);
809                         return rc;
810                 }
811
812                 rc = poolpath(NULL, rname, pathname);
813                 if (rc != 0) {
814                         errno = -rc;
815                         llapi_err(LLAPI_MSG_ERROR, "'%s' is not"
816                                   " a Lustre filesystem", name);
817                         return rc;
818                 }
819                 strcpy(fsname, rname);
820         } else {
821                 /* name is FSNAME */
822                 strcpy(fsname, name);
823                 rc = poolpath(fsname, NULL, pathname);
824         }
825         if (rc != 0) {
826                 errno = -rc;
827                 llapi_err(LLAPI_MSG_ERROR, "Lustre filesystem '%s' not found",
828                           name);
829                 return rc;
830         }
831
832         llapi_printf(LLAPI_MSG_NORMAL, "Pools from %s:\n", fsname);
833         if ((dir = opendir(pathname)) == NULL) {
834                 llapi_err(LLAPI_MSG_ERROR, "Could not open pool list for '%s'",
835                           name);
836                 return -errno;
837         }
838
839         while(1) {
840                 rc = readdir_r(dir, &pool, &cookie);
841
842                 if (rc != 0) {
843                         llapi_err(LLAPI_MSG_ERROR,
844                                   "Error reading pool list for '%s'", name);
845                         return -errno;
846                 } else if ((rc == 0) && (cookie == NULL))
847                         /* end of directory */
848                         break;
849
850                 /* ignore . and .. */
851                 if (!strcmp(pool.d_name, ".") || !strcmp(pool.d_name, ".."))
852                         continue;
853
854                 /* check output bounds */
855                 if (nb_entries >= list_size)
856                         return -EOVERFLOW;
857
858                 /* +2 for '.' and final '\0' */
859                 if (used + strlen(pool.d_name) + strlen(fsname) + 2
860                     > buffer_size)
861                         return -EOVERFLOW;
862
863                 sprintf(buffer + used, "%s.%s", fsname, pool.d_name);
864                 poollist[nb_entries] = buffer + used;
865                 used += strlen(pool.d_name) + strlen(fsname) + 2;
866                 nb_entries++;
867         }
868
869         closedir(dir);
870         return nb_entries;
871 }
872
873 /* wrapper for lfs.c and obd.c */
874 int llapi_poollist(const char *name)
875 {
876         /* list of pool names (assume that pool count is smaller
877            than OST count) */
878         char *list[FIND_MAX_OSTS];
879         char *buffer;
880         /* fsname-OST0000_UUID < 32 char, 1 per OST */
881         int bufsize = FIND_MAX_OSTS * 32;
882         int i, nb;
883
884         buffer = malloc(bufsize);
885         if (buffer == NULL)
886                 return -ENOMEM;
887
888         if ((name[0] == '/') || (strchr(name, '.') == NULL))
889                 /* name is a path or fsname */
890                 nb = llapi_get_poollist(name, list, FIND_MAX_OSTS, buffer,
891                                         bufsize);
892         else
893                 /* name is a pool name (<fsname>.<poolname>) */
894                 nb = llapi_get_poolmembers(name, list, FIND_MAX_OSTS, buffer,
895                                            bufsize);
896
897         for (i = 0; i < nb; i++)
898                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", list[i]);
899
900         free(buffer);
901         return (nb < 0 ? nb : 0);
902 }
903
904 typedef int (semantic_func_t)(char *path, DIR *parent, DIR *d,
905                               void *data, struct dirent64 *de);
906
907 #define MAX_LOV_UUID_COUNT      max(LOV_MAX_STRIPE_COUNT, 1000)
908 #define OBD_NOT_FOUND           (-1)
909
910 static int common_param_init(struct find_param *param)
911 {
912         param->lumlen = lov_mds_md_size(MAX_LOV_UUID_COUNT, LOV_MAGIC_V3);
913         if ((param->lmd = malloc(sizeof(lstat_t) + param->lumlen)) == NULL) {
914                 llapi_err(LLAPI_MSG_ERROR,
915                           "error: allocation of %d bytes for ioctl",
916                           sizeof(lstat_t) + param->lumlen);
917                 return -ENOMEM;
918         }
919
920         param->got_uuids = 0;
921         param->obdindexes = NULL;
922         param->obdindex = OBD_NOT_FOUND;
923         return 0;
924 }
925
926 static void find_param_fini(struct find_param *param)
927 {
928         if (param->obdindexes)
929                 free(param->obdindexes);
930
931         if (param->lmd)
932                 free(param->lmd);
933 }
934
935 static int cb_common_fini(char *path, DIR *parent, DIR *d, void *data,
936                           struct dirent64 *de)
937 {
938         struct find_param *param = (struct find_param *)data;
939         param->depth--;
940         return 0;
941 }
942
943 static DIR *opendir_parent(char *path)
944 {
945         DIR *parent;
946         char *fname;
947         char c;
948
949         fname = strrchr(path, '/');
950         if (fname == NULL)
951                 return opendir(".");
952
953         c = fname[1];
954         fname[1] = '\0';
955         parent = opendir(path);
956         fname[1] = c;
957         return parent;
958 }
959
960 int llapi_mds_getfileinfo(char *path, DIR *parent,
961                           struct lov_user_mds_data *lmd)
962 {
963         lstat_t *st = &lmd->lmd_st;
964         char *fname = strrchr(path, '/');
965         int ret = 0;
966
967         if (parent == NULL)
968                 return -EINVAL;
969
970         fname = (fname == NULL ? path : fname + 1);
971         /* retrieve needed file info */
972         strncpy((char *)lmd, fname, lov_mds_md_size(MAX_LOV_UUID_COUNT,
973                 LOV_MAGIC));
974         ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO, (void *)lmd);
975
976         if (ret) {
977                 if (errno == ENOTTY) {
978                         /* ioctl is not supported, it is not a lustre fs.
979                          * Do the regular lstat(2) instead. */
980                         ret = lstat_f(path, st);
981                         if (ret) {
982                                 llapi_err(LLAPI_MSG_ERROR,
983                                           "error: %s: lstat failed for %s",
984                                           __func__, path);
985                                 return ret;
986                         }
987                 } else if (errno == ENOENT) {
988                         llapi_err(LLAPI_MSG_WARN,
989                                   "warning: %s: %s does not exist",
990                                   __func__, path);
991                         return -ENOENT;
992                 } else {
993                         llapi_err(LLAPI_MSG_ERROR,
994                                  "error: %s: IOC_MDC_GETFILEINFO failed for %s",
995                                  __func__, path);
996                         return ret;
997                 }
998         }
999
1000         return 0;
1001 }
1002
1003 static int llapi_semantic_traverse(char *path, int size, DIR *parent,
1004                                    semantic_func_t sem_init,
1005                                    semantic_func_t sem_fini, void *data,
1006                                    struct dirent64 *de)
1007 {
1008         struct dirent64 *dent;
1009         int len, ret;
1010         DIR *d, *p = NULL;
1011
1012         ret = 0;
1013         len = strlen(path);
1014
1015         d = opendir(path);
1016         if (!d && errno != ENOTDIR) {
1017                 llapi_err(LLAPI_MSG_ERROR, "%s: Failed to open '%s'",
1018                           __func__, path);
1019                 return -EINVAL;
1020         } else if (!d && !parent) {
1021                 /* ENOTDIR. Open the parent dir. */
1022                 p = opendir_parent(path);
1023                 if (!p)
1024                         GOTO(out, ret = -EINVAL);
1025         }
1026
1027         if (sem_init && (ret = sem_init(path, parent ?: p, d, data, de)))
1028                 goto err;
1029
1030         if (!d)
1031                 GOTO(out, ret = 0);
1032
1033         while ((dent = readdir64(d)) != NULL) {
1034                 ((struct find_param *)data)->have_fileinfo = 0;
1035
1036                 if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
1037                         continue;
1038
1039                 path[len] = 0;
1040                 if ((len + dent->d_reclen + 2) > size) {
1041                         llapi_err(LLAPI_MSG_ERROR,
1042                                   "error: %s: string buffer is too small",
1043                                   __func__);
1044                         break;
1045                 }
1046
1047                 if (path[len-1] != '/')
1048                         strcat(path, "/");
1049                 strcat(path, dent->d_name);
1050
1051                 if (dent->d_type == DT_UNKNOWN) {
1052                         lstat_t *st = &((struct find_param *)data)->lmd->lmd_st;
1053
1054                         ret = llapi_mds_getfileinfo(path, d,
1055                                              ((struct find_param *)data)->lmd);
1056                         if (ret == 0) {
1057                                 ((struct find_param *)data)->have_fileinfo = 1;
1058                                 dent->d_type =
1059                                         llapi_filetype_dir_table[st->st_mode &
1060                                                                  S_IFMT];
1061                         }
1062                         if (ret == -ENOENT)
1063                                 continue;
1064                 }
1065
1066                 switch (dent->d_type) {
1067                 case DT_UNKNOWN:
1068                         llapi_err(LLAPI_MSG_ERROR,
1069                                   "error: %s: '%s' is UNKNOWN type %d",
1070                                   __func__, dent->d_name, dent->d_type);
1071                         break;
1072                 case DT_DIR:
1073                         ret = llapi_semantic_traverse(path, size, d, sem_init,
1074                                                       sem_fini, data, dent);
1075                         if (ret < 0)
1076                                 goto out;
1077                         break;
1078                 default:
1079                         ret = 0;
1080                         if (sem_init) {
1081                                 ret = sem_init(path, d, NULL, data, dent);
1082                                 if (ret < 0)
1083                                         goto out;
1084                         }
1085                         if (sem_fini && ret == 0)
1086                                 sem_fini(path, d, NULL, data, dent);
1087                 }
1088         }
1089
1090 out:
1091         path[len] = 0;
1092
1093         if (sem_fini)
1094                 sem_fini(path, parent, d, data, de);
1095 err:
1096         if (d)
1097                 closedir(d);
1098         if (p)
1099                 closedir(p);
1100         return ret;
1101 }
1102
1103 static int param_callback(char *path, semantic_func_t sem_init,
1104                           semantic_func_t sem_fini, struct find_param *param)
1105 {
1106         int ret, len = strlen(path);
1107         char *buf;
1108
1109         if (len > PATH_MAX) {
1110                 llapi_err(LLAPI_MSG_ERROR, "Path name '%s' is too long", path);
1111                 return -EINVAL;
1112         }
1113
1114         buf = (char *)malloc(PATH_MAX + 1);
1115         if (!buf)
1116                 return -ENOMEM;
1117
1118         ret = common_param_init(param);
1119         if (ret)
1120                 goto out;
1121         param->depth = 0;
1122
1123         strncpy(buf, path, PATH_MAX + 1);
1124         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, sem_init,
1125                                       sem_fini, param, NULL);
1126 out:
1127         find_param_fini(param);
1128         free(buf);
1129         return ret < 0 ? ret : 0;
1130 }
1131
1132 int llapi_file_fget_lov_uuid(int fd, struct obd_uuid *lov_name)
1133 {
1134         int rc = ioctl(fd, OBD_IOC_GETNAME, lov_name);
1135         if (rc) {
1136                 rc = errno;
1137                 llapi_err(LLAPI_MSG_ERROR, "error: can't get lov name.");
1138         }
1139         return rc;
1140 }
1141
1142 int llapi_file_get_lov_uuid(const char *path, struct obd_uuid *lov_uuid)
1143 {
1144         int fd, rc;
1145
1146         fd = open(path, O_RDONLY);
1147         if (fd < 0) {
1148                 rc = errno;
1149                 llapi_err(LLAPI_MSG_ERROR, "error opening %s", path);
1150                 return rc;
1151         }
1152
1153         rc = llapi_file_fget_lov_uuid(fd, lov_uuid);
1154
1155         close(fd);
1156
1157         return rc;
1158 }
1159
1160 /*
1161  * If uuidp is NULL, return the number of available obd uuids.
1162  * If uuidp is non-NULL, then it will return the uuids of the obds. If
1163  * there are more OSTs then allocated to uuidp, then an error is returned with
1164  * the ost_count set to number of available obd uuids.
1165  */
1166 int llapi_lov_get_uuids(int fd, struct obd_uuid *uuidp, int *ost_count)
1167 {
1168         struct obd_uuid lov_name;
1169         char buf[1024];
1170         FILE *fp;
1171         int rc = 0, index = 0;
1172
1173         /* Get the lov name */
1174         rc = llapi_file_fget_lov_uuid(fd, &lov_name);
1175         if (rc)
1176                 return rc;
1177
1178         /* Now get the ost uuids from /proc */
1179         snprintf(buf, sizeof(buf), "/proc/fs/lustre/lov/%s/target_obd",
1180                  lov_name.uuid);
1181         fp = fopen(buf, "r");
1182         if (fp == NULL) {
1183                 rc = errno;
1184                 llapi_err(LLAPI_MSG_ERROR, "error: opening '%s'", buf);
1185                 return rc;
1186         }
1187
1188         while (fgets(buf, sizeof(buf), fp) != NULL) {
1189                 if (uuidp && (index < *ost_count)) {
1190                         if (sscanf(buf, "%d: %s", &index, uuidp[index].uuid) <2)
1191                                 break;
1192                 }
1193                 index++;
1194         }
1195
1196         fclose(fp);
1197
1198         if (uuidp && (index >= *ost_count))
1199                 return -EOVERFLOW;
1200
1201         *ost_count = index;
1202         return rc;
1203 }
1204
1205 /* Check if user specified value matches a real uuid.  Ignore _UUID,
1206  * -osc-4ba41334, other trailing gunk in comparison.
1207  * @param real_uuid ends in "_UUID"
1208  * @param search_uuid may or may not end in "_UUID"
1209  */
1210 int llapi_uuid_match(char *real_uuid, char *search_uuid)
1211 {
1212         int cmplen = strlen(real_uuid);
1213         int searchlen = strlen(search_uuid);
1214
1215         if (cmplen > 5 && strcmp(real_uuid + cmplen - 5, "_UUID") == 0)
1216                 cmplen -= 5;
1217         if (searchlen > 5 && strcmp(search_uuid + searchlen - 5, "_UUID") == 0)
1218                 searchlen -= 5;
1219
1220         /* The UUIDs may legitimately be different lengths, if
1221          * the system was upgraded from an older version. */
1222         if (cmplen != searchlen)
1223                 return 0;
1224
1225         return (strncmp(search_uuid, real_uuid, cmplen) == 0);
1226 }
1227
1228 /* Here, param->obduuid points to a single obduuid, the index of which is
1229  * returned in param->obdindex */
1230 static int setup_obd_uuid(DIR *dir, char *dname, struct find_param *param)
1231 {
1232         struct obd_uuid lov_uuid;
1233         char uuid[sizeof(struct obd_uuid)];
1234         char buf[1024];
1235         FILE *fp;
1236         int rc = 0, index;
1237
1238         if (param->got_uuids)
1239                 return rc;
1240
1241         /* Get the lov name */
1242         rc = llapi_file_fget_lov_uuid(dirfd(dir), &lov_uuid);
1243         if (rc) {
1244                 if (errno != ENOTTY) {
1245                         rc = errno;
1246                         llapi_err(LLAPI_MSG_ERROR,
1247                                   "error: can't get lov name: %s", dname);
1248                 } else {
1249                         rc = 0;
1250                 }
1251                 return rc;
1252         }
1253
1254         param->got_uuids = 1;
1255
1256         /* Now get the ost uuids from /proc */
1257         snprintf(buf, sizeof(buf), "/proc/fs/lustre/lov/%s/target_obd",
1258                  lov_uuid.uuid);
1259         fp = fopen(buf, "r");
1260         if (fp == NULL) {
1261                 rc = errno;
1262                 llapi_err(LLAPI_MSG_ERROR, "error: opening '%s'", buf);
1263                 return rc;
1264         }
1265
1266         if (!param->obduuid && !param->quiet && !param->obds_printed)
1267                 llapi_printf(LLAPI_MSG_NORMAL, "OBDS:\n");
1268
1269         while (fgets(buf, sizeof(buf), fp) != NULL) {
1270                 if (sscanf(buf, "%d: %s", &index, uuid) < 2)
1271                         break;
1272
1273                 if (param->obduuid) {
1274                         if (llapi_uuid_match(uuid, param->obduuid->uuid)) {
1275                                 param->obdindex = index;
1276                                 break;
1277                         }
1278                 } else if (!param->quiet && !param->obds_printed) {
1279                         /* Print everything */
1280                         llapi_printf(LLAPI_MSG_NORMAL, "%s", buf);
1281                 }
1282         }
1283         param->obds_printed = 1;
1284
1285         fclose(fp);
1286
1287         if (param->obduuid && (param->obdindex == OBD_NOT_FOUND)) {
1288                 llapi_err_noerrno(LLAPI_MSG_ERROR,
1289                                   "error: %s: unknown obduuid: %s",
1290                                   __FUNCTION__, param->obduuid->uuid);
1291                 rc = -EINVAL;
1292         }
1293
1294         return (rc);
1295 }
1296
1297 /* In this case, param->obduuid will be an array of obduuids and
1298  * obd index for all these obduuids will be returned in
1299  * param->obdindexes */
1300 static int setup_obd_indexes(DIR *dir, struct find_param *param)
1301 {
1302         struct obd_uuid *uuids = NULL;
1303         int obdcount = INIT_ALLOC_NUM_OSTS;
1304         int ret, obd_valid = 0, obdnum, i;
1305
1306         uuids = (struct obd_uuid *)malloc(INIT_ALLOC_NUM_OSTS *
1307                                           sizeof(struct obd_uuid));
1308         if (uuids == NULL)
1309                 return -ENOMEM;
1310
1311 retry_get_uuids:
1312         ret = llapi_lov_get_uuids(dirfd(dir), uuids,
1313                                   &obdcount);
1314         if (ret) {
1315                 struct obd_uuid *uuids_temp;
1316
1317                 if (ret == -EOVERFLOW) {
1318                         uuids_temp = realloc(uuids, obdcount *
1319                                              sizeof(struct obd_uuid));
1320                         if (uuids_temp != NULL)
1321                                 goto retry_get_uuids;
1322                         else
1323                                 ret = -ENOMEM;
1324                 }
1325
1326                 llapi_err(LLAPI_MSG_ERROR, "get ost uuid failed");
1327                 return ret;
1328         }
1329
1330         param->obdindexes = malloc(param->num_obds * sizeof(param->obdindex));
1331         if (param->obdindexes == NULL)
1332                 return -ENOMEM;
1333
1334         for (obdnum = 0; obdnum < param->num_obds; obdnum++) {
1335                 for (i = 0; i < obdcount; i++) {
1336                         if (llapi_uuid_match(uuids[i].uuid,
1337                                              param->obduuid[obdnum].uuid)) {
1338                                 param->obdindexes[obdnum] = i;
1339                                 obd_valid++;
1340                                 break;
1341                         }
1342                 }
1343                 if (i >= obdcount) {
1344                         param->obdindexes[obdnum] = OBD_NOT_FOUND;
1345                         llapi_err_noerrno(LLAPI_MSG_ERROR,
1346                                           "error: %s: unknown obduuid: %s",
1347                                           __FUNCTION__,
1348                                           param->obduuid[obdnum].uuid);
1349                         ret = -EINVAL;
1350                 }
1351         }
1352
1353         if (obd_valid == 0)
1354                 param->obdindex = OBD_NOT_FOUND;
1355         else
1356                 param->obdindex = obd_valid;
1357
1358         param->got_uuids = 1;
1359
1360         return ret;
1361 }
1362
1363
1364 int llapi_ostlist(char *path, struct find_param *param)
1365 {
1366         DIR *dir;
1367         int ret;
1368
1369         dir = opendir(path);
1370         if (dir == NULL)
1371                 return -errno;
1372
1373         ret = setup_obd_uuid(dir, path, param);
1374         closedir(dir);
1375
1376         return ret;
1377 }
1378
1379 static void lov_dump_user_lmm_header(struct lov_user_md *lum, char *path,
1380                                      int is_dir, int verbose, int depth,
1381                                      char *pool_name)
1382 {
1383         char *prefix = is_dir ? "" : "lmm_";
1384         char *nl = is_dir ? "" : "\n";
1385         char *sp = "";
1386
1387         if (is_dir && lum->lmm_object_gr == LOV_OBJECT_GROUP_DEFAULT) {
1388                 lum->lmm_object_gr = LOV_OBJECT_GROUP_CLEAR;
1389                 if (verbose & VERBOSE_DETAIL)
1390                         llapi_printf(LLAPI_MSG_NORMAL, "(Default) ");
1391         }
1392
1393         if (depth && path && ((verbose != VERBOSE_OBJID) || !is_dir))
1394                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
1395
1396         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
1397                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_magic:          0x%08X\n",
1398                              lum->lmm_magic);
1399                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_gr:      "LPX64"\n",
1400                              lum->lmm_object_gr);
1401                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_id:      "LPX64"\n",
1402                              lum->lmm_object_id);
1403         }
1404
1405         if (verbose & VERBOSE_COUNT) {
1406                 if (verbose & ~VERBOSE_COUNT) {
1407                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_count:   ",
1408                                      prefix);
1409                         sp = is_dir ? " " : "";
1410                 }
1411                 if (is_dir) 
1412                         llapi_printf(LLAPI_MSG_NORMAL, "%d%s",
1413                                      lum->lmm_stripe_count ==
1414                                      (typeof(lum->lmm_stripe_count))(-1) ? -1 :
1415                                      lum->lmm_stripe_count, nl);
1416                 else
1417                         llapi_printf(LLAPI_MSG_NORMAL, "%u%s",
1418                                      (int)lum->lmm_stripe_count, nl);
1419         }
1420
1421         if (verbose & VERBOSE_SIZE) {
1422                 if (verbose & ~VERBOSE_SIZE) {
1423                         llapi_printf(LLAPI_MSG_NORMAL, "%s%sstripe_size:    ",
1424                                      sp, prefix);
1425                         sp = is_dir ? " " : "";
1426                 }
1427                 llapi_printf(LLAPI_MSG_NORMAL, "%u%s", lum->lmm_stripe_size,
1428                              nl);
1429         }
1430
1431         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
1432                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_stripe_pattern: %x%s",
1433                              lum->lmm_pattern, nl);
1434         }
1435
1436         if (verbose & VERBOSE_OFFSET) {
1437                 if (verbose & ~VERBOSE_OFFSET) {
1438                         llapi_printf(LLAPI_MSG_NORMAL, "%s%sstripe_offset:  ",
1439                                      sp, prefix);
1440                         sp = is_dir ? " " : "";
1441                 }
1442                 if (is_dir) 
1443                         llapi_printf(LLAPI_MSG_NORMAL, "%d%s",
1444                                      lum->lmm_stripe_offset ==
1445                                      (typeof(lum->lmm_stripe_offset))(-1) ? -1 :
1446                                      lum->lmm_stripe_offset, nl);
1447                 else
1448                         llapi_printf(LLAPI_MSG_NORMAL, "%u%s",
1449                                      lum->lmm_objects[0].l_ost_idx, nl);
1450         }
1451
1452         if ((verbose & VERBOSE_POOL) && (pool_name != NULL)) {
1453                 llapi_printf(LLAPI_MSG_NORMAL, "%spool: %s", sp, pool_name);
1454                 is_dir = 1;
1455         }
1456
1457         if (is_dir && (verbose != VERBOSE_OBJID))
1458                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1459 }
1460
1461 static void lov_dump_user_lmm_join(struct lov_user_md_v1 *lum, int is_dir,
1462                                    int obdstripe, int obdindex, int header)
1463 {
1464         struct lov_user_md_join *lumj = (struct lov_user_md_join *)lum;
1465         int i;
1466
1467         if (header && (obdstripe == 1))
1468                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_extent_count:   %x\n",
1469                              lumj->lmm_extent_count);
1470
1471         if (!is_dir && (header & VERBOSE_OBJID)) {
1472                 unsigned long long start = -1, end = 0;
1473
1474                 if (obdstripe == 1)
1475                         llapi_printf(LLAPI_MSG_NORMAL,
1476                                      "joined\tobdidx\t\t objid\t\tobjid\t\t "
1477                                      "group\t\tstart\t\tend\n");
1478                 for (i = 0; i < lumj->lmm_stripe_count; i++) {
1479                         int idx = lumj->lmm_objects[i].l_ost_idx;
1480                         long long oid = lumj->lmm_objects[i].l_object_id;
1481                         long long gr = lumj->lmm_objects[i].l_object_gr;
1482                         if (obdindex == OBD_NOT_FOUND || obdindex == idx)
1483                                 llapi_printf(LLAPI_MSG_NORMAL,
1484                                              "\t%6u\t%14llu\t%#13llx\t%14llu%s",
1485                                              idx, oid, oid, gr,
1486                                              obdindex == idx ? " *" : "");
1487                         if (start != lumj->lmm_objects[i].l_extent_start ||
1488                             end != lumj->lmm_objects[i].l_extent_end) {
1489                                 start = lumj->lmm_objects[i].l_extent_start;
1490                                 llapi_printf(LLAPI_MSG_NORMAL,"\t%14llu",start);
1491                                 end = lumj->lmm_objects[i].l_extent_end;
1492                                 if (end == (unsigned long long)-1)
1493                                         llapi_printf(LLAPI_MSG_NORMAL,
1494                                                      "\t\tEOF\n");
1495                                 else
1496                                         llapi_printf(LLAPI_MSG_NORMAL,
1497                                                      "\t\t%llu\n", end);
1498                         } else {
1499                                 llapi_printf(LLAPI_MSG_NORMAL, "\t\t\t\t\n");
1500                         }
1501                 }
1502                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1503         }
1504 }
1505
1506 static void lov_dump_user_lmm_v1v3(struct lov_user_md *lum,
1507                                    struct lov_user_ost_data_v1 *objects,
1508                                    int is_dir, int obdstripe,
1509                                    int obdindex,int header)
1510 {
1511         int i;
1512
1513         if (!is_dir && (header & VERBOSE_OBJID)) {
1514                 if (obdstripe == 1)
1515                         llapi_printf(LLAPI_MSG_NORMAL,
1516                                      "\tobdidx\t\t objid\t\tobjid\t\t group\n");
1517
1518                 for (i = 0; i < lum->lmm_stripe_count; i++) {
1519                         int idx = objects[i].l_ost_idx;
1520                         long long oid = objects[i].l_object_id;
1521                         long long gr = objects[i].l_object_gr;
1522                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
1523                                 llapi_printf(LLAPI_MSG_NORMAL,
1524                                            "\t%6u\t%14llu\t%#13llx\t%14llu%s\n",
1525                                            idx, oid, oid, gr,
1526                                            obdindex == idx ? " *" : "");
1527                 }
1528                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1529         }
1530 }
1531
1532 void llapi_lov_dump_user_lmm(struct find_param *param,
1533                              char *path, int is_dir)
1534 {
1535         int i, obdstripe = (param->obdindex != OBD_NOT_FOUND) ? 0 : 1;
1536         struct lov_user_md *lum = &param->lmd->lmd_lmm;
1537
1538         if (!obdstripe) {
1539                 for (i = 0; !is_dir && i < lum->lmm_stripe_count; i++) {
1540                         if (param->obdindex == lum->lmm_objects[i].l_ost_idx) {
1541                                 obdstripe = 1;
1542                                 break;
1543                         }
1544                 }
1545         }
1546
1547         switch(*(__u32 *)&param->lmd->lmd_lmm) { /* lum->lmm_magic */
1548         case LOV_USER_MAGIC_V1:
1549                 if (param->verbose && (obdstripe == 1))
1550                         lov_dump_user_lmm_header(lum, path, is_dir,
1551                                                  param->verbose,
1552                                                  param->maxdepth,
1553                                                  NULL);
1554                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm,
1555                                        param->lmd->lmd_lmm.lmm_objects,
1556                                        is_dir, obdstripe,
1557                                        param->obdindex,
1558                                        param->verbose);
1559                 break;
1560         case LOV_USER_MAGIC_JOIN:
1561                 if (param->verbose && (obdstripe == 1))
1562                         lov_dump_user_lmm_header(lum, path, is_dir,
1563                                                  param->verbose,
1564                                                  param->maxdepth,
1565                                                  NULL);
1566                 lov_dump_user_lmm_join(&param->lmd->lmd_lmm, is_dir,
1567                                        obdstripe, param->obdindex,
1568                                        param->verbose);
1569                 break;
1570         case LOV_USER_MAGIC_V3: {
1571                 char pool_name[LOV_MAXPOOLNAME + 1];
1572                 struct lov_user_ost_data_v1 *objects;
1573                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
1574
1575                 strncpy(pool_name, lmmv3->lmm_pool_name, LOV_MAXPOOLNAME);
1576                 pool_name[LOV_MAXPOOLNAME] = '\0';
1577                 objects = lmmv3->lmm_objects;
1578                 if (param->verbose && (obdstripe == 1))
1579                         lov_dump_user_lmm_header(lum, path, is_dir,
1580                                                  param->verbose,
1581                                                  param->maxdepth,
1582                                                  pool_name);
1583                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, objects, is_dir,
1584                                        obdstripe, param->obdindex,
1585                                        param->verbose);
1586                 break;
1587         }
1588         default:
1589                 llapi_printf(LLAPI_MSG_NORMAL, "unknown lmm_magic:  %#x "
1590                              "(expecting one of %#x %#x %#x)\n",
1591                              param->lmd->lmd_lmm.lmm_magic,
1592                              LOV_USER_MAGIC_V1, LOV_USER_MAGIC_JOIN,
1593                              LOV_USER_MAGIC_V3);
1594                 return;
1595         }
1596 }
1597
1598 int llapi_file_get_stripe(const char *path, struct lov_user_md *lum)
1599 {
1600         const char *fname;
1601         char *dname;
1602         int fd, rc = 0;
1603
1604         fname = strrchr(path, '/');
1605         if (strlen(fname) + 1 < sizeof(struct lov_user_md))
1606                 return ENAMETOOLONG;
1607
1608         /* It should be a file (or other non-directory) */
1609         if (fname == NULL) {
1610                 dname = (char *)malloc(2);
1611                 if (dname == NULL)
1612                         return ENOMEM;
1613                 strcpy(dname, ".");
1614                 fname = (char *)path;
1615         } else {
1616                 dname = (char *)malloc(fname - path + 1);
1617                 if (dname == NULL)
1618                         return ENOMEM;
1619                 strncpy(dname, path, fname - path);
1620                 dname[fname - path] = '\0';
1621                 fname++;
1622         }
1623
1624         if ((fd = open(dname, O_RDONLY)) == -1) {
1625                 rc = errno;
1626                 free(dname);
1627                 return rc;
1628         }
1629
1630         strcpy((char *)lum, fname);
1631         if (ioctl(fd, IOC_MDC_GETFILESTRIPE, (void *)lum) == -1)
1632                 rc = errno;
1633
1634         if (close(fd) == -1 && rc == 0)
1635                 rc = errno;
1636
1637         free(dname);
1638
1639         return rc;
1640 }
1641
1642 int llapi_file_lookup(int dirfd, const char *name)
1643 {
1644         struct obd_ioctl_data data = { 0 };
1645         char rawbuf[8192];
1646         char *buf = rawbuf;
1647         int rc;
1648
1649         if (dirfd < 0 || name == NULL)
1650                 return -EINVAL;
1651
1652         data.ioc_version = OBD_IOCTL_VERSION;
1653         data.ioc_len = sizeof(data);
1654         data.ioc_inlbuf1 = (char *)name;
1655         data.ioc_inllen1 = strlen(name) + 1;
1656
1657         rc = obd_ioctl_pack(&data, &buf, sizeof(rawbuf));
1658         if (rc) {
1659                 llapi_err(LLAPI_MSG_ERROR,
1660                           "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
1661                           name, rc);
1662                 return rc;
1663         }
1664
1665         return ioctl(dirfd, IOC_MDC_LOOKUP, buf);
1666 }
1667
1668 /* Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
1669  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
1670  *
1671  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
1672  * The table below gives the answers for the specified parameters (value and
1673  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
1674  * --------------------------------------
1675  * 1 | file > limit; sign > 0 | -1 / -1 |
1676  * 2 | file = limit; sign > 0 |  ? /  1 |
1677  * 3 | file < limit; sign > 0 |  ? /  1 |
1678  * 4 | file > limit; sign = 0 | -1 / -1 |
1679  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
1680  * 6 | file < limit; sign = 0 |  ? / -1 |
1681  * 7 | file > limit; sign < 0 |  1 /  1 |
1682  * 8 | file = limit; sign < 0 |  ? / -1 |
1683  * 9 | file < limit; sign < 0 |  ? / -1 |
1684  * --------------------------------------
1685  * Note: 5th actually means that the value is within the interval
1686  * (limit - margin, limit]. */
1687 static int find_value_cmp(unsigned int file, unsigned int limit, int sign,
1688                           int negopt, unsigned long long margin, int mds)
1689 {
1690         int ret = -1;
1691
1692         if (sign > 0) {
1693                 if (file <= limit)
1694                         ret = mds ? 0 : 1;
1695         } else if (sign == 0) {
1696                 if (file <= limit && file + margin >= limit)
1697                         ret = mds ? 0 : 1;
1698                 else if (file + margin <= limit)
1699                         ret = mds ? 0 : -1;
1700         } else if (sign < 0) {
1701                 if (file >= limit)
1702                         ret = 1;
1703                 else if (mds)
1704                         ret = 0;
1705         }
1706
1707         return negopt ? ~ret + 1 : ret;
1708 }
1709
1710 /* Check if the file time matches all the given criteria (e.g. --atime +/-N).
1711  * Return -1 or 1 if file timestamp does not or does match the given criteria
1712  * correspondingly. Return 0 if the MDS time is being checked and there are
1713  * attributes on OSTs and it is not yet clear if the timespamp matches.
1714  *
1715  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
1716  * updated timestamps. */
1717 static int find_time_check(lstat_t *st, struct find_param *param, int mds)
1718 {
1719         int ret;
1720         int rc = 0;
1721
1722         /* Check if file is accepted. */
1723         if (param->atime) {
1724                 ret = find_value_cmp(st->st_atime, param->atime,
1725                                      param->asign, param->exclude_atime,
1726                                      24 * 60 * 60, mds);
1727                 if (ret < 0)
1728                         return ret;
1729                 rc = ret;
1730         }
1731
1732         if (param->mtime) {
1733                 ret = find_value_cmp(st->st_mtime, param->mtime,
1734                                      param->msign, param->exclude_mtime,
1735                                      24 * 60 * 60, mds);
1736                 if (ret < 0)
1737                         return ret;
1738
1739                 /* If the previous check matches, but this one is not yet clear,
1740                  * we should return 0 to do an RPC on OSTs. */
1741                 if (rc == 1)
1742                         rc = ret;
1743         }
1744
1745         if (param->ctime) {
1746                 ret = find_value_cmp(st->st_ctime, param->ctime,
1747                                      param->csign, param->exclude_ctime,
1748                                      24 * 60 * 60, mds);
1749                 if (ret < 0)
1750                         return ret;
1751
1752                 /* If the previous check matches, but this one is not yet clear,
1753                  * we should return 0 to do an RPC on OSTs. */
1754                 if (rc == 1)
1755                         rc = ret;
1756         }
1757
1758         return rc;
1759 }
1760
1761 static int cb_find_init(char *path, DIR *parent, DIR *dir,
1762                         void *data, struct dirent64 *de)
1763 {
1764         struct find_param *param = (struct find_param *)data;
1765         struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
1766         int decision = 1; /* 1 is accepted; -1 is rejected. */
1767         lstat_t *st = &param->lmd->lmd_st;
1768         int lustre_fs = 1;
1769         int checked_type = 0;
1770         int ret = 0;
1771
1772         LASSERT(parent != NULL || dir != NULL);
1773
1774         param->lmd->lmd_lmm.lmm_stripe_count = 0;
1775
1776         /* If a regular expression is presented, make the initial decision */
1777         if (param->pattern != NULL) {
1778                 char *fname = strrchr(path, '/');
1779                 fname = (fname == NULL ? path : fname + 1);
1780                 ret = fnmatch(param->pattern, fname, 0);
1781                 if ((ret == FNM_NOMATCH && !param->exclude_pattern) ||
1782                     (ret == 0 && param->exclude_pattern))
1783                         goto decided;
1784         }
1785
1786         /* See if we can check the file type from the dirent. */
1787         if (param->type && de != NULL && de->d_type != DT_UNKNOWN &&
1788             de->d_type <= DT_MAX) {
1789                 checked_type = 1;
1790                 if (llapi_dir_filetype_table[de->d_type] == param->type) {
1791                         if (param->exclude_type)
1792                                 goto decided;
1793                 } else {
1794                         if (!param->exclude_type)
1795                                 goto decided;
1796                 }
1797         }
1798
1799
1800         /* If a time or OST should be checked, the decision is not taken yet. */
1801         if (param->atime || param->ctime || param->mtime || param->obduuid ||
1802             param->size_check)
1803                 decision = 0;
1804
1805         ret = 0;
1806         /* Request MDS for the stat info. */
1807         if (param->have_fileinfo == 0) {
1808                 if (dir) {
1809                         /* retrieve needed file info */
1810                         ret = ioctl(dirfd(dir), LL_IOC_MDC_GETINFO,
1811                                     (void *)param->lmd);
1812                 } else {
1813                         char *fname = strrchr(path, '/');
1814                         fname = (fname == NULL ? path : fname + 1);
1815
1816                         /* retrieve needed file info */
1817                         strncpy((char *)param->lmd, fname, param->lumlen);
1818                         ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
1819                                    (void *)param->lmd);
1820                 }
1821         }
1822
1823         if (ret) {
1824                 if (errno == ENOTTY) {
1825                         /* ioctl is not supported, it is not a lustre fs.
1826                          * Do the regular lstat(2) instead. */
1827                         lustre_fs = 0;
1828                         ret = lstat_f(path, st);
1829                         if (ret) {
1830                                 llapi_err(LLAPI_MSG_ERROR,
1831                                           "error: %s: lstat failed for %s",
1832                                           __func__, path);
1833                                 return ret;
1834                         }
1835                 } else if (errno == ENOENT) {
1836                         llapi_err(LLAPI_MSG_WARN,
1837                                   "warning: %s: %s does not exist",
1838                                   __func__, path);
1839                         goto decided;
1840                 } else {
1841                         llapi_err(LLAPI_MSG_ERROR,"error: %s: %s failed for %s",
1842                                   __func__, dir ? "LL_IOC_MDC_GETINFO" :
1843                                   "IOC_MDC_GETFILEINFO", path);
1844                         return ret;
1845                 }
1846         }
1847
1848         if (param->check_uid) {
1849                 if (st->st_uid == param->uid) {
1850                         if (param->exclude_uid)
1851                                 goto decided;
1852                 } else {
1853                         if (!param->exclude_uid)
1854                                 goto decided;
1855                 }
1856         }
1857
1858         if (param->check_gid) {
1859                 if (st->st_gid == param->gid) {
1860                         if (param->exclude_gid)
1861                                 goto decided;
1862                 } else {
1863                         if (!param->exclude_gid)
1864                                 goto decided;
1865                 }
1866         }
1867
1868         if (param->check_pool) {
1869                 /* empty requested pool is taken as no pool search => V1 */
1870                 if ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V1 &&
1871                      param->poolname[0] == '\0') ||
1872                     (param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3 &&
1873                      (strncmp(lmmv3->lmm_pool_name, param->poolname,
1874                               LOV_MAXPOOLNAME) == 0 ||
1875                       strcmp(param->poolname, "*") == 0))) {
1876                         if (param->exclude_pool)
1877                                 goto decided;
1878                 } else {
1879                         if (!param->exclude_pool)
1880                                 goto decided;
1881                 }
1882         }
1883
1884         /* Check the time on mds. */
1885         if (!decision) {
1886                 int for_mds;
1887
1888                 for_mds = lustre_fs ? (S_ISREG(st->st_mode) &&
1889                                        param->lmd->lmd_lmm.lmm_stripe_count)
1890                                     : 0;
1891                 decision = find_time_check(st, param, for_mds);
1892                 if (decision == -1)
1893                         goto decided;
1894         }
1895
1896         if (param->type && !checked_type) {
1897                 if ((st->st_mode & S_IFMT) == param->type) {
1898                         if (param->exclude_type)
1899                                 goto decided;
1900                 } else {
1901                         if (!param->exclude_type)
1902                                 goto decided;
1903                 }
1904         }
1905
1906         /* Prepare odb. */
1907         if (param->obduuid) {
1908                 if (lustre_fs && param->got_uuids &&
1909                     param->st_dev != st->st_dev) {
1910                         /* A lustre/lustre mount point is crossed. */
1911                         param->got_uuids = 0;
1912                         param->obds_printed = 0;
1913                         param->obdindex = OBD_NOT_FOUND;
1914                 }
1915
1916                 if (lustre_fs && !param->got_uuids) {
1917                         ret = setup_obd_indexes(dir ? dir : parent, param);
1918                         if (ret)
1919                                 return ret;
1920
1921                         param->st_dev = st->st_dev;
1922                 } else if (!lustre_fs && param->got_uuids) {
1923                         /* A lustre/non-lustre mount point is crossed. */
1924                         param->got_uuids = 0;
1925                         param->obdindex = OBD_NOT_FOUND;
1926                 }
1927         }
1928
1929         /* If an OBD UUID is specified but no one matches, skip this file. */
1930         if (param->obduuid && param->obdindex == OBD_NOT_FOUND)
1931                 goto decided;
1932
1933         /* If a OST UUID is given, and some OST matches, check it here. */
1934         if (param->obdindex != OBD_NOT_FOUND) {
1935                 if (!S_ISREG(st->st_mode))
1936                         goto decided;
1937
1938                 /* Only those files should be accepted, which have a
1939                  * stripe on the specified OST. */
1940                 if (!param->lmd->lmd_lmm.lmm_stripe_count) {
1941                         goto decided;
1942                 } else {
1943                         int i, j;
1944                         struct lov_user_ost_data_v1 *lmm_objects;
1945
1946                         if (param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3)
1947                                 lmm_objects = lmmv3->lmm_objects;
1948                         else
1949                                 lmm_objects = param->lmd->lmd_lmm.lmm_objects;
1950
1951                         for (i = 0;
1952                              i < param->lmd->lmd_lmm.lmm_stripe_count; i++) {
1953                                 for (j = 0; j < param->num_obds; j++) {
1954                                         if (param->obdindexes[j] ==
1955                                             lmm_objects[i].l_ost_idx) {
1956                                                 if (param->exclude_obd)
1957                                                         goto decided;
1958                                                 goto obd_matches;
1959                                         }
1960                                 }
1961                         }
1962
1963                         if (i == param->lmd->lmd_lmm.lmm_stripe_count) {
1964                                 if (param->exclude_obd)
1965                                         goto obd_matches;
1966                                 goto decided;
1967                         }
1968                 }
1969         }
1970
1971 obd_matches:
1972
1973         /* If file still fits the request, ask osd for updated info.
1974            The regulat stat is almost of the same speed as some new
1975            'glimpse-size-ioctl'. */
1976         if (!decision && S_ISREG(st->st_mode) &&
1977             param->lmd->lmd_lmm.lmm_stripe_count &&
1978             (param->size_check ||param->atime ||param->mtime ||param->ctime)) {
1979                 if (dir) {
1980                         ret = ioctl(dirfd(dir), IOC_LOV_GETINFO,
1981                                     (void *)param->lmd);
1982                 } else if (parent) {
1983                         ret = ioctl(dirfd(parent), IOC_LOV_GETINFO,
1984                                     (void *)param->lmd);
1985                 }
1986
1987                 if (ret) {
1988                         if (errno == ENOENT) {
1989                                 llapi_err(LLAPI_MSG_ERROR,
1990                                           "warning: %s: %s does not exist",
1991                                           __func__, path);
1992                                 goto decided;
1993                         } else {
1994                                 llapi_err(LLAPI_MSG_ERROR,
1995                                           "%s: IOC_LOV_GETINFO on %s failed",
1996                                           __func__, path);
1997                                 return ret;
1998                         }
1999                 }
2000
2001                 /* Check the time on osc. */
2002                 decision = find_time_check(st, param, 0);
2003                 if (decision == -1)
2004                         goto decided;
2005         }
2006
2007         if (param->size_check) {
2008                 decision = find_value_cmp(st->st_size, param->size,
2009                                           param->size_sign, param->exclude_size,
2010                                           param->size_units, 0);
2011         }
2012
2013         if (decision != -1) {
2014                 llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
2015                 if (param->zeroend)
2016                         llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
2017                 else
2018                         llapi_printf(LLAPI_MSG_NORMAL, "\n");
2019         }
2020
2021 decided:
2022         /* Do not get down anymore? */
2023         if (param->depth == param->maxdepth)
2024                 return 1;
2025
2026         param->depth++;
2027         return 0;
2028 }
2029
2030 int llapi_find(char *path, struct find_param *param)
2031 {
2032         return param_callback(path, cb_find_init, cb_common_fini, param);
2033 }
2034
2035 static int cb_getstripe(char *path, DIR *parent, DIR *d, void *data,
2036                         struct dirent64 *de)
2037 {
2038         struct find_param *param = (struct find_param *)data;
2039         int ret = 0;
2040
2041         LASSERT(parent != NULL || d != NULL);
2042
2043         if (param->obduuid) {
2044                 param->quiet = 1;
2045                 ret = setup_obd_uuid(d ? d : parent, path, param);
2046                 if (ret)
2047                         return ret;
2048         }
2049
2050         if (d) {
2051                 ret = ioctl(dirfd(d), LL_IOC_LOV_GETSTRIPE,
2052                             (void *)&param->lmd->lmd_lmm);
2053         } else if (parent) {
2054                 char *fname = strrchr(path, '/');
2055                 fname = (fname == NULL ? path : fname + 1);
2056
2057                 strncpy((char *)&param->lmd->lmd_lmm, fname, param->lumlen);
2058                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILESTRIPE,
2059                             (void *)&param->lmd->lmd_lmm);
2060         }
2061
2062         if (ret) {
2063                 if (errno == ENODATA) {
2064                         if (!param->obduuid)
2065                                 llapi_printf(LLAPI_MSG_NORMAL,
2066                                              "%s has no stripe info\n", path);
2067                         goto out;
2068                 } else if (errno == ENOTTY) {
2069                         llapi_err(LLAPI_MSG_ERROR,
2070                                   "%s: '%s' not on a Lustre fs?",
2071                                   __func__, path);
2072                 } else if (errno == ENOENT) {
2073                         llapi_err(LLAPI_MSG_WARN,
2074                                   "warning: %s: %s does not exist",
2075                                   __func__, path);
2076                         goto out;
2077                 } else {
2078                         llapi_err(LLAPI_MSG_ERROR,
2079                                   "error: %s: %s failed for %s",
2080                                    __func__, d ? "LL_IOC_LOV_GETSTRIPE" :
2081                                   "IOC_MDC_GETFILESTRIPE", path);
2082                 }
2083
2084                 return ret;
2085         }
2086
2087         llapi_lov_dump_user_lmm(param, path, d ? 1 : 0);
2088 out:
2089         /* Do not get down anymore? */
2090         if (param->depth == param->maxdepth)
2091                 return 1;
2092
2093         param->depth++;
2094         return 0;
2095 }
2096
2097 int llapi_getstripe(char *path, struct find_param *param)
2098 {
2099         return param_callback(path, cb_getstripe, cb_common_fini, param);
2100 }
2101
2102 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
2103                      struct obd_statfs *stat_buf,
2104                      struct obd_uuid *uuid_buf)
2105 {
2106         int fd;
2107         char raw[OBD_MAX_IOCTL_BUFFER] = {'\0'};
2108         char *rawbuf = raw;
2109         struct obd_ioctl_data data = { 0 };
2110         int rc = 0;
2111
2112         data.ioc_inlbuf1 = (char *)&type;
2113         data.ioc_inllen1 = sizeof(__u32);
2114         data.ioc_inlbuf2 = (char *)&index;
2115         data.ioc_inllen2 = sizeof(__u32);
2116         data.ioc_pbuf1 = (char *)stat_buf;
2117         data.ioc_plen1 = sizeof(struct obd_statfs);
2118         data.ioc_pbuf2 = (char *)uuid_buf;
2119         data.ioc_plen2 = sizeof(struct obd_uuid);
2120
2121         if ((rc = obd_ioctl_pack(&data, &rawbuf, sizeof(raw))) != 0) {
2122                 llapi_err(LLAPI_MSG_ERROR,
2123                           "llapi_obd_statfs: error packing ioctl data");
2124                 return rc;
2125         }
2126
2127         fd = open(path, O_RDONLY);
2128         if (errno == EISDIR)
2129                 fd = open(path, O_DIRECTORY | O_RDONLY);
2130
2131         if (fd < 0) {
2132                 rc = errno ? -errno : -EBADF;
2133                 llapi_err(LLAPI_MSG_ERROR, "error: %s: opening '%s'",
2134                           __func__, path);
2135                 return rc;
2136         }
2137         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
2138         if (rc)
2139                 rc = errno ? -errno : -EINVAL;
2140
2141         close(fd);
2142         return rc;
2143 }
2144
2145 #define MAX_STRING_SIZE 128
2146 #define DEVICES_LIST "/proc/fs/lustre/devices"
2147
2148 int llapi_ping(char *obd_type, char *obd_name)
2149 {
2150         char path[MAX_STRING_SIZE];
2151         char buf[1];
2152         int rc, fd;
2153
2154         snprintf(path, MAX_STRING_SIZE, "/proc/fs/lustre/%s/%s/ping",
2155                  obd_type, obd_name);
2156
2157         fd = open(path, O_WRONLY);
2158         if (fd < 0) {
2159                 rc = errno;
2160                 llapi_err(LLAPI_MSG_ERROR, "error opening %s", path);
2161                 return rc;
2162         }
2163
2164         rc = write(fd, buf, 1);
2165         close(fd);
2166
2167         if (rc == 1)
2168                 return 0;
2169         return rc;
2170 }
2171
2172 int llapi_target_iterate(int type_num, char **obd_type,void *args,llapi_cb_t cb)
2173 {
2174         char buf[MAX_STRING_SIZE];
2175         FILE *fp = fopen(DEVICES_LIST, "r");
2176         int i, rc = 0;
2177
2178         if (fp == NULL) {
2179                 rc = errno;
2180                 llapi_err(LLAPI_MSG_ERROR, "error: opening "DEVICES_LIST);
2181                 return rc;
2182         }
2183
2184         while (fgets(buf, sizeof(buf), fp) != NULL) {
2185                 char *obd_type_name = NULL;
2186                 char *obd_name = NULL;
2187                 char *obd_uuid = NULL;
2188                 char rawbuf[OBD_MAX_IOCTL_BUFFER];
2189                 char *bufl = rawbuf;
2190                 char *bufp = buf;
2191                 struct obd_ioctl_data datal = { 0, };
2192                 struct obd_statfs osfs_buffer;
2193
2194                 while(bufp[0] == ' ')
2195                         ++bufp;
2196
2197                 for(i = 0; i < 3; i++) {
2198                         obd_type_name = strsep(&bufp, " ");
2199                 }
2200                 obd_name = strsep(&bufp, " ");
2201                 obd_uuid = strsep(&bufp, " ");
2202
2203                 memset(&osfs_buffer, 0, sizeof (osfs_buffer));
2204
2205                 memset(bufl, 0, sizeof(rawbuf));
2206                 datal.ioc_pbuf1 = (char *)&osfs_buffer;
2207                 datal.ioc_plen1 = sizeof(osfs_buffer);
2208
2209                 for (i = 0; i < type_num; i++) {
2210                         if (strcmp(obd_type_name, obd_type[i]) != 0)
2211                                 continue;
2212
2213                         cb(obd_type_name, obd_name, obd_uuid, args);
2214                 }
2215         }
2216         fclose(fp);
2217         return rc;
2218 }
2219
2220 static void do_target_check(char *obd_type_name, char *obd_name,
2221                             char *obd_uuid, void *args)
2222 {
2223         int rc;
2224
2225         rc = llapi_ping(obd_type_name, obd_name);
2226         if (rc == ENOTCONN) {
2227                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
2228         } else if (rc) {
2229                 llapi_err(LLAPI_MSG_ERROR, "error: check '%s'", obd_name);
2230         } else {
2231                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
2232         }
2233 }
2234
2235 int llapi_target_check(int type_num, char **obd_type, char *dir)
2236 {
2237         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
2238 }
2239
2240 #undef MAX_STRING_SIZE
2241
2242 int llapi_catinfo(char *dir, char *keyword, char *node_name)
2243 {
2244         char raw[OBD_MAX_IOCTL_BUFFER];
2245         char out[LLOG_CHUNK_SIZE];
2246         char *buf = raw;
2247         struct obd_ioctl_data data = { 0 };
2248         char key[30];
2249         DIR *root;
2250         int rc;
2251
2252         sprintf(key, "%s", keyword);
2253         memset(raw, 0, sizeof(raw));
2254         memset(out, 0, sizeof(out));
2255         data.ioc_inlbuf1 = key;
2256         data.ioc_inllen1 = strlen(key) + 1;
2257         if (node_name) {
2258                 data.ioc_inlbuf2 = node_name;
2259                 data.ioc_inllen2 = strlen(node_name) + 1;
2260         }
2261         data.ioc_pbuf1 = out;
2262         data.ioc_plen1 = sizeof(out);
2263         rc = obd_ioctl_pack(&data, &buf, sizeof(raw));
2264         if (rc)
2265                 return rc;
2266
2267         root = opendir(dir);
2268         if (root == NULL) {
2269                 rc = errno;
2270                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", dir);
2271                 return rc;
2272         }
2273
2274         rc = ioctl(dirfd(root), OBD_IOC_LLOG_CATINFO, buf);
2275         if (rc)
2276                 llapi_err(LLAPI_MSG_ERROR, "ioctl OBD_IOC_CATINFO failed");
2277         else
2278                 llapi_printf(LLAPI_MSG_NORMAL, "%s", data.ioc_pbuf1);
2279
2280         closedir(root);
2281         return rc;
2282 }
2283
2284 /* Is this a lustre fs? */
2285 int llapi_is_lustre_mnttype(const char *type)
2286 {
2287         return (strcmp(type, "lustre") == 0 || strcmp(type,"lustre_lite") == 0);
2288 }
2289
2290 /* Is this a lustre client fs? */
2291 int llapi_is_lustre_mnt(struct mntent *mnt)
2292 {
2293         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
2294                 strstr(mnt->mnt_fsname, ":/") != NULL);
2295 }
2296
2297 int llapi_quotacheck(char *mnt, int check_type)
2298 {
2299         DIR *root;
2300         int rc;
2301
2302         root = opendir(mnt);
2303         if (!root) {
2304                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2305                 return -1;
2306         }
2307
2308         rc = ioctl(dirfd(root), LL_IOC_QUOTACHECK, check_type);
2309
2310         closedir(root);
2311         return rc;
2312 }
2313
2314 int llapi_poll_quotacheck(char *mnt, struct if_quotacheck *qchk)
2315 {
2316         DIR *root;
2317         int poll_intvl = 2;
2318         int rc;
2319
2320         root = opendir(mnt);
2321         if (!root) {
2322                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2323                 return -1;
2324         }
2325
2326         while (1) {
2327                 rc = ioctl(dirfd(root), LL_IOC_POLL_QUOTACHECK, qchk);
2328                 if (!rc)
2329                         break;
2330                 sleep(poll_intvl);
2331                 if (poll_intvl < 30)
2332                         poll_intvl *= 2;
2333         }
2334
2335         closedir(root);
2336         return rc;
2337 }
2338
2339 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
2340 {
2341         DIR *root;
2342         int rc;
2343
2344         root = opendir(mnt);
2345         if (!root) {
2346                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2347                 return -1;
2348         }
2349
2350         rc = ioctl(dirfd(root), LL_IOC_QUOTACTL, qctl);
2351
2352         closedir(root);
2353         return rc;
2354 }
2355
2356 static int cb_quotachown(char *path, DIR *parent, DIR *d, void *data,
2357                          struct dirent64 *de)
2358 {
2359         struct find_param *param = (struct find_param *)data;
2360         lstat_t *st;
2361         int rc;
2362
2363         LASSERT(parent != NULL || d != NULL);
2364
2365         if (d) {
2366                 rc = ioctl(dirfd(d), LL_IOC_MDC_GETINFO,
2367                            (void *)param->lmd);
2368         } else if (parent) {
2369                 char *fname = strrchr(path, '/');
2370                 fname = (fname == NULL ? path : fname + 1);
2371
2372                 strncpy((char *)param->lmd, fname, param->lumlen);
2373                 rc = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
2374                            (void *)param->lmd);
2375         } else {
2376                 return 0;
2377         }
2378
2379         if (rc) {
2380                 if (errno == ENODATA) {
2381                         if (!param->obduuid && !param->quiet)
2382                                 llapi_err(LLAPI_MSG_ERROR,
2383                                           "%s has no stripe info", path);
2384                         rc = 0;
2385                 } else if (errno == ENOENT) {
2386                         llapi_err(LLAPI_MSG_ERROR,
2387                                   "warning: %s: %s does not exist",
2388                                   __func__, path);
2389                         rc = 0;
2390                 } else if (errno != EISDIR) {
2391                         rc = errno;
2392                         llapi_err(LLAPI_MSG_ERROR, "%s ioctl failed for %s.",
2393                                   d ? "LL_IOC_MDC_GETINFO" :
2394                                   "IOC_MDC_GETFILEINFO", path);
2395                 }
2396                 return rc;
2397         }
2398
2399         st = &param->lmd->lmd_st;
2400
2401         /* libc chown() will do extra check, and if the real owner is
2402          * the same as the ones to set, it won't fall into kernel, so
2403          * invoke syscall directly. */
2404         rc = syscall(SYS_chown, path, -1, -1);
2405         if (rc)
2406                 llapi_err(LLAPI_MSG_ERROR, "error: chown %s", path);
2407
2408         rc = chmod(path, st->st_mode);
2409         if (rc)
2410                 llapi_err(LLAPI_MSG_ERROR, "error: chmod %s (%hu)",
2411                           path, st->st_mode);
2412
2413         return rc;
2414 }
2415
2416 int llapi_quotachown(char *path, int flag)
2417 {
2418         struct find_param param;
2419         
2420         memset(&param, 0, sizeof(param));
2421         param.recursive = 1;
2422         param.verbose = 0;
2423         param.quiet = 1;
2424
2425         return param_callback(path, cb_quotachown, NULL, &param);
2426 }
2427
2428 int llapi_path2fid(const char *path, lustre_fid *fid)
2429 {
2430         int fd, rc;
2431
2432         fd = open(path, O_RDONLY);
2433         if (fd < 0)
2434                 return -errno;
2435
2436         rc = ioctl(fd, LL_IOC_PATH2FID, fid);
2437
2438         close(fd);
2439         return rc;
2440 }
2441
2442 int llapi_get_connect_flags(const char *mnt, __u64 *flags)
2443 {
2444         DIR *root;
2445         int rc;
2446
2447         root = opendir(mnt);
2448         if (!root) {
2449                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2450                 return -1;
2451         }
2452
2453         rc = ioctl(dirfd(root), LL_IOC_GET_CONNECT_FLAGS, flags);
2454         closedir(root);
2455         if (rc < 0)
2456                 llapi_err(LLAPI_MSG_ERROR,
2457                           "ioctl on %s for getting connect flags failed", mnt);
2458         return rc;
2459 }
2460
2461 int llapi_get_version(char *buffer, int buffer_size,
2462                       char **version)
2463 {
2464         int rc;
2465         int fd;
2466         struct obd_ioctl_data *data = (struct obd_ioctl_data *)buffer;
2467
2468         fd = open(OBD_DEV_PATH, O_RDONLY);
2469         if (fd == -1)
2470                 return -errno;
2471
2472         memset(buffer, 0, buffer_size);
2473         data->ioc_version = OBD_IOCTL_VERSION;
2474         data->ioc_inllen1 = buffer_size - size_round(sizeof(*data));
2475         data->ioc_inlbuf1 = buffer + size_round(sizeof(*data));
2476         data->ioc_len = obd_ioctl_packlen(data);
2477
2478         rc = ioctl(fd, OBD_GET_VERSION, buffer);
2479         if (rc == -1) {
2480                 rc = errno;
2481                 close(fd);
2482                 return -rc;
2483         }
2484         close(fd);
2485         *version = data->ioc_bulk;
2486         return 0;
2487 }