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