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