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