Whamcloud - gitweb
Branch HEAD
[fs/lustre-release.git] / lustre / utils / liblustreapi.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  *  Copyright (C) 2002 Cluster File Systems, Inc.
5  *   Author: Peter J. Braam <braam@clusterfs.com>
6  *   Author: Phil Schwan <phil@clusterfs.com>
7  *   Author: Robert Read <rread@clusterfs.com>
8  *
9  *   This file is part of Lustre, http://www.lustre.org.
10  *
11  *   Lustre is free software; you can redistribute it and/or
12  *   modify it under the terms of version 2 of the GNU General Public
13  *   License as published by the Free Software Foundation.
14  *
15  *   Lustre is distributed in the hope that it will be useful,
16  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *   GNU General Public License for more details.
19  *
20  *   You should have received a copy of the GNU General Public License
21  *   along with Lustre; if not, write to the Free Software
22  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  *
24  */
25
26 /* for O_DIRECTORY */
27 #define _GNU_SOURCE
28
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <stddef.h>
33 #include <sys/ioctl.h>
34 #include <unistd.h>
35 #include <fcntl.h>
36 #include <errno.h>
37 #include <dirent.h>
38 #include <stdarg.h>
39 #include <sys/stat.h>
40 #include <sys/types.h>
41 #include <sys/syscall.h>
42 #include <fnmatch.h>
43 #ifdef HAVE_ASM_TYPES_H
44 #include <asm/types.h>
45 #endif
46 #ifdef HAVE_LINUX_UNISTD_H
47 #include <linux/unistd.h>
48 #else
49 #include <unistd.h>
50 #endif
51
52 #include <liblustre.h>
53 #include <lnet/lnetctl.h>
54 #include <obd.h>
55 #include <lustre_lib.h>
56 #include <obd_lov.h>
57 #include <lustre/liblustreapi.h>
58
59 static unsigned llapi_dir_filetype_table[] = {
60         [DT_UNKNOWN]= 0,
61         [DT_FIFO]= S_IFIFO,
62         [DT_CHR] = S_IFCHR,
63         [DT_DIR] = S_IFDIR,
64         [DT_BLK] = S_IFBLK,
65         [DT_REG] = S_IFREG,
66         [DT_LNK] = S_IFLNK,
67         [DT_SOCK]= S_IFSOCK,
68 #if defined(DT_DOOR) && defined(S_IFDOOR)
69         [DT_DOOR]= S_IFDOOR,
70 #endif
71 };
72
73 #if defined(DT_DOOR) && defined(S_IFDOOR)
74 static const int DT_MAX = DT_DOOR;
75 #else
76 static const int DT_MAX = DT_SOCK;
77 #endif
78
79 static unsigned llapi_filetype_dir_table[] = {
80         [0]= DT_UNKNOWN,
81         [S_IFIFO]= DT_FIFO,
82         [S_IFCHR] = DT_CHR,
83         [S_IFDIR] = DT_DIR,
84         [S_IFBLK] = DT_BLK,
85         [S_IFREG] = DT_REG,
86         [S_IFLNK] = DT_LNK,
87         [S_IFSOCK]= DT_SOCK,
88 #if defined(DT_DOOR) && defined(S_IFDOOR)
89         [S_IFDOOR]= DT_DOOR,
90 #endif
91 };
92
93 #if defined(DT_DOOR) && defined(S_IFDOOR)
94 static const int S_IFMAX = DT_DOOR;
95 #else
96 static const int S_IFMAX = DT_SOCK;
97 #endif
98
99 /* liblustreapi message level */
100 static int llapi_msg_level = LLAPI_MSG_MAX;
101
102 void llapi_msg_set_level(int level)
103 {
104         /* ensure level is in the good range */
105         if (level < LLAPI_MSG_OFF)
106                 llapi_msg_level = LLAPI_MSG_OFF;
107         else if (level > LLAPI_MSG_MAX)
108                 llapi_msg_level = LLAPI_MSG_MAX;
109         else
110                 llapi_msg_level = level;
111 }
112
113 void llapi_err(int level, char *fmt, ...)
114 {
115         va_list args;
116         int tmp_errno = abs(errno);
117
118         if ((level & LLAPI_MSG_MASK) > llapi_msg_level)
119                 return;
120
121         va_start(args, fmt);
122         vfprintf(stderr, fmt, args);
123         va_end(args);
124
125         if (level & LLAPI_MSG_NO_ERRNO)
126                 fprintf(stderr, "\n");
127         else
128                 fprintf(stderr, ": %s (%d)\n", strerror(tmp_errno), tmp_errno);
129 }
130
131 #define llapi_err_noerrno(level, fmt, a...)                             \
132         llapi_err((level) | LLAPI_MSG_NO_ERRNO, fmt, ## a)
133
134 void llapi_printf(int level, char *fmt, ...)
135 {
136         va_list args;
137
138         if ((level & LLAPI_MSG_MASK) > llapi_msg_level)
139                 return;
140
141         va_start(args, fmt);
142         vfprintf(stdout, fmt, args);
143         va_end(args);
144 }
145
146 int parse_size(char *optarg, unsigned long long *size,
147                unsigned long long *size_units)
148 {
149         char *end;
150
151         *size = strtoul(optarg, &end, 0);
152
153         if (*end != '\0') {
154                 if ((*end == 'b') && *(end+1) == '\0' &&
155                     (*size & (~0ULL << (64 - 9))) == 0) {
156                         *size <<= 9;
157                         *size_units = 1 << 9;
158                 } else if ((*end == 'k' || *end == 'K') &&
159                            *(end+1) == '\0' && (*size &
160                            (~0ULL << (64 - 10))) == 0) {
161                         *size <<= 10;
162                         *size_units = 1 << 10;
163                 } else if ((*end == 'm' || *end == 'M') &&
164                            *(end+1) == '\0' && (*size &
165                            (~0ULL << (64 - 20))) == 0) {
166                         *size <<= 20;
167                         *size_units = 1 << 20;
168                 } else if ((*end == 'g' || *end == 'G') &&
169                            *(end+1) == '\0' && (*size &
170                            (~0ULL << (64 - 30))) == 0) {
171                         *size <<= 30;
172                         *size_units = 1 << 30;
173                 } else if ((*end == 't' || *end == 'T') &&
174                            *(end+1) == '\0' && (*size &
175                            (~0ULL << (64 - 40))) == 0) {
176                         *size <<= 40;
177                         *size_units = 1ULL << 40;
178                 } else if ((*end == 'p' || *end == 'P') &&
179                            *(end+1) == '\0' && (*size &
180                            (~0ULL << (64 - 50))) == 0) {
181                         *size <<= 50;
182                         *size_units = 1ULL << 50;
183                 } else if ((*end == 'e' || *end == 'E') &&
184                            *(end+1) == '\0' && (*size &
185                            (~0ULL << (64 - 60))) == 0) {
186                         *size <<= 60;
187                         *size_units = 1ULL << 60;
188                 } else {
189                         return -1;
190                 }
191         }
192
193         return 0;
194 }
195
196 int llapi_file_open(const char *name, int flags, int mode,
197                     unsigned long stripe_size, int stripe_offset,
198                     int stripe_count, int stripe_pattern)
199 {
200         struct lov_user_md lum = { 0 };
201         int fd, rc = 0;
202         int isdir = 0;
203         int page_size;
204
205         fd = open(name, flags | O_LOV_DELAY_CREATE, mode);
206         if (fd < 0 && errno == EISDIR) {
207                 fd = open(name, O_DIRECTORY | O_RDONLY);
208                 isdir++;
209         }
210
211         if (fd < 0) {
212                 rc = -errno;
213                 llapi_err(LLAPI_MSG_ERROR, "unable to open '%s'", name);
214                 return rc;
215         }
216
217         /* 64 KB is the largest common page size I'm aware of (on ia64), but
218          * check the local page size just in case. */
219         page_size = LOV_MIN_STRIPE_SIZE;
220         if (getpagesize() > page_size) {
221                 page_size = getpagesize();
222                 llapi_err_noerrno(LLAPI_MSG_WARN, 
223                                   "warning: your page size (%u) is "
224                                   "larger than expected (%u)", page_size, 
225                                   LOV_MIN_STRIPE_SIZE);
226         }
227         if (stripe_size < 0 || (stripe_size & (LOV_MIN_STRIPE_SIZE - 1))) {
228                 errno = rc = -EINVAL;
229                 llapi_err(LLAPI_MSG_ERROR, "error: bad stripe_size %lu, "
230                           "must be an even multiple of %d bytes", 
231                           stripe_size, page_size);
232                 goto out;
233         }
234         if (stripe_offset < -1 || stripe_offset > MAX_OBD_DEVICES) {
235                 errno = rc = -EINVAL;
236                 llapi_err(LLAPI_MSG_ERROR, "error: bad stripe offset %d", 
237                           stripe_offset);
238                 goto out;
239         }
240         if (stripe_count < -1 || stripe_count > LOV_MAX_STRIPE_COUNT) {
241                 errno = rc = -EINVAL;
242                 llapi_err(LLAPI_MSG_ERROR, "error: bad stripe count %d", 
243                           stripe_count);
244                 goto out;
245         }
246         if (stripe_count > 0 && (__u64)stripe_size * stripe_count > 0xffffffff){
247                 errno = rc = -EINVAL;
248                 llapi_err(LLAPI_MSG_ERROR, "error: stripe_size %lu * "
249                           "stripe_count %u exceeds 4GB", stripe_size, 
250                           stripe_count);
251                 goto out;
252         }
253
254         /*  Initialize IOCTL striping pattern structure */
255         lum.lmm_magic = LOV_USER_MAGIC;
256         lum.lmm_pattern = stripe_pattern;
257         lum.lmm_stripe_size = stripe_size;
258         lum.lmm_stripe_count = stripe_count;
259         lum.lmm_stripe_offset = stripe_offset;
260
261         if (ioctl(fd, LL_IOC_LOV_SETSTRIPE, &lum)) {
262                 char *errmsg = "stripe already set";
263                 rc = -errno;
264                 if (errno != EEXIST && errno != EALREADY)
265                         errmsg = strerror(errno);
266
267                 llapi_err_noerrno(LLAPI_MSG_ERROR,
268                                   "error on ioctl "LPX64" for '%s' (%d): %s",
269                                   (__u64)LL_IOC_LOV_SETSTRIPE, name, fd, errmsg);
270         }
271 out:
272         if (rc) {
273                 close(fd);
274                 fd = rc;
275         }
276
277         return fd;
278 }
279
280 int llapi_file_create(const char *name, unsigned long stripe_size,
281                       int stripe_offset, int stripe_count, int stripe_pattern)
282 {
283         int fd;
284
285         fd = llapi_file_open(name, O_CREAT | O_WRONLY, 0644, stripe_size,
286                              stripe_offset, stripe_count, stripe_pattern);
287         if (fd < 0)
288                 return fd;
289
290         close(fd);
291         return 0;
292 }
293
294 typedef int (semantic_func_t)(char *path, DIR *parent, DIR *d,
295                               void *data, struct dirent64 *de);
296
297 #define MAX_LOV_UUID_COUNT      max(LOV_MAX_STRIPE_COUNT, 1000)
298 #define OBD_NOT_FOUND           (-1)
299
300 static int common_param_init(struct find_param *param)
301 {
302         param->lumlen = lov_mds_md_size(MAX_LOV_UUID_COUNT);
303         if ((param->lmd = malloc(sizeof(lstat_t) + param->lumlen)) == NULL) {
304                 llapi_err(LLAPI_MSG_ERROR, 
305                           "error: allocation of %d bytes for ioctl",
306                           sizeof(lstat_t) + param->lumlen);
307                 return -ENOMEM;
308         }
309
310         param->got_uuids = 0;
311         param->obdindexes = NULL;
312         param->obdindex = OBD_NOT_FOUND;
313         return 0;
314 }
315
316 static void find_param_fini(struct find_param *param)
317 {
318         if (param->obdindexes)
319                 free(param->obdindexes);
320
321         if (param->lmd)
322                 free(param->lmd);
323 }
324
325 /*
326  * If uuidp is NULL, return the number of available obd uuids.
327  * If uuidp is non-NULL, then it will return the uuids of the obds. If
328  * there are more OSTs then allocated to uuidp, then an error is returned with
329  * the ost_count set to number of available obd uuids.
330  */
331 int llapi_lov_get_uuids(int fd, struct obd_uuid *uuidp, int *ost_count)
332 {
333         char lov_name[sizeof(struct obd_uuid)];
334         char buf[1024];
335         FILE *fp;
336         int rc = 0, index = 0;
337
338         /* Get the lov name */
339         rc = ioctl(fd, OBD_IOC_GETNAME, (void *) lov_name);
340         if (rc) {
341                 rc = errno;
342                 llapi_err(LLAPI_MSG_ERROR, "error: can't get lov name");
343                 return rc;
344         }
345
346         /* Now get the ost uuids from /proc */
347         snprintf(buf, sizeof(buf), "/proc/fs/lustre/lov/%s/target_obd",
348                  lov_name);
349         fp = fopen(buf, "r");
350         if (fp == NULL) {
351                 rc = errno;
352                 llapi_err(LLAPI_MSG_ERROR, "error: opening '%s'", buf);
353                 return rc;
354         }
355
356         while (fgets(buf, sizeof(buf), fp) != NULL) {
357                 if (uuidp && (index < *ost_count)) {
358                         if (sscanf(buf, "%d: %s", &index, uuidp[index].uuid) <2)
359                                 break;
360                 }
361                 index++;
362         }
363
364         fclose(fp);
365
366         if (uuidp && (index >= *ost_count))
367                 return -EOVERFLOW;
368
369         *ost_count = index;
370         return rc;
371 }
372
373 /* Here, param->obduuid points to a single obduuid, the index of which is
374  * returned in param->obdindex */
375 static int setup_obd_uuid(DIR *dir, char *dname, struct find_param *param)
376 {
377         char uuid[sizeof(struct obd_uuid)];
378         char buf[1024];
379         FILE *fp;
380         int rc = 0, index;
381
382         /* Get the lov name */
383         rc = ioctl(dirfd(dir), OBD_IOC_GETNAME, (void *)uuid);
384         if (rc) {
385                 if (errno != ENOTTY) {
386                         rc = errno;
387                         llapi_err(LLAPI_MSG_ERROR, 
388                                   "error: can't get lov name: %s", dname);
389                 } else {
390                         rc = 0;
391                 }
392                 return rc;
393         }
394
395         param->got_uuids = 1;
396
397         /* Now get the ost uuids from /proc */
398         snprintf(buf, sizeof(buf), "/proc/fs/lustre/lov/%s/target_obd",
399                  uuid);
400         fp = fopen(buf, "r");
401         if (fp == NULL) {
402                 rc = errno;
403                 llapi_err(LLAPI_MSG_ERROR, "error: opening '%s'", buf);
404                 return rc;
405         }
406
407         if (!param->obduuid && !param->quiet && !param->obds_printed)
408                 llapi_printf(LLAPI_MSG_NORMAL, "OBDS:\n");
409
410         while (fgets(buf, sizeof(buf), fp) != NULL) {
411                 if (sscanf(buf, "%d: %s", &index, uuid) < 2)
412                         break;
413
414                 if (param->obduuid) {
415                         if (strncmp(param->obduuid->uuid, uuid,
416                                     sizeof(uuid)) == 0) {
417                                 param->obdindex = index;
418                                 break;
419                         }
420                 } else if (!param->quiet && !param->obds_printed) {
421                         /* Print everything */
422                         llapi_printf(LLAPI_MSG_NORMAL, "%s", buf);
423                 }
424         }
425         param->obds_printed = 1;
426
427         fclose(fp);
428
429         if (!param->quiet && param->obduuid &&
430             (param->obdindex == OBD_NOT_FOUND)) {
431                 llapi_err_noerrno(LLAPI_MSG_ERROR, 
432                                   "error: %s: unknown obduuid: %s",
433                                   __FUNCTION__, param->obduuid->uuid);
434                 //rc = EINVAL;
435         }
436
437         return (rc);
438 }
439
440 /* In this case, param->obduuid will be an array of obduuids and
441  * obd index for all these obduuids will be returned in
442  * param->obdindexes */
443 static int setup_obd_indexes(DIR *dir, struct find_param *param)
444 {
445         struct obd_uuid *uuids = NULL;
446         int obdcount = INIT_ALLOC_NUM_OSTS;
447         int ret, obd_valid = 0, obdnum, i;
448
449         uuids = (struct obd_uuid *)malloc(INIT_ALLOC_NUM_OSTS *
450                                           sizeof(struct obd_uuid));
451         if (uuids == NULL)
452                 return -ENOMEM;
453
454 retry_get_uuids:
455         ret = llapi_lov_get_uuids(dirfd(dir), uuids,
456                                   &obdcount);
457         if (ret) {
458                 struct obd_uuid *uuids_temp;
459
460                 if (ret == -EOVERFLOW) {
461                         uuids_temp = realloc(uuids, obdcount *
462                                              sizeof(struct obd_uuid));
463                         if (uuids_temp != NULL)
464                                 goto retry_get_uuids;
465                         else
466                                 ret = -ENOMEM;
467                 }
468
469                 llapi_err(LLAPI_MSG_ERROR, "get ost uuid failed");
470                 return ret;
471         }
472
473         param->obdindexes = malloc(param->num_obds * sizeof(param->obdindex));
474         if (param->obdindexes == NULL)
475                 return -ENOMEM;
476
477         for (obdnum = 0; obdnum < param->num_obds; obdnum++) {
478                 for (i = 0; i <= obdcount; i++) {
479                         if (strcmp((char *)&param->obduuid[obdnum].uuid,
480                                    (char *)&uuids[i]) == 0) {
481                                 param->obdindexes[obdnum] = i;
482                                 obd_valid++;
483                                 break;
484                         }
485                 }
486                 if (i == obdcount)
487                         param->obdindexes[obdnum] = OBD_NOT_FOUND;
488         }
489
490         if (obd_valid == 0)
491                 param->obdindex = OBD_NOT_FOUND;
492         else
493                 param->obdindex = obd_valid;
494
495         param->got_uuids = 1;
496
497         return 0;
498 }
499
500 void lov_dump_user_lmm_v1(struct lov_user_md_v1 *lum, char *path, int is_dir,
501                           int obdindex, int quiet, int header, int body)
502 {
503         int i, obdstripe = 0;
504
505         if (obdindex != OBD_NOT_FOUND) {
506                 for (i = 0; !is_dir && i < lum->lmm_stripe_count; i++) {
507                         if (obdindex == lum->lmm_objects[i].l_ost_idx) {
508                                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
509                                 obdstripe = 1;
510                                 break;
511                         }
512                 }
513         } else if (!quiet) {
514                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
515                 obdstripe = 1;
516         }
517
518         /* if it's a directory */
519         if (is_dir) {
520                 if (obdstripe == 1) {
521                         if (lum->lmm_object_gr == LOV_OBJECT_GROUP_DEFAULT) {
522                                 llapi_printf(LLAPI_MSG_NORMAL, "(Default) ");
523                                 lum->lmm_object_gr = LOV_OBJECT_GROUP_CLEAR;
524                         }
525                         llapi_printf(LLAPI_MSG_NORMAL, 
526                                      "stripe_count: %d stripe_size: %u "
527                                      "stripe_offset: %d\n",
528                                      lum->lmm_stripe_count == (__u16)-1 ? -1 :
529                                      lum->lmm_stripe_count,
530                                      lum->lmm_stripe_size,
531                                      lum->lmm_stripe_offset == (__u16)-1 ? -1 :
532                                      lum->lmm_stripe_offset);
533                 }
534                 return;
535         }
536
537         if (header && (obdstripe == 1)) {
538                 llapi_printf(LLAPI_MSG_NORMAL, 
539                              "lmm_magic:          0x%08X\n",  lum->lmm_magic);
540                 llapi_printf(LLAPI_MSG_NORMAL, 
541                              "lmm_object_gr:      "LPX64"\n", lum->lmm_object_gr);
542                 llapi_printf(LLAPI_MSG_NORMAL, 
543                              "lmm_object_id:      "LPX64"\n", lum->lmm_object_id);
544                 llapi_printf(LLAPI_MSG_NORMAL, 
545                              "lmm_stripe_count:   %u\n", (int)lum->lmm_stripe_count);
546                 llapi_printf(LLAPI_MSG_NORMAL, 
547                              "lmm_stripe_size:    %u\n",      lum->lmm_stripe_size);
548                 llapi_printf(LLAPI_MSG_NORMAL, 
549                              "lmm_stripe_pattern: %x\n",      lum->lmm_pattern);
550         }
551
552         if (body) {
553                 if ((!quiet) && (obdstripe == 1))
554                         llapi_printf(LLAPI_MSG_NORMAL, 
555                                      "\tobdidx\t\t objid\t\tobjid\t\t group\n");
556
557                 for (i = 0; i < lum->lmm_stripe_count; i++) {
558                         int idx = lum->lmm_objects[i].l_ost_idx;
559                         long long oid = lum->lmm_objects[i].l_object_id;
560                         long long gr = lum->lmm_objects[i].l_object_gr;
561                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
562                                 llapi_printf(LLAPI_MSG_NORMAL, 
563                                              "\t%6u\t%14llu\t%#13llx\t%14llu%s\n",
564                                              idx, oid, oid, gr,
565                                              obdindex == idx ? " *" : "");
566                 }
567                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
568         }
569 }
570
571 void lov_dump_user_lmm_join(struct lov_user_md_v1 *lum, char *path,
572                             int is_dir, int obdindex, int quiet,
573                             int header, int body)
574 {
575         struct lov_user_md_join *lumj = (struct lov_user_md_join *)lum;
576         int i, obdstripe = 0;
577
578         if (obdindex != OBD_NOT_FOUND) {
579                 for (i = 0; i < lumj->lmm_stripe_count; i++) {
580                         if (obdindex == lumj->lmm_objects[i].l_ost_idx) {
581                                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
582                                 obdstripe = 1;
583                                 break;
584                         }
585                 }
586         } else if (!quiet) {
587                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
588                 obdstripe = 1;
589         }
590
591         if (header && obdstripe == 1) {
592                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_magic:          0x%08X\n",  
593                              lumj->lmm_magic);
594                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_gr:      "LPX64"\n", 
595                              lumj->lmm_object_gr);
596                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_id:      "LPX64"\n", 
597                              lumj->lmm_object_id);
598                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_stripe_count:   %u\n", 
599                              (int)lumj->lmm_stripe_count);
600                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_stripe_size:    %u\n",
601                              lumj->lmm_stripe_size);
602                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_stripe_pattern: %x\n",
603                              lumj->lmm_pattern);
604                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_extent_count:   %x\n",
605                              lumj->lmm_extent_count);
606         }
607
608         if (body) {
609                 unsigned long long start = -1, end = 0;
610                 if (!quiet && obdstripe == 1)
611                         llapi_printf(LLAPI_MSG_NORMAL, 
612                                      "joined\tobdidx\t\t objid\t\tobjid\t\t group"
613                                      "\t\tstart\t\tend\n");
614                 for (i = 0; i < lumj->lmm_stripe_count; i++) {
615                         int idx = lumj->lmm_objects[i].l_ost_idx;
616                         long long oid = lumj->lmm_objects[i].l_object_id;
617                         long long gr = lumj->lmm_objects[i].l_object_gr;
618                         if (obdindex == OBD_NOT_FOUND || obdindex == idx)
619                                 llapi_printf(LLAPI_MSG_NORMAL, 
620                                              "\t%6u\t%14llu\t%#13llx\t%14llu%s",
621                                              idx, oid, oid, gr,
622                                              obdindex == idx ? " *" : "");
623                         if (start != lumj->lmm_objects[i].l_extent_start ||
624                             end != lumj->lmm_objects[i].l_extent_end) {
625                                 start = lumj->lmm_objects[i].l_extent_start;
626                                 llapi_printf(LLAPI_MSG_NORMAL, "\t%14llu", start);
627                                 end = lumj->lmm_objects[i].l_extent_end;
628                                 if (end == (unsigned long long)-1)
629                                         llapi_printf(LLAPI_MSG_NORMAL, 
630                                                      "\t\tEOF\n");
631                                 else
632                                         llapi_printf(LLAPI_MSG_NORMAL, 
633                                                      "\t\t%llu\n", end);
634                         } else {
635                                 llapi_printf(LLAPI_MSG_NORMAL, "\t\t\t\t\n");
636                         }
637                 }
638                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
639         }
640 }
641
642 void llapi_lov_dump_user_lmm(struct find_param *param,
643                              char *path, int is_dir)
644 {
645         switch(*(__u32 *)&param->lmd->lmd_lmm) { /* lum->lmm_magic */
646         case LOV_USER_MAGIC_V1:
647                 lov_dump_user_lmm_v1(&param->lmd->lmd_lmm, path, is_dir,
648                                       param->obdindex, param->quiet,
649                                       param->verbose,
650                                       (param->verbose || !param->obduuid));
651                 break;
652         case LOV_USER_MAGIC_JOIN:
653                 lov_dump_user_lmm_join(&param->lmd->lmd_lmm, path, is_dir,
654                                        param->obdindex, param->quiet,
655                                        param->verbose,
656                                        (param->verbose || !param->obduuid));
657                 break;
658         default:
659                 llapi_printf(LLAPI_MSG_NORMAL, 
660                              "unknown lmm_magic:  %#x (expecting %#x)\n",
661                        *(__u32 *)&param->lmd->lmd_lmm, LOV_USER_MAGIC_V1);
662                 return;
663         }
664 }
665
666 int llapi_file_get_stripe(const char *path, struct lov_user_md *lum)
667 {
668         const char *fname;
669         char *dname;
670         int fd, rc = 0;
671
672         fname = strrchr(path, '/');
673
674         /* It should be a file (or other non-directory) */
675         if (fname == NULL) {
676                 dname = (char *)malloc(2);
677                 if (dname == NULL)
678                         return ENOMEM;
679                 strcpy(dname, ".");
680                 fname = (char *)path;
681         } else {
682                 dname = (char *)malloc(fname - path + 1);
683                 if (dname == NULL)
684                         return ENOMEM;
685                 strncpy(dname, path, fname - path);
686                 dname[fname - path] = '\0';
687                 fname++;
688         }
689
690         if ((fd = open(dname, O_RDONLY)) == -1) {
691                 rc = errno;
692                 free(dname);
693                 return rc;
694         }
695
696         strcpy((char *)lum, fname);
697         if (ioctl(fd, IOC_MDC_GETFILESTRIPE, (void *)lum) == -1)
698                 rc = errno;
699
700         if (close(fd) == -1 && rc == 0)
701                 rc = errno;
702
703         free(dname);
704
705         return rc;
706 }
707
708 int llapi_file_lookup(int dirfd, const char *name)
709 {
710         struct obd_ioctl_data data = { 0 };
711         char rawbuf[8192];
712         char *buf = rawbuf;
713         int rc;
714
715         if (dirfd < 0 || name == NULL)
716                 return -EINVAL;
717
718         data.ioc_version = OBD_IOCTL_VERSION;
719         data.ioc_len = sizeof(data);
720         data.ioc_inlbuf1 = (char *)name;
721         data.ioc_inllen1 = strlen(name) + 1;
722
723         rc = obd_ioctl_pack(&data, &buf, sizeof(rawbuf));
724         if (rc) {
725                 llapi_err(LLAPI_MSG_ERROR,
726                           "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
727                           name, rc);
728                 return rc;
729         }
730
731         return ioctl(dirfd, IOC_MDC_LOOKUP, buf);
732 }
733
734 int llapi_mds_getfileinfo(char *path, DIR *parent,
735                           struct lov_user_mds_data *lmd)
736 {
737         lstat_t *st = &lmd->lmd_st;
738         char *fname = strrchr(path, '/');
739         int ret = 0;
740
741         if (parent == NULL)
742                 return -EINVAL;
743
744         fname = (fname == NULL ? path : fname + 1);
745         /* retrieve needed file info */
746         strncpy((char *)lmd, fname, lov_mds_md_size(MAX_LOV_UUID_COUNT));
747         ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO, (void *)lmd);
748
749         if (ret) {
750                 if (errno == ENOTTY) {
751                         /* ioctl is not supported, it is not a lustre fs.
752                          * Do the regular lstat(2) instead. */
753                         ret = lstat_f(path, st);
754                         if (ret) {
755                                 llapi_err(LLAPI_MSG_ERROR, 
756                                           "error: %s: lstat failed for %s",
757                                           __FUNCTION__, path);
758                                 return ret;
759                         }
760                 } else if (errno == ENOENT) {
761                         llapi_err(LLAPI_MSG_WARN, 
762                                   "warning: %s: %s does not exist", 
763                                   __FUNCTION__, path);
764                         return -ENOENT;
765                 } else {
766                         llapi_err(LLAPI_MSG_ERROR, 
767                                   "error: %s: IOC_MDC_GETFILEINFO failed for %s",
768                                   __FUNCTION__, path);
769                         return ret;
770                 }
771         }
772
773         return 0;
774 }
775
776 static DIR *opendir_parent(char *path)
777 {
778         DIR *parent;
779         char *fname;
780         char c;
781
782         fname = strrchr(path, '/');
783         if (fname == NULL)
784                 return opendir(".");
785
786         c = fname[1];
787         fname[1] = '\0';
788         parent = opendir(path);
789         fname[1] = c;
790         return parent;
791 }
792
793 static int llapi_semantic_traverse(char *path, int size, DIR *parent,
794                                    semantic_func_t sem_init,
795                                    semantic_func_t sem_fini, void *data,
796                                    struct dirent64 *de)
797 {
798         struct dirent64 *dent;
799         int len, ret;
800         DIR *d, *p = NULL;
801
802         ret = 0;
803         len = strlen(path);
804
805         d = opendir(path);
806         if (!d && errno != ENOTDIR) {
807                 llapi_err(LLAPI_MSG_ERROR, "%s: Failed to open '%s'",
808                           __FUNCTION__, path);
809                 return -EINVAL;
810         } else if (!d && !parent) {
811                 /* ENOTDIR. Open the parent dir. */
812                 p = opendir_parent(path);
813                 if (!p)
814                         GOTO(out, ret = -EINVAL);
815         }
816
817         if (sem_init && (ret = sem_init(path, parent ?: p, d, data, de)))
818                 goto err;
819
820         if (!d)
821                 GOTO(out, ret = 0);
822
823         while ((dent = readdir64(d)) != NULL) {
824                 ((struct find_param *)data)->have_fileinfo = 0;
825
826                 if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
827                         continue;
828
829                 path[len] = 0;
830                 if ((len + dent->d_reclen + 2) > size) {
831                         llapi_err(LLAPI_MSG_ERROR,
832                                   "error: %s: string buffer is too small",
833                                   __FUNCTION__);
834                         break;
835                 }
836                 strcat(path, "/");
837                 strcat(path, dent->d_name);
838
839                 if (dent->d_type == DT_UNKNOWN) {
840                         lstat_t *st = &((struct find_param *)data)->lmd->lmd_st;
841
842                         ret = llapi_mds_getfileinfo(path, d,
843                                              ((struct find_param *)data)->lmd);
844                         if (ret == 0) {
845                                 ((struct find_param *)data)->have_fileinfo = 1;
846                                 dent->d_type = llapi_filetype_dir_table[st->st_mode &
847                                                                         S_IFMT];
848                         }
849                         if (ret == -ENOENT)
850                                 continue;
851                 }
852
853                 switch (dent->d_type) {
854                 case DT_UNKNOWN:
855                         llapi_err(LLAPI_MSG_ERROR, 
856                                   "error: %s: '%s' is UNKNOWN type %d",
857                                   __FUNCTION__, dent->d_name, dent->d_type);
858                         break;
859                 case DT_DIR:
860                         ret = llapi_semantic_traverse(path, size, d, sem_init,
861                                                       sem_fini, data, dent);
862                         if (ret < 0)
863                                 goto out;
864                         break;
865                 default:
866                         ret = 0;
867                         if (sem_init) {
868                                 ret = sem_init(path, d, NULL, data, dent);
869                                 if (ret < 0)
870                                         goto out;
871                         }
872                         if (sem_fini && ret == 0)
873                                 sem_fini(path, d, NULL, data, dent);
874                 }
875         }
876
877 out:
878         path[len] = 0;
879
880         if (sem_fini)
881                 sem_fini(path, parent, d, data, de);
882 err:
883         if (d)
884                 closedir(d);
885         if (p)
886                 closedir(p);
887         return ret;
888 }
889
890 /* Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
891  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
892  *
893  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
894  * The table bolow gives the answers for the specified parameters (value and
895  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
896  * --------------------------------------
897  * 1 | file > limit; sign > 0 | -1 / -1 |
898  * 2 | file = limit; sign > 0 |  ? /  1 |
899  * 3 | file < limit; sign > 0 |  ? /  1 |
900  * 4 | file > limit; sign = 0 | -1 / -1 |
901  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
902  * 6 | file < limit; sign = 0 |  ? / -1 |
903  * 7 | file > limit; sign < 0 |  1 /  1 |
904  * 8 | file = limit; sign < 0 |  ? / -1 |
905  * 9 | file < limit; sign < 0 |  ? / -1 |
906  * --------------------------------------
907  * Note: 5th actually means that the value is within the interval
908  * (limit - margin, limit]. */
909 static int find_value_cmp(unsigned int file, unsigned int limit, int sign,
910                           unsigned long long margin, int mds)
911 {
912         if (sign > 0) {
913                 if (file < limit)
914                         return mds ? 0 : 1;
915         }
916
917         if (sign == 0) {
918                 if (file <= limit && file + margin > limit)
919                         return mds ? 0 : 1;
920                 if (file + margin <= limit)
921                         return mds ? 0 : -1;
922         }
923
924         if (sign < 0) {
925                 if (file > limit)
926                         return 1;
927                 if (mds)
928                         return 0;
929         }
930
931         return -1;
932 }
933
934 /* Check if the file time matches all the given criteria (e.g. --atime +/-N).
935  * Return -1 or 1 if file timestamp does not or does match the given criteria
936  * correspondingly. Return 0 if the MDS time is being checked and there are
937  * attributes on OSTs and it is not yet clear if the timespamp matches.
938  *
939  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
940  * updated timestamps. */
941 static int find_time_check(lstat_t *st, struct find_param *param, int mds)
942 {
943         int ret;
944         int rc = 0;
945
946         /* Check if file is accepted. */
947         if (param->atime) {
948                 ret = find_value_cmp(st->st_atime, param->atime,
949                                      param->asign, 24 * 60 * 60, mds);
950                 if (ret < 0)
951                         return ret;
952                 rc = ret;
953         }
954
955         if (param->mtime) {
956                 ret = find_value_cmp(st->st_mtime, param->mtime,
957                                      param->msign, 24 * 60 * 60, mds);
958                 if (ret < 0)
959                         return ret;
960
961                 /* If the previous check matches, but this one is not yet clear,
962                  * we should return 0 to do an RPC on OSTs. */
963                 if (rc == 1)
964                         rc = ret;
965         }
966
967         if (param->ctime) {
968                 ret = find_value_cmp(st->st_ctime, param->ctime,
969                                      param->csign, 24 * 60 * 60, mds);
970                 if (ret < 0)
971                         return ret;
972
973                 /* If the previous check matches, but this one is not yet clear,
974                  * we should return 0 to do an RPC on OSTs. */
975                 if (rc == 1)
976                         rc = ret;
977         }
978
979         return rc;
980 }
981
982 static int cb_find_init(char *path, DIR *parent, DIR *dir,
983                         void *data, struct dirent64 *de)
984 {
985         struct find_param *param = (struct find_param *)data;
986         int decision = 1; /* 1 is accepted; -1 is rejected. */
987         lstat_t *st = &param->lmd->lmd_st;
988         int lustre_fs = 1;
989         int checked_type = 0;
990         int ret = 0;
991
992         LASSERT(parent != NULL || dir != NULL);
993
994         param->lmd->lmd_lmm.lmm_stripe_count = 0;
995
996         /* If a regular expression is presented, make the initial decision */
997         if (param->pattern != NULL) {
998                 char *fname = strrchr(path, '/');
999                 fname = (fname == NULL ? path : fname + 1);
1000                 ret = fnmatch(param->pattern, fname, 0);
1001                 if ((ret == FNM_NOMATCH && !param->exclude_pattern) ||
1002                     (ret == 0 && param->exclude_pattern))
1003                         goto decided;
1004         }
1005
1006         /* See if we can check the file type from the dirent. */
1007         if (param->type && de != NULL && de->d_type != DT_UNKNOWN &&
1008             de->d_type < DT_MAX) {
1009                 checked_type = 1;
1010                 if (llapi_dir_filetype_table[de->d_type] == param->type) {
1011                         if (param->exclude_type)
1012                                 goto decided;
1013                 } else {
1014                         if (!param->exclude_type)
1015                                 goto decided;
1016                 }
1017         }
1018
1019
1020         /* If a time or OST should be checked, the decision is not taken yet. */
1021         if (param->atime || param->ctime || param->mtime || param->obduuid ||
1022             param->size)
1023                 decision = 0;
1024
1025         ret = 0;
1026         /* Request MDS for the stat info. */
1027         if (param->have_fileinfo == 0) {
1028                 if (dir) {
1029                         /* retrieve needed file info */
1030                         ret = ioctl(dirfd(dir), LL_IOC_MDC_GETINFO,
1031                                     (void *)param->lmd);
1032                 } else {
1033                         char *fname = strrchr(path, '/');
1034                         fname = (fname == NULL ? path : fname + 1);
1035
1036                         /* retrieve needed file info */
1037                         strncpy((char *)param->lmd, fname, param->lumlen);
1038                         ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
1039                                    (void *)param->lmd);
1040                 }
1041         }
1042
1043         if (ret) {
1044                 if (errno == ENOTTY) {
1045                         /* ioctl is not supported, it is not a lustre fs.
1046                          * Do the regular lstat(2) instead. */
1047                         lustre_fs = 0;
1048                         ret = lstat_f(path, st);
1049                         if (ret) {
1050                                 llapi_err(LLAPI_MSG_ERROR, 
1051                                           "error: %s: lstat failed for %s",
1052                                           __FUNCTION__, path);
1053                                 return ret;
1054                         }
1055                 } else if (errno == ENOENT) {
1056                         llapi_err(LLAPI_MSG_WARN, 
1057                                   "warning: %s: %s does not exist",
1058                                   __FUNCTION__, path);
1059                         goto decided;
1060                 } else {
1061                         llapi_err(LLAPI_MSG_ERROR, "error: %s: %s failed for %s",
1062                                   __FUNCTION__, dir ? "LL_IOC_MDC_GETINFO" :
1063                                   "IOC_MDC_GETFILEINFO", path);
1064                         return ret;
1065                 }
1066         }
1067
1068         if (param->type && !checked_type) {
1069                 if ((st->st_mode & S_IFMT) == param->type) {
1070                         if (param->exclude_type)
1071                                 goto decided;
1072                 } else {
1073                         if (!param->exclude_type)
1074                                 goto decided;
1075                 }
1076         }
1077
1078         /* Prepare odb. */
1079         if (param->obduuid) {
1080                 if (lustre_fs && param->got_uuids &&
1081                     param->st_dev != st->st_dev) {
1082                         /* A lustre/lustre mount point is crossed. */
1083                         param->got_uuids = 0;
1084                         param->obds_printed = 0;
1085                         param->obdindex = OBD_NOT_FOUND;
1086                 }
1087
1088                 if (lustre_fs && !param->got_uuids) {
1089                         ret = setup_obd_indexes(dir ? dir : parent, param);
1090                         if (ret)
1091                                 return ret;
1092
1093                         param->st_dev = st->st_dev;
1094                 } else if (!lustre_fs && param->got_uuids) {
1095                         /* A lustre/non-lustre mount point is crossed. */
1096                         param->got_uuids = 0;
1097                         param->obdindex = OBD_NOT_FOUND;
1098                 }
1099         }
1100
1101         /* If an OBD UUID is specified but no one matches, skip this file. */
1102         if (param->obduuid && param->obdindex == OBD_NOT_FOUND)
1103                 goto decided;
1104
1105         /* If a OST UUID is given, and some OST matches, check it here. */
1106         if (param->obdindex != OBD_NOT_FOUND) {
1107                 if (!S_ISREG(st->st_mode))
1108                         goto decided;
1109
1110                 /* Only those files should be accepted, which have a
1111                  * stripe on the specified OST. */
1112                 if (!param->lmd->lmd_lmm.lmm_stripe_count) {
1113                         goto decided;
1114                 } else {
1115                         int i, j;
1116                         for (i = 0;
1117                              i < param->lmd->lmd_lmm.lmm_stripe_count; i++) {
1118                                 for (j = 0; j < param->num_obds; j++) {
1119                                         if (param->obdindexes[j] ==
1120                                             param->lmd->lmd_lmm.lmm_objects[i].l_ost_idx)
1121                                                 goto obd_matches;
1122                                 }
1123                         }
1124
1125                         if (i == param->lmd->lmd_lmm.lmm_stripe_count)
1126                                 goto decided;
1127                 }
1128         }
1129
1130         /* Check the time on mds. */
1131         if (!decision) {
1132                 int for_mds;
1133
1134                 for_mds = lustre_fs ? (S_ISREG(st->st_mode) &&
1135                                        param->lmd->lmd_lmm.lmm_stripe_count)
1136                                     : 0;
1137                 decision = find_time_check(st, param, for_mds);
1138         }
1139
1140 obd_matches:
1141         /* If file still fits the request, ask osd for updated info.
1142            The regulat stat is almost of the same speed as some new
1143            'glimpse-size-ioctl'. */
1144         if (!decision && S_ISREG(st->st_mode) &&
1145             (param->lmd->lmd_lmm.lmm_stripe_count || param->size)) {
1146                 if (param->obdindex != OBD_NOT_FOUND) {
1147                         /* Check whether the obd is active or not, if it is
1148                          * not active, just print the object affected by this
1149                          * failed ost 
1150                          * */
1151                         struct obd_statfs stat_buf;
1152                         struct obd_uuid uuid_buf;
1153
1154                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
1155                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1156                         ret = llapi_obd_statfs(path, LL_STATFS_LOV,
1157                                                param->obdindex, &stat_buf, 
1158                                                &uuid_buf);
1159                         if (ret) {
1160                                 if (ret == -ENODATA || ret == -ENODEV 
1161                                     || ret == -EIO)
1162                                         errno = EIO;
1163                                 llapi_printf(LLAPI_MSG_NORMAL, 
1164                                              "obd_uuid: %s failed %s ",
1165                                              param->obduuid->uuid, 
1166                                              strerror(errno));
1167                                 goto print_path;
1168                         }
1169                 }
1170                 if (dir) {
1171                         ret = ioctl(dirfd(dir), IOC_LOV_GETINFO,
1172                                     (void *)param->lmd);
1173                 } else if (parent) {
1174                         ret = ioctl(dirfd(parent), IOC_LOV_GETINFO,
1175                                     (void *)param->lmd);
1176                 }
1177
1178                 if (ret) {
1179                         if (errno == ENOENT) {
1180                                 llapi_err(LLAPI_MSG_ERROR, 
1181                                           "warning: %s: %s does not exist",
1182                                           __FUNCTION__, path);
1183                                 goto decided;
1184                         } else {
1185                                 llapi_err(LLAPI_MSG_ERROR, 
1186                                           "%s: IOC_LOV_GETINFO on %s failed",
1187                                           __FUNCTION__, path);
1188                                 return ret;
1189                         }
1190                 }
1191
1192                 /* Check the time on osc. */
1193                 decision = find_time_check(st, param, 0);
1194                 if (decision == -1)
1195                         goto decided;
1196         }
1197
1198         if (param->size)
1199                 decision = find_value_cmp(st->st_size, param->size,
1200                                           param->size_sign, param->size_units,
1201                                           0);
1202
1203 print_path:
1204         if (decision != -1) {
1205                 llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
1206                 if (param->zeroend)
1207                         llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
1208                 else
1209                         llapi_printf(LLAPI_MSG_NORMAL, "\n");
1210         }
1211
1212 decided:
1213         /* Do not get down anymore? */
1214         if (param->depth == param->maxdepth)
1215                 return 1;
1216
1217         param->depth++;
1218         return 0;
1219 }
1220
1221 static int cb_common_fini(char *path, DIR *parent, DIR *d, void *data,
1222                           struct dirent64 *de)
1223 {
1224         struct find_param *param = (struct find_param *)data;
1225         param->depth--;
1226         return 0;
1227 }
1228
1229 int llapi_find(char *path, struct find_param *param)
1230 {
1231         char *buf;
1232         int ret, len = strlen(path);
1233
1234         if (len > PATH_MAX) {
1235                 llapi_err(LLAPI_MSG_ERROR, "%s: Path name '%s' is too long",
1236                           __FUNCTION__, path);
1237                 return -EINVAL;
1238         }
1239
1240         buf = (char *)malloc(PATH_MAX + 1);
1241         if (!buf)
1242                 return -ENOMEM;
1243
1244         ret = common_param_init(param);
1245         if (ret) {
1246                 free(buf);
1247                 return ret;
1248         }
1249
1250         param->depth = 0;
1251
1252         strncpy(buf, path, PATH_MAX + 1);
1253         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, cb_find_init,
1254                                       cb_common_fini, param, NULL);
1255
1256         find_param_fini(param);
1257         free(buf);
1258         return ret < 0 ? ret : 0;
1259 }
1260
1261 static int cb_getstripe(char *path, DIR *parent, DIR *d, void *data,
1262                         struct dirent64 *de)
1263 {
1264         struct find_param *param = (struct find_param *)data;
1265         int ret = 0;
1266
1267         LASSERT(parent != NULL || d != NULL);
1268
1269         /* Prepare odb. */
1270         if (!param->got_uuids) {
1271                 ret = setup_obd_uuid(d ? d : parent, path, param);
1272                 if (ret)
1273                         return ret;
1274         }
1275
1276         if (d) {
1277                 ret = ioctl(dirfd(d), LL_IOC_LOV_GETSTRIPE,
1278                             (void *)&param->lmd->lmd_lmm);
1279         } else if (parent) {
1280                 char *fname = strrchr(path, '/');
1281                 fname = (fname == NULL ? path : fname + 1);
1282
1283                 strncpy((char *)&param->lmd->lmd_lmm, fname, param->lumlen);
1284                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILESTRIPE,
1285                             (void *)&param->lmd->lmd_lmm);
1286         }
1287
1288         if (ret) {
1289                 if (errno == ENODATA) {
1290                         if (!param->obduuid && !param->quiet)
1291                                 llapi_printf(LLAPI_MSG_NORMAL, 
1292                                              "%s has no stripe info\n", path);
1293                         goto out;
1294                 } else if (errno == ENOTTY) {
1295                         llapi_err(LLAPI_MSG_ERROR, 
1296                                   "%s: '%s' not on a Lustre fs?",
1297                                   __FUNCTION__, path);
1298                 } else if (errno == ENOENT) {
1299                         llapi_err(LLAPI_MSG_WARN, 
1300                                   "warning: %s: %s does not exist",
1301                                   __FUNCTION__, path);
1302                         goto out;
1303                 } else {
1304                         llapi_err(LLAPI_MSG_ERROR, 
1305                                   "error: %s: %s failed for %s",
1306                                    __FUNCTION__, d ? "LL_IOC_LOV_GETSTRIPE" :
1307                                   "IOC_MDC_GETFILESTRIPE", path);
1308                 }
1309
1310                 return ret;
1311         }
1312
1313         llapi_lov_dump_user_lmm(param, path, d ? 1 : 0);
1314 out:
1315         /* Do not get down anymore? */
1316         if (param->depth == param->maxdepth)
1317                 return 1;
1318
1319         param->depth++;
1320         return 0;
1321 }
1322
1323 int llapi_getstripe(char *path, struct find_param *param)
1324 {
1325         char *buf;
1326         int ret = 0, len = strlen(path);
1327
1328         if (len > PATH_MAX) {
1329                 llapi_err(LLAPI_MSG_ERROR, 
1330                           "%s: Path name '%s' is too long",
1331                           __FUNCTION__, path);
1332                 return -EINVAL;
1333         }
1334
1335         buf = (char *)malloc(PATH_MAX + 1);
1336         if (!buf)
1337                 return -ENOMEM;
1338
1339         ret = common_param_init(param);
1340         if (ret) {
1341                 free(buf);
1342                 return ret;
1343         }
1344
1345         param->depth = 0;
1346
1347         strncpy(buf, path, PATH_MAX + 1);
1348         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, cb_getstripe,
1349                                       cb_common_fini, param, NULL);
1350         find_param_fini(param);
1351         free(buf);
1352         return ret < 0 ? ret : 0;
1353 }
1354
1355 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
1356                      struct obd_statfs *stat_buf,
1357                      struct obd_uuid *uuid_buf)
1358 {
1359         int fd;
1360         char raw[OBD_MAX_IOCTL_BUFFER] = {'\0'};
1361         char *rawbuf = raw;
1362         struct obd_ioctl_data data = { 0 };
1363         int rc = 0;
1364
1365         data.ioc_inlbuf1 = (char *)&type;
1366         data.ioc_inllen1 = sizeof(__u32);
1367         data.ioc_inlbuf2 = (char *)&index;
1368         data.ioc_inllen2 = sizeof(__u32);
1369         data.ioc_pbuf1 = (char *)stat_buf;
1370         data.ioc_plen1 = sizeof(struct obd_statfs);
1371         data.ioc_pbuf2 = (char *)uuid_buf;
1372         data.ioc_plen2 = sizeof(struct obd_uuid);
1373
1374         if ((rc = obd_ioctl_pack(&data, &rawbuf, sizeof(raw))) != 0) {
1375                 llapi_err(LLAPI_MSG_ERROR, 
1376                           "llapi_obd_statfs: error packing ioctl data");
1377                 return rc;
1378         }
1379
1380         fd = open(path, O_RDONLY);
1381         if (errno == EISDIR)
1382                 fd = open(path, O_DIRECTORY | O_RDONLY);
1383
1384         if (fd < 0) {
1385                 rc = errno ? -errno : -EBADF;
1386                 llapi_err(LLAPI_MSG_ERROR, "error: %s: opening '%s'", 
1387                           __FUNCTION__, path);
1388                 return rc;
1389         }
1390         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
1391         if (rc)
1392                 rc = errno ? -errno : -EINVAL;
1393
1394         close(fd);
1395         return rc;
1396 }
1397
1398 #define MAX_STRING_SIZE 128
1399 #define DEVICES_LIST "/proc/fs/lustre/devices"
1400
1401 int llapi_ping(char *obd_type, char *obd_name)
1402 {
1403         char path[MAX_STRING_SIZE];
1404         char buf[1];
1405         int rc, fd;
1406
1407         snprintf(path, MAX_STRING_SIZE, "/proc/fs/lustre/%s/%s/ping",
1408                  obd_type, obd_name);
1409
1410         fd = open(path, O_WRONLY);
1411         if (fd < 0) {
1412                 rc = errno;
1413                 llapi_err(LLAPI_MSG_ERROR, "error opening %s", path);
1414                 return rc;
1415         }
1416
1417         rc = write(fd, buf, 1);
1418         close(fd);
1419
1420         if (rc == 1)
1421                 return 0;
1422         return rc;
1423 }
1424
1425 int llapi_target_iterate(int type_num, char **obd_type, void *args, llapi_cb_t cb)
1426 {
1427         char buf[MAX_STRING_SIZE];
1428         FILE *fp = fopen(DEVICES_LIST, "r");
1429         int i, rc = 0;
1430
1431         if (fp == NULL) {
1432                 rc = errno;
1433                 llapi_err(LLAPI_MSG_ERROR, "error: opening "DEVICES_LIST);
1434                 return rc;
1435         }
1436
1437         while (fgets(buf, sizeof(buf), fp) != NULL) {
1438                 char *obd_type_name = NULL;
1439                 char *obd_name = NULL;
1440                 char *obd_uuid = NULL;
1441                 char rawbuf[OBD_MAX_IOCTL_BUFFER];
1442                 char *bufl = rawbuf;
1443                 char *bufp = buf;
1444                 struct obd_ioctl_data datal = { 0, };
1445                 struct obd_statfs osfs_buffer;
1446
1447                 while(bufp[0] == ' ')
1448                         ++bufp;
1449
1450                 for(i = 0; i < 3; i++) {
1451                         obd_type_name = strsep(&bufp, " ");
1452                 }
1453                 obd_name = strsep(&bufp, " ");
1454                 obd_uuid = strsep(&bufp, " ");
1455
1456                 memset(&osfs_buffer, 0, sizeof (osfs_buffer));
1457
1458                 memset(bufl, 0, sizeof(rawbuf));
1459                 datal.ioc_pbuf1 = (char *)&osfs_buffer;
1460                 datal.ioc_plen1 = sizeof(osfs_buffer);
1461
1462                 for (i = 0; i < type_num; i++) {
1463                         if (strcmp(obd_type_name, obd_type[i]) != 0)
1464                                 continue;
1465
1466                         cb(obd_type_name, obd_name, obd_uuid, args);
1467                 }
1468         }
1469         fclose(fp);
1470         return rc;
1471 }
1472
1473 static void do_target_check(char *obd_type_name, char *obd_name,
1474                             char *obd_uuid, void *args)
1475 {
1476         int rc;
1477
1478         rc = llapi_ping(obd_type_name, obd_name);
1479         if (rc) {
1480                 llapi_err(LLAPI_MSG_ERROR, "error: check '%s'", obd_name);
1481         } else {
1482                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
1483         }
1484 }
1485
1486 int llapi_target_check(int type_num, char **obd_type, char *dir)
1487 {
1488         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
1489 }
1490
1491 #undef MAX_STRING_SIZE
1492
1493 int llapi_catinfo(char *dir, char *keyword, char *node_name)
1494 {
1495         char raw[OBD_MAX_IOCTL_BUFFER];
1496         char out[LLOG_CHUNK_SIZE];
1497         char *buf = raw;
1498         struct obd_ioctl_data data = { 0 };
1499         char key[30];
1500         DIR *root;
1501         int rc;
1502
1503         sprintf(key, "%s", keyword);
1504         memset(raw, 0, sizeof(raw));
1505         memset(out, 0, sizeof(out));
1506         data.ioc_inlbuf1 = key;
1507         data.ioc_inllen1 = strlen(key) + 1;
1508         if (node_name) {
1509                 data.ioc_inlbuf2 = node_name;
1510                 data.ioc_inllen2 = strlen(node_name) + 1;
1511         }
1512         data.ioc_pbuf1 = out;
1513         data.ioc_plen1 = sizeof(out);
1514         rc = obd_ioctl_pack(&data, &buf, sizeof(raw));
1515         if (rc)
1516                 return rc;
1517
1518         root = opendir(dir);
1519         if (root == NULL) {
1520                 rc = errno;
1521                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", dir);
1522                 return rc;
1523         }
1524
1525         rc = ioctl(dirfd(root), OBD_IOC_LLOG_CATINFO, buf);
1526         if (rc)
1527                 llapi_err(LLAPI_MSG_ERROR, "ioctl OBD_IOC_CATINFO failed");
1528         else
1529                 llapi_printf(LLAPI_MSG_NORMAL, "%s", data.ioc_pbuf1);
1530
1531         closedir(root);
1532         return rc;
1533 }
1534
1535 /* Is this a lustre fs? */
1536 int llapi_is_lustre_mnttype(const char *type)
1537 {
1538         return (strcmp(type, "lustre") == 0 || strcmp(type,"lustre_lite") == 0);
1539 }
1540
1541 /* Is this a lustre client fs? */
1542 int llapi_is_lustre_mnt(struct mntent *mnt)
1543 {
1544         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
1545                 strstr(mnt->mnt_fsname, ":/") != NULL);
1546 }
1547
1548 int llapi_quotacheck(char *mnt, int check_type)
1549 {
1550         DIR *root;
1551         int rc;
1552
1553         root = opendir(mnt);
1554         if (!root) {
1555                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
1556                 return -1;
1557         }
1558
1559         rc = ioctl(dirfd(root), LL_IOC_QUOTACHECK, check_type);
1560
1561         closedir(root);
1562         return rc;
1563 }
1564
1565 int llapi_poll_quotacheck(char *mnt, struct if_quotacheck *qchk)
1566 {
1567         DIR *root;
1568         int poll_intvl = 2;
1569         int rc;
1570
1571         root = opendir(mnt);
1572         if (!root) {
1573                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
1574                 return -1;
1575         }
1576
1577         while (1) {
1578                 rc = ioctl(dirfd(root), LL_IOC_POLL_QUOTACHECK, qchk);
1579                 if (!rc)
1580                         break;
1581                 sleep(poll_intvl);
1582                 if (poll_intvl < 30)
1583                         poll_intvl *= 2;
1584         }
1585
1586         closedir(root);
1587         return rc;
1588 }
1589
1590 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
1591 {
1592         DIR *root;
1593         int rc;
1594
1595         root = opendir(mnt);
1596         if (!root) {
1597                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
1598                 return -1;
1599         }
1600
1601         rc = ioctl(dirfd(root), LL_IOC_QUOTACTL, qctl);
1602
1603         closedir(root);
1604         return rc;
1605 }
1606
1607 static int cb_quotachown(char *path, DIR *parent, DIR *d, void *data,
1608                          struct dirent64 *de)
1609 {
1610         struct find_param *param = (struct find_param *)data;
1611         lstat_t *st;
1612         int rc;
1613
1614         LASSERT(parent != NULL || d != NULL);
1615
1616         if (d) {
1617                 rc = ioctl(dirfd(d), LL_IOC_MDC_GETINFO,
1618                            (void *)param->lmd);
1619         } else if (parent) {
1620                 char *fname = strrchr(path, '/');
1621                 fname = (fname == NULL ? path : fname + 1);
1622
1623                 strncpy((char *)param->lmd, fname, param->lumlen);
1624                 rc = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
1625                            (void *)param->lmd);
1626         } else {
1627                 return 0;
1628         }
1629
1630         if (rc) {
1631                 if (errno == ENODATA) {
1632                         if (!param->obduuid && !param->quiet)
1633                                 llapi_err(LLAPI_MSG_ERROR, 
1634                                           "%s has no stripe info", path);
1635                         rc = 0;
1636                 } else if (errno == ENOENT) {
1637                         llapi_err(LLAPI_MSG_ERROR, 
1638                                   "warning: %s: %s does not exist",
1639                                   __FUNCTION__, path);
1640                         rc = 0;
1641                 } else if (errno != EISDIR) {
1642                         rc = errno;
1643                         llapi_err(LLAPI_MSG_ERROR, "%s ioctl failed for %s.",
1644                                   d ? "LL_IOC_MDC_GETINFO" :
1645                                   "IOC_MDC_GETFILEINFO", path);
1646                 }
1647                 return rc;
1648         }
1649
1650         st = &param->lmd->lmd_st;
1651
1652         /* libc chown() will do extra check, and if the real owner is
1653          * the same as the ones to set, it won't fall into kernel, so
1654          * invoke syscall directly. */
1655         rc = syscall(SYS_chown, path, -1, -1);
1656         if (rc)
1657                 llapi_err(LLAPI_MSG_ERROR,"error: chown %s (%u,%u)", path);
1658
1659         rc = chmod(path, st->st_mode);
1660         if (rc)
1661                 llapi_err(LLAPI_MSG_ERROR,"error: chmod %s (%hu)", path, st->st_mode);
1662
1663         return rc;
1664 }
1665
1666 int llapi_quotachown(char *path, int flag)
1667 {
1668         struct find_param param;
1669         char *buf;
1670         int ret = 0, len = strlen(path);
1671
1672         if (len > PATH_MAX) {
1673                 llapi_err(LLAPI_MSG_ERROR, "%s: Path name '%s' is too long",
1674                           __FUNCTION__, path);
1675                 return -EINVAL;
1676         }
1677
1678         buf = (char *)malloc(PATH_MAX + 1);
1679         if (!buf)
1680                 return -ENOMEM;
1681
1682         memset(&param, 0, sizeof(param));
1683         param.recursive = 1;
1684         param.verbose = 0;
1685         param.quiet = 1;
1686
1687         ret = common_param_init(&param);
1688         if (ret)
1689                 goto out;
1690
1691         strncpy(buf, path, PATH_MAX + 1);
1692         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, cb_quotachown,
1693                                       NULL, &param, NULL);
1694 out:
1695         find_param_fini(&param);
1696         free(buf);
1697         return ret;
1698 }
1699
1700 #include <pwd.h>
1701 #include <grp.h>
1702 #include <mntent.h>
1703 #include <sys/wait.h>
1704 #include <errno.h>
1705 #include <ctype.h>
1706
1707 static int rmtacl_notify(int ops)
1708 {
1709         FILE *fp;
1710         struct mntent *mnt;
1711         int found = 0, fd, rc;
1712
1713         fp = setmntent(MOUNTED, "r");
1714         if (fp == NULL) {
1715                 perror("setmntent");
1716                 return -1;
1717         }
1718
1719         while (1) {
1720                 mnt = getmntent(fp);
1721                 if (!mnt)
1722                         break;
1723
1724                 if (!llapi_is_lustre_mnt(mnt))
1725                         continue;
1726
1727                 fd = open(mnt->mnt_dir, O_RDONLY | O_DIRECTORY);
1728                 if (fd < 0) {
1729                         perror("open");
1730                         return -1;
1731                 }
1732
1733                 rc = ioctl(fd, LL_IOC_RMTACL, ops);
1734                 if (rc < 0) {
1735                         perror("ioctl");
1736                 return -1;
1737         }
1738
1739                 found++;
1740         }
1741         endmntent(fp);
1742         return found;
1743 }
1744
1745 static char *next_token(char *p, int div)
1746 {
1747         if (p == NULL)
1748                 return NULL;
1749
1750         if (div)
1751                 while (*p && *p != ':' && !isspace(*p))
1752                         p++;
1753         else
1754                 while (*p == ':' || isspace(*p))
1755                         p++;
1756
1757         return *p ? p : NULL;
1758 }
1759
1760 static int rmtacl_name2id(char *name, int is_user)
1761 {
1762         if (is_user) {
1763                 struct passwd *pw;
1764
1765                 if ((pw = getpwnam(name)) == NULL)
1766                         return INVALID_ID;
1767                 else
1768                         return (int)(pw->pw_uid);
1769         } else {
1770                 struct group *gr;
1771
1772                 if ((gr = getgrnam(name)) == NULL)
1773                         return INVALID_ID;
1774                 else
1775                         return (int)(gr->gr_gid);
1776         }
1777 }
1778
1779 static int isodigit(int c)
1780 {
1781         return (c >= '0' && c <= '7') ? 1 : 0;
1782 }
1783
1784 /*
1785  * Whether the name is just digits string (uid/gid) already or not.
1786  * Return value:
1787  * 1: str is id
1788  * 0: str is not id
1789  */
1790 static int str_is_id(char *str)
1791 {
1792         if (str == NULL)
1793                 return 0;
1794
1795         if (*str == '0') {
1796                 str++;
1797                 if (*str == 'x' || *str == 'X') { /* for Hex. */
1798                         if (!isxdigit(*(++str)))
1799                                 return 0;
1800
1801                         while (isxdigit(*(++str)));
1802                 } else if (isodigit(*str)) { /* for Oct. */
1803                         while (isodigit(*(++str)));
1804                 }
1805         } else if (isdigit(*str)) { /* for Dec. */
1806                 while (isdigit(*(++str)));
1807         }
1808
1809         return (*str == 0) ? 1 : 0;
1810 }
1811
1812 typedef struct {
1813         char *name;
1814         int   length;
1815         int   is_user;
1816         int   next_token;
1817 } rmtacl_name_t;
1818
1819 #define RMTACL_OPTNAME(name) name, sizeof(name) - 1
1820
1821 static rmtacl_name_t rmtacl_namelist[] = {
1822         { RMTACL_OPTNAME("user:"),            1,      0 },
1823         { RMTACL_OPTNAME("group:"),           0,      0 },
1824         { RMTACL_OPTNAME("default:user:"),    1,      0 },
1825         { RMTACL_OPTNAME("default:group:"),   0,      0 },
1826         /* for --tabular option */
1827         { RMTACL_OPTNAME("user"),             1,      1 },
1828         { RMTACL_OPTNAME("group"),            0,      1 },
1829         { 0 }
1830 };
1831
1832 static int rgetfacl_output(char *str)
1833 {
1834         char *start = NULL, *end = NULL;
1835         int is_user = 0, n, id;
1836         char c;
1837         rmtacl_name_t *rn;
1838
1839         if (str == NULL)
1840                 return -1;
1841
1842         for (rn = rmtacl_namelist; rn->name; rn++) {
1843                 if(strncmp(str, rn->name, rn->length) == 0) {
1844                         if (!rn->next_token)
1845                                 start = str + rn->length;
1846                         else
1847                                 start = next_token(str + rn->length, 0);
1848                         is_user = rn->is_user;
1849                         break;
1850                 }
1851         }
1852
1853         end = next_token(start, 1);
1854         if (end == NULL || start == end) {
1855                 n = printf("%s", str);
1856                 return n;
1857         }
1858
1859         c = *end;
1860         *end = 0;
1861         id = rmtacl_name2id(start, is_user);
1862         if (id == INVALID_ID) {
1863                 if (str_is_id(start)) {
1864                         *end = c;
1865                         n = printf("%s", str);
1866                 } else
1867                         return -1;
1868         } else if ((id == NOBODY_UID && is_user) ||
1869                    (id == NOBODY_GID && !is_user)) {
1870                 *end = c;
1871                 n = printf("%s", str);
1872         } else {
1873                 *end = c;
1874                 *start = 0;
1875                 n = printf("%s%d%s", str, id, end);
1876         }
1877         return n;
1878 }
1879
1880 static int child_status(int status)
1881 {
1882         return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
1883 }
1884
1885 static int do_rmtacl(int argc, char *argv[], int ops, int (output_func)(char *))
1886 {
1887         pid_t pid = 0;
1888         int fd[2], status;
1889         FILE *fp;
1890         char buf[PIPE_BUF];
1891
1892         if (output_func) {
1893                 if (pipe(fd) < 0) {
1894                         perror("pipe");
1895                         return -1;
1896                 }
1897
1898                 if ((pid = fork()) < 0) {
1899                         perror("fork");
1900                         close(fd[0]);
1901                         close(fd[1]);
1902                         return -1;
1903                 } else if (!pid) {
1904                         /* child process redirects its output. */
1905                         close(fd[0]);
1906                         close(1);
1907                         if (dup2(fd[1], 1) < 0) {
1908                                 perror("dup2");
1909                                 close(fd[1]);
1910                                 return -1;
1911                         }
1912                 } else {
1913                         close(fd[1]);
1914                 }
1915         }
1916
1917         if (!pid) {
1918                 status = rmtacl_notify(ops);
1919                 if (status < 0)
1920                         return -1;
1921
1922                 exit(execvp(argv[0], argv));
1923         }
1924
1925         /* the following is parent process */
1926         if ((fp = fdopen(fd[0], "r")) == NULL) {
1927                 perror("fdopen");
1928                 kill(pid, SIGKILL);
1929                 close(fd[0]);
1930                 return -1;
1931         }
1932
1933         while (fgets(buf, PIPE_BUF, fp) != NULL) {
1934                 if (output_func(buf) < 0)
1935                         fprintf(stderr, "WARNING: unexpected error!\n[%s]\n",
1936                                 buf);
1937         }
1938         fclose(fp);
1939         close(fd[0]);
1940
1941         if (waitpid(pid, &status, 0) < 0) {
1942                 perror("waitpid");
1943                 return -1;
1944         }
1945
1946         return child_status(status);
1947 }
1948
1949 int llapi_lsetfacl(int argc, char *argv[])
1950 {
1951         return do_rmtacl(argc, argv, RMT_LSETFACL, NULL);
1952 }
1953
1954 int llapi_lgetfacl(int argc, char *argv[])
1955 {
1956         return do_rmtacl(argc, argv, RMT_LGETFACL, NULL);
1957 }
1958
1959 int llapi_rsetfacl(int argc, char *argv[])
1960 {
1961         return do_rmtacl(argc, argv, RMT_RSETFACL, NULL);
1962 }
1963
1964 int llapi_rgetfacl(int argc, char *argv[])
1965 {
1966         return do_rmtacl(argc, argv, RMT_RGETFACL, rgetfacl_output);
1967 }
1968
1969 int llapi_cp(int argc, char *argv[])
1970 {
1971         int rc;
1972
1973         rc = rmtacl_notify(RMT_RSETFACL);
1974         if (rc < 0)
1975                 return -1;
1976
1977         exit(execvp(argv[0], argv));
1978 }
1979
1980 int llapi_ls(int argc, char *argv[])
1981 {
1982         int rc;
1983
1984         rc = rmtacl_notify(RMT_LGETFACL);
1985         if (rc < 0)
1986                 return -1;
1987
1988         exit(execvp(argv[0], argv));
1989 }