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