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