Whamcloud - gitweb
LU-9680 net: Netlink improvements
[fs/lustre-release.git] / lnet / utils / lst.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) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lnet/selftest/conctl.c
32  *
33  * Author: Liang Zhen <liangzhen@clusterfs.com>
34  */
35 #include <errno.h>
36 #include <getopt.h>
37 #include <inttypes.h>
38 #include <pwd.h>
39 #include <unistd.h>
40 #include <stdarg.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <sys/ioctl.h>
45 #include <time.h>
46 #include <linux/types.h>
47
48 #include <libcfs/util/list.h>
49 #include <libcfs/util/ioctl.h>
50 #include <libcfs/util/parser.h>
51 #include <linux/lnet/lnetctl.h>
52 #include <linux/lnet/lnetst.h>
53 #include <linux/lnet/nidstr.h>
54 #include "lnetconfig/liblnetconfig.h"
55
56 struct lst_sid LST_INVALID_SID = { .ses_nid = LNET_NID_ANY, .ses_stamp = -1 };
57 static struct lst_sid session_id;
58 static int                 session_key;
59 static int lst_list_commands(int argc, char **argv);
60
61 /* All nodes running 2.6.50 or later understand feature LST_FEAT_BULK_LEN */
62 static unsigned         session_features = LST_FEATS_MASK;
63 static struct lstcon_trans_stat trans_stat;
64
65 typedef struct list_string {
66         struct list_string *lstr_next;
67         int                 lstr_sz;
68         char                lstr_str[0];
69 } lstr_t;
70
71 #ifndef offsetof
72 # define offsetof(typ,memb)     ((unsigned long)((char *)&(((typ *)0)->memb)))
73 #endif
74
75 static int alloc_count = 0;
76 static int alloc_nob   = 0;
77
78 lstr_t *
79 alloc_lstr(int sz)
80 {
81         lstr_t  *lstr = malloc(offsetof(lstr_t, lstr_str[sz]));
82
83         if (lstr == NULL) {
84                 fprintf(stderr, "Can't allocate lstr\n");
85                 abort();
86         }
87
88         alloc_nob += sz;
89         alloc_count++;
90
91         lstr->lstr_str[0] = 0;
92         lstr->lstr_sz = sz;
93         return lstr;
94 }
95
96 void
97 free_lstr(lstr_t *lstr)
98 {
99         alloc_count--;
100         alloc_nob -= lstr->lstr_sz;
101         free(lstr);
102 }
103
104 void
105 free_lstrs(lstr_t **list)
106 {
107         lstr_t   *lstr;
108
109         while ((lstr = *list) != NULL) {
110                 *list = lstr->lstr_next;
111                 free_lstr(lstr);
112         }
113 }
114
115 void
116 new_lstrs(lstr_t **list, char *prefix, char *postfix,
117           int lo, int hi, int stride)
118 {
119         int    n1 = strlen(prefix);
120         int    n2 = strlen(postfix);
121         int    sz = n1 + 20 + n2 + 1;
122
123         do {
124                 lstr_t *n = alloc_lstr(sz);
125
126                 snprintf(n->lstr_str, sz - 1, "%s%u%s",
127                          prefix, lo, postfix);
128
129                 n->lstr_next = *list;
130                 *list = n;
131
132                 lo += stride;
133         } while (lo <= hi);
134 }
135
136 int
137 expand_lstr(lstr_t **list, lstr_t *l)
138 {
139         int          nob = strlen(l->lstr_str);
140         char        *b1;
141         char        *b2;
142         char        *expr;
143         char        *sep;
144         int          x;
145         int          y;
146         int          z;
147         int          n;
148
149         b1 = strchr(l->lstr_str, '[');
150         if (b1 == NULL) {
151                 l->lstr_next = *list;
152                 *list = l;
153                 return 0;
154         }
155
156         b2 = strchr(b1, ']');
157         if (b2 == NULL || b2 == b1 + 1)
158                 return -1;
159
160         *b1++ = 0;
161         *b2++ = 0;
162         expr = b1;
163         do {
164
165                 sep = strchr(expr, ',');
166                 if (sep != NULL)
167                         *sep++ = 0;
168
169                 nob = strlen(expr);
170                 n = nob;
171                 if (sscanf(expr, "%u%n", &x, &n) >= 1 && n == nob) {
172                         /* simple number */
173                         new_lstrs(list, l->lstr_str, b2, x, x, 1);
174                         continue;
175                 }
176
177                 n = nob;
178                 if (sscanf(expr, "%u-%u%n", &x, &y, &n) >= 2 && n == nob &&
179                     x < y) {
180                         /* simple range */
181                         new_lstrs(list, l->lstr_str, b2, x, y, 1);
182                         continue;
183                 }
184
185                 n = nob;
186                 if (sscanf(expr, "%u-%u/%u%n", &x, &y, &z, &n) >= 3 && n == nob &&
187                     x < y) {
188                         /* strided range */
189                         new_lstrs(list, l->lstr_str, b2, x, y, z);
190                         continue;
191                 }
192
193                 /* syntax error */
194                 return -1;
195         } while ((expr = sep) != NULL);
196
197         free_lstr(l);
198
199         return 1;
200 }
201
202 int
203 expand_strs(char *str, lstr_t **head)
204 {
205         lstr_t  *list = NULL;
206         lstr_t  *nlist;
207         lstr_t  *l;
208         int      rc = 0;
209         int      expanded;
210
211         l = alloc_lstr(strlen(str) + 1);
212         memcpy(l->lstr_str, str, strlen(str) + 1);
213         l->lstr_next = NULL;
214         list = l;
215
216         do {
217                 expanded = 0;
218                 nlist = NULL;
219
220                 while ((l = list) != NULL) {
221                         list = l->lstr_next;
222
223                         rc = expand_lstr(&nlist, l);
224                         if (rc < 0) {
225                                 fprintf(stderr, "Syntax error in \"%s\"\n", str);
226                                 free_lstr(l);
227                                 break;
228                         }
229
230                         expanded |= rc > 0;
231                 }
232
233                 /* re-order onto 'list' */
234                 while ((l = nlist) != NULL) {
235                         nlist = l->lstr_next;
236                         l->lstr_next = list;
237                         list = l;
238                 }
239
240         } while (expanded && rc > 0);
241
242         if (rc >= 0) {
243                 *head = list;
244                 return 0;
245         }
246
247         while ((l = list) != NULL) {
248                 list = l->lstr_next;
249
250                 free_lstr(l);
251         }
252         return rc;
253 }
254
255 int
256 lst_parse_nids(char *str, int *countp, struct lnet_process_id **idspp)
257 {
258         lstr_t  *head = NULL;
259         lstr_t  *l;
260         int      c = 0;
261         int      i;
262         int      rc;
263
264         rc = expand_strs(str, &head);
265         if (rc != 0)
266                 goto out;
267
268         l = head;
269         while (l != NULL) {
270                 l = l->lstr_next;
271                 c++;
272         }
273
274         *idspp = malloc(c * sizeof(struct lnet_process_id));
275         if (*idspp == NULL) {
276                 fprintf(stderr, "Out of memory\n");
277                 rc = -1;
278         }
279
280         *countp = c;
281 out:
282         i = 0;
283         while ((l = head) != NULL) {
284                 head = l->lstr_next;
285
286                 if (rc == 0) {
287                         (*idspp)[i].nid = libcfs_str2nid(l->lstr_str);
288                         if ((*idspp)[i].nid == LNET_NID_ANY) {
289                                 fprintf(stderr, "Invalid nid: %s\n",
290                                         l->lstr_str);
291                                 rc = -1;
292                         }
293
294                         (*idspp)[i].pid = LNET_PID_LUSTRE;
295                         i++;
296                 }
297
298                 free_lstr(l);
299         }
300
301         if (rc == 0)
302                 return 0;
303
304         free(*idspp);
305         *idspp = NULL;
306
307         return rc;
308 }
309
310 char *
311 lst_node_state2str(int state)
312 {
313         if (state == LST_NODE_ACTIVE)
314                 return "Active";
315         if (state == LST_NODE_BUSY)
316                 return "Busy";
317         if (state == LST_NODE_DOWN)
318                 return "Down";
319
320         return "Unknown";
321 }
322
323 int
324 lst_node_str2state(char *str)
325 {
326         if (strcasecmp(str, "active") == 0)
327                 return LST_NODE_ACTIVE;
328         if (strcasecmp(str, "busy") == 0)
329                 return LST_NODE_BUSY;
330         if (strcasecmp(str, "down") == 0)
331                 return LST_NODE_DOWN;
332         if (strcasecmp(str, "unknown") == 0)
333                 return LST_NODE_UNKNOWN;
334         if (strcasecmp(str, "invalid") == 0)
335                 return (LST_NODE_UNKNOWN | LST_NODE_DOWN | LST_NODE_BUSY);
336
337         return -1;
338 }
339
340 char *
341 lst_test_type2name(int type)
342 {
343         if (type == LST_TEST_PING)
344                 return "ping";
345         if (type == LST_TEST_BULK)
346                 return "brw";
347
348         return "unknown";
349 }
350
351 int
352 lst_test_name2type(char *name)
353 {
354         if (strcasecmp(name, "ping") == 0)
355                 return LST_TEST_PING;
356         if (strcasecmp(name, "brw") == 0)
357                 return LST_TEST_BULK;
358
359         return -1;
360 }
361
362 void
363 lst_print_usage(char *cmd)
364 {
365         Parser_printhelp(cmd);
366 }
367
368 void
369 lst_print_error(char *sub, const char *def_format, ...)
370 {
371         va_list ap;
372
373         /* local error returned from kernel */
374         switch (errno) {
375         case ESRCH:
376                 fprintf(stderr, "No session exists\n");
377                 return;
378         case ESHUTDOWN:
379                 fprintf(stderr, "Session is shutting down\n");
380                 return;
381         case EACCES:
382                 fprintf(stderr, "Unmatched session key or not root\n");
383                 return;
384         case ENOENT:
385                 fprintf(stderr, "Can't find %s in current session\n", sub);
386                 return;
387         case EINVAL:
388                 fprintf(stderr, "Invalid parameters list in command line\n");
389                 return;
390         case EFAULT:
391                 fprintf(stderr, "Bad parameter address\n");
392                 return;
393         case EEXIST:
394                 fprintf(stderr, "%s already exists\n", sub);
395                 return;
396         default:
397                 va_start(ap, def_format);
398                 vfprintf(stderr, def_format, ap);
399                 va_end(ap);
400
401                 return;
402         }
403 }
404
405 void
406 lst_free_rpcent(struct list_head *head)
407 {
408         struct lstcon_rpc_ent *ent;
409
410         while (!list_empty(head)) {
411                 ent = list_entry(head->next, struct lstcon_rpc_ent, rpe_link);
412
413                 list_del(&ent->rpe_link);
414                 free(ent);
415         }
416 }
417
418 void
419 lst_reset_rpcent(struct list_head *head)
420 {
421         struct lstcon_rpc_ent *ent;
422
423         list_for_each_entry(ent, head, rpe_link) {
424                 ent->rpe_sid       = LST_INVALID_SID;
425                 ent->rpe_peer.nid  = LNET_NID_ANY;
426                 ent->rpe_peer.pid  = LNET_PID_ANY;
427                 ent->rpe_rpc_errno = ent->rpe_fwk_errno = 0;
428         }
429 }
430
431 int
432 lst_alloc_rpcent(struct list_head *head, int count, int offset)
433 {
434         struct lstcon_rpc_ent *ent;
435         int               i;
436
437         for (i = 0; i < count; i++) {
438                 ent = malloc(offsetof(struct lstcon_rpc_ent, rpe_payload[offset]));
439                 if (ent == NULL) {
440                         lst_free_rpcent(head);
441                         return -1;
442                 }
443
444                 memset(ent, 0, offsetof(struct lstcon_rpc_ent, rpe_payload[offset]));
445
446                 ent->rpe_sid      = LST_INVALID_SID;
447                 ent->rpe_peer.nid = LNET_NID_ANY;
448                 ent->rpe_peer.pid = LNET_PID_ANY;
449                 list_add(&ent->rpe_link, head);
450         }
451
452         return 0;
453 }
454
455 void
456 lst_print_transerr(struct list_head *head, char *optstr)
457 {
458         struct lstcon_rpc_ent *ent;
459
460         list_for_each_entry(ent, head, rpe_link) {
461                 if (ent->rpe_rpc_errno == 0 && ent->rpe_fwk_errno == 0)
462                         continue;
463
464                 if (ent->rpe_rpc_errno != 0) {
465                         fprintf(stderr, "%s RPC failed on %s: %s\n",
466                                 optstr, libcfs_id2str(ent->rpe_peer),
467                                 strerror(ent->rpe_rpc_errno));
468                         continue;
469                 }
470
471                 fprintf(stderr, "operation %s failed on %s: %s\n",
472                         optstr, libcfs_id2str(ent->rpe_peer),
473                         strerror(ent->rpe_fwk_errno));
474         }
475 }
476
477 int lst_info_batch_ioctl(char *batch, int test, int server,
478                         struct lstcon_test_batch_ent *entp, int *idxp,
479                         int *ndentp, struct lstcon_node_ent *dentsp);
480
481 int lst_info_group_ioctl(char *name, struct lstcon_ndlist_ent *gent,
482                          int *idx, int *count, struct lstcon_node_ent *dents);
483
484 int lst_query_batch_ioctl(char *batch, int test, int server,
485                           int timeout, struct list_head *head);
486
487 int
488 lst_ioctl(unsigned int opc, void *buf, int len)
489 {
490         struct libcfs_ioctl_data data;
491         int    rc;
492
493         LIBCFS_IOC_INIT (data);
494         data.ioc_u32[0]  = opc;
495         data.ioc_plen1   = len;
496         data.ioc_pbuf1   = (char *)buf;
497         data.ioc_plen2   = sizeof(trans_stat);
498         data.ioc_pbuf2   = (char *)&trans_stat;
499
500         memset(&trans_stat, 0, sizeof(trans_stat));
501
502         rc = l_ioctl(LNET_DEV_ID, IOC_LIBCFS_LNETST, &data);
503
504         /* local error, no valid RPC result */
505         if (rc != 0)
506                 return -1;
507
508         /* RPC error */
509         if (trans_stat.trs_rpc_errno != 0)
510                 return -2;
511
512         /* Framework error */
513         if (trans_stat.trs_fwk_errno != 0)
514                 return -3;
515
516         return 0;
517 }
518
519 int
520 lst_new_session_ioctl(char *name, int timeout, int force, struct lst_sid *sid)
521 {
522         struct lstio_session_new_args args = { 0 };
523
524         args.lstio_ses_key     = session_key;
525         args.lstio_ses_timeout = timeout;
526         args.lstio_ses_force   = force;
527         args.lstio_ses_idp     = sid;
528         args.lstio_ses_feats   = session_features;
529         args.lstio_ses_nmlen   = strlen(name);
530         args.lstio_ses_namep   = name;
531
532         return lst_ioctl (LSTIO_SESSION_NEW, &args, sizeof(args));
533 }
534
535 int
536 jt_lst_new_session(int argc, char **argv)
537 {
538         char  buf[LST_NAME_SIZE * 2 + 1];
539         char *name;
540         int   optidx = 0;
541         int   timeout = 300;
542         int   force = 0;
543         int   c;
544         int   rc;
545
546         static const struct option session_opts[] = {
547                 { .name = "timeout", .has_arg = required_argument, .val = 't' },
548                 { .name = "force",   .has_arg = no_argument,       .val = 'f' },
549                 { .name = NULL } };
550
551         if (session_key == 0) {
552                 fprintf(stderr,
553                         "Can't find env LST_SESSION or value is not valid\n");
554                 return -1;
555         }
556
557         while (1) {
558
559                 c = getopt_long(argc, argv, "ft:",
560                                 session_opts, &optidx);
561
562                 if (c == -1)
563                         break;
564
565                 switch (c) {
566                 case 'f':
567                         force = 1;
568                         break;
569                 case 't':
570                         timeout = atoi(optarg);
571                         break;
572                 default:
573                         lst_print_usage(argv[0]);
574                         return -1;
575                 }
576         }
577
578         if (timeout <= 0) {
579                 fprintf(stderr, "Invalid timeout value\n");
580                 return -1;
581         }
582
583         if (optind == argc - 1) {
584                 name = argv[optind ++];
585                 if (strlen(name) >= LST_NAME_SIZE) {
586                         fprintf(stderr, "Name size is limited to %d\n",
587                                 LST_NAME_SIZE - 1);
588                         return -1;
589                 }
590
591         } else if (optind == argc) {
592                 char           user[LST_NAME_SIZE];
593                 char           host[LST_NAME_SIZE];
594                 struct passwd *pw = getpwuid(getuid());
595
596                 if (pw == NULL)
597                         snprintf(user, sizeof(user), "%d", (int)getuid());
598                 else
599                         snprintf(user, sizeof(user), "%s", pw->pw_name);
600
601                 rc = gethostname(host, sizeof(host));
602                 if (rc != 0)
603                         snprintf(host, sizeof(host), "unknown_host");
604
605                 snprintf(buf, sizeof(buf), "%s@%s", user, host);
606                 name = buf;
607
608         } else {
609                 lst_print_usage(argv[0]);
610                 return -1;
611         }
612
613         rc = lst_new_session_ioctl(name, timeout, force, &session_id);
614         if (rc != 0) {
615                 lst_print_error("session", "Failed to create session: %s\n",
616                                 strerror(errno));
617                 return rc;
618         }
619
620         fprintf(stdout, "SESSION: %s FEATURES: %x TIMEOUT: %d FORCE: %s\n",
621                 name, session_features, timeout, force ? "Yes" : "No");
622         return 0;
623 }
624
625 int
626 lst_session_info_ioctl(char *name, int len, int *key, unsigned *featp,
627                        struct lst_sid *sid, struct lstcon_ndlist_ent *ndinfo)
628 {
629         struct lstio_session_info_args args = { 0 };
630
631         args.lstio_ses_idp     = sid;
632         args.lstio_ses_keyp    = key;
633         args.lstio_ses_featp   = featp;
634         args.lstio_ses_ndinfo  = ndinfo;
635         args.lstio_ses_nmlen   = len;
636         args.lstio_ses_namep   = name;
637
638         return lst_ioctl(LSTIO_SESSION_INFO, &args, sizeof(args));
639 }
640
641 int
642 jt_lst_show_session(int argc, char **argv)
643 {
644         struct lstcon_ndlist_ent ndinfo;
645         struct lst_sid sid;
646         char                name[LST_NAME_SIZE];
647         unsigned            feats;
648         int                 key;
649         int                 rc;
650
651         rc = lst_session_info_ioctl(name, sizeof(name), &key,
652                                     &feats, &sid, &ndinfo);
653
654         if (rc != 0) {
655                 lst_print_error("session", "Failed to show session: %s\n",
656                                 strerror(errno));
657                 return -1;
658         }
659
660         fprintf(stdout, "%s ID: %ju@%s, KEY: %d FEATURES: %x NODES: %d\n",
661                 name, (uintmax_t)sid.ses_stamp, libcfs_nid2str(sid.ses_nid),
662                 key, feats, ndinfo.nle_nnode);
663
664         return 0;
665 }
666
667 int
668 lst_end_session_ioctl(void)
669 {
670         struct lstio_session_end_args args = { 0 };
671
672         args.lstio_ses_key = session_key;
673         return lst_ioctl(LSTIO_SESSION_END, &args, sizeof(args));
674 }
675
676 int
677 jt_lst_end_session(int argc, char **argv)
678 {
679         int             rc;
680
681         if (session_key == 0) {
682                 fprintf(stderr,
683                         "Can't find env LST_SESSION or value is not valid\n");
684                 return -1;
685         }
686
687         rc = lst_end_session_ioctl();
688
689         if (rc == 0) {
690                 fprintf(stdout, "session is ended\n");
691                 return 0;
692         }
693
694         if (rc == -1) {
695                 lst_print_error("session", "Failed to end session: %s\n",
696                                 strerror(errno));
697                 return rc;
698         }
699
700         if (trans_stat.trs_rpc_errno != 0) {
701                 fprintf(stderr,
702                         "[RPC] Failed to send %d session RPCs: %s\n",
703                         lstcon_rpc_stat_failure(&trans_stat, 0),
704                         strerror(trans_stat.trs_rpc_errno));
705         }
706
707         if (trans_stat.trs_fwk_errno != 0) {
708                 fprintf(stderr,
709                         "[FWK] Failed to end session on %d nodes: %s\n",
710                         lstcon_sesop_stat_failure(&trans_stat, 0),
711                         strerror(trans_stat.trs_fwk_errno));
712         }
713
714         return rc;
715 }
716
717 int
718 lst_ping_ioctl(char *str, int type, int timeout,
719                int count, struct lnet_process_id *ids, struct list_head *head)
720 {
721         struct lstio_debug_args args = { 0 };
722
723         args.lstio_dbg_key     = session_key;
724         args.lstio_dbg_type    = type;
725         args.lstio_dbg_flags   = 0;
726         args.lstio_dbg_timeout = timeout;
727         args.lstio_dbg_nmlen   = (str == NULL) ? 0: strlen(str);
728         args.lstio_dbg_namep   = str;
729         args.lstio_dbg_count   = count;
730         args.lstio_dbg_idsp    = ids;
731         args.lstio_dbg_resultp = head;
732
733         return lst_ioctl (LSTIO_DEBUG, &args, sizeof(args));
734 }
735
736 int
737 lst_get_node_count(int type, char *str, int *countp,
738                    struct lnet_process_id **idspp)
739 {
740         char                    buf[LST_NAME_SIZE];
741         struct lstcon_test_batch_ent ent;
742         struct lstcon_ndlist_ent    *entp = &ent.tbe_cli_nle;
743         struct lst_sid sid;
744         unsigned                feats;
745         int                     key;
746         int                     rc;
747
748         switch (type) {
749         case LST_OPC_SESSION:
750                 rc = lst_session_info_ioctl(buf, LST_NAME_SIZE,
751                                             &key, &feats, &sid, entp);
752                 break;
753
754         case LST_OPC_BATCHSRV:
755                 entp = &ent.tbe_srv_nle;
756         case LST_OPC_BATCHCLI:
757                 rc = lst_info_batch_ioctl(str, 0, 0, &ent, NULL, NULL, NULL);
758                 break;
759
760         case LST_OPC_GROUP:
761                 rc = lst_info_group_ioctl(str, entp, NULL, NULL, NULL);
762                 break;
763
764         case LST_OPC_NODES:
765                 rc = lst_parse_nids(str, &entp->nle_nnode, idspp) < 0 ? -1 : 0;
766                 break;
767
768         default:
769                 rc = -1;
770                 break;
771         }
772
773         if (rc == 0)
774                 *countp = entp->nle_nnode;
775
776         return rc;
777 }
778
779 int
780 jt_lst_ping(int argc,  char **argv)
781 {
782         struct list_head   head;
783         struct lnet_process_id *ids = NULL;
784         struct lstcon_rpc_ent  *ent = NULL;
785         char              *str = NULL;
786         int                optidx  = 0;
787         int                server  = 0;
788         int                timeout = 5;
789         int                count   = 0;
790         int                type    = 0;
791         int                rc      = 0;
792         int                c;
793
794         static const struct option ping_opts[] = {
795                 { .name = "session", .has_arg = no_argument,       .val = 's' },
796                 { .name = "server",  .has_arg = no_argument,       .val = 'v' },
797                 { .name = "batch",   .has_arg = required_argument, .val = 'b' },
798                 { .name = "group",   .has_arg = required_argument, .val = 'g' },
799                 { .name = "nodes",   .has_arg = required_argument, .val = 'n' },
800                 { .name = "timeout", .has_arg = required_argument, .val = 't' },
801                 { .name = NULL, } };
802
803         if (session_key == 0) {
804                 fprintf(stderr,
805                         "Can't find env LST_SESSION or value is not valid\n");
806                 return -1;
807         }
808
809         while (1) {
810
811                 c = getopt_long(argc, argv, "g:b:n:t:sv",
812                                 ping_opts, &optidx);
813
814                 if (c == -1)
815                         break;
816
817                 switch (c) {
818                 case 's':
819                         type = LST_OPC_SESSION;
820                         break;
821
822                 case 'g':
823                         type = LST_OPC_GROUP;
824                         str = optarg;
825                         break;
826
827                 case 'b':
828                         type = LST_OPC_BATCHCLI;
829                         str = optarg;
830                         break;
831
832                 case 'n':
833                         type = LST_OPC_NODES;
834                         str = optarg;
835                         break;
836
837                 case 't':
838                         timeout = atoi(optarg);
839                         break;
840
841                 case 'v':
842                         server = 1;
843                         break;
844
845                 default:
846                         lst_print_usage(argv[0]);
847                         return -1;
848                 }
849         }
850
851         if (type == 0 || timeout <= 0 || optind != argc) {
852                 lst_print_usage(argv[0]);
853                 return -1;
854         }
855
856         if (type == LST_OPC_BATCHCLI && server)
857                 type = LST_OPC_BATCHSRV;
858
859         rc = lst_get_node_count(type, str, &count, &ids);
860         if (rc < 0) {
861                 fprintf(stderr, "Failed to get count of nodes from %s: %s\n",
862                         (str == NULL) ? "session" : str, strerror(errno));
863                 return -1;
864         }
865
866         INIT_LIST_HEAD(&head);
867
868         rc = lst_alloc_rpcent(&head, count, LST_NAME_SIZE);
869         if (rc != 0) {
870                 fprintf(stderr, "Out of memory\n");
871                 goto out;
872         }
873
874         if (count == 0) {
875                 fprintf(stdout, "Target %s is empty\n",
876                         (str == NULL) ? "session" : str);
877                 goto out;
878         }
879
880         rc = lst_ping_ioctl(str, type, timeout, count, ids, &head);
881         if (rc == -1) { /* local failure */
882                 lst_print_error("debug", "Failed to ping %s: %s\n",
883                                 (str == NULL) ? "session" : str,
884                                 strerror(errno));
885                 rc = -1;
886                 goto out;
887         }
888
889         /* ignore RPC errors and framwork errors */
890         list_for_each_entry(ent, &head, rpe_link) {
891                 fprintf(stdout, "\t%s: %s [session: %s id: %s]\n",
892                         libcfs_id2str(ent->rpe_peer),
893                         lst_node_state2str(ent->rpe_state),
894                         (ent->rpe_state == LST_NODE_ACTIVE ||
895                          ent->rpe_state == LST_NODE_BUSY) ?
896                                 (ent->rpe_rpc_errno == 0 ?
897                                         &ent->rpe_payload[0] : "Unknown") :
898                                 "<NULL>", libcfs_nid2str(ent->rpe_sid.ses_nid));
899         }
900
901 out:
902         lst_free_rpcent(&head);
903
904         if (ids != NULL)
905                 free(ids);
906
907         return rc;
908
909 }
910
911 int
912 lst_add_nodes_ioctl(char *name, int count, struct lnet_process_id *ids,
913                     unsigned *featp, struct list_head *resultp)
914 {
915         struct lstio_group_nodes_args args = { 0 };
916
917         args.lstio_grp_key     = session_key;
918         args.lstio_grp_nmlen   = strlen(name);
919         args.lstio_grp_namep   = name;
920         args.lstio_grp_count   = count;
921         args.lstio_grp_featp   = featp;
922         args.lstio_grp_idsp    = ids;
923         args.lstio_grp_resultp = resultp;
924
925         return lst_ioctl(LSTIO_NODES_ADD, &args, sizeof(args));
926 }
927
928 int
929 lst_del_group_ioctl(char *name)
930 {
931         struct lstio_group_del_args args = { 0 };
932
933         args.lstio_grp_key   = session_key;
934         args.lstio_grp_nmlen = strlen(name);
935         args.lstio_grp_namep = name;
936
937         return lst_ioctl(LSTIO_GROUP_DEL, &args, sizeof(args));
938 }
939
940 int
941 lst_del_group(char *grp_name)
942 {
943         int     rc;
944
945         rc = lst_del_group_ioctl(grp_name);
946         if (rc == 0) {
947                 fprintf(stdout, "Group is deleted\n");
948                 return 0;
949         }
950
951         if (rc == -1) {
952                 lst_print_error("group", "Failed to delete group: %s\n",
953                                 strerror(errno));
954                 return rc;
955         }
956
957         fprintf(stderr, "Group is deleted with some errors\n");
958
959         if (trans_stat.trs_rpc_errno != 0) {
960                 fprintf(stderr,
961                         "[RPC] Failed to send %d end session RPCs: %s\n",
962                         lstcon_rpc_stat_failure(&trans_stat, 0),
963                         strerror(trans_stat.trs_rpc_errno));
964         }
965
966         if (trans_stat.trs_fwk_errno != 0) {
967                 fprintf(stderr,
968                         "[FWK] Failed to end session on %d nodes: %s\n",
969                 lstcon_sesop_stat_failure(&trans_stat, 0),
970                 strerror(trans_stat.trs_fwk_errno));
971         }
972
973         return -1;
974 }
975
976 int
977 lst_add_group_ioctl(char *name)
978 {
979         struct lstio_group_add_args args = { 0 };
980
981         args.lstio_grp_key     =  session_key;
982         args.lstio_grp_nmlen   =  strlen(name);
983         args.lstio_grp_namep   =  name;
984
985         return lst_ioctl(LSTIO_GROUP_ADD, &args, sizeof(args));
986 }
987
988 int
989 jt_lst_add_group(int argc, char **argv)
990 {
991         struct list_head   head;
992         struct lnet_process_id *ids;
993         char              *name;
994         unsigned           feats = session_features;
995         int                count;
996         int                rc;
997         int                i;
998         bool               nodes_added = false;
999
1000         if (session_key == 0) {
1001                 fprintf(stderr,
1002                         "Can't find env LST_SESSION or value is not valid\n");
1003                 return -1;
1004         }
1005
1006         if (argc < 3) {
1007                 lst_print_usage(argv[0]);
1008                 return -1;
1009         }
1010
1011         name = argv[1];
1012         if (strlen(name) >= LST_NAME_SIZE) {
1013                 fprintf(stderr, "Name length is limited to %d\n",
1014                         LST_NAME_SIZE - 1);
1015                 return -1;
1016         }
1017
1018         rc = lst_add_group_ioctl(name);
1019         if (rc != 0) {
1020                 lst_print_error("group", "Failed to add group %s: %s\n",
1021                                 name, strerror(errno));
1022                 return -1;
1023         }
1024
1025         INIT_LIST_HEAD(&head);
1026
1027         for (i = 2; i < argc; i++) {
1028                 /* parse address list */
1029                 rc = lst_parse_nids(argv[i], &count, &ids);
1030                 if (rc < 0) {
1031                         fprintf(stderr, "Ignore invalid id list %s\n",
1032                                 argv[i]);
1033                         continue;
1034                 }
1035
1036                 if (count == 0)
1037                         continue;
1038
1039                 rc = lst_alloc_rpcent(&head, count, 0);
1040                 if (rc != 0) {
1041                         fprintf(stderr, "Out of memory\n");
1042                         free(ids);
1043                         rc = -1;
1044                         goto failed;
1045                 }
1046
1047                 rc = lst_add_nodes_ioctl(name, count, ids, &feats, &head);
1048
1049                 free(ids);
1050
1051                 if (rc != 0)
1052                         goto failed;
1053
1054                 fprintf(stdout, "%s are added to session\n", argv[i]);
1055
1056                 nodes_added = true;
1057
1058                 if ((feats & session_features) != session_features) {
1059                         fprintf(stdout,
1060                                 "Warning, this session will run with "
1061                                 "compatible mode because some test nodes "
1062                                 "might not understand these features: %x\n",
1063                                 (~feats & session_features));
1064                 }
1065
1066                 lst_free_rpcent(&head);
1067         }
1068
1069         if (!nodes_added) {
1070                 /*
1071                  * The selftest kernel module expects that a group should
1072                  * have at least one node, since it doesn't make sense for
1073                  * an empty group to be added to a test.
1074                  */
1075                 fprintf(stderr,
1076                         "No nodes added successfully, deleting group %s\n",
1077                         name);
1078                 rc = lst_del_group(name);
1079                 if (rc != 0) {
1080                         fprintf(stderr,
1081                                 "Failed to delete group %s."
1082                                 "  Group is empty.\n", name);
1083                 }
1084         }
1085
1086         return rc;
1087
1088 failed:
1089         if (rc == -1) {
1090                 lst_print_error("group", "Failed to add nodes %s: %s\n",
1091                                 argv[i], strerror(errno));
1092
1093         } else {
1094                 if (trans_stat.trs_fwk_errno == EPROTO) {
1095                         fprintf(stderr,
1096                                 "test nodes might have different LST "
1097                                 "features, please disable some features by "
1098                                 "setting LST_FEATURES\n");
1099                 }
1100
1101                 lst_print_transerr(&head, "create session");
1102         }
1103
1104         lst_free_rpcent(&head);
1105
1106         if (!nodes_added) {
1107                 fprintf(stderr,
1108                         "No nodes added successfully, deleting group %s\n",
1109                         name);
1110                 if (lst_del_group(name) != 0) {
1111                         fprintf(stderr,
1112                                 "Failed to delete group %s."
1113                                 "  Group is empty.\n", name);
1114                 }
1115         }
1116
1117         return rc;
1118 }
1119
1120 int
1121 jt_lst_del_group(int argc, char **argv)
1122 {
1123         int     rc;
1124
1125         if (session_key == 0) {
1126                 fprintf(stderr,
1127                         "Can't find env LST_SESSION or value is not valid\n");
1128                 return -1;
1129         }
1130
1131         if (argc != 2) {
1132                 lst_print_usage(argv[0]);
1133                 return -1;
1134         }
1135
1136         rc = lst_del_group(argv[1]);
1137
1138         return rc;
1139 }
1140
1141 int
1142 lst_update_group_ioctl(int opc, char *name, int clean, int count,
1143                        struct lnet_process_id *ids, struct list_head *resultp)
1144 {
1145         struct lstio_group_update_args args = { 0 };
1146
1147         args.lstio_grp_key      = session_key;
1148         args.lstio_grp_opc      = opc;
1149         args.lstio_grp_args     = clean;
1150         args.lstio_grp_nmlen    = strlen(name);
1151         args.lstio_grp_namep    = name;
1152         args.lstio_grp_count    = count;
1153         args.lstio_grp_idsp     = ids;
1154         args.lstio_grp_resultp  = resultp;
1155
1156         return lst_ioctl(LSTIO_GROUP_UPDATE, &args, sizeof(args));
1157 }
1158
1159 int
1160 jt_lst_update_group(int argc, char **argv)
1161 {
1162         struct list_head   head;
1163         struct lnet_process_id *ids = NULL;
1164         char              *str = NULL;
1165         char              *grp = NULL;
1166         int                optidx = 0;
1167         int                count = 0;
1168         int                clean = 0;
1169         int                opc = 0;
1170         int                rc;
1171         int                c;
1172
1173         static const struct option update_group_opts[] = {
1174                 { .name = "refresh", .has_arg = no_argument,       .val = 'f' },
1175                 { .name = "clean",   .has_arg = required_argument, .val = 'c' },
1176                 { .name = "remove",  .has_arg = required_argument, .val = 'r' },
1177                 { .name = NULL } };
1178
1179         if (session_key == 0) {
1180                 fprintf(stderr,
1181                         "Can't find env LST_SESSION or value is not valid\n");
1182                 return -1;
1183         }
1184
1185         while (1) {
1186                 c = getopt_long(argc, argv, "fc:r:",
1187                                 update_group_opts, &optidx);
1188
1189                 /* Detect the end of the options. */
1190                 if (c == -1)
1191                         break;
1192
1193                 switch (c) {
1194                 case 'f':
1195                         if (opc != 0) {
1196                                 lst_print_usage(argv[0]);
1197                                 return -1;
1198                         }
1199                         opc = LST_GROUP_REFRESH;
1200                         break;
1201
1202                 case 'r':
1203                         if (opc != 0) {
1204                                 lst_print_usage(argv[0]);
1205                                 return -1;
1206                         }
1207                         opc = LST_GROUP_RMND;
1208                         str = optarg;
1209                         break;
1210
1211                 case 'c':
1212                         clean = lst_node_str2state(optarg);
1213                         if (opc != 0 || clean <= 0) {
1214                                 lst_print_usage(argv[0]);
1215                                 return -1;
1216                         }
1217                         opc = LST_GROUP_CLEAN;
1218                         break;
1219
1220                 default:
1221                         lst_print_usage(argv[0]);
1222                         return -1;
1223                 }
1224         }
1225
1226         /* no OPC or group is specified */
1227         if (opc == 0 || optind != argc - 1) {
1228                 lst_print_usage(argv[0]);
1229                 return -1;
1230         }
1231
1232         grp = argv[optind];
1233
1234         INIT_LIST_HEAD(&head);
1235
1236         if (opc == LST_GROUP_RMND || opc == LST_GROUP_REFRESH) {
1237                 rc = lst_get_node_count(opc == LST_GROUP_RMND ? LST_OPC_NODES :
1238                                                                 LST_OPC_GROUP,
1239                                         opc == LST_GROUP_RMND ? str : grp,
1240                                         &count, &ids);
1241
1242                 if (rc != 0) {
1243                         fprintf(stderr, "Can't get count of nodes from %s: %s\n",
1244                                 opc == LST_GROUP_RMND ? str : grp,
1245                                 strerror(errno));
1246                         return -1;
1247                 }
1248
1249                 rc = lst_alloc_rpcent(&head, count, 0);
1250                 if (rc != 0) {
1251                         fprintf(stderr, "Out of memory\n");
1252                         free(ids);
1253                         return -1;
1254                 }
1255
1256         }
1257
1258         rc = lst_update_group_ioctl(opc, grp, clean, count, ids, &head);
1259
1260         if (ids != NULL)
1261                 free(ids);
1262
1263         if (rc == 0) {
1264                 lst_free_rpcent(&head);
1265                 return 0;
1266         }
1267
1268         if (rc == -1) {
1269                 lst_free_rpcent(&head);
1270                 lst_print_error("group", "Failed to update group: %s\n",
1271                                 strerror(errno));
1272                 return rc;
1273         }
1274
1275         lst_print_transerr(&head, "Updating group");
1276
1277         lst_free_rpcent(&head);
1278
1279         return rc;
1280 }
1281
1282 int
1283 lst_list_group_ioctl(int len, char *name, int idx)
1284 {
1285         struct lstio_group_list_args args = { 0 };
1286
1287         args.lstio_grp_key   = session_key;
1288         args.lstio_grp_idx   = idx;
1289         args.lstio_grp_nmlen = len;
1290         args.lstio_grp_namep = name;
1291
1292         return lst_ioctl(LSTIO_GROUP_LIST, &args, sizeof(args));
1293 }
1294
1295 int
1296 lst_info_group_ioctl(char *name, struct lstcon_ndlist_ent *gent,
1297                      int *idx, int *count, struct lstcon_node_ent *dents)
1298 {
1299         struct lstio_group_info_args args = { 0 };
1300
1301         args.lstio_grp_key    = session_key;
1302         args.lstio_grp_nmlen  = strlen(name);
1303         args.lstio_grp_namep  = name;
1304         args.lstio_grp_entp   = gent;
1305         args.lstio_grp_idxp   = idx;
1306         args.lstio_grp_ndentp = count;
1307         args.lstio_grp_dentsp = dents;
1308
1309         return lst_ioctl(LSTIO_GROUP_INFO, &args, sizeof(args));
1310 }
1311
1312 int
1313 lst_list_group_all(void)
1314 {
1315         char  name[LST_NAME_SIZE];
1316         int   rc;
1317         int   i;
1318
1319         /* no group is specified, list name of all groups */
1320         for (i = 0; ; i++) {
1321                 rc = lst_list_group_ioctl(LST_NAME_SIZE, name, i);
1322                 if (rc == 0) {
1323                         fprintf(stdout, "%d) %s\n", i + 1, name);
1324                         continue;
1325                 }
1326
1327                 if (errno == ENOENT)
1328                         break;
1329
1330                 lst_print_error("group", "Failed to list group: %s\n",
1331                                 strerror(errno));
1332                 return -1;
1333         }
1334
1335         fprintf(stdout, "Total %d groups\n", i);
1336
1337         return 0;
1338 }
1339
1340 #define LST_NODES_TITLE "\tACTIVE\tBUSY\tDOWN\tUNKNOWN\tTOTAL\n"
1341
1342 int
1343 jt_lst_list_group(int argc, char **argv)
1344 {
1345         struct lstcon_ndlist_ent gent;
1346         struct lstcon_node_ent   *dents;
1347         int optidx  = 0;
1348         int verbose = 0;
1349         int active  = 0;
1350         int busy    = 0;
1351         int down    = 0;
1352         int unknown = 0;
1353         int all     = 0;
1354         int count;
1355         int index;
1356         int i;
1357         int j;
1358         int c;
1359         int rc      = 0;
1360
1361         static const struct option list_group_opts[] = {
1362                 { .name = "active",  .has_arg = no_argument, .val = 'a' },
1363                 { .name = "busy",    .has_arg = no_argument, .val = 'b' },
1364                 { .name = "down",    .has_arg = no_argument, .val = 'd' },
1365                 { .name = "unknown", .has_arg = no_argument, .val = 'u' },
1366                 { .name = "all",     .has_arg = no_argument, .val = 'l' },
1367                 { .name = NULL, } };
1368
1369         if (session_key == 0) {
1370                 fprintf(stderr,
1371                         "Can't find env LST_SESSION or value is not valid\n");
1372                 return -1;
1373         }
1374
1375         while (1) {
1376                 c = getopt_long(argc, argv, "abdul",
1377                                 list_group_opts, &optidx);
1378
1379                 if (c == -1)
1380                         break;
1381
1382                 switch (c) {
1383                 case 'a':
1384                         verbose = active = 1;
1385                         all = 0;
1386                         break;
1387                 case 'b':
1388                         verbose = busy = 1;
1389                         all = 0;
1390                         break;
1391                 case 'd':
1392                         verbose = down = 1;
1393                         all = 0;
1394                         break;
1395                 case 'u':
1396                         verbose = unknown = 1;
1397                         all = 0;
1398                         break;
1399                 case 'l':
1400                         verbose = all = 1;
1401                         break;
1402                 default:
1403                         lst_print_usage(argv[0]);
1404                         return -1;
1405                 }
1406         }
1407
1408         if (optind == argc) {
1409                 /* no group is specified, list name of all groups */
1410                 rc = lst_list_group_all();
1411
1412                 return rc;
1413         }
1414
1415         if (!verbose)
1416                 fprintf(stdout, LST_NODES_TITLE);
1417
1418         /* list nodes in specified groups */
1419         for (i = optind; i < argc; i++) {
1420                 rc = lst_info_group_ioctl(argv[i], &gent, NULL, NULL, NULL);
1421                 if (rc != 0) {
1422                         if (errno == ENOENT) {
1423                                 rc = 0;
1424                                 break;
1425                         }
1426
1427                         lst_print_error("group", "Failed to list group\n",
1428                                         strerror(errno));
1429                         break;
1430                 }
1431
1432                 if (!verbose) {
1433                         fprintf(stdout, "\t%d\t%d\t%d\t%d\t%d\t%s\n",
1434                                 gent.nle_nactive, gent.nle_nbusy,
1435                                 gent.nle_ndown, gent.nle_nunknown,
1436                                 gent.nle_nnode, argv[i]);
1437                         continue;
1438                 }
1439
1440                 fprintf(stdout, "Group [ %s ]\n", argv[i]);
1441
1442                 if (gent.nle_nnode == 0) {
1443                         fprintf(stdout, "No nodes found [ %s ]\n", argv[i]);
1444                         continue;
1445                 }
1446
1447                 count = gent.nle_nnode;
1448
1449                 dents = malloc(count * sizeof(struct lstcon_node_ent));
1450                 if (dents == NULL) {
1451                         fprintf(stderr, "Failed to malloc: %s\n",
1452                                 strerror(errno));
1453                         return -1;
1454                 }
1455
1456                 index = 0;
1457                 rc = lst_info_group_ioctl(argv[i], &gent, &index, &count, dents);
1458                 if (rc != 0) {
1459                         lst_print_error("group", "Failed to list group: %s\n",
1460                                         strerror(errno));
1461                         free(dents);
1462                         return -1;
1463                 }
1464
1465                 for (j = 0, c = 0; j < count; j++) {
1466                         if (all ||
1467                             ((active  &&  dents[j].nde_state == LST_NODE_ACTIVE) ||
1468                              (busy    &&  dents[j].nde_state == LST_NODE_BUSY)   ||
1469                              (down    &&  dents[j].nde_state == LST_NODE_DOWN)   ||
1470                              (unknown &&  dents[j].nde_state == LST_NODE_UNKNOWN))) {
1471
1472                                 fprintf(stdout, "\t%s: %s\n",
1473                                         libcfs_id2str(dents[j].nde_id),
1474                                         lst_node_state2str(dents[j].nde_state));
1475                                 c++;
1476                         }
1477                 }
1478
1479                 fprintf(stdout, "Total %d nodes [ %s ]\n", c, argv[i]);
1480
1481                 free(dents);
1482         }
1483
1484         return rc;
1485 }
1486
1487 int
1488 lst_stat_ioctl(char *name, int count, struct lnet_process_id *idsp,
1489                int timeout, struct list_head *resultp)
1490 {
1491         struct lstio_stat_args args = { 0 };
1492
1493         args.lstio_sta_key     = session_key;
1494         args.lstio_sta_timeout = timeout;
1495         args.lstio_sta_nmlen   = strlen(name);
1496         args.lstio_sta_namep   = name;
1497         args.lstio_sta_count   = count;
1498         args.lstio_sta_idsp    = idsp;
1499         args.lstio_sta_resultp = resultp;
1500
1501         return lst_ioctl(LSTIO_STAT_QUERY, &args, sizeof(args));
1502 }
1503
1504 typedef struct {
1505         struct list_head              srp_link;
1506         int                     srp_count;
1507         char                   *srp_name;
1508         struct lnet_process_id      *srp_ids;
1509         struct list_head              srp_result[2];
1510 } lst_stat_req_param_t;
1511
1512 static void
1513 lst_stat_req_param_free(lst_stat_req_param_t *srp)
1514 {
1515         int     i;
1516
1517         for (i = 0; i < 2; i++)
1518                 lst_free_rpcent(&srp->srp_result[i]);
1519
1520         if (srp->srp_ids != NULL)
1521                 free(srp->srp_ids);
1522
1523         free(srp);
1524 }
1525
1526 static int
1527 lst_stat_req_param_alloc(char *name, lst_stat_req_param_t **srpp, int save_old)
1528 {
1529         lst_stat_req_param_t *srp = NULL;
1530         int                   count = save_old ? 2 : 1;
1531         int                   rc;
1532         int                   i;
1533
1534         srp = malloc(sizeof(*srp));
1535         if (srp == NULL)
1536                 return -ENOMEM;
1537
1538         memset(srp, 0, sizeof(*srp));
1539         INIT_LIST_HEAD(&srp->srp_result[0]);
1540         INIT_LIST_HEAD(&srp->srp_result[1]);
1541
1542         rc = lst_get_node_count(LST_OPC_GROUP, name,
1543                                 &srp->srp_count, NULL);
1544         if (rc != 0 && errno == ENOENT) {
1545                 rc = lst_get_node_count(LST_OPC_NODES, name,
1546                                         &srp->srp_count, &srp->srp_ids);
1547         }
1548
1549         if (rc != 0) {
1550                 fprintf(stderr,
1551                         "Failed to get count of nodes from %s: %s\n",
1552                         name, strerror(errno));
1553                 lst_stat_req_param_free(srp);
1554
1555                 return rc;
1556         }
1557
1558         srp->srp_name = name;
1559
1560         for (i = 0; i < count; i++) {
1561                 rc = lst_alloc_rpcent(&srp->srp_result[i], srp->srp_count,
1562                                       sizeof(struct sfw_counters)  +
1563                                       sizeof(struct srpc_counters) +
1564                                       sizeof(struct lnet_counters_common));
1565                 if (rc != 0) {
1566                         fprintf(stderr, "Out of memory\n");
1567                         break;
1568                 }
1569         }
1570
1571         if (rc == 0) {
1572                 *srpp = srp;
1573                 return 0;
1574         }
1575
1576         lst_stat_req_param_free(srp);
1577
1578         return rc;
1579 }
1580
1581 typedef struct {
1582         /* TODO */
1583         int foo;
1584 } lst_srpc_stat_result;
1585
1586 #define LST_LNET_AVG    0
1587 #define LST_LNET_MIN    1
1588 #define LST_LNET_MAX    2
1589
1590 typedef struct {
1591         float           lnet_avg_sndrate;
1592         float           lnet_min_sndrate;
1593         float           lnet_max_sndrate;
1594         float           lnet_total_sndrate;
1595
1596         float           lnet_avg_rcvrate;
1597         float           lnet_min_rcvrate;
1598         float           lnet_max_rcvrate;
1599         float           lnet_total_rcvrate;
1600
1601         float           lnet_avg_sndperf;
1602         float           lnet_min_sndperf;
1603         float           lnet_max_sndperf;
1604         float           lnet_total_sndperf;
1605
1606         float           lnet_avg_rcvperf;
1607         float           lnet_min_rcvperf;
1608         float           lnet_max_rcvperf;
1609         float           lnet_total_rcvperf;
1610
1611         int             lnet_stat_count;
1612 } lst_lnet_stat_result_t;
1613
1614 lst_lnet_stat_result_t lnet_stat_result;
1615
1616 static float
1617 lst_lnet_stat_value(int bw, int send, int off)
1618 {
1619         float  *p;
1620
1621         p = bw ? &lnet_stat_result.lnet_avg_sndperf :
1622                  &lnet_stat_result.lnet_avg_sndrate;
1623
1624         if (!send)
1625                 p += 4;
1626
1627         p += off;
1628
1629         return *p;
1630 }
1631
1632 static void
1633 lst_cal_lnet_stat(float delta, struct lnet_counters_common *lnet_new,
1634                   struct lnet_counters_common *lnet_old, int mbs)
1635 {
1636         float perf;
1637         float rate;
1638         unsigned int unit_divisor;
1639
1640         unit_divisor = (mbs) ? (1000 * 1000) : (1024 * 1024);
1641         perf = (float)(lnet_new->lcc_send_length -
1642                        lnet_old->lcc_send_length) / unit_divisor / delta;
1643         lnet_stat_result.lnet_total_sndperf += perf;
1644
1645         if (lnet_stat_result.lnet_min_sndperf > perf ||
1646             lnet_stat_result.lnet_min_sndperf == 0)
1647                 lnet_stat_result.lnet_min_sndperf = perf;
1648
1649         if (lnet_stat_result.lnet_max_sndperf < perf)
1650                 lnet_stat_result.lnet_max_sndperf = perf;
1651
1652         perf = (float)(lnet_new->lcc_recv_length -
1653                        lnet_old->lcc_recv_length) / unit_divisor / delta;
1654         lnet_stat_result.lnet_total_rcvperf += perf;
1655
1656         if (lnet_stat_result.lnet_min_rcvperf > perf ||
1657             lnet_stat_result.lnet_min_rcvperf == 0)
1658                 lnet_stat_result.lnet_min_rcvperf = perf;
1659
1660         if (lnet_stat_result.lnet_max_rcvperf < perf)
1661                 lnet_stat_result.lnet_max_rcvperf = perf;
1662
1663         rate = (lnet_new->lcc_send_count - lnet_old->lcc_send_count) / delta;
1664         lnet_stat_result.lnet_total_sndrate += rate;
1665
1666         if (lnet_stat_result.lnet_min_sndrate > rate ||
1667             lnet_stat_result.lnet_min_sndrate == 0)
1668                 lnet_stat_result.lnet_min_sndrate = rate;
1669
1670         if (lnet_stat_result.lnet_max_sndrate < rate)
1671                 lnet_stat_result.lnet_max_sndrate = rate;
1672
1673         rate = (lnet_new->lcc_recv_count - lnet_old->lcc_recv_count) / delta;
1674         lnet_stat_result.lnet_total_rcvrate += rate;
1675
1676         if (lnet_stat_result.lnet_min_rcvrate > rate ||
1677             lnet_stat_result.lnet_min_rcvrate == 0)
1678                 lnet_stat_result.lnet_min_rcvrate = rate;
1679
1680         if (lnet_stat_result.lnet_max_rcvrate < rate)
1681                 lnet_stat_result.lnet_max_rcvrate = rate;
1682
1683         lnet_stat_result.lnet_stat_count++;
1684
1685         lnet_stat_result.lnet_avg_sndrate = lnet_stat_result.lnet_total_sndrate /
1686                                             lnet_stat_result.lnet_stat_count;
1687         lnet_stat_result.lnet_avg_rcvrate = lnet_stat_result.lnet_total_rcvrate /
1688                                             lnet_stat_result.lnet_stat_count;
1689
1690         lnet_stat_result.lnet_avg_sndperf = lnet_stat_result.lnet_total_sndperf /
1691                                             lnet_stat_result.lnet_stat_count;
1692         lnet_stat_result.lnet_avg_rcvperf = lnet_stat_result.lnet_total_rcvperf /
1693                                             lnet_stat_result.lnet_stat_count;
1694 }
1695
1696 static void
1697 lst_print_lnet_stat(char *name, int bwrt, int rdwr, int type, int mbs)
1698 {
1699         int     start1 = 0;
1700         int     end1   = 1;
1701         int     start2 = 0;
1702         int     end2   = 1;
1703         int     i;
1704         int     j;
1705         char   *units;
1706
1707         if (lnet_stat_result.lnet_stat_count == 0)
1708                 return;
1709
1710         units = (mbs) ? "MB/s  " : "MiB/s ";
1711
1712         if (bwrt == 1) /* bw only */
1713                 start1 = 1;
1714
1715         if (bwrt == 2) /* rates only */
1716                 end1 = 0;
1717
1718         if (rdwr == 1) /* recv only */
1719                 start2 = 1;
1720
1721         if (rdwr == 2) /* send only */
1722                 end2 = 0;
1723
1724         for (i = start1; i <= end1; i++) {
1725                 fprintf(stdout, "[LNet %s of %s]\n",
1726                         i == 0 ? "Rates" : "Bandwidth", name);
1727
1728                 for (j = start2; j <= end2; j++) {
1729                         fprintf(stdout, "[%c] ", j == 0 ? 'R' : 'W');
1730
1731                         if ((type & 1) != 0) {
1732                                 fprintf(stdout, i == 0 ? "Avg: %-8.0f RPC/s " :
1733                                                          "Avg: %-8.2f %s",
1734                                         lst_lnet_stat_value(i, j, 0), units);
1735                         }
1736
1737                         if ((type & 2) != 0) {
1738                                 fprintf(stdout, i == 0 ? "Min: %-8.0f RPC/s " :
1739                                                          "Min: %-8.2f %s",
1740                                         lst_lnet_stat_value(i, j, 1), units);
1741                         }
1742
1743                         if ((type & 4) != 0) {
1744                                 fprintf(stdout, i == 0 ? "Max: %-8.0f RPC/s" :
1745                                                          "Max: %-8.2f %s",
1746                                         lst_lnet_stat_value(i, j, 2), units);
1747                         }
1748
1749                         fprintf(stdout, "\n");
1750                 }
1751         }
1752 }
1753
1754 static void
1755 lst_print_stat(char *name, struct list_head *resultp,
1756                int idx, int lnet, int bwrt, int rdwr, int type,
1757                int mbs)
1758 {
1759         struct list_head tmp[2];
1760         struct lstcon_rpc_ent *new;
1761         struct lstcon_rpc_ent *old;
1762         struct sfw_counters *sfwk_new;
1763         struct sfw_counters *sfwk_old;
1764         struct srpc_counters *srpc_new;
1765         struct srpc_counters *srpc_old;
1766         struct lnet_counters_common *lnet_new;
1767         struct lnet_counters_common *lnet_old;
1768         float delta;
1769         int errcount = 0;
1770
1771         INIT_LIST_HEAD(&tmp[0]);
1772         INIT_LIST_HEAD(&tmp[1]);
1773
1774         memset(&lnet_stat_result, 0, sizeof(lnet_stat_result));
1775
1776         while (!list_empty(&resultp[idx])) {
1777                 if (list_empty(&resultp[1 - idx])) {
1778                         fprintf(stderr, "Group is changed, re-run stat\n");
1779                         break;
1780                 }
1781
1782                 new = list_entry(resultp[idx].next, struct lstcon_rpc_ent,
1783                                      rpe_link);
1784                 old = list_entry(resultp[1 - idx].next, struct lstcon_rpc_ent,
1785                                      rpe_link);
1786
1787                 /* first time get stats result, can't calculate diff */
1788                 if (new->rpe_peer.nid == LNET_NID_ANY)
1789                         break;
1790
1791                 if (new->rpe_peer.nid != old->rpe_peer.nid ||
1792                     new->rpe_peer.pid != old->rpe_peer.pid) {
1793                         /* Something wrong. i.e, somebody change the group */
1794                         break;
1795                 }
1796
1797                 list_move_tail(&new->rpe_link, &tmp[idx]);
1798
1799                 list_move_tail(&old->rpe_link, &tmp[1 - idx]);
1800
1801                 if (new->rpe_rpc_errno != 0 || new->rpe_fwk_errno != 0 ||
1802                     old->rpe_rpc_errno != 0 || old->rpe_fwk_errno != 0) {
1803                         errcount ++;
1804                         continue;
1805                 }
1806
1807                 sfwk_new = (struct sfw_counters *)&new->rpe_payload[0];
1808                 sfwk_old = (struct sfw_counters *)&old->rpe_payload[0];
1809
1810                 srpc_new = (struct srpc_counters *)((char *)sfwk_new +
1811                                                     sizeof(*sfwk_new));
1812                 srpc_old = (struct srpc_counters *)((char *)sfwk_old +
1813                                                     sizeof(*sfwk_old));
1814
1815                 lnet_new = (struct lnet_counters_common *)((char *)srpc_new +
1816                                                            sizeof(*srpc_new));
1817                 lnet_old = (struct lnet_counters_common *)((char *)srpc_old +
1818                                                            sizeof(*srpc_old));
1819
1820                 /* Prior to version 2.3, the running_ms was a counter for
1821                  * the number of running tests. Since 2.3, running_ms is
1822                  * changed to hold the millisecond since the start of
1823                  * the work item. The rpe_stamp field was formerly used,
1824                  * but is no longer. In 2.12 rpe_stamp was changed to
1825                  * struct timespec64 and has nanosecond resolution, in
1826                  * case it is needed in the future.
1827                  */
1828                 delta = (float)(sfwk_new->running_ms -
1829                                 sfwk_old->running_ms) / 1000;
1830
1831                 if (!lnet) /* TODO */
1832                         continue;
1833
1834                 lst_cal_lnet_stat(delta, lnet_new, lnet_old, mbs);
1835         }
1836
1837         list_splice(&tmp[idx], &resultp[idx]);
1838         list_splice(&tmp[1 - idx], &resultp[1 - idx]);
1839
1840         if (errcount > 0)
1841                 fprintf(stdout, "Failed to stat on %d nodes\n", errcount);
1842
1843         if (!lnet)  /* TODO */
1844                 return;
1845
1846         lst_print_lnet_stat(name, bwrt, rdwr, type, mbs);
1847 }
1848
1849 int
1850 jt_lst_stat(int argc, char **argv)
1851 {
1852         struct list_head        head;
1853         lst_stat_req_param_t *srp;
1854         time_t                last    = 0;
1855         int                   optidx  = 0;
1856         int                   timeout = 5; /* default timeout, 5 sec */
1857         int                   delay   = 5; /* default delay, 5 sec */
1858         int                   count   = -1; /* run forever */
1859         int                   lnet    = 1; /* lnet stat by default */
1860         int                   bwrt    = 0;
1861         int                   rdwr    = 0;
1862         int                   type    = -1;
1863         int                   idx     = 0;
1864         int                   rc;
1865         int                   c;
1866         int                   mbs     = 0; /* report as MB/s */
1867
1868         static const struct option stat_opts[] = {
1869                 { .name = "timeout", .has_arg = required_argument, .val = 't' },
1870                 { .name = "delay",   .has_arg = required_argument, .val = 'd' },
1871                 { .name = "count",   .has_arg = required_argument, .val = 'o' },
1872                 { .name = "lnet",    .has_arg = no_argument,       .val = 'l' },
1873                 { .name = "rpc",     .has_arg = no_argument,       .val = 'c' },
1874                 { .name = "bw",      .has_arg = no_argument,       .val = 'b' },
1875                 { .name = "rate",    .has_arg = no_argument,       .val = 'a' },
1876                 { .name = "read",    .has_arg = no_argument,       .val = 'r' },
1877                 { .name = "write",   .has_arg = no_argument,       .val = 'w' },
1878                 { .name = "avg",     .has_arg = no_argument,       .val = 'g' },
1879                 { .name = "min",     .has_arg = no_argument,       .val = 'n' },
1880                 { .name = "max",     .has_arg = no_argument,       .val = 'x' },
1881                 { .name = "mbs",     .has_arg = no_argument,       .val = 'm' },
1882                 { .name = NULL } };
1883
1884         if (session_key == 0) {
1885                 fprintf(stderr,
1886                         "Can't find env LST_SESSION or value is not valid\n");
1887                 return -1;
1888         }
1889
1890         while (1) {
1891                 c = getopt_long(argc, argv, "t:d:lcbarwgnxm", stat_opts,
1892                                 &optidx);
1893
1894                 if (c == -1)
1895                         break;
1896
1897                 switch (c) {
1898                 case 't':
1899                         timeout = atoi(optarg);
1900                         break;
1901                 case 'd':
1902                         delay = atoi(optarg);
1903                         break;
1904                 case 'o':
1905                         count = atoi(optarg);
1906                         break;
1907                 case 'l':
1908                         lnet = 1;
1909                         break;
1910                 case 'c':
1911                         lnet = 0;
1912                         break;
1913                 case 'b':
1914                         bwrt |= 1;
1915                         break;
1916                 case 'a':
1917                         bwrt |= 2;
1918                         break;
1919                 case 'r':
1920                         rdwr |= 1;
1921                         break;
1922                 case 'w':
1923                         rdwr |= 2;
1924                         break;
1925                 case 'g':
1926                         if (type == -1) {
1927                                 type = 1;
1928                                 break;
1929                         }
1930                         type |= 1;
1931                         break;
1932                 case 'n':
1933                         if (type == -1) {
1934                                 type = 2;
1935                                 break;
1936                         }
1937                         type |= 2;
1938                         break;
1939                 case 'x':
1940                         if (type == -1) {
1941                                 type = 4;
1942                                 break;
1943                         }
1944                         type |= 4;
1945                         break;
1946                 case 'm':
1947                         mbs = 1;
1948                         break;
1949
1950                 default:
1951                         lst_print_usage(argv[0]);
1952                         return -1;
1953                 }
1954         }
1955
1956         if (optind == argc) {
1957                 lst_print_usage(argv[0]);
1958                 return -1;
1959         }
1960
1961         if (timeout <= 0 || delay <= 0) {
1962                 fprintf(stderr, "Invalid timeout or delay value\n");
1963                 return -1;
1964         }
1965
1966         if (count < -1) {
1967             fprintf(stderr, "Invalid count value\n");
1968             return -1;
1969         }
1970
1971         /* extra count to get first data point */
1972         if (count != -1)
1973             count++;
1974
1975         INIT_LIST_HEAD(&head);
1976
1977         while (optind < argc) {
1978                 rc = lst_stat_req_param_alloc(argv[optind++], &srp, 1);
1979                 if (rc != 0)
1980                         goto out;
1981
1982                 list_add_tail(&srp->srp_link, &head);
1983         }
1984
1985         do {
1986                 time_t  now = time(NULL);
1987
1988                 if (now - last < delay) {
1989                         sleep(delay - now + last);
1990                         time(&now);
1991                 }
1992                 last = now;
1993
1994                 list_for_each_entry(srp, &head, srp_link) {
1995                         rc = lst_stat_ioctl(srp->srp_name,
1996                                             srp->srp_count, srp->srp_ids,
1997                                             timeout, &srp->srp_result[idx]);
1998                         if (rc == -1) {
1999                                 lst_print_error("stat", "Failed to stat %s: %s\n",
2000                                                 srp->srp_name, strerror(errno));
2001                                 goto out;
2002                         }
2003
2004                         lst_print_stat(srp->srp_name, srp->srp_result,
2005                                        idx, lnet, bwrt, rdwr, type, mbs);
2006
2007                         lst_reset_rpcent(&srp->srp_result[1 - idx]);
2008                 }
2009
2010                 idx = 1 - idx;
2011
2012                 if (count > 0)
2013                         count--;
2014         } while (count == -1 || count > 0);
2015
2016 out:
2017         while (!list_empty(&head)) {
2018                 srp = list_entry(head.next, lst_stat_req_param_t, srp_link);
2019
2020                 list_del(&srp->srp_link);
2021                 lst_stat_req_param_free(srp);
2022         }
2023
2024         return rc;
2025 }
2026
2027 int
2028 jt_lst_show_error(int argc, char **argv)
2029 {
2030         struct list_head       head;
2031         lst_stat_req_param_t  *srp;
2032         struct lstcon_rpc_ent *ent;
2033         struct sfw_counters   *sfwk;
2034         struct srpc_counters  *srpc;
2035         int                    show_rpc = 1;
2036         int                    optidx = 0;
2037         int                    rc = 0;
2038         int                    ecount;
2039         int                    c;
2040
2041         static const struct option show_error_opts[] = {
2042                 { .name = "session", .has_arg = no_argument, .val = 's' },
2043                 { .name = NULL, } };
2044
2045         if (session_key == 0) {
2046                 fprintf(stderr,
2047                         "Can't find env LST_SESSION or value is not valid\n");
2048                 return -1;
2049         }
2050
2051         while (1) {
2052                 c = getopt_long(argc, argv, "s", show_error_opts, &optidx);
2053
2054                 if (c == -1)
2055                         break;
2056
2057                 switch (c) {
2058                 case 's':
2059                         show_rpc  = 0;
2060                         break;
2061
2062                 default:
2063                         lst_print_usage(argv[0]);
2064                         return -1;
2065                 }
2066         }
2067
2068         if (optind == argc) {
2069                 lst_print_usage(argv[0]);
2070                 return -1;
2071         }
2072
2073         INIT_LIST_HEAD(&head);
2074
2075         while (optind < argc) {
2076                 rc = lst_stat_req_param_alloc(argv[optind++], &srp, 0);
2077                 if (rc != 0)
2078                         goto out;
2079
2080                 list_add_tail(&srp->srp_link, &head);
2081         }
2082
2083         list_for_each_entry(srp, &head, srp_link) {
2084                 rc = lst_stat_ioctl(srp->srp_name, srp->srp_count,
2085                                     srp->srp_ids, 10, &srp->srp_result[0]);
2086
2087                 if (rc == -1) {
2088                         lst_print_error(srp->srp_name, "Failed to show errors of %s: %s\n",
2089                                         srp->srp_name, strerror(errno));
2090                         goto out;
2091                 }
2092
2093                 fprintf(stdout, "%s:\n", srp->srp_name);
2094
2095                 ecount = 0;
2096
2097                 list_for_each_entry(ent, &srp->srp_result[0], rpe_link) {
2098                         if (ent->rpe_rpc_errno != 0) {
2099                                 ecount ++;
2100                                 fprintf(stderr, "RPC failure, can't show error on %s\n",
2101                                         libcfs_id2str(ent->rpe_peer));
2102                                 continue;
2103                         }
2104
2105                         if (ent->rpe_fwk_errno != 0) {
2106                                 ecount ++;
2107                                 fprintf(stderr, "Framework failure, can't show error on %s\n",
2108                                         libcfs_id2str(ent->rpe_peer));
2109                                 continue;
2110                         }
2111
2112                         sfwk = (struct sfw_counters *)&ent->rpe_payload[0];
2113                         srpc = (struct srpc_counters *)((char *)sfwk + sizeof(*sfwk));
2114
2115                         if (srpc->errors == 0 &&
2116                             sfwk->brw_errors == 0 && sfwk->ping_errors == 0)
2117                                 continue;
2118
2119                         if (!show_rpc  &&
2120                             sfwk->brw_errors == 0 && sfwk->ping_errors == 0)
2121                                 continue;
2122
2123                         ecount ++;
2124
2125                         fprintf(stderr, "%s: [Session %d brw errors, %d ping errors]%c",
2126                                 libcfs_id2str(ent->rpe_peer),
2127                                 sfwk->brw_errors, sfwk->ping_errors,
2128                                 show_rpc  ? ' ' : '\n');
2129
2130                         if (!show_rpc)
2131                                 continue;
2132
2133                         fprintf(stderr, "[RPC: %d errors, %d dropped, %d expired]\n",
2134                                 srpc->errors, srpc->rpcs_dropped, srpc->rpcs_expired);
2135                 }
2136
2137                 fprintf(stdout, "Total %d error nodes in %s\n", ecount, srp->srp_name);
2138         }
2139 out:
2140         while (!list_empty(&head)) {
2141                 srp = list_entry(head.next, lst_stat_req_param_t, srp_link);
2142
2143                 list_del(&srp->srp_link);
2144                 lst_stat_req_param_free(srp);
2145         }
2146
2147         return rc;
2148 }
2149
2150 int
2151 lst_add_batch_ioctl(char *name)
2152 {
2153         struct lstio_batch_add_args args = { 0 };
2154
2155         args.lstio_bat_key   = session_key;
2156         args.lstio_bat_nmlen = strlen(name);
2157         args.lstio_bat_namep = name;
2158
2159         return lst_ioctl (LSTIO_BATCH_ADD, &args, sizeof(args));
2160 }
2161
2162 int
2163 jt_lst_add_batch(int argc, char **argv)
2164 {
2165         char   *name;
2166         int     rc;
2167
2168         if (session_key == 0) {
2169                 fprintf(stderr,
2170                         "Can't find env LST_SESSION or value is not valid\n");
2171                 return -1;
2172         }
2173
2174         if (argc != 2) {
2175                 lst_print_usage(argv[0]);
2176                 return -1;
2177         }
2178
2179         name = argv[1];
2180         if (strlen(name) >= LST_NAME_SIZE) {
2181                 fprintf(stderr, "Name length is limited to %d\n",
2182                         LST_NAME_SIZE - 1);
2183                 return -1;
2184         }
2185
2186         rc = lst_add_batch_ioctl(name);
2187         if (rc == 0)
2188                 return 0;
2189
2190         lst_print_error("batch", "Failed to create batch: %s\n",
2191                         strerror(errno));
2192
2193         return -1;
2194 }
2195
2196 int
2197 lst_start_batch_ioctl(char *name, int timeout, struct list_head *resultp)
2198 {
2199         struct lstio_batch_run_args args = { 0 };
2200
2201         args.lstio_bat_key     = session_key;
2202         args.lstio_bat_timeout = timeout;
2203         args.lstio_bat_nmlen   = strlen(name);
2204         args.lstio_bat_namep   = name;
2205         args.lstio_bat_resultp = resultp;
2206
2207         return lst_ioctl(LSTIO_BATCH_START, &args, sizeof(args));
2208 }
2209
2210 int
2211 jt_lst_start_batch(int argc, char **argv)
2212 {
2213         struct list_head  head;
2214         char             *batch;
2215         int               optidx = 0;
2216         int               timeout = 0;
2217         int               count = 0;
2218         int               rc;
2219         int               c;
2220
2221         static const struct option start_batch_opts[] = {
2222                 { .name = "timeout", .has_arg = required_argument, .val = 't' },
2223                 { .name = NULL } };
2224
2225         if (session_key == 0) {
2226                 fprintf(stderr,
2227                         "Can't find env LST_SESSION or value is not valid\n");
2228                 return -1;
2229         }
2230
2231         while (1) {
2232                 c = getopt_long(argc, argv, "t:",
2233                                 start_batch_opts, &optidx);
2234
2235                 /* Detect the end of the options. */
2236                 if (c == -1)
2237                         break;
2238
2239                 switch (c) {
2240                 case 't':
2241                         timeout = atoi(optarg);
2242                         break;
2243                 default:
2244                         lst_print_usage(argv[0]);
2245                         return -1;
2246                 }
2247         }
2248
2249         if (optind == argc) {
2250                 batch = LST_DEFAULT_BATCH;
2251
2252         } else if (optind == argc - 1) {
2253                 batch = argv[optind];
2254
2255         } else {
2256                 lst_print_usage(argv[0]);
2257                 return -1;
2258         }
2259
2260         rc = lst_get_node_count(LST_OPC_BATCHCLI, batch, &count, NULL);
2261         if (rc != 0) {
2262                 fprintf(stderr, "Failed to get count of nodes from %s: %s\n",
2263                         batch, strerror(errno));
2264                 return -1;
2265         }
2266
2267         INIT_LIST_HEAD(&head);
2268
2269         rc = lst_alloc_rpcent(&head, count, 0);
2270         if (rc != 0) {
2271                 fprintf(stderr, "Out of memory\n");
2272                 return -1;
2273         }
2274
2275         rc = lst_start_batch_ioctl(batch, timeout, &head);
2276
2277         if (rc == 0) {
2278                 fprintf(stdout, "%s is running now\n", batch);
2279                 lst_free_rpcent(&head);
2280                 return 0;
2281         }
2282
2283         if (rc == -1) {
2284                 lst_print_error("batch", "Failed to start batch: %s\n",
2285                                 strerror(errno));
2286                 lst_free_rpcent(&head);
2287                 return rc;
2288         }
2289
2290         lst_print_transerr(&head, "Run batch");
2291
2292         lst_free_rpcent(&head);
2293
2294         return rc;
2295 }
2296
2297 int
2298 lst_stop_batch_ioctl(char *name, int force, struct list_head *resultp)
2299 {
2300         struct lstio_batch_stop_args args = { 0 };
2301
2302         args.lstio_bat_key     = session_key;
2303         args.lstio_bat_force   = force;
2304         args.lstio_bat_nmlen   = strlen(name);
2305         args.lstio_bat_namep   = name;
2306         args.lstio_bat_resultp = resultp;
2307
2308         return lst_ioctl(LSTIO_BATCH_STOP, &args, sizeof(args));
2309 }
2310
2311 int
2312 jt_lst_stop_batch(int argc, char **argv)
2313 {
2314         struct list_head  head;
2315         char             *batch;
2316         int               force = 0;
2317         int               optidx;
2318         int               count;
2319         int               rc;
2320         int               c;
2321
2322         static const struct option stop_batch_opts[] = {
2323                 { .name = "force", .has_arg = no_argument, .val = 'f' },
2324                 { .name = NULL } };
2325
2326         if (session_key == 0) {
2327                 fprintf(stderr,
2328                         "Can't find env LST_SESSION or value is not valid\n");
2329                 return -1;
2330         }
2331
2332         while (1) {
2333                 c = getopt_long(argc, argv, "f",
2334                                 stop_batch_opts, &optidx);
2335
2336                 /* Detect the end of the options. */
2337                 if (c == -1)
2338                         break;
2339
2340                 switch (c) {
2341                 case 'f':
2342                         force = 1;
2343                         break;
2344                 default:
2345                         lst_print_usage(argv[0]);
2346                         return -1;
2347                 }
2348         }
2349
2350         if (optind == argc) {
2351                 batch = LST_DEFAULT_BATCH;
2352
2353         } else if (optind == argc - 1) {
2354                 batch = argv[optind];
2355
2356         } else {
2357                 lst_print_usage(argv[0]);
2358                 return -1;
2359         }
2360
2361         rc = lst_get_node_count(LST_OPC_BATCHCLI, batch, &count, NULL);
2362         if (rc != 0) {
2363                 fprintf(stderr, "Failed to get count of nodes from %s: %s\n",
2364                         batch, strerror(errno));
2365                 return -1;
2366         }
2367
2368         INIT_LIST_HEAD(&head);
2369
2370         rc = lst_alloc_rpcent(&head, count, 0);
2371         if (rc != 0) {
2372                 fprintf(stderr, "Out of memory\n");
2373                 return -1;
2374         }
2375
2376         rc = lst_stop_batch_ioctl(batch, force, &head);
2377         if (rc != 0)
2378                 goto out;
2379
2380         while (1) {
2381                 lst_reset_rpcent(&head);
2382
2383                 rc = lst_query_batch_ioctl(batch, 0, 0, 30, &head);
2384                 if (rc != 0)
2385                         goto out;
2386
2387                 if (lstcon_tsbqry_stat_run(&trans_stat, 0)  == 0 &&
2388                     lstcon_tsbqry_stat_failure(&trans_stat, 0) == 0)
2389                         break;
2390
2391                 fprintf(stdout, "%d batch in stopping\n",
2392                         lstcon_tsbqry_stat_run(&trans_stat, 0));
2393                 sleep(1);
2394         }
2395
2396         fprintf(stdout, "Batch is stopped\n");
2397         lst_free_rpcent(&head);
2398
2399         return 0;
2400 out:
2401         if (rc == -1) {
2402                 lst_print_error("batch", "Failed to stop batch: %s\n",
2403                                 strerror(errno));
2404                 lst_free_rpcent(&head);
2405                 return -1;
2406         }
2407
2408         lst_print_transerr(&head, "stop batch");
2409
2410         lst_free_rpcent(&head);
2411
2412         return rc;
2413 }
2414
2415 int
2416 lst_list_batch_ioctl(int len, char *name, int index)
2417 {
2418         struct lstio_batch_list_args args = { 0 };
2419
2420         args.lstio_bat_key   = session_key;
2421         args.lstio_bat_idx   = index;
2422         args.lstio_bat_nmlen = len;
2423         args.lstio_bat_namep = name;
2424
2425         return lst_ioctl(LSTIO_BATCH_LIST, &args, sizeof(args));
2426 }
2427
2428 int
2429 lst_info_batch_ioctl(char *batch, int test, int server,
2430                      struct lstcon_test_batch_ent *entp, int *idxp,
2431                      int *ndentp, struct lstcon_node_ent *dentsp)
2432 {
2433         struct lstio_batch_info_args args = { 0 };
2434
2435         args.lstio_bat_key     = session_key;
2436         args.lstio_bat_nmlen   = strlen(batch);
2437         args.lstio_bat_namep   = batch;
2438         args.lstio_bat_server  = server;
2439         args.lstio_bat_testidx = test;
2440         args.lstio_bat_entp    = entp;
2441         args.lstio_bat_idxp    = idxp;
2442         args.lstio_bat_ndentp  = ndentp;
2443         args.lstio_bat_dentsp  = dentsp;
2444
2445         return lst_ioctl(LSTIO_BATCH_INFO, &args, sizeof(args));
2446 }
2447
2448 int
2449 lst_list_batch_all(void)
2450 {
2451         char name[LST_NAME_SIZE];
2452         int  rc;
2453         int  i;
2454
2455         for (i = 0; ; i++) {
2456                 rc = lst_list_batch_ioctl(LST_NAME_SIZE, name, i);
2457                 if (rc == 0) {
2458                         fprintf(stdout, "%d) %s\n", i + 1, name);
2459                         continue;
2460                 }
2461
2462                 if (errno == ENOENT)
2463                         break;
2464
2465                 lst_print_error("batch", "Failed to list batch: %s\n",
2466                                 strerror(errno));
2467                 return rc;
2468         }
2469
2470         fprintf(stdout, "Total %d batches\n", i);
2471
2472         return 0;
2473 }
2474
2475 int
2476 lst_list_tsb_nodes(char *batch, int test, int server,
2477                    int count, int active, int invalid)
2478 {
2479         struct lstcon_node_ent *dents;
2480         int                index = 0;
2481         int                rc;
2482         int                c;
2483         int                i;
2484
2485         if (count == 0)
2486                 return 0;
2487
2488         /* verbose list, show nodes in batch or test */
2489         dents = malloc(count * sizeof(struct lstcon_node_ent));
2490         if (dents == NULL) {
2491                 fprintf(stdout, "Can't allocate memory\n");
2492                 return -1;
2493         }
2494
2495         rc = lst_info_batch_ioctl(batch, test, server,
2496                                   NULL, &index, &count, dents);
2497         if (rc != 0) {
2498                 free(dents);
2499                 lst_print_error((test > 0) ? "test" : "batch",
2500                                 (test > 0) ? "Failed to query test: %s\n" :
2501                                              "Failed to query batch: %s\n",
2502                                 strerror(errno));
2503                 return -1;
2504         }
2505
2506         for (i = 0, c = 0; i < count; i++) {
2507                 if ((!active  && dents[i].nde_state == LST_NODE_ACTIVE) ||
2508                     (!invalid && (dents[i].nde_state == LST_NODE_BUSY  ||
2509                                   dents[i].nde_state == LST_NODE_DOWN  ||
2510                                   dents[i].nde_state == LST_NODE_UNKNOWN)))
2511                         continue;
2512
2513                 fprintf(stdout, "\t%s: %s\n",
2514                         libcfs_id2str(dents[i].nde_id),
2515                         lst_node_state2str(dents[i].nde_state));
2516                 c++;
2517         }
2518
2519         fprintf(stdout, "Total %d nodes\n", c);
2520         free(dents);
2521
2522         return 0;
2523 }
2524
2525 int
2526 jt_lst_list_batch(int argc, char **argv)
2527 {
2528         struct lstcon_test_batch_ent ent;
2529         char *batch   = NULL;
2530         int   optidx  = 0;
2531         int   verbose = 0; /* list nodes in batch or test */
2532         int   invalid = 0;
2533         int   active  = 0;
2534         int   server  = 0;
2535         int   ntest   = 0;
2536         int   test    = 0;
2537         int   c       = 0;
2538         int   rc;
2539
2540         static const struct option list_batch_opts[] = {
2541                 { .name = "test",    .has_arg = required_argument, .val = 't' },
2542                 { .name = "invalid", .has_arg = no_argument,       .val = 'i' },
2543                 { .name = "active",  .has_arg = no_argument,       .val = 'a' },
2544                 { .name = "all",     .has_arg = no_argument,       .val = 'l' },
2545                 { .name = "server",  .has_arg = no_argument,       .val = 's' },
2546                 { .name = NULL, } };
2547
2548         if (session_key == 0) {
2549                 fprintf(stderr,
2550                         "Can't find env LST_SESSION or value is not valid\n");
2551                 return -1;
2552         }
2553
2554         while (1) {
2555                 c = getopt_long(argc, argv, "ailst:",
2556                                 list_batch_opts, &optidx);
2557
2558                 if (c == -1)
2559                         break;
2560
2561                 switch (c) {
2562                 case 'a':
2563                         verbose = active = 1;
2564                         break;
2565                 case 'i':
2566                         verbose = invalid = 1;
2567                         break;
2568                 case 'l':
2569                         verbose = active = invalid = 1;
2570                         break;
2571                 case 's':
2572                         server = 1;
2573                         break;
2574                 case 't':
2575                         test = atoi(optarg);
2576                         ntest = 1;
2577                         break;
2578                 default:
2579                         lst_print_usage(argv[0]);
2580                         return -1;
2581                 }
2582         }
2583
2584         if (optind == argc) {
2585                 /* list all batches */
2586                 rc = lst_list_batch_all();
2587                 return rc;
2588         }
2589
2590         if (ntest == 1 && test <= 0) {
2591                 fprintf(stderr, "Invalid test id, test id starts from 1\n");
2592                 return -1;
2593         }
2594
2595         if (optind != argc - 1) {
2596                 lst_print_usage(argv[0]);
2597                 return -1;
2598         }
2599
2600         batch = argv[optind];
2601
2602 loop:
2603         /* show detail of specified batch or test */
2604         rc = lst_info_batch_ioctl(batch, test, server,
2605                                   &ent, NULL, NULL, NULL);
2606         if (rc != 0) {
2607                 lst_print_error((test > 0) ? "test" : "batch",
2608                                 (test > 0) ? "Failed to query test: %s\n" :
2609                                              "Failed to query batch: %s\n",
2610                                 strerror(errno));
2611                 return -1;
2612         }
2613
2614         if (verbose) {
2615                 /* list nodes in test or batch */
2616                 rc = lst_list_tsb_nodes(batch, test, server,
2617                                         server ? ent.tbe_srv_nle.nle_nnode :
2618                                                  ent.tbe_cli_nle.nle_nnode,
2619                                         active, invalid);
2620                 return rc;
2621         }
2622
2623         /* only show number of hosts in batch or test */
2624         if (test == 0) {
2625                 fprintf(stdout, "Batch: %s Tests: %d State: %d\n",
2626                         batch, ent.u.tbe_batch.bae_ntest,
2627                         ent.u.tbe_batch.bae_state);
2628                 ntest = ent.u.tbe_batch.bae_ntest;
2629                 test = 1; /* starting from test 1 */
2630
2631         } else {
2632                 fprintf(stdout,
2633                         "\tTest %d(%s) (loop: %d, concurrency: %d)\n",
2634                         test, lst_test_type2name(ent.u.tbe_test.tse_type),
2635                         ent.u.tbe_test.tse_loop,
2636                         ent.u.tbe_test.tse_concur);
2637                 ntest --;
2638                 test ++;
2639         }
2640
2641         fprintf(stdout, LST_NODES_TITLE);
2642         fprintf(stdout, "client\t%d\t%d\t%d\t%d\t%d\n"
2643                         "server\t%d\t%d\t%d\t%d\t%d\n",
2644                 ent.tbe_cli_nle.nle_nactive,
2645                 ent.tbe_cli_nle.nle_nbusy,
2646                 ent.tbe_cli_nle.nle_ndown,
2647                 ent.tbe_cli_nle.nle_nunknown,
2648                 ent.tbe_cli_nle.nle_nnode,
2649                 ent.tbe_srv_nle.nle_nactive,
2650                 ent.tbe_srv_nle.nle_nbusy,
2651                 ent.tbe_srv_nle.nle_ndown,
2652                 ent.tbe_srv_nle.nle_nunknown,
2653                 ent.tbe_srv_nle.nle_nnode);
2654
2655         if (ntest != 0)
2656                 goto loop;
2657
2658         return 0;
2659 }
2660
2661 int
2662 lst_query_batch_ioctl(char *batch, int test, int server,
2663                       int timeout, struct list_head *head)
2664 {
2665         struct lstio_batch_query_args args = { 0 };
2666
2667         args.lstio_bat_key     = session_key;
2668         args.lstio_bat_testidx = test;
2669         args.lstio_bat_client  = !(server);
2670         args.lstio_bat_timeout = timeout;
2671         args.lstio_bat_nmlen   = strlen(batch);
2672         args.lstio_bat_namep   = batch;
2673         args.lstio_bat_resultp = head;
2674
2675         return lst_ioctl(LSTIO_BATCH_QUERY, &args, sizeof(args));
2676 }
2677
2678 void
2679 lst_print_tsb_verbose(struct list_head *head,
2680                       int active, int idle, int error)
2681 {
2682         struct lstcon_rpc_ent *ent;
2683
2684         list_for_each_entry(ent, head, rpe_link) {
2685                 if (ent->rpe_priv[0] == 0 && active)
2686                         continue;
2687
2688                 if (ent->rpe_priv[0] != 0 && idle)
2689                         continue;
2690
2691                 if (ent->rpe_fwk_errno == 0 && error)
2692                         continue;
2693
2694                 fprintf(stdout, "%s [%s]: %s\n",
2695                         libcfs_id2str(ent->rpe_peer),
2696                         lst_node_state2str(ent->rpe_state),
2697                         ent->rpe_rpc_errno != 0 ?
2698                                 strerror(ent->rpe_rpc_errno) :
2699                                 (ent->rpe_priv[0] > 0 ? "Running" : "Idle"));
2700         }
2701 }
2702
2703 int
2704 jt_lst_query_batch(int argc, char **argv)
2705 {
2706         struct lstcon_test_batch_ent ent;
2707         struct list_head head;
2708         char   *batch   = NULL;
2709         time_t  last    = 0;
2710         int     optidx  = 0;
2711         int     verbose = 0;
2712         int     server  = 0;
2713         int     timeout = 5; /* default 5 seconds */
2714         int     delay   = 5; /* default 5 seconds */
2715         int     loop    = 1; /* default 1 loop */
2716         int     active  = 0;
2717         int     error   = 0;
2718         int     idle    = 0;
2719         int     count   = 0;
2720         int     test    = 0;
2721         int     rc      = 0;
2722         int     c       = 0;
2723         int     i;
2724
2725         static const struct option query_batch_opts[] = {
2726                 { .name = "timeout", .has_arg = required_argument, .val = 'o' },
2727                 { .name = "delay",   .has_arg = required_argument, .val = 'd' },
2728                 { .name = "loop",    .has_arg = required_argument, .val = 'c' },
2729                 { .name = "test",    .has_arg = required_argument, .val = 't' },
2730                 { .name = "server",  .has_arg = no_argument,       .val = 's' },
2731                 { .name = "active",  .has_arg = no_argument,       .val = 'a' },
2732                 { .name = "idle",    .has_arg = no_argument,       .val = 'i' },
2733                 { .name = "error",   .has_arg = no_argument,       .val = 'e' },
2734                 { .name = "all",     .has_arg = no_argument,       .val = 'l' },
2735                 { .name = NULL, } };
2736
2737         if (session_key == 0) {
2738                 fprintf(stderr,
2739                         "Can't find env LST_SESSION or value is not valid\n");
2740                 return -1;
2741         }
2742
2743         while (1) {
2744                 c = getopt_long(argc, argv, "o:d:c:t:saiel",
2745                                 query_batch_opts, &optidx);
2746
2747                 /* Detect the end of the options. */
2748                 if (c == -1)
2749                         break;
2750
2751                 switch (c) {
2752                 case 'o':
2753                         timeout = atoi(optarg);
2754                         break;
2755                 case 'd':
2756                         delay = atoi(optarg);
2757                         break;
2758                 case 'c':
2759                         loop = atoi(optarg);
2760                         break;
2761                 case 't':
2762                         test = atoi(optarg);
2763                         break;
2764                 case 's':
2765                         server = 1;
2766                         break;
2767                 case 'a':
2768                         active = verbose = 1;
2769                         break;
2770                 case 'i':
2771                         idle = verbose = 1;
2772                         break;
2773                 case 'e':
2774                         error = verbose = 1;
2775                         break;
2776                 case 'l':
2777                         verbose = 1;
2778                         break;
2779                 default:
2780                         lst_print_usage(argv[0]);
2781                         return -1;
2782                 }
2783         }
2784
2785         if (test < 0 || timeout <= 0 || delay <= 0 || loop <= 0) {
2786                 lst_print_usage(argv[0]);
2787                 return -1;
2788         }
2789
2790         if (optind == argc) {
2791                 batch = LST_DEFAULT_BATCH;
2792
2793         } else if (optind == argc - 1) {
2794                 batch = argv[optind];
2795
2796         } else {
2797                 lst_print_usage(argv[0]);
2798                 return -1;
2799         }
2800
2801
2802         INIT_LIST_HEAD(&head);
2803
2804         if (verbose) {
2805                 rc = lst_info_batch_ioctl(batch, test, server,
2806                                           &ent, NULL, NULL, NULL);
2807                 if (rc != 0) {
2808                         fprintf(stderr, "Failed to query %s [%d]: %s\n",
2809                                 batch, test, strerror(errno));
2810                         return -1;
2811                 }
2812
2813                 count = server ? ent.tbe_srv_nle.nle_nnode :
2814                                  ent.tbe_cli_nle.nle_nnode;
2815                 if (count == 0) {
2816                         fprintf(stdout, "Batch or test is empty\n");
2817                         return 0;
2818                 }
2819         }
2820
2821         rc = lst_alloc_rpcent(&head, count, 0);
2822         if (rc != 0) {
2823                 fprintf(stderr, "Out of memory\n");
2824                 return rc;
2825         }
2826
2827         for (i = 0; i < loop; i++) {
2828                 time_t  now = time(NULL);
2829
2830                 if (now - last < delay) {
2831                         sleep(delay - now + last);
2832                         time(&now);
2833                 }
2834
2835                 last = now;
2836
2837                 rc = lst_query_batch_ioctl(batch, test,
2838                                            server, timeout, &head);
2839                 if (rc == -1) {
2840                         fprintf(stderr, "Failed to query batch: %s\n",
2841                                 strerror(errno));
2842                         break;
2843                 }
2844
2845                 if (verbose) {
2846                         /* Verbose mode */
2847                         lst_print_tsb_verbose(&head, active, idle, error);
2848                         continue;
2849                 }
2850
2851                 fprintf(stdout, "%s [%d] ", batch, test);
2852
2853                 if (lstcon_rpc_stat_failure(&trans_stat, 0) != 0) {
2854                         fprintf(stdout, "%d of %d nodes are unknown, ",
2855                                 lstcon_rpc_stat_failure(&trans_stat, 0),
2856                                 lstcon_rpc_stat_total(&trans_stat, 0));
2857                 }
2858
2859                 if (lstcon_rpc_stat_failure(&trans_stat, 0) == 0 &&
2860                     lstcon_tsbqry_stat_run(&trans_stat, 0)  == 0  &&
2861                     lstcon_tsbqry_stat_failure(&trans_stat, 0) == 0) {
2862                         fprintf(stdout, "is stopped\n");
2863                         continue;
2864                 }
2865
2866                 if (lstcon_rpc_stat_failure(&trans_stat, 0) == 0 &&
2867                     lstcon_tsbqry_stat_idle(&trans_stat, 0) == 0 &&
2868                     lstcon_tsbqry_stat_failure(&trans_stat, 0) == 0) {
2869                         fprintf(stdout, "is running\n");
2870                         continue;
2871                 }
2872
2873                 fprintf(stdout, "stopped: %d , running: %d, failed: %d\n",
2874                                 lstcon_tsbqry_stat_idle(&trans_stat, 0),
2875                                 lstcon_tsbqry_stat_run(&trans_stat, 0),
2876                                 lstcon_tsbqry_stat_failure(&trans_stat, 0));
2877         }
2878
2879         lst_free_rpcent(&head);
2880
2881         return rc;
2882 }
2883
2884 int
2885 lst_parse_distribute(char *dstr, int *dist, int *span)
2886 {
2887         *dist = atoi(dstr);
2888         if (*dist <= 0)
2889                 return -1;
2890
2891         dstr = strchr(dstr, ':');
2892         if (dstr == NULL)
2893                 return -1;
2894
2895         *span = atoi(dstr + 1);
2896         if (*span <= 0)
2897                 return -1;
2898
2899         return 0;
2900 }
2901
2902 int
2903 lst_get_bulk_param(int argc, char **argv, struct lst_test_bulk_param *bulk)
2904 {
2905         char   *tok = NULL;
2906         char   *end = NULL;
2907         int     rc  = 0;
2908         int     i   = 0;
2909
2910         bulk->blk_size  = 4096;
2911         bulk->blk_opc   = LST_BRW_READ;
2912         bulk->blk_flags = LST_BRW_CHECK_NONE;
2913         bulk->blk_srv_off = bulk->blk_cli_off = 0;
2914
2915         while (i < argc) {
2916                 if (strcasestr(argv[i], "check=") == argv[i] ||
2917                     strcasestr(argv[i], "c=") == argv[i]) {
2918                         tok = strchr(argv[i], '=') + 1;
2919
2920                         if (strcasecmp(tok, "full") == 0) {
2921                                 bulk->blk_flags = LST_BRW_CHECK_FULL;
2922                         } else if (strcasecmp(tok, "simple") == 0) {
2923                                 bulk->blk_flags = LST_BRW_CHECK_SIMPLE;
2924                         } else {
2925                                 fprintf(stderr, "Unknow flag %s\n", tok);
2926                                 return -1;
2927                         }
2928
2929                 } else if (strcasestr(argv[i], "size=") == argv[i] ||
2930                            strcasestr(argv[i], "s=") == argv[i]) {
2931                         tok = strchr(argv[i], '=') + 1;
2932
2933                         bulk->blk_size = strtol(tok, &end, 0);
2934                         if (bulk->blk_size <= 0) {
2935                                 fprintf(stderr, "Invalid size %s\n", tok);
2936                                 return -1;
2937                         }
2938
2939                         if (end == NULL)
2940                                 return 0;
2941
2942                         if (*end == 'k' || *end == 'K')
2943                                 bulk->blk_size *= 1024;
2944                         else if (*end == 'm' || *end == 'M')
2945                                 bulk->blk_size *= 1024 * 1024;
2946
2947                         if (bulk->blk_size > LNET_MTU) {
2948                                 fprintf(stderr, "Size exceed limitation: %d bytes\n",
2949                                         bulk->blk_size);
2950                                 return -1;
2951                         }
2952
2953                 } else if (strcasestr(argv[i], "off=") == argv[i]) {
2954                         int     off;
2955
2956                         tok = strchr(argv[i], '=') + 1;
2957
2958                         off = strtol(tok, &end, 0);
2959                         /* NB: align with sizeof(__u64) to simplify page
2960                          * checking implementation */
2961                         if (off < 0 || off % sizeof(__u64) != 0) {
2962                                 fprintf(stderr,
2963                                         "Invalid offset %s/%d, it should be "
2964                                         "postive value and multiple of %d\n",
2965                                         tok, off, (int)sizeof(__u64));
2966                                 return -1;
2967                         }
2968
2969                         /* NB: blk_srv_off is reserved so far */
2970                         bulk->blk_cli_off = bulk->blk_srv_off = off;
2971                         if (end == NULL)
2972                                 return 0;
2973
2974                 } else if (strcasecmp(argv[i], "read") == 0 ||
2975                            strcasecmp(argv[i], "r") == 0) {
2976                         bulk->blk_opc = LST_BRW_READ;
2977
2978                 } else if (strcasecmp(argv[i], "write") == 0 ||
2979                            strcasecmp(argv[i], "w") == 0) {
2980                         bulk->blk_opc = LST_BRW_WRITE;
2981
2982                 } else {
2983                         fprintf(stderr, "Unknow parameter: %s\n", argv[i]);
2984                         return -1;
2985                 }
2986
2987                 i++;
2988         }
2989
2990         return rc;
2991 }
2992
2993 int
2994 lst_get_test_param(char *test, int argc, char **argv, void **param, int *plen)
2995 {
2996         struct lst_test_bulk_param *bulk = NULL;
2997         int                    type;
2998
2999         type = lst_test_name2type(test);
3000         if (type < 0) {
3001                 fprintf(stderr, "Unknow test name %s\n", test);
3002                 return -1;
3003         }
3004
3005         switch (type) {
3006         case LST_TEST_PING:
3007                 break;
3008
3009         case LST_TEST_BULK:
3010                 bulk = malloc(sizeof(*bulk));
3011                 if (bulk == NULL) {
3012                         fprintf(stderr, "Out of memory\n");
3013                         return -1;
3014                 }
3015
3016                 memset(bulk, 0, sizeof(*bulk));
3017
3018                 if (lst_get_bulk_param(argc, argv, bulk) != 0) {
3019                         free(bulk);
3020                         return -1;
3021                 }
3022
3023                 *param = bulk;
3024                 *plen  = sizeof(*bulk);
3025
3026                 break;
3027
3028         default:
3029                 break;
3030         }
3031
3032         /* TODO: parse more parameter */
3033         return type;
3034 }
3035
3036 int
3037 lst_add_test_ioctl(char *batch, int type, int loop, int concur,
3038                    int dist, int span, char *sgrp, char *dgrp,
3039                    void *param, int plen, int *retp, struct list_head *resultp)
3040 {
3041         struct lstio_test_args args = { 0 };
3042
3043         args.lstio_tes_key        = session_key;
3044         args.lstio_tes_bat_nmlen  = strlen(batch);
3045         args.lstio_tes_bat_name   = batch;
3046         args.lstio_tes_type       = type;
3047         args.lstio_tes_oneside    = 0;
3048         args.lstio_tes_loop       = loop;
3049         args.lstio_tes_concur     = concur;
3050         args.lstio_tes_dist       = dist;
3051         args.lstio_tes_span       = span;
3052         args.lstio_tes_sgrp_nmlen = strlen(sgrp);
3053         args.lstio_tes_sgrp_name  = sgrp;
3054         args.lstio_tes_dgrp_nmlen = strlen(dgrp);
3055         args.lstio_tes_dgrp_name  = dgrp;
3056         args.lstio_tes_param_len  = plen;
3057         args.lstio_tes_param      = param;
3058         args.lstio_tes_retp       = retp;
3059         args.lstio_tes_resultp    = resultp;
3060
3061         return lst_ioctl(LSTIO_TEST_ADD, &args, sizeof(args));
3062 }
3063
3064 int
3065 jt_lst_add_test(int argc, char **argv)
3066 {
3067         struct list_head head;
3068         char *batch  = NULL;
3069         char *test   = NULL;
3070         char *dstr   = NULL;
3071         char *from   = NULL;
3072         char *to     = NULL;
3073         void *param  = NULL;
3074         int   optidx = 0;
3075         int   concur = 1;
3076         int   loop   = -1;
3077         int   dist   = 1;
3078         int   span   = 1;
3079         int   plen   = 0;
3080         int   fcount = 0;
3081         int   tcount = 0;
3082         int   ret    = 0;
3083         int   type;
3084         int   rc;
3085         int   c;
3086
3087         static const struct option add_test_opts[] = {
3088         { .name = "batch",       .has_arg = required_argument, .val = 'b' },
3089         { .name = "concurrency", .has_arg = required_argument, .val = 'c' },
3090         { .name = "distribute",  .has_arg = required_argument, .val = 'd' },
3091         { .name = "from",        .has_arg = required_argument, .val = 'f' },
3092         { .name = "to",          .has_arg = required_argument, .val = 't' },
3093         { .name = "loop",        .has_arg = required_argument, .val = 'l' },
3094         { .name = NULL } };
3095
3096         if (session_key == 0) {
3097                 fprintf(stderr,
3098                         "Can't find env LST_SESSION or value is not valid\n");
3099                 return -1;
3100         }
3101
3102         while (1) {
3103                 c = getopt_long(argc, argv, "b:c:d:f:l:t:",
3104                                 add_test_opts, &optidx);
3105
3106                 /* Detect the end of the options. */
3107                 if (c == -1)
3108                         break;
3109
3110                 switch (c) {
3111                 case 'b':
3112                         batch = optarg;
3113                         break;
3114                 case 'c':
3115                         concur = atoi(optarg);
3116                         break;
3117                 case 'd':
3118                         dstr = optarg;
3119                         break;
3120                 case 'f':
3121                         from = optarg;
3122                         break;
3123                 case 'l':
3124                         loop = atoi(optarg);
3125                         break;
3126                 case 't':
3127                         to = optarg;
3128                         break;
3129                 default:
3130                         lst_print_usage(argv[0]);
3131                         return -1;
3132                 }
3133         }
3134
3135         if (optind == argc || from == NULL || to == NULL) {
3136                 lst_print_usage(argv[0]);
3137                 return -1;
3138         }
3139
3140         if (concur <= 0 || concur > LST_MAX_CONCUR) {
3141                 fprintf(stderr, "Invalid concurrency of test: %d\n", concur);
3142                 return -1;
3143         }
3144
3145         if (batch == NULL)
3146                 batch = LST_DEFAULT_BATCH;
3147
3148         if (dstr != NULL) {
3149                 rc = lst_parse_distribute(dstr, &dist, &span);
3150                 if (rc != 0) {
3151                         fprintf(stderr, "Invalid distribution: %s\n", dstr);
3152                         return -1;
3153                 }
3154         }
3155
3156         test = argv[optind++];
3157
3158         argc -= optind;
3159         argv += optind;
3160
3161         type = lst_get_test_param(test, argc, argv, &param, &plen);
3162         if (type < 0) {
3163                 fprintf(stderr, "Failed to add test (%s)\n", test);
3164                 return -1;
3165         }
3166
3167         INIT_LIST_HEAD(&head);
3168
3169         rc = lst_get_node_count(LST_OPC_GROUP, from, &fcount, NULL);
3170         if (rc != 0) {
3171                 fprintf(stderr, "Can't get count of nodes from %s: %s\n",
3172                         from, strerror(errno));
3173                 goto out;
3174         }
3175
3176         rc = lst_get_node_count(LST_OPC_GROUP, to, &tcount, NULL);
3177         if (rc != 0) {
3178                 fprintf(stderr, "Can't get count of nodes from %s: %s\n",
3179                         to, strerror(errno));
3180                 goto out;
3181         }
3182
3183         rc = lst_alloc_rpcent(&head, fcount > tcount ? fcount : tcount, 0);
3184         if (rc != 0) {
3185                 fprintf(stderr, "Out of memory\n");
3186                 goto out;
3187         }
3188
3189         rc = lst_add_test_ioctl(batch, type, loop, concur,
3190                                 dist, span, from, to, param, plen, &ret, &head);
3191
3192         if (rc == 0) {
3193                 fprintf(stdout, "Test was added successfully\n");
3194                 if (ret != 0) {
3195                         fprintf(stdout, "Server group contains userland test "
3196                                 "nodes, old version of tcplnd can't accept "
3197                                 "connection request\n");
3198                 }
3199
3200                 goto out;
3201         }
3202
3203         if (rc == -1) {
3204                 lst_print_error("test", "Failed to add test: %s\n",
3205                                 strerror(errno));
3206                 goto out;
3207         }
3208
3209         lst_print_transerr(&head, "add test");
3210 out:
3211         lst_free_rpcent(&head);
3212
3213         if (param != NULL)
3214                 free(param);
3215
3216         return rc;
3217 }
3218
3219 static command_t lst_cmdlist[] = {
3220         {"new_session",         jt_lst_new_session,     NULL,
3221          "Usage: lst new_session [--timeout TIME] [--force] [NAME]"                     },
3222         {"end_session",         jt_lst_end_session,     NULL,
3223          "Usage: lst end_session"                                                       },
3224         {"show_session",        jt_lst_show_session,    NULL,
3225          "Usage: lst show_session"                                                      },
3226         {"ping",                jt_lst_ping ,           NULL,
3227          "Usage: lst ping  [--group NAME] [--batch NAME] [--session] [--nodes IDS]"     },
3228         {"add_group",           jt_lst_add_group,       NULL,
3229          "Usage: lst group NAME IDs [IDs]..."                                           },
3230         {"del_group",           jt_lst_del_group,       NULL,
3231          "Usage: lst del_group NAME"                                                    },
3232         {"update_group",        jt_lst_update_group,    NULL,
3233          "Usage: lst update_group NAME [--clean] [--refresh] [--remove IDs]"            },
3234         {"list_group",          jt_lst_list_group,      NULL,
3235           "Usage: lst list_group [--active] [--busy] [--down] [--unknown] GROUP ..."    },
3236         {"stat",                jt_lst_stat,            NULL,
3237          "Usage: lst stat [--bw] [--rate] [--read] [--write] [--max] [--min] [--avg] "
3238          " [--mbs] [--timeout #] [--delay #] [--count #] GROUP [GROUP]"                 },
3239         {"show_error",          jt_lst_show_error,      NULL,
3240          "Usage: lst show_error NAME | IDS ..."                                         },
3241         {"add_batch",           jt_lst_add_batch,       NULL,
3242          "Usage: lst add_batch NAME"                                                    },
3243         {"run",                 jt_lst_start_batch,     NULL,
3244          "Usage: lst run [--timeout TIME] [NAME]"                                       },
3245         {"stop",                jt_lst_stop_batch,      NULL,
3246          "Usage: lst stop [--force] BATCH_NAME"                                         },
3247         {"list_batch",          jt_lst_list_batch,      NULL,
3248          "Usage: lst list_batch NAME [--test ID] [--server]"                            },
3249         {"query",               jt_lst_query_batch,     NULL,
3250          "Usage: lst query [--test ID] [--server] [--timeout TIME] NAME"                },
3251         {"add_test",            jt_lst_add_test,        NULL,
3252          "Usage: lst add_test [--batch BATCH] [--loop #] [--concurrency #] "
3253          " [--distribute #:#] [--from GROUP] [--to GROUP] TEST..."                      },
3254         {"help",                Parser_help,            0,     "help"                   },
3255         {"--list-commands",     lst_list_commands,      0,     "list commands"          },
3256         {0,                     0,                      0,      NULL                    }
3257 };
3258
3259 int
3260 lst_initialize(void)
3261 {
3262         char   *key;
3263         char   *feats;
3264
3265         feats = getenv("LST_FEATURES");
3266         if (feats != NULL)
3267                 session_features = strtol(feats, NULL, 16);
3268
3269         if ((session_features & ~LST_FEATS_MASK) != 0) {
3270                 fprintf(stderr,
3271                         "Unsupported session features %x, "
3272                         "only support these features so far: %x\n",
3273                         (session_features & ~LST_FEATS_MASK), LST_FEATS_MASK);
3274                 return -1;
3275         }
3276
3277         key = getenv("LST_SESSION");
3278
3279         if (key == NULL) {
3280                 session_key = 0;
3281                 return 0;
3282         }
3283
3284         session_key = atoi(key);
3285
3286         return 0;
3287 }
3288
3289 static int lst_list_commands(int argc, char **argv)
3290 {
3291         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
3292
3293         Parser_list_commands(lst_cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
3294
3295         return 0;
3296 }
3297
3298 int
3299 main(int argc, char **argv)
3300 {
3301         int rc = 0;
3302
3303         setlinebuf(stdout);
3304
3305         rc = lst_initialize();
3306         if (rc < 0)
3307                 goto errorout;
3308
3309         rc = lustre_lnet_config_lib_init();
3310         if (rc < 0)
3311                 goto errorout;
3312
3313         Parser_init("lst > ", lst_cmdlist);
3314
3315         if (argc != 1)  {
3316                 rc = Parser_execarg(argc - 1, argv + 1, lst_cmdlist);
3317                 goto errorout;
3318         }
3319
3320         Parser_commands();
3321
3322 errorout:
3323         return rc;
3324 }