Whamcloud - gitweb
Branch HEAD
[fs/lustre-release.git] / lustre / utils / liblustreapi.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  *  Copyright (C) 2002 Cluster File Systems, Inc.
5  *   Author: Peter J. Braam <braam@clusterfs.com>
6  *   Author: Phil Schwan <phil@clusterfs.com>
7  *   Author: Robert Read <rread@clusterfs.com>
8  *
9  *   This file is part of Lustre, http://www.lustre.org.
10  *
11  *   Lustre is free software; you can redistribute it and/or
12  *   modify it under the terms of version 2 of the GNU General Public
13  *   License as published by the Free Software Foundation.
14  *
15  *   Lustre is distributed in the hope that it will be useful,
16  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *   GNU General Public License for more details.
19  *
20  *   You should have received a copy of the GNU General Public License
21  *   along with Lustre; if not, write to the Free Software
22  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  *
24  */
25
26 /* for O_DIRECTORY */
27 #define _GNU_SOURCE
28
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <stddef.h>
33 #include <sys/ioctl.h>
34 #include <unistd.h>
35 #include <fcntl.h>
36 #include <errno.h>
37 #include <dirent.h>
38 #include <stdarg.h>
39 #include <sys/stat.h>
40 #include <sys/types.h>
41 #include <sys/syscall.h>
42 #include <fnmatch.h>
43 #ifdef HAVE_ASM_TYPES_H
44 #include <asm/types.h>
45 #endif
46 #ifdef HAVE_LINUX_UNISTD_H
47 #include <linux/unistd.h>
48 #else
49 #include <unistd.h>
50 #endif
51
52 #include <liblustre.h>
53 #include <lnet/lnetctl.h>
54 #include <obd.h>
55 #include <lustre_lib.h>
56 #include <obd_lov.h>
57 #include <lustre/liblustreapi.h>
58
59 static unsigned llapi_dir_filetype_table[] = {
60         [DT_UNKNOWN]= 0,
61         [DT_FIFO]= S_IFIFO,
62         [DT_CHR] = S_IFCHR,
63         [DT_DIR] = S_IFDIR,
64         [DT_BLK] = S_IFBLK,
65         [DT_REG] = S_IFREG,
66         [DT_LNK] = S_IFLNK,
67         [DT_SOCK]= S_IFSOCK,
68 #if defined(DT_DOOR) && defined(S_IFDOOR)
69         [DT_DOOR]= S_IFDOOR,
70 #endif
71 };
72
73 #if defined(DT_DOOR) && defined(S_IFDOOR)
74 static const int DT_MAX = DT_DOOR;
75 #else
76 static const int DT_MAX = DT_SOCK;
77 #endif
78
79 static unsigned llapi_filetype_dir_table[] = {
80         [0]= DT_UNKNOWN,
81         [S_IFIFO]= DT_FIFO,
82         [S_IFCHR] = DT_CHR,
83         [S_IFDIR] = DT_DIR,
84         [S_IFBLK] = DT_BLK,
85         [S_IFREG] = DT_REG,
86         [S_IFLNK] = DT_LNK,
87         [S_IFSOCK]= DT_SOCK,
88 #if defined(DT_DOOR) && defined(S_IFDOOR)
89         [S_IFDOOR]= DT_DOOR,
90 #endif
91 };
92
93 #if defined(DT_DOOR) && defined(S_IFDOOR)
94 static const int S_IFMAX = DT_DOOR;
95 #else
96 static const int S_IFMAX = DT_SOCK;
97 #endif
98
99 /* liblustreapi message level */
100 static int llapi_msg_level = LLAPI_MSG_MAX;
101
102 void llapi_msg_set_level(int level)
103 {
104         /* ensure level is in the good range */
105         if (level < LLAPI_MSG_OFF)
106                 llapi_msg_level = LLAPI_MSG_OFF;
107         else if (level > LLAPI_MSG_MAX)
108                 llapi_msg_level = LLAPI_MSG_MAX;
109         else
110                 llapi_msg_level = level;
111 }
112
113 void llapi_err(int level, char *fmt, ...)
114 {
115         va_list args;
116         int tmp_errno = abs(errno);
117
118         if ((level & LLAPI_MSG_MASK) > llapi_msg_level)
119                 return;
120
121         va_start(args, fmt);
122         vfprintf(stderr, fmt, args);
123         va_end(args);
124
125         if (level & LLAPI_MSG_NO_ERRNO)
126                 fprintf(stderr, "\n");
127         else
128                 fprintf(stderr, ": %s (%d)\n", strerror(tmp_errno), tmp_errno);
129 }
130
131 #define llapi_err_noerrno(level, fmt, a...)                             \
132         llapi_err((level) | LLAPI_MSG_NO_ERRNO, fmt, ## a)
133
134 void llapi_printf(int level, char *fmt, ...)
135 {
136         va_list args;
137
138         if ((level & LLAPI_MSG_MASK) > llapi_msg_level)
139                 return;
140
141         va_start(args, fmt);
142         vfprintf(stdout, fmt, args);
143         va_end(args);
144 }
145
146 int parse_size(char *optarg, unsigned long long *size,
147                unsigned long long *size_units)
148 {
149         char *end;
150
151         *size = strtoul(optarg, &end, 0);
152
153         if (*end != '\0') {
154                 if ((*end == 'b') && *(end+1) == '\0' &&
155                     (*size & (~0ULL << (64 - 9))) == 0) {
156                         *size <<= 9;
157                         *size_units = 1 << 9;
158                 } else if ((*end == 'k' || *end == 'K') &&
159                            *(end+1) == '\0' && (*size &
160                            (~0ULL << (64 - 10))) == 0) {
161                         *size <<= 10;
162                         *size_units = 1 << 10;
163                 } else if ((*end == 'm' || *end == 'M') &&
164                            *(end+1) == '\0' && (*size &
165                            (~0ULL << (64 - 20))) == 0) {
166                         *size <<= 20;
167                         *size_units = 1 << 20;
168                 } else if ((*end == 'g' || *end == 'G') &&
169                            *(end+1) == '\0' && (*size &
170                            (~0ULL << (64 - 30))) == 0) {
171                         *size <<= 30;
172                         *size_units = 1 << 30;
173                 } else if ((*end == 't' || *end == 'T') &&
174                            *(end+1) == '\0' && (*size &
175                            (~0ULL << (64 - 40))) == 0) {
176                         *size <<= 40;
177                         *size_units = 1ULL << 40;
178                 } else if ((*end == 'p' || *end == 'P') &&
179                            *(end+1) == '\0' && (*size &
180                            (~0ULL << (64 - 50))) == 0) {
181                         *size <<= 50;
182                         *size_units = 1ULL << 50;
183                 } else if ((*end == 'e' || *end == 'E') &&
184                            *(end+1) == '\0' && (*size &
185                            (~0ULL << (64 - 60))) == 0) {
186                         *size <<= 60;
187                         *size_units = 1ULL << 60;
188                 } else {
189                         return -1;
190                 }
191         }
192
193         return 0;
194 }
195
196 int llapi_file_open(const char *name, int flags, int mode,
197                     unsigned long stripe_size, int stripe_offset,
198                     int stripe_count, int stripe_pattern)
199 {
200         struct lov_user_md lum = { 0 };
201         int fd, rc = 0;
202         int isdir = 0;
203         int page_size;
204
205         fd = open(name, flags | O_LOV_DELAY_CREATE, mode);
206         if (fd < 0 && errno == EISDIR) {
207                 fd = open(name, O_DIRECTORY | O_RDONLY);
208                 isdir++;
209         }
210
211         if (fd < 0) {
212                 rc = -errno;
213                 llapi_err(LLAPI_MSG_ERROR, "unable to open '%s'", name);
214                 return rc;
215         }
216
217         /* 64 KB is the largest common page size I'm aware of (on ia64), but
218          * check the local page size just in case. */
219         page_size = LOV_MIN_STRIPE_SIZE;
220         if (getpagesize() > page_size) {
221                 page_size = getpagesize();
222                 llapi_err_noerrno(LLAPI_MSG_WARN, 
223                                   "warning: your page size (%u) is "
224                                   "larger than expected (%u)", page_size, 
225                                   LOV_MIN_STRIPE_SIZE);
226         }
227         if (stripe_size < 0 || (stripe_size & (LOV_MIN_STRIPE_SIZE - 1))) {
228                 errno = rc = -EINVAL;
229                 llapi_err(LLAPI_MSG_ERROR, "error: bad stripe_size %lu, "
230                           "must be an even multiple of %d bytes", 
231                           stripe_size, page_size);
232                 goto out;
233         }
234         if (stripe_offset < -1 || stripe_offset > MAX_OBD_DEVICES) {
235                 errno = rc = -EINVAL;
236                 llapi_err(LLAPI_MSG_ERROR, "error: bad stripe offset %d", 
237                           stripe_offset);
238                 goto out;
239         }
240         if (stripe_count < -1 || stripe_count > LOV_MAX_STRIPE_COUNT) {
241                 errno = rc = -EINVAL;
242                 llapi_err(LLAPI_MSG_ERROR, "error: bad stripe count %d", 
243                           stripe_count);
244                 goto out;
245         }
246         if (stripe_count > 0 && (__u64)stripe_size * stripe_count > 0xffffffff){
247                 errno = rc = -EINVAL;
248                 llapi_err(LLAPI_MSG_ERROR, "error: stripe_size %lu * "
249                           "stripe_count %u exceeds 4GB", stripe_size, 
250                           stripe_count);
251                 goto out;
252         }
253
254         /*  Initialize IOCTL striping pattern structure */
255         lum.lmm_magic = LOV_USER_MAGIC;
256         lum.lmm_pattern = stripe_pattern;
257         lum.lmm_stripe_size = stripe_size;
258         lum.lmm_stripe_count = stripe_count;
259         lum.lmm_stripe_offset = stripe_offset;
260
261         if (ioctl(fd, LL_IOC_LOV_SETSTRIPE, &lum)) {
262                 char *errmsg = "stripe already set";
263                 rc = -errno;
264                 if (errno != EEXIST && errno != EALREADY)
265                         errmsg = strerror(errno);
266
267                 llapi_err_noerrno(LLAPI_MSG_ERROR,
268                                   "error on ioctl "LPX64" for '%s' (%d): %s",
269                                   (__u64)LL_IOC_LOV_SETSTRIPE, name, fd, errmsg);
270         }
271 out:
272         if (rc) {
273                 close(fd);
274                 fd = rc;
275         }
276
277         return fd;
278 }
279
280 int llapi_file_create(const char *name, unsigned long stripe_size,
281                       int stripe_offset, int stripe_count, int stripe_pattern)
282 {
283         int fd;
284
285         fd = llapi_file_open(name, O_CREAT | O_WRONLY, 0644, stripe_size,
286                              stripe_offset, stripe_count, stripe_pattern);
287         if (fd < 0)
288                 return fd;
289
290         close(fd);
291         return 0;
292 }
293
294 typedef int (semantic_func_t)(char *path, DIR *parent, DIR *d,
295                               void *data, 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         /* Check the time on mds. */
1157         if (!decision) {
1158                 int for_mds;
1159
1160                 for_mds = lustre_fs ? (S_ISREG(st->st_mode) &&
1161                                        param->lmd->lmd_lmm.lmm_stripe_count)
1162                                     : 0;
1163                 decision = find_time_check(st, param, for_mds);
1164         }
1165
1166 obd_matches:
1167         /* If file still fits the request, ask osd for updated info.
1168            The regulat stat is almost of the same speed as some new
1169            'glimpse-size-ioctl'. */
1170         if (!decision && S_ISREG(st->st_mode) &&
1171             (param->lmd->lmd_lmm.lmm_stripe_count || param->size)) {
1172                 if (param->obdindex != OBD_NOT_FOUND) {
1173                         /* Check whether the obd is active or not, if it is
1174                          * not active, just print the object affected by this
1175                          * failed ost 
1176                          * */
1177                         struct obd_statfs stat_buf;
1178                         struct obd_uuid uuid_buf;
1179
1180                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
1181                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1182                         ret = llapi_obd_statfs(path, LL_STATFS_LOV,
1183                                                param->obdindex, &stat_buf, 
1184                                                &uuid_buf);
1185                         if (ret) {
1186                                 if (ret == -ENODATA || ret == -ENODEV 
1187                                     || ret == -EIO)
1188                                         errno = EIO;
1189                                 llapi_printf(LLAPI_MSG_NORMAL, 
1190                                              "obd_uuid: %s failed %s ",
1191                                              param->obduuid->uuid, 
1192                                              strerror(errno));
1193                                 goto print_path;
1194                         }
1195                 }
1196                 if (dir) {
1197                         ret = ioctl(dirfd(dir), IOC_LOV_GETINFO,
1198                                     (void *)param->lmd);
1199                 } else if (parent) {
1200                         ret = ioctl(dirfd(parent), IOC_LOV_GETINFO,
1201                                     (void *)param->lmd);
1202                 }
1203
1204                 if (ret) {
1205                         if (errno == ENOENT) {
1206                                 llapi_err(LLAPI_MSG_ERROR, 
1207                                           "warning: %s: %s does not exist",
1208                                           __FUNCTION__, path);
1209                                 goto decided;
1210                         } else {
1211                                 llapi_err(LLAPI_MSG_ERROR, 
1212                                           "%s: IOC_LOV_GETINFO on %s failed",
1213                                           __FUNCTION__, path);
1214                                 return ret;
1215                         }
1216                 }
1217
1218                 /* Check the time on osc. */
1219                 decision = find_time_check(st, param, 0);
1220                 if (decision == -1)
1221                         goto decided;
1222         }
1223
1224         if (param->size)
1225                 decision = find_value_cmp(st->st_size, param->size,
1226                                           param->size_sign, param->size_units,
1227                                           0);
1228
1229 print_path:
1230         if (decision != -1) {
1231                 llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
1232                 if (param->zeroend)
1233                         llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
1234                 else
1235                         llapi_printf(LLAPI_MSG_NORMAL, "\n");
1236         }
1237
1238 decided:
1239         /* Do not get down anymore? */
1240         if (param->depth == param->maxdepth)
1241                 return 1;
1242
1243         param->depth++;
1244         return 0;
1245 }
1246
1247 static int cb_common_fini(char *path, DIR *parent, DIR *d, void *data,
1248                           cfs_dirent_t *de)
1249 {
1250         struct find_param *param = (struct find_param *)data;
1251         param->depth--;
1252         return 0;
1253 }
1254
1255 int llapi_find(char *path, struct find_param *param)
1256 {
1257         char *buf;
1258         int ret, len = strlen(path);
1259
1260         if (len > PATH_MAX) {
1261                 llapi_err(LLAPI_MSG_ERROR, "%s: Path name '%s' is too long",
1262                           __FUNCTION__, path);
1263                 return -EINVAL;
1264         }
1265
1266         buf = (char *)malloc(PATH_MAX + 1);
1267         if (!buf)
1268                 return -ENOMEM;
1269
1270         ret = common_param_init(param);
1271         if (ret) {
1272                 free(buf);
1273                 return ret;
1274         }
1275
1276         param->depth = 0;
1277
1278         strncpy(buf, path, PATH_MAX + 1);
1279         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, cb_find_init,
1280                                       cb_common_fini, param, NULL);
1281
1282         find_param_fini(param);
1283         free(buf);
1284         return ret < 0 ? ret : 0;
1285 }
1286
1287 static int cb_getstripe(char *path, DIR *parent, DIR *d, void *data,
1288                         cfs_dirent_t *de)
1289 {
1290         struct find_param *param = (struct find_param *)data;
1291         int ret = 0;
1292
1293         LASSERT(parent != NULL || d != NULL);
1294
1295         /* Prepare odb. */
1296         if (!param->got_uuids) {
1297                 ret = setup_obd_uuid(d ? d : parent, path, param);
1298                 if (ret)
1299                         return ret;
1300         }
1301
1302         if (d) {
1303                 ret = ioctl(dirfd(d), LL_IOC_LOV_GETSTRIPE,
1304                             (void *)&param->lmd->lmd_lmm);
1305         } else if (parent) {
1306                 char *fname = strrchr(path, '/');
1307                 fname = (fname == NULL ? path : fname + 1);
1308
1309                 strncpy((char *)&param->lmd->lmd_lmm, fname, param->lumlen);
1310                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILESTRIPE,
1311                             (void *)&param->lmd->lmd_lmm);
1312         }
1313
1314         if (ret) {
1315                 if (errno == ENODATA) {
1316                         if (!param->obduuid && !param->quiet)
1317                                 llapi_printf(LLAPI_MSG_NORMAL, 
1318                                              "%s has no stripe info\n", path);
1319                         goto out;
1320                 } else if (errno == ENOTTY) {
1321                         llapi_err(LLAPI_MSG_ERROR, 
1322                                   "%s: '%s' not on a Lustre fs?",
1323                                   __FUNCTION__, path);
1324                 } else if (errno == ENOENT) {
1325                         llapi_err(LLAPI_MSG_WARN, 
1326                                   "warning: %s: %s does not exist",
1327                                   __FUNCTION__, path);
1328                         goto out;
1329                 } else {
1330                         llapi_err(LLAPI_MSG_ERROR, 
1331                                   "error: %s: %s failed for %s",
1332                                    __FUNCTION__, d ? "LL_IOC_LOV_GETSTRIPE" :
1333                                   "IOC_MDC_GETFILESTRIPE", path);
1334                 }
1335
1336                 return ret;
1337         }
1338
1339         llapi_lov_dump_user_lmm(param, path, d ? 1 : 0);
1340 out:
1341         /* Do not get down anymore? */
1342         if (param->depth == param->maxdepth)
1343                 return 1;
1344
1345         param->depth++;
1346         return 0;
1347 }
1348
1349 int llapi_getstripe(char *path, struct find_param *param)
1350 {
1351         char *buf;
1352         int ret = 0, len = strlen(path);
1353
1354         if (len > PATH_MAX) {
1355                 llapi_err(LLAPI_MSG_ERROR, 
1356                           "%s: Path name '%s' is too long",
1357                           __FUNCTION__, path);
1358                 return -EINVAL;
1359         }
1360
1361         buf = (char *)malloc(PATH_MAX + 1);
1362         if (!buf)
1363                 return -ENOMEM;
1364
1365         ret = common_param_init(param);
1366         if (ret) {
1367                 free(buf);
1368                 return ret;
1369         }
1370
1371         param->depth = 0;
1372
1373         strncpy(buf, path, PATH_MAX + 1);
1374         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, cb_getstripe,
1375                                       cb_common_fini, param, NULL);
1376         find_param_fini(param);
1377         free(buf);
1378         return ret < 0 ? ret : 0;
1379 }
1380
1381 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
1382                      struct obd_statfs *stat_buf,
1383                      struct obd_uuid *uuid_buf)
1384 {
1385         int fd;
1386         char raw[OBD_MAX_IOCTL_BUFFER] = {'\0'};
1387         char *rawbuf = raw;
1388         struct obd_ioctl_data data = { 0 };
1389         int rc = 0;
1390
1391         data.ioc_inlbuf1 = (char *)&type;
1392         data.ioc_inllen1 = sizeof(__u32);
1393         data.ioc_inlbuf2 = (char *)&index;
1394         data.ioc_inllen2 = sizeof(__u32);
1395         data.ioc_pbuf1 = (char *)stat_buf;
1396         data.ioc_plen1 = sizeof(struct obd_statfs);
1397         data.ioc_pbuf2 = (char *)uuid_buf;
1398         data.ioc_plen2 = sizeof(struct obd_uuid);
1399
1400         if ((rc = obd_ioctl_pack(&data, &rawbuf, sizeof(raw))) != 0) {
1401                 llapi_err(LLAPI_MSG_ERROR, 
1402                           "llapi_obd_statfs: error packing ioctl data");
1403                 return rc;
1404         }
1405
1406         fd = open(path, O_RDONLY);
1407         if (errno == EISDIR)
1408                 fd = open(path, O_DIRECTORY | O_RDONLY);
1409
1410         if (fd < 0) {
1411                 rc = errno ? -errno : -EBADF;
1412                 llapi_err(LLAPI_MSG_ERROR, "error: %s: opening '%s'", 
1413                           __FUNCTION__, path);
1414                 return rc;
1415         }
1416         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
1417         if (rc)
1418                 rc = errno ? -errno : -EINVAL;
1419
1420         close(fd);
1421         return rc;
1422 }
1423
1424 #define MAX_STRING_SIZE 128
1425 #define DEVICES_LIST "/proc/fs/lustre/devices"
1426
1427 int llapi_ping(char *obd_type, char *obd_name)
1428 {
1429         char path[MAX_STRING_SIZE];
1430         char buf[1];
1431         int rc, fd;
1432
1433         snprintf(path, MAX_STRING_SIZE, "/proc/fs/lustre/%s/%s/ping",
1434                  obd_type, obd_name);
1435
1436         fd = open(path, O_WRONLY);
1437         if (fd < 0) {
1438                 rc = errno;
1439                 llapi_err(LLAPI_MSG_ERROR, "error opening %s", path);
1440                 return rc;
1441         }
1442
1443         rc = write(fd, buf, 1);
1444         close(fd);
1445
1446         if (rc == 1)
1447                 return 0;
1448         return rc;
1449 }
1450
1451 int llapi_target_iterate(int type_num, char **obd_type, void *args, llapi_cb_t cb)
1452 {
1453         char buf[MAX_STRING_SIZE];
1454         FILE *fp = fopen(DEVICES_LIST, "r");
1455         int i, rc = 0;
1456
1457         if (fp == NULL) {
1458                 rc = errno;
1459                 llapi_err(LLAPI_MSG_ERROR, "error: opening "DEVICES_LIST);
1460                 return rc;
1461         }
1462
1463         while (fgets(buf, sizeof(buf), fp) != NULL) {
1464                 char *obd_type_name = NULL;
1465                 char *obd_name = NULL;
1466                 char *obd_uuid = NULL;
1467                 char rawbuf[OBD_MAX_IOCTL_BUFFER];
1468                 char *bufl = rawbuf;
1469                 char *bufp = buf;
1470                 struct obd_ioctl_data datal = { 0, };
1471                 struct obd_statfs osfs_buffer;
1472
1473                 while(bufp[0] == ' ')
1474                         ++bufp;
1475
1476                 for(i = 0; i < 3; i++) {
1477                         obd_type_name = strsep(&bufp, " ");
1478                 }
1479                 obd_name = strsep(&bufp, " ");
1480                 obd_uuid = strsep(&bufp, " ");
1481
1482                 memset(&osfs_buffer, 0, sizeof (osfs_buffer));
1483
1484                 memset(bufl, 0, sizeof(rawbuf));
1485                 datal.ioc_pbuf1 = (char *)&osfs_buffer;
1486                 datal.ioc_plen1 = sizeof(osfs_buffer);
1487
1488                 for (i = 0; i < type_num; i++) {
1489                         if (strcmp(obd_type_name, obd_type[i]) != 0)
1490                                 continue;
1491
1492                         cb(obd_type_name, obd_name, obd_uuid, args);
1493                 }
1494         }
1495         fclose(fp);
1496         return rc;
1497 }
1498
1499 static void do_target_check(char *obd_type_name, char *obd_name,
1500                             char *obd_uuid, void *args)
1501 {
1502         int rc;
1503
1504         rc = llapi_ping(obd_type_name, obd_name);
1505         if (rc) {
1506                 llapi_err(LLAPI_MSG_ERROR, "error: check '%s'", obd_name);
1507         } else {
1508                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
1509         }
1510 }
1511
1512 int llapi_target_check(int type_num, char **obd_type, char *dir)
1513 {
1514         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
1515 }
1516
1517 #undef MAX_STRING_SIZE
1518
1519 int llapi_catinfo(char *dir, char *keyword, char *node_name)
1520 {
1521         char raw[OBD_MAX_IOCTL_BUFFER];
1522         char out[LLOG_CHUNK_SIZE];
1523         char *buf = raw;
1524         struct obd_ioctl_data data = { 0 };
1525         char key[30];
1526         DIR *root;
1527         int rc;
1528
1529         sprintf(key, "%s", keyword);
1530         memset(raw, 0, sizeof(raw));
1531         memset(out, 0, sizeof(out));
1532         data.ioc_inlbuf1 = key;
1533         data.ioc_inllen1 = strlen(key) + 1;
1534         if (node_name) {
1535                 data.ioc_inlbuf2 = node_name;
1536                 data.ioc_inllen2 = strlen(node_name) + 1;
1537         }
1538         data.ioc_pbuf1 = out;
1539         data.ioc_plen1 = sizeof(out);
1540         rc = obd_ioctl_pack(&data, &buf, sizeof(raw));
1541         if (rc)
1542                 return rc;
1543
1544         root = opendir(dir);
1545         if (root == NULL) {
1546                 rc = errno;
1547                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", dir);
1548                 return rc;
1549         }
1550
1551         rc = ioctl(dirfd(root), OBD_IOC_LLOG_CATINFO, buf);
1552         if (rc)
1553                 llapi_err(LLAPI_MSG_ERROR, "ioctl OBD_IOC_CATINFO failed");
1554         else
1555                 llapi_printf(LLAPI_MSG_NORMAL, "%s", data.ioc_pbuf1);
1556
1557         closedir(root);
1558         return rc;
1559 }
1560
1561 /* Is this a lustre fs? */
1562 int llapi_is_lustre_mnttype(const char *type)
1563 {
1564         return (strcmp(type, "lustre") == 0 || strcmp(type,"lustre_lite") == 0);
1565 }
1566
1567 /* Is this a lustre client fs? */
1568 int llapi_is_lustre_mnt(struct mntent *mnt)
1569 {
1570         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
1571                 strstr(mnt->mnt_fsname, ":/") != NULL);
1572 }
1573
1574 int llapi_quotacheck(char *mnt, int check_type)
1575 {
1576         DIR *root;
1577         int rc;
1578
1579         root = opendir(mnt);
1580         if (!root) {
1581                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
1582                 return -1;
1583         }
1584
1585         rc = ioctl(dirfd(root), LL_IOC_QUOTACHECK, check_type);
1586
1587         closedir(root);
1588         return rc;
1589 }
1590
1591 int llapi_poll_quotacheck(char *mnt, struct if_quotacheck *qchk)
1592 {
1593         DIR *root;
1594         int poll_intvl = 2;
1595         int rc;
1596
1597         root = opendir(mnt);
1598         if (!root) {
1599                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
1600                 return -1;
1601         }
1602
1603         while (1) {
1604                 rc = ioctl(dirfd(root), LL_IOC_POLL_QUOTACHECK, qchk);
1605                 if (!rc)
1606                         break;
1607                 sleep(poll_intvl);
1608                 if (poll_intvl < 30)
1609                         poll_intvl *= 2;
1610         }
1611
1612         closedir(root);
1613         return rc;
1614 }
1615
1616 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
1617 {
1618         DIR *root;
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         rc = ioctl(dirfd(root), LL_IOC_QUOTACTL, qctl);
1628
1629         closedir(root);
1630         return rc;
1631 }
1632
1633 static int cb_quotachown(char *path, DIR *parent, DIR *d, void *data,
1634                          cfs_dirent_t *de)
1635 {
1636         struct find_param *param = (struct find_param *)data;
1637         lstat_t *st;
1638         int rc;
1639
1640         LASSERT(parent != NULL || d != NULL);
1641
1642         if (d) {
1643                 rc = ioctl(dirfd(d), LL_IOC_MDC_GETINFO,
1644                            (void *)param->lmd);
1645         } else if (parent) {
1646                 char *fname = strrchr(path, '/');
1647                 fname = (fname == NULL ? path : fname + 1);
1648
1649                 strncpy((char *)param->lmd, fname, param->lumlen);
1650                 rc = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
1651                            (void *)param->lmd);
1652         } else {
1653                 return 0;
1654         }
1655
1656         if (rc) {
1657                 if (errno == ENODATA) {
1658                         if (!param->obduuid && !param->quiet)
1659                                 llapi_err(LLAPI_MSG_ERROR, 
1660                                           "%s has no stripe info", path);
1661                         rc = 0;
1662                 } else if (errno == ENOENT) {
1663                         llapi_err(LLAPI_MSG_ERROR, 
1664                                   "warning: %s: %s does not exist",
1665                                   __FUNCTION__, path);
1666                         rc = 0;
1667                 } else if (errno != EISDIR) {
1668                         rc = errno;
1669                         llapi_err(LLAPI_MSG_ERROR, "%s ioctl failed for %s.",
1670                                   d ? "LL_IOC_MDC_GETINFO" :
1671                                   "IOC_MDC_GETFILEINFO", path);
1672                 }
1673                 return rc;
1674         }
1675
1676         st = &param->lmd->lmd_st;
1677
1678         /* libc chown() will do extra check, and if the real owner is
1679          * the same as the ones to set, it won't fall into kernel, so
1680          * invoke syscall directly. */
1681         rc = syscall(SYS_chown, path, -1, -1);
1682         if (rc)
1683                 llapi_err(LLAPI_MSG_ERROR,"error: chown %s (%u,%u)", path);
1684
1685         rc = chmod(path, st->st_mode);
1686         if (rc)
1687                 llapi_err(LLAPI_MSG_ERROR,"error: chmod %s (%hu)", path, st->st_mode);
1688
1689         return rc;
1690 }
1691
1692 int llapi_quotachown(char *path, int flag)
1693 {
1694         struct find_param param;
1695         char *buf;
1696         int ret = 0, len = strlen(path);
1697
1698         if (len > PATH_MAX) {
1699                 llapi_err(LLAPI_MSG_ERROR, "%s: Path name '%s' is too long",
1700                           __FUNCTION__, path);
1701                 return -EINVAL;
1702         }
1703
1704         buf = (char *)malloc(PATH_MAX + 1);
1705         if (!buf)
1706                 return -ENOMEM;
1707
1708         memset(&param, 0, sizeof(param));
1709         param.recursive = 1;
1710         param.verbose = 0;
1711         param.quiet = 1;
1712
1713         ret = common_param_init(&param);
1714         if (ret)
1715                 goto out;
1716
1717         strncpy(buf, path, PATH_MAX + 1);
1718         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, cb_quotachown,
1719                                       NULL, &param, NULL);
1720 out:
1721         find_param_fini(&param);
1722         free(buf);
1723         return ret;
1724 }
1725
1726 #include <pwd.h>
1727 #include <grp.h>
1728 #include <mntent.h>
1729 #include <sys/wait.h>
1730 #include <errno.h>
1731 #include <ctype.h>
1732
1733 static int rmtacl_notify(int ops)
1734 {
1735         FILE *fp;
1736         struct mntent *mnt;
1737         int found = 0, fd, rc;
1738
1739         fp = setmntent(MOUNTED, "r");
1740         if (fp == NULL) {
1741                 perror("setmntent");
1742                 return -1;
1743         }
1744
1745         while (1) {
1746                 mnt = getmntent(fp);
1747                 if (!mnt)
1748                         break;
1749
1750                 if (!llapi_is_lustre_mnt(mnt))
1751                         continue;
1752
1753                 fd = open(mnt->mnt_dir, O_RDONLY | O_DIRECTORY);
1754                 if (fd < 0) {
1755                         perror("open");
1756                         return -1;
1757                 }
1758
1759                 rc = ioctl(fd, LL_IOC_RMTACL, ops);
1760                 if (rc < 0) {
1761                         perror("ioctl");
1762                 return -1;
1763         }
1764
1765                 found++;
1766         }
1767         endmntent(fp);
1768         return found;
1769 }
1770
1771 static char *next_token(char *p, int div)
1772 {
1773         if (p == NULL)
1774                 return NULL;
1775
1776         if (div)
1777                 while (*p && *p != ':' && !isspace(*p))
1778                         p++;
1779         else
1780                 while (*p == ':' || isspace(*p))
1781                         p++;
1782
1783         return *p ? p : NULL;
1784 }
1785
1786 static int rmtacl_name2id(char *name, int is_user)
1787 {
1788         if (is_user) {
1789                 struct passwd *pw;
1790
1791                 if ((pw = getpwnam(name)) == NULL)
1792                         return INVALID_ID;
1793                 else
1794                         return (int)(pw->pw_uid);
1795         } else {
1796                 struct group *gr;
1797
1798                 if ((gr = getgrnam(name)) == NULL)
1799                         return INVALID_ID;
1800                 else
1801                         return (int)(gr->gr_gid);
1802         }
1803 }
1804
1805 static int isodigit(int c)
1806 {
1807         return (c >= '0' && c <= '7') ? 1 : 0;
1808 }
1809
1810 /*
1811  * Whether the name is just digits string (uid/gid) already or not.
1812  * Return value:
1813  * 1: str is id
1814  * 0: str is not id
1815  */
1816 static int str_is_id(char *str)
1817 {
1818         if (str == NULL)
1819                 return 0;
1820
1821         if (*str == '0') {
1822                 str++;
1823                 if (*str == 'x' || *str == 'X') { /* for Hex. */
1824                         if (!isxdigit(*(++str)))
1825                                 return 0;
1826
1827                         while (isxdigit(*(++str)));
1828                 } else if (isodigit(*str)) { /* for Oct. */
1829                         while (isodigit(*(++str)));
1830                 }
1831         } else if (isdigit(*str)) { /* for Dec. */
1832                 while (isdigit(*(++str)));
1833         }
1834
1835         return (*str == 0) ? 1 : 0;
1836 }
1837
1838 typedef struct {
1839         char *name;
1840         int   length;
1841         int   is_user;
1842         int   next_token;
1843 } rmtacl_name_t;
1844
1845 #define RMTACL_OPTNAME(name) name, sizeof(name) - 1
1846
1847 static rmtacl_name_t rmtacl_namelist[] = {
1848         { RMTACL_OPTNAME("user:"),            1,      0 },
1849         { RMTACL_OPTNAME("group:"),           0,      0 },
1850         { RMTACL_OPTNAME("default:user:"),    1,      0 },
1851         { RMTACL_OPTNAME("default:group:"),   0,      0 },
1852         /* for --tabular option */
1853         { RMTACL_OPTNAME("user"),             1,      1 },
1854         { RMTACL_OPTNAME("group"),            0,      1 },
1855         { 0 }
1856 };
1857
1858 static int rgetfacl_output(char *str)
1859 {
1860         char *start = NULL, *end = NULL;
1861         int is_user = 0, n, id;
1862         char c;
1863         rmtacl_name_t *rn;
1864
1865         if (str == NULL)
1866                 return -1;
1867
1868         for (rn = rmtacl_namelist; rn->name; rn++) {
1869                 if(strncmp(str, rn->name, rn->length) == 0) {
1870                         if (!rn->next_token)
1871                                 start = str + rn->length;
1872                         else
1873                                 start = next_token(str + rn->length, 0);
1874                         is_user = rn->is_user;
1875                         break;
1876                 }
1877         }
1878
1879         end = next_token(start, 1);
1880         if (end == NULL || start == end) {
1881                 n = printf("%s", str);
1882                 return n;
1883         }
1884
1885         c = *end;
1886         *end = 0;
1887         id = rmtacl_name2id(start, is_user);
1888         if (id == INVALID_ID) {
1889                 if (str_is_id(start)) {
1890                         *end = c;
1891                         n = printf("%s", str);
1892                 } else
1893                         return -1;
1894         } else if ((id == NOBODY_UID && is_user) ||
1895                    (id == NOBODY_GID && !is_user)) {
1896                 *end = c;
1897                 n = printf("%s", str);
1898         } else {
1899                 *end = c;
1900                 *start = 0;
1901                 n = printf("%s%d%s", str, id, end);
1902         }
1903         return n;
1904 }
1905
1906 static int child_status(int status)
1907 {
1908         return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
1909 }
1910
1911 static int do_rmtacl(int argc, char *argv[], int ops, int (output_func)(char *))
1912 {
1913         pid_t pid = 0;
1914         int fd[2], status;
1915         FILE *fp;
1916         char buf[PIPE_BUF];
1917
1918         if (output_func) {
1919                 if (pipe(fd) < 0) {
1920                         perror("pipe");
1921                         return -1;
1922                 }
1923
1924                 if ((pid = fork()) < 0) {
1925                         perror("fork");
1926                         close(fd[0]);
1927                         close(fd[1]);
1928                         return -1;
1929                 } else if (!pid) {
1930                         /* child process redirects its output. */
1931                         close(fd[0]);
1932                         close(1);
1933                         if (dup2(fd[1], 1) < 0) {
1934                                 perror("dup2");
1935                                 close(fd[1]);
1936                                 return -1;
1937                         }
1938                 } else {
1939                         close(fd[1]);
1940                 }
1941         }
1942
1943         if (!pid) {
1944                 status = rmtacl_notify(ops);
1945                 if (status < 0)
1946                         return -1;
1947
1948                 exit(execvp(argv[0], argv));
1949         }
1950
1951         /* the following is parent process */
1952         if ((fp = fdopen(fd[0], "r")) == NULL) {
1953                 perror("fdopen");
1954                 kill(pid, SIGKILL);
1955                 close(fd[0]);
1956                 return -1;
1957         }
1958
1959         while (fgets(buf, PIPE_BUF, fp) != NULL) {
1960                 if (output_func(buf) < 0)
1961                         fprintf(stderr, "WARNING: unexpected error!\n[%s]\n",
1962                                 buf);
1963         }
1964         fclose(fp);
1965         close(fd[0]);
1966
1967         if (waitpid(pid, &status, 0) < 0) {
1968                 perror("waitpid");
1969                 return -1;
1970         }
1971
1972         return child_status(status);
1973 }
1974
1975 int llapi_lsetfacl(int argc, char *argv[])
1976 {
1977         return do_rmtacl(argc, argv, RMT_LSETFACL, NULL);
1978 }
1979
1980 int llapi_lgetfacl(int argc, char *argv[])
1981 {
1982         return do_rmtacl(argc, argv, RMT_LGETFACL, NULL);
1983 }
1984
1985 int llapi_rsetfacl(int argc, char *argv[])
1986 {
1987         return do_rmtacl(argc, argv, RMT_RSETFACL, NULL);
1988 }
1989
1990 int llapi_rgetfacl(int argc, char *argv[])
1991 {
1992         return do_rmtacl(argc, argv, RMT_RGETFACL, rgetfacl_output);
1993 }
1994
1995 int llapi_cp(int argc, char *argv[])
1996 {
1997         int rc;
1998
1999         rc = rmtacl_notify(RMT_RSETFACL);
2000         if (rc < 0)
2001                 return -1;
2002
2003         exit(execvp(argv[0], argv));
2004 }
2005
2006 int llapi_ls(int argc, char *argv[])
2007 {
2008         int rc;
2009
2010         rc = rmtacl_notify(RMT_LGETFACL);
2011         if (rc < 0)
2012                 return -1;
2013
2014         exit(execvp(argv[0], argv));
2015 }