Whamcloud - gitweb
88a0cd23be6688223103ed1871a4f4479cb65088
[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_OFFSET) {
1702                 if (verbose & ~VERBOSE_OFFSET)
1703                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_offset:  ",
1704                                      prefix);
1705                 if (is_dir)
1706                         llapi_printf(LLAPI_MSG_NORMAL, "%d%c",
1707                                      lum->lmm_stripe_offset ==
1708                                      (typeof(lum->lmm_stripe_offset))(-1) ? -1 :
1709                                      lum->lmm_stripe_offset, nl);
1710                 else
1711                         llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
1712                                      objects[0].l_ost_idx, nl);
1713         }
1714
1715         if ((verbose & VERBOSE_POOL) && (pool_name != NULL)) {
1716                 if (verbose & ~VERBOSE_POOL)
1717                         llapi_printf(LLAPI_MSG_NORMAL, "%spool:           ",
1718                                      prefix);
1719                 llapi_printf(LLAPI_MSG_NORMAL, "%s%c", pool_name, nl);
1720         }
1721
1722         if (is_dir && (verbose != VERBOSE_OBJID))
1723                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1724 }
1725
1726 void lov_dump_user_lmm_v1v3(struct lov_user_md *lum, char *pool_name,
1727                             struct lov_user_ost_data_v1 *objects,
1728                             char *path, int is_dir,
1729                             int obdindex, int depth, int header, int raw)
1730 {
1731         int i, obdstripe = (obdindex != OBD_NOT_FOUND) ? 0 : 1;
1732
1733         if (!obdstripe) {
1734                 for (i = 0; !is_dir && i < lum->lmm_stripe_count; i++) {
1735                         if (obdindex == objects[i].l_ost_idx) {
1736                                 obdstripe = 1;
1737                                 break;
1738                         }
1739                 }
1740         }
1741
1742         if (obdstripe == 1)
1743                 lov_dump_user_lmm_header(lum, path, objects, is_dir, header,
1744                                          depth, raw, pool_name);
1745
1746         if (!is_dir && (header & VERBOSE_OBJID)) {
1747                 if (obdstripe == 1)
1748                         llapi_printf(LLAPI_MSG_NORMAL,
1749                                      "\tobdidx\t\t objid\t\tobjid\t\t group\n");
1750
1751                 for (i = 0; i < lum->lmm_stripe_count; i++) {
1752                         int idx = objects[i].l_ost_idx;
1753                         long long oid = objects[i].l_object_id;
1754                         long long gr = objects[i].l_object_seq;
1755                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
1756                                 llapi_printf(LLAPI_MSG_NORMAL,
1757                                            "\t%6u\t%14llu\t%#13llx\t%14llu%s\n",
1758                                            idx, oid, oid, gr,
1759                                            obdindex == idx ? " *" : "");
1760                 }
1761                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1762         }
1763 }
1764
1765 void llapi_lov_dump_user_lmm(struct find_param *param,
1766                              char *path, int is_dir)
1767 {
1768         switch(*(__u32 *)&param->lmd->lmd_lmm) { /* lum->lmm_magic */
1769         case LOV_USER_MAGIC_V1:
1770                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, NULL,
1771                                        param->lmd->lmd_lmm.lmm_objects,
1772                                        path, is_dir,
1773                                        param->obdindex, param->maxdepth,
1774                                        param->verbose, param->raw);
1775                 break;
1776         case LOV_USER_MAGIC_V3: {
1777                 char pool_name[LOV_MAXPOOLNAME + 1];
1778                 struct lov_user_ost_data_v1 *objects;
1779                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
1780
1781                 strncpy(pool_name, lmmv3->lmm_pool_name, LOV_MAXPOOLNAME);
1782                 pool_name[LOV_MAXPOOLNAME] = '\0';
1783                 objects = lmmv3->lmm_objects;
1784                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, pool_name,
1785                                        objects, path, is_dir,
1786                                        param->obdindex, param->maxdepth,
1787                                        param->verbose, param->raw);
1788                 break;
1789         }
1790         default:
1791                 llapi_printf(LLAPI_MSG_NORMAL, "unknown lmm_magic:  %#x "
1792                              "(expecting one of %#x %#x %#x)\n",
1793                              *(__u32 *)&param->lmd->lmd_lmm,
1794                              LOV_USER_MAGIC_V1, LOV_USER_MAGIC_V3);
1795                 return;
1796         }
1797 }
1798
1799 int llapi_file_get_stripe(const char *path, struct lov_user_md *lum)
1800 {
1801         const char *fname;
1802         char *dname;
1803         int fd, rc = 0;
1804
1805         fname = strrchr(path, '/');
1806
1807         /* It should be a file (or other non-directory) */
1808         if (fname == NULL) {
1809                 dname = (char *)malloc(2);
1810                 if (dname == NULL)
1811                         return -ENOMEM;
1812                 strcpy(dname, ".");
1813                 fname = (char *)path;
1814         } else {
1815                 dname = (char *)malloc(fname - path + 1);
1816                 if (dname == NULL)
1817                         return -ENOMEM;
1818                 strncpy(dname, path, fname - path);
1819                 dname[fname - path] = '\0';
1820                 fname++;
1821         }
1822
1823         fd = open(dname, O_RDONLY);
1824         if (fd == -1) {
1825                 rc = -errno;
1826                 free(dname);
1827                 return rc;
1828         }
1829
1830         strcpy((char *)lum, fname);
1831         if (ioctl(fd, IOC_MDC_GETFILESTRIPE, (void *)lum) == -1)
1832                 rc = -errno;
1833
1834         if (close(fd) == -1 && rc == 0)
1835                 rc = -errno;
1836
1837         free(dname);
1838         return rc;
1839 }
1840
1841 int llapi_file_lookup(int dirfd, const char *name)
1842 {
1843         struct obd_ioctl_data data = { 0 };
1844         char rawbuf[8192];
1845         char *buf = rawbuf;
1846         int rc;
1847
1848         if (dirfd < 0 || name == NULL)
1849                 return -EINVAL;
1850
1851         data.ioc_version = OBD_IOCTL_VERSION;
1852         data.ioc_len = sizeof(data);
1853         data.ioc_inlbuf1 = (char *)name;
1854         data.ioc_inllen1 = strlen(name) + 1;
1855
1856         rc = obd_ioctl_pack(&data, &buf, sizeof(rawbuf));
1857         if (rc) {
1858                 llapi_error(LLAPI_MSG_ERROR, rc,
1859                             "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
1860                             name, rc);
1861                 return rc;
1862         }
1863
1864         rc = ioctl(dirfd, IOC_MDC_LOOKUP, buf);
1865         if (rc < 0)
1866                 rc = -errno;
1867         return rc;
1868 }
1869
1870 /* Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
1871  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
1872  *
1873  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
1874  * The table below gives the answers for the specified parameters (value and
1875  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
1876  * --------------------------------------
1877  * 1 | file > limit; sign > 0 | -1 / -1 |
1878  * 2 | file = limit; sign > 0 | -1 / -1 |
1879  * 3 | file < limit; sign > 0 |  ? /  1 |
1880  * 4 | file > limit; sign = 0 | -1 / -1 |
1881  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
1882  * 6 | file < limit; sign = 0 |  ? / -1 |
1883  * 7 | file > limit; sign < 0 |  1 /  1 |
1884  * 8 | file = limit; sign < 0 |  ? / -1 |
1885  * 9 | file < limit; sign < 0 |  ? / -1 |
1886  * --------------------------------------
1887  * Note: 5th actually means that the value is within the interval
1888  * (limit - margin, limit]. */
1889 static int find_value_cmp(unsigned long long file, unsigned long long limit,
1890                           int sign, int negopt, unsigned long long margin,
1891                           int mds)
1892 {
1893         int ret = -1;
1894
1895         if (sign > 0) {
1896                 /* Drop the fraction of margin (of days). */
1897                 if (file + margin <= limit)
1898                         ret = mds ? 0 : 1;
1899         } else if (sign == 0) {
1900                 if (file <= limit && file + margin > limit)
1901                         ret = mds ? 0 : 1;
1902                 else if (file + margin <= limit)
1903                         ret = mds ? 0 : -1;
1904         } else if (sign < 0) {
1905                 if (file > limit)
1906                         ret = 1;
1907                 else if (mds)
1908                         ret = 0;
1909         }
1910
1911         return negopt ? ~ret + 1 : ret;
1912 }
1913
1914 /* Check if the file time matches all the given criteria (e.g. --atime +/-N).
1915  * Return -1 or 1 if file timestamp does not or does match the given criteria
1916  * correspondingly. Return 0 if the MDS time is being checked and there are
1917  * attributes on OSTs and it is not yet clear if the timespamp matches.
1918  *
1919  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
1920  * updated timestamps. */
1921 static int find_time_check(lstat_t *st, struct find_param *param, int mds)
1922 {
1923         int ret;
1924         int rc = 1;
1925
1926         /* Check if file is accepted. */
1927         if (param->atime) {
1928                 ret = find_value_cmp(st->st_atime, param->atime,
1929                                      param->asign, param->exclude_atime, 
1930                                      24 * 60 * 60, mds);
1931                 if (ret < 0)
1932                         return ret;
1933                 rc = ret;
1934         }
1935
1936         if (param->mtime) {
1937                 ret = find_value_cmp(st->st_mtime, param->mtime,
1938                                      param->msign, param->exclude_mtime, 
1939                                      24 * 60 * 60, mds);
1940                 if (ret < 0)
1941                         return ret;
1942
1943                 /* If the previous check matches, but this one is not yet clear,
1944                  * we should return 0 to do an RPC on OSTs. */
1945                 if (rc == 1)
1946                         rc = ret;
1947         }
1948
1949         if (param->ctime) {
1950                 ret = find_value_cmp(st->st_ctime, param->ctime,
1951                                      param->csign, param->exclude_ctime,
1952                                      24 * 60 * 60, mds);
1953                 if (ret < 0)
1954                         return ret;
1955
1956                 /* If the previous check matches, but this one is not yet clear,
1957                  * we should return 0 to do an RPC on OSTs. */
1958                 if (rc == 1)
1959                         rc = ret;
1960         }
1961
1962         return rc;
1963 }
1964
1965 static int cb_find_init(char *path, DIR *parent, DIR *dir,
1966                         void *data, cfs_dirent_t *de)
1967 {
1968         struct find_param *param = (struct find_param *)data;
1969         int decision = 1; /* 1 is accepted; -1 is rejected. */
1970         lstat_t *st = &param->lmd->lmd_st;
1971         int lustre_fs = 1;
1972         int checked_type = 0;
1973         int ret = 0;
1974
1975         LASSERT(parent != NULL || dir != NULL);
1976
1977         if (param->have_fileinfo == 0)
1978                 param->lmd->lmd_lmm.lmm_stripe_count = 0;
1979
1980         /* If a regular expression is presented, make the initial decision */
1981         if (param->pattern != NULL) {
1982                 char *fname = strrchr(path, '/');
1983                 fname = (fname == NULL ? path : fname + 1);
1984                 ret = fnmatch(param->pattern, fname, 0);
1985                 if ((ret == FNM_NOMATCH && !param->exclude_pattern) ||
1986                     (ret == 0 && param->exclude_pattern))
1987                         goto decided;
1988         }
1989
1990         /* See if we can check the file type from the dirent. */
1991         if (param->type && de != NULL && de->d_type != DT_UNKNOWN &&
1992             de->d_type < DT_MAX) {
1993                 checked_type = 1;
1994                 if (llapi_dir_filetype_table[de->d_type] == param->type) {
1995                         if (param->exclude_type)
1996                                 goto decided;
1997                 } else {
1998                         if (!param->exclude_type)
1999                                 goto decided;
2000                 }
2001         }
2002
2003
2004         ret = 0;
2005
2006         /* Request MDS for the stat info if some of these parameters need
2007          * to be compared. */
2008         if (param->obduuid    || param->check_uid || param->check_gid ||
2009             param->check_pool || param->atime     || param->ctime     ||
2010             param->mtime      || param->check_size)
2011                 decision = 0;
2012         if (param->type && checked_type == 0)
2013                 decision = 0;
2014
2015         if (param->have_fileinfo == 0 && decision == 0) {
2016                 if (dir) {
2017                         /* retrieve needed file info */
2018                         ret = ioctl(dirfd(dir), LL_IOC_MDC_GETINFO,
2019                                     (void *)param->lmd);
2020                 } else {
2021                         char *fname = strrchr(path, '/');
2022                         fname = (fname == NULL ? path : fname + 1);
2023
2024                         /* retrieve needed file info */
2025                         strncpy((char *)param->lmd, fname, param->lumlen);
2026                         ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
2027                                    (void *)param->lmd);
2028                 }
2029         }
2030
2031         if (ret) {
2032                 if (errno == ENOTTY) {
2033                         /* ioctl is not supported, it is not a lustre fs.
2034                          * Do the regular lstat(2) instead. */
2035                         lustre_fs = 0;
2036                         ret = lstat_f(path, st);
2037                         if (ret) {
2038                                 ret = -errno;
2039                                 llapi_error(LLAPI_MSG_ERROR, ret,
2040                                             "error: %s: lstat failed for %s",
2041                                             __func__, path);
2042                                 return ret;
2043                         }
2044                 } else if (errno == ENOENT) {
2045                         llapi_error(LLAPI_MSG_WARN, -ENOENT,
2046                                   "warning: %s: %s does not exist",
2047                                   __func__, path);
2048                         goto decided;
2049                 } else {
2050                         ret = -errno;
2051                         llapi_error(LLAPI_MSG_ERROR, ret,
2052                                     "error: %s: %s failed for %s",
2053                                     __func__, dir ? "LL_IOC_MDC_GETINFO" :
2054                                   "IOC_MDC_GETFILEINFO", path);
2055                         return ret;
2056                 }
2057         }
2058
2059         if (param->type && !checked_type) {
2060                 if ((st->st_mode & S_IFMT) == param->type) {
2061                         if (param->exclude_type)
2062                                 goto decided;
2063                 } else {
2064                         if (!param->exclude_type)
2065                                 goto decided;
2066                 }
2067         }
2068
2069         /* Prepare odb. */
2070         if (param->obduuid) {
2071                 if (lustre_fs && param->got_uuids &&
2072                     param->st_dev != st->st_dev) {
2073                         /* A lustre/lustre mount point is crossed. */
2074                         param->got_uuids = 0;
2075                         param->obds_printed = 0;
2076                         param->obdindex = OBD_NOT_FOUND;
2077                 }
2078
2079                 if (lustre_fs && !param->got_uuids) {
2080                         ret = setup_obd_indexes(dir ? dir : parent, param);
2081                         if (ret)
2082                                 return ret;
2083
2084                         param->st_dev = st->st_dev;
2085                 } else if (!lustre_fs && param->got_uuids) {
2086                         /* A lustre/non-lustre mount point is crossed. */
2087                         param->got_uuids = 0;
2088                         param->obdindex = OBD_NOT_FOUND;
2089                 }
2090         }
2091
2092         /* If an OBD UUID is specified but no one matches, skip this file. */
2093         if (param->obduuid && param->obdindex == OBD_NOT_FOUND)
2094                 goto decided;
2095
2096         /* If a OST UUID is given, and some OST matches, check it here. */
2097         if (param->obdindex != OBD_NOT_FOUND) {
2098                 if (!S_ISREG(st->st_mode))
2099                         goto decided;
2100
2101                 /* Only those files should be accepted, which have a
2102                  * stripe on the specified OST. */
2103                 if (!param->lmd->lmd_lmm.lmm_stripe_count) {
2104                         goto decided;
2105                 } else {
2106                         int i, j;
2107                         struct lov_user_ost_data_v1 *lmm_objects;
2108
2109                         if (param->lmd->lmd_lmm.lmm_magic ==
2110                             LOV_USER_MAGIC_V3) {
2111                                 struct lov_user_md_v3 *lmmv3 =
2112                                         (void *)&param->lmd->lmd_lmm;
2113
2114                                 lmm_objects = lmmv3->lmm_objects;
2115                         } else {
2116                                 lmm_objects = param->lmd->lmd_lmm.lmm_objects;
2117                         }
2118
2119                         for (i = 0;
2120                              i < param->lmd->lmd_lmm.lmm_stripe_count; i++) {
2121                                 for (j = 0; j < param->num_obds; j++) {
2122                                         if (param->obdindexes[j] ==
2123                                             lmm_objects[i].l_ost_idx) {
2124                                                 if (param->exclude_obd)
2125                                                         goto decided;
2126                                                 break;
2127                                         }
2128                                 }
2129                                 /* If an OBD matches, just break */
2130                                 if (j != param->num_obds)
2131                                         break;
2132                         }
2133
2134                         if (i == param->lmd->lmd_lmm.lmm_stripe_count) {
2135                                 if (!param->exclude_obd)
2136                                         goto decided;
2137                         }
2138                 }
2139         }
2140
2141         if (param->check_uid) {
2142                 if (st->st_uid == param->uid) {
2143                         if (param->exclude_uid)
2144                                 goto decided;
2145                 } else {
2146                         if (!param->exclude_uid)
2147                                 goto decided;
2148                 }
2149         }
2150
2151         if (param->check_gid) {
2152                 if (st->st_gid == param->gid) {
2153                         if (param->exclude_gid)
2154                                 goto decided;
2155                 } else {
2156                         if (!param->exclude_gid)
2157                                 goto decided;
2158                 }
2159         }
2160
2161         if (param->check_pool) {
2162                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
2163
2164                 /* empty requested pool is taken as no pool search => V1 */
2165                 if (((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V1) &&
2166                      (param->poolname[0] == '\0')) ||
2167                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
2168                      (strncmp(lmmv3->lmm_pool_name,
2169                               param->poolname, LOV_MAXPOOLNAME) == 0)) ||
2170                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
2171                      (strcmp(param->poolname, "*") == 0))) {
2172                         if (param->exclude_pool)
2173                                 goto decided;
2174                 } else {
2175                         if (!param->exclude_pool)
2176                                 goto decided;
2177                 }
2178         }
2179
2180         /* Check the time on mds. */
2181         decision = 1;
2182         if (param->atime || param->ctime || param->mtime) {
2183                 int for_mds;
2184
2185                 for_mds = lustre_fs ? (S_ISREG(st->st_mode) &&
2186                                        param->lmd->lmd_lmm.lmm_stripe_count)
2187                                     : 0;
2188                 decision = find_time_check(st, param, for_mds);
2189                 if (decision == -1)
2190                         goto decided;
2191         }
2192
2193         /* If file still fits the request, ask ost for updated info.
2194            The regular stat is almost of the same speed as some new
2195            'glimpse-size-ioctl'. */
2196
2197         if (param->check_size && S_ISREG(st->st_mode) &&
2198             param->lmd->lmd_lmm.lmm_stripe_count)
2199                 decision = 0;
2200
2201         while (!decision) {
2202                 /* For regular files with the stripe the decision may have not
2203                  * been taken yet if *time or size is to be checked. */
2204                 LASSERT(S_ISREG(st->st_mode) &&
2205                         param->lmd->lmd_lmm.lmm_stripe_count);
2206
2207                 if (param->obdindex != OBD_NOT_FOUND) {
2208                         /* Check whether the obd is active or not, if it is
2209                          * not active, just print the object affected by this
2210                          * failed ost
2211                          * */
2212                         struct obd_statfs stat_buf;
2213                         struct obd_uuid uuid_buf;
2214
2215                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
2216                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
2217                         ret = llapi_obd_statfs(path, LL_STATFS_LOV,
2218                                                param->obdindex, &stat_buf,
2219                                                &uuid_buf);
2220                         if (ret) {
2221                                 llapi_printf(LLAPI_MSG_NORMAL,
2222                                              "obd_uuid: %s failed %s ",
2223                                              param->obduuid->uuid,
2224                                              strerror(errno));
2225                                 break;
2226                         }
2227                 }
2228                 if (dir) {
2229                         ret = ioctl(dirfd(dir), IOC_LOV_GETINFO,
2230                                     (void *)param->lmd);
2231                 } else if (parent) {
2232                         ret = ioctl(dirfd(parent), IOC_LOV_GETINFO,
2233                                     (void *)param->lmd);
2234                 }
2235
2236                 if (ret) {
2237                         if (errno == ENOENT) {
2238                                 llapi_error(LLAPI_MSG_ERROR, -ENOENT,
2239                                             "warning: %s: %s does not exist",
2240                                             __func__, path);
2241                                 goto decided;
2242                         } else {
2243                                 ret = -errno;
2244                                 llapi_error(LLAPI_MSG_ERROR, ret,
2245                                             "%s: IOC_LOV_GETINFO on %s failed",
2246                                             __func__, path);
2247                                 return ret;
2248                         }
2249                 }
2250
2251                 /* Check the time on osc. */
2252                 decision = find_time_check(st, param, 0);
2253                 if (decision == -1)
2254                         goto decided;
2255
2256                 break;
2257         }
2258
2259         if (param->check_size)
2260                 decision = find_value_cmp(st->st_size, param->size,
2261                                           param->size_sign, param->exclude_size,
2262                                           param->size_units, 0);
2263
2264         if (decision != -1) {
2265                 llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
2266                 if (param->zeroend)
2267                         llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
2268                 else
2269                         llapi_printf(LLAPI_MSG_NORMAL, "\n");
2270         }
2271
2272 decided:
2273         /* Do not get down anymore? */
2274         if (param->depth == param->maxdepth)
2275                 return 1;
2276
2277         param->depth++;
2278         return 0;
2279 }
2280
2281 int llapi_find(char *path, struct find_param *param)
2282 {
2283         return param_callback(path, cb_find_init, cb_common_fini, param);
2284 }
2285
2286 /*
2287  * Get MDT number that the file/directory inode referenced
2288  * by the open fd resides on.
2289  * Return 0 and mdtidx on success, or -ve errno.
2290  */
2291 int llapi_file_fget_mdtidx(int fd, int *mdtidx)
2292 {
2293         if (ioctl(fd, LL_IOC_GET_MDTIDX, &mdtidx) < 0)
2294                 return -errno;
2295         return 0;
2296 }
2297
2298 static int cb_get_mdt_index(char *path, DIR *parent, DIR *d, void *data,
2299                             cfs_dirent_t *de)
2300 {
2301         struct find_param *param = (struct find_param *)data;
2302         int ret = 0;
2303         int mdtidx;
2304
2305         LASSERT(parent != NULL || d != NULL);
2306
2307         if (d) {
2308                 ret = llapi_file_fget_mdtidx(dirfd(d), &mdtidx);
2309         } else if (parent) {
2310                 int fd;
2311
2312                 fd = open(path, O_RDONLY);
2313                 if (fd > 0) {
2314                         ret = llapi_file_fget_mdtidx(fd, &mdtidx);
2315                         close(fd);
2316                 } else {
2317                         ret = -errno;
2318                 }
2319         }
2320
2321         if (ret) {
2322                 if (ret == -ENODATA) {
2323                         if (!param->obduuid)
2324                                 llapi_printf(LLAPI_MSG_NORMAL,
2325                                              "%s has no stripe info\n", path);
2326                         goto out;
2327                 } else if (ret == -ENOENT) {
2328                         llapi_error(LLAPI_MSG_WARN, ret,
2329                                     "warning: %s: %s does not exist",
2330                                     __func__, path);
2331                         goto out;
2332                 } else if (ret == -ENOTTY) {
2333                         llapi_error(LLAPI_MSG_ERROR, ret,
2334                                     "%s: '%s' not on a Lustre fs?",
2335                                     __func__, path);
2336                 } else {
2337                         llapi_error(LLAPI_MSG_ERROR, ret,
2338                                     "error: %s: LL_IOC_GET_MDTIDX failed for %s",
2339                                     __func__, path);
2340                 }
2341                 return ret;
2342         }
2343
2344         if (param->quiet)
2345                 llapi_printf(LLAPI_MSG_NORMAL, "%d\n", mdtidx);
2346         else
2347                 llapi_printf(LLAPI_MSG_NORMAL, "%s MDT index: %d\n",
2348                              path, mdtidx);
2349
2350 out:
2351         /* Do not get down anymore? */
2352         if (param->depth == param->maxdepth)
2353                 return 1;
2354
2355         param->depth++;
2356         return 0;
2357 }
2358
2359 static int cb_getstripe(char *path, DIR *parent, DIR *d, void *data,
2360                         cfs_dirent_t *de)
2361 {
2362         struct find_param *param = (struct find_param *)data;
2363         int ret = 0;
2364
2365         LASSERT(parent != NULL || d != NULL);
2366
2367         if (param->obduuid) {
2368                 param->quiet = 1;
2369                 ret = setup_obd_uuid(d ? d : parent, path, param);
2370                 if (ret)
2371                         return ret;
2372         }
2373
2374         if (d) {
2375                 ret = ioctl(dirfd(d), LL_IOC_LOV_GETSTRIPE,
2376                             (void *)&param->lmd->lmd_lmm);
2377         } else if (parent) {
2378                 char *fname = strrchr(path, '/');
2379                 fname = (fname == NULL ? path : fname + 1);
2380
2381                 strncpy((char *)&param->lmd->lmd_lmm, fname, param->lumlen);
2382
2383                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILESTRIPE,
2384                             (void *)&param->lmd->lmd_lmm);
2385         }
2386
2387         if (ret) {
2388                 if (errno == ENODATA && d != NULL) {
2389                         /* We need to "fake" the "use the default" values
2390                          * since the lmm struct is zeroed out at this point.
2391                          * The magic needs to be set in order to satisfy
2392                          * a check later on in the code path.
2393                          * The object_seq needs to be set for the "(Default)"
2394                          * prefix to be displayed. */
2395                         struct lov_user_md *lmm = &param->lmd->lmd_lmm;
2396                         lmm->lmm_magic = LOV_MAGIC_V1;
2397                         if (!param->raw)
2398                                 lmm->lmm_object_seq = FID_SEQ_LOV_DEFAULT;
2399                         lmm->lmm_stripe_count = 0;
2400                         lmm->lmm_stripe_size = 0;
2401                         lmm->lmm_stripe_offset = -1;
2402                         goto dump;
2403
2404                 } else if (errno == ENODATA && parent != NULL) {
2405                         if (!param->obduuid)
2406                                 llapi_printf(LLAPI_MSG_NORMAL,
2407                                              "%s has no stripe info\n", path);
2408                         goto out;
2409                 } else if (errno == ENOENT) {
2410                         llapi_error(LLAPI_MSG_WARN, -ENOENT,
2411                                     "warning: %s: %s does not exist",
2412                                     __func__, path);
2413                         goto out;
2414                 } else if (errno == ENOTTY) {
2415                         ret = -errno;
2416                         llapi_error(LLAPI_MSG_ERROR, ret,
2417                                     "%s: '%s' not on a Lustre fs?",
2418                                     __func__, path);
2419                 } else {
2420                         ret = -errno;
2421                         llapi_error(LLAPI_MSG_ERROR, ret,
2422                                     "error: %s: %s failed for %s",
2423                                      __func__, d ? "LL_IOC_LOV_GETSTRIPE" :
2424                                     "IOC_MDC_GETFILESTRIPE", path);
2425                 }
2426
2427                 return ret;
2428         }
2429
2430 dump:
2431         if (!param->get_mdt_index)
2432                 llapi_lov_dump_user_lmm(param, path, d ? 1 : 0);
2433
2434 out:
2435         /* Do not get down anymore? */
2436         if (param->depth == param->maxdepth)
2437                 return 1;
2438
2439         param->depth++;
2440         return 0;
2441 }
2442
2443 int llapi_getstripe(char *path, struct find_param *param)
2444 {
2445         return param_callback(path, param->get_mdt_index ?
2446                               cb_get_mdt_index : cb_getstripe,
2447                               cb_common_fini, param);
2448 }
2449
2450 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
2451                      struct obd_statfs *stat_buf,
2452                      struct obd_uuid *uuid_buf)
2453 {
2454         int fd;
2455         char raw[OBD_MAX_IOCTL_BUFFER] = {'\0'};
2456         char *rawbuf = raw;
2457         struct obd_ioctl_data data = { 0 };
2458         int rc = 0;
2459
2460         data.ioc_inlbuf1 = (char *)&type;
2461         data.ioc_inllen1 = sizeof(__u32);
2462         data.ioc_inlbuf2 = (char *)&index;
2463         data.ioc_inllen2 = sizeof(__u32);
2464         data.ioc_pbuf1 = (char *)stat_buf;
2465         data.ioc_plen1 = sizeof(struct obd_statfs);
2466         data.ioc_pbuf2 = (char *)uuid_buf;
2467         data.ioc_plen2 = sizeof(struct obd_uuid);
2468
2469         rc = obd_ioctl_pack(&data, &rawbuf, sizeof(raw));
2470         if (rc != 0) {
2471                 llapi_error(LLAPI_MSG_ERROR, rc,
2472                             "llapi_obd_statfs: error packing ioctl data");
2473                 return rc;
2474         }
2475
2476         fd = open(path, O_RDONLY);
2477         if (errno == EISDIR)
2478                 fd = open(path, O_DIRECTORY | O_RDONLY);
2479
2480         if (fd < 0) {
2481                 rc = errno ? -errno : -EBADF;
2482                 llapi_error(LLAPI_MSG_ERROR, rc, "error: %s: opening '%s'",
2483                             __func__, path);
2484                 return rc;
2485         }
2486         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
2487         if (rc)
2488                 rc = errno ? -errno : -EINVAL;
2489
2490         close(fd);
2491         return rc;
2492 }
2493
2494 #define MAX_STRING_SIZE 128
2495 #define DEVICES_LIST "/proc/fs/lustre/devices"
2496
2497 int llapi_ping(char *obd_type, char *obd_name)
2498 {
2499         char path[MAX_STRING_SIZE];
2500         char buf[1];
2501         int rc, fd;
2502
2503         snprintf(path, MAX_STRING_SIZE, "/proc/fs/lustre/%s/%s/ping",
2504                  obd_type, obd_name);
2505
2506         fd = open(path, O_WRONLY);
2507         if (fd < 0) {
2508                 rc = -errno;
2509                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s", path);
2510                 return rc;
2511         }
2512
2513         rc = write(fd, buf, 1);
2514         if (rc < 0)
2515                 rc = -errno;
2516         close(fd);
2517
2518         if (rc == 1)
2519                 return 0;
2520         return rc;
2521 }
2522
2523 int llapi_target_iterate(int type_num, char **obd_type,
2524                          void *args, llapi_cb_t cb)
2525 {
2526         char buf[MAX_STRING_SIZE];
2527         FILE *fp = fopen(DEVICES_LIST, "r");
2528         int i, rc = 0;
2529
2530         if (fp == NULL) {
2531                 rc = -errno;
2532                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening "DEVICES_LIST);
2533                 return rc;
2534         }
2535
2536         while (fgets(buf, sizeof(buf), fp) != NULL) {
2537                 char *obd_type_name = NULL;
2538                 char *obd_name = NULL;
2539                 char *obd_uuid = NULL;
2540                 char *bufp = buf;
2541                 struct obd_statfs osfs_buffer;
2542
2543                 while(bufp[0] == ' ')
2544                         ++bufp;
2545
2546                 for(i = 0; i < 3; i++) {
2547                         obd_type_name = strsep(&bufp, " ");
2548                 }
2549                 obd_name = strsep(&bufp, " ");
2550                 obd_uuid = strsep(&bufp, " ");
2551
2552                 memset(&osfs_buffer, 0, sizeof (osfs_buffer));
2553
2554                 for (i = 0; i < type_num; i++) {
2555                         if (strcmp(obd_type_name, obd_type[i]) != 0)
2556                                 continue;
2557
2558                         cb(obd_type_name, obd_name, obd_uuid, args);
2559                 }
2560         }
2561         fclose(fp);
2562         return 0;
2563 }
2564
2565 static void do_target_check(char *obd_type_name, char *obd_name,
2566                             char *obd_uuid, void *args)
2567 {
2568         int rc;
2569
2570         rc = llapi_ping(obd_type_name, obd_name);
2571         if (rc == ENOTCONN) {
2572                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
2573         } else if (rc) {
2574                 llapi_error(LLAPI_MSG_ERROR, rc, "error: check '%s'", obd_name);
2575         } else {
2576                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
2577         }
2578 }
2579
2580 int llapi_target_check(int type_num, char **obd_type, char *dir)
2581 {
2582         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
2583 }
2584
2585 #undef MAX_STRING_SIZE
2586
2587 int llapi_catinfo(char *dir, char *keyword, char *node_name)
2588 {
2589         char raw[OBD_MAX_IOCTL_BUFFER];
2590         char out[LLOG_CHUNK_SIZE];
2591         char *buf = raw;
2592         struct obd_ioctl_data data = { 0 };
2593         char key[30];
2594         DIR *root;
2595         int rc;
2596
2597         sprintf(key, "%s", keyword);
2598         memset(raw, 0, sizeof(raw));
2599         memset(out, 0, sizeof(out));
2600         data.ioc_inlbuf1 = key;
2601         data.ioc_inllen1 = strlen(key) + 1;
2602         if (node_name) {
2603                 data.ioc_inlbuf2 = node_name;
2604                 data.ioc_inllen2 = strlen(node_name) + 1;
2605         }
2606         data.ioc_pbuf1 = out;
2607         data.ioc_plen1 = sizeof(out);
2608         rc = obd_ioctl_pack(&data, &buf, sizeof(raw));
2609         if (rc)
2610                 return rc;
2611
2612         root = opendir(dir);
2613         if (root == NULL) {
2614                 rc = -errno;
2615                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", dir);
2616                 return rc;
2617         }
2618
2619         rc = ioctl(dirfd(root), OBD_IOC_LLOG_CATINFO, buf);
2620         if (rc) {
2621                 rc = -errno;
2622                 llapi_error(LLAPI_MSG_ERROR, rc,
2623                             "ioctl OBD_IOC_CATINFO failed");
2624         } else {
2625                 llapi_printf(LLAPI_MSG_NORMAL, "%s", data.ioc_pbuf1);
2626         }
2627
2628         closedir(root);
2629         return rc;
2630 }
2631
2632 /* Is this a lustre fs? */
2633 int llapi_is_lustre_mnttype(const char *type)
2634 {
2635         return (strcmp(type, "lustre") == 0 || strcmp(type,"lustre_lite") == 0);
2636 }
2637
2638 /* Is this a lustre client fs? */
2639 int llapi_is_lustre_mnt(struct mntent *mnt)
2640 {
2641         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
2642                 strstr(mnt->mnt_fsname, ":/") != NULL);
2643 }
2644
2645 int llapi_quotacheck(char *mnt, int check_type)
2646 {
2647         DIR *root;
2648         int rc;
2649
2650         root = opendir(mnt);
2651         if (!root) {
2652                 rc = -errno;
2653                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
2654                 return rc;
2655         }
2656
2657         rc = ioctl(dirfd(root), LL_IOC_QUOTACHECK, check_type);
2658         if (rc < 0)
2659                 rc = -errno;
2660
2661         closedir(root);
2662         return rc;
2663 }
2664
2665 int llapi_poll_quotacheck(char *mnt, struct if_quotacheck *qchk)
2666 {
2667         DIR *root;
2668         int poll_intvl = 2;
2669         int rc;
2670
2671         root = opendir(mnt);
2672         if (!root) {
2673                 rc = -errno;
2674                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
2675                 return rc;
2676         }
2677
2678         while (1) {
2679                 rc = ioctl(dirfd(root), LL_IOC_POLL_QUOTACHECK, qchk);
2680                 if (!rc)
2681                         break;
2682                 sleep(poll_intvl);
2683                 if (poll_intvl < 30)
2684                         poll_intvl *= 2;
2685         }
2686
2687         closedir(root);
2688         return 0;
2689 }
2690
2691 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
2692 {
2693         DIR *root;
2694         int rc;
2695
2696         root = opendir(mnt);
2697         if (!root) {
2698                 rc = -errno;
2699                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
2700                 return rc;
2701         }
2702
2703         rc = ioctl(dirfd(root), LL_IOC_QUOTACTL, qctl);
2704         if (rc < 0)
2705                 rc = -errno;
2706
2707         closedir(root);
2708         return rc;
2709 }
2710
2711 static int cb_quotachown(char *path, DIR *parent, DIR *d, void *data,
2712                          cfs_dirent_t *de)
2713 {
2714         struct find_param *param = (struct find_param *)data;
2715         lstat_t *st;
2716         int rc;
2717
2718         LASSERT(parent != NULL || d != NULL);
2719
2720         if (d) {
2721                 rc = ioctl(dirfd(d), LL_IOC_MDC_GETINFO,
2722                            (void *)param->lmd);
2723         } else if (parent) {
2724                 char *fname = strrchr(path, '/');
2725                 fname = (fname == NULL ? path : fname + 1);
2726
2727                 strncpy((char *)param->lmd, fname, param->lumlen);
2728                 rc = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
2729                            (void *)param->lmd);
2730         } else {
2731                 return 0;
2732         }
2733
2734         if (rc) {
2735                 if (errno == ENODATA) {
2736                         if (!param->obduuid && !param->quiet)
2737                                 llapi_error(LLAPI_MSG_ERROR, -ENODATA,
2738                                           "%s has no stripe info", path);
2739                         rc = 0;
2740                 } else if (errno == ENOENT) {
2741                         llapi_error(LLAPI_MSG_ERROR, -ENOENT,
2742                                   "warning: %s: %s does not exist",
2743                                   __func__, path);
2744                         rc = 0;
2745                 } else if (errno != EISDIR) {
2746                         rc = -errno;
2747                         llapi_error(LLAPI_MSG_ERROR, rc, "%s ioctl failed for %s.",
2748                                     d ? "LL_IOC_MDC_GETINFO" :
2749                                     "IOC_MDC_GETFILEINFO", path);
2750                 }
2751                 return rc;
2752         }
2753
2754         st = &param->lmd->lmd_st;
2755
2756         /* libc chown() will do extra check, and if the real owner is
2757          * the same as the ones to set, it won't fall into kernel, so
2758          * invoke syscall directly. */
2759         rc = syscall(SYS_chown, path, -1, -1);
2760         if (rc)
2761                 llapi_error(LLAPI_MSG_ERROR, errno,
2762                             "error: chown %s", path);
2763
2764         rc = chmod(path, st->st_mode);
2765         if (rc) {
2766                 rc = -errno;
2767                 llapi_error(LLAPI_MSG_ERROR, rc, "error: chmod %s (%hu)",
2768                             path, st->st_mode);
2769         }
2770
2771         return rc;
2772 }
2773
2774 int llapi_quotachown(char *path, int flag)
2775 {
2776         struct find_param param;
2777
2778         memset(&param, 0, sizeof(param));
2779         param.recursive = 1;
2780         param.verbose = 0;
2781         param.quiet = 1;
2782
2783         return param_callback(path, cb_quotachown, NULL, &param);
2784 }
2785
2786 #include <pwd.h>
2787 #include <grp.h>
2788 #include <mntent.h>
2789 #include <sys/wait.h>
2790 #include <errno.h>
2791 #include <ctype.h>
2792
2793 static int rmtacl_notify(int ops)
2794 {
2795         FILE *fp;
2796         struct mntent *mnt;
2797         int found = 0, fd, rc;
2798
2799         fp = setmntent(MOUNTED, "r");
2800         if (fp == NULL) {
2801                 rc = -errno;
2802                 llapi_error(LLAPI_MSG_ERROR, rc,
2803                             "error setmntent(%s)", MOUNTED);
2804                 return rc;
2805         }
2806
2807         while (1) {
2808                 mnt = getmntent(fp);
2809                 if (!mnt)
2810                         break;
2811
2812                 if (!llapi_is_lustre_mnt(mnt))
2813                         continue;
2814
2815                 fd = open(mnt->mnt_dir, O_RDONLY | O_DIRECTORY);
2816                 if (fd < 0) {
2817                         rc = -errno;
2818                         llapi_error(LLAPI_MSG_ERROR, rc,
2819                                     "Can't open '%s'\n", mnt->mnt_dir);
2820                         return rc;
2821                 }
2822
2823                 rc = ioctl(fd, LL_IOC_RMTACL, ops);
2824                 if (rc < 0) {
2825                         rc = -errno;
2826                         llapi_error(LLAPI_MSG_ERROR, rc, "ioctl %d\n", fd);
2827                         return rc;
2828                 }
2829
2830                 found++;
2831         }
2832         endmntent(fp);
2833         return found;
2834 }
2835
2836 static char *next_token(char *p, int div)
2837 {
2838         if (p == NULL)
2839                 return NULL;
2840
2841         if (div)
2842                 while (*p && *p != ':' && !isspace(*p))
2843                         p++;
2844         else
2845                 while (*p == ':' || isspace(*p))
2846                         p++;
2847
2848         return *p ? p : NULL;
2849 }
2850
2851 static int rmtacl_name2id(char *name, int is_user)
2852 {
2853         if (is_user) {
2854                 struct passwd *pw;
2855
2856                 pw = getpwnam(name);
2857                 if (pw == NULL)
2858                         return INVALID_ID;
2859                 else
2860                         return (int)(pw->pw_uid);
2861         } else {
2862                 struct group *gr;
2863
2864                 gr = getgrnam(name);
2865                 if (gr == NULL)
2866                         return INVALID_ID;
2867                 else
2868                         return (int)(gr->gr_gid);
2869         }
2870 }
2871
2872 static int isodigit(int c)
2873 {
2874         return (c >= '0' && c <= '7') ? 1 : 0;
2875 }
2876
2877 /*
2878  * Whether the name is just digits string (uid/gid) already or not.
2879  * Return value:
2880  * 1: str is id
2881  * 0: str is not id
2882  */
2883 static int str_is_id(char *str)
2884 {
2885         if (str == NULL)
2886                 return 0;
2887
2888         if (*str == '0') {
2889                 str++;
2890                 if (*str == 'x' || *str == 'X') { /* for Hex. */
2891                         if (!isxdigit(*(++str)))
2892                                 return 0;
2893
2894                         while (isxdigit(*(++str)));
2895                 } else if (isodigit(*str)) { /* for Oct. */
2896                         while (isodigit(*(++str)));
2897                 }
2898         } else if (isdigit(*str)) { /* for Dec. */
2899                 while (isdigit(*(++str)));
2900         }
2901
2902         return (*str == 0) ? 1 : 0;
2903 }
2904
2905 typedef struct {
2906         char *name;
2907         int   length;
2908         int   is_user;
2909         int   next_token;
2910 } rmtacl_name_t;
2911
2912 #define RMTACL_OPTNAME(name) name, sizeof(name) - 1
2913
2914 static rmtacl_name_t rmtacl_namelist[] = {
2915         { RMTACL_OPTNAME("user:"),            1,      0 },
2916         { RMTACL_OPTNAME("group:"),           0,      0 },
2917         { RMTACL_OPTNAME("default:user:"),    1,      0 },
2918         { RMTACL_OPTNAME("default:group:"),   0,      0 },
2919         /* for --tabular option */
2920         { RMTACL_OPTNAME("user"),             1,      1 },
2921         { RMTACL_OPTNAME("group"),            0,      1 },
2922         { 0 }
2923 };
2924
2925 static int rgetfacl_output(char *str)
2926 {
2927         char *start = NULL, *end = NULL;
2928         int is_user = 0, n, id;
2929         char c;
2930         rmtacl_name_t *rn;
2931
2932         if (str == NULL)
2933                 return -1;
2934
2935         for (rn = rmtacl_namelist; rn->name; rn++) {
2936                 if(strncmp(str, rn->name, rn->length) == 0) {
2937                         if (!rn->next_token)
2938                                 start = str + rn->length;
2939                         else
2940                                 start = next_token(str + rn->length, 0);
2941                         is_user = rn->is_user;
2942                         break;
2943                 }
2944         }
2945
2946         end = next_token(start, 1);
2947         if (end == NULL || start == end) {
2948                 n = printf("%s", str);
2949                 return n;
2950         }
2951
2952         c = *end;
2953         *end = 0;
2954         id = rmtacl_name2id(start, is_user);
2955         if (id == INVALID_ID) {
2956                 if (str_is_id(start)) {
2957                         *end = c;
2958                         n = printf("%s", str);
2959                 } else
2960                         return -1;
2961         } else if ((id == NOBODY_UID && is_user) ||
2962                    (id == NOBODY_GID && !is_user)) {
2963                 *end = c;
2964                 n = printf("%s", str);
2965         } else {
2966                 *end = c;
2967                 *start = 0;
2968                 n = printf("%s%d%s", str, id, end);
2969         }
2970         return n;
2971 }
2972
2973 static int child_status(int status)
2974 {
2975         return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
2976 }
2977
2978 static int do_rmtacl(int argc, char *argv[], int ops, int (output_func)(char *))
2979 {
2980         pid_t pid = 0;
2981         int fd[2], status, rc;
2982         FILE *fp;
2983         char buf[PIPE_BUF];
2984
2985         if (output_func) {
2986                 if (pipe(fd) < 0) {
2987                         rc = -errno;
2988                         llapi_error(LLAPI_MSG_ERROR, rc, "Can't create pipe\n");
2989                         return rc;
2990                 }
2991
2992                 pid = fork();
2993                 if (pid < 0) {
2994                         rc = -errno;
2995                         llapi_error(LLAPI_MSG_ERROR, rc, "Can't fork\n");
2996                         close(fd[0]);
2997                         close(fd[1]);
2998                         return rc;
2999                 } else if (!pid) {
3000                         /* child process redirects its output. */
3001                         close(fd[0]);
3002                         close(1);
3003                         if (dup2(fd[1], 1) < 0) {
3004                                 rc = -errno;
3005                                 llapi_error(LLAPI_MSG_ERROR, rc,
3006                                             "Can't dup2 %d\n", fd[1]);
3007                                 close(fd[1]);
3008                                 return rc;
3009                         }
3010                 } else {
3011                         close(fd[1]);
3012                 }
3013         }
3014
3015         if (!pid) {
3016                 status = rmtacl_notify(ops);
3017                 if (status < 0)
3018                         return -errno;
3019
3020                 exit(execvp(argv[0], argv));
3021         }
3022
3023         /* the following is parent process */
3024         fp = fdopen(fd[0], "r");
3025         if (fp == NULL) {
3026                 rc = -errno;
3027                 llapi_error(LLAPI_MSG_ERROR, rc, "fdopen %d failed\n", fd[0]);
3028                 kill(pid, SIGKILL);
3029                 close(fd[0]);
3030                 return rc;
3031         }
3032
3033         while (fgets(buf, PIPE_BUF, fp) != NULL) {
3034                 if (output_func(buf) < 0)
3035                         fprintf(stderr, "WARNING: unexpected error!\n[%s]\n",
3036                                 buf);
3037         }
3038         fclose(fp);
3039         close(fd[0]);
3040
3041         if (waitpid(pid, &status, 0) < 0) {
3042                 rc = -errno;
3043                 llapi_error(LLAPI_MSG_ERROR, rc, "waitpid %d failed\n", pid);
3044                 return rc;
3045         }
3046
3047         return child_status(status);
3048 }
3049
3050 int llapi_lsetfacl(int argc, char *argv[])
3051 {
3052         return do_rmtacl(argc, argv, RMT_LSETFACL, NULL);
3053 }
3054
3055 int llapi_lgetfacl(int argc, char *argv[])
3056 {
3057         return do_rmtacl(argc, argv, RMT_LGETFACL, NULL);
3058 }
3059
3060 int llapi_rsetfacl(int argc, char *argv[])
3061 {
3062         return do_rmtacl(argc, argv, RMT_RSETFACL, NULL);
3063 }
3064
3065 int llapi_rgetfacl(int argc, char *argv[])
3066 {
3067         return do_rmtacl(argc, argv, RMT_RGETFACL, rgetfacl_output);
3068 }
3069
3070 int llapi_cp(int argc, char *argv[])
3071 {
3072         int rc;
3073
3074         rc = rmtacl_notify(RMT_RSETFACL);
3075         if (rc < 0)
3076                 return rc;
3077
3078         exit(execvp(argv[0], argv));
3079 }
3080
3081 int llapi_ls(int argc, char *argv[])
3082 {
3083         int rc;
3084
3085         rc = rmtacl_notify(RMT_LGETFACL);
3086         if (rc < 0)
3087                 return rc;
3088
3089         exit(execvp(argv[0], argv));
3090 }
3091
3092 /* Print mdtname 'name' into 'buf' using 'format'.  Add -MDT0000 if needed.
3093  * format must have %s%s, buf must be > 16
3094  * Eg: if name = "lustre-MDT0000", "lustre", or "lustre-MDT0000_UUID"
3095  *     then buf = "lustre-MDT0000"
3096  */
3097 static int get_mdtname(char *name, char *format, char *buf)
3098 {
3099         char suffix[]="-MDT0000";
3100         int len = strlen(name);
3101
3102         if ((len > 5) && (strncmp(name + len - 5, "_UUID", 5) == 0)) {
3103                 name[len - 5] = '\0';
3104                 len -= 5;
3105         }
3106
3107         if (len > 8) {
3108                 if ((len <= 16) && strncmp(name + len - 8, "-MDT", 4) == 0) {
3109                         suffix[0] = '\0';
3110                 } else {
3111                         /* Not enough room to add suffix */
3112                         llapi_err_noerrno(LLAPI_MSG_ERROR,
3113                                           "MDT name too long |%s|", name);
3114                         return -EINVAL;
3115                 }
3116         }
3117
3118         return sprintf(buf, format, name, suffix);
3119 }
3120
3121 /** ioctl on filsystem root, with mdtindex sent as data
3122  * \param mdtname path, fsname, or mdtname (lutre-MDT0004)
3123  * \param mdtidxp pointer to integer within data to be filled in with the
3124  *    mdt index (0 if no mdt is specified).  NULL won't be filled.
3125  */
3126 static int root_ioctl(const char *mdtname, int opc, void *data, int *mdtidxp,
3127                       int want_error)
3128 {
3129         char fsname[20];
3130         char *ptr;
3131         int fd, index, rc;
3132
3133         /* Take path, fsname, or MDTname.  Assume MDT0000 in the former cases.
3134          Open root and parse mdt index. */
3135         if (mdtname[0] == '/') {
3136                 index = 0;
3137                 rc = get_root_path(WANT_FD | want_error, NULL, &fd,
3138                                    (char *)mdtname, -1);
3139         } else {
3140                 if (get_mdtname((char *)mdtname, "%s%s", fsname) < 0)
3141                         return -EINVAL;
3142                 ptr = fsname + strlen(fsname) - 8;
3143                 *ptr = '\0';
3144                 index = strtol(ptr + 4, NULL, 10);
3145                 rc = get_root_path(WANT_FD | want_error, fsname, &fd, NULL, -1);
3146         }
3147         if (rc < 0) {
3148                 if (want_error)
3149                         llapi_err_noerrno(LLAPI_MSG_ERROR,
3150                                           "Can't open %s: %d\n", mdtname, rc);
3151                 return rc;
3152         }
3153
3154         if (mdtidxp)
3155                 *mdtidxp = index;
3156
3157         rc = ioctl(fd, opc, data);
3158         if (rc == -1)
3159                 rc = -errno;
3160         else
3161                 rc = 0;
3162         if (rc && want_error)
3163                 llapi_error(LLAPI_MSG_ERROR, rc, "ioctl %d err %d", opc, rc);
3164
3165         close(fd);
3166         return rc;
3167 }
3168
3169 /****** Changelog API ********/
3170
3171 static int changelog_ioctl(const char *mdtname, int opc, int id,
3172                            long long recno, int flags)
3173 {
3174         struct ioc_changelog data;
3175         int *idx;
3176
3177         data.icc_id = id;
3178         data.icc_recno = recno;
3179         data.icc_flags = flags;
3180         idx = (int *)(&data.icc_mdtindex);
3181
3182         return root_ioctl(mdtname, opc, &data, idx, WANT_ERROR);
3183 }
3184
3185 #define CHANGELOG_PRIV_MAGIC 0xCA8E1080
3186 struct changelog_private {
3187         int magic;
3188         int flags;
3189         lustre_kernelcomm kuc;
3190 };
3191
3192 /** Start reading from a changelog
3193  * @param priv Opaque private control structure
3194  * @param flags Start flags (e.g. CHANGELOG_FLAG_BLOCK)
3195  * @param device Report changes recorded on this MDT
3196  * @param startrec Report changes beginning with this record number
3197  * (just call llapi_changelog_fini when done; don't need an endrec)
3198  */
3199 int llapi_changelog_start(void **priv, int flags, const char *device,
3200                           long long startrec)
3201 {
3202         struct changelog_private *cp;
3203         int rc;
3204
3205         /* Set up the receiver control struct */
3206         cp = calloc(1, sizeof(*cp));
3207         if (cp == NULL)
3208                 return -ENOMEM;
3209
3210         cp->magic = CHANGELOG_PRIV_MAGIC;
3211         cp->flags = flags;
3212
3213         /* Set up the receiver */
3214         rc = libcfs_ukuc_start(&cp->kuc, 0 /* no group registration */);
3215         if (rc < 0)
3216                 goto out_free;
3217
3218         *priv = cp;
3219
3220         /* Tell the kernel to start sending */
3221         rc = changelog_ioctl(device, OBD_IOC_CHANGELOG_SEND, cp->kuc.lk_wfd,
3222                              startrec, flags);
3223         /* Only the kernel reference keeps the write side open */
3224         close(cp->kuc.lk_wfd);
3225         cp->kuc.lk_wfd = 0;
3226         if (rc < 0) {
3227                 /* frees and clears priv */
3228                 llapi_changelog_fini(priv);
3229                 return rc;
3230         }
3231
3232         return 0;
3233
3234 out_free:
3235         free(cp);
3236         return rc;
3237 }
3238
3239 /** Finish reading from a changelog */
3240 int llapi_changelog_fini(void **priv)
3241 {
3242         struct changelog_private *cp = (struct changelog_private *)*priv;
3243
3244         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
3245                 return -EINVAL;
3246
3247         libcfs_ukuc_stop(&cp->kuc);
3248         free(cp);
3249         *priv = NULL;
3250         return 0;
3251 }
3252
3253 /** Read the next changelog entry
3254  * @param priv Opaque private control structure
3255  * @param rech Changelog record handle; record will be allocated here
3256  * @return 0 valid message received; rec is set
3257  *         <0 error code
3258  *         1 EOF
3259  */
3260 int llapi_changelog_recv(void *priv, struct changelog_rec **rech)
3261 {
3262         struct changelog_private *cp = (struct changelog_private *)priv;
3263         struct kuc_hdr *kuch;
3264         int rc = 0;
3265
3266         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
3267                 return -EINVAL;
3268         if (rech == NULL)
3269                 return -EINVAL;
3270         kuch = malloc(CR_MAXSIZE + sizeof(*kuch));
3271         if (kuch == NULL)
3272                 return -ENOMEM;
3273
3274 repeat:
3275         rc = libcfs_ukuc_msg_get(&cp->kuc, (char *)kuch,
3276                                  CR_MAXSIZE + sizeof(*kuch),
3277                                  KUC_TRANSPORT_CHANGELOG);
3278         if (rc < 0)
3279                 goto out_free;
3280
3281         if ((kuch->kuc_transport != KUC_TRANSPORT_CHANGELOG) ||
3282             ((kuch->kuc_msgtype != CL_RECORD) &&
3283              (kuch->kuc_msgtype != CL_EOF))) {
3284                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3285                                   "Unknown changelog message type %d:%d\n",
3286                                   kuch->kuc_transport, kuch->kuc_msgtype);
3287                 rc = -EPROTO;
3288                 goto out_free;
3289         }
3290
3291         if (kuch->kuc_msgtype == CL_EOF) {
3292                 if (cp->flags & CHANGELOG_FLAG_FOLLOW) {
3293                         /* Ignore EOFs */
3294                         goto repeat;
3295                 } else {
3296                         rc = 1;
3297                         goto out_free;
3298                 }
3299         }
3300
3301         /* Our message is a changelog_rec.  Use pointer math to skip
3302          * kuch_hdr and point directly to the message payload.
3303          */
3304         *rech = (struct changelog_rec *)(kuch + 1);
3305
3306         return 0;
3307
3308 out_free:
3309         *rech = NULL;
3310         free(kuch);
3311         return rc;
3312 }
3313
3314 /** Release the changelog record when done with it. */
3315 int llapi_changelog_free(struct changelog_rec **rech)
3316 {
3317         if (*rech) {
3318                 /* We allocated memory starting at the kuc_hdr, but passed
3319                  * the consumer a pointer to the payload.
3320                  * Use pointer math to get back to the header.
3321                  */
3322                 struct kuc_hdr *kuch = (struct kuc_hdr *)*rech - 1;
3323                 free(kuch);
3324         }
3325         *rech = NULL;
3326         return 0;
3327 }
3328
3329 int llapi_changelog_clear(const char *mdtname, const char *idstr,
3330                           long long endrec)
3331 {
3332         int id;
3333
3334         if (endrec < 0) {
3335                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3336                                   "can't purge negative records\n");
3337                 return -EINVAL;
3338         }
3339
3340         id = strtol(idstr + strlen(CHANGELOG_USER_PREFIX), NULL, 10);
3341         if ((id == 0) || (strncmp(idstr, CHANGELOG_USER_PREFIX,
3342                                   strlen(CHANGELOG_USER_PREFIX)) != 0)) {
3343                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3344                                   "expecting id of the form '"
3345                                   CHANGELOG_USER_PREFIX
3346                                   "<num>'; got '%s'\n", idstr);
3347                 return -EINVAL;
3348         }
3349
3350         return changelog_ioctl(mdtname, OBD_IOC_CHANGELOG_CLEAR, id, endrec, 0);
3351 }
3352
3353 int llapi_fid2path(const char *device, const char *fidstr, char *buf,
3354                    int buflen, long long *recno, int *linkno)
3355 {
3356         struct lu_fid fid;
3357         struct getinfo_fid2path *gf;
3358         int rc;
3359
3360         while (*fidstr == '[')
3361                 fidstr++;
3362
3363         sscanf(fidstr, SFID, RFID(&fid));
3364         if (!fid_is_sane(&fid)) {
3365                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3366                                   "bad FID format [%s], should be "DFID"\n",
3367                                   fidstr, (__u64)1, 2, 0);
3368                 return -EINVAL;
3369         }
3370
3371         gf = malloc(sizeof(*gf) + buflen);
3372         if (gf == NULL)
3373                 return -ENOMEM;
3374         gf->gf_fid = fid;
3375         gf->gf_recno = *recno;
3376         gf->gf_linkno = *linkno;
3377         gf->gf_pathlen = buflen;
3378
3379         /* Take path or fsname */
3380         rc = root_ioctl(device, OBD_IOC_FID2PATH, gf, NULL, 0);
3381         if (rc) {
3382                 if (rc != -ENOENT)
3383                         llapi_error(LLAPI_MSG_ERROR, rc, "ioctl err %d", rc);
3384         } else {
3385                 memcpy(buf, gf->gf_path, gf->gf_pathlen);
3386                 *recno = gf->gf_recno;
3387                 *linkno = gf->gf_linkno;
3388         }
3389
3390         free(gf);
3391         return rc;
3392 }
3393
3394 static int path2fid_from_lma(const char *path, lustre_fid *fid)
3395 {
3396         char buf[512];
3397         struct lustre_mdt_attrs *lma;
3398         int rc;
3399
3400         rc = lgetxattr(path, XATTR_NAME_LMA, buf, sizeof(buf));
3401         if (rc < 0)
3402                 return -errno;
3403         lma = (struct lustre_mdt_attrs *)buf;
3404         fid_le_to_cpu(fid, &lma->lma_self_fid);
3405         return 0;
3406 }
3407
3408 int llapi_path2fid(const char *path, lustre_fid *fid)
3409 {
3410         int fd, rc;
3411
3412         memset(fid, 0, sizeof(*fid));
3413         fd = open(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
3414         if (fd < 0) {
3415                 if (errno == ELOOP) /* symbolic link */
3416                         return path2fid_from_lma(path, fid);
3417                 return -errno;
3418         }
3419
3420         rc = ioctl(fd, LL_IOC_PATH2FID, fid) < 0 ? -errno : 0;
3421         if (rc == -EINVAL) /* char special device */
3422                 rc = path2fid_from_lma(path, fid);
3423
3424         close(fd);
3425         return rc;
3426 }
3427
3428 /****** HSM Copytool API ********/
3429 #define CT_PRIV_MAGIC 0xC0BE2001
3430 struct copytool_private {
3431         int magic;
3432         char *fsname;
3433         lustre_kernelcomm kuc;
3434         __u32 archives;
3435 };
3436
3437 #include <libcfs/libcfs.h>
3438
3439 /** Register a copytool
3440  * @param[out] priv Opaque private control structure
3441  * @param fsname Lustre filesystem
3442  * @param flags Open flags, currently unused (e.g. O_NONBLOCK)
3443  * @param archive_count
3444  * @param archives Which archive numbers this copytool is responsible for
3445  */
3446 int llapi_copytool_start(void **priv, char *fsname, int flags,
3447                          int archive_count, int *archives)
3448 {
3449         struct copytool_private *ct;
3450         int rc;
3451
3452         if (archive_count > 0 && archives == NULL) {
3453                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3454                                   "NULL archive numbers");
3455                 return -EINVAL;
3456         }
3457
3458         ct = calloc(1, sizeof(*ct));
3459         if (ct == NULL)
3460                 return -ENOMEM;
3461
3462         ct->fsname = malloc(strlen(fsname) + 1);
3463         if (ct->fsname == NULL) {
3464                 rc = -ENOMEM;
3465                 goto out_err;
3466         }
3467         strcpy(ct->fsname, fsname);
3468         ct->magic = CT_PRIV_MAGIC;
3469         ct->archives = 0;
3470         for (rc = 0; rc < archive_count; rc++) {
3471                 if (archives[rc] > sizeof(ct->archives)) {
3472                         llapi_err_noerrno(LLAPI_MSG_ERROR,
3473                                           "Maximum of %d archives supported",
3474                                           sizeof(ct->archives));
3475                         goto out_err;
3476                 }
3477                 ct->archives |= 1 << archives[rc];
3478         }
3479         /* special case: if no archives specified, default to archive #0. */
3480         if (ct->archives == 0)
3481                 ct->archives = 1;
3482
3483         rc = libcfs_ukuc_start(&ct->kuc, KUC_GRP_HSM);
3484         if (rc < 0)
3485                 goto out_err;
3486
3487         /* Storing archive(s) in lk_data; see mdc_ioc_hsm_ct_start */
3488         ct->kuc.lk_data = ct->archives;
3489         rc = root_ioctl(ct->fsname, LL_IOC_HSM_CT_START, &(ct->kuc), NULL,
3490                         WANT_ERROR);
3491         /* Only the kernel reference keeps the write side open */
3492         close(ct->kuc.lk_wfd);
3493         ct->kuc.lk_wfd = 0;
3494         if (rc < 0)
3495                 goto out_err;
3496
3497         *priv = ct;
3498         return 0;
3499
3500 out_err:
3501         if (ct->fsname)
3502                 free(ct->fsname);
3503         free(ct);
3504         return rc;
3505 }
3506
3507 /** Deregister a copytool */
3508 int llapi_copytool_fini(void **priv)
3509 {
3510         struct copytool_private *ct = (struct copytool_private *)*priv;
3511
3512         if (!ct || (ct->magic != CT_PRIV_MAGIC))
3513                 return -EINVAL;
3514
3515         /* Tell the kernel to stop sending us messages */
3516         ct->kuc.lk_flags = LK_FLG_STOP;
3517         root_ioctl(ct->fsname, LL_IOC_HSM_CT_START, &(ct->kuc), NULL, 0);
3518
3519         /* Shut down the kernelcomms */
3520         libcfs_ukuc_stop(&ct->kuc);
3521
3522         free(ct->fsname);
3523         free(ct);
3524         *priv = NULL;
3525         return 0;
3526 }
3527
3528 /** Wait for the next hsm_action_list
3529  * @param priv Opaque private control structure
3530  * @param halh Action list handle, will be allocated here
3531  * @param msgsize Number of bytes in the message, will be set here
3532  * @return 0 valid message received; halh and msgsize are set
3533  *         <0 error code
3534  */
3535 int llapi_copytool_recv(void *priv, struct hsm_action_list **halh, int *msgsize)
3536 {
3537         struct copytool_private *ct = (struct copytool_private *)priv;
3538         struct kuc_hdr *kuch;
3539         struct hsm_action_list *hal;
3540         int rc = 0;
3541
3542         if (!ct || (ct->magic != CT_PRIV_MAGIC))
3543                 return -EINVAL;
3544         if (halh == NULL || msgsize == NULL)
3545                 return -EINVAL;
3546
3547         kuch = malloc(HAL_MAXSIZE + sizeof(*kuch));
3548         if (kuch == NULL)
3549                 return -ENOMEM;
3550
3551         rc = libcfs_ukuc_msg_get(&ct->kuc, (char *)kuch,
3552                                  HAL_MAXSIZE + sizeof(*kuch),
3553                                  KUC_TRANSPORT_HSM);
3554         if (rc < 0)
3555                 goto out_free;
3556
3557         /* Handle generic messages */
3558         if (kuch->kuc_transport == KUC_TRANSPORT_GENERIC &&
3559             kuch->kuc_msgtype == KUC_MSG_SHUTDOWN) {
3560                 rc = -ESHUTDOWN;
3561                 goto out_free;
3562         }
3563
3564         if (kuch->kuc_transport != KUC_TRANSPORT_HSM ||
3565             kuch->kuc_msgtype != HMT_ACTION_LIST) {
3566                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3567                                   "Unknown HSM message type %d:%d\n",
3568                                   kuch->kuc_transport, kuch->kuc_msgtype);
3569                 rc = -EPROTO;
3570                 goto out_free;
3571         }
3572
3573         /* Our message is a hsm_action_list.  Use pointer math to skip
3574          * kuch_hdr and point directly to the message payload.
3575          */
3576         hal = (struct hsm_action_list *)(kuch + 1);
3577
3578         /* Check that we have registered for this archive # */
3579         if (((1 << hal->hal_archive_num) & ct->archives) == 0) {
3580                     llapi_err_noerrno(LLAPI_MSG_INFO,
3581                              "Ignoring request for archive #%d (bitmask %#x)\n",
3582                              hal->hal_archive_num, ct->archives);
3583                 rc = 0;
3584                 goto out_free;
3585         }
3586
3587         *halh = hal;
3588         *msgsize = kuch->kuc_msglen - sizeof(*kuch);
3589         return 0;
3590
3591 out_free:
3592         *halh = NULL;
3593         *msgsize = 0;
3594         free(kuch);
3595         return rc;
3596 }
3597
3598 /** Release the action list when done with it. */
3599 int llapi_copytool_free(struct hsm_action_list **hal)
3600 {
3601         /* Reuse the llapi_changelog_free function */
3602         return llapi_changelog_free((struct changelog_rec **)hal);
3603 }
3604
3605 int llapi_get_connect_flags(const char *mnt, __u64 *flags)
3606 {
3607         DIR *root;
3608         int rc;
3609
3610         root = opendir(mnt);
3611         if (!root) {
3612                 rc = -errno;
3613                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
3614                 return rc;
3615         }
3616
3617         rc = ioctl(dirfd(root), LL_IOC_GET_CONNECT_FLAGS, flags);
3618         if (rc < 0) {
3619                 rc = -errno;
3620                 llapi_error(LLAPI_MSG_ERROR, rc,
3621                             "ioctl on %s for getting connect flags failed", mnt);
3622         }
3623         closedir(root);
3624         return rc;
3625 }
3626
3627 int llapi_get_version(char *buffer, int buffer_size,
3628                       char **version)
3629 {
3630         int rc;
3631         int fd;
3632         struct obd_ioctl_data *data = (struct obd_ioctl_data *)buffer;
3633
3634         fd = open(OBD_DEV_PATH, O_RDONLY);
3635         if (fd == -1)
3636                 return -errno;
3637
3638         memset(buffer, 0, buffer_size);
3639         data->ioc_version = OBD_IOCTL_VERSION;
3640         data->ioc_inllen1 = buffer_size - cfs_size_round(sizeof(*data));
3641         data->ioc_inlbuf1 = buffer + cfs_size_round(sizeof(*data));
3642         data->ioc_len = obd_ioctl_packlen(data);
3643
3644         rc = ioctl(fd, OBD_GET_VERSION, buffer);
3645         if (rc == -1) {
3646                 rc = -errno;
3647                 close(fd);
3648                 return rc;
3649         }
3650         close(fd);
3651         *version = data->ioc_bulk;
3652         return 0;
3653 }