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