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