Whamcloud - gitweb
b=21571 stacksize and locking fixes for loadgen patch from umka
[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                                           __FUNCTION__, path);
950                                 return ret;
951                         }
952                 } else if (errno == ENOENT) {
953                         llapi_err(LLAPI_MSG_WARN,
954                                   "warning: %s: %s does not exist",
955                                   __FUNCTION__, path);
956                         return -ENOENT;
957                 } else {
958                         llapi_err(LLAPI_MSG_ERROR,
959                                  "error: %s: IOC_MDC_GETFILEINFO failed for %s",
960                                  __FUNCTION__, 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                           __FUNCTION__, 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                                   __FUNCTION__);
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                                   __FUNCTION__, 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                                   __FUNCTION__, 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                                           __FUNCTION__,
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                                           __FUNCTION__, path);
1726                                 return ret;
1727                         }
1728                 } else if (errno == ENOENT) {
1729                         llapi_err(LLAPI_MSG_WARN,
1730                                   "warning: %s: %s does not exist",
1731                                   __FUNCTION__, path);
1732                         goto decided;
1733                 } else {
1734                         llapi_err(LLAPI_MSG_ERROR,"error: %s: %s failed for %s",
1735                                   __FUNCTION__, 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                                           __FUNCTION__, path);
1907                                 goto decided;
1908                         } else {
1909                                 llapi_err(LLAPI_MSG_ERROR,
1910                                           "%s: IOC_LOV_GETINFO on %s failed",
1911                                           __FUNCTION__, 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 static int cb_getstripe(char *path, DIR *parent, DIR *d, void *data,
1951                         cfs_dirent_t *de)
1952 {
1953         struct find_param *param = (struct find_param *)data;
1954         int ret = 0;
1955
1956         LASSERT(parent != NULL || d != NULL);
1957
1958         if (param->obduuid) {
1959                 param->quiet = 1;
1960                 ret = setup_obd_uuid(d ? d : parent, path, param);
1961                 if (ret)
1962                         return ret;
1963         }
1964
1965         if (d) {
1966                 ret = ioctl(dirfd(d), LL_IOC_LOV_GETSTRIPE,
1967                             (void *)&param->lmd->lmd_lmm);
1968         } else if (parent) {
1969                 char *fname = strrchr(path, '/');
1970                 fname = (fname == NULL ? path : fname + 1);
1971
1972                 strncpy((char *)&param->lmd->lmd_lmm, fname, param->lumlen);
1973                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILESTRIPE,
1974                             (void *)&param->lmd->lmd_lmm);
1975         }
1976
1977         if (ret) {
1978                 if (errno == ENODATA) {
1979                         if (!param->obduuid)
1980                                 llapi_printf(LLAPI_MSG_NORMAL,
1981                                              "%s has no stripe info\n", path);
1982                         goto out;
1983                 } else if (errno == ENOTTY) {
1984                         llapi_err(LLAPI_MSG_ERROR,
1985                                   "%s: '%s' not on a Lustre fs?",
1986                                   __FUNCTION__, path);
1987                 } else if (errno == ENOENT) {
1988                         llapi_err(LLAPI_MSG_WARN,
1989                                   "warning: %s: %s does not exist",
1990                                   __FUNCTION__, path);
1991                         goto out;
1992                 } else {
1993                         llapi_err(LLAPI_MSG_ERROR,
1994                                   "error: %s: %s failed for %s",
1995                                    __FUNCTION__, d ? "LL_IOC_LOV_GETSTRIPE" :
1996                                   "IOC_MDC_GETFILESTRIPE", path);
1997                 }
1998
1999                 return ret;
2000         }
2001
2002         llapi_lov_dump_user_lmm(param, path, d ? 1 : 0);
2003 out:
2004         /* Do not get down anymore? */
2005         if (param->depth == param->maxdepth)
2006                 return 1;
2007
2008         param->depth++;
2009         return 0;
2010 }
2011
2012 int llapi_getstripe(char *path, struct find_param *param)
2013 {
2014         return param_callback(path, cb_getstripe, cb_common_fini, param);
2015 }
2016
2017 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
2018                      struct obd_statfs *stat_buf,
2019                      struct obd_uuid *uuid_buf)
2020 {
2021         int fd;
2022         char raw[OBD_MAX_IOCTL_BUFFER] = {'\0'};
2023         char *rawbuf = raw;
2024         struct obd_ioctl_data data = { 0 };
2025         int rc = 0;
2026
2027         data.ioc_inlbuf1 = (char *)&type;
2028         data.ioc_inllen1 = sizeof(__u32);
2029         data.ioc_inlbuf2 = (char *)&index;
2030         data.ioc_inllen2 = sizeof(__u32);
2031         data.ioc_pbuf1 = (char *)stat_buf;
2032         data.ioc_plen1 = sizeof(struct obd_statfs);
2033         data.ioc_pbuf2 = (char *)uuid_buf;
2034         data.ioc_plen2 = sizeof(struct obd_uuid);
2035
2036         if ((rc = obd_ioctl_pack(&data, &rawbuf, sizeof(raw))) != 0) {
2037                 llapi_err(LLAPI_MSG_ERROR,
2038                           "llapi_obd_statfs: error packing ioctl data");
2039                 return rc;
2040         }
2041
2042         fd = open(path, O_RDONLY);
2043         if (errno == EISDIR)
2044                 fd = open(path, O_DIRECTORY | O_RDONLY);
2045
2046         if (fd < 0) {
2047                 rc = errno ? -errno : -EBADF;
2048                 llapi_err(LLAPI_MSG_ERROR, "error: %s: opening '%s'",
2049                           __FUNCTION__, path);
2050                 return rc;
2051         }
2052         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
2053         if (rc)
2054                 rc = errno ? -errno : -EINVAL;
2055
2056         close(fd);
2057         return rc;
2058 }
2059
2060 #define MAX_STRING_SIZE 128
2061 #define DEVICES_LIST "/proc/fs/lustre/devices"
2062
2063 int llapi_ping(char *obd_type, char *obd_name)
2064 {
2065         char path[MAX_STRING_SIZE];
2066         char buf[1];
2067         int rc, fd;
2068
2069         snprintf(path, MAX_STRING_SIZE, "/proc/fs/lustre/%s/%s/ping",
2070                  obd_type, obd_name);
2071
2072         fd = open(path, O_WRONLY);
2073         if (fd < 0) {
2074                 rc = errno;
2075                 llapi_err(LLAPI_MSG_ERROR, "error opening %s", path);
2076                 return rc;
2077         }
2078
2079         rc = write(fd, buf, 1);
2080         close(fd);
2081
2082         if (rc == 1)
2083                 return 0;
2084         return rc;
2085 }
2086
2087 int llapi_target_iterate(int type_num, char **obd_type,void *args,llapi_cb_t cb)
2088 {
2089         char buf[MAX_STRING_SIZE];
2090         FILE *fp = fopen(DEVICES_LIST, "r");
2091         int i, rc = 0;
2092
2093         if (fp == NULL) {
2094                 rc = errno;
2095                 llapi_err(LLAPI_MSG_ERROR, "error: opening "DEVICES_LIST);
2096                 return rc;
2097         }
2098
2099         while (fgets(buf, sizeof(buf), fp) != NULL) {
2100                 char *obd_type_name = NULL;
2101                 char *obd_name = NULL;
2102                 char *obd_uuid = NULL;
2103                 char *bufp = buf;
2104                 struct obd_ioctl_data datal = { 0, };
2105                 struct obd_statfs osfs_buffer;
2106
2107                 while(bufp[0] == ' ')
2108                         ++bufp;
2109
2110                 for(i = 0; i < 3; i++) {
2111                         obd_type_name = strsep(&bufp, " ");
2112                 }
2113                 obd_name = strsep(&bufp, " ");
2114                 obd_uuid = strsep(&bufp, " ");
2115
2116                 memset(&osfs_buffer, 0, sizeof (osfs_buffer));
2117
2118                 datal.ioc_pbuf1 = (char *)&osfs_buffer;
2119                 datal.ioc_plen1 = sizeof(osfs_buffer);
2120
2121                 for (i = 0; i < type_num; i++) {
2122                         if (strcmp(obd_type_name, obd_type[i]) != 0)
2123                                 continue;
2124
2125                         cb(obd_type_name, obd_name, obd_uuid, args);
2126                 }
2127         }
2128         fclose(fp);
2129         return rc;
2130 }
2131
2132 static void do_target_check(char *obd_type_name, char *obd_name,
2133                             char *obd_uuid, void *args)
2134 {
2135         int rc;
2136
2137         rc = llapi_ping(obd_type_name, obd_name);
2138         if (rc == ENOTCONN) {
2139                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
2140         } else if (rc) {
2141                 llapi_err(LLAPI_MSG_ERROR, "error: check '%s'", obd_name);
2142         } else {
2143                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
2144         }
2145 }
2146
2147 int llapi_target_check(int type_num, char **obd_type, char *dir)
2148 {
2149         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
2150 }
2151
2152 #undef MAX_STRING_SIZE
2153
2154 int llapi_catinfo(char *dir, char *keyword, char *node_name)
2155 {
2156         char raw[OBD_MAX_IOCTL_BUFFER];
2157         char out[LLOG_CHUNK_SIZE];
2158         char *buf = raw;
2159         struct obd_ioctl_data data = { 0 };
2160         char key[30];
2161         DIR *root;
2162         int rc;
2163
2164         sprintf(key, "%s", keyword);
2165         memset(raw, 0, sizeof(raw));
2166         memset(out, 0, sizeof(out));
2167         data.ioc_inlbuf1 = key;
2168         data.ioc_inllen1 = strlen(key) + 1;
2169         if (node_name) {
2170                 data.ioc_inlbuf2 = node_name;
2171                 data.ioc_inllen2 = strlen(node_name) + 1;
2172         }
2173         data.ioc_pbuf1 = out;
2174         data.ioc_plen1 = sizeof(out);
2175         rc = obd_ioctl_pack(&data, &buf, sizeof(raw));
2176         if (rc)
2177                 return rc;
2178
2179         root = opendir(dir);
2180         if (root == NULL) {
2181                 rc = errno;
2182                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", dir);
2183                 return rc;
2184         }
2185
2186         rc = ioctl(dirfd(root), OBD_IOC_LLOG_CATINFO, buf);
2187         if (rc)
2188                 llapi_err(LLAPI_MSG_ERROR, "ioctl OBD_IOC_CATINFO failed");
2189         else
2190                 llapi_printf(LLAPI_MSG_NORMAL, "%s", data.ioc_pbuf1);
2191
2192         closedir(root);
2193         return rc;
2194 }
2195
2196 /* Is this a lustre fs? */
2197 int llapi_is_lustre_mnttype(const char *type)
2198 {
2199         return (strcmp(type, "lustre") == 0 || strcmp(type,"lustre_lite") == 0);
2200 }
2201
2202 /* Is this a lustre client fs? */
2203 int llapi_is_lustre_mnt(struct mntent *mnt)
2204 {
2205         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
2206                 strstr(mnt->mnt_fsname, ":/") != NULL);
2207 }
2208
2209 int llapi_quotacheck(char *mnt, int check_type)
2210 {
2211         DIR *root;
2212         int rc;
2213
2214         root = opendir(mnt);
2215         if (!root) {
2216                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2217                 return -1;
2218         }
2219
2220         rc = ioctl(dirfd(root), LL_IOC_QUOTACHECK, check_type);
2221
2222         closedir(root);
2223         return rc;
2224 }
2225
2226 int llapi_poll_quotacheck(char *mnt, struct if_quotacheck *qchk)
2227 {
2228         DIR *root;
2229         int poll_intvl = 2;
2230         int rc;
2231
2232         root = opendir(mnt);
2233         if (!root) {
2234                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2235                 return -1;
2236         }
2237
2238         while (1) {
2239                 rc = ioctl(dirfd(root), LL_IOC_POLL_QUOTACHECK, qchk);
2240                 if (!rc)
2241                         break;
2242                 sleep(poll_intvl);
2243                 if (poll_intvl < 30)
2244                         poll_intvl *= 2;
2245         }
2246
2247         closedir(root);
2248         return rc;
2249 }
2250
2251 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
2252 {
2253         DIR *root;
2254         int rc;
2255
2256         root = opendir(mnt);
2257         if (!root) {
2258                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2259                 return -1;
2260         }
2261
2262         rc = ioctl(dirfd(root), LL_IOC_QUOTACTL, qctl);
2263
2264         closedir(root);
2265         return rc;
2266 }
2267
2268 static int cb_quotachown(char *path, DIR *parent, DIR *d, void *data,
2269                          cfs_dirent_t *de)
2270 {
2271         struct find_param *param = (struct find_param *)data;
2272         lstat_t *st;
2273         int rc;
2274
2275         LASSERT(parent != NULL || d != NULL);
2276
2277         if (d) {
2278                 rc = ioctl(dirfd(d), LL_IOC_MDC_GETINFO,
2279                            (void *)param->lmd);
2280         } else if (parent) {
2281                 char *fname = strrchr(path, '/');
2282                 fname = (fname == NULL ? path : fname + 1);
2283
2284                 strncpy((char *)param->lmd, fname, param->lumlen);
2285                 rc = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
2286                            (void *)param->lmd);
2287         } else {
2288                 return 0;
2289         }
2290
2291         if (rc) {
2292                 if (errno == ENODATA) {
2293                         if (!param->obduuid && !param->quiet)
2294                                 llapi_err(LLAPI_MSG_ERROR,
2295                                           "%s has no stripe info", path);
2296                         rc = 0;
2297                 } else if (errno == ENOENT) {
2298                         llapi_err(LLAPI_MSG_ERROR,
2299                                   "warning: %s: %s does not exist",
2300                                   __FUNCTION__, path);
2301                         rc = 0;
2302                 } else if (errno != EISDIR) {
2303                         rc = errno;
2304                         llapi_err(LLAPI_MSG_ERROR, "%s ioctl failed for %s.",
2305                                   d ? "LL_IOC_MDC_GETINFO" :
2306                                   "IOC_MDC_GETFILEINFO", path);
2307                 }
2308                 return rc;
2309         }
2310
2311         st = &param->lmd->lmd_st;
2312
2313         /* libc chown() will do extra check, and if the real owner is
2314          * the same as the ones to set, it won't fall into kernel, so
2315          * invoke syscall directly. */
2316         rc = syscall(SYS_chown, path, -1, -1);
2317         if (rc)
2318                 llapi_err(LLAPI_MSG_ERROR,"error: chown %s (%u,%u)", path);
2319
2320         rc = chmod(path, st->st_mode);
2321         if (rc)
2322                 llapi_err(LLAPI_MSG_ERROR, "error: chmod %s (%hu)",
2323                           path, st->st_mode);
2324
2325         return rc;
2326 }
2327
2328 int llapi_quotachown(char *path, int flag)
2329 {
2330         struct find_param param;
2331
2332         memset(&param, 0, sizeof(param));
2333         param.recursive = 1;
2334         param.verbose = 0;
2335         param.quiet = 1;
2336
2337         return param_callback(path, cb_quotachown, NULL, &param);
2338 }
2339
2340 #include <pwd.h>
2341 #include <grp.h>
2342 #include <mntent.h>
2343 #include <sys/wait.h>
2344 #include <errno.h>
2345 #include <ctype.h>
2346
2347 static int rmtacl_notify(int ops)
2348 {
2349         FILE *fp;
2350         struct mntent *mnt;
2351         int found = 0, fd, rc;
2352
2353         fp = setmntent(MOUNTED, "r");
2354         if (fp == NULL) {
2355                 perror("setmntent");
2356                 return -1;
2357         }
2358
2359         while (1) {
2360                 mnt = getmntent(fp);
2361                 if (!mnt)
2362                         break;
2363
2364                 if (!llapi_is_lustre_mnt(mnt))
2365                         continue;
2366
2367                 fd = open(mnt->mnt_dir, O_RDONLY | O_DIRECTORY);
2368                 if (fd < 0) {
2369                         perror("open");
2370                         return -1;
2371                 }
2372
2373                 rc = ioctl(fd, LL_IOC_RMTACL, ops);
2374                 if (rc < 0) {
2375                         perror("ioctl");
2376                 return -1;
2377                 }
2378
2379                 found++;
2380         }
2381         endmntent(fp);
2382         return found;
2383 }
2384
2385 static char *next_token(char *p, int div)
2386 {
2387         if (p == NULL)
2388                 return NULL;
2389
2390         if (div)
2391                 while (*p && *p != ':' && !isspace(*p))
2392                         p++;
2393         else
2394                 while (*p == ':' || isspace(*p))
2395                         p++;
2396
2397         return *p ? p : NULL;
2398 }
2399
2400 static int rmtacl_name2id(char *name, int is_user)
2401 {
2402         if (is_user) {
2403                 struct passwd *pw;
2404
2405                 if ((pw = getpwnam(name)) == NULL)
2406                         return INVALID_ID;
2407                 else
2408                         return (int)(pw->pw_uid);
2409         } else {
2410                 struct group *gr;
2411
2412                 if ((gr = getgrnam(name)) == NULL)
2413                         return INVALID_ID;
2414                 else
2415                         return (int)(gr->gr_gid);
2416         }
2417 }
2418
2419 static int isodigit(int c)
2420 {
2421         return (c >= '0' && c <= '7') ? 1 : 0;
2422 }
2423
2424 /*
2425  * Whether the name is just digits string (uid/gid) already or not.
2426  * Return value:
2427  * 1: str is id
2428  * 0: str is not id
2429  */
2430 static int str_is_id(char *str)
2431 {
2432         if (str == NULL)
2433                 return 0;
2434
2435         if (*str == '0') {
2436                 str++;
2437                 if (*str == 'x' || *str == 'X') { /* for Hex. */
2438                         if (!isxdigit(*(++str)))
2439                                 return 0;
2440
2441                         while (isxdigit(*(++str)));
2442                 } else if (isodigit(*str)) { /* for Oct. */
2443                         while (isodigit(*(++str)));
2444                 }
2445         } else if (isdigit(*str)) { /* for Dec. */
2446                 while (isdigit(*(++str)));
2447         }
2448
2449         return (*str == 0) ? 1 : 0;
2450 }
2451
2452 typedef struct {
2453         char *name;
2454         int   length;
2455         int   is_user;
2456         int   next_token;
2457 } rmtacl_name_t;
2458
2459 #define RMTACL_OPTNAME(name) name, sizeof(name) - 1
2460
2461 static rmtacl_name_t rmtacl_namelist[] = {
2462         { RMTACL_OPTNAME("user:"),            1,      0 },
2463         { RMTACL_OPTNAME("group:"),           0,      0 },
2464         { RMTACL_OPTNAME("default:user:"),    1,      0 },
2465         { RMTACL_OPTNAME("default:group:"),   0,      0 },
2466         /* for --tabular option */
2467         { RMTACL_OPTNAME("user"),             1,      1 },
2468         { RMTACL_OPTNAME("group"),            0,      1 },
2469         { 0 }
2470 };
2471
2472 static int rgetfacl_output(char *str)
2473 {
2474         char *start = NULL, *end = NULL;
2475         int is_user = 0, n, id;
2476         char c;
2477         rmtacl_name_t *rn;
2478
2479         if (str == NULL)
2480                 return -1;
2481
2482         for (rn = rmtacl_namelist; rn->name; rn++) {
2483                 if(strncmp(str, rn->name, rn->length) == 0) {
2484                         if (!rn->next_token)
2485                                 start = str + rn->length;
2486                         else
2487                                 start = next_token(str + rn->length, 0);
2488                         is_user = rn->is_user;
2489                         break;
2490                 }
2491         }
2492
2493         end = next_token(start, 1);
2494         if (end == NULL || start == end) {
2495                 n = printf("%s", str);
2496                 return n;
2497         }
2498
2499         c = *end;
2500         *end = 0;
2501         id = rmtacl_name2id(start, is_user);
2502         if (id == INVALID_ID) {
2503                 if (str_is_id(start)) {
2504                         *end = c;
2505                         n = printf("%s", str);
2506                 } else
2507                         return -1;
2508         } else if ((id == NOBODY_UID && is_user) ||
2509                    (id == NOBODY_GID && !is_user)) {
2510                 *end = c;
2511                 n = printf("%s", str);
2512         } else {
2513                 *end = c;
2514                 *start = 0;
2515                 n = printf("%s%d%s", str, id, end);
2516         }
2517         return n;
2518 }
2519
2520 static int child_status(int status)
2521 {
2522         return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
2523 }
2524
2525 static int do_rmtacl(int argc, char *argv[], int ops, int (output_func)(char *))
2526 {
2527         pid_t pid = 0;
2528         int fd[2], status;
2529         FILE *fp;
2530         char buf[PIPE_BUF];
2531
2532         if (output_func) {
2533                 if (pipe(fd) < 0) {
2534                         perror("pipe");
2535                         return -1;
2536                 }
2537
2538                 if ((pid = fork()) < 0) {
2539                         perror("fork");
2540                         close(fd[0]);
2541                         close(fd[1]);
2542                         return -1;
2543                 } else if (!pid) {
2544                         /* child process redirects its output. */
2545                         close(fd[0]);
2546                         close(1);
2547                         if (dup2(fd[1], 1) < 0) {
2548                                 perror("dup2");
2549                                 close(fd[1]);
2550                                 return -1;
2551                         }
2552                 } else {
2553                         close(fd[1]);
2554                 }
2555         }
2556
2557         if (!pid) {
2558                 status = rmtacl_notify(ops);
2559                 if (status < 0)
2560                         return -1;
2561
2562                 exit(execvp(argv[0], argv));
2563         }
2564
2565         /* the following is parent process */
2566         if ((fp = fdopen(fd[0], "r")) == NULL) {
2567                 perror("fdopen");
2568                 kill(pid, SIGKILL);
2569                 close(fd[0]);
2570                 return -1;
2571         }
2572
2573         while (fgets(buf, PIPE_BUF, fp) != NULL) {
2574                 if (output_func(buf) < 0)
2575                         fprintf(stderr, "WARNING: unexpected error!\n[%s]\n",
2576                                 buf);
2577         }
2578         fclose(fp);
2579         close(fd[0]);
2580
2581         if (waitpid(pid, &status, 0) < 0) {
2582                 perror("waitpid");
2583                 return -1;
2584         }
2585
2586         return child_status(status);
2587 }
2588
2589 int llapi_lsetfacl(int argc, char *argv[])
2590 {
2591         return do_rmtacl(argc, argv, RMT_LSETFACL, NULL);
2592 }
2593
2594 int llapi_lgetfacl(int argc, char *argv[])
2595 {
2596         return do_rmtacl(argc, argv, RMT_LGETFACL, NULL);
2597 }
2598
2599 int llapi_rsetfacl(int argc, char *argv[])
2600 {
2601         return do_rmtacl(argc, argv, RMT_RSETFACL, NULL);
2602 }
2603
2604 int llapi_rgetfacl(int argc, char *argv[])
2605 {
2606         return do_rmtacl(argc, argv, RMT_RGETFACL, rgetfacl_output);
2607 }
2608
2609 int llapi_cp(int argc, char *argv[])
2610 {
2611         int rc;
2612
2613         rc = rmtacl_notify(RMT_RSETFACL);
2614         if (rc < 0)
2615                 return -1;
2616
2617         exit(execvp(argv[0], argv));
2618 }
2619
2620 int llapi_ls(int argc, char *argv[])
2621 {
2622         int rc;
2623
2624         rc = rmtacl_notify(RMT_LGETFACL);
2625         if (rc < 0)
2626                 return -1;
2627
2628         exit(execvp(argv[0], argv));
2629 }
2630
2631 /* Print mdtname 'name' into 'buf' using 'format'.  Add -MDT0000 if needed.
2632  * format must have %s%s, buf must be > 16
2633  */
2634 static int get_mdtname(char *name, char *format, char *buf)
2635 {
2636         char suffix[]="-MDT0000";
2637         int len = strlen(name);
2638
2639         if ((len > 5) && (strncmp(name + len - 5, "_UUID", 5) == 0)) {
2640                 name[len - 5] = '\0';
2641                 len -= 5;
2642         }
2643
2644         if (len > 8) {
2645                 if ((len <= 16) && strncmp(name + len - 8, "-MDT", 4) == 0) {
2646                         suffix[0] = '\0';
2647                 } else {
2648                         /* Not enough room to add suffix */
2649                         llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2650                                   "MDT name too long |%s|", name);
2651                         return -EINVAL;
2652                 }
2653         }
2654
2655         return sprintf(buf, format, name, suffix);
2656 }
2657
2658 /****** Changelog API ********/
2659 #define CHANGELOG_PRIV_MAGIC 0xCA8E1080
2660 struct changelog_private {
2661         int magic;
2662         int flags;
2663         lustre_netlink lnl;
2664 };
2665
2666 /** Start reading from a changelog
2667  * @param priv Opaque private control structure
2668  * @param flags Start flags (e.g. CHANGELOG_FLAG_BLOCK)
2669  * @param device Report changes recorded on this MDT
2670  * @param startrec Report changes beginning with this record number
2671  * (just call llapi_changelog_fini when done; don't need an endrec)
2672  */
2673 int llapi_changelog_start(void **priv, int flags, const char *device,
2674                           long long startrec)
2675 {
2676         struct changelog_private *cp;
2677         struct changelog_show cs = {};
2678         char mdtname[20];
2679         char pattern[PATH_MAX];
2680         char trigger[PATH_MAX];
2681         int fd, rc, pid;
2682
2683         /* Find mdtname from path, fsname, mdtname, or mdtname_UUID */
2684         if (device[0] == '/') {
2685                 if ((rc = llapi_search_fsname(device, mdtname)))
2686                         return rc;
2687                 if ((rc = get_mdtname(mdtname, "%s%s", mdtname)) < 0)
2688                         return rc;
2689         } else {
2690                 if ((rc = get_mdtname((char *)device, "%s%s", mdtname)) < 0)
2691                         return rc;
2692         }
2693
2694         /* Find corresponding mdc trigger */
2695         snprintf(pattern, PATH_MAX,
2696                  "/proc/fs/lustre/mdc/%s-*/changelog_trigger", mdtname);
2697         rc = first_match(pattern, trigger);
2698         if (rc)
2699                 return rc;
2700
2701         /* Make sure we can write the trigger */
2702         fd = open(trigger, O_WRONLY);
2703         if (fd < 0)
2704                 return -errno;
2705
2706         /* Set up the receiver control struct */
2707         cp = malloc(sizeof(*cp));
2708         if (cp == NULL) {
2709                 close(fd);
2710                 return -ENOMEM;
2711         }
2712
2713         cp->magic = CHANGELOG_PRIV_MAGIC;
2714         cp->flags = flags;
2715         /* Start the receiver */
2716         rc = libcfs_ulnl_start(&cp->lnl, 0 /* unicast */);
2717         if (rc < 0)
2718                 goto out_free;
2719
2720         /* We need to trigger Lustre to start sending messages now.
2721            We could send a lnl message to a kernel listener,
2722            or write into proc.  Proc has the advantage of running in this
2723            context, avoiding the need for a kernel thread. */
2724         cs.cs_pid = getpid();
2725         cs.cs_startrec = startrec;
2726         cs.cs_flags = flags & CHANGELOG_FLAG_BLOCK ? LNL_FL_BLOCK : 0;
2727         if ((pid = fork()) < 0) {
2728                 goto out_free;
2729         } else if (!pid) {
2730                 /* Write triggers Lustre to start sending, but it
2731                    won't return until it is complete, meaning everything
2732                    got shipped through lnl (or error).  So we trigger it
2733                    from a child process here, allowing the llapi call to
2734                    return and wait for the lnl messages. */
2735                 rc = write(fd, &cs, sizeof(cs));
2736                 exit(rc);
2737         }
2738
2739         close(fd);
2740         *priv = cp;
2741         return 0;
2742
2743 out_free:
2744         free(cp);
2745         close(fd);
2746         return rc;
2747 }
2748
2749 /** Finish reading from a changelog */
2750 int llapi_changelog_fini(void **priv)
2751 {
2752         struct changelog_private *cp = (struct changelog_private *)*priv;
2753
2754         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
2755                 return -EINVAL;
2756
2757         libcfs_ulnl_stop(&cp->lnl);
2758         free(cp);
2759         *priv = NULL;
2760         return 0;
2761 }
2762
2763 /** Read the next changelog entry
2764  * @param priv Opaque private control structure
2765  * @param rech Changelog record handle; record will be allocated here
2766  * @return 0 valid message received; rec is set
2767  *         <0 error code
2768  *         1 EOF
2769  */
2770 int llapi_changelog_recv(void *priv, struct changelog_rec **rech)
2771 {
2772         struct changelog_private *cp = (struct changelog_private *)priv;
2773         struct lnl_hdr *lnlh;
2774         int rc = 0;
2775
2776         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
2777                 return -EINVAL;
2778         if (rech == NULL)
2779                 return -EINVAL;
2780
2781 repeat:
2782         rc = libcfs_ulnl_msg_get(&cp->lnl, CR_MAXSIZE, LNL_TRANSPORT_CHANGELOG,
2783                                  &lnlh);
2784         if (rc < 0)
2785                 return rc;
2786
2787         if ((lnlh->lnl_transport != LNL_TRANSPORT_CHANGELOG) ||
2788             ((lnlh->lnl_msgtype != CL_RECORD) &&
2789              (lnlh->lnl_msgtype != CL_EOF))) {
2790                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2791                           "Unknown changelog message type %d:%d\n",
2792                           lnlh->lnl_transport, lnlh->lnl_msgtype);
2793                 rc = -EPROTO;
2794                 goto out_free;
2795         }
2796
2797         if (lnlh->lnl_msgtype == CL_EOF) {
2798                 if (cp->flags & CHANGELOG_FLAG_FOLLOW) {
2799                         /* Ignore EOFs */
2800                         goto repeat;
2801                 } else {
2802                         rc = 1;
2803                         goto out_free;
2804                 }
2805         }
2806
2807         /* Our message is a changelog_rec */
2808         *rech = (struct changelog_rec *)(lnlh + 1);
2809
2810         return 0;
2811
2812 out_free:
2813         libcfs_ulnl_msg_free(&lnlh);
2814         *rech = NULL;
2815         return rc;
2816 }
2817
2818 /** Release the changelog record when done with it. */
2819 int llapi_changelog_free(struct changelog_rec **rech)
2820 {
2821         if (*rech) {
2822                 struct lnl_hdr *lnlh = (struct lnl_hdr *)*rech - 1;
2823                 libcfs_ulnl_msg_free(&lnlh);
2824         }
2825         *rech = NULL;
2826         return 0;
2827 }
2828
2829 int llapi_changelog_clear(const char *mdtname, const char *idstr,
2830                           long long endrec)
2831 {
2832         struct ioc_changelog_clear data;
2833         char fsname[17];
2834         char *ptr;
2835         int id, fd, index, rc;
2836
2837         if (endrec < 0) {
2838                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2839                           "can't purge negative records\n");
2840                 return -EINVAL;
2841         }
2842
2843         id = strtol(idstr + strlen(CHANGELOG_USER_PREFIX), NULL, 10);
2844         if ((id == 0) || (strncmp(idstr, CHANGELOG_USER_PREFIX,
2845                                   strlen(CHANGELOG_USER_PREFIX)) != 0)) {
2846                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2847                           "expecting id of the form '"CHANGELOG_USER_PREFIX
2848                           "<num>'; got '%s'\n", idstr);
2849                 return -EINVAL;
2850         }
2851
2852         /* Take path, fsname, or MDTNAME.  Assume MDT0000 in the former cases */
2853         if (mdtname[0] == '/') {
2854                 index = 0;
2855                 fd = open(mdtname, O_RDONLY | O_DIRECTORY | O_NONBLOCK);
2856                 rc = fd < 0 ? -errno : 0;
2857         } else {
2858                 if (get_mdtname((char *)mdtname, "%s%s", fsname) < 0)
2859                         return -EINVAL;
2860                 ptr = fsname + strlen(fsname) - 8;
2861                 *ptr = '\0';
2862                 index = strtol(ptr + 4, NULL, 10);
2863                 rc = get_root_path(WANT_FD | WANT_ERROR, fsname, &fd, NULL, -1);
2864         }
2865         if (rc < 0) {
2866                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2867                           "Can't open %s: %d\n", mdtname, rc);
2868                 return rc;
2869         }
2870
2871         data.icc_mdtindex = index;
2872         data.icc_id = id;
2873         data.icc_recno = endrec;
2874         rc = ioctl(fd, OBD_IOC_CHANGELOG_CLEAR, &data);
2875         if (rc)
2876                 llapi_err(LLAPI_MSG_ERROR, "ioctl err %d", rc);
2877
2878         close(fd);
2879         return rc;
2880 }
2881
2882 int llapi_fid2path(const char *device, const char *fidstr, char *buf,
2883                    int buflen, long long *recno, int *linkno)
2884 {
2885         char path[PATH_MAX];
2886         struct lu_fid fid;
2887         struct getinfo_fid2path *gf;
2888         int fd, rc;
2889
2890         while (*fidstr == '[')
2891                 fidstr++;
2892
2893         sscanf(fidstr, SFID, RFID(&fid));
2894         if (!fid_is_sane(&fid)) {
2895                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2896                           "bad FID format [%s], should be "DFID"\n",
2897                           fidstr, (__u64)1, 2, 0);
2898                 return -EINVAL;
2899         }
2900
2901         /* Take path or fsname */
2902         if (device[0] == '/') {
2903                 strcpy(path, device);
2904         } else {
2905                 rc = get_root_path(WANT_PATH | WANT_ERROR, (char *)device,
2906                                    NULL, path, -1);
2907                 if (rc < 0)
2908                         return rc;
2909         }
2910         sprintf(path, "%s/%s/fid/%s", path, dot_lustre_name, fidstr);
2911         fd = open(path, O_RDONLY | O_NONBLOCK);
2912         if (fd < 0)
2913                 return -errno;
2914
2915         gf = malloc(sizeof(*gf) + buflen);
2916         gf->gf_fid = fid;
2917         gf->gf_recno = *recno;
2918         gf->gf_linkno = *linkno;
2919         gf->gf_pathlen = buflen;
2920         rc = ioctl(fd, OBD_IOC_FID2PATH, gf);
2921         if (rc) {
2922                 llapi_err(LLAPI_MSG_ERROR, "ioctl err %d", rc);
2923         } else {
2924                 memcpy(buf, gf->gf_path, gf->gf_pathlen);
2925                 *recno = gf->gf_recno;
2926                 *linkno = gf->gf_linkno;
2927         }
2928
2929         free(gf);
2930         close(fd);
2931         return rc;
2932 }
2933
2934 static int path2fid_from_lma(const char *path, lustre_fid *fid)
2935 {
2936         char buf[512];
2937         struct lustre_mdt_attrs *lma;
2938         int rc;
2939
2940         rc = lgetxattr(path, XATTR_NAME_LMA, buf, sizeof(buf));
2941         if (rc < 0)
2942                 return -errno;
2943         lma = (struct lustre_mdt_attrs *)buf;
2944         fid_le_to_cpu(fid, &lma->lma_self_fid);
2945         return 0;
2946 }
2947
2948 int llapi_path2fid(const char *path, lustre_fid *fid)
2949 {
2950         int fd, rc;
2951
2952         memset(fid, 0, sizeof(*fid));
2953         fd = open(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
2954         if (fd < 0) {
2955                 if (errno == ELOOP) /* symbolic link */
2956                         return path2fid_from_lma(path, fid);
2957                 return -errno;
2958         }
2959
2960         rc = ioctl(fd, LL_IOC_PATH2FID, fid) < 0 ? -errno : 0;
2961         if (rc == -EINVAL) /* char special device */
2962                 rc = path2fid_from_lma(path, fid);
2963
2964         close(fd);
2965         return rc;
2966 }
2967
2968 /****** HSM Copytool API ********/
2969 #define CT_PRIV_MAGIC 0xC0BE2001
2970 struct copytool_private {
2971         int magic;
2972         lustre_netlink lnl;
2973         int archive_num_count;
2974         int archive_nums[0];
2975 };
2976
2977 #include <libcfs/libcfs.h>
2978
2979 /** Register a copytool
2980  * @param priv Opaque private control structure
2981  * @param flags Open flags, currently unused (e.g. O_NONBLOCK)
2982  * @param archive_num_count
2983  * @param archive_nums Which archive numbers this copytool is responsible for
2984  */
2985 int llapi_copytool_start(void **priv, int flags, int archive_num_count,
2986                          int *archive_nums)
2987 {
2988         struct copytool_private *ct;
2989         int rc;
2990
2991         if (archive_num_count > 0 && archive_nums == NULL) {
2992                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2993                           "NULL archive numbers");
2994                 return -EINVAL;
2995         }
2996
2997         ct = malloc(sizeof(*ct) +
2998                     archive_num_count * sizeof(ct->archive_nums[0]));
2999         if (ct == NULL)
3000                 return -ENOMEM;
3001
3002         ct->magic = CT_PRIV_MAGIC;
3003         ct->archive_num_count = archive_num_count;
3004         if (ct->archive_num_count > 0)
3005                 memcpy(ct->archive_nums, archive_nums, archive_num_count *
3006                        sizeof(ct->archive_nums[0]));
3007
3008         rc = libcfs_ulnl_start(&ct->lnl, LNL_GRP_HSM);
3009         if (rc < 0)
3010                 goto out_err;
3011
3012         *priv = ct;
3013         return 0;
3014
3015 out_err:
3016         free(ct);
3017         return rc;
3018 }
3019
3020 /** Deregister a copytool */
3021 int llapi_copytool_fini(void **priv)
3022 {
3023         struct copytool_private *ct = (struct copytool_private *)*priv;
3024
3025         if (!ct || (ct->magic != CT_PRIV_MAGIC))
3026                 return -EINVAL;
3027
3028         libcfs_ulnl_stop(&ct->lnl);
3029         free(ct);
3030         *priv = NULL;
3031         return 0;
3032 }
3033
3034 /** Wait for the next hsm_action_list
3035  * @param priv Opaque private control structure
3036  * @param halh Action list handle, will be allocated here
3037  * @param msgsize Number of bytes in the message, will be set here
3038  * @return 0 valid message received; halh and msgsize are set
3039  *         <0 error code
3040  */
3041 int llapi_copytool_recv(void *priv, struct hsm_action_list **halh, int *msgsize)
3042 {
3043         struct copytool_private *ct = (struct copytool_private *)priv;
3044         struct lnl_hdr *lnlh;
3045         struct hsm_action_list *hal;
3046         int rc = 0;
3047
3048         if (!ct || (ct->magic != CT_PRIV_MAGIC))
3049                 return -EINVAL;
3050         if (halh == NULL || msgsize == NULL)
3051                 return -EINVAL;
3052
3053         rc = libcfs_ulnl_msg_get(&ct->lnl, HAL_MAXSIZE,
3054                                  LNL_TRANSPORT_HSM, &lnlh);
3055         if (rc < 0)
3056                 return rc;
3057
3058         /* Handle generic messages */
3059         if (lnlh->lnl_transport == LNL_TRANSPORT_GENERIC &&
3060             lnlh->lnl_msgtype == LNL_MSG_SHUTDOWN) {
3061                 rc = -ESHUTDOWN;
3062                 goto out_free;
3063         }
3064
3065         if (lnlh->lnl_transport != LNL_TRANSPORT_HSM ||
3066             lnlh->lnl_msgtype != HMT_ACTION_LIST) {
3067                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
3068                           "Unknown HSM message type %d:%d\n",
3069                           lnlh->lnl_transport, lnlh->lnl_msgtype);
3070                 rc = -EPROTO;
3071                 goto out_free;
3072         }
3073
3074         /* Our message is an hsm_action_list */
3075
3076         hal = (struct hsm_action_list *)(lnlh + 1);
3077
3078         /* Check that we have registered for this archive # */
3079         for (rc = 0; rc < ct->archive_num_count; rc++) {
3080                 if (hal->hal_archive_num == ct->archive_nums[rc])
3081                         break;
3082         }
3083         if (rc >= ct->archive_num_count) {
3084                 CDEBUG(D_INFO, "This copytool does not service archive #%d, "
3085                        "ignoring this request.\n", hal->hal_archive_num);
3086                 rc = 0;
3087                 goto out_free;
3088         }
3089
3090         *halh = hal;
3091         *msgsize = lnlh->lnl_msglen - sizeof(*lnlh);
3092         return 0;
3093
3094 out_free:
3095         libcfs_ulnl_msg_free(&lnlh);
3096         *halh = NULL;
3097         *msgsize = 0;
3098         return rc;
3099 }
3100
3101 /** Release the action list when done with it. */
3102 int llapi_copytool_free(struct hsm_action_list **hal)
3103 {
3104         if (*hal) {
3105                 struct lnl_hdr *lnlh = (struct lnl_hdr *)*hal - 1;
3106                 libcfs_ulnl_msg_free(&lnlh);
3107         }
3108         *hal = NULL;
3109         return 0;
3110 }
3111
3112
3113