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