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