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