Whamcloud - gitweb
LU-169 lov: add generation number to LOV EA
[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 (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
30  * Use is subject to license terms.
31  */
32 /*
33  * Copyright (c) 2011 Whamcloud, Inc.
34  */
35 /*
36  * This file is part of Lustre, http://www.lustre.org/
37  * Lustre is a trademark of Sun Microsystems, Inc.
38  *
39  * lustre/utils/liblustreapi.c
40  *
41  * Author: Peter J. Braam <braam@clusterfs.com>
42  * Author: Phil Schwan <phil@clusterfs.com>
43  * Author: Robert Read <rread@clusterfs.com>
44  */
45
46 /* for O_DIRECTORY */
47 #ifndef _GNU_SOURCE
48 #define _GNU_SOURCE
49 #endif
50
51 #include <stdlib.h>
52 #include <stdio.h>
53 #include <string.h>
54 #include <stddef.h>
55 #include <sys/ioctl.h>
56 #include <unistd.h>
57 #include <fcntl.h>
58 #include <errno.h>
59 #include <dirent.h>
60 #include <stdarg.h>
61 #include <sys/stat.h>
62 #include <sys/types.h>
63 #include <sys/syscall.h>
64 #include <sys/xattr.h>
65 #include <fnmatch.h>
66 #include <glob.h>
67 #ifdef HAVE_LINUX_UNISTD_H
68 #include <linux/unistd.h>
69 #else
70 #include <unistd.h>
71 #endif
72 #include <poll.h>
73
74 #include <liblustre.h>
75 #include <lnet/lnetctl.h>
76 #include <obd.h>
77 #include <lustre_lib.h>
78 #include <obd_lov.h>
79 #include <lustre/liblustreapi.h>
80
81 static unsigned llapi_dir_filetype_table[] = {
82         [DT_UNKNOWN]= 0,
83         [DT_FIFO]= S_IFIFO,
84         [DT_CHR] = S_IFCHR,
85         [DT_DIR] = S_IFDIR,
86         [DT_BLK] = S_IFBLK,
87         [DT_REG] = S_IFREG,
88         [DT_LNK] = S_IFLNK,
89         [DT_SOCK]= S_IFSOCK,
90 #if defined(DT_DOOR) && defined(S_IFDOOR)
91         [DT_DOOR]= S_IFDOOR,
92 #endif
93 };
94
95 #if defined(DT_DOOR) && defined(S_IFDOOR)
96 static const int DT_MAX = DT_DOOR;
97 #else
98 static const int DT_MAX = DT_SOCK;
99 #endif
100
101 static unsigned llapi_filetype_dir_table[] = {
102         [0]= DT_UNKNOWN,
103         [S_IFIFO]= DT_FIFO,
104         [S_IFCHR] = DT_CHR,
105         [S_IFDIR] = DT_DIR,
106         [S_IFBLK] = DT_BLK,
107         [S_IFREG] = DT_REG,
108         [S_IFLNK] = DT_LNK,
109         [S_IFSOCK]= DT_SOCK,
110 #if defined(DT_DOOR) && defined(S_IFDOOR)
111         [S_IFDOOR]= DT_DOOR,
112 #endif
113 };
114
115 #if defined(DT_DOOR) && defined(S_IFDOOR)
116 static const int S_IFMAX = DT_DOOR;
117 #else
118 static const int S_IFMAX = DT_SOCK;
119 #endif
120
121 /* liblustreapi message level */
122 static int llapi_msg_level = LLAPI_MSG_MAX;
123
124 void llapi_msg_set_level(int level)
125 {
126         /* ensure level is in the good range */
127         if (level < LLAPI_MSG_OFF)
128                 llapi_msg_level = LLAPI_MSG_OFF;
129         else if (level > LLAPI_MSG_MAX)
130                 llapi_msg_level = LLAPI_MSG_MAX;
131         else
132                 llapi_msg_level = level;
133 }
134
135 /* llapi_error will preserve errno */
136 void llapi_error(int level, int _rc, char *fmt, ...)
137 {
138         va_list args;
139         int tmp_errno = errno;
140         /* to protect using errno as _rc argument */
141         int rc = abs(_rc);
142
143         if ((level & LLAPI_MSG_MASK) > llapi_msg_level)
144                 return;
145
146         va_start(args, fmt);
147         vfprintf(stderr, fmt, args);
148         va_end(args);
149
150         if (level & LLAPI_MSG_NO_ERRNO)
151                 fprintf(stderr, "\n");
152         else
153                 fprintf(stderr, ": %s (%d)\n", strerror(rc), rc);
154         errno = tmp_errno;
155 }
156
157 /* llapi_printf will preserve errno */
158 void llapi_printf(int level, char *fmt, ...)
159 {
160         va_list args;
161         int tmp_errno = errno;
162
163         if ((level & LLAPI_MSG_MASK) > llapi_msg_level)
164                 return;
165
166         va_start(args, fmt);
167         vfprintf(stdout, fmt, args);
168         va_end(args);
169         errno = tmp_errno;
170 }
171
172 /**
173  * size_units is to be initialized (or zeroed) by caller.
174  */
175 int parse_size(char *optarg, unsigned long long *size,
176                unsigned long long *size_units, int bytes_spec)
177 {
178         char *end;
179
180         if (*size_units == 0)
181                 *size_units = 1;
182
183         *size = strtoull(optarg, &end, 0);
184
185         if (*end != '\0') {
186                 if ((*end == 'b') && *(end+1) == '\0' &&
187                     (*size & (~0ULL << (64 - 9))) == 0 &&
188                     !bytes_spec) {
189                         *size_units = 1 << 9;
190                 } else if ((*end == 'b') && *(end+1) == '\0' &&
191                            bytes_spec) {
192                         *size_units = 1;
193                 } else if ((*end == 'k' || *end == 'K') &&
194                            *(end+1) == '\0' && (*size &
195                            (~0ULL << (64 - 10))) == 0) {
196                         *size_units = 1 << 10;
197                 } else if ((*end == 'm' || *end == 'M') &&
198                            *(end+1) == '\0' && (*size &
199                            (~0ULL << (64 - 20))) == 0) {
200                         *size_units = 1 << 20;
201                 } else if ((*end == 'g' || *end == 'G') &&
202                            *(end+1) == '\0' && (*size &
203                            (~0ULL << (64 - 30))) == 0) {
204                         *size_units = 1 << 30;
205                 } else if ((*end == 't' || *end == 'T') &&
206                            *(end+1) == '\0' && (*size &
207                            (~0ULL << (64 - 40))) == 0) {
208                         *size_units = 1ULL << 40;
209                 } else if ((*end == 'p' || *end == 'P') &&
210                            *(end+1) == '\0' && (*size &
211                            (~0ULL << (64 - 50))) == 0) {
212                         *size_units = 1ULL << 50;
213                 } else if ((*end == 'e' || *end == 'E') &&
214                            *(end+1) == '\0' && (*size &
215                            (~0ULL << (64 - 60))) == 0) {
216                         *size_units = 1ULL << 60;
217                 } else {
218                         return -1;
219                 }
220         }
221         *size *= *size_units;
222         return 0;
223 }
224
225 /* XXX: llapi_xxx() functions return negative values upon failure */
226
227 int llapi_stripe_limit_check(unsigned long long stripe_size, int stripe_offset,
228                              int stripe_count, int stripe_pattern)
229 {
230         int page_size, rc;
231
232         /* 64 KB is the largest common page size I'm aware of (on ia64), but
233          * check the local page size just in case. */
234         page_size = LOV_MIN_STRIPE_SIZE;
235         if (getpagesize() > page_size) {
236                 page_size = getpagesize();
237                 llapi_err_noerrno(LLAPI_MSG_WARN,
238                                   "warning: your page size (%u) is "
239                                   "larger than expected (%u)", page_size,
240                                   LOV_MIN_STRIPE_SIZE);
241         }
242         if (stripe_size < 0 || (stripe_size & (LOV_MIN_STRIPE_SIZE - 1))) {
243                 rc = -EINVAL;
244                 llapi_error(LLAPI_MSG_ERROR, rc, "error: bad stripe_size %lu, "
245                             "must be an even multiple of %d bytes",
246                             stripe_size, page_size);
247                 return rc;
248         }
249         if (stripe_offset < -1 || stripe_offset > MAX_OBD_DEVICES) {
250                 rc = -EINVAL;
251                 llapi_error(LLAPI_MSG_ERROR, rc, "error: bad stripe offset %d",
252                             stripe_offset);
253                 return rc;
254         }
255         if (stripe_count < -1 || stripe_count > LOV_MAX_STRIPE_COUNT) {
256                 rc = -EINVAL;
257                 llapi_error(LLAPI_MSG_ERROR, rc, "error: bad stripe count %d",
258                             stripe_count);
259                 return rc;
260         }
261         if (stripe_size >= (1ULL << 32)){
262                 rc = -EINVAL;
263                 llapi_error(LLAPI_MSG_ERROR, rc,
264                             "warning: stripe size larger than 4G "
265                             "is not currently supported and would wrap");
266                 return rc;
267         }
268         return 0;
269 }
270
271 static int find_target_obdpath(char *fsname, char *path)
272 {
273         glob_t glob_info;
274         char pattern[PATH_MAX + 1];
275         int rc;
276
277         snprintf(pattern, PATH_MAX,
278                  "/proc/fs/lustre/lov/%s-*/target_obd",
279                  fsname);
280         rc = glob(pattern, GLOB_BRACE, NULL, &glob_info);
281         if (rc == GLOB_NOMATCH)
282                 return -ENODEV;
283         else if (rc)
284                 return -EINVAL;
285
286         strcpy(path, glob_info.gl_pathv[0]);
287         globfree(&glob_info);
288         return 0;
289 }
290
291 static int find_poolpath(char *fsname, char *poolname, char *poolpath)
292 {
293         glob_t glob_info;
294         char pattern[PATH_MAX + 1];
295         int rc;
296
297         snprintf(pattern, PATH_MAX,
298                  "/proc/fs/lustre/lov/%s-*/pools/%s",
299                  fsname, poolname);
300         rc = glob(pattern, GLOB_BRACE, NULL, &glob_info);
301         /* If no pools, make sure the lov is available */
302         if ((rc == GLOB_NOMATCH) &&
303             (find_target_obdpath(fsname, poolpath) == -ENODEV))
304                 return -ENODEV;
305         if (rc)
306                 return -EINVAL;
307
308         strcpy(poolpath, glob_info.gl_pathv[0]);
309         globfree(&glob_info);
310         return 0;
311 }
312
313 /*
314  * if pool is NULL, search ostname in target_obd
315  * if pool is not NULL:
316  *  if pool not found returns errno < 0
317  *  if ostname is NULL, returns 1 if pool is not empty and 0 if pool empty
318  *  if ostname is not NULL, returns 1 if OST is in pool and 0 if not
319  */
320 int llapi_search_ost(char *fsname, char *poolname, char *ostname)
321 {
322         FILE *fd;
323         char buffer[PATH_MAX + 1];
324         int len = 0, rc;
325
326         if (ostname != NULL)
327                 len = strlen(ostname);
328
329         if (poolname == NULL)
330                 rc = find_target_obdpath(fsname, buffer);
331         else
332                 rc = find_poolpath(fsname, poolname, buffer);
333         if (rc)
334                 return rc;
335
336         fd = fopen(buffer, "r");
337         if (fd == NULL)
338                 return -errno;
339
340         while (fgets(buffer, sizeof(buffer), fd) != NULL) {
341                 if (poolname == NULL) {
342                         char *ptr;
343                         /* Search for an ostname in the list of OSTs
344                          Line format is IDX: fsname-OSTxxxx_UUID STATUS */
345                         ptr = strchr(buffer, ' ');
346                         if ((ptr != NULL) &&
347                             (strncmp(ptr + 1, ostname, len) == 0)) {
348                                 fclose(fd);
349                                 return 1;
350                         }
351                 } else {
352                         /* Search for an ostname in a pool,
353                          (or an existing non-empty pool if no ostname) */
354                         if ((ostname == NULL) ||
355                             (strncmp(buffer, ostname, len) == 0)) {
356                                 fclose(fd);
357                                 return 1;
358                         }
359                 }
360         }
361         fclose(fd);
362         return 0;
363 }
364
365 int llapi_file_open_pool(const char *name, int flags, int mode,
366                          unsigned long long stripe_size, int stripe_offset,
367                          int stripe_count, int stripe_pattern, char *pool_name)
368 {
369         struct lov_user_md_v3 lum = { 0 };
370         int fd, rc = 0;
371         int isdir = 0;
372
373         /* Make sure we have a good pool */
374         if (pool_name != NULL) {
375                 char fsname[MAX_OBD_NAME + 1], *ptr;
376
377                 rc = llapi_search_fsname(name, fsname);
378                 if (rc) {
379                         llapi_error(LLAPI_MSG_ERROR, rc,
380                                     "'%s' is not on a Lustre filesystem",
381                                     name);
382                         return rc;
383                 }
384
385                 /* in case user gives the full pool name <fsname>.<poolname>,
386                  * strip the fsname */
387                 ptr = strchr(pool_name, '.');
388                 if (ptr != NULL) {
389                         *ptr = '\0';
390                         if (strcmp(pool_name, fsname) != 0) {
391                                 *ptr = '.';
392                                 llapi_err_noerrno(LLAPI_MSG_ERROR,
393                                           "Pool '%s' is not on filesystem '%s'",
394                                           pool_name, fsname);
395                                 return -EINVAL;
396                         }
397                         pool_name = ptr + 1;
398                 }
399
400                 /* Make sure the pool exists and is non-empty */
401                 rc = llapi_search_ost(fsname, pool_name, NULL);
402                 if (rc < 1) {
403                         llapi_err_noerrno(LLAPI_MSG_ERROR,
404                                           "pool '%s.%s' %s", fsname, pool_name,
405                                           rc == 0 ? "has no OSTs" : "does not exist");
406                         return -EINVAL;
407                 }
408         }
409
410         fd = open(name, flags | O_LOV_DELAY_CREATE, mode);
411         if (fd < 0 && errno == EISDIR) {
412                 fd = open(name, O_DIRECTORY | O_RDONLY);
413                 isdir++;
414         }
415
416         if (fd < 0) {
417                 rc = -errno;
418                 llapi_error(LLAPI_MSG_ERROR, rc, "unable to open '%s'", name);
419                 return rc;
420         }
421
422         rc = llapi_stripe_limit_check(stripe_size, stripe_offset, stripe_count,
423                                       stripe_pattern);
424         if (rc != 0)
425                 goto out;
426
427         /*  Initialize IOCTL striping pattern structure */
428         lum.lmm_magic = LOV_USER_MAGIC_V3;
429         lum.lmm_pattern = stripe_pattern;
430         lum.lmm_stripe_size = stripe_size;
431         lum.lmm_stripe_count = stripe_count;
432         lum.lmm_stripe_offset = stripe_offset;
433         if (pool_name != NULL) {
434                 strncpy(lum.lmm_pool_name, pool_name, LOV_MAXPOOLNAME);
435         } else {
436                 /* If no pool is specified at all, use V1 request */
437                 lum.lmm_magic = LOV_USER_MAGIC_V1;
438         }
439
440         if (ioctl(fd, LL_IOC_LOV_SETSTRIPE, &lum)) {
441                 char *errmsg = "stripe already set";
442                 rc = -errno;
443                 if (errno != EEXIST && errno != EALREADY)
444                         errmsg = strerror(errno);
445
446                 llapi_err_noerrno(LLAPI_MSG_ERROR,
447                                   "error on ioctl "LPX64" for '%s' (%d): %s",
448                                   (__u64)LL_IOC_LOV_SETSTRIPE, name, fd,errmsg);
449         }
450 out:
451         if (rc) {
452                 close(fd);
453                 fd = rc;
454         }
455
456         return fd;
457 }
458
459 int llapi_file_open(const char *name, int flags, int mode,
460                     unsigned long long stripe_size, int stripe_offset,
461                     int stripe_count, int stripe_pattern)
462 {
463         return llapi_file_open_pool(name, flags, mode, stripe_size,
464                                     stripe_offset, stripe_count,
465                                     stripe_pattern, NULL);
466 }
467
468 int llapi_file_create(const char *name, unsigned long long stripe_size,
469                       int stripe_offset, int stripe_count, int stripe_pattern)
470 {
471         int fd;
472
473         fd = llapi_file_open_pool(name, O_CREAT | O_WRONLY, 0644, stripe_size,
474                                   stripe_offset, stripe_count, stripe_pattern,
475                                   NULL);
476         if (fd < 0)
477                 return fd;
478
479         close(fd);
480         return 0;
481 }
482
483 int llapi_file_create_pool(const char *name, unsigned long long stripe_size,
484                            int stripe_offset, int stripe_count,
485                            int stripe_pattern, char *pool_name)
486 {
487         int fd;
488
489         fd = llapi_file_open_pool(name, O_CREAT | O_WRONLY, 0644, stripe_size,
490                                   stripe_offset, stripe_count, stripe_pattern,
491                                   pool_name);
492         if (fd < 0)
493                 return fd;
494
495         close(fd);
496         return 0;
497 }
498
499 /*
500  * Find the fsname, the full path, and/or an open fd.
501  * Either the fsname or path must not be NULL
502  */
503 #define WANT_PATH   0x1
504 #define WANT_FSNAME 0x2
505 #define WANT_FD     0x4
506 #define WANT_INDEX  0x8
507 #define WANT_ERROR  0x10
508 static int get_root_path(int want, char *fsname, int *outfd, char *path,
509                          int index)
510 {
511         struct mntent mnt;
512         char buf[PATH_MAX], mntdir[PATH_MAX];
513         char *ptr;
514         FILE *fp;
515         int idx = 0, len = 0, mntlen, fd;
516         int rc = -ENODEV;
517
518         /* get the mount point */
519         fp = setmntent(MOUNTED, "r");
520         if (fp == NULL) {
521                 rc = -EIO;
522                 llapi_error(LLAPI_MSG_ERROR, rc,
523                             "setmntent(%s) failed", MOUNTED);
524                 return rc;
525         }
526         while (1) {
527                 if (getmntent_r(fp, &mnt, buf, sizeof(buf)) == NULL)
528                         break;
529
530                 if (!llapi_is_lustre_mnt(&mnt))
531                         continue;
532
533                 if ((want & WANT_INDEX) && (idx++ != index))
534                         continue;
535
536                 mntlen = strlen(mnt.mnt_dir);
537                 ptr = strrchr(mnt.mnt_fsname, '/');
538                 if (!ptr && !len) {
539                         rc = -EINVAL;
540                         break;
541                 }
542                 ptr++;
543
544                 /* Check the fsname for a match, if given */
545                 if (!(want & WANT_FSNAME) && fsname != NULL &&
546                     (strlen(fsname) > 0) && (strcmp(ptr, fsname) != 0))
547                         continue;
548
549                 /* If the path isn't set return the first one we find */
550                 if (path == NULL || strlen(path) == 0) {
551                         strcpy(mntdir, mnt.mnt_dir);
552                         if ((want & WANT_FSNAME) && fsname != NULL)
553                                 strcpy(fsname, ptr);
554                         rc = 0;
555                         break;
556                 /* Otherwise find the longest matching path */
557                 } else if ((strlen(path) >= mntlen) && (mntlen >= len) &&
558                            (strncmp(mnt.mnt_dir, path, mntlen) == 0)) {
559                         strcpy(mntdir, mnt.mnt_dir);
560                         len = mntlen;
561                         if ((want & WANT_FSNAME) && fsname != NULL)
562                                 strcpy(fsname, ptr);
563                         rc = 0;
564                 }
565         }
566         endmntent(fp);
567
568         /* Found it */
569         if (rc == 0) {
570                 if ((want & WANT_PATH) && path != NULL)
571                         strcpy(path, mntdir);
572                 if (want & WANT_FD) {
573                         fd = open(mntdir, O_RDONLY | O_DIRECTORY | O_NONBLOCK);
574                         if (fd < 0) {
575                                 rc = -errno;
576                                 llapi_error(LLAPI_MSG_ERROR, rc,
577                                             "error opening '%s'", mntdir);
578
579                         } else {
580                                 *outfd = fd;
581                         }
582                 }
583         } else if (want & WANT_ERROR)
584                 llapi_err_noerrno(LLAPI_MSG_ERROR,
585                                   "can't find fs root for '%s': %d",
586                                   (want & WANT_PATH) ? fsname : path, rc);
587         return rc;
588 }
589
590 /*
591  * search lustre mounts
592  *
593  * Calling this function will return to the user the mount point, mntdir, and
594  * the file system name, fsname, if the user passed a buffer to this routine.
595  *
596  * The user inputs are pathname and index. If the pathname is supplied then
597  * the value of the index will be ignored. The pathname will return data if
598  * the pathname is located on a lustre mount. Index is used to pick which
599  * mount point you want in the case of multiple mounted lustre file systems.
600  * See function lfs_osts in lfs.c for a example of the index use.
601  */
602 int llapi_search_mounts(const char *pathname, int index, char *mntdir,
603                         char *fsname)
604 {
605         int want = WANT_PATH, idx = -1;
606
607         if (!pathname || pathname[0] == '\0') {
608                 want |= WANT_INDEX;
609                 idx = index;
610         } else
611                 strcpy(mntdir, pathname);
612
613         if (fsname)
614                 want |= WANT_FSNAME;
615         return get_root_path(want, fsname, NULL, mntdir, idx);
616 }
617
618 /* Given a path, find the corresponding Lustre fsname */
619 int llapi_search_fsname(const char *pathname, char *fsname)
620 {
621         char *path;
622         int rc;
623
624         path = realpath(pathname, NULL);
625         if (path == NULL) {
626                 char buf[PATH_MAX + 1], *ptr;
627
628                 buf[0] = 0;
629                 if (pathname[0] != '/') {
630                         /* Need an absolute path, but realpath() only works for
631                          * pathnames that actually exist.  We go through the
632                          * extra hurdle of dirname(getcwd() + pathname) in
633                          * case the relative pathname contains ".." in it. */
634                         if (getcwd(buf, sizeof(buf) - 1) == NULL)
635                                 return -errno;
636                         strcat(buf, "/");
637                 }
638                 strncat(buf, pathname, sizeof(buf) - strlen(buf));
639                 path = realpath(buf, NULL);
640                 if (path == NULL) {
641                         ptr = strrchr(buf, '/');
642                         if (ptr == NULL)
643                                 return -ENOENT;
644                         *ptr = '\0';
645                         path = realpath(buf, NULL);
646                         if (path == NULL) {
647                                 rc = -errno;
648                                 llapi_error(LLAPI_MSG_ERROR, rc,
649                                             "pathname '%s' cannot expand",
650                                             pathname);
651                                 return rc;
652                         }
653                 }
654         }
655         rc = get_root_path(WANT_FSNAME | WANT_ERROR, fsname, NULL, path, -1);
656         free(path);
657         return rc;
658 }
659
660 int llapi_getname(const char *path, char *buf, size_t size)
661 {
662         struct obd_uuid uuid_buf;
663         char *uuid = uuid_buf.uuid;
664         int rc, nr;
665
666         memset(&uuid_buf, 0, sizeof(uuid_buf));
667         rc = llapi_file_get_lov_uuid(path, &uuid_buf);
668         if (rc)
669                 return rc;
670
671         /* We want to turn lustre-clilov-ffff88002738bc00 into
672          * lustre-ffff88002738bc00. */
673
674         nr = snprintf(buf, size, "%.*s-%s",
675                       (int) (strlen(uuid) - 24), uuid,
676                       uuid + strlen(uuid) - 16);
677
678         if (nr >= size)
679                 rc = -ENAMETOOLONG;
680
681         return rc;
682 }
683
684
685 /* return the first file matching this pattern */
686 static int first_match(char *pattern, char *buffer)
687 {
688         glob_t glob_info;
689
690         if (glob(pattern, GLOB_BRACE, NULL, &glob_info))
691                 return -ENOENT;
692
693         if (glob_info.gl_pathc < 1) {
694                 globfree(&glob_info);
695                 return -ENOENT;
696         }
697
698         strcpy(buffer, glob_info.gl_pathv[0]);
699
700         globfree(&glob_info);
701         return 0;
702 }
703
704 /*
705  * find the pool directory path under /proc
706  * (can be also used to test if a fsname is known)
707  */
708 static int poolpath(char *fsname, char *pathname, char *pool_pathname)
709 {
710         int rc = 0;
711         char pattern[PATH_MAX + 1];
712         char buffer[PATH_MAX];
713
714         if (fsname == NULL) {
715                 rc = llapi_search_fsname(pathname, buffer);
716                 if (rc != 0)
717                         return rc;
718                 fsname = buffer;
719                 strcpy(pathname, fsname);
720         }
721
722         snprintf(pattern, PATH_MAX, "/proc/fs/lustre/lov/%s-*/pools", fsname);
723         rc = first_match(pattern, buffer);
724         if (rc)
725                 return rc;
726
727         /* in fsname test mode, pool_pathname is NULL */
728         if (pool_pathname != NULL)
729                 strcpy(pool_pathname, buffer);
730
731         return 0;
732 }
733
734 /**
735  * Get the list of pool members.
736  * \param poolname    string of format \<fsname\>.\<poolname\>
737  * \param members     caller-allocated array of char*
738  * \param list_size   size of the members array
739  * \param buffer      caller-allocated buffer for storing OST names
740  * \param buffer_size size of the buffer
741  *
742  * \return number of members retrieved for this pool
743  * \retval -error failure
744  */
745 int llapi_get_poolmembers(const char *poolname, char **members,
746                           int list_size, char *buffer, int buffer_size)
747 {
748         char fsname[PATH_MAX + 1];
749         char *pool, *tmp;
750         char pathname[PATH_MAX + 1];
751         char path[PATH_MAX + 1];
752         char buf[1024];
753         FILE *fd;
754         int rc = 0;
755         int nb_entries = 0;
756         int used = 0;
757
758         /* name is FSNAME.POOLNAME */
759         if (strlen(poolname) > PATH_MAX)
760                 return -EOVERFLOW;
761         strcpy(fsname, poolname);
762         pool = strchr(fsname, '.');
763         if (pool == NULL)
764                 return -EINVAL;
765
766         *pool = '\0';
767         pool++;
768
769         rc = poolpath(fsname, NULL, pathname);
770         if (rc != 0) {
771                 llapi_error(LLAPI_MSG_ERROR, rc,
772                             "Lustre filesystem '%s' not found",
773                             fsname);
774                 return rc;
775         }
776
777         llapi_printf(LLAPI_MSG_NORMAL, "Pool: %s.%s\n", fsname, pool);
778         sprintf(path, "%s/%s", pathname, pool);
779         fd = fopen(path, "r");
780         if (fd == NULL) {
781                 rc = -errno;
782                 llapi_error(LLAPI_MSG_ERROR, rc, "Cannot open %s", path);
783                 return rc;
784         }
785
786         rc = 0;
787         while (fgets(buf, sizeof(buf), fd) != NULL) {
788                 if (nb_entries >= list_size) {
789                         rc = -EOVERFLOW;
790                         break;
791                 }
792                 /* remove '\n' */
793                 tmp = strchr(buf, '\n');
794                 if (tmp != NULL)
795                         *tmp='\0';
796                 if (used + strlen(buf) + 1 > buffer_size) {
797                         rc = -EOVERFLOW;
798                         break;
799                 }
800
801                 strcpy(buffer + used, buf);
802                 members[nb_entries] = buffer + used;
803                 used += strlen(buf) + 1;
804                 nb_entries++;
805                 rc = nb_entries;
806         }
807
808         fclose(fd);
809         return rc;
810 }
811
812 /**
813  * Get the list of pools in a filesystem.
814  * \param name        filesystem name or path
815  * \param poollist    caller-allocated array of char*
816  * \param list_size   size of the poollist array
817  * \param buffer      caller-allocated buffer for storing pool names
818  * \param buffer_size size of the buffer
819  *
820  * \return number of pools retrieved for this filesystem
821  * \retval -error failure
822  */
823 int llapi_get_poollist(const char *name, char **poollist, int list_size,
824                        char *buffer, int buffer_size)
825 {
826         char fsname[PATH_MAX + 1], rname[PATH_MAX + 1], pathname[PATH_MAX + 1];
827         char *ptr;
828         DIR *dir;
829         struct dirent pool;
830         struct dirent *cookie = NULL;
831         int rc = 0;
832         unsigned int nb_entries = 0;
833         unsigned int used = 0;
834         unsigned int i;
835
836         /* initilize output array */
837         for (i = 0; i < list_size; i++)
838                 poollist[i] = NULL;
839
840         /* is name a pathname ? */
841         ptr = strchr(name, '/');
842         if (ptr != NULL) {
843                 /* only absolute pathname is supported */
844                 if (*name != '/')
845                         return -EINVAL;
846
847                 if (!realpath(name, rname)) {
848                         rc = -errno;
849                         llapi_error(LLAPI_MSG_ERROR, rc, "invalid path '%s'",
850                                     name);
851                         return rc;
852                 }
853
854                 rc = poolpath(NULL, rname, pathname);
855                 if (rc != 0) {
856                         llapi_error(LLAPI_MSG_ERROR, rc, "'%s' is not"
857                                     " a Lustre filesystem", name);
858                         return rc;
859                 }
860                 strcpy(fsname, rname);
861         } else {
862                 /* name is FSNAME */
863                 strcpy(fsname, name);
864                 rc = poolpath(fsname, NULL, pathname);
865         }
866         if (rc != 0) {
867                 llapi_error(LLAPI_MSG_ERROR, rc,
868                             "Lustre filesystem '%s' not found", name);
869                 return rc;
870         }
871
872         llapi_printf(LLAPI_MSG_NORMAL, "Pools from %s:\n", fsname);
873         dir = opendir(pathname);
874         if (dir == NULL) {
875                 rc = -errno;
876                 llapi_error(LLAPI_MSG_ERROR, rc,
877                             "Could not open pool list for '%s'",
878                             name);
879                 return rc;
880         }
881
882         while(1) {
883                 rc = readdir_r(dir, &pool, &cookie);
884
885                 if (rc != 0) {
886                         rc = -errno;
887                         llapi_error(LLAPI_MSG_ERROR, rc,
888                                     "Error reading pool list for '%s'", name);
889                         return rc;
890                 } else if ((rc == 0) && (cookie == NULL)) {
891                         /* end of directory */
892                         break;
893                 }
894
895                 /* ignore . and .. */
896                 if (!strcmp(pool.d_name, ".") || !strcmp(pool.d_name, ".."))
897                         continue;
898
899                 /* check output bounds */
900                 if (nb_entries >= list_size)
901                         return -EOVERFLOW;
902
903                 /* +2 for '.' and final '\0' */
904                 if (used + strlen(pool.d_name) + strlen(fsname) + 2
905                     > buffer_size)
906                         return -EOVERFLOW;
907
908                 sprintf(buffer + used, "%s.%s", fsname, pool.d_name);
909                 poollist[nb_entries] = buffer + used;
910                 used += strlen(pool.d_name) + strlen(fsname) + 2;
911                 nb_entries++;
912         }
913
914         closedir(dir);
915         return nb_entries;
916 }
917
918 /* wrapper for lfs.c and obd.c */
919 int llapi_poollist(const char *name)
920 {
921         /* list of pool names (assume that pool count is smaller
922            than OST count) */
923         char *list[FIND_MAX_OSTS];
924         char *buffer;
925         /* fsname-OST0000_UUID < 32 char, 1 per OST */
926         int bufsize = FIND_MAX_OSTS * 32;
927         int i, nb;
928
929         buffer = malloc(bufsize);
930         if (buffer == NULL)
931                 return -ENOMEM;
932
933         if ((name[0] == '/') || (strchr(name, '.') == NULL))
934                 /* name is a path or fsname */
935                 nb = llapi_get_poollist(name, list, FIND_MAX_OSTS, buffer,
936                                         bufsize);
937         else
938                 /* name is a pool name (<fsname>.<poolname>) */
939                 nb = llapi_get_poolmembers(name, list, FIND_MAX_OSTS, buffer,
940                                            bufsize);
941
942         for (i = 0; i < nb; i++)
943                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", list[i]);
944
945         free(buffer);
946         return (nb < 0 ? nb : 0);
947 }
948
949
950 typedef int (semantic_func_t)(char *path, DIR *parent, DIR *d,
951                               void *data, cfs_dirent_t *de);
952
953 #define MAX_LOV_UUID_COUNT      max(LOV_MAX_STRIPE_COUNT, 1000)
954 #define OBD_NOT_FOUND           (-1)
955
956 static int common_param_init(struct find_param *param)
957 {
958         param->lumlen = lov_mds_md_size(MAX_LOV_UUID_COUNT, LOV_MAGIC_V3);
959         param->lmd = malloc(sizeof(lstat_t) + param->lumlen);
960         if (param->lmd == NULL) {
961                 llapi_error(LLAPI_MSG_ERROR, -ENOMEM,
962                             "error: allocation of %d bytes for ioctl",
963                             sizeof(lstat_t) + param->lumlen);
964                 return -ENOMEM;
965         }
966
967         param->got_uuids = 0;
968         param->obdindexes = NULL;
969         param->obdindex = OBD_NOT_FOUND;
970         return 0;
971 }
972
973 static void find_param_fini(struct find_param *param)
974 {
975         if (param->obdindexes)
976                 free(param->obdindexes);
977
978         if (param->lmd)
979                 free(param->lmd);
980 }
981
982 static int cb_common_fini(char *path, DIR *parent, DIR *d, void *data,
983                           cfs_dirent_t *de)
984 {
985         struct find_param *param = (struct find_param *)data;
986         param->depth--;
987         return 0;
988 }
989
990 /* set errno upon failure */
991 static DIR *opendir_parent(char *path)
992 {
993         DIR *parent;
994         char *fname;
995         char c;
996
997         fname = strrchr(path, '/');
998         if (fname == NULL)
999                 return opendir(".");
1000
1001         c = fname[1];
1002         fname[1] = '\0';
1003         parent = opendir(path);
1004         fname[1] = c;
1005         return parent;
1006 }
1007
1008 int llapi_mds_getfileinfo(char *path, DIR *parent,
1009                           struct lov_user_mds_data *lmd)
1010 {
1011         lstat_t *st = &lmd->lmd_st;
1012         char *fname = strrchr(path, '/');
1013         int ret = 0;
1014
1015         if (parent == NULL)
1016                 return -EINVAL;
1017
1018         fname = (fname == NULL ? path : fname + 1);
1019         /* retrieve needed file info */
1020         strncpy((char *)lmd, fname,
1021                 lov_mds_md_size(MAX_LOV_UUID_COUNT, LOV_MAGIC));
1022         ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO, (void *)lmd);
1023
1024         if (ret) {
1025                 if (errno == ENOTTY) {
1026                         /* ioctl is not supported, it is not a lustre fs.
1027                          * Do the regular lstat(2) instead. */
1028                         ret = lstat_f(path, st);
1029                         if (ret) {
1030                                 ret = -errno;
1031                                 llapi_error(LLAPI_MSG_ERROR, ret,
1032                                             "error: %s: lstat failed for %s",
1033                                             __func__, path);
1034                                 return ret;
1035                         }
1036                 } else if (errno == ENOENT) {
1037                         ret = -errno;
1038                         llapi_error(LLAPI_MSG_WARN, ret,
1039                                     "warning: %s: %s does not exist",
1040                                     __func__, path);
1041                         return ret;
1042                 } else {
1043                         ret = -errno;
1044                         llapi_error(LLAPI_MSG_ERROR, ret,
1045                                    "error: %s: IOC_MDC_GETFILEINFO failed for %s",
1046                                    __func__, path);
1047                         return ret;
1048                 }
1049         }
1050
1051         return 0;
1052 }
1053
1054 static int llapi_semantic_traverse(char *path, int size, DIR *parent,
1055                                    semantic_func_t sem_init,
1056                                    semantic_func_t sem_fini, void *data,
1057                                    cfs_dirent_t *de)
1058 {
1059         cfs_dirent_t *dent;
1060         int len, ret;
1061         DIR *d, *p = NULL;
1062
1063         ret = 0;
1064         len = strlen(path);
1065
1066         d = opendir(path);
1067         if (!d && errno != ENOTDIR) {
1068                 ret = -errno;
1069                 llapi_error(LLAPI_MSG_ERROR, ret, "%s: Failed to open '%s'",
1070                             __func__, path);
1071                 return ret;
1072         } else if (!d && !parent) {
1073                 /* ENOTDIR. Open the parent dir. */
1074                 p = opendir_parent(path);
1075                 if (!p)
1076                         GOTO(out, ret = -errno);
1077         }
1078
1079         if (sem_init && (ret = sem_init(path, parent ?: p, d, data, de)))
1080                 goto err;
1081
1082         if (!d)
1083                 GOTO(out, ret = 0);
1084
1085         while ((dent = readdir64(d)) != NULL) {
1086                 ((struct find_param *)data)->have_fileinfo = 0;
1087
1088                 if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
1089                         continue;
1090
1091                 /* Don't traverse .lustre directory */
1092                 if (!(strcmp(dent->d_name, dot_lustre_name)))
1093                         continue;
1094
1095                 path[len] = 0;
1096                 if ((len + dent->d_reclen + 2) > size) {
1097                         llapi_err_noerrno(LLAPI_MSG_ERROR,
1098                                           "error: %s: string buffer is too small",
1099                                           __func__);
1100                         break;
1101                 }
1102                 strcat(path, "/");
1103                 strcat(path, dent->d_name);
1104
1105                 if (dent->d_type == DT_UNKNOWN) {
1106                         lstat_t *st = &((struct find_param *)data)->lmd->lmd_st;
1107
1108                         ret = llapi_mds_getfileinfo(path, d,
1109                                              ((struct find_param *)data)->lmd);
1110                         if (ret == 0) {
1111                                 ((struct find_param *)data)->have_fileinfo = 1;
1112                                 dent->d_type =
1113                                         llapi_filetype_dir_table[st->st_mode &
1114                                                                  S_IFMT];
1115                         }
1116                         if (ret == -ENOENT)
1117                                 continue;
1118                 }
1119
1120                 switch (dent->d_type) {
1121                 case DT_UNKNOWN:
1122                         llapi_err_noerrno(LLAPI_MSG_ERROR,
1123                                           "error: %s: '%s' is UNKNOWN type %d",
1124                                           __func__, dent->d_name, dent->d_type);
1125                         break;
1126                 case DT_DIR:
1127                         ret = llapi_semantic_traverse(path, size, d, sem_init,
1128                                                       sem_fini, data, dent);
1129                         if (ret < 0)
1130                                 goto out;
1131                         break;
1132                 default:
1133                         ret = 0;
1134                         if (sem_init) {
1135                                 ret = sem_init(path, d, NULL, data, dent);
1136                                 if (ret < 0)
1137                                         goto out;
1138                         }
1139                         if (sem_fini && ret == 0)
1140                                 sem_fini(path, d, NULL, data, dent);
1141                 }
1142         }
1143
1144 out:
1145         path[len] = 0;
1146
1147         if (sem_fini)
1148                 sem_fini(path, parent, d, data, de);
1149 err:
1150         if (d)
1151                 closedir(d);
1152         if (p)
1153                 closedir(p);
1154         return ret;
1155 }
1156
1157 static int param_callback(char *path, semantic_func_t sem_init,
1158                           semantic_func_t sem_fini, struct find_param *param)
1159 {
1160         int ret, len = strlen(path);
1161         char *buf;
1162
1163         if (len > PATH_MAX) {
1164                 ret = -EINVAL;
1165                 llapi_error(LLAPI_MSG_ERROR, ret,
1166                             "Path name '%s' is too long", path);
1167                 return ret;
1168         }
1169
1170         buf = (char *)malloc(PATH_MAX + 1);
1171         if (!buf)
1172                 return -ENOMEM;
1173
1174         ret = common_param_init(param);
1175         if (ret)
1176                 goto out;
1177         param->depth = 0;
1178
1179         strncpy(buf, path, PATH_MAX + 1);
1180         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, sem_init,
1181                                       sem_fini, param, NULL);
1182 out:
1183         find_param_fini(param);
1184         free(buf);
1185         return ret < 0 ? ret : 0;
1186 }
1187
1188 int llapi_file_fget_lov_uuid(int fd, struct obd_uuid *lov_name)
1189 {
1190         int rc = ioctl(fd, OBD_IOC_GETNAME, lov_name);
1191         if (rc) {
1192                 rc = -errno;
1193                 llapi_error(LLAPI_MSG_ERROR, rc, "error: can't get lov name.");
1194         }
1195         return rc;
1196 }
1197
1198 int llapi_file_get_lov_uuid(const char *path, struct obd_uuid *lov_uuid)
1199 {
1200         int fd, rc;
1201
1202         fd = open(path, O_RDONLY);
1203         if (fd < 0) {
1204                 rc = -errno;
1205                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s", path);
1206                 return rc;
1207         }
1208
1209         rc = llapi_file_fget_lov_uuid(fd, lov_uuid);
1210
1211         close(fd);
1212         return rc;
1213 }
1214
1215 /*
1216  * If uuidp is NULL, return the number of available obd uuids.
1217  * If uuidp is non-NULL, then it will return the uuids of the obds. If
1218  * there are more OSTs then allocated to uuidp, then an error is returned with
1219  * the ost_count set to number of available obd uuids.
1220  */
1221 int llapi_lov_get_uuids(int fd, struct obd_uuid *uuidp, int *ost_count)
1222 {
1223         struct obd_uuid lov_name;
1224         char buf[1024];
1225         FILE *fp;
1226         int rc = 0, index = 0;
1227
1228         /* Get the lov name */
1229         rc = llapi_file_fget_lov_uuid(fd, &lov_name);
1230         if (rc)
1231                 return rc;
1232
1233         /* Now get the ost uuids from /proc */
1234         snprintf(buf, sizeof(buf), "/proc/fs/lustre/lov/%s/target_obd",
1235                  lov_name.uuid);
1236         fp = fopen(buf, "r");
1237         if (fp == NULL) {
1238                 rc = -errno;
1239                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening '%s'", buf);
1240                 return rc;
1241         }
1242
1243         while (fgets(buf, sizeof(buf), fp) != NULL) {
1244                 if (uuidp && (index < *ost_count)) {
1245                         if (sscanf(buf, "%d: %s", &index, uuidp[index].uuid) <2)
1246                                 break;
1247                 }
1248                 index++;
1249         }
1250
1251         fclose(fp);
1252
1253         if (uuidp && (index >= *ost_count))
1254                 return -EOVERFLOW;
1255
1256         *ost_count = index;
1257         return 0;
1258 }
1259
1260 int llapi_get_obd_count(char *mnt, int *count, int is_mdt)
1261 {
1262         DIR *root;
1263         int rc;
1264
1265         root = opendir(mnt);
1266         if (!root) {
1267                 rc = -errno;
1268                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
1269                 return rc;
1270         }
1271
1272         *count = is_mdt;
1273         rc = ioctl(dirfd(root), LL_IOC_GETOBDCOUNT, count);
1274         if (rc < 0)
1275                 rc = -errno;
1276
1277         closedir(root);
1278         return rc;
1279 }
1280
1281 /* Check if user specified value matches a real uuid.  Ignore _UUID,
1282  * -osc-4ba41334, other trailing gunk in comparison.
1283  * @param real_uuid ends in "_UUID"
1284  * @param search_uuid may or may not end in "_UUID"
1285  */
1286 int llapi_uuid_match(char *real_uuid, char *search_uuid)
1287 {
1288         int cmplen = strlen(real_uuid);
1289         int searchlen = strlen(search_uuid);
1290
1291         if (cmplen > 5 && strcmp(real_uuid + cmplen - 5, "_UUID") == 0)
1292                 cmplen -= 5;
1293         if (searchlen > 5 && strcmp(search_uuid + searchlen - 5, "_UUID") == 0)
1294                 searchlen -= 5;
1295
1296         /* The UUIDs may legitimately be different lengths, if
1297          * the system was upgraded from an older version. */
1298         if (cmplen != searchlen)
1299                 return 0;
1300
1301         return (strncmp(search_uuid, real_uuid, cmplen) == 0);
1302 }
1303
1304 /* Here, param->obduuid points to a single obduuid, the index of which is
1305  * returned in param->obdindex */
1306 static int setup_obd_uuid(DIR *dir, char *dname, struct find_param *param)
1307 {
1308         struct obd_uuid lov_uuid;
1309         char uuid[sizeof(struct obd_uuid)];
1310         char buf[1024];
1311         FILE *fp;
1312         int rc = 0, index;
1313
1314         if (param->got_uuids)
1315                 return rc;
1316
1317         /* Get the lov name */
1318         rc = llapi_file_fget_lov_uuid(dirfd(dir), &lov_uuid);
1319         if (rc) {
1320                 if (rc != -ENOTTY) {
1321                         llapi_error(LLAPI_MSG_ERROR, rc,
1322                                     "error: can't get lov name: %s", dname);
1323                 } else {
1324                         rc = 0;
1325                 }
1326                 return rc;
1327         }
1328
1329         param->got_uuids = 1;
1330
1331         /* Now get the ost uuids from /proc */
1332         snprintf(buf, sizeof(buf), "/proc/fs/lustre/lov/%s/target_obd",
1333                  lov_uuid.uuid);
1334         fp = fopen(buf, "r");
1335         if (fp == NULL) {
1336                 rc = -errno;
1337                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening '%s'", buf);
1338                 return rc;
1339         }
1340
1341         if (!param->obduuid && !param->quiet && !param->obds_printed)
1342                 llapi_printf(LLAPI_MSG_NORMAL, "OBDS:\n");
1343
1344         while (fgets(buf, sizeof(buf), fp) != NULL) {
1345                 if (sscanf(buf, "%d: %s", &index, uuid) < 2)
1346                         break;
1347
1348                 if (param->obduuid) {
1349                         if (llapi_uuid_match(uuid, param->obduuid->uuid)) {
1350                                 param->obdindex = index;
1351                                 break;
1352                         }
1353                 } else if (!param->quiet && !param->obds_printed) {
1354                         /* Print everything */
1355                         llapi_printf(LLAPI_MSG_NORMAL, "%s", buf);
1356                 }
1357         }
1358         param->obds_printed = 1;
1359
1360         fclose(fp);
1361
1362         if (param->obduuid && (param->obdindex == OBD_NOT_FOUND)) {
1363                 llapi_err_noerrno(LLAPI_MSG_ERROR,
1364                                   "error: %s: unknown obduuid: %s",
1365                                   __func__, param->obduuid->uuid);
1366                 rc = -EINVAL;
1367         }
1368
1369         return (rc);
1370 }
1371
1372 /* In this case, param->obduuid will be an array of obduuids and
1373  * obd index for all these obduuids will be returned in
1374  * param->obdindexes */
1375 static int setup_obd_indexes(DIR *dir, struct find_param *param)
1376 {
1377         struct obd_uuid *uuids = NULL;
1378         int obdcount = INIT_ALLOC_NUM_OSTS;
1379         int ret, obd_valid = 0, obdnum, i;
1380
1381         uuids = (struct obd_uuid *)malloc(INIT_ALLOC_NUM_OSTS *
1382                                           sizeof(struct obd_uuid));
1383         if (uuids == NULL)
1384                 return -ENOMEM;
1385
1386 retry_get_uuids:
1387         ret = llapi_lov_get_uuids(dirfd(dir), uuids,
1388                                   &obdcount);
1389         if (ret) {
1390                 struct obd_uuid *uuids_temp;
1391
1392                 if (ret == -EOVERFLOW) {
1393                         uuids_temp = realloc(uuids, obdcount *
1394                                              sizeof(struct obd_uuid));
1395                         if (uuids_temp != NULL)
1396                                 goto retry_get_uuids;
1397                         else
1398                                 ret = -ENOMEM;
1399                 }
1400
1401                 llapi_error(LLAPI_MSG_ERROR, ret, "get ost uuid failed");
1402                 return ret;
1403         }
1404
1405         param->obdindexes = malloc(param->num_obds * sizeof(param->obdindex));
1406         if (param->obdindexes == NULL)
1407                 return -ENOMEM;
1408
1409         for (obdnum = 0; obdnum < param->num_obds; obdnum++) {
1410                 for (i = 0; i < obdcount; i++) {
1411                         if (llapi_uuid_match(uuids[i].uuid,
1412                                              param->obduuid[obdnum].uuid)) {
1413                                 param->obdindexes[obdnum] = i;
1414                                 obd_valid++;
1415                                 break;
1416                         }
1417                 }
1418                 if (i >= obdcount) {
1419                         param->obdindexes[obdnum] = OBD_NOT_FOUND;
1420                         llapi_err_noerrno(LLAPI_MSG_ERROR,
1421                                           "error: %s: unknown obduuid: %s",
1422                                           __func__,
1423                                           param->obduuid[obdnum].uuid);
1424                         ret = -EINVAL;
1425                 }
1426         }
1427
1428         if (obd_valid == 0)
1429                 param->obdindex = OBD_NOT_FOUND;
1430         else
1431                 param->obdindex = obd_valid;
1432
1433         param->got_uuids = 1;
1434
1435         return ret;
1436 }
1437
1438 int llapi_ostlist(char *path, struct find_param *param)
1439 {
1440         DIR *dir;
1441         int ret;
1442
1443         dir = opendir(path);
1444         if (dir == NULL)
1445                 return -errno;
1446
1447         ret = setup_obd_uuid(dir, path, param);
1448         closedir(dir);
1449
1450         return ret;
1451 }
1452
1453 /*
1454  * Given a filesystem name, or a pathname of a file on a lustre filesystem,
1455  * tries to determine the path to the filesystem's clilov directory under /proc
1456  *
1457  * fsname is limited to MTI_NAME_MAXLEN in lustre_idl.h
1458  * The NUL terminator is compensated by the additional "%s" bytes. */
1459 #define LOV_LEN (sizeof("/proc/fs/lustre/lov/%s-clilov-*") + MTI_NAME_MAXLEN)
1460 static int clilovpath(const char *fsname, const char *const pathname,
1461                       char *clilovpath)
1462 {
1463         int rc;
1464         char pattern[LOV_LEN];
1465         char buffer[PATH_MAX + 1];
1466
1467         if (fsname == NULL) {
1468                 rc = llapi_search_fsname(pathname, buffer);
1469                 if (rc != 0)
1470                         return rc;
1471                 fsname = buffer;
1472         }
1473
1474         snprintf(pattern, sizeof(pattern), "/proc/fs/lustre/lov/%s-clilov-*",
1475                  fsname);
1476
1477         rc = first_match(pattern, buffer);
1478         if (rc != 0)
1479                 return rc;
1480
1481         strncpy(clilovpath, buffer, sizeof(buffer));
1482
1483         return 0;
1484 }
1485
1486 /*
1487  * Given the path to a stripe attribute proc file, tries to open and
1488  * read the attribute and return the value using the attr parameter
1489  */
1490 static int sattr_read_attr(const char *const fpath,
1491                            unsigned int *attr)
1492 {
1493
1494         FILE *f;
1495         char line[PATH_MAX + 1];
1496         int rc = 0;
1497
1498         f = fopen(fpath, "r");
1499         if (f == NULL) {
1500                 rc = -errno;
1501                 llapi_error(LLAPI_MSG_ERROR, rc, "Cannot open '%s'", fpath);
1502                 return rc;
1503         }
1504
1505         if (fgets(line, sizeof(line), f) != NULL) {
1506                 *attr = atoi(line);
1507         } else {
1508                 llapi_error(LLAPI_MSG_ERROR, errno, "Cannot read from '%s'", fpath);
1509                 rc = 1;
1510         }
1511
1512         fclose(f);
1513         return rc;
1514 }
1515
1516 /*
1517  * Tries to determine the default stripe attributes for a given filesystem. The
1518  * filesystem to check should be specified by fsname, or will be determined
1519  * using pathname.
1520  */
1521 static int sattr_get_defaults(const char *const fsname,
1522                               const char *const pathname,
1523                               unsigned int *scount,
1524                               unsigned int *ssize,
1525                               unsigned int *soffset)
1526 {
1527         int rc;
1528         char dpath[PATH_MAX + 1];
1529         char fpath[PATH_MAX + 1];
1530
1531         rc = clilovpath(fsname, pathname, dpath);
1532         if (rc != 0)
1533                 return rc;
1534
1535         if (scount) {
1536                 snprintf(fpath, PATH_MAX, "%s/stripecount", dpath);
1537                 rc = sattr_read_attr(fpath, scount);
1538                 if (rc != 0)
1539                         return rc;
1540         }
1541
1542         if (ssize) {
1543                 snprintf(fpath, PATH_MAX, "%s/stripesize", dpath);
1544                 rc = sattr_read_attr(fpath, ssize);
1545                 if (rc != 0)
1546                         return rc;
1547         }
1548
1549         if (soffset) {
1550                 snprintf(fpath, PATH_MAX, "%s/stripeoffset", dpath);
1551                 rc = sattr_read_attr(fpath, soffset);
1552                 if (rc != 0)
1553                         return rc;
1554         }
1555
1556         return 0;
1557 }
1558
1559 /*
1560  * Tries to gather the default stripe attributes for a given filesystem. If
1561  * the attributes can be determined, they are cached for easy retreival the
1562  * next time they are needed. Only a single filesystem's attributes are
1563  * cached at a time.
1564  */
1565 static int sattr_cache_get_defaults(const char *const fsname,
1566                                     const char *const pathname,
1567                                     unsigned int *scount,
1568                                     unsigned int *ssize,
1569                                     unsigned int *soffset)
1570 {
1571         static struct {
1572                 char fsname[PATH_MAX + 1];
1573                 unsigned int stripecount;
1574                 unsigned int stripesize;
1575                 unsigned int stripeoffset;
1576         } cache = {
1577                 .fsname = {'\0'}
1578         };
1579
1580         int rc;
1581         char fsname_buf[PATH_MAX + 1];
1582         unsigned int tmp[3];
1583
1584         if (fsname == NULL) {
1585                 rc = llapi_search_fsname(pathname, fsname_buf);
1586                 if (rc)
1587                         return rc;
1588         } else {
1589                 strncpy(fsname_buf, fsname, PATH_MAX);
1590         }
1591
1592         if (strncmp(fsname_buf, cache.fsname, PATH_MAX) != 0) {
1593                 /*
1594                  * Ensure all 3 sattrs (count, size, and offset) are
1595                  * successfully retrieved and stored in tmp before writing to
1596                  * cache.
1597                  */
1598                 rc = sattr_get_defaults(fsname_buf, NULL, &tmp[0], &tmp[1],
1599                                         &tmp[2]);
1600                 if (rc != 0)
1601                         return rc;
1602
1603                 cache.stripecount = tmp[0];
1604                 cache.stripesize = tmp[1];
1605                 cache.stripeoffset = tmp[2];
1606                 strncpy(cache.fsname, fsname_buf, PATH_MAX);
1607         }
1608
1609         if (scount)
1610                 *scount = cache.stripecount;
1611         if (ssize)
1612                 *ssize = cache.stripesize;
1613         if (soffset)
1614                 *soffset = cache.stripeoffset;
1615
1616         return 0;
1617 }
1618
1619 static void lov_dump_user_lmm_header(struct lov_user_md *lum, char *path,
1620                                      struct lov_user_ost_data_v1 *objects,
1621                                      int is_dir, int verbose, int depth,
1622                                      int raw, char *pool_name)
1623 {
1624         char *prefix = is_dir ? "" : "lmm_";
1625         char nl = is_dir ? ' ' : '\n';
1626         int rc;
1627
1628         if (is_dir && lum->lmm_object_seq == FID_SEQ_LOV_DEFAULT) {
1629                 lum->lmm_object_seq = FID_SEQ_OST_MDT0;
1630                 if (verbose & VERBOSE_DETAIL)
1631                         llapi_printf(LLAPI_MSG_NORMAL, "(Default) ");
1632         }
1633
1634         if (depth && path && ((verbose != VERBOSE_OBJID) || !is_dir))
1635                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
1636
1637         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
1638                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_magic:          0x%08X\n",
1639                              lum->lmm_magic);
1640                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_seq:            "LPX64"\n",
1641                              lum->lmm_object_seq);
1642                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_id:      "LPX64"\n",
1643                              lum->lmm_object_id);
1644         }
1645
1646         if (verbose & VERBOSE_COUNT) {
1647                 if (verbose & ~VERBOSE_COUNT)
1648                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_count:   ",
1649                                      prefix);
1650                 if (is_dir) {
1651                         if (!raw && lum->lmm_stripe_count == 0) {
1652                                 unsigned int scount;
1653                                 rc = sattr_cache_get_defaults(NULL, path,
1654                                                               &scount, NULL,
1655                                                               NULL);
1656                                 if (rc == 0)
1657                                         llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
1658                                                      scount, nl);
1659                                 else
1660                                         llapi_error(LLAPI_MSG_ERROR, rc,
1661                                                     "Cannot determine default"
1662                                                     " stripe count.");
1663                         } else {
1664                                 llapi_printf(LLAPI_MSG_NORMAL, "%d%c",
1665                                              lum->lmm_stripe_count ==
1666                                              (typeof(lum->lmm_stripe_count))(-1)
1667                                              ? -1 : lum->lmm_stripe_count, nl);
1668                         }
1669                 } else {
1670                         llapi_printf(LLAPI_MSG_NORMAL, "%hd%c",
1671                                      (__s16)lum->lmm_stripe_count, nl);
1672                 }
1673         }
1674
1675         if (verbose & VERBOSE_SIZE) {
1676                 if (verbose & ~VERBOSE_SIZE)
1677                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_size:    ",
1678                                      prefix);
1679                 if (is_dir && !raw && lum->lmm_stripe_size == 0) {
1680                         unsigned int ssize;
1681                         rc = sattr_cache_get_defaults(NULL, path, NULL, &ssize,
1682                                                       NULL);
1683                         if (rc == 0)
1684                                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c", ssize,
1685                                              nl);
1686                         else
1687                                 llapi_error(LLAPI_MSG_ERROR, rc,
1688                                             "Cannot determine default"
1689                                             " stripe size.");
1690                 } else {
1691                         llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
1692                                      lum->lmm_stripe_size, nl);
1693                 }
1694         }
1695
1696         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
1697                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_stripe_pattern: %x%c",
1698                              lum->lmm_pattern, nl);
1699         }
1700
1701         if ((verbose & VERBOSE_GENERATION) && !is_dir) {
1702                 if (verbose & ~VERBOSE_GENERATION)
1703                         llapi_printf(LLAPI_MSG_NORMAL, "%slayout_gen:     ",
1704                                      prefix);
1705                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
1706                              (int)lum->u.lum_layout_gen, nl);
1707         }
1708
1709         if (verbose & VERBOSE_OFFSET) {
1710                 if (verbose & ~VERBOSE_OFFSET)
1711                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_offset:  ",
1712                                      prefix);
1713                 if (is_dir)
1714                         llapi_printf(LLAPI_MSG_NORMAL, "%d%c",
1715                                      lum->lmm_stripe_offset ==
1716                                      (typeof(lum->lmm_stripe_offset))(-1) ? -1 :
1717                                      lum->lmm_stripe_offset, nl);
1718                 else
1719                         llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
1720                                      objects[0].l_ost_idx, nl);
1721         }
1722
1723         if ((verbose & VERBOSE_POOL) && (pool_name != NULL)) {
1724                 if (verbose & ~VERBOSE_POOL)
1725                         llapi_printf(LLAPI_MSG_NORMAL, "%spool:           ",
1726                                      prefix);
1727                 llapi_printf(LLAPI_MSG_NORMAL, "%s%c", pool_name, nl);
1728         }
1729
1730         if (is_dir && (verbose != VERBOSE_OBJID))
1731                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1732 }
1733
1734 void lov_dump_user_lmm_v1v3(struct lov_user_md *lum, char *pool_name,
1735                             struct lov_user_ost_data_v1 *objects,
1736                             char *path, int is_dir,
1737                             int obdindex, int depth, int header, int raw)
1738 {
1739         int i, obdstripe = (obdindex != OBD_NOT_FOUND) ? 0 : 1;
1740
1741         if (!obdstripe) {
1742                 for (i = 0; !is_dir && i < lum->lmm_stripe_count; i++) {
1743                         if (obdindex == objects[i].l_ost_idx) {
1744                                 obdstripe = 1;
1745                                 break;
1746                         }
1747                 }
1748         }
1749
1750         if (obdstripe == 1)
1751                 lov_dump_user_lmm_header(lum, path, objects, is_dir, header,
1752                                          depth, raw, pool_name);
1753
1754         if (!is_dir && (header & VERBOSE_OBJID)) {
1755                 if (obdstripe == 1)
1756                         llapi_printf(LLAPI_MSG_NORMAL,
1757                                      "\tobdidx\t\t objid\t\tobjid\t\t group\n");
1758
1759                 for (i = 0; i < lum->lmm_stripe_count; i++) {
1760                         int idx = objects[i].l_ost_idx;
1761                         long long oid = objects[i].l_object_id;
1762                         long long gr = objects[i].l_object_seq;
1763                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
1764                                 llapi_printf(LLAPI_MSG_NORMAL,
1765                                            "\t%6u\t%14llu\t%#13llx\t%14llu%s\n",
1766                                            idx, oid, oid, gr,
1767                                            obdindex == idx ? " *" : "");
1768                 }
1769                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1770         }
1771 }
1772
1773 void llapi_lov_dump_user_lmm(struct find_param *param,
1774                              char *path, int is_dir)
1775 {
1776         switch(*(__u32 *)&param->lmd->lmd_lmm) { /* lum->lmm_magic */
1777         case LOV_USER_MAGIC_V1:
1778                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, NULL,
1779                                        param->lmd->lmd_lmm.lmm_objects,
1780                                        path, is_dir,
1781                                        param->obdindex, param->maxdepth,
1782                                        param->verbose, param->raw);
1783                 break;
1784         case LOV_USER_MAGIC_V3: {
1785                 char pool_name[LOV_MAXPOOLNAME + 1];
1786                 struct lov_user_ost_data_v1 *objects;
1787                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
1788
1789                 strncpy(pool_name, lmmv3->lmm_pool_name, LOV_MAXPOOLNAME);
1790                 pool_name[LOV_MAXPOOLNAME] = '\0';
1791                 objects = lmmv3->lmm_objects;
1792                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, pool_name,
1793                                        objects, path, is_dir,
1794                                        param->obdindex, param->maxdepth,
1795                                        param->verbose, param->raw);
1796                 break;
1797         }
1798         default:
1799                 llapi_printf(LLAPI_MSG_NORMAL, "unknown lmm_magic:  %#x "
1800                              "(expecting one of %#x %#x %#x)\n",
1801                              *(__u32 *)&param->lmd->lmd_lmm,
1802                              LOV_USER_MAGIC_V1, LOV_USER_MAGIC_V3);
1803                 return;
1804         }
1805 }
1806
1807 int llapi_file_get_stripe(const char *path, struct lov_user_md *lum)
1808 {
1809         const char *fname;
1810         char *dname;
1811         int fd, rc = 0;
1812
1813         fname = strrchr(path, '/');
1814
1815         /* It should be a file (or other non-directory) */
1816         if (fname == NULL) {
1817                 dname = (char *)malloc(2);
1818                 if (dname == NULL)
1819                         return -ENOMEM;
1820                 strcpy(dname, ".");
1821                 fname = (char *)path;
1822         } else {
1823                 dname = (char *)malloc(fname - path + 1);
1824                 if (dname == NULL)
1825                         return -ENOMEM;
1826                 strncpy(dname, path, fname - path);
1827                 dname[fname - path] = '\0';
1828                 fname++;
1829         }
1830
1831         fd = open(dname, O_RDONLY);
1832         if (fd == -1) {
1833                 rc = -errno;
1834                 free(dname);
1835                 return rc;
1836         }
1837
1838         strcpy((char *)lum, fname);
1839         if (ioctl(fd, IOC_MDC_GETFILESTRIPE, (void *)lum) == -1)
1840                 rc = -errno;
1841
1842         if (close(fd) == -1 && rc == 0)
1843                 rc = -errno;
1844
1845         free(dname);
1846         return rc;
1847 }
1848
1849 int llapi_file_lookup(int dirfd, const char *name)
1850 {
1851         struct obd_ioctl_data data = { 0 };
1852         char rawbuf[8192];
1853         char *buf = rawbuf;
1854         int rc;
1855
1856         if (dirfd < 0 || name == NULL)
1857                 return -EINVAL;
1858
1859         data.ioc_version = OBD_IOCTL_VERSION;
1860         data.ioc_len = sizeof(data);
1861         data.ioc_inlbuf1 = (char *)name;
1862         data.ioc_inllen1 = strlen(name) + 1;
1863
1864         rc = obd_ioctl_pack(&data, &buf, sizeof(rawbuf));
1865         if (rc) {
1866                 llapi_error(LLAPI_MSG_ERROR, rc,
1867                             "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
1868                             name, rc);
1869                 return rc;
1870         }
1871
1872         rc = ioctl(dirfd, IOC_MDC_LOOKUP, buf);
1873         if (rc < 0)
1874                 rc = -errno;
1875         return rc;
1876 }
1877
1878 /* Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
1879  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
1880  *
1881  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
1882  * The table below gives the answers for the specified parameters (value and
1883  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
1884  * --------------------------------------
1885  * 1 | file > limit; sign > 0 | -1 / -1 |
1886  * 2 | file = limit; sign > 0 | -1 / -1 |
1887  * 3 | file < limit; sign > 0 |  ? /  1 |
1888  * 4 | file > limit; sign = 0 | -1 / -1 |
1889  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
1890  * 6 | file < limit; sign = 0 |  ? / -1 |
1891  * 7 | file > limit; sign < 0 |  1 /  1 |
1892  * 8 | file = limit; sign < 0 |  ? / -1 |
1893  * 9 | file < limit; sign < 0 |  ? / -1 |
1894  * --------------------------------------
1895  * Note: 5th actually means that the value is within the interval
1896  * (limit - margin, limit]. */
1897 static int find_value_cmp(unsigned long long file, unsigned long long limit,
1898                           int sign, int negopt, unsigned long long margin,
1899                           int mds)
1900 {
1901         int ret = -1;
1902
1903         if (sign > 0) {
1904                 /* Drop the fraction of margin (of days). */
1905                 if (file + margin <= limit)
1906                         ret = mds ? 0 : 1;
1907         } else if (sign == 0) {
1908                 if (file <= limit && file + margin > limit)
1909                         ret = mds ? 0 : 1;
1910                 else if (file + margin <= limit)
1911                         ret = mds ? 0 : -1;
1912         } else if (sign < 0) {
1913                 if (file > limit)
1914                         ret = 1;
1915                 else if (mds)
1916                         ret = 0;
1917         }
1918
1919         return negopt ? ~ret + 1 : ret;
1920 }
1921
1922 /* Check if the file time matches all the given criteria (e.g. --atime +/-N).
1923  * Return -1 or 1 if file timestamp does not or does match the given criteria
1924  * correspondingly. Return 0 if the MDS time is being checked and there are
1925  * attributes on OSTs and it is not yet clear if the timespamp matches.
1926  *
1927  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
1928  * updated timestamps. */
1929 static int find_time_check(lstat_t *st, struct find_param *param, int mds)
1930 {
1931         int ret;
1932         int rc = 1;
1933
1934         /* Check if file is accepted. */
1935         if (param->atime) {
1936                 ret = find_value_cmp(st->st_atime, param->atime,
1937                                      param->asign, param->exclude_atime,
1938                                      24 * 60 * 60, mds);
1939                 if (ret < 0)
1940                         return ret;
1941                 rc = ret;
1942         }
1943
1944         if (param->mtime) {
1945                 ret = find_value_cmp(st->st_mtime, param->mtime,
1946                                      param->msign, param->exclude_mtime,
1947                                      24 * 60 * 60, mds);
1948                 if (ret < 0)
1949                         return ret;
1950
1951                 /* If the previous check matches, but this one is not yet clear,
1952                  * we should return 0 to do an RPC on OSTs. */
1953                 if (rc == 1)
1954                         rc = ret;
1955         }
1956
1957         if (param->ctime) {
1958                 ret = find_value_cmp(st->st_ctime, param->ctime,
1959                                      param->csign, param->exclude_ctime,
1960                                      24 * 60 * 60, mds);
1961                 if (ret < 0)
1962                         return ret;
1963
1964                 /* If the previous check matches, but this one is not yet clear,
1965                  * we should return 0 to do an RPC on OSTs. */
1966                 if (rc == 1)
1967                         rc = ret;
1968         }
1969
1970         return rc;
1971 }
1972
1973 static int cb_find_init(char *path, DIR *parent, DIR *dir,
1974                         void *data, cfs_dirent_t *de)
1975 {
1976         struct find_param *param = (struct find_param *)data;
1977         int decision = 1; /* 1 is accepted; -1 is rejected. */
1978         lstat_t *st = &param->lmd->lmd_st;
1979         int lustre_fs = 1;
1980         int checked_type = 0;
1981         int ret = 0;
1982
1983         LASSERT(parent != NULL || dir != NULL);
1984
1985         if (param->have_fileinfo == 0)
1986                 param->lmd->lmd_lmm.lmm_stripe_count = 0;
1987
1988         /* If a regular expression is presented, make the initial decision */
1989         if (param->pattern != NULL) {
1990                 char *fname = strrchr(path, '/');
1991                 fname = (fname == NULL ? path : fname + 1);
1992                 ret = fnmatch(param->pattern, fname, 0);
1993                 if ((ret == FNM_NOMATCH && !param->exclude_pattern) ||
1994                     (ret == 0 && param->exclude_pattern))
1995                         goto decided;
1996         }
1997
1998         /* See if we can check the file type from the dirent. */
1999         if (param->type && de != NULL && de->d_type != DT_UNKNOWN &&
2000             de->d_type < DT_MAX) {
2001                 checked_type = 1;
2002                 if (llapi_dir_filetype_table[de->d_type] == param->type) {
2003                         if (param->exclude_type)
2004                                 goto decided;
2005                 } else {
2006                         if (!param->exclude_type)
2007                                 goto decided;
2008                 }
2009         }
2010
2011
2012         ret = 0;
2013
2014         /* Request MDS for the stat info if some of these parameters need
2015          * to be compared. */
2016         if (param->obduuid    || param->check_uid || param->check_gid ||
2017             param->check_pool || param->atime     || param->ctime     ||
2018             param->mtime      || param->check_size)
2019                 decision = 0;
2020         if (param->type && checked_type == 0)
2021                 decision = 0;
2022
2023         if (param->have_fileinfo == 0 && decision == 0) {
2024                 if (dir) {
2025                         /* retrieve needed file info */
2026                         ret = ioctl(dirfd(dir), LL_IOC_MDC_GETINFO,
2027                                     (void *)param->lmd);
2028                 } else {
2029                         char *fname = strrchr(path, '/');
2030                         fname = (fname == NULL ? path : fname + 1);
2031
2032                         /* retrieve needed file info */
2033                         strncpy((char *)param->lmd, fname, param->lumlen);
2034                         ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
2035                                    (void *)param->lmd);
2036                 }
2037         }
2038
2039         if (ret) {
2040                 if (errno == ENOTTY) {
2041                         /* ioctl is not supported, it is not a lustre fs.
2042                          * Do the regular lstat(2) instead. */
2043                         lustre_fs = 0;
2044                         ret = lstat_f(path, st);
2045                         if (ret) {
2046                                 ret = -errno;
2047                                 llapi_error(LLAPI_MSG_ERROR, ret,
2048                                             "error: %s: lstat failed for %s",
2049                                             __func__, path);
2050                                 return ret;
2051                         }
2052                 } else if (errno == ENOENT) {
2053                         llapi_error(LLAPI_MSG_WARN, -ENOENT,
2054                                   "warning: %s: %s does not exist",
2055                                   __func__, path);
2056                         goto decided;
2057                 } else {
2058                         ret = -errno;
2059                         llapi_error(LLAPI_MSG_ERROR, ret,
2060                                     "error: %s: %s failed for %s",
2061                                     __func__, dir ? "LL_IOC_MDC_GETINFO" :
2062                                   "IOC_MDC_GETFILEINFO", path);
2063                         return ret;
2064                 }
2065         }
2066
2067         if (param->type && !checked_type) {
2068                 if ((st->st_mode & S_IFMT) == param->type) {
2069                         if (param->exclude_type)
2070                                 goto decided;
2071                 } else {
2072                         if (!param->exclude_type)
2073                                 goto decided;
2074                 }
2075         }
2076
2077         /* Prepare odb. */
2078         if (param->obduuid) {
2079                 if (lustre_fs && param->got_uuids &&
2080                     param->st_dev != st->st_dev) {
2081                         /* A lustre/lustre mount point is crossed. */
2082                         param->got_uuids = 0;
2083                         param->obds_printed = 0;
2084                         param->obdindex = OBD_NOT_FOUND;
2085                 }
2086
2087                 if (lustre_fs && !param->got_uuids) {
2088                         ret = setup_obd_indexes(dir ? dir : parent, param);
2089                         if (ret)
2090                                 return ret;
2091
2092                         param->st_dev = st->st_dev;
2093                 } else if (!lustre_fs && param->got_uuids) {
2094                         /* A lustre/non-lustre mount point is crossed. */
2095                         param->got_uuids = 0;
2096                         param->obdindex = OBD_NOT_FOUND;
2097                 }
2098         }
2099
2100         /* If an OBD UUID is specified but no one matches, skip this file. */
2101         if (param->obduuid && param->obdindex == OBD_NOT_FOUND)
2102                 goto decided;
2103
2104         /* If a OST UUID is given, and some OST matches, check it here. */
2105         if (param->obdindex != OBD_NOT_FOUND) {
2106                 if (!S_ISREG(st->st_mode))
2107                         goto decided;
2108
2109                 /* Only those files should be accepted, which have a
2110                  * stripe on the specified OST. */
2111                 if (!param->lmd->lmd_lmm.lmm_stripe_count) {
2112                         goto decided;
2113                 } else {
2114                         int i, j;
2115                         struct lov_user_ost_data_v1 *lmm_objects;
2116
2117                         if (param->lmd->lmd_lmm.lmm_magic ==
2118                             LOV_USER_MAGIC_V3) {
2119                                 struct lov_user_md_v3 *lmmv3 =
2120                                         (void *)&param->lmd->lmd_lmm;
2121
2122                                 lmm_objects = lmmv3->lmm_objects;
2123                         } else {
2124                                 lmm_objects = param->lmd->lmd_lmm.lmm_objects;
2125                         }
2126
2127                         for (i = 0;
2128                              i < param->lmd->lmd_lmm.lmm_stripe_count; i++) {
2129                                 for (j = 0; j < param->num_obds; j++) {
2130                                         if (param->obdindexes[j] ==
2131                                             lmm_objects[i].l_ost_idx) {
2132                                                 if (param->exclude_obd)
2133                                                         goto decided;
2134                                                 break;
2135                                         }
2136                                 }
2137                                 /* If an OBD matches, just break */
2138                                 if (j != param->num_obds)
2139                                         break;
2140                         }
2141
2142                         if (i == param->lmd->lmd_lmm.lmm_stripe_count) {
2143                                 if (!param->exclude_obd)
2144                                         goto decided;
2145                         }
2146                 }
2147         }
2148
2149         if (param->check_uid) {
2150                 if (st->st_uid == param->uid) {
2151                         if (param->exclude_uid)
2152                                 goto decided;
2153                 } else {
2154                         if (!param->exclude_uid)
2155                                 goto decided;
2156                 }
2157         }
2158
2159         if (param->check_gid) {
2160                 if (st->st_gid == param->gid) {
2161                         if (param->exclude_gid)
2162                                 goto decided;
2163                 } else {
2164                         if (!param->exclude_gid)
2165                                 goto decided;
2166                 }
2167         }
2168
2169         if (param->check_pool) {
2170                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
2171
2172                 /* empty requested pool is taken as no pool search => V1 */
2173                 if (((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V1) &&
2174                      (param->poolname[0] == '\0')) ||
2175                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
2176                      (strncmp(lmmv3->lmm_pool_name,
2177                               param->poolname, LOV_MAXPOOLNAME) == 0)) ||
2178                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
2179                      (strcmp(param->poolname, "*") == 0))) {
2180                         if (param->exclude_pool)
2181                                 goto decided;
2182                 } else {
2183                         if (!param->exclude_pool)
2184                                 goto decided;
2185                 }
2186         }
2187
2188         /* Check the time on mds. */
2189         decision = 1;
2190         if (param->atime || param->ctime || param->mtime) {
2191                 int for_mds;
2192
2193                 for_mds = lustre_fs ? (S_ISREG(st->st_mode) &&
2194                                        param->lmd->lmd_lmm.lmm_stripe_count)
2195                                     : 0;
2196                 decision = find_time_check(st, param, for_mds);
2197                 if (decision == -1)
2198                         goto decided;
2199         }
2200
2201         /* If file still fits the request, ask ost for updated info.
2202            The regular stat is almost of the same speed as some new
2203            'glimpse-size-ioctl'. */
2204
2205         if (param->check_size && S_ISREG(st->st_mode) &&
2206             param->lmd->lmd_lmm.lmm_stripe_count)
2207                 decision = 0;
2208
2209         while (!decision) {
2210                 /* For regular files with the stripe the decision may have not
2211                  * been taken yet if *time or size is to be checked. */
2212                 LASSERT(S_ISREG(st->st_mode) &&
2213                         param->lmd->lmd_lmm.lmm_stripe_count);
2214
2215                 if (param->obdindex != OBD_NOT_FOUND) {
2216                         /* Check whether the obd is active or not, if it is
2217                          * not active, just print the object affected by this
2218                          * failed ost
2219                          * */
2220                         struct obd_statfs stat_buf;
2221                         struct obd_uuid uuid_buf;
2222
2223                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
2224                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
2225                         ret = llapi_obd_statfs(path, LL_STATFS_LOV,
2226                                                param->obdindex, &stat_buf,
2227                                                &uuid_buf);
2228                         if (ret) {
2229                                 llapi_printf(LLAPI_MSG_NORMAL,
2230                                              "obd_uuid: %s failed %s ",
2231                                              param->obduuid->uuid,
2232                                              strerror(errno));
2233                                 break;
2234                         }
2235                 }
2236                 if (dir) {
2237                         ret = ioctl(dirfd(dir), IOC_LOV_GETINFO,
2238                                     (void *)param->lmd);
2239                 } else if (parent) {
2240                         ret = ioctl(dirfd(parent), IOC_LOV_GETINFO,
2241                                     (void *)param->lmd);
2242                 }
2243
2244                 if (ret) {
2245                         if (errno == ENOENT) {
2246                                 llapi_error(LLAPI_MSG_ERROR, -ENOENT,
2247                                             "warning: %s: %s does not exist",
2248                                             __func__, path);
2249                                 goto decided;
2250                         } else {
2251                                 ret = -errno;
2252                                 llapi_error(LLAPI_MSG_ERROR, ret,
2253                                             "%s: IOC_LOV_GETINFO on %s failed",
2254                                             __func__, path);
2255                                 return ret;
2256                         }
2257                 }
2258
2259                 /* Check the time on osc. */
2260                 decision = find_time_check(st, param, 0);
2261                 if (decision == -1)
2262                         goto decided;
2263
2264                 break;
2265         }
2266
2267         if (param->check_size)
2268                 decision = find_value_cmp(st->st_size, param->size,
2269                                           param->size_sign, param->exclude_size,
2270                                           param->size_units, 0);
2271
2272         if (decision != -1) {
2273                 llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
2274                 if (param->zeroend)
2275                         llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
2276                 else
2277                         llapi_printf(LLAPI_MSG_NORMAL, "\n");
2278         }
2279
2280 decided:
2281         /* Do not get down anymore? */
2282         if (param->depth == param->maxdepth)
2283                 return 1;
2284
2285         param->depth++;
2286         return 0;
2287 }
2288
2289 int llapi_find(char *path, struct find_param *param)
2290 {
2291         return param_callback(path, cb_find_init, cb_common_fini, param);
2292 }
2293
2294 /*
2295  * Get MDT number that the file/directory inode referenced
2296  * by the open fd resides on.
2297  * Return 0 and mdtidx on success, or -ve errno.
2298  */
2299 int llapi_file_fget_mdtidx(int fd, int *mdtidx)
2300 {
2301         if (ioctl(fd, LL_IOC_GET_MDTIDX, &mdtidx) < 0)
2302                 return -errno;
2303         return 0;
2304 }
2305
2306 static int cb_get_mdt_index(char *path, DIR *parent, DIR *d, void *data,
2307                             cfs_dirent_t *de)
2308 {
2309         struct find_param *param = (struct find_param *)data;
2310         int ret = 0;
2311         int mdtidx;
2312
2313         LASSERT(parent != NULL || d != NULL);
2314
2315         if (d) {
2316                 ret = llapi_file_fget_mdtidx(dirfd(d), &mdtidx);
2317         } else if (parent) {
2318                 int fd;
2319
2320                 fd = open(path, O_RDONLY);
2321                 if (fd > 0) {
2322                         ret = llapi_file_fget_mdtidx(fd, &mdtidx);
2323                         close(fd);
2324                 } else {
2325                         ret = -errno;
2326                 }
2327         }
2328
2329         if (ret) {
2330                 if (ret == -ENODATA) {
2331                         if (!param->obduuid)
2332                                 llapi_printf(LLAPI_MSG_NORMAL,
2333                                              "%s has no stripe info\n", path);
2334                         goto out;
2335                 } else if (ret == -ENOENT) {
2336                         llapi_error(LLAPI_MSG_WARN, ret,
2337                                     "warning: %s: %s does not exist",
2338                                     __func__, path);
2339                         goto out;
2340                 } else if (ret == -ENOTTY) {
2341                         llapi_error(LLAPI_MSG_ERROR, ret,
2342                                     "%s: '%s' not on a Lustre fs?",
2343                                     __func__, path);
2344                 } else {
2345                         llapi_error(LLAPI_MSG_ERROR, ret,
2346                                     "error: %s: LL_IOC_GET_MDTIDX failed for %s",
2347                                     __func__, path);
2348                 }
2349                 return ret;
2350         }
2351
2352         if (param->quiet)
2353                 llapi_printf(LLAPI_MSG_NORMAL, "%d\n", mdtidx);
2354         else
2355                 llapi_printf(LLAPI_MSG_NORMAL, "%s MDT index: %d\n",
2356                              path, mdtidx);
2357
2358 out:
2359         /* Do not get down anymore? */
2360         if (param->depth == param->maxdepth)
2361                 return 1;
2362
2363         param->depth++;
2364         return 0;
2365 }
2366
2367 static int cb_getstripe(char *path, DIR *parent, DIR *d, void *data,
2368                         cfs_dirent_t *de)
2369 {
2370         struct find_param *param = (struct find_param *)data;
2371         int ret = 0;
2372
2373         LASSERT(parent != NULL || d != NULL);
2374
2375         if (param->obduuid) {
2376                 param->quiet = 1;
2377                 ret = setup_obd_uuid(d ? d : parent, path, param);
2378                 if (ret)
2379                         return ret;
2380         }
2381
2382         if (d) {
2383                 ret = ioctl(dirfd(d), LL_IOC_LOV_GETSTRIPE,
2384                             (void *)&param->lmd->lmd_lmm);
2385         } else if (parent) {
2386                 char *fname = strrchr(path, '/');
2387                 fname = (fname == NULL ? path : fname + 1);
2388
2389                 strncpy((char *)&param->lmd->lmd_lmm, fname, param->lumlen);
2390
2391                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILESTRIPE,
2392                             (void *)&param->lmd->lmd_lmm);
2393         }
2394
2395         if (ret) {
2396                 if (errno == ENODATA && d != NULL) {
2397                         /* We need to "fake" the "use the default" values
2398                          * since the lmm struct is zeroed out at this point.
2399                          * The magic needs to be set in order to satisfy
2400                          * a check later on in the code path.
2401                          * The object_seq needs to be set for the "(Default)"
2402                          * prefix to be displayed. */
2403                         struct lov_user_md *lmm = &param->lmd->lmd_lmm;
2404                         lmm->lmm_magic = LOV_MAGIC_V1;
2405                         if (!param->raw)
2406                                 lmm->lmm_object_seq = FID_SEQ_LOV_DEFAULT;
2407                         lmm->lmm_stripe_count = 0;
2408                         lmm->lmm_stripe_size = 0;
2409                         lmm->lmm_stripe_offset = -1;
2410                         goto dump;
2411
2412                 } else if (errno == ENODATA && parent != NULL) {
2413                         if (!param->obduuid)
2414                                 llapi_printf(LLAPI_MSG_NORMAL,
2415                                              "%s has no stripe info\n", path);
2416                         goto out;
2417                 } else if (errno == ENOENT) {
2418                         llapi_error(LLAPI_MSG_WARN, -ENOENT,
2419                                     "warning: %s: %s does not exist",
2420                                     __func__, path);
2421                         goto out;
2422                 } else if (errno == ENOTTY) {
2423                         ret = -errno;
2424                         llapi_error(LLAPI_MSG_ERROR, ret,
2425                                     "%s: '%s' not on a Lustre fs?",
2426                                     __func__, path);
2427                 } else {
2428                         ret = -errno;
2429                         llapi_error(LLAPI_MSG_ERROR, ret,
2430                                     "error: %s: %s failed for %s",
2431                                      __func__, d ? "LL_IOC_LOV_GETSTRIPE" :
2432                                     "IOC_MDC_GETFILESTRIPE", path);
2433                 }
2434
2435                 return ret;
2436         }
2437
2438 dump:
2439         if (!param->get_mdt_index)
2440                 llapi_lov_dump_user_lmm(param, path, d ? 1 : 0);
2441
2442 out:
2443         /* Do not get down anymore? */
2444         if (param->depth == param->maxdepth)
2445                 return 1;
2446
2447         param->depth++;
2448         return 0;
2449 }
2450
2451 int llapi_getstripe(char *path, struct find_param *param)
2452 {
2453         return param_callback(path, param->get_mdt_index ?
2454                               cb_get_mdt_index : cb_getstripe,
2455                               cb_common_fini, param);
2456 }
2457
2458 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
2459                      struct obd_statfs *stat_buf,
2460                      struct obd_uuid *uuid_buf)
2461 {
2462         int fd;
2463         char raw[OBD_MAX_IOCTL_BUFFER] = {'\0'};
2464         char *rawbuf = raw;
2465         struct obd_ioctl_data data = { 0 };
2466         int rc = 0;
2467
2468         data.ioc_inlbuf1 = (char *)&type;
2469         data.ioc_inllen1 = sizeof(__u32);
2470         data.ioc_inlbuf2 = (char *)&index;
2471         data.ioc_inllen2 = sizeof(__u32);
2472         data.ioc_pbuf1 = (char *)stat_buf;
2473         data.ioc_plen1 = sizeof(struct obd_statfs);
2474         data.ioc_pbuf2 = (char *)uuid_buf;
2475         data.ioc_plen2 = sizeof(struct obd_uuid);
2476
2477         rc = obd_ioctl_pack(&data, &rawbuf, sizeof(raw));
2478         if (rc != 0) {
2479                 llapi_error(LLAPI_MSG_ERROR, rc,
2480                             "llapi_obd_statfs: error packing ioctl data");
2481                 return rc;
2482         }
2483
2484         fd = open(path, O_RDONLY);
2485         if (errno == EISDIR)
2486                 fd = open(path, O_DIRECTORY | O_RDONLY);
2487
2488         if (fd < 0) {
2489                 rc = errno ? -errno : -EBADF;
2490                 llapi_error(LLAPI_MSG_ERROR, rc, "error: %s: opening '%s'",
2491                             __func__, path);
2492                 return rc;
2493         }
2494         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
2495         if (rc)
2496                 rc = errno ? -errno : -EINVAL;
2497
2498         close(fd);
2499         return rc;
2500 }
2501
2502 #define MAX_STRING_SIZE 128
2503 #define DEVICES_LIST "/proc/fs/lustre/devices"
2504
2505 int llapi_ping(char *obd_type, char *obd_name)
2506 {
2507         char path[MAX_STRING_SIZE];
2508         char buf[1];
2509         int rc, fd;
2510
2511         snprintf(path, MAX_STRING_SIZE, "/proc/fs/lustre/%s/%s/ping",
2512                  obd_type, obd_name);
2513
2514         fd = open(path, O_WRONLY);
2515         if (fd < 0) {
2516                 rc = -errno;
2517                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s", path);
2518                 return rc;
2519         }
2520
2521         rc = write(fd, buf, 1);
2522         if (rc < 0)
2523                 rc = -errno;
2524         close(fd);
2525
2526         if (rc == 1)
2527                 return 0;
2528         return rc;
2529 }
2530
2531 int llapi_target_iterate(int type_num, char **obd_type,
2532                          void *args, llapi_cb_t cb)
2533 {
2534         char buf[MAX_STRING_SIZE];
2535         FILE *fp = fopen(DEVICES_LIST, "r");
2536         int i, rc = 0;
2537
2538         if (fp == NULL) {
2539                 rc = -errno;
2540                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening "DEVICES_LIST);
2541                 return rc;
2542         }
2543
2544         while (fgets(buf, sizeof(buf), fp) != NULL) {
2545                 char *obd_type_name = NULL;
2546                 char *obd_name = NULL;
2547                 char *obd_uuid = NULL;
2548                 char *bufp = buf;
2549                 struct obd_statfs osfs_buffer;
2550
2551                 while(bufp[0] == ' ')
2552                         ++bufp;
2553
2554                 for(i = 0; i < 3; i++) {
2555                         obd_type_name = strsep(&bufp, " ");
2556                 }
2557                 obd_name = strsep(&bufp, " ");
2558                 obd_uuid = strsep(&bufp, " ");
2559
2560                 memset(&osfs_buffer, 0, sizeof (osfs_buffer));
2561
2562                 for (i = 0; i < type_num; i++) {
2563                         if (strcmp(obd_type_name, obd_type[i]) != 0)
2564                                 continue;
2565
2566                         cb(obd_type_name, obd_name, obd_uuid, args);
2567                 }
2568         }
2569         fclose(fp);
2570         return 0;
2571 }
2572
2573 static void do_target_check(char *obd_type_name, char *obd_name,
2574                             char *obd_uuid, void *args)
2575 {
2576         int rc;
2577
2578         rc = llapi_ping(obd_type_name, obd_name);
2579         if (rc == ENOTCONN) {
2580                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
2581         } else if (rc) {
2582                 llapi_error(LLAPI_MSG_ERROR, rc, "error: check '%s'", obd_name);
2583         } else {
2584                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
2585         }
2586 }
2587
2588 int llapi_target_check(int type_num, char **obd_type, char *dir)
2589 {
2590         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
2591 }
2592
2593 #undef MAX_STRING_SIZE
2594
2595 int llapi_catinfo(char *dir, char *keyword, char *node_name)
2596 {
2597         char raw[OBD_MAX_IOCTL_BUFFER];
2598         char out[LLOG_CHUNK_SIZE];
2599         char *buf = raw;
2600         struct obd_ioctl_data data = { 0 };
2601         char key[30];
2602         DIR *root;
2603         int rc;
2604
2605         sprintf(key, "%s", keyword);
2606         memset(raw, 0, sizeof(raw));
2607         memset(out, 0, sizeof(out));
2608         data.ioc_inlbuf1 = key;
2609         data.ioc_inllen1 = strlen(key) + 1;
2610         if (node_name) {
2611                 data.ioc_inlbuf2 = node_name;
2612                 data.ioc_inllen2 = strlen(node_name) + 1;
2613         }
2614         data.ioc_pbuf1 = out;
2615         data.ioc_plen1 = sizeof(out);
2616         rc = obd_ioctl_pack(&data, &buf, sizeof(raw));
2617         if (rc)
2618                 return rc;
2619
2620         root = opendir(dir);
2621         if (root == NULL) {
2622                 rc = -errno;
2623                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", dir);
2624                 return rc;
2625         }
2626
2627         rc = ioctl(dirfd(root), OBD_IOC_LLOG_CATINFO, buf);
2628         if (rc) {
2629                 rc = -errno;
2630                 llapi_error(LLAPI_MSG_ERROR, rc,
2631                             "ioctl OBD_IOC_CATINFO failed");
2632         } else {
2633                 llapi_printf(LLAPI_MSG_NORMAL, "%s", data.ioc_pbuf1);
2634         }
2635
2636         closedir(root);
2637         return rc;
2638 }
2639
2640 /* Is this a lustre fs? */
2641 int llapi_is_lustre_mnttype(const char *type)
2642 {
2643         return (strcmp(type, "lustre") == 0 || strcmp(type,"lustre_lite") == 0);
2644 }
2645
2646 /* Is this a lustre client fs? */
2647 int llapi_is_lustre_mnt(struct mntent *mnt)
2648 {
2649         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
2650                 strstr(mnt->mnt_fsname, ":/") != NULL);
2651 }
2652
2653 int llapi_quotacheck(char *mnt, int check_type)
2654 {
2655         DIR *root;
2656         int rc;
2657
2658         root = opendir(mnt);
2659         if (!root) {
2660                 rc = -errno;
2661                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
2662                 return rc;
2663         }
2664
2665         rc = ioctl(dirfd(root), LL_IOC_QUOTACHECK, check_type);
2666         if (rc < 0)
2667                 rc = -errno;
2668
2669         closedir(root);
2670         return rc;
2671 }
2672
2673 int llapi_poll_quotacheck(char *mnt, struct if_quotacheck *qchk)
2674 {
2675         DIR *root;
2676         int poll_intvl = 2;
2677         int rc;
2678
2679         root = opendir(mnt);
2680         if (!root) {
2681                 rc = -errno;
2682                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
2683                 return rc;
2684         }
2685
2686         while (1) {
2687                 rc = ioctl(dirfd(root), LL_IOC_POLL_QUOTACHECK, qchk);
2688                 if (!rc)
2689                         break;
2690                 sleep(poll_intvl);
2691                 if (poll_intvl < 30)
2692                         poll_intvl *= 2;
2693         }
2694
2695         closedir(root);
2696         return 0;
2697 }
2698
2699 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
2700 {
2701         DIR *root;
2702         int rc;
2703
2704         root = opendir(mnt);
2705         if (!root) {
2706                 rc = -errno;
2707                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
2708                 return rc;
2709         }
2710
2711         rc = ioctl(dirfd(root), LL_IOC_QUOTACTL, qctl);
2712         if (rc < 0)
2713                 rc = -errno;
2714
2715         closedir(root);
2716         return rc;
2717 }
2718
2719 static int cb_quotachown(char *path, DIR *parent, DIR *d, void *data,
2720                          cfs_dirent_t *de)
2721 {
2722         struct find_param *param = (struct find_param *)data;
2723         lstat_t *st;
2724         int rc;
2725
2726         LASSERT(parent != NULL || d != NULL);
2727
2728         if (d) {
2729                 rc = ioctl(dirfd(d), LL_IOC_MDC_GETINFO,
2730                            (void *)param->lmd);
2731         } else if (parent) {
2732                 char *fname = strrchr(path, '/');
2733                 fname = (fname == NULL ? path : fname + 1);
2734
2735                 strncpy((char *)param->lmd, fname, param->lumlen);
2736                 rc = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
2737                            (void *)param->lmd);
2738         } else {
2739                 return 0;
2740         }
2741
2742         if (rc) {
2743                 if (errno == ENODATA) {
2744                         if (!param->obduuid && !param->quiet)
2745                                 llapi_error(LLAPI_MSG_ERROR, -ENODATA,
2746                                           "%s has no stripe info", path);
2747                         rc = 0;
2748                 } else if (errno == ENOENT) {
2749                         llapi_error(LLAPI_MSG_ERROR, -ENOENT,
2750                                   "warning: %s: %s does not exist",
2751                                   __func__, path);
2752                         rc = 0;
2753                 } else if (errno != EISDIR) {
2754                         rc = -errno;
2755                         llapi_error(LLAPI_MSG_ERROR, rc, "%s ioctl failed for %s.",
2756                                     d ? "LL_IOC_MDC_GETINFO" :
2757                                     "IOC_MDC_GETFILEINFO", path);
2758                 }
2759                 return rc;
2760         }
2761
2762         st = &param->lmd->lmd_st;
2763
2764         /* libc chown() will do extra check, and if the real owner is
2765          * the same as the ones to set, it won't fall into kernel, so
2766          * invoke syscall directly. */
2767         rc = syscall(SYS_chown, path, -1, -1);
2768         if (rc)
2769                 llapi_error(LLAPI_MSG_ERROR, errno,
2770                             "error: chown %s", path);
2771
2772         rc = chmod(path, st->st_mode);
2773         if (rc) {
2774                 rc = -errno;
2775                 llapi_error(LLAPI_MSG_ERROR, rc, "error: chmod %s (%hu)",
2776                             path, st->st_mode);
2777         }
2778
2779         return rc;
2780 }
2781
2782 int llapi_quotachown(char *path, int flag)
2783 {
2784         struct find_param param;
2785
2786         memset(&param, 0, sizeof(param));
2787         param.recursive = 1;
2788         param.verbose = 0;
2789         param.quiet = 1;
2790
2791         return param_callback(path, cb_quotachown, NULL, &param);
2792 }
2793
2794 #include <pwd.h>
2795 #include <grp.h>
2796 #include <mntent.h>
2797 #include <sys/wait.h>
2798 #include <errno.h>
2799 #include <ctype.h>
2800
2801 static int rmtacl_notify(int ops)
2802 {
2803         FILE *fp;
2804         struct mntent *mnt;
2805         int found = 0, fd, rc;
2806
2807         fp = setmntent(MOUNTED, "r");
2808         if (fp == NULL) {
2809                 rc = -errno;
2810                 llapi_error(LLAPI_MSG_ERROR, rc,
2811                             "error setmntent(%s)", MOUNTED);
2812                 return rc;
2813         }
2814
2815         while (1) {
2816                 mnt = getmntent(fp);
2817                 if (!mnt)
2818                         break;
2819
2820                 if (!llapi_is_lustre_mnt(mnt))
2821                         continue;
2822
2823                 fd = open(mnt->mnt_dir, O_RDONLY | O_DIRECTORY);
2824                 if (fd < 0) {
2825                         rc = -errno;
2826                         llapi_error(LLAPI_MSG_ERROR, rc,
2827                                     "Can't open '%s'\n", mnt->mnt_dir);
2828                         return rc;
2829                 }
2830
2831                 rc = ioctl(fd, LL_IOC_RMTACL, ops);
2832                 if (rc < 0) {
2833                         rc = -errno;
2834                         llapi_error(LLAPI_MSG_ERROR, rc, "ioctl %d\n", fd);
2835                         return rc;
2836                 }
2837
2838                 found++;
2839         }
2840         endmntent(fp);
2841         return found;
2842 }
2843
2844 static char *next_token(char *p, int div)
2845 {
2846         if (p == NULL)
2847                 return NULL;
2848
2849         if (div)
2850                 while (*p && *p != ':' && !isspace(*p))
2851                         p++;
2852         else
2853                 while (*p == ':' || isspace(*p))
2854                         p++;
2855
2856         return *p ? p : NULL;
2857 }
2858
2859 static int rmtacl_name2id(char *name, int is_user)
2860 {
2861         if (is_user) {
2862                 struct passwd *pw;
2863
2864                 pw = getpwnam(name);
2865                 if (pw == NULL)
2866                         return INVALID_ID;
2867                 else
2868                         return (int)(pw->pw_uid);
2869         } else {
2870                 struct group *gr;
2871
2872                 gr = getgrnam(name);
2873                 if (gr == NULL)
2874                         return INVALID_ID;
2875                 else
2876                         return (int)(gr->gr_gid);
2877         }
2878 }
2879
2880 static int isodigit(int c)
2881 {
2882         return (c >= '0' && c <= '7') ? 1 : 0;
2883 }
2884
2885 /*
2886  * Whether the name is just digits string (uid/gid) already or not.
2887  * Return value:
2888  * 1: str is id
2889  * 0: str is not id
2890  */
2891 static int str_is_id(char *str)
2892 {
2893         if (str == NULL)
2894                 return 0;
2895
2896         if (*str == '0') {
2897                 str++;
2898                 if (*str == 'x' || *str == 'X') { /* for Hex. */
2899                         if (!isxdigit(*(++str)))
2900                                 return 0;
2901
2902                         while (isxdigit(*(++str)));
2903                 } else if (isodigit(*str)) { /* for Oct. */
2904                         while (isodigit(*(++str)));
2905                 }
2906         } else if (isdigit(*str)) { /* for Dec. */
2907                 while (isdigit(*(++str)));
2908         }
2909
2910         return (*str == 0) ? 1 : 0;
2911 }
2912
2913 typedef struct {
2914         char *name;
2915         int   length;
2916         int   is_user;
2917         int   next_token;
2918 } rmtacl_name_t;
2919
2920 #define RMTACL_OPTNAME(name) name, sizeof(name) - 1
2921
2922 static rmtacl_name_t rmtacl_namelist[] = {
2923         { RMTACL_OPTNAME("user:"),            1,      0 },
2924         { RMTACL_OPTNAME("group:"),           0,      0 },
2925         { RMTACL_OPTNAME("default:user:"),    1,      0 },
2926         { RMTACL_OPTNAME("default:group:"),   0,      0 },
2927         /* for --tabular option */
2928         { RMTACL_OPTNAME("user"),             1,      1 },
2929         { RMTACL_OPTNAME("group"),            0,      1 },
2930         { 0 }
2931 };
2932
2933 static int rgetfacl_output(char *str)
2934 {
2935         char *start = NULL, *end = NULL;
2936         int is_user = 0, n, id;
2937         char c;
2938         rmtacl_name_t *rn;
2939
2940         if (str == NULL)
2941                 return -1;
2942
2943         for (rn = rmtacl_namelist; rn->name; rn++) {
2944                 if(strncmp(str, rn->name, rn->length) == 0) {
2945                         if (!rn->next_token)
2946                                 start = str + rn->length;
2947                         else
2948                                 start = next_token(str + rn->length, 0);
2949                         is_user = rn->is_user;
2950                         break;
2951                 }
2952         }
2953
2954         end = next_token(start, 1);
2955         if (end == NULL || start == end) {
2956                 n = printf("%s", str);
2957                 return n;
2958         }
2959
2960         c = *end;
2961         *end = 0;
2962         id = rmtacl_name2id(start, is_user);
2963         if (id == INVALID_ID) {
2964                 if (str_is_id(start)) {
2965                         *end = c;
2966                         n = printf("%s", str);
2967                 } else
2968                         return -1;
2969         } else if ((id == NOBODY_UID && is_user) ||
2970                    (id == NOBODY_GID && !is_user)) {
2971                 *end = c;
2972                 n = printf("%s", str);
2973         } else {
2974                 *end = c;
2975                 *start = 0;
2976                 n = printf("%s%d%s", str, id, end);
2977         }
2978         return n;
2979 }
2980
2981 static int child_status(int status)
2982 {
2983         return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
2984 }
2985
2986 static int do_rmtacl(int argc, char *argv[], int ops, int (output_func)(char *))
2987 {
2988         pid_t pid = 0;
2989         int fd[2], status, rc;
2990         FILE *fp;
2991         char buf[PIPE_BUF];
2992
2993         if (output_func) {
2994                 if (pipe(fd) < 0) {
2995                         rc = -errno;
2996                         llapi_error(LLAPI_MSG_ERROR, rc, "Can't create pipe\n");
2997                         return rc;
2998                 }
2999
3000                 pid = fork();
3001                 if (pid < 0) {
3002                         rc = -errno;
3003                         llapi_error(LLAPI_MSG_ERROR, rc, "Can't fork\n");
3004                         close(fd[0]);
3005                         close(fd[1]);
3006                         return rc;
3007                 } else if (!pid) {
3008                         /* child process redirects its output. */
3009                         close(fd[0]);
3010                         close(1);
3011                         if (dup2(fd[1], 1) < 0) {
3012                                 rc = -errno;
3013                                 llapi_error(LLAPI_MSG_ERROR, rc,
3014                                             "Can't dup2 %d\n", fd[1]);
3015                                 close(fd[1]);
3016                                 return rc;
3017                         }
3018                 } else {
3019                         close(fd[1]);
3020                 }
3021         }
3022
3023         if (!pid) {
3024                 status = rmtacl_notify(ops);
3025                 if (status < 0)
3026                         return -errno;
3027
3028                 exit(execvp(argv[0], argv));
3029         }
3030
3031         /* the following is parent process */
3032         fp = fdopen(fd[0], "r");
3033         if (fp == NULL) {
3034                 rc = -errno;
3035                 llapi_error(LLAPI_MSG_ERROR, rc, "fdopen %d failed\n", fd[0]);
3036                 kill(pid, SIGKILL);
3037                 close(fd[0]);
3038                 return rc;
3039         }
3040
3041         while (fgets(buf, PIPE_BUF, fp) != NULL) {
3042                 if (output_func(buf) < 0)
3043                         fprintf(stderr, "WARNING: unexpected error!\n[%s]\n",
3044                                 buf);
3045         }
3046         fclose(fp);
3047         close(fd[0]);
3048
3049         if (waitpid(pid, &status, 0) < 0) {
3050                 rc = -errno;
3051                 llapi_error(LLAPI_MSG_ERROR, rc, "waitpid %d failed\n", pid);
3052                 return rc;
3053         }
3054
3055         return child_status(status);
3056 }
3057
3058 int llapi_lsetfacl(int argc, char *argv[])
3059 {
3060         return do_rmtacl(argc, argv, RMT_LSETFACL, NULL);
3061 }
3062
3063 int llapi_lgetfacl(int argc, char *argv[])
3064 {
3065         return do_rmtacl(argc, argv, RMT_LGETFACL, NULL);
3066 }
3067
3068 int llapi_rsetfacl(int argc, char *argv[])
3069 {
3070         return do_rmtacl(argc, argv, RMT_RSETFACL, NULL);
3071 }
3072
3073 int llapi_rgetfacl(int argc, char *argv[])
3074 {
3075         return do_rmtacl(argc, argv, RMT_RGETFACL, rgetfacl_output);
3076 }
3077
3078 int llapi_cp(int argc, char *argv[])
3079 {
3080         int rc;
3081
3082         rc = rmtacl_notify(RMT_RSETFACL);
3083         if (rc < 0)
3084                 return rc;
3085
3086         exit(execvp(argv[0], argv));
3087 }
3088
3089 int llapi_ls(int argc, char *argv[])
3090 {
3091         int rc;
3092
3093         rc = rmtacl_notify(RMT_LGETFACL);
3094         if (rc < 0)
3095                 return rc;
3096
3097         exit(execvp(argv[0], argv));
3098 }
3099
3100 /* Print mdtname 'name' into 'buf' using 'format'.  Add -MDT0000 if needed.
3101  * format must have %s%s, buf must be > 16
3102  * Eg: if name = "lustre-MDT0000", "lustre", or "lustre-MDT0000_UUID"
3103  *     then buf = "lustre-MDT0000"
3104  */
3105 static int get_mdtname(char *name, char *format, char *buf)
3106 {
3107         char suffix[]="-MDT0000";
3108         int len = strlen(name);
3109
3110         if ((len > 5) && (strncmp(name + len - 5, "_UUID", 5) == 0)) {
3111                 name[len - 5] = '\0';
3112                 len -= 5;
3113         }
3114
3115         if (len > 8) {
3116                 if ((len <= 16) && strncmp(name + len - 8, "-MDT", 4) == 0) {
3117                         suffix[0] = '\0';
3118                 } else {
3119                         /* Not enough room to add suffix */
3120                         llapi_err_noerrno(LLAPI_MSG_ERROR,
3121                                           "MDT name too long |%s|", name);
3122                         return -EINVAL;
3123                 }
3124         }
3125
3126         return sprintf(buf, format, name, suffix);
3127 }
3128
3129 /** ioctl on filsystem root, with mdtindex sent as data
3130  * \param mdtname path, fsname, or mdtname (lutre-MDT0004)
3131  * \param mdtidxp pointer to integer within data to be filled in with the
3132  *    mdt index (0 if no mdt is specified).  NULL won't be filled.
3133  */
3134 static int root_ioctl(const char *mdtname, int opc, void *data, int *mdtidxp,
3135                       int want_error)
3136 {
3137         char fsname[20];
3138         char *ptr;
3139         int fd, index, rc;
3140
3141         /* Take path, fsname, or MDTname.  Assume MDT0000 in the former cases.
3142          Open root and parse mdt index. */
3143         if (mdtname[0] == '/') {
3144                 index = 0;
3145                 rc = get_root_path(WANT_FD | want_error, NULL, &fd,
3146                                    (char *)mdtname, -1);
3147         } else {
3148                 if (get_mdtname((char *)mdtname, "%s%s", fsname) < 0)
3149                         return -EINVAL;
3150                 ptr = fsname + strlen(fsname) - 8;
3151                 *ptr = '\0';
3152                 index = strtol(ptr + 4, NULL, 10);
3153                 rc = get_root_path(WANT_FD | want_error, fsname, &fd, NULL, -1);
3154         }
3155         if (rc < 0) {
3156                 if (want_error)
3157                         llapi_err_noerrno(LLAPI_MSG_ERROR,
3158                                           "Can't open %s: %d\n", mdtname, rc);
3159                 return rc;
3160         }
3161
3162         if (mdtidxp)
3163                 *mdtidxp = index;
3164
3165         rc = ioctl(fd, opc, data);
3166         if (rc == -1)
3167                 rc = -errno;
3168         else
3169                 rc = 0;
3170         if (rc && want_error)
3171                 llapi_error(LLAPI_MSG_ERROR, rc, "ioctl %d err %d", opc, rc);
3172
3173         close(fd);
3174         return rc;
3175 }
3176
3177 /****** Changelog API ********/
3178
3179 static int changelog_ioctl(const char *mdtname, int opc, int id,
3180                            long long recno, int flags)
3181 {
3182         struct ioc_changelog data;
3183         int *idx;
3184
3185         data.icc_id = id;
3186         data.icc_recno = recno;
3187         data.icc_flags = flags;
3188         idx = (int *)(&data.icc_mdtindex);
3189
3190         return root_ioctl(mdtname, opc, &data, idx, WANT_ERROR);
3191 }
3192
3193 #define CHANGELOG_PRIV_MAGIC 0xCA8E1080
3194 struct changelog_private {
3195         int magic;
3196         int flags;
3197         lustre_kernelcomm kuc;
3198 };
3199
3200 /** Start reading from a changelog
3201  * @param priv Opaque private control structure
3202  * @param flags Start flags (e.g. CHANGELOG_FLAG_BLOCK)
3203  * @param device Report changes recorded on this MDT
3204  * @param startrec Report changes beginning with this record number
3205  * (just call llapi_changelog_fini when done; don't need an endrec)
3206  */
3207 int llapi_changelog_start(void **priv, int flags, const char *device,
3208                           long long startrec)
3209 {
3210         struct changelog_private *cp;
3211         int rc;
3212
3213         /* Set up the receiver control struct */
3214         cp = calloc(1, sizeof(*cp));
3215         if (cp == NULL)
3216                 return -ENOMEM;
3217
3218         cp->magic = CHANGELOG_PRIV_MAGIC;
3219         cp->flags = flags;
3220
3221         /* Set up the receiver */
3222         rc = libcfs_ukuc_start(&cp->kuc, 0 /* no group registration */);
3223         if (rc < 0)
3224                 goto out_free;
3225
3226         *priv = cp;
3227
3228         /* Tell the kernel to start sending */
3229         rc = changelog_ioctl(device, OBD_IOC_CHANGELOG_SEND, cp->kuc.lk_wfd,
3230                              startrec, flags);
3231         /* Only the kernel reference keeps the write side open */
3232         close(cp->kuc.lk_wfd);
3233         cp->kuc.lk_wfd = 0;
3234         if (rc < 0) {
3235                 /* frees and clears priv */
3236                 llapi_changelog_fini(priv);
3237                 return rc;
3238         }
3239
3240         return 0;
3241
3242 out_free:
3243         free(cp);
3244         return rc;
3245 }
3246
3247 /** Finish reading from a changelog */
3248 int llapi_changelog_fini(void **priv)
3249 {
3250         struct changelog_private *cp = (struct changelog_private *)*priv;
3251
3252         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
3253                 return -EINVAL;
3254
3255         libcfs_ukuc_stop(&cp->kuc);
3256         free(cp);
3257         *priv = NULL;
3258         return 0;
3259 }
3260
3261 /** Read the next changelog entry
3262  * @param priv Opaque private control structure
3263  * @param rech Changelog record handle; record will be allocated here
3264  * @return 0 valid message received; rec is set
3265  *         <0 error code
3266  *         1 EOF
3267  */
3268 int llapi_changelog_recv(void *priv, struct changelog_rec **rech)
3269 {
3270         struct changelog_private *cp = (struct changelog_private *)priv;
3271         struct kuc_hdr *kuch;
3272         int rc = 0;
3273
3274         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
3275                 return -EINVAL;
3276         if (rech == NULL)
3277                 return -EINVAL;
3278         kuch = malloc(CR_MAXSIZE + sizeof(*kuch));
3279         if (kuch == NULL)
3280                 return -ENOMEM;
3281
3282 repeat:
3283         rc = libcfs_ukuc_msg_get(&cp->kuc, (char *)kuch,
3284                                  CR_MAXSIZE + sizeof(*kuch),
3285                                  KUC_TRANSPORT_CHANGELOG);
3286         if (rc < 0)
3287                 goto out_free;
3288
3289         if ((kuch->kuc_transport != KUC_TRANSPORT_CHANGELOG) ||
3290             ((kuch->kuc_msgtype != CL_RECORD) &&
3291              (kuch->kuc_msgtype != CL_EOF))) {
3292                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3293                                   "Unknown changelog message type %d:%d\n",
3294                                   kuch->kuc_transport, kuch->kuc_msgtype);
3295                 rc = -EPROTO;
3296                 goto out_free;
3297         }
3298
3299         if (kuch->kuc_msgtype == CL_EOF) {
3300                 if (cp->flags & CHANGELOG_FLAG_FOLLOW) {
3301                         /* Ignore EOFs */
3302                         goto repeat;
3303                 } else {
3304                         rc = 1;
3305                         goto out_free;
3306                 }
3307         }
3308
3309         /* Our message is a changelog_rec.  Use pointer math to skip
3310          * kuch_hdr and point directly to the message payload.
3311          */
3312         *rech = (struct changelog_rec *)(kuch + 1);
3313
3314         return 0;
3315
3316 out_free:
3317         *rech = NULL;
3318         free(kuch);
3319         return rc;
3320 }
3321
3322 /** Release the changelog record when done with it. */
3323 int llapi_changelog_free(struct changelog_rec **rech)
3324 {
3325         if (*rech) {
3326                 /* We allocated memory starting at the kuc_hdr, but passed
3327                  * the consumer a pointer to the payload.
3328                  * Use pointer math to get back to the header.
3329                  */
3330                 struct kuc_hdr *kuch = (struct kuc_hdr *)*rech - 1;
3331                 free(kuch);
3332         }
3333         *rech = NULL;
3334         return 0;
3335 }
3336
3337 int llapi_changelog_clear(const char *mdtname, const char *idstr,
3338                           long long endrec)
3339 {
3340         int id;
3341
3342         if (endrec < 0) {
3343                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3344                                   "can't purge negative records\n");
3345                 return -EINVAL;
3346         }
3347
3348         id = strtol(idstr + strlen(CHANGELOG_USER_PREFIX), NULL, 10);
3349         if ((id == 0) || (strncmp(idstr, CHANGELOG_USER_PREFIX,
3350                                   strlen(CHANGELOG_USER_PREFIX)) != 0)) {
3351                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3352                                   "expecting id of the form '"
3353                                   CHANGELOG_USER_PREFIX
3354                                   "<num>'; got '%s'\n", idstr);
3355                 return -EINVAL;
3356         }
3357
3358         return changelog_ioctl(mdtname, OBD_IOC_CHANGELOG_CLEAR, id, endrec, 0);
3359 }
3360
3361 int llapi_fid2path(const char *device, const char *fidstr, char *buf,
3362                    int buflen, long long *recno, int *linkno)
3363 {
3364         struct lu_fid fid;
3365         struct getinfo_fid2path *gf;
3366         int rc;
3367
3368         while (*fidstr == '[')
3369                 fidstr++;
3370
3371         sscanf(fidstr, SFID, RFID(&fid));
3372         if (!fid_is_sane(&fid)) {
3373                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3374                                   "bad FID format [%s], should be "DFID"\n",
3375                                   fidstr, (__u64)1, 2, 0);
3376                 return -EINVAL;
3377         }
3378
3379         gf = malloc(sizeof(*gf) + buflen);
3380         if (gf == NULL)
3381                 return -ENOMEM;
3382         gf->gf_fid = fid;
3383         gf->gf_recno = *recno;
3384         gf->gf_linkno = *linkno;
3385         gf->gf_pathlen = buflen;
3386
3387         /* Take path or fsname */
3388         rc = root_ioctl(device, OBD_IOC_FID2PATH, gf, NULL, 0);
3389         if (rc) {
3390                 if (rc != -ENOENT)
3391                         llapi_error(LLAPI_MSG_ERROR, rc, "ioctl err %d", rc);
3392         } else {
3393                 memcpy(buf, gf->gf_path, gf->gf_pathlen);
3394                 *recno = gf->gf_recno;
3395                 *linkno = gf->gf_linkno;
3396         }
3397
3398         free(gf);
3399         return rc;
3400 }
3401
3402 static int path2fid_from_lma(const char *path, lustre_fid *fid)
3403 {
3404         char buf[512];
3405         struct lustre_mdt_attrs *lma;
3406         int rc;
3407
3408         rc = lgetxattr(path, XATTR_NAME_LMA, buf, sizeof(buf));
3409         if (rc < 0)
3410                 return -errno;
3411         lma = (struct lustre_mdt_attrs *)buf;
3412         fid_le_to_cpu(fid, &lma->lma_self_fid);
3413         return 0;
3414 }
3415
3416 int llapi_path2fid(const char *path, lustre_fid *fid)
3417 {
3418         int fd, rc;
3419
3420         memset(fid, 0, sizeof(*fid));
3421         fd = open(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
3422         if (fd < 0) {
3423                 if (errno == ELOOP) /* symbolic link */
3424                         return path2fid_from_lma(path, fid);
3425                 return -errno;
3426         }
3427
3428         rc = ioctl(fd, LL_IOC_PATH2FID, fid) < 0 ? -errno : 0;
3429         if (rc == -EINVAL) /* char special device */
3430                 rc = path2fid_from_lma(path, fid);
3431
3432         close(fd);
3433         return rc;
3434 }
3435
3436 /****** HSM Copytool API ********/
3437 #define CT_PRIV_MAGIC 0xC0BE2001
3438 struct copytool_private {
3439         int magic;
3440         char *fsname;
3441         lustre_kernelcomm kuc;
3442         __u32 archives;
3443 };
3444
3445 #include <libcfs/libcfs.h>
3446
3447 /** Register a copytool
3448  * @param[out] priv Opaque private control structure
3449  * @param fsname Lustre filesystem
3450  * @param flags Open flags, currently unused (e.g. O_NONBLOCK)
3451  * @param archive_count
3452  * @param archives Which archive numbers this copytool is responsible for
3453  */
3454 int llapi_copytool_start(void **priv, char *fsname, int flags,
3455                          int archive_count, int *archives)
3456 {
3457         struct copytool_private *ct;
3458         int rc;
3459
3460         if (archive_count > 0 && archives == NULL) {
3461                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3462                                   "NULL archive numbers");
3463                 return -EINVAL;
3464         }
3465
3466         ct = calloc(1, sizeof(*ct));
3467         if (ct == NULL)
3468                 return -ENOMEM;
3469
3470         ct->fsname = malloc(strlen(fsname) + 1);
3471         if (ct->fsname == NULL) {
3472                 rc = -ENOMEM;
3473                 goto out_err;
3474         }
3475         strcpy(ct->fsname, fsname);
3476         ct->magic = CT_PRIV_MAGIC;
3477         ct->archives = 0;
3478         for (rc = 0; rc < archive_count; rc++) {
3479                 if (archives[rc] > sizeof(ct->archives)) {
3480                         llapi_err_noerrno(LLAPI_MSG_ERROR,
3481                                           "Maximum of %d archives supported",
3482                                           sizeof(ct->archives));
3483                         goto out_err;
3484                 }
3485                 ct->archives |= 1 << archives[rc];
3486         }
3487         /* special case: if no archives specified, default to archive #0. */
3488         if (ct->archives == 0)
3489                 ct->archives = 1;
3490
3491         rc = libcfs_ukuc_start(&ct->kuc, KUC_GRP_HSM);
3492         if (rc < 0)
3493                 goto out_err;
3494
3495         /* Storing archive(s) in lk_data; see mdc_ioc_hsm_ct_start */
3496         ct->kuc.lk_data = ct->archives;
3497         rc = root_ioctl(ct->fsname, LL_IOC_HSM_CT_START, &(ct->kuc), NULL,
3498                         WANT_ERROR);
3499         /* Only the kernel reference keeps the write side open */
3500         close(ct->kuc.lk_wfd);
3501         ct->kuc.lk_wfd = 0;
3502         if (rc < 0)
3503                 goto out_err;
3504
3505         *priv = ct;
3506         return 0;
3507
3508 out_err:
3509         if (ct->fsname)
3510                 free(ct->fsname);
3511         free(ct);
3512         return rc;
3513 }
3514
3515 /** Deregister a copytool */
3516 int llapi_copytool_fini(void **priv)
3517 {
3518         struct copytool_private *ct = (struct copytool_private *)*priv;
3519
3520         if (!ct || (ct->magic != CT_PRIV_MAGIC))
3521                 return -EINVAL;
3522
3523         /* Tell the kernel to stop sending us messages */
3524         ct->kuc.lk_flags = LK_FLG_STOP;
3525         root_ioctl(ct->fsname, LL_IOC_HSM_CT_START, &(ct->kuc), NULL, 0);
3526
3527         /* Shut down the kernelcomms */
3528         libcfs_ukuc_stop(&ct->kuc);
3529
3530         free(ct->fsname);
3531         free(ct);
3532         *priv = NULL;
3533         return 0;
3534 }
3535
3536 /** Wait for the next hsm_action_list
3537  * @param priv Opaque private control structure
3538  * @param halh Action list handle, will be allocated here
3539  * @param msgsize Number of bytes in the message, will be set here
3540  * @return 0 valid message received; halh and msgsize are set
3541  *         <0 error code
3542  */
3543 int llapi_copytool_recv(void *priv, struct hsm_action_list **halh, int *msgsize)
3544 {
3545         struct copytool_private *ct = (struct copytool_private *)priv;
3546         struct kuc_hdr *kuch;
3547         struct hsm_action_list *hal;
3548         int rc = 0;
3549
3550         if (!ct || (ct->magic != CT_PRIV_MAGIC))
3551                 return -EINVAL;
3552         if (halh == NULL || msgsize == NULL)
3553                 return -EINVAL;
3554
3555         kuch = malloc(HAL_MAXSIZE + sizeof(*kuch));
3556         if (kuch == NULL)
3557                 return -ENOMEM;
3558
3559         rc = libcfs_ukuc_msg_get(&ct->kuc, (char *)kuch,
3560                                  HAL_MAXSIZE + sizeof(*kuch),
3561                                  KUC_TRANSPORT_HSM);
3562         if (rc < 0)
3563                 goto out_free;
3564
3565         /* Handle generic messages */
3566         if (kuch->kuc_transport == KUC_TRANSPORT_GENERIC &&
3567             kuch->kuc_msgtype == KUC_MSG_SHUTDOWN) {
3568                 rc = -ESHUTDOWN;
3569                 goto out_free;
3570         }
3571
3572         if (kuch->kuc_transport != KUC_TRANSPORT_HSM ||
3573             kuch->kuc_msgtype != HMT_ACTION_LIST) {
3574                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3575                                   "Unknown HSM message type %d:%d\n",
3576                                   kuch->kuc_transport, kuch->kuc_msgtype);
3577                 rc = -EPROTO;
3578                 goto out_free;
3579         }
3580
3581         /* Our message is a hsm_action_list.  Use pointer math to skip
3582          * kuch_hdr and point directly to the message payload.
3583          */
3584         hal = (struct hsm_action_list *)(kuch + 1);
3585
3586         /* Check that we have registered for this archive # */
3587         if (((1 << hal->hal_archive_num) & ct->archives) == 0) {
3588                     llapi_err_noerrno(LLAPI_MSG_INFO,
3589                              "Ignoring request for archive #%d (bitmask %#x)\n",
3590                              hal->hal_archive_num, ct->archives);
3591                 rc = 0;
3592                 goto out_free;
3593         }
3594
3595         *halh = hal;
3596         *msgsize = kuch->kuc_msglen - sizeof(*kuch);
3597         return 0;
3598
3599 out_free:
3600         *halh = NULL;
3601         *msgsize = 0;
3602         free(kuch);
3603         return rc;
3604 }
3605
3606 /** Release the action list when done with it. */
3607 int llapi_copytool_free(struct hsm_action_list **hal)
3608 {
3609         /* Reuse the llapi_changelog_free function */
3610         return llapi_changelog_free((struct changelog_rec **)hal);
3611 }
3612
3613 int llapi_get_connect_flags(const char *mnt, __u64 *flags)
3614 {
3615         DIR *root;
3616         int rc;
3617
3618         root = opendir(mnt);
3619         if (!root) {
3620                 rc = -errno;
3621                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
3622                 return rc;
3623         }
3624
3625         rc = ioctl(dirfd(root), LL_IOC_GET_CONNECT_FLAGS, flags);
3626         if (rc < 0) {
3627                 rc = -errno;
3628                 llapi_error(LLAPI_MSG_ERROR, rc,
3629                             "ioctl on %s for getting connect flags failed", mnt);
3630         }
3631         closedir(root);
3632         return rc;
3633 }
3634
3635 int llapi_get_version(char *buffer, int buffer_size,
3636                       char **version)
3637 {
3638         int rc;
3639         int fd;
3640         struct obd_ioctl_data *data = (struct obd_ioctl_data *)buffer;
3641
3642         fd = open(OBD_DEV_PATH, O_RDONLY);
3643         if (fd == -1)
3644                 return -errno;
3645
3646         memset(buffer, 0, buffer_size);
3647         data->ioc_version = OBD_IOCTL_VERSION;
3648         data->ioc_inllen1 = buffer_size - cfs_size_round(sizeof(*data));
3649         data->ioc_inlbuf1 = buffer + cfs_size_round(sizeof(*data));
3650         data->ioc_len = obd_ioctl_packlen(data);
3651
3652         rc = ioctl(fd, OBD_GET_VERSION, buffer);
3653         if (rc == -1) {
3654                 rc = -errno;
3655                 close(fd);
3656                 return rc;
3657         }
3658         close(fd);
3659         *version = data->ioc_bulk;
3660         return 0;
3661 }