Whamcloud - gitweb
LU-2684 fid: unify ostid and FID
[fs/lustre-release.git] / lustre / utils / liblustreapi.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2012, Intel Corporation.
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 #include <libgen.h> /* for dirname() */
65 #ifdef HAVE_LINUX_UNISTD_H
66 #include <linux/unistd.h>
67 #else
68 #include <unistd.h>
69 #endif
70 #include <poll.h>
71
72 #include <liblustre.h>
73 #include <lnet/lnetctl.h>
74 #include <obd.h>
75 #include <obd_lov.h>
76 #include <lustre/lustreapi.h>
77 #include "lustreapi_internal.h"
78
79 static unsigned llapi_dir_filetype_table[] = {
80         [DT_UNKNOWN]= 0,
81         [DT_FIFO]= S_IFIFO,
82         [DT_CHR] = S_IFCHR,
83         [DT_DIR] = S_IFDIR,
84         [DT_BLK] = S_IFBLK,
85         [DT_REG] = S_IFREG,
86         [DT_LNK] = S_IFLNK,
87         [DT_SOCK]= S_IFSOCK,
88 #if defined(DT_DOOR) && defined(S_IFDOOR)
89         [DT_DOOR]= S_IFDOOR,
90 #endif
91 };
92
93 #if defined(DT_DOOR) && defined(S_IFDOOR)
94 static const int DT_MAX = DT_DOOR;
95 #else
96 static const int DT_MAX = DT_SOCK;
97 #endif
98
99 static unsigned llapi_filetype_dir_table[] = {
100         [0]= DT_UNKNOWN,
101         [S_IFIFO]= DT_FIFO,
102         [S_IFCHR] = DT_CHR,
103         [S_IFDIR] = DT_DIR,
104         [S_IFBLK] = DT_BLK,
105         [S_IFREG] = DT_REG,
106         [S_IFLNK] = DT_LNK,
107         [S_IFSOCK]= DT_SOCK,
108 #if defined(DT_DOOR) && defined(S_IFDOOR)
109         [S_IFDOOR]= DT_DOOR,
110 #endif
111 };
112
113 #if defined(DT_DOOR) && defined(S_IFDOOR)
114 static const int S_IFMAX = DT_DOOR;
115 #else
116 static const int S_IFMAX = DT_SOCK;
117 #endif
118
119 /* liblustreapi message level */
120 static int llapi_msg_level = LLAPI_MSG_MAX;
121
122 void llapi_msg_set_level(int level)
123 {
124         /* ensure level is in the good range */
125         if (level < LLAPI_MSG_OFF)
126                 llapi_msg_level = LLAPI_MSG_OFF;
127         else if (level > LLAPI_MSG_MAX)
128                 llapi_msg_level = LLAPI_MSG_MAX;
129         else
130                 llapi_msg_level = level;
131 }
132
133 /* llapi_error will preserve errno */
134 void llapi_error(int level, int _rc, char *fmt, ...)
135 {
136         va_list args;
137         int tmp_errno = errno;
138         /* to protect using errno as _rc argument */
139         int rc = abs(_rc);
140
141         if ((level & LLAPI_MSG_MASK) > llapi_msg_level)
142                 return;
143
144         va_start(args, fmt);
145         vfprintf(stderr, fmt, args);
146         va_end(args);
147
148         if (level & LLAPI_MSG_NO_ERRNO)
149                 fprintf(stderr, "\n");
150         else
151                 fprintf(stderr, ": %s (%d)\n", strerror(rc), rc);
152         errno = tmp_errno;
153 }
154
155 /* llapi_printf will preserve errno */
156 void llapi_printf(int level, char *fmt, ...)
157 {
158         va_list args;
159         int tmp_errno = errno;
160
161         if ((level & LLAPI_MSG_MASK) > llapi_msg_level)
162                 return;
163
164         va_start(args, fmt);
165         vfprintf(stdout, fmt, args);
166         va_end(args);
167         errno = tmp_errno;
168 }
169
170 /**
171  * size_units is to be initialized (or zeroed) by caller.
172  */
173 int parse_size(char *optarg, unsigned long long *size,
174                unsigned long long *size_units, int bytes_spec)
175 {
176         char *end;
177
178         if (strncmp(optarg, "-", 1) == 0)
179                 return -1;
180
181         if (*size_units == 0)
182                 *size_units = 1;
183
184         *size = strtoull(optarg, &end, 0);
185
186         if (*end != '\0') {
187                 if ((*end == 'b') && *(end + 1) == '\0' &&
188                     (*size & (~0ULL << (64 - 9))) == 0 &&
189                     !bytes_spec) {
190                         *size_units = 1 << 9;
191                 } else if ((*end == 'b') &&
192                            *(end + 1) == '\0' &&
193                            bytes_spec) {
194                         *size_units = 1;
195                 } else if ((*end == 'k' || *end == 'K') &&
196                            *(end + 1) == '\0' &&
197                            (*size & (~0ULL << (64 - 10))) == 0) {
198                         *size_units = 1 << 10;
199                 } else if ((*end == 'm' || *end == 'M') &&
200                            *(end + 1) == '\0' &&
201                            (*size & (~0ULL << (64 - 20))) == 0) {
202                         *size_units = 1 << 20;
203                 } else if ((*end == 'g' || *end == 'G') &&
204                            *(end + 1) == '\0' &&
205                            (*size & (~0ULL << (64 - 30))) == 0) {
206                         *size_units = 1 << 30;
207                 } else if ((*end == 't' || *end == 'T') &&
208                            *(end + 1) == '\0' &&
209                            (*size & (~0ULL << (64 - 40))) == 0) {
210                         *size_units = 1ULL << 40;
211                 } else if ((*end == 'p' || *end == 'P') &&
212                            *(end + 1) == '\0' &&
213                            (*size & (~0ULL << (64 - 50))) == 0) {
214                         *size_units = 1ULL << 50;
215                 } else if ((*end == 'e' || *end == 'E') &&
216                            *(end + 1) == '\0' &&
217                            (*size & (~0ULL << (64 - 60))) == 0) {
218                         *size_units = 1ULL << 60;
219                 } else {
220                         return -1;
221                 }
222         }
223         *size *= *size_units;
224         return 0;
225 }
226
227 /* XXX: llapi_xxx() functions return negative values upon failure */
228
229 int llapi_stripe_limit_check(unsigned long long stripe_size, int stripe_offset,
230                                 int stripe_count, int stripe_pattern)
231 {
232         int page_size, rc;
233
234         /* 64 KB is the largest common page size I'm aware of (on ia64), but
235          * check the local page size just in case. */
236         page_size = LOV_MIN_STRIPE_SIZE;
237         if (getpagesize() > page_size) {
238                 page_size = getpagesize();
239                 llapi_err_noerrno(LLAPI_MSG_WARN,
240                                 "warning: your page size (%u) is "
241                                 "larger than expected (%u)", page_size,
242                                 LOV_MIN_STRIPE_SIZE);
243         }
244         if (stripe_size < 0 || (stripe_size & (LOV_MIN_STRIPE_SIZE - 1))) {
245                 rc = -EINVAL;
246                 llapi_error(LLAPI_MSG_ERROR, rc, "error: bad stripe_size %lu, "
247                                 "must be an even multiple of %d bytes",
248                                 stripe_size, page_size);
249                 return rc;
250         }
251         if (stripe_offset < -1 || stripe_offset > MAX_OBD_DEVICES) {
252                 rc = -EINVAL;
253                 llapi_error(LLAPI_MSG_ERROR, rc, "error: bad stripe offset %d",
254                                 stripe_offset);
255                 return rc;
256         }
257         if (stripe_count < -1 || stripe_count > LOV_MAX_STRIPE_COUNT) {
258                 rc = -EINVAL;
259                 llapi_error(LLAPI_MSG_ERROR, rc, "error: bad stripe count %d",
260                                 stripe_count);
261                 return rc;
262         }
263         if (stripe_size >= (1ULL << 32)) {
264                 rc = -EINVAL;
265                 llapi_error(LLAPI_MSG_ERROR, rc,
266                                 "warning: stripe size 4G or larger "
267                                 "is not currently supported and would wrap");
268                 return rc;
269         }
270         return 0;
271 }
272
273 /* return the first file matching this pattern */
274 static int first_match(char *pattern, char *buffer)
275 {
276         glob_t glob_info;
277
278         if (glob(pattern, GLOB_BRACE, NULL, &glob_info))
279                 return -ENOENT;
280
281         if (glob_info.gl_pathc < 1) {
282                 globfree(&glob_info);
283                 return -ENOENT;
284         }
285
286         strcpy(buffer, glob_info.gl_pathv[0]);
287
288         globfree(&glob_info);
289         return 0;
290 }
291
292 static int find_target_obdpath(char *fsname, char *path)
293 {
294         glob_t glob_info;
295         char pattern[PATH_MAX + 1];
296         int rc;
297
298         snprintf(pattern, PATH_MAX,
299                  "/proc/fs/lustre/lov/%s-*/target_obd",
300                  fsname);
301         rc = glob(pattern, GLOB_BRACE, NULL, &glob_info);
302         if (rc == GLOB_NOMATCH)
303                 return -ENODEV;
304         else if (rc)
305                 return -EINVAL;
306
307         strcpy(path, glob_info.gl_pathv[0]);
308         globfree(&glob_info);
309         return 0;
310 }
311
312 static int find_poolpath(char *fsname, char *poolname, char *poolpath)
313 {
314         glob_t glob_info;
315         char pattern[PATH_MAX + 1];
316         int rc;
317
318         snprintf(pattern, PATH_MAX,
319                  "/proc/fs/lustre/lov/%s-*/pools/%s",
320                  fsname, poolname);
321         rc = glob(pattern, GLOB_BRACE, NULL, &glob_info);
322         /* If no pools, make sure the lov is available */
323         if ((rc == GLOB_NOMATCH) &&
324             (find_target_obdpath(fsname, poolpath) == -ENODEV))
325                 return -ENODEV;
326         if (rc)
327                 return -EINVAL;
328
329         strcpy(poolpath, glob_info.gl_pathv[0]);
330         globfree(&glob_info);
331         return 0;
332 }
333
334 /**
335   * return a parameter string for a specific device type or mountpoint
336   *
337   * \param param_path the path to the file containing parameter data
338   * \param result buffer for parameter value string
339   * \param result_size size of buffer for return value
340   *
341   * The \param param_path is appended to /proc/{fs,sys}/{lnet,lustre} to
342   * complete the absolute path to the file containing the parameter data
343   * the user is requesting. If that file exist then the data is read from
344   * the file and placed into the \param result buffer that is passed by
345   * the user. Data is only copied up to the \param result_size to prevent
346   * overflow of the array.
347   *
348   * Return 0 for success, with a NUL-terminated string in \param result.
349   * Return -ve value for error.
350   */
351 static int get_param(const char *param_path, char *result,
352                      unsigned int result_size)
353 {
354         char file[PATH_MAX + 1], pattern[PATH_MAX + 1], buf[result_size];
355         FILE *fp = NULL;
356         int rc = 0;
357
358         snprintf(pattern, PATH_MAX, "/proc/{fs,sys}/{lnet,lustre}/%s",
359                  param_path);
360         rc = first_match(pattern, file);
361         if (rc)
362                 return rc;
363
364         fp = fopen(file, "r");
365         if (fp != NULL) {
366                 while (fgets(buf, result_size, fp) != NULL)
367                         strcpy(result, buf);
368                 fclose(fp);
369         } else {
370                 rc = -errno;
371         }
372         return rc;
373 }
374
375 #define DEVICES_LIST "/proc/fs/lustre/devices"
376
377 /**
378   * return a parameter string for a specific device type or mountpoint
379   *
380   * \param fsname Lustre filesystem name (optional)
381   * \param file_path path to file in filesystem (optional, if fsname unset)
382   * \param obd_type Lustre OBD device type
383   * \param param_name parameter name to fetch
384   * \param value return buffer for parameter value string
385   * \param val_len size of buffer for return value
386   *
387   * If fsname is specified then the parameter will be from that filesystem
388   * (if it exists). If file_path is given and it is in a mounted Lustre
389   * filesystem, then the parameter will be otherwise the value may be
390   * from any mounted filesystem (if there is more than one).
391   *
392   * If "obd_type" matches a Lustre device then the first matching device
393   * (as with "lctl dl", constrained by \param fsname or \param mount_path)
394   * will be used to provide the return value, otherwise the first such
395   * device found will be used.
396   *
397   * Return 0 for success, with a NUL-terminated string in \param buffer.
398   * Return -ve value for error.
399   */
400 static int get_param_obdvar(const char *fsname, const char *file_path,
401                             const char *obd_type, const char *param_name,
402                             char *value, unsigned int val_len)
403 {
404         char devices[PATH_MAX + 1], dev[PATH_MAX + 1] = "*", fs[PATH_MAX + 1];
405         FILE *fp = fopen(DEVICES_LIST, "r");
406         int rc = 0;
407
408         if (!fsname && file_path) {
409                 rc = llapi_search_fsname(file_path, fs);
410                 if (rc) {
411                         llapi_error(LLAPI_MSG_ERROR, rc,
412                                     "'%s' is not on a Lustre filesystem",
413                                     file_path);
414                         if (fp != NULL)
415                                 fclose(fp);
416                         return rc;
417                 }
418         } else if (fsname) {
419                 strcpy(fs, fsname);
420         }
421
422         if (fp == NULL) {
423                 rc = -errno;
424                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening "DEVICES_LIST);
425                 return rc;
426         }
427
428         while (fgets(devices, sizeof(devices), fp) != NULL) {
429                 char *bufp = devices, *tmp;
430
431                 while (bufp[0] == ' ')
432                         ++bufp;
433
434                 tmp = strstr(bufp, obd_type);
435                 if (tmp) {
436                         tmp += strlen(obd_type) + 1;
437                         if (strcmp(tmp, fs))
438                                 continue;
439                         strcpy(dev, tmp);
440                         tmp = strchr(dev, ' ');
441                         *tmp = '\0';
442                         break;
443                 }
444         }
445
446         if (dev[0] == '*' && strlen(fs))
447                 snprintf(dev, PATH_MAX, "%s-*", fs);
448         snprintf(devices, PATH_MAX, "%s/%s/%s", obd_type, dev, param_name);
449         fclose(fp);
450         return get_param(devices, value, val_len);
451 }
452
453 static int get_mds_md_size(char *path)
454 {
455         int lumlen = lov_mds_md_size(LOV_MAX_STRIPE_COUNT, LOV_MAGIC_V3);
456         char buf[16];
457
458         /* Now get the maxea from llite proc */
459         if (!get_param_obdvar(NULL, path, "llite", "max_easize",
460                               buf, sizeof(buf)))
461                 lumlen = atoi(buf);
462         return lumlen;
463 }
464
465 /*
466  * if pool is NULL, search ostname in target_obd
467  * if pool is not NULL:
468  *  if pool not found returns errno < 0
469  *  if ostname is NULL, returns 1 if pool is not empty and 0 if pool empty
470  *  if ostname is not NULL, returns 1 if OST is in pool and 0 if not
471  */
472 int llapi_search_ost(char *fsname, char *poolname, char *ostname)
473 {
474         FILE *fd;
475         char buffer[PATH_MAX + 1];
476         int len = 0, rc;
477
478         if (ostname != NULL)
479                 len = strlen(ostname);
480
481         if (poolname == NULL)
482                 rc = find_target_obdpath(fsname, buffer);
483         else
484                 rc = find_poolpath(fsname, poolname, buffer);
485         if (rc)
486                 return rc;
487
488         fd = fopen(buffer, "r");
489         if (fd == NULL)
490                 return -errno;
491
492         while (fgets(buffer, sizeof(buffer), fd) != NULL) {
493                 if (poolname == NULL) {
494                         char *ptr;
495                         /* Search for an ostname in the list of OSTs
496                          Line format is IDX: fsname-OSTxxxx_UUID STATUS */
497                         ptr = strchr(buffer, ' ');
498                         if ((ptr != NULL) &&
499                             (strncmp(ptr + 1, ostname, len) == 0)) {
500                                 fclose(fd);
501                                 return 1;
502                         }
503                 } else {
504                         /* Search for an ostname in a pool,
505                          (or an existing non-empty pool if no ostname) */
506                         if ((ostname == NULL) ||
507                             (strncmp(buffer, ostname, len) == 0)) {
508                                 fclose(fd);
509                                 return 1;
510                         }
511                 }
512         }
513         fclose(fd);
514         return 0;
515 }
516
517 int llapi_file_open_pool(const char *name, int flags, int mode,
518                          unsigned long long stripe_size, int stripe_offset,
519                          int stripe_count, int stripe_pattern, char *pool_name)
520 {
521         struct lov_user_md_v3 lum = { 0 };
522         int fd, rc = 0;
523         int isdir = 0;
524
525         /* Make sure we have a good pool */
526         if (pool_name != NULL) {
527                 char fsname[MAX_OBD_NAME + 1], *ptr;
528
529                 rc = llapi_search_fsname(name, fsname);
530                 if (rc) {
531                         llapi_error(LLAPI_MSG_ERROR, rc,
532                                     "'%s' is not on a Lustre filesystem",
533                                     name);
534                         return rc;
535                 }
536
537                 /* in case user gives the full pool name <fsname>.<poolname>,
538                  * strip the fsname */
539                 ptr = strchr(pool_name, '.');
540                 if (ptr != NULL) {
541                         *ptr = '\0';
542                         if (strcmp(pool_name, fsname) != 0) {
543                                 *ptr = '.';
544                                 llapi_err_noerrno(LLAPI_MSG_ERROR,
545                                           "Pool '%s' is not on filesystem '%s'",
546                                           pool_name, fsname);
547                                 return -EINVAL;
548                         }
549                         pool_name = ptr + 1;
550                 }
551
552                 /* Make sure the pool exists and is non-empty */
553                 rc = llapi_search_ost(fsname, pool_name, NULL);
554                 if (rc < 1) {
555                         llapi_err_noerrno(LLAPI_MSG_ERROR,
556                                           "pool '%s.%s' %s", fsname, pool_name,
557                                           rc == 0 ? "has no OSTs" : "does not exist");
558                         return -EINVAL;
559                 }
560         }
561
562         fd = open(name, flags | O_LOV_DELAY_CREATE, mode);
563         if (fd < 0 && errno == EISDIR) {
564                 fd = open(name, O_DIRECTORY | O_RDONLY);
565                 isdir++;
566         }
567
568         if (fd < 0) {
569                 rc = -errno;
570                 llapi_error(LLAPI_MSG_ERROR, rc, "unable to open '%s'", name);
571                 return rc;
572         }
573
574         rc = llapi_stripe_limit_check(stripe_size, stripe_offset, stripe_count,
575                                       stripe_pattern);
576         if (rc != 0)
577                 goto out;
578
579         /*  Initialize IOCTL striping pattern structure */
580         lum.lmm_magic = LOV_USER_MAGIC_V3;
581         lum.lmm_pattern = stripe_pattern;
582         lum.lmm_stripe_size = stripe_size;
583         lum.lmm_stripe_count = stripe_count;
584         lum.lmm_stripe_offset = stripe_offset;
585         if (pool_name != NULL) {
586                 strncpy(lum.lmm_pool_name, pool_name, LOV_MAXPOOLNAME);
587         } else {
588                 /* If no pool is specified at all, use V1 request */
589                 lum.lmm_magic = LOV_USER_MAGIC_V1;
590         }
591
592         if (ioctl(fd, LL_IOC_LOV_SETSTRIPE, &lum)) {
593                 char *errmsg = "stripe already set";
594                 rc = -errno;
595                 if (errno != EEXIST && errno != EALREADY)
596                         errmsg = strerror(errno);
597
598                 llapi_err_noerrno(LLAPI_MSG_ERROR,
599                                   "error on ioctl "LPX64" for '%s' (%d): %s",
600                                   (__u64)LL_IOC_LOV_SETSTRIPE, name, fd,errmsg);
601         }
602 out:
603         if (rc) {
604                 close(fd);
605                 fd = rc;
606         }
607
608         return fd;
609 }
610
611 int llapi_file_open(const char *name, int flags, int mode,
612                     unsigned long long stripe_size, int stripe_offset,
613                     int stripe_count, int stripe_pattern)
614 {
615         return llapi_file_open_pool(name, flags, mode, stripe_size,
616                                     stripe_offset, stripe_count,
617                                     stripe_pattern, NULL);
618 }
619
620 int llapi_file_create(const char *name, unsigned long long stripe_size,
621                       int stripe_offset, int stripe_count, int stripe_pattern)
622 {
623         int fd;
624
625         fd = llapi_file_open_pool(name, O_CREAT | O_WRONLY, 0644, stripe_size,
626                                   stripe_offset, stripe_count, stripe_pattern,
627                                   NULL);
628         if (fd < 0)
629                 return fd;
630
631         close(fd);
632         return 0;
633 }
634
635 int llapi_file_create_pool(const char *name, unsigned long long stripe_size,
636                            int stripe_offset, int stripe_count,
637                            int stripe_pattern, char *pool_name)
638 {
639         int fd;
640
641         fd = llapi_file_open_pool(name, O_CREAT | O_WRONLY, 0644, stripe_size,
642                                   stripe_offset, stripe_count, stripe_pattern,
643                                   pool_name);
644         if (fd < 0)
645                 return fd;
646
647         close(fd);
648         return 0;
649 }
650
651 /**
652  * In DNE phase I, only stripe_offset will be used in this function.
653  * stripe_count, stripe_pattern and pool_name will be supported later.
654  */
655 int llapi_dir_create_pool(const char *name, int flags, int stripe_offset,
656                           int stripe_count, int stripe_pattern, char *pool_name)
657 {
658         struct lmv_user_md lmu = { 0 };
659         struct obd_ioctl_data data = { 0 };
660         char rawbuf[8192];
661         char *buf = rawbuf;
662         char *dirpath = NULL;
663         char *namepath = NULL;
664         char *dir;
665         char *filename;
666         int fd = -1;
667         int rc;
668
669         dirpath = strdup(name);
670         namepath = strdup(name);
671         if (!dirpath || !namepath)
672                 return -ENOMEM;
673
674         lmu.lum_magic = LMV_USER_MAGIC;
675         lmu.lum_stripe_offset = stripe_offset;
676         lmu.lum_stripe_count = stripe_count;
677         lmu.lum_hash_type = stripe_pattern;
678         if (pool_name != NULL) {
679                 if (strlen(pool_name) >= LOV_MAXPOOLNAME) {
680                         llapi_err_noerrno(LLAPI_MSG_ERROR,
681                                   "error LL_IOC_LMV_SETSTRIPE '%s' : too large"
682                                   "pool name: %s", name, pool_name);
683                         GOTO(out, rc = -E2BIG);
684                 }
685                 memcpy(lmu.lum_pool_name, pool_name, strlen(pool_name));
686         }
687
688         filename = basename(namepath);
689         lmu.lum_type = LMV_STRIPE_TYPE;
690         dir = dirname(dirpath);
691
692         data.ioc_inlbuf1 = (char *)filename;
693         data.ioc_inllen1 = strlen(filename) + 1;
694         data.ioc_inlbuf2 = (char *)&lmu;
695         data.ioc_inllen2 = sizeof(struct lmv_user_md);
696         rc = obd_ioctl_pack(&data, &buf, sizeof(rawbuf));
697         if (rc) {
698                 llapi_error(LLAPI_MSG_ERROR, rc,
699                             "error: LL_IOC_LMV_SETSTRIPE pack failed '%s'.",
700                             name);
701                 GOTO(out, rc);
702         }
703
704         fd = open(dir, O_DIRECTORY | O_RDONLY);
705         if (fd < 0) {
706                 rc = -errno;
707                 llapi_error(LLAPI_MSG_ERROR, rc, "unable to open '%s'", name);
708                 GOTO(out, rc);
709         }
710
711         if (ioctl(fd, LL_IOC_LMV_SETSTRIPE, buf)) {
712                 char *errmsg = "stripe already set";
713                 rc = -errno;
714                 if (errno != EEXIST && errno != EALREADY)
715                         errmsg = strerror(errno);
716
717                 llapi_err_noerrno(LLAPI_MSG_ERROR,
718                                   "error on LL_IOC_LMV_SETSTRIPE '%s' (%d): %s",
719                                   name, fd, errmsg);
720         }
721         close(fd);
722 out:
723         free(dirpath);
724         free(namepath);
725         return rc;
726 }
727
728 int llapi_direntry_remove(char *dname)
729 {
730         char *dirpath = NULL;
731         char *namepath = NULL;
732         char *dir;
733         char *filename;
734         int fd = -1;
735         int rc = 0;
736
737         dirpath = strdup(dname);
738         namepath = strdup(dname);
739         if (!dirpath || !namepath)
740                 return -ENOMEM;
741
742         filename = basename(namepath);
743
744         dir = dirname(dirpath);
745
746         fd = open(dir, O_DIRECTORY | O_RDONLY);
747         if (fd < 0) {
748                 rc = -errno;
749                 llapi_error(LLAPI_MSG_ERROR, rc, "unable to open '%s'",
750                             filename);
751                 GOTO(out, rc);
752         }
753
754         if (ioctl(fd, LL_IOC_REMOVE_ENTRY, filename)) {
755                 char *errmsg = strerror(errno);
756                 llapi_err_noerrno(LLAPI_MSG_ERROR,
757                                   "error on ioctl "LPX64" for '%s' (%d): %s",
758                                   (__u64)LL_IOC_LMV_SETSTRIPE, filename,
759                                   fd, errmsg);
760         }
761 out:
762         free(dirpath);
763         free(namepath);
764         if (fd != -1)
765                 close(fd);
766         return rc;
767 }
768
769 /*
770  * Find the fsname, the full path, and/or an open fd.
771  * Either the fsname or path must not be NULL
772  */
773 int get_root_path(int want, char *fsname, int *outfd, char *path, int index)
774 {
775         struct mntent mnt;
776         char buf[PATH_MAX], mntdir[PATH_MAX];
777         char *ptr;
778         FILE *fp;
779         int idx = 0, len = 0, mntlen, fd;
780         int rc = -ENODEV;
781
782         /* get the mount point */
783         fp = setmntent(MOUNTED, "r");
784         if (fp == NULL) {
785                 rc = -EIO;
786                 llapi_error(LLAPI_MSG_ERROR, rc,
787                             "setmntent(%s) failed", MOUNTED);
788                 return rc;
789         }
790         while (1) {
791                 if (getmntent_r(fp, &mnt, buf, sizeof(buf)) == NULL)
792                         break;
793
794                 if (!llapi_is_lustre_mnt(&mnt))
795                         continue;
796
797                 if ((want & WANT_INDEX) && (idx++ != index))
798                         continue;
799
800                 mntlen = strlen(mnt.mnt_dir);
801                 ptr = strrchr(mnt.mnt_fsname, '/');
802                 if (!ptr && !len) {
803                         rc = -EINVAL;
804                         break;
805                 }
806                 ptr++;
807
808                 /* Check the fsname for a match, if given */
809                 if (!(want & WANT_FSNAME) && fsname != NULL &&
810                     (strlen(fsname) > 0) && (strcmp(ptr, fsname) != 0))
811                         continue;
812
813                 /* If the path isn't set return the first one we find */
814                 if (path == NULL || strlen(path) == 0) {
815                         strcpy(mntdir, mnt.mnt_dir);
816                         if ((want & WANT_FSNAME) && fsname != NULL)
817                                 strcpy(fsname, ptr);
818                         rc = 0;
819                         break;
820                 /* Otherwise find the longest matching path */
821                 } else if ((strlen(path) >= mntlen) && (mntlen >= len) &&
822                            (strncmp(mnt.mnt_dir, path, mntlen) == 0)) {
823                         strcpy(mntdir, mnt.mnt_dir);
824                         len = mntlen;
825                         if ((want & WANT_FSNAME) && fsname != NULL)
826                                 strcpy(fsname, ptr);
827                         rc = 0;
828                 }
829         }
830         endmntent(fp);
831
832         /* Found it */
833         if (rc == 0) {
834                 if ((want & WANT_PATH) && path != NULL)
835                         strcpy(path, mntdir);
836                 if (want & WANT_FD) {
837                         fd = open(mntdir, O_RDONLY | O_DIRECTORY | O_NONBLOCK);
838                         if (fd < 0) {
839                                 rc = -errno;
840                                 llapi_error(LLAPI_MSG_ERROR, rc,
841                                             "error opening '%s'", mntdir);
842
843                         } else {
844                                 *outfd = fd;
845                         }
846                 }
847         } else if (want & WANT_ERROR)
848                 llapi_err_noerrno(LLAPI_MSG_ERROR,
849                                   "can't find fs root for '%s': %d",
850                                   (want & WANT_PATH) ? fsname : path, rc);
851         return rc;
852 }
853
854 /*
855  * search lustre mounts
856  *
857  * Calling this function will return to the user the mount point, mntdir, and
858  * the file system name, fsname, if the user passed a buffer to this routine.
859  *
860  * The user inputs are pathname and index. If the pathname is supplied then
861  * the value of the index will be ignored. The pathname will return data if
862  * the pathname is located on a lustre mount. Index is used to pick which
863  * mount point you want in the case of multiple mounted lustre file systems.
864  * See function lfs_osts in lfs.c for a example of the index use.
865  */
866 int llapi_search_mounts(const char *pathname, int index, char *mntdir,
867                         char *fsname)
868 {
869         int want = WANT_PATH, idx = -1;
870
871         if (!pathname || pathname[0] == '\0') {
872                 want |= WANT_INDEX;
873                 idx = index;
874         } else
875                 strcpy(mntdir, pathname);
876
877         if (fsname)
878                 want |= WANT_FSNAME;
879         return get_root_path(want, fsname, NULL, mntdir, idx);
880 }
881
882 /* Given a path, find the corresponding Lustre fsname */
883 int llapi_search_fsname(const char *pathname, char *fsname)
884 {
885         char *path;
886         int rc;
887
888         path = realpath(pathname, NULL);
889         if (path == NULL) {
890                 char buf[PATH_MAX + 1], *ptr;
891
892                 buf[0] = 0;
893                 if (pathname[0] != '/') {
894                         /* Need an absolute path, but realpath() only works for
895                          * pathnames that actually exist.  We go through the
896                          * extra hurdle of dirname(getcwd() + pathname) in
897                          * case the relative pathname contains ".." in it. */
898                         if (getcwd(buf, sizeof(buf) - 1) == NULL)
899                                 return -errno;
900                         strcat(buf, "/");
901                 }
902                 strncat(buf, pathname, sizeof(buf) - strlen(buf));
903                 path = realpath(buf, NULL);
904                 if (path == NULL) {
905                         ptr = strrchr(buf, '/');
906                         if (ptr == NULL)
907                                 return -ENOENT;
908                         *ptr = '\0';
909                         path = realpath(buf, NULL);
910                         if (path == NULL) {
911                                 rc = -errno;
912                                 llapi_error(LLAPI_MSG_ERROR, rc,
913                                             "pathname '%s' cannot expand",
914                                             pathname);
915                                 return rc;
916                         }
917                 }
918         }
919         rc = get_root_path(WANT_FSNAME | WANT_ERROR, fsname, NULL, path, -1);
920         free(path);
921         return rc;
922 }
923
924 int llapi_search_rootpath(char *pathname, const char *fsname)
925 {
926         return get_root_path(WANT_PATH, (char *)fsname, NULL, pathname, -1);
927 }
928
929 int llapi_getname(const char *path, char *buf, size_t size)
930 {
931         struct obd_uuid uuid_buf;
932         char *uuid = uuid_buf.uuid;
933         int rc, nr;
934
935         memset(&uuid_buf, 0, sizeof(uuid_buf));
936         rc = llapi_file_get_lov_uuid(path, &uuid_buf);
937         if (rc)
938                 return rc;
939
940         /* We want to turn lustre-clilov-ffff88002738bc00 into
941          * lustre-ffff88002738bc00. */
942
943         nr = snprintf(buf, size, "%.*s-%s",
944                       (int) (strlen(uuid) - 24), uuid,
945                       uuid + strlen(uuid) - 16);
946
947         if (nr >= size)
948                 rc = -ENAMETOOLONG;
949
950         return rc;
951 }
952
953
954 /*
955  * find the pool directory path under /proc
956  * (can be also used to test if a fsname is known)
957  */
958 static int poolpath(char *fsname, char *pathname, char *pool_pathname)
959 {
960         int rc = 0;
961         char pattern[PATH_MAX + 1];
962         char buffer[PATH_MAX];
963
964         if (fsname == NULL) {
965                 rc = llapi_search_fsname(pathname, buffer);
966                 if (rc != 0)
967                         return rc;
968                 fsname = buffer;
969                 strcpy(pathname, fsname);
970         }
971
972         snprintf(pattern, PATH_MAX, "/proc/fs/lustre/lov/%s-*/pools", fsname);
973         rc = first_match(pattern, buffer);
974         if (rc)
975                 return rc;
976
977         /* in fsname test mode, pool_pathname is NULL */
978         if (pool_pathname != NULL)
979                 strcpy(pool_pathname, buffer);
980
981         return 0;
982 }
983
984 /**
985  * Get the list of pool members.
986  * \param poolname    string of format \<fsname\>.\<poolname\>
987  * \param members     caller-allocated array of char*
988  * \param list_size   size of the members array
989  * \param buffer      caller-allocated buffer for storing OST names
990  * \param buffer_size size of the buffer
991  *
992  * \return number of members retrieved for this pool
993  * \retval -error failure
994  */
995 int llapi_get_poolmembers(const char *poolname, char **members,
996                           int list_size, char *buffer, int buffer_size)
997 {
998         char fsname[PATH_MAX + 1];
999         char *pool, *tmp;
1000         char pathname[PATH_MAX + 1];
1001         char path[PATH_MAX + 1];
1002         char buf[1024];
1003         FILE *fd;
1004         int rc = 0;
1005         int nb_entries = 0;
1006         int used = 0;
1007
1008         /* name is FSNAME.POOLNAME */
1009         if (strlen(poolname) > PATH_MAX)
1010                 return -EOVERFLOW;
1011         strcpy(fsname, poolname);
1012         pool = strchr(fsname, '.');
1013         if (pool == NULL)
1014                 return -EINVAL;
1015
1016         *pool = '\0';
1017         pool++;
1018
1019         rc = poolpath(fsname, NULL, pathname);
1020         if (rc != 0) {
1021                 llapi_error(LLAPI_MSG_ERROR, rc,
1022                             "Lustre filesystem '%s' not found",
1023                             fsname);
1024                 return rc;
1025         }
1026
1027         llapi_printf(LLAPI_MSG_NORMAL, "Pool: %s.%s\n", fsname, pool);
1028         sprintf(path, "%s/%s", pathname, pool);
1029         fd = fopen(path, "r");
1030         if (fd == NULL) {
1031                 rc = -errno;
1032                 llapi_error(LLAPI_MSG_ERROR, rc, "Cannot open %s", path);
1033                 return rc;
1034         }
1035
1036         rc = 0;
1037         while (fgets(buf, sizeof(buf), fd) != NULL) {
1038                 if (nb_entries >= list_size) {
1039                         rc = -EOVERFLOW;
1040                         break;
1041                 }
1042                 /* remove '\n' */
1043                 tmp = strchr(buf, '\n');
1044                 if (tmp != NULL)
1045                         *tmp='\0';
1046                 if (used + strlen(buf) + 1 > buffer_size) {
1047                         rc = -EOVERFLOW;
1048                         break;
1049                 }
1050
1051                 strcpy(buffer + used, buf);
1052                 members[nb_entries] = buffer + used;
1053                 used += strlen(buf) + 1;
1054                 nb_entries++;
1055                 rc = nb_entries;
1056         }
1057
1058         fclose(fd);
1059         return rc;
1060 }
1061
1062 /**
1063  * Get the list of pools in a filesystem.
1064  * \param name        filesystem name or path
1065  * \param poollist    caller-allocated array of char*
1066  * \param list_size   size of the poollist array
1067  * \param buffer      caller-allocated buffer for storing pool names
1068  * \param buffer_size size of the buffer
1069  *
1070  * \return number of pools retrieved for this filesystem
1071  * \retval -error failure
1072  */
1073 int llapi_get_poollist(const char *name, char **poollist, int list_size,
1074                        char *buffer, int buffer_size)
1075 {
1076         char fsname[PATH_MAX + 1], rname[PATH_MAX + 1], pathname[PATH_MAX + 1];
1077         char *ptr;
1078         DIR *dir;
1079         struct dirent pool;
1080         struct dirent *cookie = NULL;
1081         int rc = 0;
1082         unsigned int nb_entries = 0;
1083         unsigned int used = 0;
1084         unsigned int i;
1085
1086         /* initilize output array */
1087         for (i = 0; i < list_size; i++)
1088                 poollist[i] = NULL;
1089
1090         /* is name a pathname ? */
1091         ptr = strchr(name, '/');
1092         if (ptr != NULL) {
1093                 /* only absolute pathname is supported */
1094                 if (*name != '/')
1095                         return -EINVAL;
1096
1097                 if (!realpath(name, rname)) {
1098                         rc = -errno;
1099                         llapi_error(LLAPI_MSG_ERROR, rc, "invalid path '%s'",
1100                                     name);
1101                         return rc;
1102                 }
1103
1104                 rc = poolpath(NULL, rname, pathname);
1105                 if (rc != 0) {
1106                         llapi_error(LLAPI_MSG_ERROR, rc, "'%s' is not"
1107                                     " a Lustre filesystem", name);
1108                         return rc;
1109                 }
1110                 strcpy(fsname, rname);
1111         } else {
1112                 /* name is FSNAME */
1113                 strcpy(fsname, name);
1114                 rc = poolpath(fsname, NULL, pathname);
1115         }
1116         if (rc != 0) {
1117                 llapi_error(LLAPI_MSG_ERROR, rc,
1118                             "Lustre filesystem '%s' not found", name);
1119                 return rc;
1120         }
1121
1122         llapi_printf(LLAPI_MSG_NORMAL, "Pools from %s:\n", fsname);
1123         dir = opendir(pathname);
1124         if (dir == NULL) {
1125                 rc = -errno;
1126                 llapi_error(LLAPI_MSG_ERROR, rc,
1127                             "Could not open pool list for '%s'",
1128                             name);
1129                 return rc;
1130         }
1131
1132         while(1) {
1133                 rc = readdir_r(dir, &pool, &cookie);
1134
1135                 if (rc != 0) {
1136                         rc = -errno;
1137                         llapi_error(LLAPI_MSG_ERROR, rc,
1138                                     "Error reading pool list for '%s'", name);
1139                         goto out;
1140                 } else if ((rc == 0) && (cookie == NULL)) {
1141                         /* end of directory */
1142                         break;
1143                 }
1144
1145                 /* ignore . and .. */
1146                 if (!strcmp(pool.d_name, ".") || !strcmp(pool.d_name, ".."))
1147                         continue;
1148
1149                 /* check output bounds */
1150                 if (nb_entries >= list_size) {
1151                         rc = -EOVERFLOW;
1152                         goto out;
1153                 }
1154
1155                 /* +2 for '.' and final '\0' */
1156                 if (used + strlen(pool.d_name) + strlen(fsname) + 2
1157                     > buffer_size) {
1158                         rc = -EOVERFLOW;
1159                         goto out;
1160                 }
1161
1162                 sprintf(buffer + used, "%s.%s", fsname, pool.d_name);
1163                 poollist[nb_entries] = buffer + used;
1164                 used += strlen(pool.d_name) + strlen(fsname) + 2;
1165                 nb_entries++;
1166         }
1167
1168 out:
1169         closedir(dir);
1170         return ((rc != 0) ? rc : nb_entries);
1171 }
1172
1173 /* wrapper for lfs.c and obd.c */
1174 int llapi_poollist(const char *name)
1175 {
1176         /* list of pool names (assume that pool count is smaller
1177            than OST count) */
1178         char **list, *buffer = NULL, *path = NULL, *fsname = NULL;
1179         int obdcount, bufsize, rc, nb, i;
1180         char *poolname = NULL, *tmp = NULL, data[16];
1181
1182         if (name[0] != '/') {
1183                 fsname = strdup(name);
1184                 poolname = strchr(fsname, '.');
1185                 if (poolname)
1186                         *poolname = '\0';
1187         } else {
1188                 path = (char *) name;
1189         }
1190
1191         rc = get_param_obdvar(fsname, path, "lov", "numobd",
1192                               data, sizeof(data));
1193         if (rc < 0)
1194                 goto err;
1195         obdcount = atoi(data);
1196
1197         /* Allocate space for each fsname-OST0000_UUID, 1 per OST,
1198          * and also an array to store the pointers for all that
1199          * allocated space. */
1200 retry_get_pools:
1201         bufsize = sizeof(struct obd_uuid) * obdcount;
1202         buffer = realloc(tmp, bufsize + sizeof(*list) * obdcount);
1203         if (buffer == NULL) {
1204                 rc = -ENOMEM;
1205                 goto err;
1206         }
1207         list = (char **) (buffer + bufsize);
1208
1209         if (!poolname) {
1210                 /* name is a path or fsname */
1211                 nb = llapi_get_poollist(name, list, obdcount,
1212                                         buffer, bufsize);
1213         } else {
1214                 /* name is a pool name (<fsname>.<poolname>) */
1215                 nb = llapi_get_poolmembers(name, list, obdcount,
1216                                            buffer, bufsize);
1217         }
1218
1219         if (nb == -EOVERFLOW) {
1220                 obdcount *= 2;
1221                 tmp = buffer;
1222                 goto retry_get_pools;
1223         }
1224
1225         for (i = 0; i < nb; i++)
1226                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", list[i]);
1227         rc = (nb < 0 ? nb : 0);
1228 err:
1229         if (buffer)
1230                 free(buffer);
1231         if (fsname)
1232                 free(fsname);
1233         return rc;
1234 }
1235
1236 typedef int (semantic_func_t)(char *path, DIR *parent, DIR *d,
1237                               void *data, struct dirent64 *de);
1238
1239 #define OBD_NOT_FOUND           (-1)
1240
1241 static int common_param_init(struct find_param *param, char *path)
1242 {
1243         param->lumlen = get_mds_md_size(path);
1244         param->lmd = malloc(sizeof(lstat_t) + param->lumlen);
1245         if (param->lmd == NULL) {
1246                 llapi_error(LLAPI_MSG_ERROR, -ENOMEM,
1247                             "error: allocation of %d bytes for ioctl",
1248                             sizeof(lstat_t) + param->lumlen);
1249                 return -ENOMEM;
1250         }
1251
1252         param->fp_lmv_count = 256;
1253         param->fp_lmv_md = malloc(lmv_user_md_size(256, LMV_MAGIC_V1));
1254         if (param->fp_lmv_md == NULL) {
1255                 llapi_error(LLAPI_MSG_ERROR, -ENOMEM,
1256                             "error: allocation of %d bytes for ioctl",
1257                             lmv_user_md_size(256, LMV_MAGIC_V1));
1258                 return -ENOMEM;
1259         }
1260
1261         param->got_uuids = 0;
1262         param->obdindexes = NULL;
1263         param->obdindex = OBD_NOT_FOUND;
1264         param->mdtindex = OBD_NOT_FOUND;
1265         return 0;
1266 }
1267
1268 static void find_param_fini(struct find_param *param)
1269 {
1270         if (param->obdindexes)
1271                 free(param->obdindexes);
1272
1273         if (param->lmd)
1274                 free(param->lmd);
1275
1276         if (param->fp_lmv_md)
1277                 free(param->fp_lmv_md);
1278 }
1279
1280 static int cb_common_fini(char *path, DIR *parent, DIR *d, void *data,
1281                           struct dirent64 *de)
1282 {
1283         struct find_param *param = (struct find_param *)data;
1284         param->depth--;
1285         return 0;
1286 }
1287
1288 /* set errno upon failure */
1289 static DIR *opendir_parent(char *path)
1290 {
1291         DIR *parent;
1292         char *fname;
1293         char c;
1294
1295         fname = strrchr(path, '/');
1296         if (fname == NULL)
1297                 return opendir(".");
1298
1299         c = fname[1];
1300         fname[1] = '\0';
1301         parent = opendir(path);
1302         fname[1] = c;
1303         return parent;
1304 }
1305
1306 static int cb_get_dirstripe(char *path, DIR *d, struct find_param *param)
1307 {
1308         struct lmv_user_md *lmv = (struct lmv_user_md *)param->fp_lmv_md;
1309         int ret = 0;
1310
1311         lmv->lum_stripe_count = param->fp_lmv_count;
1312         lmv->lum_magic = LMV_MAGIC_V1;
1313         ret = ioctl(dirfd(d), LL_IOC_LMV_GETSTRIPE, lmv);
1314         return ret;
1315 }
1316
1317 static int get_lmd_info(char *path, DIR *parent, DIR *dir,
1318                  struct lov_user_mds_data *lmd, int lumlen)
1319 {
1320         lstat_t *st = &lmd->lmd_st;
1321         int ret = 0;
1322
1323         if (parent == NULL && dir == NULL)
1324                 return -EINVAL;
1325
1326         if (dir) {
1327                 ret = ioctl(dirfd(dir), LL_IOC_MDC_GETINFO, (void *)lmd);
1328         } else if (parent) {
1329                 char *fname = strrchr(path, '/');
1330
1331                 fname = (fname == NULL ? path : fname + 1);
1332                 /* retrieve needed file info */
1333                 strncpy((char *)lmd, fname, lumlen);
1334                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO, (void *)lmd);
1335         } else {
1336                 return ret;
1337         }
1338
1339         if (ret) {
1340                 if (errno == ENOTTY) {
1341                         /* ioctl is not supported, it is not a lustre fs.
1342                          * Do the regular lstat(2) instead. */
1343                         ret = lstat_f(path, st);
1344                         if (ret) {
1345                                 ret = -errno;
1346                                 llapi_error(LLAPI_MSG_ERROR, ret,
1347                                             "error: %s: lstat failed for %s",
1348                                             __func__, path);
1349                         }
1350                 } else if (errno == ENOENT) {
1351                         ret = -errno;
1352                         llapi_error(LLAPI_MSG_WARN, ret,
1353                                     "warning: %s: %s does not exist",
1354                                     __func__, path);
1355                 } else if (errno != EISDIR) {
1356                         ret = -errno;
1357                         llapi_error(LLAPI_MSG_ERROR, ret,
1358                                     "%s ioctl failed for %s.",
1359                                     dir ? "LL_IOC_MDC_GETINFO" :
1360                                     "IOC_MDC_GETFILEINFO", path);
1361                 } else {
1362                         ret = -errno;
1363                         llapi_error(LLAPI_MSG_ERROR, ret,
1364                                  "error: %s: IOC_MDC_GETFILEINFO failed for %s",
1365                                    __func__, path);
1366                 }
1367         }
1368         return ret;
1369 }
1370
1371 int llapi_mds_getfileinfo(char *path, DIR *parent,
1372                           struct lov_user_mds_data *lmd)
1373 {
1374         int lumlen = get_mds_md_size(path);
1375
1376         return get_lmd_info(path, parent, NULL, lmd, lumlen);
1377 }
1378
1379 static int llapi_semantic_traverse(char *path, int size, DIR *parent,
1380                                    semantic_func_t sem_init,
1381                                    semantic_func_t sem_fini, void *data,
1382                                    struct dirent64 *de)
1383 {
1384         struct find_param *param = (struct find_param *)data;
1385         struct dirent64 *dent;
1386         int len, ret;
1387         DIR *d, *p = NULL;
1388
1389         ret = 0;
1390         len = strlen(path);
1391
1392         d = opendir(path);
1393         if (!d && errno != ENOTDIR) {
1394                 ret = -errno;
1395                 llapi_error(LLAPI_MSG_ERROR, ret, "%s: Failed to open '%s'",
1396                             __func__, path);
1397                 return ret;
1398         } else if (!d && !parent) {
1399                 /* ENOTDIR. Open the parent dir. */
1400                 p = opendir_parent(path);
1401                 if (!p)
1402                         GOTO(out, ret = -errno);
1403         }
1404
1405         if (sem_init && (ret = sem_init(path, parent ?: p, d, data, de)))
1406                 goto err;
1407
1408         if (!d || (param->get_lmv && !param->recursive))
1409                 GOTO(out, ret = 0);
1410
1411         while ((dent = readdir64(d)) != NULL) {
1412                 param->have_fileinfo = 0;
1413
1414                 if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
1415                         continue;
1416
1417                 /* Don't traverse .lustre directory */
1418                 if (!(strcmp(dent->d_name, dot_lustre_name)))
1419                         continue;
1420
1421                 path[len] = 0;
1422                 if ((len + dent->d_reclen + 2) > size) {
1423                         llapi_err_noerrno(LLAPI_MSG_ERROR,
1424                                           "error: %s: string buffer is too small",
1425                                           __func__);
1426                         break;
1427                 }
1428                 strcat(path, "/");
1429                 strcat(path, dent->d_name);
1430
1431                 if (dent->d_type == DT_UNKNOWN) {
1432                         lstat_t *st = &param->lmd->lmd_st;
1433
1434                         ret = llapi_mds_getfileinfo(path, d, param->lmd);
1435                         if (ret == 0) {
1436                                 dent->d_type =
1437                                         llapi_filetype_dir_table[st->st_mode &
1438                                                                  S_IFMT];
1439                         }
1440                         if (ret == -ENOENT)
1441                                 continue;
1442                 }
1443                 switch (dent->d_type) {
1444                 case DT_UNKNOWN:
1445                         llapi_err_noerrno(LLAPI_MSG_ERROR,
1446                                           "error: %s: '%s' is UNKNOWN type %d",
1447                                           __func__, dent->d_name, dent->d_type);
1448                         break;
1449                 case DT_DIR:
1450                         ret = llapi_semantic_traverse(path, size, d, sem_init,
1451                                                       sem_fini, data, dent);
1452                         if (ret < 0)
1453                                 goto out;
1454                         break;
1455                 default:
1456                         ret = 0;
1457                         if (sem_init) {
1458                                 ret = sem_init(path, d, NULL, data, dent);
1459                                 if (ret < 0)
1460                                         goto out;
1461                         }
1462                         if (sem_fini && ret == 0)
1463                                 sem_fini(path, d, NULL, data, dent);
1464                 }
1465         }
1466
1467 out:
1468         path[len] = 0;
1469
1470         if (sem_fini)
1471                 sem_fini(path, parent, d, data, de);
1472 err:
1473         if (d)
1474                 closedir(d);
1475         if (p)
1476                 closedir(p);
1477         return ret;
1478 }
1479
1480 static int param_callback(char *path, semantic_func_t sem_init,
1481                           semantic_func_t sem_fini, struct find_param *param)
1482 {
1483         int ret, len = strlen(path);
1484         char *buf;
1485
1486         if (len > PATH_MAX) {
1487                 ret = -EINVAL;
1488                 llapi_error(LLAPI_MSG_ERROR, ret,
1489                             "Path name '%s' is too long", path);
1490                 return ret;
1491         }
1492
1493         buf = (char *)malloc(PATH_MAX + 1);
1494         if (!buf)
1495                 return -ENOMEM;
1496
1497         strncpy(buf, path, PATH_MAX + 1);
1498         ret = common_param_init(param, buf);
1499         if (ret)
1500                 goto out;
1501         param->depth = 0;
1502
1503         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, sem_init,
1504                                       sem_fini, param, NULL);
1505 out:
1506         find_param_fini(param);
1507         free(buf);
1508         return ret < 0 ? ret : 0;
1509 }
1510
1511 int llapi_file_fget_lov_uuid(int fd, struct obd_uuid *lov_name)
1512 {
1513         int rc = ioctl(fd, OBD_IOC_GETNAME, lov_name);
1514         if (rc) {
1515                 rc = -errno;
1516                 llapi_error(LLAPI_MSG_ERROR, rc, "error: can't get lov name.");
1517         }
1518         return rc;
1519 }
1520
1521 int llapi_file_fget_lmv_uuid(int fd, struct obd_uuid *lov_name)
1522 {
1523         int rc = ioctl(fd, OBD_IOC_GETMDNAME, lov_name);
1524         if (rc) {
1525                 rc = -errno;
1526                 llapi_error(LLAPI_MSG_ERROR, rc, "error: can't get lmv name.");
1527         }
1528         return rc;
1529 }
1530
1531 int llapi_file_get_lov_uuid(const char *path, struct obd_uuid *lov_uuid)
1532 {
1533         int fd, rc;
1534
1535         fd = open(path, O_RDONLY);
1536         if (fd < 0) {
1537                 rc = -errno;
1538                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s", path);
1539                 return rc;
1540         }
1541
1542         rc = llapi_file_fget_lov_uuid(fd, lov_uuid);
1543
1544         close(fd);
1545         return rc;
1546 }
1547
1548 enum tgt_type {
1549         LOV_TYPE = 1,
1550         LMV_TYPE
1551 };
1552 /*
1553  * If uuidp is NULL, return the number of available obd uuids.
1554  * If uuidp is non-NULL, then it will return the uuids of the obds. If
1555  * there are more OSTs then allocated to uuidp, then an error is returned with
1556  * the ost_count set to number of available obd uuids.
1557  */
1558 static int llapi_get_target_uuids(int fd, struct obd_uuid *uuidp,
1559                                   int *ost_count, enum tgt_type type)
1560 {
1561         struct obd_uuid name;
1562         char buf[1024];
1563         FILE *fp;
1564         int rc = 0, index = 0;
1565
1566         /* Get the lov name */
1567         if (type == LOV_TYPE) {
1568                 rc = llapi_file_fget_lov_uuid(fd, &name);
1569                 if (rc)
1570                         return rc;
1571         } else {
1572                 rc = llapi_file_fget_lmv_uuid(fd, &name);
1573                 if (rc)
1574                         return rc;
1575         }
1576
1577         /* Now get the ost uuids from /proc */
1578         snprintf(buf, sizeof(buf), "/proc/fs/lustre/%s/%s/target_obd",
1579                  type == LOV_TYPE ? "lov" : "lmv", name.uuid);
1580         fp = fopen(buf, "r");
1581         if (fp == NULL) {
1582                 rc = -errno;
1583                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening '%s'", buf);
1584                 return rc;
1585         }
1586
1587         while (fgets(buf, sizeof(buf), fp) != NULL) {
1588                 if (uuidp && (index < *ost_count)) {
1589                         if (sscanf(buf, "%d: %s", &index, uuidp[index].uuid) <2)
1590                                 break;
1591                 }
1592                 index++;
1593         }
1594
1595         fclose(fp);
1596
1597         if (uuidp && (index > *ost_count))
1598                 rc = -EOVERFLOW;
1599
1600         *ost_count = index;
1601         return rc;
1602 }
1603
1604 int llapi_lov_get_uuids(int fd, struct obd_uuid *uuidp, int *ost_count)
1605 {
1606         return llapi_get_target_uuids(fd, uuidp, ost_count, LOV_TYPE);
1607 }
1608
1609 int llapi_get_obd_count(char *mnt, int *count, int is_mdt)
1610 {
1611         DIR *root;
1612         int rc;
1613
1614         root = opendir(mnt);
1615         if (!root) {
1616                 rc = -errno;
1617                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
1618                 return rc;
1619         }
1620
1621         *count = is_mdt;
1622         rc = ioctl(dirfd(root), LL_IOC_GETOBDCOUNT, count);
1623         if (rc < 0)
1624                 rc = -errno;
1625
1626         closedir(root);
1627         return rc;
1628 }
1629
1630 /* Check if user specified value matches a real uuid.  Ignore _UUID,
1631  * -osc-4ba41334, other trailing gunk in comparison.
1632  * @param real_uuid ends in "_UUID"
1633  * @param search_uuid may or may not end in "_UUID"
1634  */
1635 int llapi_uuid_match(char *real_uuid, char *search_uuid)
1636 {
1637         int cmplen = strlen(real_uuid);
1638         int searchlen = strlen(search_uuid);
1639
1640         if (cmplen > 5 && strcmp(real_uuid + cmplen - 5, "_UUID") == 0)
1641                 cmplen -= 5;
1642         if (searchlen > 5 && strcmp(search_uuid + searchlen - 5, "_UUID") == 0)
1643                 searchlen -= 5;
1644
1645         /* The UUIDs may legitimately be different lengths, if
1646          * the system was upgraded from an older version. */
1647         if (cmplen != searchlen)
1648                 return 0;
1649
1650         return (strncmp(search_uuid, real_uuid, cmplen) == 0);
1651 }
1652
1653 /* Here, param->obduuid points to a single obduuid, the index of which is
1654  * returned in param->obdindex */
1655 static int setup_obd_uuid(DIR *dir, char *dname, struct find_param *param)
1656 {
1657         struct obd_uuid obd_uuid;
1658         char uuid[sizeof(struct obd_uuid)];
1659         char buf[1024];
1660         FILE *fp;
1661         int rc = 0, index;
1662
1663         if (param->got_uuids)
1664                 return rc;
1665
1666         /* Get the lov/lmv name */
1667         if (param->get_lmv)
1668                 rc = llapi_file_fget_lmv_uuid(dirfd(dir), &obd_uuid);
1669         else
1670                 rc = llapi_file_fget_lov_uuid(dirfd(dir), &obd_uuid);
1671         if (rc) {
1672                 if (rc != -ENOTTY) {
1673                         llapi_error(LLAPI_MSG_ERROR, rc,
1674                                     "error: can't get lov name: %s", dname);
1675                 } else {
1676                         rc = 0;
1677                 }
1678                 return rc;
1679         }
1680
1681         param->got_uuids = 1;
1682
1683         /* Now get the ost uuids from /proc */
1684         snprintf(buf, sizeof(buf), "/proc/fs/lustre/%s/%s/target_obd",
1685                  param->get_lmv ? "lmv" : "lov", obd_uuid.uuid);
1686         fp = fopen(buf, "r");
1687         if (fp == NULL) {
1688                 rc = -errno;
1689                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening '%s'", buf);
1690                 return rc;
1691         }
1692
1693         if (!param->obduuid && !param->quiet && !param->obds_printed)
1694                 llapi_printf(LLAPI_MSG_NORMAL, "%s:\n",
1695                              param->get_lmv ? "MDTS" : "OBDS:");
1696
1697         while (fgets(buf, sizeof(buf), fp) != NULL) {
1698                 if (sscanf(buf, "%d: %s", &index, uuid) < 2)
1699                         break;
1700
1701                 if (param->obduuid) {
1702                         if (llapi_uuid_match(uuid, param->obduuid->uuid)) {
1703                                 param->obdindex = index;
1704                                 break;
1705                         }
1706                 } else if (!param->quiet && !param->obds_printed) {
1707                         /* Print everything */
1708                         llapi_printf(LLAPI_MSG_NORMAL, "%s", buf);
1709                 }
1710         }
1711         param->obds_printed = 1;
1712
1713         fclose(fp);
1714
1715         if (param->obduuid && (param->obdindex == OBD_NOT_FOUND)) {
1716                 llapi_err_noerrno(LLAPI_MSG_ERROR,
1717                                   "error: %s: unknown obduuid: %s",
1718                                   __func__, param->obduuid->uuid);
1719                 rc = -EINVAL;
1720         }
1721
1722         return (rc);
1723 }
1724
1725 /* In this case, param->obduuid will be an array of obduuids and
1726  * obd index for all these obduuids will be returned in
1727  * param->obdindexes */
1728 static int setup_indexes(DIR *dir, char *path, struct obd_uuid *obduuids,
1729                          int num_obds, int **obdindexes, int *obdindex,
1730                          enum tgt_type type)
1731 {
1732         int ret, obdcount, obd_valid = 0, obdnum, i;
1733         struct obd_uuid *uuids = NULL;
1734         char buf[16];
1735         int *indexes;
1736
1737         ret = get_param_obdvar(NULL, path, type == LOV_TYPE ? "lov" : "lmv",
1738                                "numobd", buf, sizeof(buf));
1739         if (ret)
1740                 return ret;
1741
1742         obdcount = atoi(buf);
1743         uuids = (struct obd_uuid *)malloc(obdcount *
1744                                           sizeof(struct obd_uuid));
1745         if (uuids == NULL)
1746                 return -ENOMEM;
1747
1748 retry_get_uuids:
1749         ret = llapi_get_target_uuids(dirfd(dir), uuids, &obdcount, type);
1750         if (ret) {
1751                 struct obd_uuid *uuids_temp;
1752
1753                 if (ret == -EOVERFLOW) {
1754                         uuids_temp = realloc(uuids, obdcount *
1755                                              sizeof(struct obd_uuid));
1756                         if (uuids_temp != NULL) {
1757                                 uuids = uuids_temp;
1758                                 goto retry_get_uuids;
1759                         }
1760                         else
1761                                 ret = -ENOMEM;
1762                 }
1763
1764                 llapi_error(LLAPI_MSG_ERROR, ret, "get ost uuid failed");
1765                 goto out_free;
1766         }
1767
1768         indexes = malloc(num_obds * sizeof(*obdindex));
1769         if (indexes == NULL) {
1770                 ret = -ENOMEM;
1771                 goto out_free;
1772         }
1773
1774         for (obdnum = 0; obdnum < num_obds; obdnum++) {
1775                 char *end = NULL;
1776
1777                 /* The user may have specified a simple index */
1778                 i = strtol(obduuids[obdnum].uuid, &end, 0);
1779                 if (end && *end == '\0' && i < obdcount) {
1780                         indexes[obdnum] = i;
1781                         obd_valid++;
1782                 } else {
1783                         for (i = 0; i < obdcount; i++) {
1784                                 if (llapi_uuid_match(uuids[i].uuid,
1785                                                      obduuids[obdnum].uuid)) {
1786                                         indexes[obdnum] = i;
1787                                         obd_valid++;
1788                                         break;
1789                                 }
1790                         }
1791                 }
1792                 if (i >= obdcount) {
1793                         indexes[obdnum] = OBD_NOT_FOUND;
1794                         llapi_err_noerrno(LLAPI_MSG_ERROR,
1795                                           "error: %s: unknown obduuid: %s",
1796                                           __func__, obduuids[obdnum].uuid);
1797                         ret = -EINVAL;
1798                 }
1799         }
1800
1801         if (obd_valid == 0)
1802                 *obdindex = OBD_NOT_FOUND;
1803         else
1804                 *obdindex = obd_valid;
1805
1806         *obdindexes = indexes;
1807 out_free:
1808         if (uuids)
1809                 free(uuids);
1810
1811         return ret;
1812 }
1813
1814 static int setup_target_indexes(DIR *dir, char *path, struct find_param *param)
1815 {
1816         int ret = 0;
1817
1818         if (param->mdtuuid) {
1819                 ret = setup_indexes(dir, path, param->mdtuuid, param->num_mdts,
1820                               &param->mdtindexes, &param->mdtindex, LMV_TYPE);
1821                 if (ret)
1822                         return ret;
1823         }
1824         if (param->obduuid) {
1825                 ret = setup_indexes(dir, path, param->obduuid, param->num_obds,
1826                               &param->obdindexes, &param->obdindex, LOV_TYPE);
1827                 if (ret)
1828                         return ret;
1829         }
1830         param->got_uuids = 1;
1831         return ret;
1832 }
1833
1834 int llapi_ostlist(char *path, struct find_param *param)
1835 {
1836         DIR *dir;
1837         int ret;
1838
1839         dir = opendir(path);
1840         if (dir == NULL)
1841                 return -errno;
1842
1843         ret = setup_obd_uuid(dir, path, param);
1844         closedir(dir);
1845
1846         return ret;
1847 }
1848
1849 /*
1850  * Given a filesystem name, or a pathname of a file on a lustre filesystem,
1851  * tries to determine the path to the filesystem's clilov directory under /proc
1852  *
1853  * fsname is limited to MTI_NAME_MAXLEN in lustre_idl.h
1854  * The NUL terminator is compensated by the additional "%s" bytes. */
1855 #define LOV_LEN (sizeof("/proc/fs/lustre/lov/%s-clilov-*") + MTI_NAME_MAXLEN)
1856 static int clilovpath(const char *fsname, const char *const pathname,
1857                       char *clilovpath)
1858 {
1859         int rc;
1860         char pattern[LOV_LEN];
1861         char buffer[PATH_MAX + 1];
1862
1863         if (fsname == NULL) {
1864                 rc = llapi_search_fsname(pathname, buffer);
1865                 if (rc != 0)
1866                         return rc;
1867                 fsname = buffer;
1868         }
1869
1870         snprintf(pattern, sizeof(pattern), "/proc/fs/lustre/lov/%s-clilov-*",
1871                  fsname);
1872
1873         rc = first_match(pattern, buffer);
1874         if (rc != 0)
1875                 return rc;
1876
1877         strncpy(clilovpath, buffer, sizeof(buffer));
1878
1879         return 0;
1880 }
1881
1882 /*
1883  * Given the path to a stripe attribute proc file, tries to open and
1884  * read the attribute and return the value using the attr parameter
1885  */
1886 static int sattr_read_attr(const char *const fpath,
1887                            unsigned int *attr)
1888 {
1889
1890         FILE *f;
1891         char line[PATH_MAX + 1];
1892         int rc = 0;
1893
1894         f = fopen(fpath, "r");
1895         if (f == NULL) {
1896                 rc = -errno;
1897                 llapi_error(LLAPI_MSG_ERROR, rc, "Cannot open '%s'", fpath);
1898                 return rc;
1899         }
1900
1901         if (fgets(line, sizeof(line), f) != NULL) {
1902                 *attr = atoi(line);
1903         } else {
1904                 llapi_error(LLAPI_MSG_ERROR, errno, "Cannot read from '%s'", fpath);
1905                 rc = 1;
1906         }
1907
1908         fclose(f);
1909         return rc;
1910 }
1911
1912 /*
1913  * Tries to determine the default stripe attributes for a given filesystem. The
1914  * filesystem to check should be specified by fsname, or will be determined
1915  * using pathname.
1916  */
1917 static int sattr_get_defaults(const char *const fsname,
1918                               const char *const pathname,
1919                               unsigned int *scount,
1920                               unsigned int *ssize,
1921                               unsigned int *soffset)
1922 {
1923         int rc;
1924         char dpath[PATH_MAX + 1];
1925         char fpath[PATH_MAX + 1];
1926
1927         rc = clilovpath(fsname, pathname, dpath);
1928         if (rc != 0)
1929                 return rc;
1930
1931         if (scount) {
1932                 snprintf(fpath, PATH_MAX, "%s/stripecount", dpath);
1933                 rc = sattr_read_attr(fpath, scount);
1934                 if (rc != 0)
1935                         return rc;
1936         }
1937
1938         if (ssize) {
1939                 snprintf(fpath, PATH_MAX, "%s/stripesize", dpath);
1940                 rc = sattr_read_attr(fpath, ssize);
1941                 if (rc != 0)
1942                         return rc;
1943         }
1944
1945         if (soffset) {
1946                 snprintf(fpath, PATH_MAX, "%s/stripeoffset", dpath);
1947                 rc = sattr_read_attr(fpath, soffset);
1948                 if (rc != 0)
1949                         return rc;
1950         }
1951
1952         return 0;
1953 }
1954
1955 /*
1956  * Tries to gather the default stripe attributes for a given filesystem. If
1957  * the attributes can be determined, they are cached for easy retreival the
1958  * next time they are needed. Only a single filesystem's attributes are
1959  * cached at a time.
1960  */
1961 static int sattr_cache_get_defaults(const char *const fsname,
1962                                     const char *const pathname,
1963                                     unsigned int *scount,
1964                                     unsigned int *ssize,
1965                                     unsigned int *soffset)
1966 {
1967         static struct {
1968                 char fsname[PATH_MAX + 1];
1969                 unsigned int stripecount;
1970                 unsigned int stripesize;
1971                 unsigned int stripeoffset;
1972         } cache = {
1973                 .fsname = {'\0'}
1974         };
1975
1976         int rc;
1977         char fsname_buf[PATH_MAX + 1];
1978         unsigned int tmp[3];
1979
1980         if (fsname == NULL) {
1981                 rc = llapi_search_fsname(pathname, fsname_buf);
1982                 if (rc)
1983                         return rc;
1984         } else {
1985                 strncpy(fsname_buf, fsname, PATH_MAX);
1986         }
1987
1988         if (strncmp(fsname_buf, cache.fsname, PATH_MAX) != 0) {
1989                 /*
1990                  * Ensure all 3 sattrs (count, size, and offset) are
1991                  * successfully retrieved and stored in tmp before writing to
1992                  * cache.
1993                  */
1994                 rc = sattr_get_defaults(fsname_buf, NULL, &tmp[0], &tmp[1],
1995                                         &tmp[2]);
1996                 if (rc != 0)
1997                         return rc;
1998
1999                 cache.stripecount = tmp[0];
2000                 cache.stripesize = tmp[1];
2001                 cache.stripeoffset = tmp[2];
2002                 strncpy(cache.fsname, fsname_buf, PATH_MAX);
2003         }
2004
2005         if (scount)
2006                 *scount = cache.stripecount;
2007         if (ssize)
2008                 *ssize = cache.stripesize;
2009         if (soffset)
2010                 *soffset = cache.stripeoffset;
2011
2012         return 0;
2013 }
2014
2015 static void lov_dump_user_lmm_header(struct lov_user_md *lum, char *path,
2016                                      struct lov_user_ost_data_v1 *objects,
2017                                      int is_dir, int verbose, int depth,
2018                                      int raw, char *pool_name)
2019 {
2020         char *prefix = is_dir ? "" : "lmm_";
2021         char nl = is_dir ? ' ' : '\n';
2022         int rc;
2023
2024         if (is_dir && ostid_seq(&lum->lmm_oi) == FID_SEQ_LOV_DEFAULT) {
2025                 ostid_set_seq_mdt0(&lum->lmm_oi);
2026                 if (verbose & VERBOSE_DETAIL)
2027                         llapi_printf(LLAPI_MSG_NORMAL, "(Default) ");
2028         }
2029
2030         if (depth && path && ((verbose != VERBOSE_OBJID) || !is_dir))
2031                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
2032
2033         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
2034                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_magic:          0x%08X\n",
2035                              lum->lmm_magic);
2036                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_seq:            "LPX64"\n",
2037                              ostid_seq(&lum->lmm_oi));
2038                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_id:      "LPX64"\n",
2039                              ostid_id(&lum->lmm_oi));
2040         }
2041
2042         if (verbose & VERBOSE_COUNT) {
2043                 if (verbose & ~VERBOSE_COUNT)
2044                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_count:   ",
2045                                      prefix);
2046                 if (is_dir) {
2047                         if (!raw && lum->lmm_stripe_count == 0) {
2048                                 unsigned int scount;
2049                                 rc = sattr_cache_get_defaults(NULL, path,
2050                                                               &scount, NULL,
2051                                                               NULL);
2052                                 if (rc == 0)
2053                                         llapi_printf(LLAPI_MSG_NORMAL, "%d%c",
2054                                                      scount, nl);
2055                                 else
2056                                         llapi_error(LLAPI_MSG_ERROR, rc,
2057                                                     "Cannot determine default"
2058                                                     " stripe count.");
2059                         } else {
2060                                 llapi_printf(LLAPI_MSG_NORMAL, "%d%c",
2061                                              lum->lmm_stripe_count ==
2062                                              (typeof(lum->lmm_stripe_count))(-1)
2063                                              ? -1 : lum->lmm_stripe_count, nl);
2064                         }
2065                 } else {
2066                         llapi_printf(LLAPI_MSG_NORMAL, "%hd%c",
2067                                      (__s16)lum->lmm_stripe_count, nl);
2068                 }
2069         }
2070
2071         if (verbose & VERBOSE_SIZE) {
2072                 if (verbose & ~VERBOSE_SIZE)
2073                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_size:    ",
2074                                      prefix);
2075                 if (is_dir && !raw && lum->lmm_stripe_size == 0) {
2076                         unsigned int ssize;
2077                         rc = sattr_cache_get_defaults(NULL, path, NULL, &ssize,
2078                                                       NULL);
2079                         if (rc == 0)
2080                                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c", ssize,
2081                                              nl);
2082                         else
2083                                 llapi_error(LLAPI_MSG_ERROR, rc,
2084                                             "Cannot determine default"
2085                                             " stripe size.");
2086                 } else {
2087                         llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
2088                                      lum->lmm_stripe_size, nl);
2089                 }
2090         }
2091
2092         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
2093                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_stripe_pattern: %x%c",
2094                              lum->lmm_pattern, nl);
2095         }
2096
2097         if ((verbose & VERBOSE_GENERATION) && !is_dir) {
2098                 if (verbose & ~VERBOSE_GENERATION)
2099                         llapi_printf(LLAPI_MSG_NORMAL, "%slayout_gen:     ",
2100                                      prefix);
2101                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
2102                                 (int)lum->lmm_layout_gen, nl);
2103         }
2104
2105         if (verbose & VERBOSE_OFFSET) {
2106                 if (verbose & ~VERBOSE_OFFSET)
2107                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_offset:  ",
2108                                      prefix);
2109                 if (is_dir)
2110                         llapi_printf(LLAPI_MSG_NORMAL, "%d%c",
2111                                      lum->lmm_stripe_offset ==
2112                                      (typeof(lum->lmm_stripe_offset))(-1) ? -1 :
2113                                      lum->lmm_stripe_offset, nl);
2114                 else
2115                         llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
2116                                      objects[0].l_ost_idx, nl);
2117         }
2118
2119         if ((verbose & VERBOSE_POOL) && (pool_name != NULL)) {
2120                 if (verbose & ~VERBOSE_POOL)
2121                         llapi_printf(LLAPI_MSG_NORMAL, "%spool:           ",
2122                                      prefix);
2123                 llapi_printf(LLAPI_MSG_NORMAL, "%s%c", pool_name, nl);
2124         }
2125
2126         if (is_dir && (verbose != VERBOSE_OBJID))
2127                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
2128 }
2129
2130 void lov_dump_user_lmm_v1v3(struct lov_user_md *lum, char *pool_name,
2131                             struct lov_user_ost_data_v1 *objects,
2132                             char *path, int is_dir, int obdindex,
2133                             int depth, int header, int raw)
2134 {
2135         int i, obdstripe = (obdindex != OBD_NOT_FOUND) ? 0 : 1;
2136
2137         if (!obdstripe) {
2138                 for (i = 0; !is_dir && i < lum->lmm_stripe_count; i++) {
2139                         if (obdindex == objects[i].l_ost_idx) {
2140                                 obdstripe = 1;
2141                                 break;
2142                         }
2143                 }
2144         }
2145
2146         if (obdstripe == 1)
2147                 lov_dump_user_lmm_header(lum, path, objects, is_dir, header,
2148                                          depth, raw, pool_name);
2149
2150         if (!is_dir && (header & VERBOSE_OBJID)) {
2151                 if (obdstripe == 1)
2152                         llapi_printf(LLAPI_MSG_NORMAL,
2153                                    "\tobdidx\t\t objid\t\t objid\t\t group\n");
2154
2155                 for (i = 0; i < lum->lmm_stripe_count; i++) {
2156                         int idx = objects[i].l_ost_idx;
2157                         long long oid = ostid_id(&objects[i].l_ost_oi);
2158                         long long gr = ostid_seq(&objects[i].l_ost_oi);
2159                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx)) {
2160                                 char fmt[48];
2161                                 sprintf(fmt, "%s%s%s\n",
2162                                         "\t%6u\t%14llu\t%#13llx\t",
2163                                         (fid_seq_is_rsvd(gr) ||
2164                                          fid_seq_is_mdt0(gr)) ?
2165                                          "%14llu" : "%#14llx", "%s");
2166                                 llapi_printf(LLAPI_MSG_NORMAL, fmt, idx, oid,
2167                                              oid, gr,
2168                                              obdindex == idx ? " *" : "");
2169                         }
2170
2171                 }
2172                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
2173         }
2174 }
2175
2176 void lmv_dump_user_lmm(struct lmv_user_md *lum, char *pool_name,
2177                        char *path, int obdindex, int depth, int verbose)
2178 {
2179         struct lmv_user_mds_data *objects = lum->lum_objects;
2180         char *prefix = lum->lum_magic == LMV_USER_MAGIC ? "(Default)" : "";
2181         int i, obdstripe = 0;
2182
2183         if (obdindex != OBD_NOT_FOUND) {
2184                 for (i = 0; i < lum->lum_stripe_count; i++) {
2185                         if (obdindex == objects[i].lum_mds) {
2186                                 llapi_printf(LLAPI_MSG_NORMAL, "%s%s\n", prefix,
2187                                              path);
2188                                 obdstripe = 1;
2189                                 break;
2190                         }
2191                 }
2192         } else {
2193                 obdstripe = 1;
2194         }
2195
2196         /* show all information default */
2197         if (!verbose) {
2198                 if (lum->lum_magic == LMV_USER_MAGIC)
2199                         verbose = VERBOSE_POOL | VERBOSE_COUNT | VERBOSE_OFFSET;
2200                 else
2201                         verbose = VERBOSE_OBJID;
2202         }
2203
2204         if (lum->lum_magic == LMV_USER_MAGIC)
2205                 verbose &= ~VERBOSE_OBJID;
2206
2207         if (depth && path && ((verbose != VERBOSE_OBJID)))
2208                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
2209
2210         if (verbose & VERBOSE_COUNT) {
2211                 if (verbose & ~VERBOSE_COUNT)
2212                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_stripe_count: ");
2213                 llapi_printf(LLAPI_MSG_NORMAL, "%u\n",
2214                              (int)lum->lum_stripe_count);
2215         }
2216
2217         if (verbose & VERBOSE_OFFSET) {
2218                 if (verbose & ~VERBOSE_OFFSET)
2219                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_stripe_offset: ");
2220                 llapi_printf(LLAPI_MSG_NORMAL, "%d\n",
2221                              (int)lum->lum_stripe_offset);
2222         }
2223
2224         if (verbose & VERBOSE_OBJID) {
2225                 if ((obdstripe == 1))
2226                         llapi_printf(LLAPI_MSG_NORMAL,
2227                                      "\tmdtidx\t\t FID[seq:oid:ver]\n");
2228                 for (i = 0; i < lum->lum_stripe_count; i++) {
2229                         int idx = objects[i].lum_mds;
2230                         struct lu_fid *fid = &objects[i].lum_fid;
2231                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
2232                                 llapi_printf(LLAPI_MSG_NORMAL,
2233                                              "\t%6u\t\t "DFID"\t\t%s\n",
2234                                             idx, PFID(fid),
2235                                             obdindex == idx ? " *" : "");
2236                 }
2237
2238         }
2239
2240         if ((verbose & VERBOSE_POOL) && (pool_name[0] != '\0')) {
2241                 if (verbose & ~VERBOSE_POOL)
2242                         llapi_printf(LLAPI_MSG_NORMAL, "%slmv_pool:           ",
2243                                      prefix);
2244                 llapi_printf(LLAPI_MSG_NORMAL, "%s%c ", pool_name, ' ');
2245         }
2246         llapi_printf(LLAPI_MSG_NORMAL, "\n");
2247 }
2248
2249 void llapi_lov_dump_user_lmm(struct find_param *param, char *path, int is_dir)
2250 {
2251         __u32 magic;
2252
2253         if (param->get_lmv)
2254                 magic = (__u32)param->fp_lmv_md->lum_magic;
2255         else
2256                 magic = *(__u32 *)&param->lmd->lmd_lmm; /* lum->lmm_magic */
2257
2258         switch (magic) {
2259         case LOV_USER_MAGIC_V1:
2260                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, NULL,
2261                                        param->lmd->lmd_lmm.lmm_objects,
2262                                        path, is_dir,
2263                                        param->obdindex, param->maxdepth,
2264                                        param->verbose, param->raw);
2265                 break;
2266         case LOV_USER_MAGIC_V3: {
2267                 char pool_name[LOV_MAXPOOLNAME + 1];
2268                 struct lov_user_ost_data_v1 *objects;
2269                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
2270
2271                 strncpy(pool_name, lmmv3->lmm_pool_name, LOV_MAXPOOLNAME);
2272                 pool_name[LOV_MAXPOOLNAME] = '\0';
2273                 objects = lmmv3->lmm_objects;
2274                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, pool_name,
2275                                        objects, path, is_dir,
2276                                        param->obdindex, param->maxdepth,
2277                                        param->verbose, param->raw);
2278                 break;
2279         }
2280         case LMV_MAGIC_V1:
2281         case LMV_USER_MAGIC: {
2282                 char pool_name[LOV_MAXPOOLNAME + 1];
2283                 struct lmv_user_md *lum;
2284
2285                 lum = (struct lmv_user_md *)param->fp_lmv_md;
2286                 strncpy(pool_name, lum->lum_pool_name, LOV_MAXPOOLNAME);
2287                 lmv_dump_user_lmm(lum, pool_name, path,
2288                                   param->obdindex, param->maxdepth,
2289                                   param->verbose);
2290                 break;
2291         }
2292         default:
2293                 llapi_printf(LLAPI_MSG_NORMAL, "unknown lmm_magic:  %#x "
2294                              "(expecting one of %#x %#x %#x %#x)\n",
2295                              *(__u32 *)&param->lmd->lmd_lmm,
2296                              LOV_USER_MAGIC_V1, LOV_USER_MAGIC_V3,
2297                              LMV_USER_MAGIC, LMV_MAGIC_V1);
2298                 return;
2299         }
2300 }
2301
2302 int llapi_file_get_stripe(const char *path, struct lov_user_md *lum)
2303 {
2304         const char *fname;
2305         char *dname;
2306         int fd, rc = 0;
2307
2308         fname = strrchr(path, '/');
2309
2310         /* It should be a file (or other non-directory) */
2311         if (fname == NULL) {
2312                 dname = (char *)malloc(2);
2313                 if (dname == NULL)
2314                         return -ENOMEM;
2315                 strcpy(dname, ".");
2316                 fname = (char *)path;
2317         } else {
2318                 dname = (char *)malloc(fname - path + 1);
2319                 if (dname == NULL)
2320                         return -ENOMEM;
2321                 strncpy(dname, path, fname - path);
2322                 dname[fname - path] = '\0';
2323                 fname++;
2324         }
2325
2326         fd = open(dname, O_RDONLY);
2327         if (fd == -1) {
2328                 rc = -errno;
2329                 free(dname);
2330                 return rc;
2331         }
2332
2333         strcpy((char *)lum, fname);
2334         if (ioctl(fd, IOC_MDC_GETFILESTRIPE, (void *)lum) == -1)
2335                 rc = -errno;
2336
2337         if (close(fd) == -1 && rc == 0)
2338                 rc = -errno;
2339
2340         free(dname);
2341         return rc;
2342 }
2343
2344 int llapi_file_lookup(int dirfd, const char *name)
2345 {
2346         struct obd_ioctl_data data = { 0 };
2347         char rawbuf[8192];
2348         char *buf = rawbuf;
2349         int rc;
2350
2351         if (dirfd < 0 || name == NULL)
2352                 return -EINVAL;
2353
2354         data.ioc_version = OBD_IOCTL_VERSION;
2355         data.ioc_len = sizeof(data);
2356         data.ioc_inlbuf1 = (char *)name;
2357         data.ioc_inllen1 = strlen(name) + 1;
2358
2359         rc = obd_ioctl_pack(&data, &buf, sizeof(rawbuf));
2360         if (rc) {
2361                 llapi_error(LLAPI_MSG_ERROR, rc,
2362                             "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
2363                             name, rc);
2364                 return rc;
2365         }
2366
2367         rc = ioctl(dirfd, IOC_MDC_LOOKUP, buf);
2368         if (rc < 0)
2369                 rc = -errno;
2370         return rc;
2371 }
2372
2373 /* Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
2374  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
2375  *
2376  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
2377  * The table below gives the answers for the specified parameters (value and
2378  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
2379  * --------------------------------------
2380  * 1 | file > limit; sign > 0 | -1 / -1 |
2381  * 2 | file = limit; sign > 0 | -1 / -1 |
2382  * 3 | file < limit; sign > 0 |  ? /  1 |
2383  * 4 | file > limit; sign = 0 | -1 / -1 |
2384  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
2385  * 6 | file < limit; sign = 0 |  ? / -1 |
2386  * 7 | file > limit; sign < 0 |  1 /  1 |
2387  * 8 | file = limit; sign < 0 |  ? / -1 |
2388  * 9 | file < limit; sign < 0 |  ? / -1 |
2389  * --------------------------------------
2390  * Note: 5th actually means that the value is within the interval
2391  * (limit - margin, limit]. */
2392 static int find_value_cmp(unsigned long long file, unsigned long long limit,
2393                           int sign, int negopt, unsigned long long margin,
2394                           int mds)
2395 {
2396         int ret = -1;
2397
2398         if (sign > 0) {
2399                 /* Drop the fraction of margin (of days). */
2400                 if (file + margin <= limit)
2401                         ret = mds ? 0 : 1;
2402         } else if (sign == 0) {
2403                 if (file <= limit && file + margin > limit)
2404                         ret = mds ? 0 : 1;
2405                 else if (file + margin <= limit)
2406                         ret = mds ? 0 : -1;
2407         } else if (sign < 0) {
2408                 if (file > limit)
2409                         ret = 1;
2410                 else if (mds)
2411                         ret = 0;
2412         }
2413
2414         return negopt ? ~ret + 1 : ret;
2415 }
2416
2417 /* Check if the file time matches all the given criteria (e.g. --atime +/-N).
2418  * Return -1 or 1 if file timestamp does not or does match the given criteria
2419  * correspondingly. Return 0 if the MDS time is being checked and there are
2420  * attributes on OSTs and it is not yet clear if the timespamp matches.
2421  *
2422  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
2423  * updated timestamps. */
2424 static int find_time_check(lstat_t *st, struct find_param *param, int mds)
2425 {
2426         int ret;
2427         int rc = 1;
2428
2429         /* Check if file is accepted. */
2430         if (param->atime) {
2431                 ret = find_value_cmp(st->st_atime, param->atime,
2432                                      param->asign, param->exclude_atime,
2433                                      24 * 60 * 60, mds);
2434                 if (ret < 0)
2435                         return ret;
2436                 rc = ret;
2437         }
2438
2439         if (param->mtime) {
2440                 ret = find_value_cmp(st->st_mtime, param->mtime,
2441                                      param->msign, param->exclude_mtime,
2442                                      24 * 60 * 60, mds);
2443                 if (ret < 0)
2444                         return ret;
2445
2446                 /* If the previous check matches, but this one is not yet clear,
2447                  * we should return 0 to do an RPC on OSTs. */
2448                 if (rc == 1)
2449                         rc = ret;
2450         }
2451
2452         if (param->ctime) {
2453                 ret = find_value_cmp(st->st_ctime, param->ctime,
2454                                      param->csign, param->exclude_ctime,
2455                                      24 * 60 * 60, mds);
2456                 if (ret < 0)
2457                         return ret;
2458
2459                 /* If the previous check matches, but this one is not yet clear,
2460                  * we should return 0 to do an RPC on OSTs. */
2461                 if (rc == 1)
2462                         rc = ret;
2463         }
2464
2465         return rc;
2466 }
2467
2468 /**
2469  * Check whether the stripes matches the indexes user provided
2470  *       1   : matched
2471  *       0   : Unmatched
2472  */
2473 static int check_obd_match(struct find_param *param)
2474 {
2475         lstat_t *st = &param->lmd->lmd_st;
2476         struct lov_user_ost_data_v1 *lmm_objects;
2477         int i, j;
2478
2479         if (param->obduuid && param->obdindex == OBD_NOT_FOUND)
2480                 return 0;
2481
2482         if (!S_ISREG(st->st_mode))
2483                 return 0;
2484
2485         /* Only those files should be accepted, which have a
2486          * stripe on the specified OST. */
2487         if (!param->lmd->lmd_lmm.lmm_stripe_count)
2488                 return 0;
2489
2490         if (param->lmd->lmd_lmm.lmm_magic ==
2491             LOV_USER_MAGIC_V3) {
2492                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
2493
2494                 lmm_objects = lmmv3->lmm_objects;
2495         } else if (param->lmd->lmd_lmm.lmm_magic ==  LOV_USER_MAGIC_V1) {
2496                 lmm_objects = param->lmd->lmd_lmm.lmm_objects;
2497         } else {
2498                 llapi_err_noerrno(LLAPI_MSG_ERROR, "%s:Unknown magic: 0x%08X\n",
2499                                   __func__, param->lmd->lmd_lmm.lmm_magic);
2500                 return -EINVAL;
2501         }
2502
2503         for (i = 0; i < param->lmd->lmd_lmm.lmm_stripe_count; i++) {
2504                 for (j = 0; j < param->num_obds; j++) {
2505                         if (param->obdindexes[j] ==
2506                             lmm_objects[i].l_ost_idx) {
2507                                 if (param->exclude_obd)
2508                                         return 0;
2509                                 return 1;
2510                         }
2511                 }
2512         }
2513
2514         if (param->exclude_obd)
2515                 return 1;
2516         return 0;
2517 }
2518
2519 static int check_mdt_match(struct find_param *param)
2520 {
2521         int i;
2522
2523         if (param->mdtuuid && param->mdtindex == OBD_NOT_FOUND)
2524                 return 0;
2525
2526         /* FIXME: For striped dir, we should get stripe information and check */
2527         for (i = 0; i < param->num_mdts; i++) {
2528                 if (param->mdtindexes[i] == param->file_mdtindex)
2529                         if (param->exclude_mdt)
2530                                 return 0;
2531                         return 1;
2532         }
2533
2534         if (param->exclude_mdt)
2535                 return 1;
2536         return 0;
2537 }
2538
2539 /**
2540  * Check whether the obd is active or not, if it is
2541  * not active, just print the object affected by this
2542  * failed target
2543  **/
2544 static int print_failed_tgt(struct find_param *param, char *path, int type)
2545 {
2546         struct obd_statfs stat_buf;
2547         struct obd_uuid uuid_buf;
2548         int ret;
2549
2550         LASSERT(type == LL_STATFS_LOV || type == LL_STATFS_LMV);
2551
2552         memset(&stat_buf, 0, sizeof(struct obd_statfs));
2553         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
2554         ret = llapi_obd_statfs(path, type,
2555                                param->obdindex, &stat_buf,
2556                                &uuid_buf);
2557         if (ret) {
2558                 llapi_printf(LLAPI_MSG_NORMAL,
2559                              "obd_uuid: %s failed %s ",
2560                              param->obduuid->uuid,
2561                              strerror(errno));
2562         }
2563         return ret;
2564 }
2565
2566 static int cb_find_init(char *path, DIR *parent, DIR *dir,
2567                         void *data, struct dirent64 *de)
2568 {
2569         struct find_param *param = (struct find_param *)data;
2570         int decision = 1; /* 1 is accepted; -1 is rejected. */
2571         lstat_t *st = &param->lmd->lmd_st;
2572         int lustre_fs = 1;
2573         int checked_type = 0;
2574         int ret = 0;
2575
2576         LASSERT(parent != NULL || dir != NULL);
2577
2578         if (param->have_fileinfo == 0)
2579                 param->lmd->lmd_lmm.lmm_stripe_count = 0;
2580
2581         /* If a regular expression is presented, make the initial decision */
2582         if (param->pattern != NULL) {
2583                 char *fname = strrchr(path, '/');
2584                 fname = (fname == NULL ? path : fname + 1);
2585                 ret = fnmatch(param->pattern, fname, 0);
2586                 if ((ret == FNM_NOMATCH && !param->exclude_pattern) ||
2587                     (ret == 0 && param->exclude_pattern))
2588                         goto decided;
2589         }
2590
2591         /* See if we can check the file type from the dirent. */
2592         if (param->type && de != NULL && de->d_type != DT_UNKNOWN &&
2593             de->d_type < DT_MAX) {
2594                 checked_type = 1;
2595                 if (llapi_dir_filetype_table[de->d_type] == param->type) {
2596                         if (param->exclude_type)
2597                                 goto decided;
2598                 } else {
2599                         if (!param->exclude_type)
2600                                 goto decided;
2601                 }
2602         }
2603
2604         ret = 0;
2605
2606         /* Request MDS for the stat info if some of these parameters need
2607          * to be compared. */
2608         if (param->obduuid    || param->mdtuuid || param->check_uid ||
2609             param->check_gid || param->check_pool || param->atime   ||
2610             param->ctime     || param->mtime || param->check_size ||
2611             param->check_stripecount || param->check_stripesize)
2612                 decision = 0;
2613
2614         if (param->type && checked_type == 0)
2615                 decision = 0;
2616
2617         if (param->have_fileinfo == 0 && decision == 0) {
2618                 ret = get_lmd_info(path, parent, dir, param->lmd,
2619                                    param->lumlen);
2620                 if (ret == 0) {
2621                         if (dir) {
2622                                 ret = llapi_file_fget_mdtidx(dirfd(dir),
2623                                                      &param->file_mdtindex);
2624                         } else {
2625                                 int fd;
2626                                 lstat_t tmp_st;
2627
2628                                 ret = lstat_f(path, &tmp_st);
2629                                 if (ret) {
2630                                         ret = -errno;
2631                                         llapi_error(LLAPI_MSG_ERROR, ret,
2632                                                     "error: %s: lstat failed"
2633                                                     "for %s", __func__, path);
2634                                         return ret;
2635                                 }
2636                                 if (S_ISREG(tmp_st.st_mode)) {
2637                                         fd = open(path, O_RDONLY);
2638                                         if (fd > 0) {
2639                                                 ret = llapi_file_fget_mdtidx(fd,
2640                                                          &param->file_mdtindex);
2641                                                 close(fd);
2642                                         } else {
2643                                                 ret = fd;
2644                                         }
2645                                 } else {
2646                                         /* For special inode, it assumes to
2647                                          * reside on the same MDT with the
2648                                          * parent */
2649                                         fd = dirfd(parent);
2650                                         ret = llapi_file_fget_mdtidx(fd,
2651                                                         &param->file_mdtindex);
2652                                 }
2653                         }
2654                 }
2655                 if (ret) {
2656                         if (ret == -ENOTTY)
2657                                 lustre_fs = 0;
2658                         if (ret == -ENOENT)
2659                                 goto decided;
2660                         return ret;
2661                 }
2662         }
2663
2664         if (param->type && !checked_type) {
2665                 if ((st->st_mode & S_IFMT) == param->type) {
2666                         if (param->exclude_type)
2667                                 goto decided;
2668                 } else {
2669                         if (!param->exclude_type)
2670                                 goto decided;
2671                 }
2672         }
2673
2674         /* Prepare odb. */
2675         if (param->obduuid || param->mdtuuid) {
2676                 if (lustre_fs && param->got_uuids &&
2677                     param->st_dev != st->st_dev) {
2678                         /* A lustre/lustre mount point is crossed. */
2679                         param->got_uuids = 0;
2680                         param->obds_printed = 0;
2681                         param->obdindex = param->mdtindex = OBD_NOT_FOUND;
2682                 }
2683
2684                 if (lustre_fs && !param->got_uuids) {
2685                         ret = setup_target_indexes(dir ? dir : parent, path,
2686                                                    param);
2687                         if (ret)
2688                                 return ret;
2689
2690                         param->st_dev = st->st_dev;
2691                 } else if (!lustre_fs && param->got_uuids) {
2692                         /* A lustre/non-lustre mount point is crossed. */
2693                         param->got_uuids = 0;
2694                         param->obdindex = param->mdtindex = OBD_NOT_FOUND;
2695                 }
2696         }
2697
2698         if (param->check_stripesize) {
2699                 decision = find_value_cmp(param->lmd->lmd_lmm.lmm_stripe_size,
2700                                           param->stripesize,
2701                                           param->stripesize_sign,
2702                                           param->exclude_stripesize,
2703                                           param->stripesize_units, 0);
2704                 if (decision == -1)
2705                         goto decided;
2706         }
2707
2708         if (param->check_stripecount) {
2709                 decision = find_value_cmp(param->lmd->lmd_lmm.lmm_stripe_count,
2710                                           param->stripecount,
2711                                           param->stripecount_sign,
2712                                           param->exclude_stripecount, 1, 0);
2713                 if (decision == -1)
2714                         goto decided;
2715         }
2716
2717         /* If an OBD UUID is specified but none matches, skip this file. */
2718         if ((param->obduuid && param->obdindex == OBD_NOT_FOUND) ||
2719             (param->mdtuuid && param->mdtindex == OBD_NOT_FOUND))
2720                 goto decided;
2721
2722         /* If a OST or MDT UUID is given, and some OST matches,
2723          * check it here. */
2724         if (param->obdindex != OBD_NOT_FOUND ||
2725             param->mdtindex != OBD_NOT_FOUND) {
2726                 if (param->obduuid) {
2727                         if (check_obd_match(param)) {
2728                                 /* If no mdtuuid is given, we are done.
2729                                  * Otherwise, fall through to the mdtuuid
2730                                  * check below. */
2731                                 if (!param->mdtuuid)
2732                                         goto obd_matches;
2733                         } else {
2734                                 goto decided;
2735                         }
2736                 }
2737                 if (param->mdtuuid) {
2738                         if (check_mdt_match(param))
2739                                 goto obd_matches;
2740                         goto decided;
2741                 }
2742         }
2743 obd_matches:
2744         if (param->check_uid) {
2745                 if (st->st_uid == param->uid) {
2746                         if (param->exclude_uid)
2747                                 goto decided;
2748                 } else {
2749                         if (!param->exclude_uid)
2750                                 goto decided;
2751                 }
2752         }
2753
2754         if (param->check_gid) {
2755                 if (st->st_gid == param->gid) {
2756                         if (param->exclude_gid)
2757                                 goto decided;
2758                 } else {
2759                         if (!param->exclude_gid)
2760                                 goto decided;
2761                 }
2762         }
2763
2764         if (param->check_pool) {
2765                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
2766
2767                 /* empty requested pool is taken as no pool search => V1 */
2768                 if (((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V1) &&
2769                      (param->poolname[0] == '\0')) ||
2770                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
2771                      (strncmp(lmmv3->lmm_pool_name,
2772                               param->poolname, LOV_MAXPOOLNAME) == 0)) ||
2773                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
2774                      (strcmp(param->poolname, "*") == 0))) {
2775                         if (param->exclude_pool)
2776                                 goto decided;
2777                 } else {
2778                         if (!param->exclude_pool)
2779                                 goto decided;
2780                 }
2781         }
2782
2783         /* Check the time on mds. */
2784         decision = 1;
2785         if (param->atime || param->ctime || param->mtime) {
2786                 int for_mds;
2787
2788                 for_mds = lustre_fs ? (S_ISREG(st->st_mode) &&
2789                                        param->lmd->lmd_lmm.lmm_stripe_count)
2790                                     : 0;
2791                 decision = find_time_check(st, param, for_mds);
2792                 if (decision == -1)
2793                         goto decided;
2794         }
2795
2796         /* If file still fits the request, ask ost for updated info.
2797            The regular stat is almost of the same speed as some new
2798            'glimpse-size-ioctl'. */
2799
2800         if (param->check_size && S_ISREG(st->st_mode) &&
2801             param->lmd->lmd_lmm.lmm_stripe_count)
2802                 decision = 0;
2803
2804         while (!decision) {
2805                 /* For regular files with the stripe the decision may have not
2806                  * been taken yet if *time or size is to be checked. */
2807                 LASSERT((S_ISREG(st->st_mode) &&
2808                         param->lmd->lmd_lmm.lmm_stripe_count) ||
2809                         param->mdtindex != OBD_NOT_FOUND);
2810
2811                 if (param->obdindex != OBD_NOT_FOUND)
2812                         print_failed_tgt(param, path, LL_STATFS_LOV);
2813
2814                 if (param->mdtindex != OBD_NOT_FOUND)
2815                         print_failed_tgt(param, path, LL_STATFS_LMV);
2816
2817                 if (dir) {
2818                         ret = ioctl(dirfd(dir), IOC_LOV_GETINFO,
2819                                     (void *)param->lmd);
2820                 } else if (parent) {
2821                         ret = ioctl(dirfd(parent), IOC_LOV_GETINFO,
2822                                     (void *)param->lmd);
2823                 }
2824
2825                 if (ret) {
2826                         if (errno == ENOENT) {
2827                                 llapi_error(LLAPI_MSG_ERROR, -ENOENT,
2828                                             "warning: %s: %s does not exist",
2829                                             __func__, path);
2830                                 goto decided;
2831                         } else {
2832                                 ret = -errno;
2833                                 llapi_error(LLAPI_MSG_ERROR, ret,
2834                                             "%s: IOC_LOV_GETINFO on %s failed",
2835                                             __func__, path);
2836                                 return ret;
2837                         }
2838                 }
2839
2840                 /* Check the time on osc. */
2841                 decision = find_time_check(st, param, 0);
2842                 if (decision == -1)
2843                         goto decided;
2844
2845                 break;
2846         }
2847
2848         if (param->check_size)
2849                 decision = find_value_cmp(st->st_size, param->size,
2850                                           param->size_sign, param->exclude_size,
2851                                           param->size_units, 0);
2852
2853         if (decision != -1) {
2854                 llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
2855                 if (param->zeroend)
2856                         llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
2857                 else
2858                         llapi_printf(LLAPI_MSG_NORMAL, "\n");
2859         }
2860
2861 decided:
2862         /* Do not get down anymore? */
2863         if (param->depth == param->maxdepth)
2864                 return 1;
2865
2866         param->depth++;
2867         return 0;
2868 }
2869
2870 int llapi_find(char *path, struct find_param *param)
2871 {
2872         return param_callback(path, cb_find_init, cb_common_fini, param);
2873 }
2874
2875 /*
2876  * Get MDT number that the file/directory inode referenced
2877  * by the open fd resides on.
2878  * Return 0 and mdtidx on success, or -ve errno.
2879  */
2880 int llapi_file_fget_mdtidx(int fd, int *mdtidx)
2881 {
2882         if (ioctl(fd, LL_IOC_GET_MDTIDX, mdtidx) < 0)
2883                 return -errno;
2884         return 0;
2885 }
2886
2887 static int cb_get_mdt_index(char *path, DIR *parent, DIR *d, void *data,
2888                             struct dirent64 *de)
2889 {
2890         struct find_param *param = (struct find_param *)data;
2891         int ret = 0;
2892         int mdtidx;
2893
2894         LASSERT(parent != NULL || d != NULL);
2895
2896         if (d) {
2897                 ret = llapi_file_fget_mdtidx(dirfd(d), &mdtidx);
2898         } else if (parent) {
2899                 int fd;
2900
2901                 fd = open(path, O_RDONLY);
2902                 if (fd > 0) {
2903                         ret = llapi_file_fget_mdtidx(fd, &mdtidx);
2904                         close(fd);
2905                 } else {
2906                         ret = -errno;
2907                 }
2908         }
2909
2910         if (ret) {
2911                 if (ret == -ENODATA) {
2912                         if (!param->obduuid)
2913                                 llapi_printf(LLAPI_MSG_NORMAL,
2914                                              "%s has no stripe info\n", path);
2915                         goto out;
2916                 } else if (ret == -ENOENT) {
2917                         llapi_error(LLAPI_MSG_WARN, ret,
2918                                     "warning: %s: %s does not exist",
2919                                     __func__, path);
2920                         goto out;
2921                 } else if (ret == -ENOTTY) {
2922                         llapi_error(LLAPI_MSG_ERROR, ret,
2923                                     "%s: '%s' not on a Lustre fs?",
2924                                     __func__, path);
2925                 } else {
2926                         llapi_error(LLAPI_MSG_ERROR, ret,
2927                                     "error: %s: LL_IOC_GET_MDTIDX failed for %s",
2928                                     __func__, path);
2929                 }
2930                 return ret;
2931         }
2932
2933         /* The 'LASSERT(parent != NULL || d != NULL);' guarantees
2934          * that either 'd' or 'parent' is not null.
2935          * So in all cases llapi_file_fget_mdtidx() is called,
2936          * thus initializing 'mdtidx'. */
2937         if (param->quiet || !(param->verbose & VERBOSE_DETAIL))
2938                 /* coverity[uninit_use_in_call] */
2939                 llapi_printf(LLAPI_MSG_NORMAL, "%d\n", mdtidx);
2940         else
2941                 /* coverity[uninit_use_in_call] */
2942                 llapi_printf(LLAPI_MSG_NORMAL, "%s\nmdt_index:\t%d\n",
2943                              path, mdtidx);
2944
2945 out:
2946         /* Do not get down anymore? */
2947         if (param->depth == param->maxdepth)
2948                 return 1;
2949
2950         param->depth++;
2951         return 0;
2952 }
2953
2954 static int cb_getstripe(char *path, DIR *parent, DIR *d, void *data,
2955                         struct dirent64 *de)
2956 {
2957         struct find_param *param = (struct find_param *)data;
2958         int ret = 0;
2959
2960         LASSERT(parent != NULL || d != NULL);
2961
2962         if (param->obduuid) {
2963                 param->quiet = 1;
2964                 ret = setup_obd_uuid(d ? d : parent, path, param);
2965                 if (ret)
2966                         return ret;
2967         }
2968
2969         if (d) {
2970                 if (param->get_lmv) {
2971                         ret = cb_get_dirstripe(path, d, param);
2972                 } else {
2973                         ret = ioctl(dirfd(d), LL_IOC_LOV_GETSTRIPE,
2974                                      (void *)&param->lmd->lmd_lmm);
2975                 }
2976
2977         } else if (parent) {
2978                 char *fname = strrchr(path, '/');
2979                 fname = (fname == NULL ? path : fname + 1);
2980
2981                 if (param->get_lmv) {
2982                         llapi_printf(LLAPI_MSG_NORMAL,
2983                                      "%s get dirstripe information for file\n",
2984                                      path);
2985                         goto out;
2986                 }
2987
2988                 strncpy((char *)&param->lmd->lmd_lmm, fname, param->lumlen);
2989
2990                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILESTRIPE,
2991                             (void *)&param->lmd->lmd_lmm);
2992         }
2993
2994         if (ret) {
2995                 if (errno == ENODATA && d != NULL) {
2996                         /* We need to "fake" the "use the default" values
2997                          * since the lmm struct is zeroed out at this point.
2998                          * The magic needs to be set in order to satisfy
2999                          * a check later on in the code path.
3000                          * The object_seq needs to be set for the "(Default)"
3001                          * prefix to be displayed. */
3002                         struct lov_user_md *lmm = &param->lmd->lmd_lmm;
3003                         lmm->lmm_magic = LOV_MAGIC_V1;
3004                         if (!param->raw)
3005                                 ostid_set_seq(&lmm->lmm_oi,
3006                                               FID_SEQ_LOV_DEFAULT);
3007                         lmm->lmm_stripe_count = 0;
3008                         lmm->lmm_stripe_size = 0;
3009                         lmm->lmm_stripe_offset = -1;
3010                         goto dump;
3011                 } else if (errno == ENODATA && parent != NULL) {
3012                         if (!param->obduuid && !param->mdtuuid)
3013                                 llapi_printf(LLAPI_MSG_NORMAL,
3014                                              "%s has no stripe info\n", path);
3015                         goto out;
3016                 } else if (errno == ENOENT) {
3017                         llapi_error(LLAPI_MSG_WARN, -ENOENT,
3018                                     "warning: %s: %s does not exist",
3019                                     __func__, path);
3020                         goto out;
3021                 } else if (errno == ENOTTY) {
3022                         ret = -errno;
3023                         llapi_error(LLAPI_MSG_ERROR, ret,
3024                                     "%s: '%s' not on a Lustre fs?",
3025                                     __func__, path);
3026                 } else {
3027                         ret = -errno;
3028                         llapi_error(LLAPI_MSG_ERROR, ret,
3029                                     "error: %s: %s failed for %s",
3030                                      __func__, d ? "LL_IOC_LOV_GETSTRIPE" :
3031                                     "IOC_MDC_GETFILESTRIPE", path);
3032                 }
3033
3034                 return ret;
3035         }
3036
3037 dump:
3038         if (!(param->verbose & VERBOSE_MDTINDEX))
3039                 llapi_lov_dump_user_lmm(param, path, d ? 1 : 0);
3040
3041 out:
3042         /* Do not get down anymore? */
3043         if (param->depth == param->maxdepth)
3044                 return 1;
3045
3046         param->depth++;
3047         return 0;
3048 }
3049
3050 int llapi_getstripe(char *path, struct find_param *param)
3051 {
3052         return param_callback(path, (param->verbose & VERBOSE_MDTINDEX) ?
3053                               cb_get_mdt_index : cb_getstripe,
3054                               cb_common_fini, param);
3055 }
3056
3057 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
3058                      struct obd_statfs *stat_buf,
3059                      struct obd_uuid *uuid_buf)
3060 {
3061         int fd;
3062         char raw[OBD_MAX_IOCTL_BUFFER] = {'\0'};
3063         char *rawbuf = raw;
3064         struct obd_ioctl_data data = { 0 };
3065         int rc = 0;
3066
3067         data.ioc_inlbuf1 = (char *)&type;
3068         data.ioc_inllen1 = sizeof(__u32);
3069         data.ioc_inlbuf2 = (char *)&index;
3070         data.ioc_inllen2 = sizeof(__u32);
3071         data.ioc_pbuf1 = (char *)stat_buf;
3072         data.ioc_plen1 = sizeof(struct obd_statfs);
3073         data.ioc_pbuf2 = (char *)uuid_buf;
3074         data.ioc_plen2 = sizeof(struct obd_uuid);
3075
3076         rc = obd_ioctl_pack(&data, &rawbuf, sizeof(raw));
3077         if (rc != 0) {
3078                 llapi_error(LLAPI_MSG_ERROR, rc,
3079                             "llapi_obd_statfs: error packing ioctl data");
3080                 return rc;
3081         }
3082
3083         fd = open(path, O_RDONLY);
3084         if (errno == EISDIR)
3085                 fd = open(path, O_DIRECTORY | O_RDONLY);
3086
3087         if (fd < 0) {
3088                 rc = errno ? -errno : -EBADF;
3089                 llapi_error(LLAPI_MSG_ERROR, rc, "error: %s: opening '%s'",
3090                             __func__, path);
3091                 return rc;
3092         }
3093         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
3094         if (rc)
3095                 rc = errno ? -errno : -EINVAL;
3096
3097         close(fd);
3098         return rc;
3099 }
3100
3101 #define MAX_STRING_SIZE 128
3102
3103 int llapi_ping(char *obd_type, char *obd_name)
3104 {
3105         char path[MAX_STRING_SIZE];
3106         char buf[1];
3107         int rc, fd;
3108
3109         snprintf(path, MAX_STRING_SIZE, "/proc/fs/lustre/%s/%s/ping",
3110                  obd_type, obd_name);
3111
3112         fd = open(path, O_WRONLY);
3113         if (fd < 0) {
3114                 rc = -errno;
3115                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s", path);
3116                 return rc;
3117         }
3118
3119         /* The purpose is to send a byte as a ping, whatever this byte is. */
3120         /* coverity[uninit_use_in_call] */
3121         rc = write(fd, buf, 1);
3122         if (rc < 0)
3123                 rc = -errno;
3124         close(fd);
3125
3126         if (rc == 1)
3127                 return 0;
3128         return rc;
3129 }
3130
3131 int llapi_target_iterate(int type_num, char **obd_type,
3132                          void *args, llapi_cb_t cb)
3133 {
3134         char buf[MAX_STRING_SIZE];
3135         FILE *fp = fopen(DEVICES_LIST, "r");
3136         int i, rc = 0;
3137
3138         if (fp == NULL) {
3139                 rc = -errno;
3140                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening "DEVICES_LIST);
3141                 return rc;
3142         }
3143
3144         while (fgets(buf, sizeof(buf), fp) != NULL) {
3145                 char *obd_type_name = NULL;
3146                 char *obd_name = NULL;
3147                 char *obd_uuid = NULL;
3148                 char *bufp = buf;
3149                 struct obd_statfs osfs_buffer;
3150
3151                 while(bufp[0] == ' ')
3152                         ++bufp;
3153
3154                 for(i = 0; i < 3; i++) {
3155                         obd_type_name = strsep(&bufp, " ");
3156                 }
3157                 obd_name = strsep(&bufp, " ");
3158                 obd_uuid = strsep(&bufp, " ");
3159
3160                 memset(&osfs_buffer, 0, sizeof (osfs_buffer));
3161
3162                 for (i = 0; i < type_num; i++) {
3163                         if (strcmp(obd_type_name, obd_type[i]) != 0)
3164                                 continue;
3165
3166                         cb(obd_type_name, obd_name, obd_uuid, args);
3167                 }
3168         }
3169         fclose(fp);
3170         return 0;
3171 }
3172
3173 static void do_target_check(char *obd_type_name, char *obd_name,
3174                             char *obd_uuid, void *args)
3175 {
3176         int rc;
3177
3178         rc = llapi_ping(obd_type_name, obd_name);
3179         if (rc == ENOTCONN) {
3180                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
3181         } else if (rc) {
3182                 llapi_error(LLAPI_MSG_ERROR, rc, "error: check '%s'", obd_name);
3183         } else {
3184                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
3185         }
3186 }
3187
3188 int llapi_target_check(int type_num, char **obd_type, char *dir)
3189 {
3190         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
3191 }
3192
3193 #undef MAX_STRING_SIZE
3194
3195 /* Is this a lustre fs? */
3196 int llapi_is_lustre_mnttype(const char *type)
3197 {
3198         return (strcmp(type, "lustre") == 0 || strcmp(type,"lustre_lite") == 0);
3199 }
3200
3201 /* Is this a lustre client fs? */
3202 int llapi_is_lustre_mnt(struct mntent *mnt)
3203 {
3204         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
3205                 strstr(mnt->mnt_fsname, ":/") != NULL);
3206 }
3207
3208 int llapi_quotacheck(char *mnt, int check_type)
3209 {
3210         DIR *root;
3211         int rc;
3212
3213         root = opendir(mnt);
3214         if (!root) {
3215                 rc = -errno;
3216                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
3217                 return rc;
3218         }
3219
3220         rc = ioctl(dirfd(root), LL_IOC_QUOTACHECK, check_type);
3221         if (rc < 0)
3222                 rc = -errno;
3223
3224         closedir(root);
3225         return rc;
3226 }
3227
3228 int llapi_poll_quotacheck(char *mnt, struct if_quotacheck *qchk)
3229 {
3230         DIR *root;
3231         int poll_intvl = 2;
3232         int rc;
3233
3234         root = opendir(mnt);
3235         if (!root) {
3236                 rc = -errno;
3237                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
3238                 return rc;
3239         }
3240
3241         while (1) {
3242                 rc = ioctl(dirfd(root), LL_IOC_POLL_QUOTACHECK, qchk);
3243                 if (!rc)
3244                         break;
3245                 sleep(poll_intvl);
3246                 if (poll_intvl < 30)
3247                         poll_intvl *= 2;
3248         }
3249
3250         closedir(root);
3251         return 0;
3252 }
3253
3254 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
3255 {
3256         DIR *root;
3257         int rc;
3258
3259         root = opendir(mnt);
3260         if (!root) {
3261                 rc = -errno;
3262                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
3263                 return rc;
3264         }
3265
3266         rc = ioctl(dirfd(root), LL_IOC_QUOTACTL, qctl);
3267         if (rc < 0)
3268                 rc = -errno;
3269
3270         closedir(root);
3271         return rc;
3272 }
3273
3274 static int cb_quotachown(char *path, DIR *parent, DIR *d, void *data,
3275                          struct dirent64 *de)
3276 {
3277         struct find_param *param = (struct find_param *)data;
3278         lstat_t *st;
3279         int rc;
3280
3281         LASSERT(parent != NULL || d != NULL);
3282
3283         rc = get_lmd_info(path, parent, d, param->lmd, param->lumlen);
3284         if (rc) {
3285                 if (rc == -ENODATA) {
3286                         if (!param->obduuid && !param->quiet)
3287                                 llapi_error(LLAPI_MSG_ERROR, -ENODATA,
3288                                           "%s has no stripe info", path);
3289                         rc = 0;
3290                 } else if (rc == -ENOENT) {
3291                         rc = 0;
3292                 }
3293                 return rc;
3294         }
3295
3296         st = &param->lmd->lmd_st;
3297
3298         /* libc chown() will do extra check, and if the real owner is
3299          * the same as the ones to set, it won't fall into kernel, so
3300          * invoke syscall directly. */
3301         rc = syscall(SYS_chown, path, -1, -1);
3302         if (rc)
3303                 llapi_error(LLAPI_MSG_ERROR, errno,
3304                             "error: chown %s", path);
3305
3306         rc = chmod(path, st->st_mode);
3307         if (rc) {
3308                 rc = -errno;
3309                 llapi_error(LLAPI_MSG_ERROR, rc, "error: chmod %s (%hu)",
3310                             path, st->st_mode);
3311         }
3312
3313         return rc;
3314 }
3315
3316 int llapi_quotachown(char *path, int flag)
3317 {
3318         struct find_param param;
3319
3320         memset(&param, 0, sizeof(param));
3321         param.recursive = 1;
3322         param.verbose = 0;
3323         param.quiet = 1;
3324
3325         return param_callback(path, cb_quotachown, NULL, &param);
3326 }
3327
3328 #include <pwd.h>
3329 #include <grp.h>
3330 #include <mntent.h>
3331 #include <sys/wait.h>
3332 #include <errno.h>
3333 #include <ctype.h>
3334
3335 static int rmtacl_notify(int ops)
3336 {
3337         FILE *fp;
3338         struct mntent *mnt;
3339         int found = 0, fd = 0, rc = 0;
3340
3341         fp = setmntent(MOUNTED, "r");
3342         if (fp == NULL) {
3343                 rc = -errno;
3344                 llapi_error(LLAPI_MSG_ERROR, rc,
3345                             "error setmntent(%s)", MOUNTED);
3346                 return rc;
3347         }
3348
3349         while (1) {
3350                 mnt = getmntent(fp);
3351                 if (!mnt)
3352                         break;
3353
3354                 if (!llapi_is_lustre_mnt(mnt))
3355                         continue;
3356
3357                 fd = open(mnt->mnt_dir, O_RDONLY | O_DIRECTORY);
3358                 if (fd < 0) {
3359                         rc = -errno;
3360                         llapi_error(LLAPI_MSG_ERROR, rc,
3361                                     "Can't open '%s'\n", mnt->mnt_dir);
3362                         goto out;
3363                 }
3364
3365                 rc = ioctl(fd, LL_IOC_RMTACL, ops);
3366                 close(fd);
3367                 if (rc < 0) {
3368                         rc = -errno;
3369                         llapi_error(LLAPI_MSG_ERROR, rc, "ioctl %d\n", fd);
3370                         goto out;
3371                 }
3372
3373                 found++;
3374         }
3375
3376 out:
3377         endmntent(fp);
3378         return ((rc != 0) ? rc : found);
3379 }
3380
3381 static char *next_token(char *p, int div)
3382 {
3383         if (p == NULL)
3384                 return NULL;
3385
3386         if (div)
3387                 while (*p && *p != ':' && !isspace(*p))
3388                         p++;
3389         else
3390                 while (*p == ':' || isspace(*p))
3391                         p++;
3392
3393         return *p ? p : NULL;
3394 }
3395
3396 static int rmtacl_name2id(char *name, int is_user)
3397 {
3398         if (is_user) {
3399                 struct passwd *pw;
3400
3401                 pw = getpwnam(name);
3402                 if (pw == NULL)
3403                         return INVALID_ID;
3404                 else
3405                         return (int)(pw->pw_uid);
3406         } else {
3407                 struct group *gr;
3408
3409                 gr = getgrnam(name);
3410                 if (gr == NULL)
3411                         return INVALID_ID;
3412                 else
3413                         return (int)(gr->gr_gid);
3414         }
3415 }
3416
3417 static int isodigit(int c)
3418 {
3419         return (c >= '0' && c <= '7') ? 1 : 0;
3420 }
3421
3422 /*
3423  * Whether the name is just digits string (uid/gid) already or not.
3424  * Return value:
3425  * 1: str is id
3426  * 0: str is not id
3427  */
3428 static int str_is_id(char *str)
3429 {
3430         if (str == NULL)
3431                 return 0;
3432
3433         if (*str == '0') {
3434                 str++;
3435                 if (*str == 'x' || *str == 'X') { /* for Hex. */
3436                         if (!isxdigit(*(++str)))
3437                                 return 0;
3438
3439                         while (isxdigit(*(++str)));
3440                 } else if (isodigit(*str)) { /* for Oct. */
3441                         while (isodigit(*(++str)));
3442                 }
3443         } else if (isdigit(*str)) { /* for Dec. */
3444                 while (isdigit(*(++str)));
3445         }
3446
3447         return (*str == 0) ? 1 : 0;
3448 }
3449
3450 typedef struct {
3451         char *name;
3452         int   length;
3453         int   is_user;
3454         int   next_token;
3455 } rmtacl_name_t;
3456
3457 #define RMTACL_OPTNAME(name) name, sizeof(name) - 1
3458
3459 static rmtacl_name_t rmtacl_namelist[] = {
3460         { RMTACL_OPTNAME("user:"),            1,      0 },
3461         { RMTACL_OPTNAME("group:"),           0,      0 },
3462         { RMTACL_OPTNAME("default:user:"),    1,      0 },
3463         { RMTACL_OPTNAME("default:group:"),   0,      0 },
3464         /* for --tabular option */
3465         { RMTACL_OPTNAME("user"),             1,      1 },
3466         { RMTACL_OPTNAME("group"),            0,      1 },
3467         { 0 }
3468 };
3469
3470 static int rgetfacl_output(char *str)
3471 {
3472         char *start = NULL, *end = NULL;
3473         int is_user = 0, n, id;
3474         char c;
3475         rmtacl_name_t *rn;
3476
3477         if (str == NULL)
3478                 return -1;
3479
3480         for (rn = rmtacl_namelist; rn->name; rn++) {
3481                 if(strncmp(str, rn->name, rn->length) == 0) {
3482                         if (!rn->next_token)
3483                                 start = str + rn->length;
3484                         else
3485                                 start = next_token(str + rn->length, 0);
3486                         is_user = rn->is_user;
3487                         break;
3488                 }
3489         }
3490
3491         end = next_token(start, 1);
3492         if (end == NULL || start == end) {
3493                 n = printf("%s", str);
3494                 return n;
3495         }
3496
3497         c = *end;
3498         *end = 0;
3499         id = rmtacl_name2id(start, is_user);
3500         if (id == INVALID_ID) {
3501                 if (str_is_id(start)) {
3502                         *end = c;
3503                         n = printf("%s", str);
3504                 } else
3505                         return -1;
3506         } else if ((id == NOBODY_UID && is_user) ||
3507                    (id == NOBODY_GID && !is_user)) {
3508                 *end = c;
3509                 n = printf("%s", str);
3510         } else {
3511                 *end = c;
3512                 *start = 0;
3513                 n = printf("%s%d%s", str, id, end);
3514         }
3515         return n;
3516 }
3517
3518 static int child_status(int status)
3519 {
3520         return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
3521 }
3522
3523 static int do_rmtacl(int argc, char *argv[], int ops, int (output_func)(char *))
3524 {
3525         pid_t pid = 0;
3526         int fd[2], status, rc;
3527         FILE *fp;
3528         char buf[PIPE_BUF];
3529
3530         if (output_func) {
3531                 if (pipe(fd) < 0) {
3532                         rc = -errno;
3533                         llapi_error(LLAPI_MSG_ERROR, rc, "Can't create pipe\n");
3534                         return rc;
3535                 }
3536
3537                 pid = fork();
3538                 if (pid < 0) {
3539                         rc = -errno;
3540                         llapi_error(LLAPI_MSG_ERROR, rc, "Can't fork\n");
3541                         close(fd[0]);
3542                         close(fd[1]);
3543                         return rc;
3544                 } else if (!pid) {
3545                         /* child process redirects its output. */
3546                         close(fd[0]);
3547                         close(1);
3548                         if (dup2(fd[1], 1) < 0) {
3549                                 rc = -errno;
3550                                 llapi_error(LLAPI_MSG_ERROR, rc,
3551                                             "Can't dup2 %d\n", fd[1]);
3552                                 close(fd[1]);
3553                                 return rc;
3554                         }
3555                 } else {
3556                         close(fd[1]);
3557                 }
3558         }
3559
3560         if (!pid) {
3561                 status = rmtacl_notify(ops);
3562                 if (status < 0)
3563                         return -errno;
3564
3565                 exit(execvp(argv[0], argv));
3566         }
3567
3568         /* the following is parent process */
3569         fp = fdopen(fd[0], "r");
3570         if (fp == NULL) {
3571                 rc = -errno;
3572                 llapi_error(LLAPI_MSG_ERROR, rc, "fdopen %d failed\n", fd[0]);
3573                 kill(pid, SIGKILL);
3574                 close(fd[0]);
3575                 return rc;
3576         }
3577
3578         while (fgets(buf, PIPE_BUF, fp) != NULL) {
3579                 if (output_func(buf) < 0)
3580                         fprintf(stderr, "WARNING: unexpected error!\n[%s]\n",
3581                                 buf);
3582         }
3583         fclose(fp);
3584         close(fd[0]);
3585
3586         if (waitpid(pid, &status, 0) < 0) {
3587                 rc = -errno;
3588                 llapi_error(LLAPI_MSG_ERROR, rc, "waitpid %d failed\n", pid);
3589                 return rc;
3590         }
3591
3592         return child_status(status);
3593 }
3594
3595 int llapi_lsetfacl(int argc, char *argv[])
3596 {
3597         return do_rmtacl(argc, argv, RMT_LSETFACL, NULL);
3598 }
3599
3600 int llapi_lgetfacl(int argc, char *argv[])
3601 {
3602         return do_rmtacl(argc, argv, RMT_LGETFACL, NULL);
3603 }
3604
3605 int llapi_rsetfacl(int argc, char *argv[])
3606 {
3607         return do_rmtacl(argc, argv, RMT_RSETFACL, NULL);
3608 }
3609
3610 int llapi_rgetfacl(int argc, char *argv[])
3611 {
3612         return do_rmtacl(argc, argv, RMT_RGETFACL, rgetfacl_output);
3613 }
3614
3615 int llapi_cp(int argc, char *argv[])
3616 {
3617         int rc;
3618
3619         rc = rmtacl_notify(RMT_RSETFACL);
3620         if (rc < 0)
3621                 return rc;
3622
3623         exit(execvp(argv[0], argv));
3624 }
3625
3626 int llapi_ls(int argc, char *argv[])
3627 {
3628         int rc;
3629
3630         rc = rmtacl_notify(RMT_LGETFACL);
3631         if (rc < 0)
3632                 return rc;
3633
3634         exit(execvp(argv[0], argv));
3635 }
3636
3637 /* Print mdtname 'name' into 'buf' using 'format'.  Add -MDT0000 if needed.
3638  * format must have %s%s, buf must be > 16
3639  * Eg: if name = "lustre-MDT0000", "lustre", or "lustre-MDT0000_UUID"
3640  *     then buf = "lustre-MDT0000"
3641  */
3642 static int get_mdtname(char *name, char *format, char *buf)
3643 {
3644         char suffix[]="-MDT0000";
3645         int len = strlen(name);
3646
3647         if ((len > 5) && (strncmp(name + len - 5, "_UUID", 5) == 0)) {
3648                 name[len - 5] = '\0';
3649                 len -= 5;
3650         }
3651
3652         if (len > 8) {
3653                 if ((len <= 16) && strncmp(name + len - 8, "-MDT", 4) == 0) {
3654                         suffix[0] = '\0';
3655                 } else {
3656                         /* Not enough room to add suffix */
3657                         llapi_err_noerrno(LLAPI_MSG_ERROR,
3658                                           "MDT name too long |%s|", name);
3659                         return -EINVAL;
3660                 }
3661         }
3662
3663         return sprintf(buf, format, name, suffix);
3664 }
3665
3666 /** ioctl on filsystem root, with mdtindex sent as data
3667  * \param mdtname path, fsname, or mdtname (lutre-MDT0004)
3668  * \param mdtidxp pointer to integer within data to be filled in with the
3669  *    mdt index (0 if no mdt is specified).  NULL won't be filled.
3670  */
3671 int root_ioctl(const char *mdtname, int opc, void *data, int *mdtidxp,
3672                int want_error)
3673 {
3674         char fsname[20];
3675         char *ptr;
3676         int fd, index, rc;
3677
3678         /* Take path, fsname, or MDTname.  Assume MDT0000 in the former cases.
3679          Open root and parse mdt index. */
3680         if (mdtname[0] == '/') {
3681                 index = 0;
3682                 rc = get_root_path(WANT_FD | want_error, NULL, &fd,
3683                                    (char *)mdtname, -1);
3684         } else {
3685                 if (get_mdtname((char *)mdtname, "%s%s", fsname) < 0)
3686                         return -EINVAL;
3687                 ptr = fsname + strlen(fsname) - 8;
3688                 *ptr = '\0';
3689                 index = strtol(ptr + 4, NULL, 10);
3690                 rc = get_root_path(WANT_FD | want_error, fsname, &fd, NULL, -1);
3691         }
3692         if (rc < 0) {
3693                 if (want_error)
3694                         llapi_err_noerrno(LLAPI_MSG_ERROR,
3695                                           "Can't open %s: %d\n", mdtname, rc);
3696                 return rc;
3697         }
3698
3699         if (mdtidxp)
3700                 *mdtidxp = index;
3701
3702         rc = ioctl(fd, opc, data);
3703         if (rc == -1)
3704                 rc = -errno;
3705         else
3706                 rc = 0;
3707         if (rc && want_error)
3708                 llapi_error(LLAPI_MSG_ERROR, rc, "ioctl %d err %d", opc, rc);
3709
3710         close(fd);
3711         return rc;
3712 }
3713
3714 /****** Changelog API ********/
3715
3716 static int changelog_ioctl(const char *mdtname, int opc, int id,
3717                            long long recno, int flags)
3718 {
3719         struct ioc_changelog data;
3720         int *idx;
3721
3722         data.icc_id = id;
3723         data.icc_recno = recno;
3724         data.icc_flags = flags;
3725         idx = (int *)(&data.icc_mdtindex);
3726
3727         return root_ioctl(mdtname, opc, &data, idx, WANT_ERROR);
3728 }
3729
3730 #define CHANGELOG_PRIV_MAGIC 0xCA8E1080
3731 struct changelog_private {
3732         int magic;
3733         int flags;
3734         lustre_kernelcomm kuc;
3735 };
3736
3737 /** Start reading from a changelog
3738  * @param priv Opaque private control structure
3739  * @param flags Start flags (e.g. CHANGELOG_FLAG_BLOCK)
3740  * @param device Report changes recorded on this MDT
3741  * @param startrec Report changes beginning with this record number
3742  * (just call llapi_changelog_fini when done; don't need an endrec)
3743  */
3744 int llapi_changelog_start(void **priv, int flags, const char *device,
3745                           long long startrec)
3746 {
3747         struct changelog_private *cp;
3748         int rc;
3749
3750         /* Set up the receiver control struct */
3751         cp = calloc(1, sizeof(*cp));
3752         if (cp == NULL)
3753                 return -ENOMEM;
3754
3755         cp->magic = CHANGELOG_PRIV_MAGIC;
3756         cp->flags = flags;
3757
3758         /* Set up the receiver */
3759         rc = libcfs_ukuc_start(&cp->kuc, 0 /* no group registration */);
3760         if (rc < 0)
3761                 goto out_free;
3762
3763         *priv = cp;
3764
3765         /* Tell the kernel to start sending */
3766         rc = changelog_ioctl(device, OBD_IOC_CHANGELOG_SEND, cp->kuc.lk_wfd,
3767                              startrec, flags);
3768         /* Only the kernel reference keeps the write side open */
3769         close(cp->kuc.lk_wfd);
3770         cp->kuc.lk_wfd = 0;
3771         if (rc < 0) {
3772                 /* frees and clears priv */
3773                 llapi_changelog_fini(priv);
3774                 return rc;
3775         }
3776
3777         return 0;
3778
3779 out_free:
3780         free(cp);
3781         return rc;
3782 }
3783
3784 /** Finish reading from a changelog */
3785 int llapi_changelog_fini(void **priv)
3786 {
3787         struct changelog_private *cp = (struct changelog_private *)*priv;
3788
3789         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
3790                 return -EINVAL;
3791
3792         libcfs_ukuc_stop(&cp->kuc);
3793         free(cp);
3794         *priv = NULL;
3795         return 0;
3796 }
3797
3798 /** Convert a changelog_rec to changelog_ext_rec, in this way client can treat
3799  *  all records in the format of changelog_ext_rec, this can make record
3800  *  analysis simpler.
3801  */
3802 static inline int changelog_extend_rec(struct changelog_ext_rec *ext)
3803 {
3804         if (!CHANGELOG_REC_EXTENDED(ext)) {
3805                 struct changelog_rec *rec = (struct changelog_rec *)ext;
3806
3807                 memmove(ext->cr_name, rec->cr_name, rec->cr_namelen);
3808                 fid_zero(&ext->cr_sfid);
3809                 fid_zero(&ext->cr_spfid);
3810                 return 1;
3811         }
3812
3813         return 0;
3814 }
3815
3816 /** Read the next changelog entry
3817  * @param priv Opaque private control structure
3818  * @param rech Changelog record handle; record will be allocated here
3819  * @return 0 valid message received; rec is set
3820  *         <0 error code
3821  *         1 EOF
3822  */
3823 int llapi_changelog_recv(void *priv, struct changelog_ext_rec **rech)
3824 {
3825         struct changelog_private *cp = (struct changelog_private *)priv;
3826         struct kuc_hdr *kuch;
3827         int rc = 0;
3828
3829         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
3830                 return -EINVAL;
3831         if (rech == NULL)
3832                 return -EINVAL;
3833         kuch = malloc(CR_MAXSIZE + sizeof(*kuch));
3834         if (kuch == NULL)
3835                 return -ENOMEM;
3836
3837 repeat:
3838         rc = libcfs_ukuc_msg_get(&cp->kuc, (char *)kuch,
3839                                  CR_MAXSIZE + sizeof(*kuch),
3840                                  KUC_TRANSPORT_CHANGELOG);
3841         if (rc < 0)
3842                 goto out_free;
3843
3844         if ((kuch->kuc_transport != KUC_TRANSPORT_CHANGELOG) ||
3845             ((kuch->kuc_msgtype != CL_RECORD) &&
3846              (kuch->kuc_msgtype != CL_EOF))) {
3847                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3848                                   "Unknown changelog message type %d:%d\n",
3849                                   kuch->kuc_transport, kuch->kuc_msgtype);
3850                 rc = -EPROTO;
3851                 goto out_free;
3852         }
3853
3854         if (kuch->kuc_msgtype == CL_EOF) {
3855                 if (cp->flags & CHANGELOG_FLAG_FOLLOW) {
3856                         /* Ignore EOFs */
3857                         goto repeat;
3858                 } else {
3859                         rc = 1;
3860                         goto out_free;
3861                 }
3862         }
3863
3864         /* Our message is a changelog_ext_rec.  Use pointer math to skip
3865          * kuch_hdr and point directly to the message payload.
3866          */
3867         *rech = (struct changelog_ext_rec *)(kuch + 1);
3868         changelog_extend_rec(*rech);
3869
3870         return 0;
3871
3872 out_free:
3873         *rech = NULL;
3874         free(kuch);
3875         return rc;
3876 }
3877
3878 /** Release the changelog record when done with it. */
3879 int llapi_changelog_free(struct changelog_ext_rec **rech)
3880 {
3881         if (*rech) {
3882                 /* We allocated memory starting at the kuc_hdr, but passed
3883                  * the consumer a pointer to the payload.
3884                  * Use pointer math to get back to the header.
3885                  */
3886                 struct kuc_hdr *kuch = (struct kuc_hdr *)*rech - 1;
3887                 free(kuch);
3888         }
3889         *rech = NULL;
3890         return 0;
3891 }
3892
3893 int llapi_changelog_clear(const char *mdtname, const char *idstr,
3894                           long long endrec)
3895 {
3896         int id;
3897
3898         if (endrec < 0) {
3899                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3900                                   "can't purge negative records\n");
3901                 return -EINVAL;
3902         }
3903
3904         id = strtol(idstr + strlen(CHANGELOG_USER_PREFIX), NULL, 10);
3905         if ((id == 0) || (strncmp(idstr, CHANGELOG_USER_PREFIX,
3906                                   strlen(CHANGELOG_USER_PREFIX)) != 0)) {
3907                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3908                                   "expecting id of the form '"
3909                                   CHANGELOG_USER_PREFIX
3910                                   "<num>'; got '%s'\n", idstr);
3911                 return -EINVAL;
3912         }
3913
3914         return changelog_ioctl(mdtname, OBD_IOC_CHANGELOG_CLEAR, id, endrec, 0);
3915 }
3916
3917 int llapi_fid2path(const char *device, const char *fidstr, char *buf,
3918                    int buflen, long long *recno, int *linkno)
3919 {
3920         struct lu_fid fid;
3921         struct getinfo_fid2path *gf;
3922         int rc;
3923
3924         while (*fidstr == '[')
3925                 fidstr++;
3926
3927         sscanf(fidstr, SFID, RFID(&fid));
3928         if (!fid_is_sane(&fid)) {
3929                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3930                                   "bad FID format [%s], should be "DFID"\n",
3931                                   fidstr, (__u64)1, 2, 0);
3932                 return -EINVAL;
3933         }
3934
3935         gf = malloc(sizeof(*gf) + buflen);
3936         if (gf == NULL)
3937                 return -ENOMEM;
3938         gf->gf_fid = fid;
3939         gf->gf_recno = *recno;
3940         gf->gf_linkno = *linkno;
3941         gf->gf_pathlen = buflen;
3942
3943         /* Take path or fsname */
3944         rc = root_ioctl(device, OBD_IOC_FID2PATH, gf, NULL, 0);
3945         if (rc) {
3946                 if (rc != -ENOENT)
3947                         llapi_error(LLAPI_MSG_ERROR, rc, "ioctl err %d", rc);
3948         } else {
3949                 memcpy(buf, gf->gf_path, gf->gf_pathlen);
3950                 *recno = gf->gf_recno;
3951                 *linkno = gf->gf_linkno;
3952         }
3953
3954         free(gf);
3955         return rc;
3956 }
3957
3958 static int fid_from_lma(const char *path, const int fd, lustre_fid *fid)
3959 {
3960         char                     buf[512];
3961         struct lustre_mdt_attrs *lma;
3962         int                      rc;
3963
3964         if (path == NULL)
3965                 rc = fgetxattr(fd, XATTR_NAME_LMA, buf, sizeof(buf));
3966         else
3967                 rc = lgetxattr(path, XATTR_NAME_LMA, buf, sizeof(buf));
3968         if (rc < 0)
3969                 return -errno;
3970         lma = (struct lustre_mdt_attrs *)buf;
3971         fid_le_to_cpu(fid, &lma->lma_self_fid);
3972         return 0;
3973 }
3974
3975 int llapi_fd2fid(const int fd, lustre_fid *fid)
3976 {
3977         int rc;
3978
3979         memset(fid, 0, sizeof(*fid));
3980
3981         rc = ioctl(fd, LL_IOC_PATH2FID, fid) < 0 ? -errno : 0;
3982         if (rc == -EINVAL || rc == -ENOTTY)
3983                 rc = fid_from_lma(NULL, fd, fid);
3984
3985         return rc;
3986 }
3987
3988 int llapi_path2fid(const char *path, lustre_fid *fid)
3989 {
3990         int fd, rc;
3991
3992         memset(fid, 0, sizeof(*fid));
3993         fd = open(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
3994         if (fd < 0) {
3995                 if (errno == ELOOP || errno == ENXIO)
3996                         return fid_from_lma(path, -1, fid);
3997                 return -errno;
3998         }
3999
4000         rc = llapi_fd2fid(fd, fid);
4001         if (rc == -EINVAL || rc == -ENOTTY)
4002                 rc = fid_from_lma(path, -1, fid);
4003
4004         close(fd);
4005         return rc;
4006 }
4007
4008 int llapi_get_connect_flags(const char *mnt, __u64 *flags)
4009 {
4010         DIR *root;
4011         int rc;
4012
4013         root = opendir(mnt);
4014         if (!root) {
4015                 rc = -errno;
4016                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
4017                 return rc;
4018         }
4019
4020         rc = ioctl(dirfd(root), LL_IOC_GET_CONNECT_FLAGS, flags);
4021         if (rc < 0) {
4022                 rc = -errno;
4023                 llapi_error(LLAPI_MSG_ERROR, rc,
4024                             "ioctl on %s for getting connect flags failed", mnt);
4025         }
4026         closedir(root);
4027         return rc;
4028 }
4029
4030 int llapi_get_version(char *buffer, int buffer_size,
4031                       char **version)
4032 {
4033         int rc;
4034         int fd;
4035         struct obd_ioctl_data *data = (struct obd_ioctl_data *)buffer;
4036
4037         fd = open(OBD_DEV_PATH, O_RDONLY);
4038         if (fd == -1)
4039                 return -errno;
4040
4041         memset(buffer, 0, buffer_size);
4042         data->ioc_version = OBD_IOCTL_VERSION;
4043         data->ioc_inllen1 = buffer_size - cfs_size_round(sizeof(*data));
4044         data->ioc_inlbuf1 = buffer + cfs_size_round(sizeof(*data));
4045         data->ioc_len = obd_ioctl_packlen(data);
4046
4047         rc = ioctl(fd, OBD_GET_VERSION, buffer);
4048         if (rc == -1) {
4049                 rc = -errno;
4050                 close(fd);
4051                 return rc;
4052         }
4053         close(fd);
4054         *version = data->ioc_bulk;
4055         return 0;
4056 }
4057
4058 /**
4059  * Get a 64-bit value representing the version of file data pointed by fd.
4060  *
4061  * Each write or truncate, flushed on OST, will change this value. You can use
4062  * this value to verify if file data was modified. This only checks the file
4063  * data, not metadata.
4064  *
4065  * \param  flags  If set to LL_DV_NOFLUSH, the data version will be read
4066  *                directly from OST without regard to possible dirty cache on
4067  *                client nodes.
4068  *
4069  * \retval 0 on success.
4070  * \retval -errno on error.
4071  */
4072 int llapi_get_data_version(int fd, __u64 *data_version, __u64 flags)
4073 {
4074         int rc;
4075         struct ioc_data_version idv;
4076
4077         idv.idv_flags = flags;
4078
4079         rc = ioctl(fd, LL_IOC_DATA_VERSION, &idv);
4080         if (rc)
4081                 rc = -errno;
4082         else
4083                 *data_version = idv.idv_version;
4084
4085         return rc;
4086 }
4087
4088 /*
4089  * Create a volatile file and open it for write:
4090  * - file is created as a standard file in the directory
4091  * - file does not appears in directory and directory mtime does not change
4092  * - file is removed at close
4093  * - file modes are rw-------, if user wants another one it must use fchmod()
4094  * \param       directory       Directory where the file is created
4095  * \param       idx             MDT index on which the file is created
4096  * \param       flags           Std open flags
4097  *
4098  * \retval      0 on success.
4099  * \retval      -errno on error.
4100  */
4101 int llapi_create_volatile_idx(char *directory, int idx, int mode)
4102 {
4103         char    file_path[PATH_MAX];
4104         char    filename[PATH_MAX];
4105         int     fd;
4106         int     random;
4107         int     rc;
4108
4109         fd = open("/dev/urandom", O_RDONLY);
4110         if (fd < 0) {
4111                 llapi_error(LLAPI_MSG_ERROR, errno,
4112                             "Cannot open /dev/urandom\n");
4113                 return -errno;
4114         }
4115         rc = read(fd, &random, sizeof(random));
4116         close(fd);
4117         if (rc < sizeof(random)) {
4118                 llapi_error(LLAPI_MSG_ERROR, errno,
4119                             "Cannot read %d bytes from /dev/urandom\n",
4120                             sizeof(random));
4121                 return -errno;
4122         }
4123         if (idx == -1)
4124                 sprintf(filename, LUSTRE_VOLATILE_HDR"::%.4X", random);
4125         else
4126                 sprintf(filename, LUSTRE_VOLATILE_IDX"%.4X", 0, random);
4127
4128         sprintf(file_path, "%s/%s", directory, filename);
4129
4130         fd = open(file_path, O_RDWR|O_CREAT|mode, S_IRUSR|S_IWUSR);
4131         if (fd < 0) {
4132                 llapi_error(LLAPI_MSG_ERROR, errno,
4133                             "Cannot create volatile file %s in %s\n",
4134                             filename + LUSTRE_VOLATILE_HDR_LEN,
4135                             directory);
4136                 return -errno;
4137         }
4138         return fd;
4139 }
4140
4141 /**
4142  * Swap the layouts between 2 file descriptors
4143  * the 2 files must be open in write
4144  * first fd received the ioctl, second fd is passed as arg
4145  * this is assymetric but avoid use of root path for ioctl
4146  */
4147 int llapi_fswap_layouts(int fd1, int fd2, __u64 dv1, __u64 dv2, __u64 flags)
4148 {
4149         struct lustre_swap_layouts lsl;
4150         int rc;
4151
4152         srandom(time(NULL));
4153         lsl.sl_fd = fd2;
4154         lsl.sl_flags = flags;
4155         lsl.sl_gid = random();
4156         lsl.sl_dv1 = dv1;
4157         lsl.sl_dv2 = dv2;
4158         rc = ioctl(fd1, LL_IOC_LOV_SWAP_LAYOUTS, &lsl);
4159         if (rc)
4160                 rc = -errno;
4161         return rc;
4162 }
4163
4164 /**
4165  * Swap the layouts between 2 files
4166  * the 2 files are open in write
4167  */
4168 int llapi_swap_layouts(const char *path1, const char *path2,
4169                        __u64 dv1, __u64 dv2, __u64 flags)
4170 {
4171         int     fd1, fd2, rc;
4172
4173         fd1 = open(path1, O_WRONLY);
4174         if (fd1 < 0) {
4175                 llapi_error(LLAPI_MSG_ERROR, -errno,
4176                                 "error: cannot open for write %s",
4177                                 path1);
4178                 return -errno;
4179         }
4180
4181         fd2 = open(path2, O_WRONLY);
4182         if (fd2 < 0) {
4183                 llapi_error(LLAPI_MSG_ERROR, -errno,
4184                                 "error: cannot open for write %s",
4185                                 path2);
4186                 close(fd1);
4187                 return -errno;
4188         }
4189
4190         rc = llapi_fswap_layouts(fd1, fd2, dv1, dv2, flags);
4191         if (rc < 0)
4192                 llapi_error(LLAPI_MSG_ERROR, rc,
4193                         "error: cannot swap layouts between %s and %s\n",
4194                         path1, path2);
4195
4196         close(fd1);
4197         close(fd2);
4198         return rc;
4199 }