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