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