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