Whamcloud - gitweb
1614dd87002bbc548ab97069bb6a35966558cec6
[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                 if ((want & WANT_INDEX) && (idx++ != index))
524                         continue;
525
526                 mntlen = strlen(mnt.mnt_dir);
527                 ptr = strrchr(mnt.mnt_fsname, '/');
528                 if (!ptr && !len) {
529                         rc = -EINVAL;
530                         break;
531                 }
532                 ptr++;
533
534                 /* Check the fsname for a match, if given */
535                 if (!(want & WANT_FSNAME) && fsname != NULL &&
536                     (strlen(fsname) > 0) && (strcmp(ptr, fsname) != 0))
537                         continue;
538
539                 /* If the path isn't set return the first one we find */
540                 if (path == NULL || strlen(path) == 0) {
541                         strcpy(mntdir, mnt.mnt_dir);
542                         if ((want & WANT_FSNAME) && fsname != NULL)
543                                 strcpy(fsname, ptr);
544                         rc = 0;
545                         break;
546                 /* Otherwise find the longest matching path */
547                 } else if ((strlen(path) >= mntlen) && (mntlen >= len) &&
548                            (strncmp(mnt.mnt_dir, path, mntlen) == 0)) {
549                         strcpy(mntdir, mnt.mnt_dir);
550                         len = mntlen;
551                         if ((want & WANT_FSNAME) && fsname != NULL)
552                                 strcpy(fsname, ptr);
553                         rc = 0;
554                 }
555         }
556         endmntent(fp);
557
558         /* Found it */
559         if (rc == 0) {
560                 if ((want & WANT_PATH) && path != NULL)
561                         strcpy(path, mntdir);
562                 if (want & WANT_FD) {
563                         fd = open(mntdir, O_RDONLY | O_DIRECTORY | O_NONBLOCK);
564                         if (fd < 0) {
565                                 perror("open");
566                                 rc = -errno;
567                         } else {
568                                 *outfd = fd;
569                         }
570                 }
571         } else if (want & WANT_ERROR)
572                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
573                           "can't find fs root for '%s': %d",
574                           (want & WANT_PATH) ? fsname : path, rc);
575         return rc;
576 }
577
578 /*
579  * search lustre mounts
580  *
581  * Calling this function will return to the user the mount point, mntdir, and
582  * the file system name, fsname, if the user passed a buffer to this routine.
583  *
584  * The user inputs are pathname and index. If the pathname is supplied then
585  * the value of the index will be ignored. The pathname will return data if
586  * the pathname is located on a lustre mount. Index is used to pick which
587  * mount point you want in the case of multiple mounted lustre file systems.
588  * See function lfs_osts in lfs.c for a example of the index use.
589  */
590 int llapi_search_mounts(const char *pathname, int index, char *mntdir,
591                         char *fsname)
592 {
593         int want = WANT_PATH, idx = -1;
594
595         if (!pathname) {
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);
1199         int searchlen = strlen(search_uuid);
1200
1201         if (cmplen > 5 && strcmp(real_uuid + cmplen - 5, "_UUID") == 0)
1202                 cmplen -= 5;
1203         if (searchlen > 5 && strcmp(search_uuid + searchlen - 5, "_UUID") == 0)
1204                 searchlen -= 5;
1205
1206         /* The UUIDs may legitimately be different lengths, if
1207          * the system was upgraded from an older version. */
1208         if (cmplen != searchlen)
1209                 return 0;
1210
1211         return (strncmp(search_uuid, real_uuid, cmplen) == 0);
1212 }
1213
1214 /* Here, param->obduuid points to a single obduuid, the index of which is
1215  * returned in param->obdindex */
1216 static int setup_obd_uuid(DIR *dir, char *dname, struct find_param *param)
1217 {
1218         struct obd_uuid lov_uuid;
1219         char uuid[sizeof(struct obd_uuid)];
1220         char buf[1024];
1221         FILE *fp;
1222         int rc = 0, index;
1223
1224         if (param->got_uuids)
1225                 return rc;
1226
1227         /* Get the lov name */
1228         rc = llapi_file_fget_lov_uuid(dirfd(dir), &lov_uuid);
1229         if (rc) {
1230                 if (errno != ENOTTY) {
1231                         rc = errno;
1232                         llapi_err(LLAPI_MSG_ERROR,
1233                                   "error: can't get lov name: %s", dname);
1234                 } else {
1235                         rc = 0;
1236                 }
1237                 return rc;
1238         }
1239
1240         param->got_uuids = 1;
1241
1242         /* Now get the ost uuids from /proc */
1243         snprintf(buf, sizeof(buf), "/proc/fs/lustre/lov/%s/target_obd",
1244                  lov_uuid.uuid);
1245         fp = fopen(buf, "r");
1246         if (fp == NULL) {
1247                 rc = errno;
1248                 llapi_err(LLAPI_MSG_ERROR, "error: opening '%s'", buf);
1249                 return rc;
1250         }
1251
1252         if (!param->obduuid && !param->quiet && !param->obds_printed)
1253                 llapi_printf(LLAPI_MSG_NORMAL, "OBDS:\n");
1254
1255         while (fgets(buf, sizeof(buf), fp) != NULL) {
1256                 if (sscanf(buf, "%d: %s", &index, uuid) < 2)
1257                         break;
1258
1259                 if (param->obduuid) {
1260                         if (llapi_uuid_match(uuid, param->obduuid->uuid)) {
1261                                 param->obdindex = index;
1262                                 break;
1263                         }
1264                 } else if (!param->quiet && !param->obds_printed) {
1265                         /* Print everything */
1266                         llapi_printf(LLAPI_MSG_NORMAL, "%s", buf);
1267                 }
1268         }
1269         param->obds_printed = 1;
1270
1271         fclose(fp);
1272
1273         if (param->obduuid && (param->obdindex == OBD_NOT_FOUND)) {
1274                 llapi_err_noerrno(LLAPI_MSG_ERROR,
1275                                   "error: %s: unknown obduuid: %s",
1276                                   __func__, param->obduuid->uuid);
1277                 rc = -EINVAL;
1278         }
1279
1280         return (rc);
1281 }
1282
1283 /* In this case, param->obduuid will be an array of obduuids and
1284  * obd index for all these obduuids will be returned in
1285  * param->obdindexes */
1286 static int setup_obd_indexes(DIR *dir, struct find_param *param)
1287 {
1288         struct obd_uuid *uuids = NULL;
1289         int obdcount = INIT_ALLOC_NUM_OSTS;
1290         int ret, obd_valid = 0, obdnum, i;
1291
1292         uuids = (struct obd_uuid *)malloc(INIT_ALLOC_NUM_OSTS *
1293                                           sizeof(struct obd_uuid));
1294         if (uuids == NULL)
1295                 return -ENOMEM;
1296
1297 retry_get_uuids:
1298         ret = llapi_lov_get_uuids(dirfd(dir), uuids,
1299                                   &obdcount);
1300         if (ret) {
1301                 struct obd_uuid *uuids_temp;
1302
1303                 if (ret == -EOVERFLOW) {
1304                         uuids_temp = realloc(uuids, obdcount *
1305                                              sizeof(struct obd_uuid));
1306                         if (uuids_temp != NULL)
1307                                 goto retry_get_uuids;
1308                         else
1309                                 ret = -ENOMEM;
1310                 }
1311
1312                 llapi_err(LLAPI_MSG_ERROR, "get ost uuid failed");
1313                 return ret;
1314         }
1315
1316         param->obdindexes = malloc(param->num_obds * sizeof(param->obdindex));
1317         if (param->obdindexes == NULL)
1318                 return -ENOMEM;
1319
1320         for (obdnum = 0; obdnum < param->num_obds; obdnum++) {
1321                 for (i = 0; i < obdcount; i++) {
1322                         if (llapi_uuid_match(uuids[i].uuid,
1323                                              param->obduuid[obdnum].uuid)) {
1324                                 param->obdindexes[obdnum] = i;
1325                                 obd_valid++;
1326                                 break;
1327                         }
1328                 }
1329                 if (i >= obdcount) {
1330                         param->obdindexes[obdnum] = OBD_NOT_FOUND;
1331                         llapi_err_noerrno(LLAPI_MSG_ERROR,
1332                                           "error: %s: unknown obduuid: %s",
1333                                           __func__,
1334                                           param->obduuid[obdnum].uuid);
1335                         ret = -EINVAL;
1336                 }
1337         }
1338
1339         if (obd_valid == 0)
1340                 param->obdindex = OBD_NOT_FOUND;
1341         else
1342                 param->obdindex = obd_valid;
1343
1344         param->got_uuids = 1;
1345
1346         return ret;
1347 }
1348
1349 static int cb_ostlist(char *path, DIR *parent, DIR *d, void *data,
1350                       struct dirent64 *de)
1351 {
1352         struct find_param *param = (struct find_param *)data;
1353
1354         LASSERT(parent != NULL || d != NULL);
1355
1356         /* Prepare odb. */
1357         return setup_obd_uuid(d ? d : parent, path, param);
1358 }
1359
1360 int llapi_ostlist(char *path, struct find_param *param)
1361 {
1362         return param_callback(path, cb_ostlist, cb_common_fini, param);
1363 }
1364
1365 static void lov_dump_user_lmm_header(struct lov_user_md *lum, char *path,
1366                                      int is_dir, int verbose, int depth,
1367                                      char *pool_name)
1368 {
1369         char *prefix = is_dir ? "" : "lmm_";
1370         char nl = is_dir ? ' ' : '\n';
1371
1372         if (is_dir && lum->lmm_object_gr == LOV_OBJECT_GROUP_DEFAULT) {
1373                 lum->lmm_object_gr = LOV_OBJECT_GROUP_CLEAR;
1374                 if (verbose & VERBOSE_DETAIL)
1375                         llapi_printf(LLAPI_MSG_NORMAL, "(Default) ");
1376         }
1377
1378         if (depth && path && ((verbose != VERBOSE_OBJID) || !is_dir))
1379                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
1380
1381         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
1382                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_magic:          0x%08X\n",
1383                              lum->lmm_magic);
1384                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_gr:      "LPX64"\n",
1385                              lum->lmm_object_gr);
1386                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_id:      "LPX64"\n",
1387                              lum->lmm_object_id);
1388         }
1389
1390         if (verbose & VERBOSE_COUNT) {
1391                 if (verbose & ~VERBOSE_COUNT)
1392                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_count:   ",
1393                                      prefix);
1394                 llapi_printf(LLAPI_MSG_NORMAL, "%hd%c",
1395                              (__s16)lum->lmm_stripe_count, nl);
1396         }
1397
1398         if (verbose & VERBOSE_SIZE) {
1399                 if (verbose & ~VERBOSE_SIZE)
1400                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_size:    ",
1401                                      prefix);
1402                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c", lum->lmm_stripe_size,
1403                              nl);
1404         }
1405
1406         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
1407                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_stripe_pattern: %x%c",
1408                              lum->lmm_pattern, nl);
1409         }
1410
1411         if (verbose & VERBOSE_OFFSET) {
1412                 if (verbose & ~VERBOSE_OFFSET)
1413                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_offset:  ",
1414                                      prefix);
1415                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
1416                              lum->lmm_objects[0].l_ost_idx, nl);
1417         }
1418
1419         if ((verbose & VERBOSE_POOL) && (pool_name != NULL)) {
1420                 llapi_printf(LLAPI_MSG_NORMAL, "pool: %s", pool_name);
1421                 is_dir = 1;
1422         }
1423
1424         if (is_dir && (verbose != VERBOSE_OBJID))
1425                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1426 }
1427
1428 void lov_dump_user_lmm_v1v3(struct lov_user_md *lum, char *pool_name,
1429                             struct lov_user_ost_data_v1 *objects,
1430                             char *path, int is_dir,
1431                             int obdindex, int depth, int header)
1432 {
1433         int i, obdstripe = (obdindex != OBD_NOT_FOUND) ? 0 : 1;
1434
1435         if (!obdstripe) {
1436                 for (i = 0; !is_dir && i < lum->lmm_stripe_count; i++) {
1437                         if (obdindex == objects[i].l_ost_idx) {
1438                                 obdstripe = 1;
1439                                 break;
1440                         }
1441                 }
1442         }
1443
1444         if (obdstripe == 1)
1445                 lov_dump_user_lmm_header(lum, path, is_dir, header, depth,
1446                                          pool_name);
1447
1448         if (!is_dir && (header & VERBOSE_OBJID)) {
1449                 if (obdstripe == 1)
1450                         llapi_printf(LLAPI_MSG_NORMAL,
1451                                      "\tobdidx\t\t objid\t\tobjid\t\t group\n");
1452
1453                 for (i = 0; i < lum->lmm_stripe_count; i++) {
1454                         int idx = objects[i].l_ost_idx;
1455                         long long oid = objects[i].l_object_id;
1456                         long long gr = objects[i].l_object_gr;
1457                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
1458                                 llapi_printf(LLAPI_MSG_NORMAL,
1459                                            "\t%6u\t%14llu\t%#13llx\t%14llu%s\n",
1460                                            idx, oid, oid, gr,
1461                                            obdindex == idx ? " *" : "");
1462                 }
1463                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1464         }
1465 }
1466
1467 void llapi_lov_dump_user_lmm(struct find_param *param,
1468                              char *path, int is_dir)
1469 {
1470         switch(*(__u32 *)&param->lmd->lmd_lmm) { /* lum->lmm_magic */
1471         case LOV_USER_MAGIC_V1:
1472                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, NULL,
1473                                        param->lmd->lmd_lmm.lmm_objects,
1474                                        path, is_dir,
1475                                        param->obdindex, param->maxdepth,
1476                                        param->verbose);
1477                 break;
1478         case LOV_USER_MAGIC_V3: {
1479                 char pool_name[LOV_MAXPOOLNAME + 1];
1480                 struct lov_user_ost_data_v1 *objects;
1481                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
1482
1483                 strncpy(pool_name, lmmv3->lmm_pool_name, LOV_MAXPOOLNAME);
1484                 pool_name[LOV_MAXPOOLNAME] = '\0';
1485                 objects = lmmv3->lmm_objects;
1486                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, pool_name,
1487                                        objects, path, is_dir,
1488                                        param->obdindex, param->maxdepth,
1489                                        param->verbose);
1490                 break;
1491         }
1492         default:
1493                 llapi_printf(LLAPI_MSG_NORMAL, "unknown lmm_magic:  %#x "
1494                              "(expecting one of %#x %#x %#x)\n",
1495                              *(__u32 *)&param->lmd->lmd_lmm,
1496                              LOV_USER_MAGIC_V1, LOV_USER_MAGIC_V3);
1497                 return;
1498         }
1499 }
1500
1501 int llapi_file_get_stripe(const char *path, struct lov_user_md *lum)
1502 {
1503         const char *fname;
1504         char *dname;
1505         int fd, rc = 0;
1506
1507         fname = strrchr(path, '/');
1508
1509         /* It should be a file (or other non-directory) */
1510         if (fname == NULL) {
1511                 dname = (char *)malloc(2);
1512                 if (dname == NULL)
1513                         return ENOMEM;
1514                 strcpy(dname, ".");
1515                 fname = (char *)path;
1516         } else {
1517                 dname = (char *)malloc(fname - path + 1);
1518                 if (dname == NULL)
1519                         return ENOMEM;
1520                 strncpy(dname, path, fname - path);
1521                 dname[fname - path] = '\0';
1522                 fname++;
1523         }
1524
1525         if ((fd = open(dname, O_RDONLY)) == -1) {
1526                 rc = errno;
1527                 free(dname);
1528                 return rc;
1529         }
1530
1531         strcpy((char *)lum, fname);
1532         if (ioctl(fd, IOC_MDC_GETFILESTRIPE, (void *)lum) == -1)
1533                 rc = errno;
1534
1535         if (close(fd) == -1 && rc == 0)
1536                 rc = errno;
1537
1538         free(dname);
1539
1540         return rc;
1541 }
1542
1543 int llapi_file_lookup(int dirfd, const char *name)
1544 {
1545         struct obd_ioctl_data data = { 0 };
1546         char rawbuf[8192];
1547         char *buf = rawbuf;
1548         int rc;
1549
1550         if (dirfd < 0 || name == NULL)
1551                 return -EINVAL;
1552
1553         data.ioc_version = OBD_IOCTL_VERSION;
1554         data.ioc_len = sizeof(data);
1555         data.ioc_inlbuf1 = (char *)name;
1556         data.ioc_inllen1 = strlen(name) + 1;
1557
1558         rc = obd_ioctl_pack(&data, &buf, sizeof(rawbuf));
1559         if (rc) {
1560                 llapi_err(LLAPI_MSG_ERROR,
1561                           "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
1562                           name, rc);
1563                 return rc;
1564         }
1565
1566         return ioctl(dirfd, IOC_MDC_LOOKUP, buf);
1567 }
1568
1569 /* Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
1570  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
1571  *
1572  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
1573  * The table below gives the answers for the specified parameters (value and
1574  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
1575  * --------------------------------------
1576  * 1 | file > limit; sign > 0 | -1 / -1 |
1577  * 2 | file = limit; sign > 0 |  ? /  1 |
1578  * 3 | file < limit; sign > 0 |  ? /  1 |
1579  * 4 | file > limit; sign = 0 | -1 / -1 |
1580  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
1581  * 6 | file < limit; sign = 0 |  ? / -1 |
1582  * 7 | file > limit; sign < 0 |  1 /  1 |
1583  * 8 | file = limit; sign < 0 |  ? / -1 |
1584  * 9 | file < limit; sign < 0 |  ? / -1 |
1585  * --------------------------------------
1586  * Note: 5th actually means that the value is within the interval
1587  * (limit - margin, limit]. */
1588 static int find_value_cmp(unsigned int file, unsigned int limit, int sign,
1589                           unsigned long long margin, int mds)
1590 {
1591         if (sign > 0) {
1592                 if (file < limit)
1593                         return mds ? 0 : 1;
1594         }
1595
1596         if (sign == 0) {
1597                 if (file <= limit && file + margin > limit)
1598                         return mds ? 0 : 1;
1599                 if (file + margin <= limit)
1600                         return mds ? 0 : -1;
1601         }
1602
1603         if (sign < 0) {
1604                 if (file > limit)
1605                         return 1;
1606                 if (mds)
1607                         return 0;
1608         }
1609
1610         return -1;
1611 }
1612
1613 /* Check if the file time matches all the given criteria (e.g. --atime +/-N).
1614  * Return -1 or 1 if file timestamp does not or does match the given criteria
1615  * correspondingly. Return 0 if the MDS time is being checked and there are
1616  * attributes on OSTs and it is not yet clear if the timespamp matches.
1617  *
1618  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
1619  * updated timestamps. */
1620 static int find_time_check(lstat_t *st, struct find_param *param, int mds)
1621 {
1622         int ret;
1623         int rc = 0;
1624
1625         /* Check if file is accepted. */
1626         if (param->atime) {
1627                 ret = find_value_cmp(st->st_atime, param->atime,
1628                                      param->asign, 24 * 60 * 60, mds);
1629                 if (ret < 0)
1630                         return ret;
1631                 rc = ret;
1632         }
1633
1634         if (param->mtime) {
1635                 ret = find_value_cmp(st->st_mtime, param->mtime,
1636                                      param->msign, 24 * 60 * 60, mds);
1637                 if (ret < 0)
1638                         return ret;
1639
1640                 /* If the previous check matches, but this one is not yet clear,
1641                  * we should return 0 to do an RPC on OSTs. */
1642                 if (rc == 1)
1643                         rc = ret;
1644         }
1645
1646         if (param->ctime) {
1647                 ret = find_value_cmp(st->st_ctime, param->ctime,
1648                                      param->csign, 24 * 60 * 60, mds);
1649                 if (ret < 0)
1650                         return ret;
1651
1652                 /* If the previous check matches, but this one is not yet clear,
1653                  * we should return 0 to do an RPC on OSTs. */
1654                 if (rc == 1)
1655                         rc = ret;
1656         }
1657
1658         return rc;
1659 }
1660
1661 static int cb_find_init(char *path, DIR *parent, DIR *dir,
1662                         void *data, cfs_dirent_t *de)
1663 {
1664         struct find_param *param = (struct find_param *)data;
1665         int decision = 1; /* 1 is accepted; -1 is rejected. */
1666         lstat_t *st = &param->lmd->lmd_st;
1667         int lustre_fs = 1;
1668         int checked_type = 0;
1669         int ret = 0;
1670
1671         LASSERT(parent != NULL || dir != NULL);
1672
1673         param->lmd->lmd_lmm.lmm_stripe_count = 0;
1674
1675         /* If a regular expression is presented, make the initial decision */
1676         if (param->pattern != NULL) {
1677                 char *fname = strrchr(path, '/');
1678                 fname = (fname == NULL ? path : fname + 1);
1679                 ret = fnmatch(param->pattern, fname, 0);
1680                 if ((ret == FNM_NOMATCH && !param->exclude_pattern) ||
1681                     (ret == 0 && param->exclude_pattern))
1682                         goto decided;
1683         }
1684
1685         /* See if we can check the file type from the dirent. */
1686         if (param->type && de != NULL && de->d_type != DT_UNKNOWN &&
1687             de->d_type < DT_MAX) {
1688                 checked_type = 1;
1689                 if (llapi_dir_filetype_table[de->d_type] == param->type) {
1690                         if (param->exclude_type)
1691                                 goto decided;
1692                 } else {
1693                         if (!param->exclude_type)
1694                                 goto decided;
1695                 }
1696         }
1697
1698
1699         /* If a time or OST should be checked, the decision is not taken yet. */
1700         if (param->atime || param->ctime || param->mtime || param->obduuid ||
1701             param->size)
1702                 decision = 0;
1703
1704         ret = 0;
1705         /* Request MDS for the stat info. */
1706         if (param->have_fileinfo == 0) {
1707                 if (dir) {
1708                         /* retrieve needed file info */
1709                         ret = ioctl(dirfd(dir), LL_IOC_MDC_GETINFO,
1710                                     (void *)param->lmd);
1711                 } else {
1712                         char *fname = strrchr(path, '/');
1713                         fname = (fname == NULL ? path : fname + 1);
1714
1715                         /* retrieve needed file info */
1716                         strncpy((char *)param->lmd, fname, param->lumlen);
1717                         ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
1718                                    (void *)param->lmd);
1719                 }
1720         }
1721
1722         if (ret) {
1723                 if (errno == ENOTTY) {
1724                         /* ioctl is not supported, it is not a lustre fs.
1725                          * Do the regular lstat(2) instead. */
1726                         lustre_fs = 0;
1727                         ret = lstat_f(path, st);
1728                         if (ret) {
1729                                 llapi_err(LLAPI_MSG_ERROR,
1730                                           "error: %s: lstat failed for %s",
1731                                           __func__, path);
1732                                 return ret;
1733                         }
1734                 } else if (errno == ENOENT) {
1735                         llapi_err(LLAPI_MSG_WARN,
1736                                   "warning: %s: %s does not exist",
1737                                   __func__, path);
1738                         goto decided;
1739                 } else {
1740                         llapi_err(LLAPI_MSG_ERROR,"error: %s: %s failed for %s",
1741                                   __func__, dir ? "LL_IOC_MDC_GETINFO" :
1742                                   "IOC_MDC_GETFILEINFO", path);
1743                         return ret;
1744                 }
1745         }
1746
1747         if (param->type && !checked_type) {
1748                 if ((st->st_mode & S_IFMT) == param->type) {
1749                         if (param->exclude_type)
1750                                 goto decided;
1751                 } else {
1752                         if (!param->exclude_type)
1753                                 goto decided;
1754                 }
1755         }
1756
1757         /* Prepare odb. */
1758         if (param->obduuid) {
1759                 if (lustre_fs && param->got_uuids &&
1760                     param->st_dev != st->st_dev) {
1761                         /* A lustre/lustre mount point is crossed. */
1762                         param->got_uuids = 0;
1763                         param->obds_printed = 0;
1764                         param->obdindex = OBD_NOT_FOUND;
1765                 }
1766
1767                 if (lustre_fs && !param->got_uuids) {
1768                         ret = setup_obd_indexes(dir ? dir : parent, param);
1769                         if (ret)
1770                                 return ret;
1771
1772                         param->st_dev = st->st_dev;
1773                 } else if (!lustre_fs && param->got_uuids) {
1774                         /* A lustre/non-lustre mount point is crossed. */
1775                         param->got_uuids = 0;
1776                         param->obdindex = OBD_NOT_FOUND;
1777                 }
1778         }
1779
1780         /* If an OBD UUID is specified but no one matches, skip this file. */
1781         if (param->obduuid && param->obdindex == OBD_NOT_FOUND)
1782                 goto decided;
1783
1784         /* If a OST UUID is given, and some OST matches, check it here. */
1785         if (param->obdindex != OBD_NOT_FOUND) {
1786                 if (!S_ISREG(st->st_mode))
1787                         goto decided;
1788
1789                 /* Only those files should be accepted, which have a
1790                  * stripe on the specified OST. */
1791                 if (!param->lmd->lmd_lmm.lmm_stripe_count) {
1792                         goto decided;
1793                 } else {
1794                         int i, j;
1795                         struct lov_user_ost_data_v1 *lmm_objects;
1796
1797                         if (param->lmd->lmd_lmm.lmm_magic ==
1798                             LOV_USER_MAGIC_V3) {
1799                                 struct lov_user_md_v3 *lmmv3 =
1800                                         (void *)&param->lmd->lmd_lmm;
1801
1802                                 lmm_objects = lmmv3->lmm_objects;
1803                         } else {
1804                                 lmm_objects = param->lmd->lmd_lmm.lmm_objects;
1805                         }
1806
1807                         for (i = 0;
1808                              i < param->lmd->lmd_lmm.lmm_stripe_count; i++) {
1809                                 for (j = 0; j < param->num_obds; j++) {
1810                                         if (param->obdindexes[j] ==
1811                                             lmm_objects[i].l_ost_idx) {
1812                                                 if (param->exclude_obd)
1813                                                         goto decided;
1814                                                 goto obd_matches;
1815                                         }
1816                                 }
1817                         }
1818
1819                         if (i == param->lmd->lmd_lmm.lmm_stripe_count) {
1820                                 if (param->exclude_obd)
1821                                         goto obd_matches;
1822                                 goto decided;
1823                         }
1824                 }
1825         }
1826
1827         if (param->check_uid) {
1828                 if (st->st_uid == param->uid) {
1829                         if (param->exclude_uid)
1830                                 goto decided;
1831                 } else {
1832                         if (!param->exclude_uid)
1833                                 goto decided;
1834                 }
1835         }
1836
1837         if (param->check_gid) {
1838                 if (st->st_gid == param->gid) {
1839                         if (param->exclude_gid)
1840                                 goto decided;
1841                 } else {
1842                         if (!param->exclude_gid)
1843                                 goto decided;
1844                 }
1845         }
1846
1847         if (param->check_pool) {
1848                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
1849
1850                 /* empty requested pool is taken as no pool search => V1 */
1851                 if (((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V1) &&
1852                      (param->poolname[0] == '\0')) ||
1853                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
1854                      (strncmp(lmmv3->lmm_pool_name,
1855                               param->poolname, LOV_MAXPOOLNAME) == 0)) ||
1856                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
1857                      (strcmp(param->poolname, "*") == 0))) {
1858                         if (param->exclude_pool)
1859                                 goto decided;
1860                 } else {
1861                         if (!param->exclude_pool)
1862                                 goto decided;
1863                 }
1864         }
1865
1866         /* Check the time on mds. */
1867         if (!decision) {
1868                 int for_mds;
1869
1870                 for_mds = lustre_fs ? (S_ISREG(st->st_mode) &&
1871                                        param->lmd->lmd_lmm.lmm_stripe_count)
1872                                     : 0;
1873                 decision = find_time_check(st, param, for_mds);
1874         }
1875
1876 obd_matches:
1877         /* If file still fits the request, ask ost for updated info.
1878            The regular stat is almost of the same speed as some new
1879            'glimpse-size-ioctl'. */
1880         if (!decision && S_ISREG(st->st_mode) &&
1881             param->lmd->lmd_lmm.lmm_stripe_count &&
1882             (param->size ||param->atime || param->mtime || param->ctime)) {
1883                 if (param->obdindex != OBD_NOT_FOUND) {
1884                         /* Check whether the obd is active or not, if it is
1885                          * not active, just print the object affected by this
1886                          * failed ost
1887                          * */
1888                         struct obd_statfs stat_buf;
1889                         struct obd_uuid uuid_buf;
1890
1891                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
1892                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1893                         ret = llapi_obd_statfs(path, LL_STATFS_LOV,
1894                                                param->obdindex, &stat_buf,
1895                                                &uuid_buf);
1896                         if (ret) {
1897                                 if (ret == -ENODATA || ret == -ENODEV
1898                                     || ret == -EIO)
1899                                         errno = EIO;
1900                                 llapi_printf(LLAPI_MSG_NORMAL,
1901                                              "obd_uuid: %s failed %s ",
1902                                              param->obduuid->uuid,
1903                                              strerror(errno));
1904                                 goto print_path;
1905                         }
1906                 }
1907                 if (dir) {
1908                         ret = ioctl(dirfd(dir), IOC_LOV_GETINFO,
1909                                     (void *)param->lmd);
1910                 } else if (parent) {
1911                         ret = ioctl(dirfd(parent), IOC_LOV_GETINFO,
1912                                     (void *)param->lmd);
1913                 }
1914
1915                 if (ret) {
1916                         if (errno == ENOENT) {
1917                                 llapi_err(LLAPI_MSG_ERROR,
1918                                           "warning: %s: %s does not exist",
1919                                           __func__, path);
1920                                 goto decided;
1921                         } else {
1922                                 llapi_err(LLAPI_MSG_ERROR,
1923                                           "%s: IOC_LOV_GETINFO on %s failed",
1924                                           __func__, path);
1925                                 return ret;
1926                         }
1927                 }
1928
1929                 /* Check the time on osc. */
1930                 decision = find_time_check(st, param, 0);
1931                 if (decision == -1)
1932                         goto decided;
1933         }
1934
1935         if (param->size)
1936                 decision = find_value_cmp(st->st_size, param->size,
1937                                           param->size_sign, param->size_units,
1938                                           0);
1939
1940 print_path:
1941         if (decision != -1) {
1942                 llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
1943                 if (param->zeroend)
1944                         llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
1945                 else
1946                         llapi_printf(LLAPI_MSG_NORMAL, "\n");
1947         }
1948
1949 decided:
1950         /* Do not get down anymore? */
1951         if (param->depth == param->maxdepth)
1952                 return 1;
1953
1954         param->depth++;
1955         return 0;
1956 }
1957
1958 int llapi_find(char *path, struct find_param *param)
1959 {
1960         return param_callback(path, cb_find_init, cb_common_fini, param);
1961 }
1962
1963 /*
1964  * Get MDT number that the file/directory inode referenced
1965  * by the open fd resides on.
1966  * Return 0 and mdtidx on success, or -ve errno.
1967  */
1968 int llapi_file_fget_mdtidx(int fd, int *mdtidx)
1969 {
1970         if (ioctl(fd, LL_IOC_GET_MDTIDX, &mdtidx) < 0)
1971                 return -errno;
1972         return 0;
1973 }
1974
1975 static int cb_get_mdt_index(char *path, DIR *parent, DIR *d, void *data,
1976                             cfs_dirent_t *de)
1977 {
1978         struct find_param *param = (struct find_param *)data;
1979         int ret = 0;
1980         int mdtidx;
1981
1982         LASSERT(parent != NULL || d != NULL);
1983
1984         if (d) {
1985                 ret = llapi_file_fget_mdtidx(dirfd(d), &mdtidx);
1986         } else if (parent) {
1987                 int fd;
1988
1989                 fd = open(path, O_RDONLY);
1990                 if (fd > 0) {
1991                         ret = llapi_file_fget_mdtidx(fd, &mdtidx);
1992                         close(fd);
1993                 } else {
1994                         ret = fd;
1995                 }
1996         }
1997
1998         if (ret) {
1999                 if (errno == ENODATA) {
2000                         if (!param->obduuid)
2001                                 llapi_printf(LLAPI_MSG_NORMAL,
2002                                              "%s has no stripe info\n", path);
2003                         goto out;
2004                 } else if (errno == ENOTTY) {
2005                         llapi_err(LLAPI_MSG_ERROR,
2006                                   "%s: '%s' not on a Lustre fs?",
2007                                   __func__, path);
2008                 } else if (errno == ENOENT) {
2009                         llapi_err(LLAPI_MSG_WARN,
2010                                   "warning: %s: %s does not exist",
2011                                   __func__, path);
2012                         goto out;
2013                 } else {
2014                         llapi_err(LLAPI_MSG_ERROR,
2015                                   "error: %s: LL_IOC_GET_MDTIDX failed for %s",
2016                                    __func__, path);
2017                 }
2018                 return ret;
2019         }
2020
2021         if (param->quiet)
2022                 llapi_printf(LLAPI_MSG_NORMAL, "%d\n", mdtidx);
2023         else
2024                 llapi_printf(LLAPI_MSG_NORMAL, "%s MDT index: %d\n",
2025                              path, mdtidx);
2026
2027 out:
2028         /* Do not get down anymore? */
2029         if (param->depth == param->maxdepth)
2030                 return 1;
2031
2032         param->depth++;
2033         return 0;
2034 }
2035
2036 static int cb_getstripe(char *path, DIR *parent, DIR *d, void *data,
2037                         cfs_dirent_t *de)
2038 {
2039         struct find_param *param = (struct find_param *)data;
2040         int ret = 0;
2041
2042         LASSERT(parent != NULL || d != NULL);
2043
2044         if (param->obduuid) {
2045                 param->quiet = 1;
2046                 ret = setup_obd_uuid(d ? d : parent, path, param);
2047                 if (ret)
2048                         return ret;
2049         }
2050
2051         if (d) {
2052                 ret = ioctl(dirfd(d), LL_IOC_LOV_GETSTRIPE,
2053                             (void *)&param->lmd->lmd_lmm);
2054         } else if (parent) {
2055                 char *fname = strrchr(path, '/');
2056                 fname = (fname == NULL ? path : fname + 1);
2057
2058                 strncpy((char *)&param->lmd->lmd_lmm, fname, param->lumlen);
2059
2060                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILESTRIPE,
2061                             (void *)&param->lmd->lmd_lmm);
2062         }
2063
2064         if (ret) {
2065                 if (errno == ENODATA) {
2066                         if (!param->obduuid)
2067                                 llapi_printf(LLAPI_MSG_NORMAL,
2068                                              "%s has no stripe info\n", path);
2069                         goto out;
2070                 } else if (errno == ENOTTY) {
2071                         llapi_err(LLAPI_MSG_ERROR,
2072                                   "%s: '%s' not on a Lustre fs?",
2073                                   __func__, path);
2074                 } else if (errno == ENOENT) {
2075                         llapi_err(LLAPI_MSG_WARN,
2076                                   "warning: %s: %s does not exist",
2077                                   __func__, path);
2078                         goto out;
2079                 } else {
2080                         llapi_err(LLAPI_MSG_ERROR,
2081                                   "error: %s: %s failed for %s",
2082                                    __func__, d ? "LL_IOC_LOV_GETSTRIPE" :
2083                                   "IOC_MDC_GETFILESTRIPE", path);
2084                 }
2085
2086                 return ret;
2087         }
2088
2089         if (!param->get_mdt_index)
2090                 llapi_lov_dump_user_lmm(param, path, d ? 1 : 0);
2091
2092 out:
2093         /* Do not get down anymore? */
2094         if (param->depth == param->maxdepth)
2095                 return 1;
2096
2097         param->depth++;
2098         return 0;
2099 }
2100
2101 int llapi_getstripe(char *path, struct find_param *param)
2102 {
2103         return param_callback(path, param->get_mdt_index ?
2104                               cb_get_mdt_index : cb_getstripe,
2105                               cb_common_fini, param);
2106 }
2107
2108 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
2109                      struct obd_statfs *stat_buf,
2110                      struct obd_uuid *uuid_buf)
2111 {
2112         int fd;
2113         char raw[OBD_MAX_IOCTL_BUFFER] = {'\0'};
2114         char *rawbuf = raw;
2115         struct obd_ioctl_data data = { 0 };
2116         int rc = 0;
2117
2118         data.ioc_inlbuf1 = (char *)&type;
2119         data.ioc_inllen1 = sizeof(__u32);
2120         data.ioc_inlbuf2 = (char *)&index;
2121         data.ioc_inllen2 = sizeof(__u32);
2122         data.ioc_pbuf1 = (char *)stat_buf;
2123         data.ioc_plen1 = sizeof(struct obd_statfs);
2124         data.ioc_pbuf2 = (char *)uuid_buf;
2125         data.ioc_plen2 = sizeof(struct obd_uuid);
2126
2127         if ((rc = obd_ioctl_pack(&data, &rawbuf, sizeof(raw))) != 0) {
2128                 llapi_err(LLAPI_MSG_ERROR,
2129                           "llapi_obd_statfs: error packing ioctl data");
2130                 return rc;
2131         }
2132
2133         fd = open(path, O_RDONLY);
2134         if (errno == EISDIR)
2135                 fd = open(path, O_DIRECTORY | O_RDONLY);
2136
2137         if (fd < 0) {
2138                 rc = errno ? -errno : -EBADF;
2139                 llapi_err(LLAPI_MSG_ERROR, "error: %s: opening '%s'",
2140                           __func__, path);
2141                 return rc;
2142         }
2143         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
2144         if (rc)
2145                 rc = errno ? -errno : -EINVAL;
2146
2147         close(fd);
2148         return rc;
2149 }
2150
2151 #define MAX_STRING_SIZE 128
2152 #define DEVICES_LIST "/proc/fs/lustre/devices"
2153
2154 int llapi_ping(char *obd_type, char *obd_name)
2155 {
2156         char path[MAX_STRING_SIZE];
2157         char buf[1];
2158         int rc, fd;
2159
2160         snprintf(path, MAX_STRING_SIZE, "/proc/fs/lustre/%s/%s/ping",
2161                  obd_type, obd_name);
2162
2163         fd = open(path, O_WRONLY);
2164         if (fd < 0) {
2165                 rc = errno;
2166                 llapi_err(LLAPI_MSG_ERROR, "error opening %s", path);
2167                 return rc;
2168         }
2169
2170         rc = write(fd, buf, 1);
2171         close(fd);
2172
2173         if (rc == 1)
2174                 return 0;
2175         return rc;
2176 }
2177
2178 int llapi_target_iterate(int type_num, char **obd_type,void *args,llapi_cb_t cb)
2179 {
2180         char buf[MAX_STRING_SIZE];
2181         FILE *fp = fopen(DEVICES_LIST, "r");
2182         int i, rc = 0;
2183
2184         if (fp == NULL) {
2185                 rc = errno;
2186                 llapi_err(LLAPI_MSG_ERROR, "error: opening "DEVICES_LIST);
2187                 return rc;
2188         }
2189
2190         while (fgets(buf, sizeof(buf), fp) != NULL) {
2191                 char *obd_type_name = NULL;
2192                 char *obd_name = NULL;
2193                 char *obd_uuid = NULL;
2194                 char *bufp = buf;
2195                 struct obd_ioctl_data datal = { 0, };
2196                 struct obd_statfs osfs_buffer;
2197
2198                 while(bufp[0] == ' ')
2199                         ++bufp;
2200
2201                 for(i = 0; i < 3; i++) {
2202                         obd_type_name = strsep(&bufp, " ");
2203                 }
2204                 obd_name = strsep(&bufp, " ");
2205                 obd_uuid = strsep(&bufp, " ");
2206
2207                 memset(&osfs_buffer, 0, sizeof (osfs_buffer));
2208
2209                 datal.ioc_pbuf1 = (char *)&osfs_buffer;
2210                 datal.ioc_plen1 = sizeof(osfs_buffer);
2211
2212                 for (i = 0; i < type_num; i++) {
2213                         if (strcmp(obd_type_name, obd_type[i]) != 0)
2214                                 continue;
2215
2216                         cb(obd_type_name, obd_name, obd_uuid, args);
2217                 }
2218         }
2219         fclose(fp);
2220         return rc;
2221 }
2222
2223 static void do_target_check(char *obd_type_name, char *obd_name,
2224                             char *obd_uuid, void *args)
2225 {
2226         int rc;
2227
2228         rc = llapi_ping(obd_type_name, obd_name);
2229         if (rc == ENOTCONN) {
2230                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
2231         } else if (rc) {
2232                 llapi_err(LLAPI_MSG_ERROR, "error: check '%s'", obd_name);
2233         } else {
2234                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
2235         }
2236 }
2237
2238 int llapi_target_check(int type_num, char **obd_type, char *dir)
2239 {
2240         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
2241 }
2242
2243 #undef MAX_STRING_SIZE
2244
2245 int llapi_catinfo(char *dir, char *keyword, char *node_name)
2246 {
2247         char raw[OBD_MAX_IOCTL_BUFFER];
2248         char out[LLOG_CHUNK_SIZE];
2249         char *buf = raw;
2250         struct obd_ioctl_data data = { 0 };
2251         char key[30];
2252         DIR *root;
2253         int rc;
2254
2255         sprintf(key, "%s", keyword);
2256         memset(raw, 0, sizeof(raw));
2257         memset(out, 0, sizeof(out));
2258         data.ioc_inlbuf1 = key;
2259         data.ioc_inllen1 = strlen(key) + 1;
2260         if (node_name) {
2261                 data.ioc_inlbuf2 = node_name;
2262                 data.ioc_inllen2 = strlen(node_name) + 1;
2263         }
2264         data.ioc_pbuf1 = out;
2265         data.ioc_plen1 = sizeof(out);
2266         rc = obd_ioctl_pack(&data, &buf, sizeof(raw));
2267         if (rc)
2268                 return rc;
2269
2270         root = opendir(dir);
2271         if (root == NULL) {
2272                 rc = errno;
2273                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", dir);
2274                 return rc;
2275         }
2276
2277         rc = ioctl(dirfd(root), OBD_IOC_LLOG_CATINFO, buf);
2278         if (rc)
2279                 llapi_err(LLAPI_MSG_ERROR, "ioctl OBD_IOC_CATINFO failed");
2280         else
2281                 llapi_printf(LLAPI_MSG_NORMAL, "%s", data.ioc_pbuf1);
2282
2283         closedir(root);
2284         return rc;
2285 }
2286
2287 /* Is this a lustre fs? */
2288 int llapi_is_lustre_mnttype(const char *type)
2289 {
2290         return (strcmp(type, "lustre") == 0 || strcmp(type,"lustre_lite") == 0);
2291 }
2292
2293 /* Is this a lustre client fs? */
2294 int llapi_is_lustre_mnt(struct mntent *mnt)
2295 {
2296         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
2297                 strstr(mnt->mnt_fsname, ":/") != NULL);
2298 }
2299
2300 int llapi_quotacheck(char *mnt, int check_type)
2301 {
2302         DIR *root;
2303         int rc;
2304
2305         root = opendir(mnt);
2306         if (!root) {
2307                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2308                 return -1;
2309         }
2310
2311         rc = ioctl(dirfd(root), LL_IOC_QUOTACHECK, check_type);
2312
2313         closedir(root);
2314         return rc;
2315 }
2316
2317 int llapi_poll_quotacheck(char *mnt, struct if_quotacheck *qchk)
2318 {
2319         DIR *root;
2320         int poll_intvl = 2;
2321         int rc;
2322
2323         root = opendir(mnt);
2324         if (!root) {
2325                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2326                 return -1;
2327         }
2328
2329         while (1) {
2330                 rc = ioctl(dirfd(root), LL_IOC_POLL_QUOTACHECK, qchk);
2331                 if (!rc)
2332                         break;
2333                 sleep(poll_intvl);
2334                 if (poll_intvl < 30)
2335                         poll_intvl *= 2;
2336         }
2337
2338         closedir(root);
2339         return rc;
2340 }
2341
2342 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
2343 {
2344         DIR *root;
2345         int rc;
2346
2347         root = opendir(mnt);
2348         if (!root) {
2349                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2350                 return -1;
2351         }
2352
2353         rc = ioctl(dirfd(root), LL_IOC_QUOTACTL, qctl);
2354
2355         closedir(root);
2356         return rc;
2357 }
2358
2359 static int cb_quotachown(char *path, DIR *parent, DIR *d, void *data,
2360                          cfs_dirent_t *de)
2361 {
2362         struct find_param *param = (struct find_param *)data;
2363         lstat_t *st;
2364         int rc;
2365
2366         LASSERT(parent != NULL || d != NULL);
2367
2368         if (d) {
2369                 rc = ioctl(dirfd(d), LL_IOC_MDC_GETINFO,
2370                            (void *)param->lmd);
2371         } else if (parent) {
2372                 char *fname = strrchr(path, '/');
2373                 fname = (fname == NULL ? path : fname + 1);
2374
2375                 strncpy((char *)param->lmd, fname, param->lumlen);
2376                 rc = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
2377                            (void *)param->lmd);
2378         } else {
2379                 return 0;
2380         }
2381
2382         if (rc) {
2383                 if (errno == ENODATA) {
2384                         if (!param->obduuid && !param->quiet)
2385                                 llapi_err(LLAPI_MSG_ERROR,
2386                                           "%s has no stripe info", path);
2387                         rc = 0;
2388                 } else if (errno == ENOENT) {
2389                         llapi_err(LLAPI_MSG_ERROR,
2390                                   "warning: %s: %s does not exist",
2391                                   __func__, path);
2392                         rc = 0;
2393                 } else if (errno != EISDIR) {
2394                         rc = errno;
2395                         llapi_err(LLAPI_MSG_ERROR, "%s ioctl failed for %s.",
2396                                   d ? "LL_IOC_MDC_GETINFO" :
2397                                   "IOC_MDC_GETFILEINFO", path);
2398                 }
2399                 return rc;
2400         }
2401
2402         st = &param->lmd->lmd_st;
2403
2404         /* libc chown() will do extra check, and if the real owner is
2405          * the same as the ones to set, it won't fall into kernel, so
2406          * invoke syscall directly. */
2407         rc = syscall(SYS_chown, path, -1, -1);
2408         if (rc)
2409                 llapi_err(LLAPI_MSG_ERROR,"error: chown %s (%u,%u)", path);
2410
2411         rc = chmod(path, st->st_mode);
2412         if (rc)
2413                 llapi_err(LLAPI_MSG_ERROR, "error: chmod %s (%hu)",
2414                           path, st->st_mode);
2415
2416         return rc;
2417 }
2418
2419 int llapi_quotachown(char *path, int flag)
2420 {
2421         struct find_param param;
2422
2423         memset(&param, 0, sizeof(param));
2424         param.recursive = 1;
2425         param.verbose = 0;
2426         param.quiet = 1;
2427
2428         return param_callback(path, cb_quotachown, NULL, &param);
2429 }
2430
2431 #include <pwd.h>
2432 #include <grp.h>
2433 #include <mntent.h>
2434 #include <sys/wait.h>
2435 #include <errno.h>
2436 #include <ctype.h>
2437
2438 static int rmtacl_notify(int ops)
2439 {
2440         FILE *fp;
2441         struct mntent *mnt;
2442         int found = 0, fd, rc;
2443
2444         fp = setmntent(MOUNTED, "r");
2445         if (fp == NULL) {
2446                 perror("setmntent");
2447                 return -1;
2448         }
2449
2450         while (1) {
2451                 mnt = getmntent(fp);
2452                 if (!mnt)
2453                         break;
2454
2455                 if (!llapi_is_lustre_mnt(mnt))
2456                         continue;
2457
2458                 fd = open(mnt->mnt_dir, O_RDONLY | O_DIRECTORY);
2459                 if (fd < 0) {
2460                         perror("open");
2461                         return -1;
2462                 }
2463
2464                 rc = ioctl(fd, LL_IOC_RMTACL, ops);
2465                 if (rc < 0) {
2466                         perror("ioctl");
2467                 return -1;
2468                 }
2469
2470                 found++;
2471         }
2472         endmntent(fp);
2473         return found;
2474 }
2475
2476 static char *next_token(char *p, int div)
2477 {
2478         if (p == NULL)
2479                 return NULL;
2480
2481         if (div)
2482                 while (*p && *p != ':' && !isspace(*p))
2483                         p++;
2484         else
2485                 while (*p == ':' || isspace(*p))
2486                         p++;
2487
2488         return *p ? p : NULL;
2489 }
2490
2491 static int rmtacl_name2id(char *name, int is_user)
2492 {
2493         if (is_user) {
2494                 struct passwd *pw;
2495
2496                 if ((pw = getpwnam(name)) == NULL)
2497                         return INVALID_ID;
2498                 else
2499                         return (int)(pw->pw_uid);
2500         } else {
2501                 struct group *gr;
2502
2503                 if ((gr = getgrnam(name)) == NULL)
2504                         return INVALID_ID;
2505                 else
2506                         return (int)(gr->gr_gid);
2507         }
2508 }
2509
2510 static int isodigit(int c)
2511 {
2512         return (c >= '0' && c <= '7') ? 1 : 0;
2513 }
2514
2515 /*
2516  * Whether the name is just digits string (uid/gid) already or not.
2517  * Return value:
2518  * 1: str is id
2519  * 0: str is not id
2520  */
2521 static int str_is_id(char *str)
2522 {
2523         if (str == NULL)
2524                 return 0;
2525
2526         if (*str == '0') {
2527                 str++;
2528                 if (*str == 'x' || *str == 'X') { /* for Hex. */
2529                         if (!isxdigit(*(++str)))
2530                                 return 0;
2531
2532                         while (isxdigit(*(++str)));
2533                 } else if (isodigit(*str)) { /* for Oct. */
2534                         while (isodigit(*(++str)));
2535                 }
2536         } else if (isdigit(*str)) { /* for Dec. */
2537                 while (isdigit(*(++str)));
2538         }
2539
2540         return (*str == 0) ? 1 : 0;
2541 }
2542
2543 typedef struct {
2544         char *name;
2545         int   length;
2546         int   is_user;
2547         int   next_token;
2548 } rmtacl_name_t;
2549
2550 #define RMTACL_OPTNAME(name) name, sizeof(name) - 1
2551
2552 static rmtacl_name_t rmtacl_namelist[] = {
2553         { RMTACL_OPTNAME("user:"),            1,      0 },
2554         { RMTACL_OPTNAME("group:"),           0,      0 },
2555         { RMTACL_OPTNAME("default:user:"),    1,      0 },
2556         { RMTACL_OPTNAME("default:group:"),   0,      0 },
2557         /* for --tabular option */
2558         { RMTACL_OPTNAME("user"),             1,      1 },
2559         { RMTACL_OPTNAME("group"),            0,      1 },
2560         { 0 }
2561 };
2562
2563 static int rgetfacl_output(char *str)
2564 {
2565         char *start = NULL, *end = NULL;
2566         int is_user = 0, n, id;
2567         char c;
2568         rmtacl_name_t *rn;
2569
2570         if (str == NULL)
2571                 return -1;
2572
2573         for (rn = rmtacl_namelist; rn->name; rn++) {
2574                 if(strncmp(str, rn->name, rn->length) == 0) {
2575                         if (!rn->next_token)
2576                                 start = str + rn->length;
2577                         else
2578                                 start = next_token(str + rn->length, 0);
2579                         is_user = rn->is_user;
2580                         break;
2581                 }
2582         }
2583
2584         end = next_token(start, 1);
2585         if (end == NULL || start == end) {
2586                 n = printf("%s", str);
2587                 return n;
2588         }
2589
2590         c = *end;
2591         *end = 0;
2592         id = rmtacl_name2id(start, is_user);
2593         if (id == INVALID_ID) {
2594                 if (str_is_id(start)) {
2595                         *end = c;
2596                         n = printf("%s", str);
2597                 } else
2598                         return -1;
2599         } else if ((id == NOBODY_UID && is_user) ||
2600                    (id == NOBODY_GID && !is_user)) {
2601                 *end = c;
2602                 n = printf("%s", str);
2603         } else {
2604                 *end = c;
2605                 *start = 0;
2606                 n = printf("%s%d%s", str, id, end);
2607         }
2608         return n;
2609 }
2610
2611 static int child_status(int status)
2612 {
2613         return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
2614 }
2615
2616 static int do_rmtacl(int argc, char *argv[], int ops, int (output_func)(char *))
2617 {
2618         pid_t pid = 0;
2619         int fd[2], status;
2620         FILE *fp;
2621         char buf[PIPE_BUF];
2622
2623         if (output_func) {
2624                 if (pipe(fd) < 0) {
2625                         perror("pipe");
2626                         return -1;
2627                 }
2628
2629                 if ((pid = fork()) < 0) {
2630                         perror("fork");
2631                         close(fd[0]);
2632                         close(fd[1]);
2633                         return -1;
2634                 } else if (!pid) {
2635                         /* child process redirects its output. */
2636                         close(fd[0]);
2637                         close(1);
2638                         if (dup2(fd[1], 1) < 0) {
2639                                 perror("dup2");
2640                                 close(fd[1]);
2641                                 return -1;
2642                         }
2643                 } else {
2644                         close(fd[1]);
2645                 }
2646         }
2647
2648         if (!pid) {
2649                 status = rmtacl_notify(ops);
2650                 if (status < 0)
2651                         return -1;
2652
2653                 exit(execvp(argv[0], argv));
2654         }
2655
2656         /* the following is parent process */
2657         if ((fp = fdopen(fd[0], "r")) == NULL) {
2658                 perror("fdopen");
2659                 kill(pid, SIGKILL);
2660                 close(fd[0]);
2661                 return -1;
2662         }
2663
2664         while (fgets(buf, PIPE_BUF, fp) != NULL) {
2665                 if (output_func(buf) < 0)
2666                         fprintf(stderr, "WARNING: unexpected error!\n[%s]\n",
2667                                 buf);
2668         }
2669         fclose(fp);
2670         close(fd[0]);
2671
2672         if (waitpid(pid, &status, 0) < 0) {
2673                 perror("waitpid");
2674                 return -1;
2675         }
2676
2677         return child_status(status);
2678 }
2679
2680 int llapi_lsetfacl(int argc, char *argv[])
2681 {
2682         return do_rmtacl(argc, argv, RMT_LSETFACL, NULL);
2683 }
2684
2685 int llapi_lgetfacl(int argc, char *argv[])
2686 {
2687         return do_rmtacl(argc, argv, RMT_LGETFACL, NULL);
2688 }
2689
2690 int llapi_rsetfacl(int argc, char *argv[])
2691 {
2692         return do_rmtacl(argc, argv, RMT_RSETFACL, NULL);
2693 }
2694
2695 int llapi_rgetfacl(int argc, char *argv[])
2696 {
2697         return do_rmtacl(argc, argv, RMT_RGETFACL, rgetfacl_output);
2698 }
2699
2700 int llapi_cp(int argc, char *argv[])
2701 {
2702         int rc;
2703
2704         rc = rmtacl_notify(RMT_RSETFACL);
2705         if (rc < 0)
2706                 return -1;
2707
2708         exit(execvp(argv[0], argv));
2709 }
2710
2711 int llapi_ls(int argc, char *argv[])
2712 {
2713         int rc;
2714
2715         rc = rmtacl_notify(RMT_LGETFACL);
2716         if (rc < 0)
2717                 return -1;
2718
2719         exit(execvp(argv[0], argv));
2720 }
2721
2722 /* Print mdtname 'name' into 'buf' using 'format'.  Add -MDT0000 if needed.
2723  * format must have %s%s, buf must be > 16
2724  * Eg: if name = "lustre-MDT0000", "lustre", or "lustre-MDT0000_UUID"
2725  *     then buf = "lustre-MDT0000"
2726  */
2727 static int get_mdtname(char *name, char *format, char *buf)
2728 {
2729         char suffix[]="-MDT0000";
2730         int len = strlen(name);
2731
2732         if ((len > 5) && (strncmp(name + len - 5, "_UUID", 5) == 0)) {
2733                 name[len - 5] = '\0';
2734                 len -= 5;
2735         }
2736
2737         if (len > 8) {
2738                 if ((len <= 16) && strncmp(name + len - 8, "-MDT", 4) == 0) {
2739                         suffix[0] = '\0';
2740                 } else {
2741                         /* Not enough room to add suffix */
2742                         llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2743                                   "MDT name too long |%s|", name);
2744                         return -EINVAL;
2745                 }
2746         }
2747
2748         return sprintf(buf, format, name, suffix);
2749 }
2750
2751 /** ioctl on filsystem root, with mdtindex sent as data
2752  * \param mdtname path, fsname, or mdtname (lutre-MDT0004)
2753  * \param mdtidxp pointer to integer within data to be filled in with the
2754  *    mdt index (0 if no mdt is specified).  NULL won't be filled.
2755  */
2756 static int root_ioctl(const char *mdtname, int opc, void *data, int *mdtidxp,
2757                       int want_error)
2758 {
2759         char fsname[20];
2760         char *ptr;
2761         int fd, index, rc;
2762
2763         /* Take path, fsname, or MDTname.  Assume MDT0000 in the former cases.
2764          Open root and parse mdt index. */
2765         if (mdtname[0] == '/') {
2766                 index = 0;
2767                 rc = get_root_path(WANT_FD | want_error, NULL, &fd,
2768                                    (char *)mdtname, -1);
2769         } else {
2770                 if (get_mdtname((char *)mdtname, "%s%s", fsname) < 0)
2771                         return -EINVAL;
2772                 ptr = fsname + strlen(fsname) - 8;
2773                 *ptr = '\0';
2774                 index = strtol(ptr + 4, NULL, 10);
2775                 rc = get_root_path(WANT_FD | want_error, fsname, &fd, NULL, -1);
2776         }
2777         if (rc < 0) {
2778                 if (want_error)
2779                         llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2780                                   "Can't open %s: %d\n", mdtname, rc);
2781                 return rc;
2782         }
2783
2784         if (mdtidxp)
2785                 *mdtidxp = index;
2786
2787         rc = ioctl(fd, opc, data);
2788         if (rc && want_error)
2789                 llapi_err(LLAPI_MSG_ERROR, "ioctl %d err %d", opc, rc);
2790
2791         close(fd);
2792         return rc;
2793 }
2794
2795 /****** Changelog API ********/
2796
2797 static int changelog_ioctl(const char *mdtname, int opc, int id,
2798                            long long recno, int flags)
2799 {
2800         struct ioc_changelog data;
2801         int *idx;
2802
2803         data.icc_id = id;
2804         data.icc_recno = recno;
2805         data.icc_flags = flags;
2806         idx = (int *)(&data.icc_mdtindex);
2807
2808         return root_ioctl(mdtname, opc, &data, idx, WANT_ERROR);
2809 }
2810
2811 #define CHANGELOG_PRIV_MAGIC 0xCA8E1080
2812 struct changelog_private {
2813         int magic;
2814         int flags;
2815         lustre_kernelcomm kuc;
2816         char *buf;
2817 };
2818
2819 /** Start reading from a changelog
2820  * @param priv Opaque private control structure
2821  * @param flags Start flags (e.g. CHANGELOG_FLAG_BLOCK)
2822  * @param device Report changes recorded on this MDT
2823  * @param startrec Report changes beginning with this record number
2824  * (just call llapi_changelog_fini when done; don't need an endrec)
2825  */
2826 int llapi_changelog_start(void **priv, int flags, const char *device,
2827                           long long startrec)
2828 {
2829         struct changelog_private *cp;
2830         int rc;
2831
2832         /* Set up the receiver control struct */
2833         cp = malloc(sizeof(*cp));
2834         if (cp == NULL)
2835                 return -ENOMEM;
2836
2837         cp->buf = malloc(CR_MAXSIZE);
2838         if (cp->buf == NULL) {
2839                 rc = -ENOMEM;
2840                 goto out_free;
2841         }
2842
2843         cp->magic = CHANGELOG_PRIV_MAGIC;
2844         cp->flags = flags;
2845
2846         /* Set up the receiver */
2847         rc = libcfs_ukuc_start(&cp->kuc, 0 /* no group registration */);
2848         if (rc < 0)
2849                 goto out_free;
2850
2851         *priv = cp;
2852
2853         /* Tell the kernel to start sending */
2854         rc = changelog_ioctl(device, OBD_IOC_CHANGELOG_SEND, cp->kuc.lk_wfd,
2855                              startrec, flags);
2856         /* Only the kernel reference keeps the write side open */
2857         close(cp->kuc.lk_wfd);
2858         cp->kuc.lk_wfd = 0;
2859         if (rc < 0) {
2860                 /* frees and clears priv */
2861                 llapi_changelog_fini(priv);
2862                 return rc;
2863         }
2864
2865         return 0;
2866
2867 out_free:
2868         if (cp->buf)
2869                 free(cp->buf);
2870         free(cp);
2871         return rc;
2872 }
2873
2874 /** Finish reading from a changelog */
2875 int llapi_changelog_fini(void **priv)
2876 {
2877         struct changelog_private *cp = (struct changelog_private *)*priv;
2878
2879         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
2880                 return -EINVAL;
2881
2882         libcfs_ukuc_stop(&cp->kuc);
2883         free(cp->buf);
2884         free(cp);
2885         *priv = NULL;
2886         return 0;
2887 }
2888
2889 /** Read the next changelog entry
2890  * @param priv Opaque private control structure
2891  * @param rech Changelog record handle; record will be allocated here
2892  * @return 0 valid message received; rec is set
2893  *         <0 error code
2894  *         1 EOF
2895  */
2896 int llapi_changelog_recv(void *priv, struct changelog_rec **rech)
2897 {
2898         struct changelog_private *cp = (struct changelog_private *)priv;
2899         struct kuc_hdr *kuch;
2900         int rc = 0;
2901
2902         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
2903                 return -EINVAL;
2904         if (rech == NULL)
2905                 return -EINVAL;
2906
2907 repeat:
2908         rc = libcfs_ukuc_msg_get(&cp->kuc, cp->buf, CR_MAXSIZE,
2909                                  KUC_TRANSPORT_CHANGELOG);
2910         if (rc < 0)
2911                 return rc;
2912
2913         kuch = (struct kuc_hdr *)cp->buf;
2914         if ((kuch->kuc_transport != KUC_TRANSPORT_CHANGELOG) ||
2915             ((kuch->kuc_msgtype != CL_RECORD) &&
2916              (kuch->kuc_msgtype != CL_EOF))) {
2917                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2918                           "Unknown changelog message type %d:%d\n",
2919                           kuch->kuc_transport, kuch->kuc_msgtype);
2920                 rc = -EPROTO;
2921                 goto out_free;
2922         }
2923
2924         if (kuch->kuc_msgtype == CL_EOF) {
2925                 if (cp->flags & CHANGELOG_FLAG_FOLLOW) {
2926                         /* Ignore EOFs */
2927                         goto repeat;
2928                 } else {
2929                         rc = 1;
2930                         goto out_free;
2931                 }
2932         }
2933
2934         /* Our message is a changelog_rec */
2935         *rech = (struct changelog_rec *)(kuch + 1);
2936
2937         return 0;
2938
2939 out_free:
2940         *rech = NULL;
2941         return rc;
2942 }
2943
2944 /** Release the changelog record when done with it. */
2945 int llapi_changelog_free(struct changelog_rec **rech)
2946 {
2947         *rech = NULL;
2948         return 0;
2949 }
2950
2951 int llapi_changelog_clear(const char *mdtname, const char *idstr,
2952                           long long endrec)
2953 {
2954         int id;
2955
2956         if (endrec < 0) {
2957                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2958                           "can't purge negative records\n");
2959                 return -EINVAL;
2960         }
2961
2962         id = strtol(idstr + strlen(CHANGELOG_USER_PREFIX), NULL, 10);
2963         if ((id == 0) || (strncmp(idstr, CHANGELOG_USER_PREFIX,
2964                                   strlen(CHANGELOG_USER_PREFIX)) != 0)) {
2965                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2966                           "expecting id of the form '"CHANGELOG_USER_PREFIX
2967                           "<num>'; got '%s'\n", idstr);
2968                 return -EINVAL;
2969         }
2970
2971         return changelog_ioctl(mdtname, OBD_IOC_CHANGELOG_CLEAR, id, endrec, 0);
2972 }
2973
2974 int llapi_fid2path(const char *device, const char *fidstr, char *buf,
2975                    int buflen, long long *recno, int *linkno)
2976 {
2977         char path[PATH_MAX];
2978         struct lu_fid fid;
2979         struct getinfo_fid2path *gf;
2980         int fd, rc;
2981
2982         while (*fidstr == '[')
2983                 fidstr++;
2984
2985         sscanf(fidstr, SFID, RFID(&fid));
2986         if (!fid_is_sane(&fid)) {
2987                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2988                           "bad FID format [%s], should be "DFID"\n",
2989                           fidstr, (__u64)1, 2, 0);
2990                 return -EINVAL;
2991         }
2992
2993         /* Take path or fsname */
2994         if (device[0] == '/') {
2995                 strcpy(path, device);
2996         } else {
2997                 rc = get_root_path(WANT_PATH | WANT_ERROR, (char *)device,
2998                                    NULL, path, -1);
2999                 if (rc < 0)
3000                         return rc;
3001         }
3002         sprintf(path, "%s/%s/fid/%s", path, dot_lustre_name, fidstr);
3003         fd = open(path, O_RDONLY | O_NONBLOCK);
3004         if (fd < 0)
3005                 return -errno;
3006
3007         gf = malloc(sizeof(*gf) + buflen);
3008         gf->gf_fid = fid;
3009         gf->gf_recno = *recno;
3010         gf->gf_linkno = *linkno;
3011         gf->gf_pathlen = buflen;
3012         rc = ioctl(fd, OBD_IOC_FID2PATH, gf);
3013         if (rc) {
3014                 llapi_err(LLAPI_MSG_ERROR, "ioctl err %d", rc);
3015         } else {
3016                 memcpy(buf, gf->gf_path, gf->gf_pathlen);
3017                 *recno = gf->gf_recno;
3018                 *linkno = gf->gf_linkno;
3019         }
3020
3021         free(gf);
3022         close(fd);
3023         return rc;
3024 }
3025
3026 static int path2fid_from_lma(const char *path, lustre_fid *fid)
3027 {
3028         char buf[512];
3029         struct lustre_mdt_attrs *lma;
3030         int rc;
3031
3032         rc = lgetxattr(path, XATTR_NAME_LMA, buf, sizeof(buf));
3033         if (rc < 0)
3034                 return -errno;
3035         lma = (struct lustre_mdt_attrs *)buf;
3036         fid_le_to_cpu(fid, &lma->lma_self_fid);
3037         return 0;
3038 }
3039
3040 int llapi_path2fid(const char *path, lustre_fid *fid)
3041 {
3042         int fd, rc;
3043
3044         memset(fid, 0, sizeof(*fid));
3045         fd = open(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
3046         if (fd < 0) {
3047                 if (errno == ELOOP) /* symbolic link */
3048                         return path2fid_from_lma(path, fid);
3049                 return -errno;
3050         }
3051
3052         rc = ioctl(fd, LL_IOC_PATH2FID, fid) < 0 ? -errno : 0;
3053         if (rc == -EINVAL) /* char special device */
3054                 rc = path2fid_from_lma(path, fid);
3055
3056         close(fd);
3057         return rc;
3058 }
3059
3060 /****** HSM Copytool API ********/
3061 #define CT_PRIV_MAGIC 0xC0BE2001
3062 struct copytool_private {
3063         int magic;
3064         char *buf;
3065         char *fsname;
3066         lustre_kernelcomm kuc;
3067         __u32 archives;
3068 };
3069
3070 #include <libcfs/libcfs.h>
3071
3072 /** Register a copytool
3073  * @param[out] priv Opaque private control structure
3074  * @param fsname Lustre filesystem
3075  * @param flags Open flags, currently unused (e.g. O_NONBLOCK)
3076  * @param archive_count
3077  * @param archives Which archive numbers this copytool is responsible for
3078  */
3079 int llapi_copytool_start(void **priv, char *fsname, int flags,
3080                          int archive_count, int *archives)
3081 {
3082         struct copytool_private *ct;
3083         int rc;
3084
3085         if (archive_count > 0 && archives == NULL) {
3086                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
3087                           "NULL archive numbers");
3088                 return -EINVAL;
3089         }
3090
3091         ct = malloc(sizeof(*ct));
3092         if (ct == NULL)
3093                 return -ENOMEM;
3094
3095         ct->buf = malloc(HAL_MAXSIZE);
3096         ct->fsname = malloc(strlen(fsname) + 1);
3097         if (ct->buf == NULL || ct->fsname == NULL) {
3098                 rc = -ENOMEM;
3099                 goto out_err;
3100         }
3101         strcpy(ct->fsname, fsname);
3102         ct->magic = CT_PRIV_MAGIC;
3103         ct->archives = 0;
3104         for (rc = 0; rc < archive_count; rc++) {
3105                 if (archives[rc] > sizeof(ct->archives)) {
3106                         llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
3107                                   "Maximum of %d archives supported",
3108                                   sizeof(ct->archives));
3109                         goto out_err;
3110                 }
3111                 ct->archives |= 1 << archives[rc];
3112         }
3113         /* special case: if no archives specified, default to archive #0. */
3114         if (ct->archives == 0)
3115                 ct->archives = 1;
3116
3117         rc = libcfs_ukuc_start(&ct->kuc, KUC_GRP_HSM);
3118         if (rc < 0)
3119                 goto out_err;
3120
3121         /* Storing archive(s) in lk_data; see mdc_ioc_hsm_ct_start */
3122         ct->kuc.lk_data = ct->archives;
3123         rc = root_ioctl(ct->fsname, LL_IOC_HSM_CT_START, &(ct->kuc), NULL,
3124                         WANT_ERROR);
3125         /* Only the kernel reference keeps the write side open */
3126         close(ct->kuc.lk_wfd);
3127         ct->kuc.lk_wfd = 0;
3128         if (rc < 0)
3129                 goto out_err;
3130
3131         *priv = ct;
3132         return 0;
3133
3134 out_err:
3135         if (ct->buf)
3136                 free(ct->buf);
3137         if (ct->fsname)
3138                 free(ct->fsname);
3139         free(ct);
3140         return rc;
3141 }
3142
3143 /** Deregister a copytool */
3144 int llapi_copytool_fini(void **priv)
3145 {
3146         struct copytool_private *ct = (struct copytool_private *)*priv;
3147
3148         if (!ct || (ct->magic != CT_PRIV_MAGIC))
3149                 return -EINVAL;
3150
3151         /* Tell the kernel to stop sending us messages */
3152         ct->kuc.lk_flags = LK_FLG_STOP;
3153         root_ioctl(ct->fsname, LL_IOC_HSM_CT_START, &(ct->kuc), NULL, 0);
3154
3155         /* Shut down the kernelcomms */
3156         libcfs_ukuc_stop(&ct->kuc);
3157
3158         free(ct->buf);
3159         free(ct->fsname);
3160         free(ct);
3161         *priv = NULL;
3162         return 0;
3163 }
3164
3165 /** Wait for the next hsm_action_list
3166  * @param priv Opaque private control structure
3167  * @param halh Action list handle, will be allocated here
3168  * @param msgsize Number of bytes in the message, will be set here
3169  * @return 0 valid message received; halh and msgsize are set
3170  *         <0 error code
3171  */
3172 int llapi_copytool_recv(void *priv, struct hsm_action_list **halh, int *msgsize)
3173 {
3174         struct copytool_private *ct = (struct copytool_private *)priv;
3175         struct kuc_hdr *kuch;
3176         struct hsm_action_list *hal;
3177         int rc = 0;
3178
3179         if (!ct || (ct->magic != CT_PRIV_MAGIC))
3180                 return -EINVAL;
3181         if (halh == NULL || msgsize == NULL)
3182                 return -EINVAL;
3183
3184         rc = libcfs_ukuc_msg_get(&ct->kuc, ct->buf, HAL_MAXSIZE,
3185                                  KUC_TRANSPORT_HSM);
3186         if (rc < 0)
3187                 return rc;
3188
3189         /* Handle generic messages */
3190         kuch = (struct kuc_hdr *)ct->buf;
3191         if (kuch->kuc_transport == KUC_TRANSPORT_GENERIC &&
3192             kuch->kuc_msgtype == KUC_MSG_SHUTDOWN) {
3193                 rc = -ESHUTDOWN;
3194                 goto out_free;
3195         }
3196
3197         if (kuch->kuc_transport != KUC_TRANSPORT_HSM ||
3198             kuch->kuc_msgtype != HMT_ACTION_LIST) {
3199                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
3200                           "Unknown HSM message type %d:%d\n",
3201                           kuch->kuc_transport, kuch->kuc_msgtype);
3202                 rc = -EPROTO;
3203                 goto out_free;
3204         }
3205
3206         /* Our message is an hsm_action_list */
3207
3208         hal = (struct hsm_action_list *)(kuch + 1);
3209
3210         /* Check that we have registered for this archive # */
3211         if (((1 << hal->hal_archive_num) & ct->archives) == 0) {
3212                     llapi_err(LLAPI_MSG_INFO | LLAPI_MSG_NO_ERRNO,
3213                           "Ignoring request for archive #%d (bitmask %#x)\n",
3214                           hal->hal_archive_num, ct->archives);
3215                 rc = 0;
3216                 goto out_free;
3217         }
3218
3219         *halh = hal;
3220         *msgsize = kuch->kuc_msglen - sizeof(*kuch);
3221         return 0;
3222
3223 out_free:
3224         *halh = NULL;
3225         *msgsize = 0;
3226         return rc;
3227 }
3228
3229 /** Release the action list when done with it. */
3230 int llapi_copytool_free(struct hsm_action_list **hal)
3231 {
3232         *hal = NULL;
3233         return 0;
3234 }
3235
3236
3237