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