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