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