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