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