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