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