Whamcloud - gitweb
b=20030
[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  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/utils/liblustreapi.c
37  *
38  * Author: Peter J. Braam <braam@clusterfs.com>
39  * Author: Phil Schwan <phil@clusterfs.com>
40  * Author: Robert Read <rread@clusterfs.com>
41  */
42
43 /* for O_DIRECTORY */
44 #ifndef _GNU_SOURCE
45 #define _GNU_SOURCE
46 #endif
47
48 #include <stdlib.h>
49 #include <stdio.h>
50 #include <string.h>
51 #include <stddef.h>
52 #include <sys/ioctl.h>
53 #include <unistd.h>
54 #include <fcntl.h>
55 #include <errno.h>
56 #include <dirent.h>
57 #include <stdarg.h>
58 #include <sys/stat.h>
59 #include <sys/types.h>
60 #include <sys/syscall.h>
61 #include <fnmatch.h>
62 #include <glob.h>
63 #ifdef HAVE_LINUX_UNISTD_H
64 #include <linux/unistd.h>
65 #else
66 #include <unistd.h>
67 #endif
68 #include <poll.h>
69
70 #include <liblustre.h>
71 #include <lnet/lnetctl.h>
72 #include <obd.h>
73 #include <lustre_lib.h>
74 #include <obd_lov.h>
75 #include <lustre/liblustreapi.h>
76
77 static unsigned llapi_dir_filetype_table[] = {
78         [DT_UNKNOWN]= 0,
79         [DT_FIFO]= S_IFIFO,
80         [DT_CHR] = S_IFCHR,
81         [DT_DIR] = S_IFDIR,
82         [DT_BLK] = S_IFBLK,
83         [DT_REG] = S_IFREG,
84         [DT_LNK] = S_IFLNK,
85         [DT_SOCK]= S_IFSOCK,
86 #if defined(DT_DOOR) && defined(S_IFDOOR)
87         [DT_DOOR]= S_IFDOOR,
88 #endif
89 };
90
91 #if defined(DT_DOOR) && defined(S_IFDOOR)
92 static const int DT_MAX = DT_DOOR;
93 #else
94 static const int DT_MAX = DT_SOCK;
95 #endif
96
97 static unsigned llapi_filetype_dir_table[] = {
98         [0]= DT_UNKNOWN,
99         [S_IFIFO]= DT_FIFO,
100         [S_IFCHR] = DT_CHR,
101         [S_IFDIR] = DT_DIR,
102         [S_IFBLK] = DT_BLK,
103         [S_IFREG] = DT_REG,
104         [S_IFLNK] = DT_LNK,
105         [S_IFSOCK]= DT_SOCK,
106 #if defined(DT_DOOR) && defined(S_IFDOOR)
107         [S_IFDOOR]= DT_DOOR,
108 #endif
109 };
110
111 #if defined(DT_DOOR) && defined(S_IFDOOR)
112 static const int S_IFMAX = DT_DOOR;
113 #else
114 static const int S_IFMAX = DT_SOCK;
115 #endif
116
117 /* liblustreapi message level */
118 static int llapi_msg_level = LLAPI_MSG_MAX;
119
120 void llapi_msg_set_level(int level)
121 {
122         /* ensure level is in the good range */
123         if (level < LLAPI_MSG_OFF)
124                 llapi_msg_level = LLAPI_MSG_OFF;
125         else if (level > LLAPI_MSG_MAX)
126                 llapi_msg_level = LLAPI_MSG_MAX;
127         else
128                 llapi_msg_level = level;
129 }
130
131 void llapi_err(int level, char *fmt, ...)
132 {
133         va_list args;
134         int tmp_errno = abs(errno);
135
136         if ((level & LLAPI_MSG_MASK) > llapi_msg_level)
137                 return;
138
139         va_start(args, fmt);
140         vfprintf(stderr, fmt, args);
141         va_end(args);
142
143         if (level & LLAPI_MSG_NO_ERRNO)
144                 fprintf(stderr, "\n");
145         else
146                 fprintf(stderr, ": %s (%d)\n", strerror(tmp_errno), tmp_errno);
147 }
148
149 #define llapi_err_noerrno(level, fmt, a...)                             \
150         llapi_err((level) | LLAPI_MSG_NO_ERRNO, fmt, ## a)
151
152 void llapi_printf(int level, char *fmt, ...)
153 {
154         va_list args;
155
156         if ((level & LLAPI_MSG_MASK) > llapi_msg_level)
157                 return;
158
159         va_start(args, fmt);
160         vfprintf(stdout, fmt, args);
161         va_end(args);
162 }
163
164 /**
165  * size_units is unchanged if no specifier used
166  */
167 int parse_size(char *optarg, unsigned long long *size,
168                unsigned long long *size_units, int bytes_spec)
169 {
170         char *end;
171
172         *size = strtoull(optarg, &end, 0);
173
174         if (*end != '\0') {
175                 if ((*end == 'b') && *(end+1) == '\0' &&
176                     (*size & (~0ULL << (64 - 9))) == 0 &&
177                     !bytes_spec) {
178                         *size <<= 9;
179                         *size_units = 1 << 9;
180                 } else if ((*end == 'b') && *(end+1) == '\0' &&
181                            bytes_spec) {
182                         *size_units = 1;
183                 } else if ((*end == 'k' || *end == 'K') &&
184                            *(end+1) == '\0' && (*size &
185                            (~0ULL << (64 - 10))) == 0) {
186                         *size <<= 10;
187                         *size_units = 1 << 10;
188                 } else if ((*end == 'm' || *end == 'M') &&
189                            *(end+1) == '\0' && (*size &
190                            (~0ULL << (64 - 20))) == 0) {
191                         *size <<= 20;
192                         *size_units = 1 << 20;
193                 } else if ((*end == 'g' || *end == 'G') &&
194                            *(end+1) == '\0' && (*size &
195                            (~0ULL << (64 - 30))) == 0) {
196                         *size <<= 30;
197                         *size_units = 1 << 30;
198                 } else if ((*end == 't' || *end == 'T') &&
199                            *(end+1) == '\0' && (*size &
200                            (~0ULL << (64 - 40))) == 0) {
201                         *size <<= 40;
202                         *size_units = 1ULL << 40;
203                 } else if ((*end == 'p' || *end == 'P') &&
204                            *(end+1) == '\0' && (*size &
205                            (~0ULL << (64 - 50))) == 0) {
206                         *size <<= 50;
207                         *size_units = 1ULL << 50;
208                 } else if ((*end == 'e' || *end == 'E') &&
209                            *(end+1) == '\0' && (*size &
210                            (~0ULL << (64 - 60))) == 0) {
211                         *size <<= 60;
212                         *size_units = 1ULL << 60;
213                 } else {
214                         return -1;
215                 }
216         }
217
218         return 0;
219 }
220
221 int llapi_stripe_limit_check(unsigned long long stripe_size, int stripe_offset,
222                              int stripe_count, int stripe_pattern)
223 {
224         int page_size;
225
226         /* 64 KB is the largest common page size I'm aware of (on ia64), but
227          * check the local page size just in case. */
228         page_size = LOV_MIN_STRIPE_SIZE;
229         if (getpagesize() > page_size) {
230                 page_size = getpagesize();
231                 llapi_err_noerrno(LLAPI_MSG_WARN,
232                                   "warning: your page size (%u) is "
233                                   "larger than expected (%u)", page_size,
234                                   LOV_MIN_STRIPE_SIZE);
235         }
236         if (stripe_size < 0 || (stripe_size & (LOV_MIN_STRIPE_SIZE - 1))) {
237                 llapi_err(LLAPI_MSG_ERROR, "error: bad stripe_size %lu, "
238                           "must be an even multiple of %d bytes",
239                           stripe_size, page_size);
240                 return -EINVAL;
241         }
242         if (stripe_offset < -1 || stripe_offset > MAX_OBD_DEVICES) {
243                 errno = -EINVAL;
244                 llapi_err(LLAPI_MSG_ERROR, "error: bad stripe offset %d",
245                           stripe_offset);
246                 return -EINVAL;
247         }
248         if (stripe_count < -1 || stripe_count > LOV_MAX_STRIPE_COUNT) {
249                 errno = -EINVAL;
250                 llapi_err(LLAPI_MSG_ERROR, "error: bad stripe count %d",
251                           stripe_count);
252                 return -EINVAL;
253         }
254         if (stripe_size >= (1ULL << 32)){
255                 errno = -EINVAL;
256                 llapi_err(LLAPI_MSG_ERROR, "warning: stripe size larger than 4G"
257                           " is not currently supported and would wrap");
258                 return -EINVAL;
259         }
260         return 0;
261 }
262
263 static int poolpath(char *fsname, char *pathname, char *pool_pathname);
264
265 int llapi_file_open_pool(const char *name, int flags, int mode,
266                          unsigned long long stripe_size, int stripe_offset,
267                          int stripe_count, int stripe_pattern, char *pool_name)
268 {
269         struct lov_user_md_v3 lum = { 0 };
270         int fd, rc = 0;
271         int isdir = 0;
272         char fsname[MAX_OBD_NAME + 1], *ptr;
273
274         fd = open(name, flags | O_LOV_DELAY_CREATE, mode);
275         if (fd < 0 && errno == EISDIR) {
276                 fd = open(name, O_DIRECTORY | O_RDONLY);
277                 isdir++;
278         }
279
280         if (fd < 0) {
281                 rc = -errno;
282                 llapi_err(LLAPI_MSG_ERROR, "unable to open '%s'", name);
283                 return rc;
284         }
285
286         if ((rc = llapi_stripe_limit_check(stripe_size, stripe_offset,
287                                            stripe_count, stripe_pattern)) != 0){
288                 errno = rc;
289                 goto out;
290         }
291
292         /*  Initialize IOCTL striping pattern structure */
293         lum.lmm_magic = LOV_USER_MAGIC_V3;
294         lum.lmm_pattern = stripe_pattern;
295         lum.lmm_stripe_size = stripe_size;
296         lum.lmm_stripe_count = stripe_count;
297         lum.lmm_stripe_offset = stripe_offset;
298
299         /* in case user give the full pool name <fsname>.<poolname>, skip
300          * the fsname */
301         if (pool_name != NULL) {
302                 ptr = strchr(pool_name, '.');
303                 if (ptr != NULL) {
304                         strncpy(fsname, pool_name, ptr - pool_name);
305                         *ptr = '\0';
306                         /* if fsname matches a filesystem skip it
307                          * if not keep the poolname as is */
308                         if (poolpath(fsname, NULL, NULL) == 0)
309                                 pool_name = ptr + 1;
310                 }
311                 strncpy(lum.lmm_pool_name, pool_name, LOV_MAXPOOLNAME);
312         } else {
313                 /* If no pool is specified at all, use V1 request */
314                 lum.lmm_magic = LOV_USER_MAGIC_V1;
315         }
316
317         if (ioctl(fd, LL_IOC_LOV_SETSTRIPE, &lum)) {
318                 char *errmsg = "stripe already set";
319                 rc = -errno;
320                 if (errno != EEXIST && errno != EALREADY)
321                         errmsg = strerror(errno);
322
323                 llapi_err_noerrno(LLAPI_MSG_ERROR,
324                                   "error on ioctl "LPX64" for '%s' (%d): %s",
325                                   (__u64)LL_IOC_LOV_SETSTRIPE, name, fd,errmsg);
326         }
327 out:
328         if (rc) {
329                 close(fd);
330                 fd = rc;
331         }
332
333         return fd;
334 }
335
336 int llapi_file_open(const char *name, int flags, int mode,
337                     unsigned long long stripe_size, int stripe_offset,
338                     int stripe_count, int stripe_pattern)
339 {
340         return llapi_file_open_pool(name, flags, mode, stripe_size,
341                                     stripe_offset, stripe_count,
342                                     stripe_pattern, NULL);
343 }
344
345 int llapi_file_create(const char *name, unsigned long long stripe_size,
346                       int stripe_offset, int stripe_count, int stripe_pattern)
347 {
348         int fd;
349
350         fd = llapi_file_open_pool(name, O_CREAT | O_WRONLY, 0644, stripe_size,
351                                   stripe_offset, stripe_count, stripe_pattern,
352                                   NULL);
353         if (fd < 0)
354                 return fd;
355
356         close(fd);
357         return 0;
358 }
359
360 int llapi_file_create_pool(const char *name, unsigned long long stripe_size,
361                            int stripe_offset, int stripe_count,
362                            int stripe_pattern, char *pool_name)
363 {
364         int fd;
365
366         fd = llapi_file_open_pool(name, O_CREAT | O_WRONLY, 0644, stripe_size,
367                                   stripe_offset, stripe_count, stripe_pattern,
368                                   pool_name);
369         if (fd < 0)
370                 return fd;
371
372         close(fd);
373         return 0;
374 }
375
376 static int print_pool_members(char *fs, char *pool_dir, char *pool_file)
377 {
378         char path[PATH_MAX + 1];
379         char buf[1024];
380         FILE *fd;
381
382         llapi_printf(LLAPI_MSG_NORMAL, "Pool: %s.%s\n", fs, pool_file);
383         sprintf(path, "%s/%s", pool_dir, pool_file);
384         if ((fd = fopen(path, "r")) == NULL) {
385                 llapi_err(LLAPI_MSG_ERROR, "Cannot open %s\n", path);
386                 return -EINVAL;
387         }
388         while (fgets(buf, sizeof(buf), fd) != NULL)
389                llapi_printf(LLAPI_MSG_NORMAL, buf);
390
391         fclose(fd);
392         return 0;
393 }
394
395 /*
396  * Find the fsname, the full path, and/or an open fd.
397  * Either the fsname or path must not be NULL
398  */
399 #define WANT_PATH   0x1
400 #define WANT_FSNAME 0x2
401 #define WANT_FD     0x4
402 static int get_root_path(int want, char *fsname, int *outfd, char *path)
403 {
404         struct mntent mnt;
405         char buf[PATH_MAX];
406         char *ptr;
407         FILE *fp;
408         int fd;
409         int rc = -ENODEV;
410
411         /* get the mount point */
412         fp = setmntent(MOUNTED, "r");
413         if (fp == NULL) {
414                  llapi_err(LLAPI_MSG_ERROR,
415                            "setmntent(%s) failed: %s:", MOUNTED,
416                            strerror (errno));
417                  return -EIO;
418         }
419         while (1) {
420                 if (getmntent_r(fp, &mnt, buf, sizeof(buf)) == NULL)
421                         break;
422
423                 if (!llapi_is_lustre_mnt(&mnt))
424                         continue;
425
426                 ptr = strrchr(mnt.mnt_fsname, '/');
427                 if (!ptr) {
428                         rc = -EINVAL;
429                         break;
430                 }
431                 ptr++;
432
433                 /* If path was specified and matches, store the fsname */
434                 if ((want & WANT_FSNAME) && (strcmp(mnt.mnt_dir, path) == 0))
435                         strcpy(fsname, ptr);
436                 /* Else check the fsname for a match */
437                 else if (strcmp(ptr, fsname) != 0)
438                         continue;
439
440                 /* Found it */
441                 rc = 0;
442                 if (want & WANT_PATH)
443                         strcpy(path, mnt.mnt_dir);
444                 if (want & WANT_FD) {
445                         fd = open(mnt.mnt_dir,
446                                   O_RDONLY | O_DIRECTORY | O_NONBLOCK);
447                         if (fd < 0) {
448                                 perror("open");
449                                 rc = -errno;
450                         } else {
451                                 *outfd = fd;
452                         }
453                 }
454                 break;
455         }
456         endmntent(fp);
457         if (rc)
458                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
459                           "can't find fs root for '%s': %d",
460                           (want & WANT_PATH) ? fsname : path, rc);
461         return rc;
462 }
463
464 int llapi_search_fsname(const char *pathname, char *fsname)
465 {
466         return get_root_path(WANT_FSNAME, fsname, NULL, (char *)pathname);
467 }
468
469 /* return the first file matching this pattern */
470 static int first_match(char *pattern, char *buffer)
471 {
472         glob_t glob_info;
473
474         if (glob(pattern, GLOB_BRACE, NULL, &glob_info))
475                 return -ENOENT;
476
477         if (glob_info.gl_pathc < 1) {
478                 globfree(&glob_info);
479                 return -ENOENT;
480         }
481
482         strcpy(buffer, glob_info.gl_pathv[0]);
483
484         globfree(&glob_info);
485         return 0;
486 }
487
488 /*
489  * find the pool directory path under /proc
490  * (can be also used to test if a fsname is known)
491  */
492 static int poolpath(char *fsname, char *pathname, char *pool_pathname)
493 {
494         int rc = 0;
495         char pattern[PATH_MAX + 1];
496         char buffer[PATH_MAX];
497
498         if (fsname == NULL) {
499                 rc = get_root_path(WANT_FSNAME, buffer, NULL, pathname);
500                 if (rc != 0)
501                         return rc;
502                 fsname = buffer;
503                 strcpy(pathname, fsname);
504         }
505
506         snprintf(pattern, PATH_MAX, "/proc/fs/lustre/lov/%s-*/pools", fsname);
507         rc = first_match(pattern, buffer);
508         if (rc)
509                 return rc;
510
511         /* in fsname test mode, pool_pathname is NULL */
512         if (pool_pathname != NULL)
513                 strcpy(pool_pathname, buffer);
514
515         return 0;
516 }
517
518 int llapi_poollist(char *name)
519 {
520         char *poolname;
521         char *fsname;
522         char rname[PATH_MAX + 1], pathname[PATH_MAX + 1];
523         char *ptr;
524         int rc = 0;
525
526         /* is name a pathname ? */
527         ptr = strchr(name, '/');
528         if (ptr != NULL) {
529                 /* only absolute pathname is supported */
530                 if (*name != '/')
531                         return -EINVAL;
532                 if (!realpath(name, rname)) {
533                         rc = -errno;
534                         llapi_err(LLAPI_MSG_ERROR, "invalid path '%s'", name);
535                         return rc;
536                 }
537
538                 rc = poolpath(NULL, rname, pathname);
539                 if (rc != 0) {
540                         errno = -rc;
541                         llapi_err(LLAPI_MSG_ERROR, "'%s' is not"
542                                   " a Lustre filesystem", name);
543                         return rc;
544                 }
545                 fsname = rname;
546                 poolname = NULL;
547         } else {
548                 /* name is FSNAME[.POOLNAME] */
549                 fsname = name;
550                 poolname = strchr(name, '.');
551                 if (poolname != NULL) {
552                         *poolname = '\0';
553                         poolname++;
554                 }
555                 rc = poolpath(fsname, NULL, pathname);
556         }
557         if (rc != 0) {
558                 errno = -rc;
559                 llapi_err(LLAPI_MSG_ERROR, "Lustre filesystem '%s' not found",
560                           name);
561                 return rc;
562         }
563
564         if (poolname != NULL) {
565                 rc = print_pool_members(fsname, pathname, poolname);
566                 poolname--;
567                 *poolname = '.';
568         } else {
569                 DIR *dir;
570                 struct dirent *pool;
571
572                 llapi_printf(LLAPI_MSG_NORMAL, "Pools from %s:\n", fsname);
573                 if ((dir = opendir(pathname)) == NULL) {
574                         return -EINVAL;
575                 }
576                 while ((pool = readdir(dir)) != NULL) {
577                         if (!((pool->d_name[0] == '.') &&
578                               (pool->d_name[1] == '\0')) &&
579                             !((pool->d_name[0] == '.') &&
580                               (pool->d_name[1] == '.') &&
581                               (pool->d_name[2] == '\0')))
582                         llapi_printf(LLAPI_MSG_NORMAL, " %s.%s\n",
583                                      fsname, pool->d_name);
584                 }
585                 closedir(dir);
586         }
587         return rc;
588 }
589
590 typedef int (semantic_func_t)(char *path, DIR *parent, DIR *d,
591                               void *data, cfs_dirent_t *de);
592
593 #define MAX_LOV_UUID_COUNT      max(LOV_MAX_STRIPE_COUNT, 1000)
594 #define OBD_NOT_FOUND           (-1)
595
596 static int common_param_init(struct find_param *param)
597 {
598         param->lumlen = lov_mds_md_size(MAX_LOV_UUID_COUNT, LOV_MAGIC_V3);
599         if ((param->lmd = malloc(sizeof(lstat_t) + param->lumlen)) == NULL) {
600                 llapi_err(LLAPI_MSG_ERROR,
601                           "error: allocation of %d bytes for ioctl",
602                           sizeof(lstat_t) + param->lumlen);
603                 return -ENOMEM;
604         }
605
606         param->got_uuids = 0;
607         param->obdindexes = NULL;
608         param->obdindex = OBD_NOT_FOUND;
609         return 0;
610 }
611
612 static void find_param_fini(struct find_param *param)
613 {
614         if (param->obdindexes)
615                 free(param->obdindexes);
616
617         if (param->lmd)
618                 free(param->lmd);
619 }
620
621 int llapi_file_fget_lov_uuid(int fd, struct obd_uuid *lov_name)
622 {
623         int rc = ioctl(fd, OBD_IOC_GETNAME, lov_name);
624         if (rc) {
625                 rc = errno;
626                 llapi_err(LLAPI_MSG_ERROR, "error: can't get lov name.");
627         }
628         return rc;
629 }
630
631 int llapi_file_get_lov_uuid(const char *path, struct obd_uuid *lov_uuid)
632 {
633         int fd, rc;
634
635         fd = open(path, O_RDONLY);
636         if (fd < 0) {
637                 rc = errno;
638                 llapi_err(LLAPI_MSG_ERROR, "error opening %s", path);
639                 return rc;
640         }
641
642         rc = llapi_file_fget_lov_uuid(fd, lov_uuid);
643
644         close(fd);
645
646         return rc;
647 }
648
649 /*
650  * If uuidp is NULL, return the number of available obd uuids.
651  * If uuidp is non-NULL, then it will return the uuids of the obds. If
652  * there are more OSTs then allocated to uuidp, then an error is returned with
653  * the ost_count set to number of available obd uuids.
654  */
655 int llapi_lov_get_uuids(int fd, struct obd_uuid *uuidp, int *ost_count)
656 {
657         struct obd_uuid lov_name;
658         char buf[1024];
659         FILE *fp;
660         int rc = 0, index = 0;
661
662         /* Get the lov name */
663         rc = llapi_file_fget_lov_uuid(fd, &lov_name);
664         if (rc)
665                 return rc;
666
667         /* Now get the ost uuids from /proc */
668         snprintf(buf, sizeof(buf), "/proc/fs/lustre/lov/%s/target_obd",
669                  lov_name.uuid);
670         fp = fopen(buf, "r");
671         if (fp == NULL) {
672                 rc = errno;
673                 llapi_err(LLAPI_MSG_ERROR, "error: opening '%s'", buf);
674                 return rc;
675         }
676
677         while (fgets(buf, sizeof(buf), fp) != NULL) {
678                 if (uuidp && (index < *ost_count)) {
679                         if (sscanf(buf, "%d: %s", &index, uuidp[index].uuid) <2)
680                                 break;
681                 }
682                 index++;
683         }
684
685         fclose(fp);
686
687         if (uuidp && (index >= *ost_count))
688                 return -EOVERFLOW;
689
690         *ost_count = index;
691         return rc;
692 }
693
694 int llapi_get_obd_count(char *mnt, int *count, int is_mdt)
695 {
696         DIR *root;
697         int rc;
698
699         root = opendir(mnt);
700         if (!root) {
701                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
702                 return -1;
703         }
704
705         *count = is_mdt;
706         rc = ioctl(dirfd(root), LL_IOC_GETOBDCOUNT, count);
707
708         closedir(root);
709         return rc;
710 }
711
712 /* Here, param->obduuid points to a single obduuid, the index of which is
713  * returned in param->obdindex */
714 static int setup_obd_uuid(DIR *dir, char *dname, struct find_param *param)
715 {
716         struct obd_uuid lov_uuid;
717         char uuid[sizeof(struct obd_uuid)];
718         char buf[1024];
719         FILE *fp;
720         int rc = 0, index;
721
722         /* Get the lov name */
723         rc = llapi_file_fget_lov_uuid(dirfd(dir), &lov_uuid);
724         if (rc) {
725                 if (errno != ENOTTY) {
726                         rc = errno;
727                         llapi_err(LLAPI_MSG_ERROR,
728                                   "error: can't get lov name: %s", dname);
729                 } else {
730                         rc = 0;
731                 }
732                 return rc;
733         }
734
735         param->got_uuids = 1;
736
737         /* Now get the ost uuids from /proc */
738         snprintf(buf, sizeof(buf), "/proc/fs/lustre/lov/%s/target_obd",
739                  lov_uuid.uuid);
740         fp = fopen(buf, "r");
741         if (fp == NULL) {
742                 rc = errno;
743                 llapi_err(LLAPI_MSG_ERROR, "error: opening '%s'", buf);
744                 return rc;
745         }
746
747         if (!param->obduuid && !param->quiet && !param->obds_printed)
748                 llapi_printf(LLAPI_MSG_NORMAL, "OBDS:\n");
749
750         while (fgets(buf, sizeof(buf), fp) != NULL) {
751                 if (sscanf(buf, "%d: %s", &index, uuid) < 2)
752                         break;
753
754                 if (param->obduuid) {
755                         if (strncmp(param->obduuid->uuid, uuid,
756                                     sizeof(uuid)) == 0) {
757                                 param->obdindex = index;
758                                 break;
759                         }
760                 } else if (!param->quiet && !param->obds_printed) {
761                         /* Print everything */
762                         llapi_printf(LLAPI_MSG_NORMAL, "%s", buf);
763                 }
764         }
765         param->obds_printed = 1;
766
767         fclose(fp);
768
769         if (!param->quiet && param->obduuid &&
770             (param->obdindex == OBD_NOT_FOUND)) {
771                 llapi_err_noerrno(LLAPI_MSG_ERROR,
772                                   "error: %s: unknown obduuid: %s",
773                                   __FUNCTION__, param->obduuid->uuid);
774                 //rc = EINVAL;
775         }
776
777         return (rc);
778 }
779
780 /* In this case, param->obduuid will be an array of obduuids and
781  * obd index for all these obduuids will be returned in
782  * param->obdindexes */
783 static int setup_obd_indexes(DIR *dir, struct find_param *param)
784 {
785         struct obd_uuid *uuids = NULL;
786         int obdcount = INIT_ALLOC_NUM_OSTS;
787         int ret, obd_valid = 0, obdnum, i;
788
789         uuids = (struct obd_uuid *)malloc(INIT_ALLOC_NUM_OSTS *
790                                           sizeof(struct obd_uuid));
791         if (uuids == NULL)
792                 return -ENOMEM;
793
794 retry_get_uuids:
795         ret = llapi_lov_get_uuids(dirfd(dir), uuids,
796                                   &obdcount);
797         if (ret) {
798                 struct obd_uuid *uuids_temp;
799
800                 if (ret == -EOVERFLOW) {
801                         uuids_temp = realloc(uuids, obdcount *
802                                              sizeof(struct obd_uuid));
803                         if (uuids_temp != NULL)
804                                 goto retry_get_uuids;
805                         else
806                                 ret = -ENOMEM;
807                 }
808
809                 llapi_err(LLAPI_MSG_ERROR, "get ost uuid failed");
810                 return ret;
811         }
812
813         param->obdindexes = malloc(param->num_obds * sizeof(param->obdindex));
814         if (param->obdindexes == NULL)
815                 return -ENOMEM;
816
817         for (obdnum = 0; obdnum < param->num_obds; obdnum++) {
818                 for (i = 0; i <= obdcount; i++) {
819                         if (strcmp((char *)&param->obduuid[obdnum].uuid,
820                                    (char *)&uuids[i]) == 0) {
821                                 param->obdindexes[obdnum] = i;
822                                 obd_valid++;
823                                 break;
824                         }
825                 }
826                 if (i == obdcount)
827                         param->obdindexes[obdnum] = OBD_NOT_FOUND;
828         }
829
830         if (obd_valid == 0)
831                 param->obdindex = OBD_NOT_FOUND;
832         else
833                 param->obdindex = obd_valid;
834
835         param->got_uuids = 1;
836
837         return 0;
838 }
839
840 static void lov_dump_user_lmm_header(struct lov_user_md *lum, char *path,
841                                      int is_dir, int verbose, int quiet,
842                                      char *pool_name)
843 {
844         char *prefix = is_dir ? "" : "lmm_";
845         char nl = is_dir ? ' ' : '\n';
846
847         if (verbose && path)
848                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
849
850         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
851                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_magic:          0x%08X\n",
852                              lum->lmm_magic);
853                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_gr:      "LPX64"\n",
854                              lum->lmm_object_gr);
855                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_object_id:      "LPX64"\n",
856                              lum->lmm_object_id);
857         }
858
859         if (verbose & VERBOSE_COUNT) {
860                 if (!quiet)
861                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_count:   ",
862                                      prefix);
863                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
864                              (int)lum->lmm_stripe_count, nl);
865         }
866
867         if (verbose & VERBOSE_SIZE) {
868                 if (!quiet)
869                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_size:    ",
870                                      prefix);
871                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c", lum->lmm_stripe_size,
872                              nl);
873         }
874
875         if ((verbose & VERBOSE_DETAIL) && !is_dir) {
876                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_stripe_pattern: %x%c",
877                              lum->lmm_pattern, nl);
878         }
879
880         if (verbose & VERBOSE_OFFSET) {
881                 if (!quiet)
882                         llapi_printf(LLAPI_MSG_NORMAL, "%sstripe_offset:   ",
883                                      prefix);
884                 llapi_printf(LLAPI_MSG_NORMAL, "%u%c",
885                              lum->lmm_objects[0].l_ost_idx, nl);
886         }
887
888         if ((verbose & VERBOSE_POOL) && (pool_name != NULL))
889                 llapi_printf(LLAPI_MSG_NORMAL, "pool: %s%c", pool_name, nl);
890
891         if (is_dir)
892                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
893 }
894
895 void lov_dump_user_lmm_v1v3(struct lov_user_md *lum, char *pool_name,
896                             struct lov_user_ost_data_v1 *objects,
897                             char *path, int is_dir,
898                             int obdindex, int quiet, int header, int body)
899 {
900         int i, obdstripe = 0;
901
902         if (obdindex != OBD_NOT_FOUND) {
903                 for (i = 0; !is_dir && i < lum->lmm_stripe_count; i++) {
904                         if (obdindex == objects[i].l_ost_idx) {
905                                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
906                                 obdstripe = 1;
907                                 break;
908                         }
909                 }
910         } else {
911                 if (!quiet)
912                         llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
913                 obdstripe = 1;
914         }
915
916         /* if it's a directory */
917         if (is_dir) {
918                 if (obdstripe == 1) {
919                         if (lum->lmm_object_gr == LOV_OBJECT_GROUP_DEFAULT) {
920                                 llapi_printf(LLAPI_MSG_NORMAL, "(Default) ");
921                                 lum->lmm_object_gr = LOV_OBJECT_GROUP_CLEAR;
922                         }
923                         /* maintain original behavior */
924                         if (!header)
925                                 header |= VERBOSE_ALL;
926                         lov_dump_user_lmm_header(lum, path, is_dir, header,
927                                                  quiet, pool_name);
928                 }
929                 return;
930         }
931
932         if (header && (obdstripe == 1))
933                 lov_dump_user_lmm_header(lum, NULL, is_dir, header, quiet,
934                                          pool_name);
935
936         if (body) {
937                 if ((!quiet) && (obdstripe == 1))
938                         llapi_printf(LLAPI_MSG_NORMAL,
939                                      "\tobdidx\t\t objid\t\tobjid\t\t group\n");
940
941                 for (i = 0; i < lum->lmm_stripe_count; i++) {
942                         int idx = objects[i].l_ost_idx;
943                         long long oid = objects[i].l_object_id;
944                         long long gr = objects[i].l_object_gr;
945                         if ((obdindex == OBD_NOT_FOUND) || (obdindex == idx))
946                                 llapi_printf(LLAPI_MSG_NORMAL,
947                                            "\t%6u\t%14llu\t%#13llx\t%14llu%s\n",
948                                            idx, oid, oid, gr,
949                                            obdindex == idx ? " *" : "");
950                 }
951                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
952         }
953 }
954
955 void lov_dump_user_lmm_join(struct lov_user_md_v1 *lum, char *path,
956                             int is_dir, int obdindex, int quiet,
957                             int header, int body)
958 {
959         struct lov_user_md_join *lumj = (struct lov_user_md_join *)lum;
960         int i, obdstripe = 0;
961
962         if (obdindex != OBD_NOT_FOUND) {
963                 for (i = 0; i < lumj->lmm_stripe_count; i++) {
964                         if (obdindex == lumj->lmm_objects[i].l_ost_idx) {
965                                 llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
966                                 obdstripe = 1;
967                                 break;
968                         }
969                 }
970         } else {
971                 if (!quiet)
972                         llapi_printf(LLAPI_MSG_NORMAL, "%s\n", path);
973                 obdstripe = 1;
974         }
975
976         if (header && obdstripe == 1) {
977                 lov_dump_user_lmm_header(lum, NULL, 0, header, quiet, NULL);
978
979                 llapi_printf(LLAPI_MSG_NORMAL, "lmm_extent_count:   %x\n",
980                              lumj->lmm_extent_count);
981         }
982
983         if (body) {
984                 unsigned long long start = -1, end = 0;
985                 if (!quiet && obdstripe == 1)
986                         llapi_printf(LLAPI_MSG_NORMAL,
987                                      "joined\tobdidx\t\t objid\t\tobjid\t\t "
988                                      "group\t\tstart\t\tend\n");
989                 for (i = 0; i < lumj->lmm_stripe_count; i++) {
990                         int idx = lumj->lmm_objects[i].l_ost_idx;
991                         long long oid = lumj->lmm_objects[i].l_object_id;
992                         long long gr = lumj->lmm_objects[i].l_object_gr;
993                         if (obdindex == OBD_NOT_FOUND || obdindex == idx)
994                                 llapi_printf(LLAPI_MSG_NORMAL,
995                                              "\t%6u\t%14llu\t%#13llx\t%14llu%s",
996                                              idx, oid, oid, gr,
997                                              obdindex == idx ? " *" : "");
998                         if (start != lumj->lmm_objects[i].l_extent_start ||
999                             end != lumj->lmm_objects[i].l_extent_end) {
1000                                 start = lumj->lmm_objects[i].l_extent_start;
1001                                 llapi_printf(LLAPI_MSG_NORMAL,"\t%14llu",start);
1002                                 end = lumj->lmm_objects[i].l_extent_end;
1003                                 if (end == (unsigned long long)-1)
1004                                         llapi_printf(LLAPI_MSG_NORMAL,
1005                                                      "\t\tEOF\n");
1006                                 else
1007                                         llapi_printf(LLAPI_MSG_NORMAL,
1008                                                      "\t\t%llu\n", end);
1009                         } else {
1010                                 llapi_printf(LLAPI_MSG_NORMAL, "\t\t\t\t\n");
1011                         }
1012                 }
1013                 llapi_printf(LLAPI_MSG_NORMAL, "\n");
1014         }
1015 }
1016
1017 void llapi_lov_dump_user_lmm(struct find_param *param,
1018                              char *path, int is_dir)
1019 {
1020         switch(*(__u32 *)&param->lmd->lmd_lmm) { /* lum->lmm_magic */
1021         case LOV_USER_MAGIC_V1:
1022                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, NULL,
1023                                        param->lmd->lmd_lmm.lmm_objects,
1024                                        path, is_dir,
1025                                        param->obdindex, param->quiet,
1026                                        param->verbose,
1027                                        (param->verbose || !param->obduuid));
1028                 break;
1029         case LOV_USER_MAGIC_JOIN:
1030                 lov_dump_user_lmm_join(&param->lmd->lmd_lmm, path, is_dir,
1031                                        param->obdindex, param->quiet,
1032                                        param->verbose,
1033                                        (param->verbose || !param->obduuid));
1034                 break;
1035         case LOV_USER_MAGIC_V3: {
1036                 char pool_name[LOV_MAXPOOLNAME + 1];
1037                 struct lov_user_ost_data_v1 *objects;
1038                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
1039
1040                 strncpy(pool_name, lmmv3->lmm_pool_name, LOV_MAXPOOLNAME);
1041                 pool_name[LOV_MAXPOOLNAME] = '\0';
1042                 objects = lmmv3->lmm_objects;
1043                 lov_dump_user_lmm_v1v3(&param->lmd->lmd_lmm, pool_name,
1044                                        objects, path, is_dir,
1045                                        param->obdindex, param->quiet,
1046                                        param->verbose,
1047                                        (param->verbose || !param->obduuid));
1048                 break;
1049         }
1050         default:
1051                 llapi_printf(LLAPI_MSG_NORMAL, "unknown lmm_magic:  %#x "
1052                              "(expecting one of %#x %#x %#x)\n",
1053                              *(__u32 *)&param->lmd->lmd_lmm,
1054                              LOV_USER_MAGIC_V1, LOV_USER_MAGIC_JOIN,
1055                              LOV_USER_MAGIC_V3);
1056                 return;
1057         }
1058 }
1059
1060 int llapi_file_get_stripe(const char *path, struct lov_user_md *lum)
1061 {
1062         const char *fname;
1063         char *dname;
1064         int fd, rc = 0;
1065
1066         fname = strrchr(path, '/');
1067
1068         /* It should be a file (or other non-directory) */
1069         if (fname == NULL) {
1070                 dname = (char *)malloc(2);
1071                 if (dname == NULL)
1072                         return ENOMEM;
1073                 strcpy(dname, ".");
1074                 fname = (char *)path;
1075         } else {
1076                 dname = (char *)malloc(fname - path + 1);
1077                 if (dname == NULL)
1078                         return ENOMEM;
1079                 strncpy(dname, path, fname - path);
1080                 dname[fname - path] = '\0';
1081                 fname++;
1082         }
1083
1084         if ((fd = open(dname, O_RDONLY)) == -1) {
1085                 rc = errno;
1086                 free(dname);
1087                 return rc;
1088         }
1089
1090         strcpy((char *)lum, fname);
1091         if (ioctl(fd, IOC_MDC_GETFILESTRIPE, (void *)lum) == -1)
1092                 rc = errno;
1093
1094         if (close(fd) == -1 && rc == 0)
1095                 rc = errno;
1096
1097         free(dname);
1098
1099         return rc;
1100 }
1101
1102 int llapi_file_lookup(int dirfd, const char *name)
1103 {
1104         struct obd_ioctl_data data = { 0 };
1105         char rawbuf[8192];
1106         char *buf = rawbuf;
1107         int rc;
1108
1109         if (dirfd < 0 || name == NULL)
1110                 return -EINVAL;
1111
1112         data.ioc_version = OBD_IOCTL_VERSION;
1113         data.ioc_len = sizeof(data);
1114         data.ioc_inlbuf1 = (char *)name;
1115         data.ioc_inllen1 = strlen(name) + 1;
1116
1117         rc = obd_ioctl_pack(&data, &buf, sizeof(rawbuf));
1118         if (rc) {
1119                 llapi_err(LLAPI_MSG_ERROR,
1120                           "error: IOC_MDC_LOOKUP pack failed for '%s': rc %d",
1121                           name, rc);
1122                 return rc;
1123         }
1124
1125         return ioctl(dirfd, IOC_MDC_LOOKUP, buf);
1126 }
1127
1128 int llapi_mds_getfileinfo(char *path, DIR *parent,
1129                           struct lov_user_mds_data *lmd)
1130 {
1131         lstat_t *st = &lmd->lmd_st;
1132         char *fname = strrchr(path, '/');
1133         int ret = 0;
1134
1135         if (parent == NULL)
1136                 return -EINVAL;
1137
1138         fname = (fname == NULL ? path : fname + 1);
1139         /* retrieve needed file info */
1140         strncpy((char *)lmd, fname,
1141                 lov_mds_md_size(MAX_LOV_UUID_COUNT, LOV_MAGIC));
1142         ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO, (void *)lmd);
1143
1144         if (ret) {
1145                 if (errno == ENOTTY) {
1146                         /* ioctl is not supported, it is not a lustre fs.
1147                          * Do the regular lstat(2) instead. */
1148                         ret = lstat_f(path, st);
1149                         if (ret) {
1150                                 llapi_err(LLAPI_MSG_ERROR,
1151                                           "error: %s: lstat failed for %s",
1152                                           __FUNCTION__, path);
1153                                 return ret;
1154                         }
1155                 } else if (errno == ENOENT) {
1156                         llapi_err(LLAPI_MSG_WARN,
1157                                   "warning: %s: %s does not exist",
1158                                   __FUNCTION__, path);
1159                         return -ENOENT;
1160                 } else {
1161                         llapi_err(LLAPI_MSG_ERROR,
1162                                  "error: %s: IOC_MDC_GETFILEINFO failed for %s",
1163                                  __FUNCTION__, path);
1164                         return ret;
1165                 }
1166         }
1167
1168         return 0;
1169 }
1170
1171 static DIR *opendir_parent(char *path)
1172 {
1173         DIR *parent;
1174         char *fname;
1175         char c;
1176
1177         fname = strrchr(path, '/');
1178         if (fname == NULL)
1179                 return opendir(".");
1180
1181         c = fname[1];
1182         fname[1] = '\0';
1183         parent = opendir(path);
1184         fname[1] = c;
1185         return parent;
1186 }
1187
1188 static int llapi_semantic_traverse(char *path, int size, DIR *parent,
1189                                    semantic_func_t sem_init,
1190                                    semantic_func_t sem_fini, void *data,
1191                                    cfs_dirent_t *de)
1192 {
1193         cfs_dirent_t *dent;
1194         int len, ret;
1195         DIR *d, *p = NULL;
1196
1197         ret = 0;
1198         len = strlen(path);
1199
1200         d = opendir(path);
1201         if (!d && errno != ENOTDIR) {
1202                 llapi_err(LLAPI_MSG_ERROR, "%s: Failed to open '%s'",
1203                           __FUNCTION__, path);
1204                 return -EINVAL;
1205         } else if (!d && !parent) {
1206                 /* ENOTDIR. Open the parent dir. */
1207                 p = opendir_parent(path);
1208                 if (!p)
1209                         GOTO(out, ret = -EINVAL);
1210         }
1211
1212         if (sem_init && (ret = sem_init(path, parent ?: p, d, data, de)))
1213                 goto err;
1214
1215         if (!d)
1216                 GOTO(out, ret = 0);
1217
1218         while ((dent = readdir64(d)) != NULL) {
1219                 ((struct find_param *)data)->have_fileinfo = 0;
1220
1221                 if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
1222                         continue;
1223
1224                 /* Don't traverse .lustre directory */
1225                 if (!(strcmp(dent->d_name, dot_lustre_name)))
1226                         continue;
1227
1228                 path[len] = 0;
1229                 if ((len + dent->d_reclen + 2) > size) {
1230                         llapi_err(LLAPI_MSG_ERROR,
1231                                   "error: %s: string buffer is too small",
1232                                   __FUNCTION__);
1233                         break;
1234                 }
1235                 strcat(path, "/");
1236                 strcat(path, dent->d_name);
1237
1238                 if (dent->d_type == DT_UNKNOWN) {
1239                         lstat_t *st = &((struct find_param *)data)->lmd->lmd_st;
1240
1241                         ret = llapi_mds_getfileinfo(path, d,
1242                                              ((struct find_param *)data)->lmd);
1243                         if (ret == 0) {
1244                                 ((struct find_param *)data)->have_fileinfo = 1;
1245                                 dent->d_type =
1246                                         llapi_filetype_dir_table[st->st_mode &
1247                                                                  S_IFMT];
1248                         }
1249                         if (ret == -ENOENT)
1250                                 continue;
1251                 }
1252
1253                 switch (dent->d_type) {
1254                 case DT_UNKNOWN:
1255                         llapi_err(LLAPI_MSG_ERROR,
1256                                   "error: %s: '%s' is UNKNOWN type %d",
1257                                   __FUNCTION__, dent->d_name, dent->d_type);
1258                         break;
1259                 case DT_DIR:
1260                         ret = llapi_semantic_traverse(path, size, d, sem_init,
1261                                                       sem_fini, data, dent);
1262                         if (ret < 0)
1263                                 goto out;
1264                         break;
1265                 default:
1266                         ret = 0;
1267                         if (sem_init) {
1268                                 ret = sem_init(path, d, NULL, data, dent);
1269                                 if (ret < 0)
1270                                         goto out;
1271                         }
1272                         if (sem_fini && ret == 0)
1273                                 sem_fini(path, d, NULL, data, dent);
1274                 }
1275         }
1276
1277 out:
1278         path[len] = 0;
1279
1280         if (sem_fini)
1281                 sem_fini(path, parent, d, data, de);
1282 err:
1283         if (d)
1284                 closedir(d);
1285         if (p)
1286                 closedir(p);
1287         return ret;
1288 }
1289
1290 /* Check if the value matches 1 of the given criteria (e.g. --atime +/-N).
1291  * @mds indicates if this is MDS timestamps and there are attributes on OSTs.
1292  *
1293  * The result is -1 if it does not match, 0 if not yet clear, 1 if matches.
1294  * The table below gives the answers for the specified parameters (value and
1295  * sign), 1st column is the answer for the MDS value, the 2nd is for the OST:
1296  * --------------------------------------
1297  * 1 | file > limit; sign > 0 | -1 / -1 |
1298  * 2 | file = limit; sign > 0 |  ? /  1 |
1299  * 3 | file < limit; sign > 0 |  ? /  1 |
1300  * 4 | file > limit; sign = 0 | -1 / -1 |
1301  * 5 | file = limit; sign = 0 |  ? /  1 |  <- (see the Note below)
1302  * 6 | file < limit; sign = 0 |  ? / -1 |
1303  * 7 | file > limit; sign < 0 |  1 /  1 |
1304  * 8 | file = limit; sign < 0 |  ? / -1 |
1305  * 9 | file < limit; sign < 0 |  ? / -1 |
1306  * --------------------------------------
1307  * Note: 5th actually means that the value is within the interval
1308  * (limit - margin, limit]. */
1309 static int find_value_cmp(unsigned int file, unsigned int limit, int sign,
1310                           unsigned long long margin, int mds)
1311 {
1312         if (sign > 0) {
1313                 if (file < limit)
1314                         return mds ? 0 : 1;
1315         }
1316
1317         if (sign == 0) {
1318                 if (file <= limit && file + margin > limit)
1319                         return mds ? 0 : 1;
1320                 if (file + margin <= limit)
1321                         return mds ? 0 : -1;
1322         }
1323
1324         if (sign < 0) {
1325                 if (file > limit)
1326                         return 1;
1327                 if (mds)
1328                         return 0;
1329         }
1330
1331         return -1;
1332 }
1333
1334 /* Check if the file time matches all the given criteria (e.g. --atime +/-N).
1335  * Return -1 or 1 if file timestamp does not or does match the given criteria
1336  * correspondingly. Return 0 if the MDS time is being checked and there are
1337  * attributes on OSTs and it is not yet clear if the timespamp matches.
1338  *
1339  * If 0 is returned, we need to do another RPC to the OSTs to obtain the
1340  * updated timestamps. */
1341 static int find_time_check(lstat_t *st, struct find_param *param, int mds)
1342 {
1343         int ret;
1344         int rc = 0;
1345
1346         /* Check if file is accepted. */
1347         if (param->atime) {
1348                 ret = find_value_cmp(st->st_atime, param->atime,
1349                                      param->asign, 24 * 60 * 60, mds);
1350                 if (ret < 0)
1351                         return ret;
1352                 rc = ret;
1353         }
1354
1355         if (param->mtime) {
1356                 ret = find_value_cmp(st->st_mtime, param->mtime,
1357                                      param->msign, 24 * 60 * 60, mds);
1358                 if (ret < 0)
1359                         return ret;
1360
1361                 /* If the previous check matches, but this one is not yet clear,
1362                  * we should return 0 to do an RPC on OSTs. */
1363                 if (rc == 1)
1364                         rc = ret;
1365         }
1366
1367         if (param->ctime) {
1368                 ret = find_value_cmp(st->st_ctime, param->ctime,
1369                                      param->csign, 24 * 60 * 60, mds);
1370                 if (ret < 0)
1371                         return ret;
1372
1373                 /* If the previous check matches, but this one is not yet clear,
1374                  * we should return 0 to do an RPC on OSTs. */
1375                 if (rc == 1)
1376                         rc = ret;
1377         }
1378
1379         return rc;
1380 }
1381
1382 static int cb_find_init(char *path, DIR *parent, DIR *dir,
1383                         void *data, cfs_dirent_t *de)
1384 {
1385         struct find_param *param = (struct find_param *)data;
1386         int decision = 1; /* 1 is accepted; -1 is rejected. */
1387         lstat_t *st = &param->lmd->lmd_st;
1388         int lustre_fs = 1;
1389         int checked_type = 0;
1390         int ret = 0;
1391
1392         LASSERT(parent != NULL || dir != NULL);
1393
1394         param->lmd->lmd_lmm.lmm_stripe_count = 0;
1395
1396         /* If a regular expression is presented, make the initial decision */
1397         if (param->pattern != NULL) {
1398                 char *fname = strrchr(path, '/');
1399                 fname = (fname == NULL ? path : fname + 1);
1400                 ret = fnmatch(param->pattern, fname, 0);
1401                 if ((ret == FNM_NOMATCH && !param->exclude_pattern) ||
1402                     (ret == 0 && param->exclude_pattern))
1403                         goto decided;
1404         }
1405
1406         /* See if we can check the file type from the dirent. */
1407         if (param->type && de != NULL && de->d_type != DT_UNKNOWN &&
1408             de->d_type < DT_MAX) {
1409                 checked_type = 1;
1410                 if (llapi_dir_filetype_table[de->d_type] == param->type) {
1411                         if (param->exclude_type)
1412                                 goto decided;
1413                 } else {
1414                         if (!param->exclude_type)
1415                                 goto decided;
1416                 }
1417         }
1418
1419
1420         /* If a time or OST should be checked, the decision is not taken yet. */
1421         if (param->atime || param->ctime || param->mtime || param->obduuid ||
1422             param->size)
1423                 decision = 0;
1424
1425         ret = 0;
1426         /* Request MDS for the stat info. */
1427         if (param->have_fileinfo == 0) {
1428                 if (dir) {
1429                         /* retrieve needed file info */
1430                         ret = ioctl(dirfd(dir), LL_IOC_MDC_GETINFO,
1431                                     (void *)param->lmd);
1432                 } else {
1433                         char *fname = strrchr(path, '/');
1434                         fname = (fname == NULL ? path : fname + 1);
1435
1436                         /* retrieve needed file info */
1437                         strncpy((char *)param->lmd, fname, param->lumlen);
1438                         ret = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
1439                                    (void *)param->lmd);
1440                 }
1441         }
1442
1443         if (ret) {
1444                 if (errno == ENOTTY) {
1445                         /* ioctl is not supported, it is not a lustre fs.
1446                          * Do the regular lstat(2) instead. */
1447                         lustre_fs = 0;
1448                         ret = lstat_f(path, st);
1449                         if (ret) {
1450                                 llapi_err(LLAPI_MSG_ERROR,
1451                                           "error: %s: lstat failed for %s",
1452                                           __FUNCTION__, path);
1453                                 return ret;
1454                         }
1455                 } else if (errno == ENOENT) {
1456                         llapi_err(LLAPI_MSG_WARN,
1457                                   "warning: %s: %s does not exist",
1458                                   __FUNCTION__, path);
1459                         goto decided;
1460                 } else {
1461                         llapi_err(LLAPI_MSG_ERROR,"error: %s: %s failed for %s",
1462                                   __FUNCTION__, dir ? "LL_IOC_MDC_GETINFO" :
1463                                   "IOC_MDC_GETFILEINFO", path);
1464                         return ret;
1465                 }
1466         }
1467
1468         if (param->type && !checked_type) {
1469                 if ((st->st_mode & S_IFMT) == param->type) {
1470                         if (param->exclude_type)
1471                                 goto decided;
1472                 } else {
1473                         if (!param->exclude_type)
1474                                 goto decided;
1475                 }
1476         }
1477
1478         /* Prepare odb. */
1479         if (param->obduuid) {
1480                 if (lustre_fs && param->got_uuids &&
1481                     param->st_dev != st->st_dev) {
1482                         /* A lustre/lustre mount point is crossed. */
1483                         param->got_uuids = 0;
1484                         param->obds_printed = 0;
1485                         param->obdindex = OBD_NOT_FOUND;
1486                 }
1487
1488                 if (lustre_fs && !param->got_uuids) {
1489                         ret = setup_obd_indexes(dir ? dir : parent, param);
1490                         if (ret)
1491                                 return ret;
1492
1493                         param->st_dev = st->st_dev;
1494                 } else if (!lustre_fs && param->got_uuids) {
1495                         /* A lustre/non-lustre mount point is crossed. */
1496                         param->got_uuids = 0;
1497                         param->obdindex = OBD_NOT_FOUND;
1498                 }
1499         }
1500
1501         /* If an OBD UUID is specified but no one matches, skip this file. */
1502         if (param->obduuid && param->obdindex == OBD_NOT_FOUND)
1503                 goto decided;
1504
1505         /* If a OST UUID is given, and some OST matches, check it here. */
1506         if (param->obdindex != OBD_NOT_FOUND) {
1507                 if (!S_ISREG(st->st_mode))
1508                         goto decided;
1509
1510                 /* Only those files should be accepted, which have a
1511                  * stripe on the specified OST. */
1512                 if (!param->lmd->lmd_lmm.lmm_stripe_count) {
1513                         goto decided;
1514                 } else {
1515                         int i, j;
1516                         struct lov_user_ost_data_v1 *lmm_objects;
1517
1518                         if (param->lmd->lmd_lmm.lmm_magic ==
1519                             LOV_USER_MAGIC_V3) {
1520                                 struct lov_user_md_v3 *lmmv3 =
1521                                         (void *)&param->lmd->lmd_lmm;
1522
1523                                 lmm_objects = lmmv3->lmm_objects;
1524                         } else {
1525                                 lmm_objects = param->lmd->lmd_lmm.lmm_objects;
1526                         }
1527
1528                         for (i = 0;
1529                              i < param->lmd->lmd_lmm.lmm_stripe_count; i++) {
1530                                 for (j = 0; j < param->num_obds; j++) {
1531                                         if (param->obdindexes[j] ==
1532                                             lmm_objects[i].l_ost_idx)
1533                                                 goto obd_matches;
1534                                 }
1535                         }
1536
1537                         if (i == param->lmd->lmd_lmm.lmm_stripe_count)
1538                                 goto decided;
1539                 }
1540         }
1541
1542         if (param->check_uid) {
1543                 if (st->st_uid == param->uid) {
1544                         if (param->exclude_uid)
1545                                 goto decided;
1546                 } else {
1547                         if (!param->exclude_uid)
1548                                 goto decided;
1549                 }
1550         }
1551
1552         if (param->check_gid) {
1553                 if (st->st_gid == param->gid) {
1554                         if (param->exclude_gid)
1555                                 goto decided;
1556                 } else {
1557                         if (!param->exclude_gid)
1558                                 goto decided;
1559                 }
1560         }
1561
1562         if (param->check_pool) {
1563                 struct lov_user_md_v3 *lmmv3 = (void *)&param->lmd->lmd_lmm;
1564
1565                 /* empty requested pool is taken as no pool search => V1 */
1566                 if (((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V1) &&
1567                      (param->poolname[0] == '\0')) ||
1568                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
1569                      (strncmp(lmmv3->lmm_pool_name,
1570                               param->poolname, LOV_MAXPOOLNAME) == 0)) ||
1571                     ((param->lmd->lmd_lmm.lmm_magic == LOV_USER_MAGIC_V3) &&
1572                      (strcmp(param->poolname, "*") == 0))) {
1573                         if (param->exclude_pool)
1574                                 goto decided;
1575                 } else {
1576                         if (!param->exclude_pool)
1577                                 goto decided;
1578                 }
1579         }
1580
1581         /* Check the time on mds. */
1582         if (!decision) {
1583                 int for_mds;
1584
1585                 for_mds = lustre_fs ? (S_ISREG(st->st_mode) &&
1586                                        param->lmd->lmd_lmm.lmm_stripe_count)
1587                                     : 0;
1588                 decision = find_time_check(st, param, for_mds);
1589         }
1590
1591 obd_matches:
1592         /* If file still fits the request, ask ost for updated info.
1593            The regular stat is almost of the same speed as some new
1594            'glimpse-size-ioctl'. */
1595         if (!decision && S_ISREG(st->st_mode) &&
1596             (param->lmd->lmd_lmm.lmm_stripe_count || param->size)) {
1597                 if (param->obdindex != OBD_NOT_FOUND) {
1598                         /* Check whether the obd is active or not, if it is
1599                          * not active, just print the object affected by this
1600                          * failed ost
1601                          * */
1602                         struct obd_statfs stat_buf;
1603                         struct obd_uuid uuid_buf;
1604
1605                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
1606                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1607                         ret = llapi_obd_statfs(path, LL_STATFS_LOV,
1608                                                param->obdindex, &stat_buf,
1609                                                &uuid_buf);
1610                         if (ret) {
1611                                 if (ret == -ENODATA || ret == -ENODEV
1612                                     || ret == -EIO)
1613                                         errno = EIO;
1614                                 llapi_printf(LLAPI_MSG_NORMAL,
1615                                              "obd_uuid: %s failed %s ",
1616                                              param->obduuid->uuid,
1617                                              strerror(errno));
1618                                 goto print_path;
1619                         }
1620                 }
1621                 if (dir) {
1622                         ret = ioctl(dirfd(dir), IOC_LOV_GETINFO,
1623                                     (void *)param->lmd);
1624                 } else if (parent) {
1625                         ret = ioctl(dirfd(parent), IOC_LOV_GETINFO,
1626                                     (void *)param->lmd);
1627                 }
1628
1629                 if (ret) {
1630                         if (errno == ENOENT) {
1631                                 llapi_err(LLAPI_MSG_ERROR,
1632                                           "warning: %s: %s does not exist",
1633                                           __FUNCTION__, path);
1634                                 goto decided;
1635                         } else {
1636                                 llapi_err(LLAPI_MSG_ERROR,
1637                                           "%s: IOC_LOV_GETINFO on %s failed",
1638                                           __FUNCTION__, path);
1639                                 return ret;
1640                         }
1641                 }
1642
1643                 /* Check the time on osc. */
1644                 decision = find_time_check(st, param, 0);
1645                 if (decision == -1)
1646                         goto decided;
1647         }
1648
1649         if (param->size)
1650                 decision = find_value_cmp(st->st_size, param->size,
1651                                           param->size_sign, param->size_units,
1652                                           0);
1653
1654 print_path:
1655         if (decision != -1) {
1656                 llapi_printf(LLAPI_MSG_NORMAL, "%s", path);
1657                 if (param->zeroend)
1658                         llapi_printf(LLAPI_MSG_NORMAL, "%c", '\0');
1659                 else
1660                         llapi_printf(LLAPI_MSG_NORMAL, "\n");
1661         }
1662
1663 decided:
1664         /* Do not get down anymore? */
1665         if (param->depth == param->maxdepth)
1666                 return 1;
1667
1668         param->depth++;
1669         return 0;
1670 }
1671
1672 static int cb_common_fini(char *path, DIR *parent, DIR *d, void *data,
1673                           cfs_dirent_t *de)
1674 {
1675         struct find_param *param = (struct find_param *)data;
1676         param->depth--;
1677         return 0;
1678 }
1679
1680 int llapi_find(char *path, struct find_param *param)
1681 {
1682         char *buf;
1683         int ret, len = strlen(path);
1684
1685         if (len > PATH_MAX) {
1686                 llapi_err(LLAPI_MSG_ERROR, "%s: Path name '%s' is too long",
1687                           __FUNCTION__, path);
1688                 return -EINVAL;
1689         }
1690
1691         buf = (char *)malloc(PATH_MAX + 1);
1692         if (!buf)
1693                 return -ENOMEM;
1694
1695         ret = common_param_init(param);
1696         if (ret) {
1697                 free(buf);
1698                 return ret;
1699         }
1700
1701         param->depth = 0;
1702
1703         strncpy(buf, path, PATH_MAX + 1);
1704         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, cb_find_init,
1705                                       cb_common_fini, param, NULL);
1706
1707         find_param_fini(param);
1708         free(buf);
1709         return ret < 0 ? ret : 0;
1710 }
1711
1712 static int cb_getstripe(char *path, DIR *parent, DIR *d, void *data,
1713                         cfs_dirent_t *de)
1714 {
1715         struct find_param *param = (struct find_param *)data;
1716         int ret = 0;
1717
1718         LASSERT(parent != NULL || d != NULL);
1719
1720         /* Prepare odb. */
1721         if (!param->got_uuids) {
1722                 ret = setup_obd_uuid(d ? d : parent, path, param);
1723                 if (ret)
1724                         return ret;
1725         }
1726
1727         if (d) {
1728                 ret = ioctl(dirfd(d), LL_IOC_LOV_GETSTRIPE,
1729                             (void *)&param->lmd->lmd_lmm);
1730         } else if (parent) {
1731                 char *fname = strrchr(path, '/');
1732                 fname = (fname == NULL ? path : fname + 1);
1733
1734                 strncpy((char *)&param->lmd->lmd_lmm, fname, param->lumlen);
1735                 ret = ioctl(dirfd(parent), IOC_MDC_GETFILESTRIPE,
1736                             (void *)&param->lmd->lmd_lmm);
1737         }
1738
1739         if (ret) {
1740                 if (errno == ENODATA) {
1741                         if (!param->obduuid && !param->quiet)
1742                                 llapi_printf(LLAPI_MSG_NORMAL,
1743                                              "%s has no stripe info\n", path);
1744                         goto out;
1745                 } else if (errno == ENOTTY) {
1746                         llapi_err(LLAPI_MSG_ERROR,
1747                                   "%s: '%s' not on a Lustre fs?",
1748                                   __FUNCTION__, path);
1749                 } else if (errno == ENOENT) {
1750                         llapi_err(LLAPI_MSG_WARN,
1751                                   "warning: %s: %s does not exist",
1752                                   __FUNCTION__, path);
1753                         goto out;
1754                 } else {
1755                         llapi_err(LLAPI_MSG_ERROR,
1756                                   "error: %s: %s failed for %s",
1757                                    __FUNCTION__, d ? "LL_IOC_LOV_GETSTRIPE" :
1758                                   "IOC_MDC_GETFILESTRIPE", path);
1759                 }
1760
1761                 return ret;
1762         }
1763
1764         llapi_lov_dump_user_lmm(param, path, d ? 1 : 0);
1765 out:
1766         /* Do not get down anymore? */
1767         if (param->depth == param->maxdepth)
1768                 return 1;
1769
1770         param->depth++;
1771         return 0;
1772 }
1773
1774 int llapi_getstripe(char *path, struct find_param *param)
1775 {
1776         char *buf;
1777         int ret = 0, len = strlen(path);
1778
1779         if (len > PATH_MAX) {
1780                 llapi_err(LLAPI_MSG_ERROR,
1781                           "%s: Path name '%s' is too long",
1782                           __FUNCTION__, path);
1783                 return -EINVAL;
1784         }
1785
1786         buf = (char *)malloc(PATH_MAX + 1);
1787         if (!buf)
1788                 return -ENOMEM;
1789
1790         ret = common_param_init(param);
1791         if (ret) {
1792                 free(buf);
1793                 return ret;
1794         }
1795
1796         param->depth = 0;
1797
1798         strncpy(buf, path, PATH_MAX + 1);
1799         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, cb_getstripe,
1800                                       cb_common_fini, param, NULL);
1801         find_param_fini(param);
1802         free(buf);
1803         return ret < 0 ? ret : 0;
1804 }
1805
1806 int llapi_obd_statfs(char *path, __u32 type, __u32 index,
1807                      struct obd_statfs *stat_buf,
1808                      struct obd_uuid *uuid_buf)
1809 {
1810         int fd;
1811         char raw[OBD_MAX_IOCTL_BUFFER] = {'\0'};
1812         char *rawbuf = raw;
1813         struct obd_ioctl_data data = { 0 };
1814         int rc = 0;
1815
1816         data.ioc_inlbuf1 = (char *)&type;
1817         data.ioc_inllen1 = sizeof(__u32);
1818         data.ioc_inlbuf2 = (char *)&index;
1819         data.ioc_inllen2 = sizeof(__u32);
1820         data.ioc_pbuf1 = (char *)stat_buf;
1821         data.ioc_plen1 = sizeof(struct obd_statfs);
1822         data.ioc_pbuf2 = (char *)uuid_buf;
1823         data.ioc_plen2 = sizeof(struct obd_uuid);
1824
1825         if ((rc = obd_ioctl_pack(&data, &rawbuf, sizeof(raw))) != 0) {
1826                 llapi_err(LLAPI_MSG_ERROR,
1827                           "llapi_obd_statfs: error packing ioctl data");
1828                 return rc;
1829         }
1830
1831         fd = open(path, O_RDONLY);
1832         if (errno == EISDIR)
1833                 fd = open(path, O_DIRECTORY | O_RDONLY);
1834
1835         if (fd < 0) {
1836                 rc = errno ? -errno : -EBADF;
1837                 llapi_err(LLAPI_MSG_ERROR, "error: %s: opening '%s'",
1838                           __FUNCTION__, path);
1839                 return rc;
1840         }
1841         rc = ioctl(fd, IOC_OBD_STATFS, (void *)rawbuf);
1842         if (rc)
1843                 rc = errno ? -errno : -EINVAL;
1844
1845         close(fd);
1846         return rc;
1847 }
1848
1849 #define MAX_STRING_SIZE 128
1850 #define DEVICES_LIST "/proc/fs/lustre/devices"
1851
1852 int llapi_ping(char *obd_type, char *obd_name)
1853 {
1854         char path[MAX_STRING_SIZE];
1855         char buf[1];
1856         int rc, fd;
1857
1858         snprintf(path, MAX_STRING_SIZE, "/proc/fs/lustre/%s/%s/ping",
1859                  obd_type, obd_name);
1860
1861         fd = open(path, O_WRONLY);
1862         if (fd < 0) {
1863                 rc = errno;
1864                 llapi_err(LLAPI_MSG_ERROR, "error opening %s", path);
1865                 return rc;
1866         }
1867
1868         rc = write(fd, buf, 1);
1869         close(fd);
1870
1871         if (rc == 1)
1872                 return 0;
1873         return rc;
1874 }
1875
1876 int llapi_target_iterate(int type_num, char **obd_type,void *args,llapi_cb_t cb)
1877 {
1878         char buf[MAX_STRING_SIZE];
1879         FILE *fp = fopen(DEVICES_LIST, "r");
1880         int i, rc = 0;
1881
1882         if (fp == NULL) {
1883                 rc = errno;
1884                 llapi_err(LLAPI_MSG_ERROR, "error: opening "DEVICES_LIST);
1885                 return rc;
1886         }
1887
1888         while (fgets(buf, sizeof(buf), fp) != NULL) {
1889                 char *obd_type_name = NULL;
1890                 char *obd_name = NULL;
1891                 char *obd_uuid = NULL;
1892                 char *bufp = buf;
1893                 struct obd_ioctl_data datal = { 0, };
1894                 struct obd_statfs osfs_buffer;
1895
1896                 while(bufp[0] == ' ')
1897                         ++bufp;
1898
1899                 for(i = 0; i < 3; i++) {
1900                         obd_type_name = strsep(&bufp, " ");
1901                 }
1902                 obd_name = strsep(&bufp, " ");
1903                 obd_uuid = strsep(&bufp, " ");
1904
1905                 memset(&osfs_buffer, 0, sizeof (osfs_buffer));
1906
1907                 datal.ioc_pbuf1 = (char *)&osfs_buffer;
1908                 datal.ioc_plen1 = sizeof(osfs_buffer);
1909
1910                 for (i = 0; i < type_num; i++) {
1911                         if (strcmp(obd_type_name, obd_type[i]) != 0)
1912                                 continue;
1913
1914                         cb(obd_type_name, obd_name, obd_uuid, args);
1915                 }
1916         }
1917         fclose(fp);
1918         return rc;
1919 }
1920
1921 static void do_target_check(char *obd_type_name, char *obd_name,
1922                             char *obd_uuid, void *args)
1923 {
1924         int rc;
1925
1926         rc = llapi_ping(obd_type_name, obd_name);
1927         if (rc == ENOTCONN) {
1928                 llapi_printf(LLAPI_MSG_NORMAL, "%s inactive.\n", obd_name);
1929         } else if (rc) {
1930                 llapi_err(LLAPI_MSG_ERROR, "error: check '%s'", obd_name);
1931         } else {
1932                 llapi_printf(LLAPI_MSG_NORMAL, "%s active.\n", obd_name);
1933         }
1934 }
1935
1936 int llapi_target_check(int type_num, char **obd_type, char *dir)
1937 {
1938         return llapi_target_iterate(type_num, obd_type, NULL, do_target_check);
1939 }
1940
1941 #undef MAX_STRING_SIZE
1942
1943 int llapi_catinfo(char *dir, char *keyword, char *node_name)
1944 {
1945         char raw[OBD_MAX_IOCTL_BUFFER];
1946         char out[LLOG_CHUNK_SIZE];
1947         char *buf = raw;
1948         struct obd_ioctl_data data = { 0 };
1949         char key[30];
1950         DIR *root;
1951         int rc;
1952
1953         sprintf(key, "%s", keyword);
1954         memset(raw, 0, sizeof(raw));
1955         memset(out, 0, sizeof(out));
1956         data.ioc_inlbuf1 = key;
1957         data.ioc_inllen1 = strlen(key) + 1;
1958         if (node_name) {
1959                 data.ioc_inlbuf2 = node_name;
1960                 data.ioc_inllen2 = strlen(node_name) + 1;
1961         }
1962         data.ioc_pbuf1 = out;
1963         data.ioc_plen1 = sizeof(out);
1964         rc = obd_ioctl_pack(&data, &buf, sizeof(raw));
1965         if (rc)
1966                 return rc;
1967
1968         root = opendir(dir);
1969         if (root == NULL) {
1970                 rc = errno;
1971                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", dir);
1972                 return rc;
1973         }
1974
1975         rc = ioctl(dirfd(root), OBD_IOC_LLOG_CATINFO, buf);
1976         if (rc)
1977                 llapi_err(LLAPI_MSG_ERROR, "ioctl OBD_IOC_CATINFO failed");
1978         else
1979                 llapi_printf(LLAPI_MSG_NORMAL, "%s", data.ioc_pbuf1);
1980
1981         closedir(root);
1982         return rc;
1983 }
1984
1985 /* Is this a lustre fs? */
1986 int llapi_is_lustre_mnttype(const char *type)
1987 {
1988         return (strcmp(type, "lustre") == 0 || strcmp(type,"lustre_lite") == 0);
1989 }
1990
1991 /* Is this a lustre client fs? */
1992 int llapi_is_lustre_mnt(struct mntent *mnt)
1993 {
1994         return (llapi_is_lustre_mnttype(mnt->mnt_type) &&
1995                 strstr(mnt->mnt_fsname, ":/") != NULL);
1996 }
1997
1998 int llapi_quotacheck(char *mnt, int check_type)
1999 {
2000         DIR *root;
2001         int rc;
2002
2003         root = opendir(mnt);
2004         if (!root) {
2005                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2006                 return -1;
2007         }
2008
2009         rc = ioctl(dirfd(root), LL_IOC_QUOTACHECK, check_type);
2010
2011         closedir(root);
2012         return rc;
2013 }
2014
2015 int llapi_poll_quotacheck(char *mnt, struct if_quotacheck *qchk)
2016 {
2017         DIR *root;
2018         int poll_intvl = 2;
2019         int rc;
2020
2021         root = opendir(mnt);
2022         if (!root) {
2023                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2024                 return -1;
2025         }
2026
2027         while (1) {
2028                 rc = ioctl(dirfd(root), LL_IOC_POLL_QUOTACHECK, qchk);
2029                 if (!rc)
2030                         break;
2031                 sleep(poll_intvl);
2032                 if (poll_intvl < 30)
2033                         poll_intvl *= 2;
2034         }
2035
2036         closedir(root);
2037         return rc;
2038 }
2039
2040 int llapi_quotactl(char *mnt, struct if_quotactl *qctl)
2041 {
2042         DIR *root;
2043         int rc;
2044
2045         root = opendir(mnt);
2046         if (!root) {
2047                 llapi_err(LLAPI_MSG_ERROR, "open %s failed", mnt);
2048                 return -1;
2049         }
2050
2051         rc = ioctl(dirfd(root), LL_IOC_QUOTACTL, qctl);
2052
2053         closedir(root);
2054         return rc;
2055 }
2056
2057 static int cb_quotachown(char *path, DIR *parent, DIR *d, void *data,
2058                          cfs_dirent_t *de)
2059 {
2060         struct find_param *param = (struct find_param *)data;
2061         lstat_t *st;
2062         int rc;
2063
2064         LASSERT(parent != NULL || d != NULL);
2065
2066         if (d) {
2067                 rc = ioctl(dirfd(d), LL_IOC_MDC_GETINFO,
2068                            (void *)param->lmd);
2069         } else if (parent) {
2070                 char *fname = strrchr(path, '/');
2071                 fname = (fname == NULL ? path : fname + 1);
2072
2073                 strncpy((char *)param->lmd, fname, param->lumlen);
2074                 rc = ioctl(dirfd(parent), IOC_MDC_GETFILEINFO,
2075                            (void *)param->lmd);
2076         } else {
2077                 return 0;
2078         }
2079
2080         if (rc) {
2081                 if (errno == ENODATA) {
2082                         if (!param->obduuid && !param->quiet)
2083                                 llapi_err(LLAPI_MSG_ERROR,
2084                                           "%s has no stripe info", path);
2085                         rc = 0;
2086                 } else if (errno == ENOENT) {
2087                         llapi_err(LLAPI_MSG_ERROR,
2088                                   "warning: %s: %s does not exist",
2089                                   __FUNCTION__, path);
2090                         rc = 0;
2091                 } else if (errno != EISDIR) {
2092                         rc = errno;
2093                         llapi_err(LLAPI_MSG_ERROR, "%s ioctl failed for %s.",
2094                                   d ? "LL_IOC_MDC_GETINFO" :
2095                                   "IOC_MDC_GETFILEINFO", path);
2096                 }
2097                 return rc;
2098         }
2099
2100         st = &param->lmd->lmd_st;
2101
2102         /* libc chown() will do extra check, and if the real owner is
2103          * the same as the ones to set, it won't fall into kernel, so
2104          * invoke syscall directly. */
2105         rc = syscall(SYS_chown, path, -1, -1);
2106         if (rc)
2107                 llapi_err(LLAPI_MSG_ERROR,"error: chown %s (%u,%u)", path);
2108
2109         rc = chmod(path, st->st_mode);
2110         if (rc)
2111                 llapi_err(LLAPI_MSG_ERROR, "error: chmod %s (%hu)",
2112                           path, st->st_mode);
2113
2114         return rc;
2115 }
2116
2117 int llapi_quotachown(char *path, int flag)
2118 {
2119         struct find_param param;
2120         char *buf;
2121         int ret = 0, len = strlen(path);
2122
2123         if (len > PATH_MAX) {
2124                 llapi_err(LLAPI_MSG_ERROR, "%s: Path name '%s' is too long",
2125                           __FUNCTION__, path);
2126                 return -EINVAL;
2127         }
2128
2129         buf = (char *)malloc(PATH_MAX + 1);
2130         if (!buf)
2131                 return -ENOMEM;
2132
2133         memset(&param, 0, sizeof(param));
2134         param.recursive = 1;
2135         param.verbose = 0;
2136         param.quiet = 1;
2137
2138         ret = common_param_init(&param);
2139         if (ret)
2140                 goto out;
2141
2142         strncpy(buf, path, PATH_MAX + 1);
2143         ret = llapi_semantic_traverse(buf, PATH_MAX + 1, NULL, cb_quotachown,
2144                                       NULL, &param, NULL);
2145 out:
2146         find_param_fini(&param);
2147         free(buf);
2148         return ret;
2149 }
2150
2151 #include <pwd.h>
2152 #include <grp.h>
2153 #include <mntent.h>
2154 #include <sys/wait.h>
2155 #include <errno.h>
2156 #include <ctype.h>
2157
2158 static int rmtacl_notify(int ops)
2159 {
2160         FILE *fp;
2161         struct mntent *mnt;
2162         int found = 0, fd, rc;
2163
2164         fp = setmntent(MOUNTED, "r");
2165         if (fp == NULL) {
2166                 perror("setmntent");
2167                 return -1;
2168         }
2169
2170         while (1) {
2171                 mnt = getmntent(fp);
2172                 if (!mnt)
2173                         break;
2174
2175                 if (!llapi_is_lustre_mnt(mnt))
2176                         continue;
2177
2178                 fd = open(mnt->mnt_dir, O_RDONLY | O_DIRECTORY);
2179                 if (fd < 0) {
2180                         perror("open");
2181                         return -1;
2182                 }
2183
2184                 rc = ioctl(fd, LL_IOC_RMTACL, ops);
2185                 if (rc < 0) {
2186                         perror("ioctl");
2187                 return -1;
2188                 }
2189
2190                 found++;
2191         }
2192         endmntent(fp);
2193         return found;
2194 }
2195
2196 static char *next_token(char *p, int div)
2197 {
2198         if (p == NULL)
2199                 return NULL;
2200
2201         if (div)
2202                 while (*p && *p != ':' && !isspace(*p))
2203                         p++;
2204         else
2205                 while (*p == ':' || isspace(*p))
2206                         p++;
2207
2208         return *p ? p : NULL;
2209 }
2210
2211 static int rmtacl_name2id(char *name, int is_user)
2212 {
2213         if (is_user) {
2214                 struct passwd *pw;
2215
2216                 if ((pw = getpwnam(name)) == NULL)
2217                         return INVALID_ID;
2218                 else
2219                         return (int)(pw->pw_uid);
2220         } else {
2221                 struct group *gr;
2222
2223                 if ((gr = getgrnam(name)) == NULL)
2224                         return INVALID_ID;
2225                 else
2226                         return (int)(gr->gr_gid);
2227         }
2228 }
2229
2230 static int isodigit(int c)
2231 {
2232         return (c >= '0' && c <= '7') ? 1 : 0;
2233 }
2234
2235 /*
2236  * Whether the name is just digits string (uid/gid) already or not.
2237  * Return value:
2238  * 1: str is id
2239  * 0: str is not id
2240  */
2241 static int str_is_id(char *str)
2242 {
2243         if (str == NULL)
2244                 return 0;
2245
2246         if (*str == '0') {
2247                 str++;
2248                 if (*str == 'x' || *str == 'X') { /* for Hex. */
2249                         if (!isxdigit(*(++str)))
2250                                 return 0;
2251
2252                         while (isxdigit(*(++str)));
2253                 } else if (isodigit(*str)) { /* for Oct. */
2254                         while (isodigit(*(++str)));
2255                 }
2256         } else if (isdigit(*str)) { /* for Dec. */
2257                 while (isdigit(*(++str)));
2258         }
2259
2260         return (*str == 0) ? 1 : 0;
2261 }
2262
2263 typedef struct {
2264         char *name;
2265         int   length;
2266         int   is_user;
2267         int   next_token;
2268 } rmtacl_name_t;
2269
2270 #define RMTACL_OPTNAME(name) name, sizeof(name) - 1
2271
2272 static rmtacl_name_t rmtacl_namelist[] = {
2273         { RMTACL_OPTNAME("user:"),            1,      0 },
2274         { RMTACL_OPTNAME("group:"),           0,      0 },
2275         { RMTACL_OPTNAME("default:user:"),    1,      0 },
2276         { RMTACL_OPTNAME("default:group:"),   0,      0 },
2277         /* for --tabular option */
2278         { RMTACL_OPTNAME("user"),             1,      1 },
2279         { RMTACL_OPTNAME("group"),            0,      1 },
2280         { 0 }
2281 };
2282
2283 static int rgetfacl_output(char *str)
2284 {
2285         char *start = NULL, *end = NULL;
2286         int is_user = 0, n, id;
2287         char c;
2288         rmtacl_name_t *rn;
2289
2290         if (str == NULL)
2291                 return -1;
2292
2293         for (rn = rmtacl_namelist; rn->name; rn++) {
2294                 if(strncmp(str, rn->name, rn->length) == 0) {
2295                         if (!rn->next_token)
2296                                 start = str + rn->length;
2297                         else
2298                                 start = next_token(str + rn->length, 0);
2299                         is_user = rn->is_user;
2300                         break;
2301                 }
2302         }
2303
2304         end = next_token(start, 1);
2305         if (end == NULL || start == end) {
2306                 n = printf("%s", str);
2307                 return n;
2308         }
2309
2310         c = *end;
2311         *end = 0;
2312         id = rmtacl_name2id(start, is_user);
2313         if (id == INVALID_ID) {
2314                 if (str_is_id(start)) {
2315                         *end = c;
2316                         n = printf("%s", str);
2317                 } else
2318                         return -1;
2319         } else if ((id == NOBODY_UID && is_user) ||
2320                    (id == NOBODY_GID && !is_user)) {
2321                 *end = c;
2322                 n = printf("%s", str);
2323         } else {
2324                 *end = c;
2325                 *start = 0;
2326                 n = printf("%s%d%s", str, id, end);
2327         }
2328         return n;
2329 }
2330
2331 static int child_status(int status)
2332 {
2333         return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
2334 }
2335
2336 static int do_rmtacl(int argc, char *argv[], int ops, int (output_func)(char *))
2337 {
2338         pid_t pid = 0;
2339         int fd[2], status;
2340         FILE *fp;
2341         char buf[PIPE_BUF];
2342
2343         if (output_func) {
2344                 if (pipe(fd) < 0) {
2345                         perror("pipe");
2346                         return -1;
2347                 }
2348
2349                 if ((pid = fork()) < 0) {
2350                         perror("fork");
2351                         close(fd[0]);
2352                         close(fd[1]);
2353                         return -1;
2354                 } else if (!pid) {
2355                         /* child process redirects its output. */
2356                         close(fd[0]);
2357                         close(1);
2358                         if (dup2(fd[1], 1) < 0) {
2359                                 perror("dup2");
2360                                 close(fd[1]);
2361                                 return -1;
2362                         }
2363                 } else {
2364                         close(fd[1]);
2365                 }
2366         }
2367
2368         if (!pid) {
2369                 status = rmtacl_notify(ops);
2370                 if (status < 0)
2371                         return -1;
2372
2373                 exit(execvp(argv[0], argv));
2374         }
2375
2376         /* the following is parent process */
2377         if ((fp = fdopen(fd[0], "r")) == NULL) {
2378                 perror("fdopen");
2379                 kill(pid, SIGKILL);
2380                 close(fd[0]);
2381                 return -1;
2382         }
2383
2384         while (fgets(buf, PIPE_BUF, fp) != NULL) {
2385                 if (output_func(buf) < 0)
2386                         fprintf(stderr, "WARNING: unexpected error!\n[%s]\n",
2387                                 buf);
2388         }
2389         fclose(fp);
2390         close(fd[0]);
2391
2392         if (waitpid(pid, &status, 0) < 0) {
2393                 perror("waitpid");
2394                 return -1;
2395         }
2396
2397         return child_status(status);
2398 }
2399
2400 int llapi_lsetfacl(int argc, char *argv[])
2401 {
2402         return do_rmtacl(argc, argv, RMT_LSETFACL, NULL);
2403 }
2404
2405 int llapi_lgetfacl(int argc, char *argv[])
2406 {
2407         return do_rmtacl(argc, argv, RMT_LGETFACL, NULL);
2408 }
2409
2410 int llapi_rsetfacl(int argc, char *argv[])
2411 {
2412         return do_rmtacl(argc, argv, RMT_RSETFACL, NULL);
2413 }
2414
2415 int llapi_rgetfacl(int argc, char *argv[])
2416 {
2417         return do_rmtacl(argc, argv, RMT_RGETFACL, rgetfacl_output);
2418 }
2419
2420 int llapi_cp(int argc, char *argv[])
2421 {
2422         int rc;
2423
2424         rc = rmtacl_notify(RMT_RSETFACL);
2425         if (rc < 0)
2426                 return -1;
2427
2428         exit(execvp(argv[0], argv));
2429 }
2430
2431 int llapi_ls(int argc, char *argv[])
2432 {
2433         int rc;
2434
2435         rc = rmtacl_notify(RMT_LGETFACL);
2436         if (rc < 0)
2437                 return -1;
2438
2439         exit(execvp(argv[0], argv));
2440 }
2441
2442 /* Print mdtname 'name' into 'buf' using 'format'.  Add -MDT0000 if needed.
2443  * format must have %s%s, buf must be > 16
2444  */
2445 static int get_mdtname(char *name, char *format, char *buf)
2446 {
2447         char suffix[]="-MDT0000";
2448         int len = strlen(name);
2449
2450         if ((len > 5) && (strncmp(name + len - 5, "_UUID", 5) == 0)) {
2451                 name[len - 5] = '\0';
2452                 len -= 5;
2453         }
2454
2455         if (len > 8) {
2456                 if ((len <= 16) && strncmp(name + len - 8, "-MDT", 4) == 0) {
2457                         suffix[0] = '\0';
2458                 } else {
2459                         /* Not enough room to add suffix */
2460                         llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2461                                   "MDT name too long |%s|", name);
2462                         return -EINVAL;
2463                 }
2464         }
2465
2466         return sprintf(buf, format, name, suffix);
2467 }
2468
2469 /****** Changelog API ********/
2470 #define CHANGELOG_PRIV_MAGIC 0xCA8E1080
2471 struct changelog_private {
2472         int magic;
2473         int fd;
2474         int flags;
2475 };
2476
2477 /** Start reading from a changelog
2478  * @param priv Opaque private control structure
2479  * @param flags Start flags (e.g. follow)
2480  * @param device Report changes recorded on this MDT
2481  * @param startrec Report changes beginning with this record number
2482  */
2483 int llapi_changelog_start(void **priv, int flags, const char *device,
2484                           long long startrec)
2485 {
2486         struct changelog_private *cp;
2487         char path[256];
2488         char mdtname[20];
2489         int rc, fd;
2490
2491         if (device[0] == '/')
2492                 rc = get_root_path(WANT_FSNAME, mdtname, NULL, (char *)device);
2493         else
2494                 strncpy(mdtname, device, sizeof(mdtname));
2495
2496         /* Use either the mdd changelog (preferred) or a client mdc changelog */
2497         if (get_mdtname(mdtname,
2498                         "/proc/fs/lustre/md[cd]/%s%s{,-mdc-*}/changelog",
2499                         path) < 0)
2500                 return -EINVAL;
2501         rc = first_match(path, path);
2502         if (rc)
2503                 return rc;
2504
2505         if ((fd = open(path, O_RDONLY)) < 0) {
2506                 llapi_err(LLAPI_MSG_ERROR, "error: can't open |%s|\n", path);
2507                 return -errno;
2508         }
2509
2510         rc = lseek(fd, (off_t)startrec, SEEK_SET);
2511         if (rc < 0) {
2512                 llapi_err(LLAPI_MSG_ERROR, "can't seek rc=%d\n", rc);
2513                 return -errno;
2514         }
2515
2516         cp = malloc(sizeof(*cp));
2517         if (cp == NULL) {
2518                 close(fd);
2519                 return -ENOMEM;
2520         }
2521
2522         cp->magic = CHANGELOG_PRIV_MAGIC;
2523         cp->fd = fd;
2524         cp->flags = flags;
2525         *priv = cp;
2526
2527         return 0;
2528 }
2529
2530 /** Finish reading from a changelog */
2531 int llapi_changelog_fini(void **priv)
2532 {
2533         struct changelog_private *cp = (struct changelog_private *)*priv;
2534
2535         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
2536                 return -EINVAL;
2537
2538         close(cp->fd);
2539         free(cp);
2540         *priv = NULL;
2541         return 0;
2542 }
2543
2544 static int pollwait(int fd) {
2545         struct pollfd pfds[1];
2546         int rc;
2547
2548         pfds[0].fd = fd;
2549         pfds[0].events = POLLIN;
2550         rc = poll(pfds, 1, -1);
2551         return rc < 0 ? -errno : rc;
2552 }
2553
2554 /** Read the next changelog entry
2555  * @param priv Opaque private control structure
2556  * @param rech Changelog record handle; record will be allocated here
2557  * @return 0 valid message received; rec is set
2558  *         <0 error code
2559  *         1 EOF
2560  */
2561 int llapi_changelog_recv(void *priv, struct changelog_rec **rech)
2562 {
2563         struct changelog_private *cp = (struct changelog_private *)priv;
2564         struct changelog_rec rec, *recp;
2565         int rc = 0;
2566
2567         if (!cp || (cp->magic != CHANGELOG_PRIV_MAGIC))
2568                 return -EINVAL;
2569         if (rech == NULL)
2570                 return -EINVAL;
2571
2572 readrec:
2573         /* Read in the rec to get the namelen */
2574         rc = read(cp->fd, &rec, sizeof(rec));
2575         if (rc < 0)
2576                 return -errno;
2577         if (rc == 0) {
2578                 if (cp->flags && CHANGELOG_FLAG_FOLLOW) {
2579                         rc = pollwait(cp->fd);
2580                         if (rc < 0)
2581                                 return rc;
2582                         goto readrec;
2583                 }
2584                 return 1;
2585         }
2586
2587         recp = malloc(sizeof(rec) + rec.cr_namelen);
2588         if (recp == NULL)
2589                 return -ENOMEM;
2590         memcpy(recp, &rec, sizeof(rec));
2591         rc = read(cp->fd, recp->cr_name, rec.cr_namelen);
2592         if (rc < 0) {
2593                 free(recp);
2594                 llapi_err(LLAPI_MSG_ERROR, "Can't read entire filename");
2595                 return -errno;
2596         }
2597
2598         *rech = recp;
2599         return 0;
2600 }
2601
2602 /** Release the changelog record when done with it. */
2603 int llapi_changelog_free(struct changelog_rec **rech)
2604 {
2605         if (*rech)
2606                 free(*rech);
2607         *rech = NULL;
2608         return 0;
2609 }
2610
2611 int llapi_changelog_clear(const char *mdtname, const char *idstr,
2612                           long long endrec)
2613 {
2614         struct ioc_changelog_clear data;
2615         char fsname[17];
2616         char *ptr;
2617         int id, fd, index, rc;
2618
2619         if (endrec < 0) {
2620                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2621                           "can't purge negative records\n");
2622                 return -EINVAL;
2623         }
2624
2625         id = strtol(idstr + strlen(CHANGELOG_USER_PREFIX), NULL, 10);
2626         if ((id == 0) || (strncmp(idstr, CHANGELOG_USER_PREFIX,
2627                                   strlen(CHANGELOG_USER_PREFIX)) != 0)) {
2628                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2629                           "expecting id of the form '"CHANGELOG_USER_PREFIX
2630                           "<num>'; got '%s'\n", idstr);
2631                 return -EINVAL;
2632         }
2633
2634         /* Take path, fsname, or MDTNAME.  Assume MDT0000 in the former cases */
2635         if (mdtname[0] == '/') {
2636                 index = 0;
2637                 fd = open(mdtname, O_RDONLY | O_DIRECTORY | O_NONBLOCK);
2638                 rc = fd < 0 ? -errno : 0;
2639         } else {
2640                 if (get_mdtname((char *)mdtname, "%s%s", fsname) < 0)
2641                         return -EINVAL;
2642                 ptr = fsname + strlen(fsname) - 8;
2643                 *ptr = '\0';
2644                 index = strtol(ptr + 4, NULL, 10);
2645                 rc = get_root_path(WANT_FD, fsname, &fd, NULL);
2646         }
2647         if (rc < 0) {
2648                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2649                           "Can't open %s: %d\n", mdtname, rc);
2650                 return rc;
2651         }
2652
2653         data.icc_mdtindex = index;
2654         data.icc_id = id;
2655         data.icc_recno = endrec;
2656         rc = ioctl(fd, OBD_IOC_CHANGELOG_CLEAR, &data);
2657         if (rc)
2658                 llapi_err(LLAPI_MSG_ERROR, "ioctl err %d", rc);
2659
2660         close(fd);
2661         return rc;
2662 }
2663
2664 int llapi_fid2path(const char *device, const char *fidstr, char *buf,
2665                    int buflen, long long *recno, int *linkno)
2666 {
2667         char path[PATH_MAX];
2668         struct lu_fid fid;
2669         struct getinfo_fid2path *gf;
2670         int fd, rc;
2671
2672         while (*fidstr == '[')
2673                 fidstr++;
2674
2675         sscanf(fidstr, SFID, RFID(&fid));
2676         if (!fid_is_sane(&fid)) {
2677                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2678                           "bad FID format [%s], should be "DFID"\n",
2679                           fidstr, (__u64)1, 2, 0);
2680                 return -EINVAL;
2681         }
2682
2683         /* Take path or fsname */
2684         if (device[0] == '/') {
2685                 strcpy(path, device);
2686         } else {
2687                 rc = get_root_path(WANT_PATH, (char *)device, NULL, path);
2688                 if (rc < 0)
2689                         return rc;
2690         }
2691         sprintf(path, "%s/%s/fid/%s", path, dot_lustre_name, fidstr);
2692         fd = open(path, O_RDONLY | O_NONBLOCK);
2693         if (fd < 0)
2694                 return -errno;
2695
2696         gf = malloc(sizeof(*gf) + buflen);
2697         gf->gf_fid = fid;
2698         gf->gf_recno = *recno;
2699         gf->gf_linkno = *linkno;
2700         gf->gf_pathlen = buflen;
2701         rc = ioctl(fd, OBD_IOC_FID2PATH, gf);
2702         if (rc) {
2703                 llapi_err(LLAPI_MSG_ERROR, "ioctl err %d", rc);
2704         } else {
2705                 memcpy(buf, gf->gf_path, gf->gf_pathlen);
2706                 *recno = gf->gf_recno;
2707                 *linkno = gf->gf_linkno;
2708         }
2709
2710         free(gf);
2711         close(fd);
2712         return rc;
2713 }
2714
2715 int llapi_path2fid(const char *path, lustre_fid *fid)
2716 {
2717         int fd, rc;
2718
2719         fd = open(path, O_RDONLY);
2720         if (fd < 0)
2721                 return -errno;
2722
2723         rc = ioctl(fd, LL_IOC_PATH2FID, fid);
2724
2725         close(fd);
2726         return rc;
2727 }
2728
2729 /****** HSM Copytool API ********/
2730 #define CT_PRIV_MAGIC 0xC0BE2001
2731 struct copytool_private {
2732         int magic;
2733         lustre_netlink lnl;
2734         int archive_num_count;
2735         int archive_nums[0];
2736 };
2737
2738 #include <libcfs/libcfs.h>
2739
2740 /** Register a copytool
2741  * @param priv Opaque private control structure
2742  * @param flags Open flags, currently unused (e.g. O_NONBLOCK)
2743  * @param archive_nums Which archive numbers this copytool is responsible for
2744  */
2745 int llapi_copytool_start(void **priv, int flags, int archive_num_count,
2746                          int *archive_nums)
2747 {
2748         struct copytool_private *ct;
2749         int rc;
2750
2751         if (archive_num_count > 0 && archive_nums == NULL) {
2752                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2753                           "NULL archive numbers");
2754                 return -EINVAL;
2755         }
2756
2757         ct = malloc(sizeof(*ct) +
2758                     archive_num_count * sizeof(ct->archive_nums[0]));
2759         if (ct == NULL)
2760                 return -ENOMEM;
2761
2762         ct->magic = CT_PRIV_MAGIC;
2763         ct->archive_num_count = archive_num_count;
2764         if (ct->archive_num_count > 0)
2765                 memcpy(ct->archive_nums, archive_nums, archive_num_count *
2766                        sizeof(ct->archive_nums[0]));
2767
2768         rc = libcfs_ulnl_start(&ct->lnl, LNL_GRP_HSM);
2769         if (rc < 0)
2770                 goto out_err;
2771
2772         *priv = ct;
2773         return 0;
2774
2775 out_err:
2776         free(ct);
2777         return rc;
2778 }
2779
2780 /** Deregister a copytool */
2781 int llapi_copytool_fini(void **priv)
2782 {
2783         struct copytool_private *ct = (struct copytool_private *)*priv;
2784
2785         if (!ct || (ct->magic != CT_PRIV_MAGIC))
2786                 return -EINVAL;
2787
2788         libcfs_ulnl_stop(&ct->lnl);
2789         free(ct);
2790         *priv = NULL;
2791         return 0;
2792 }
2793
2794 /** Wait for the next hsm_action_list
2795  * @param priv Opaque private control structure
2796  * @param halh Action list handle, will be allocated here
2797  * @param msgsize Number of bytes in the message, will be set here
2798  * @return 0 valid message received; halh and msgsize are set
2799  *         <0 error code
2800  */
2801 int llapi_copytool_recv(void *priv, struct hsm_action_list **halh, int *msgsize)
2802 {
2803         struct copytool_private *ct = (struct copytool_private *)priv;
2804         struct lnl_hdr *lnlh;
2805         struct hsm_action_list *hal;
2806         int rc = 0;
2807
2808         if (!ct || (ct->magic != CT_PRIV_MAGIC))
2809                 return -EINVAL;
2810         if (halh == NULL || msgsize == NULL)
2811                 return -EINVAL;
2812
2813         rc = libcfs_ulnl_msg_get(&ct->lnl, HAL_MAXSIZE,
2814                                  LNL_TRANSPORT_HSM, &lnlh);
2815         if (rc < 0)
2816                 return rc;
2817
2818         /* Handle generic messages */
2819         if (lnlh->lnl_transport == LNL_TRANSPORT_GENERIC &&
2820             lnlh->lnl_msgtype == LNL_MSG_SHUTDOWN) {
2821                 rc = -ESHUTDOWN;
2822                 goto out_free;
2823         }
2824
2825         if (lnlh->lnl_transport != LNL_TRANSPORT_HSM ||
2826             lnlh->lnl_msgtype != HMT_ACTION_LIST) {
2827                 llapi_err(LLAPI_MSG_ERROR | LLAPI_MSG_NO_ERRNO,
2828                           "Unknown HSM message type %d:%d\n",
2829                           lnlh->lnl_transport, lnlh->lnl_msgtype);
2830                 rc = -EPROTO;
2831                 goto out_free;
2832         }
2833
2834         /* Our message is an hsm_action_list */
2835
2836         hal = (struct hsm_action_list *)(lnlh + 1);
2837
2838         /* Check that we have registered for this archive # */
2839         for (rc = 0; rc < ct->archive_num_count; rc++) {
2840                 if (hal->hal_archive_num == ct->archive_nums[rc])
2841                         break;
2842         }
2843         if (rc >= ct->archive_num_count) {
2844                 CDEBUG(D_INFO, "This copytool does not service archive #%d, "
2845                        "ignoring this request.\n", hal->hal_archive_num);
2846                 rc = 0;
2847                 goto out_free;
2848         }
2849
2850         *halh = hal;
2851         *msgsize = lnlh->lnl_msglen - sizeof(*lnlh);
2852         return 0;
2853
2854 out_free:
2855         libcfs_ulnl_msg_free(&lnlh);
2856         *halh = NULL;
2857         *msgsize = 0;
2858         return rc;
2859 }
2860
2861 /** Release the action list when done with it. */
2862 int llapi_copytool_free(struct hsm_action_list **hal)
2863 {
2864         if (*hal) {
2865                 struct lnl_hdr *lnlh = (struct lnl_hdr *)*hal - 1;
2866                 libcfs_ulnl_msg_free(&lnlh);
2867         }
2868         *hal = NULL;
2869         return 0;
2870 }
2871
2872
2873