Whamcloud - gitweb
LU-16374 enc: rename O_FILE_ENC to O_CIPHERTEXT
[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         /* coverity[uninit_use_in_call] */
3193         sigaction(SIGINT, &sigact, NULL);
3194
3195         shmem_cleanup();
3196         do_disconnect(argv[0], 1);
3197 }
3198
3199 /**
3200  * Get the index of the last llog record
3201  *
3202  * logid:            [0x3:0xa:0x0]:0
3203  * flags:            4 (plain)
3204  * records_count:    57
3205  * last_index:       57
3206  *
3207  * \param logname[in]   pointer to config log name
3208  *
3209  * \retval              > 0 on success
3210  *                      <= 0 on error
3211  */
3212 static long llog_last_index(char *logname)
3213 {
3214         struct obd_ioctl_data data = { 0 };
3215         char rawbuf[MAX_IOC_BUFLEN] = "", *buf = rawbuf;
3216         char *last_index;
3217         long rc;
3218
3219         data.ioc_dev = cur_device;
3220         data.ioc_inllen1 = strlen(logname) + 1;
3221         data.ioc_inlbuf1 = logname;
3222         data.ioc_inllen2 = sizeof(rawbuf) - __ALIGN_KERNEL(sizeof(data), 8) -
3223                            __ALIGN_KERNEL(data.ioc_inllen1, 8);
3224         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
3225         if (rc) {
3226                 fprintf(stderr, "%s: ioctl_pack failed for catalog '%s': %s\n",
3227                         __func__, logname, strerror(-rc));
3228                 return rc;
3229         }
3230
3231         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_LLOG_INFO, buf);
3232         if (rc == 0) {
3233                 last_index = strstr(((struct obd_ioctl_data *)buf)->ioc_bulk,
3234                                     "last_index:");
3235                 return strtol(last_index + 11, NULL, 10);
3236         }
3237
3238         rc = -errno;
3239
3240         return rc;
3241 }
3242
3243 static char *get_llog_event_name(__u32 cmd)
3244 {
3245 #ifdef HAVE_SERVER_SUPPORT
3246         struct lcfg_type_data *data;
3247
3248         data = lcfg_cmd2data(cmd);
3249         if (data)
3250                 return data->ltd_name;
3251 #endif
3252         return NULL;
3253 }
3254
3255 static char *get_event_filter(__u32 cmd)
3256 {
3257         char *event_name;
3258         char *filter = NULL;
3259         int len;
3260
3261         event_name = get_llog_event_name(cmd);
3262         if (event_name) {
3263                 /* 9 bytes for "event: , " */
3264                 len = 9 + strlen(event_name);
3265                 filter = malloc(len + 1);
3266                 if (!filter)
3267                         return NULL;
3268                 memset(filter, 0, len + 1);
3269                 snprintf(filter, len, "event: %s, ", event_name);
3270                 return filter;
3271         }
3272
3273         return NULL;
3274 }
3275
3276 /**
3277  * Callback to search ostname in llog
3278  * - { index: 23, event: attach, device: lustre-OST0000-osc, type: osc,
3279  *     UUID: lustre-clilov_UUID }
3280  * - { index: 24, event: setup, device: lustre-OST0000-osc,
3281  *     UUID: lustre-OST0000_UUID, node: 192.168.0.120@tcp }
3282  * - { index: 25, event: add_osc, device: lustre-clilov,
3283  *     ost: lustre-OST0000_UUID, index: 0, gen: 1 }
3284  *
3285  * \param record[in]    pointer to llog record
3286  * \param data[in]      pointer to ostname
3287  *
3288  * \retval              1 if ostname is found
3289  *                      0 if ostname is not found
3290  *                      -ENOENT if ostname is deleted
3291  */
3292 static int llog_search_ost_cb(const char *record, void *data)
3293 {
3294         char *ostname = data;
3295         char ost_filter[MAX_STRING_SIZE] = {'\0'};
3296         char *add_osc, *del_osc, *setup, *cleanup;
3297
3298         add_osc = get_event_filter(LCFG_LOV_ADD_OBD);
3299         del_osc = get_event_filter(LCFG_LOV_DEL_OBD);
3300         setup = get_event_filter(LCFG_SETUP);
3301         cleanup = get_event_filter(LCFG_CLEANUP);
3302         if (!add_osc || !del_osc || !setup || !cleanup)
3303                 return -ENOMEM;
3304
3305         if (ostname && ostname[0])
3306                 snprintf(ost_filter, sizeof(ost_filter), " %s,", ostname);
3307
3308         if (strstr(record, ost_filter)) {
3309                 if (strstr(record, add_osc) || strstr(record, setup))
3310                         return 1;
3311                 if (strstr(record, del_osc) || strstr(record, cleanup))
3312                         return -ENOENT;
3313         }
3314
3315         free(add_osc);
3316         free(del_osc);
3317         free(setup);
3318         free(cleanup);
3319
3320         return 0;
3321 }
3322
3323 /**
3324  * Search ost in llog
3325  *
3326  * \param logname[in]           pointer to config log name
3327  * \param last_index[in]        the index of the last llog record
3328  * \param ostname[in]           pointer to ost name
3329  *
3330  * \retval                      1 if ostname is found
3331  *                              0 if ostname is not found
3332  */
3333 static int llog_search_ost(char *logname, long last_index, char *ostname)
3334 {
3335         long start, end, inc = MAX_IOC_BUFLEN / 128;
3336         int rc = 0;
3337
3338         for (end = last_index; end > 1; end -= inc) {
3339                 start = end - inc > 0 ? end - inc : 1;
3340                 rc = jt_llog_print_iter(logname, start, end, llog_search_ost_cb,
3341                                         ostname, true, false);
3342                 if (rc)
3343                         break;
3344         }
3345
3346         return (rc == 1 ? 1 : 0);
3347 }
3348
3349 struct llog_del_ost_priv {
3350         char *logname;
3351         char *ostname;
3352         int found;
3353         int dryrun;
3354 };
3355
3356 /**
3357  * Callback to search and delete ostname in llog
3358  *
3359  * \param record[in]    pointer to llog record
3360  * \param data[in]      pointer to ostname
3361  *
3362  * \retval              1 if ostname is found and entry deleted
3363  *                      0 if ostname is not found
3364  *                      < 0 if error
3365  */
3366 static int llog_del_ost_cb(const char *record, void *data)
3367 {
3368         char ost_filter[MAX_STRING_SIZE] = {'\0'};
3369         char log_idxstr[MAX_STRING_SIZE] = {'\0'};
3370         long int log_idx = 0;
3371         struct llog_del_ost_priv *priv = data;
3372         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
3373         struct obd_ioctl_data ioc_data = { 0 };
3374         int rc = 0;
3375
3376         if (priv->ostname && priv->ostname[0])
3377                 snprintf(ost_filter, sizeof(ost_filter), " %s", priv->ostname);
3378
3379         if (!strstr(record, ost_filter))
3380                 return rc;
3381
3382         rc = sscanf(record, "- { index: %ld", &log_idx);
3383         if (rc < 0) {
3384                 fprintf(stderr, "error: record without index:\n%s\n",
3385                         record);
3386                 return 0;
3387         }
3388         snprintf(log_idxstr, sizeof(log_idxstr), "%ld", log_idx);
3389
3390         ioc_data.ioc_dev = cur_device;
3391         ioc_data.ioc_inllen1 = strlen(priv->logname) + 1;
3392         ioc_data.ioc_inlbuf1 = priv->logname;
3393         ioc_data.ioc_inllen3 = strlen(log_idxstr) + 1;
3394         ioc_data.ioc_inlbuf3 = log_idxstr;
3395
3396         rc = llapi_ioctl_pack(&ioc_data, &buf, sizeof(rawbuf));
3397         if (rc) {
3398                 fprintf(stderr, "ioctl_pack for catalog '%s' failed: %s\n",
3399                         ioc_data.ioc_inlbuf1, strerror(-rc));
3400                 return rc;
3401         }
3402
3403         if (priv->dryrun) {
3404                 fprintf(stdout, "[DRY RUN] cancel catalog '%s:%s':\"%s\"\n",
3405                         ioc_data.ioc_inlbuf1, ioc_data.ioc_inlbuf3, record);
3406         } else {
3407                 rc = l_ioctl(OBD_DEV_ID, OBD_IOC_LLOG_CANCEL, buf);
3408                 if (rc)
3409                         fprintf(stderr, "cancel catalog '%s:%s' failed: %s\n",
3410                                 ioc_data.ioc_inlbuf1, ioc_data.ioc_inlbuf3,
3411                                 strerror(errno));
3412                 else {
3413                         fprintf(stdout, "cancel catalog %s log_idx %ld: done\n",
3414                                 priv->logname, log_idx);
3415                         priv->found++;
3416                 }
3417         }
3418         return rc;
3419 }
3420
3421 /**
3422  * Search and delete ost in llog
3423  *
3424  * \param logname[in]           pointer to config log name
3425  * \param last_index[in]        the index of the last llog record
3426  * \param ostname[in]           pointer to ost name
3427  * \param dryrun[in]            dry run?
3428  *
3429  * \retval                      1 if ostname is found and deleted
3430  *                              0 if ostname is not found
3431  */
3432 static int llog_del_ost(char *logname, long last_index, char *ostname,
3433                         int dryrun)
3434 {
3435         long start, end, inc = MAX_IOC_BUFLEN / 128;
3436         int rc = 0;
3437         struct llog_del_ost_priv priv = { logname, ostname, false, dryrun };
3438
3439         for (end = last_index; end > 1; end -= inc) {
3440                 start = end - inc > 0 ? end - inc : 1;
3441                 rc = jt_llog_print_iter(logname, start, end, llog_del_ost_cb,
3442                                         &priv, true, false);
3443                 if (rc)
3444                         break;
3445         }
3446
3447         if (priv.found)
3448                 fprintf(stdout, "del_ost: cancelled %d catalog entries\n",
3449                         priv.found);
3450         else
3451                 fprintf(stdout, "del_ost: no catalog entry deleted\n");
3452
3453         return rc;
3454 }
3455
3456 struct llog_pool_data {
3457         char lpd_fsname[LUSTRE_MAXFSNAME + 1];
3458         char lpd_poolname[LOV_MAXPOOLNAME + 1];
3459         char lpd_ostname[MAX_OBD_NAME + 1];
3460         enum lcfg_command_type lpd_cmd_type;
3461         bool lpd_pool_exists;
3462         int lpd_ost_num;
3463 };
3464
3465 /**
3466  * Called for each formatted line in the config log (within range).
3467  *
3468  * - { index: 74, event: new_pool, device: tfs-clilov, fsname: tfs, pool: tmp }
3469  * - { index: 77, event: add_pool, device: tfs-clilov, fsname: tfs, pool: tmp,
3470  *     ost: tfs-OST0000_UUID }
3471  * - { index: 224, event: remove_pool, device: tfs-clilov, fsname: tfs,
3472  *     pool: tmp, ost: tfs-OST0003_UUID }
3473  * - { index: 227, event: del_pool, device: tfs-clilov, fsname: tfs, pool: tmp }
3474  *
3475  * \param record[in]    pointer to llog record
3476  * \param data[in]      pointer to llog_pool_data
3477  *
3478  * \retval              1 if pool or OST is found
3479  *                      0 if pool or OST is not found
3480  *                      -ENOENT if pool or OST is removed
3481  */
3482 static int llog_search_pool_cb(const char *record, void *data)
3483 {
3484         struct llog_pool_data *lpd = data;
3485         char pool_filter[MAX_STRING_SIZE] = "";
3486         char *new_pool, *del_pool, *add_pool, *rem_pool;
3487         char *found = NULL;
3488         int fs_pool_len = 0, rc = 0;
3489
3490         new_pool = get_event_filter(LCFG_POOL_NEW);
3491         del_pool = get_event_filter(LCFG_POOL_DEL);
3492         add_pool = get_event_filter(LCFG_POOL_ADD);
3493         rem_pool = get_event_filter(LCFG_POOL_REM);
3494         if (!new_pool || !del_pool || !add_pool || !rem_pool) {
3495                 rc = -ENOMEM;
3496                 goto out;
3497         }
3498
3499         fs_pool_len = 16 + strlen(lpd->lpd_fsname) + strlen(lpd->lpd_poolname);
3500         snprintf(pool_filter, fs_pool_len + 1, "fsname: %s, pool: %s",
3501                  lpd->lpd_fsname, lpd->lpd_poolname);
3502
3503         /* search poolname */
3504         found = strstr(record, pool_filter);
3505         if (found &&
3506             (found[fs_pool_len] == ' ' || found[fs_pool_len] == ',')) {
3507                 if (strstr(record, new_pool)) {
3508                         lpd->lpd_pool_exists = true;
3509                         rc = 1;
3510                         goto out;
3511                 }
3512                 if (strstr(record, del_pool)) {
3513                         lpd->lpd_pool_exists = false;
3514                         rc = -ENOENT;
3515                         goto out;
3516                 }
3517
3518                 if (lpd->lpd_cmd_type == LCFG_POOL_NEW ||
3519                     lpd->lpd_cmd_type == LCFG_POOL_DEL) {
3520                         /* In function mgs_pool_cmd(), a pool's pool_new/add
3521                          * record will be marked as "SKIP" if its pool_destroy/
3522                          * remove record is logged later. That means the "SKIP"
3523                          * record won't be printed here and thus lpd_ost_num
3524                          * doesn't need to be decreased as well.
3525                          */
3526                         if (strstr(record, add_pool))
3527                                 lpd->lpd_ost_num++;
3528                 } else if (lpd->lpd_ostname[0] != '\0') {
3529                         if (strstr(record, lpd->lpd_ostname)) {
3530                                 lpd->lpd_pool_exists = true;
3531                                 if (strstr(record, add_pool)) {
3532                                         lpd->lpd_ost_num = 1;
3533                                         rc = 1;
3534                                         goto out;
3535                                 }
3536                                 if (strstr(record, rem_pool)) {
3537                                         lpd->lpd_ost_num = 0;
3538                                         rc = -ENOENT;
3539                                         goto out;
3540                                 }
3541                         }
3542                 }
3543         }
3544 out:
3545         if (new_pool)
3546                 free(new_pool);
3547         if (del_pool)
3548                 free(del_pool);
3549         if (add_pool)
3550                 free(add_pool);
3551         if (rem_pool)
3552                 free(rem_pool);
3553
3554         return rc;
3555 }
3556
3557 /* Search pool and its ost in llog
3558  *
3559  * \param logname[in]           pointer to config log name
3560  * \param last_index[in]        the index of the last llog record
3561  * \param fsname[in]            pointer to filesystem name
3562  * \param poolname[in]          pointer pool name
3563  * \param ostname[in]           pointer to OST name(OSTnnnn-UUID)
3564  * \param cmd[in]               pool command type
3565  *
3566  * \retval                      < 0 on error
3567  *                              0 if pool is empty or OST is not found
3568  *                              1 if pool is not empty or OST is found
3569  */
3570 static int llog_search_pool(char *logname, long last_index, char *fsname,
3571                             char *poolname, char *ostname,
3572                             enum lcfg_command_type cmd)
3573 {
3574         struct llog_pool_data lpd;
3575         long start, end, inc = MAX_IOC_BUFLEN / 128;
3576         int rc = 0;
3577
3578         memset(&lpd, 0, sizeof(lpd));
3579         lpd.lpd_cmd_type = cmd;
3580         lpd.lpd_pool_exists = false;
3581         lpd.lpd_ost_num = 0;
3582         strncpy(lpd.lpd_fsname, fsname, sizeof(lpd.lpd_fsname) - 1);
3583         if (poolname && poolname[0])
3584                 strncpy(lpd.lpd_poolname, poolname,
3585                         sizeof(lpd.lpd_poolname) - 1);
3586         if (ostname && ostname[0])
3587                 strncpy(lpd.lpd_ostname, ostname, sizeof(lpd.lpd_ostname) - 1);
3588
3589         for (end = last_index; end > 1; end -= inc) {
3590                 start = end - inc > 0 ? end - inc : 1;
3591                 rc = jt_llog_print_iter(logname, start, end,
3592                                         llog_search_pool_cb, &lpd, true, false);
3593                 if (rc) {
3594                         if (rc == 1 && lpd.lpd_pool_exists)
3595                                 rc = lpd.lpd_ost_num ? 1 : 0;
3596                         else if (rc == -ENOENT && lpd.lpd_pool_exists &&
3597                                  !lpd.lpd_ost_num)
3598                                 rc = 0;
3599                         goto out;
3600                 }
3601         }
3602
3603         rc = -ENOENT;
3604 out:
3605         return rc;
3606 }
3607
3608 static bool combined_mgs_mds(char *fsname)
3609 {
3610         glob_t path;
3611         int rc;
3612
3613         rc = cfs_get_param_paths(&path, "mdt/%s-MDT0000", fsname);
3614         if (!rc)
3615                 cfs_free_param_data(&path);
3616
3617         if (get_mgs_device() > 0 && !rc)
3618                 return true;
3619
3620         return false;
3621 }
3622
3623 /*
3624  * if pool is NULL, search ostname in target_obd
3625  * if pool is not NULL:
3626  *  - if pool not found returns errno < 0
3627  *  - if ostname is NULL, returns 1 if pool is not empty and 0 if pool empty
3628  *  - if ostname is not NULL, returns 1 if OST is in pool and 0 if not
3629  */
3630 int lctl_search_ost(char *fsname, char *poolname, char *ostname,
3631                     enum lcfg_command_type cmd)
3632 {
3633         char logname[MAX_OBD_NAME] = {'\0'};
3634         long last_index;
3635
3636         if (fsname && fsname[0] == '\0')
3637                 fsname = NULL;
3638         if (!fsname)
3639                 return -EINVAL;
3640
3641         if (combined_mgs_mds(fsname))
3642                 return llapi_search_ost(fsname, poolname, ostname);
3643
3644         /* fetch the last_index of llog record */
3645         snprintf(logname, sizeof(logname), "%s-client", fsname);
3646         last_index = llog_last_index(logname);
3647         if (last_index < 0)
3648                 return last_index;
3649
3650         /* if pool is NULL, search ostname in target_obd */
3651         if (!poolname && ostname)
3652                 return llog_search_ost(logname, last_index, ostname);
3653
3654         return llog_search_pool(logname, last_index, fsname, poolname,
3655                                 ostname, cmd);
3656 }
3657
3658 static int check_pool_cmd(enum lcfg_command_type cmd, char *fsname,
3659                           char *poolname, char *ostname)
3660 {
3661         int rc;
3662
3663         rc = lctl_search_ost(fsname, poolname, ostname, cmd);
3664         if (rc < 0 && (cmd != LCFG_POOL_NEW)) {
3665                 fprintf(stderr, "Pool %s.%s not found\n",
3666                         fsname, poolname);
3667                 return rc;
3668         }
3669
3670         switch (cmd) {
3671         case LCFG_POOL_NEW: {
3672                 if (ostname)
3673                         return -EINVAL;
3674
3675                 if (rc >= 0) {
3676                         fprintf(stderr, "Pool %s.%s already exists\n",
3677                                 fsname, poolname);
3678                         return -EEXIST;
3679                 }
3680                 return 0;
3681         }
3682         case LCFG_POOL_DEL: {
3683                 if (ostname)
3684                         return -EINVAL;
3685
3686                 if (rc == 1) {
3687                         fprintf(stderr,
3688                                 "Pool %s.%s not empty, please remove all members\n",
3689                                 fsname, poolname);
3690                         return -ENOTEMPTY;
3691                 }
3692                 return 0;
3693         }
3694         case LCFG_POOL_ADD: {
3695                 if (rc == 1) {
3696                         fprintf(stderr, "OST %s is already in pool %s.%s\n",
3697                                 ostname, fsname, poolname);
3698                         return -EEXIST;
3699                 }
3700                 rc = lctl_search_ost(fsname, NULL, ostname, cmd);
3701                 if (rc == 0) {
3702                         fprintf(stderr, "OST %s is not part of the '%s' fs.\n",
3703                                 ostname, fsname);
3704                         return -ENOENT;
3705                 }
3706                 return 0;
3707         }
3708         case LCFG_POOL_REM: {
3709                 if (rc == 0) {
3710                         fprintf(stderr, "OST %s not found in pool %s.%s\n",
3711                                 ostname, fsname, poolname);
3712                         return -ENOENT;
3713                 }
3714                 return 0;
3715         }
3716         default:
3717                 break;
3718         } /* switch */
3719         return -EINVAL;
3720 }
3721
3722 /*
3723  * This check only verifies that the changes have been "pushed out" to
3724  * the client successfully.  This involves waiting for a config update,
3725  * and so may fail because of problems in that code or post-command
3726  * network loss. So reporting a warning is appropriate, but not a failure.
3727  */
3728 static int check_pool_cmd_result(enum lcfg_command_type cmd, char *fsname,
3729                                  char *poolname, char *ostname)
3730 {
3731         int cpt = 10;
3732         int rc = 0;
3733
3734         switch (cmd) {
3735         case LCFG_POOL_NEW: {
3736                 do {
3737                         rc = lctl_search_ost(fsname, poolname, NULL, cmd);
3738                         if (rc == -ENODEV)
3739                                 return rc;
3740                         if (rc < 0)
3741                                 sleep(1);
3742                         cpt--;
3743                 } while ((rc < 0) && (cpt > 0));
3744                 if (rc >= 0) {
3745                         fprintf(stderr, "Pool %s.%s created\n",
3746                                 fsname, poolname);
3747                         return 0;
3748                 }
3749
3750                 fprintf(stderr, "Warning, pool %s.%s not found\n", fsname,
3751                         poolname);
3752                 return -ENOENT;
3753         }
3754         case LCFG_POOL_DEL: {
3755                 do {
3756                         rc = lctl_search_ost(fsname, poolname, NULL, cmd);
3757                         if (rc == -ENODEV)
3758                                 return rc;
3759                         if (rc >= 0)
3760                                 sleep(1);
3761                         cpt--;
3762                 } while ((rc >= 0) && (cpt > 0));
3763                 if (rc < 0) {
3764                         fprintf(stderr, "Pool %s.%s destroyed\n",
3765                                 fsname, poolname);
3766                         return 0;
3767                 }
3768
3769                 fprintf(stderr, "Warning, pool %s.%s still found\n", fsname,
3770                         poolname);
3771                 return -EEXIST;
3772         }
3773         case LCFG_POOL_ADD: {
3774                 do {
3775                         rc = lctl_search_ost(fsname, poolname, ostname, cmd);
3776                         if (rc == -ENODEV)
3777                                 return rc;
3778                         if (rc != 1)
3779                                 sleep(1);
3780                         cpt--;
3781                 } while ((rc != 1) && (cpt > 0));
3782                 if (rc == 1) {
3783                         fprintf(stderr, "OST %s added to pool %s.%s\n",
3784                                 ostname, fsname, poolname);
3785                         return 0;
3786                 }
3787                 fprintf(stderr, "Warning, OST %s not found in pool %s.%s\n",
3788                         ostname, fsname, poolname);
3789                 return -ENOENT;
3790         }
3791         case LCFG_POOL_REM: {
3792                 do {
3793                         rc = lctl_search_ost(fsname, poolname, ostname, cmd);
3794                         if (rc == -ENODEV)
3795                                 return rc;
3796                         if (rc == 1)
3797                                 sleep(1);
3798                         cpt--;
3799                 } while ((rc == 1) && (cpt > 0));
3800                 if (rc != 1) {
3801                         fprintf(stderr, "OST %s removed from pool %s.%s\n",
3802                                 ostname, fsname, poolname);
3803                         return 0;
3804                 }
3805                 fprintf(stderr, "Warning, OST %s still found in pool %s.%s\n",
3806                         ostname, fsname, poolname);
3807                 return -EEXIST;
3808         }
3809         default:
3810                 break;
3811         }
3812         return -EINVAL;
3813 }
3814
3815 static int check_and_complete_ostname(char *fsname, char *ostname)
3816 {
3817         char *ptr;
3818         char real_ostname[MAX_OBD_NAME + 1];
3819         char i;
3820
3821         /* if OST name does not start with fsname, we add it */
3822         /* if not check if the fsname is the right one */
3823         ptr = strchr(ostname, '-');
3824         if (!ptr) {
3825                 sprintf(real_ostname, "%s-%s", fsname, ostname);
3826         } else if (strncmp(ostname, fsname, strlen(fsname)) != 0) {
3827                 fprintf(stderr, "%s does not start with fsname %s\n",
3828                         ostname, fsname);
3829                 return -EINVAL;
3830         } else {
3831                 if (strlen(ostname) > sizeof(real_ostname) - 1)
3832                         return -E2BIG;
3833
3834                 strncpy(real_ostname, ostname, sizeof(real_ostname));
3835         }
3836
3837         /* real_ostname is fsname-????? */
3838         ptr = real_ostname + strlen(fsname) + 1;
3839         if (strncmp(ptr, "OST", 3) != 0) {
3840                 fprintf(stderr, "%s does not start by %s-OST nor OST\n",
3841                         ostname, fsname);
3842                 return -EINVAL;
3843         }
3844         /* real_ostname is fsname-OST????? */
3845         ptr += 3;
3846         for (i = 0; i < 4; i++) {
3847                 if (!isxdigit(*ptr)) {
3848                         fprintf(stderr,
3849                                 "ost's index in %s is not an hexa number\n",
3850                                 ostname);
3851                         return -EINVAL;
3852                 }
3853                 ptr++;
3854         }
3855         /* real_ostname is fsname-OSTXXXX????? */
3856         /* if OST name does not end with _UUID, we add it */
3857         if (*ptr == '\0') {
3858                 strcat(real_ostname, "_UUID");
3859         } else if (strcmp(ptr, "_UUID") != 0) {
3860                 fprintf(stderr,
3861                         "ostname %s does not end with _UUID\n", ostname);
3862                 return -EINVAL;
3863         }
3864         /* real_ostname is fsname-OSTXXXX_UUID */
3865         strcpy(ostname, real_ostname);
3866         return 0;
3867 }
3868
3869 /* returns 0 or -errno */
3870 static int pool_cmd(enum lcfg_command_type cmd, char *cmdname,
3871                     char *fullpoolname, char *fsname, char *poolname,
3872                     char *ostname)
3873 {
3874         int rc = 0;
3875         struct obd_ioctl_data data;
3876         struct lustre_cfg_bufs bufs;
3877         struct lustre_cfg *lcfg;
3878         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
3879
3880         rc = check_pool_cmd(cmd, fsname, poolname, ostname);
3881         if (rc == -ENODEV)
3882                 fprintf(stderr,
3883                         "Can't verify pool command since there is no local MDT or client, proceeding anyhow...\n");
3884         else if (rc)
3885                 return rc;
3886
3887         lustre_cfg_bufs_reset(&bufs, NULL);
3888         lustre_cfg_bufs_set_string(&bufs, 0, cmdname);
3889         lustre_cfg_bufs_set_string(&bufs, 1, fullpoolname);
3890         if (ostname)
3891                 lustre_cfg_bufs_set_string(&bufs, 2, ostname);
3892
3893         lcfg = malloc(lustre_cfg_len(bufs.lcfg_bufcount, bufs.lcfg_buflen));
3894         if (!lcfg)
3895                 return -ENOMEM;
3896         lustre_cfg_init(lcfg, cmd, &bufs);
3897
3898         memset(&data, 0, sizeof(data));
3899         rc = data.ioc_dev = get_mgs_device();
3900         if (rc < 0)
3901                 goto out;
3902
3903         data.ioc_type = LUSTRE_CFG_TYPE;
3904         data.ioc_plen1 = lustre_cfg_len(lcfg->lcfg_bufcount,
3905                                         lcfg->lcfg_buflens);
3906         data.ioc_pbuf1 = (void *)lcfg;
3907
3908         memset(buf, 0, sizeof(rawbuf));
3909         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
3910         if (rc) {
3911                 fprintf(stderr, "error: %s: invalid ioctl\n",
3912                         jt_cmdname(cmdname));
3913                 free(lcfg);
3914                 return rc;
3915         }
3916         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_POOL, buf);
3917 out:
3918         if (rc)
3919                 rc = -errno;
3920         switch (rc) {
3921         case -ENAMETOOLONG:
3922                 fprintf(stderr,
3923                         "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",
3924                         jt_cmdname(cmdname), LOV_MAXPOOLNAME, LUSTRE_MAXFSNAME);
3925                 break;
3926         case -EINVAL:
3927                 fprintf(stderr,
3928                         "error: %s can contain only alphanumeric characters, underscores, and dashes besides the required '.'\n",
3929                         jt_cmdname(cmdname));
3930         default:
3931                 break;
3932         }
3933         free(lcfg);
3934         return rc;
3935 }
3936
3937 int jt_del_ost(int argc, char **argv)
3938 {
3939         char *fsname = NULL, *ptr, *logname;
3940         char mdtpattern[16], clipattern[16];
3941         char ostname[MAX_OBD_NAME + 1];
3942         long last_index;
3943         __u32 index;
3944         int rc, start = 0, dryrun = 0;
3945         char c;
3946
3947         static struct option long_opts[] = {
3948         { .val = 'h',   .name = "help",         .has_arg = no_argument },
3949         { .val = 'n',   .name = "dryrun",       .has_arg = no_argument },
3950         { .val = 't',   .name = "target",       .has_arg = required_argument },
3951         { .name = NULL } };
3952
3953         while ((c = getopt_long(argc, argv, "hnt:", long_opts, NULL)) != -1) {
3954                 switch (c) {
3955                 case 't':
3956                         fsname = strdup(optarg);
3957                         break;
3958                 case 'n':
3959                         dryrun = 1;
3960                         break;
3961                 case 'h':
3962                 default:
3963                         free(fsname);
3964                         return CMD_HELP;
3965                 }
3966         }
3967
3968         if (fsname == NULL)
3969                 return CMD_HELP;
3970
3971         if (llog_default_device(LLOG_DFLT_MGS_SET)) {
3972                 rc = CMD_INCOMPLETE;
3973                 goto out;
3974         }
3975
3976         ptr = strstr(fsname, "-OST");
3977         if (!ptr) {
3978                 rc = CMD_HELP;
3979                 goto err;
3980         }
3981
3982         if (dryrun)
3983                 fprintf(stdout, "del_ost: dry run for target %s\n", fsname);
3984
3985         *ptr++ = '\0';
3986         rc = sscanf(ptr, "OST%04x", &index);
3987         if (rc != 1) {
3988                 rc = -EINVAL;
3989                 goto err;
3990         }
3991
3992         if (strlen(ptr) > sizeof(ostname) - 1) {
3993                 rc = -E2BIG;
3994                 goto err;
3995         }
3996
3997         snprintf(mdtpattern, sizeof(mdtpattern), "%s-MDT", fsname);
3998         snprintf(clipattern, sizeof(clipattern), "%s-client", fsname);
3999         snprintf(ostname, sizeof(ostname), "%s-%s", fsname, ptr);
4000
4001         do {
4002                 char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
4003                 char *begin, *end;
4004
4005                 start = llog_catlist_next(start, rawbuf, sizeof(rawbuf));
4006                 if (start < 0)
4007                         break;
4008                 begin = ((struct obd_ioctl_data *)buf)->ioc_bulk;
4009                 if (strlen(begin) == 0)
4010                         break;
4011
4012                 while ((end = strchr(begin, '\n'))) {
4013                         *end = '\0';
4014                         logname = strstr(begin, "config_log: ");
4015
4016                         if (logname && (strstr(logname, mdtpattern) ||
4017                                         strstr(logname, clipattern))) {
4018                                 logname += 12;
4019
4020                                 fprintf(stdout, "config_log: %s\n", logname);
4021
4022                                 last_index = llog_last_index(logname);
4023                                 if (last_index < 0) {
4024                                         fprintf(stderr,
4025                                                 "error with catalog %s: %s\n",
4026                                                 logname, strerror(-last_index));
4027                                         rc = -last_index;
4028                                         goto err;
4029                                 }
4030                                 rc = llog_del_ost(logname, last_index, ostname,
4031                                                   dryrun);
4032                                 if (rc < 0)
4033                                         goto err;
4034                         }
4035                         begin = end + 1;
4036                 }
4037         } while (start);
4038
4039 err:
4040         llog_default_device(LLOG_DFLT_DEV_RESET);
4041 out:
4042         free(fsname);
4043         return rc;
4044 }
4045
4046 #ifdef HAVE_SERVER_SUPPORT
4047 /**
4048  * Format and send the ioctl to the MGS.
4049  *
4050  * \param       cmd             IOCTL to send
4051  * \param       ret_data        void pointer to return anything from
4052  *                              ioctl
4053  * \param       num_args        number of arguments to pack into the
4054  *                              ioctl buffer
4055  * \param       argv[]          variable number of string arguments
4056  *
4057  * \retval                      0 on success
4058  */
4059 static int nodemap_cmd(enum lcfg_command_type cmd, void *ret_data,
4060                        unsigned int ret_size, ...)
4061 {
4062         va_list                 ap;
4063         char                    *arg;
4064         int                     i = 0;
4065         struct lustre_cfg_bufs  bufs;
4066         struct obd_ioctl_data   data;
4067         struct lustre_cfg       *lcfg;
4068         char                    rawbuf[MAX_IOC_BUFLEN];
4069         char                    *buf = rawbuf;
4070         int                     rc = 0;
4071
4072         lustre_cfg_bufs_reset(&bufs, NULL);
4073
4074         va_start(ap, ret_size);
4075         arg = va_arg(ap, char *);
4076         while (arg) {
4077                 lustre_cfg_bufs_set_string(&bufs, i, arg);
4078                 i++;
4079                 arg = va_arg(ap, char *);
4080         }
4081         va_end(ap);
4082
4083         lcfg = malloc(lustre_cfg_len(bufs.lcfg_bufcount, bufs.lcfg_buflen));
4084         if (!lcfg)
4085                 return -ENOMEM;
4086         lustre_cfg_init(lcfg, cmd, &bufs);
4087
4088         memset(&data, 0, sizeof(data));
4089         rc = data.ioc_dev = get_mgs_device();
4090         if (rc < 0)
4091                 goto out;
4092
4093         data.ioc_type = LUSTRE_CFG_TYPE;
4094         data.ioc_plen1 = lustre_cfg_len(lcfg->lcfg_bufcount,
4095                                         lcfg->lcfg_buflens);
4096         data.ioc_pbuf1 = (void *)lcfg;
4097
4098         memset(buf, 0, sizeof(rawbuf));
4099         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
4100         if (rc) {
4101                 fprintf(stderr,
4102                         "error: invalid ioctl request: %08x errno: %d: %s\n",
4103                         cmd, errno, strerror(-rc));
4104                 goto out;
4105         }
4106
4107         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_NODEMAP, buf);
4108         if (rc) {
4109                 fprintf(stderr,
4110                         "error: invalid ioctl: %08x errno: %d: %s\n",
4111                         cmd, errno, strerror(errno));
4112                 goto out;
4113         }
4114
4115         if (ret_data) {
4116                 rc = llapi_ioctl_unpack(&data, buf, sizeof(rawbuf));
4117                 if (rc)
4118                         goto out;
4119
4120                 if (ret_size > data.ioc_plen1)
4121                         ret_size = data.ioc_plen1;
4122
4123                 memcpy(ret_data, data.ioc_pbuf1, ret_size);
4124         }
4125 out:
4126         free(lcfg);
4127
4128         return rc;
4129 }
4130
4131 /**
4132  * activate nodemap functions
4133  *
4134  * \param       argc            number of args
4135  * \param       argv[]          variable string arguments
4136  *
4137  * argv[0]                      1 for activate or 0 for deactivate
4138  *
4139  * \retval                      0 on success
4140  */
4141 int jt_nodemap_activate(int argc, char **argv)
4142 {
4143         int rc;
4144
4145         rc = nodemap_cmd(LCFG_NODEMAP_ACTIVATE, NULL, 0, argv[0], argv[1],
4146                          NULL);
4147
4148         if (rc != 0) {
4149                 errno = -rc;
4150                 perror(argv[0]);
4151         }
4152
4153         return rc;
4154 }
4155
4156 /**
4157  * add a nodemap
4158  *
4159  * \param       argc            number of args
4160  * \param       argv[]          variable string arguments
4161  *
4162  * argv[0]                      nodemap name
4163  *
4164  * \retval                      0 on success
4165  */
4166 int jt_nodemap_add(int argc, char **argv)
4167 {
4168         int rc;
4169
4170         rc = llapi_nodemap_exists(argv[1]);
4171         if (rc == 0) {
4172                 fprintf(stderr, "error: %s existing nodemap name\n", argv[1]);
4173                 return 1;
4174         }
4175
4176         rc = nodemap_cmd(LCFG_NODEMAP_ADD, NULL, 0, argv[0], argv[1], NULL);
4177
4178         if (rc != 0) {
4179                 errno = -rc;
4180                 perror(argv[0]);
4181         }
4182
4183         return rc;
4184 }
4185
4186 /**
4187  * delete a nodemap
4188  *
4189  * \param       argc            number of args
4190  * \param       argv[]          variable string arguments
4191  *
4192  * argv[0]                      nodemap name
4193  *
4194  * \retval                      0 on success
4195  */
4196 int jt_nodemap_del(int argc, char **argv)
4197 {
4198         int rc;
4199
4200         rc = llapi_nodemap_exists(argv[1]);
4201         if (rc != 0) {
4202                 fprintf(stderr, "error: %s not existing nodemap name\n",
4203                         argv[1]);
4204                 return rc;
4205         }
4206         rc = nodemap_cmd(LCFG_NODEMAP_DEL, NULL, 0, argv[0], argv[1], NULL);
4207
4208         if (rc != 0) {
4209                 errno = -rc;
4210                 perror(argv[0]);
4211         }
4212
4213         return rc;
4214 }
4215
4216 /**
4217  * test a nid for nodemap membership
4218  *
4219  * \param       argc            number of args
4220  * \param       argv[]          variable string arguments
4221  *
4222  * argv[0]                      properly formatted nid
4223  *
4224  * \retval                      0 on success
4225  */
4226 int jt_nodemap_test_nid(int argc, char **argv)
4227 {
4228         char    rawbuf[MAX_IOC_BUFLEN];
4229         int     rc;
4230
4231         rc = nodemap_cmd(LCFG_NODEMAP_TEST_NID, &rawbuf, sizeof(rawbuf),
4232                          argv[0], argv[1], NULL);
4233         if (rc == 0)
4234                 printf("%s\n", (char *)rawbuf);
4235
4236         return rc;
4237 }
4238
4239 /**
4240  * test a nodemap id pair for mapping
4241  *
4242  * \param       argc            number of args
4243  * \param       argv[[]         variable string arguments
4244  *
4245  * \retval                      0 on success
4246  *
4247  * The argv array should contain the nodemap name, the id
4248  * to checking the mapping on, and the id type (UID or GID)
4249  *
4250  */
4251 int jt_nodemap_test_id(int argc, char **argv)
4252 {
4253         char    rawbuf[MAX_IOC_BUFLEN];
4254         char    *nidstr = NULL;
4255         char    *idstr = NULL;
4256         char    *typestr = NULL;
4257         int     rc = 0;
4258         int     c;
4259
4260         static struct option long_opts[] = {
4261                 { .val = 'i',   .name = "id",   .has_arg = required_argument },
4262                 { .val = 'n',   .name = "nid",  .has_arg = required_argument },
4263                 { .val = 't',   .name = "idtype",
4264                                                 .has_arg = required_argument },
4265                 { .name = NULL } };
4266
4267         while ((c = getopt_long(argc, argv, "n:t:i:",
4268                                 long_opts, NULL)) != -1) {
4269                 switch (c) {
4270                 case 'n':
4271                         nidstr = optarg;
4272                         break;
4273                 case 't':
4274                         typestr = optarg;
4275                         break;
4276                 case 'i':
4277                         idstr = optarg;
4278                         break;
4279                 }
4280         }
4281
4282         if (!nidstr || !typestr || !idstr) {
4283                 fprintf(stderr,
4284                         "usage: nodemap_test_id --nid <nid> --idtype [uid|gid] --id <id>\n");
4285                 return -1;
4286         }
4287
4288         rc = nodemap_cmd(LCFG_NODEMAP_TEST_ID, &rawbuf, sizeof(rawbuf),
4289                          argv[0], nidstr, typestr, idstr, NULL);
4290         if (rc == 0)
4291                 printf("%s\n", (char *)rawbuf);
4292
4293         return rc;
4294 }
4295
4296 /**
4297  * parse nid range
4298  *
4299  * \param       nodemap_range   --range string
4300  * \param       nid_range       nid range string, min_nid:max_nid
4301  *
4302  * \retval                      0 on success
4303  */
4304 static int parse_nid_range(char *nodemap_range, char *nid_range, int range_len)
4305 {
4306         char                    min_nid[LNET_NIDSTR_SIZE + 1];
4307         char                    max_nid[LNET_NIDSTR_SIZE + 1];
4308         struct list_head        nidlist;
4309         int                     rc = 0;
4310
4311         INIT_LIST_HEAD(&nidlist);
4312
4313         if (cfs_parse_nidlist(nodemap_range, strlen(nodemap_range),
4314                               &nidlist) <= 0) {
4315                 fprintf(stderr,
4316                         "error: nodemap_xxx_range: can't parse nid range: %s\n",
4317                         nodemap_range);
4318                 return -EINVAL;
4319         }
4320
4321         rc = cfs_nidrange_find_min_max(&nidlist, &min_nid[0], &max_nid[0],
4322                                        LNET_NIDSTR_SIZE);
4323         if (rc < 0) {
4324                 if (rc == -EINVAL)
4325                         fprintf(stderr,
4326                                 "error: nodemap_xxx_range: nid range uses currently unsupported features\n");
4327                 else if (rc == -ERANGE)
4328                         fprintf(stderr,
4329                                 "error: nodemap_xxx_range: nodemap ranges must be contiguous\n");
4330
4331                 return rc;
4332         }
4333
4334         snprintf(nid_range, range_len, "%s:%s", min_nid, max_nid);
4335
4336         return rc;
4337 }
4338
4339 /**
4340  * add an nid range to a nodemap
4341  *
4342  * \param       argc            number of args
4343  * \param       argv[]          variable string arguments
4344  *
4345  * --name                       nodemap name
4346  * --range                      properly formatted nid range
4347  *
4348  * \retval                      0 on success, -errno on error
4349  */
4350 int jt_nodemap_add_range(int argc, char **argv)
4351 {
4352         char                    *nodemap_name = NULL;
4353         char                    *nodemap_range = NULL;
4354         char                    nid_range[2 * LNET_NIDSTR_SIZE + 2];
4355         int                     rc = 0;
4356         int                     c;
4357
4358         static struct option long_opts[] = {
4359         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4360         { .val = 'r',   .name = "range",        .has_arg = required_argument },
4361         { .name = NULL } };
4362
4363         while ((c = getopt_long(argc, argv, "n:r:",
4364                                 long_opts, NULL)) != -1) {
4365                 switch (c) {
4366                 case 'n':
4367                         nodemap_name = optarg;
4368                         break;
4369                 case 'r':
4370                         nodemap_range = optarg;
4371                         break;
4372                 }
4373         }
4374
4375         if (!nodemap_name || !nodemap_range) {
4376                 fprintf(stderr,
4377                         "usage: nodemap_add_range --name <name> --range <range>\n");
4378                 return -EINVAL;
4379         }
4380
4381         rc = parse_nid_range(nodemap_range, nid_range, sizeof(nid_range));
4382         if (rc) {
4383                 return rc;
4384         }
4385         rc = nodemap_cmd(LCFG_NODEMAP_ADD_RANGE, NULL, 0, argv[0],
4386                          nodemap_name, nid_range, NULL);
4387         if (rc) {
4388                 fprintf(stderr,
4389                         "error: %s: cannot add range '%s' to nodemap '%s': %s\n",
4390                         jt_cmdname(argv[0]), nodemap_range, nodemap_name,
4391                         strerror(-rc));
4392         }
4393
4394         return rc;
4395 }
4396
4397 /**
4398  * delete an nid range to a nodemap
4399  *
4400  * \param       argc            number of args
4401  * \param       argv[]          variable string arguments
4402  *
4403  * --name                       nodemap name
4404  * --range                      properly formatted nid range
4405  *
4406  * \retval                      0 on success
4407  */
4408 int jt_nodemap_del_range(int argc, char **argv)
4409 {
4410         char                    *nodemap_name = NULL;
4411         char                    *nodemap_range = NULL;
4412         char                    nid_range[2 * LNET_NIDSTR_SIZE + 2];
4413         int                     rc = 0;
4414         int                     c;
4415
4416         static struct option long_opts[] = {
4417         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4418         { .val = 'r',   .name = "range",        .has_arg = required_argument },
4419         { .name = NULL } };
4420
4421         while ((c = getopt_long(argc, argv, "n:r:",
4422                                 long_opts, NULL)) != -1) {
4423                 switch (c) {
4424                 case 'n':
4425                         nodemap_name = optarg;
4426                         break;
4427                 case 'r':
4428                         nodemap_range = optarg;
4429                         break;
4430                 }
4431         }
4432
4433         if (!nodemap_name || !nodemap_range) {
4434                 fprintf(stderr,
4435                         "usage: nodemap_del_range --name <name> --range <range>\n");
4436                 return -1;
4437         }
4438
4439         rc = parse_nid_range(nodemap_range, nid_range, sizeof(nid_range));
4440         if (rc) {
4441                 errno = -rc;
4442                 return rc;
4443         }
4444         rc = nodemap_cmd(LCFG_NODEMAP_DEL_RANGE, NULL, 0, argv[0],
4445                          nodemap_name, nid_range, NULL);
4446         if (rc != 0) {
4447                 errno = -rc;
4448                 fprintf(stderr,
4449                         "error: %s: cannot delete range '%s' to nodemap '%s': rc = %d\n",
4450                         jt_cmdname(argv[0]), nodemap_range, nodemap_name, rc);
4451         }
4452
4453         return rc;
4454 }
4455
4456 /**
4457  * set a fileset on a nodemap
4458  *
4459  * \param       argc            number of args
4460  * \param       argv[]          variable string arguments
4461  *
4462  * --name                       nodemap name
4463  * --fileset                    fileset name
4464  *
4465  * \retval                      0 on success
4466  */
4467 int jt_nodemap_set_fileset(int argc, char **argv)
4468 {
4469         char *nodemap_name = NULL;
4470         char *fileset_name = NULL;
4471         int   rc = 0;
4472         int   c;
4473
4474         static struct option long_opts[] = {
4475         { .val = 'f',   .name = "fileset",      .has_arg = required_argument },
4476         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4477         { .name = NULL } };
4478
4479         while ((c = getopt_long(argc, argv, "n:f:",
4480                                 long_opts, NULL)) != -1) {
4481                 switch (c) {
4482                 case 'n':
4483                         nodemap_name = optarg;
4484                         break;
4485                 case 'f':
4486                         fileset_name = optarg;
4487                         break;
4488                 }
4489         }
4490
4491         if (!nodemap_name || !fileset_name) {
4492                 fprintf(stderr,
4493                         "usage: nodemap_set_fileset --name <name> --fileset <fileset>\n");
4494                 return -1;
4495         }
4496
4497         rc = nodemap_cmd(LCFG_NODEMAP_SET_FILESET, NULL, 0, argv[0],
4498                          nodemap_name, fileset_name, NULL);
4499         if (rc != 0) {
4500                 errno = -rc;
4501                 fprintf(stderr,
4502                         "error: %s: cannot set fileset '%s' on nodemap '%s': rc = %d\n",
4503                         jt_cmdname(argv[0]), fileset_name, nodemap_name, rc);
4504         }
4505
4506         return rc;
4507 }
4508
4509 /**
4510  * set SELinux policy info on a nodemap
4511  *
4512  * \param       argc            number of args
4513  * \param       argv[]          variable string arguments
4514  *
4515  * --name                       nodemap name
4516  * --sepol                      SELinux policy info
4517  *
4518  * \retval                      0 on success
4519  */
4520 int jt_nodemap_set_sepol(int argc, char **argv)
4521 {
4522         char *nodemap_name = NULL;
4523         char *sepol = NULL;
4524         int   rc = 0;
4525         int   c;
4526
4527         static struct option long_options[] = {
4528                 {
4529                         .name           = "name",
4530                         .has_arg        = required_argument,
4531                         .val            = 'n',
4532                 },
4533                 {
4534                         .name           = "sepol",
4535                         .has_arg        = required_argument,
4536                         .val            = 's',
4537                 },
4538                 {
4539                         .name = NULL,
4540                 }
4541         };
4542
4543         while ((c = getopt_long(argc, argv, "n:s:",
4544                                 long_options, NULL)) != -1) {
4545                 switch (c) {
4546                 case 'n':
4547                         nodemap_name = optarg;
4548                         break;
4549                 case 's':
4550                         sepol = optarg;
4551                         break;
4552                 }
4553         }
4554
4555         if (!nodemap_name || !sepol) {
4556                 fprintf(stderr,
4557                         "usage: nodemap_set_sepol --name <name> --sepol <sepol>\n");
4558                 return -1;
4559         }
4560
4561         rc = nodemap_cmd(LCFG_NODEMAP_SET_SEPOL, NULL, 0, argv[0],
4562                          nodemap_name, sepol, NULL);
4563         if (rc != 0) {
4564                 errno = -rc;
4565                 fprintf(stderr,
4566                         "error: %s: cannot set sepol '%s' on nodemap '%s': rc = %d\n",
4567                         jt_cmdname(argv[0]), sepol, nodemap_name, rc);
4568         }
4569
4570         return rc;
4571 }
4572
4573 /**
4574  * modify a nodemap's behavior
4575  *
4576  * \param       argc            number of args
4577  * \param       argv[]          variable string arguments
4578  *
4579  * --name                       nodemap name
4580  * --property                   nodemap property to change
4581  *                              admin, trusted, squash_uid, squash_gid)
4582  * --value                      value to set property
4583  *
4584  * \retval                      0 on success
4585  */
4586 int jt_nodemap_modify(int argc, char **argv)
4587 {
4588         int                     c;
4589         int                     rc = 0;
4590         enum lcfg_command_type  cmd = 0;
4591         char                    *nodemap_name = NULL;
4592         char                    *param = NULL;
4593         char                    *value = NULL;
4594
4595         static struct option long_opts[] = {
4596         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4597         { .val = 'p',   .name = "property",     .has_arg = required_argument },
4598         { .val = 'v',   .name = "value",        .has_arg = required_argument },
4599         { .name = NULL } };
4600
4601         while ((c = getopt_long(argc, argv, "n:p:v:",
4602                                 long_opts, NULL)) != -1) {
4603                 switch (c) {
4604                 case 'n':
4605                         nodemap_name = optarg;
4606                         break;
4607                 case 'p':
4608                         param = optarg;
4609                         break;
4610                 case 'v':
4611                         value = optarg;
4612                         break;
4613                 }
4614         }
4615
4616         if (!nodemap_name || !param || !value) {
4617                 fprintf(stderr,
4618                         "usage: nodemap_modify --name <nodemap_name> --property <property_name> --value <value>\n");
4619                 fprintf(stderr,
4620                         "valid properties: admin trusted map_mode squash_uid squash_gid squash_projid deny_unknown audit_mode forbid_encryption readonly_mount rbac\n");
4621                 return -1;
4622         }
4623
4624         if (strcmp("admin", param) == 0) {
4625                 cmd = LCFG_NODEMAP_ADMIN;
4626         } else if (strcmp("trusted", param) == 0) {
4627                 cmd = LCFG_NODEMAP_TRUSTED;
4628         } else if (strcmp("deny_unknown", param) == 0) {
4629                 cmd = LCFG_NODEMAP_DENY_UNKNOWN;
4630         } else if (strcmp("squash_uid", param) == 0) {
4631                 cmd = LCFG_NODEMAP_SQUASH_UID;
4632         } else if (strcmp("squash_gid", param) == 0) {
4633                 cmd = LCFG_NODEMAP_SQUASH_GID;
4634         } else if (strcmp("squash_projid", param) == 0) {
4635                 cmd = LCFG_NODEMAP_SQUASH_PROJID;
4636         } else if (strcmp("map_mode", param) == 0) {
4637                 cmd = LCFG_NODEMAP_MAP_MODE;
4638         } else if (strcmp("audit_mode", param) == 0) {
4639                 cmd = LCFG_NODEMAP_AUDIT_MODE;
4640         } else if (strcmp("forbid_encryption", param) == 0) {
4641                 cmd = LCFG_NODEMAP_FORBID_ENCRYPT;
4642         } else if (strcmp("readonly_mount", param) == 0) {
4643                 cmd = LCFG_NODEMAP_READONLY_MOUNT;
4644         } else if (strcmp("rbac", param) == 0) {
4645                 cmd = LCFG_NODEMAP_RBAC;
4646         } else {
4647                 fprintf(stderr,
4648                         "error: %s: nodemap_modify invalid subcommand: %s\n",
4649                         jt_cmdname(argv[0]), param);
4650                 return -1;
4651         }
4652
4653         rc = nodemap_cmd(cmd, NULL, 0, argv[0], nodemap_name, param,
4654                          value, NULL);
4655         if (rc != 0) {
4656                 errno = -rc;
4657                 fprintf(stderr,
4658                         "error: %s: cannot modify nodemap '%s' to param '%s': value '%s': rc = %d\n",
4659                         jt_cmdname(argv[0]), nodemap_name, param, value, rc);
4660         }
4661
4662         return rc;
4663 }
4664
4665 int jt_nodemap_add_idmap(int argc, char **argv)
4666 {
4667         int                     c;
4668         enum                    lcfg_command_type cmd = 0;
4669         char                    *nodemap_name = NULL;
4670         char                    *idmap = NULL;
4671         char                    *idtype = NULL;
4672         int                     rc = 0;
4673
4674         static struct option long_opts[] = {
4675         { .val = 'i',   .name = "idtype",       .has_arg = required_argument },
4676         { .val = 'm',   .name = "idmap",        .has_arg = required_argument },
4677         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4678         { .name = NULL } };
4679
4680         while ((c = getopt_long(argc, argv, "n:m:i:",
4681                                 long_opts, NULL)) != -1) {
4682                 switch (c) {
4683                 case 'n':
4684                         nodemap_name = optarg;
4685                         break;
4686                 case 'm':
4687                         idmap = optarg;
4688                         break;
4689                 case 'i':
4690                         idtype = optarg;
4691                         break;
4692                 }
4693         }
4694
4695         if (!nodemap_name || !idmap || !idtype) {
4696                 fprintf(stderr,
4697                         "usage: %s --name <name> --idtype [uid | gid | projid] --idmap <client id>:<filesystem id>\n",
4698                         argv[0]);
4699                 return -1;
4700         }
4701
4702         if (strcmp("uid", idtype) == 0) {
4703                 cmd = LCFG_NODEMAP_ADD_UIDMAP;
4704         } else if (strcmp("gid", idtype) == 0) {
4705                 cmd = LCFG_NODEMAP_ADD_GIDMAP;
4706         } else if (strcmp("projid", idtype) == 0) {
4707                 cmd = LCFG_NODEMAP_ADD_PROJIDMAP;
4708         } else {
4709                 fprintf(stderr,
4710                         "usage: %s --name <name> --idtype [uid | gid | projid] --idmap <client id>:<filesystem id>\n",
4711                         argv[0]);
4712                 return -1;
4713         }
4714
4715         rc = nodemap_cmd(cmd, NULL, 0, argv[0], nodemap_name, idmap, NULL);
4716         if (rc != 0) {
4717                 errno = -rc;
4718                 fprintf(stderr,
4719                         "cannot add %smap '%s' to nodemap '%s': rc = %d\n",
4720                         idtype, idmap, nodemap_name, rc);
4721         }
4722
4723         return rc;
4724 }
4725
4726 int jt_nodemap_del_idmap(int argc, char **argv)
4727 {
4728         int                     c;
4729         enum                    lcfg_command_type cmd = 0;
4730         char                    *nodemap_name = NULL;
4731         char                    *idmap = NULL;
4732         char                    *idtype = NULL;
4733         int                     rc = 0;
4734
4735         static struct option long_opts[] = {
4736         { .val = 'i',   .name = "idtype",       .has_arg = required_argument },
4737         { .val = 'm',   .name = "idmap",        .has_arg = required_argument },
4738         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4739         { .name = NULL } };
4740
4741         while ((c = getopt_long(argc, argv, "n:m:i:",
4742                                 long_opts, NULL)) != -1) {
4743                 switch (c) {
4744                 case 'n':
4745                         nodemap_name = optarg;
4746                         break;
4747                 case 'm':
4748                         idmap = optarg;
4749                         break;
4750                 case 'i':
4751                         idtype = optarg;
4752                         break;
4753                 }
4754         }
4755
4756         if (!nodemap_name || !idmap || !idtype) {
4757                 fprintf(stderr,
4758                         "usage: %s --name <name> --idtype [uid | gid | projid] --idmap <client id>:<filesystem id>\n",
4759                         argv[0]);
4760                 return -1;
4761         }
4762
4763         if (strcmp("uid", idtype) == 0) {
4764                 cmd = LCFG_NODEMAP_DEL_UIDMAP;
4765         } else if (strcmp("gid", idtype) == 0) {
4766                 cmd = LCFG_NODEMAP_DEL_GIDMAP;
4767         } else if (strcmp("projid", idtype) == 0) {
4768                 cmd = LCFG_NODEMAP_DEL_PROJIDMAP;
4769         } else {
4770                 fprintf(stderr,
4771                         "usage: %s --name <name> --idtype [uid | gid | projid] --idmap <client id>:<filesystem id>\n",
4772                         argv[0]);
4773                 return -1;
4774         }
4775
4776         rc = nodemap_cmd(cmd, NULL, 0, argv[0], nodemap_name, idmap, NULL);
4777         if (rc != 0) {
4778                 errno = -rc;
4779                 fprintf(stderr,
4780                         "cannot delete %smap '%s' from nodemap '%s': rc = %d\n",
4781                         idtype, idmap, nodemap_name, rc);
4782         }
4783
4784         return rc;
4785 }
4786 #else /* !HAVE_SERVER_SUPPORT */
4787 int jt_nodemap_activate(int argc, char **argv)
4788 {
4789         fprintf(stderr, "error: %s: invalid ioctl\n",
4790                 jt_cmdname(argv[0]));
4791         return -EOPNOTSUPP;
4792 }
4793
4794 int jt_nodemap_add(int argc, char **argv)
4795 {
4796         fprintf(stderr, "error: %s: invalid ioctl\n",
4797                 jt_cmdname(argv[0]));
4798         return -EOPNOTSUPP;
4799 }
4800
4801 int jt_nodemap_del(int argc, char **argv)
4802 {
4803         fprintf(stderr, "error: %s: invalid ioctl\n",
4804                 jt_cmdname(argv[0]));
4805         return -EOPNOTSUPP;
4806 }
4807
4808 int jt_nodemap_modify(int argc, char **argv)
4809 {
4810         fprintf(stderr, "error: %s: invalid ioctl\n",
4811                 jt_cmdname(argv[0]));
4812         return -EOPNOTSUPP;
4813 }
4814
4815 int jt_nodemap_add_range(int argc, char **argv)
4816 {
4817         fprintf(stderr, "error: %s: invalid ioctl\n",
4818                 jt_cmdname(argv[0]));
4819         return -EOPNOTSUPP;
4820 }
4821
4822 int jt_nodemap_test_nid(int argc, char **argv)
4823 {
4824         fprintf(stderr, "error: %s: invalid ioctl\n",
4825                 jt_cmdname(argv[0]));
4826         return -EOPNOTSUPP;
4827 }
4828
4829 int jt_nodemap_del_range(int argc, char **argv)
4830 {
4831         fprintf(stderr, "error: %s: invalid ioctl\n",
4832                 jt_cmdname(argv[0]));
4833         return -EOPNOTSUPP;
4834 }
4835
4836 int jt_nodemap_add_idmap(int argc, char **argv)
4837 {
4838         fprintf(stderr, "error: %s: invalid ioctl\n",
4839                 jt_cmdname(argv[0]));
4840         return -EOPNOTSUPP;
4841 }
4842
4843 int jt_nodemap_del_idmap(int argc, char **argv)
4844 {
4845         fprintf(stderr, "error: %s: invalid ioctl\n",
4846                 jt_cmdname(argv[0]));
4847         return -EOPNOTSUPP;
4848 }
4849
4850 int jt_nodemap_test_id(int argc, char **argv)
4851 {
4852         fprintf(stderr, "error: %s: invalid ioctl\n",
4853                 jt_cmdname(argv[0]));
4854         return -EOPNOTSUPP;
4855 }
4856
4857 int jt_nodemap_set_fileset(int argc, char **argv)
4858 {
4859         fprintf(stderr, "error: %s: invalid ioctl\n",
4860                 jt_cmdname(argv[0]));
4861         return -EOPNOTSUPP;
4862 }
4863
4864 int jt_nodemap_set_sepol(int argc, char **argv)
4865 {
4866         fprintf(stderr, "error: %s: invalid ioctl\n",
4867                 jt_cmdname(argv[0]));
4868         return -EOPNOTSUPP;
4869 }
4870
4871 int jt_nodemap_info(int argc, char **argv)
4872 {
4873         fprintf(stderr, "error: %s: invalid ioctl\n",
4874                 jt_cmdname(argv[0]));
4875         return -EOPNOTSUPP;
4876 }
4877 #endif /* HAVE_SERVER_SUPPORT */
4878
4879 /*
4880  * this function tranforms a rule [start-end/step] into an array
4881  * of matching numbers
4882  * supported forms are:
4883  * [start]                : just this number
4884  * [start-end]            : all numbers from start to end
4885  * [start-end/step]       : numbers from start to end with increment of step
4886  * on return, format contains a printf format string which can be used
4887  * to generate all the strings
4888  */
4889 static int get_array_idx(char *rule, char *format, int **array)
4890 {
4891         char *start, *end, *ptr;
4892         unsigned int lo, hi, step;
4893         int array_sz = 0;
4894         int i, array_idx;
4895         int rc;
4896
4897         start = strchr(rule, '[');
4898         end = strchr(rule, ']');
4899         if ((!start) || (!end)) {
4900                 *array = malloc(sizeof(int));
4901                 if (!*array)
4902                         return 0;
4903                 strcpy(format, rule);
4904                 array_sz = 1;
4905                 return array_sz;
4906         }
4907         *start = '\0';
4908         *end = '\0';
4909         end++;
4910         start++;
4911         /* put in format the printf format (the rule without the range) */
4912         sprintf(format, "%s%%.4x%s", rule, end);
4913
4914         array_idx = 0;
4915         array_sz = 0;
4916         *array = NULL;
4917         /* loop on , separator */
4918         do {
4919                 /* extract the 3 fields */
4920                 rc = sscanf(start, "%x-%x/%u", &lo, &hi, &step);
4921                 switch (rc) {
4922                 case 0:
4923                         goto err;
4924                 case 1: {
4925                         void *tmp;
4926
4927                         array_sz++;
4928                         tmp = realloc(*array, array_sz * sizeof(int));
4929                         if (!tmp)
4930                                 goto err;
4931                         *array = tmp;
4932                         (*array)[array_idx] = lo;
4933                         array_idx++;
4934                         break;
4935                 }
4936                 case 2: {
4937                         step = 1;
4938                         /* do not break to share code with case 3: */
4939                 }
4940                 case 3: {
4941                         void *tmp;
4942
4943                         if ((hi < lo) || (step == 0))
4944                                 goto err;
4945                         array_sz += (hi - lo) / step + 1;
4946                         tmp = realloc(*array, array_sz * sizeof(int));
4947                         if (!tmp)
4948                                 goto err;
4949                         *array = tmp;
4950                         for (i = lo; i <= hi; i += step, array_idx++)
4951                                 (*array)[array_idx] = i;
4952                         break;
4953                 }
4954                 }
4955                 ptr = strchr(start, ',');
4956                 if (ptr)
4957                         start = ptr + 1;
4958
4959         } while (ptr);
4960         return array_sz;
4961 err:
4962         if (*array) {
4963                 free(*array);
4964                 *array = NULL;
4965         }
4966         return 0;
4967 }
4968
4969 struct llog_pool_name {
4970         char lpn_name[UUID_MAX];
4971         struct list_head lpn_list;
4972 };
4973
4974 struct llog_pool_list_data {
4975         char lpld_fsname[LUSTRE_MAXFSNAME + 1];
4976         char lpld_poolname[LOV_MAXPOOLNAME + 1];
4977         bool lpld_exists;
4978         struct list_head lpld_list_head;
4979 };
4980
4981 /**
4982  * Callback to list pool information in llog
4983  * - { index: 74, event: new_pool, device: tfs-clilov, fsname: tfs, pool: tmp }
4984  * - { index: 77, event: add_pool, device: tfs-clilov, fsname: tfs, pool: tmp,
4985  *     ost: tfs-OST0000_UUID }
4986  * - { index: 224, event: remove_pool, device: tfs-clilov, fsname: tfs,
4987  *     pool: tmp, ost: tfs-OST0003_UUID }
4988  * - { index: 227, event: del_pool, device: tfs-clilov, fsname: tfs, pool: tmp }
4989  *
4990  * \param record[in]    pointer to llog record
4991  * \param data[in]      pointer to struct llog_pool_list_data
4992  *
4993  * \retval              0 on success
4994  *                      <0 on error
4995  */
4996 static int llog_poollist_cb(const char *record, void *data)
4997 {
4998         struct llog_pool_list_data *lpld = data;
4999         char pool_filter[MAX_STRING_SIZE] = "";
5000         char *new_record, *del_record, *del_pool, *found;
5001         char type[10] = "";
5002         int filter_len, rc = 0;
5003
5004         filter_len = snprintf(pool_filter, sizeof(pool_filter), " fsname: %s,",
5005                               lpld->lpld_fsname);
5006         if (lpld->lpld_poolname[0] == '\0') {
5007                 new_record = get_event_filter(LCFG_POOL_NEW);
5008                 del_record = get_event_filter(LCFG_POOL_DEL);
5009                 strncpy(type, " pool: ", sizeof(type));
5010         } else {
5011                 filter_len += snprintf(pool_filter + filter_len,
5012                                        sizeof(pool_filter) - filter_len,
5013                                        " pool: %s", lpld->lpld_poolname);
5014                 new_record = get_event_filter(LCFG_POOL_ADD);
5015                 del_record = get_event_filter(LCFG_POOL_REM);
5016                 strncpy(type, " ost: ", sizeof(type));
5017         }
5018         del_pool = get_event_filter(LCFG_POOL_DEL);
5019
5020         if (!new_record || !del_record || !del_pool) {
5021                 rc = -ENOMEM;
5022                 goto out;
5023         }
5024
5025         found = strstr(record, pool_filter);
5026         if (found &&
5027             (found[filter_len] == ' ' || found[filter_len] == ',')) {
5028                 struct llog_pool_name *tmp = NULL;
5029                 struct list_head *head = &lpld->lpld_list_head;
5030                 char *name;
5031                 int name_len, type_len = strlen(type);
5032
5033                 lpld->lpld_exists = true;
5034                 if (strstr(record, new_record)) {
5035                         name = strstr(record, type);
5036                         /* 2 bytes for " }" */
5037                         name_len = strlen(name) - type_len - 2;
5038                         if (name_len <= 0 || name_len > sizeof(tmp->lpn_name))
5039                                 return -EINVAL;
5040                         tmp = malloc(sizeof(struct llog_pool_name));
5041                         if (!tmp) {
5042                                 rc = -ENOMEM;
5043                                 goto out;
5044                         }
5045                         memset(tmp, 0, sizeof(struct llog_pool_name));
5046                         strncpy(tmp->lpn_name, name + type_len, name_len);
5047                         list_add_tail(&tmp->lpn_list, &lpld->lpld_list_head);
5048                 } else if (strstr(record, del_record)) {
5049                         name = strstr(record, type);
5050                         name_len = strlen(name) - type_len - 2;
5051                         list_for_each_entry(tmp, head, lpn_list) {
5052                                 if (strncmp(tmp->lpn_name, name + type_len,
5053                                             name_len) == 0 &&
5054                                             tmp->lpn_name[name_len] == '\0') {
5055                                         list_del(&tmp->lpn_list);
5056                                         free(tmp);
5057                                         break;
5058                                 }
5059                         }
5060                 }
5061                 /* verify if the specified pool still exists */
5062                 if (lpld->lpld_poolname[0] && strstr(record, del_pool))
5063                         lpld->lpld_exists = false;
5064         }
5065 out:
5066         if (new_record)
5067                 free(new_record);
5068         if (del_record)
5069                 free(del_record);
5070         if (del_pool)
5071                 free(del_pool);
5072
5073         return rc;
5074 }
5075
5076 /**
5077  * List pool information by config log
5078  *
5079  * \param fsname[in]    pointer to filesystem name
5080  * \param poolname[in]  pointer to pool name
5081  *
5082  * \retval              0 on success
5083  *                      < 0 on error
5084  */
5085 int llog_poollist(char *fsname, char *poolname)
5086 {
5087         char logname[MAX_OBD_NAME] = {'\0'};
5088         struct llog_pool_list_data lpld;
5089         struct llog_pool_name *tmp;
5090         struct list_head *head;
5091         int rc = 0;
5092
5093         if (fsname && fsname[0] == '\0')
5094                 fsname = NULL;
5095         if (!fsname)
5096                 return -EINVAL;
5097
5098         memset(&lpld, 0, sizeof(lpld));
5099         INIT_LIST_HEAD(&lpld.lpld_list_head);
5100         lpld.lpld_exists = false;
5101         strncpy(lpld.lpld_fsname, fsname, sizeof(lpld.lpld_fsname) - 1);
5102         if (poolname && poolname[0])
5103                 strncpy(lpld.lpld_poolname, poolname,
5104                         sizeof(lpld.lpld_poolname) - 1);
5105         snprintf(logname, sizeof(logname), "%s-client", fsname);
5106         rc = jt_llog_print_iter(logname, 0, -1, llog_poollist_cb, &lpld, false,
5107                                 false);
5108
5109         if (poolname && poolname[0])
5110                 printf("Pool: %s.%s\n", fsname, poolname);
5111         else
5112                 printf("Pools from %s:\n", fsname);
5113
5114         head = &lpld.lpld_list_head;
5115         if (poolname && poolname[0] && !lpld.lpld_exists && list_empty(head))
5116                 return -ENOENT;
5117
5118         list_for_each_entry(tmp, head, lpn_list) {
5119                 if (poolname && poolname[0])
5120                         printf("%s\n", tmp->lpn_name);
5121                 else
5122                         printf("%s.%s\n", fsname, tmp->lpn_name);
5123                 list_del(&tmp->lpn_list);
5124         }
5125
5126         return rc;
5127 }
5128
5129 static bool get_pools_path(char *fsname)
5130 {
5131         glob_t path;
5132         int rc;
5133
5134         rc = cfs_get_param_paths(&path, "lov/%s-*/pools", fsname);
5135         if (!rc)
5136                 cfs_free_param_data(&path);
5137
5138         return (rc == 0);
5139 }
5140
5141 static int extract_fsname_poolname(char **argv, char *fsname,
5142                                    char *poolname)
5143 {
5144         char *cmd = argv[0], *param = argv[1];
5145         char *ptr;
5146         int rc;
5147
5148         snprintf(fsname, PATH_MAX + 1, "%s", param);
5149         ptr = strchr(fsname, '.');
5150         if (!ptr) {
5151                 if (strcmp(cmd, "pool_list") == 0) {
5152                         poolname = NULL;
5153                         goto out;
5154                 }
5155                 fprintf(stderr, ". is missing in %s\n", fsname);
5156                 rc = -EINVAL;
5157                 goto err;
5158         }
5159
5160         if ((ptr - fsname) == 0) {
5161                 fprintf(stderr, "fsname is empty\n");
5162                 rc = -EINVAL;
5163                 goto err;
5164         }
5165
5166         *ptr = '\0';
5167         ++ptr;
5168
5169         if (ptr[0] == '\0') {
5170                 fprintf(stderr, "poolname is empty\n");
5171                 rc = -EINVAL;
5172                 goto err;
5173         }
5174
5175         strncpy(poolname, ptr, LOV_MAXPOOLNAME);
5176         poolname[LOV_MAXPOOLNAME] = '\0';
5177
5178         if (lov_pool_is_reserved(poolname)) {
5179                 fprintf(stderr, "poolname cannot be '%s'\n", poolname);
5180                 return -EINVAL;
5181         }
5182 out:
5183         return 0;
5184
5185 err:
5186         fprintf(stderr, "argument %s must be <fsname>.<poolname>\n", param);
5187         return rc;
5188 }
5189
5190 int jt_pool_cmd(int argc, char **argv)
5191 {
5192         enum lcfg_command_type cmd;
5193         char fsname[PATH_MAX + 1];
5194         char poolname[LOV_MAXPOOLNAME + 1];
5195         char *ostnames_buf = NULL;
5196         int i, rc;
5197         int *array = NULL, array_sz;
5198         struct {
5199                 int     rc;
5200                 char   *ostname;
5201         } *cmds = NULL;
5202
5203         switch (argc) {
5204         case 0:
5205         case 1: return CMD_HELP;
5206         case 2: {
5207                 rc = extract_fsname_poolname(argv, fsname, poolname);
5208                 if (rc)
5209                         break;
5210
5211                 if (strcmp("pool_new", argv[0]) == 0) {
5212                         cmd = LCFG_POOL_NEW;
5213                 } else if (strcmp("pool_destroy", argv[0]) == 0) {
5214                         cmd = LCFG_POOL_DEL;
5215                 } else if (strcmp("pool_list", argv[0]) == 0) {
5216                         if (get_pools_path(fsname))
5217                                 return llapi_poollist(argv[1]);
5218                         if (get_mgs_device() > 0)
5219                                 return llog_poollist(fsname, poolname);
5220                         fprintf(stderr,
5221                                 "Cannot run pool_list command since there is no local MGS/MDT or client\n");
5222                         return CMD_HELP;
5223                 } else {
5224                         return CMD_HELP;
5225                 }
5226
5227                 rc = pool_cmd(cmd, argv[0], argv[1], fsname, poolname, NULL);
5228                 if (rc)
5229                         break;
5230
5231                 check_pool_cmd_result(cmd, fsname, poolname, NULL);
5232                 break;
5233         }
5234         default: {
5235                 char format[2 * MAX_OBD_NAME];
5236
5237                 if (strcmp("pool_remove", argv[0]) == 0)
5238                         cmd = LCFG_POOL_REM;
5239                 else if (strcmp("pool_add", argv[0]) == 0)
5240                         cmd = LCFG_POOL_ADD;
5241                 else
5242                         return CMD_HELP;
5243
5244                 rc = extract_fsname_poolname(argv, fsname, poolname);
5245                 if (rc)
5246                         break;
5247
5248                 for (i = 2; i < argc; i++) {
5249                         int j;
5250
5251                         array_sz = get_array_idx(argv[i], format, &array);
5252                         if (array_sz == 0)
5253                                 return CMD_HELP;
5254
5255                         cmds = malloc(array_sz * sizeof(cmds[0]));
5256                         if (cmds) {
5257                                 ostnames_buf = malloc(array_sz *
5258                                                       (MAX_OBD_NAME + 1));
5259                         } else {
5260                                 free(array);
5261                                 rc = -ENOMEM;
5262                                 goto out;
5263                         }
5264
5265                         for (j = 0; j < array_sz; j++) {
5266                                 char ostname[MAX_OBD_NAME + 1];
5267                                 int rc2;
5268
5269                                 snprintf(ostname, MAX_OBD_NAME, format,
5270                                          array[j]);
5271                                 ostname[MAX_OBD_NAME] = '\0';
5272
5273                                 rc2 = check_and_complete_ostname(fsname,
5274                                                                 ostname);
5275                                 if (rc2) {
5276                                         free(array);
5277                                         free(cmds);
5278                                         if (ostnames_buf)
5279                                                 free(ostnames_buf);
5280                                         rc = rc ? rc : rc2;
5281                                         goto out;
5282                                 }
5283                                 if (ostnames_buf) {
5284                                         cmds[j].ostname =
5285                                         &ostnames_buf[(MAX_OBD_NAME + 1) * j];
5286                                         strcpy(cmds[j].ostname, ostname);
5287                                 } else {
5288                                         cmds[j].ostname = NULL;
5289                                 }
5290                                 cmds[j].rc = pool_cmd(cmd, argv[0], argv[1],
5291                                                       fsname, poolname,
5292                                                       ostname);
5293                                 /* Return an err if any of the add/dels fail */
5294                                 if (!rc)
5295                                         rc = cmds[j].rc;
5296                         }
5297                         for (j = 0; j < array_sz; j++) {
5298                                 if (!cmds[j].rc) {
5299                                         char ostname[MAX_OBD_NAME + 1];
5300
5301                                         if (!cmds[j].ostname) {
5302                                                 snprintf(ostname, MAX_OBD_NAME,
5303                                                          format, array[j]);
5304                                                 ostname[MAX_OBD_NAME] = '\0';
5305                                                 check_and_complete_ostname(
5306                                                         fsname, ostname);
5307                                         } else {
5308                                                 strcpy(ostname,
5309                                                        cmds[j].ostname);
5310                                         }
5311                                         check_pool_cmd_result(cmd, fsname,
5312                                                               poolname,
5313                                                               ostname);
5314                                 }
5315                         }
5316                         if (array_sz > 0)
5317                                 free(array);
5318                         if (cmds)
5319                                 free(cmds);
5320                         if (ostnames_buf)
5321                                 free(ostnames_buf);
5322                 }
5323                 fallthrough;
5324         }
5325         } /* switch */
5326
5327 out:
5328         if (rc != 0) {
5329                 errno = -rc;
5330                 perror(argv[0]);
5331         }
5332
5333         return rc;
5334 }
5335
5336 #ifdef HAVE_SERVER_SUPPORT
5337 static const char *barrier_status2name(enum barrier_status status)
5338 {
5339         switch (status) {
5340         case BS_INIT:
5341                 return "init";
5342         case BS_FREEZING_P1:
5343                 return "freezing_p1";
5344         case BS_FREEZING_P2:
5345                 return "freezing_p2";
5346         case BS_FROZEN:
5347                 return "frozen";
5348         case BS_THAWING:
5349                 return "thawing";
5350         case BS_THAWED:
5351                 return "thawed";
5352         case BS_FAILED:
5353                 return "failed";
5354         case BS_EXPIRED:
5355                 return "expired";
5356         case BS_RESCAN:
5357                 return "rescan";
5358         default:
5359                 return "unknown";
5360         }
5361 }
5362
5363 int jt_barrier_freeze(int argc, char **argv)
5364 {
5365         struct obd_ioctl_data data;
5366         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
5367         struct barrier_ctl bc;
5368         int rc;
5369
5370         if (argc < 2 || argc > 3)
5371                 return CMD_HELP;
5372
5373         memset(&data, 0, sizeof(data));
5374         rc = data.ioc_dev = get_mgs_device();
5375         if (rc < 0)
5376                 return rc;
5377
5378         memset(&bc, 0, sizeof(bc));
5379         bc.bc_version = BARRIER_VERSION_V1;
5380         bc.bc_cmd = BC_FREEZE;
5381         if (argc == 3)
5382                 bc.bc_timeout = atoi(argv[2]);
5383         if (bc.bc_timeout == 0)
5384                 bc.bc_timeout = BARRIER_TIMEOUT_DEFAULT;
5385
5386         if (strlen(argv[1]) > 8) {
5387                 fprintf(stderr,
5388                         "%s: fsname name %s is too long. It should not exceed 8.\n",
5389                         argv[0], argv[1]);
5390                 return -EINVAL;
5391         }
5392
5393         strncpy(bc.bc_name, argv[1], sizeof(bc.bc_name));
5394         data.ioc_inlbuf1 = (char *)&bc;
5395         data.ioc_inllen1 = sizeof(bc);
5396         memset(buf, 0, sizeof(rawbuf));
5397         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
5398         if (rc) {
5399                 fprintf(stderr, "Fail to pack ioctl data: rc = %d.\n", rc);
5400                 return rc;
5401         }
5402
5403         rc = llapi_ioctl_dev(OBD_DEV_ID, OBD_IOC_BARRIER_V2, buf);
5404         if (rc < 0)
5405                 fprintf(stderr, "Fail to freeze barrier for %s: %s\n",
5406                         argv[1], strerror(errno));
5407
5408         return rc;
5409 }
5410
5411 int jt_barrier_thaw(int argc, char **argv)
5412 {
5413         struct obd_ioctl_data data;
5414         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
5415         struct barrier_ctl bc;
5416         int rc;
5417
5418         if (argc != 2)
5419                 return CMD_HELP;
5420
5421         memset(&data, 0, sizeof(data));
5422         rc = data.ioc_dev = get_mgs_device();
5423         if (rc < 0)
5424                 return rc;
5425
5426         memset(&bc, 0, sizeof(bc));
5427         bc.bc_version = BARRIER_VERSION_V1;
5428         bc.bc_cmd = BC_THAW;
5429
5430         if (strlen(argv[1]) > 8) {
5431                 fprintf(stderr,
5432                         "fsname name %s is too long. It should not exceed 8.\n",
5433                         argv[1]);
5434                 return -EINVAL;
5435         }
5436
5437         strncpy(bc.bc_name, argv[1], sizeof(bc.bc_name));
5438         data.ioc_inlbuf1 = (char *)&bc;
5439         data.ioc_inllen1 = sizeof(bc);
5440         memset(buf, 0, sizeof(rawbuf));
5441         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
5442         if (rc) {
5443                 fprintf(stderr, "Fail to pack ioctl data: rc = %d.\n", rc);
5444                 return rc;
5445         }
5446
5447         rc = llapi_ioctl_dev(OBD_DEV_ID, OBD_IOC_BARRIER_V2, buf);
5448         if (rc < 0)
5449                 fprintf(stderr, "Fail to thaw barrier for %s: %s\n",
5450                         argv[1], strerror(errno));
5451
5452         return rc;
5453 }
5454
5455 int __jt_barrier_stat(const char *fsname, struct barrier_ctl *bc)
5456 {
5457         struct obd_ioctl_data data;
5458         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
5459         int rc;
5460
5461         memset(&data, 0, sizeof(data));
5462         rc = data.ioc_dev = get_mgs_device();
5463         if (rc < 0)
5464                 return rc;
5465
5466         memset(bc, 0, sizeof(*bc));
5467         bc->bc_version = BARRIER_VERSION_V1;
5468         bc->bc_cmd = BC_STAT;
5469         strncpy(bc->bc_name, fsname, sizeof(bc->bc_name) - 1);
5470         data.ioc_inlbuf1 = (char *)bc;
5471         data.ioc_inllen1 = sizeof(*bc);
5472         memset(buf, 0, sizeof(rawbuf));
5473         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
5474         if (rc) {
5475                 fprintf(stderr, "Fail to pack ioctl data: rc = %d.\n", rc);
5476                 return rc;
5477         }
5478
5479         rc = llapi_ioctl_dev(OBD_DEV_ID, OBD_IOC_BARRIER_V2, buf);
5480         if (rc < 0)
5481                 fprintf(stderr, "Fail to query barrier for %s: %s\n",
5482                         fsname, strerror(errno));
5483         else
5484                 llapi_ioctl_unpack(&data, buf, sizeof(rawbuf));
5485
5486         return rc;
5487 }
5488
5489 int jt_barrier_stat(int argc, char **argv)
5490 {
5491         struct barrier_ctl bc;
5492         static struct option long_opt_barrier_stat[] = {
5493                 {
5494                         .val            = 's',
5495                         .name           = "state",
5496                         .has_arg        = no_argument,
5497                 },
5498                 {       .val            = 't',
5499                         .name           = "timeout",
5500                         .has_arg        = no_argument,
5501                 },
5502                 {
5503                         NULL
5504                 }
5505         };
5506         const char *name;
5507         int index;
5508         int opt;
5509         int rc;
5510         bool state = false;
5511         bool timeout = false;
5512
5513         while ((opt = getopt_long(argc, argv, "st", long_opt_barrier_stat,
5514                                   &index)) != EOF) {
5515                 switch (opt) {
5516                 case 's':
5517                         state = true;
5518                         break;
5519                 case 't':
5520                         timeout = true;
5521                         break;
5522                 default:
5523                         return CMD_HELP;
5524                 }
5525         }
5526
5527         if (optind >= argc)
5528                 return CMD_HELP;
5529
5530         name = argv[optind];
5531         if (strlen(name) > 8) {
5532                 fprintf(stderr,
5533                         "fsname name %s is too long. It should not exceed 8.\n",
5534                         name);
5535                 return -EINVAL;
5536         }
5537
5538         rc = __jt_barrier_stat(name, &bc);
5539         if (!rc) {
5540                 if (state && !timeout)
5541                         printf("%s\n", barrier_status2name(bc.bc_status));
5542                 else if (timeout && !state)
5543                         printf("%d\n",
5544                                (bc.bc_status == BS_FREEZING_P1 ||
5545                                 bc.bc_status == BS_FREEZING_P2 ||
5546                                 bc.bc_status == BS_FROZEN) ?
5547                                bc.bc_timeout : 0);
5548                 else
5549                         printf("state: %s\ntimeout: %d seconds\n",
5550                                barrier_status2name(bc.bc_status),
5551                                (bc.bc_status == BS_FREEZING_P1 ||
5552                                 bc.bc_status == BS_FREEZING_P2 ||
5553                                 bc.bc_status == BS_FROZEN) ?
5554                                bc.bc_timeout : 0);
5555         }
5556
5557         return rc;
5558 }
5559
5560 int jt_barrier_rescan(int argc, char **argv)
5561 {
5562         struct obd_ioctl_data data;
5563         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf;
5564         struct barrier_ctl bc;
5565         int rc;
5566
5567         if (argc < 2 || argc > 3)
5568                 return CMD_HELP;
5569
5570         memset(&data, 0, sizeof(data));
5571         rc = data.ioc_dev = get_mgs_device();
5572         if (rc < 0)
5573                 return rc;
5574
5575         memset(&bc, 0, sizeof(bc));
5576         bc.bc_version = BARRIER_VERSION_V1;
5577         bc.bc_cmd = BC_RESCAN;
5578         if (argc == 3)
5579                 bc.bc_timeout = atoi(argv[2]);
5580         if (bc.bc_timeout == 0)
5581                 bc.bc_timeout = BARRIER_TIMEOUT_DEFAULT;
5582
5583         if (strlen(argv[1]) > 8) {
5584                 fprintf(stderr,
5585                         "fsname name %s is too long. It should not exceed 8.\n",
5586                         argv[1]);
5587                 return -EINVAL;
5588         }
5589
5590         strncpy(bc.bc_name, argv[1], sizeof(bc.bc_name));
5591         data.ioc_inlbuf1 = (char *)&bc;
5592         data.ioc_inllen1 = sizeof(bc);
5593         memset(buf, 0, sizeof(rawbuf));
5594         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
5595         if (rc) {
5596                 fprintf(stderr, "Fail to pack ioctl data: rc = %d.\n", rc);
5597                 return rc;
5598         }
5599
5600         rc = llapi_ioctl_dev(OBD_DEV_ID, OBD_IOC_BARRIER_V2, buf);
5601         if (rc < 0) {
5602                 fprintf(stderr, "Fail to rescan barrier bitmap for %s: %s\n",
5603                         argv[1], strerror(errno));
5604         } else {
5605                 llapi_ioctl_unpack(&data, buf, sizeof(rawbuf));
5606                 printf("%u of %u MDT(s) in the filesystem %s are inactive\n",
5607                        bc.bc_absence, bc.bc_total, argv[1]);
5608         }
5609
5610         return rc;
5611 }
5612 #endif /* HAVE_SERVER_SUPPORT */
5613
5614 int jt_get_obj_version(int argc, char **argv)
5615 {
5616         struct lu_fid fid;
5617         struct obd_ioctl_data data;
5618         __u64 version, id = ULLONG_MAX, group = ULLONG_MAX;
5619         char rawbuf[MAX_IOC_BUFLEN], *buf = rawbuf, *fidstr;
5620         int rc, c;
5621
5622         while ((c = getopt(argc, argv, "i:g:")) != -1) {
5623                 switch (c) {
5624                 case 'i':
5625                         id = strtoull(optarg, NULL, 0);
5626                         break;
5627                 case 'g':
5628                         group = strtoull(optarg, NULL, 0);
5629                         break;
5630                 default:
5631                         return CMD_HELP;
5632                 }
5633         }
5634
5635         argc -= optind;
5636         fidstr = *(argv + optind);
5637
5638         if (!(id != ULLONG_MAX && group != ULLONG_MAX && argc == 0) &&
5639             !(id == ULLONG_MAX && group == ULLONG_MAX && argc == 1))
5640                 return CMD_HELP;
5641
5642         memset(&data, 0, sizeof(data));
5643         data.ioc_dev = cur_device;
5644         if (argc == 1) {
5645                 rc = llapi_fid_parse(fidstr, &fid, NULL);
5646                 if (rc) {
5647                         fprintf(stderr, "%s: error parsing FID '%s': %s\n",
5648                                 jt_cmdname(argv[0]), fidstr, strerror(-rc));
5649                         return rc;
5650                 }
5651
5652                 data.ioc_inlbuf1 = (char *)&fid;
5653                 data.ioc_inllen1 = sizeof(fid);
5654         } else {
5655                 data.ioc_inlbuf3 = (char *)&id;
5656                 data.ioc_inllen3 = sizeof(id);
5657                 data.ioc_inlbuf4 = (char *)&group;
5658                 data.ioc_inllen4 = sizeof(group);
5659         }
5660         data.ioc_inlbuf2 = (char *)&version;
5661         data.ioc_inllen2 = sizeof(version);
5662
5663         memset(buf, 0, sizeof(*buf));
5664         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
5665         if (rc) {
5666                 fprintf(stderr, "error: %s: packing ioctl arguments: %s\n",
5667                         jt_cmdname(argv[0]), strerror(-rc));
5668                 return rc;
5669         }
5670
5671         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_GET_OBJ_VERSION, buf);
5672         if (rc) {
5673                 fprintf(stderr, "error: %s: ioctl: %s\n",
5674                         jt_cmdname(argv[0]), strerror(errno));
5675                 return -errno;
5676         }
5677
5678         llapi_ioctl_unpack(&data, buf, sizeof(rawbuf));
5679         printf("%#jx\n", (uintmax_t)version);
5680
5681         return 0;
5682 }
5683
5684 #ifdef HAVE_SERVER_SUPPORT
5685 int jt_changelog_register(int argc, char **argv)
5686 {
5687         struct option long_opts[] = {
5688         { .val = 'h', .name = "help", .has_arg = no_argument },
5689         { .val = 'm', .name = "mask", .has_arg = required_argument },
5690         { .val = 'n', .name = "nameonly", .has_arg = no_argument },
5691         { .val = 'u', .name = "user", .has_arg = required_argument },
5692         { .name = NULL } };
5693         struct obd_ioctl_data data = { 0 };
5694         char rawbuf[MAX_IOC_BUFLEN] = "";
5695         char *buf = rawbuf;
5696         char *device = lcfg_get_devname();
5697         char *username = NULL, *usermask = NULL;
5698         bool print_name_only = false;
5699         int c;
5700         int rc;
5701
5702         if (cur_device < 0 || !device)
5703                 return CMD_HELP;
5704
5705         while ((c = getopt_long(argc, argv, "hm:nu:", long_opts, NULL)) != -1) {
5706                 switch (c) {
5707                 case 'm':
5708                         usermask = strdup(optarg);
5709                         if (!usermask) {
5710                                 fprintf(stderr,
5711                                         "error: %s: %s: cannot copy '%s'\n",
5712                                         jt_cmdname(argv[0]), strerror(errno),
5713                                         optarg);
5714                                 return -errno;
5715                         }
5716                         break;
5717                 case 'n':
5718                         print_name_only = true;
5719                         break;
5720                 case 'u':
5721                         username = strdup(optarg);
5722                         if (!username) {
5723                                 fprintf(stderr,
5724                                         "error: %s: %s: cannot copy '%s'\n",
5725                                         jt_cmdname(argv[0]), strerror(errno),
5726                                         optarg);
5727                                 return -errno;
5728                         }
5729                         break;
5730                 case 'h':
5731                 default:
5732                         free(username);
5733                         free(usermask);
5734                         return CMD_HELP;
5735                 }
5736         }
5737
5738         data.ioc_dev = cur_device;
5739         if (username) {
5740                 data.ioc_inlbuf1 = username;
5741                 data.ioc_inllen1 = strlen(username) + 1;
5742         }
5743
5744         if (usermask) {
5745                 data.ioc_inlbuf2 = usermask;
5746                 data.ioc_inllen2 = strlen(usermask) + 1;
5747         }
5748
5749         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
5750         if (rc < 0) {
5751                 fprintf(stderr, "error: %s: cannot pack ioctl: %s\n",
5752                         jt_cmdname(argv[0]), strerror(-rc));
5753                 goto out;
5754         }
5755         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_CHANGELOG_REG, buf);
5756         if (rc < 0) {
5757                 rc = -errno;
5758                 fprintf(stderr, "error: %s: %s\n", jt_cmdname(argv[0]),
5759                         rc == -EEXIST ? "User exists" : strerror(-rc));
5760                 goto out;
5761         }
5762
5763         llapi_ioctl_unpack(&data, buf, sizeof(rawbuf));
5764
5765         if (data.ioc_u32_1 == 0) {
5766                 fprintf(stderr, "received invalid userid!\n");
5767                 rc = -EPROTO;
5768                 goto out;
5769         }
5770
5771         if (print_name_only)
5772                 printf("%s%u%s%s\n", CHANGELOG_USER_PREFIX, data.ioc_u32_1,
5773                        username ? "-" : "", username ? : "");
5774         else
5775                 printf("%s: Registered changelog userid '%s%u%s%s'\n",
5776                        device, CHANGELOG_USER_PREFIX, data.ioc_u32_1,
5777                        username ? "-" : "", username ? : "");
5778 out:
5779         free(usermask);
5780         free(username);
5781         return rc;
5782 }
5783
5784 int jt_changelog_deregister(int argc, char **argv)
5785 {
5786         struct option long_opts[] = {
5787         { .val = 'h', .name = "help", .has_arg = no_argument },
5788         { .val = 'u', .name = "user", .has_arg = required_argument },
5789         { .name = NULL } };
5790         struct obd_ioctl_data data = { 0 };
5791         char rawbuf[MAX_IOC_BUFLEN] = "";
5792         char *buf = rawbuf;
5793         char *device = lcfg_get_devname();
5794         char *username = NULL;
5795         int id = 0;
5796         int c, rc;
5797
5798         if (cur_device < 0 || !device)
5799                 return CMD_HELP;
5800
5801         while ((c = getopt_long(argc, argv, "hu:", long_opts, NULL)) != -1) {
5802                 switch (c) {
5803                 case 'u':
5804                         username = strdup(optarg);
5805                         if (!username) {
5806                                 fprintf(stderr,
5807                                         "error: %s: %s: cannot copy '%s'\n",
5808                                         jt_cmdname(argv[0]), strerror(errno),
5809                                         optarg);
5810                                 return -errno;
5811                         }
5812                         break;
5813                 case 'h':
5814                 default:
5815                         free(username);
5816                         return CMD_HELP;
5817                 }
5818         }
5819
5820         if (1 == optind && argc > 1) {
5821                 /* first check if pure ID was passed */
5822                 id = atoi(argv[optind]);
5823                 /* nameless cl<ID> format or cl<ID>-... format, only ID matters */
5824                 if (id == 0)
5825                         sscanf(argv[optind], CHANGELOG_USER_PREFIX"%d", &id);
5826
5827                 /* no valid ID was parsed */
5828                 if (id <= 0) {
5829                         rc = -EINVAL;
5830                         fprintf(stderr,
5831                                 "error: %s: expect <ID> or cl<ID>[-name] got '%s'\n",
5832                                 strerror(-rc), argv[optind]);
5833                         return CMD_HELP;
5834                 }
5835                 optind++;
5836         }
5837
5838         if (optind < argc || argc == 1)
5839                 return CMD_HELP;
5840
5841         data.ioc_dev = cur_device;
5842         data.ioc_u32_1 = id;
5843         if (username) {
5844                 data.ioc_inlbuf1 = username;
5845                 data.ioc_inllen1 = strlen(username) + 1;
5846         }
5847
5848         rc = llapi_ioctl_pack(&data, &buf, sizeof(rawbuf));
5849         if (rc < 0) {
5850                 fprintf(stderr, "error: %s: invalid ioctl\n",
5851                         jt_cmdname(argv[0]));
5852                 return rc;
5853         }
5854
5855         rc = l_ioctl(OBD_DEV_ID, OBD_IOC_CHANGELOG_DEREG, buf);
5856         if (rc < 0) {
5857                 rc = -errno;
5858                 fprintf(stderr, "error: %s: %s\n", jt_cmdname(argv[0]),
5859                         rc == -ENOENT ? "User not found" : strerror(-rc));
5860                 return rc;
5861         }
5862
5863         llapi_ioctl_unpack(&data, buf, sizeof(rawbuf));
5864         printf("%s: Deregistered changelog user #%u\n", device, data.ioc_u32_1);
5865
5866         return 0;
5867 }
5868 #else /* !HAVE_SERVER_SUPPORT */
5869 int jt_changelog_register(int argc, char **argv)
5870 {
5871         fprintf(stderr, "error: %s: invalid ioctl\n",
5872                 jt_cmdname(argv[0]));
5873         return -EOPNOTSUPP;
5874 }
5875
5876 int jt_changelog_deregister(int argc, char **argv)
5877 {
5878         fprintf(stderr, "error: %s: invalid ioctl\n",
5879                 jt_cmdname(argv[0]));
5880         return -EOPNOTSUPP;
5881 }
5882 #endif /* HAVE_SERVER_SUPPORT */
5883
5884 int jt_pcc_add(int argc, char **argv)
5885 {
5886         struct option long_opts[] = {
5887                 { .val = 'p', .name = "param", .has_arg = required_argument },
5888                 { .name = NULL } };
5889         const char *mntpath;
5890         const char *pccpath;
5891         char *param = NULL;
5892         char cmd[PATH_MAX];
5893         int rc;
5894
5895         optind = 1;
5896         while ((rc = getopt_long(argc, argv, "p:", long_opts, NULL)) != -1) {
5897                 switch (rc) {
5898                 case 'p':
5899                         param = optarg;
5900                         break;
5901                 default:
5902                         return CMD_HELP;
5903                 }
5904         }
5905
5906         if (!param) {
5907                 fprintf(stderr, "%s: must specify the config param for PCC\n",
5908                         jt_cmdname(argv[0]));
5909                 return CMD_HELP;
5910         }
5911
5912         if (optind + 2 != argc) {
5913                 fprintf(stderr,
5914                         "%s: must specify mount path and PCC path %d:%d\n",
5915                         jt_cmdname(argv[0]), optind, argc);
5916                 return CMD_HELP;
5917         }
5918
5919         mntpath = argv[optind++];
5920         pccpath = argv[optind];
5921
5922         snprintf(cmd, PATH_MAX, "add %s %s", pccpath, param);
5923         rc = llapi_pccdev_set(mntpath, cmd);
5924         if (rc < 0)
5925                 fprintf(stderr, "%s: failed to run '%s' on %s\n",
5926                         jt_cmdname(argv[0]), cmd, mntpath);
5927
5928         return rc;
5929 }
5930
5931 int jt_pcc_del(int argc, char **argv)
5932 {
5933         const char *mntpath;
5934         const char *pccpath;
5935         char cmd[PATH_MAX];
5936         int rc;
5937
5938         optind = 1;
5939         if (argc != 3) {
5940                 fprintf(stderr, "%s: require 3 arguments\n",
5941                         jt_cmdname(argv[0]));
5942                 return CMD_HELP;
5943         }
5944
5945         mntpath = argv[optind++];
5946         pccpath = argv[optind++];
5947
5948         snprintf(cmd, PATH_MAX, "del %s", pccpath);
5949         rc = llapi_pccdev_set(mntpath, cmd);
5950         if (rc < 0)
5951                 fprintf(stderr, "%s: failed to run '%s' on %s\n",
5952                         jt_cmdname(argv[0]), cmd, mntpath);
5953
5954         return rc;
5955 }
5956
5957 int jt_pcc_clear(int argc, char **argv)
5958 {
5959         const char *mntpath;
5960         int rc;
5961
5962         optind = 1;
5963         if (argc != 2) {
5964                 fprintf(stderr, "%s: require 2 arguments\n",
5965                         jt_cmdname(argv[0]));
5966                 return CMD_HELP;
5967         }
5968
5969         mntpath = argv[optind];
5970         rc = llapi_pccdev_set(mntpath, "clear");
5971         if (rc < 0)
5972                 fprintf(stderr, "%s: failed to run 'clear' on %s\n",
5973                         jt_cmdname(argv[0]), mntpath);
5974
5975         return rc;
5976 }
5977
5978 int jt_pcc_list(int argc, char **argv)
5979 {
5980         const char *mntpath;
5981         int rc;
5982
5983         optind = 1;
5984         if (argc != 2) {
5985                 fprintf(stderr, "%s: require 2 arguments\n",
5986                         jt_cmdname(argv[0]));
5987                 return CMD_HELP;
5988         }
5989
5990         mntpath = argv[optind];
5991         rc = llapi_pccdev_get(mntpath);
5992         if (rc < 0)
5993                 fprintf(stderr, "%s: failed to run 'pcc list' on %s\n",
5994                         jt_cmdname(argv[0]), mntpath);
5995
5996         return rc;
5997 }