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