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