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