Whamcloud - gitweb
328c7dfa9cfae45bc04515fc7f73a1dce395664f
[fs/lustre-release.git] / lustre / utils / obd.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/utils/obd.c
32  *
33  * Author: Peter J. Braam <braam@clusterfs.com>
34  * Author: Phil Schwan <phil@clusterfs.com>
35  * Author: Andreas Dilger <adilger@clusterfs.com>
36  * Author: Robert Read <rread@clusterfs.com>
37  */
38
39 #include <sys/ioctl.h>
40 #include <sys/socket.h>
41 #include <sys/stat.h>
42 #include <sys/time.h>
43 #include <sys/types.h>
44 #include <sys/un.h>
45 #include <sys/wait.h>
46
47 #include <ctype.h>
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <getopt.h>
51 #include <signal.h>
52 #include <stdarg.h>
53 #include <stdbool.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <time.h>
58 #include <unistd.h>
59 #include <limits.h>
60 #include "obdctl.h"
61 #include "lustreapi_internal.h"
62 #include <libcfs/util/list.h>
63 #include <libcfs/util/ioctl.h>
64 #include <libcfs/util/param.h>
65 #include <libcfs/util/parser.h>
66 #include <libcfs/util/string.h>
67
68 #include <linux/lnet/nidstr.h>
69 #include <linux/lnet/lnetctl.h>
70 #ifdef HAVE_SERVER_SUPPPORT
71 #include <linux/lustre/lustre_barrier_user.h>
72 #include <linux/lustre/lustre_disk.h>
73 #endif
74 #include <linux/lustre/lustre_cfg.h>
75 #include <linux/lustre/lustre_ioctl.h>
76 #include <linux/lustre/lustre_ostid.h>
77 #include <linux/lustre/lustre_param.h>
78 #include <linux/lustre/lustre_ver.h>
79
80 #include <lustre/lustreapi.h>
81
82 #define MAX_STRING_SIZE 128
83
84 #if HAVE_LIBPTHREAD
85 #include <sys/ipc.h>
86 #include <sys/shm.h>
87 #include <pthread.h>
88
89 #define MAX_THREADS 4096
90 #define MAX_BASE_ID 0xffffffff
91 #define NIDSTRING_LENGTH 64
92 struct shared_data {
93         pthread_mutex_t mutex;
94         pthread_cond_t  cond;
95         int       stopping;
96         struct {
97                 __u64 counters[MAX_THREADS];
98                 __u64 offsets[MAX_THREADS];
99                 int   thr_running;
100                 int   start_barrier;
101                 int   stop_barrier;
102                 struct timeval start_time;
103                 struct timeval end_time;
104         } body;
105 };
106
107 static struct shared_data *shared_data;
108 static __u64 counter_snapshot[2][MAX_THREADS];
109 static int prev_valid;
110 static struct timeval prev_time;
111 static int thread;
112 static int nthreads;
113 #else
114 const int thread;
115 const int nthreads = 1;
116 #endif
117
118 static int cur_device = -1;
119
120 int lcfg_ioctl(char *func, int dev_id, struct lustre_cfg *lcfg)
121 {
122         struct obd_ioctl_data data;
123         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
124         int rc;
125
126         memset(&data, 0, sizeof(data));
127         data.ioc_dev = cur_device;
128         data.ioc_type = LUSTRE_CFG_TYPE;
129         data.ioc_plen1 = lustre_cfg_len(lcfg->lcfg_bufcount,
130                                         lcfg->lcfg_buflens);
131         data.ioc_pbuf1 = (void *)lcfg;
132         memset(buf, 0, sizeof(rawbuf));
133         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
134         if (rc) {
135                 fprintf(stderr, "error: %s: invalid ioctl\n", jt_cmdname(func));
136                 return rc;
137         }
138
139         rc =  l_ioctl(dev_id, OBD_IOC_PROCESS_CFG, buf);
140
141         return rc;
142 }
143
144 static int do_device(char *func, char *devname);
145
146 static int get_mgs_device(void)
147 {
148         char mgs[] = "$MGS";
149         static int mgs_device = -1;
150
151         if (mgs_device == -1) {
152                 int rc;
153
154                 do_disconnect(NULL, 1);
155                 rc = do_device("mgsioc", mgs);
156                 if (rc) {
157                         fprintf(stderr,
158                                 "This command must be run on the MGS.\n");
159                         errno = ENODEV;
160                         return -1;
161                 }
162                 mgs_device = cur_device;
163         }
164         return mgs_device;
165 }
166
167 /* Returns -1 on error with errno set */
168 int lcfg_mgs_ioctl(char *func, int dev_id, struct lustre_cfg *lcfg)
169 {
170         struct obd_ioctl_data data;
171         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
172         int rc;
173
174         memset(&data, 0, sizeof(data));
175         rc = data.ioc_dev = get_mgs_device();
176         if (rc < 0)
177                 goto out;
178         data.ioc_type = LUSTRE_CFG_TYPE;
179         data.ioc_plen1 = lustre_cfg_len(lcfg->lcfg_bufcount,
180                                         lcfg->lcfg_buflens);
181         data.ioc_pbuf1 = (void *)lcfg;
182         memset(buf, 0, sizeof(rawbuf));
183         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
184         if (rc) {
185                 fprintf(stderr, "error: %s: invalid ioctl\n", jt_cmdname(func));
186                 return rc;
187         }
188
189         rc = l_ioctl(dev_id, OBD_IOC_PARAM, buf);
190 out:
191         if (rc && errno == ENOSYS)
192                 fprintf(stderr, "Make sure cfg_device is set first.\n");
193
194         return rc;
195 }
196
197 char *obdo_print(struct obdo *obd)
198 {
199         char buf[1024];
200
201         snprintf(buf, sizeof(buf), "id: %#jx\ngrp: %#jx\natime: %ju\n"
202                  "mtime: %ju\nctime: %ju\nsize: %ju\nblocks: %ju"
203                  "\nblksize: %u\nmode: %o\nuid: %d\ngid: %d\nflags: %x\n"
204                  "misc: %x\nnlink: %d,\nvalid %#jx\n",
205                  (uintmax_t)ostid_id(&obd->o_oi),
206                  (uintmax_t)ostid_seq(&obd->o_oi),
207                  (uintmax_t)obd->o_atime, (uintmax_t)obd->o_mtime,
208                  (uintmax_t)obd->o_ctime, (uintmax_t)obd->o_size,
209                  (uintmax_t)obd->o_blocks, obd->o_blksize, obd->o_mode,
210                  obd->o_uid, obd->o_gid, obd->o_flags, obd->o_misc,
211                  obd->o_nlink, (uintmax_t)obd->o_valid);
212         return strdup(buf);
213 }
214
215 #define BAD_VERBOSE (-999999999)
216
217 #define N2D_OFF 0x100      /* So we can tell between error codes and devices */
218
219 static int do_name2dev(char *func, char *name)
220 {
221         struct obd_ioctl_data data;
222         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
223         int rc;
224
225         memset(&data, 0, sizeof(data));
226         data.ioc_dev = cur_device;
227         data.ioc_inllen1 = strlen(name) + 1;
228         data.ioc_inlbuf1 = name;
229
230         memset(buf, 0, sizeof(rawbuf));
231         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
232         if (rc < 0) {
233                 fprintf(stderr, "error: %s: invalid ioctl\n", jt_cmdname(func));
234                 return -rc;
235         }
236         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_NAME2DEV, buf);
237         if (rc < 0)
238                 return errno;
239         rc = llapi_ioctl_unpack(&data, buf, sizeof(rawbuf));
240         if (rc) {
241                 fprintf(stderr, "error: %s: invalid reply\n", jt_cmdname(func));
242                 return rc;
243         }
244
245         return data.ioc_dev + N2D_OFF;
246 }
247
248 /*
249  * resolve a device name to a device number.
250  * supports a number, $name or %uuid.
251  */
252 int parse_devname(char *func, char *name)
253 {
254         int rc;
255         int ret = -1;
256         int try_digit;
257
258         if (!name)
259                 return ret;
260
261         try_digit = isdigit(name[0]);
262
263         if (name[0] == '$' || name[0] == '%')
264                 name++;
265
266         rc = do_name2dev(func, name);
267         if (rc >= N2D_OFF)
268                 return rc - N2D_OFF;
269
270         if (try_digit)
271                 ret = strtoul(name, NULL, 0);
272         else
273                 fprintf(stderr, "No device found for name %s: %s\n",
274                         name, strerror(rc));
275         return ret;
276 }
277
278 char *jt_cmdname(char *func)
279 {
280         static char buf[512];
281
282         if (thread) {
283                 sprintf(buf, "%s-%d", func, thread);
284                 return buf;
285         }
286
287         return func;
288 }
289
290 #define difftime(a, b)                                  \
291         ((a)->tv_sec - (b)->tv_sec +                    \
292          ((a)->tv_usec - (b)->tv_usec) / 1000000.0)
293
294 static int be_verbose(int verbose, struct timeval *next_time,
295                       __u64 num, __u64 *next_num, int num_total)
296 {
297         struct timeval now;
298
299         if (!verbose)
300                 return 0;
301
302         if (next_time)
303                 gettimeofday(&now, NULL);
304
305         /* A positive verbosity means to print every X iterations */
306         if (verbose > 0 && (num >= *next_num || num >= num_total)) {
307                 *next_num += verbose;
308                 if (next_time) {
309                         next_time->tv_sec = now.tv_sec - verbose;
310                         next_time->tv_usec = now.tv_usec;
311                 }
312                 return 1;
313         }
314
315         /* A negative verbosity means to print at most each X seconds */
316         if (verbose < 0 && next_time && difftime(&now, next_time) >= 0.0) {
317                 next_time->tv_sec = now.tv_sec - verbose;
318                 next_time->tv_usec = now.tv_usec;
319                 *next_num = num;
320                 return 1;
321         }
322
323         return 0;
324 }
325
326 static int get_verbose(char *func, const char *arg)
327 {
328         int verbose;
329         char *end;
330
331         if (!arg || arg[0] == 'v') {
332                 verbose = 1;
333         } else if (arg[0] == 's' || arg[0] == 'q') {
334                 verbose = 0;
335         } else {
336                 verbose = (int)strtoul(arg, &end, 0);
337                 if (*end) {
338                         fprintf(stderr, "error: %s: bad verbose option '%s'\n",
339                                 jt_cmdname(func), arg);
340                         return BAD_VERBOSE;
341                 }
342         }
343
344         if (verbose < 0)
345                 printf("Print status every %d seconds\n", -verbose);
346         else if (verbose == 1)
347                 printf("Print status every operation\n");
348         else if (verbose > 1)
349                 printf("Print status every %d operations\n", verbose);
350
351         return verbose;
352 }
353
354 int do_disconnect(char *func, int verbose)
355 {
356         lcfg_set_devname(NULL);
357         cur_device = -1;
358         return 0;
359 }
360
361 #ifdef MAX_THREADS
362 static int shmem_setup(void)
363 {
364         pthread_mutexattr_t mattr;
365         pthread_condattr_t  cattr;
366         int rc;
367         int shmid;
368
369         /* Create new segment */
370         shmid = shmget(IPC_PRIVATE, sizeof(*shared_data), 0600);
371         if (shmid == -1) {
372                 fprintf(stderr, "Can't create shared data: %s\n",
373                         strerror(errno));
374                 return errno;
375         }
376
377         /* Attatch to new segment */
378         shared_data = (struct shared_data *)shmat(shmid, NULL, 0);
379
380         if (shared_data == (struct shared_data *)(-1)) {
381                 fprintf(stderr, "Can't attach shared data: %s\n",
382                         strerror(errno));
383                 shared_data = NULL;
384                 return errno;
385         }
386
387         /*
388          * Mark segment as destroyed, so it will disappear when we exit.
389          * Forks will inherit attached segments, so we should be OK.
390          */
391         if (shmctl(shmid, IPC_RMID, NULL) == -1) {
392                 fprintf(stderr, "Can't destroy shared data: %s\n",
393                         strerror(errno));
394                 return errno;
395         }
396
397         pthread_mutexattr_init(&mattr);
398         pthread_condattr_init(&cattr);
399
400         rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
401         if (rc != 0) {
402                 fprintf(stderr, "Can't set shared mutex attr\n");
403                 goto out;
404         }
405
406         rc = pthread_condattr_setpshared(&cattr, PTHREAD_PROCESS_SHARED);
407         if (rc != 0) {
408                 fprintf(stderr, "Can't set shared cond attr\n");
409                 goto out;
410         }
411
412         pthread_mutex_init(&shared_data->mutex, &mattr);
413         pthread_cond_init(&shared_data->cond, &cattr);
414 out:
415         pthread_mutexattr_destroy(&mattr);
416         pthread_condattr_destroy(&cattr);
417
418         return rc;
419 }
420
421 static inline void shmem_lock(void)
422 {
423         pthread_mutex_lock(&shared_data->mutex);
424 }
425
426 static inline void shmem_unlock(void)
427 {
428         pthread_mutex_unlock(&shared_data->mutex);
429 }
430
431 static inline void shmem_wait(void)
432 {
433         pthread_cond_wait(&shared_data->cond, &shared_data->mutex);
434 }
435
436 static inline void shmem_wakeup_all(void)
437 {
438         pthread_cond_broadcast(&shared_data->cond);
439 }
440
441 static inline void shmem_reset(int total_threads)
442 {
443         if (!shared_data)
444                 return;
445
446         memset(&shared_data->body, 0, sizeof(shared_data->body));
447         memset(counter_snapshot, 0, sizeof(counter_snapshot));
448         prev_valid = 0;
449         shared_data->stopping = 0;
450         shared_data->body.start_barrier = total_threads;
451         shared_data->body.stop_barrier = total_threads;
452 }
453
454 static inline void shmem_bump(__u32 counter)
455 {
456         static bool running_not_bumped = true;
457
458         if (!shared_data || thread <= 0 || thread > MAX_THREADS)
459                 return;
460
461         shmem_lock();
462         shared_data->body.counters[thread - 1] += counter;
463         if (running_not_bumped) {
464                 shared_data->body.thr_running++;
465                 running_not_bumped = false;
466         }
467         shmem_unlock();
468 }
469
470 static void shmem_total(int total_threads)
471 {
472         __u64 total = 0;
473         double secs;
474         int i;
475
476         if (!shared_data || total_threads > MAX_THREADS)
477                 return;
478
479         shmem_lock();
480         for (i = 0; i < total_threads; i++)
481                 total += shared_data->body.counters[i];
482
483         secs = difftime(&shared_data->body.end_time,
484                         &shared_data->body.start_time);
485         shmem_unlock();
486
487         printf("Total: total %ju threads %d sec %f %f/second\n",
488                (uintmax_t)total, total_threads, secs, total / secs);
489 }
490
491 static void shmem_snap(int total_threads, int live_threads)
492 {
493         struct timeval this_time;
494         int non_zero = 0;
495         __u64 total = 0;
496         double secs;
497         int running;
498         int i;
499
500         if (!shared_data || total_threads > MAX_THREADS)
501                 return;
502
503         shmem_lock();
504         memcpy(counter_snapshot[0], shared_data->body.counters,
505                total_threads * sizeof(counter_snapshot[0][0]));
506         running = shared_data->body.thr_running;
507         shmem_unlock();
508
509         gettimeofday(&this_time, NULL);
510
511         for (i = 0; i < total_threads; i++) {
512                 long long this_count =
513                         counter_snapshot[0][i] - counter_snapshot[1][i];
514
515                 if (this_count != 0) {
516                         non_zero++;
517                         total += this_count;
518                 }
519         }
520
521         secs = difftime(&this_time, &prev_time);
522         if (prev_valid && secs > 1.0) {   /* someone screwed with the time? */
523                 printf("%d/%d Total: %f/second\n", non_zero, total_threads,
524                        total / secs);
525
526                 memcpy(counter_snapshot[1], counter_snapshot[0],
527                        total_threads * sizeof(counter_snapshot[0][0]));
528                 prev_time = this_time;
529         }
530         if (!prev_valid && running == total_threads) {
531                 prev_valid = 1;
532                 /* drop counters when all threads were started */
533                 memcpy(counter_snapshot[1], counter_snapshot[0],
534                        total_threads * sizeof(counter_snapshot[0][0]));
535                 prev_time = this_time;
536         }
537 }
538
539 static void shmem_stop(void)
540 {
541         if (!shared_data)
542                 return;
543
544         shared_data->stopping = 1;
545 }
546
547 static void shmem_cleanup(void)
548 {
549         if (!shared_data)
550                 return;
551
552         shmem_stop();
553
554         pthread_mutex_destroy(&shared_data->mutex);
555         pthread_cond_destroy(&shared_data->cond);
556 }
557
558 static int shmem_running(void)
559 {
560         return (!shared_data || !shared_data->stopping);
561 }
562
563 static void shmem_end_time_locked(void)
564 {
565         shared_data->body.stop_barrier--;
566         if (shared_data->body.stop_barrier == 0)
567                 gettimeofday(&shared_data->body.end_time, NULL);
568 }
569
570 static void shmem_start_time_locked(void)
571 {
572         shared_data->body.start_barrier--;
573         if (shared_data->body.start_barrier == 0) {
574                 shmem_wakeup_all();
575                 gettimeofday(&shared_data->body.start_time, NULL);
576         } else {
577                 shmem_wait();
578         }
579 }
580
581 #else
582 static int shmem_setup(void)
583 {
584         return 0;
585 }
586
587 static inline void shmem_reset(int total_threads)
588 {
589 }
590
591 static inline void shmem_bump(__u32 counters)
592 {
593 }
594
595 static void shmem_lock(void)
596 {
597 }
598
599 static void shmem_unlock(void)
600 {
601 }
602
603 static void shmem_cleanup(void)
604 {
605 }
606
607 static int shmem_running(void)
608 {
609         return 1;
610 }
611 #endif
612
613 extern command_t cmdlist[];
614
615 static int do_device(char *func, char *devname)
616 {
617         int dev;
618
619         dev = parse_devname(func, devname);
620         if (dev < 0)
621                 return -1;
622
623         lcfg_set_devname(devname);
624         cur_device = dev;
625         return 0;
626 }
627
628 int jt_obd_get_device(void)
629 {
630         return cur_device;
631 }
632
633 int jt_obd_device(int argc, char **argv)
634 {
635         int rc;
636
637         if (argc > 2)
638                 return CMD_HELP;
639
640         if (argc == 1) {
641                 printf("current device is %d - %s\n",
642                        cur_device, lcfg_get_devname() ? : "not set");
643                 return 0;
644         }
645         rc = do_device("device", argv[1]);
646         return rc;
647 }
648
649 int jt_opt_device(int argc, char **argv)
650 {
651         int ret;
652         int rc;
653
654         if (argc < 3)
655                 return CMD_HELP;
656
657         rc = do_device("device", argv[1]);
658
659         if (!rc)
660                 rc = Parser_execarg(argc - 2, argv + 2, cmdlist);
661
662         ret = do_disconnect(argv[0], 0);
663         if (!rc)
664                 rc = ret;
665
666         return rc;
667 }
668
669 #ifdef MAX_THREADS
670 static void parent_sighandler(int sig)
671 {
672 }
673
674 int jt_opt_threads(int argc, char **argv)
675 {
676         static char      cmdstr[129];
677         sigset_t         saveset;
678         sigset_t         sigset;
679         struct sigaction sigact;
680         struct sigaction saveact1;
681         struct sigaction saveact2;
682         unsigned long    threads;
683         __u64            next_thread;
684         int verbose;
685         int rc = 0;
686         int report_count = -1;
687         char *end;
688         int i;
689
690         if (argc < 5)
691                 return CMD_HELP;
692
693         threads = strtoul(argv[1], &end, 0);
694
695         if (*end == '.')
696                 report_count = strtoul(end + 1, &end, 0);
697
698         if (*end || threads > MAX_THREADS) {
699                 fprintf(stderr, "error: %s: invalid thread count '%s'\n",
700                         jt_cmdname(argv[0]), argv[1]);
701                 return CMD_HELP;
702         }
703
704         verbose = get_verbose(argv[0], argv[2]);
705         if (verbose == BAD_VERBOSE)
706                 return CMD_HELP;
707
708         if (verbose != 0) {
709                 snprintf(cmdstr, sizeof(cmdstr), "%s", argv[4]);
710                 for (i = 5; i < argc; i++)
711                         snprintf(cmdstr + strlen(cmdstr),
712                                  sizeof(cmdstr) - strlen(cmdstr),
713                                  " %s", argv[i]);
714
715                 printf("%s: starting %ld threads on device %s running %s\n",
716                        argv[0], threads, argv[3], cmdstr);
717         }
718
719         shmem_reset(threads);
720
721         sigemptyset(&sigset);
722         sigaddset(&sigset, SIGALRM);
723         sigaddset(&sigset, SIGCHLD);
724         sigprocmask(SIG_BLOCK, &sigset, &saveset);
725
726         nthreads = threads;
727
728         for (i = 1, next_thread = verbose; i <= threads; i++) {
729                 rc = fork();
730                 if (rc < 0) {
731                         fprintf(stderr, "error: %s: #%d - %s\n", argv[0], i,
732                                 strerror(rc = errno));
733                         break;
734                 } else if (rc == 0) {
735                         sigprocmask(SIG_SETMASK, &saveset, NULL);
736
737                         thread = i;
738                         argv[2] = "--device";
739                         exit(jt_opt_device(argc - 2, argv + 2));
740                 } else if (be_verbose(verbose, NULL, i, &next_thread, threads))
741                         printf("%s: thread #%d (PID %d) started\n",
742                                argv[0], i, rc);
743                 rc = 0;
744         }
745
746         if (!thread) {          /* parent process */
747                 int live_threads = threads;
748
749                 sigemptyset(&sigset);
750                 sigemptyset(&sigact.sa_mask);
751                 sigact.sa_handler = parent_sighandler;
752                 sigact.sa_flags = 0;
753
754                 sigaction(SIGALRM, &sigact, &saveact1);
755                 sigaction(SIGCHLD, &sigact, &saveact2);
756
757                 while (live_threads > 0) {
758                         int status;
759                         pid_t ret;
760
761                         if (verbose < 0)        /* periodic stats */
762                                 alarm(-verbose);
763
764                         sigsuspend(&sigset);
765                         alarm(0);
766
767                         while (live_threads > 0) {
768                                 ret = waitpid(0, &status, WNOHANG);
769                                 if (ret == 0)
770                                         break;
771
772                                 if (ret < 0) {
773                                         fprintf(stderr,
774                                                 "error: %s: wait - %s\n",
775                                                 argv[0], strerror(errno));
776                                         if (!rc)
777                                                 rc = errno;
778                                         continue;
779                                 } else {
780                                         /*
781                                          * This is a hack.  We _should_ be able
782                                          * to use WIFEXITED(status) to see if
783                                          * there was an error, but it appears
784                                          * to be broken and it always returns 1
785                                          * (OK).  See wait(2).
786                                          */
787                                         int err = WEXITSTATUS(status);
788
789                                         if (err || WIFSIGNALED(status))
790                                                 fprintf(stderr,
791                                                         "%s: PID %d had rc=%d\n",
792                                                         argv[0], ret, err);
793                                         if (!rc)
794                                                 rc = err;
795
796                                         live_threads--;
797                                 }
798                         }
799
800                         /* Show stats while all threads running */
801                         if (verbose < 0) {
802                                 shmem_snap(threads, live_threads);
803                                 if (report_count > 0 && --report_count == 0)
804                                         shmem_stop();
805                         }
806                 }
807                 sigaction(SIGCHLD, &saveact2, NULL);
808                 sigaction(SIGALRM, &saveact1, NULL);
809         }
810
811         shmem_total(threads);
812         sigprocmask(SIG_SETMASK, &saveset, NULL);
813
814         return rc;
815 }
816 #else
817 int jt_opt_threads(int argc, char **argv)
818 {
819         fprintf(stderr, "%s not-supported in a single-threaded runtime\n",
820                 jt_cmdname(argv[0]));
821         return CMD_HELP;
822 }
823 #endif
824
825 int jt_opt_net(int argc, char **argv)
826 {
827         char *arg2[3];
828         int rc;
829
830         if (argc < 3)
831                 return CMD_HELP;
832
833         arg2[0] = argv[0];
834         arg2[1] = argv[1];
835         arg2[2] = NULL;
836         rc = jt_ptl_network(2, arg2);
837
838         if (!rc)
839                 rc = Parser_execarg(argc - 2, argv + 2, cmdlist);
840
841         return rc;
842 }
843
844 #ifdef HAVE_SERVER_SUPPORT
845 /*
846  * Place this here so we can build tools that work with
847  * older Lustre versions
848  */
849 #ifndef OBD_IOC_NO_TRANSNO
850 #define OBD_IOC_NO_TRANSNO      _IOW('f', 140, OBD_IOC_DATA_TYPE)
851 #endif
852
853 int jt_obd_no_transno(int argc, char **argv)
854 {
855         struct obd_ioctl_data data;
856         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
857         glob_t path;
858         int count;
859         int fd;
860         int rc;
861
862         if (argc != 1)
863                 return CMD_HELP;
864
865         memset(buf, 0, sizeof(rawbuf));
866
867         rc = cfs_get_param_paths(&path, "no_transno");
868         if (rc != 0)
869                 goto old_ioctl;
870
871         fd = open(path.gl_pathv[0], O_WRONLY);
872         if (fd < 0) {
873                 cfs_free_param_data(&path);
874                 goto old_ioctl;
875         }
876
877         snprintf(rawbuf, sizeof(rawbuf), "%d", cur_device);
878
879         count = write(fd, rawbuf, strlen(rawbuf));
880         if (count < 0)
881                 rc = errno;
882
883         cfs_free_param_data(&path);
884         close(fd);
885         if (rc)
886                 goto old_ioctl;
887
888         return 0;
889
890 old_ioctl:
891 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
892         memset(&data, 0, sizeof(data));
893         data.ioc_dev = cur_device;
894
895         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
896         if (rc) {
897                 fprintf(stderr, "error: %s: invalid ioctl\n",
898                         jt_cmdname(argv[0]));
899                 return rc;
900         }
901         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_NO_TRANSNO, buf);
902         if (rc < 0)
903                 fprintf(stderr, "error: %s: %s\n", jt_cmdname(argv[0]),
904                         strerror(rc = errno));
905 #endif
906         return rc;
907 }
908
909 int jt_obd_set_readonly(int argc, char **argv)
910 {
911         struct obd_ioctl_data data;
912         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
913         int rc;
914
915         memset(&data, 0, sizeof(data));
916         data.ioc_dev = cur_device;
917
918         if (argc != 1)
919                 return CMD_HELP;
920
921         memset(buf, 0, sizeof(rawbuf));
922         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
923         if (rc) {
924                 fprintf(stderr, "error: %s: invalid ioctl\n",
925                         jt_cmdname(argv[0]));
926                 return rc;
927         }
928         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_SET_READONLY, buf);
929         if (rc < 0)
930                 fprintf(stderr, "error: %s: %s\n", jt_cmdname(argv[0]),
931                         strerror(rc = errno));
932
933         return rc;
934 }
935
936 static int obd_abort_recovery(char *cmd, enum obd_abort_recovery_flags flags)
937 {
938         struct obd_ioctl_data data = {
939                 .ioc_dev = cur_device,
940                 .ioc_type = flags,
941         };
942         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
943         int rc;
944
945         memset(buf, 0, sizeof(rawbuf));
946         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
947         if (rc) {
948                 fprintf(stderr, "error: %s: invalid ioctl\n",
949                         jt_cmdname(cmd));
950                 return rc;
951         }
952         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_ABORT_RECOVERY, buf);
953         if (rc < 0)
954                 fprintf(stderr, "error: %s: %s\n", jt_cmdname(cmd),
955                         strerror(rc = errno));
956
957         return rc;
958 }
959
960 int jt_obd_abort_recovery(int argc, char **argv)
961 {
962         if (argc != 1)
963                 return CMD_HELP;
964
965         return obd_abort_recovery(argv[0], OBD_FLG_ABORT_RECOV_OST);
966 }
967
968 int jt_obd_abort_recovery_mdt(int argc, char **argv)
969 {
970         if (argc != 1)
971                 return CMD_HELP;
972
973         return obd_abort_recovery(argv[0], OBD_FLG_ABORT_RECOV_MDT);
974 }
975 #else /* ! HAVE_SERVER_SUPPROT */
976 int jt_obd_no_transno(int argc, char **argv)
977 {
978         if (argc != 1)
979                 return CMD_HELP;
980
981         fprintf(stderr, "error: %s: invalid ioctl\n",
982                 jt_cmdname(argv[0]));
983         return -EOPNOTSUPP;
984 }
985
986 int jt_obd_set_readonly(int argc, char **argv)
987 {
988         if (argc != 1)
989                 return CMD_HELP;
990
991         fprintf(stderr, "error: %s: invalid ioctl\n",
992                 jt_cmdname(argv[0]));
993         return -EOPNOTSUPP;
994 }
995
996 int jt_obd_abort_recovery(int argc, char **argv)
997 {
998         if (argc != 1)
999                 return CMD_HELP;
1000
1001         fprintf(stderr, "error: %s: invalid ioctl\n",
1002                 jt_cmdname(argv[0]));
1003         return -EOPNOTSUPP;
1004 }
1005
1006 int jt_obd_abort_recovery_mdt(int argc, char **argv)
1007 {
1008         if (argc != 1)
1009                 return CMD_HELP;
1010
1011         fprintf(stderr, "error: %s: invalid ioctl\n",
1012                 jt_cmdname(argv[0]));
1013         return -EOPNOTSUPP;
1014 }
1015 #endif /* HAVE_SERVER_SUPPORT */
1016
1017 int jt_get_version(int argc, char **argv)
1018 {
1019         char version[128];
1020         int rc;
1021
1022         if (argc != 1)
1023                 return CMD_HELP;
1024
1025         rc = llapi_get_version_string(version, sizeof(version));
1026         if (rc)
1027                 printf("Lustre version: %s\n", LUSTRE_VERSION_STRING);
1028         else
1029                 printf("Lustre version: %s\n", version);
1030
1031         return 0;
1032 }
1033
1034 static void print_obd_line(char *s)
1035 {
1036         const char *param = "osc/%s/ost_conn_uuid";
1037         char buf[MAX_STRING_SIZE];
1038         char obd_name[MAX_OBD_NAME];
1039         FILE *fp = NULL;
1040         glob_t path;
1041         char *ptr;
1042 retry:
1043         /* obd device type is the first 3 characters of param name */
1044         snprintf(buf, sizeof(buf), " %%*d %%*s %.3s %%%zus %%*s %%*d ",
1045                  param, sizeof(obd_name) - 1);
1046         if (sscanf(s, buf, obd_name) == 0)
1047                 goto try_mdc;
1048         if (cfs_get_param_paths(&path, param, obd_name) != 0)
1049                 goto try_mdc;
1050         fp = fopen(path.gl_pathv[0], "r");
1051         if (!fp) {
1052                 /* need to free path data before retry */
1053                 cfs_free_param_data(&path);
1054 try_mdc:
1055                 if (param[0] == 'o') { /* failed with osc, try mdc */
1056                         param = "mdc/%s/mds_conn_uuid";
1057                         goto retry;
1058                 }
1059                 buf[0] = '\0';
1060                 goto fail_print;
1061         }
1062
1063         /* should not ignore fgets(3)'s return value */
1064         if (!fgets(buf, sizeof(buf), fp)) {
1065                 fprintf(stderr, "reading from %s: %s", buf, strerror(errno));
1066                 goto fail_close;
1067         }
1068
1069 fail_close:
1070         fclose(fp);
1071         cfs_free_param_data(&path);
1072
1073         /* trim trailing newlines */
1074         ptr = strrchr(buf, '\n');
1075         if (ptr)
1076                 *ptr = '\0';
1077 fail_print:
1078         ptr = strrchr(s, '\n');
1079         if (ptr)
1080                 *ptr = '\0';
1081         printf("%s%s%s\n", s, buf[0] ? " " : "", buf);
1082 }
1083
1084 /* get device list by ioctl */
1085 int jt_obd_list_ioctl(int argc, char **argv)
1086 {
1087         int rc, index;
1088         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
1089         struct obd_ioctl_data *data = (struct obd_ioctl_data *)buf;
1090
1091         if (argc > 2)
1092                 return CMD_HELP;
1093         /* Just ignore a -t option.  Only supported with /proc. */
1094         else if (argc == 2 && strcmp(argv[1], "-t") != 0)
1095                 return CMD_HELP;
1096
1097         for (index = 0;; index++) {
1098                 memset(buf, 0, sizeof(rawbuf));
1099                 data->ioc_version = OBD_IOCTL_VERSION;
1100                 data->ioc_inllen1 =
1101                         sizeof(rawbuf) - __ALIGN_KERNEL(sizeof(*data), 8);
1102                 data->ioc_inlbuf1 = buf + __ALIGN_KERNEL(sizeof(*data), 8);
1103                 data->ioc_len = obd_ioctl_packlen(data);
1104                 data->ioc_count = index;
1105
1106                 rc = l_ioctl(OBD_DEV_ID, OBD_IOC_GETDEVICE, buf);
1107                 if (rc != 0)
1108                         break;
1109                 printf("%s\n", (char *)data->ioc_bulk);
1110         }
1111         if (rc != 0) {
1112                 if (errno == ENOENT)
1113                         /* no device or the last device */
1114                         rc = 0;
1115                 else
1116                         fprintf(stderr,
1117                                 "Error getting device list: %s: check dmesg\n",
1118                                 strerror(errno));
1119         }
1120         return rc;
1121 }
1122
1123 int jt_obd_list(int argc, char **argv)
1124 {
1125         char buf[MAX_STRING_SIZE];
1126         int print_obd = 0;
1127         glob_t path;
1128         FILE *fp;
1129
1130         if (argc > 2)
1131                 return CMD_HELP;
1132
1133         if (argc == 2) {
1134                 if (strcmp(argv[1], "-t") == 0)
1135                         print_obd = 1;
1136                 else
1137                         return CMD_HELP;
1138         }
1139
1140         if (cfs_get_param_paths(&path, "devices") ||
1141             !(fp = fopen(path.gl_pathv[0], "r"))) {
1142                 cfs_free_param_data(&path);
1143
1144                 return jt_obd_list_ioctl(argc, argv);
1145         }
1146
1147         while (fgets(buf, sizeof(buf), fp) != NULL)
1148                 if (print_obd)
1149                         print_obd_line(buf);
1150                 else
1151                         printf("%s", buf);
1152
1153         cfs_free_param_data(&path);
1154         fclose(fp);
1155         return 0;
1156 }
1157
1158 struct jt_fid_space {
1159         __u64   jt_seq;
1160         __u64   jt_id;
1161         int     jt_width;
1162 };
1163
1164 int jt_obd_alloc_fids(struct jt_fid_space *space, struct lu_fid *fid,
1165                       __u64 *count)
1166 {
1167         int rc;
1168
1169         if (space->jt_seq == 0 || space->jt_id == space->jt_width) {
1170                 struct obd_ioctl_data  data;
1171                 char rawbuf[MAX_IOC_BUFLEN];
1172                 char *buf = rawbuf;
1173                 __u64 seqnr;
1174                 int max_count;
1175
1176                 memset(&data, 0, sizeof(data));
1177                 data.ioc_dev = cur_device;
1178
1179                 data.ioc_pbuf1 = (char *)&seqnr;
1180                 data.ioc_plen1 = sizeof(seqnr);
1181
1182                 data.ioc_pbuf2 = (char *)&max_count;
1183                 data.ioc_plen2 = sizeof(max_count);
1184
1185                 memset(buf, 0, sizeof(rawbuf));
1186                 rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
1187                 if (rc) {
1188                         fprintf(stderr, "error: invalid ioctl rc = %d\n", rc);
1189                         return rc;
1190                 }
1191
1192                 rc = l_ioctl(OBD_DEV_ID, OBD_IOC_ECHO_ALLOC_SEQ, buf);
1193                 if (rc) {
1194                         fprintf(stderr, "ioctl error: rc = %d\n", rc);
1195                         return rc;
1196                 }
1197
1198                 space->jt_seq = *(__u64 *)data.ioc_pbuf1;
1199                 space->jt_width = *(int *)data.ioc_pbuf2;
1200                 space->jt_id = 1;
1201         }
1202         fid->f_seq = space->jt_seq;
1203         fid->f_oid = space->jt_id;
1204         fid->f_ver = 0;
1205
1206         space->jt_id = space->jt_id + *count;
1207         if (space->jt_id > space->jt_width)
1208                 space->jt_id = space->jt_width;
1209
1210         *count = space->jt_id - fid->f_oid;
1211         return 0;
1212 }
1213
1214 #define MD_STEP_COUNT 1000
1215 int jt_obd_md_common(int argc, char **argv, int cmd)
1216 {
1217         struct obd_ioctl_data  data;
1218         struct timeval         start;
1219         struct timeval         end_time;
1220         char rawbuf[MAX_IOC_BUFLEN];
1221         char *buf = rawbuf;
1222         int mode = 0000644;
1223         int create_mode;
1224         int rc = 0;
1225         char *parent_basedir = NULL;
1226         char dirname[4096];
1227         int parent_base_id = 0;
1228         int parent_count = 1;
1229         __u64 child_base_id = -1;
1230         int stripe_count = 0;
1231         int stripe_index = -1;
1232         int count = 0;
1233         char *end;
1234         __u64 seconds = 0;
1235         double diff;
1236         int c;
1237         __u64 total_count = 0;
1238         char *name = NULL;
1239         struct jt_fid_space fid_space = {0};
1240         int version = 0;
1241         struct option long_opts[] = {
1242         { .val = 'b',   .name = "child_base_id",
1243                                                 .has_arg = required_argument },
1244         { .val = 'c',   .name = "stripe_count",
1245                                                 .has_arg = required_argument },
1246         { .val = 'd',   .name = "parent_basedir",
1247                                                 .has_arg = required_argument },
1248         { .val = 'D',   .name = "parent_dircount",
1249                                                 .has_arg = required_argument },
1250         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument },
1251         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
1252         { .val = 'n',   .name = "count",        .has_arg = required_argument },
1253         { .val = 't',   .name = "time",         .has_arg = required_argument },
1254         { .val = 'v',   .name = "version",      .has_arg = no_argument },
1255         { .name = NULL } };
1256
1257         while ((c = getopt_long(argc, argv, "b:c:d:D:m:n:t:v",
1258                                 long_opts, NULL)) >= 0) {
1259                 switch (c) {
1260                 case 'b':
1261                         child_base_id = strtoull(optarg, &end, 0);
1262                         if (*end) {
1263                                 fprintf(stderr,
1264                                         "error: %s: bad child_base_id '%s'\n",
1265                                         jt_cmdname(argv[0]), optarg);
1266                                 return CMD_HELP;
1267                         }
1268                         break;
1269                 case 'c':
1270                         stripe_count = strtoul(optarg, &end, 0);
1271                         if (*end) {
1272                                 fprintf(stderr,
1273                                         "error: %s: bad stripe count '%s'\n",
1274                                         jt_cmdname(argv[0]), optarg);
1275                                 return CMD_HELP;
1276                         }
1277                         break;
1278                 case 'd':
1279                         parent_basedir = optarg;
1280                         break;
1281                 case 'D':
1282                         parent_count = strtoul(optarg, &end, 0);
1283                         if (*end) {
1284                                 fprintf(stderr,
1285                                         "error: %s: bad parent count '%s'\n",
1286                                         jt_cmdname(argv[0]), optarg);
1287                                 return CMD_HELP;
1288                         }
1289                         break;
1290                 case 'i':
1291                         stripe_index = strtoul(optarg, &end, 0);
1292                         if (*end) {
1293                                 fprintf(stderr,
1294                                         "error: %s: bad stripe index '%s'\n",
1295                                         jt_cmdname(argv[0]), optarg);
1296                                 return CMD_HELP;
1297                         }
1298                         break;
1299                 case 'm':
1300                         mode = strtoul(optarg, &end, 0);
1301                         if (*end) {
1302                                 fprintf(stderr, "error: %s: bad mode '%s'\n",
1303                                         jt_cmdname(argv[0]), optarg);
1304                                 return CMD_HELP;
1305                         }
1306                         break;
1307                 case 'n':
1308                         total_count = strtoul(optarg, &end, 0);
1309                         if (*end || total_count == 0) {
1310                                 fprintf(stderr, "%s: bad child count '%s'\n",
1311                                         jt_cmdname(argv[0]), optarg);
1312                                 return CMD_HELP;
1313                         }
1314                         break;
1315                 case 't':
1316                         seconds = strtoull(optarg, &end, 0);
1317                         if (*end) {
1318                                 fprintf(stderr, "error: %s: seconds '%s'\n",
1319                                         jt_cmdname(argv[0]), optarg);
1320                                 return CMD_HELP;
1321                         }
1322                         break;
1323                 case 'v':
1324                         version = 1;
1325                         break;
1326                 default:
1327                         fprintf(stderr,
1328                                 "error: %s: option '%s' unrecognized\n",
1329                                 argv[0], argv[optind - 1]);
1330                         return CMD_HELP;
1331                 }
1332         }
1333
1334         memset(&data, 0, sizeof(data));
1335         data.ioc_dev = cur_device;
1336         if (child_base_id == -1) {
1337                 if (optind >= argc)
1338                         return CMD_HELP;
1339                 name = argv[optind];
1340                 total_count = 1;
1341         } else {
1342                 if (optind < argc) {
1343                         fprintf(stderr,
1344                                 "child_base_id and name can not specified at the same time\n");
1345                         return CMD_HELP;
1346                 }
1347         }
1348
1349         if (stripe_count == 0 && stripe_index != -1) {
1350                 fprintf(stderr,
1351                         "If stripe_count is 0, stripe_index can not be specified\n");
1352                 return CMD_HELP;
1353         }
1354
1355         if (total_count == 0 && seconds == 0) {
1356                 fprintf(stderr, "count or seconds needs to be indicated\n");
1357                 return CMD_HELP;
1358         }
1359
1360         if (parent_count <= 0) {
1361                 fprintf(stderr, "parent count must < 0\n");
1362                 return CMD_HELP;
1363         }
1364
1365 #ifdef MAX_THREADS
1366         if (thread) {
1367                 shmem_lock();
1368                 /* threads interleave */
1369                 if (parent_base_id != -1)
1370                         parent_base_id += (thread - 1) % parent_count;
1371
1372                 if (child_base_id != -1)
1373                         child_base_id +=  (thread - 1) *
1374                                 (MAX_BASE_ID / nthreads);
1375
1376                 shmem_start_time_locked();
1377                 shmem_unlock();
1378         }
1379 #endif
1380         /*
1381          * If parent directory is not specified, try to get the directory
1382          * from name
1383          */
1384         if (!parent_basedir) {
1385                 char *last_lash;
1386
1387                 if (!name) {
1388                         fprintf(stderr,
1389                                 "parent_basedir or name must be indicated!\n");
1390                         return CMD_HELP;
1391                 }
1392                 /*Get directory and name from name*/
1393                 last_lash = strrchr(name, '/');
1394                 if (!last_lash || name[0] != '/') {
1395                         fprintf(stderr, "Can not locate %s\n", name);
1396                         return CMD_HELP;
1397                 }
1398
1399                 if (last_lash == name) {
1400                         sprintf(dirname, "%s", "/");
1401                         name++;
1402                 } else {
1403                         int namelen = (unsigned long)last_lash -
1404                                       (unsigned long)name + 1;
1405                         snprintf(dirname, namelen, "%s", name);
1406                         name = last_lash + 1;
1407                 }
1408
1409                 data.ioc_pbuf1 = dirname;
1410                 data.ioc_plen1 = strlen(dirname);
1411
1412                 data.ioc_pbuf2 = name;
1413                 data.ioc_plen2 = strlen(name);
1414         } else {
1415                 if (name) {
1416                         data.ioc_pbuf2 = name;
1417                         data.ioc_plen2 = strlen(name);
1418                 }
1419                 if (parent_base_id > 0)
1420                         sprintf(dirname, "%s%d", parent_basedir,
1421                                 parent_base_id);
1422                 else
1423                         sprintf(dirname, "%s", parent_basedir);
1424                 data.ioc_pbuf1 = dirname;
1425                 data.ioc_plen1 = strlen(dirname);
1426         }
1427
1428         if (cmd == ECHO_MD_MKDIR || cmd == ECHO_MD_RMDIR)
1429                 create_mode = S_IFDIR;
1430         else
1431                 create_mode = S_IFREG;
1432
1433         data.ioc_obdo1.o_mode = mode | S_IFDIR;
1434         data.ioc_obdo1.o_valid = OBD_MD_FLID | OBD_MD_FLTYPE | OBD_MD_FLMODE |
1435                                  OBD_MD_FLFLAGS | OBD_MD_FLGROUP;
1436         data.ioc_command = cmd;
1437
1438         gettimeofday(&start, NULL);
1439         while (shmem_running()) {
1440                 struct lu_fid fid = { 0 };
1441
1442                 if (child_base_id != -1)
1443                         data.ioc_obdo2.o_oi.oi.oi_id = child_base_id;
1444                 data.ioc_obdo2.o_mode = mode | create_mode;
1445                 data.ioc_obdo2.o_valid = OBD_MD_FLID | OBD_MD_FLTYPE |
1446                                          OBD_MD_FLMODE | OBD_MD_FLFLAGS |
1447                                          OBD_MD_FLGROUP;
1448                 data.ioc_obdo2.o_misc = stripe_count;
1449                 data.ioc_obdo2.o_stripe_idx = stripe_index;
1450
1451                 if (total_count > 0) {
1452                         if ((total_count - count) > MD_STEP_COUNT)
1453                                 data.ioc_count = MD_STEP_COUNT;
1454                         else
1455                                 data.ioc_count = total_count - count;
1456                 } else {
1457                         data.ioc_count = MD_STEP_COUNT;
1458                 }
1459
1460                 if (cmd == ECHO_MD_CREATE || cmd == ECHO_MD_MKDIR) {
1461                         /*Allocate fids for the create */
1462                         rc = jt_obd_alloc_fids(&fid_space, &fid,
1463                                                &data.ioc_count);
1464                         if (rc) {
1465                                 fprintf(stderr, "Allocate fids error %d.\n",
1466                                         rc);
1467                                 return rc;
1468                         }
1469                         data.ioc_obdo1.o_oi.oi_fid = fid;
1470                 }
1471
1472                 child_base_id += data.ioc_count;
1473                 count += data.ioc_count;
1474
1475                 memset(buf, 0, sizeof(rawbuf));
1476                 rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
1477                 if (rc) {
1478                         fprintf(stderr, "error: %s: invalid ioctl %d\n",
1479                                 jt_cmdname(argv[0]), rc);
1480                         return rc;
1481                 }
1482
1483                 rc = l_ioctl(OBD_DEV_ID, OBD_IOC_ECHO_MD, buf);
1484                 if (rc) {
1485                         fprintf(stderr, "error: %s: %s\n",
1486                                 jt_cmdname(argv[0]), strerror(rc = errno));
1487                         return rc;
1488                 }
1489                 shmem_bump(data.ioc_count);
1490
1491                 gettimeofday(&end_time, NULL);
1492                 diff = difftime(&end_time, &start);
1493                 if (seconds > 0 && (__u64)diff > seconds)
1494                         break;
1495
1496                 if (count >= total_count && total_count > 0)
1497                         break;
1498         }
1499
1500         if (count > 0 && version) {
1501                 gettimeofday(&end_time, NULL);
1502                 diff = difftime(&end_time, &start);
1503                 printf("%s: %d in %.3fs (%.3f /s): %s",
1504                        jt_cmdname(argv[0]), count, diff,
1505                        (double)count / diff, ctime(&end_time.tv_sec));
1506         }
1507
1508 #ifdef MAX_THREADS
1509         if (thread) {
1510                 shmem_lock();
1511                 shmem_end_time_locked();
1512                 shmem_unlock();
1513         }
1514 #endif
1515         return rc;
1516 }
1517
1518 int jt_obd_test_create(int argc, char **argv)
1519 {
1520         return jt_obd_md_common(argc, argv, ECHO_MD_CREATE);
1521 }
1522
1523 int jt_obd_test_mkdir(int argc, char **argv)
1524 {
1525         return jt_obd_md_common(argc, argv, ECHO_MD_MKDIR);
1526 }
1527
1528 int jt_obd_test_destroy(int argc, char **argv)
1529 {
1530         return jt_obd_md_common(argc, argv, ECHO_MD_DESTROY);
1531 }
1532
1533 int jt_obd_test_rmdir(int argc, char **argv)
1534 {
1535         return jt_obd_md_common(argc, argv, ECHO_MD_RMDIR);
1536 }
1537
1538 int jt_obd_test_lookup(int argc, char **argv)
1539 {
1540         return jt_obd_md_common(argc, argv, ECHO_MD_LOOKUP);
1541 }
1542
1543 int jt_obd_test_setxattr(int argc, char **argv)
1544 {
1545         return jt_obd_md_common(argc, argv, ECHO_MD_SETATTR);
1546 }
1547
1548 int jt_obd_test_md_getattr(int argc, char **argv)
1549 {
1550         return jt_obd_md_common(argc, argv, ECHO_MD_GETATTR);
1551 }
1552
1553 int jt_obd_create(int argc, char **argv)
1554 {
1555         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
1556         struct obd_ioctl_data data;
1557         struct timeval next_time;
1558         __u64 count = 1, next_count, base_id = 1;
1559         int verbose = 1, mode = 0100644, rc = 0, i;
1560         char *end;
1561
1562         memset(&data, 0, sizeof(data));
1563         data.ioc_dev = cur_device;
1564         if (argc < 2 || argc > 4)
1565                 return CMD_HELP;
1566
1567         count = strtoull(argv[1], &end, 0);
1568         if (*end) {
1569                 fprintf(stderr, "error: %s: invalid iteration count '%s'\n",
1570                         jt_cmdname(argv[0]), argv[1]);
1571                 return CMD_HELP;
1572         }
1573
1574         if (argc > 2) {
1575                 mode = strtoul(argv[2], &end, 0);
1576                 if (*end) {
1577                         fprintf(stderr, "error: %s: invalid mode '%s'\n",
1578                                 jt_cmdname(argv[0]), argv[2]);
1579                         return CMD_HELP;
1580                 }
1581                 if (!(mode & S_IFMT))
1582                         mode |= S_IFREG;
1583         }
1584
1585         if (argc > 3) {
1586                 verbose = get_verbose(argv[0], argv[3]);
1587                 if (verbose == BAD_VERBOSE)
1588                         return CMD_HELP;
1589         }
1590
1591         printf("%s: %jd objects\n", jt_cmdname(argv[0]), (uintmax_t)count);
1592         gettimeofday(&next_time, NULL);
1593         next_time.tv_sec -= verbose;
1594
1595         ostid_set_seq_echo(&data.ioc_obdo1.o_oi);
1596         for (i = 1, next_count = verbose; i <= count && shmem_running(); i++) {
1597                 /*
1598                  * base_id is 1 so we don't need to worry about it being
1599                  * greater than OBIF_MAX_OID
1600                  */
1601                 data.ioc_obdo1.o_oi.oi_fid.f_oid = base_id;
1602                 data.ioc_obdo1.o_mode = mode;
1603                 data.ioc_obdo1.o_uid = 0;
1604                 data.ioc_obdo1.o_gid = 0;
1605                 data.ioc_obdo1.o_projid = 0;
1606                 data.ioc_obdo1.o_valid = OBD_MD_FLTYPE | OBD_MD_FLMODE |
1607                                          OBD_MD_FLID | OBD_MD_FLUID |
1608                                          OBD_MD_FLGID | OBD_MD_FLGROUP |
1609                                          OBD_MD_FLPROJID;
1610
1611                 memset(buf, 0, sizeof(rawbuf));
1612                 rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
1613                 if (rc) {
1614                         fprintf(stderr, "error: %s: invalid ioctl\n",
1615                                 jt_cmdname(argv[0]));
1616                         return rc;
1617                 }
1618                 rc = l_ioctl(OBD_DEV_ID, OBD_IOC_CREATE, buf);
1619                 llapi_ioctl_unpack(&data, buf, sizeof(rawbuf));
1620                 shmem_bump(1);
1621                 if (rc < 0) {
1622                         fprintf(stderr, "error: %s: #%d - %s\n",
1623                                 jt_cmdname(argv[0]), i, strerror(rc = errno));
1624                         break;
1625                 }
1626                 if (!(data.ioc_obdo1.o_valid & OBD_MD_FLID)) {
1627                         fprintf(stderr, "error: %s: oid not valid #%d:%#jx\n",
1628                                 jt_cmdname(argv[0]), i,
1629                                 (uintmax_t)data.ioc_obdo1.o_valid);
1630                         rc = EINVAL;
1631                         break;
1632                 }
1633
1634                 if (be_verbose(verbose, &next_time, i, &next_count, count))
1635                         printf("%s: #%d is object id %#jx\n",
1636                                jt_cmdname(argv[0]), i,
1637                                (uintmax_t)ostid_id(&data.ioc_obdo1.o_oi));
1638         }
1639
1640         return rc;
1641 }
1642
1643 int jt_obd_setattr(int argc, char **argv)
1644 {
1645         struct obd_ioctl_data data;
1646         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
1647         __u64 objid;
1648         char *end;
1649         int mode;
1650         int rc;
1651
1652         memset(&data, 0, sizeof(data));
1653         data.ioc_dev = cur_device;
1654         if (argc != 2)
1655                 return CMD_HELP;
1656
1657         objid = strtoull(argv[1], &end, 0);
1658         if (*end) {
1659                 fprintf(stderr, "error: %s: objid '%s' is not a number\n",
1660                         jt_cmdname(argv[0]), argv[1]);
1661                 return CMD_HELP;
1662         }
1663
1664         if (objid >= OBIF_MAX_OID) {
1665                 fprintf(stderr, "error: %s: invalid objid '%s'\n",
1666                         jt_cmdname(argv[0]), argv[1]);
1667                 return CMD_HELP;
1668         }
1669
1670         mode = strtoul(argv[2], &end, 0);
1671         if (*end) {
1672                 fprintf(stderr, "error: %s: invalid mode '%s'\n",
1673                         jt_cmdname(argv[0]), argv[2]);
1674                 return CMD_HELP;
1675         }
1676
1677         ostid_set_seq_echo(&data.ioc_obdo1.o_oi);
1678         data.ioc_obdo1.o_mode = S_IFREG | mode;
1679         data.ioc_obdo1.o_oi.oi_fid.f_oid = objid;
1680         data.ioc_obdo1.o_valid = OBD_MD_FLID | OBD_MD_FLTYPE | OBD_MD_FLMODE;
1681
1682         memset(buf, 0, sizeof(rawbuf));
1683         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
1684         if (rc) {
1685                 fprintf(stderr, "error: %s: invalid ioctl\n",
1686                         jt_cmdname(argv[0]));
1687                 return rc;
1688         }
1689         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_SETATTR, buf);
1690         if (rc < 0)
1691                 fprintf(stderr, "error: %s: %s\n", jt_cmdname(argv[0]),
1692                         strerror(rc = errno));
1693
1694         return rc;
1695 }
1696
1697 int jt_obd_test_setattr(int argc, char **argv)
1698 {
1699         struct obd_ioctl_data data;
1700         struct timeval start, next_time;
1701         __u64 i, count, next_count;
1702         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
1703         int verbose = 1;
1704         __u64 objid = 3;
1705         char *end;
1706         int rc = 0;
1707
1708         if (argc < 2 || argc > 4)
1709                 return CMD_HELP;
1710
1711         memset(&data, 0, sizeof(data));
1712         data.ioc_dev = cur_device;
1713         count = strtoull(argv[1], &end, 0);
1714         if (*end) {
1715                 fprintf(stderr, "error: %s: invalid iteration count '%s'\n",
1716                         jt_cmdname(argv[0]), argv[1]);
1717                 return CMD_HELP;
1718         }
1719
1720         if (argc >= 3) {
1721                 verbose = get_verbose(argv[0], argv[2]);
1722                 if (verbose == BAD_VERBOSE)
1723                         return CMD_HELP;
1724         }
1725
1726         if (argc >= 4) {
1727                 if (argv[3][0] == 't') {
1728                         objid = strtoull(argv[3] + 1, &end, 0);
1729                         if (thread)
1730                                 objid += thread - 1;
1731                 } else {
1732                         objid = strtoull(argv[3], &end, 0);
1733                 }
1734                 if (*end) {
1735                         fprintf(stderr, "error: %s: invalid objid '%s'\n",
1736                                 jt_cmdname(argv[0]), argv[3]);
1737                         return CMD_HELP;
1738                 }
1739         }
1740
1741         gettimeofday(&start, NULL);
1742         next_time.tv_sec = start.tv_sec - verbose;
1743         next_time.tv_usec = start.tv_usec;
1744         if (verbose != 0)
1745                 printf("%s: setting %jd attrs (objid %#jx): %s",
1746                        jt_cmdname(argv[0]), (uintmax_t)count,
1747                        (uintmax_t)objid, ctime(&start.tv_sec));
1748
1749         ostid_set_seq_echo(&data.ioc_obdo1.o_oi);
1750         for (i = 1, next_count = verbose; i <= count && shmem_running(); i++) {
1751                 if (objid >= OBIF_MAX_OID) {
1752                         fprintf(stderr, "errr: %s: invalid objid '%llu'\n",
1753                                 jt_cmdname(argv[0]), (unsigned long long)objid);
1754                         return -E2BIG;
1755                 }
1756
1757                 data.ioc_obdo1.o_oi.oi_fid.f_oid = objid;
1758                 data.ioc_obdo1.o_mode = S_IFREG;
1759                 data.ioc_obdo1.o_valid = OBD_MD_FLID | OBD_MD_FLTYPE |
1760                                          OBD_MD_FLMODE;
1761                 memset(buf, 0, sizeof(rawbuf));
1762                 rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
1763                 if (rc) {
1764                         fprintf(stderr, "error: %s: invalid ioctl\n",
1765                                 jt_cmdname(argv[0]));
1766                         return rc;
1767                 }
1768                 rc = l_ioctl(OBD_DEV_ID, OBD_IOC_SETATTR, &data);
1769                 shmem_bump(1);
1770                 if (rc < 0) {
1771                         fprintf(stderr, "error: %s: #%jd - %d:%s\n",
1772                                 jt_cmdname(argv[0]), (uintmax_t)i,
1773                                 errno, strerror(rc = errno));
1774                         break;
1775                 }
1776                 if (be_verbose(verbose, &next_time, i, &next_count, count))
1777                         printf("%s: set attr #%jd\n",
1778                                jt_cmdname(argv[0]), (uintmax_t)i);
1779         }
1780
1781         if (!rc) {
1782                 struct timeval end;
1783                 double diff;
1784
1785                 gettimeofday(&end, NULL);
1786
1787                 diff = difftime(&end, &start);
1788
1789                 --i;
1790                 if (verbose != 0)
1791                         printf("%s: %jd attrs in %.3fs (%.3f attr/s): %s",
1792                                jt_cmdname(argv[0]), (uintmax_t)i, diff,
1793                                i / diff, ctime(&end.tv_sec));
1794         }
1795         return rc;
1796 }
1797
1798 int jt_obd_destroy(int argc, char **argv)
1799 {
1800         struct obd_ioctl_data data;
1801         struct timeval next_time;
1802         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
1803         __u64 count = 1, next_count;
1804         int verbose = 1;
1805         __u64 id;
1806         char *end;
1807         int rc = 0, i;
1808
1809         memset(&data, 0, sizeof(data));
1810         data.ioc_dev = cur_device;
1811         if (argc < 2 || argc > 4)
1812                 return CMD_HELP;
1813
1814         errno = 0;
1815         id = strtoull(argv[1], &end, 0);
1816         if (*end || id == 0 || errno != 0) {
1817                 fprintf(stderr, "error: %s: invalid objid '%s'\n",
1818                         jt_cmdname(argv[0]), argv[1]);
1819                 return CMD_HELP;
1820         }
1821         if (argc > 2) {
1822                 count = strtoull(argv[2], &end, 0);
1823                 if (*end) {
1824                         fprintf(stderr,
1825                                 "error: %s: invalid iteration count '%s'\n",
1826                                 jt_cmdname(argv[0]), argv[2]);
1827                         return CMD_HELP;
1828                 }
1829         }
1830
1831         if (argc > 3) {
1832                 verbose = get_verbose(argv[0], argv[3]);
1833                 if (verbose == BAD_VERBOSE)
1834                         return CMD_HELP;
1835         }
1836
1837         printf("%s: %jd objects\n", jt_cmdname(argv[0]), (uintmax_t)count);
1838         gettimeofday(&next_time, NULL);
1839         next_time.tv_sec -= verbose;
1840
1841         ostid_set_seq_echo(&data.ioc_obdo1.o_oi);
1842         for (i = 1, next_count = verbose; i <= count && shmem_running();
1843              i++, id++) {
1844                 if (id >= OBIF_MAX_OID) {
1845                         fprintf(stderr, "errr: %s: invalid objid '%llu'\n",
1846                                 jt_cmdname(argv[0]), (unsigned long long)id);
1847                         return -E2BIG;
1848                 }
1849
1850                 data.ioc_obdo1.o_oi.oi_fid.f_oid = id;
1851                 data.ioc_obdo1.o_mode = S_IFREG | 0644;
1852                 data.ioc_obdo1.o_valid = OBD_MD_FLID | OBD_MD_FLMODE;
1853
1854                 memset(buf, 0, sizeof(rawbuf));
1855                 rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
1856                 if (rc) {
1857                         fprintf(stderr, "error: %s: invalid ioctl\n",
1858                                 jt_cmdname(argv[0]));
1859                         return rc;
1860                 }
1861                 rc = l_ioctl(OBD_DEV_ID, OBD_IOC_DESTROY, buf);
1862                 llapi_ioctl_unpack(&data, buf, sizeof(rawbuf));
1863                 shmem_bump(1);
1864                 if (rc < 0) {
1865                         fprintf(stderr, "error: %s: objid %#jx: %s\n",
1866                                 jt_cmdname(argv[0]), (uintmax_t)id,
1867                                 strerror(rc = errno));
1868                         break;
1869                 }
1870
1871                 if (be_verbose(verbose, &next_time, i, &next_count, count))
1872                         printf("%s: #%d is object id %#jx\n",
1873                                jt_cmdname(argv[0]), i, (uintmax_t)id);
1874         }
1875
1876         return rc;
1877 }
1878
1879 static int jt_str_to_ost_id(const char *str, struct ost_id *oi)
1880 {
1881         __u64 oid;
1882         char *end;
1883
1884         oid = strtoull(str, &end, 0);
1885         if (*end == '\0') {
1886                 /* If str is a single number then assume old echo
1887                  * client usage. */
1888                 if (oid >= OBIF_MAX_OID)
1889                         return -EINVAL;
1890
1891                 ostid_set_seq_echo(oi);
1892                 oi->oi_fid.f_oid = oid;
1893                 return 0;
1894         }
1895
1896         return llapi_fid_parse(str, &oi->oi_fid, NULL);
1897 }
1898
1899 int jt_obd_getattr(int argc, char **argv)
1900 {
1901         struct obd_ioctl_data data;
1902         struct obdo *oa;
1903         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
1904         int rc;
1905
1906         if (argc != 2)
1907                 return CMD_HELP;
1908
1909         memset(&data, 0, sizeof(data));
1910         data.ioc_dev = cur_device;
1911         oa = &data.ioc_obdo1;
1912
1913         rc = jt_str_to_ost_id(argv[1], &oa->o_oi);
1914         if (rc < 0) {
1915                 fprintf(stderr, "error: %s: invalid objid of FID '%s'\n",
1916                         jt_cmdname(argv[0]), argv[1]);
1917                 return CMD_HELP;
1918         }
1919
1920         oa->o_valid = OBD_MD_FLID | OBD_MD_FLGROUP;
1921
1922         memset(buf, 0, sizeof(rawbuf));
1923         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
1924         if (rc) {
1925                 fprintf(stderr, "error: %s: invalid ioctl\n",
1926                         jt_cmdname(argv[0]));
1927                 return rc;
1928         }
1929         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_GETATTR, buf);
1930         llapi_ioctl_unpack(&data, buf, sizeof(rawbuf));
1931         if (rc) {
1932                 fprintf(stderr, "error: %s: %s\n", jt_cmdname(argv[0]),
1933                         strerror(rc = errno));
1934                 return rc;
1935         }
1936
1937 #define OP4(bits, name, format, value)                                  \
1938         do {                                                            \
1939                 if ((oa->o_valid & (bits)) == (bits))                   \
1940                         printf("%s: "format"\n", (name), value);        \
1941         } while (0)
1942
1943 #define OPM(bits, member, format)                                       \
1944         OP4(bits, #member, format, (uintmax_t)(oa->o_ ## member))
1945
1946 #define OPO(bits, member) OPM(bits, member, "%#jo")
1947 #define OPU(bits, member) OPM(bits, member, "%ju")
1948 #define OPX(bits, member) OPM(bits, member, "%#jx")
1949
1950         OPX(0, valid);
1951         OPX(OBD_MD_FLID | OBD_MD_FLGROUP, oi.oi.oi_id);
1952         OPX(OBD_MD_FLID | OBD_MD_FLGROUP, oi.oi.oi_seq);
1953         OP4(OBD_MD_FLID | OBD_MD_FLGROUP, "oi.oi_fid", DFID, PFID(&oa->o_oi.oi_fid));
1954         OPU(OBD_MD_FLATIME, atime);
1955         OPU(OBD_MD_FLMTIME, mtime);
1956         OPU(OBD_MD_FLCTIME, ctime);
1957         OPU(OBD_MD_FLSIZE, size);
1958         OPU(OBD_MD_FLBLOCKS, blocks);
1959         OPU(OBD_MD_FLBLKSZ, blksize);
1960         OPO(OBD_MD_FLMODE | OBD_MD_FLTYPE, mode);
1961         OPU(OBD_MD_FLUID, uid);
1962         OPU(OBD_MD_FLGID, gid);
1963         OPU(OBD_MD_FLFLAGS, flags);
1964         OPU(OBD_MD_FLNLINK, nlink);
1965         OPX(OBD_MD_FLPARENT | OBD_MD_FLFID, parent_seq);
1966         OPX(OBD_MD_FLPARENT | OBD_MD_FLFID, parent_oid);
1967         OPX(OBD_MD_FLPARENT | OBD_MD_FLFID, parent_ver);
1968         OPU(OBD_MD_LAYOUT_VERSION, layout_version);
1969         OPU(OBD_MD_FLGRANT, grant);
1970         OPU(OBD_MD_FLPROJID, projid);
1971         OPU(OBD_MD_FLDATAVERSION, data_version);
1972 #undef OP4
1973 #undef OPM
1974 #undef OPO
1975 #undef OPU
1976 #undef OPX
1977
1978         return 0;
1979 }
1980
1981 int jt_obd_test_getattr(int argc, char **argv)
1982 {
1983         struct obd_ioctl_data data;
1984         struct timeval start, next_time;
1985         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
1986         __u64 i, count, next_count;
1987         int verbose = 1;
1988         __u64 objid = 3;
1989         char *end;
1990         int rc = 0;
1991
1992         if (argc < 2 || argc > 4)
1993                 return CMD_HELP;
1994
1995         memset(&data, 0, sizeof(data));
1996         data.ioc_dev = cur_device;
1997         count = strtoull(argv[1], &end, 0);
1998         if (*end) {
1999                 fprintf(stderr, "error: %s: invalid iteration count '%s'\n",
2000                         jt_cmdname(argv[0]), argv[1]);
2001                 return CMD_HELP;
2002         }
2003
2004         if (argc >= 3) {
2005                 verbose = get_verbose(argv[0], argv[2]);
2006                 if (verbose == BAD_VERBOSE)
2007                         return CMD_HELP;
2008         }
2009
2010         if (argc >= 4) {
2011                 if (argv[3][0] == 't') {
2012                         objid = strtoull(argv[3] + 1, &end, 0);
2013                         if (thread)
2014                                 objid += thread - 1;
2015                 } else {
2016                         objid = strtoull(argv[3], &end, 0);
2017                 }
2018                 if (*end) {
2019                         fprintf(stderr, "error: %s: invalid objid '%s'\n",
2020                                 jt_cmdname(argv[0]), argv[3]);
2021                         return CMD_HELP;
2022                 }
2023         }
2024
2025         gettimeofday(&start, NULL);
2026         next_time.tv_sec = start.tv_sec - verbose;
2027         next_time.tv_usec = start.tv_usec;
2028         if (verbose != 0)
2029                 printf("%s: getting %jd attrs (objid %#jx): %s",
2030                        jt_cmdname(argv[0]), (uintmax_t)count,
2031                        (uintmax_t)objid, ctime(&start.tv_sec));
2032
2033         ostid_set_seq_echo(&data.ioc_obdo1.o_oi);
2034         for (i = 1, next_count = verbose; i <= count && shmem_running(); i++) {
2035                 if (objid >= OBIF_MAX_OID) {
2036                         fprintf(stderr, "errr: %s: invalid objid '%llu'\n",
2037                                 jt_cmdname(argv[0]), (unsigned long long)objid);
2038                         return -E2BIG;
2039                 }
2040
2041                 data.ioc_obdo1.o_oi.oi_fid.f_oid = objid;
2042                 data.ioc_obdo1.o_mode = S_IFREG;
2043                 data.ioc_obdo1.o_valid = 0xffffffff;
2044                 memset(buf, 0, sizeof(rawbuf));
2045                 rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
2046                 if (rc) {
2047                         fprintf(stderr, "error: %s: invalid ioctl\n",
2048                                 jt_cmdname(argv[0]));
2049                         return rc;
2050                 }
2051                 rc = l_ioctl(OBD_DEV_ID, OBD_IOC_GETATTR, &data);
2052                 shmem_bump(1);
2053                 if (rc < 0) {
2054                         fprintf(stderr, "error: %s: #%jd - %d:%s\n",
2055                                 jt_cmdname(argv[0]), (uintmax_t)i,
2056                                 errno, strerror(rc = errno));
2057                         break;
2058                 }
2059                 if (be_verbose(verbose, &next_time, i, &next_count, count))
2060                         printf("%s: got attr #%jd\n",
2061                                jt_cmdname(argv[0]), (uintmax_t)i);
2062         }
2063
2064         if (!rc) {
2065                 struct timeval end;
2066                 double diff;
2067
2068                 gettimeofday(&end, NULL);
2069
2070                 diff = difftime(&end, &start);
2071
2072                 --i;
2073                 if (verbose != 0)
2074                         printf("%s: %jd attrs in %.3fs (%.3f attr/s): %s",
2075                                jt_cmdname(argv[0]), (uintmax_t)i, diff,
2076                                i / diff, ctime(&end.tv_sec));
2077         }
2078
2079         return rc;
2080 }
2081
2082 /*
2083  * test_brw <cnt>                                               count
2084  *      <r|w[r(repeat)x(noverify)]>                             mode
2085  *      <q|v|#(print interval)>                                 verbosity
2086  *      <npages[+offset]>                                       blocksize
2087  *      <[[<interleave_threads>]t(inc obj by thread#)]obj>      object
2088  *      [p|g<args>]                                             batch
2089  */
2090 int jt_obd_test_brw(int argc, char **argv)
2091 {
2092         struct obd_ioctl_data data;
2093         struct timeval start, next_time;
2094         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
2095         __u64 count, next_count, len, stride, thr_offset = 0, objid = 3;
2096         int write = 0, verbose = 1, cmd, i, rc = 0, pages = 1;
2097         int offset_pages = 0;
2098         long n;
2099         int repeat_offset = 0;
2100         unsigned long long ull;
2101         int  nthr_per_obj = 0;
2102         int  verify = 1;
2103         int  obj_idx = 0;
2104         char *end;
2105
2106         if (argc < 2 || argc > 7) {
2107                 fprintf(stderr, "error: %s: bad number of arguments: %d\n",
2108                         jt_cmdname(argv[0]), argc);
2109                 return CMD_HELP;
2110         }
2111
2112         count = strtoull(argv[1], &end, 0);
2113         if (*end) {
2114                 fprintf(stderr, "error: %s: bad iteration count '%s'\n",
2115                         jt_cmdname(argv[0]), argv[1]);
2116                 return CMD_HELP;
2117         }
2118
2119         if (argc >= 3) {
2120                 if (argv[2][0] == 'w' || argv[2][0] == '1')
2121                         write = 1;
2122                 /* else it's a read */
2123
2124                 if (argv[2][0] != 0)
2125                         for (i = 1; argv[2][i] != 0; i++)
2126                                 switch (argv[2][i]) {
2127                                 case 'r':
2128                                         repeat_offset = 1;
2129                                         break;
2130
2131                                 case 'x':
2132                                         verify = 0;
2133                                         break;
2134
2135                                 default:
2136                                         fprintf(stderr,
2137                                                 "Can't parse cmd '%s'\n",
2138                                                 argv[2]);
2139                                         return CMD_HELP;
2140                                 }
2141         }
2142
2143         if (argc >= 4) {
2144                 verbose = get_verbose(argv[0], argv[3]);
2145                 if (verbose == BAD_VERBOSE)
2146                         return CMD_HELP;
2147         }
2148
2149         if (argc >= 5) {
2150                 pages = strtoul(argv[4], &end, 0);
2151
2152                 if (*end == '+')
2153                         offset_pages = strtoul(end + 1, &end, 0);
2154
2155                 if (*end != 0 || offset_pages < 0 || offset_pages >= pages) {
2156                         fprintf(stderr, "error: %s: bad npages[+offset] parameter '%s'\n",
2157                                 jt_cmdname(argv[0]), argv[4]);
2158                         return CMD_HELP;
2159                 }
2160         }
2161
2162         if (argc >= 6) {
2163                 if (thread && (n = strtol(argv[5], &end, 0)) > 0 &&
2164                     *end == 't' && (ull = strtoull(end + 1, &end, 0)) > 0 &&
2165                     *end == 0) {
2166                         nthr_per_obj = n;
2167                         objid = ull;
2168                 } else if (thread && argv[5][0] == 't') {
2169                         nthr_per_obj = 1;
2170                         objid = strtoull(argv[5] + 1, &end, 0);
2171                 } else {
2172                         nthr_per_obj = 0;
2173                         objid = strtoull(argv[5], &end, 0);
2174                 }
2175                 if (*end) {
2176                         fprintf(stderr, "error: %s: bad objid '%s'\n",
2177                                 jt_cmdname(argv[0]), argv[5]);
2178                         return CMD_HELP;
2179                 }
2180         }
2181
2182         memset(&data, 0, sizeof(data));
2183         data.ioc_dev = cur_device;
2184
2185         /*
2186          * communicate the 'type' of brw test and batching to echo_client.
2187          * don't start.  we'd love to refactor this lctl->echo_client
2188          * interface
2189          */
2190         data.ioc_pbuf1 = (void *)1;
2191         data.ioc_plen1 = 1;
2192
2193         if (argc >= 7) {
2194                 switch (argv[6][0]) {
2195                 case 'g': /* plug and unplug */
2196                         data.ioc_pbuf1 = (void *)2;
2197                         data.ioc_plen1 = strtoull(argv[6] + 1, &end, 0);
2198                         break;
2199                 case 'p': /* prep and commit */
2200                         data.ioc_pbuf1 = (void *)3;
2201                         data.ioc_plen1 = strtoull(argv[6] + 1, &end, 0);
2202                         break;
2203                 default:
2204                         fprintf(stderr,
2205                                 "error: %s: batching '%s' needs to specify 'p' or 'g'\n",
2206                                 jt_cmdname(argv[0]), argv[6]);
2207                         return CMD_HELP;
2208                 }
2209
2210                 if (*end) {
2211                         fprintf(stderr, "error: %s: bad batching '%s'\n",
2212                                 jt_cmdname(argv[0]), argv[6]);
2213                         return CMD_HELP;
2214                 }
2215                 data.ioc_plen1 *= getpagesize();
2216         }
2217
2218         len = pages * getpagesize();
2219         thr_offset = offset_pages * getpagesize();
2220         stride = len;
2221
2222 #ifdef MAX_THREADS
2223         if (thread) {
2224                 shmem_lock();
2225                 if (nthr_per_obj != 0) {
2226                         /* threads interleave */
2227                         obj_idx = (thread - 1) / nthr_per_obj;
2228                         objid += obj_idx;
2229                         stride *= nthr_per_obj;
2230                         if ((thread - 1) % nthr_per_obj == 0) {
2231                                 shared_data->body.offsets[obj_idx] =
2232                                         stride + thr_offset;
2233                         }
2234                         thr_offset += ((thread - 1) % nthr_per_obj) * len;
2235                 } else {
2236                         /* threads disjoint */
2237                         thr_offset += (thread - 1) * len;
2238                 }
2239
2240                 shmem_start_time_locked();
2241                 shmem_unlock();
2242         }
2243 #endif
2244
2245         ostid_set_seq_echo(&data.ioc_obdo1.o_oi);
2246         if (objid >= OBIF_MAX_OID) {
2247                 fprintf(stderr, "errr: %s: invalid objid '%llu'\n",
2248                         jt_cmdname(argv[0]), (unsigned long long)objid);
2249                 return -E2BIG;
2250         }
2251
2252         data.ioc_obdo1.o_oi.oi_fid.f_oid = objid;
2253         data.ioc_obdo1.o_mode = S_IFREG;
2254         data.ioc_obdo1.o_valid = OBD_MD_FLID | OBD_MD_FLTYPE | OBD_MD_FLMODE |
2255                                  OBD_MD_FLFLAGS | OBD_MD_FLGROUP;
2256         data.ioc_obdo1.o_flags = (verify ? OBD_FL_DEBUG_CHECK : 0);
2257         data.ioc_count = len;
2258         data.ioc_offset = (repeat_offset ? 0 : thr_offset);
2259
2260         gettimeofday(&start, NULL);
2261         next_time.tv_sec = start.tv_sec - verbose;
2262         next_time.tv_usec = start.tv_usec;
2263
2264         if (verbose != 0)
2265                 printf("%s: %s %jux%d pages (obj %#jx, off %ju): %s",
2266                        jt_cmdname(argv[0]), write ? "writing" : "reading",
2267                        (uintmax_t)count, pages, (uintmax_t)objid,
2268                        (uintmax_t)data.ioc_offset, ctime(&start.tv_sec));
2269
2270         cmd = write ? OBD_IOC_BRW_WRITE : OBD_IOC_BRW_READ;
2271         for (i = 1, next_count = verbose; i <= count && shmem_running(); i++) {
2272                 data.ioc_obdo1.o_valid &= ~(OBD_MD_FLBLOCKS | OBD_MD_FLGRANT);
2273                 memset(buf, 0, sizeof(rawbuf));
2274                 rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
2275                 if (rc) {
2276                         fprintf(stderr, "error: %s: invalid ioctl\n",
2277                                 jt_cmdname(argv[0]));
2278                         return rc;
2279                 }
2280                 rc = l_ioctl(OBD_DEV_ID, cmd, buf);
2281                 shmem_bump(1);
2282                 if (rc) {
2283                         fprintf(stderr, "error: %s: #%d - %s on %s\n",
2284                                 jt_cmdname(argv[0]), i, strerror(rc = errno),
2285                                 write ? "write" : "read");
2286                         break;
2287                 } else if (be_verbose(verbose, &next_time, i,
2288                                       &next_count, count)) {
2289                         shmem_lock();
2290                         printf("%s: %s number %d @ %jd:%ju for %d\n",
2291                                jt_cmdname(argv[0]), write ? "write" : "read", i,
2292                                (uintmax_t)ostid_id(&data.ioc_obdo1.o_oi),
2293                                (uintmax_t)data.ioc_offset,
2294                                (int)(pages * getpagesize()));
2295                         shmem_unlock();
2296                 }
2297
2298                 if (!repeat_offset) {
2299 #ifdef MAX_THREADS
2300                         if (stride == len) {
2301                                 data.ioc_offset += stride;
2302                         } else if (i < count) {
2303                                 shmem_lock();
2304                                 data.ioc_offset =
2305                                         shared_data->body.offsets[obj_idx];
2306                                 shared_data->body.offsets[obj_idx] += len;
2307                                 shmem_unlock();
2308                         }
2309 #else
2310                         data.ioc_offset += len;
2311                         obj_idx = 0; /* avoids an unused var warning */
2312 #endif
2313                 }
2314         }
2315
2316         if (!rc) {
2317                 struct timeval end;
2318                 double diff;
2319
2320                 gettimeofday(&end, NULL);
2321
2322                 diff = difftime(&end, &start);
2323
2324                 --i;
2325                 if (verbose != 0)
2326                         printf("%s: %s %dx%d pages in %.3fs (%.3f MB/s): %s",
2327                                jt_cmdname(argv[0]), write ? "wrote" : "read",
2328                                i, pages, diff,
2329                                ((double)i * pages * getpagesize()) /
2330                                (diff * 1048576.0), ctime(&end.tv_sec));
2331         }
2332
2333 #ifdef MAX_THREADS
2334         if (thread) {
2335                 shmem_lock();
2336                 shmem_end_time_locked();
2337                 shmem_unlock();
2338         }
2339 #endif
2340         return rc;
2341 }
2342
2343 static int do_activate(int argc, char **argv, int flag)
2344 {
2345         struct obd_ioctl_data data;
2346         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
2347         int rc;
2348
2349         memset(&data, 0, sizeof(data));
2350         data.ioc_dev = cur_device;
2351         if (argc != 1)
2352                 return CMD_HELP;
2353
2354         /* reuse offset for 'active' */
2355         data.ioc_offset = flag;
2356
2357         memset(buf, 0, sizeof(rawbuf));
2358         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
2359         if (rc) {
2360                 fprintf(stderr, "error: %s: invalid ioctl\n",
2361                         jt_cmdname(argv[0]));
2362                 return rc;
2363         }
2364         rc = l_ioctl(OBD_DEV_ID, IOC_OSC_SET_ACTIVE, buf);
2365         if (rc)
2366                 fprintf(stderr, "error: %s: failed: %s\n",
2367                         jt_cmdname(argv[0]), strerror(rc = errno));
2368
2369         return rc;
2370 }
2371
2372 /**
2373  * Replace nids for given device.
2374  * lctl replace_nids <devicename> <nid1>[,nid2,nid3]
2375  * Command should be started on MGS server.
2376  * Only MGS server should be started (command execution
2377  * returns error in another cases). Command mount
2378  * -t lustre <MDT partition> -o nosvc <mount point>
2379  * can be used for that.
2380  *
2381  * llogs for MDTs and clients are processed. All
2382  * records copied as is except add_uuid and setup. This records
2383  * are skipped and recorded with new nids and uuid.
2384  *
2385  * \see mgs_replace_nids
2386  * \see mgs_replace_log
2387  * \see mgs_replace_nids_handler
2388  */
2389 int jt_replace_nids(int argc, char **argv)
2390 {
2391         int rc;
2392         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
2393         struct obd_ioctl_data data;
2394
2395         memset(&data, 0, sizeof(data));
2396         data.ioc_dev = get_mgs_device();
2397         if (argc != 3)
2398                 return CMD_HELP;
2399
2400         data.ioc_inllen1 = strlen(argv[1]) + 1;
2401         data.ioc_inlbuf1 = argv[1];
2402
2403         data.ioc_inllen2 = strlen(argv[2]) + 1;
2404         data.ioc_inlbuf2 = argv[2];
2405         memset(buf, 0, sizeof(rawbuf));
2406         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
2407         if (rc) {
2408                 fprintf(stderr, "error: %s: invalid ioctl\n",
2409                         jt_cmdname(argv[0]));
2410                 return rc;
2411         }
2412
2413         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_REPLACE_NIDS, buf);
2414         if (rc < 0) {
2415                 fprintf(stderr, "error: %s: %s\n", jt_cmdname(argv[0]),
2416                         strerror(rc = errno));
2417         }
2418
2419         return rc;
2420 }
2421
2422 int jt_obd_deactivate(int argc, char **argv)
2423 {
2424         return do_activate(argc, argv, 0);
2425 }
2426
2427 int jt_obd_activate(int argc, char **argv)
2428 {
2429         return do_activate(argc, argv, 1);
2430 }
2431
2432 int jt_obd_recover(int argc, char **argv)
2433 {
2434         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
2435         struct obd_ioctl_data data;
2436         int rc;
2437
2438         memset(&data, 0, sizeof(data));
2439         data.ioc_dev = cur_device;
2440         if (argc > 2)
2441                 return CMD_HELP;
2442
2443         if (argc == 2) {
2444                 data.ioc_inllen1 = strlen(argv[1]) + 1;
2445                 data.ioc_inlbuf1 = argv[1];
2446         }
2447
2448         memset(buf, 0, sizeof(rawbuf));
2449         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
2450         if (rc) {
2451                 fprintf(stderr, "error: %s: invalid ioctl\n",
2452                         jt_cmdname(argv[0]));
2453                 return rc;
2454         }
2455         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_CLIENT_RECOVER, buf);
2456         if (rc < 0) {
2457                 fprintf(stderr, "error: %s: %s\n", jt_cmdname(argv[0]),
2458                         strerror(rc = errno));
2459         }
2460
2461         return rc;
2462 }
2463
2464 int jt_obd_mdc_lookup(int argc, char **argv)
2465 {
2466         struct obd_ioctl_data data;
2467         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
2468         char *parent, *child;
2469         int rc, fd, verbose = 1;
2470
2471         if (argc < 3 || argc > 4)
2472                 return CMD_HELP;
2473
2474         parent = argv[1];
2475         child = argv[2];
2476         if (argc == 4)
2477                 verbose = get_verbose(argv[0], argv[3]);
2478
2479         memset(&data, 0, sizeof(data));
2480         data.ioc_dev = cur_device;
2481
2482         data.ioc_inllen1 = strlen(child) + 1;
2483         data.ioc_inlbuf1 = child;
2484
2485         memset(buf, 0, sizeof(rawbuf));
2486         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
2487         if (rc) {
2488                 fprintf(stderr, "error: %s: invalid ioctl\n",
2489                         jt_cmdname(argv[0]));
2490                 return rc;
2491         }
2492
2493         fd = open(parent, O_RDONLY);
2494         if (fd < 0) {
2495                 fprintf(stderr, "open \"%s\" failed: %s\n", parent,
2496                         strerror(errno));
2497                 return -1;
2498         }
2499
2500         rc = ioctl(fd, IOC_MDC_LOOKUP, buf);
2501         if (rc < 0) {
2502                 fprintf(stderr, "error: %s: ioctl error: %s\n",
2503                         jt_cmdname(argv[0]), strerror(rc = errno));
2504         }
2505         close(fd);
2506
2507         if (verbose) {
2508                 rc = llapi_ioctl_unpack(&data, buf, sizeof(rawbuf));
2509                 if (rc) {
2510                         fprintf(stderr, "error: %s: invalid reply\n",
2511                                 jt_cmdname(argv[0]));
2512                         return rc;
2513                 }
2514                 printf("%s: mode %o uid %d gid %d\n",
2515                        child, data.ioc_obdo1.o_mode, data.ioc_obdo1.o_uid,
2516                        data.ioc_obdo1.o_gid);
2517         }
2518
2519         return rc;
2520 }
2521
2522 #ifdef HAVE_SERVER_SUPPORT
2523 /**
2524  * Clear config logs for given device or filesystem.
2525  * lctl clear_conf <devicename|fsname>
2526  * Command has to be run on MGS node having MGS device mounted with -o
2527  * nosvc.
2528  *
2529  * Configuration logs for filesystem or one particular log is
2530  * processed. New log is created, original log is read, its records
2531  * marked SKIP do not get copied to new log. Others are copied as-is.
2532  * Original file is renamed to log.${time}.bak.
2533  *
2534  * \see mgs_clear_configs
2535  * \see mgs_replace_log
2536  * \see mgs_clear_config_handler
2537  **/
2538 int jt_lcfg_clear(int argc, char **argv)
2539 {
2540         int rc;
2541         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
2542         struct obd_ioctl_data data;
2543
2544         memset(&data, 0, sizeof(data));
2545         data.ioc_dev = get_mgs_device();
2546         if (argc != 2)
2547                 return CMD_HELP;
2548
2549         data.ioc_inllen1 = strlen(argv[1]) + 1;
2550         data.ioc_inlbuf1 = argv[1];
2551
2552         memset(buf, 0, sizeof(rawbuf));
2553         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
2554         if (rc) {
2555                 fprintf(stderr, "error: %s: invalid ioctl\n",
2556                         jt_cmdname(argv[0]));
2557                 return rc;
2558         }
2559
2560         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_CLEAR_CONFIGS, buf);
2561         if (rc < 0) {
2562                 fprintf(stderr, "error: %s: %s\n", jt_cmdname(argv[0]),
2563                         strerror(rc = errno));
2564         }
2565
2566         return rc;
2567 }
2568
2569 int jt_lcfg_fork(int argc, char **argv)
2570 {
2571         struct obd_ioctl_data data;
2572         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
2573         int rc;
2574
2575         if (argc != 3)
2576                 return CMD_HELP;
2577
2578         memset(&data, 0, sizeof(data));
2579         data.ioc_dev = get_mgs_device();
2580         data.ioc_inllen1 = strlen(argv[1]) + 1;
2581         data.ioc_inlbuf1 = argv[1];
2582         data.ioc_inllen2 = strlen(argv[2]) + 1;
2583         data.ioc_inlbuf2 = argv[2];
2584
2585         memset(buf, 0, sizeof(rawbuf));
2586         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
2587         if (rc) {
2588                 fprintf(stderr, "error: %s: invalid ioctl\n",
2589                         jt_cmdname(argv[0]));
2590                 return rc;
2591         }
2592
2593         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_LCFG_FORK, buf);
2594         if (rc < 0)
2595                 fprintf(stderr, "error: %s: OBD_IOC_LCFG_FORK failed: %s\n",
2596                         jt_cmdname(argv[0]), strerror(errno));
2597
2598         return rc;
2599 }
2600
2601 int jt_lcfg_erase(int argc, char **argv)
2602 {
2603         struct obd_ioctl_data data;
2604         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
2605         int rc;
2606
2607         if (argc == 3) {
2608                 if (strncmp(argv[2], "-q", strlen("-q")) != 0 &&
2609                     strncmp(argv[2], "--quiet", strlen("--quiet")) != 0)
2610                         return CMD_HELP;
2611         } else if (argc != 2) {
2612                 return CMD_HELP;
2613         }
2614
2615         memset(&data, 0, sizeof(data));
2616         data.ioc_dev = get_mgs_device();
2617         data.ioc_inllen1 = strlen(argv[1]) + 1;
2618         data.ioc_inlbuf1 = argv[1];
2619
2620         memset(buf, 0, sizeof(rawbuf));
2621         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
2622         if (rc) {
2623                 fprintf(stderr, "error: %s: invalid ioctl\n",
2624                         jt_cmdname(argv[0]));
2625                 return rc;
2626         }
2627
2628         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_LCFG_ERASE, buf);
2629         if (rc < 0)
2630                 fprintf(stderr, "error: %s: OBD_IOC_LCFG_ERASE failed: %s\n",
2631                         jt_cmdname(argv[0]), strerror(errno));
2632
2633         return rc;
2634 }
2635 #else /* !HAVE_SERVER_SUPPORT */
2636 int jt_lcfg_clear(int argc, char **argv)
2637 {
2638         if (argc != 2)
2639                 return CMD_HELP;
2640
2641         fprintf(stderr, "error: %s: invalid ioctl\n",
2642                 jt_cmdname(argv[0]));
2643         return -EOPNOTSUPP;
2644 }
2645
2646 int jt_lcfg_fork(int argc, char **argv)
2647 {
2648         if (argc != 3)
2649                 return CMD_HELP;
2650
2651         fprintf(stderr, "error: %s: invalid ioctl\n",
2652                 jt_cmdname(argv[0]));
2653         return -EOPNOTSUPP;
2654 }
2655
2656 int jt_lcfg_erase(int argc, char **argv)
2657 {
2658         if (argc != 3)
2659                 return CMD_HELP;
2660
2661         fprintf(stderr, "error: %s: invalid ioctl\n",
2662                 jt_cmdname(argv[0]));
2663         return -EOPNOTSUPP;
2664 }
2665 #endif /* HAVE_SERVER_SUPPORT */
2666
2667 enum llog_default_dev_op {
2668         LLOG_DFLT_MGS_SET = 0,
2669         LLOG_DFLT_DEV_RESET
2670 };
2671
2672 static int llog_default_device(enum llog_default_dev_op op)
2673 {
2674         int rc = 0;
2675         static int dflt_dev = -1;
2676
2677         if (op == LLOG_DFLT_MGS_SET && (cur_device == -1)) {
2678                 char mgs[] = "$MGS";
2679
2680                 rc = do_device("llog_default_device", mgs);
2681                 dflt_dev = cur_device;
2682
2683         } else if (op == LLOG_DFLT_DEV_RESET && (dflt_dev != -1)) {
2684                 do_disconnect(NULL, 1);
2685                 dflt_dev = -1;
2686         }
2687
2688         return rc;
2689 }
2690
2691 static int llog_catlist_next(int index, char *buf, size_t buflen)
2692 {
2693         struct obd_ioctl_data data;
2694         int rc;
2695
2696         memset(&data, 0, sizeof(data));
2697         data.ioc_dev = cur_device;
2698         data.ioc_inllen1 = buflen - __ALIGN_KERNEL(sizeof(data), 8);
2699         data.ioc_count = index;
2700         memset(buf, 0, buflen);
2701         rc = llapi_ioctl_pack(&data, &buf, buflen);
2702         if (rc < 0) {
2703                 fprintf(stderr, "error: invalid llapi_ioctl_pack: %s\n",
2704                         strerror(errno));
2705                 return rc;
2706         }
2707         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_CATLOGLIST, buf);
2708         if (rc < 0) {
2709                 fprintf(stderr, "OBD_IOC_CATLOGLIST failed: %s\n",
2710                         strerror(errno));
2711                 return rc;
2712         }
2713         return ((struct obd_ioctl_data *)buf)->ioc_count;
2714 }
2715
2716 int jt_llog_catlist(int argc, char **argv)
2717 {
2718         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
2719         char *tmp = NULL;
2720         int start = 0;
2721
2722         if (argc != 1)
2723                 return CMD_HELP;
2724
2725         if (llog_default_device(LLOG_DFLT_MGS_SET))
2726                 return CMD_INCOMPLETE;
2727
2728         do {
2729                 start = llog_catlist_next(start, rawbuf, sizeof(rawbuf));
2730                 if (start < 0)
2731                         break;
2732                 tmp = ((struct obd_ioctl_data *)buf)->ioc_bulk;
2733                 if (strlen(tmp) > 0)
2734                         fprintf(stdout, "%s", tmp);
2735                 else
2736                         break;
2737         } while (start);
2738
2739         llog_default_device(LLOG_DFLT_DEV_RESET);
2740
2741         return start;
2742 }
2743
2744 int jt_llog_info(int argc, char **argv)
2745 {
2746         const struct option long_opts[] = {
2747         /* Allow optional "--catalog" for compatibility with llog commands. */
2748         { .val = 'c',   .name = "catalog",      .has_arg = required_argument },
2749         { .val = 'h',   .name = "help",         .has_arg = no_argument },
2750         { .name = NULL } };
2751         struct obd_ioctl_data data = { 0 };
2752         char rawbuf[MAX_IOC_BUFLEN] = "", *buf = rawbuf;
2753         char *cmd = argv[0];
2754         char *catalog = NULL;
2755         int rc, c;
2756
2757         while ((c = getopt_long(argc, argv, "c:h", long_opts, NULL)) != -1) {
2758                 switch (c) {
2759                 case 'c':
2760                         catalog = optarg;
2761                         break;
2762                 case 'h':
2763                 default:
2764                         return CMD_HELP;
2765                 }
2766         }
2767         argc -= optind;
2768         argv += optind;
2769         /* support "logname" positional parameter */
2770         if (argc == 1) {
2771                 if (catalog) {
2772                         fprintf(stderr,
2773                                 "%s: catalog is set, unknown argument '%s'\n",
2774                                 cmd, optarg);
2775                         return CMD_HELP;
2776                 }
2777                 catalog = argv[0];
2778         } else if (!catalog || argc > 1) {
2779                 return CMD_HELP;
2780         }
2781
2782         /* Manage default device */
2783         if (llog_default_device(LLOG_DFLT_MGS_SET))
2784                 return CMD_INCOMPLETE;
2785
2786         data.ioc_dev = cur_device;
2787         data.ioc_inllen1 = strlen(catalog) + 1;
2788         data.ioc_inlbuf1 = catalog;
2789         data.ioc_inllen2 = sizeof(rawbuf) - __ALIGN_KERNEL(sizeof(data), 8) -
2790                            __ALIGN_KERNEL(data.ioc_inllen1, 8);
2791         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
2792         if (rc) {
2793                 fprintf(stderr, "%s: ioctl_pack failed for catalog '%s': %s\n",
2794                         jt_cmdname(cmd), catalog, strerror(-rc));
2795                 goto err;
2796         }
2797
2798         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_LLOG_INFO, buf);
2799         if (rc == 0)
2800                 fprintf(stdout, "%s", ((struct obd_ioctl_data *)buf)->ioc_bulk);
2801         else
2802                 fprintf(stderr, "%s: OBD_IOC_LLOG_INFO failed: %s\n",
2803                         jt_cmdname(cmd), strerror(errno));
2804
2805 err:
2806         llog_default_device(LLOG_DFLT_DEV_RESET);
2807
2808         return rc;
2809 }
2810
2811 int jt_llog_print_cb(const char *record, void *private)
2812 {
2813         printf("%s\n", record);
2814
2815         return 0;
2816 }
2817
2818 static int
2819 llog_process_records(int (record_cb)(const char *record, void *private),
2820                      const char *record, void *private, bool reverse)
2821 {
2822         char *ptr = NULL;
2823         char *tmp = NULL;
2824         int rc = 0;
2825
2826         if (!reverse) {
2827                 do {
2828                         ptr = strchr(record, '\n');
2829                         if (ptr)
2830                                 *ptr = '\0';
2831                         rc = record_cb(record, private);
2832                         if (rc)
2833                                 goto out;
2834                         if (ptr)
2835                                 record = ptr + 1;
2836                 } while (ptr && *(ptr + 1));
2837         } else {
2838                 tmp = (char *)record;
2839
2840                 ptr = strrchr(record, '\n');
2841                 if (ptr)
2842                         *ptr = '\0';
2843                 else
2844                         goto out;
2845                 while ((ptr = strrchr(record, '\n'))) {
2846                         tmp = ptr + 1;
2847                         *ptr = '\0';
2848                         rc = record_cb(tmp, private);
2849                         if (rc)
2850                                 goto out;
2851                 };
2852                 rc = record_cb(record, private);
2853                 if (rc)
2854                         goto out;
2855         }
2856 out:
2857         return rc;
2858 }
2859
2860 /**
2861  * Iterate over llog records, typically YAML-formatted configuration logs
2862  *
2863  * \param logname[in]   name of llog file or FID
2864  * \param start[in]     first record to process
2865  * \param end[in]       last record to process (inclusive)
2866  * \param cb[in]        callback for records. Return -ve error, or +ve abort.
2867  * \param private[in,out] private data passed to the \a record_cb function
2868  * \param reverse[in]   print the llog records from the beginning or the end
2869  *
2870  * \retval              0 on success
2871  *                      others handled by the caller
2872  */
2873 int jt_llog_print_iter(char *logname, long start, long end,
2874                        int (record_cb)(const char *record, void *private),
2875                        void *private, bool reverse, bool raw)
2876 {
2877         struct obd_ioctl_data data = { 0 };
2878         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
2879         char startbuf[16], endbuf[16];
2880         static long inc = sizeof(rawbuf) / 128;
2881         long rec;
2882         int rc = 0;
2883
2884         if (end == -1)
2885                 end = 0x7fffffff;
2886
2887         data.ioc_dev = cur_device;
2888         data.ioc_inlbuf1 = logname;
2889         data.ioc_inllen1 = strlen(logname) + 1;
2890
2891         /*
2892          * Estimate about 128 characters per configuration record.  Not all
2893          * records will be printed in any case, so they should easily fit.  If
2894          * not, the kernel will return -EOVERFLOW and ask for fewer records.
2895          *
2896          * We don't want to request records from the kernel one-at-a-time, as
2897          * it restarts the config llog iteration from the beginning, so we
2898          * fetch multiple records from the kernel per call and split locally.
2899          */
2900         for (rec = start; rec < end; rec += inc) {
2901                 char *record = ((struct obd_ioctl_data *)buf)->ioc_bulk;
2902
2903 retry:
2904                 snprintf(startbuf, sizeof(startbuf), "%lu", rec);
2905                 snprintf(endbuf, sizeof(endbuf), "%lu",
2906                          end < rec + inc - 1 ? end : rec + inc - 1);
2907
2908                 data.ioc_u32_1 = raw ? 1 : 0;
2909                 /* start and end record numbers are passed as ASCII digits */
2910                 data.ioc_inlbuf2 = startbuf;
2911                 data.ioc_inllen2 = strlen(startbuf) + 1;
2912                 data.ioc_inlbuf3 = endbuf;
2913                 data.ioc_inllen3 = strlen(endbuf) + 1;
2914
2915                 data.ioc_inllen4 = sizeof(rawbuf) -
2916                         __ALIGN_KERNEL(sizeof(data), 8) -
2917                         __ALIGN_KERNEL(data.ioc_inllen1, 8) -
2918                         __ALIGN_KERNEL(data.ioc_inllen2, 8) -
2919                         __ALIGN_KERNEL(data.ioc_inllen3, 8);
2920                 memset(buf, 0, sizeof(rawbuf));
2921                 rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
2922                 if (rc) {
2923                         fprintf(stderr, "%s: invalid ioctl data\n", logname);
2924                         goto out;
2925                 }
2926
2927                 rc = l_ioctl(OBD_DEV_ID, OBD_IOC_LLOG_PRINT, buf);
2928                 if (rc == -EOVERFLOW && inc > 2) {
2929                         inc /= 2;
2930                         goto retry;
2931                 }
2932                 if (rc) {
2933                         fprintf(stderr, "%s: OBD_IOC_LLOG_PRINT failed: %s\n",
2934                                 logname, strerror(errno));
2935                         rc = -errno;
2936                         goto out;
2937                 }
2938
2939                 /* There is no "end of list" marker, record was not modified */
2940                 if (strcmp(record, logname) == 0)
2941                         break;
2942
2943                 rc = llog_process_records(record_cb, record, private, reverse);
2944                 if (rc)
2945                         goto out;
2946         }
2947
2948 out:
2949         return rc;
2950 }
2951
2952 static int llog_parse_catalog_options(int *argc, char ***argv, char **catalog,
2953                                       long *start, long *end, int *raw)
2954 {
2955         const struct option long_opts[] = {
2956         /* the --catalog option is not required, just for consistency */
2957         { .val = 'c',   .name = "catalog",      .has_arg = required_argument },
2958         { .val = 'e',   .name = "end",          .has_arg = required_argument },
2959         { .val = 'h',   .name = "help",         .has_arg = no_argument },
2960         { .val = 'r',   .name = "raw",          .has_arg = no_argument },
2961         { .val = 's',   .name = "start",        .has_arg = required_argument },
2962         { .name = NULL } };
2963         char *cmd = (*argv)[0];
2964         char *endp;
2965         int c;
2966
2967         if (!catalog || !start || !end)
2968                 return -EINVAL;
2969
2970         /* now process command line arguments*/
2971         while ((c = getopt_long(*argc, *argv, "c:e:hrs:",
2972                                 long_opts, NULL)) != -1) {
2973                 switch (c) {
2974                 case 'c':
2975                         *catalog = optarg;
2976                         break;
2977                 case 'e':
2978                         *end = strtol(optarg, &endp, 0);
2979                         if (*endp != '\0') {
2980                                 fprintf(stderr, "%s: bad end value '%s'\n",
2981                                         cmd, optarg);
2982                                 return CMD_HELP;
2983                         }
2984                         break;
2985                 case 'r':
2986                         if (!raw)
2987                                 return CMD_HELP;
2988                         *raw = 1;
2989                         break;
2990                 case 's':
2991                         *start = strtol(optarg, &endp, 0);
2992                         if (*endp != '\0') {
2993                                 fprintf(stderr, "%s: bad start value '%s'\n",
2994                                         cmd, optarg);
2995                                 return CMD_HELP;
2996                         }
2997                         break;
2998                 case 'h':
2999                 default:
3000                         return CMD_HELP;
3001                 }
3002         }
3003         *argc -= optind;
3004         *argv += optind;
3005
3006         /*
3007          * support old optional positional parameters only if they were
3008          * not already specified with named arguments: logname [start [end]]
3009          */
3010         if (*argc >= 1) {
3011                 if (*catalog) {
3012                         fprintf(stderr,
3013                                 "%s: logname is set, unknown argument '%s'\n",
3014                                 cmd, (*argv)[0]);
3015                         return CMD_HELP;
3016                 }
3017                 *catalog = (*argv)[0];
3018                 (*argc)--;
3019                 (*argv)++;
3020         }
3021
3022         if (*catalog == NULL) {
3023                 fprintf(stderr, "%s: no logname specified\n", cmd);
3024                 return CMD_HELP;
3025         }
3026
3027         if (*argc >= 1) {
3028                 if (*start != 1) {
3029                         fprintf(stderr,
3030                                 "%s: --start is set, unknown argument '%s'\n",
3031                                 cmd, (*argv)[0]);
3032                         return CMD_HELP;
3033                 }
3034
3035                 *start = strtol((*argv)[0], &endp, 0);
3036                 if (*endp != '\0') {
3037                         fprintf(stderr, "%s: bad start value '%s'\n",
3038                                 cmd, (*argv)[0]);
3039                         return CMD_HELP;
3040                 }
3041                 (*argc)--;
3042                 (*argv)++;
3043         }
3044         if (*argc >= 1) {
3045                 if (*end != -1) {
3046                         fprintf(stderr,
3047                                 "%s: --end is set, unknown argument '%s'\n",
3048                                 cmd, (*argv)[0]);
3049                         return CMD_HELP;
3050                 }
3051
3052                 *end = strtol((*argv)[0], &endp, 0);
3053                 if (*endp != '\0') {
3054                         fprintf(stderr, "%s: bad end value '%s'\n",
3055                                 cmd, (*argv)[0]);
3056                         return CMD_HELP;
3057                 }
3058                 (*argc)--;
3059                 (*argv)++;
3060         }
3061         if (*argc > 1) {
3062                 fprintf(stderr, "%s: unknown argument '%s'\n", cmd, (*argv)[0]);
3063                 return CMD_HELP;
3064         }
3065
3066         if (*end != -1 && *end < *start) {
3067                 fprintf(stderr, "%s: end '%lu' less than than start '%lu'\n",
3068                         cmd, *end, *start);
3069                 return CMD_HELP;
3070         }
3071
3072         return 0;
3073 }
3074
3075 int jt_llog_print(int argc, char **argv)
3076 {
3077         char *catalog = NULL;
3078         long start = 1, end = -1;
3079         int raw = 0;
3080         int rc;
3081
3082         rc = llog_parse_catalog_options(&argc, &argv, &catalog, &start, &end,
3083                                         &raw);
3084         if (rc)
3085                 return rc;
3086
3087         if (llog_default_device(LLOG_DFLT_MGS_SET))
3088                 return CMD_INCOMPLETE;
3089
3090         rc = jt_llog_print_iter(catalog, start, end, jt_llog_print_cb,
3091                                 NULL, false, !!raw);
3092
3093         llog_default_device(LLOG_DFLT_DEV_RESET);
3094
3095         return rc;
3096 }
3097
3098 /*
3099  * Parse catalog, log ID, and optionally a log index with either optional
3100  * arguments or positional arguments.  Only the initial catalog argument
3101  * may be positional with other optional arguments.
3102  *
3103  * The positional arguments option should eventually be phased out.
3104  */
3105 static int llog_parse_catalog_log_idx(int *argc, char ***argv, const char *opts,
3106                                       struct obd_ioctl_data *data)
3107 {
3108         const struct option long_opts[] = {
3109         /* the --catalog option is not required, just for consistency */
3110         { .val = 'c',   .name = "catalog",      .has_arg = required_argument },
3111         { .val = 'h',   .name = "help",         .has_arg = no_argument },
3112         { .val = 'i',   .name = "log_idx",      .has_arg = required_argument },
3113         { .val = 'l',   .name = "log_id",       .has_arg = required_argument },
3114         { .name = NULL } };
3115         int c;
3116
3117         /* sanity check */
3118         if (!data || *argc <= 1)
3119                 return -1;
3120
3121         data->ioc_dev = cur_device;
3122
3123         /* now process command line arguments*/
3124         while ((c = getopt_long(*argc, *argv, opts, long_opts, NULL)) != -1) {
3125                 switch (c) {
3126                 case 'c':
3127                         data->ioc_inllen1 = strlen(optarg) + 1;
3128                         data->ioc_inlbuf1 = optarg;
3129                         break;
3130                 case 'i':
3131                         data->ioc_inllen3 = strlen(optarg) + 1;
3132                         data->ioc_inlbuf3 = optarg;
3133                         break;
3134                 case 'l': /* The log_id option isn't currently needed for
3135                            * cancel as mdt_iocontrol() handles IOC_LLOG_CANCEL,
3136                            * but we may as well keep it for now.
3137                            */
3138                         data->ioc_inllen2 = strlen(optarg) + 1;
3139                         data->ioc_inlbuf2 = optarg;
3140                         break;
3141                 case 'h':
3142                 default:
3143                         return CMD_HELP;
3144                 }
3145         }
3146
3147         *argc -= optind;
3148         *argv += optind;
3149
3150         /* Allow catalog to be specified as first option without --catalog */
3151         if (!data->ioc_inlbuf1 && *argc > 0) {
3152                 data->ioc_inlbuf1 = (*argv)[0];
3153                 data->ioc_inllen1 = strlen((*argv)[0]) + 1;
3154                 (*argc)--;
3155                 (*argv)++;
3156         }
3157
3158         return 0;
3159 }
3160
3161 int jt_llog_cancel(int argc, char **argv)
3162 {
3163         struct obd_ioctl_data data = { 0 };
3164         char rawbuf[MAX_IOC_BUFLEN] = "", *buf = rawbuf;
3165         char *cmd = argv[0];
3166         int rc;
3167
3168         /* Manage default device */
3169         if (llog_default_device(LLOG_DFLT_MGS_SET))
3170                 return CMD_INCOMPLETE;
3171
3172         /* Parse catalog file (in inlbuf1) and named parameters */
3173         rc = llog_parse_catalog_log_idx(&argc, &argv, "c:hi:l:", &data);
3174
3175         /*
3176          * Handle old positional parameters if not using named parameters,
3177          * either "<catalog> <log_idx>" or "<catalog> <log_id> <log_idx>".
3178          * It was "inlbuf3 = log_idx", and "inlbuf2 = log_id" (ignored by
3179          * config log cancel), and shows why I hate positional parameters.
3180          */
3181         if (argc == 1) {
3182                 data.ioc_inllen3 = strlen(argv[0]) + 1;
3183                 data.ioc_inlbuf3 = argv[0];
3184         } else if (argc == 2) {
3185                 data.ioc_inllen2 = strlen(argv[0]) + 1;
3186                 data.ioc_inlbuf2 = argv[0];
3187                 data.ioc_inllen3 = strlen(argv[1]) + 1;
3188                 data.ioc_inlbuf3 = argv[1];
3189         }
3190
3191         if (!data.ioc_inlbuf1 || !data.ioc_inlbuf3) {
3192                 /* missing mandatory parameters */
3193                 rc = CMD_HELP;
3194                 goto err;
3195         }
3196
3197         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
3198         if (rc) {
3199                 fprintf(stderr, "%s: ioctl_pack for catalog '%s' failed: %s\n",
3200                         jt_cmdname(cmd), data.ioc_inlbuf1, strerror(-rc));
3201                 goto err;
3202         }
3203
3204         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_LLOG_CANCEL, buf);
3205         if (rc)
3206                 fprintf(stderr, "%s: cancel catalog '%s:%s' failed: %s\n",
3207                         jt_cmdname(cmd), data.ioc_inlbuf1, data.ioc_inlbuf3,
3208                         strerror(errno));
3209
3210 err:
3211         llog_default_device(LLOG_DFLT_DEV_RESET);
3212         return rc;
3213 }
3214
3215 int jt_llog_check(int argc, char **argv)
3216 {
3217         struct obd_ioctl_data data = { 0 };
3218         char rawbuf[MAX_IOC_BUFLEN] = "", *buf = rawbuf;
3219         char *catalog = NULL;
3220         char startbuf[16], endbuf[16];
3221         long start = 1, end = -1;
3222         char *cmd = argv[0];
3223         int rc;
3224
3225         rc = llog_parse_catalog_options(&argc, &argv, &catalog, &start,
3226                                         &end, NULL);
3227         if (rc)
3228                 return rc;
3229
3230         if (llog_default_device(LLOG_DFLT_MGS_SET))
3231                 return CMD_INCOMPLETE;
3232
3233         if (end == -1)
3234                 end = 0x7fffffff;
3235
3236         data.ioc_dev = cur_device;
3237         data.ioc_inllen1 = strlen(catalog) + 1;
3238         data.ioc_inlbuf1 = catalog;
3239
3240         snprintf(startbuf, sizeof(startbuf), "%lu", start);
3241         snprintf(endbuf, sizeof(endbuf), "%lu", end);
3242         /* start and end record numbers are passed as ASCII digits */
3243         data.ioc_inllen2 = strlen(startbuf) + 1;
3244         data.ioc_inlbuf2 = startbuf;
3245         data.ioc_inllen3 = strlen(endbuf) + 1;
3246         data.ioc_inlbuf3 = endbuf;
3247
3248         data.ioc_inllen4 = sizeof(rawbuf) - __ALIGN_KERNEL(sizeof(data), 8) -
3249                            __ALIGN_KERNEL(data.ioc_inllen1, 8) -
3250                            __ALIGN_KERNEL(data.ioc_inllen2, 8) -
3251                            __ALIGN_KERNEL(data.ioc_inllen3, 8);
3252         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
3253         if (rc) {
3254                 fprintf(stderr, "%s: ioctl_pack failed for catalog '%s': %s\n",
3255                         jt_cmdname(cmd), data.ioc_inlbuf1, strerror(-rc));
3256                 goto err;
3257         }
3258
3259         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_LLOG_CHECK, buf);
3260         if (rc == 0)
3261                 fprintf(stdout, "%s", ((struct obd_ioctl_data *)buf)->ioc_bulk);
3262         else
3263                 fprintf(stderr, "%s: OBD_IOC_LLOG_CHECK failed: %s\n",
3264                         jt_cmdname(cmd), strerror(errno));
3265 err:
3266         llog_default_device(LLOG_DFLT_DEV_RESET);
3267         return rc;
3268 }
3269
3270 int jt_llog_remove(int argc, char **argv)
3271 {
3272         struct obd_ioctl_data data = { 0 };
3273         char rawbuf[MAX_IOC_BUFLEN] = "", *buf = rawbuf;
3274         char *cmd = argv[0];
3275         int rc;
3276
3277         if (llog_default_device(LLOG_DFLT_MGS_SET))
3278                 return CMD_INCOMPLETE;
3279
3280         rc = llog_parse_catalog_log_idx(&argc, &argv, "c:hl:", &data);
3281         if (rc)
3282                 goto err;
3283
3284         if (argc == 1) {
3285                 if (data.ioc_inlbuf2) {
3286                         fprintf(stderr,
3287                                 "%s: --log_id is set, unknown argument '%s'\n",
3288                                 jt_cmdname(cmd), argv[0]);
3289                         rc = CMD_HELP;
3290                         goto err;
3291                 }
3292
3293                 data.ioc_inllen2 = strlen(argv[0]) + 1;
3294                 data.ioc_inlbuf2 = argv[0];
3295         }
3296
3297         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
3298         if (rc) {
3299                 fprintf(stderr, "%s: ioctl_pack for catalog '%s' failed: %s\n",
3300                         jt_cmdname(cmd), data.ioc_inlbuf1, strerror(-rc));
3301                 goto err;
3302         }
3303
3304         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_LLOG_REMOVE, buf);
3305         if (rc)
3306                 fprintf(stderr, "%s: cancel catalog '%s:%s' failed: %s\n",
3307                         jt_cmdname(cmd), data.ioc_inlbuf1, data.ioc_inlbuf2,
3308                         strerror(-rc));
3309
3310 err:
3311         llog_default_device(LLOG_DFLT_DEV_RESET);
3312         return rc;
3313 }
3314
3315 static void signal_server(int sig)
3316 {
3317         if (sig == SIGINT) {
3318                 do_disconnect("sigint", 1);
3319                 exit(1);
3320         } else {
3321                 fprintf(stderr, "%s: got signal %d\n", jt_cmdname("sigint"),
3322                         sig);
3323         }
3324 }
3325
3326 int obd_initialize(int argc, char **argv)
3327 {
3328         if (shmem_setup() != 0)
3329                 return -1;
3330
3331         register_ioc_dev(OBD_DEV_ID, OBD_DEV_PATH);
3332
3333         return 0;
3334 }
3335
3336 void obd_finalize(int argc, char **argv)
3337 {
3338         struct sigaction sigact;
3339
3340         /* sigact initialization */
3341         sigact.sa_handler = signal_server;
3342         sigfillset(&sigact.sa_mask);
3343         sigact.sa_flags = SA_RESTART;
3344         /* coverity[uninit_use_in_call] */
3345         sigaction(SIGINT, &sigact, NULL);
3346
3347         shmem_cleanup();
3348         do_disconnect(argv[0], 1);
3349 }
3350
3351 /**
3352  * Get the index of the last llog record
3353  *
3354  * logid:            [0x3:0xa:0x0]:0
3355  * flags:            4 (plain)
3356  * records_count:    57
3357  * last_index:       57
3358  *
3359  * \param logname[in]   pointer to config log name
3360  *
3361  * \retval              > 0 on success
3362  *                      <= 0 on error
3363  */
3364 static long llog_last_index(char *logname)
3365 {
3366         struct obd_ioctl_data data = { 0 };
3367         char rawbuf[MAX_IOC_BUFLEN] = "", *buf = rawbuf;
3368         char *last_index;
3369         long rc;
3370
3371         data.ioc_dev = cur_device;
3372         data.ioc_inllen1 = strlen(logname) + 1;
3373         data.ioc_inlbuf1 = logname;
3374         data.ioc_inllen2 = sizeof(rawbuf) - __ALIGN_KERNEL(sizeof(data), 8) -
3375                            __ALIGN_KERNEL(data.ioc_inllen1, 8);
3376         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
3377         if (rc) {
3378                 fprintf(stderr, "%s: ioctl_pack failed for catalog '%s': %s\n",
3379                         __func__, logname, strerror(-rc));
3380                 return rc;
3381         }
3382
3383         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_LLOG_INFO, buf);
3384         if (rc == 0) {
3385                 last_index = strstr(((struct obd_ioctl_data *)buf)->ioc_bulk,
3386                                     "last_index:");
3387                 return strtol(last_index + 11, NULL, 10);
3388         }
3389
3390         rc = -errno;
3391
3392         return rc;
3393 }
3394
3395 static char *get_llog_event_name(__u32 cmd)
3396 {
3397 #ifdef HAVE_SERVER_SUPPORT
3398         struct lcfg_type_data *data;
3399
3400         data = lcfg_cmd2data(cmd);
3401         if (data)
3402                 return data->ltd_name;
3403 #endif
3404         return NULL;
3405 }
3406
3407 static char *get_event_filter(__u32 cmd)
3408 {
3409         char *event_name;
3410         char *filter = NULL;
3411         int len;
3412
3413         event_name = get_llog_event_name(cmd);
3414         if (event_name) {
3415                 /* 9 bytes for "event: , " */
3416                 len = 9 + strlen(event_name);
3417                 filter = malloc(len + 1);
3418                 if (!filter)
3419                         return NULL;
3420                 memset(filter, 0, len + 1);
3421                 snprintf(filter, len, "event: %s, ", event_name);
3422                 return filter;
3423         }
3424
3425         return NULL;
3426 }
3427
3428 /**
3429  * Callback to search ostname in llog
3430  * - { index: 23, event: attach, device: lustre-OST0000-osc, type: osc,
3431  *     UUID: lustre-clilov_UUID }
3432  * - { index: 24, event: setup, device: lustre-OST0000-osc,
3433  *     UUID: lustre-OST0000_UUID, node: 192.168.0.120@tcp }
3434  * - { index: 25, event: add_osc, device: lustre-clilov,
3435  *     ost: lustre-OST0000_UUID, index: 0, gen: 1 }
3436  *
3437  * \param record[in]    pointer to llog record
3438  * \param data[in]      pointer to ostname
3439  *
3440  * \retval              1 if ostname is found
3441  *                      0 if ostname is not found
3442  *                      -ENOENT if ostname is deleted
3443  */
3444 static int llog_search_ost_cb(const char *record, void *data)
3445 {
3446         char *ostname = data;
3447         char ost_filter[MAX_STRING_SIZE] = {'\0'};
3448         char *add_osc, *del_osc, *setup, *cleanup;
3449
3450         add_osc = get_event_filter(LCFG_LOV_ADD_OBD);
3451         del_osc = get_event_filter(LCFG_LOV_DEL_OBD);
3452         setup = get_event_filter(LCFG_SETUP);
3453         cleanup = get_event_filter(LCFG_CLEANUP);
3454         if (!add_osc || !del_osc || !setup || !cleanup)
3455                 return -ENOMEM;
3456
3457         if (ostname && ostname[0])
3458                 snprintf(ost_filter, sizeof(ost_filter), " %s,", ostname);
3459
3460         if (strstr(record, ost_filter)) {
3461                 if (strstr(record, add_osc) || strstr(record, setup))
3462                         return 1;
3463                 if (strstr(record, del_osc) || strstr(record, cleanup))
3464                         return -ENOENT;
3465         }
3466
3467         free(add_osc);
3468         free(del_osc);
3469         free(setup);
3470         free(cleanup);
3471
3472         return 0;
3473 }
3474
3475 /**
3476  * Search ost in llog
3477  *
3478  * \param logname[in]           pointer to config log name
3479  * \param last_index[in]        the index of the last llog record
3480  * \param ostname[in]           pointer to ost name
3481  *
3482  * \retval                      1 if ostname is found
3483  *                              0 if ostname is not found
3484  */
3485 static int llog_search_ost(char *logname, long last_index, char *ostname)
3486 {
3487         long start, end, inc = MAX_IOC_BUFLEN / 128;
3488         int rc = 0;
3489
3490         for (end = last_index; end > 1; end -= inc) {
3491                 start = end - inc > 0 ? end - inc : 1;
3492                 rc = jt_llog_print_iter(logname, start, end, llog_search_ost_cb,
3493                                         ostname, true, false);
3494                 if (rc)
3495                         break;
3496         }
3497
3498         return (rc == 1 ? 1 : 0);
3499 }
3500
3501 struct llog_del_ost_priv {
3502         char *logname;
3503         char *ostname;
3504         int found;
3505         int dryrun;
3506 };
3507
3508 /**
3509  * Callback to search and delete ostname in llog
3510  *
3511  * \param record[in]    pointer to llog record
3512  * \param data[in]      pointer to ostname
3513  *
3514  * \retval              1 if ostname is found and entry deleted
3515  *                      0 if ostname is not found
3516  *                      < 0 if error
3517  */
3518 static int llog_del_ost_cb(const char *record, void *data)
3519 {
3520         char ost_filter[MAX_STRING_SIZE] = {'\0'};
3521         char log_idxstr[MAX_STRING_SIZE] = {'\0'};
3522         long int log_idx = 0;
3523         struct llog_del_ost_priv *priv = data;
3524         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
3525         struct obd_ioctl_data ioc_data = { 0 };
3526         int rc = 0;
3527
3528         if (priv->ostname && priv->ostname[0])
3529                 snprintf(ost_filter, sizeof(ost_filter), " %s", priv->ostname);
3530
3531         if (!strstr(record, ost_filter))
3532                 return rc;
3533
3534         rc = sscanf(record, "- { index: %ld", &log_idx);
3535         if (rc < 0) {
3536                 fprintf(stderr, "error: record without index:\n%s\n",
3537                         record);
3538                 return 0;
3539         }
3540         snprintf(log_idxstr, sizeof(log_idxstr), "%ld", log_idx);
3541
3542         ioc_data.ioc_dev = cur_device;
3543         ioc_data.ioc_inllen1 = strlen(priv->logname) + 1;
3544         ioc_data.ioc_inlbuf1 = priv->logname;
3545         ioc_data.ioc_inllen3 = strlen(log_idxstr) + 1;
3546         ioc_data.ioc_inlbuf3 = log_idxstr;
3547
3548         rc = llapi_ioctl_pack(&ioc_data, &buf, sizeof(rawbuf));
3549         if (rc) {
3550                 fprintf(stderr, "ioctl_pack for catalog '%s' failed: %s\n",
3551                         ioc_data.ioc_inlbuf1, strerror(-rc));
3552                 return rc;
3553         }
3554
3555         if (priv->dryrun) {
3556                 fprintf(stdout, "[DRY RUN] cancel catalog '%s:%s':\"%s\"\n",
3557                         ioc_data.ioc_inlbuf1, ioc_data.ioc_inlbuf3, record);
3558         } else {
3559                 rc = l_ioctl(OBD_DEV_ID, OBD_IOC_LLOG_CANCEL, buf);
3560                 if (rc)
3561                         fprintf(stderr, "cancel catalog '%s:%s' failed: %s\n",
3562                                 ioc_data.ioc_inlbuf1, ioc_data.ioc_inlbuf3,
3563                                 strerror(errno));
3564                 else {
3565                         fprintf(stdout, "cancel catalog %s log_idx %ld: done\n",
3566                                 priv->logname, log_idx);
3567                         priv->found++;
3568                 }
3569         }
3570         return rc;
3571 }
3572
3573 /**
3574  * Search and delete ost in llog
3575  *
3576  * \param logname[in]           pointer to config log name
3577  * \param last_index[in]        the index of the last llog record
3578  * \param ostname[in]           pointer to ost name
3579  * \param dryrun[in]            dry run?
3580  *
3581  * \retval                      1 if ostname is found and deleted
3582  *                              0 if ostname is not found
3583  */
3584 static int llog_del_ost(char *logname, long last_index, char *ostname,
3585                         int dryrun)
3586 {
3587         long start, end, inc = MAX_IOC_BUFLEN / 128;
3588         int rc = 0;
3589         struct llog_del_ost_priv priv = { logname, ostname, false, dryrun };
3590
3591         for (end = last_index; end > 1; end -= inc) {
3592                 start = end - inc > 0 ? end - inc : 1;
3593                 rc = jt_llog_print_iter(logname, start, end, llog_del_ost_cb,
3594                                         &priv, true, false);
3595                 if (rc)
3596                         break;
3597         }
3598
3599         if (priv.found)
3600                 fprintf(stdout, "del_ost: cancelled %d catalog entries\n",
3601                         priv.found);
3602         else
3603                 fprintf(stdout, "del_ost: no catalog entry deleted\n");
3604
3605         return rc;
3606 }
3607
3608 struct llog_pool_data {
3609         char lpd_fsname[LUSTRE_MAXFSNAME + 1];
3610         char lpd_poolname[LOV_MAXPOOLNAME + 1];
3611         char lpd_ostname[MAX_OBD_NAME + 1];
3612         enum lcfg_command_type lpd_cmd_type;
3613         bool lpd_pool_exists;
3614         int lpd_ost_num;
3615 };
3616
3617 /**
3618  * Called for each formatted line in the config log (within range).
3619  *
3620  * - { index: 74, event: new_pool, device: tfs-clilov, fsname: tfs, pool: tmp }
3621  * - { index: 77, event: add_pool, device: tfs-clilov, fsname: tfs, pool: tmp,
3622  *     ost: tfs-OST0000_UUID }
3623  * - { index: 224, event: remove_pool, device: tfs-clilov, fsname: tfs,
3624  *     pool: tmp, ost: tfs-OST0003_UUID }
3625  * - { index: 227, event: del_pool, device: tfs-clilov, fsname: tfs, pool: tmp }
3626  *
3627  * \param record[in]    pointer to llog record
3628  * \param data[in]      pointer to llog_pool_data
3629  *
3630  * \retval              1 if pool or OST is found
3631  *                      0 if pool or OST is not found
3632  *                      -ENOENT if pool or OST is removed
3633  */
3634 static int llog_search_pool_cb(const char *record, void *data)
3635 {
3636         struct llog_pool_data *lpd = data;
3637         char pool_filter[MAX_STRING_SIZE] = "";
3638         char *new_pool, *del_pool, *add_pool, *rem_pool;
3639         char *found = NULL;
3640         int fs_pool_len = 0, rc = 0;
3641
3642         new_pool = get_event_filter(LCFG_POOL_NEW);
3643         del_pool = get_event_filter(LCFG_POOL_DEL);
3644         add_pool = get_event_filter(LCFG_POOL_ADD);
3645         rem_pool = get_event_filter(LCFG_POOL_REM);
3646         if (!new_pool || !del_pool || !add_pool || !rem_pool) {
3647                 rc = -ENOMEM;
3648                 goto out;
3649         }
3650
3651         fs_pool_len = 16 + strlen(lpd->lpd_fsname) + strlen(lpd->lpd_poolname);
3652         snprintf(pool_filter, fs_pool_len + 1, "fsname: %s, pool: %s",
3653                  lpd->lpd_fsname, lpd->lpd_poolname);
3654
3655         /* search poolname */
3656         found = strstr(record, pool_filter);
3657         if (found &&
3658             (found[fs_pool_len] == ' ' || found[fs_pool_len] == ',')) {
3659                 if (strstr(record, new_pool)) {
3660                         lpd->lpd_pool_exists = true;
3661                         rc = 1;
3662                         goto out;
3663                 }
3664                 if (strstr(record, del_pool)) {
3665                         lpd->lpd_pool_exists = false;
3666                         rc = -ENOENT;
3667                         goto out;
3668                 }
3669
3670                 if (lpd->lpd_cmd_type == LCFG_POOL_NEW ||
3671                     lpd->lpd_cmd_type == LCFG_POOL_DEL) {
3672                         /* In function mgs_pool_cmd(), a pool's pool_new/add
3673                          * record will be marked as "SKIP" if its pool_destroy/
3674                          * remove record is logged later. That means the "SKIP"
3675                          * record won't be printed here and thus lpd_ost_num
3676                          * doesn't need to be decreased as well.
3677                          */
3678                         if (strstr(record, add_pool))
3679                                 lpd->lpd_ost_num++;
3680                 } else if (lpd->lpd_ostname && lpd->lpd_ostname[0]) {
3681                         if (strstr(record, lpd->lpd_ostname)) {
3682                                 lpd->lpd_pool_exists = true;
3683                                 if (strstr(record, add_pool)) {
3684                                         lpd->lpd_ost_num = 1;
3685                                         rc = 1;
3686                                         goto out;
3687                                 }
3688                                 if (strstr(record, rem_pool)) {
3689                                         lpd->lpd_ost_num = 0;
3690                                         rc = -ENOENT;
3691                                         goto out;
3692                                 }
3693                         }
3694                 }
3695         }
3696 out:
3697         if (new_pool)
3698                 free(new_pool);
3699         if (del_pool)
3700                 free(del_pool);
3701         if (add_pool)
3702                 free(add_pool);
3703         if (rem_pool)
3704                 free(rem_pool);
3705
3706         return rc;
3707 }
3708
3709 /* Search pool and its ost in llog
3710  *
3711  * \param logname[in]           pointer to config log name
3712  * \param last_index[in]        the index of the last llog record
3713  * \param fsname[in]            pointer to filesystem name
3714  * \param poolname[in]          pointer pool name
3715  * \param ostname[in]           pointer to OST name(OSTnnnn-UUID)
3716  * \param cmd[in]               pool command type
3717  *
3718  * \retval                      < 0 on error
3719  *                              0 if pool is empty or OST is not found
3720  *                              1 if pool is not empty or OST is found
3721  */
3722 static int llog_search_pool(char *logname, long last_index, char *fsname,
3723                             char *poolname, char *ostname,
3724                             enum lcfg_command_type cmd)
3725 {
3726         struct llog_pool_data lpd;
3727         long start, end, inc = MAX_IOC_BUFLEN / 128;
3728         int rc = 0;
3729
3730         memset(&lpd, 0, sizeof(lpd));
3731         lpd.lpd_cmd_type = cmd;
3732         lpd.lpd_pool_exists = false;
3733         lpd.lpd_ost_num = 0;
3734         strncpy(lpd.lpd_fsname, fsname, sizeof(lpd.lpd_fsname) - 1);
3735         if (poolname && poolname[0])
3736                 strncpy(lpd.lpd_poolname, poolname,
3737                         sizeof(lpd.lpd_poolname) - 1);
3738         if (ostname && ostname[0])
3739                 strncpy(lpd.lpd_ostname, ostname, sizeof(lpd.lpd_ostname) - 1);
3740
3741         for (end = last_index; end > 1; end -= inc) {
3742                 start = end - inc > 0 ? end - inc : 1;
3743                 rc = jt_llog_print_iter(logname, start, end,
3744                                         llog_search_pool_cb, &lpd, true, false);
3745                 if (rc) {
3746                         if (rc == 1 && lpd.lpd_pool_exists)
3747                                 rc = lpd.lpd_ost_num ? 1 : 0;
3748                         else if (rc == -ENOENT && lpd.lpd_pool_exists &&
3749                                  !lpd.lpd_ost_num)
3750                                 rc = 0;
3751                         goto out;
3752                 }
3753         }
3754
3755         rc = -ENOENT;
3756 out:
3757         return rc;
3758 }
3759
3760 static bool combined_mgs_mds(char *fsname)
3761 {
3762         glob_t path;
3763         int rc;
3764
3765         rc = cfs_get_param_paths(&path, "mdt/%s-MDT0000", fsname);
3766         if (!rc)
3767                 cfs_free_param_data(&path);
3768
3769         if (get_mgs_device() > 0 && !rc)
3770                 return true;
3771
3772         return false;
3773 }
3774
3775 /*
3776  * if pool is NULL, search ostname in target_obd
3777  * if pool is not NULL:
3778  *  - if pool not found returns errno < 0
3779  *  - if ostname is NULL, returns 1 if pool is not empty and 0 if pool empty
3780  *  - if ostname is not NULL, returns 1 if OST is in pool and 0 if not
3781  */
3782 int lctl_search_ost(char *fsname, char *poolname, char *ostname,
3783                     enum lcfg_command_type cmd)
3784 {
3785         char logname[MAX_OBD_NAME] = {'\0'};
3786         long last_index;
3787
3788         if (fsname && fsname[0] == '\0')
3789                 fsname = NULL;
3790         if (!fsname)
3791                 return -EINVAL;
3792
3793         if (combined_mgs_mds(fsname))
3794                 return llapi_search_ost(fsname, poolname, ostname);
3795
3796         /* fetch the last_index of llog record */
3797         snprintf(logname, sizeof(logname), "%s-client", fsname);
3798         last_index = llog_last_index(logname);
3799         if (last_index < 0)
3800                 return last_index;
3801
3802         /* if pool is NULL, search ostname in target_obd */
3803         if (!poolname && ostname)
3804                 return llog_search_ost(logname, last_index, ostname);
3805
3806         return llog_search_pool(logname, last_index, fsname, poolname,
3807                                 ostname, cmd);
3808 }
3809
3810 static int check_pool_cmd(enum lcfg_command_type cmd, char *fsname,
3811                           char *poolname, char *ostname)
3812 {
3813         int rc;
3814
3815         rc = lctl_search_ost(fsname, poolname, ostname, cmd);
3816         if (rc < 0 && (cmd != LCFG_POOL_NEW)) {
3817                 fprintf(stderr, "Pool %s.%s not found\n",
3818                         fsname, poolname);
3819                 return rc;
3820         }
3821
3822         switch (cmd) {
3823         case LCFG_POOL_NEW: {
3824                 if (ostname)
3825                         return -EINVAL;
3826
3827                 if (rc >= 0) {
3828                         fprintf(stderr, "Pool %s.%s already exists\n",
3829                                 fsname, poolname);
3830                         return -EEXIST;
3831                 }
3832                 return 0;
3833         }
3834         case LCFG_POOL_DEL: {
3835                 if (ostname)
3836                         return -EINVAL;
3837
3838                 if (rc == 1) {
3839                         fprintf(stderr,
3840                                 "Pool %s.%s not empty, please remove all members\n",
3841                                 fsname, poolname);
3842                         return -ENOTEMPTY;
3843                 }
3844                 return 0;
3845         }
3846         case LCFG_POOL_ADD: {
3847                 if (rc == 1) {
3848                         fprintf(stderr, "OST %s is already in pool %s.%s\n",
3849                                 ostname, fsname, poolname);
3850                         return -EEXIST;
3851                 }
3852                 rc = lctl_search_ost(fsname, NULL, ostname, cmd);
3853                 if (rc == 0) {
3854                         fprintf(stderr, "OST %s is not part of the '%s' fs.\n",
3855                                 ostname, fsname);
3856                         return -ENOENT;
3857                 }
3858                 return 0;
3859         }
3860         case LCFG_POOL_REM: {
3861                 if (rc == 0) {
3862                         fprintf(stderr, "OST %s not found in pool %s.%s\n",
3863                                 ostname, fsname, poolname);
3864                         return -ENOENT;
3865                 }
3866                 return 0;
3867         }
3868         default:
3869                 break;
3870         } /* switch */
3871         return -EINVAL;
3872 }
3873
3874 /*
3875  * This check only verifies that the changes have been "pushed out" to
3876  * the client successfully.  This involves waiting for a config update,
3877  * and so may fail because of problems in that code or post-command
3878  * network loss. So reporting a warning is appropriate, but not a failure.
3879  */
3880 static int check_pool_cmd_result(enum lcfg_command_type cmd, char *fsname,
3881                                  char *poolname, char *ostname)
3882 {
3883         int cpt = 10;
3884         int rc = 0;
3885
3886         switch (cmd) {
3887         case LCFG_POOL_NEW: {
3888                 do {
3889                         rc = lctl_search_ost(fsname, poolname, NULL, cmd);
3890                         if (rc == -ENODEV)
3891                                 return rc;
3892                         if (rc < 0)
3893                                 sleep(1);
3894                         cpt--;
3895                 } while ((rc < 0) && (cpt > 0));
3896                 if (rc >= 0) {
3897                         fprintf(stderr, "Pool %s.%s created\n",
3898                                 fsname, poolname);
3899                         return 0;
3900                 }
3901
3902                 fprintf(stderr, "Warning, pool %s.%s not found\n", fsname,
3903                         poolname);
3904                 return -ENOENT;
3905         }
3906         case LCFG_POOL_DEL: {
3907                 do {
3908                         rc = lctl_search_ost(fsname, poolname, NULL, cmd);
3909                         if (rc == -ENODEV)
3910                                 return rc;
3911                         if (rc >= 0)
3912                                 sleep(1);
3913                         cpt--;
3914                 } while ((rc >= 0) && (cpt > 0));
3915                 if (rc < 0) {
3916                         fprintf(stderr, "Pool %s.%s destroyed\n",
3917                                 fsname, poolname);
3918                         return 0;
3919                 }
3920
3921                 fprintf(stderr, "Warning, pool %s.%s still found\n", fsname,
3922                         poolname);
3923                 return -EEXIST;
3924         }
3925         case LCFG_POOL_ADD: {
3926                 do {
3927                         rc = lctl_search_ost(fsname, poolname, ostname, cmd);
3928                         if (rc == -ENODEV)
3929                                 return rc;
3930                         if (rc != 1)
3931                                 sleep(1);
3932                         cpt--;
3933                 } while ((rc != 1) && (cpt > 0));
3934                 if (rc == 1) {
3935                         fprintf(stderr, "OST %s added to pool %s.%s\n",
3936                                 ostname, fsname, poolname);
3937                         return 0;
3938                 }
3939                 fprintf(stderr, "Warning, OST %s not found in pool %s.%s\n",
3940                         ostname, fsname, poolname);
3941                 return -ENOENT;
3942         }
3943         case LCFG_POOL_REM: {
3944                 do {
3945                         rc = lctl_search_ost(fsname, poolname, ostname, cmd);
3946                         if (rc == -ENODEV)
3947                                 return rc;
3948                         if (rc == 1)
3949                                 sleep(1);
3950                         cpt--;
3951                 } while ((rc == 1) && (cpt > 0));
3952                 if (rc != 1) {
3953                         fprintf(stderr, "OST %s removed from pool %s.%s\n",
3954                                 ostname, fsname, poolname);
3955                         return 0;
3956                 }
3957                 fprintf(stderr, "Warning, OST %s still found in pool %s.%s\n",
3958                         ostname, fsname, poolname);
3959                 return -EEXIST;
3960         }
3961         default:
3962                 break;
3963         }
3964         return -EINVAL;
3965 }
3966
3967 static int check_and_complete_ostname(char *fsname, char *ostname)
3968 {
3969         char *ptr;
3970         char real_ostname[MAX_OBD_NAME + 1];
3971         char i;
3972
3973         /* if OST name does not start with fsname, we add it */
3974         /* if not check if the fsname is the right one */
3975         ptr = strchr(ostname, '-');
3976         if (!ptr) {
3977                 sprintf(real_ostname, "%s-%s", fsname, ostname);
3978         } else if (strncmp(ostname, fsname, strlen(fsname)) != 0) {
3979                 fprintf(stderr, "%s does not start with fsname %s\n",
3980                         ostname, fsname);
3981                 return -EINVAL;
3982         } else {
3983                 if (strlen(ostname) > sizeof(real_ostname) - 1)
3984                         return -E2BIG;
3985
3986                 strncpy(real_ostname, ostname, sizeof(real_ostname));
3987         }
3988
3989         /* real_ostname is fsname-????? */
3990         ptr = real_ostname + strlen(fsname) + 1;
3991         if (strncmp(ptr, "OST", 3) != 0) {
3992                 fprintf(stderr, "%s does not start by %s-OST nor OST\n",
3993                         ostname, fsname);
3994                 return -EINVAL;
3995         }
3996         /* real_ostname is fsname-OST????? */
3997         ptr += 3;
3998         for (i = 0; i < 4; i++) {
3999                 if (!isxdigit(*ptr)) {
4000                         fprintf(stderr,
4001                                 "ost's index in %s is not an hexa number\n",
4002                                 ostname);
4003                         return -EINVAL;
4004                 }
4005                 ptr++;
4006         }
4007         /* real_ostname is fsname-OSTXXXX????? */
4008         /* if OST name does not end with _UUID, we add it */
4009         if (*ptr == '\0') {
4010                 strcat(real_ostname, "_UUID");
4011         } else if (strcmp(ptr, "_UUID") != 0) {
4012                 fprintf(stderr,
4013                         "ostname %s does not end with _UUID\n", ostname);
4014                 return -EINVAL;
4015         }
4016         /* real_ostname is fsname-OSTXXXX_UUID */
4017         strcpy(ostname, real_ostname);
4018         return 0;
4019 }
4020
4021 /* returns 0 or -errno */
4022 static int pool_cmd(enum lcfg_command_type cmd, char *cmdname,
4023                     char *fullpoolname, char *fsname, char *poolname,
4024                     char *ostname)
4025 {
4026         int rc = 0;
4027         struct obd_ioctl_data data;
4028         struct lustre_cfg_bufs bufs;
4029         struct lustre_cfg *lcfg;
4030         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
4031
4032         rc = check_pool_cmd(cmd, fsname, poolname, ostname);
4033         if (rc == -ENODEV)
4034                 fprintf(stderr,
4035                         "Can't verify pool command since there is no local MDT or client, proceeding anyhow...\n");
4036         else if (rc)
4037                 return rc;
4038
4039         lustre_cfg_bufs_reset(&bufs, NULL);
4040         lustre_cfg_bufs_set_string(&bufs, 0, cmdname);
4041         lustre_cfg_bufs_set_string(&bufs, 1, fullpoolname);
4042         if (ostname)
4043                 lustre_cfg_bufs_set_string(&bufs, 2, ostname);
4044
4045         lcfg = malloc(lustre_cfg_len(bufs.lcfg_bufcount, bufs.lcfg_buflen));
4046         if (!lcfg)
4047                 return -ENOMEM;
4048         lustre_cfg_init(lcfg, cmd, &bufs);
4049
4050         memset(&data, 0, sizeof(data));
4051         rc = data.ioc_dev = get_mgs_device();
4052         if (rc < 0)
4053                 goto out;
4054
4055         data.ioc_type = LUSTRE_CFG_TYPE;
4056         data.ioc_plen1 = lustre_cfg_len(lcfg->lcfg_bufcount,
4057                                         lcfg->lcfg_buflens);
4058         data.ioc_pbuf1 = (void *)lcfg;
4059
4060         memset(buf, 0, sizeof(rawbuf));
4061         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
4062         if (rc) {
4063                 fprintf(stderr, "error: %s: invalid ioctl\n",
4064                         jt_cmdname(cmdname));
4065                 free(lcfg);
4066                 return rc;
4067         }
4068         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_POOL, buf);
4069 out:
4070         if (rc)
4071                 rc = -errno;
4072         switch (rc) {
4073         case -ENAMETOOLONG:
4074                 fprintf(stderr,
4075                         "error: %s: either the pool or file system name is too long (max pool name len is %d and file system name is %d)\n",
4076                         jt_cmdname(cmdname), LOV_MAXPOOLNAME, LUSTRE_MAXFSNAME);
4077                 break;
4078         case -EINVAL:
4079                 fprintf(stderr,
4080                         "error: %s can contain only alphanumeric characters, underscores, and dashes besides the required '.'\n",
4081                         jt_cmdname(cmdname));
4082         default:
4083                 break;
4084         }
4085         free(lcfg);
4086         return rc;
4087 }
4088
4089 int jt_del_ost(int argc, char **argv)
4090 {
4091         char *fsname = NULL, *ptr, *logname;
4092         char mdtpattern[16], clipattern[16];
4093         char ostname[MAX_OBD_NAME + 1];
4094         long last_index;
4095         __u32 index;
4096         int rc, start = 0, dryrun = 0;
4097         char c;
4098
4099         static struct option long_opts[] = {
4100         { .val = 'h',   .name = "help",         .has_arg = no_argument },
4101         { .val = 'n',   .name = "dryrun",       .has_arg = no_argument },
4102         { .val = 't',   .name = "target",       .has_arg = required_argument },
4103         { .name = NULL } };
4104
4105         while ((c = getopt_long(argc, argv, "hnt:", long_opts, NULL)) != -1) {
4106                 switch (c) {
4107                 case 't':
4108                         fsname = strdup(optarg);
4109                         break;
4110                 case 'n':
4111                         dryrun = 1;
4112                         break;
4113                 case 'h':
4114                 default:
4115                         free(fsname);
4116                         return CMD_HELP;
4117                 }
4118         }
4119
4120         if (fsname == NULL)
4121                 return CMD_HELP;
4122
4123         if (llog_default_device(LLOG_DFLT_MGS_SET)) {
4124                 rc = CMD_INCOMPLETE;
4125                 goto out;
4126         }
4127
4128         ptr = strstr(fsname, "-OST");
4129         if (!ptr) {
4130                 rc = CMD_HELP;
4131                 goto err;
4132         }
4133
4134         if (dryrun)
4135                 fprintf(stdout, "del_ost: dry run for target %s\n", fsname);
4136
4137         *ptr++ = '\0';
4138         rc = sscanf(ptr, "OST%04x", &index);
4139         if (rc != 1) {
4140                 rc = -EINVAL;
4141                 goto err;
4142         }
4143
4144         if (strlen(ptr) > sizeof(ostname) - 1) {
4145                 rc = -E2BIG;
4146                 goto err;
4147         }
4148
4149         snprintf(mdtpattern, sizeof(mdtpattern), "%s-MDT", fsname);
4150         snprintf(clipattern, sizeof(clipattern), "%s-client", fsname);
4151         snprintf(ostname, sizeof(ostname), "%s-%s", fsname, ptr);
4152
4153         do {
4154                 char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
4155                 char *begin, *end;
4156
4157                 start = llog_catlist_next(start, rawbuf, sizeof(rawbuf));
4158                 if (start < 0)
4159                         break;
4160                 begin = ((struct obd_ioctl_data *)buf)->ioc_bulk;
4161                 if (strlen(begin) == 0)
4162                         break;
4163
4164                 while ((end = strchr(begin, '\n'))) {
4165                         *end = '\0';
4166                         logname = strstr(begin, "config_log: ");
4167
4168                         if (logname && (strstr(logname, mdtpattern) ||
4169                                         strstr(logname, clipattern))) {
4170                                 logname += 12;
4171
4172                                 fprintf(stdout, "config_log: %s\n", logname);
4173
4174                                 last_index = llog_last_index(logname);
4175                                 if (last_index < 0) {
4176                                         fprintf(stderr,
4177                                                 "error with catalog %s: %s\n",
4178                                                 logname, strerror(-last_index));
4179                                         rc = -last_index;
4180                                         goto err;
4181                                 }
4182                                 rc = llog_del_ost(logname, last_index, ostname,
4183                                                   dryrun);
4184                                 if (rc < 0)
4185                                         goto err;
4186                         }
4187                         begin = end + 1;
4188                 }
4189         } while (start);
4190
4191 err:
4192         llog_default_device(LLOG_DFLT_DEV_RESET);
4193 out:
4194         free(fsname);
4195         return rc;
4196 }
4197
4198 #ifdef HAVE_SERVER_SUPPORT
4199 /**
4200  * Format and send the ioctl to the MGS.
4201  *
4202  * \param       cmd             IOCTL to send
4203  * \param       ret_data        void pointer to return anything from
4204  *                              ioctl
4205  * \param       num_args        number of arguments to pack into the
4206  *                              ioctl buffer
4207  * \param       argv[]          variable number of string arguments
4208  *
4209  * \retval                      0 on success
4210  */
4211 static int nodemap_cmd(enum lcfg_command_type cmd, void *ret_data,
4212                        unsigned int ret_size, ...)
4213 {
4214         va_list                 ap;
4215         char                    *arg;
4216         int                     i = 0;
4217         struct lustre_cfg_bufs  bufs;
4218         struct obd_ioctl_data   data;
4219         struct lustre_cfg       *lcfg;
4220         char                    rawbuf[MAX_IOC_BUFLEN];
4221         char                    *buf = rawbuf;
4222         int                     rc = 0;
4223
4224         lustre_cfg_bufs_reset(&bufs, NULL);
4225
4226         va_start(ap, ret_size);
4227         arg = va_arg(ap, char *);
4228         while (arg) {
4229                 lustre_cfg_bufs_set_string(&bufs, i, arg);
4230                 i++;
4231                 arg = va_arg(ap, char *);
4232         }
4233         va_end(ap);
4234
4235         lcfg = malloc(lustre_cfg_len(bufs.lcfg_bufcount, bufs.lcfg_buflen));
4236         if (!lcfg)
4237                 return -ENOMEM;
4238         lustre_cfg_init(lcfg, cmd, &bufs);
4239
4240         memset(&data, 0, sizeof(data));
4241         rc = data.ioc_dev = get_mgs_device();
4242         if (rc < 0)
4243                 goto out;
4244
4245         data.ioc_type = LUSTRE_CFG_TYPE;
4246         data.ioc_plen1 = lustre_cfg_len(lcfg->lcfg_bufcount,
4247                                         lcfg->lcfg_buflens);
4248         data.ioc_pbuf1 = (void *)lcfg;
4249
4250         memset(buf, 0, sizeof(rawbuf));
4251         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
4252         if (rc) {
4253                 fprintf(stderr,
4254                         "error: invalid ioctl request: %08x errno: %d: %s\n",
4255                         cmd, errno, strerror(-rc));
4256                 goto out;
4257         }
4258
4259         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_NODEMAP, buf);
4260         if (rc) {
4261                 fprintf(stderr,
4262                         "error: invalid ioctl: %08x errno: %d: %s\n",
4263                         cmd, errno, strerror(errno));
4264                 goto out;
4265         }
4266
4267         if (ret_data) {
4268                 rc = llapi_ioctl_unpack(&data, buf, sizeof(rawbuf));
4269                 if (rc)
4270                         goto out;
4271
4272                 if (ret_size > data.ioc_plen1)
4273                         ret_size = data.ioc_plen1;
4274
4275                 memcpy(ret_data, data.ioc_pbuf1, ret_size);
4276         }
4277 out:
4278         free(lcfg);
4279
4280         return rc;
4281 }
4282
4283 /**
4284  * activate nodemap functions
4285  *
4286  * \param       argc            number of args
4287  * \param       argv[]          variable string arguments
4288  *
4289  * argv[0]                      1 for activate or 0 for deactivate
4290  *
4291  * \retval                      0 on success
4292  */
4293 int jt_nodemap_activate(int argc, char **argv)
4294 {
4295         int rc;
4296
4297         rc = nodemap_cmd(LCFG_NODEMAP_ACTIVATE, NULL, 0, argv[0], argv[1],
4298                          NULL);
4299
4300         if (rc != 0) {
4301                 errno = -rc;
4302                 perror(argv[0]);
4303         }
4304
4305         return rc;
4306 }
4307
4308 /**
4309  * add a nodemap
4310  *
4311  * \param       argc            number of args
4312  * \param       argv[]          variable string arguments
4313  *
4314  * argv[0]                      nodemap name
4315  *
4316  * \retval                      0 on success
4317  */
4318 int jt_nodemap_add(int argc, char **argv)
4319 {
4320         int rc;
4321
4322         rc = llapi_nodemap_exists(argv[1]);
4323         if (rc == 0) {
4324                 fprintf(stderr, "error: %s existing nodemap name\n", argv[1]);
4325                 return 1;
4326         }
4327
4328         rc = nodemap_cmd(LCFG_NODEMAP_ADD, NULL, 0, argv[0], argv[1], NULL);
4329
4330         if (rc != 0) {
4331                 errno = -rc;
4332                 perror(argv[0]);
4333         }
4334
4335         return rc;
4336 }
4337
4338 /**
4339  * delete a nodemap
4340  *
4341  * \param       argc            number of args
4342  * \param       argv[]          variable string arguments
4343  *
4344  * argv[0]                      nodemap name
4345  *
4346  * \retval                      0 on success
4347  */
4348 int jt_nodemap_del(int argc, char **argv)
4349 {
4350         int rc;
4351
4352         rc = llapi_nodemap_exists(argv[1]);
4353         if (rc != 0) {
4354                 fprintf(stderr, "error: %s not existing nodemap name\n",
4355                         argv[1]);
4356                 return rc;
4357         }
4358         rc = nodemap_cmd(LCFG_NODEMAP_DEL, NULL, 0, argv[0], argv[1], NULL);
4359
4360         if (rc != 0) {
4361                 errno = -rc;
4362                 perror(argv[0]);
4363         }
4364
4365         return rc;
4366 }
4367
4368 /**
4369  * test a nid for nodemap membership
4370  *
4371  * \param       argc            number of args
4372  * \param       argv[]          variable string arguments
4373  *
4374  * argv[0]                      properly formatted nid
4375  *
4376  * \retval                      0 on success
4377  */
4378 int jt_nodemap_test_nid(int argc, char **argv)
4379 {
4380         char    rawbuf[MAX_IOC_BUFLEN];
4381         int     rc;
4382
4383         rc = nodemap_cmd(LCFG_NODEMAP_TEST_NID, &rawbuf, sizeof(rawbuf),
4384                          argv[0], argv[1], NULL);
4385         if (rc == 0)
4386                 printf("%s\n", (char *)rawbuf);
4387
4388         return rc;
4389 }
4390
4391 /**
4392  * test a nodemap id pair for mapping
4393  *
4394  * \param       argc            number of args
4395  * \param       argv[[]         variable string arguments
4396  *
4397  * \retval                      0 on success
4398  *
4399  * The argv array should contain the nodemap name, the id
4400  * to checking the mapping on, and the id type (UID or GID)
4401  *
4402  */
4403 int jt_nodemap_test_id(int argc, char **argv)
4404 {
4405         char    rawbuf[MAX_IOC_BUFLEN];
4406         char    *nidstr = NULL;
4407         char    *idstr = NULL;
4408         char    *typestr = NULL;
4409         int     rc = 0;
4410         int     c;
4411
4412         static struct option long_opts[] = {
4413                 { .val = 'i',   .name = "id",   .has_arg = required_argument },
4414                 { .val = 'n',   .name = "nid",  .has_arg = required_argument },
4415                 { .val = 't',   .name = "idtype",
4416                                                 .has_arg = required_argument },
4417                 { .name = NULL } };
4418
4419         while ((c = getopt_long(argc, argv, "n:t:i:",
4420                                 long_opts, NULL)) != -1) {
4421                 switch (c) {
4422                 case 'n':
4423                         nidstr = optarg;
4424                         break;
4425                 case 't':
4426                         typestr = optarg;
4427                         break;
4428                 case 'i':
4429                         idstr = optarg;
4430                         break;
4431                 }
4432         }
4433
4434         if (!nidstr || !typestr || !idstr) {
4435                 fprintf(stderr,
4436                         "usage: nodemap_test_id --nid <nid> --idtype [uid|gid] --id <id>\n");
4437                 return -1;
4438         }
4439
4440         rc = nodemap_cmd(LCFG_NODEMAP_TEST_ID, &rawbuf, sizeof(rawbuf),
4441                          argv[0], nidstr, typestr, idstr, NULL);
4442         if (rc == 0)
4443                 printf("%s\n", (char *)rawbuf);
4444
4445         return rc;
4446 }
4447
4448 /**
4449  * parse nid range
4450  *
4451  * \param       nodemap_range   --range string
4452  * \param       nid_range       nid range string, min_nid:max_nid
4453  *
4454  * \retval                      0 on success
4455  */
4456 static int parse_nid_range(char *nodemap_range, char *nid_range, int range_len)
4457 {
4458         char                    min_nid[LNET_NIDSTR_SIZE + 1];
4459         char                    max_nid[LNET_NIDSTR_SIZE + 1];
4460         struct list_head        nidlist;
4461         int                     rc = 0;
4462
4463         INIT_LIST_HEAD(&nidlist);
4464
4465         if (cfs_parse_nidlist(nodemap_range, strlen(nodemap_range),
4466                               &nidlist) <= 0) {
4467                 fprintf(stderr,
4468                         "error: nodemap_xxx_range: can't parse nid range: %s\n",
4469                         nodemap_range);
4470                 return -EINVAL;
4471         }
4472
4473         rc = cfs_nidrange_find_min_max(&nidlist, &min_nid[0], &max_nid[0],
4474                                        LNET_NIDSTR_SIZE);
4475         if (rc < 0) {
4476                 if (rc == -EINVAL)
4477                         fprintf(stderr,
4478                                 "error: nodemap_xxx_range: nid range uses currently unsupported features\n");
4479                 else if (rc == -ERANGE)
4480                         fprintf(stderr,
4481                                 "error: nodemap_xxx_range: nodemap ranges must be contiguous\n");
4482
4483                 return rc;
4484         }
4485
4486         snprintf(nid_range, range_len, "%s:%s", min_nid, max_nid);
4487
4488         return rc;
4489 }
4490
4491 /**
4492  * add an nid range to a nodemap
4493  *
4494  * \param       argc            number of args
4495  * \param       argv[]          variable string arguments
4496  *
4497  * --name                       nodemap name
4498  * --range                      properly formatted nid range
4499  *
4500  * \retval                      0 on success, -errno on error
4501  */
4502 int jt_nodemap_add_range(int argc, char **argv)
4503 {
4504         char                    *nodemap_name = NULL;
4505         char                    *nodemap_range = NULL;
4506         char                    nid_range[2 * LNET_NIDSTR_SIZE + 2];
4507         int                     rc = 0;
4508         int                     c;
4509
4510         static struct option long_opts[] = {
4511         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4512         { .val = 'r',   .name = "range",        .has_arg = required_argument },
4513         { .name = NULL } };
4514
4515         while ((c = getopt_long(argc, argv, "n:r:",
4516                                 long_opts, NULL)) != -1) {
4517                 switch (c) {
4518                 case 'n':
4519                         nodemap_name = optarg;
4520                         break;
4521                 case 'r':
4522                         nodemap_range = optarg;
4523                         break;
4524                 }
4525         }
4526
4527         if (!nodemap_name || !nodemap_range) {
4528                 fprintf(stderr,
4529                         "usage: nodemap_add_range --name <name> --range <range>\n");
4530                 return -EINVAL;
4531         }
4532
4533         rc = parse_nid_range(nodemap_range, nid_range, sizeof(nid_range));
4534         if (rc) {
4535                 return rc;
4536         }
4537         rc = nodemap_cmd(LCFG_NODEMAP_ADD_RANGE, NULL, 0, argv[0],
4538                          nodemap_name, nid_range, NULL);
4539         if (rc) {
4540                 fprintf(stderr,
4541                         "error: %s: cannot add range '%s' to nodemap '%s': %s\n",
4542                         jt_cmdname(argv[0]), nodemap_range, nodemap_name,
4543                         strerror(-rc));
4544         }
4545
4546         return rc;
4547 }
4548
4549 /**
4550  * delete an nid range to a nodemap
4551  *
4552  * \param       argc            number of args
4553  * \param       argv[]          variable string arguments
4554  *
4555  * --name                       nodemap name
4556  * --range                      properly formatted nid range
4557  *
4558  * \retval                      0 on success
4559  */
4560 int jt_nodemap_del_range(int argc, char **argv)
4561 {
4562         char                    *nodemap_name = NULL;
4563         char                    *nodemap_range = NULL;
4564         char                    nid_range[2 * LNET_NIDSTR_SIZE + 2];
4565         int                     rc = 0;
4566         int                     c;
4567
4568         static struct option long_opts[] = {
4569         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4570         { .val = 'r',   .name = "range",        .has_arg = required_argument },
4571         { .name = NULL } };
4572
4573         while ((c = getopt_long(argc, argv, "n:r:",
4574                                 long_opts, NULL)) != -1) {
4575                 switch (c) {
4576                 case 'n':
4577                         nodemap_name = optarg;
4578                         break;
4579                 case 'r':
4580                         nodemap_range = optarg;
4581                         break;
4582                 }
4583         }
4584
4585         if (!nodemap_name || !nodemap_range) {
4586                 fprintf(stderr,
4587                         "usage: nodemap_del_range --name <name> --range <range>\n");
4588                 return -1;
4589         }
4590
4591         rc = parse_nid_range(nodemap_range, nid_range, sizeof(nid_range));
4592         if (rc) {
4593                 errno = -rc;
4594                 return rc;
4595         }
4596         rc = nodemap_cmd(LCFG_NODEMAP_DEL_RANGE, NULL, 0, argv[0],
4597                          nodemap_name, nid_range, NULL);
4598         if (rc != 0) {
4599                 errno = -rc;
4600                 fprintf(stderr,
4601                         "error: %s: cannot delete range '%s' to nodemap '%s': rc = %d\n",
4602                         jt_cmdname(argv[0]), nodemap_range, nodemap_name, rc);
4603         }
4604
4605         return rc;
4606 }
4607
4608 /**
4609  * set a fileset on a nodemap
4610  *
4611  * \param       argc            number of args
4612  * \param       argv[]          variable string arguments
4613  *
4614  * --name                       nodemap name
4615  * --fileset                    fileset name
4616  *
4617  * \retval                      0 on success
4618  */
4619 int jt_nodemap_set_fileset(int argc, char **argv)
4620 {
4621         char *nodemap_name = NULL;
4622         char *fileset_name = NULL;
4623         int   rc = 0;
4624         int   c;
4625
4626         static struct option long_opts[] = {
4627         { .val = 'f',   .name = "fileset",      .has_arg = required_argument },
4628         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4629         { .name = NULL } };
4630
4631         while ((c = getopt_long(argc, argv, "n:f:",
4632                                 long_opts, NULL)) != -1) {
4633                 switch (c) {
4634                 case 'n':
4635                         nodemap_name = optarg;
4636                         break;
4637                 case 'f':
4638                         fileset_name = optarg;
4639                         break;
4640                 }
4641         }
4642
4643         if (!nodemap_name || !fileset_name) {
4644                 fprintf(stderr,
4645                         "usage: nodemap_set_fileset --name <name> --fileset <fileset>\n");
4646                 return -1;
4647         }
4648
4649         rc = nodemap_cmd(LCFG_NODEMAP_SET_FILESET, NULL, 0, argv[0],
4650                          nodemap_name, fileset_name, NULL);
4651         if (rc != 0) {
4652                 errno = -rc;
4653                 fprintf(stderr,
4654                         "error: %s: cannot set fileset '%s' on nodemap '%s': rc = %d\n",
4655                         jt_cmdname(argv[0]), fileset_name, nodemap_name, rc);
4656         }
4657
4658         return rc;
4659 }
4660
4661 /**
4662  * set SELinux policy info on a nodemap
4663  *
4664  * \param       argc            number of args
4665  * \param       argv[]          variable string arguments
4666  *
4667  * --name                       nodemap name
4668  * --sepol                      SELinux policy info
4669  *
4670  * \retval                      0 on success
4671  */
4672 int jt_nodemap_set_sepol(int argc, char **argv)
4673 {
4674         char *nodemap_name = NULL;
4675         char *sepol = NULL;
4676         int   rc = 0;
4677         int   c;
4678
4679         static struct option long_options[] = {
4680                 {
4681                         .name           = "name",
4682                         .has_arg        = required_argument,
4683                         .val            = 'n',
4684                 },
4685                 {
4686                         .name           = "sepol",
4687                         .has_arg        = required_argument,
4688                         .val            = 's',
4689                 },
4690                 {
4691                         .name = NULL,
4692                 }
4693         };
4694
4695         while ((c = getopt_long(argc, argv, "n:s:",
4696                                 long_options, NULL)) != -1) {
4697                 switch (c) {
4698                 case 'n':
4699                         nodemap_name = optarg;
4700                         break;
4701                 case 's':
4702                         sepol = optarg;
4703                         break;
4704                 }
4705         }
4706
4707         if (!nodemap_name || !sepol) {
4708                 fprintf(stderr,
4709                         "usage: nodemap_set_sepol --name <name> --sepol <sepol>\n");
4710                 return -1;
4711         }
4712
4713         rc = nodemap_cmd(LCFG_NODEMAP_SET_SEPOL, NULL, 0, argv[0],
4714                          nodemap_name, sepol, NULL);
4715         if (rc != 0) {
4716                 errno = -rc;
4717                 fprintf(stderr,
4718                         "error: %s: cannot set sepol '%s' on nodemap '%s': rc = %d\n",
4719                         jt_cmdname(argv[0]), sepol, nodemap_name, rc);
4720         }
4721
4722         return rc;
4723 }
4724
4725 /**
4726  * modify a nodemap's behavior
4727  *
4728  * \param       argc            number of args
4729  * \param       argv[]          variable string arguments
4730  *
4731  * --name                       nodemap name
4732  * --property                   nodemap property to change
4733  *                              admin, trusted, squash_uid, squash_gid)
4734  * --value                      value to set property
4735  *
4736  * \retval                      0 on success
4737  */
4738 int jt_nodemap_modify(int argc, char **argv)
4739 {
4740         int                     c;
4741         int                     rc = 0;
4742         enum lcfg_command_type  cmd = 0;
4743         char                    *nodemap_name = NULL;
4744         char                    *param = NULL;
4745         char                    *value = NULL;
4746
4747         static struct option long_opts[] = {
4748         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4749         { .val = 'p',   .name = "property",     .has_arg = required_argument },
4750         { .val = 'v',   .name = "value",        .has_arg = required_argument },
4751         { .name = NULL } };
4752
4753         while ((c = getopt_long(argc, argv, "n:p:v:",
4754                                 long_opts, NULL)) != -1) {
4755                 switch (c) {
4756                 case 'n':
4757                         nodemap_name = optarg;
4758                         break;
4759                 case 'p':
4760                         param = optarg;
4761                         break;
4762                 case 'v':
4763                         value = optarg;
4764                         break;
4765                 }
4766         }
4767
4768         if (!nodemap_name || !param || !value) {
4769                 fprintf(stderr,
4770                         "usage: nodemap_modify --name <nodemap_name> --property <property_name> --value <value>\n");
4771                 fprintf(stderr,
4772                         "valid properties: admin trusted map_mode squash_uid squash_gid squash_projid deny_unknown audit_mode forbid_encryption\n");
4773                 return -1;
4774         }
4775
4776         if (strcmp("admin", param) == 0) {
4777                 cmd = LCFG_NODEMAP_ADMIN;
4778         } else if (strcmp("trusted", param) == 0) {
4779                 cmd = LCFG_NODEMAP_TRUSTED;
4780         } else if (strcmp("deny_unknown", param) == 0) {
4781                 cmd = LCFG_NODEMAP_DENY_UNKNOWN;
4782         } else if (strcmp("squash_uid", param) == 0) {
4783                 cmd = LCFG_NODEMAP_SQUASH_UID;
4784         } else if (strcmp("squash_gid", param) == 0) {
4785                 cmd = LCFG_NODEMAP_SQUASH_GID;
4786         } else if (strcmp("squash_projid", param) == 0) {
4787                 cmd = LCFG_NODEMAP_SQUASH_PROJID;
4788         } else if (strcmp("map_mode", param) == 0) {
4789                 cmd = LCFG_NODEMAP_MAP_MODE;
4790         } else if (strcmp("audit_mode", param) == 0) {
4791                 cmd = LCFG_NODEMAP_AUDIT_MODE;
4792         } else if (strcmp("forbid_encryption", param) == 0) {
4793                 cmd = LCFG_NODEMAP_FORBID_ENCRYPT;
4794         } else {
4795                 fprintf(stderr,
4796                         "error: %s: nodemap_modify invalid subcommand: %s\n",
4797                         jt_cmdname(argv[0]), param);
4798                 return -1;
4799         }
4800
4801         rc = nodemap_cmd(cmd, NULL, 0, argv[0], nodemap_name, param,
4802                          value, NULL);
4803         if (rc != 0) {
4804                 errno = -rc;
4805                 fprintf(stderr,
4806                         "error: %s: cannot modify nodemap '%s' to param '%s': value '%s': rc = %d\n",
4807                         jt_cmdname(argv[0]), nodemap_name, param, value, rc);
4808         }
4809
4810         return rc;
4811 }
4812
4813 int jt_nodemap_add_idmap(int argc, char **argv)
4814 {
4815         int                     c;
4816         enum                    lcfg_command_type cmd = 0;
4817         char                    *nodemap_name = NULL;
4818         char                    *idmap = NULL;
4819         char                    *idtype = NULL;
4820         int                     rc = 0;
4821
4822         static struct option long_opts[] = {
4823         { .val = 'i',   .name = "idtype",       .has_arg = required_argument },
4824         { .val = 'm',   .name = "idmap",        .has_arg = required_argument },
4825         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4826         { .name = NULL } };
4827
4828         while ((c = getopt_long(argc, argv, "n:m:i:",
4829                                 long_opts, NULL)) != -1) {
4830                 switch (c) {
4831                 case 'n':
4832                         nodemap_name = optarg;
4833                         break;
4834                 case 'm':
4835                         idmap = optarg;
4836                         break;
4837                 case 'i':
4838                         idtype = optarg;
4839                         break;
4840                 }
4841         }
4842
4843         if (!nodemap_name || !idmap || !idtype) {
4844                 fprintf(stderr,
4845                         "usage: %s --name <name> --idtype [uid | gid | projid] --idmap <client id>:<filesystem id>\n",
4846                         argv[0]);
4847                 return -1;
4848         }
4849
4850         if (strcmp("uid", idtype) == 0) {
4851                 cmd = LCFG_NODEMAP_ADD_UIDMAP;
4852         } else if (strcmp("gid", idtype) == 0) {
4853                 cmd = LCFG_NODEMAP_ADD_GIDMAP;
4854         } else if (strcmp("projid", idtype) == 0) {
4855                 cmd = LCFG_NODEMAP_ADD_PROJIDMAP;
4856         } else {
4857                 fprintf(stderr,
4858                         "usage: %s --name <name> --idtype [uid | gid | projid] --idmap <client id>:<filesystem id>\n",
4859                         argv[0]);
4860                 return -1;
4861         }
4862
4863         rc = nodemap_cmd(cmd, NULL, 0, argv[0], nodemap_name, idmap, NULL);
4864         if (rc != 0) {
4865                 errno = -rc;
4866                 fprintf(stderr,
4867                         "cannot add %smap '%s' to nodemap '%s': rc = %d\n",
4868                         idtype, idmap, nodemap_name, rc);
4869         }
4870
4871         return rc;
4872 }
4873
4874 int jt_nodemap_del_idmap(int argc, char **argv)
4875 {
4876         int                     c;
4877         enum                    lcfg_command_type cmd = 0;
4878         char                    *nodemap_name = NULL;
4879         char                    *idmap = NULL;
4880         char                    *idtype = NULL;
4881         int                     rc = 0;
4882
4883         static struct option long_opts[] = {
4884         { .val = 'i',   .name = "idtype",       .has_arg = required_argument },
4885         { .val = 'm',   .name = "idmap",        .has_arg = required_argument },
4886         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4887         { .name = NULL } };
4888
4889         while ((c = getopt_long(argc, argv, "n:m:i:",
4890                                 long_opts, NULL)) != -1) {
4891                 switch (c) {
4892                 case 'n':
4893                         nodemap_name = optarg;
4894                         break;
4895                 case 'm':
4896                         idmap = optarg;
4897                         break;
4898                 case 'i':
4899                         idtype = optarg;
4900                         break;
4901                 }
4902         }
4903
4904         if (!nodemap_name || !idmap || !idtype) {
4905                 fprintf(stderr,
4906                         "usage: %s --name <name> --idtype [uid | gid | projid] --idmap <client id>:<filesystem id>\n",
4907                         argv[0]);
4908                 return -1;
4909         }
4910
4911         if (strcmp("uid", idtype) == 0) {
4912                 cmd = LCFG_NODEMAP_DEL_UIDMAP;
4913         } else if (strcmp("gid", idtype) == 0) {
4914                 cmd = LCFG_NODEMAP_DEL_GIDMAP;
4915         } else if (strcmp("projid", idtype) == 0) {
4916                 cmd = LCFG_NODEMAP_DEL_PROJIDMAP;
4917         } else {
4918                 fprintf(stderr,
4919                         "usage: %s --name <name> --idtype [uid | gid | projid] --idmap <client id>:<filesystem id>\n",
4920                         argv[0]);
4921                 return -1;
4922         }
4923
4924         rc = nodemap_cmd(cmd, NULL, 0, argv[0], nodemap_name, idmap, NULL);
4925         if (rc != 0) {
4926                 errno = -rc;
4927                 fprintf(stderr,
4928                         "cannot delete %smap '%s' from nodemap '%s': rc = %d\n",
4929                         idtype, idmap, nodemap_name, rc);
4930         }
4931
4932         return rc;
4933 }
4934 #else /* !HAVE_SERVER_SUPPORT */
4935 int jt_nodemap_activate(int argc, char **argv)
4936 {
4937         fprintf(stderr, "error: %s: invalid ioctl\n",
4938                 jt_cmdname(argv[0]));
4939         return -EOPNOTSUPP;
4940 }
4941
4942 int jt_nodemap_add(int argc, char **argv)
4943 {
4944         fprintf(stderr, "error: %s: invalid ioctl\n",
4945                 jt_cmdname(argv[0]));
4946         return -EOPNOTSUPP;
4947 }
4948
4949 int jt_nodemap_del(int argc, char **argv)
4950 {
4951         fprintf(stderr, "error: %s: invalid ioctl\n",
4952                 jt_cmdname(argv[0]));
4953         return -EOPNOTSUPP;
4954 }
4955
4956 int jt_nodemap_modify(int argc, char **argv)
4957 {
4958         fprintf(stderr, "error: %s: invalid ioctl\n",
4959                 jt_cmdname(argv[0]));
4960         return -EOPNOTSUPP;
4961 }
4962
4963 int jt_nodemap_add_range(int argc, char **argv)
4964 {
4965         fprintf(stderr, "error: %s: invalid ioctl\n",
4966                 jt_cmdname(argv[0]));
4967         return -EOPNOTSUPP;
4968 }
4969
4970 int jt_nodemap_test_nid(int argc, char **argv)
4971 {
4972         fprintf(stderr, "error: %s: invalid ioctl\n",
4973                 jt_cmdname(argv[0]));
4974         return -EOPNOTSUPP;
4975 }
4976
4977 int jt_nodemap_del_range(int argc, char **argv)
4978 {
4979         fprintf(stderr, "error: %s: invalid ioctl\n",
4980                 jt_cmdname(argv[0]));
4981         return -EOPNOTSUPP;
4982 }
4983
4984 int jt_nodemap_add_idmap(int argc, char **argv)
4985 {
4986         fprintf(stderr, "error: %s: invalid ioctl\n",
4987                 jt_cmdname(argv[0]));
4988         return -EOPNOTSUPP;
4989 }
4990
4991 int jt_nodemap_del_idmap(int argc, char **argv)
4992 {
4993         fprintf(stderr, "error: %s: invalid ioctl\n",
4994                 jt_cmdname(argv[0]));
4995         return -EOPNOTSUPP;
4996 }
4997
4998 int jt_nodemap_test_id(int argc, char **argv)
4999 {
5000         fprintf(stderr, "error: %s: invalid ioctl\n",
5001                 jt_cmdname(argv[0]));
5002         return -EOPNOTSUPP;
5003 }
5004
5005 int jt_nodemap_set_fileset(int argc, char **argv)
5006 {
5007         fprintf(stderr, "error: %s: invalid ioctl\n",
5008                 jt_cmdname(argv[0]));
5009         return -EOPNOTSUPP;
5010 }
5011
5012 int jt_nodemap_set_sepol(int argc, char **argv)
5013 {
5014         fprintf(stderr, "error: %s: invalid ioctl\n",
5015                 jt_cmdname(argv[0]));
5016         return -EOPNOTSUPP;
5017 }
5018
5019 int jt_nodemap_info(int argc, char **argv)
5020 {
5021         fprintf(stderr, "error: %s: invalid ioctl\n",
5022                 jt_cmdname(argv[0]));
5023         return -EOPNOTSUPP;
5024 }
5025 #endif /* HAVE_SERVER_SUPPORT */
5026
5027 /*
5028  * this function tranforms a rule [start-end/step] into an array
5029  * of matching numbers
5030  * supported forms are:
5031  * [start]                : just this number
5032  * [start-end]            : all numbers from start to end
5033  * [start-end/step]       : numbers from start to end with increment of step
5034  * on return, format contains a printf format string which can be used
5035  * to generate all the strings
5036  */
5037 static int get_array_idx(char *rule, char *format, int **array)
5038 {
5039         char *start, *end, *ptr;
5040         unsigned int lo, hi, step;
5041         int array_sz = 0;
5042         int i, array_idx;
5043         int rc;
5044
5045         start = strchr(rule, '[');
5046         end = strchr(rule, ']');
5047         if ((!start) || (!end)) {
5048                 *array = malloc(sizeof(int));
5049                 if (!*array)
5050                         return 0;
5051                 strcpy(format, rule);
5052                 array_sz = 1;
5053                 return array_sz;
5054         }
5055         *start = '\0';
5056         *end = '\0';
5057         end++;
5058         start++;
5059         /* put in format the printf format (the rule without the range) */
5060         sprintf(format, "%s%%.4x%s", rule, end);
5061
5062         array_idx = 0;
5063         array_sz = 0;
5064         *array = NULL;
5065         /* loop on , separator */
5066         do {
5067                 /* extract the 3 fields */
5068                 rc = sscanf(start, "%x-%x/%u", &lo, &hi, &step);
5069                 switch (rc) {
5070                 case 0:
5071                         goto err;
5072                 case 1: {
5073                         void *tmp;
5074
5075                         array_sz++;
5076                         tmp = realloc(*array, array_sz * sizeof(int));
5077                         if (!tmp)
5078                                 goto err;
5079                         *array = tmp;
5080                         (*array)[array_idx] = lo;
5081                         array_idx++;
5082                         break;
5083                 }
5084                 case 2: {
5085                         step = 1;
5086                         /* do not break to share code with case 3: */
5087                 }
5088                 case 3: {
5089                         void *tmp;
5090
5091                         if ((hi < lo) || (step == 0))
5092                                 goto err;
5093                         array_sz += (hi - lo) / step + 1;
5094                         tmp = realloc(*array, array_sz * sizeof(int));
5095                         if (!tmp)
5096                                 goto err;
5097                         *array = tmp;
5098                         for (i = lo; i <= hi; i += step, array_idx++)
5099                                 (*array)[array_idx] = i;
5100                         break;
5101                 }
5102                 }
5103                 ptr = strchr(start, ',');
5104                 if (ptr)
5105                         start = ptr + 1;
5106
5107         } while (ptr);
5108         return array_sz;
5109 err:
5110         if (*array) {
5111                 free(*array);
5112                 *array = NULL;
5113         }
5114         return 0;
5115 }
5116
5117 struct llog_pool_name {
5118         char lpn_name[UUID_MAX];
5119         struct list_head lpn_list;
5120 };
5121
5122 struct llog_pool_list_data {
5123         char lpld_fsname[LUSTRE_MAXFSNAME + 1];
5124         char lpld_poolname[LOV_MAXPOOLNAME + 1];
5125         bool lpld_exists;
5126         struct list_head lpld_list_head;
5127 };
5128
5129 /**
5130  * Callback to list pool information in llog
5131  * - { index: 74, event: new_pool, device: tfs-clilov, fsname: tfs, pool: tmp }
5132  * - { index: 77, event: add_pool, device: tfs-clilov, fsname: tfs, pool: tmp,
5133  *     ost: tfs-OST0000_UUID }
5134  * - { index: 224, event: remove_pool, device: tfs-clilov, fsname: tfs,
5135  *     pool: tmp, ost: tfs-OST0003_UUID }
5136  * - { index: 227, event: del_pool, device: tfs-clilov, fsname: tfs, pool: tmp }
5137  *
5138  * \param record[in]    pointer to llog record
5139  * \param data[in]      pointer to struct llog_pool_list_data
5140  *
5141  * \retval              0 on success
5142  *                      <0 on error
5143  */
5144 static int llog_poollist_cb(const char *record, void *data)
5145 {
5146         struct llog_pool_list_data *lpld = data;
5147         char pool_filter[MAX_STRING_SIZE] = "";
5148         char *new_record, *del_record, *del_pool, *found;
5149         char type[10] = "";
5150         int filter_len, rc = 0;
5151
5152         filter_len = snprintf(pool_filter, sizeof(pool_filter), " fsname: %s,",
5153                               lpld->lpld_fsname);
5154         if (lpld->lpld_poolname[0] == '\0') {
5155                 new_record = get_event_filter(LCFG_POOL_NEW);
5156                 del_record = get_event_filter(LCFG_POOL_DEL);
5157                 strncpy(type, " pool: ", sizeof(type));
5158         } else {
5159                 filter_len += snprintf(pool_filter + filter_len,
5160                                        sizeof(pool_filter) - filter_len,
5161                                        " pool: %s", lpld->lpld_poolname);
5162                 new_record = get_event_filter(LCFG_POOL_ADD);
5163                 del_record = get_event_filter(LCFG_POOL_REM);
5164                 strncpy(type, " ost: ", sizeof(type));
5165         }
5166         del_pool = get_event_filter(LCFG_POOL_DEL);
5167
5168         if (!new_record || !del_record || !del_pool) {
5169                 rc = -ENOMEM;
5170                 goto out;
5171         }
5172
5173         found = strstr(record, pool_filter);
5174         if (found &&
5175             (found[filter_len] == ' ' || found[filter_len] == ',')) {
5176                 struct llog_pool_name *tmp = NULL;
5177                 struct list_head *head = &lpld->lpld_list_head;
5178                 char *name;
5179                 int name_len, type_len = strlen(type);
5180
5181                 lpld->lpld_exists = true;
5182                 if (strstr(record, new_record)) {
5183                         name = strstr(record, type);
5184                         /* 2 bytes for " }" */
5185                         name_len = strlen(name) - type_len - 2;
5186                         if (name_len <= 0 || name_len > sizeof(tmp->lpn_name))
5187                                 return -EINVAL;
5188                         tmp = malloc(sizeof(struct llog_pool_name));
5189                         if (!tmp) {
5190                                 rc = -ENOMEM;
5191                                 goto out;
5192                         }
5193                         memset(tmp, 0, sizeof(struct llog_pool_name));
5194                         strncpy(tmp->lpn_name, name + type_len, name_len);
5195                         list_add_tail(&tmp->lpn_list, &lpld->lpld_list_head);
5196                 } else if (strstr(record, del_record)) {
5197                         name = strstr(record, type);
5198                         name_len = strlen(name) - type_len - 2;
5199                         list_for_each_entry(tmp, head, lpn_list) {
5200                                 if (strncmp(tmp->lpn_name, name + type_len,
5201                                             name_len) == 0 &&
5202                                             tmp->lpn_name[name_len] == '\0') {
5203                                         list_del(&tmp->lpn_list);
5204                                         free(tmp);
5205                                         break;
5206                                 }
5207                         }
5208                 }
5209                 /* verify if the specified pool still exists */
5210                 if (lpld->lpld_poolname[0] && strstr(record, del_pool))
5211                         lpld->lpld_exists = false;
5212         }
5213 out:
5214         if (new_record)
5215                 free(new_record);
5216         if (del_record)
5217                 free(del_record);
5218         if (del_pool)
5219                 free(del_pool);
5220
5221         return rc;
5222 }
5223
5224 /**
5225  * List pool information by config log
5226  *
5227  * \param fsname[in]    pointer to filesystem name
5228  * \param poolname[in]  pointer to pool name
5229  *
5230  * \retval              0 on success
5231  *                      < 0 on error
5232  */
5233 int llog_poollist(char *fsname, char *poolname)
5234 {
5235         char logname[MAX_OBD_NAME] = {'\0'};
5236         struct llog_pool_list_data lpld;
5237         struct llog_pool_name *tmp;
5238         struct list_head *head;
5239         int rc = 0;
5240
5241         if (fsname && fsname[0] == '\0')
5242                 fsname = NULL;
5243         if (!fsname)
5244                 return -EINVAL;
5245
5246         memset(&lpld, 0, sizeof(lpld));
5247         INIT_LIST_HEAD(&lpld.lpld_list_head);
5248         lpld.lpld_exists = false;
5249         strncpy(lpld.lpld_fsname, fsname, sizeof(lpld.lpld_fsname) - 1);
5250         if (poolname && poolname[0])
5251                 strncpy(lpld.lpld_poolname, poolname,
5252                         sizeof(lpld.lpld_poolname) - 1);
5253         snprintf(logname, sizeof(logname), "%s-client", fsname);
5254         rc = jt_llog_print_iter(logname, 0, -1, llog_poollist_cb, &lpld, false,
5255                                 false);
5256
5257         if (poolname && poolname[0])
5258                 printf("Pool: %s.%s\n", fsname, poolname);
5259         else
5260                 printf("Pools from %s:\n", fsname);
5261
5262         head = &lpld.lpld_list_head;
5263         if (poolname && poolname[0] && !lpld.lpld_exists && list_empty(head))
5264                 return -ENOENT;
5265
5266         list_for_each_entry(tmp, head, lpn_list) {
5267                 if (poolname && poolname[0])
5268                         printf("%s\n", tmp->lpn_name);
5269                 else
5270                         printf("%s.%s\n", fsname, tmp->lpn_name);
5271                 list_del(&tmp->lpn_list);
5272                 free(tmp);
5273         }
5274
5275         return rc;
5276 }
5277
5278 static bool get_pools_path(char *fsname)
5279 {
5280         glob_t path;
5281         int rc;
5282
5283         rc = cfs_get_param_paths(&path, "lov/%s-*/pools", fsname);
5284         if (!rc)
5285                 cfs_free_param_data(&path);
5286
5287         return (rc == 0);
5288 }
5289
5290 static int extract_fsname_poolname(char **argv, char *fsname,
5291                                    char *poolname)
5292 {
5293         char *cmd = argv[0], *param = argv[1];
5294         char *ptr;
5295         int rc;
5296
5297         snprintf(fsname, PATH_MAX + 1, "%s", param);
5298         ptr = strchr(fsname, '.');
5299         if (!ptr) {
5300                 if (strcmp(cmd, "pool_list") == 0) {
5301                         poolname = NULL;
5302                         goto out;
5303                 }
5304                 fprintf(stderr, ". is missing in %s\n", fsname);
5305                 rc = -EINVAL;
5306                 goto err;
5307         }
5308
5309         if ((ptr - fsname) == 0) {
5310                 fprintf(stderr, "fsname is empty\n");
5311                 rc = -EINVAL;
5312                 goto err;
5313         }
5314
5315         *ptr = '\0';
5316         ++ptr;
5317
5318         if (strlen(ptr) == 0) {
5319                 fprintf(stderr, "poolname is empty\n");
5320                 rc = -EINVAL;
5321                 goto err;
5322         }
5323
5324         strncpy(poolname, ptr, LOV_MAXPOOLNAME);
5325         poolname[LOV_MAXPOOLNAME] = '\0';
5326
5327         if (strncmp(poolname, "none", LOV_MAXPOOLNAME) == 0) {
5328                 fprintf(stderr, "poolname cannot be 'none'\n");
5329                 return -EINVAL;
5330         }
5331 out:
5332         return 0;
5333
5334 err:
5335         fprintf(stderr, "argument %s must be <fsname>.<poolname>\n", param);
5336         return rc;
5337 }
5338
5339 int jt_pool_cmd(int argc, char **argv)
5340 {
5341         enum lcfg_command_type cmd;
5342         char fsname[PATH_MAX + 1];
5343         char poolname[LOV_MAXPOOLNAME + 1];
5344         char *ostnames_buf = NULL;
5345         int i, rc;
5346         int *array = NULL, array_sz;
5347         struct {
5348                 int     rc;
5349                 char   *ostname;
5350         } *cmds = NULL;
5351
5352         switch (argc) {
5353         case 0:
5354         case 1: return CMD_HELP;
5355         case 2: {
5356                 rc = extract_fsname_poolname(argv, fsname, poolname);
5357                 if (rc)
5358                         break;
5359
5360                 if (strcmp("pool_new", argv[0]) == 0) {
5361                         cmd = LCFG_POOL_NEW;
5362                 } else if (strcmp("pool_destroy", argv[0]) == 0) {
5363                         cmd = LCFG_POOL_DEL;
5364                 } else if (strcmp("pool_list", argv[0]) == 0) {
5365                         if (get_pools_path(fsname))
5366                                 return llapi_poollist(argv[1]);
5367                         if (get_mgs_device() > 0)
5368                                 return llog_poollist(fsname, poolname);
5369                         fprintf(stderr,
5370                                 "Cannot run pool_list command since there is no local MGS/MDT or client\n");
5371                         return CMD_HELP;
5372                 } else {
5373                         return CMD_HELP;
5374                 }
5375
5376                 rc = pool_cmd(cmd, argv[0], argv[1], fsname, poolname, NULL);
5377                 if (rc)
5378                         break;
5379
5380                 check_pool_cmd_result(cmd, fsname, poolname, NULL);
5381                 break;
5382         }
5383         default: {
5384                 char format[2 * MAX_OBD_NAME];
5385
5386                 if (strcmp("pool_remove", argv[0]) == 0)
5387                         cmd = LCFG_POOL_REM;
5388                 else if (strcmp("pool_add", argv[0]) == 0)
5389                         cmd = LCFG_POOL_ADD;
5390                 else
5391                         return CMD_HELP;
5392
5393                 rc = extract_fsname_poolname(argv, fsname, poolname);
5394                 if (rc)
5395                         break;
5396
5397                 for (i = 2; i < argc; i++) {
5398                         int j;
5399
5400                         array_sz = get_array_idx(argv[i], format, &array);
5401                         if (array_sz == 0)
5402                                 return CMD_HELP;
5403
5404                         cmds = malloc(array_sz * sizeof(cmds[0]));
5405                         if (cmds) {
5406                                 ostnames_buf = malloc(array_sz *
5407                                                       (MAX_OBD_NAME + 1));
5408                         } else {
5409                                 free(array);
5410                                 rc = -ENOMEM;
5411                                 goto out;
5412                         }
5413
5414                         for (j = 0; j < array_sz; j++) {
5415                                 char ostname[MAX_OBD_NAME + 1];
5416                                 int rc2;
5417
5418                                 snprintf(ostname, MAX_OBD_NAME, format,
5419                                          array[j]);
5420                                 ostname[MAX_OBD_NAME] = '\0';
5421
5422                                 rc2 = check_and_complete_ostname(fsname,
5423                                                                 ostname);
5424                                 if (rc2) {
5425                                         free(array);
5426                                         free(cmds);
5427                                         if (ostnames_buf)
5428                                                 free(ostnames_buf);
5429                                         rc = rc ? rc : rc2;
5430                                         goto out;
5431                                 }
5432                                 if (ostnames_buf) {
5433                                         cmds[j].ostname =
5434                                         &ostnames_buf[(MAX_OBD_NAME + 1) * j];
5435                                         strcpy(cmds[j].ostname, ostname);
5436                                 } else {
5437                                         cmds[j].ostname = NULL;
5438                                 }
5439                                 cmds[j].rc = pool_cmd(cmd, argv[0], argv[1],
5440                                                       fsname, poolname,
5441                                                       ostname);
5442                                 /* Return an err if any of the add/dels fail */
5443                                 if (!rc)
5444                                         rc = cmds[j].rc;
5445                         }
5446                         for (j = 0; j < array_sz; j++) {
5447                                 if (!cmds[j].rc) {
5448                                         char ostname[MAX_OBD_NAME + 1];
5449
5450                                         if (!cmds[j].ostname) {
5451                                                 snprintf(ostname, MAX_OBD_NAME,
5452                                                          format, array[j]);
5453                                                 ostname[MAX_OBD_NAME] = '\0';
5454                                                 check_and_complete_ostname(
5455                                                         fsname, ostname);
5456                                         } else {
5457                                                 strcpy(ostname,
5458                                                        cmds[j].ostname);
5459                                         }
5460                                         check_pool_cmd_result(cmd, fsname,
5461                                                               poolname,
5462                                                               ostname);
5463                                 }
5464                         }
5465                         if (array_sz > 0)
5466                                 free(array);
5467                         if (cmds)
5468                                 free(cmds);
5469                         if (ostnames_buf)
5470                                 free(ostnames_buf);
5471                 }
5472                 fallthrough;
5473         }
5474         } /* switch */
5475
5476 out:
5477         if (rc != 0) {
5478                 errno = -rc;
5479                 perror(argv[0]);
5480         }
5481
5482         return rc;
5483 }
5484
5485 #ifdef HAVE_SERVER_SUPPORT
5486 static const char *barrier_status2name(enum barrier_status status)
5487 {
5488         switch (status) {
5489         case BS_INIT:
5490                 return "init";
5491         case BS_FREEZING_P1:
5492                 return "freezing_p1";
5493         case BS_FREEZING_P2:
5494                 return "freezing_p2";
5495         case BS_FROZEN:
5496                 return "frozen";
5497         case BS_THAWING:
5498                 return "thawing";
5499         case BS_THAWED:
5500                 return "thawed";
5501         case BS_FAILED:
5502                 return "failed";
5503         case BS_EXPIRED:
5504                 return "expired";
5505         case BS_RESCAN:
5506                 return "rescan";
5507         default:
5508                 return "unknown";
5509         }
5510 }
5511
5512 int jt_barrier_freeze(int argc, char **argv)
5513 {
5514         struct obd_ioctl_data data;
5515         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
5516         struct barrier_ctl bc;
5517         int rc;
5518
5519         if (argc < 2 || argc > 3)
5520                 return CMD_HELP;
5521
5522         memset(&data, 0, sizeof(data));
5523         rc = data.ioc_dev = get_mgs_device();
5524         if (rc < 0)
5525                 return rc;
5526
5527         memset(&bc, 0, sizeof(bc));
5528         bc.bc_version = BARRIER_VERSION_V1;
5529         bc.bc_cmd = BC_FREEZE;
5530         if (argc == 3)
5531                 bc.bc_timeout = atoi(argv[2]);
5532         if (bc.bc_timeout == 0)
5533                 bc.bc_timeout = BARRIER_TIMEOUT_DEFAULT;
5534
5535         if (strlen(argv[1]) > 8) {
5536                 fprintf(stderr,
5537                         "%s: fsname name %s is too long. It should not exceed 8.\n",
5538                         argv[0], argv[1]);
5539                 return -EINVAL;
5540         }
5541
5542         strncpy(bc.bc_name, argv[1], sizeof(bc.bc_name));
5543         data.ioc_inlbuf1 = (char *)&bc;
5544         data.ioc_inllen1 = sizeof(bc);
5545         memset(buf, 0, sizeof(rawbuf));
5546         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
5547         if (rc) {
5548                 fprintf(stderr, "Fail to pack ioctl data: rc = %d.\n", rc);
5549                 return rc;
5550         }
5551
5552         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_BARRIER, buf);
5553         if (rc < 0)
5554                 fprintf(stderr, "Fail to freeze barrier for %s: %s\n",
5555                         argv[1], strerror(errno));
5556
5557         return rc;
5558 }
5559
5560 int jt_barrier_thaw(int argc, char **argv)
5561 {
5562         struct obd_ioctl_data data;
5563         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
5564         struct barrier_ctl bc;
5565         int rc;
5566
5567         if (argc != 2)
5568                 return CMD_HELP;
5569
5570         memset(&data, 0, sizeof(data));
5571         rc = data.ioc_dev = get_mgs_device();
5572         if (rc < 0)
5573                 return rc;
5574
5575         memset(&bc, 0, sizeof(bc));
5576         bc.bc_version = BARRIER_VERSION_V1;
5577         bc.bc_cmd = BC_THAW;
5578
5579         if (strlen(argv[1]) > 8) {
5580                 fprintf(stderr,
5581                         "fsname name %s is too long. It should not exceed 8.\n",
5582                         argv[1]);
5583                 return -EINVAL;
5584         }
5585
5586         strncpy(bc.bc_name, argv[1], sizeof(bc.bc_name));
5587         data.ioc_inlbuf1 = (char *)&bc;
5588         data.ioc_inllen1 = sizeof(bc);
5589         memset(buf, 0, sizeof(rawbuf));
5590         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
5591         if (rc) {
5592                 fprintf(stderr, "Fail to pack ioctl data: rc = %d.\n", rc);
5593                 return rc;
5594         }
5595
5596         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_BARRIER, buf);
5597         if (rc < 0)
5598                 fprintf(stderr, "Fail to thaw barrier for %s: %s\n",
5599                         argv[1], strerror(errno));
5600
5601         return rc;
5602 }
5603
5604 int __jt_barrier_stat(const char *fsname, struct barrier_ctl *bc)
5605 {
5606         struct obd_ioctl_data data;
5607         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
5608         int rc;
5609
5610         memset(&data, 0, sizeof(data));
5611         rc = data.ioc_dev = get_mgs_device();
5612         if (rc < 0)
5613                 return rc;
5614
5615         memset(bc, 0, sizeof(*bc));
5616         bc->bc_version = BARRIER_VERSION_V1;
5617         bc->bc_cmd = BC_STAT;
5618         strncpy(bc->bc_name, fsname, sizeof(bc->bc_name) - 1);
5619         data.ioc_inlbuf1 = (char *)bc;
5620         data.ioc_inllen1 = sizeof(*bc);
5621         memset(buf, 0, sizeof(rawbuf));
5622         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
5623         if (rc) {
5624                 fprintf(stderr, "Fail to pack ioctl data: rc = %d.\n", rc);
5625                 return rc;
5626         }
5627
5628         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_BARRIER, buf);
5629         if (rc < 0)
5630                 fprintf(stderr, "Fail to query barrier for %s: %s\n",
5631                         fsname, strerror(errno));
5632         else
5633                 llapi_ioctl_unpack(&data, buf, sizeof(rawbuf));
5634
5635         return rc;
5636 }
5637
5638 int jt_barrier_stat(int argc, char **argv)
5639 {
5640         struct barrier_ctl bc;
5641         static struct option long_opt_barrier_stat[] = {
5642                 {
5643                         .val            = 's',
5644                         .name           = "state",
5645                         .has_arg        = no_argument,
5646                 },
5647                 {       .val            = 't',
5648                         .name           = "timeout",
5649                         .has_arg        = no_argument,
5650                 },
5651                 {
5652                         NULL
5653                 }
5654         };
5655         const char *name;
5656         int index;
5657         int opt;
5658         int rc;
5659         bool state = false;
5660         bool timeout = false;
5661
5662         while ((opt = getopt_long(argc, argv, "st", long_opt_barrier_stat,
5663                                   &index)) != EOF) {
5664                 switch (opt) {
5665                 case 's':
5666                         state = true;
5667                         break;
5668                 case 't':
5669                         timeout = true;
5670                         break;
5671                 default:
5672                         return CMD_HELP;
5673                 }
5674         }
5675
5676         if (optind >= argc)
5677                 return CMD_HELP;
5678
5679         name = argv[optind];
5680         if (strlen(name) > 8) {
5681                 fprintf(stderr,
5682                         "fsname name %s is too long. It should not exceed 8.\n",
5683                         name);
5684                 return -EINVAL;
5685         }
5686
5687         rc = __jt_barrier_stat(name, &bc);
5688         if (!rc) {
5689                 if (state && !timeout)
5690                         printf("%s\n", barrier_status2name(bc.bc_status));
5691                 else if (timeout && !state)
5692                         printf("%d\n",
5693                                (bc.bc_status == BS_FREEZING_P1 ||
5694                                 bc.bc_status == BS_FREEZING_P2 ||
5695                                 bc.bc_status == BS_FROZEN) ?
5696                                bc.bc_timeout : 0);
5697                 else
5698                         printf("state: %s\ntimeout: %d seconds\n",
5699                                barrier_status2name(bc.bc_status),
5700                                (bc.bc_status == BS_FREEZING_P1 ||
5701                                 bc.bc_status == BS_FREEZING_P2 ||
5702                                 bc.bc_status == BS_FROZEN) ?
5703                                bc.bc_timeout : 0);
5704         }
5705
5706         return rc;
5707 }
5708
5709 int jt_barrier_rescan(int argc, char **argv)
5710 {
5711         struct obd_ioctl_data data;
5712         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
5713         struct barrier_ctl bc;
5714         int rc;
5715
5716         if (argc < 2 || argc > 3)
5717                 return CMD_HELP;
5718
5719         memset(&data, 0, sizeof(data));
5720         rc = data.ioc_dev = get_mgs_device();
5721         if (rc < 0)
5722                 return rc;
5723
5724         memset(&bc, 0, sizeof(bc));
5725         bc.bc_version = BARRIER_VERSION_V1;
5726         bc.bc_cmd = BC_RESCAN;
5727         if (argc == 3)
5728                 bc.bc_timeout = atoi(argv[2]);
5729         if (bc.bc_timeout == 0)
5730                 bc.bc_timeout = BARRIER_TIMEOUT_DEFAULT;
5731
5732         if (strlen(argv[1]) > 8) {
5733                 fprintf(stderr,
5734                         "fsname name %s is too long. It should not exceed 8.\n",
5735                         argv[1]);
5736                 return -EINVAL;
5737         }
5738
5739         strncpy(bc.bc_name, argv[1], sizeof(bc.bc_name));
5740         data.ioc_inlbuf1 = (char *)&bc;
5741         data.ioc_inllen1 = sizeof(bc);
5742         memset(buf, 0, sizeof(rawbuf));
5743         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
5744         if (rc) {
5745                 fprintf(stderr, "Fail to pack ioctl data: rc = %d.\n", rc);
5746                 return rc;
5747         }
5748
5749         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_BARRIER, buf);
5750         if (rc < 0) {
5751                 fprintf(stderr, "Fail to rescan barrier bitmap for %s: %s\n",
5752                         argv[1], strerror(errno));
5753         } else {
5754                 llapi_ioctl_unpack(&data, buf, sizeof(rawbuf));
5755                 printf("%u of %u MDT(s) in the filesystem %s are inactive\n",
5756                        bc.bc_absence, bc.bc_total, argv[1]);
5757         }
5758
5759         return rc;
5760 }
5761 #endif /* HAVE_SERVER_SUPPORT */
5762
5763 int jt_get_obj_version(int argc, char **argv)
5764 {
5765         struct lu_fid fid;
5766         struct obd_ioctl_data data;
5767         __u64 version, id = ULLONG_MAX, group = ULLONG_MAX;
5768         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf, *fidstr;
5769         int rc, c;
5770
5771         while ((c = getopt(argc, argv, "i:g:")) != -1) {
5772                 switch (c) {
5773                 case 'i':
5774                         id = strtoull(optarg, NULL, 0);
5775                         break;
5776                 case 'g':
5777                         group = strtoull(optarg, NULL, 0);
5778                         break;
5779                 default:
5780                         return CMD_HELP;
5781                 }
5782         }
5783
5784         argc -= optind;
5785         fidstr = *(argv + optind);
5786
5787         if (!(id != ULLONG_MAX && group != ULLONG_MAX && argc == 0) &&
5788             !(id == ULLONG_MAX && group == ULLONG_MAX && argc == 1))
5789                 return CMD_HELP;
5790
5791         memset(&data, 0, sizeof(data));
5792         data.ioc_dev = cur_device;
5793         if (argc == 1) {
5794                 rc = llapi_fid_parse(fidstr, &fid, NULL);
5795                 if (rc) {
5796                         fprintf(stderr, "%s: error parsing FID '%s': %s\n",
5797                                 jt_cmdname(argv[0]), fidstr, strerror(-rc));
5798                         return rc;
5799                 }
5800
5801                 data.ioc_inlbuf1 = (char *)&fid;
5802                 data.ioc_inllen1 = sizeof(fid);
5803         } else {
5804                 data.ioc_inlbuf3 = (char *)&id;
5805                 data.ioc_inllen3 = sizeof(id);
5806                 data.ioc_inlbuf4 = (char *)&group;
5807                 data.ioc_inllen4 = sizeof(group);
5808         }
5809         data.ioc_inlbuf2 = (char *)&version;
5810         data.ioc_inllen2 = sizeof(version);
5811
5812         memset(buf, 0, sizeof(*buf));
5813         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
5814         if (rc) {
5815                 fprintf(stderr, "error: %s: packing ioctl arguments: %s\n",
5816                         jt_cmdname(argv[0]), strerror(-rc));
5817                 return rc;
5818         }
5819
5820         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_GET_OBJ_VERSION, buf);
5821         if (rc) {
5822                 fprintf(stderr, "error: %s: ioctl: %s\n",
5823                         jt_cmdname(argv[0]), strerror(errno));
5824                 return -errno;
5825         }
5826
5827         llapi_ioctl_unpack(&data, buf, sizeof(rawbuf));
5828         printf("%#jx\n", (uintmax_t)version);
5829
5830         return 0;
5831 }
5832
5833 #ifdef HAVE_SERVER_SUPPORT
5834 int jt_changelog_register(int argc, char **argv)
5835 {
5836         struct option long_opts[] = {
5837         { .val = 'h', .name = "help", .has_arg = no_argument },
5838         { .val = 'm', .name = "mask", .has_arg = required_argument },
5839         { .val = 'n', .name = "nameonly", .has_arg = no_argument },
5840         { .val = 'u', .name = "user", .has_arg = required_argument },
5841         { .name = NULL } };
5842         struct obd_ioctl_data data = { 0 };
5843         char rawbuf[MAX_IOC_BUFLEN] = "";
5844         char *buf = rawbuf;
5845         char *device = lcfg_get_devname();
5846         char *username = NULL, *usermask = NULL;
5847         bool print_name_only = false;
5848         int c;
5849         int rc;
5850
5851         if (cur_device < 0 || !device)
5852                 return CMD_HELP;
5853
5854         while ((c = getopt_long(argc, argv, "hm:nu:", long_opts, NULL)) != -1) {
5855                 switch (c) {
5856                 case 'm':
5857                         usermask = strdup(optarg);
5858                         if (!usermask) {
5859                                 fprintf(stderr,
5860                                         "error: %s: %s: cannot copy '%s'\n",
5861                                         jt_cmdname(argv[0]), strerror(errno),
5862                                         optarg);
5863                                 return -errno;
5864                         }
5865                         break;
5866                 case 'n':
5867                         print_name_only = true;
5868                         break;
5869                 case 'u':
5870                         username = strdup(optarg);
5871                         if (!username) {
5872                                 fprintf(stderr,
5873                                         "error: %s: %s: cannot copy '%s'\n",
5874                                         jt_cmdname(argv[0]), strerror(errno),
5875                                         optarg);
5876                                 return -errno;
5877                         }
5878                         break;
5879                 case 'h':
5880                 default:
5881                         free(username);
5882                         free(usermask);
5883                         return CMD_HELP;
5884                 }
5885         }
5886
5887         data.ioc_dev = cur_device;
5888         if (username) {
5889                 data.ioc_inlbuf1 = username;
5890                 data.ioc_inllen1 = strlen(username) + 1;
5891         }
5892
5893         if (usermask) {
5894                 data.ioc_inlbuf2 = usermask;
5895                 data.ioc_inllen2 = strlen(usermask) + 1;
5896         }
5897
5898         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
5899         if (rc < 0) {
5900                 fprintf(stderr, "error: %s: cannot pack ioctl: %s\n",
5901                         jt_cmdname(argv[0]), strerror(-rc));
5902                 goto out;
5903         }
5904         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_CHANGELOG_REG, buf);
5905         if (rc < 0) {
5906                 rc = -errno;
5907                 fprintf(stderr, "error: %s: %s\n", jt_cmdname(argv[0]),
5908                         rc == -EEXIST ? "User exists" : strerror(-rc));
5909                 goto out;
5910         }
5911
5912         llapi_ioctl_unpack(&data, buf, sizeof(rawbuf));
5913
5914         if (data.ioc_u32_1 == 0) {
5915                 fprintf(stderr, "received invalid userid!\n");
5916                 rc = -EPROTO;
5917                 goto out;
5918         }
5919
5920         if (print_name_only)
5921                 printf("%s%u%s%s\n", CHANGELOG_USER_PREFIX, data.ioc_u32_1,
5922                        username ? "-" : "", username ? : "");
5923         else
5924                 printf("%s: Registered changelog userid '%s%u%s%s'\n",
5925                        device, CHANGELOG_USER_PREFIX, data.ioc_u32_1,
5926                        username ? "-" : "", username ? : "");
5927 out:
5928         free(usermask);
5929         free(username);
5930         return rc;
5931 }
5932
5933 int jt_changelog_deregister(int argc, char **argv)
5934 {
5935         struct option long_opts[] = {
5936         { .val = 'h', .name = "help", .has_arg = no_argument },
5937         { .val = 'u', .name = "user", .has_arg = required_argument },
5938         { .name = NULL } };
5939         struct obd_ioctl_data data = { 0 };
5940         char rawbuf[MAX_IOC_BUFLEN] = "";
5941         char *buf = rawbuf;
5942         char *device = lcfg_get_devname();
5943         char *username = NULL;
5944         int id = 0;
5945         int c, rc;
5946
5947         if (cur_device < 0 || !device)
5948                 return CMD_HELP;
5949
5950         while ((c = getopt_long(argc, argv, "hu:", long_opts, NULL)) != -1) {
5951                 switch (c) {
5952                 case 'u':
5953                         username = strdup(optarg);
5954                         if (!username) {
5955                                 fprintf(stderr,
5956                                         "error: %s: %s: cannot copy '%s'\n",
5957                                         jt_cmdname(argv[0]), strerror(errno),
5958                                         optarg);
5959                                 return -errno;
5960                         }
5961                         break;
5962                 case 'h':
5963                 default:
5964                         free(username);
5965                         return CMD_HELP;
5966                 }
5967         }
5968
5969         if (1 == optind && argc > 1) {
5970                 /* first check if pure ID was passed */
5971                 id = atoi(argv[optind]);
5972                 /* nameless cl<ID> format or cl<ID>-... format, only ID matters */
5973                 if (id == 0)
5974                         sscanf(argv[optind], CHANGELOG_USER_PREFIX"%d", &id);
5975
5976                 /* no valid ID was parsed */
5977                 if (id <= 0) {
5978                         rc = -EINVAL;
5979                         fprintf(stderr,
5980                                 "error: %s: expect <ID> or cl<ID>[-name] got '%s'\n",
5981                                 strerror(-rc), argv[optind]);
5982                         return CMD_HELP;
5983                 }
5984                 optind++;
5985         }
5986
5987         if (optind < argc || argc == 1)
5988                 return CMD_HELP;
5989
5990         data.ioc_dev = cur_device;
5991         data.ioc_u32_1 = id;
5992         if (username) {
5993                 data.ioc_inlbuf1 = username;
5994                 data.ioc_inllen1 = strlen(username) + 1;
5995         }
5996
5997         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
5998         if (rc < 0) {
5999                 fprintf(stderr, "error: %s: invalid ioctl\n",
6000                         jt_cmdname(argv[0]));
6001                 return rc;
6002         }
6003
6004         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_CHANGELOG_DEREG, buf);
6005         if (rc < 0) {
6006                 rc = -errno;
6007                 fprintf(stderr, "error: %s: %s\n", jt_cmdname(argv[0]),
6008                         rc == -ENOENT ? "User not found" : strerror(-rc));
6009                 return rc;
6010         }
6011
6012         llapi_ioctl_unpack(&data, buf, sizeof(rawbuf));
6013         printf("%s: Deregistered changelog user #%u\n", device, data.ioc_u32_1);
6014
6015         return 0;
6016 }
6017 #else /* !HAVE_SERVER_SUPPORT */
6018 int jt_changelog_register(int argc, char **argv)
6019 {
6020         fprintf(stderr, "error: %s: invalid ioctl\n",
6021                 jt_cmdname(argv[0]));
6022         return -EOPNOTSUPP;
6023 }
6024
6025 int jt_changelog_deregister(int argc, char **argv)
6026 {
6027         fprintf(stderr, "error: %s: invalid ioctl\n",
6028                 jt_cmdname(argv[0]));
6029         return -EOPNOTSUPP;
6030 }
6031 #endif /* HAVE_SERVER_SUPPORT */
6032
6033 int jt_pcc_add(int argc, char **argv)
6034 {
6035         struct option long_opts[] = {
6036                 { .val = 'p', .name = "param", .has_arg = required_argument },
6037                 { .name = NULL } };
6038         const char *mntpath;
6039         const char *pccpath;
6040         char *param = NULL;
6041         char cmd[PATH_MAX];
6042         int rc;
6043
6044         optind = 1;
6045         while ((rc = getopt_long(argc, argv, "p:", long_opts, NULL)) != -1) {
6046                 switch (rc) {
6047                 case 'p':
6048                         param = optarg;
6049                         break;
6050                 default:
6051                         return CMD_HELP;
6052                 }
6053         }
6054
6055         if (!param) {
6056                 fprintf(stderr, "%s: must specify the config param for PCC\n",
6057                         jt_cmdname(argv[0]));
6058                 return CMD_HELP;
6059         }
6060
6061         if (optind + 2 != argc) {
6062                 fprintf(stderr,
6063                         "%s: must specify mount path and PCC path %d:%d\n",
6064                         jt_cmdname(argv[0]), optind, argc);
6065                 return CMD_HELP;
6066         }
6067
6068         mntpath = argv[optind++];
6069         pccpath = argv[optind];
6070
6071         snprintf(cmd, PATH_MAX, "add %s %s", pccpath, param);
6072         rc = llapi_pccdev_set(mntpath, cmd);
6073         if (rc < 0)
6074                 fprintf(stderr, "%s: failed to run '%s' on %s\n",
6075                         jt_cmdname(argv[0]), cmd, mntpath);
6076
6077         return rc;
6078 }
6079
6080 int jt_pcc_del(int argc, char **argv)
6081 {
6082         const char *mntpath;
6083         const char *pccpath;
6084         char cmd[PATH_MAX];
6085         int rc;
6086
6087         optind = 1;
6088         if (argc != 3) {
6089                 fprintf(stderr, "%s: require 3 arguments\n",
6090                         jt_cmdname(argv[0]));
6091                 return CMD_HELP;
6092         }
6093
6094         mntpath = argv[optind++];
6095         pccpath = argv[optind++];
6096
6097         snprintf(cmd, PATH_MAX, "del %s", pccpath);
6098         rc = llapi_pccdev_set(mntpath, cmd);
6099         if (rc < 0)
6100                 fprintf(stderr, "%s: failed to run '%s' on %s\n",
6101                         jt_cmdname(argv[0]), cmd, mntpath);
6102
6103         return rc;
6104 }
6105
6106 int jt_pcc_clear(int argc, char **argv)
6107 {
6108         const char *mntpath;
6109         int rc;
6110
6111         optind = 1;
6112         if (argc != 2) {
6113                 fprintf(stderr, "%s: require 2 arguments\n",
6114                         jt_cmdname(argv[0]));
6115                 return CMD_HELP;
6116         }
6117
6118         mntpath = argv[optind];
6119         rc = llapi_pccdev_set(mntpath, "clear");
6120         if (rc < 0)
6121                 fprintf(stderr, "%s: failed to run 'clear' on %s\n",
6122                         jt_cmdname(argv[0]), mntpath);
6123
6124         return rc;
6125 }
6126
6127 int jt_pcc_list(int argc, char **argv)
6128 {
6129         const char *mntpath;
6130         int rc;
6131
6132         optind = 1;
6133         if (argc != 2) {
6134                 fprintf(stderr, "%s: require 2 arguments\n",
6135                         jt_cmdname(argv[0]));
6136                 return CMD_HELP;
6137         }
6138
6139         mntpath = argv[optind];
6140         rc = llapi_pccdev_get(mntpath);
6141         if (rc < 0)
6142                 fprintf(stderr, "%s: failed to run 'pcc list' on %s\n",
6143                         jt_cmdname(argv[0]), mntpath);
6144
6145         return rc;
6146 }