Whamcloud - gitweb
b=17299
[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, LOV_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",
543                                      fsname, pool->d_name);
544                 }
545                 closedir(dir);
546         }
547         return rc;
548 }
549
550 typedef int (semantic_func_t)(char *path, DIR *parent, DIR *d,
551                               void *data, cfs_dirent_t *de);
552
553 #define MAX_LOV_UUID_COUNT      max(LOV_MAX_STRIPE_COUNT, 1000)
554 #define OBD_NOT_FOUND           (-1)
555
556 static int common_param_init(struct find_param *param)
557 {
558         param->lumlen = lov_mds_md_size(MAX_LOV_UUID_COUNT, LOV_MAGIC_V3);
559         if ((param->lmd = malloc(sizeof(lstat_t) + param->lumlen)) == NULL) {
560                 llapi_err(LLAPI_MSG_ERROR,
561                           "error: allocation of %d bytes for ioctl",
562                           sizeof(lstat_t) + param->lumlen);
563                 return -ENOMEM;
564         }
565
566         param->got_uuids = 0;
567         param->obdindexes = NULL;
568         param->obdindex = OBD_NOT_FOUND;
569         return 0;
570 }
571
572 static void find_param_fini(struct find_param *param)
573 {
574         if (param->obdindexes)
575                 free(param->obdindexes);
576
577         if (param->lmd)
578                 free(param->lmd);
579 }
580
581 int llapi_file_fget_lov_uuid(int fd, struct obd_uuid *lov_name)
582 {
583         int rc = ioctl(fd, OBD_IOC_GETNAME, lov_name);
584         if (rc) {
585                 rc = errno;
586                 llapi_err(LLAPI_MSG_ERROR, "error: can't get lov name.");
587         }
588         return rc;
589 }
590
591 int llapi_file_get_lov_uuid(const char *path, struct obd_uuid *lov_uuid)
592 {
593         int fd, rc;
594
595         fd = open(path, O_RDONLY);
596         if (fd < 0) {
597                 rc = errno;
598                 llapi_err(LLAPI_MSG_ERROR, "error opening %s", path);
599                 return rc;
600         }
601
602         rc = llapi_file_fget_lov_uuid(fd, lov_uuid);
603
604         close(fd);
605
606         return rc;
607 }
608
609 /*
610  * If uuidp is NULL, return the number of available obd uuids.
611  * If uuidp is non-NULL, then it will return the uuids of the obds. If
612  * there are more OSTs then allocated to uuidp, then an error is returned with
613  * the ost_count set to number of available obd uuids.
614  */
615 int llapi_lov_get_uuids(int fd, struct obd_uuid *uuidp, int *ost_count)
616 {
617         struct obd_uuid lov_name;
618         char buf[1024];
619         FILE *fp;
620         int rc = 0, index = 0;
621
622         /* Get the lov name */
623         rc = llapi_file_fget_lov_uuid(fd, &lov_name);
624         if (rc)
625                 return rc;
626
627         /* Now get the ost uuids from /proc */
628         snprintf(buf, sizeof(buf), "/proc/fs/lustre/lov/%s/target_obd",
629                  lov_name.uuid);
630         fp = fopen(buf, "r");
631         if (fp == NULL) {
632                 rc = errno;
633                 llapi_err(LLAPI_MSG_ERROR, "error: opening '%s'", buf);
634                 return rc;
635         }
636
637         while (fgets(buf, sizeof(buf), fp) != NULL) {
638                 if (uuidp && (index < *ost_count)) {
639                         if (sscanf(buf, "%d: %s", &index, uuidp[index].uuid) <2)
640                                 break;
641                 }
642                 index++;
643         }
644
645         fclose(fp);
646
647         if (uuidp && (index >= *ost_count))
648                 return -EOVERFLOW;
649
650         *ost_count = index;
651         return rc;
652 }
653
654 /* Here, param->obduuid points to a single obduuid, the index of which is
655  * returned in param->obdindex */
656 static int setup_obd_uuid(DIR *dir, char *dname, struct find_param *param)
657 {
658         struct obd_uuid lov_uuid;
659         char uuid[sizeof(struct obd_uuid)];
660         char buf[1024];
661         FILE *fp;
662         int rc = 0, index;
663
664         /* Get the lov name */
665         rc = llapi_file_fget_lov_uuid(dirfd(dir), &lov_uuid);
666         if (rc) {
667                 if (errno != ENOTTY) {
668                         rc = errno;
669                         llapi_err(LLAPI_MSG_ERROR,
670                                   "error: can't get lov name: %s", dname);
671                 } else {
672                         rc = 0;
673                 }
674                 return rc;
675         }
676
677         param->got_uuids = 1;
678
679         /* Now get the ost uuids from /proc */
680         snprintf(buf, sizeof(buf), "/proc/fs/lustre/lov/%s/target_obd",
681                  lov_uuid.uuid);
682         fp = fopen(buf, "r");
683         if (fp == NULL) {
684                 rc = errno;
685                 llapi_err(LLAPI_MSG_ERROR, "error: opening '%s'", buf);
686                 return rc;
687         }
688
689         if (!param->obduuid && !param->quiet && !param->obds_printed)
690                 llapi_printf(LLAPI_MSG_NORMAL, "OBDS:\n");
691
692         while (fgets(buf, sizeof(buf), fp) != NULL) {
693                 if (sscanf(buf, "%d: %s", &index, uuid) < 2)
694                         break;
695
696                 if (param->obduuid) {
697                         if (strncmp(param->obduuid->uuid, uuid,
698                                     sizeof(uuid)) == 0) {
699                                 param->obdindex = index;
700                                 break;
701                         }
702                 } else if (!param->quiet && !param->obds_printed) {
703                         /* Print everything */
704                         llapi_printf(LLAPI_MSG_NORMAL, "%s", buf);
705                 }
706         }
707         param->obds_printed = 1;
708
709         fclose(fp);
710
711         if (!param->quiet && param->obduuid &&
712             (param->obdindex == OBD_NOT_FOUND)) {
713                 llapi_err_noerrno(LLAPI_MSG_ERROR,
714                                   "error: %s: unknown obduuid: %s",
715                                   __FUNCTION__, param->obduuid->uuid);
716                 //rc = EINVAL;
717         }
718
719         return (rc);
720 }
721
722 /* In this case, param->obduuid will be an array of obduuids and
723  * obd index for all these obduuids will be returned in
724  * param->obdindexes */
725 static int setup_obd_indexes(DIR *dir, struct find_param *param)
726 {
727         struct obd_uuid *uuids = NULL;
728         int obdcount = INIT_ALLOC_NUM_OSTS;
729         int ret, obd_valid = 0, obdnum, i;
730
731         uuids = (struct obd_uuid *)malloc(INIT_ALLOC_NUM_OSTS *
732                                           sizeof(struct obd_uuid));
733         if (uuids == NULL)
734                 return -ENOMEM;
735
736 retry_get_uuids:
737         ret = llapi_lov_get_uuids(dirfd(dir), uuids,
738                                   &obdcount);
739         if (ret) {
740                 struct obd_uuid *uuids_temp;
741
742                 if (ret == -EOVERFLOW) {
743                         uuids_temp = realloc(uuids, obdcount *
744                                              sizeof(struct obd_uuid));
745                         if (uuids_temp != NULL)
746                                 goto retry_get_uuids;
747                         else
748                                 ret = -ENOMEM;
749                 }
750
751                 llapi_err(LLAPI_MSG_ERROR, "get ost uuid failed");
752                 return ret;
753         }
754
755         param->obdindexes = malloc(param->num_obds * sizeof(param->obdindex));
756         if (param->obdindexes == NULL)
757                 return -ENOMEM;
758
759         for (obdnum = 0; obdnum < param->num_obds; obdnum++) {
760                 for (i = 0; i <= obdcount; i++) {
761                         if (strcmp((char *)&param->obduuid[obdnum].uuid,
762                                    (char *)&uuids[i]) == 0) {
763                                 param->obdindexes[obdnum] = i;
764                                 obd_valid++;
765                                 break;
766                         }
767                 }
768                 if (i == obdcount)
769                         param->obdindexes[obdnum] = OBD_NOT_FOUND;
770         }
771
772         if (obd_valid == 0)
773                 param->obdindex = OBD_NOT_FOUND;
774         else
775                 param->obdindex = obd_valid;
776
777         param->got_uuids = 1;
778
779         return 0;
780 }
781
782 void lov_dump_user_lmm_v1v3(struct lov_user_md *lum, char *pool_name,
783                             struct lov_user_ost_data_v1 *objects,
784                             char *path, int is_dir,
785                             int obdindex, int quiet, int header, int body)
786 {
787         int i, obdstripe = 0;
788
789         if (obdindex != OBD_NOT_FOUND) {
790                 for (i = 0; !is_dir && i < lum->lmm_stripe_count; i++) {
791                         if (obdindex == objects[i].l_ost_idx) {
792                                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
793                                 obdstripe = 1;
794                                 break;
795                         }
796                 }
797         } else if (!quiet) {
798                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
799                 obdstripe = 1;
800         }
801
802         /* if it's a directory */
803         if (is_dir) {
804                 if (obdstripe == 1) {
805                         if (lum->lmm_object_gr == LOV_OBJECT_GROUP_DEFAULT) {
806                                 llapi_printf(LLAPI_MSG_NORMAL, "(Default) ");
807                                 lum->lmm_object_gr = LOV_OBJECT_GROUP_CLEAR;
808                         }
809                         llapi_printf(LLAPI_MSG_NORMAL,
810                                      "stripe_count: %d stripe_size: %u "
811                                      "stripe_offset: %d%s%s\n",
812                                      lum->lmm_stripe_count == (__u16)-1 ? -1 :
813                                         lum->lmm_stripe_count,
814                                      lum->lmm_stripe_size,
815                                      lum->lmm_stripe_offset == (__u16)-1 ? -1 :
816                                         lum->lmm_stripe_offset,
817                                      pool_name != NULL ? " pool: " : "",
818                                      pool_name != NULL ? pool_name : "");
819                 }
820                 return;
821         }
822
823         if (header && (obdstripe == 1)) {
824                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_magic:          0x%08X\n",
825                              lum->lmm_magic);
826                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_gr:      "LPX64"\n",
827                              lum->lmm_object_gr);
828                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_id:      "LPX64"\n",
829                              lum->lmm_object_id);
830                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_stripe_count:   %u\n",
831                              (int)lum->lmm_stripe_count);
832                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_stripe_size:    %u\n",
833                              lum->lmm_stripe_size);
834                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_stripe_pattern: %x\n",
835                              lum->lmm_pattern);
836                 if (pool_name != NULL)
837                         llapi_printf(LLAPI_MSG_NORMAL,
838                              "lmm_pool_name:      %s\n", pool_name);
839         }
840
841         if (body) {
842                 if ((!quiet) && (obdstripe == 1))
843                         llapi_printf(LLAPI_MSG_NORMAL,
844                                      "\tobdidx\t\t objid\t\tobjid\t\t group\n");
845
846                 for (i = 0; i < lum->lmm_stripe_count; i++) {
847                         int idx = objects[i].l_ost_idx;
848                         long long oid = objects[i].l_object_id;
849                         long long gr = objects[i].l_object_gr;
850                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
851                                 llapi_printf(LLAPI_MSG_NORMAL,
852                                            "\t%6u\t%14llu\t%#13llx\t%14llu%s\n",
853                                            idx, oid, oid, gr,
854                                            obdindex == idx ? " *" : "");
855                 }
856                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
857         }
858 }
859
860 void lov_dump_user_lmm_join(struct lov_user_md_v1 *lum, char *path,
861                             int is_dir, int obdindex, int quiet,
862                             int header, int body)
863 {
864         struct lov_user_md_join *lumj = (struct lov_user_md_join *)lum;
865         int i, obdstripe = 0;
866
867         if (obdindex != OBD_NOT_FOUND) {
868                 for (i = 0; i < lumj->lmm_stripe_count; i++) {
869                         if (obdindex == lumj->lmm_objects[i].l_ost_idx) {
870                                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
871                                 obdstripe = 1;
872                                 break;
873                         }
874                 }
875         } else if (!quiet) {
876                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
877                 obdstripe = 1;
878         }
879
880         if (header && obdstripe == 1) {
881                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_magic:          0x%08X\n",
882                              lumj->lmm_magic);
883                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_gr:      "LPX64"\n",
884                              lumj->lmm_object_gr);
885                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_id:      "LPX64"\n",
886                              lumj->lmm_object_id);
887                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_stripe_count:   %u\n",
888                              (int)lumj->lmm_stripe_count);
889                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_stripe_size:    %u\n",
890                              lumj->lmm_stripe_size);
891                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_stripe_pattern: %x\n",
892                              lumj->lmm_pattern);
893                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_extent_count:   %x\n",
894                              lumj->lmm_extent_count);
895         }
896
897         if (body) {
898                 unsigned long long start = -1, end = 0;
899                 if (!quiet && obdstripe == 1)
900                         llapi_printf(LLAPI_MSG_NORMAL,
901                                      "joined\tobdidx\t\t objid\t\tobjid\t\t "
902                                      "group\t\tstart\t\tend\n");
903                 for (i = 0; i < lumj->lmm_stripe_count; i++) {
904                         int idx = lumj->lmm_objects[i].l_ost_idx;
905                         long long oid = lumj->lmm_objects[i].l_object_id;
906                         long long gr = lumj->lmm_objects[i].l_object_gr;
907                         if (obdindex == OBD_NOT_FOUND || obdindex == idx)
908                                 llapi_printf(LLAPI_MSG_NORMAL,
909                                              "\t%6u\t%14llu\t%#13llx\t%14llu%s",
910                                              idx, oid, oid, gr,
911                                              obdindex == idx ? " *" : "");
912                         if (start != lumj->lmm_objects[i].l_extent_start ||
913                             end != lumj->lmm_objects[i].l_extent_end) {
914                                 start = lumj->lmm_objects[i].l_extent_start;
915                                 llapi_printf(LLAPI_MSG_NORMAL,"\t%14llu",start);
916                                 end = lumj->lmm_objects[i].l_extent_end;
917                                 if (end == (unsigned long long)-1)
918                                         llapi_printf(LLAPI_MSG_NORMAL,
919                                                      "\t\tEOF\n");
920                                 else
921                                         llapi_printf(LLAPI_MSG_NORMAL,
922                                                      "\t\t%llu\n", end);
923                         } else {
924                                 llapi_printf(LLAPI_MSG_NORMAL, "\t\t\t\t\n");
925                         }
926                 }
927                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
928         }
929 }
930
931 void llapi_lov_dump_user_lmm(struct find_param *param,
932                              char *path, int is_dir)
933 {
934         switch(*(__u32 *)&param->lmd->lmd_lmm) { /* lum->lmm_magic */
935         case LOV_USER_MAGIC_V1:
936                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, NULL,
937                                        param->lmd->lmd_lmm.lmm_objects,
938                                        path, is_dir,
939                                        param->obdindex, param->quiet,
940                                        param->verbose,
941                                        (param->verbose || !param->obduuid));
942                 break;
943         case LOV_USER_MAGIC_JOIN:
944                 lov_dump_user_lmm_join(&param->lmd->lmd_lmm, path, is_dir,
945                                        param->obdindex, param->quiet,
946                                        param->verbose,
947                                        (param->verbose || !param->obduuid));
948                 break;
949         case LOV_USER_MAGIC_V3: {
950                 char pool_name[LOV_MAXPOOLNAME + 1];
951                 struct lov_user_ost_data_v1 *objects;
952                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
953
954                 strncpy(pool_name, lmmv3->lmm_pool_name, LOV_MAXPOOLNAME);
955                 pool_name[LOV_MAXPOOLNAME] = '\0';
956                 objects = lmmv3->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 =
1156                                         llapi_filetype_dir_table[st->st_mode &
1157                                                                  S_IFMT];
1158                         }
1159                         if (ret == -ENOENT)
1160                                 continue;
1161                 }
1162
1163                 switch (dent->d_type) {
1164                 case DT_UNKNOWN:
1165                         llapi_err(LLAPI_MSG_ERROR,
1166                                   "error: %s: '%s' is UNKNOWN type %d",
1167                                   __FUNCTION__, dent->d_name, dent->d_type);
1168                         break;
1169                 case DT_DIR:
1170                         ret = llapi_semantic_traverse(path, size, d, sem_init,
1171                                                       sem_fini, data, dent);
1172                         if (ret < 0)
1173                                 goto out;
1174                         break;
1175                 default:
1176                         ret = 0;
1177                         if (sem_init) {
1178                                 ret = sem_init(path, d, NULL, data, dent);
1179                                 if (ret < 0)
1180                                         goto out;
1181                         }
1182                         if (sem_fini && ret == 0)
1183                                 sem_fini(path, d, NULL, data, dent);
1184                 }
1185         }
1186
1187 out:
1188         path[len] = 0;
1189
1190         if (sem_fini)
1191                 sem_fini(path, parent, d, data, de);
1192 err:
1193         if (d)
1194                 closedir(d);
1195         if (p)
1196                 closedir(p);
1197         return ret;
1198 }
1199
1200 /* Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
1201  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
1202  *
1203  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
1204  * The table bolow gives the answers for the specified parameters (value and
1205  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
1206  * --------------------------------------
1207  * 1 | file > limit; sign > 0 | -1 / -1 |
1208  * 2 | file = limit; sign > 0 |  ? /  1 |
1209  * 3 | file < limit; sign > 0 |  ? /  1 |
1210  * 4 | file > limit; sign = 0 | -1 / -1 |
1211  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
1212  * 6 | file < limit; sign = 0 |  ? / -1 |
1213  * 7 | file > limit; sign < 0 |  1 /  1 |
1214  * 8 | file = limit; sign < 0 |  ? / -1 |
1215  * 9 | file < limit; sign < 0 |  ? / -1 |
1216  * --------------------------------------
1217  * Note: 5th actually means that the value is within the interval
1218  * (limit - margin, limit]. */
1219 static int find_value_cmp(unsigned int file, unsigned int limit, int sign,
1220                           unsigned long long margin, int mds)
1221 {
1222         if (sign > 0) {
1223                 if (file < limit)
1224                         return mds ? 0 : 1;
1225         }
1226
1227         if (sign == 0) {
1228                 if (file <= limit && file + margin > limit)
1229                         return mds ? 0 : 1;
1230                 if (file + margin <= limit)
1231                         return mds ? 0 : -1;
1232         }
1233
1234         if (sign < 0) {
1235                 if (file > limit)
1236                         return 1;
1237                 if (mds)
1238                         return 0;
1239         }
1240
1241         return -1;
1242 }
1243
1244 /* Check if the file time matches all the given criteria (e.g. --atime +/-N).
1245  * Return -1 or 1 if file timestamp does not or does match the given criteria
1246  * correspondingly. Return 0 if the MDS time is being checked and there are
1247  * attributes on OSTs and it is not yet clear if the timespamp matches.
1248  *
1249  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
1250  * updated timestamps. */
1251 static int find_time_check(lstat_t *st, struct find_param *param, int mds)
1252 {
1253         int ret;
1254         int rc = 0;
1255
1256         /* Check if file is accepted. */
1257         if (param->atime) {
1258                 ret = find_value_cmp(st->st_atime, param->atime,
1259                                      param->asign, 24 * 60 * 60, mds);
1260                 if (ret < 0)
1261                         return ret;
1262                 rc = ret;
1263         }
1264
1265         if (param->mtime) {
1266                 ret = find_value_cmp(st->st_mtime, param->mtime,
1267                                      param->msign, 24 * 60 * 60, mds);
1268                 if (ret < 0)
1269                         return ret;
1270
1271                 /* If the previous check matches, but this one is not yet clear,
1272                  * we should return 0 to do an RPC on OSTs. */
1273                 if (rc == 1)
1274                         rc = ret;
1275         }
1276
1277         if (param->ctime) {
1278                 ret = find_value_cmp(st->st_ctime, param->ctime,
1279                                      param->csign, 24 * 60 * 60, mds);
1280                 if (ret < 0)
1281                         return ret;
1282
1283                 /* If the previous check matches, but this one is not yet clear,
1284                  * we should return 0 to do an RPC on OSTs. */
1285                 if (rc == 1)
1286                         rc = ret;
1287         }
1288
1289         return rc;
1290 }
1291
1292 static int cb_find_init(char *path, DIR *parent, DIR *dir,
1293                         void *data, cfs_dirent_t *de)
1294 {
1295         struct find_param *param = (struct find_param *)data;
1296         int decision = 1; /* 1 is accepted; -1 is rejected. */
1297         lstat_t *st = &param->lmd->lmd_st;
1298         int lustre_fs = 1;
1299         int checked_type = 0;
1300         int ret = 0;
1301
1302         LASSERT(parent != NULL || dir != NULL);
1303
1304         param->lmd->lmd_lmm.lmm_stripe_count = 0;
1305
1306         /* If a regular expression is presented, make the initial decision */
1307         if (param->pattern != NULL) {
1308                 char *fname = strrchr(path, '/');
1309                 fname = (fname == NULL ? path : fname + 1);
1310                 ret = fnmatch(param->pattern, fname, 0);
1311                 if ((ret == FNM_NOMATCH && !param->exclude_pattern) ||
1312                     (ret == 0 && param->exclude_pattern))
1313                         goto decided;
1314         }
1315
1316         /* See if we can check the file type from the dirent. */
1317         if (param->type && de != NULL && de->d_type != DT_UNKNOWN &&
1318             de->d_type < DT_MAX) {
1319                 checked_type = 1;
1320                 if (llapi_dir_filetype_table[de->d_type] == param->type) {
1321                         if (param->exclude_type)
1322                                 goto decided;
1323                 } else {
1324                         if (!param->exclude_type)
1325                                 goto decided;
1326                 }
1327         }
1328
1329
1330         /* If a time or OST should be checked, the decision is not taken yet. */
1331         if (param->atime || param->ctime || param->mtime || param->obduuid ||
1332             param->size)
1333                 decision = 0;
1334
1335         ret = 0;
1336         /* Request MDS for the stat info. */
1337         if (param->have_fileinfo == 0) {
1338                 if (dir) {
1339                         /* retrieve needed file info */
1340                         ret = ioctl(dirfd(dir), LL_IOC_MDC_GETINFO,
1341                                     (void *)param->lmd);
1342                 } else {
1343                         char *fname = strrchr(path, '/');
1344                         fname = (fname == NULL ? path : fname + 1);
1345
1346                         /* retrieve needed file info */
1347                         strncpy((char *)param->lmd, fname, param->lumlen);
1348                         ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
1349                                    (void *)param->lmd);
1350                 }
1351         }
1352
1353         if (ret) {
1354                 if (errno == ENOTTY) {
1355                         /* ioctl is not supported, it is not a lustre fs.
1356                          * Do the regular lstat(2) instead. */
1357                         lustre_fs = 0;
1358                         ret = lstat_f(path, st);
1359                         if (ret) {
1360                                 llapi_err(LLAPI_MSG_ERROR,
1361                                           "error: %s: lstat failed for %s",
1362                                           __FUNCTION__, path);
1363                                 return ret;
1364                         }
1365                 } else if (errno == ENOENT) {
1366                         llapi_err(LLAPI_MSG_WARN,
1367                                   "warning: %s: %s does not exist",
1368                                   __FUNCTION__, path);
1369                         goto decided;
1370                 } else {
1371                         llapi_err(LLAPI_MSG_ERROR,"error: %s: %s failed for %s",
1372                                   __FUNCTION__, dir ? "LL_IOC_MDC_GETINFO" :
1373                                   "IOC_MDC_GETFILEINFO", path);
1374                         return ret;
1375                 }
1376         }
1377
1378         if (param->type && !checked_type) {
1379                 if ((st->st_mode & S_IFMT) == param->type) {
1380                         if (param->exclude_type)
1381                                 goto decided;
1382                 } else {
1383                         if (!param->exclude_type)
1384                                 goto decided;
1385                 }
1386         }
1387
1388         /* Prepare odb. */
1389         if (param->obduuid) {
1390                 if (lustre_fs && param->got_uuids &&
1391                     param->st_dev != st->st_dev) {
1392                         /* A lustre/lustre mount point is crossed. */
1393                         param->got_uuids = 0;
1394                         param->obds_printed = 0;
1395                         param->obdindex = OBD_NOT_FOUND;
1396                 }
1397
1398                 if (lustre_fs && !param->got_uuids) {
1399                         ret = setup_obd_indexes(dir ? dir : parent, param);
1400                         if (ret)
1401                                 return ret;
1402
1403                         param->st_dev = st->st_dev;
1404                 } else if (!lustre_fs && param->got_uuids) {
1405                         /* A lustre/non-lustre mount point is crossed. */
1406                         param->got_uuids = 0;
1407                         param->obdindex = OBD_NOT_FOUND;
1408                 }
1409         }
1410
1411         /* If an OBD UUID is specified but no one matches, skip this file. */
1412         if (param->obduuid && param->obdindex == OBD_NOT_FOUND)
1413                 goto decided;
1414
1415         /* If a OST UUID is given, and some OST matches, check it here. */
1416         if (param->obdindex != OBD_NOT_FOUND) {
1417                 if (!S_ISREG(st->st_mode))
1418                         goto decided;
1419
1420                 /* Only those files should be accepted, which have a
1421                  * stripe on the specified OST. */
1422                 if (!param->lmd->lmd_lmm.lmm_stripe_count) {
1423                         goto decided;
1424                 } else {
1425                         int i, j;
1426                         struct lov_user_ost_data_v1 *lmm_objects;
1427
1428                         if (param->lmd->lmd_lmm.lmm_magic ==
1429                             LOV_USER_MAGIC_V3) {
1430                                 struct lov_user_md_v3 *lmmv3 =
1431                                         (void *)&param->lmd->lmd_lmm;
1432
1433                                 lmm_objects = lmmv3->lmm_objects;
1434                         } else {
1435                                 lmm_objects = param->lmd->lmd_lmm.lmm_objects;
1436                         }
1437
1438                         for (i = 0;
1439                              i < param->lmd->lmd_lmm.lmm_stripe_count; i++) {
1440                                 for (j = 0; j < param->num_obds; j++) {
1441                                         if (param->obdindexes[j] ==
1442                                             lmm_objects[i].l_ost_idx)
1443                                                 goto obd_matches;
1444                                 }
1445                         }
1446
1447                         if (i == param->lmd->lmd_lmm.lmm_stripe_count)
1448                                 goto decided;
1449                 }
1450         }
1451
1452         if (param->check_uid) {
1453                 if (st->st_uid == param->uid) {
1454                         if (param->exclude_uid)
1455                                 goto decided;
1456                 } else {
1457                         if (!param->exclude_uid)
1458                                 goto decided;
1459                 }
1460         }
1461
1462         if (param->check_gid) {
1463                 if (st->st_gid == param->gid) {
1464                         if (param->exclude_gid)
1465                                 goto decided;
1466                 } else {
1467                         if (!param->exclude_gid)
1468                                 goto decided;
1469                 }
1470         }
1471
1472         if (param->check_pool) {
1473                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
1474
1475                 /* empty requested pool is taken as no pool search => V1 */
1476                 if (((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V1) &&
1477                      (param->poolname[0] == '\0')) ||
1478                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
1479                      (strncmp(lmmv3->lmm_pool_name,
1480                               param->poolname, LOV_MAXPOOLNAME) == 0)) ||
1481                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
1482                      (strcmp(param->poolname, "*") == 0))) {
1483                         if (param->exclude_pool)
1484                                 goto decided;
1485                 } else {
1486                         if (!param->exclude_pool)
1487                                 goto decided;
1488                 }
1489         }
1490
1491         /* Check the time on mds. */
1492         if (!decision) {
1493                 int for_mds;
1494
1495                 for_mds = lustre_fs ? (S_ISREG(st->st_mode) &&
1496                                        param->lmd->lmd_lmm.lmm_stripe_count)
1497                                     : 0;
1498                 decision = find_time_check(st, param, for_mds);
1499         }
1500
1501 obd_matches:
1502         /* If file still fits the request, ask osd for updated info.
1503            The regulat stat is almost of the same speed as some new
1504            'glimpse-size-ioctl'. */
1505         if (!decision && S_ISREG(st->st_mode) &&
1506             (param->lmd->lmd_lmm.lmm_stripe_count || param->size)) {
1507                 if (param->obdindex != OBD_NOT_FOUND) {
1508                         /* Check whether the obd is active or not, if it is
1509                          * not active, just print the object affected by this
1510                          * failed ost
1511                          * */
1512                         struct obd_statfs stat_buf;
1513                         struct obd_uuid uuid_buf;
1514
1515                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
1516                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1517                         ret = llapi_obd_statfs(path, LL_STATFS_LOV,
1518                                                param->obdindex, &stat_buf,
1519                                                &uuid_buf);
1520                         if (ret) {
1521                                 if (ret == -ENODATA || ret == -ENODEV
1522                                     || ret == -EIO)
1523                                         errno = EIO;
1524                                 llapi_printf(LLAPI_MSG_NORMAL,
1525                                              "obd_uuid: %s failed %s ",
1526                                              param->obduuid->uuid,
1527                                              strerror(errno));
1528                                 goto print_path;
1529                         }
1530                 }
1531                 if (dir) {
1532                         ret = ioctl(dirfd(dir), IOC_LOV_GETINFO,
1533                                     (void *)param->lmd);
1534                 } else if (parent) {
1535                         ret = ioctl(dirfd(parent), IOC_LOV_GETINFO,
1536                                     (void *)param->lmd);
1537                 }
1538
1539                 if (ret) {
1540                         if (errno == ENOENT) {
1541                                 llapi_err(LLAPI_MSG_ERROR,
1542                                           "warning: %s: %s does not exist",
1543                                           __FUNCTION__, path);
1544                                 goto decided;
1545                         } else {
1546                                 llapi_err(LLAPI_MSG_ERROR,
1547                                           "%s: IOC_LOV_GETINFO on %s failed",
1548                                           __FUNCTION__, path);
1549                                 return ret;
1550                         }
1551                 }
1552
1553                 /* Check the time on osc. */
1554                 decision = find_time_check(st, param, 0);
1555                 if (decision == -1)
1556                         goto decided;
1557         }
1558
1559         if (param->size)
1560                 decision = find_value_cmp(st->st_size, param->size,
1561                                           param->size_sign, param->size_units,
1562                                           0);
1563
1564 print_path:
1565         if (decision != -1) {
1566                 llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
1567                 if (param->zeroend)
1568                         llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
1569                 else
1570                         llapi_printf(LLAPI_MSG_NORMAL, "\n");
1571         }
1572
1573 decided:
1574         /* Do not get down anymore? */
1575         if (param->depth == param->maxdepth)
1576                 return 1;
1577
1578         param->depth++;
1579         return 0;
1580 }
1581
1582 static int cb_common_fini(char *path, DIR *parent, DIR *d, void *data,
1583                           cfs_dirent_t *de)
1584 {
1585         struct find_param *param = (struct find_param *)data;
1586         param->depth--;
1587         return 0;
1588 }
1589
1590 int llapi_find(char *path, struct find_param *param)
1591 {
1592         char *buf;
1593         int ret, len = strlen(path);
1594
1595         if (len > PATH_MAX) {
1596                 llapi_err(LLAPI_MSG_ERROR, "%s: Path name '%s' is too long",
1597                           __FUNCTION__, path);
1598                 return -EINVAL;
1599         }
1600
1601         buf = (char *)malloc(PATH_MAX + 1);
1602         if (!buf)
1603                 return -ENOMEM;
1604
1605         ret = common_param_init(param);
1606         if (ret) {
1607                 free(buf);
1608                 return ret;
1609         }
1610
1611         param->depth = 0;
1612
1613         strncpy(buf, path, PATH_MAX + 1);
1614         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, cb_find_init,
1615                                       cb_common_fini, param, NULL);
1616
1617         find_param_fini(param);
1618         free(buf);
1619         return ret < 0 ? ret : 0;
1620 }
1621
1622 static int cb_getstripe(char *path, DIR *parent, DIR *d, void *data,
1623                         cfs_dirent_t *de)
1624 {
1625         struct find_param *param = (struct find_param *)data;
1626         int ret = 0;
1627
1628         LASSERT(parent != NULL || d != NULL);
1629
1630         /* Prepare odb. */
1631         if (!param->got_uuids) {
1632                 ret = setup_obd_uuid(d ? d : parent, path, param);
1633                 if (ret)
1634                         return ret;
1635         }
1636
1637         if (d) {
1638                 ret = ioctl(dirfd(d), LL_IOC_LOV_GETSTRIPE,
1639                             (void *)&param->lmd->lmd_lmm);
1640         } else if (parent) {
1641                 char *fname = strrchr(path, '/');
1642                 fname = (fname == NULL ? path : fname + 1);
1643
1644                 strncpy((char *)&param->lmd->lmd_lmm, fname, param->lumlen);
1645                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILESTRIPE,
1646                             (void *)&param->lmd->lmd_lmm);
1647         }
1648
1649         if (ret) {
1650                 if (errno == ENODATA) {
1651                         if (!param->obduuid && !param->quiet)
1652                                 llapi_printf(LLAPI_MSG_NORMAL,
1653                                              "%s has no stripe info\n", path);
1654                         goto out;
1655                 } else if (errno == ENOTTY) {
1656                         llapi_err(LLAPI_MSG_ERROR,
1657                                   "%s: '%s' not on a Lustre fs?",
1658                                   __FUNCTION__, path);
1659                 } else if (errno == ENOENT) {
1660                         llapi_err(LLAPI_MSG_WARN,
1661                                   "warning: %s: %s does not exist",
1662                                   __FUNCTION__, path);
1663                         goto out;
1664                 } else {
1665                         llapi_err(LLAPI_MSG_ERROR,
1666                                   "error: %s: %s failed for %s",
1667                                    __FUNCTION__, d ? "LL_IOC_LOV_GETSTRIPE" :
1668                                   "IOC_MDC_GETFILESTRIPE", path);
1669                 }
1670
1671                 return ret;
1672         }
1673
1674         llapi_lov_dump_user_lmm(param, path, d ? 1 : 0);
1675 out:
1676         /* Do not get down anymore? */
1677         if (param->depth == param->maxdepth)
1678                 return 1;
1679
1680         param->depth++;
1681         return 0;
1682 }
1683
1684 int llapi_getstripe(char *path, struct find_param *param)
1685 {
1686         char *buf;
1687         int ret = 0, len = strlen(path);
1688
1689         if (len > PATH_MAX) {
1690                 llapi_err(LLAPI_MSG_ERROR,
1691                           "%s: Path name '%s' is too long",
1692                           __FUNCTION__, path);
1693                 return -EINVAL;
1694         }
1695
1696         buf = (char *)malloc(PATH_MAX + 1);
1697         if (!buf)
1698                 return -ENOMEM;
1699
1700         ret = common_param_init(param);
1701         if (ret) {
1702                 free(buf);
1703                 return ret;
1704         }
1705
1706         param->depth = 0;
1707
1708         strncpy(buf, path, PATH_MAX + 1);
1709         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, cb_getstripe,
1710                                       cb_common_fini, param, NULL);
1711         find_param_fini(param);
1712         free(buf);
1713         return ret < 0 ? ret : 0;
1714 }
1715
1716 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
1717                      struct obd_statfs *stat_buf,
1718                      struct obd_uuid *uuid_buf)
1719 {
1720         int fd;
1721         char raw[OBD_MAX_IOCTL_BUFFER] = {'\0'};
1722         char *rawbuf = raw;
1723         struct obd_ioctl_data data = { 0 };
1724         int rc = 0;
1725
1726         data.ioc_inlbuf1 = (char *)&type;
1727         data.ioc_inllen1 = sizeof(__u32);
1728         data.ioc_inlbuf2 = (char *)&index;
1729         data.ioc_inllen2 = sizeof(__u32);
1730         data.ioc_pbuf1 = (char *)stat_buf;
1731         data.ioc_plen1 = sizeof(struct obd_statfs);
1732         data.ioc_pbuf2 = (char *)uuid_buf;
1733         data.ioc_plen2 = sizeof(struct obd_uuid);
1734
1735         if ((rc = obd_ioctl_pack(&data, &rawbuf, sizeof(raw))) != 0) {
1736                 llapi_err(LLAPI_MSG_ERROR,
1737                           "llapi_obd_statfs: error packing ioctl data");
1738                 return rc;
1739         }
1740
1741         fd = open(path, O_RDONLY);
1742         if (errno == EISDIR)
1743                 fd = open(path, O_DIRECTORY | O_RDONLY);
1744
1745         if (fd < 0) {
1746                 rc = errno ? -errno : -EBADF;
1747                 llapi_err(LLAPI_MSG_ERROR, "error: %s: opening '%s'",
1748                           __FUNCTION__, path);
1749                 return rc;
1750         }
1751         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
1752         if (rc)
1753                 rc = errno ? -errno : -EINVAL;
1754
1755         close(fd);
1756         return rc;
1757 }
1758
1759 #define MAX_STRING_SIZE 128
1760 #define DEVICES_LIST "/proc/fs/lustre/devices"
1761
1762 int llapi_ping(char *obd_type, char *obd_name)
1763 {
1764         char path[MAX_STRING_SIZE];
1765         char buf[1];
1766         int rc, fd;
1767
1768         snprintf(path, MAX_STRING_SIZE, "/proc/fs/lustre/%s/%s/ping",
1769                  obd_type, obd_name);
1770
1771         fd = open(path, O_WRONLY);
1772         if (fd < 0) {
1773                 rc = errno;
1774                 llapi_err(LLAPI_MSG_ERROR, "error opening %s", path);
1775                 return rc;
1776         }
1777
1778         rc = write(fd, buf, 1);
1779         close(fd);
1780
1781         if (rc == 1)
1782                 return 0;
1783         return rc;
1784 }
1785
1786 int llapi_target_iterate(int type_num, char **obd_type,void *args,llapi_cb_t cb)
1787 {
1788         char buf[MAX_STRING_SIZE];
1789         FILE *fp = fopen(DEVICES_LIST, "r");
1790         int i, rc = 0;
1791
1792         if (fp == NULL) {
1793                 rc = errno;
1794                 llapi_err(LLAPI_MSG_ERROR, "error: opening "DEVICES_LIST);
1795                 return rc;
1796         }
1797
1798         while (fgets(buf, sizeof(buf), fp) != NULL) {
1799                 char *obd_type_name = NULL;
1800                 char *obd_name = NULL;
1801                 char *obd_uuid = NULL;
1802                 char rawbuf[OBD_MAX_IOCTL_BUFFER];
1803                 char *bufl = rawbuf;
1804                 char *bufp = buf;
1805                 struct obd_ioctl_data datal = { 0, };
1806                 struct obd_statfs osfs_buffer;
1807
1808                 while(bufp[0] == ' ')
1809                         ++bufp;
1810
1811                 for(i = 0; i < 3; i++) {
1812                         obd_type_name = strsep(&bufp, " ");
1813                 }
1814                 obd_name = strsep(&bufp, " ");
1815                 obd_uuid = strsep(&bufp, " ");
1816
1817                 memset(&osfs_buffer, 0, sizeof (osfs_buffer));
1818
1819                 memset(bufl, 0, sizeof(rawbuf));
1820                 datal.ioc_pbuf1 = (char *)&osfs_buffer;
1821                 datal.ioc_plen1 = sizeof(osfs_buffer);
1822
1823                 for (i = 0; i < type_num; i++) {
1824                         if (strcmp(obd_type_name, obd_type[i]) != 0)
1825                                 continue;
1826
1827                         cb(obd_type_name, obd_name, obd_uuid, args);
1828                 }
1829         }
1830         fclose(fp);
1831         return rc;
1832 }
1833
1834 static void do_target_check(char *obd_type_name, char *obd_name,
1835                             char *obd_uuid, void *args)
1836 {
1837         int rc;
1838
1839         rc = llapi_ping(obd_type_name, obd_name);
1840         if (rc == ENOTCONN) {
1841                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
1842         } else if (rc) {
1843                 llapi_err(LLAPI_MSG_ERROR, "error: check '%s'", obd_name);
1844         } else {
1845                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
1846         }
1847 }
1848
1849 int llapi_target_check(int type_num, char **obd_type, char *dir)
1850 {
1851         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
1852 }
1853
1854 #undef MAX_STRING_SIZE
1855
1856 int llapi_catinfo(char *dir, char *keyword, char *node_name)
1857 {
1858         char raw[OBD_MAX_IOCTL_BUFFER];
1859         char out[LLOG_CHUNK_SIZE];
1860         char *buf = raw;
1861         struct obd_ioctl_data data = { 0 };
1862         char key[30];
1863         DIR *root;
1864         int rc;
1865
1866         sprintf(key, "%s", keyword);
1867         memset(raw, 0, sizeof(raw));
1868         memset(out, 0, sizeof(out));
1869         data.ioc_inlbuf1 = key;
1870         data.ioc_inllen1 = strlen(key) + 1;
1871         if (node_name) {
1872                 data.ioc_inlbuf2 = node_name;
1873                 data.ioc_inllen2 = strlen(node_name) + 1;
1874         }
1875         data.ioc_pbuf1 = out;
1876         data.ioc_plen1 = sizeof(out);
1877         rc = obd_ioctl_pack(&data, &buf, sizeof(raw));
1878         if (rc)
1879                 return rc;
1880
1881         root = opendir(dir);
1882         if (root == NULL) {
1883                 rc = errno;
1884                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", dir);
1885                 return rc;
1886         }
1887
1888         rc = ioctl(dirfd(root), OBD_IOC_LLOG_CATINFO, buf);
1889         if (rc)
1890                 llapi_err(LLAPI_MSG_ERROR, "ioctl OBD_IOC_CATINFO failed");
1891         else
1892                 llapi_printf(LLAPI_MSG_NORMAL, "%s", data.ioc_pbuf1);
1893
1894         closedir(root);
1895         return rc;
1896 }
1897
1898 /* Is this a lustre fs? */
1899 int llapi_is_lustre_mnttype(const char *type)
1900 {
1901         return (strcmp(type, "lustre") == 0 || strcmp(type,"lustre_lite") == 0);
1902 }
1903
1904 /* Is this a lustre client fs? */
1905 int llapi_is_lustre_mnt(struct mntent *mnt)
1906 {
1907         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
1908                 strstr(mnt->mnt_fsname, ":/") != NULL);
1909 }
1910
1911 int llapi_quotacheck(char *mnt, int check_type)
1912 {
1913         DIR *root;
1914         int rc;
1915
1916         root = opendir(mnt);
1917         if (!root) {
1918                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
1919                 return -1;
1920         }
1921
1922         rc = ioctl(dirfd(root), LL_IOC_QUOTACHECK, check_type);
1923
1924         closedir(root);
1925         return rc;
1926 }
1927
1928 int llapi_poll_quotacheck(char *mnt, struct if_quotacheck *qchk)
1929 {
1930         DIR *root;
1931         int poll_intvl = 2;
1932         int rc;
1933
1934         root = opendir(mnt);
1935         if (!root) {
1936                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
1937                 return -1;
1938         }
1939
1940         while (1) {
1941                 rc = ioctl(dirfd(root), LL_IOC_POLL_QUOTACHECK, qchk);
1942                 if (!rc)
1943                         break;
1944                 sleep(poll_intvl);
1945                 if (poll_intvl < 30)
1946                         poll_intvl *= 2;
1947         }
1948
1949         closedir(root);
1950         return rc;
1951 }
1952
1953 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
1954 {
1955         DIR *root;
1956         int rc;
1957
1958         root = opendir(mnt);
1959         if (!root) {
1960                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
1961                 return -1;
1962         }
1963
1964         rc = ioctl(dirfd(root), LL_IOC_QUOTACTL, qctl);
1965
1966         closedir(root);
1967         return rc;
1968 }
1969
1970 static int cb_quotachown(char *path, DIR *parent, DIR *d, void *data,
1971                          cfs_dirent_t *de)
1972 {
1973         struct find_param *param = (struct find_param *)data;
1974         lstat_t *st;
1975         int rc;
1976
1977         LASSERT(parent != NULL || d != NULL);
1978
1979         if (d) {
1980                 rc = ioctl(dirfd(d), LL_IOC_MDC_GETINFO,
1981                            (void *)param->lmd);
1982         } else if (parent) {
1983                 char *fname = strrchr(path, '/');
1984                 fname = (fname == NULL ? path : fname + 1);
1985
1986                 strncpy((char *)param->lmd, fname, param->lumlen);
1987                 rc = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
1988                            (void *)param->lmd);
1989         } else {
1990                 return 0;
1991         }
1992
1993         if (rc) {
1994                 if (errno == ENODATA) {
1995                         if (!param->obduuid && !param->quiet)
1996                                 llapi_err(LLAPI_MSG_ERROR,
1997                                           "%s has no stripe info", path);
1998                         rc = 0;
1999                 } else if (errno == ENOENT) {
2000                         llapi_err(LLAPI_MSG_ERROR,
2001                                   "warning: %s: %s does not exist",
2002                                   __FUNCTION__, path);
2003                         rc = 0;
2004                 } else if (errno != EISDIR) {
2005                         rc = errno;
2006                         llapi_err(LLAPI_MSG_ERROR, "%s ioctl failed for %s.",
2007                                   d ? "LL_IOC_MDC_GETINFO" :
2008                                   "IOC_MDC_GETFILEINFO", path);
2009                 }
2010                 return rc;
2011         }
2012
2013         st = &param->lmd->lmd_st;
2014
2015         /* libc chown() will do extra check, and if the real owner is
2016          * the same as the ones to set, it won't fall into kernel, so
2017          * invoke syscall directly. */
2018         rc = syscall(SYS_chown, path, -1, -1);
2019         if (rc)
2020                 llapi_err(LLAPI_MSG_ERROR,"error: chown %s (%u,%u)", path);
2021
2022         rc = chmod(path, st->st_mode);
2023         if (rc)
2024                 llapi_err(LLAPI_MSG_ERROR, "error: chmod %s (%hu)",
2025                           path, st->st_mode);
2026
2027         return rc;
2028 }
2029
2030 int llapi_quotachown(char *path, int flag)
2031 {
2032         struct find_param param;
2033         char *buf;
2034         int ret = 0, len = strlen(path);
2035
2036         if (len > PATH_MAX) {
2037                 llapi_err(LLAPI_MSG_ERROR, "%s: Path name '%s' is too long",
2038                           __FUNCTION__, path);
2039                 return -EINVAL;
2040         }
2041
2042         buf = (char *)malloc(PATH_MAX + 1);
2043         if (!buf)
2044                 return -ENOMEM;
2045
2046         memset(&param, 0, sizeof(param));
2047         param.recursive = 1;
2048         param.verbose = 0;
2049         param.quiet = 1;
2050
2051         ret = common_param_init(&param);
2052         if (ret)
2053                 goto out;
2054
2055         strncpy(buf, path, PATH_MAX + 1);
2056         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, cb_quotachown,
2057                                       NULL, &param, NULL);
2058 out:
2059         find_param_fini(&param);
2060         free(buf);
2061         return ret;
2062 }
2063
2064 #include <pwd.h>
2065 #include <grp.h>
2066 #include <mntent.h>
2067 #include <sys/wait.h>
2068 #include <errno.h>
2069 #include <ctype.h>
2070
2071 static int rmtacl_notify(int ops)
2072 {
2073         FILE *fp;
2074         struct mntent *mnt;
2075         int found = 0, fd, rc;
2076
2077         fp = setmntent(MOUNTED, "r");
2078         if (fp == NULL) {
2079                 perror("setmntent");
2080                 return -1;
2081         }
2082
2083         while (1) {
2084                 mnt = getmntent(fp);
2085                 if (!mnt)
2086                         break;
2087
2088                 if (!llapi_is_lustre_mnt(mnt))
2089                         continue;
2090
2091                 fd = open(mnt->mnt_dir, O_RDONLY | O_DIRECTORY);
2092                 if (fd < 0) {
2093                         perror("open");
2094                         return -1;
2095                 }
2096
2097                 rc = ioctl(fd, LL_IOC_RMTACL, ops);
2098                 if (rc < 0) {
2099                         perror("ioctl");
2100                 return -1;
2101         }
2102
2103                 found++;
2104         }
2105         endmntent(fp);
2106         return found;
2107 }
2108
2109 static char *next_token(char *p, int div)
2110 {
2111         if (p == NULL)
2112                 return NULL;
2113
2114         if (div)
2115                 while (*p && *p != ':' && !isspace(*p))
2116                         p++;
2117         else
2118                 while (*p == ':' || isspace(*p))
2119                         p++;
2120
2121         return *p ? p : NULL;
2122 }
2123
2124 static int rmtacl_name2id(char *name, int is_user)
2125 {
2126         if (is_user) {
2127                 struct passwd *pw;
2128
2129                 if ((pw = getpwnam(name)) == NULL)
2130                         return INVALID_ID;
2131                 else
2132                         return (int)(pw->pw_uid);
2133         } else {
2134                 struct group *gr;
2135
2136                 if ((gr = getgrnam(name)) == NULL)
2137                         return INVALID_ID;
2138                 else
2139                         return (int)(gr->gr_gid);
2140         }
2141 }
2142
2143 static int isodigit(int c)
2144 {
2145         return (c >= '0' && c <= '7') ? 1 : 0;
2146 }
2147
2148 /*
2149  * Whether the name is just digits string (uid/gid) already or not.
2150  * Return value:
2151  * 1: str is id
2152  * 0: str is not id
2153  */
2154 static int str_is_id(char *str)
2155 {
2156         if (str == NULL)
2157                 return 0;
2158
2159         if (*str == '0') {
2160                 str++;
2161                 if (*str == 'x' || *str == 'X') { /* for Hex. */
2162                         if (!isxdigit(*(++str)))
2163                                 return 0;
2164
2165                         while (isxdigit(*(++str)));
2166                 } else if (isodigit(*str)) { /* for Oct. */
2167                         while (isodigit(*(++str)));
2168                 }
2169         } else if (isdigit(*str)) { /* for Dec. */
2170                 while (isdigit(*(++str)));
2171         }
2172
2173         return (*str == 0) ? 1 : 0;
2174 }
2175
2176 typedef struct {
2177         char *name;
2178         int   length;
2179         int   is_user;
2180         int   next_token;
2181 } rmtacl_name_t;
2182
2183 #define RMTACL_OPTNAME(name) name, sizeof(name) - 1
2184
2185 static rmtacl_name_t rmtacl_namelist[] = {
2186         { RMTACL_OPTNAME("user:"),            1,      0 },
2187         { RMTACL_OPTNAME("group:"),           0,      0 },
2188         { RMTACL_OPTNAME("default:user:"),    1,      0 },
2189         { RMTACL_OPTNAME("default:group:"),   0,      0 },
2190         /* for --tabular option */
2191         { RMTACL_OPTNAME("user"),             1,      1 },
2192         { RMTACL_OPTNAME("group"),            0,      1 },
2193         { 0 }
2194 };
2195
2196 static int rgetfacl_output(char *str)
2197 {
2198         char *start = NULL, *end = NULL;
2199         int is_user = 0, n, id;
2200         char c;
2201         rmtacl_name_t *rn;
2202
2203         if (str == NULL)
2204                 return -1;
2205
2206         for (rn = rmtacl_namelist; rn->name; rn++) {
2207                 if(strncmp(str, rn->name, rn->length) == 0) {
2208                         if (!rn->next_token)
2209                                 start = str + rn->length;
2210                         else
2211                                 start = next_token(str + rn->length, 0);
2212                         is_user = rn->is_user;
2213                         break;
2214                 }
2215         }
2216
2217         end = next_token(start, 1);
2218         if (end == NULL || start == end) {
2219                 n = printf("%s", str);
2220                 return n;
2221         }
2222
2223         c = *end;
2224         *end = 0;
2225         id = rmtacl_name2id(start, is_user);
2226         if (id == INVALID_ID) {
2227                 if (str_is_id(start)) {
2228                         *end = c;
2229                         n = printf("%s", str);
2230                 } else
2231                         return -1;
2232         } else if ((id == NOBODY_UID && is_user) ||
2233                    (id == NOBODY_GID && !is_user)) {
2234                 *end = c;
2235                 n = printf("%s", str);
2236         } else {
2237                 *end = c;
2238                 *start = 0;
2239                 n = printf("%s%d%s", str, id, end);
2240         }
2241         return n;
2242 }
2243
2244 static int child_status(int status)
2245 {
2246         return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
2247 }
2248
2249 static int do_rmtacl(int argc, char *argv[], int ops, int (output_func)(char *))
2250 {
2251         pid_t pid = 0;
2252         int fd[2], status;
2253         FILE *fp;
2254         char buf[PIPE_BUF];
2255
2256         if (output_func) {
2257                 if (pipe(fd) < 0) {
2258                         perror("pipe");
2259                         return -1;
2260                 }
2261
2262                 if ((pid = fork()) < 0) {
2263                         perror("fork");
2264                         close(fd[0]);
2265                         close(fd[1]);
2266                         return -1;
2267                 } else if (!pid) {
2268                         /* child process redirects its output. */
2269                         close(fd[0]);
2270                         close(1);
2271                         if (dup2(fd[1], 1) < 0) {
2272                                 perror("dup2");
2273                                 close(fd[1]);
2274                                 return -1;
2275                         }
2276                 } else {
2277                         close(fd[1]);
2278                 }
2279         }
2280
2281         if (!pid) {
2282                 status = rmtacl_notify(ops);
2283                 if (status < 0)
2284                         return -1;
2285
2286                 exit(execvp(argv[0], argv));
2287         }
2288
2289         /* the following is parent process */
2290         if ((fp = fdopen(fd[0], "r")) == NULL) {
2291                 perror("fdopen");
2292                 kill(pid, SIGKILL);
2293                 close(fd[0]);
2294                 return -1;
2295         }
2296
2297         while (fgets(buf, PIPE_BUF, fp) != NULL) {
2298                 if (output_func(buf) < 0)
2299                         fprintf(stderr, "WARNING: unexpected error!\n[%s]\n",
2300                                 buf);
2301         }
2302         fclose(fp);
2303         close(fd[0]);
2304
2305         if (waitpid(pid, &status, 0) < 0) {
2306                 perror("waitpid");
2307                 return -1;
2308         }
2309
2310         return child_status(status);
2311 }
2312
2313 int llapi_lsetfacl(int argc, char *argv[])
2314 {
2315         return do_rmtacl(argc, argv, RMT_LSETFACL, NULL);
2316 }
2317
2318 int llapi_lgetfacl(int argc, char *argv[])
2319 {
2320         return do_rmtacl(argc, argv, RMT_LGETFACL, NULL);
2321 }
2322
2323 int llapi_rsetfacl(int argc, char *argv[])
2324 {
2325         return do_rmtacl(argc, argv, RMT_RSETFACL, NULL);
2326 }
2327
2328 int llapi_rgetfacl(int argc, char *argv[])
2329 {
2330         return do_rmtacl(argc, argv, RMT_RGETFACL, rgetfacl_output);
2331 }
2332
2333 int llapi_cp(int argc, char *argv[])
2334 {
2335         int rc;
2336
2337         rc = rmtacl_notify(RMT_RSETFACL);
2338         if (rc < 0)
2339                 return -1;
2340
2341         exit(execvp(argv[0], argv));
2342 }
2343
2344 int llapi_ls(int argc, char *argv[])
2345 {
2346         int rc;
2347
2348         rc = rmtacl_notify(RMT_LGETFACL);
2349         if (rc < 0)
2350                 return -1;
2351
2352         exit(execvp(argv[0], argv));
2353 }