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