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