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