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