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