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