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