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