Whamcloud - gitweb
LU-3647 hsm: Add support to drop all pages for ll_data_version
[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;
1833         long i;
1834         struct obd_uuid *uuids = NULL;
1835         char buf[16];
1836         int *indexes;
1837
1838         if (type == LOV_TYPE)
1839                 ret = get_param_lov(path, "numobd", buf, sizeof(buf));
1840         else
1841                 ret = get_param_lmv(path, "numobd", buf, sizeof(buf));
1842         if (ret != 0)
1843                 return ret;
1844
1845         obdcount = atoi(buf);
1846         uuids = (struct obd_uuid *)malloc(obdcount *
1847                                           sizeof(struct obd_uuid));
1848         if (uuids == NULL)
1849                 return -ENOMEM;
1850
1851 retry_get_uuids:
1852         ret = llapi_get_target_uuids(dirfd(dir), uuids, &obdcount, type);
1853         if (ret) {
1854                 struct obd_uuid *uuids_temp;
1855
1856                 if (ret == -EOVERFLOW) {
1857                         uuids_temp = realloc(uuids, obdcount *
1858                                              sizeof(struct obd_uuid));
1859                         if (uuids_temp != NULL) {
1860                                 uuids = uuids_temp;
1861                                 goto retry_get_uuids;
1862                         }
1863                         else
1864                                 ret = -ENOMEM;
1865                 }
1866
1867                 llapi_error(LLAPI_MSG_ERROR, ret, "get ost uuid failed");
1868                 goto out_free;
1869         }
1870
1871         indexes = malloc(num_obds * sizeof(*obdindex));
1872         if (indexes == NULL) {
1873                 ret = -ENOMEM;
1874                 goto out_free;
1875         }
1876
1877         for (obdnum = 0; obdnum < num_obds; obdnum++) {
1878                 char *end = NULL;
1879
1880                 /* The user may have specified a simple index */
1881                 i = strtol(obduuids[obdnum].uuid, &end, 0);
1882                 if (end && *end == '\0' && i < obdcount) {
1883                         indexes[obdnum] = i;
1884                         obd_valid++;
1885                 } else {
1886                         for (i = 0; i < obdcount; i++) {
1887                                 if (llapi_uuid_match(uuids[i].uuid,
1888                                                      obduuids[obdnum].uuid)) {
1889                                         indexes[obdnum] = i;
1890                                         obd_valid++;
1891                                         break;
1892                                 }
1893                         }
1894                 }
1895                 if (i >= obdcount) {
1896                         indexes[obdnum] = OBD_NOT_FOUND;
1897                         llapi_err_noerrno(LLAPI_MSG_ERROR,
1898                                           "error: %s: unknown obduuid: %s",
1899                                           __func__, obduuids[obdnum].uuid);
1900                         ret = -EINVAL;
1901                 }
1902         }
1903
1904         if (obd_valid == 0)
1905                 *obdindex = OBD_NOT_FOUND;
1906         else
1907                 *obdindex = obd_valid;
1908
1909         *obdindexes = indexes;
1910 out_free:
1911         if (uuids)
1912                 free(uuids);
1913
1914         return ret;
1915 }
1916
1917 static int setup_target_indexes(DIR *dir, char *path, struct find_param *param)
1918 {
1919         int ret = 0;
1920
1921         if (param->mdtuuid) {
1922                 ret = setup_indexes(dir, path, param->mdtuuid, param->num_mdts,
1923                               &param->mdtindexes, &param->mdtindex, LMV_TYPE);
1924                 if (ret)
1925                         return ret;
1926         }
1927         if (param->obduuid) {
1928                 ret = setup_indexes(dir, path, param->obduuid, param->num_obds,
1929                               &param->obdindexes, &param->obdindex, LOV_TYPE);
1930                 if (ret)
1931                         return ret;
1932         }
1933         param->got_uuids = 1;
1934         return ret;
1935 }
1936
1937 int llapi_ostlist(char *path, struct find_param *param)
1938 {
1939         DIR *dir;
1940         int ret;
1941
1942         dir = opendir(path);
1943         if (dir == NULL)
1944                 return -errno;
1945
1946         ret = setup_obd_uuid(dir, path, param);
1947         closedir(dir);
1948
1949         return ret;
1950 }
1951
1952 /*
1953  * Given a filesystem name, or a pathname of a file on a lustre filesystem,
1954  * tries to determine the path to the filesystem's clilov directory under /proc
1955  *
1956  * fsname is limited to MTI_NAME_MAXLEN in lustre_idl.h
1957  * The NUL terminator is compensated by the additional "%s" bytes. */
1958 #define LOV_LEN (sizeof("/proc/fs/lustre/lov/%s-clilov-*") + MTI_NAME_MAXLEN)
1959 static int clilovpath(const char *fsname, const char *const pathname,
1960                       char *clilovpath)
1961 {
1962         int rc;
1963         char pattern[LOV_LEN];
1964         char buffer[PATH_MAX + 1];
1965
1966         if (fsname == NULL) {
1967                 rc = llapi_search_fsname(pathname, buffer);
1968                 if (rc != 0)
1969                         return rc;
1970                 fsname = buffer;
1971         }
1972
1973         snprintf(pattern, sizeof(pattern), "/proc/fs/lustre/lov/%s-clilov-*",
1974                  fsname);
1975
1976         rc = first_match(pattern, buffer);
1977         if (rc != 0)
1978                 return rc;
1979
1980         strncpy(clilovpath, buffer, sizeof(buffer));
1981
1982         return 0;
1983 }
1984
1985 /*
1986  * Given the path to a stripe attribute proc file, tries to open and
1987  * read the attribute and return the value using the attr parameter
1988  */
1989 static int sattr_read_attr(const char *const fpath,
1990                            unsigned int *attr)
1991 {
1992
1993         FILE *f;
1994         char line[PATH_MAX + 1];
1995         int rc = 0;
1996
1997         f = fopen(fpath, "r");
1998         if (f == NULL) {
1999                 rc = -errno;
2000                 llapi_error(LLAPI_MSG_ERROR, rc, "Cannot open '%s'", fpath);
2001                 return rc;
2002         }
2003
2004         if (fgets(line, sizeof(line), f) != NULL) {
2005                 *attr = atoi(line);
2006         } else {
2007                 llapi_error(LLAPI_MSG_ERROR, errno, "Cannot read from '%s'", fpath);
2008                 rc = 1;
2009         }
2010
2011         fclose(f);
2012         return rc;
2013 }
2014
2015 /*
2016  * Tries to determine the default stripe attributes for a given filesystem. The
2017  * filesystem to check should be specified by fsname, or will be determined
2018  * using pathname.
2019  */
2020 static int sattr_get_defaults(const char *const fsname,
2021                               const char *const pathname,
2022                               unsigned int *scount,
2023                               unsigned int *ssize,
2024                               unsigned int *soffset)
2025 {
2026         int rc;
2027         char dpath[PATH_MAX + 1];
2028         char fpath[PATH_MAX + 1];
2029
2030         rc = clilovpath(fsname, pathname, dpath);
2031         if (rc != 0)
2032                 return rc;
2033
2034         if (scount) {
2035                 snprintf(fpath, PATH_MAX, "%s/stripecount", dpath);
2036                 rc = sattr_read_attr(fpath, scount);
2037                 if (rc != 0)
2038                         return rc;
2039         }
2040
2041         if (ssize) {
2042                 snprintf(fpath, PATH_MAX, "%s/stripesize", dpath);
2043                 rc = sattr_read_attr(fpath, ssize);
2044                 if (rc != 0)
2045                         return rc;
2046         }
2047
2048         if (soffset) {
2049                 snprintf(fpath, PATH_MAX, "%s/stripeoffset", dpath);
2050                 rc = sattr_read_attr(fpath, soffset);
2051                 if (rc != 0)
2052                         return rc;
2053         }
2054
2055         return 0;
2056 }
2057
2058 /*
2059  * Tries to gather the default stripe attributes for a given filesystem. If
2060  * the attributes can be determined, they are cached for easy retreival the
2061  * next time they are needed. Only a single filesystem's attributes are
2062  * cached at a time.
2063  */
2064 static int sattr_cache_get_defaults(const char *const fsname,
2065                                     const char *const pathname,
2066                                     unsigned int *scount,
2067                                     unsigned int *ssize,
2068                                     unsigned int *soffset)
2069 {
2070         static struct {
2071                 char fsname[PATH_MAX + 1];
2072                 unsigned int stripecount;
2073                 unsigned int stripesize;
2074                 unsigned int stripeoffset;
2075         } cache = {
2076                 .fsname = {'\0'}
2077         };
2078
2079         int rc;
2080         char fsname_buf[PATH_MAX + 1];
2081         unsigned int tmp[3];
2082
2083         if (fsname == NULL) {
2084                 rc = llapi_search_fsname(pathname, fsname_buf);
2085                 if (rc)
2086                         return rc;
2087         } else {
2088                 strncpy(fsname_buf, fsname, PATH_MAX);
2089         }
2090
2091         if (strncmp(fsname_buf, cache.fsname, PATH_MAX) != 0) {
2092                 /*
2093                  * Ensure all 3 sattrs (count, size, and offset) are
2094                  * successfully retrieved and stored in tmp before writing to
2095                  * cache.
2096                  */
2097                 rc = sattr_get_defaults(fsname_buf, NULL, &tmp[0], &tmp[1],
2098                                         &tmp[2]);
2099                 if (rc != 0)
2100                         return rc;
2101
2102                 cache.stripecount = tmp[0];
2103                 cache.stripesize = tmp[1];
2104                 cache.stripeoffset = tmp[2];
2105                 strncpy(cache.fsname, fsname_buf, PATH_MAX);
2106         }
2107
2108         if (scount)
2109                 *scount = cache.stripecount;
2110         if (ssize)
2111                 *ssize = cache.stripesize;
2112         if (soffset)
2113                 *soffset = cache.stripeoffset;
2114
2115         return 0;
2116 }
2117
2118 static void lov_dump_user_lmm_header(struct lov_user_md *lum, char *path,
2119                                      struct lov_user_ost_data_v1 *objects,
2120                                      int is_dir, int verbose, int depth,
2121                                      int raw, char *pool_name)
2122 {
2123         char *prefix = is_dir ? "" : "lmm_";
2124         char nl = is_dir ? ' ' : '\n';
2125         int rc;
2126
2127         if (is_dir && lmm_oi_seq(&lum->lmm_oi) == FID_SEQ_LOV_DEFAULT) {
2128                 lmm_oi_set_seq(&lum->lmm_oi, 0);
2129                 if (verbose & VERBOSE_DETAIL)
2130                         llapi_printf(LLAPI_MSG_NORMAL, "(Default) ");
2131         }
2132
2133         if (depth && path && ((verbose != VERBOSE_OBJID) || !is_dir))
2134                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
2135
2136         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
2137                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_magic:          0x%08X\n",
2138                              lum->lmm_magic);
2139                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_seq:            "LPX64"\n",
2140                              lmm_oi_seq(&lum->lmm_oi));
2141                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_id:      "LPX64"\n",
2142                              lmm_oi_id(&lum->lmm_oi));
2143         }
2144
2145         if (verbose & VERBOSE_COUNT) {
2146                 if (verbose & ~VERBOSE_COUNT)
2147                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_count:   ",
2148                                      prefix);
2149                 if (is_dir) {
2150                         if (!raw && lum->lmm_stripe_count == 0) {
2151                                 unsigned int scount;
2152                                 rc = sattr_cache_get_defaults(NULL, path,
2153                                                               &scount, NULL,
2154                                                               NULL);
2155                                 if (rc == 0)
2156                                         llapi_printf(LLAPI_MSG_NORMAL, "%d%c",
2157                                                      scount, nl);
2158                                 else
2159                                         llapi_error(LLAPI_MSG_ERROR, rc,
2160                                                     "Cannot determine default"
2161                                                     " stripe count.");
2162                         } else {
2163                                 llapi_printf(LLAPI_MSG_NORMAL, "%d%c",
2164                                              lum->lmm_stripe_count ==
2165                                              (typeof(lum->lmm_stripe_count))(-1)
2166                                              ? -1 : lum->lmm_stripe_count, nl);
2167                         }
2168                 } else {
2169                         llapi_printf(LLAPI_MSG_NORMAL, "%hd%c",
2170                                      (__s16)lum->lmm_stripe_count, nl);
2171                 }
2172         }
2173
2174         if (verbose & VERBOSE_SIZE) {
2175                 if (verbose & ~VERBOSE_SIZE)
2176                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_size:    ",
2177                                      prefix);
2178                 if (is_dir && !raw && lum->lmm_stripe_size == 0) {
2179                         unsigned int ssize;
2180                         rc = sattr_cache_get_defaults(NULL, path, NULL, &ssize,
2181                                                       NULL);
2182                         if (rc == 0)
2183                                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c", ssize,
2184                                              nl);
2185                         else
2186                                 llapi_error(LLAPI_MSG_ERROR, rc,
2187                                             "Cannot determine default"
2188                                             " stripe size.");
2189                 } else {
2190                         llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
2191                                      lum->lmm_stripe_size, nl);
2192                 }
2193         }
2194
2195         if ((verbose & VERBOSE_LAYOUT) && !is_dir) {
2196                 if (verbose & ~VERBOSE_LAYOUT)
2197                         llapi_printf(LLAPI_MSG_NORMAL, "%spattern:        ",
2198                                      prefix);
2199                 llapi_printf(LLAPI_MSG_NORMAL, "%.x%c", lum->lmm_pattern, nl);
2200         }
2201
2202         if ((verbose & VERBOSE_GENERATION) && !is_dir) {
2203                 if (verbose & ~VERBOSE_GENERATION)
2204                         llapi_printf(LLAPI_MSG_NORMAL, "%slayout_gen:     ",
2205                                      prefix);
2206                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
2207                                 (int)lum->lmm_layout_gen, nl);
2208         }
2209
2210         if (verbose & VERBOSE_OFFSET) {
2211                 if (verbose & ~VERBOSE_OFFSET)
2212                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_offset:  ",
2213                                      prefix);
2214                 if (is_dir)
2215                         llapi_printf(LLAPI_MSG_NORMAL, "%d%c",
2216                                      lum->lmm_stripe_offset ==
2217                                      (typeof(lum->lmm_stripe_offset))(-1) ? -1 :
2218                                      lum->lmm_stripe_offset, nl);
2219                 else
2220                         llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
2221                                      objects[0].l_ost_idx, nl);
2222         }
2223
2224         if ((verbose & VERBOSE_POOL) && (pool_name != NULL)) {
2225                 if (verbose & ~VERBOSE_POOL)
2226                         llapi_printf(LLAPI_MSG_NORMAL, "%spool:           ",
2227                                      prefix);
2228                 llapi_printf(LLAPI_MSG_NORMAL, "%s%c", pool_name, nl);
2229         }
2230
2231         if (is_dir && (verbose != VERBOSE_OBJID))
2232                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
2233 }
2234
2235 void lov_dump_user_lmm_v1v3(struct lov_user_md *lum, char *pool_name,
2236                             struct lov_user_ost_data_v1 *objects,
2237                             char *path, int is_dir, int obdindex,
2238                             int depth, int header, int raw)
2239 {
2240         int i, obdstripe = (obdindex != OBD_NOT_FOUND) ? 0 : 1;
2241
2242         if (!obdstripe) {
2243                 for (i = 0; !is_dir && i < lum->lmm_stripe_count; i++) {
2244                         if (obdindex == objects[i].l_ost_idx) {
2245                                 obdstripe = 1;
2246                                 break;
2247                         }
2248                 }
2249         }
2250
2251         if (obdstripe == 1)
2252                 lov_dump_user_lmm_header(lum, path, objects, is_dir, header,
2253                                          depth, raw, pool_name);
2254
2255         if (!is_dir && (header & VERBOSE_OBJID) &&
2256             !(lum->lmm_pattern & LOV_PATTERN_F_RELEASED)) {
2257                 if (obdstripe == 1)
2258                         llapi_printf(LLAPI_MSG_NORMAL,
2259                                    "\tobdidx\t\t objid\t\t objid\t\t group\n");
2260
2261                 for (i = 0; i < lum->lmm_stripe_count; i++) {
2262                         int idx = objects[i].l_ost_idx;
2263                         long long oid = ostid_id(&objects[i].l_ost_oi);
2264                         long long gr = ostid_seq(&objects[i].l_ost_oi);
2265                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx)) {
2266                                 char fmt[48];
2267                                 sprintf(fmt, "%s%s%s\n",
2268                                         "\t%6u\t%14llu\t%#13llx\t",
2269                                         (fid_seq_is_rsvd(gr) ||
2270                                          fid_seq_is_mdt0(gr)) ?
2271                                          "%14llu" : "%#14llx", "%s");
2272                                 llapi_printf(LLAPI_MSG_NORMAL, fmt, idx, oid,
2273                                              oid, gr,
2274                                              obdindex == idx ? " *" : "");
2275                         }
2276
2277                 }
2278                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
2279         }
2280 }
2281
2282 void lmv_dump_user_lmm(struct lmv_user_md *lum, char *pool_name,
2283                        char *path, int obdindex, int depth, int verbose)
2284 {
2285         struct lmv_user_mds_data *objects = lum->lum_objects;
2286         char *prefix = lum->lum_magic == LMV_USER_MAGIC ? "(Default)" : "";
2287         int i, obdstripe = 0;
2288
2289         if (obdindex != OBD_NOT_FOUND) {
2290                 for (i = 0; i < lum->lum_stripe_count; i++) {
2291                         if (obdindex == objects[i].lum_mds) {
2292                                 llapi_printf(LLAPI_MSG_NORMAL, "%s%s\n", prefix,
2293                                              path);
2294                                 obdstripe = 1;
2295                                 break;
2296                         }
2297                 }
2298         } else {
2299                 obdstripe = 1;
2300         }
2301
2302         /* show all information default */
2303         if (!verbose) {
2304                 if (lum->lum_magic == LMV_USER_MAGIC)
2305                         verbose = VERBOSE_POOL | VERBOSE_COUNT | VERBOSE_OFFSET;
2306                 else
2307                         verbose = VERBOSE_OBJID;
2308         }
2309
2310         if (lum->lum_magic == LMV_USER_MAGIC)
2311                 verbose &= ~VERBOSE_OBJID;
2312
2313         if (depth && path && ((verbose != VERBOSE_OBJID)))
2314                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
2315
2316         if (verbose & VERBOSE_COUNT) {
2317                 if (verbose & ~VERBOSE_COUNT)
2318                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_stripe_count: ");
2319                 llapi_printf(LLAPI_MSG_NORMAL, "%u\n",
2320                              (int)lum->lum_stripe_count);
2321         }
2322
2323         if (verbose & VERBOSE_OFFSET) {
2324                 if (verbose & ~VERBOSE_OFFSET)
2325                         llapi_printf(LLAPI_MSG_NORMAL, "lmv_stripe_offset: ");
2326                 llapi_printf(LLAPI_MSG_NORMAL, "%d\n",
2327                              (int)lum->lum_stripe_offset);
2328         }
2329
2330         if (verbose & VERBOSE_OBJID) {
2331                 if ((obdstripe == 1))
2332                         llapi_printf(LLAPI_MSG_NORMAL,
2333                                      "\tmdtidx\t\t FID[seq:oid:ver]\n");
2334                 for (i = 0; i < lum->lum_stripe_count; i++) {
2335                         int idx = objects[i].lum_mds;
2336                         struct lu_fid *fid = &objects[i].lum_fid;
2337                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
2338                                 llapi_printf(LLAPI_MSG_NORMAL,
2339                                              "\t%6u\t\t "DFID"\t\t%s\n",
2340                                             idx, PFID(fid),
2341                                             obdindex == idx ? " *" : "");
2342                 }
2343
2344         }
2345
2346         if ((verbose & VERBOSE_POOL) && (pool_name[0] != '\0')) {
2347                 if (verbose & ~VERBOSE_POOL)
2348                         llapi_printf(LLAPI_MSG_NORMAL, "%slmv_pool:           ",
2349                                      prefix);
2350                 llapi_printf(LLAPI_MSG_NORMAL, "%s%c ", pool_name, ' ');
2351         }
2352         llapi_printf(LLAPI_MSG_NORMAL, "\n");
2353 }
2354
2355 void llapi_lov_dump_user_lmm(struct find_param *param, char *path, int is_dir)
2356 {
2357         __u32 magic;
2358
2359         if (param->get_lmv)
2360                 magic = (__u32)param->fp_lmv_md->lum_magic;
2361         else
2362                 magic = *(__u32 *)&param->lmd->lmd_lmm; /* lum->lmm_magic */
2363
2364         switch (magic) {
2365         case LOV_USER_MAGIC_V1:
2366                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, NULL,
2367                                        param->lmd->lmd_lmm.lmm_objects,
2368                                        path, is_dir,
2369                                        param->obdindex, param->maxdepth,
2370                                        param->verbose, param->raw);
2371                 break;
2372         case LOV_USER_MAGIC_V3: {
2373                 char pool_name[LOV_MAXPOOLNAME + 1];
2374                 struct lov_user_ost_data_v1 *objects;
2375                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
2376
2377                 strncpy(pool_name, lmmv3->lmm_pool_name, LOV_MAXPOOLNAME);
2378                 pool_name[LOV_MAXPOOLNAME] = '\0';
2379                 objects = lmmv3->lmm_objects;
2380                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, pool_name,
2381                                        objects, path, is_dir,
2382                                        param->obdindex, param->maxdepth,
2383                                        param->verbose, param->raw);
2384                 break;
2385         }
2386         case LMV_MAGIC_V1:
2387         case LMV_USER_MAGIC: {
2388                 char pool_name[LOV_MAXPOOLNAME + 1];
2389                 struct lmv_user_md *lum;
2390
2391                 lum = (struct lmv_user_md *)param->fp_lmv_md;
2392                 strncpy(pool_name, lum->lum_pool_name, LOV_MAXPOOLNAME);
2393                 lmv_dump_user_lmm(lum, pool_name, path,
2394                                   param->obdindex, param->maxdepth,
2395                                   param->verbose);
2396                 break;
2397         }
2398         default:
2399                 llapi_printf(LLAPI_MSG_NORMAL, "unknown lmm_magic:  %#x "
2400                              "(expecting one of %#x %#x %#x %#x)\n",
2401                              *(__u32 *)&param->lmd->lmd_lmm,
2402                              LOV_USER_MAGIC_V1, LOV_USER_MAGIC_V3,
2403                              LMV_USER_MAGIC, LMV_MAGIC_V1);
2404                 return;
2405         }
2406 }
2407
2408 int llapi_file_get_stripe(const char *path, struct lov_user_md *lum)
2409 {
2410         const char *fname;
2411         char *dname;
2412         int fd, rc = 0;
2413
2414         fname = strrchr(path, '/');
2415
2416         /* It should be a file (or other non-directory) */
2417         if (fname == NULL) {
2418                 dname = (char *)malloc(2);
2419                 if (dname == NULL)
2420                         return -ENOMEM;
2421                 strcpy(dname, ".");
2422                 fname = (char *)path;
2423         } else {
2424                 dname = (char *)malloc(fname - path + 1);
2425                 if (dname == NULL)
2426                         return -ENOMEM;
2427                 strncpy(dname, path, fname - path);
2428                 dname[fname - path] = '\0';
2429                 fname++;
2430         }
2431
2432         fd = open(dname, O_RDONLY);
2433         if (fd == -1) {
2434                 rc = -errno;
2435                 free(dname);
2436                 return rc;
2437         }
2438
2439         strcpy((char *)lum, fname);
2440         if (ioctl(fd, IOC_MDC_GETFILESTRIPE, (void *)lum) == -1)
2441                 rc = -errno;
2442
2443         if (close(fd) == -1 && rc == 0)
2444                 rc = -errno;
2445
2446         free(dname);
2447         return rc;
2448 }
2449
2450 int llapi_file_lookup(int dirfd, const char *name)
2451 {
2452         struct obd_ioctl_data data = { 0 };
2453         char rawbuf[8192];
2454         char *buf = rawbuf;
2455         int rc;
2456
2457         if (dirfd < 0 || name == NULL)
2458                 return -EINVAL;
2459
2460         data.ioc_version = OBD_IOCTL_VERSION;
2461         data.ioc_len = sizeof(data);
2462         data.ioc_inlbuf1 = (char *)name;
2463         data.ioc_inllen1 = strlen(name) + 1;
2464
2465         rc = obd_ioctl_pack(&data, &buf, sizeof(rawbuf));
2466         if (rc) {
2467                 llapi_error(LLAPI_MSG_ERROR, rc,
2468                             "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
2469                             name, rc);
2470                 return rc;
2471         }
2472
2473         rc = ioctl(dirfd, IOC_MDC_LOOKUP, buf);
2474         if (rc < 0)
2475                 rc = -errno;
2476         return rc;
2477 }
2478
2479 /* Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
2480  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
2481  *
2482  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
2483  * The table below gives the answers for the specified parameters (value and
2484  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
2485  * --------------------------------------
2486  * 1 | file > limit; sign > 0 | -1 / -1 |
2487  * 2 | file = limit; sign > 0 | -1 / -1 |
2488  * 3 | file < limit; sign > 0 |  ? /  1 |
2489  * 4 | file > limit; sign = 0 | -1 / -1 |
2490  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
2491  * 6 | file < limit; sign = 0 |  ? / -1 |
2492  * 7 | file > limit; sign < 0 |  1 /  1 |
2493  * 8 | file = limit; sign < 0 |  ? / -1 |
2494  * 9 | file < limit; sign < 0 |  ? / -1 |
2495  * --------------------------------------
2496  * Note: 5th actually means that the value is within the interval
2497  * (limit - margin, limit]. */
2498 static int find_value_cmp(unsigned long long file, unsigned long long limit,
2499                           int sign, int negopt, unsigned long long margin,
2500                           int mds)
2501 {
2502         int ret = -1;
2503
2504         if (sign > 0) {
2505                 /* Drop the fraction of margin (of days). */
2506                 if (file + margin <= limit)
2507                         ret = mds ? 0 : 1;
2508         } else if (sign == 0) {
2509                 if (file <= limit && file + margin > limit)
2510                         ret = mds ? 0 : 1;
2511                 else if (file + margin <= limit)
2512                         ret = mds ? 0 : -1;
2513         } else if (sign < 0) {
2514                 if (file > limit)
2515                         ret = 1;
2516                 else if (mds)
2517                         ret = 0;
2518         }
2519
2520         return negopt ? ~ret + 1 : ret;
2521 }
2522
2523 /* Check if the file time matches all the given criteria (e.g. --atime +/-N).
2524  * Return -1 or 1 if file timestamp does not or does match the given criteria
2525  * correspondingly. Return 0 if the MDS time is being checked and there are
2526  * attributes on OSTs and it is not yet clear if the timespamp matches.
2527  *
2528  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
2529  * updated timestamps. */
2530 static int find_time_check(lstat_t *st, struct find_param *param, int mds)
2531 {
2532         int ret;
2533         int rc = 1;
2534
2535         /* Check if file is accepted. */
2536         if (param->atime) {
2537                 ret = find_value_cmp(st->st_atime, param->atime,
2538                                      param->asign, param->exclude_atime,
2539                                      24 * 60 * 60, mds);
2540                 if (ret < 0)
2541                         return ret;
2542                 rc = ret;
2543         }
2544
2545         if (param->mtime) {
2546                 ret = find_value_cmp(st->st_mtime, param->mtime,
2547                                      param->msign, param->exclude_mtime,
2548                                      24 * 60 * 60, mds);
2549                 if (ret < 0)
2550                         return ret;
2551
2552                 /* If the previous check matches, but this one is not yet clear,
2553                  * we should return 0 to do an RPC on OSTs. */
2554                 if (rc == 1)
2555                         rc = ret;
2556         }
2557
2558         if (param->ctime) {
2559                 ret = find_value_cmp(st->st_ctime, param->ctime,
2560                                      param->csign, param->exclude_ctime,
2561                                      24 * 60 * 60, mds);
2562                 if (ret < 0)
2563                         return ret;
2564
2565                 /* If the previous check matches, but this one is not yet clear,
2566                  * we should return 0 to do an RPC on OSTs. */
2567                 if (rc == 1)
2568                         rc = ret;
2569         }
2570
2571         return rc;
2572 }
2573
2574 /**
2575  * Check whether the stripes matches the indexes user provided
2576  *       1   : matched
2577  *       0   : Unmatched
2578  */
2579 static int check_obd_match(struct find_param *param)
2580 {
2581         lstat_t *st = &param->lmd->lmd_st;
2582         struct lov_user_ost_data_v1 *lmm_objects;
2583         int i, j;
2584
2585         if (param->obduuid && param->obdindex == OBD_NOT_FOUND)
2586                 return 0;
2587
2588         if (!S_ISREG(st->st_mode))
2589                 return 0;
2590
2591         /* Only those files should be accepted, which have a
2592          * stripe on the specified OST. */
2593         if (!param->lmd->lmd_lmm.lmm_stripe_count)
2594                 return 0;
2595
2596         if (param->lmd->lmd_lmm.lmm_magic ==
2597             LOV_USER_MAGIC_V3) {
2598                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
2599
2600                 lmm_objects = lmmv3->lmm_objects;
2601         } else if (param->lmd->lmd_lmm.lmm_magic ==  LOV_USER_MAGIC_V1) {
2602                 lmm_objects = param->lmd->lmd_lmm.lmm_objects;
2603         } else {
2604                 llapi_err_noerrno(LLAPI_MSG_ERROR, "%s:Unknown magic: 0x%08X\n",
2605                                   __func__, param->lmd->lmd_lmm.lmm_magic);
2606                 return -EINVAL;
2607         }
2608
2609         for (i = 0; i < param->lmd->lmd_lmm.lmm_stripe_count; i++) {
2610                 for (j = 0; j < param->num_obds; j++) {
2611                         if (param->obdindexes[j] ==
2612                             lmm_objects[i].l_ost_idx) {
2613                                 if (param->exclude_obd)
2614                                         return 0;
2615                                 return 1;
2616                         }
2617                 }
2618         }
2619
2620         if (param->exclude_obd)
2621                 return 1;
2622         return 0;
2623 }
2624
2625 static int check_mdt_match(struct find_param *param)
2626 {
2627         int i;
2628
2629         if (param->mdtuuid && param->mdtindex == OBD_NOT_FOUND)
2630                 return 0;
2631
2632         /* FIXME: For striped dir, we should get stripe information and check */
2633         for (i = 0; i < param->num_mdts; i++) {
2634                 if (param->mdtindexes[i] == param->file_mdtindex)
2635                         if (param->exclude_mdt)
2636                                 return 0;
2637                         return 1;
2638         }
2639
2640         if (param->exclude_mdt)
2641                 return 1;
2642         return 0;
2643 }
2644
2645 /**
2646  * Check whether the obd is active or not, if it is
2647  * not active, just print the object affected by this
2648  * failed target
2649  **/
2650 static int print_failed_tgt(struct find_param *param, char *path, int type)
2651 {
2652         struct obd_statfs stat_buf;
2653         struct obd_uuid uuid_buf;
2654         int ret;
2655
2656         LASSERT(type == LL_STATFS_LOV || type == LL_STATFS_LMV);
2657
2658         memset(&stat_buf, 0, sizeof(struct obd_statfs));
2659         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
2660         ret = llapi_obd_statfs(path, type,
2661                                param->obdindex, &stat_buf,
2662                                &uuid_buf);
2663         if (ret) {
2664                 llapi_printf(LLAPI_MSG_NORMAL,
2665                              "obd_uuid: %s failed %s ",
2666                              param->obduuid->uuid,
2667                              strerror(errno));
2668         }
2669         return ret;
2670 }
2671
2672 static int cb_find_init(char *path, DIR *parent, DIR *dir,
2673                         void *data, struct dirent64 *de)
2674 {
2675         struct find_param *param = (struct find_param *)data;
2676         int decision = 1; /* 1 is accepted; -1 is rejected. */
2677         lstat_t *st = &param->lmd->lmd_st;
2678         int lustre_fs = 1;
2679         int checked_type = 0;
2680         int ret = 0;
2681
2682         LASSERT(parent != NULL || dir != NULL);
2683
2684         if (param->have_fileinfo == 0)
2685                 param->lmd->lmd_lmm.lmm_stripe_count = 0;
2686
2687         /* If a regular expression is presented, make the initial decision */
2688         if (param->pattern != NULL) {
2689                 char *fname = strrchr(path, '/');
2690                 fname = (fname == NULL ? path : fname + 1);
2691                 ret = fnmatch(param->pattern, fname, 0);
2692                 if ((ret == FNM_NOMATCH && !param->exclude_pattern) ||
2693                     (ret == 0 && param->exclude_pattern))
2694                         goto decided;
2695         }
2696
2697         /* See if we can check the file type from the dirent. */
2698         if (param->type && de != NULL && de->d_type != DT_UNKNOWN &&
2699             de->d_type < DT_MAX) {
2700                 checked_type = 1;
2701                 if (llapi_dir_filetype_table[de->d_type] == param->type) {
2702                         if (param->exclude_type)
2703                                 goto decided;
2704                 } else {
2705                         if (!param->exclude_type)
2706                                 goto decided;
2707                 }
2708         }
2709
2710         ret = 0;
2711
2712         /* Request MDS for the stat info if some of these parameters need
2713          * to be compared. */
2714         if (param->obduuid   || param->mdtuuid || param->check_uid ||
2715             param->check_gid || param->check_pool || param->atime   ||
2716             param->ctime     || param->mtime || param->check_size ||
2717             param->check_stripecount || param->check_stripesize ||
2718             param->check_layout)
2719                 decision = 0;
2720
2721         if (param->type && checked_type == 0)
2722                 decision = 0;
2723
2724         if (param->have_fileinfo == 0 && decision == 0) {
2725                 ret = get_lmd_info(path, parent, dir, param->lmd,
2726                                    param->lumlen);
2727                 if (ret == 0) {
2728                         if (dir) {
2729                                 ret = llapi_file_fget_mdtidx(dirfd(dir),
2730                                                      &param->file_mdtindex);
2731                         } else {
2732                                 int fd;
2733                                 lstat_t tmp_st;
2734
2735                                 ret = lstat_f(path, &tmp_st);
2736                                 if (ret) {
2737                                         ret = -errno;
2738                                         llapi_error(LLAPI_MSG_ERROR, ret,
2739                                                     "error: %s: lstat failed"
2740                                                     "for %s", __func__, path);
2741                                         return ret;
2742                                 }
2743                                 if (S_ISREG(tmp_st.st_mode)) {
2744                                         fd = open(path, O_RDONLY);
2745                                         if (fd > 0) {
2746                                                 ret = llapi_file_fget_mdtidx(fd,
2747                                                          &param->file_mdtindex);
2748                                                 close(fd);
2749                                         } else {
2750                                                 ret = fd;
2751                                         }
2752                                 } else {
2753                                         /* For special inode, it assumes to
2754                                          * reside on the same MDT with the
2755                                          * parent */
2756                                         fd = dirfd(parent);
2757                                         ret = llapi_file_fget_mdtidx(fd,
2758                                                         &param->file_mdtindex);
2759                                 }
2760                         }
2761                 }
2762                 if (ret) {
2763                         if (ret == -ENOTTY)
2764                                 lustre_fs = 0;
2765                         if (ret == -ENOENT)
2766                                 goto decided;
2767                         return ret;
2768                 }
2769         }
2770
2771         if (param->type && !checked_type) {
2772                 if ((st->st_mode & S_IFMT) == param->type) {
2773                         if (param->exclude_type)
2774                                 goto decided;
2775                 } else {
2776                         if (!param->exclude_type)
2777                                 goto decided;
2778                 }
2779         }
2780
2781         /* Prepare odb. */
2782         if (param->obduuid || param->mdtuuid) {
2783                 if (lustre_fs && param->got_uuids &&
2784                     param->st_dev != st->st_dev) {
2785                         /* A lustre/lustre mount point is crossed. */
2786                         param->got_uuids = 0;
2787                         param->obds_printed = 0;
2788                         param->obdindex = param->mdtindex = OBD_NOT_FOUND;
2789                 }
2790
2791                 if (lustre_fs && !param->got_uuids) {
2792                         ret = setup_target_indexes(dir ? dir : parent, path,
2793                                                    param);
2794                         if (ret)
2795                                 return ret;
2796
2797                         param->st_dev = st->st_dev;
2798                 } else if (!lustre_fs && param->got_uuids) {
2799                         /* A lustre/non-lustre mount point is crossed. */
2800                         param->got_uuids = 0;
2801                         param->obdindex = param->mdtindex = OBD_NOT_FOUND;
2802                 }
2803         }
2804
2805         if (param->check_stripesize) {
2806                 decision = find_value_cmp(param->lmd->lmd_lmm.lmm_stripe_size,
2807                                           param->stripesize,
2808                                           param->stripesize_sign,
2809                                           param->exclude_stripesize,
2810                                           param->stripesize_units, 0);
2811                 if (decision == -1)
2812                         goto decided;
2813         }
2814
2815         if (param->check_stripecount) {
2816                 decision = find_value_cmp(param->lmd->lmd_lmm.lmm_stripe_count,
2817                                           param->stripecount,
2818                                           param->stripecount_sign,
2819                                           param->exclude_stripecount, 1, 0);
2820                 if (decision == -1)
2821                         goto decided;
2822         }
2823
2824         if (param->check_layout) {
2825                 __u32 found;
2826
2827                 found = (param->lmd->lmd_lmm.lmm_pattern & param->layout);
2828                 if ((param->lmd->lmd_lmm.lmm_pattern == 0xFFFFFFFF) ||
2829                     (found && param->exclude_layout) ||
2830                     (!found && !param->exclude_layout)) {
2831                         decision = -1;
2832                         goto decided;
2833                 }
2834         }
2835
2836         /* If an OBD UUID is specified but none matches, skip this file. */
2837         if ((param->obduuid && param->obdindex == OBD_NOT_FOUND) ||
2838             (param->mdtuuid && param->mdtindex == OBD_NOT_FOUND))
2839                 goto decided;
2840
2841         /* If a OST or MDT UUID is given, and some OST matches,
2842          * check it here. */
2843         if (param->obdindex != OBD_NOT_FOUND ||
2844             param->mdtindex != OBD_NOT_FOUND) {
2845                 if (param->obduuid) {
2846                         if (check_obd_match(param)) {
2847                                 /* If no mdtuuid is given, we are done.
2848                                  * Otherwise, fall through to the mdtuuid
2849                                  * check below. */
2850                                 if (!param->mdtuuid)
2851                                         goto obd_matches;
2852                         } else {
2853                                 goto decided;
2854                         }
2855                 }
2856                 if (param->mdtuuid) {
2857                         if (check_mdt_match(param))
2858                                 goto obd_matches;
2859                         goto decided;
2860                 }
2861         }
2862 obd_matches:
2863         if (param->check_uid) {
2864                 if (st->st_uid == param->uid) {
2865                         if (param->exclude_uid)
2866                                 goto decided;
2867                 } else {
2868                         if (!param->exclude_uid)
2869                                 goto decided;
2870                 }
2871         }
2872
2873         if (param->check_gid) {
2874                 if (st->st_gid == param->gid) {
2875                         if (param->exclude_gid)
2876                                 goto decided;
2877                 } else {
2878                         if (!param->exclude_gid)
2879                                 goto decided;
2880                 }
2881         }
2882
2883         if (param->check_pool) {
2884                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
2885
2886                 /* empty requested pool is taken as no pool search => V1 */
2887                 if (((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V1) &&
2888                      (param->poolname[0] == '\0')) ||
2889                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
2890                      (strncmp(lmmv3->lmm_pool_name,
2891                               param->poolname, LOV_MAXPOOLNAME) == 0)) ||
2892                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
2893                      (strcmp(param->poolname, "*") == 0))) {
2894                         if (param->exclude_pool)
2895                                 goto decided;
2896                 } else {
2897                         if (!param->exclude_pool)
2898                                 goto decided;
2899                 }
2900         }
2901
2902         /* Check the time on mds. */
2903         decision = 1;
2904         if (param->atime || param->ctime || param->mtime) {
2905                 int for_mds;
2906
2907                 for_mds = lustre_fs ? (S_ISREG(st->st_mode) &&
2908                                        param->lmd->lmd_lmm.lmm_stripe_count)
2909                                     : 0;
2910                 decision = find_time_check(st, param, for_mds);
2911                 if (decision == -1)
2912                         goto decided;
2913         }
2914
2915         /* If file still fits the request, ask ost for updated info.
2916            The regular stat is almost of the same speed as some new
2917            'glimpse-size-ioctl'. */
2918
2919         if (param->check_size && S_ISREG(st->st_mode) &&
2920             param->lmd->lmd_lmm.lmm_stripe_count)
2921                 decision = 0;
2922
2923         while (!decision) {
2924                 /* For regular files with the stripe the decision may have not
2925                  * been taken yet if *time or size is to be checked. */
2926                 LASSERT((S_ISREG(st->st_mode) &&
2927                         param->lmd->lmd_lmm.lmm_stripe_count) ||
2928                         param->mdtindex != OBD_NOT_FOUND);
2929
2930                 if (param->obdindex != OBD_NOT_FOUND)
2931                         print_failed_tgt(param, path, LL_STATFS_LOV);
2932
2933                 if (param->mdtindex != OBD_NOT_FOUND)
2934                         print_failed_tgt(param, path, LL_STATFS_LMV);
2935
2936                 if (dir) {
2937                         ret = ioctl(dirfd(dir), IOC_LOV_GETINFO,
2938                                     (void *)param->lmd);
2939                 } else if (parent) {
2940                         ret = ioctl(dirfd(parent), IOC_LOV_GETINFO,
2941                                     (void *)param->lmd);
2942                 }
2943
2944                 if (ret) {
2945                         if (errno == ENOENT) {
2946                                 llapi_error(LLAPI_MSG_ERROR, -ENOENT,
2947                                             "warning: %s: %s does not exist",
2948                                             __func__, path);
2949                                 goto decided;
2950                         } else {
2951                                 ret = -errno;
2952                                 llapi_error(LLAPI_MSG_ERROR, ret,
2953                                             "%s: IOC_LOV_GETINFO on %s failed",
2954                                             __func__, path);
2955                                 return ret;
2956                         }
2957                 }
2958
2959                 /* Check the time on osc. */
2960                 decision = find_time_check(st, param, 0);
2961                 if (decision == -1)
2962                         goto decided;
2963
2964                 break;
2965         }
2966
2967         if (param->check_size)
2968                 decision = find_value_cmp(st->st_size, param->size,
2969                                           param->size_sign, param->exclude_size,
2970                                           param->size_units, 0);
2971
2972         if (decision != -1) {
2973                 llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
2974                 if (param->zeroend)
2975                         llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
2976                 else
2977                         llapi_printf(LLAPI_MSG_NORMAL, "\n");
2978         }
2979
2980 decided:
2981         /* Do not get down anymore? */
2982         if (param->depth == param->maxdepth)
2983                 return 1;
2984
2985         param->depth++;
2986         return 0;
2987 }
2988
2989 int llapi_find(char *path, struct find_param *param)
2990 {
2991         return param_callback(path, cb_find_init, cb_common_fini, param);
2992 }
2993
2994 /*
2995  * Get MDT number that the file/directory inode referenced
2996  * by the open fd resides on.
2997  * Return 0 and mdtidx on success, or -ve errno.
2998  */
2999 int llapi_file_fget_mdtidx(int fd, int *mdtidx)
3000 {
3001         if (ioctl(fd, LL_IOC_GET_MDTIDX, mdtidx) < 0)
3002                 return -errno;
3003         return 0;
3004 }
3005
3006 static int cb_get_mdt_index(char *path, DIR *parent, DIR *d, void *data,
3007                             struct dirent64 *de)
3008 {
3009         struct find_param *param = (struct find_param *)data;
3010         int ret = 0;
3011         int mdtidx;
3012
3013         LASSERT(parent != NULL || d != NULL);
3014
3015         if (d) {
3016                 ret = llapi_file_fget_mdtidx(dirfd(d), &mdtidx);
3017         } else if (parent) {
3018                 int fd;
3019
3020                 fd = open(path, O_RDONLY);
3021                 if (fd > 0) {
3022                         ret = llapi_file_fget_mdtidx(fd, &mdtidx);
3023                         close(fd);
3024                 } else {
3025                         ret = -errno;
3026                 }
3027         }
3028
3029         if (ret) {
3030                 if (ret == -ENODATA) {
3031                         if (!param->obduuid)
3032                                 llapi_printf(LLAPI_MSG_NORMAL,
3033                                              "%s has no stripe info\n", path);
3034                         goto out;
3035                 } else if (ret == -ENOENT) {
3036                         llapi_error(LLAPI_MSG_WARN, ret,
3037                                     "warning: %s: %s does not exist",
3038                                     __func__, path);
3039                         goto out;
3040                 } else if (ret == -ENOTTY) {
3041                         llapi_error(LLAPI_MSG_ERROR, ret,
3042                                     "%s: '%s' not on a Lustre fs?",
3043                                     __func__, path);
3044                 } else {
3045                         llapi_error(LLAPI_MSG_ERROR, ret,
3046                                     "error: %s: LL_IOC_GET_MDTIDX failed for %s",
3047                                     __func__, path);
3048                 }
3049                 return ret;
3050         }
3051
3052         /* The 'LASSERT(parent != NULL || d != NULL);' guarantees
3053          * that either 'd' or 'parent' is not null.
3054          * So in all cases llapi_file_fget_mdtidx() is called,
3055          * thus initializing 'mdtidx'. */
3056         if (param->quiet || !(param->verbose & VERBOSE_DETAIL))
3057                 /* coverity[uninit_use_in_call] */
3058                 llapi_printf(LLAPI_MSG_NORMAL, "%d\n", mdtidx);
3059         else
3060                 /* coverity[uninit_use_in_call] */
3061                 llapi_printf(LLAPI_MSG_NORMAL, "%s\nmdt_index:\t%d\n",
3062                              path, mdtidx);
3063
3064 out:
3065         /* Do not get down anymore? */
3066         if (param->depth == param->maxdepth)
3067                 return 1;
3068
3069         param->depth++;
3070         return 0;
3071 }
3072
3073 static int cb_getstripe(char *path, DIR *parent, DIR *d, void *data,
3074                         struct dirent64 *de)
3075 {
3076         struct find_param *param = (struct find_param *)data;
3077         int ret = 0;
3078
3079         LASSERT(parent != NULL || d != NULL);
3080
3081         if (param->obduuid) {
3082                 param->quiet = 1;
3083                 ret = setup_obd_uuid(d ? d : parent, path, param);
3084                 if (ret)
3085                         return ret;
3086         }
3087
3088         if (d) {
3089                 if (param->get_lmv) {
3090                         ret = cb_get_dirstripe(path, d, param);
3091                 } else {
3092                         ret = ioctl(dirfd(d), LL_IOC_LOV_GETSTRIPE,
3093                                      (void *)&param->lmd->lmd_lmm);
3094                 }
3095
3096         } else if (parent) {
3097                 char *fname = strrchr(path, '/');
3098                 fname = (fname == NULL ? path : fname + 1);
3099
3100                 if (param->get_lmv) {
3101                         llapi_printf(LLAPI_MSG_NORMAL,
3102                                      "%s get dirstripe information for file\n",
3103                                      path);
3104                         goto out;
3105                 }
3106
3107                 strncpy((char *)&param->lmd->lmd_lmm, fname, param->lumlen);
3108
3109                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILESTRIPE,
3110                             (void *)&param->lmd->lmd_lmm);
3111         }
3112
3113         if (ret) {
3114                 if (errno == ENODATA && d != NULL) {
3115                         /* We need to "fake" the "use the default" values
3116                          * since the lmm struct is zeroed out at this point.
3117                          * The magic needs to be set in order to satisfy
3118                          * a check later on in the code path.
3119                          * The object_seq needs to be set for the "(Default)"
3120                          * prefix to be displayed. */
3121                         struct lov_user_md *lmm = &param->lmd->lmd_lmm;
3122                         lmm->lmm_magic = LOV_USER_MAGIC_V1;
3123                         if (!param->raw)
3124                                 ostid_set_seq(&lmm->lmm_oi,
3125                                               FID_SEQ_LOV_DEFAULT);
3126                         lmm->lmm_stripe_count = 0;
3127                         lmm->lmm_stripe_size = 0;
3128                         lmm->lmm_stripe_offset = -1;
3129                         goto dump;
3130                 } else if (errno == ENODATA && parent != NULL) {
3131                         if (!param->obduuid && !param->mdtuuid)
3132                                 llapi_printf(LLAPI_MSG_NORMAL,
3133                                              "%s has no stripe info\n", path);
3134                         goto out;
3135                 } else if (errno == ENOENT) {
3136                         llapi_error(LLAPI_MSG_WARN, -ENOENT,
3137                                     "warning: %s: %s does not exist",
3138                                     __func__, path);
3139                         goto out;
3140                 } else if (errno == ENOTTY) {
3141                         ret = -errno;
3142                         llapi_error(LLAPI_MSG_ERROR, ret,
3143                                     "%s: '%s' not on a Lustre fs?",
3144                                     __func__, path);
3145                 } else {
3146                         ret = -errno;
3147                         llapi_error(LLAPI_MSG_ERROR, ret,
3148                                     "error: %s: %s failed for %s",
3149                                      __func__, d ? "LL_IOC_LOV_GETSTRIPE" :
3150                                     "IOC_MDC_GETFILESTRIPE", path);
3151                 }
3152
3153                 return ret;
3154         }
3155
3156 dump:
3157         if (!(param->verbose & VERBOSE_MDTINDEX))
3158                 llapi_lov_dump_user_lmm(param, path, d ? 1 : 0);
3159
3160 out:
3161         /* Do not get down anymore? */
3162         if (param->depth == param->maxdepth)
3163                 return 1;
3164
3165         param->depth++;
3166         return 0;
3167 }
3168
3169 int llapi_getstripe(char *path, struct find_param *param)
3170 {
3171         return param_callback(path, (param->verbose & VERBOSE_MDTINDEX) ?
3172                               cb_get_mdt_index : cb_getstripe,
3173                               cb_common_fini, param);
3174 }
3175
3176 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
3177                      struct obd_statfs *stat_buf,
3178                      struct obd_uuid *uuid_buf)
3179 {
3180         int fd;
3181         char raw[OBD_MAX_IOCTL_BUFFER] = {'\0'};
3182         char *rawbuf = raw;
3183         struct obd_ioctl_data data = { 0 };
3184         int rc = 0;
3185
3186         data.ioc_inlbuf1 = (char *)&type;
3187         data.ioc_inllen1 = sizeof(__u32);
3188         data.ioc_inlbuf2 = (char *)&index;
3189         data.ioc_inllen2 = sizeof(__u32);
3190         data.ioc_pbuf1 = (char *)stat_buf;
3191         data.ioc_plen1 = sizeof(struct obd_statfs);
3192         data.ioc_pbuf2 = (char *)uuid_buf;
3193         data.ioc_plen2 = sizeof(struct obd_uuid);
3194
3195         rc = obd_ioctl_pack(&data, &rawbuf, sizeof(raw));
3196         if (rc != 0) {
3197                 llapi_error(LLAPI_MSG_ERROR, rc,
3198                             "llapi_obd_statfs: error packing ioctl data");
3199                 return rc;
3200         }
3201
3202         fd = open(path, O_RDONLY);
3203         if (errno == EISDIR)
3204                 fd = open(path, O_DIRECTORY | O_RDONLY);
3205
3206         if (fd < 0) {
3207                 rc = errno ? -errno : -EBADF;
3208                 llapi_error(LLAPI_MSG_ERROR, rc, "error: %s: opening '%s'",
3209                             __func__, path);
3210                 return rc;
3211         }
3212         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
3213         if (rc)
3214                 rc = errno ? -errno : -EINVAL;
3215
3216         close(fd);
3217         return rc;
3218 }
3219
3220 #define MAX_STRING_SIZE 128
3221
3222 int llapi_ping(char *obd_type, char *obd_name)
3223 {
3224         char path[MAX_STRING_SIZE];
3225         char buf[1];
3226         int rc, fd;
3227
3228         snprintf(path, MAX_STRING_SIZE, "/proc/fs/lustre/%s/%s/ping",
3229                  obd_type, obd_name);
3230
3231         fd = open(path, O_WRONLY);
3232         if (fd < 0) {
3233                 rc = -errno;
3234                 llapi_error(LLAPI_MSG_ERROR, rc, "error opening %s", path);
3235                 return rc;
3236         }
3237
3238         /* The purpose is to send a byte as a ping, whatever this byte is. */
3239         /* coverity[uninit_use_in_call] */
3240         rc = write(fd, buf, 1);
3241         if (rc < 0)
3242                 rc = -errno;
3243         close(fd);
3244
3245         if (rc == 1)
3246                 return 0;
3247         return rc;
3248 }
3249
3250 int llapi_target_iterate(int type_num, char **obd_type,
3251                          void *args, llapi_cb_t cb)
3252 {
3253         char buf[MAX_STRING_SIZE];
3254         FILE *fp = fopen(DEVICES_LIST, "r");
3255         int i, rc = 0;
3256
3257         if (fp == NULL) {
3258                 rc = -errno;
3259                 llapi_error(LLAPI_MSG_ERROR, rc, "error: opening "DEVICES_LIST);
3260                 return rc;
3261         }
3262
3263         while (fgets(buf, sizeof(buf), fp) != NULL) {
3264                 char *obd_type_name = NULL;
3265                 char *obd_name = NULL;
3266                 char *obd_uuid = NULL;
3267                 char *bufp = buf;
3268                 struct obd_statfs osfs_buffer;
3269
3270                 while(bufp[0] == ' ')
3271                         ++bufp;
3272
3273                 for(i = 0; i < 3; i++) {
3274                         obd_type_name = strsep(&bufp, " ");
3275                 }
3276                 obd_name = strsep(&bufp, " ");
3277                 obd_uuid = strsep(&bufp, " ");
3278
3279                 memset(&osfs_buffer, 0, sizeof (osfs_buffer));
3280
3281                 for (i = 0; i < type_num; i++) {
3282                         if (strcmp(obd_type_name, obd_type[i]) != 0)
3283                                 continue;
3284
3285                         cb(obd_type_name, obd_name, obd_uuid, args);
3286                 }
3287         }
3288         fclose(fp);
3289         return 0;
3290 }
3291
3292 static void do_target_check(char *obd_type_name, char *obd_name,
3293                             char *obd_uuid, void *args)
3294 {
3295         int rc;
3296
3297         rc = llapi_ping(obd_type_name, obd_name);
3298         if (rc == ENOTCONN) {
3299                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
3300         } else if (rc) {
3301                 llapi_error(LLAPI_MSG_ERROR, rc, "error: check '%s'", obd_name);
3302         } else {
3303                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
3304         }
3305 }
3306
3307 int llapi_target_check(int type_num, char **obd_type, char *dir)
3308 {
3309         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
3310 }
3311
3312 #undef MAX_STRING_SIZE
3313
3314 /* Is this a lustre fs? */
3315 int llapi_is_lustre_mnttype(const char *type)
3316 {
3317         return (strcmp(type, "lustre") == 0 || strcmp(type,"lustre_lite") == 0);
3318 }
3319
3320 /* Is this a lustre client fs? */
3321 int llapi_is_lustre_mnt(struct mntent *mnt)
3322 {
3323         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
3324                 strstr(mnt->mnt_fsname, ":/") != NULL);
3325 }
3326
3327 int llapi_quotacheck(char *mnt, int check_type)
3328 {
3329         DIR *root;
3330         int rc;
3331
3332         root = opendir(mnt);
3333         if (!root) {
3334                 rc = -errno;
3335                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
3336                 return rc;
3337         }
3338
3339         rc = ioctl(dirfd(root), LL_IOC_QUOTACHECK, check_type);
3340         if (rc < 0)
3341                 rc = -errno;
3342
3343         closedir(root);
3344         return rc;
3345 }
3346
3347 int llapi_poll_quotacheck(char *mnt, struct if_quotacheck *qchk)
3348 {
3349         DIR *root;
3350         int poll_intvl = 2;
3351         int rc;
3352
3353         root = opendir(mnt);
3354         if (!root) {
3355                 rc = -errno;
3356                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
3357                 return rc;
3358         }
3359
3360         while (1) {
3361                 rc = ioctl(dirfd(root), LL_IOC_POLL_QUOTACHECK, qchk);
3362                 if (!rc)
3363                         break;
3364                 sleep(poll_intvl);
3365                 if (poll_intvl < 30)
3366                         poll_intvl *= 2;
3367         }
3368
3369         closedir(root);
3370         return 0;
3371 }
3372
3373 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
3374 {
3375         DIR *root;
3376         int rc;
3377
3378         root = opendir(mnt);
3379         if (!root) {
3380                 rc = -errno;
3381                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
3382                 return rc;
3383         }
3384
3385         rc = ioctl(dirfd(root), LL_IOC_QUOTACTL, qctl);
3386         if (rc < 0)
3387                 rc = -errno;
3388
3389         closedir(root);
3390         return rc;
3391 }
3392
3393 static int cb_quotachown(char *path, DIR *parent, DIR *d, void *data,
3394                          struct dirent64 *de)
3395 {
3396         struct find_param *param = (struct find_param *)data;
3397         lstat_t *st;
3398         int rc;
3399
3400         LASSERT(parent != NULL || d != NULL);
3401
3402         rc = get_lmd_info(path, parent, d, param->lmd, param->lumlen);
3403         if (rc) {
3404                 if (rc == -ENODATA) {
3405                         if (!param->obduuid && !param->quiet)
3406                                 llapi_error(LLAPI_MSG_ERROR, -ENODATA,
3407                                           "%s has no stripe info", path);
3408                         rc = 0;
3409                 } else if (rc == -ENOENT) {
3410                         rc = 0;
3411                 }
3412                 return rc;
3413         }
3414
3415         st = &param->lmd->lmd_st;
3416
3417         /* libc chown() will do extra check, and if the real owner is
3418          * the same as the ones to set, it won't fall into kernel, so
3419          * invoke syscall directly. */
3420         rc = syscall(SYS_chown, path, -1, -1);
3421         if (rc)
3422                 llapi_error(LLAPI_MSG_ERROR, errno,
3423                             "error: chown %s", path);
3424
3425         rc = chmod(path, st->st_mode);
3426         if (rc) {
3427                 rc = -errno;
3428                 llapi_error(LLAPI_MSG_ERROR, rc, "error: chmod %s (%hu)",
3429                             path, st->st_mode);
3430         }
3431
3432         return rc;
3433 }
3434
3435 int llapi_quotachown(char *path, int flag)
3436 {
3437         struct find_param param;
3438
3439         memset(&param, 0, sizeof(param));
3440         param.recursive = 1;
3441         param.verbose = 0;
3442         param.quiet = 1;
3443
3444         return param_callback(path, cb_quotachown, NULL, &param);
3445 }
3446
3447 #include <pwd.h>
3448 #include <grp.h>
3449 #include <mntent.h>
3450 #include <sys/wait.h>
3451 #include <errno.h>
3452 #include <ctype.h>
3453
3454 static int rmtacl_notify(int ops)
3455 {
3456         FILE *fp;
3457         struct mntent *mnt;
3458         int found = 0, fd = 0, rc = 0;
3459
3460         fp = setmntent(MOUNTED, "r");
3461         if (fp == NULL) {
3462                 rc = -errno;
3463                 llapi_error(LLAPI_MSG_ERROR, rc,
3464                             "error setmntent(%s)", MOUNTED);
3465                 return rc;
3466         }
3467
3468         while (1) {
3469                 mnt = getmntent(fp);
3470                 if (!mnt)
3471                         break;
3472
3473                 if (!llapi_is_lustre_mnt(mnt))
3474                         continue;
3475
3476                 fd = open(mnt->mnt_dir, O_RDONLY | O_DIRECTORY);
3477                 if (fd < 0) {
3478                         rc = -errno;
3479                         llapi_error(LLAPI_MSG_ERROR, rc,
3480                                     "Can't open '%s'\n", mnt->mnt_dir);
3481                         goto out;
3482                 }
3483
3484                 rc = ioctl(fd, LL_IOC_RMTACL, ops);
3485                 close(fd);
3486                 if (rc < 0) {
3487                         rc = -errno;
3488                         llapi_error(LLAPI_MSG_ERROR, rc,
3489                                     "ioctl RMTACL on '%s' err %d\n",
3490                                     mnt->mnt_dir, rc);
3491                         goto out;
3492                 }
3493
3494                 found++;
3495         }
3496
3497 out:
3498         endmntent(fp);
3499         return ((rc != 0) ? rc : found);
3500 }
3501
3502 static char *next_token(char *p, int div)
3503 {
3504         if (p == NULL)
3505                 return NULL;
3506
3507         if (div)
3508                 while (*p && *p != ':' && !isspace(*p))
3509                         p++;
3510         else
3511                 while (*p == ':' || isspace(*p))
3512                         p++;
3513
3514         return *p ? p : NULL;
3515 }
3516
3517 static int rmtacl_name2id(char *name, int is_user)
3518 {
3519         if (is_user) {
3520                 struct passwd *pw;
3521
3522                 pw = getpwnam(name);
3523                 if (pw == NULL)
3524                         return INVALID_ID;
3525                 else
3526                         return (int)(pw->pw_uid);
3527         } else {
3528                 struct group *gr;
3529
3530                 gr = getgrnam(name);
3531                 if (gr == NULL)
3532                         return INVALID_ID;
3533                 else
3534                         return (int)(gr->gr_gid);
3535         }
3536 }
3537
3538 static int isodigit(int c)
3539 {
3540         return (c >= '0' && c <= '7') ? 1 : 0;
3541 }
3542
3543 /*
3544  * Whether the name is just digits string (uid/gid) already or not.
3545  * Return value:
3546  * 1: str is id
3547  * 0: str is not id
3548  */
3549 static int str_is_id(char *str)
3550 {
3551         if (str == NULL)
3552                 return 0;
3553
3554         if (*str == '0') {
3555                 str++;
3556                 if (*str == 'x' || *str == 'X') { /* for Hex. */
3557                         if (!isxdigit(*(++str)))
3558                                 return 0;
3559
3560                         while (isxdigit(*(++str)));
3561                 } else if (isodigit(*str)) { /* for Oct. */
3562                         while (isodigit(*(++str)));
3563                 }
3564         } else if (isdigit(*str)) { /* for Dec. */
3565                 while (isdigit(*(++str)));
3566         }
3567
3568         return (*str == 0) ? 1 : 0;
3569 }
3570
3571 typedef struct {
3572         char *name;
3573         int   length;
3574         int   is_user;
3575         int   next_token;
3576 } rmtacl_name_t;
3577
3578 #define RMTACL_OPTNAME(name) name, sizeof(name) - 1
3579
3580 static rmtacl_name_t rmtacl_namelist[] = {
3581         { RMTACL_OPTNAME("user:"),            1,      0 },
3582         { RMTACL_OPTNAME("group:"),           0,      0 },
3583         { RMTACL_OPTNAME("default:user:"),    1,      0 },
3584         { RMTACL_OPTNAME("default:group:"),   0,      0 },
3585         /* for --tabular option */
3586         { RMTACL_OPTNAME("user"),             1,      1 },
3587         { RMTACL_OPTNAME("group"),            0,      1 },
3588         { 0 }
3589 };
3590
3591 static int rgetfacl_output(char *str)
3592 {
3593         char *start = NULL, *end = NULL;
3594         int is_user = 0, n, id;
3595         char c;
3596         rmtacl_name_t *rn;
3597
3598         if (str == NULL)
3599                 return -1;
3600
3601         for (rn = rmtacl_namelist; rn->name; rn++) {
3602                 if(strncmp(str, rn->name, rn->length) == 0) {
3603                         if (!rn->next_token)
3604                                 start = str + rn->length;
3605                         else
3606                                 start = next_token(str + rn->length, 0);
3607                         is_user = rn->is_user;
3608                         break;
3609                 }
3610         }
3611
3612         end = next_token(start, 1);
3613         if (end == NULL || start == end) {
3614                 n = printf("%s", str);
3615                 return n;
3616         }
3617
3618         c = *end;
3619         *end = 0;
3620         id = rmtacl_name2id(start, is_user);
3621         if (id == INVALID_ID) {
3622                 if (str_is_id(start)) {
3623                         *end = c;
3624                         n = printf("%s", str);
3625                 } else
3626                         return -1;
3627         } else if ((id == NOBODY_UID && is_user) ||
3628                    (id == NOBODY_GID && !is_user)) {
3629                 *end = c;
3630                 n = printf("%s", str);
3631         } else {
3632                 *end = c;
3633                 *start = 0;
3634                 n = printf("%s%d%s", str, id, end);
3635         }
3636         return n;
3637 }
3638
3639 static int child_status(int status)
3640 {
3641         return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
3642 }
3643
3644 static int do_rmtacl(int argc, char *argv[], int ops, int (output_func)(char *))
3645 {
3646         pid_t pid = 0;
3647         int fd[2], status, rc;
3648         FILE *fp;
3649         char buf[PIPE_BUF];
3650
3651         if (output_func) {
3652                 if (pipe(fd) < 0) {
3653                         rc = -errno;
3654                         llapi_error(LLAPI_MSG_ERROR, rc, "Can't create pipe\n");
3655                         return rc;
3656                 }
3657
3658                 pid = fork();
3659                 if (pid < 0) {
3660                         rc = -errno;
3661                         llapi_error(LLAPI_MSG_ERROR, rc, "Can't fork\n");
3662                         close(fd[0]);
3663                         close(fd[1]);
3664                         return rc;
3665                 } else if (!pid) {
3666                         /* child process redirects its output. */
3667                         close(fd[0]);
3668                         close(1);
3669                         if (dup2(fd[1], 1) < 0) {
3670                                 rc = -errno;
3671                                 llapi_error(LLAPI_MSG_ERROR, rc,
3672                                             "Can't dup2 %d\n", fd[1]);
3673                                 close(fd[1]);
3674                                 return rc;
3675                         }
3676                 } else {
3677                         close(fd[1]);
3678                 }
3679         }
3680
3681         if (!pid) {
3682                 status = rmtacl_notify(ops);
3683                 if (status < 0)
3684                         return -errno;
3685
3686                 exit(execvp(argv[0], argv));
3687         }
3688
3689         /* the following is parent process */
3690         fp = fdopen(fd[0], "r");
3691         if (fp == NULL) {
3692                 rc = -errno;
3693                 llapi_error(LLAPI_MSG_ERROR, rc, "fdopen %d failed\n", fd[0]);
3694                 kill(pid, SIGKILL);
3695                 close(fd[0]);
3696                 return rc;
3697         }
3698
3699         while (fgets(buf, PIPE_BUF, fp) != NULL) {
3700                 if (output_func(buf) < 0)
3701                         fprintf(stderr, "WARNING: unexpected error!\n[%s]\n",
3702                                 buf);
3703         }
3704         fclose(fp);
3705         close(fd[0]);
3706
3707         if (waitpid(pid, &status, 0) < 0) {
3708                 rc = -errno;
3709                 llapi_error(LLAPI_MSG_ERROR, rc, "waitpid %d failed\n", pid);
3710                 return rc;
3711         }
3712
3713         return child_status(status);
3714 }
3715
3716 int llapi_lsetfacl(int argc, char *argv[])
3717 {
3718         return do_rmtacl(argc, argv, RMT_LSETFACL, NULL);
3719 }
3720
3721 int llapi_lgetfacl(int argc, char *argv[])
3722 {
3723         return do_rmtacl(argc, argv, RMT_LGETFACL, NULL);
3724 }
3725
3726 int llapi_rsetfacl(int argc, char *argv[])
3727 {
3728         return do_rmtacl(argc, argv, RMT_RSETFACL, NULL);
3729 }
3730
3731 int llapi_rgetfacl(int argc, char *argv[])
3732 {
3733         return do_rmtacl(argc, argv, RMT_RGETFACL, rgetfacl_output);
3734 }
3735
3736 int llapi_cp(int argc, char *argv[])
3737 {
3738         int rc;
3739
3740         rc = rmtacl_notify(RMT_RSETFACL);
3741         if (rc < 0)
3742                 return rc;
3743
3744         exit(execvp(argv[0], argv));
3745 }
3746
3747 int llapi_ls(int argc, char *argv[])
3748 {
3749         int rc;
3750
3751         rc = rmtacl_notify(RMT_LGETFACL);
3752         if (rc < 0)
3753                 return rc;
3754
3755         exit(execvp(argv[0], argv));
3756 }
3757
3758 /* Print mdtname 'name' into 'buf' using 'format'.  Add -MDT0000 if needed.
3759  * format must have %s%s, buf must be > 16
3760  * Eg: if name = "lustre-MDT0000", "lustre", or "lustre-MDT0000_UUID"
3761  *     then buf = "lustre-MDT0000"
3762  */
3763 static int get_mdtname(char *name, char *format, char *buf)
3764 {
3765         char suffix[]="-MDT0000";
3766         int len = strlen(name);
3767
3768         if ((len > 5) && (strncmp(name + len - 5, "_UUID", 5) == 0)) {
3769                 name[len - 5] = '\0';
3770                 len -= 5;
3771         }
3772
3773         if (len > 8) {
3774                 if ((len <= 16) && strncmp(name + len - 8, "-MDT", 4) == 0) {
3775                         suffix[0] = '\0';
3776                 } else {
3777                         /* Not enough room to add suffix */
3778                         llapi_err_noerrno(LLAPI_MSG_ERROR,
3779                                           "MDT name too long |%s|", name);
3780                         return -EINVAL;
3781                 }
3782         }
3783
3784         return sprintf(buf, format, name, suffix);
3785 }
3786
3787 /** ioctl on filsystem root, with mdtindex sent as data
3788  * \param mdtname path, fsname, or mdtname (lutre-MDT0004)
3789  * \param mdtidxp pointer to integer within data to be filled in with the
3790  *    mdt index (0 if no mdt is specified).  NULL won't be filled.
3791  */
3792 int root_ioctl(const char *mdtname, int opc, void *data, int *mdtidxp,
3793                int want_error)
3794 {
3795         char fsname[20];
3796         char *ptr;
3797         int fd, rc;
3798         long index;
3799
3800         /* Take path, fsname, or MDTname.  Assume MDT0000 in the former cases.
3801          Open root and parse mdt index. */
3802         if (mdtname[0] == '/') {
3803                 index = 0;
3804                 rc = get_root_path(WANT_FD | want_error, NULL, &fd,
3805                                    (char *)mdtname, -1);
3806         } else {
3807                 if (get_mdtname((char *)mdtname, "%s%s", fsname) < 0)
3808                         return -EINVAL;
3809                 ptr = fsname + strlen(fsname) - 8;
3810                 *ptr = '\0';
3811                 index = strtol(ptr + 4, NULL, 10);
3812                 rc = get_root_path(WANT_FD | want_error, fsname, &fd, NULL, -1);
3813         }
3814         if (rc < 0) {
3815                 if (want_error)
3816                         llapi_err_noerrno(LLAPI_MSG_ERROR,
3817                                           "Can't open %s: %d\n", mdtname, rc);
3818                 return rc;
3819         }
3820
3821         if (mdtidxp)
3822                 *mdtidxp = index;
3823
3824         rc = ioctl(fd, opc, data);
3825         if (rc == -1)
3826                 rc = -errno;
3827         else
3828                 rc = 0;
3829         if (rc && want_error)
3830                 llapi_error(LLAPI_MSG_ERROR, rc, "ioctl %d err %d", opc, rc);
3831
3832         close(fd);
3833         return rc;
3834 }
3835
3836 /****** Changelog API ********/
3837
3838 static int changelog_ioctl(const char *mdtname, int opc, int id,
3839                            long long recno, int flags)
3840 {
3841         struct ioc_changelog data;
3842         int *idx;
3843
3844         data.icc_id = id;
3845         data.icc_recno = recno;
3846         data.icc_flags = flags;
3847         idx = (int *)(&data.icc_mdtindex);
3848
3849         return root_ioctl(mdtname, opc, &data, idx, WANT_ERROR);
3850 }
3851
3852 #define CHANGELOG_PRIV_MAGIC 0xCA8E1080
3853 struct changelog_private {
3854         int magic;
3855         int flags;
3856         lustre_kernelcomm kuc;
3857 };
3858
3859 /** Start reading from a changelog
3860  * @param priv Opaque private control structure
3861  * @param flags Start flags (e.g. CHANGELOG_FLAG_BLOCK)
3862  * @param device Report changes recorded on this MDT
3863  * @param startrec Report changes beginning with this record number
3864  * (just call llapi_changelog_fini when done; don't need an endrec)
3865  */
3866 int llapi_changelog_start(void **priv, int flags, const char *device,
3867                           long long startrec)
3868 {
3869         struct changelog_private *cp;
3870         int rc;
3871
3872         /* Set up the receiver control struct */
3873         cp = calloc(1, sizeof(*cp));
3874         if (cp == NULL)
3875                 return -ENOMEM;
3876
3877         cp->magic = CHANGELOG_PRIV_MAGIC;
3878         cp->flags = flags;
3879
3880         /* Set up the receiver */
3881         rc = libcfs_ukuc_start(&cp->kuc, 0 /* no group registration */);
3882         if (rc < 0)
3883                 goto out_free;
3884
3885         *priv = cp;
3886
3887         /* Tell the kernel to start sending */
3888         rc = changelog_ioctl(device, OBD_IOC_CHANGELOG_SEND, cp->kuc.lk_wfd,
3889                              startrec, flags);
3890         /* Only the kernel reference keeps the write side open */
3891         close(cp->kuc.lk_wfd);
3892         cp->kuc.lk_wfd = LK_NOFD;
3893         if (rc < 0) {
3894                 /* frees and clears priv */
3895                 llapi_changelog_fini(priv);
3896                 return rc;
3897         }
3898
3899         return 0;
3900
3901 out_free:
3902         free(cp);
3903         return rc;
3904 }
3905
3906 /** Finish reading from a changelog */
3907 int llapi_changelog_fini(void **priv)
3908 {
3909         struct changelog_private *cp = (struct changelog_private *)*priv;
3910
3911         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
3912                 return -EINVAL;
3913
3914         libcfs_ukuc_stop(&cp->kuc);
3915         free(cp);
3916         *priv = NULL;
3917         return 0;
3918 }
3919
3920 /** Convert a changelog_rec to changelog_ext_rec, in this way client can treat
3921  *  all records in the format of changelog_ext_rec, this can make record
3922  *  analysis simpler.
3923  */
3924 static inline int changelog_extend_rec(struct changelog_ext_rec *ext)
3925 {
3926         if (!CHANGELOG_REC_EXTENDED(ext)) {
3927                 struct changelog_rec *rec = (struct changelog_rec *)ext;
3928
3929                 memmove(ext->cr_name, rec->cr_name, rec->cr_namelen);
3930                 fid_zero(&ext->cr_sfid);
3931                 fid_zero(&ext->cr_spfid);
3932                 return 1;
3933         }
3934
3935         return 0;
3936 }
3937
3938 /** Read the next changelog entry
3939  * @param priv Opaque private control structure
3940  * @param rech Changelog record handle; record will be allocated here
3941  * @return 0 valid message received; rec is set
3942  *         <0 error code
3943  *         1 EOF
3944  */
3945 int llapi_changelog_recv(void *priv, struct changelog_ext_rec **rech)
3946 {
3947         struct changelog_private *cp = (struct changelog_private *)priv;
3948         struct kuc_hdr *kuch;
3949         int rc = 0;
3950
3951         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
3952                 return -EINVAL;
3953         if (rech == NULL)
3954                 return -EINVAL;
3955         kuch = malloc(CR_MAXSIZE + sizeof(*kuch));
3956         if (kuch == NULL)
3957                 return -ENOMEM;
3958
3959 repeat:
3960         rc = libcfs_ukuc_msg_get(&cp->kuc, (char *)kuch,
3961                                  CR_MAXSIZE + sizeof(*kuch),
3962                                  KUC_TRANSPORT_CHANGELOG);
3963         if (rc < 0)
3964                 goto out_free;
3965
3966         if ((kuch->kuc_transport != KUC_TRANSPORT_CHANGELOG) ||
3967             ((kuch->kuc_msgtype != CL_RECORD) &&
3968              (kuch->kuc_msgtype != CL_EOF))) {
3969                 llapi_err_noerrno(LLAPI_MSG_ERROR,
3970                                   "Unknown changelog message type %d:%d\n",
3971                                   kuch->kuc_transport, kuch->kuc_msgtype);
3972                 rc = -EPROTO;
3973                 goto out_free;
3974         }
3975
3976         if (kuch->kuc_msgtype == CL_EOF) {
3977                 if (cp->flags & CHANGELOG_FLAG_FOLLOW) {
3978                         /* Ignore EOFs */
3979                         goto repeat;
3980                 } else {
3981                         rc = 1;
3982                         goto out_free;
3983                 }
3984         }
3985
3986         /* Our message is a changelog_ext_rec.  Use pointer math to skip
3987          * kuch_hdr and point directly to the message payload.
3988          */
3989         *rech = (struct changelog_ext_rec *)(kuch + 1);
3990         changelog_extend_rec(*rech);
3991
3992         return 0;
3993
3994 out_free:
3995         *rech = NULL;
3996         free(kuch);
3997         return rc;
3998 }
3999
4000 /** Release the changelog record when done with it. */
4001 int llapi_changelog_free(struct changelog_ext_rec **rech)
4002 {
4003         if (*rech) {
4004                 /* We allocated memory starting at the kuc_hdr, but passed
4005                  * the consumer a pointer to the payload.
4006                  * Use pointer math to get back to the header.
4007                  */
4008                 struct kuc_hdr *kuch = (struct kuc_hdr *)*rech - 1;
4009                 free(kuch);
4010         }
4011         *rech = NULL;
4012         return 0;
4013 }
4014
4015 int llapi_changelog_clear(const char *mdtname, const char *idstr,
4016                           long long endrec)
4017 {
4018         long id;
4019
4020         if (endrec < 0) {
4021                 llapi_err_noerrno(LLAPI_MSG_ERROR,
4022                                   "can't purge negative records\n");
4023                 return -EINVAL;
4024         }
4025
4026         id = strtol(idstr + strlen(CHANGELOG_USER_PREFIX), NULL, 10);
4027         if ((id == 0) || (strncmp(idstr, CHANGELOG_USER_PREFIX,
4028                                   strlen(CHANGELOG_USER_PREFIX)) != 0)) {
4029                 llapi_err_noerrno(LLAPI_MSG_ERROR,
4030                                   "expecting id of the form '"
4031                                   CHANGELOG_USER_PREFIX
4032                                   "<num>'; got '%s'\n", idstr);
4033                 return -EINVAL;
4034         }
4035
4036         return changelog_ioctl(mdtname, OBD_IOC_CHANGELOG_CLEAR, id, endrec, 0);
4037 }
4038
4039 int llapi_fid2path(const char *device, const char *fidstr, char *buf,
4040                    int buflen, long long *recno, int *linkno)
4041 {
4042         struct lu_fid fid;
4043         struct getinfo_fid2path *gf;
4044         int rc;
4045
4046         while (*fidstr == '[')
4047                 fidstr++;
4048
4049         sscanf(fidstr, SFID, RFID(&fid));
4050         if (!fid_is_sane(&fid)) {
4051                 llapi_err_noerrno(LLAPI_MSG_ERROR,
4052                                   "bad FID format [%s], should be "DFID"\n",
4053                                   fidstr, (__u64)1, 2, 0);
4054                 return -EINVAL;
4055         }
4056
4057         gf = malloc(sizeof(*gf) + buflen);
4058         if (gf == NULL)
4059                 return -ENOMEM;
4060         gf->gf_fid = fid;
4061         gf->gf_recno = *recno;
4062         gf->gf_linkno = *linkno;
4063         gf->gf_pathlen = buflen;
4064
4065         /* Take path or fsname */
4066         rc = root_ioctl(device, OBD_IOC_FID2PATH, gf, NULL, 0);
4067         if (rc) {
4068                 if (rc != -ENOENT)
4069                         llapi_error(LLAPI_MSG_ERROR, rc, "ioctl err %d", rc);
4070         } else {
4071                 memcpy(buf, gf->gf_path, gf->gf_pathlen);
4072                 *recno = gf->gf_recno;
4073                 *linkno = gf->gf_linkno;
4074         }
4075
4076         free(gf);
4077         return rc;
4078 }
4079
4080 static int fid_from_lma(const char *path, const int fd, lustre_fid *fid)
4081 {
4082         char                     buf[512];
4083         struct lustre_mdt_attrs *lma;
4084         int                      rc;
4085
4086         if (path == NULL)
4087                 rc = fgetxattr(fd, XATTR_NAME_LMA, buf, sizeof(buf));
4088         else
4089                 rc = lgetxattr(path, XATTR_NAME_LMA, buf, sizeof(buf));
4090         if (rc < 0)
4091                 return -errno;
4092         lma = (struct lustre_mdt_attrs *)buf;
4093         fid_le_to_cpu(fid, &lma->lma_self_fid);
4094         return 0;
4095 }
4096
4097 int llapi_fd2fid(const int fd, lustre_fid *fid)
4098 {
4099         int rc;
4100
4101         memset(fid, 0, sizeof(*fid));
4102
4103         rc = ioctl(fd, LL_IOC_PATH2FID, fid) < 0 ? -errno : 0;
4104         if (rc == -EINVAL || rc == -ENOTTY)
4105                 rc = fid_from_lma(NULL, fd, fid);
4106
4107         return rc;
4108 }
4109
4110 int llapi_path2fid(const char *path, lustre_fid *fid)
4111 {
4112         int fd, rc;
4113
4114         memset(fid, 0, sizeof(*fid));
4115         fd = open(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
4116         if (fd < 0) {
4117                 if (errno == ELOOP || errno == ENXIO)
4118                         return fid_from_lma(path, -1, fid);
4119                 return -errno;
4120         }
4121
4122         rc = llapi_fd2fid(fd, fid);
4123         if (rc == -EINVAL || rc == -ENOTTY)
4124                 rc = fid_from_lma(path, -1, fid);
4125
4126         close(fd);
4127         return rc;
4128 }
4129
4130 int llapi_get_connect_flags(const char *mnt, __u64 *flags)
4131 {
4132         DIR *root;
4133         int rc;
4134
4135         root = opendir(mnt);
4136         if (!root) {
4137                 rc = -errno;
4138                 llapi_error(LLAPI_MSG_ERROR, rc, "open %s failed", mnt);
4139                 return rc;
4140         }
4141
4142         rc = ioctl(dirfd(root), LL_IOC_GET_CONNECT_FLAGS, flags);
4143         if (rc < 0) {
4144                 rc = -errno;
4145                 llapi_error(LLAPI_MSG_ERROR, rc,
4146                             "ioctl on %s for getting connect flags failed", mnt);
4147         }
4148         closedir(root);
4149         return rc;
4150 }
4151
4152 int llapi_get_version(char *buffer, int buffer_size,
4153                       char **version)
4154 {
4155         int rc;
4156         int fd;
4157         struct obd_ioctl_data *data = (struct obd_ioctl_data *)buffer;
4158
4159         fd = open(OBD_DEV_PATH, O_RDONLY);
4160         if (fd == -1)
4161                 return -errno;
4162
4163         memset(buffer, 0, buffer_size);
4164         data->ioc_version = OBD_IOCTL_VERSION;
4165         data->ioc_inllen1 = buffer_size - cfs_size_round(sizeof(*data));
4166         data->ioc_inlbuf1 = buffer + cfs_size_round(sizeof(*data));
4167         data->ioc_len = obd_ioctl_packlen(data);
4168
4169         rc = ioctl(fd, OBD_GET_VERSION, buffer);
4170         if (rc == -1) {
4171                 rc = -errno;
4172                 close(fd);
4173                 return rc;
4174         }
4175         close(fd);
4176         *version = data->ioc_bulk;
4177         return 0;
4178 }
4179
4180 /**
4181  * Get a 64-bit value representing the version of file data pointed by fd.
4182  *
4183  * Each write or truncate, flushed on OST, will change this value. You can use
4184  * this value to verify if file data was modified. This only checks the file
4185  * data, not metadata.
4186  *
4187  * \param  flags  0: no flush pages, usually used it the process has already
4188  *                  taken locks;
4189  *                LL_DV_RD_FLUSH: OSTs will take LCK_PR to flush dirty pages
4190  *                  from clients;
4191  *                LL_DV_WR_FLUSH: OSTs will take LCK_PW to flush all caching
4192  *                  pages from clients.
4193  *
4194  * \retval 0 on success.
4195  * \retval -errno on error.
4196  */
4197 int llapi_get_data_version(int fd, __u64 *data_version, __u64 flags)
4198 {
4199         int rc;
4200         struct ioc_data_version idv;
4201
4202         idv.idv_flags = flags;
4203
4204         rc = ioctl(fd, LL_IOC_DATA_VERSION, &idv);
4205         if (rc)
4206                 rc = -errno;
4207         else
4208                 *data_version = idv.idv_version;
4209
4210         return rc;
4211 }
4212
4213 /*
4214  * Create a volatile file and open it for write:
4215  * - file is created as a standard file in the directory
4216  * - file does not appears in directory and directory mtime does not change
4217  * - file is removed at close
4218  * - file modes are rw-------, if user wants another one it must use fchmod()
4219  * \param       directory       Directory where the file is created
4220  * \param       idx             MDT index on which the file is created
4221  * \param       flags           Std open flags
4222  *
4223  * \retval      0 on success.
4224  * \retval      -errno on error.
4225  */
4226 int llapi_create_volatile_idx(char *directory, int idx, int mode)
4227 {
4228         char    file_path[PATH_MAX];
4229         char    filename[PATH_MAX];
4230         int     fd;
4231         int     random;
4232         int     rc;
4233
4234         fd = open("/dev/urandom", O_RDONLY);
4235         if (fd < 0) {
4236                 llapi_error(LLAPI_MSG_ERROR, errno,
4237                             "Cannot open /dev/urandom\n");
4238                 return -errno;
4239         }
4240         rc = read(fd, &random, sizeof(random));
4241         close(fd);
4242         if (rc < sizeof(random)) {
4243                 llapi_error(LLAPI_MSG_ERROR, errno,
4244                             "Cannot read %d bytes from /dev/urandom\n",
4245                             sizeof(random));
4246                 return -errno;
4247         }
4248         if (idx == -1)
4249                 snprintf(filename, sizeof(filename),
4250                          LUSTRE_VOLATILE_HDR"::%.4X", random);
4251         else
4252                 snprintf(filename, sizeof(filename),
4253                          LUSTRE_VOLATILE_IDX"%.4X", 0, random);
4254
4255         rc = snprintf(file_path, sizeof(file_path),
4256                       "%s/%s", directory, filename);
4257         if (rc >= sizeof(file_path))
4258                 return -E2BIG;
4259
4260         fd = open(file_path, (O_RDWR | O_CREAT | mode), (S_IRUSR | S_IWUSR));
4261         if (fd < 0) {
4262                 llapi_error(LLAPI_MSG_ERROR, errno,
4263                             "Cannot create volatile file %s in %s\n",
4264                             filename + LUSTRE_VOLATILE_HDR_LEN,
4265                             directory);
4266                 return -errno;
4267         }
4268         return fd;
4269 }
4270
4271 /**
4272  * Swap the layouts between 2 file descriptors
4273  * the 2 files must be open in write
4274  * first fd received the ioctl, second fd is passed as arg
4275  * this is assymetric but avoid use of root path for ioctl
4276  */
4277 int llapi_fswap_layouts(int fd1, int fd2, __u64 dv1, __u64 dv2, __u64 flags)
4278 {
4279         struct lustre_swap_layouts lsl;
4280         int rc;
4281
4282         srandom(time(NULL));
4283         lsl.sl_fd = fd2;
4284         lsl.sl_flags = flags;
4285         lsl.sl_gid = random();
4286         lsl.sl_dv1 = dv1;
4287         lsl.sl_dv2 = dv2;
4288         rc = ioctl(fd1, LL_IOC_LOV_SWAP_LAYOUTS, &lsl);
4289         if (rc)
4290                 rc = -errno;
4291         return rc;
4292 }
4293
4294 /**
4295  * Swap the layouts between 2 files
4296  * the 2 files are open in write
4297  */
4298 int llapi_swap_layouts(const char *path1, const char *path2,
4299                        __u64 dv1, __u64 dv2, __u64 flags)
4300 {
4301         int     fd1, fd2, rc;
4302
4303         fd1 = open(path1, O_WRONLY | O_LOV_DELAY_CREATE);
4304         if (fd1 < 0) {
4305                 llapi_error(LLAPI_MSG_ERROR, -errno,
4306                                 "error: cannot open for write %s",
4307                                 path1);
4308                 return -errno;
4309         }
4310
4311         fd2 = open(path2, O_WRONLY | O_LOV_DELAY_CREATE);
4312         if (fd2 < 0) {
4313                 llapi_error(LLAPI_MSG_ERROR, -errno,
4314                                 "error: cannot open for write %s",
4315                                 path2);
4316                 close(fd1);
4317                 return -errno;
4318         }
4319
4320         rc = llapi_fswap_layouts(fd1, fd2, dv1, dv2, flags);
4321         if (rc < 0)
4322                 llapi_error(LLAPI_MSG_ERROR, rc,
4323                         "error: cannot swap layouts between %s and %s\n",
4324                         path1, path2);
4325
4326         close(fd1);
4327         close(fd2);
4328         return rc;
4329 }