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