Whamcloud - gitweb
b=20878 change kernelcomms from netlink to pipes
[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  2008 Sun Microsystems, Inc. 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                 mntlen = strlen(mnt.mnt_dir);
524                 ptr = strrchr(mnt.mnt_fsname, '/');
525                 if (!ptr && !len) {
526                         rc = -EINVAL;
527                         break;
528                 }
529                 ptr++;
530
531                 if ((want & WANT_INDEX) && (idx++ != index))
532                         continue;
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) {
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         return get_root_path(WANT_FSNAME | WANT_ERROR, fsname, NULL,
610                              (char *)pathname, -1);
611 }
612
613 /* return the first file matching this pattern */
614 static int first_match(char *pattern, char *buffer)
615 {
616         glob_t glob_info;
617
618         if (glob(pattern, GLOB_BRACE, NULL, &glob_info))
619                 return -ENOENT;
620
621         if (glob_info.gl_pathc < 1) {
622                 globfree(&glob_info);
623                 return -ENOENT;
624         }
625
626         strcpy(buffer, glob_info.gl_pathv[0]);
627
628         globfree(&glob_info);
629         return 0;
630 }
631
632 /*
633  * find the pool directory path under /proc
634  * (can be also used to test if a fsname is known)
635  */
636 static int poolpath(char *fsname, char *pathname, char *pool_pathname)
637 {
638         int rc = 0;
639         char pattern[PATH_MAX + 1];
640         char buffer[PATH_MAX];
641
642         if (fsname == NULL) {
643                 rc = llapi_search_fsname(pathname, buffer);
644                 if (rc != 0)
645                         return rc;
646                 fsname = buffer;
647                 strcpy(pathname, fsname);
648         }
649
650         snprintf(pattern, PATH_MAX, "/proc/fs/lustre/lov/%s-*/pools", fsname);
651         rc = first_match(pattern, buffer);
652         if (rc)
653                 return rc;
654
655         /* in fsname test mode, pool_pathname is NULL */
656         if (pool_pathname != NULL)
657                 strcpy(pool_pathname, buffer);
658
659         return 0;
660 }
661
662 /**
663  * Get the list of pool members.
664  * \param poolname    string of format \<fsname\>.\<poolname\>
665  * \param members     caller-allocated array of char*
666  * \param list_size   size of the members array
667  * \param buffer      caller-allocated buffer for storing OST names
668  * \param buffer_size size of the buffer
669  *
670  * \return number of members retrieved for this pool
671  * \retval -error failure
672  */
673 int llapi_get_poolmembers(const char *poolname, char **members,
674                           int list_size, char *buffer, int buffer_size)
675 {
676         char fsname[PATH_MAX + 1];
677         char *pool, *tmp;
678         char pathname[PATH_MAX + 1];
679         char path[PATH_MAX + 1];
680         char buf[1024];
681         FILE *fd;
682         int rc = 0;
683         int nb_entries = 0;
684         int used = 0;
685
686         /* name is FSNAME.POOLNAME */
687         if (strlen(poolname) > PATH_MAX)
688                 return -EOVERFLOW;
689         strcpy(fsname, poolname);
690         pool = strchr(fsname, '.');
691         if (pool == NULL)
692                 return -EINVAL;
693
694         *pool = '\0';
695         pool++;
696
697         rc = poolpath(fsname, NULL, pathname);
698         if (rc != 0) {
699                 errno = -rc;
700                 llapi_err(LLAPI_MSG_ERROR, "Lustre filesystem '%s' not found",
701                           fsname);
702                 return rc;
703         }
704
705         llapi_printf(LLAPI_MSG_NORMAL, "Pool: %s.%s\n", fsname, pool);
706         sprintf(path, "%s/%s", pathname, pool);
707         if ((fd = fopen(path, "r")) == NULL) {
708                 llapi_err(LLAPI_MSG_ERROR, "Cannot open %s", path);
709                 return -EINVAL;
710         }
711
712         rc = 0;
713         while (fgets(buf, sizeof(buf), fd) != NULL) {
714                 if (nb_entries >= list_size) {
715                         rc = -EOVERFLOW;
716                         break;
717                 }
718                 /* remove '\n' */
719                 if ((tmp = strchr(buf, '\n')) != NULL)
720                         *tmp='\0';
721                 if (used + strlen(buf) + 1 > buffer_size) {
722                         rc = -EOVERFLOW;
723                         break;
724                 }
725
726                 strcpy(buffer + used, buf);
727                 members[nb_entries] = buffer + used;
728                 used += strlen(buf) + 1;
729                 nb_entries++;
730                 rc = nb_entries;
731         }
732
733         fclose(fd);
734         return rc;
735 }
736
737 /**
738  * Get the list of pools in a filesystem.
739  * \param name        filesystem name or path
740  * \param poollist    caller-allocated array of char*
741  * \param list_size   size of the poollist array
742  * \param buffer      caller-allocated buffer for storing pool names
743  * \param buffer_size size of the buffer
744  *
745  * \return number of pools retrieved for this filesystem
746  * \retval -error failure
747  */
748 int llapi_get_poollist(const char *name, char **poollist, int list_size,
749                        char *buffer, int buffer_size)
750 {
751         char fsname[PATH_MAX + 1], rname[PATH_MAX + 1], pathname[PATH_MAX + 1];
752         char *ptr;
753         DIR *dir;
754         struct dirent pool;
755         struct dirent *cookie = NULL;
756         int rc = 0;
757         unsigned int nb_entries = 0;
758         unsigned int used = 0;
759         unsigned int i;
760
761         /* initilize output array */
762         for (i = 0; i < list_size; i++)
763                 poollist[i] = NULL;
764
765         /* is name a pathname ? */
766         ptr = strchr(name, '/');
767         if (ptr != NULL) {
768                 /* only absolute pathname is supported */
769                 if (*name != '/')
770                         return -EINVAL;
771                 if (!realpath(name, rname)) {
772                         rc = -errno;
773                         llapi_err(LLAPI_MSG_ERROR, "invalid path '%s'", name);
774                         return rc;
775                 }
776
777                 rc = poolpath(NULL, rname, pathname);
778                 if (rc != 0) {
779                         errno = -rc;
780                         llapi_err(LLAPI_MSG_ERROR, "'%s' is not"
781                                   " a Lustre filesystem", name);
782                         return rc;
783                 }
784                 strcpy(fsname, rname);
785         } else {
786                 /* name is FSNAME */
787                 strcpy(fsname, name);
788                 rc = poolpath(fsname, NULL, pathname);
789         }
790         if (rc != 0) {
791                 errno = -rc;
792                 llapi_err(LLAPI_MSG_ERROR, "Lustre filesystem '%s' not found",
793                           name);
794                 return rc;
795         }
796
797         llapi_printf(LLAPI_MSG_NORMAL, "Pools from %s:\n", fsname);
798         if ((dir = opendir(pathname)) == NULL) {
799                 llapi_err(LLAPI_MSG_ERROR, "Could not open pool list for '%s'",
800                           name);
801                 return -errno;
802         }
803
804         while(1) {
805                 rc = readdir_r(dir, &pool, &cookie);
806
807                 if (rc != 0) {
808                         llapi_err(LLAPI_MSG_ERROR,
809                                   "Error reading pool list for '%s'", name);
810                         return -errno;
811                 } else if ((rc == 0) && (cookie == NULL))
812                         /* end of directory */
813                         break;
814
815                 /* ignore . and .. */
816                 if (!strcmp(pool.d_name, ".") || !strcmp(pool.d_name, ".."))
817                         continue;
818
819                 /* check output bounds */
820                 if (nb_entries >= list_size)
821                         return -EOVERFLOW;
822
823                 /* +2 for '.' and final '\0' */
824                 if (used + strlen(pool.d_name) + strlen(fsname) + 2
825                     > buffer_size)
826                         return -EOVERFLOW;
827
828                 sprintf(buffer + used, "%s.%s", fsname, pool.d_name);
829                 poollist[nb_entries] = buffer + used;
830                 used += strlen(pool.d_name) + strlen(fsname) + 2;
831                 nb_entries++;
832         }
833
834         closedir(dir);
835         return nb_entries;
836 }
837
838 /* wrapper for lfs.c and obd.c */
839 int llapi_poollist(const char *name)
840 {
841         /* list of pool names (assume that pool count is smaller
842            than OST count) */
843         char *list[FIND_MAX_OSTS];
844         char *buffer;
845         /* fsname-OST0000_UUID < 32 char, 1 per OST */
846         int bufsize = FIND_MAX_OSTS * 32;
847         int i, nb;
848
849         buffer = malloc(bufsize);
850         if (buffer == NULL)
851                 return -ENOMEM;
852
853         if ((name[0] == '/') || (strchr(name, '.') == NULL))
854                 /* name is a path or fsname */
855                 nb = llapi_get_poollist(name, list, FIND_MAX_OSTS, buffer,
856                                         bufsize);
857         else
858                 /* name is a pool name (<fsname>.<poolname>) */
859                 nb = llapi_get_poolmembers(name, list, FIND_MAX_OSTS, buffer,
860                                            bufsize);
861
862         for (i = 0; i < nb; i++)
863                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", list[i]);
864
865         free(buffer);
866         return (nb < 0 ? nb : 0);
867 }
868
869
870 typedef int (semantic_func_t)(char *path, DIR *parent, DIR *d,
871                               void *data, cfs_dirent_t *de);
872
873 #define MAX_LOV_UUID_COUNT      max(LOV_MAX_STRIPE_COUNT, 1000)
874 #define OBD_NOT_FOUND           (-1)
875
876 static int common_param_init(struct find_param *param)
877 {
878         param->lumlen = lov_mds_md_size(MAX_LOV_UUID_COUNT, LOV_MAGIC_V3);
879         if ((param->lmd = malloc(sizeof(lstat_t) + param->lumlen)) == NULL) {
880                 llapi_err(LLAPI_MSG_ERROR,
881                           "error: allocation of %d bytes for ioctl",
882                           sizeof(lstat_t) + param->lumlen);
883                 return -ENOMEM;
884         }
885
886         param->got_uuids = 0;
887         param->obdindexes = NULL;
888         param->obdindex = OBD_NOT_FOUND;
889         return 0;
890 }
891
892 static void find_param_fini(struct find_param *param)
893 {
894         if (param->obdindexes)
895                 free(param->obdindexes);
896
897         if (param->lmd)
898                 free(param->lmd);
899 }
900
901 static int cb_common_fini(char *path, DIR *parent, DIR *d, void *data,
902                           cfs_dirent_t *de)
903 {
904         struct find_param *param = (struct find_param *)data;
905         param->depth--;
906         return 0;
907 }
908
909 static DIR *opendir_parent(char *path)
910 {
911         DIR *parent;
912         char *fname;
913         char c;
914
915         fname = strrchr(path, '/');
916         if (fname == NULL)
917                 return opendir(".");
918
919         c = fname[1];
920         fname[1] = '\0';
921         parent = opendir(path);
922         fname[1] = c;
923         return parent;
924 }
925
926 int llapi_mds_getfileinfo(char *path, DIR *parent,
927                           struct lov_user_mds_data *lmd)
928 {
929         lstat_t *st = &lmd->lmd_st;
930         char *fname = strrchr(path, '/');
931         int ret = 0;
932
933         if (parent == NULL)
934                 return -EINVAL;
935
936         fname = (fname == NULL ? path : fname + 1);
937         /* retrieve needed file info */
938         strncpy((char *)lmd, fname,
939                 lov_mds_md_size(MAX_LOV_UUID_COUNT, LOV_MAGIC));
940         ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO, (void *)lmd);
941
942         if (ret) {
943                 if (errno == ENOTTY) {
944                         /* ioctl is not supported, it is not a lustre fs.
945                          * Do the regular lstat(2) instead. */
946                         ret = lstat_f(path, st);
947                         if (ret) {
948                                 llapi_err(LLAPI_MSG_ERROR,
949                                           "error: %s: lstat failed for %s",
950                                           __func__, path);
951                                 return ret;
952                         }
953                 } else if (errno == ENOENT) {
954                         llapi_err(LLAPI_MSG_WARN,
955                                   "warning: %s: %s does not exist",
956                                   __func__, path);
957                         return -ENOENT;
958                 } else {
959                         llapi_err(LLAPI_MSG_ERROR,
960                                  "error: %s: IOC_MDC_GETFILEINFO failed for %s",
961                                  __func__, path);
962                         return ret;
963                 }
964         }
965
966         return 0;
967 }
968
969 static int llapi_semantic_traverse(char *path, int size, DIR *parent,
970                                    semantic_func_t sem_init,
971                                    semantic_func_t sem_fini, void *data,
972                                    cfs_dirent_t *de)
973 {
974         cfs_dirent_t *dent;
975         int len, ret;
976         DIR *d, *p = NULL;
977
978         ret = 0;
979         len = strlen(path);
980
981         d = opendir(path);
982         if (!d && errno != ENOTDIR) {
983                 llapi_err(LLAPI_MSG_ERROR, "%s: Failed to open '%s'",
984                           __func__, path);
985                 return -EINVAL;
986         } else if (!d && !parent) {
987                 /* ENOTDIR. Open the parent dir. */
988                 p = opendir_parent(path);
989                 if (!p)
990                         GOTO(out, ret = -EINVAL);
991         }
992
993         if (sem_init && (ret = sem_init(path, parent ?: p, d, data, de)))
994                 goto err;
995
996         if (!d)
997                 GOTO(out, ret = 0);
998
999         while ((dent = readdir64(d)) != NULL) {
1000                 ((struct find_param *)data)->have_fileinfo = 0;
1001
1002                 if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
1003                         continue;
1004
1005                 /* Don't traverse .lustre directory */
1006                 if (!(strcmp(dent->d_name, dot_lustre_name)))
1007                         continue;
1008
1009                 path[len] = 0;
1010                 if ((len + dent->d_reclen + 2) > size) {
1011                         llapi_err(LLAPI_MSG_ERROR,
1012                                   "error: %s: string buffer is too small",
1013                                   __func__);
1014                         break;
1015                 }
1016                 strcat(path, "/");
1017                 strcat(path, dent->d_name);
1018
1019                 if (dent->d_type == DT_UNKNOWN) {
1020                         lstat_t *st = &((struct find_param *)data)->lmd->lmd_st;
1021
1022                         ret = llapi_mds_getfileinfo(path, d,
1023                                              ((struct find_param *)data)->lmd);
1024                         if (ret == 0) {
1025                                 ((struct find_param *)data)->have_fileinfo = 1;
1026                                 dent->d_type =
1027                                         llapi_filetype_dir_table[st->st_mode &
1028                                                                  S_IFMT];
1029                         }
1030                         if (ret == -ENOENT)
1031                                 continue;
1032                 }
1033
1034                 switch (dent->d_type) {
1035                 case DT_UNKNOWN:
1036                         llapi_err(LLAPI_MSG_ERROR,
1037                                   "error: %s: '%s' is UNKNOWN type %d",
1038                                   __func__, dent->d_name, dent->d_type);
1039                         break;
1040                 case DT_DIR:
1041                         ret = llapi_semantic_traverse(path, size, d, sem_init,
1042                                                       sem_fini, data, dent);
1043                         if (ret < 0)
1044                                 goto out;
1045                         break;
1046                 default:
1047                         ret = 0;
1048                         if (sem_init) {
1049                                 ret = sem_init(path, d, NULL, data, dent);
1050                                 if (ret < 0)
1051                                         goto out;
1052                         }
1053                         if (sem_fini && ret == 0)
1054                                 sem_fini(path, d, NULL, data, dent);
1055                 }
1056         }
1057
1058 out:
1059         path[len] = 0;
1060
1061         if (sem_fini)
1062                 sem_fini(path, parent, d, data, de);
1063 err:
1064         if (d)
1065                 closedir(d);
1066         if (p)
1067                 closedir(p);
1068         return ret;
1069 }
1070
1071 static int param_callback(char *path, semantic_func_t sem_init,
1072                           semantic_func_t sem_fini, struct find_param *param)
1073 {
1074         int ret, len = strlen(path);
1075         char *buf;
1076
1077         if (len > PATH_MAX) {
1078                 llapi_err(LLAPI_MSG_ERROR, "Path name '%s' is too long", path);
1079                 return -EINVAL;
1080         }
1081
1082         buf = (char *)malloc(PATH_MAX + 1);
1083         if (!buf)
1084                 return -ENOMEM;
1085
1086         ret = common_param_init(param);
1087         if (ret)
1088                 goto out;
1089         param->depth = 0;
1090
1091         strncpy(buf, path, PATH_MAX + 1);
1092         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, sem_init,
1093                                       sem_fini, param, NULL);
1094 out:
1095         find_param_fini(param);
1096         free(buf);
1097         return ret < 0 ? ret : 0;
1098 }
1099
1100 int llapi_file_fget_lov_uuid(int fd, struct obd_uuid *lov_name)
1101 {
1102         int rc = ioctl(fd, OBD_IOC_GETNAME, lov_name);
1103         if (rc) {
1104                 rc = errno;
1105                 llapi_err(LLAPI_MSG_ERROR, "error: can't get lov name.");
1106         }
1107         return rc;
1108 }
1109
1110 int llapi_file_get_lov_uuid(const char *path, struct obd_uuid *lov_uuid)
1111 {
1112         int fd, rc;
1113
1114         fd = open(path, O_RDONLY);
1115         if (fd < 0) {
1116                 rc = errno;
1117                 llapi_err(LLAPI_MSG_ERROR, "error opening %s", path);
1118                 return rc;
1119         }
1120
1121         rc = llapi_file_fget_lov_uuid(fd, lov_uuid);
1122
1123         close(fd);
1124
1125         return rc;
1126 }
1127
1128 /*
1129  * If uuidp is NULL, return the number of available obd uuids.
1130  * If uuidp is non-NULL, then it will return the uuids of the obds. If
1131  * there are more OSTs then allocated to uuidp, then an error is returned with
1132  * the ost_count set to number of available obd uuids.
1133  */
1134 int llapi_lov_get_uuids(int fd, struct obd_uuid *uuidp, int *ost_count)
1135 {
1136         struct obd_uuid lov_name;
1137         char buf[1024];
1138         FILE *fp;
1139         int rc = 0, index = 0;
1140
1141         /* Get the lov name */
1142         rc = llapi_file_fget_lov_uuid(fd, &lov_name);
1143         if (rc)
1144                 return rc;
1145
1146         /* Now get the ost uuids from /proc */
1147         snprintf(buf, sizeof(buf), "/proc/fs/lustre/lov/%s/target_obd",
1148                  lov_name.uuid);
1149         fp = fopen(buf, "r");
1150         if (fp == NULL) {
1151                 rc = errno;
1152                 llapi_err(LLAPI_MSG_ERROR, "error: opening '%s'", buf);
1153                 return rc;
1154         }
1155
1156         while (fgets(buf, sizeof(buf), fp) != NULL) {
1157                 if (uuidp && (index < *ost_count)) {
1158                         if (sscanf(buf, "%d: %s", &index, uuidp[index].uuid) <2)
1159                                 break;
1160                 }
1161                 index++;
1162         }
1163
1164         fclose(fp);
1165
1166         if (uuidp && (index >= *ost_count))
1167                 return -EOVERFLOW;
1168
1169         *ost_count = index;
1170         return rc;
1171 }
1172
1173 int llapi_get_obd_count(char *mnt, int *count, int is_mdt)
1174 {
1175         DIR *root;
1176         int rc;
1177
1178         root = opendir(mnt);
1179         if (!root) {
1180                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
1181                 return -1;
1182         }
1183
1184         *count = is_mdt;
1185         rc = ioctl(dirfd(root), LL_IOC_GETOBDCOUNT, count);
1186
1187         closedir(root);
1188         return rc;
1189 }
1190
1191 /* Check if user specified value matches a real uuid.  Ignore _UUID,
1192  * -osc-4ba41334, other trailing gunk in comparison.
1193  * @param real_uuid ends in "_UUID"
1194  * @param search_uuid may or may not end in "_UUID"
1195  */
1196 int llapi_uuid_match(char *real_uuid, char *search_uuid)
1197 {
1198         int cmplen = strlen(real_uuid) - 5;
1199
1200         if ((strlen(search_uuid) > cmplen) && isxdigit(search_uuid[cmplen])) {
1201                 /* OST00000003 doesn't match OST0000 */
1202                 llapi_err(LLAPI_MSG_ERROR, "Bad UUID format '%s'", search_uuid);
1203                 return 0;
1204         }
1205
1206         return (strncmp(search_uuid, real_uuid, cmplen) == 0);
1207 }
1208
1209 /* Here, param->obduuid points to a single obduuid, the index of which is
1210  * returned in param->obdindex */
1211 static int setup_obd_uuid(DIR *dir, char *dname, struct find_param *param)
1212 {
1213         struct obd_uuid lov_uuid;
1214         char uuid[sizeof(struct obd_uuid)];
1215         char buf[1024];
1216         FILE *fp;
1217         int rc = 0, index;
1218
1219         if (param->got_uuids)
1220                 return rc;
1221
1222         /* Get the lov name */
1223         rc = llapi_file_fget_lov_uuid(dirfd(dir), &lov_uuid);
1224         if (rc) {
1225                 if (errno != ENOTTY) {
1226                         rc = errno;
1227                         llapi_err(LLAPI_MSG_ERROR,
1228                                   "error: can't get lov name: %s", dname);
1229                 } else {
1230                         rc = 0;
1231                 }
1232                 return rc;
1233         }
1234
1235         param->got_uuids = 1;
1236
1237         /* Now get the ost uuids from /proc */
1238         snprintf(buf, sizeof(buf), "/proc/fs/lustre/lov/%s/target_obd",
1239                  lov_uuid.uuid);
1240         fp = fopen(buf, "r");
1241         if (fp == NULL) {
1242                 rc = errno;
1243                 llapi_err(LLAPI_MSG_ERROR, "error: opening '%s'", buf);
1244                 return rc;
1245         }
1246
1247         if (!param->obduuid && !param->quiet && !param->obds_printed)
1248                 llapi_printf(LLAPI_MSG_NORMAL, "OBDS:\n");
1249
1250         while (fgets(buf, sizeof(buf), fp) != NULL) {
1251                 if (sscanf(buf, "%d: %s", &index, uuid) < 2)
1252                         break;
1253
1254                 if (param->obduuid) {
1255                         if (llapi_uuid_match(uuid, param->obduuid->uuid)) {
1256                                 param->obdindex = index;
1257                                 break;
1258                         }
1259                 } else if (!param->quiet && !param->obds_printed) {
1260                         /* Print everything */
1261                         llapi_printf(LLAPI_MSG_NORMAL, "%s", buf);
1262                 }
1263         }
1264         param->obds_printed = 1;
1265
1266         fclose(fp);
1267
1268         if (param->obduuid && (param->obdindex == OBD_NOT_FOUND)) {
1269                 llapi_err_noerrno(LLAPI_MSG_ERROR,
1270                                   "error: %s: unknown obduuid: %s",
1271                                   __func__, param->obduuid->uuid);
1272                 rc = -EINVAL;
1273         }
1274
1275         return (rc);
1276 }
1277
1278 /* In this case, param->obduuid will be an array of obduuids and
1279  * obd index for all these obduuids will be returned in
1280  * param->obdindexes */
1281 static int setup_obd_indexes(DIR *dir, struct find_param *param)
1282 {
1283         struct obd_uuid *uuids = NULL;
1284         int obdcount = INIT_ALLOC_NUM_OSTS;
1285         int ret, obd_valid = 0, obdnum, i;
1286
1287         uuids = (struct obd_uuid *)malloc(INIT_ALLOC_NUM_OSTS *
1288                                           sizeof(struct obd_uuid));
1289         if (uuids == NULL)
1290                 return -ENOMEM;
1291
1292 retry_get_uuids:
1293         ret = llapi_lov_get_uuids(dirfd(dir), uuids,
1294                                   &obdcount);
1295         if (ret) {
1296                 struct obd_uuid *uuids_temp;
1297
1298                 if (ret == -EOVERFLOW) {
1299                         uuids_temp = realloc(uuids, obdcount *
1300                                              sizeof(struct obd_uuid));
1301                         if (uuids_temp != NULL)
1302                                 goto retry_get_uuids;
1303                         else
1304                                 ret = -ENOMEM;
1305                 }
1306
1307                 llapi_err(LLAPI_MSG_ERROR, "get ost uuid failed");
1308                 return ret;
1309         }
1310
1311         param->obdindexes = malloc(param->num_obds * sizeof(param->obdindex));
1312         if (param->obdindexes == NULL)
1313                 return -ENOMEM;
1314
1315         for (obdnum = 0; obdnum < param->num_obds; obdnum++) {
1316                 for (i = 0; i < obdcount; i++) {
1317                         if (llapi_uuid_match(uuids[i].uuid,
1318                                              param->obduuid[obdnum].uuid)) {
1319                                 param->obdindexes[obdnum] = i;
1320                                 obd_valid++;
1321                                 break;
1322                         }
1323                 }
1324                 if (i >= obdcount) {
1325                         param->obdindexes[obdnum] = OBD_NOT_FOUND;
1326                         llapi_err_noerrno(LLAPI_MSG_ERROR,
1327                                           "error: %s: unknown obduuid: %s",
1328                                           __func__,
1329                                           param->obduuid[obdnum].uuid);
1330                         ret = -EINVAL;
1331                 }
1332         }
1333
1334         if (obd_valid == 0)
1335                 param->obdindex = OBD_NOT_FOUND;
1336         else
1337                 param->obdindex = obd_valid;
1338
1339         param->got_uuids = 1;
1340
1341         return ret;
1342 }
1343
1344 static int cb_ostlist(char *path, DIR *parent, DIR *d, void *data,
1345                       struct dirent64 *de)
1346 {
1347         struct find_param *param = (struct find_param *)data;
1348
1349         LASSERT(parent != NULL || d != NULL);
1350
1351         /* Prepare odb. */
1352         return setup_obd_uuid(d ? d : parent, path, param);
1353 }
1354
1355 int llapi_ostlist(char *path, struct find_param *param)
1356 {
1357         return param_callback(path, cb_ostlist, cb_common_fini, param);
1358 }
1359
1360 static void lov_dump_user_lmm_header(struct lov_user_md *lum, char *path,
1361                                      int is_dir, int verbose, int depth,
1362                                      char *pool_name)
1363 {
1364         char *prefix = is_dir ? "" : "lmm_";
1365         char nl = is_dir ? ' ' : '\n';
1366
1367         if (is_dir && lum->lmm_object_gr == LOV_OBJECT_GROUP_DEFAULT) {
1368                 lum->lmm_object_gr = LOV_OBJECT_GROUP_CLEAR;
1369                 if (verbose & VERBOSE_DETAIL)
1370                         llapi_printf(LLAPI_MSG_NORMAL, "(Default) ");
1371         }
1372
1373         if (depth && path && ((verbose != VERBOSE_OBJID) || !is_dir))
1374                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
1375
1376         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
1377                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_magic:          0x%08X\n",
1378                              lum->lmm_magic);
1379                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_gr:      "LPX64"\n",
1380                              lum->lmm_object_gr);
1381                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_id:      "LPX64"\n",
1382                              lum->lmm_object_id);
1383         }
1384
1385         if (verbose & VERBOSE_COUNT) {
1386                 if (verbose & ~VERBOSE_COUNT)
1387                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_count:   ",
1388                                      prefix);
1389                 llapi_printf(LLAPI_MSG_NORMAL, "%hd%c",
1390                              (__s16)lum->lmm_stripe_count, nl);
1391         }
1392
1393         if (verbose & VERBOSE_SIZE) {
1394                 if (verbose & ~VERBOSE_SIZE)
1395                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_size:    ",
1396                                      prefix);
1397                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c", lum->lmm_stripe_size,
1398                              nl);
1399         }
1400
1401         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
1402                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_stripe_pattern: %x%c",
1403                              lum->lmm_pattern, nl);
1404         }
1405
1406         if (verbose & VERBOSE_OFFSET) {
1407                 if (verbose & ~VERBOSE_OFFSET)
1408                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_offset:  ",
1409                                      prefix);
1410                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
1411                              lum->lmm_objects[0].l_ost_idx, nl);
1412         }
1413
1414         if ((verbose & VERBOSE_POOL) && (pool_name != NULL)) {
1415                 llapi_printf(LLAPI_MSG_NORMAL, "pool: %s", pool_name);
1416                 is_dir = 1;
1417         }
1418
1419         if (is_dir && (verbose != VERBOSE_OBJID))
1420                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1421 }
1422
1423 void lov_dump_user_lmm_v1v3(struct lov_user_md *lum, char *pool_name,
1424                             struct lov_user_ost_data_v1 *objects,
1425                             char *path, int is_dir,
1426                             int obdindex, int depth, int header)
1427 {
1428         int i, obdstripe = (obdindex != OBD_NOT_FOUND) ? 0 : 1;
1429
1430         if (!obdstripe) {
1431                 for (i = 0; !is_dir && i < lum->lmm_stripe_count; i++) {
1432                         if (obdindex == objects[i].l_ost_idx) {
1433                                 obdstripe = 1;
1434                                 break;
1435                         }
1436                 }
1437         }
1438
1439         if (obdstripe == 1)
1440                 lov_dump_user_lmm_header(lum, path, is_dir, header, depth,
1441                                          pool_name);
1442
1443         if (!is_dir && (header & VERBOSE_OBJID)) {
1444                 if (obdstripe == 1)
1445                         llapi_printf(LLAPI_MSG_NORMAL,
1446                                      "\tobdidx\t\t objid\t\tobjid\t\t group\n");
1447
1448                 for (i = 0; i < lum->lmm_stripe_count; i++) {
1449                         int idx = objects[i].l_ost_idx;
1450                         long long oid = objects[i].l_object_id;
1451                         long long gr = objects[i].l_object_gr;
1452                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
1453                                 llapi_printf(LLAPI_MSG_NORMAL,
1454                                            "\t%6u\t%14llu\t%#13llx\t%14llu%s\n",
1455                                            idx, oid, oid, gr,
1456                                            obdindex == idx ? " *" : "");
1457                 }
1458                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1459         }
1460 }
1461
1462 void llapi_lov_dump_user_lmm(struct find_param *param,
1463                              char *path, int is_dir)
1464 {
1465         switch(*(__u32 *)&param->lmd->lmd_lmm) { /* lum->lmm_magic */
1466         case LOV_USER_MAGIC_V1:
1467                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, NULL,
1468                                        param->lmd->lmd_lmm.lmm_objects,
1469                                        path, is_dir,
1470                                        param->obdindex, param->maxdepth,
1471                                        param->verbose);
1472                 break;
1473         case LOV_USER_MAGIC_V3: {
1474                 char pool_name[LOV_MAXPOOLNAME + 1];
1475                 struct lov_user_ost_data_v1 *objects;
1476                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
1477
1478                 strncpy(pool_name, lmmv3->lmm_pool_name, LOV_MAXPOOLNAME);
1479                 pool_name[LOV_MAXPOOLNAME] = '\0';
1480                 objects = lmmv3->lmm_objects;
1481                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, pool_name,
1482                                        objects, path, is_dir,
1483                                        param->obdindex, param->maxdepth,
1484                                        param->verbose);
1485                 break;
1486         }
1487         default:
1488                 llapi_printf(LLAPI_MSG_NORMAL, "unknown lmm_magic:  %#x "
1489                              "(expecting one of %#x %#x %#x)\n",
1490                              *(__u32 *)&param->lmd->lmd_lmm,
1491                              LOV_USER_MAGIC_V1, LOV_USER_MAGIC_V3);
1492                 return;
1493         }
1494 }
1495
1496 int llapi_file_get_stripe(const char *path, struct lov_user_md *lum)
1497 {
1498         const char *fname;
1499         char *dname;
1500         int fd, rc = 0;
1501
1502         fname = strrchr(path, '/');
1503
1504         /* It should be a file (or other non-directory) */
1505         if (fname == NULL) {
1506                 dname = (char *)malloc(2);
1507                 if (dname == NULL)
1508                         return ENOMEM;
1509                 strcpy(dname, ".");
1510                 fname = (char *)path;
1511         } else {
1512                 dname = (char *)malloc(fname - path + 1);
1513                 if (dname == NULL)
1514                         return ENOMEM;
1515                 strncpy(dname, path, fname - path);
1516                 dname[fname - path] = '\0';
1517                 fname++;
1518         }
1519
1520         if ((fd = open(dname, O_RDONLY)) == -1) {
1521                 rc = errno;
1522                 free(dname);
1523                 return rc;
1524         }
1525
1526         strcpy((char *)lum, fname);
1527         if (ioctl(fd, IOC_MDC_GETFILESTRIPE, (void *)lum) == -1)
1528                 rc = errno;
1529
1530         if (close(fd) == -1 && rc == 0)
1531                 rc = errno;
1532
1533         free(dname);
1534
1535         return rc;
1536 }
1537
1538 int llapi_file_lookup(int dirfd, const char *name)
1539 {
1540         struct obd_ioctl_data data = { 0 };
1541         char rawbuf[8192];
1542         char *buf = rawbuf;
1543         int rc;
1544
1545         if (dirfd < 0 || name == NULL)
1546                 return -EINVAL;
1547
1548         data.ioc_version = OBD_IOCTL_VERSION;
1549         data.ioc_len = sizeof(data);
1550         data.ioc_inlbuf1 = (char *)name;
1551         data.ioc_inllen1 = strlen(name) + 1;
1552
1553         rc = obd_ioctl_pack(&data, &buf, sizeof(rawbuf));
1554         if (rc) {
1555                 llapi_err(LLAPI_MSG_ERROR,
1556                           "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
1557                           name, rc);
1558                 return rc;
1559         }
1560
1561         return ioctl(dirfd, IOC_MDC_LOOKUP, buf);
1562 }
1563
1564 /* Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
1565  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
1566  *
1567  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
1568  * The table below gives the answers for the specified parameters (value and
1569  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
1570  * --------------------------------------
1571  * 1 | file > limit; sign > 0 | -1 / -1 |
1572  * 2 | file = limit; sign > 0 |  ? /  1 |
1573  * 3 | file < limit; sign > 0 |  ? /  1 |
1574  * 4 | file > limit; sign = 0 | -1 / -1 |
1575  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
1576  * 6 | file < limit; sign = 0 |  ? / -1 |
1577  * 7 | file > limit; sign < 0 |  1 /  1 |
1578  * 8 | file = limit; sign < 0 |  ? / -1 |
1579  * 9 | file < limit; sign < 0 |  ? / -1 |
1580  * --------------------------------------
1581  * Note: 5th actually means that the value is within the interval
1582  * (limit - margin, limit]. */
1583 static int find_value_cmp(unsigned int file, unsigned int limit, int sign,
1584                           unsigned long long margin, int mds)
1585 {
1586         if (sign > 0) {
1587                 if (file < limit)
1588                         return mds ? 0 : 1;
1589         }
1590
1591         if (sign == 0) {
1592                 if (file <= limit && file + margin > limit)
1593                         return mds ? 0 : 1;
1594                 if (file + margin <= limit)
1595                         return mds ? 0 : -1;
1596         }
1597
1598         if (sign < 0) {
1599                 if (file > limit)
1600                         return 1;
1601                 if (mds)
1602                         return 0;
1603         }
1604
1605         return -1;
1606 }
1607
1608 /* Check if the file time matches all the given criteria (e.g. --atime +/-N).
1609  * Return -1 or 1 if file timestamp does not or does match the given criteria
1610  * correspondingly. Return 0 if the MDS time is being checked and there are
1611  * attributes on OSTs and it is not yet clear if the timespamp matches.
1612  *
1613  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
1614  * updated timestamps. */
1615 static int find_time_check(lstat_t *st, struct find_param *param, int mds)
1616 {
1617         int ret;
1618         int rc = 0;
1619
1620         /* Check if file is accepted. */
1621         if (param->atime) {
1622                 ret = find_value_cmp(st->st_atime, param->atime,
1623                                      param->asign, 24 * 60 * 60, mds);
1624                 if (ret < 0)
1625                         return ret;
1626                 rc = ret;
1627         }
1628
1629         if (param->mtime) {
1630                 ret = find_value_cmp(st->st_mtime, param->mtime,
1631                                      param->msign, 24 * 60 * 60, mds);
1632                 if (ret < 0)
1633                         return ret;
1634
1635                 /* If the previous check matches, but this one is not yet clear,
1636                  * we should return 0 to do an RPC on OSTs. */
1637                 if (rc == 1)
1638                         rc = ret;
1639         }
1640
1641         if (param->ctime) {
1642                 ret = find_value_cmp(st->st_ctime, param->ctime,
1643                                      param->csign, 24 * 60 * 60, mds);
1644                 if (ret < 0)
1645                         return ret;
1646
1647                 /* If the previous check matches, but this one is not yet clear,
1648                  * we should return 0 to do an RPC on OSTs. */
1649                 if (rc == 1)
1650                         rc = ret;
1651         }
1652
1653         return rc;
1654 }
1655
1656 static int cb_find_init(char *path, DIR *parent, DIR *dir,
1657                         void *data, cfs_dirent_t *de)
1658 {
1659         struct find_param *param = (struct find_param *)data;
1660         int decision = 1; /* 1 is accepted; -1 is rejected. */
1661         lstat_t *st = &param->lmd->lmd_st;
1662         int lustre_fs = 1;
1663         int checked_type = 0;
1664         int ret = 0;
1665
1666         LASSERT(parent != NULL || dir != NULL);
1667
1668         param->lmd->lmd_lmm.lmm_stripe_count = 0;
1669
1670         /* If a regular expression is presented, make the initial decision */
1671         if (param->pattern != NULL) {
1672                 char *fname = strrchr(path, '/');
1673                 fname = (fname == NULL ? path : fname + 1);
1674                 ret = fnmatch(param->pattern, fname, 0);
1675                 if ((ret == FNM_NOMATCH && !param->exclude_pattern) ||
1676                     (ret == 0 && param->exclude_pattern))
1677                         goto decided;
1678         }
1679
1680         /* See if we can check the file type from the dirent. */
1681         if (param->type && de != NULL && de->d_type != DT_UNKNOWN &&
1682             de->d_type < DT_MAX) {
1683                 checked_type = 1;
1684                 if (llapi_dir_filetype_table[de->d_type] == param->type) {
1685                         if (param->exclude_type)
1686                                 goto decided;
1687                 } else {
1688                         if (!param->exclude_type)
1689                                 goto decided;
1690                 }
1691         }
1692
1693
1694         /* If a time or OST should be checked, the decision is not taken yet. */
1695         if (param->atime || param->ctime || param->mtime || param->obduuid ||
1696             param->size)
1697                 decision = 0;
1698
1699         ret = 0;
1700         /* Request MDS for the stat info. */
1701         if (param->have_fileinfo == 0) {
1702                 if (dir) {
1703                         /* retrieve needed file info */
1704                         ret = ioctl(dirfd(dir), LL_IOC_MDC_GETINFO,
1705                                     (void *)param->lmd);
1706                 } else {
1707                         char *fname = strrchr(path, '/');
1708                         fname = (fname == NULL ? path : fname + 1);
1709
1710                         /* retrieve needed file info */
1711                         strncpy((char *)param->lmd, fname, param->lumlen);
1712                         ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
1713                                    (void *)param->lmd);
1714                 }
1715         }
1716
1717         if (ret) {
1718                 if (errno == ENOTTY) {
1719                         /* ioctl is not supported, it is not a lustre fs.
1720                          * Do the regular lstat(2) instead. */
1721                         lustre_fs = 0;
1722                         ret = lstat_f(path, st);
1723                         if (ret) {
1724                                 llapi_err(LLAPI_MSG_ERROR,
1725                                           "error: %s: lstat failed for %s",
1726                                           __func__, path);
1727                                 return ret;
1728                         }
1729                 } else if (errno == ENOENT) {
1730                         llapi_err(LLAPI_MSG_WARN,
1731                                   "warning: %s: %s does not exist",
1732                                   __func__, path);
1733                         goto decided;
1734                 } else {
1735                         llapi_err(LLAPI_MSG_ERROR,"error: %s: %s failed for %s",
1736                                   __func__, dir ? "LL_IOC_MDC_GETINFO" :
1737                                   "IOC_MDC_GETFILEINFO", path);
1738                         return ret;
1739                 }
1740         }
1741
1742         if (param->type && !checked_type) {
1743                 if ((st->st_mode & S_IFMT) == param->type) {
1744                         if (param->exclude_type)
1745                                 goto decided;
1746                 } else {
1747                         if (!param->exclude_type)
1748                                 goto decided;
1749                 }
1750         }
1751
1752         /* Prepare odb. */
1753         if (param->obduuid) {
1754                 if (lustre_fs && param->got_uuids &&
1755                     param->st_dev != st->st_dev) {
1756                         /* A lustre/lustre mount point is crossed. */
1757                         param->got_uuids = 0;
1758                         param->obds_printed = 0;
1759                         param->obdindex = OBD_NOT_FOUND;
1760                 }
1761
1762                 if (lustre_fs && !param->got_uuids) {
1763                         ret = setup_obd_indexes(dir ? dir : parent, param);
1764                         if (ret)
1765                                 return ret;
1766
1767                         param->st_dev = st->st_dev;
1768                 } else if (!lustre_fs && param->got_uuids) {
1769                         /* A lustre/non-lustre mount point is crossed. */
1770                         param->got_uuids = 0;
1771                         param->obdindex = OBD_NOT_FOUND;
1772                 }
1773         }
1774
1775         /* If an OBD UUID is specified but no one matches, skip this file. */
1776         if (param->obduuid && param->obdindex == OBD_NOT_FOUND)
1777                 goto decided;
1778
1779         /* If a OST UUID is given, and some OST matches, check it here. */
1780         if (param->obdindex != OBD_NOT_FOUND) {
1781                 if (!S_ISREG(st->st_mode))
1782                         goto decided;
1783
1784                 /* Only those files should be accepted, which have a
1785                  * stripe on the specified OST. */
1786                 if (!param->lmd->lmd_lmm.lmm_stripe_count) {
1787                         goto decided;
1788                 } else {
1789                         int i, j;
1790                         struct lov_user_ost_data_v1 *lmm_objects;
1791
1792                         if (param->lmd->lmd_lmm.lmm_magic ==
1793                             LOV_USER_MAGIC_V3) {
1794                                 struct lov_user_md_v3 *lmmv3 =
1795                                         (void *)&param->lmd->lmd_lmm;
1796
1797                                 lmm_objects = lmmv3->lmm_objects;
1798                         } else {
1799                                 lmm_objects = param->lmd->lmd_lmm.lmm_objects;
1800                         }
1801
1802                         for (i = 0;
1803                              i < param->lmd->lmd_lmm.lmm_stripe_count; i++) {
1804                                 for (j = 0; j < param->num_obds; j++) {
1805                                         if (param->obdindexes[j] ==
1806                                             lmm_objects[i].l_ost_idx)
1807                                                 goto obd_matches;
1808                                 }
1809                         }
1810
1811                         if (i == param->lmd->lmd_lmm.lmm_stripe_count)
1812                                 goto decided;
1813                 }
1814         }
1815
1816         if (param->check_uid) {
1817                 if (st->st_uid == param->uid) {
1818                         if (param->exclude_uid)
1819                                 goto decided;
1820                 } else {
1821                         if (!param->exclude_uid)
1822                                 goto decided;
1823                 }
1824         }
1825
1826         if (param->check_gid) {
1827                 if (st->st_gid == param->gid) {
1828                         if (param->exclude_gid)
1829                                 goto decided;
1830                 } else {
1831                         if (!param->exclude_gid)
1832                                 goto decided;
1833                 }
1834         }
1835
1836         if (param->check_pool) {
1837                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
1838
1839                 /* empty requested pool is taken as no pool search => V1 */
1840                 if (((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V1) &&
1841                      (param->poolname[0] == '\0')) ||
1842                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
1843                      (strncmp(lmmv3->lmm_pool_name,
1844                               param->poolname, LOV_MAXPOOLNAME) == 0)) ||
1845                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
1846                      (strcmp(param->poolname, "*") == 0))) {
1847                         if (param->exclude_pool)
1848                                 goto decided;
1849                 } else {
1850                         if (!param->exclude_pool)
1851                                 goto decided;
1852                 }
1853         }
1854
1855         /* Check the time on mds. */
1856         if (!decision) {
1857                 int for_mds;
1858
1859                 for_mds = lustre_fs ? (S_ISREG(st->st_mode) &&
1860                                        param->lmd->lmd_lmm.lmm_stripe_count)
1861                                     : 0;
1862                 decision = find_time_check(st, param, for_mds);
1863         }
1864
1865 obd_matches:
1866         /* If file still fits the request, ask ost for updated info.
1867            The regular stat is almost of the same speed as some new
1868            'glimpse-size-ioctl'. */
1869         if (!decision && S_ISREG(st->st_mode) &&
1870             (param->lmd->lmd_lmm.lmm_stripe_count || param->size)) {
1871                 if (param->obdindex != OBD_NOT_FOUND) {
1872                         /* Check whether the obd is active or not, if it is
1873                          * not active, just print the object affected by this
1874                          * failed ost
1875                          * */
1876                         struct obd_statfs stat_buf;
1877                         struct obd_uuid uuid_buf;
1878
1879                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
1880                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1881                         ret = llapi_obd_statfs(path, LL_STATFS_LOV,
1882                                                param->obdindex, &stat_buf,
1883                                                &uuid_buf);
1884                         if (ret) {
1885                                 if (ret == -ENODATA || ret == -ENODEV
1886                                     || ret == -EIO)
1887                                         errno = EIO;
1888                                 llapi_printf(LLAPI_MSG_NORMAL,
1889                                              "obd_uuid: %s failed %s ",
1890                                              param->obduuid->uuid,
1891                                              strerror(errno));
1892                                 goto print_path;
1893                         }
1894                 }
1895                 if (dir) {
1896                         ret = ioctl(dirfd(dir), IOC_LOV_GETINFO,
1897                                     (void *)param->lmd);
1898                 } else if (parent) {
1899                         ret = ioctl(dirfd(parent), IOC_LOV_GETINFO,
1900                                     (void *)param->lmd);
1901                 }
1902
1903                 if (ret) {
1904                         if (errno == ENOENT) {
1905                                 llapi_err(LLAPI_MSG_ERROR,
1906                                           "warning: %s: %s does not exist",
1907                                           __func__, path);
1908                                 goto decided;
1909                         } else {
1910                                 llapi_err(LLAPI_MSG_ERROR,
1911                                           "%s: IOC_LOV_GETINFO on %s failed",
1912                                           __func__, path);
1913                                 return ret;
1914                         }
1915                 }
1916
1917                 /* Check the time on osc. */
1918                 decision = find_time_check(st, param, 0);
1919                 if (decision == -1)
1920                         goto decided;
1921         }
1922
1923         if (param->size)
1924                 decision = find_value_cmp(st->st_size, param->size,
1925                                           param->size_sign, param->size_units,
1926                                           0);
1927
1928 print_path:
1929         if (decision != -1) {
1930                 llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
1931                 if (param->zeroend)
1932                         llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
1933                 else
1934                         llapi_printf(LLAPI_MSG_NORMAL, "\n");
1935         }
1936
1937 decided:
1938         /* Do not get down anymore? */
1939         if (param->depth == param->maxdepth)
1940                 return 1;
1941
1942         param->depth++;
1943         return 0;
1944 }
1945
1946 int llapi_find(char *path, struct find_param *param)
1947 {
1948         return param_callback(path, cb_find_init, cb_common_fini, param);
1949 }
1950
1951 /*
1952  * Get MDT number that the file/directory inode referenced
1953  * by the open fd resides on.
1954  * Return 0 and mdtidx on success, or -ve errno.
1955  */
1956 int llapi_file_fget_mdtidx(int fd, int *mdtidx)
1957 {
1958         if (ioctl(fd, LL_IOC_GET_MDTIDX, &mdtidx) < 0)
1959                 return -errno;
1960         return 0;
1961 }
1962
1963 static int cb_get_mdt_index(char *path, DIR *parent, DIR *d, void *data,
1964                             cfs_dirent_t *de)
1965 {
1966         struct find_param *param = (struct find_param *)data;
1967         int ret = 0;
1968         int mdtidx;
1969
1970         LASSERT(parent != NULL || d != NULL);
1971
1972         if (d) {
1973                 ret = llapi_file_fget_mdtidx(dirfd(d), &mdtidx);
1974         } else if (parent) {
1975                 int fd;
1976
1977                 fd = open(path, O_RDONLY);
1978                 if (fd > 0) {
1979                         ret = llapi_file_fget_mdtidx(fd, &mdtidx);
1980                         close(fd);
1981                 } else {
1982                         ret = fd;
1983                 }
1984         }
1985
1986         if (ret) {
1987                 if (errno == ENODATA) {
1988                         if (!param->obduuid)
1989                                 llapi_printf(LLAPI_MSG_NORMAL,
1990                                              "%s has no stripe info\n", path);
1991                         goto out;
1992                 } else if (errno == ENOTTY) {
1993                         llapi_err(LLAPI_MSG_ERROR,
1994                                   "%s: '%s' not on a Lustre fs?",
1995                                   __func__, path);
1996                 } else if (errno == ENOENT) {
1997                         llapi_err(LLAPI_MSG_WARN,
1998                                   "warning: %s: %s does not exist",
1999                                   __func__, path);
2000                         goto out;
2001                 } else {
2002                         llapi_err(LLAPI_MSG_ERROR,
2003                                   "error: %s: LL_IOC_GET_MDTIDX failed for %s",
2004                                    __func__, path);
2005                 }
2006                 return ret;
2007         }
2008
2009         if (param->quiet)
2010                 llapi_printf(LLAPI_MSG_NORMAL, "%d\n", mdtidx);
2011         else
2012                 llapi_printf(LLAPI_MSG_NORMAL, "%s MDT index: %d\n",
2013                              path, mdtidx);
2014
2015 out:
2016         /* Do not get down anymore? */
2017         if (param->depth == param->maxdepth)
2018                 return 1;
2019
2020         param->depth++;
2021         return 0;
2022 }
2023
2024 static int cb_getstripe(char *path, DIR *parent, DIR *d, void *data,
2025                         cfs_dirent_t *de)
2026 {
2027         struct find_param *param = (struct find_param *)data;
2028         int ret = 0;
2029
2030         LASSERT(parent != NULL || d != NULL);
2031
2032         if (param->obduuid) {
2033                 param->quiet = 1;
2034                 ret = setup_obd_uuid(d ? d : parent, path, param);
2035                 if (ret)
2036                         return ret;
2037         }
2038
2039         if (d) {
2040                 ret = ioctl(dirfd(d), LL_IOC_LOV_GETSTRIPE,
2041                             (void *)&param->lmd->lmd_lmm);
2042         } else if (parent) {
2043                 char *fname = strrchr(path, '/');
2044                 fname = (fname == NULL ? path : fname + 1);
2045
2046                 strncpy((char *)&param->lmd->lmd_lmm, fname, param->lumlen);
2047
2048                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILESTRIPE,
2049                             (void *)&param->lmd->lmd_lmm);
2050         }
2051
2052         if (ret) {
2053                 if (errno == ENODATA) {
2054                         if (!param->obduuid)
2055                                 llapi_printf(LLAPI_MSG_NORMAL,
2056                                              "%s has no stripe info\n", path);
2057                         goto out;
2058                 } else if (errno == ENOTTY) {
2059                         llapi_err(LLAPI_MSG_ERROR,
2060                                   "%s: '%s' not on a Lustre fs?",
2061                                   __func__, path);
2062                 } else if (errno == ENOENT) {
2063                         llapi_err(LLAPI_MSG_WARN,
2064                                   "warning: %s: %s does not exist",
2065                                   __func__, path);
2066                         goto out;
2067                 } else {
2068                         llapi_err(LLAPI_MSG_ERROR,
2069                                   "error: %s: %s failed for %s",
2070                                    __func__, d ? "LL_IOC_LOV_GETSTRIPE" :
2071                                   "IOC_MDC_GETFILESTRIPE", path);
2072                 }
2073
2074                 return ret;
2075         }
2076
2077         if (!param->get_mdt_index)
2078                 llapi_lov_dump_user_lmm(param, path, d ? 1 : 0);
2079
2080 out:
2081         /* Do not get down anymore? */
2082         if (param->depth == param->maxdepth)
2083                 return 1;
2084
2085         param->depth++;
2086         return 0;
2087 }
2088
2089 int llapi_getstripe(char *path, struct find_param *param)
2090 {
2091         return param_callback(path, param->get_mdt_index ?
2092                               cb_get_mdt_index : cb_getstripe,
2093                               cb_common_fini, param);
2094 }
2095
2096 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
2097                      struct obd_statfs *stat_buf,
2098                      struct obd_uuid *uuid_buf)
2099 {
2100         int fd;
2101         char raw[OBD_MAX_IOCTL_BUFFER] = {'\0'};
2102         char *rawbuf = raw;
2103         struct obd_ioctl_data data = { 0 };
2104         int rc = 0;
2105
2106         data.ioc_inlbuf1 = (char *)&type;
2107         data.ioc_inllen1 = sizeof(__u32);
2108         data.ioc_inlbuf2 = (char *)&index;
2109         data.ioc_inllen2 = sizeof(__u32);
2110         data.ioc_pbuf1 = (char *)stat_buf;
2111         data.ioc_plen1 = sizeof(struct obd_statfs);
2112         data.ioc_pbuf2 = (char *)uuid_buf;
2113         data.ioc_plen2 = sizeof(struct obd_uuid);
2114
2115         if ((rc = obd_ioctl_pack(&data, &rawbuf, sizeof(raw))) != 0) {
2116                 llapi_err(LLAPI_MSG_ERROR,
2117                           "llapi_obd_statfs: error packing ioctl data");
2118                 return rc;
2119         }
2120
2121         fd = open(path, O_RDONLY);
2122         if (errno == EISDIR)
2123                 fd = open(path, O_DIRECTORY | O_RDONLY);
2124
2125         if (fd < 0) {
2126                 rc = errno ? -errno : -EBADF;
2127                 llapi_err(LLAPI_MSG_ERROR, "error: %s: opening '%s'",
2128                           __func__, path);
2129                 return rc;
2130         }
2131         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
2132         if (rc)
2133                 rc = errno ? -errno : -EINVAL;
2134
2135         close(fd);
2136         return rc;
2137 }
2138
2139 #define MAX_STRING_SIZE 128
2140 #define DEVICES_LIST "/proc/fs/lustre/devices"
2141
2142 int llapi_ping(char *obd_type, char *obd_name)
2143 {
2144         char path[MAX_STRING_SIZE];
2145         char buf[1];
2146         int rc, fd;
2147
2148         snprintf(path, MAX_STRING_SIZE, "/proc/fs/lustre/%s/%s/ping",
2149                  obd_type, obd_name);
2150
2151         fd = open(path, O_WRONLY);
2152         if (fd < 0) {
2153                 rc = errno;
2154                 llapi_err(LLAPI_MSG_ERROR, "error opening %s", path);
2155                 return rc;
2156         }
2157
2158         rc = write(fd, buf, 1);
2159         close(fd);
2160
2161         if (rc == 1)
2162                 return 0;
2163         return rc;
2164 }
2165
2166 int llapi_target_iterate(int type_num, char **obd_type,void *args,llapi_cb_t cb)
2167 {
2168         char buf[MAX_STRING_SIZE];
2169         FILE *fp = fopen(DEVICES_LIST, "r");
2170         int i, rc = 0;
2171
2172         if (fp == NULL) {
2173                 rc = errno;
2174                 llapi_err(LLAPI_MSG_ERROR, "error: opening "DEVICES_LIST);
2175                 return rc;
2176         }
2177
2178         while (fgets(buf, sizeof(buf), fp) != NULL) {
2179                 char *obd_type_name = NULL;
2180                 char *obd_name = NULL;
2181                 char *obd_uuid = NULL;
2182                 char *bufp = buf;
2183                 struct obd_ioctl_data datal = { 0, };
2184                 struct obd_statfs osfs_buffer;
2185
2186                 while(bufp[0] == ' ')
2187                         ++bufp;
2188
2189                 for(i = 0; i < 3; i++) {
2190                         obd_type_name = strsep(&bufp, " ");
2191                 }
2192                 obd_name = strsep(&bufp, " ");
2193                 obd_uuid = strsep(&bufp, " ");
2194
2195                 memset(&osfs_buffer, 0, sizeof (osfs_buffer));
2196
2197                 datal.ioc_pbuf1 = (char *)&osfs_buffer;
2198                 datal.ioc_plen1 = sizeof(osfs_buffer);
2199
2200                 for (i = 0; i < type_num; i++) {
2201                         if (strcmp(obd_type_name, obd_type[i]) != 0)
2202                                 continue;
2203
2204                         cb(obd_type_name, obd_name, obd_uuid, args);
2205                 }
2206         }
2207         fclose(fp);
2208         return rc;
2209 }
2210
2211 static void do_target_check(char *obd_type_name, char *obd_name,
2212                             char *obd_uuid, void *args)
2213 {
2214         int rc;
2215
2216         rc = llapi_ping(obd_type_name, obd_name);
2217         if (rc == ENOTCONN) {
2218                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
2219         } else if (rc) {
2220                 llapi_err(LLAPI_MSG_ERROR, "error: check '%s'", obd_name);
2221         } else {
2222                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
2223         }
2224 }
2225
2226 int llapi_target_check(int type_num, char **obd_type, char *dir)
2227 {
2228         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
2229 }
2230
2231 #undef MAX_STRING_SIZE
2232
2233 int llapi_catinfo(char *dir, char *keyword, char *node_name)
2234 {
2235         char raw[OBD_MAX_IOCTL_BUFFER];
2236         char out[LLOG_CHUNK_SIZE];
2237         char *buf = raw;
2238         struct obd_ioctl_data data = { 0 };
2239         char key[30];
2240         DIR *root;
2241         int rc;
2242
2243         sprintf(key, "%s", keyword);
2244         memset(raw, 0, sizeof(raw));
2245         memset(out, 0, sizeof(out));
2246         data.ioc_inlbuf1 = key;
2247         data.ioc_inllen1 = strlen(key) + 1;
2248         if (node_name) {
2249                 data.ioc_inlbuf2 = node_name;
2250                 data.ioc_inllen2 = strlen(node_name) + 1;
2251         }
2252         data.ioc_pbuf1 = out;
2253         data.ioc_plen1 = sizeof(out);
2254         rc = obd_ioctl_pack(&data, &buf, sizeof(raw));
2255         if (rc)
2256                 return rc;
2257
2258         root = opendir(dir);
2259         if (root == NULL) {
2260                 rc = errno;
2261                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", dir);
2262                 return rc;
2263         }
2264
2265         rc = ioctl(dirfd(root), OBD_IOC_LLOG_CATINFO, buf);
2266         if (rc)
2267                 llapi_err(LLAPI_MSG_ERROR, "ioctl OBD_IOC_CATINFO failed");
2268         else
2269                 llapi_printf(LLAPI_MSG_NORMAL, "%s", data.ioc_pbuf1);
2270
2271         closedir(root);
2272         return rc;
2273 }
2274
2275 /* Is this a lustre fs? */
2276 int llapi_is_lustre_mnttype(const char *type)
2277 {
2278         return (strcmp(type, "lustre") == 0 || strcmp(type,"lustre_lite") == 0);
2279 }
2280
2281 /* Is this a lustre client fs? */
2282 int llapi_is_lustre_mnt(struct mntent *mnt)
2283 {
2284         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
2285                 strstr(mnt->mnt_fsname, ":/") != NULL);
2286 }
2287
2288 int llapi_quotacheck(char *mnt, int check_type)
2289 {
2290         DIR *root;
2291         int rc;
2292
2293         root = opendir(mnt);
2294         if (!root) {
2295                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2296                 return -1;
2297         }
2298
2299         rc = ioctl(dirfd(root), LL_IOC_QUOTACHECK, check_type);
2300
2301         closedir(root);
2302         return rc;
2303 }
2304
2305 int llapi_poll_quotacheck(char *mnt, struct if_quotacheck *qchk)
2306 {
2307         DIR *root;
2308         int poll_intvl = 2;
2309         int rc;
2310
2311         root = opendir(mnt);
2312         if (!root) {
2313                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2314                 return -1;
2315         }
2316
2317         while (1) {
2318                 rc = ioctl(dirfd(root), LL_IOC_POLL_QUOTACHECK, qchk);
2319                 if (!rc)
2320                         break;
2321                 sleep(poll_intvl);
2322                 if (poll_intvl < 30)
2323                         poll_intvl *= 2;
2324         }
2325
2326         closedir(root);
2327         return rc;
2328 }
2329
2330 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
2331 {
2332         DIR *root;
2333         int rc;
2334
2335         root = opendir(mnt);
2336         if (!root) {
2337                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2338                 return -1;
2339         }
2340
2341         rc = ioctl(dirfd(root), LL_IOC_QUOTACTL, qctl);
2342
2343         closedir(root);
2344         return rc;
2345 }
2346
2347 static int cb_quotachown(char *path, DIR *parent, DIR *d, void *data,
2348                          cfs_dirent_t *de)
2349 {
2350         struct find_param *param = (struct find_param *)data;
2351         lstat_t *st;
2352         int rc;
2353
2354         LASSERT(parent != NULL || d != NULL);
2355
2356         if (d) {
2357                 rc = ioctl(dirfd(d), LL_IOC_MDC_GETINFO,
2358                            (void *)param->lmd);
2359         } else if (parent) {
2360                 char *fname = strrchr(path, '/');
2361                 fname = (fname == NULL ? path : fname + 1);
2362
2363                 strncpy((char *)param->lmd, fname, param->lumlen);
2364                 rc = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
2365                            (void *)param->lmd);
2366         } else {
2367                 return 0;
2368         }
2369
2370         if (rc) {
2371                 if (errno == ENODATA) {
2372                         if (!param->obduuid && !param->quiet)
2373                                 llapi_err(LLAPI_MSG_ERROR,
2374                                           "%s has no stripe info", path);
2375                         rc = 0;
2376                 } else if (errno == ENOENT) {
2377                         llapi_err(LLAPI_MSG_ERROR,
2378                                   "warning: %s: %s does not exist",
2379                                   __func__, path);
2380                         rc = 0;
2381                 } else if (errno != EISDIR) {
2382                         rc = errno;
2383                         llapi_err(LLAPI_MSG_ERROR, "%s ioctl failed for %s.",
2384                                   d ? "LL_IOC_MDC_GETINFO" :
2385                                   "IOC_MDC_GETFILEINFO", path);
2386                 }
2387                 return rc;
2388         }
2389
2390         st = &param->lmd->lmd_st;
2391
2392         /* libc chown() will do extra check, and if the real owner is
2393          * the same as the ones to set, it won't fall into kernel, so
2394          * invoke syscall directly. */
2395         rc = syscall(SYS_chown, path, -1, -1);
2396         if (rc)
2397                 llapi_err(LLAPI_MSG_ERROR,"error: chown %s (%u,%u)", path);
2398
2399         rc = chmod(path, st->st_mode);
2400         if (rc)
2401                 llapi_err(LLAPI_MSG_ERROR, "error: chmod %s (%hu)",
2402                           path, st->st_mode);
2403
2404         return rc;
2405 }
2406
2407 int llapi_quotachown(char *path, int flag)
2408 {
2409         struct find_param param;
2410
2411         memset(&param, 0, sizeof(param));
2412         param.recursive = 1;
2413         param.verbose = 0;
2414         param.quiet = 1;
2415
2416         return param_callback(path, cb_quotachown, NULL, &param);
2417 }
2418
2419 #include <pwd.h>
2420 #include <grp.h>
2421 #include <mntent.h>
2422 #include <sys/wait.h>
2423 #include <errno.h>
2424 #include <ctype.h>
2425
2426 static int rmtacl_notify(int ops)
2427 {
2428         FILE *fp;
2429         struct mntent *mnt;
2430         int found = 0, fd, rc;
2431
2432         fp = setmntent(MOUNTED, "r");
2433         if (fp == NULL) {
2434                 perror("setmntent");
2435                 return -1;
2436         }
2437
2438         while (1) {
2439                 mnt = getmntent(fp);
2440                 if (!mnt)
2441                         break;
2442
2443                 if (!llapi_is_lustre_mnt(mnt))
2444                         continue;
2445
2446                 fd = open(mnt->mnt_dir, O_RDONLY | O_DIRECTORY);
2447                 if (fd < 0) {
2448                         perror("open");
2449                         return -1;
2450                 }
2451
2452                 rc = ioctl(fd, LL_IOC_RMTACL, ops);
2453                 if (rc < 0) {
2454                         perror("ioctl");
2455                 return -1;
2456                 }
2457
2458                 found++;
2459         }
2460         endmntent(fp);
2461         return found;
2462 }
2463
2464 static char *next_token(char *p, int div)
2465 {
2466         if (p == NULL)
2467                 return NULL;
2468
2469         if (div)
2470                 while (*p && *p != ':' && !isspace(*p))
2471                         p++;
2472         else
2473                 while (*p == ':' || isspace(*p))
2474                         p++;
2475
2476         return *p ? p : NULL;
2477 }
2478
2479 static int rmtacl_name2id(char *name, int is_user)
2480 {
2481         if (is_user) {
2482                 struct passwd *pw;
2483
2484                 if ((pw = getpwnam(name)) == NULL)
2485                         return INVALID_ID;
2486                 else
2487                         return (int)(pw->pw_uid);
2488         } else {
2489                 struct group *gr;
2490
2491                 if ((gr = getgrnam(name)) == NULL)
2492                         return INVALID_ID;
2493                 else
2494                         return (int)(gr->gr_gid);
2495         }
2496 }
2497
2498 static int isodigit(int c)
2499 {
2500         return (c >= '0' && c <= '7') ? 1 : 0;
2501 }
2502
2503 /*
2504  * Whether the name is just digits string (uid/gid) already or not.
2505  * Return value:
2506  * 1: str is id
2507  * 0: str is not id
2508  */
2509 static int str_is_id(char *str)
2510 {
2511         if (str == NULL)
2512                 return 0;
2513
2514         if (*str == '0') {
2515                 str++;
2516                 if (*str == 'x' || *str == 'X') { /* for Hex. */
2517                         if (!isxdigit(*(++str)))
2518                                 return 0;
2519
2520                         while (isxdigit(*(++str)));
2521                 } else if (isodigit(*str)) { /* for Oct. */
2522                         while (isodigit(*(++str)));
2523                 }
2524         } else if (isdigit(*str)) { /* for Dec. */
2525                 while (isdigit(*(++str)));
2526         }
2527
2528         return (*str == 0) ? 1 : 0;
2529 }
2530
2531 typedef struct {
2532         char *name;
2533         int   length;
2534         int   is_user;
2535         int   next_token;
2536 } rmtacl_name_t;
2537
2538 #define RMTACL_OPTNAME(name) name, sizeof(name) - 1
2539
2540 static rmtacl_name_t rmtacl_namelist[] = {
2541         { RMTACL_OPTNAME("user:"),            1,      0 },
2542         { RMTACL_OPTNAME("group:"),           0,      0 },
2543         { RMTACL_OPTNAME("default:user:"),    1,      0 },
2544         { RMTACL_OPTNAME("default:group:"),   0,      0 },
2545         /* for --tabular option */
2546         { RMTACL_OPTNAME("user"),             1,      1 },
2547         { RMTACL_OPTNAME("group"),            0,      1 },
2548         { 0 }
2549 };
2550
2551 static int rgetfacl_output(char *str)
2552 {
2553         char *start = NULL, *end = NULL;
2554         int is_user = 0, n, id;
2555         char c;
2556         rmtacl_name_t *rn;
2557
2558         if (str == NULL)
2559                 return -1;
2560
2561         for (rn = rmtacl_namelist; rn->name; rn++) {
2562                 if(strncmp(str, rn->name, rn->length) == 0) {
2563                         if (!rn->next_token)
2564                                 start = str + rn->length;
2565                         else
2566                                 start = next_token(str + rn->length, 0);
2567                         is_user = rn->is_user;
2568                         break;
2569                 }
2570         }
2571
2572         end = next_token(start, 1);
2573         if (end == NULL || start == end) {
2574                 n = printf("%s", str);
2575                 return n;
2576         }
2577
2578         c = *end;
2579         *end = 0;
2580         id = rmtacl_name2id(start, is_user);
2581         if (id == INVALID_ID) {
2582                 if (str_is_id(start)) {
2583                         *end = c;
2584                         n = printf("%s", str);
2585                 } else
2586                         return -1;
2587         } else if ((id == NOBODY_UID && is_user) ||
2588                    (id == NOBODY_GID && !is_user)) {
2589                 *end = c;
2590                 n = printf("%s", str);
2591         } else {
2592                 *end = c;
2593                 *start = 0;
2594                 n = printf("%s%d%s", str, id, end);
2595         }
2596         return n;
2597 }
2598
2599 static int child_status(int status)
2600 {
2601         return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
2602 }
2603
2604 static int do_rmtacl(int argc, char *argv[], int ops, int (output_func)(char *))
2605 {
2606         pid_t pid = 0;
2607         int fd[2], status;
2608         FILE *fp;
2609         char buf[PIPE_BUF];
2610
2611         if (output_func) {
2612                 if (pipe(fd) < 0) {
2613                         perror("pipe");
2614                         return -1;
2615                 }
2616
2617                 if ((pid = fork()) < 0) {
2618                         perror("fork");
2619                         close(fd[0]);
2620                         close(fd[1]);
2621                         return -1;
2622                 } else if (!pid) {
2623                         /* child process redirects its output. */
2624                         close(fd[0]);
2625                         close(1);
2626                         if (dup2(fd[1], 1) < 0) {
2627                                 perror("dup2");
2628                                 close(fd[1]);
2629                                 return -1;
2630                         }
2631                 } else {
2632                         close(fd[1]);
2633                 }
2634         }
2635
2636         if (!pid) {
2637                 status = rmtacl_notify(ops);
2638                 if (status < 0)
2639                         return -1;
2640
2641                 exit(execvp(argv[0], argv));
2642         }
2643
2644         /* the following is parent process */
2645         if ((fp = fdopen(fd[0], "r")) == NULL) {
2646                 perror("fdopen");
2647                 kill(pid, SIGKILL);
2648                 close(fd[0]);
2649                 return -1;
2650         }
2651
2652         while (fgets(buf, PIPE_BUF, fp) != NULL) {
2653                 if (output_func(buf) < 0)
2654                         fprintf(stderr, "WARNING: unexpected error!\n[%s]\n",
2655                                 buf);
2656         }
2657         fclose(fp);
2658         close(fd[0]);
2659
2660         if (waitpid(pid, &status, 0) < 0) {
2661                 perror("waitpid");
2662                 return -1;
2663         }
2664
2665         return child_status(status);
2666 }
2667
2668 int llapi_lsetfacl(int argc, char *argv[])
2669 {
2670         return do_rmtacl(argc, argv, RMT_LSETFACL, NULL);
2671 }
2672
2673 int llapi_lgetfacl(int argc, char *argv[])
2674 {
2675         return do_rmtacl(argc, argv, RMT_LGETFACL, NULL);
2676 }
2677
2678 int llapi_rsetfacl(int argc, char *argv[])
2679 {
2680         return do_rmtacl(argc, argv, RMT_RSETFACL, NULL);
2681 }
2682
2683 int llapi_rgetfacl(int argc, char *argv[])
2684 {
2685         return do_rmtacl(argc, argv, RMT_RGETFACL, rgetfacl_output);
2686 }
2687
2688 int llapi_cp(int argc, char *argv[])
2689 {
2690         int rc;
2691
2692         rc = rmtacl_notify(RMT_RSETFACL);
2693         if (rc < 0)
2694                 return -1;
2695
2696         exit(execvp(argv[0], argv));
2697 }
2698
2699 int llapi_ls(int argc, char *argv[])
2700 {
2701         int rc;
2702
2703         rc = rmtacl_notify(RMT_LGETFACL);
2704         if (rc < 0)
2705                 return -1;
2706
2707         exit(execvp(argv[0], argv));
2708 }
2709
2710 /* Print mdtname 'name' into 'buf' using 'format'.  Add -MDT0000 if needed.
2711  * format must have %s%s, buf must be > 16
2712  * Eg: if name = "lustre-MDT0000", "lustre", or "lustre-MDT0000_UUID"
2713  *     then buf = "lustre-MDT0000"
2714  */
2715 static int get_mdtname(char *name, char *format, char *buf)
2716 {
2717         char suffix[]="-MDT0000";
2718         int len = strlen(name);
2719
2720         if ((len > 5) && (strncmp(name + len - 5, "_UUID", 5) == 0)) {
2721                 name[len - 5] = '\0';
2722                 len -= 5;
2723         }
2724
2725         if (len > 8) {
2726                 if ((len <= 16) && strncmp(name + len - 8, "-MDT", 4) == 0) {
2727                         suffix[0] = '\0';
2728                 } else {
2729                         /* Not enough room to add suffix */
2730                         llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2731                                   "MDT name too long |%s|", name);
2732                         return -EINVAL;
2733                 }
2734         }
2735
2736         return sprintf(buf, format, name, suffix);
2737 }
2738
2739 /** ioctl on filsystem root, with mdtindex sent as data
2740  * \param mdtname path, fsname, or mdtname (lutre-MDT0004)
2741  * \param mdtidxp pointer to integer within data to be filled in with the
2742  *    mdt index (0 if no mdt is specified).  NULL won't be filled.
2743  */
2744 static int root_ioctl(const char *mdtname, int opc, void *data, int *mdtidxp,
2745                       int want_error)
2746 {
2747         char fsname[20];
2748         char *ptr;
2749         int fd, index, rc;
2750
2751         /* Take path, fsname, or MDTname.  Assume MDT0000 in the former cases.
2752          Open root and parse mdt index. */
2753         if (mdtname[0] == '/') {
2754                 index = 0;
2755                 rc = get_root_path(WANT_FD | want_error, NULL, &fd,
2756                                    (char *)mdtname, -1);
2757         } else {
2758                 if (get_mdtname((char *)mdtname, "%s%s", fsname) < 0)
2759                         return -EINVAL;
2760                 ptr = fsname + strlen(fsname) - 8;
2761                 *ptr = '\0';
2762                 index = strtol(ptr + 4, NULL, 10);
2763                 rc = get_root_path(WANT_FD | want_error, fsname, &fd, NULL, -1);
2764         }
2765         if (rc < 0) {
2766                 if (want_error)
2767                         llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2768                                   "Can't open %s: %d\n", mdtname, rc);
2769                 return rc;
2770         }
2771
2772         if (mdtidxp)
2773                 *mdtidxp = index;
2774
2775         rc = ioctl(fd, opc, data);
2776         if (rc && want_error)
2777                 llapi_err(LLAPI_MSG_ERROR, "ioctl %d err %d", opc, rc);
2778
2779         close(fd);
2780         return rc;
2781 }
2782
2783 /****** Changelog API ********/
2784
2785 static int changelog_ioctl(const char *mdtname, int opc, int id,
2786                            long long recno, int flags)
2787 {
2788         struct ioc_changelog data;
2789         int *idx;
2790
2791         data.icc_id = id;
2792         data.icc_recno = recno;
2793         data.icc_flags = flags;
2794         idx = (int *)(&data.icc_mdtindex);
2795
2796         return root_ioctl(mdtname, opc, &data, idx, WANT_ERROR);
2797 }
2798
2799 #define CHANGELOG_PRIV_MAGIC 0xCA8E1080
2800 struct changelog_private {
2801         int magic;
2802         int flags;
2803         lustre_kernelcomm kuc;
2804         char *buf;
2805 };
2806
2807 /** Start reading from a changelog
2808  * @param priv Opaque private control structure
2809  * @param flags Start flags (e.g. CHANGELOG_FLAG_BLOCK)
2810  * @param device Report changes recorded on this MDT
2811  * @param startrec Report changes beginning with this record number
2812  * (just call llapi_changelog_fini when done; don't need an endrec)
2813  */
2814 int llapi_changelog_start(void **priv, int flags, const char *device,
2815                           long long startrec)
2816 {
2817         struct changelog_private *cp;
2818         int rc;
2819
2820         /* Set up the receiver control struct */
2821         cp = malloc(sizeof(*cp));
2822         if (cp == NULL)
2823                 return -ENOMEM;
2824
2825         cp->buf = malloc(CR_MAXSIZE);
2826         if (cp->buf == NULL) {
2827                 rc = -ENOMEM;
2828                 goto out_free;
2829         }
2830
2831         cp->magic = CHANGELOG_PRIV_MAGIC;
2832         cp->flags = flags;
2833
2834         /* Set up the receiver */
2835         rc = libcfs_ukuc_start(&cp->kuc, 0 /* no group registration */);
2836         if (rc < 0)
2837                 goto out_free;
2838
2839         *priv = cp;
2840
2841         /* Tell the kernel to start sending */
2842         rc = changelog_ioctl(device, OBD_IOC_CHANGELOG_SEND, cp->kuc.lk_wfd,
2843                              startrec, flags);
2844         /* Only the kernel reference keeps the write side open */
2845         close(cp->kuc.lk_wfd);
2846         cp->kuc.lk_wfd = 0;
2847         if (rc < 0) {
2848                 /* frees and clears priv */
2849                 llapi_changelog_fini(priv);
2850                 return rc;
2851         }
2852
2853         return 0;
2854
2855 out_free:
2856         if (cp->buf)
2857                 free(cp->buf);
2858         free(cp);
2859         return rc;
2860 }
2861
2862 /** Finish reading from a changelog */
2863 int llapi_changelog_fini(void **priv)
2864 {
2865         struct changelog_private *cp = (struct changelog_private *)*priv;
2866
2867         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
2868                 return -EINVAL;
2869
2870         libcfs_ukuc_stop(&cp->kuc);
2871         free(cp->buf);
2872         free(cp);
2873         *priv = NULL;
2874         return 0;
2875 }
2876
2877 /** Read the next changelog entry
2878  * @param priv Opaque private control structure
2879  * @param rech Changelog record handle; record will be allocated here
2880  * @return 0 valid message received; rec is set
2881  *         <0 error code
2882  *         1 EOF
2883  */
2884 int llapi_changelog_recv(void *priv, struct changelog_rec **rech)
2885 {
2886         struct changelog_private *cp = (struct changelog_private *)priv;
2887         struct kuc_hdr *kuch;
2888         int rc = 0;
2889
2890         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
2891                 return -EINVAL;
2892         if (rech == NULL)
2893                 return -EINVAL;
2894
2895 repeat:
2896         rc = libcfs_ukuc_msg_get(&cp->kuc, cp->buf, CR_MAXSIZE,
2897                                  KUC_TRANSPORT_CHANGELOG);
2898         if (rc < 0)
2899                 return rc;
2900
2901         kuch = (struct kuc_hdr *)cp->buf;
2902         if ((kuch->kuc_transport != KUC_TRANSPORT_CHANGELOG) ||
2903             ((kuch->kuc_msgtype != CL_RECORD) &&
2904              (kuch->kuc_msgtype != CL_EOF))) {
2905                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2906                           "Unknown changelog message type %d:%d\n",
2907                           kuch->kuc_transport, kuch->kuc_msgtype);
2908                 rc = -EPROTO;
2909                 goto out_free;
2910         }
2911
2912         if (kuch->kuc_msgtype == CL_EOF) {
2913                 if (cp->flags & CHANGELOG_FLAG_FOLLOW) {
2914                         /* Ignore EOFs */
2915                         goto repeat;
2916                 } else {
2917                         rc = 1;
2918                         goto out_free;
2919                 }
2920         }
2921
2922         /* Our message is a changelog_rec */
2923         *rech = (struct changelog_rec *)(kuch + 1);
2924
2925         return 0;
2926
2927 out_free:
2928         *rech = NULL;
2929         return rc;
2930 }
2931
2932 /** Release the changelog record when done with it. */
2933 int llapi_changelog_free(struct changelog_rec **rech)
2934 {
2935         *rech = NULL;
2936         return 0;
2937 }
2938
2939 int llapi_changelog_clear(const char *mdtname, const char *idstr,
2940                           long long endrec)
2941 {
2942         int id;
2943
2944         if (endrec < 0) {
2945                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2946                           "can't purge negative records\n");
2947                 return -EINVAL;
2948         }
2949
2950         id = strtol(idstr + strlen(CHANGELOG_USER_PREFIX), NULL, 10);
2951         if ((id == 0) || (strncmp(idstr, CHANGELOG_USER_PREFIX,
2952                                   strlen(CHANGELOG_USER_PREFIX)) != 0)) {
2953                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2954                           "expecting id of the form '"CHANGELOG_USER_PREFIX
2955                           "<num>'; got '%s'\n", idstr);
2956                 return -EINVAL;
2957         }
2958
2959         return changelog_ioctl(mdtname, OBD_IOC_CHANGELOG_CLEAR, id, endrec, 0);
2960 }
2961
2962 int llapi_fid2path(const char *device, const char *fidstr, char *buf,
2963                    int buflen, long long *recno, int *linkno)
2964 {
2965         char path[PATH_MAX];
2966         struct lu_fid fid;
2967         struct getinfo_fid2path *gf;
2968         int fd, rc;
2969
2970         while (*fidstr == '[')
2971                 fidstr++;
2972
2973         sscanf(fidstr, SFID, RFID(&fid));
2974         if (!fid_is_sane(&fid)) {
2975                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2976                           "bad FID format [%s], should be "DFID"\n",
2977                           fidstr, (__u64)1, 2, 0);
2978                 return -EINVAL;
2979         }
2980
2981         /* Take path or fsname */
2982         if (device[0] == '/') {
2983                 strcpy(path, device);
2984         } else {
2985                 rc = get_root_path(WANT_PATH | WANT_ERROR, (char *)device,
2986                                    NULL, path, -1);
2987                 if (rc < 0)
2988                         return rc;
2989         }
2990         sprintf(path, "%s/%s/fid/%s", path, dot_lustre_name, fidstr);
2991         fd = open(path, O_RDONLY | O_NONBLOCK);
2992         if (fd < 0)
2993                 return -errno;
2994
2995         gf = malloc(sizeof(*gf) + buflen);
2996         gf->gf_fid = fid;
2997         gf->gf_recno = *recno;
2998         gf->gf_linkno = *linkno;
2999         gf->gf_pathlen = buflen;
3000         rc = ioctl(fd, OBD_IOC_FID2PATH, gf);
3001         if (rc) {
3002                 llapi_err(LLAPI_MSG_ERROR, "ioctl err %d", rc);
3003         } else {
3004                 memcpy(buf, gf->gf_path, gf->gf_pathlen);
3005                 *recno = gf->gf_recno;
3006                 *linkno = gf->gf_linkno;
3007         }
3008
3009         free(gf);
3010         close(fd);
3011         return rc;
3012 }
3013
3014 static int path2fid_from_lma(const char *path, lustre_fid *fid)
3015 {
3016         char buf[512];
3017         struct lustre_mdt_attrs *lma;
3018         int rc;
3019
3020         rc = lgetxattr(path, XATTR_NAME_LMA, buf, sizeof(buf));
3021         if (rc < 0)
3022                 return -errno;
3023         lma = (struct lustre_mdt_attrs *)buf;
3024         fid_le_to_cpu(fid, &lma->lma_self_fid);
3025         return 0;
3026 }
3027
3028 int llapi_path2fid(const char *path, lustre_fid *fid)
3029 {
3030         int fd, rc;
3031
3032         memset(fid, 0, sizeof(*fid));
3033         fd = open(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
3034         if (fd < 0) {
3035                 if (errno == ELOOP) /* symbolic link */
3036                         return path2fid_from_lma(path, fid);
3037                 return -errno;
3038         }
3039
3040         rc = ioctl(fd, LL_IOC_PATH2FID, fid) < 0 ? -errno : 0;
3041         if (rc == -EINVAL) /* char special device */
3042                 rc = path2fid_from_lma(path, fid);
3043
3044         close(fd);
3045         return rc;
3046 }
3047
3048 /****** HSM Copytool API ********/
3049 #define CT_PRIV_MAGIC 0xC0BE2001
3050 struct copytool_private {
3051         int magic;
3052         char *buf;
3053         char *fsname;
3054         lustre_kernelcomm kuc;
3055         __u32 archives;
3056 };
3057
3058 #include <libcfs/libcfs.h>
3059
3060 /** Register a copytool
3061  * @param[out] priv Opaque private control structure
3062  * @param fsname Lustre filesystem
3063  * @param flags Open flags, currently unused (e.g. O_NONBLOCK)
3064  * @param archive_count
3065  * @param archives Which archive numbers this copytool is responsible for
3066  */
3067 int llapi_copytool_start(void **priv, char *fsname, int flags,
3068                          int archive_count, int *archives)
3069 {
3070         struct copytool_private *ct;
3071         int rc;
3072
3073         if (archive_count > 0 && archives == NULL) {
3074                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
3075                           "NULL archive numbers");
3076                 return -EINVAL;
3077         }
3078
3079         ct = malloc(sizeof(*ct));
3080         if (ct == NULL)
3081                 return -ENOMEM;
3082
3083         ct->buf = malloc(HAL_MAXSIZE);
3084         ct->fsname = malloc(strlen(fsname) + 1);
3085         if (ct->buf == NULL || ct->fsname == NULL) {
3086                 rc = -ENOMEM;
3087                 goto out_err;
3088         }
3089         strcpy(ct->fsname, fsname);
3090         ct->magic = CT_PRIV_MAGIC;
3091         ct->archives = 0;
3092         for (rc = 0; rc < archive_count; rc++) {
3093                 if (archives[rc] > sizeof(ct->archives)) {
3094                         llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
3095                                   "Maximum of %d archives supported",
3096                                   sizeof(ct->archives));
3097                         goto out_err;
3098                 }
3099                 ct->archives |= 1 << archives[rc];
3100         }
3101         /* special case: if no archives specified, default to archive #0. */
3102         if (ct->archives == 0)
3103                 ct->archives = 1;
3104
3105         rc = libcfs_ukuc_start(&ct->kuc, KUC_GRP_HSM);
3106         if (rc < 0)
3107                 goto out_err;
3108
3109         /* Storing archive(s) in lk_data; see mdc_ioc_hsm_ct_start */
3110         ct->kuc.lk_data = ct->archives;
3111         rc = root_ioctl(ct->fsname, LL_IOC_HSM_CT_START, &(ct->kuc), NULL,
3112                         WANT_ERROR);
3113         /* Only the kernel reference keeps the write side open */
3114         close(ct->kuc.lk_wfd);
3115         ct->kuc.lk_wfd = 0;
3116         if (rc < 0)
3117                 goto out_err;
3118
3119         *priv = ct;
3120         return 0;
3121
3122 out_err:
3123         if (ct->buf)
3124                 free(ct->buf);
3125         if (ct->fsname)
3126                 free(ct->fsname);
3127         free(ct);
3128         return rc;
3129 }
3130
3131 /** Deregister a copytool */
3132 int llapi_copytool_fini(void **priv)
3133 {
3134         struct copytool_private *ct = (struct copytool_private *)*priv;
3135
3136         if (!ct || (ct->magic != CT_PRIV_MAGIC))
3137                 return -EINVAL;
3138
3139         /* Tell the kernel to stop sending us messages */
3140         ct->kuc.lk_flags = LK_FLG_STOP;
3141         root_ioctl(ct->fsname, LL_IOC_HSM_CT_START, &(ct->kuc), NULL, 0);
3142
3143         /* Shut down the kernelcomms */
3144         libcfs_ukuc_stop(&ct->kuc);
3145
3146         free(ct->buf);
3147         free(ct->fsname);
3148         free(ct);
3149         *priv = NULL;
3150         return 0;
3151 }
3152
3153 /** Wait for the next hsm_action_list
3154  * @param priv Opaque private control structure
3155  * @param halh Action list handle, will be allocated here
3156  * @param msgsize Number of bytes in the message, will be set here
3157  * @return 0 valid message received; halh and msgsize are set
3158  *         <0 error code
3159  */
3160 int llapi_copytool_recv(void *priv, struct hsm_action_list **halh, int *msgsize)
3161 {
3162         struct copytool_private *ct = (struct copytool_private *)priv;
3163         struct kuc_hdr *kuch;
3164         struct hsm_action_list *hal;
3165         int rc = 0;
3166
3167         if (!ct || (ct->magic != CT_PRIV_MAGIC))
3168                 return -EINVAL;
3169         if (halh == NULL || msgsize == NULL)
3170                 return -EINVAL;
3171
3172         rc = libcfs_ukuc_msg_get(&ct->kuc, ct->buf, HAL_MAXSIZE,
3173                                  KUC_TRANSPORT_HSM);
3174         if (rc < 0)
3175                 return rc;
3176
3177         /* Handle generic messages */
3178         kuch = (struct kuc_hdr *)ct->buf;
3179         if (kuch->kuc_transport == KUC_TRANSPORT_GENERIC &&
3180             kuch->kuc_msgtype == KUC_MSG_SHUTDOWN) {
3181                 rc = -ESHUTDOWN;
3182                 goto out_free;
3183         }
3184
3185         if (kuch->kuc_transport != KUC_TRANSPORT_HSM ||
3186             kuch->kuc_msgtype != HMT_ACTION_LIST) {
3187                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
3188                           "Unknown HSM message type %d:%d\n",
3189                           kuch->kuc_transport, kuch->kuc_msgtype);
3190                 rc = -EPROTO;
3191                 goto out_free;
3192         }
3193
3194         /* Our message is an hsm_action_list */
3195
3196         hal = (struct hsm_action_list *)(kuch + 1);
3197
3198         /* Check that we have registered for this archive # */
3199         if (((1 << hal->hal_archive_num) & ct->archives) == 0) {
3200                     llapi_err(LLAPI_MSG_INFO | LLAPI_MSG_NO_ERRNO,
3201                           "Ignoring request for archive #%d (bitmask %#x)\n",
3202                           hal->hal_archive_num, ct->archives);
3203                 rc = 0;
3204                 goto out_free;
3205         }
3206
3207         *halh = hal;
3208         *msgsize = kuch->kuc_msglen - sizeof(*kuch);
3209         return 0;
3210
3211 out_free:
3212         *halh = NULL;
3213         *msgsize = 0;
3214         return rc;
3215 }
3216
3217 /** Release the action list when done with it. */
3218 int llapi_copytool_free(struct hsm_action_list **hal)
3219 {
3220         *hal = NULL;
3221         return 0;
3222 }
3223
3224
3225