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