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