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