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