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