]> CyberLeo.Net >> Repos - FreeBSD/releng/10.3.git/blob - tools/tools/cxgbetool/cxgbetool.c
- Copy stable/10@296371 to releng/10.3 in preparation for 10.3-RC1
[FreeBSD/releng/10.3.git] / tools / tools / cxgbetool / cxgbetool.c
1 /*-
2  * Copyright (c) 2011 Chelsio Communications, Inc.
3  * All rights reserved.
4  * Written by: Navdeep Parhar <np@FreeBSD.org>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 #include <stdint.h>
32 #include <stdlib.h>
33 #include <unistd.h>
34 #include <ctype.h>
35 #include <errno.h>
36 #include <err.h>
37 #include <fcntl.h>
38 #include <string.h>
39 #include <stdio.h>
40 #include <sys/ioctl.h>
41 #include <limits.h>
42 #include <sys/mman.h>
43 #include <sys/types.h>
44 #include <sys/socket.h>
45 #include <sys/stat.h>
46 #include <net/ethernet.h>
47 #include <netinet/in.h>
48 #include <arpa/inet.h>
49 #include <net/sff8472.h>
50
51 #include "t4_ioctl.h"
52
53 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
54 #define in_range(val, lo, hi) ( val < 0 || (val <= hi && val >= lo))
55 #define max(x, y) ((x) > (y) ? (x) : (y))
56
57 static const char *progname, *nexus;
58 static int chip_id;     /* 4 for T4, 5 for T5 */
59
60 struct reg_info {
61         const char *name;
62         uint32_t addr;
63         uint32_t len;
64 };
65
66 struct mod_regs {
67         const char *name;
68         const struct reg_info *ri;
69 };
70
71 struct field_desc {
72         const char *name;     /* Field name */
73         unsigned short start; /* Start bit position */
74         unsigned short end;   /* End bit position */
75         unsigned char shift;  /* # of low order bits omitted and implicitly 0 */
76         unsigned char hex;    /* Print field in hex instead of decimal */
77         unsigned char islog2; /* Field contains the base-2 log of the value */
78 };
79
80 #include "reg_defs_t4.c"
81 #include "reg_defs_t4vf.c"
82 #include "reg_defs_t5.c"
83
84 static void
85 usage(FILE *fp)
86 {
87         fprintf(fp, "Usage: %s <nexus> [operation]\n", progname);
88         fprintf(fp,
89             "\tclearstats <port>                   clear port statistics\n"
90             "\tcontext <type> <id>                 show an SGE context\n"
91             "\tfilter <idx> [<param> <val>] ...    set a filter\n"
92             "\tfilter <idx> delete|clear           delete a filter\n"
93             "\tfilter list                         list all filters\n"
94             "\tfilter mode [<match>] ...           get/set global filter mode\n"
95             "\ti2c <port> <devaddr> <addr> [<len>] read from i2c device\n"
96             "\tloadfw <fw-image.bin>               install firmware\n"
97             "\tmemdump <addr> <len>                dump a memory range\n"
98             "\tmodinfo <port> [raw]                optics/cable information\n"
99             "\treg <address>[=<val>]               read/write register\n"
100             "\treg64 <address>[=<val>]             read/write 64 bit register\n"
101             "\tregdump [<module>] ...              dump registers\n"
102             "\tsched-class params <param> <val> .. configure TX scheduler class\n"
103             "\tsched-queue <port> <queue> <class>  bind NIC queues to TX Scheduling class\n"
104             "\tstdio                               interactive mode\n"
105             "\ttcb <tid>                           read TCB\n"
106             "\ttracer <idx> tx<n>|rx<n>            set and enable a tracer\n"
107             "\ttracer <idx> disable|enable         disable or enable a tracer\n"
108             "\ttracer list                         list all tracers\n"
109             );
110 }
111
112 static inline unsigned int
113 get_card_vers(unsigned int version)
114 {
115         return (version & 0x3ff);
116 }
117
118 static int
119 real_doit(unsigned long cmd, void *data, const char *cmdstr)
120 {
121         static int fd = -1;
122         int rc = 0;
123
124         if (fd == -1) {
125                 char buf[64];
126
127                 snprintf(buf, sizeof(buf), "/dev/%s", nexus);
128                 if ((fd = open(buf, O_RDWR)) < 0) {
129                         warn("open(%s)", nexus);
130                         rc = errno;
131                         return (rc);
132                 }
133                 chip_id = nexus[1] - '0';
134         }
135
136         rc = ioctl(fd, cmd, data);
137         if (rc < 0) {
138                 warn("%s", cmdstr);
139                 rc = errno;
140         }
141
142         return (rc);
143 }
144 #define doit(x, y) real_doit(x, y, #x)
145
146 static char *
147 str_to_number(const char *s, long *val, long long *vall)
148 {
149         char *p;
150
151         if (vall)
152                 *vall = strtoll(s, &p, 0);
153         else if (val)
154                 *val = strtol(s, &p, 0);
155         else
156                 p = NULL;
157
158         return (p);
159 }
160
161 static int
162 read_reg(long addr, int size, long long *val)
163 {
164         struct t4_reg reg;
165         int rc;
166
167         reg.addr = (uint32_t) addr;
168         reg.size = (uint32_t) size;
169         reg.val = 0;
170
171         rc = doit(CHELSIO_T4_GETREG, &reg);
172
173         *val = reg.val;
174
175         return (rc);
176 }
177
178 static int
179 write_reg(long addr, int size, long long val)
180 {
181         struct t4_reg reg;
182
183         reg.addr = (uint32_t) addr;
184         reg.size = (uint32_t) size;
185         reg.val = (uint64_t) val;
186
187         return doit(CHELSIO_T4_SETREG, &reg);
188 }
189
190 static int
191 register_io(int argc, const char *argv[], int size)
192 {
193         char *p, *v;
194         long addr;
195         long long val;
196         int w = 0, rc;
197
198         if (argc == 1) {
199                 /* <reg> OR <reg>=<value> */
200
201                 p = str_to_number(argv[0], &addr, NULL);
202                 if (*p) {
203                         if (*p != '=') {
204                                 warnx("invalid register \"%s\"", argv[0]);
205                                 return (EINVAL);
206                         }
207
208                         w = 1;
209                         v = p + 1;
210                         p = str_to_number(v, NULL, &val);
211
212                         if (*p) {
213                                 warnx("invalid value \"%s\"", v);
214                                 return (EINVAL);
215                         }
216                 }
217
218         } else if (argc == 2) {
219                 /* <reg> <value> */
220
221                 w = 1;
222
223                 p = str_to_number(argv[0], &addr, NULL);
224                 if (*p) {
225                         warnx("invalid register \"%s\"", argv[0]);
226                         return (EINVAL);
227                 }
228
229                 p = str_to_number(argv[1], NULL, &val);
230                 if (*p) {
231                         warnx("invalid value \"%s\"", argv[1]);
232                         return (EINVAL);
233                 }
234         } else {
235                 warnx("reg: invalid number of arguments (%d)", argc);
236                 return (EINVAL);
237         }
238
239         if (w)
240                 rc = write_reg(addr, size, val);
241         else {
242                 rc = read_reg(addr, size, &val);
243                 if (rc == 0)
244                         printf("0x%llx [%llu]\n", val, val);
245         }
246
247         return (rc);
248 }
249
250 static inline uint32_t
251 xtract(uint32_t val, int shift, int len)
252 {
253         return (val >> shift) & ((1 << len) - 1);
254 }
255
256 static int
257 dump_block_regs(const struct reg_info *reg_array, const uint32_t *regs)
258 {
259         uint32_t reg_val = 0;
260
261         for ( ; reg_array->name; ++reg_array)
262                 if (!reg_array->len) {
263                         reg_val = regs[reg_array->addr / 4];
264                         printf("[%#7x] %-47s %#-10x %u\n", reg_array->addr,
265                                reg_array->name, reg_val, reg_val);
266                 } else {
267                         uint32_t v = xtract(reg_val, reg_array->addr,
268                                             reg_array->len);
269
270                         printf("    %*u:%u %-47s %#-10x %u\n",
271                                reg_array->addr < 10 ? 3 : 2,
272                                reg_array->addr + reg_array->len - 1,
273                                reg_array->addr, reg_array->name, v, v);
274                 }
275
276         return (1);
277 }
278
279 static int
280 dump_regs_table(int argc, const char *argv[], const uint32_t *regs,
281     const struct mod_regs *modtab, int nmodules)
282 {
283         int i, j, match;
284
285         for (i = 0; i < argc; i++) {
286                 for (j = 0; j < nmodules; j++) {
287                         if (!strcmp(argv[i], modtab[j].name))
288                                 break;
289                 }
290
291                 if (j == nmodules) {
292                         warnx("invalid register block \"%s\"", argv[i]);
293                         fprintf(stderr, "\nAvailable blocks:");
294                         for ( ; nmodules; nmodules--, modtab++)
295                                 fprintf(stderr, " %s", modtab->name);
296                         fprintf(stderr, "\n");
297                         return (EINVAL);
298                 }
299         }
300
301         for ( ; nmodules; nmodules--, modtab++) {
302
303                 match = argc == 0 ? 1 : 0;
304                 for (i = 0; !match && i < argc; i++) {
305                         if (!strcmp(argv[i], modtab->name))
306                                 match = 1;
307                 }
308
309                 if (match)
310                         dump_block_regs(modtab->ri, regs);
311         }
312
313         return (0);
314 }
315
316 #define T4_MODREGS(name) { #name, t4_##name##_regs }
317 static int
318 dump_regs_t4(int argc, const char *argv[], const uint32_t *regs)
319 {
320         static struct mod_regs t4_mod[] = {
321                 T4_MODREGS(sge),
322                 { "pci", t4_pcie_regs },
323                 T4_MODREGS(dbg),
324                 T4_MODREGS(mc),
325                 T4_MODREGS(ma),
326                 { "edc0", t4_edc_0_regs },
327                 { "edc1", t4_edc_1_regs },
328                 T4_MODREGS(cim),
329                 T4_MODREGS(tp),
330                 T4_MODREGS(ulp_rx),
331                 T4_MODREGS(ulp_tx),
332                 { "pmrx", t4_pm_rx_regs },
333                 { "pmtx", t4_pm_tx_regs },
334                 T4_MODREGS(mps),
335                 { "cplsw", t4_cpl_switch_regs },
336                 T4_MODREGS(smb),
337                 { "i2c", t4_i2cm_regs },
338                 T4_MODREGS(mi),
339                 T4_MODREGS(uart),
340                 T4_MODREGS(pmu),
341                 T4_MODREGS(sf),
342                 T4_MODREGS(pl),
343                 T4_MODREGS(le),
344                 T4_MODREGS(ncsi),
345                 T4_MODREGS(xgmac)
346         };
347
348         return dump_regs_table(argc, argv, regs, t4_mod, ARRAY_SIZE(t4_mod));
349 }
350 #undef T4_MODREGS
351
352 static int
353 dump_regs_t4vf(int argc, const char *argv[], const uint32_t *regs)
354 {
355         static struct mod_regs t4vf_mod[] = {
356                 { "sge", t4vf_sge_regs },
357                 { "mps", t4vf_mps_regs },
358                 { "pl", t4vf_pl_regs },
359                 { "mbdata", t4vf_mbdata_regs },
360                 { "cim", t4vf_cim_regs },
361         };
362
363         return dump_regs_table(argc, argv, regs, t4vf_mod,
364             ARRAY_SIZE(t4vf_mod));
365 }
366
367 #define T5_MODREGS(name) { #name, t5_##name##_regs }
368 static int
369 dump_regs_t5(int argc, const char *argv[], const uint32_t *regs)
370 {
371         static struct mod_regs t5_mod[] = {
372                 T5_MODREGS(sge),
373                 { "pci", t5_pcie_regs },
374                 T5_MODREGS(dbg),
375                 { "mc0", t5_mc_0_regs },
376                 { "mc1", t5_mc_1_regs },
377                 T5_MODREGS(ma),
378                 { "edc0", t5_edc_t50_regs },
379                 { "edc1", t5_edc_t51_regs },
380                 T5_MODREGS(cim),
381                 T5_MODREGS(tp),
382                 { "ulprx", t5_ulp_rx_regs },
383                 { "ulptx", t5_ulp_tx_regs },
384                 { "pmrx", t5_pm_rx_regs },
385                 { "pmtx", t5_pm_tx_regs },
386                 T5_MODREGS(mps),
387                 { "cplsw", t5_cpl_switch_regs },
388                 T5_MODREGS(smb),
389                 { "i2c", t5_i2cm_regs },
390                 T5_MODREGS(mi),
391                 T5_MODREGS(uart),
392                 T5_MODREGS(pmu),
393                 T5_MODREGS(sf),
394                 T5_MODREGS(pl),
395                 T5_MODREGS(le),
396                 T5_MODREGS(ncsi),
397                 T5_MODREGS(mac),
398                 { "hma", t5_hma_t5_regs }
399         };
400
401         return dump_regs_table(argc, argv, regs, t5_mod, ARRAY_SIZE(t5_mod));
402 }
403 #undef T5_MODREGS
404
405 static int
406 dump_regs(int argc, const char *argv[])
407 {
408         int vers, revision, rc;
409         struct t4_regdump regs;
410         uint32_t len;
411
412         len = max(T4_REGDUMP_SIZE, T5_REGDUMP_SIZE);
413         regs.data = calloc(1, len);
414         if (regs.data == NULL) {
415                 warnc(ENOMEM, "regdump");
416                 return (ENOMEM);
417         }
418
419         regs.len = len;
420         rc = doit(CHELSIO_T4_REGDUMP, &regs);
421         if (rc != 0)
422                 return (rc);
423
424         vers = get_card_vers(regs.version);
425         revision = (regs.version >> 10) & 0x3f;
426
427         if (vers == 4) {
428                 if (revision == 0x3f)
429                         rc = dump_regs_t4vf(argc, argv, regs.data);
430                 else
431                         rc = dump_regs_t4(argc, argv, regs.data);
432         } else if (vers == 5)
433                 rc = dump_regs_t5(argc, argv, regs.data);
434         else {
435                 warnx("%s (type %d, rev %d) is not a known card.",
436                     nexus, vers, revision);
437                 return (ENOTSUP);
438         }
439
440         free(regs.data);
441         return (rc);
442 }
443
444 static void
445 do_show_info_header(uint32_t mode)
446 {
447         uint32_t i;
448
449         printf ("%4s %8s", "Idx", "Hits");
450         for (i = T4_FILTER_FCoE; i <= T4_FILTER_IP_FRAGMENT; i <<= 1) {
451                 switch (mode & i) {
452                 case T4_FILTER_FCoE:
453                         printf (" FCoE");
454                         break;
455
456                 case T4_FILTER_PORT:
457                         printf (" Port");
458                         break;
459
460                 case T4_FILTER_VNIC:
461                         printf ("      vld:VNIC");
462                         break;
463
464                 case T4_FILTER_VLAN:
465                         printf ("      vld:VLAN");
466                         break;
467
468                 case T4_FILTER_IP_TOS:
469                         printf ("   TOS");
470                         break;
471
472                 case T4_FILTER_IP_PROTO:
473                         printf ("  Prot");
474                         break;
475
476                 case T4_FILTER_ETH_TYPE:
477                         printf ("   EthType");
478                         break;
479
480                 case T4_FILTER_MAC_IDX:
481                         printf ("  MACIdx");
482                         break;
483
484                 case T4_FILTER_MPS_HIT_TYPE:
485                         printf (" MPS");
486                         break;
487
488                 case T4_FILTER_IP_FRAGMENT:
489                         printf (" Frag");
490                         break;
491
492                 default:
493                         /* compressed filter field not enabled */
494                         break;
495                 }
496         }
497         printf(" %20s %20s %9s %9s %s\n",
498             "DIP", "SIP", "DPORT", "SPORT", "Action");
499 }
500
501 /*
502  * Parse an argument sub-vector as a { <parameter name> <value>[:<mask>] }
503  * ordered tuple.  If the parameter name in the argument sub-vector does not
504  * match the passed in parameter name, then a zero is returned for the
505  * function and no parsing is performed.  If there is a match, then the value
506  * and optional mask are parsed and returned in the provided return value
507  * pointers.  If no optional mask is specified, then a default mask of all 1s
508  * will be returned.
509  *
510  * An error in parsing the value[:mask] will result in an error message and
511  * program termination.
512  */
513 static int
514 parse_val_mask(const char *param, const char *args[], uint32_t *val,
515     uint32_t *mask)
516 {
517         char *p;
518
519         if (strcmp(param, args[0]) != 0)
520                 return (EINVAL);
521
522         *val = strtoul(args[1], &p, 0);
523         if (p > args[1]) {
524                 if (p[0] == 0) {
525                         *mask = ~0;
526                         return (0);
527                 }
528
529                 if (p[0] == ':' && p[1] != 0) {
530                         *mask = strtoul(p+1, &p, 0);
531                         if (p[0] == 0)
532                                 return (0);
533                 }
534         }
535
536         warnx("parameter \"%s\" has bad \"value[:mask]\" %s",
537             args[0], args[1]);
538
539         return (EINVAL);
540 }
541
542 /*
543  * Parse an argument sub-vector as a { <parameter name> <addr>[/<mask>] }
544  * ordered tuple.  If the parameter name in the argument sub-vector does not
545  * match the passed in parameter name, then a zero is returned for the
546  * function and no parsing is performed.  If there is a match, then the value
547  * and optional mask are parsed and returned in the provided return value
548  * pointers.  If no optional mask is specified, then a default mask of all 1s
549  * will be returned.
550  *
551  * The value return parameter "afp" is used to specify the expected address
552  * family -- IPv4 or IPv6 -- of the address[/mask] and return its actual
553  * format.  A passed in value of AF_UNSPEC indicates that either IPv4 or IPv6
554  * is acceptable; AF_INET means that only IPv4 addresses are acceptable; and
555  * AF_INET6 means that only IPv6 are acceptable.  AF_INET is returned for IPv4
556  * and AF_INET6 for IPv6 addresses, respectively.  IPv4 address/mask pairs are
557  * returned in the first four bytes of the address and mask return values with
558  * the address A.B.C.D returned with { A, B, C, D } returned in addresses { 0,
559  * 1, 2, 3}, respectively.
560  *
561  * An error in parsing the value[:mask] will result in an error message and
562  * program termination.
563  */
564 static int
565 parse_ipaddr(const char *param, const char *args[], int *afp, uint8_t addr[],
566     uint8_t mask[])
567 {
568         const char *colon, *afn;
569         char *slash;
570         uint8_t *m;
571         int af, ret;
572         unsigned int masksize;
573
574         /*
575          * Is this our parameter?
576          */
577         if (strcmp(param, args[0]) != 0)
578                 return (EINVAL);
579
580         /*
581          * Fundamental IPv4 versus IPv6 selection.
582          */
583         colon = strchr(args[1], ':');
584         if (!colon) {
585                 afn = "IPv4";
586                 af = AF_INET;
587                 masksize = 32;
588         } else {
589                 afn = "IPv6";
590                 af = AF_INET6;
591                 masksize = 128;
592         }
593         if (*afp == AF_UNSPEC)
594                 *afp = af;
595         else if (*afp != af) {
596                 warnx("address %s is not of expected family %s",
597                     args[1], *afp == AF_INET ? "IP" : "IPv6");
598                 return (EINVAL);
599         }
600
601         /*
602          * Parse address (temporarily stripping off any "/mask"
603          * specification).
604          */
605         slash = strchr(args[1], '/');
606         if (slash)
607                 *slash = 0;
608         ret = inet_pton(af, args[1], addr);
609         if (slash)
610                 *slash = '/';
611         if (ret <= 0) {
612                 warnx("Cannot parse %s %s address %s", param, afn, args[1]);
613                 return (EINVAL);
614         }
615
616         /*
617          * Parse optional mask specification.
618          */
619         if (slash) {
620                 char *p;
621                 unsigned int prefix = strtoul(slash + 1, &p, 10);
622
623                 if (p == slash + 1) {
624                         warnx("missing address prefix for %s", param);
625                         return (EINVAL);
626                 }
627                 if (*p) {
628                         warnx("%s is not a valid address prefix", slash + 1);
629                         return (EINVAL);
630                 }
631                 if (prefix > masksize) {
632                         warnx("prefix %u is too long for an %s address",
633                              prefix, afn);
634                         return (EINVAL);
635                 }
636                 memset(mask, 0, masksize / 8);
637                 masksize = prefix;
638         }
639
640         /*
641          * Fill in mask.
642          */
643         for (m = mask; masksize >= 8; m++, masksize -= 8)
644                 *m = ~0;
645         if (masksize)
646                 *m = ~0 << (8 - masksize);
647
648         return (0);
649 }
650
651 /*
652  * Parse an argument sub-vector as a { <parameter name> <value> } ordered
653  * tuple.  If the parameter name in the argument sub-vector does not match the
654  * passed in parameter name, then a zero is returned for the function and no
655  * parsing is performed.  If there is a match, then the value is parsed and
656  * returned in the provided return value pointer.
657  */
658 static int
659 parse_val(const char *param, const char *args[], uint32_t *val)
660 {
661         char *p;
662
663         if (strcmp(param, args[0]) != 0)
664                 return (EINVAL);
665
666         *val = strtoul(args[1], &p, 0);
667         if (p > args[1] && p[0] == 0)
668                 return (0);
669
670         warnx("parameter \"%s\" has bad \"value\" %s", args[0], args[1]);
671         return (EINVAL);
672 }
673
674 static void
675 filters_show_ipaddr(int type, uint8_t *addr, uint8_t *addrm)
676 {
677         int noctets, octet;
678
679         printf(" ");
680         if (type == 0) {
681                 noctets = 4;
682                 printf("%3s", " ");
683         } else
684         noctets = 16;
685
686         for (octet = 0; octet < noctets; octet++)
687                 printf("%02x", addr[octet]);
688         printf("/");
689         for (octet = 0; octet < noctets; octet++)
690                 printf("%02x", addrm[octet]);
691 }
692
693 static void
694 do_show_one_filter_info(struct t4_filter *t, uint32_t mode)
695 {
696         uint32_t i;
697
698         printf("%4d", t->idx);
699         if (t->hits == UINT64_MAX)
700                 printf(" %8s", "-");
701         else
702                 printf(" %8ju", t->hits);
703
704         /*
705          * Compressed header portion of filter.
706          */
707         for (i = T4_FILTER_FCoE; i <= T4_FILTER_IP_FRAGMENT; i <<= 1) {
708                 switch (mode & i) {
709                 case T4_FILTER_FCoE:
710                         printf("  %1d/%1d", t->fs.val.fcoe, t->fs.mask.fcoe);
711                         break;
712
713                 case T4_FILTER_PORT:
714                         printf("  %1d/%1d", t->fs.val.iport, t->fs.mask.iport);
715                         break;
716
717                 case T4_FILTER_VNIC:
718                         printf(" %1d:%1x:%02x/%1d:%1x:%02x",
719                             t->fs.val.vnic_vld, (t->fs.val.vnic >> 7) & 0x7,
720                             t->fs.val.vnic & 0x7f, t->fs.mask.vnic_vld,
721                             (t->fs.mask.vnic >> 7) & 0x7,
722                             t->fs.mask.vnic & 0x7f);
723                         break;
724
725                 case T4_FILTER_VLAN:
726                         printf(" %1d:%04x/%1d:%04x",
727                             t->fs.val.vlan_vld, t->fs.val.vlan,
728                             t->fs.mask.vlan_vld, t->fs.mask.vlan);
729                         break;
730
731                 case T4_FILTER_IP_TOS:
732                         printf(" %02x/%02x", t->fs.val.tos, t->fs.mask.tos);
733                         break;
734
735                 case T4_FILTER_IP_PROTO:
736                         printf(" %02x/%02x", t->fs.val.proto, t->fs.mask.proto);
737                         break;
738
739                 case T4_FILTER_ETH_TYPE:
740                         printf(" %04x/%04x", t->fs.val.ethtype,
741                             t->fs.mask.ethtype);
742                         break;
743
744                 case T4_FILTER_MAC_IDX:
745                         printf(" %03x/%03x", t->fs.val.macidx,
746                             t->fs.mask.macidx);
747                         break;
748
749                 case T4_FILTER_MPS_HIT_TYPE:
750                         printf(" %1x/%1x", t->fs.val.matchtype,
751                             t->fs.mask.matchtype);
752                         break;
753
754                 case T4_FILTER_IP_FRAGMENT:
755                         printf("  %1d/%1d", t->fs.val.frag, t->fs.mask.frag);
756                         break;
757
758                 default:
759                         /* compressed filter field not enabled */
760                         break;
761                 }
762         }
763
764         /*
765          * Fixed portion of filter.
766          */
767         filters_show_ipaddr(t->fs.type, t->fs.val.dip, t->fs.mask.dip);
768         filters_show_ipaddr(t->fs.type, t->fs.val.sip, t->fs.mask.sip);
769         printf(" %04x/%04x %04x/%04x",
770                  t->fs.val.dport, t->fs.mask.dport,
771                  t->fs.val.sport, t->fs.mask.sport);
772
773         /*
774          * Variable length filter action.
775          */
776         if (t->fs.action == FILTER_DROP)
777                 printf(" Drop");
778         else if (t->fs.action == FILTER_SWITCH) {
779                 printf(" Switch: port=%d", t->fs.eport);
780         if (t->fs.newdmac)
781                 printf(
782                         ", dmac=%02x:%02x:%02x:%02x:%02x:%02x "
783                         ", l2tidx=%d",
784                         t->fs.dmac[0], t->fs.dmac[1],
785                         t->fs.dmac[2], t->fs.dmac[3],
786                         t->fs.dmac[4], t->fs.dmac[5],
787                         t->l2tidx);
788         if (t->fs.newsmac)
789                 printf(
790                         ", smac=%02x:%02x:%02x:%02x:%02x:%02x "
791                         ", smtidx=%d",
792                         t->fs.smac[0], t->fs.smac[1],
793                         t->fs.smac[2], t->fs.smac[3],
794                         t->fs.smac[4], t->fs.smac[5],
795                         t->smtidx);
796         if (t->fs.newvlan == VLAN_REMOVE)
797                 printf(", vlan=none");
798         else if (t->fs.newvlan == VLAN_INSERT)
799                 printf(", vlan=insert(%x)", t->fs.vlan);
800         else if (t->fs.newvlan == VLAN_REWRITE)
801                 printf(", vlan=rewrite(%x)", t->fs.vlan);
802         } else {
803                 printf(" Pass: Q=");
804                 if (t->fs.dirsteer == 0) {
805                         printf("RSS");
806                         if (t->fs.maskhash)
807                                 printf("(TCB=hash)");
808                 } else {
809                         printf("%d", t->fs.iq);
810                         if (t->fs.dirsteerhash == 0)
811                                 printf("(QID)");
812                         else
813                                 printf("(hash)");
814                 }
815         }
816         if (t->fs.prio)
817                 printf(" Prio");
818         if (t->fs.rpttid)
819                 printf(" RptTID");
820         printf("\n");
821 }
822
823 static int
824 show_filters(void)
825 {
826         uint32_t mode = 0, header = 0;
827         struct t4_filter t;
828         int rc;
829
830         /* Get the global filter mode first */
831         rc = doit(CHELSIO_T4_GET_FILTER_MODE, &mode);
832         if (rc != 0)
833                 return (rc);
834
835         t.idx = 0;
836         for (t.idx = 0; ; t.idx++) {
837                 rc = doit(CHELSIO_T4_GET_FILTER, &t);
838                 if (rc != 0 || t.idx == 0xffffffff)
839                         break;
840
841                 if (!header) {
842                         do_show_info_header(mode);
843                         header = 1;
844                 }
845                 do_show_one_filter_info(&t, mode);
846         };
847
848         return (rc);
849 }
850
851 static int
852 get_filter_mode(void)
853 {
854         uint32_t mode = 0;
855         int rc;
856
857         rc = doit(CHELSIO_T4_GET_FILTER_MODE, &mode);
858         if (rc != 0)
859                 return (rc);
860
861         if (mode & T4_FILTER_IPv4)
862                 printf("ipv4 ");
863
864         if (mode & T4_FILTER_IPv6)
865                 printf("ipv6 ");
866
867         if (mode & T4_FILTER_IP_SADDR)
868                 printf("sip ");
869         
870         if (mode & T4_FILTER_IP_DADDR)
871                 printf("dip ");
872
873         if (mode & T4_FILTER_IP_SPORT)
874                 printf("sport ");
875
876         if (mode & T4_FILTER_IP_DPORT)
877                 printf("dport ");
878
879         if (mode & T4_FILTER_IP_FRAGMENT)
880                 printf("frag ");
881
882         if (mode & T4_FILTER_MPS_HIT_TYPE)
883                 printf("matchtype ");
884
885         if (mode & T4_FILTER_MAC_IDX)
886                 printf("macidx ");
887
888         if (mode & T4_FILTER_ETH_TYPE)
889                 printf("ethtype ");
890
891         if (mode & T4_FILTER_IP_PROTO)
892                 printf("proto ");
893
894         if (mode & T4_FILTER_IP_TOS)
895                 printf("tos ");
896
897         if (mode & T4_FILTER_VLAN)
898                 printf("vlan ");
899
900         if (mode & T4_FILTER_VNIC)
901                 printf("vnic/ovlan ");
902
903         if (mode & T4_FILTER_PORT)
904                 printf("iport ");
905
906         if (mode & T4_FILTER_FCoE)
907                 printf("fcoe ");
908
909         printf("\n");
910
911         return (0);
912 }
913
914 static int
915 set_filter_mode(int argc, const char *argv[])
916 {
917         uint32_t mode = 0;
918
919         for (; argc; argc--, argv++) {
920                 if (!strcmp(argv[0], "frag"))
921                         mode |= T4_FILTER_IP_FRAGMENT;
922
923                 if (!strcmp(argv[0], "matchtype"))
924                         mode |= T4_FILTER_MPS_HIT_TYPE;
925
926                 if (!strcmp(argv[0], "macidx"))
927                         mode |= T4_FILTER_MAC_IDX;
928
929                 if (!strcmp(argv[0], "ethtype"))
930                         mode |= T4_FILTER_ETH_TYPE;
931
932                 if (!strcmp(argv[0], "proto"))
933                         mode |= T4_FILTER_IP_PROTO;
934
935                 if (!strcmp(argv[0], "tos"))
936                         mode |= T4_FILTER_IP_TOS;
937
938                 if (!strcmp(argv[0], "vlan"))
939                         mode |= T4_FILTER_VLAN;
940
941                 if (!strcmp(argv[0], "ovlan") ||
942                     !strcmp(argv[0], "vnic"))
943                         mode |= T4_FILTER_VNIC;
944
945                 if (!strcmp(argv[0], "iport"))
946                         mode |= T4_FILTER_PORT;
947
948                 if (!strcmp(argv[0], "fcoe"))
949                         mode |= T4_FILTER_FCoE;
950         }
951
952         return doit(CHELSIO_T4_SET_FILTER_MODE, &mode);
953 }
954
955 static int
956 del_filter(uint32_t idx)
957 {
958         struct t4_filter t;
959
960         t.idx = idx;
961
962         return doit(CHELSIO_T4_DEL_FILTER, &t);
963 }
964
965 static int
966 set_filter(uint32_t idx, int argc, const char *argv[])
967 {
968         int af = AF_UNSPEC, start_arg = 0;
969         struct t4_filter t;
970
971         if (argc < 2) {
972                 warnc(EINVAL, "%s", __func__);
973                 return (EINVAL);
974         };
975         bzero(&t, sizeof (t));
976         t.idx = idx;
977         t.fs.hitcnts = 1;
978
979         for (start_arg = 0; start_arg + 2 <= argc; start_arg += 2) {
980                 const char **args = &argv[start_arg];
981                 uint32_t val, mask;
982
983                 if (!strcmp(argv[start_arg], "type")) {
984                         int newaf;
985                         if (!strcasecmp(argv[start_arg + 1], "ipv4"))
986                                 newaf = AF_INET;
987                         else if (!strcasecmp(argv[start_arg + 1], "ipv6"))
988                                 newaf = AF_INET6;
989                         else {
990                                 warnx("invalid type \"%s\"; "
991                                     "must be one of \"ipv4\" or \"ipv6\"",
992                                     argv[start_arg + 1]);
993                                 return (EINVAL);
994                         }
995
996                         if (af != AF_UNSPEC && af != newaf) {
997                                 warnx("conflicting IPv4/IPv6 specifications.");
998                                 return (EINVAL);
999                         }
1000                         af = newaf;
1001                 } else if (!parse_val_mask("fcoe", args, &val, &mask)) {
1002                         t.fs.val.fcoe = val;
1003                         t.fs.mask.fcoe = mask;
1004                 } else if (!parse_val_mask("iport", args, &val, &mask)) {
1005                         t.fs.val.iport = val;
1006                         t.fs.mask.iport = mask;
1007                 } else if (!parse_val_mask("ovlan", args, &val, &mask)) {
1008                         t.fs.val.vnic = val;
1009                         t.fs.mask.vnic = mask;
1010                         t.fs.val.vnic_vld = 1;
1011                         t.fs.mask.vnic_vld = 1;
1012                 } else if (!parse_val_mask("vnic", args, &val, &mask)) {
1013                         t.fs.val.vnic = val;
1014                         t.fs.mask.vnic = mask;
1015                         t.fs.val.vnic_vld = 1;
1016                         t.fs.mask.vnic_vld = 1;
1017                 } else if (!parse_val_mask("ivlan", args, &val, &mask)) {
1018                         t.fs.val.vlan = val;
1019                         t.fs.mask.vlan = mask;
1020                         t.fs.val.vlan_vld = 1;
1021                         t.fs.mask.vlan_vld = 1;
1022                 } else if (!parse_val_mask("tos", args, &val, &mask)) {
1023                         t.fs.val.tos = val;
1024                         t.fs.mask.tos = mask;
1025                 } else if (!parse_val_mask("proto", args, &val, &mask)) {
1026                         t.fs.val.proto = val;
1027                         t.fs.mask.proto = mask;
1028                 } else if (!parse_val_mask("ethtype", args, &val, &mask)) {
1029                         t.fs.val.ethtype = val;
1030                         t.fs.mask.ethtype = mask;
1031                 } else if (!parse_val_mask("macidx", args, &val, &mask)) {
1032                         t.fs.val.macidx = val;
1033                         t.fs.mask.macidx = mask;
1034                 } else if (!parse_val_mask("matchtype", args, &val, &mask)) {
1035                         t.fs.val.matchtype = val;
1036                         t.fs.mask.matchtype = mask;
1037                 } else if (!parse_val_mask("frag", args, &val, &mask)) {
1038                         t.fs.val.frag = val;
1039                         t.fs.mask.frag = mask;
1040                 } else if (!parse_val_mask("dport", args, &val, &mask)) {
1041                         t.fs.val.dport = val;
1042                         t.fs.mask.dport = mask;
1043                 } else if (!parse_val_mask("sport", args, &val, &mask)) {
1044                         t.fs.val.sport = val;
1045                         t.fs.mask.sport = mask;
1046                 } else if (!parse_ipaddr("dip", args, &af, t.fs.val.dip,
1047                     t.fs.mask.dip)) {
1048                         /* nada */;
1049                 } else if (!parse_ipaddr("sip", args, &af, t.fs.val.sip,
1050                     t.fs.mask.sip)) {
1051                         /* nada */;
1052                 } else if (!strcmp(argv[start_arg], "action")) {
1053                         if (!strcmp(argv[start_arg + 1], "pass"))
1054                                 t.fs.action = FILTER_PASS;
1055                         else if (!strcmp(argv[start_arg + 1], "drop"))
1056                                 t.fs.action = FILTER_DROP;
1057                         else if (!strcmp(argv[start_arg + 1], "switch"))
1058                                 t.fs.action = FILTER_SWITCH;
1059                         else {
1060                                 warnx("invalid action \"%s\"; must be one of"
1061                                      " \"pass\", \"drop\" or \"switch\"",
1062                                      argv[start_arg + 1]);
1063                                 return (EINVAL);
1064                         }
1065                 } else if (!parse_val("hitcnts", args, &val)) {
1066                         t.fs.hitcnts = val;
1067                 } else if (!parse_val("prio", args, &val)) {
1068                         t.fs.prio = val;
1069                 } else if (!parse_val("rpttid", args, &val)) {
1070                         t.fs.rpttid = 1;
1071                 } else if (!parse_val("queue", args, &val)) {
1072                         t.fs.dirsteer = 1;
1073                         t.fs.iq = val;
1074                 } else if (!parse_val("tcbhash", args, &val)) {
1075                         t.fs.maskhash = 1;
1076                         t.fs.dirsteerhash = 1;
1077                 } else if (!parse_val("eport", args, &val)) {
1078                         t.fs.eport = val;
1079                 } else if (!strcmp(argv[start_arg], "dmac")) {
1080                         struct ether_addr *daddr;
1081
1082                         daddr = ether_aton(argv[start_arg + 1]);
1083                         if (daddr == NULL) {
1084                                 warnx("invalid dmac address \"%s\"",
1085                                     argv[start_arg + 1]);
1086                                 return (EINVAL);
1087                         }
1088                         memcpy(t.fs.dmac, daddr, ETHER_ADDR_LEN);
1089                         t.fs.newdmac = 1;
1090                 } else if (!strcmp(argv[start_arg], "smac")) {
1091                         struct ether_addr *saddr;
1092
1093                         saddr = ether_aton(argv[start_arg + 1]);
1094                         if (saddr == NULL) {
1095                                 warnx("invalid smac address \"%s\"",
1096                                     argv[start_arg + 1]);
1097                                 return (EINVAL);
1098                         }
1099                         memcpy(t.fs.smac, saddr, ETHER_ADDR_LEN);
1100                         t.fs.newsmac = 1;
1101                 } else if (!strcmp(argv[start_arg], "vlan")) {
1102                         char *p;
1103                         if (!strcmp(argv[start_arg + 1], "none")) {
1104                                 t.fs.newvlan = VLAN_REMOVE;
1105                         } else if (argv[start_arg + 1][0] == '=') {
1106                                 t.fs.newvlan = VLAN_REWRITE;
1107                         } else if (argv[start_arg + 1][0] == '+') {
1108                                 t.fs.newvlan = VLAN_INSERT;
1109                         } else if (isdigit(argv[start_arg + 1][0]) &&
1110                             !parse_val_mask("vlan", args, &val, &mask)) {
1111                                 t.fs.val.vlan = val;
1112                                 t.fs.mask.vlan = mask;
1113                                 t.fs.val.vlan_vld = 1;
1114                                 t.fs.mask.vlan_vld = 1;
1115                         } else {
1116                                 warnx("unknown vlan parameter \"%s\"; must"
1117                                      " be one of \"none\", \"=<vlan>\", "
1118                                      " \"+<vlan>\", or \"<vlan>\"",
1119                                      argv[start_arg + 1]);
1120                                 return (EINVAL);
1121                         }
1122                         if (t.fs.newvlan == VLAN_REWRITE ||
1123                             t.fs.newvlan == VLAN_INSERT) {
1124                                 t.fs.vlan = strtoul(argv[start_arg + 1] + 1,
1125                                     &p, 0);
1126                                 if (p == argv[start_arg + 1] + 1 || p[0] != 0) {
1127                                         warnx("invalid vlan \"%s\"",
1128                                              argv[start_arg + 1]);
1129                                         return (EINVAL);
1130                                 }
1131                         }
1132                 } else {
1133                         warnx("invalid parameter \"%s\"", argv[start_arg]);
1134                         return (EINVAL);
1135                 }
1136         }
1137         if (start_arg != argc) {
1138                 warnx("no value for \"%s\"", argv[start_arg]);
1139                 return (EINVAL);
1140         }
1141
1142         /*
1143          * Check basic sanity of option combinations.
1144          */
1145         if (t.fs.action != FILTER_SWITCH &&
1146             (t.fs.eport || t.fs.newdmac || t.fs.newsmac || t.fs.newvlan)) {
1147                 warnx("prio, port dmac, smac and vlan only make sense with"
1148                      " \"action switch\"");
1149                 return (EINVAL);
1150         }
1151         if (t.fs.action != FILTER_PASS &&
1152             (t.fs.rpttid || t.fs.dirsteer || t.fs.maskhash)) {
1153                 warnx("rpttid, queue and tcbhash don't make sense with"
1154                      " action \"drop\" or \"switch\"");
1155                 return (EINVAL);
1156         }
1157
1158         t.fs.type = (af == AF_INET6 ? 1 : 0); /* default IPv4 */
1159         return doit(CHELSIO_T4_SET_FILTER, &t);
1160 }
1161
1162 static int
1163 filter_cmd(int argc, const char *argv[])
1164 {
1165         long long val;
1166         uint32_t idx;
1167         char *s;
1168
1169         if (argc == 0) {
1170                 warnx("filter: no arguments.");
1171                 return (EINVAL);
1172         };
1173
1174         /* list */
1175         if (strcmp(argv[0], "list") == 0) {
1176                 if (argc != 1)
1177                         warnx("trailing arguments after \"list\" ignored.");
1178
1179                 return show_filters();
1180         }
1181
1182         /* mode */
1183         if (argc == 1 && strcmp(argv[0], "mode") == 0)
1184                 return get_filter_mode();
1185
1186         /* mode <mode> */
1187         if (strcmp(argv[0], "mode") == 0)
1188                 return set_filter_mode(argc - 1, argv + 1);
1189
1190         /* <idx> ... */
1191         s = str_to_number(argv[0], NULL, &val);
1192         if (*s || val > 0xffffffffU) {
1193                 warnx("\"%s\" is neither an index nor a filter subcommand.",
1194                     argv[0]);
1195                 return (EINVAL);
1196         }
1197         idx = (uint32_t) val;
1198
1199         /* <idx> delete|clear */
1200         if (argc == 2 &&
1201             (strcmp(argv[1], "delete") == 0 || strcmp(argv[1], "clear") == 0)) {
1202                 return del_filter(idx);
1203         }
1204
1205         /* <idx> [<param> <val>] ... */
1206         return set_filter(idx, argc - 1, argv + 1);
1207 }
1208
1209 /*
1210  * Shows the fields of a multi-word structure.  The structure is considered to
1211  * consist of @nwords 32-bit words (i.e, it's an (@nwords * 32)-bit structure)
1212  * whose fields are described by @fd.  The 32-bit words are given in @words
1213  * starting with the least significant 32-bit word.
1214  */
1215 static void
1216 show_struct(const uint32_t *words, int nwords, const struct field_desc *fd)
1217 {
1218         unsigned int w = 0;
1219         const struct field_desc *p;
1220
1221         for (p = fd; p->name; p++)
1222                 w = max(w, strlen(p->name));
1223
1224         while (fd->name) {
1225                 unsigned long long data;
1226                 int first_word = fd->start / 32;
1227                 int shift = fd->start % 32;
1228                 int width = fd->end - fd->start + 1;
1229                 unsigned long long mask = (1ULL << width) - 1;
1230
1231                 data = (words[first_word] >> shift) |
1232                        ((uint64_t)words[first_word + 1] << (32 - shift));
1233                 if (shift)
1234                        data |= ((uint64_t)words[first_word + 2] << (64 - shift));
1235                 data &= mask;
1236                 if (fd->islog2)
1237                         data = 1 << data;
1238                 printf("%-*s ", w, fd->name);
1239                 printf(fd->hex ? "%#llx\n" : "%llu\n", data << fd->shift);
1240                 fd++;
1241         }
1242 }
1243
1244 #define FIELD(name, start, end) { name, start, end, 0, 0, 0 }
1245 #define FIELD1(name, start) FIELD(name, start, start)
1246
1247 static void
1248 show_t5_ctxt(const struct t4_sge_context *p)
1249 {
1250         static struct field_desc egress_t5[] = {
1251                 FIELD("DCA_ST:", 181, 191),
1252                 FIELD1("StatusPgNS:", 180),
1253                 FIELD1("StatusPgRO:", 179),
1254                 FIELD1("FetchNS:", 178),
1255                 FIELD1("FetchRO:", 177),
1256                 FIELD1("Valid:", 176),
1257                 FIELD("PCIeDataChannel:", 174, 175),
1258                 FIELD1("StatusPgTPHintEn:", 173),
1259                 FIELD("StatusPgTPHint:", 171, 172),
1260                 FIELD1("FetchTPHintEn:", 170),
1261                 FIELD("FetchTPHint:", 168, 169),
1262                 FIELD1("FCThreshOverride:", 167),
1263                 { "WRLength:", 162, 166, 9, 0, 1 },
1264                 FIELD1("WRLengthKnown:", 161),
1265                 FIELD1("ReschedulePending:", 160),
1266                 FIELD1("OnChipQueue:", 159),
1267                 FIELD1("FetchSizeMode:", 158),
1268                 { "FetchBurstMin:", 156, 157, 4, 0, 1 },
1269                 FIELD1("FLMPacking:", 155),
1270                 FIELD("FetchBurstMax:", 153, 154),
1271                 FIELD("uPToken:", 133, 152),
1272                 FIELD1("uPTokenEn:", 132),
1273                 FIELD1("UserModeIO:", 131),
1274                 FIELD("uPFLCredits:", 123, 130),
1275                 FIELD1("uPFLCreditEn:", 122),
1276                 FIELD("FID:", 111, 121),
1277                 FIELD("HostFCMode:", 109, 110),
1278                 FIELD1("HostFCOwner:", 108),
1279                 { "CIDXFlushThresh:", 105, 107, 0, 0, 1 },
1280                 FIELD("CIDX:", 89, 104),
1281                 FIELD("PIDX:", 73, 88),
1282                 { "BaseAddress:", 18, 72, 9, 1 },
1283                 FIELD("QueueSize:", 2, 17),
1284                 FIELD1("QueueType:", 1),
1285                 FIELD1("CachePriority:", 0),
1286                 { NULL }
1287         };
1288         static struct field_desc fl_t5[] = {
1289                 FIELD("DCA_ST:", 181, 191),
1290                 FIELD1("StatusPgNS:", 180),
1291                 FIELD1("StatusPgRO:", 179),
1292                 FIELD1("FetchNS:", 178),
1293                 FIELD1("FetchRO:", 177),
1294                 FIELD1("Valid:", 176),
1295                 FIELD("PCIeDataChannel:", 174, 175),
1296                 FIELD1("StatusPgTPHintEn:", 173),
1297                 FIELD("StatusPgTPHint:", 171, 172),
1298                 FIELD1("FetchTPHintEn:", 170),
1299                 FIELD("FetchTPHint:", 168, 169),
1300                 FIELD1("FCThreshOverride:", 167),
1301                 FIELD1("ReschedulePending:", 160),
1302                 FIELD1("OnChipQueue:", 159),
1303                 FIELD1("FetchSizeMode:", 158),
1304                 { "FetchBurstMin:", 156, 157, 4, 0, 1 },
1305                 FIELD1("FLMPacking:", 155),
1306                 FIELD("FetchBurstMax:", 153, 154),
1307                 FIELD1("FLMcongMode:", 152),
1308                 FIELD("MaxuPFLCredits:", 144, 151),
1309                 FIELD("FLMcontextID:", 133, 143),
1310                 FIELD1("uPTokenEn:", 132),
1311                 FIELD1("UserModeIO:", 131),
1312                 FIELD("uPFLCredits:", 123, 130),
1313                 FIELD1("uPFLCreditEn:", 122),
1314                 FIELD("FID:", 111, 121),
1315                 FIELD("HostFCMode:", 109, 110),
1316                 FIELD1("HostFCOwner:", 108),
1317                 { "CIDXFlushThresh:", 105, 107, 0, 0, 1 },
1318                 FIELD("CIDX:", 89, 104),
1319                 FIELD("PIDX:", 73, 88),
1320                 { "BaseAddress:", 18, 72, 9, 1 },
1321                 FIELD("QueueSize:", 2, 17),
1322                 FIELD1("QueueType:", 1),
1323                 FIELD1("CachePriority:", 0),
1324                 { NULL }
1325         };
1326         static struct field_desc ingress_t5[] = {
1327                 FIELD("DCA_ST:", 143, 153),
1328                 FIELD1("ISCSICoalescing:", 142),
1329                 FIELD1("Queue_Valid:", 141),
1330                 FIELD1("TimerPending:", 140),
1331                 FIELD1("DropRSS:", 139),
1332                 FIELD("PCIeChannel:", 137, 138),
1333                 FIELD1("SEInterruptArmed:", 136),
1334                 FIELD1("CongestionMgtEnable:", 135),
1335                 FIELD1("NoSnoop:", 134),
1336                 FIELD1("RelaxedOrdering:", 133),
1337                 FIELD1("GTSmode:", 132),
1338                 FIELD1("TPHintEn:", 131),
1339                 FIELD("TPHint:", 129, 130),
1340                 FIELD1("UpdateScheduling:", 128),
1341                 FIELD("UpdateDelivery:", 126, 127),
1342                 FIELD1("InterruptSent:", 125),
1343                 FIELD("InterruptIDX:", 114, 124),
1344                 FIELD1("InterruptDestination:", 113),
1345                 FIELD1("InterruptArmed:", 112),
1346                 FIELD("RxIntCounter:", 106, 111),
1347                 FIELD("RxIntCounterThreshold:", 104, 105),
1348                 FIELD1("Generation:", 103),
1349                 { "BaseAddress:", 48, 102, 9, 1 },
1350                 FIELD("PIDX:", 32, 47),
1351                 FIELD("CIDX:", 16, 31),
1352                 { "QueueSize:", 4, 15, 4, 0 },
1353                 { "QueueEntrySize:", 2, 3, 4, 0, 1 },
1354                 FIELD1("QueueEntryOverride:", 1),
1355                 FIELD1("CachePriority:", 0),
1356                 { NULL }
1357         };
1358         static struct field_desc flm_t5[] = {
1359                 FIELD1("Valid:", 89),
1360                 FIELD("SplitLenMode:", 87, 88),
1361                 FIELD1("TPHintEn:", 86),
1362                 FIELD("TPHint:", 84, 85),
1363                 FIELD1("NoSnoop:", 83),
1364                 FIELD1("RelaxedOrdering:", 82),
1365                 FIELD("DCA_ST:", 71, 81),
1366                 FIELD("EQid:", 54, 70),
1367                 FIELD("SplitEn:", 52, 53),
1368                 FIELD1("PadEn:", 51),
1369                 FIELD1("PackEn:", 50),
1370                 FIELD1("Cache_Lock :", 49),
1371                 FIELD1("CongDrop:", 48),
1372                 FIELD("PackOffset:", 16, 47),
1373                 FIELD("CIDX:", 8, 15),
1374                 FIELD("PIDX:", 0, 7),
1375                 { NULL }
1376         };
1377         static struct field_desc conm_t5[] = {
1378                 FIELD1("CngMPSEnable:", 21),
1379                 FIELD("CngTPMode:", 19, 20),
1380                 FIELD1("CngDBPHdr:", 18),
1381                 FIELD1("CngDBPData:", 17),
1382                 FIELD1("CngIMSG:", 16),
1383                 { "CngChMap:", 0, 15, 0, 1, 0 },
1384                 { NULL }
1385         };
1386
1387         if (p->mem_id == SGE_CONTEXT_EGRESS)
1388                 show_struct(p->data, 6, (p->data[0] & 2) ? fl_t5 : egress_t5);
1389         else if (p->mem_id == SGE_CONTEXT_FLM)
1390                 show_struct(p->data, 3, flm_t5);
1391         else if (p->mem_id == SGE_CONTEXT_INGRESS)
1392                 show_struct(p->data, 5, ingress_t5);
1393         else if (p->mem_id == SGE_CONTEXT_CNM)
1394                 show_struct(p->data, 1, conm_t5);
1395 }
1396
1397 static void
1398 show_t4_ctxt(const struct t4_sge_context *p)
1399 {
1400         static struct field_desc egress_t4[] = {
1401                 FIELD1("StatusPgNS:", 180),
1402                 FIELD1("StatusPgRO:", 179),
1403                 FIELD1("FetchNS:", 178),
1404                 FIELD1("FetchRO:", 177),
1405                 FIELD1("Valid:", 176),
1406                 FIELD("PCIeDataChannel:", 174, 175),
1407                 FIELD1("DCAEgrQEn:", 173),
1408                 FIELD("DCACPUID:", 168, 172),
1409                 FIELD1("FCThreshOverride:", 167),
1410                 FIELD("WRLength:", 162, 166),
1411                 FIELD1("WRLengthKnown:", 161),
1412                 FIELD1("ReschedulePending:", 160),
1413                 FIELD1("OnChipQueue:", 159),
1414                 FIELD1("FetchSizeMode", 158),
1415                 { "FetchBurstMin:", 156, 157, 4, 0, 1 },
1416                 { "FetchBurstMax:", 153, 154, 6, 0, 1 },
1417                 FIELD("uPToken:", 133, 152),
1418                 FIELD1("uPTokenEn:", 132),
1419                 FIELD1("UserModeIO:", 131),
1420                 FIELD("uPFLCredits:", 123, 130),
1421                 FIELD1("uPFLCreditEn:", 122),
1422                 FIELD("FID:", 111, 121),
1423                 FIELD("HostFCMode:", 109, 110),
1424                 FIELD1("HostFCOwner:", 108),
1425                 { "CIDXFlushThresh:", 105, 107, 0, 0, 1 },
1426                 FIELD("CIDX:", 89, 104),
1427                 FIELD("PIDX:", 73, 88),
1428                 { "BaseAddress:", 18, 72, 9, 1 },
1429                 FIELD("QueueSize:", 2, 17),
1430                 FIELD1("QueueType:", 1),
1431                 FIELD1("CachePriority:", 0),
1432                 { NULL }
1433         };
1434         static struct field_desc fl_t4[] = {
1435                 FIELD1("StatusPgNS:", 180),
1436                 FIELD1("StatusPgRO:", 179),
1437                 FIELD1("FetchNS:", 178),
1438                 FIELD1("FetchRO:", 177),
1439                 FIELD1("Valid:", 176),
1440                 FIELD("PCIeDataChannel:", 174, 175),
1441                 FIELD1("DCAEgrQEn:", 173),
1442                 FIELD("DCACPUID:", 168, 172),
1443                 FIELD1("FCThreshOverride:", 167),
1444                 FIELD1("ReschedulePending:", 160),
1445                 FIELD1("OnChipQueue:", 159),
1446                 FIELD1("FetchSizeMode", 158),
1447                 { "FetchBurstMin:", 156, 157, 4, 0, 1 },
1448                 { "FetchBurstMax:", 153, 154, 6, 0, 1 },
1449                 FIELD1("FLMcongMode:", 152),
1450                 FIELD("MaxuPFLCredits:", 144, 151),
1451                 FIELD("FLMcontextID:", 133, 143),
1452                 FIELD1("uPTokenEn:", 132),
1453                 FIELD1("UserModeIO:", 131),
1454                 FIELD("uPFLCredits:", 123, 130),
1455                 FIELD1("uPFLCreditEn:", 122),
1456                 FIELD("FID:", 111, 121),
1457                 FIELD("HostFCMode:", 109, 110),
1458                 FIELD1("HostFCOwner:", 108),
1459                 { "CIDXFlushThresh:", 105, 107, 0, 0, 1 },
1460                 FIELD("CIDX:", 89, 104),
1461                 FIELD("PIDX:", 73, 88),
1462                 { "BaseAddress:", 18, 72, 9, 1 },
1463                 FIELD("QueueSize:", 2, 17),
1464                 FIELD1("QueueType:", 1),
1465                 FIELD1("CachePriority:", 0),
1466                 { NULL }
1467         };
1468         static struct field_desc ingress_t4[] = {
1469                 FIELD1("NoSnoop:", 145),
1470                 FIELD1("RelaxedOrdering:", 144),
1471                 FIELD1("GTSmode:", 143),
1472                 FIELD1("ISCSICoalescing:", 142),
1473                 FIELD1("Valid:", 141),
1474                 FIELD1("TimerPending:", 140),
1475                 FIELD1("DropRSS:", 139),
1476                 FIELD("PCIeChannel:", 137, 138),
1477                 FIELD1("SEInterruptArmed:", 136),
1478                 FIELD1("CongestionMgtEnable:", 135),
1479                 FIELD1("DCAIngQEnable:", 134),
1480                 FIELD("DCACPUID:", 129, 133),
1481                 FIELD1("UpdateScheduling:", 128),
1482                 FIELD("UpdateDelivery:", 126, 127),
1483                 FIELD1("InterruptSent:", 125),
1484                 FIELD("InterruptIDX:", 114, 124),
1485                 FIELD1("InterruptDestination:", 113),
1486                 FIELD1("InterruptArmed:", 112),
1487                 FIELD("RxIntCounter:", 106, 111),
1488                 FIELD("RxIntCounterThreshold:", 104, 105),
1489                 FIELD1("Generation:", 103),
1490                 { "BaseAddress:", 48, 102, 9, 1 },
1491                 FIELD("PIDX:", 32, 47),
1492                 FIELD("CIDX:", 16, 31),
1493                 { "QueueSize:", 4, 15, 4, 0 },
1494                 { "QueueEntrySize:", 2, 3, 4, 0, 1 },
1495                 FIELD1("QueueEntryOverride:", 1),
1496                 FIELD1("CachePriority:", 0),
1497                 { NULL }
1498         };
1499         static struct field_desc flm_t4[] = {
1500                 FIELD1("NoSnoop:", 79),
1501                 FIELD1("RelaxedOrdering:", 78),
1502                 FIELD1("Valid:", 77),
1503                 FIELD("DCACPUID:", 72, 76),
1504                 FIELD1("DCAFLEn:", 71),
1505                 FIELD("EQid:", 54, 70),
1506                 FIELD("SplitEn:", 52, 53),
1507                 FIELD1("PadEn:", 51),
1508                 FIELD1("PackEn:", 50),
1509                 FIELD1("DBpriority:", 48),
1510                 FIELD("PackOffset:", 16, 47),
1511                 FIELD("CIDX:", 8, 15),
1512                 FIELD("PIDX:", 0, 7),
1513                 { NULL }
1514         };
1515         static struct field_desc conm_t4[] = {
1516                 FIELD1("CngDBPHdr:", 6),
1517                 FIELD1("CngDBPData:", 5),
1518                 FIELD1("CngIMSG:", 4),
1519                 { "CngChMap:", 0, 3, 0, 1, 0},
1520                 { NULL }
1521         };
1522
1523         if (p->mem_id == SGE_CONTEXT_EGRESS)
1524                 show_struct(p->data, 6, (p->data[0] & 2) ? fl_t4 : egress_t4);
1525         else if (p->mem_id == SGE_CONTEXT_FLM)
1526                 show_struct(p->data, 3, flm_t4);
1527         else if (p->mem_id == SGE_CONTEXT_INGRESS)
1528                 show_struct(p->data, 5, ingress_t4);
1529         else if (p->mem_id == SGE_CONTEXT_CNM)
1530                 show_struct(p->data, 1, conm_t4);
1531 }
1532
1533 #undef FIELD
1534 #undef FIELD1
1535
1536 static int
1537 get_sge_context(int argc, const char *argv[])
1538 {
1539         int rc;
1540         char *p;
1541         long cid;
1542         struct t4_sge_context cntxt = {0};
1543
1544         if (argc != 2) {
1545                 warnx("sge_context: incorrect number of arguments.");
1546                 return (EINVAL);
1547         }
1548
1549         if (!strcmp(argv[0], "egress"))
1550                 cntxt.mem_id = SGE_CONTEXT_EGRESS;
1551         else if (!strcmp(argv[0], "ingress"))
1552                 cntxt.mem_id = SGE_CONTEXT_INGRESS;
1553         else if (!strcmp(argv[0], "fl"))
1554                 cntxt.mem_id = SGE_CONTEXT_FLM;
1555         else if (!strcmp(argv[0], "cong"))
1556                 cntxt.mem_id = SGE_CONTEXT_CNM;
1557         else {
1558                 warnx("unknown context type \"%s\"; known types are egress, "
1559                     "ingress, fl, and cong.", argv[0]);
1560                 return (EINVAL);
1561         }
1562
1563         p = str_to_number(argv[1], &cid, NULL);
1564         if (*p) {
1565                 warnx("invalid context id \"%s\"", argv[1]);
1566                 return (EINVAL);
1567         }
1568         cntxt.cid = cid;
1569
1570         rc = doit(CHELSIO_T4_GET_SGE_CONTEXT, &cntxt);
1571         if (rc != 0)
1572                 return (rc);
1573
1574         if (chip_id == 4)
1575                 show_t4_ctxt(&cntxt);
1576         else
1577                 show_t5_ctxt(&cntxt);
1578
1579         return (0);
1580 }
1581
1582 static int
1583 loadfw(int argc, const char *argv[])
1584 {
1585         int rc, fd;
1586         struct t4_data data = {0};
1587         const char *fname = argv[0];
1588         struct stat st = {0};
1589
1590         if (argc != 1) {
1591                 warnx("loadfw: incorrect number of arguments.");
1592                 return (EINVAL);
1593         }
1594
1595         fd = open(fname, O_RDONLY);
1596         if (fd < 0) {
1597                 warn("open(%s)", fname);
1598                 return (errno);
1599         }
1600
1601         if (fstat(fd, &st) < 0) {
1602                 warn("fstat");
1603                 close(fd);
1604                 return (errno);
1605         }
1606
1607         data.len = st.st_size;
1608         data.data = mmap(0, data.len, PROT_READ, MAP_PRIVATE, fd, 0);
1609         if (data.data == MAP_FAILED) {
1610                 warn("mmap");
1611                 close(fd);
1612                 return (errno);
1613         }
1614
1615         rc = doit(CHELSIO_T4_LOAD_FW, &data);
1616         munmap(data.data, data.len);
1617         close(fd);
1618         return (rc);
1619 }
1620
1621 static int
1622 read_mem(uint32_t addr, uint32_t len, void (*output)(uint32_t *, uint32_t))
1623 {
1624         int rc;
1625         struct t4_mem_range mr;
1626
1627         mr.addr = addr;
1628         mr.len = len;
1629         mr.data = malloc(mr.len);
1630
1631         if (mr.data == 0) {
1632                 warn("read_mem: malloc");
1633                 return (errno);
1634         }
1635
1636         rc = doit(CHELSIO_T4_GET_MEM, &mr);
1637         if (rc != 0)
1638                 goto done;
1639
1640         if (output)
1641                 (*output)(mr.data, mr.len);
1642 done:
1643         free(mr.data);
1644         return (rc);
1645 }
1646
1647 /*
1648  * Display memory as list of 'n' 4-byte values per line.
1649  */
1650 static void
1651 show_mem(uint32_t *buf, uint32_t len)
1652 {
1653         const char *s;
1654         int i, n = 8;
1655
1656         while (len) {
1657                 for (i = 0; len && i < n; i++, buf++, len -= 4) {
1658                         s = i ? " " : "";
1659                         printf("%s%08x", s, htonl(*buf));
1660                 }
1661                 printf("\n");
1662         }
1663 }
1664
1665 static int
1666 memdump(int argc, const char *argv[])
1667 {
1668         char *p;
1669         long l;
1670         uint32_t addr, len;
1671
1672         if (argc != 2) {
1673                 warnx("incorrect number of arguments.");
1674                 return (EINVAL);
1675         }
1676
1677         p = str_to_number(argv[0], &l, NULL);
1678         if (*p) {
1679                 warnx("invalid address \"%s\"", argv[0]);
1680                 return (EINVAL);
1681         }
1682         addr = l;
1683
1684         p = str_to_number(argv[1], &l, NULL);
1685         if (*p) {
1686                 warnx("memdump: invalid length \"%s\"", argv[1]);
1687                 return (EINVAL);
1688         }
1689         len = l;
1690
1691         return (read_mem(addr, len, show_mem));
1692 }
1693
1694 /*
1695  * Display TCB as list of 'n' 4-byte values per line.
1696  */
1697 static void
1698 show_tcb(uint32_t *buf, uint32_t len)
1699 {
1700         const char *s;
1701         int i, n = 8;
1702
1703         while (len) {
1704                 for (i = 0; len && i < n; i++, buf++, len -= 4) {
1705                         s = i ? " " : "";
1706                         printf("%s%08x", s, htonl(*buf));
1707                 }
1708                 printf("\n");
1709         }
1710 }
1711
1712 #define A_TP_CMM_TCB_BASE 0x7d10
1713 #define TCB_SIZE 128
1714 static int
1715 read_tcb(int argc, const char *argv[])
1716 {
1717         char *p;
1718         long l;
1719         long long val;
1720         unsigned int tid;
1721         uint32_t addr;
1722         int rc;
1723
1724         if (argc != 1) {
1725                 warnx("incorrect number of arguments.");
1726                 return (EINVAL);
1727         }
1728
1729         p = str_to_number(argv[0], &l, NULL);
1730         if (*p) {
1731                 warnx("invalid tid \"%s\"", argv[0]);
1732                 return (EINVAL);
1733         }
1734         tid = l;
1735
1736         rc = read_reg(A_TP_CMM_TCB_BASE, 4, &val);
1737         if (rc != 0)
1738                 return (rc);
1739
1740         addr = val + tid * TCB_SIZE;
1741
1742         return (read_mem(addr, TCB_SIZE, show_tcb));
1743 }
1744
1745 static int
1746 read_i2c(int argc, const char *argv[])
1747 {
1748         char *p;
1749         long l;
1750         struct t4_i2c_data i2cd;
1751         int rc, i;
1752
1753         if (argc < 3 || argc > 4) {
1754                 warnx("incorrect number of arguments.");
1755                 return (EINVAL);
1756         }
1757
1758         p = str_to_number(argv[0], &l, NULL);
1759         if (*p || l > UCHAR_MAX) {
1760                 warnx("invalid port id \"%s\"", argv[0]);
1761                 return (EINVAL);
1762         }
1763         i2cd.port_id = l;
1764
1765         p = str_to_number(argv[1], &l, NULL);
1766         if (*p || l > UCHAR_MAX) {
1767                 warnx("invalid i2c device address \"%s\"", argv[1]);
1768                 return (EINVAL);
1769         }
1770         i2cd.dev_addr = l;
1771
1772         p = str_to_number(argv[2], &l, NULL);
1773         if (*p || l > UCHAR_MAX) {
1774                 warnx("invalid byte offset \"%s\"", argv[2]);
1775                 return (EINVAL);
1776         }
1777         i2cd.offset = l;
1778
1779         if (argc == 4) {
1780                 p = str_to_number(argv[3], &l, NULL);
1781                 if (*p || l > sizeof(i2cd.data)) {
1782                         warnx("invalid number of bytes \"%s\"", argv[3]);
1783                         return (EINVAL);
1784                 }
1785                 i2cd.len = l;
1786         } else
1787                 i2cd.len = 1;
1788
1789         rc = doit(CHELSIO_T4_GET_I2C, &i2cd);
1790         if (rc != 0)
1791                 return (rc);
1792
1793         for (i = 0; i < i2cd.len; i++)
1794                 printf("0x%x [%u]\n", i2cd.data[i], i2cd.data[i]);
1795
1796         return (0);
1797 }
1798
1799 static int
1800 clearstats(int argc, const char *argv[])
1801 {
1802         char *p;
1803         long l;
1804         uint32_t port;
1805
1806         if (argc != 1) {
1807                 warnx("incorrect number of arguments.");
1808                 return (EINVAL);
1809         }
1810
1811         p = str_to_number(argv[0], &l, NULL);
1812         if (*p) {
1813                 warnx("invalid port id \"%s\"", argv[0]);
1814                 return (EINVAL);
1815         }
1816         port = l;
1817
1818         return doit(CHELSIO_T4_CLEAR_STATS, &port);
1819 }
1820
1821 static int
1822 show_tracers(void)
1823 {
1824         struct t4_tracer t;
1825         char *s;
1826         int rc, port_idx, i;
1827         long long val;
1828
1829         /* Magic values: MPS_TRC_CFG = 0x9800. MPS_TRC_CFG[1:1] = TrcEn */
1830         rc = read_reg(0x9800, 4, &val);
1831         if (rc != 0)
1832                 return (rc);
1833         printf("tracing is %s\n", val & 2 ? "ENABLED" : "DISABLED");
1834
1835         t.idx = 0;
1836         for (t.idx = 0; ; t.idx++) {
1837                 rc = doit(CHELSIO_T4_GET_TRACER, &t);
1838                 if (rc != 0 || t.idx == 0xff)
1839                         break;
1840
1841                 if (t.tp.port < 4) {
1842                         s = "Rx";
1843                         port_idx = t.tp.port;
1844                 } else if (t.tp.port < 8) {
1845                         s = "Tx";
1846                         port_idx = t.tp.port - 4;
1847                 } else if (t.tp.port < 12) {
1848                         s = "loopback";
1849                         port_idx = t.tp.port - 8;
1850                 } else if (t.tp.port < 16) {
1851                         s = "MPS Rx";
1852                         port_idx = t.tp.port - 12;
1853                 } else if (t.tp.port < 20) {
1854                         s = "MPS Tx";
1855                         port_idx = t.tp.port - 16;
1856                 } else {
1857                         s = "unknown";
1858                         port_idx = t.tp.port;
1859                 }
1860
1861                 printf("\ntracer %u (currently %s) captures ", t.idx,
1862                     t.enabled ? "ENABLED" : "DISABLED");
1863                 if (t.tp.port < 8)
1864                         printf("port %u %s, ", port_idx, s);
1865                 else
1866                         printf("%s %u, ", s, port_idx);
1867                 printf("snap length: %u, min length: %u\n", t.tp.snap_len,
1868                     t.tp.min_len);
1869                 printf("packets captured %smatch filter\n",
1870                     t.tp.invert ? "do not " : "");
1871                 if (t.tp.skip_ofst) {
1872                         printf("filter pattern: ");
1873                         for (i = 0; i < t.tp.skip_ofst * 2; i += 2)
1874                                 printf("%08x%08x", t.tp.data[i],
1875                                     t.tp.data[i + 1]);
1876                         printf("/");
1877                         for (i = 0; i < t.tp.skip_ofst * 2; i += 2)
1878                                 printf("%08x%08x", t.tp.mask[i],
1879                                     t.tp.mask[i + 1]);
1880                         printf("@0\n");
1881                 }
1882                 printf("filter pattern: ");
1883                 for (i = t.tp.skip_ofst * 2; i < T4_TRACE_LEN / 4; i += 2)
1884                         printf("%08x%08x", t.tp.data[i], t.tp.data[i + 1]);
1885                 printf("/");
1886                 for (i = t.tp.skip_ofst * 2; i < T4_TRACE_LEN / 4; i += 2)
1887                         printf("%08x%08x", t.tp.mask[i], t.tp.mask[i + 1]);
1888                 printf("@%u\n", (t.tp.skip_ofst + t.tp.skip_len) * 8);
1889         }
1890
1891         return (rc);
1892 }
1893
1894 static int
1895 tracer_onoff(uint8_t idx, int enabled)
1896 {
1897         struct t4_tracer t;
1898
1899         t.idx = idx;
1900         t.enabled = enabled;
1901         t.valid = 0;
1902
1903         return doit(CHELSIO_T4_SET_TRACER, &t);
1904 }
1905
1906 static void
1907 create_tracing_ifnet()
1908 {
1909         char *cmd[] = {
1910                 "/sbin/ifconfig", __DECONST(char *, nexus), "create", NULL
1911         };
1912         char *env[] = {NULL};
1913
1914         if (vfork() == 0) {
1915                 close(STDERR_FILENO);
1916                 execve(cmd[0], cmd, env);
1917                 _exit(0);
1918         }
1919 }
1920
1921 /*
1922  * XXX: Allow user to specify snaplen, minlen, and pattern (including inverted
1923  * matching).  Right now this is a quick-n-dirty implementation that traces the
1924  * first 128B of all tx or rx on a port
1925  */
1926 static int
1927 set_tracer(uint8_t idx, int argc, const char *argv[])
1928 {
1929         struct t4_tracer t;
1930         int len, port;
1931
1932         bzero(&t, sizeof (t));
1933         t.idx = idx;
1934         t.enabled = 1;
1935         t.valid = 1;
1936
1937         if (argc != 1) {
1938                 warnx("must specify tx<n> or rx<n>.");
1939                 return (EINVAL);
1940         }
1941
1942         len = strlen(argv[0]);
1943         if (len != 3) {
1944                 warnx("argument must be 3 characters (tx<n> or rx<n>)");
1945                 return (EINVAL);
1946         }
1947
1948         if (strncmp(argv[0], "tx", 2) == 0) {
1949                 port = argv[0][2] - '0';
1950                 if (port < 0 || port > 3) {
1951                         warnx("'%c' in %s is invalid", argv[0][2], argv[0]);
1952                         return (EINVAL);
1953                 }
1954                 port += 4;
1955         } else if (strncmp(argv[0], "rx", 2) == 0) {
1956                 port = argv[0][2] - '0';
1957                 if (port < 0 || port > 3) {
1958                         warnx("'%c' in %s is invalid", argv[0][2], argv[0]);
1959                         return (EINVAL);
1960                 }
1961         } else {
1962                 warnx("argument '%s' isn't tx<n> or rx<n>", argv[0]);
1963                 return (EINVAL);
1964         }
1965
1966         t.tp.snap_len = 128;
1967         t.tp.min_len = 0;
1968         t.tp.skip_ofst = 0;
1969         t.tp.skip_len = 0;
1970         t.tp.invert = 0;
1971         t.tp.port = port;
1972
1973         create_tracing_ifnet();
1974         return doit(CHELSIO_T4_SET_TRACER, &t);
1975 }
1976
1977 static int
1978 tracer_cmd(int argc, const char *argv[])
1979 {
1980         long long val;
1981         uint8_t idx;
1982         char *s;
1983
1984         if (argc == 0) {
1985                 warnx("tracer: no arguments.");
1986                 return (EINVAL);
1987         };
1988
1989         /* list */
1990         if (strcmp(argv[0], "list") == 0) {
1991                 if (argc != 1)
1992                         warnx("trailing arguments after \"list\" ignored.");
1993
1994                 return show_tracers();
1995         }
1996
1997         /* <idx> ... */
1998         s = str_to_number(argv[0], NULL, &val);
1999         if (*s || val > 0xff) {
2000                 warnx("\"%s\" is neither an index nor a tracer subcommand.",
2001                     argv[0]);
2002                 return (EINVAL);
2003         }
2004         idx = (int8_t)val;
2005
2006         /* <idx> disable */
2007         if (argc == 2 && strcmp(argv[1], "disable") == 0)
2008                 return tracer_onoff(idx, 0);
2009
2010         /* <idx> enable */
2011         if (argc == 2 && strcmp(argv[1], "enable") == 0)
2012                 return tracer_onoff(idx, 1);
2013
2014         /* <idx> ... */
2015         return set_tracer(idx, argc - 1, argv + 1);
2016 }
2017
2018 static int
2019 modinfo_raw(int port_id)
2020 {
2021         uint8_t offset;
2022         struct t4_i2c_data i2cd;
2023         int rc;
2024
2025         for (offset = 0; offset < 96; offset += sizeof(i2cd.data)) {
2026                 bzero(&i2cd, sizeof(i2cd));
2027                 i2cd.port_id = port_id;
2028                 i2cd.dev_addr = 0xa0;
2029                 i2cd.offset = offset;
2030                 i2cd.len = sizeof(i2cd.data);
2031                 rc = doit(CHELSIO_T4_GET_I2C, &i2cd);
2032                 if (rc != 0)
2033                         return (rc);
2034                 printf("%02x:  %02x %02x %02x %02x  %02x %02x %02x %02x",
2035                     offset, i2cd.data[0], i2cd.data[1], i2cd.data[2],
2036                     i2cd.data[3], i2cd.data[4], i2cd.data[5], i2cd.data[6],
2037                     i2cd.data[7]);
2038
2039                 printf("  %c%c%c%c %c%c%c%c\n",
2040                     isprint(i2cd.data[0]) ? i2cd.data[0] : '.',
2041                     isprint(i2cd.data[1]) ? i2cd.data[1] : '.',
2042                     isprint(i2cd.data[2]) ? i2cd.data[2] : '.',
2043                     isprint(i2cd.data[3]) ? i2cd.data[3] : '.',
2044                     isprint(i2cd.data[4]) ? i2cd.data[4] : '.',
2045                     isprint(i2cd.data[5]) ? i2cd.data[5] : '.',
2046                     isprint(i2cd.data[6]) ? i2cd.data[6] : '.',
2047                     isprint(i2cd.data[7]) ? i2cd.data[7] : '.');
2048         }
2049
2050         return (0);
2051 }
2052
2053 static int
2054 modinfo(int argc, const char *argv[])
2055 {
2056         long port;
2057         char string[16], *p;
2058         struct t4_i2c_data i2cd;
2059         int rc, i;
2060         uint16_t temp, vcc, tx_bias, tx_power, rx_power;
2061
2062         if (argc < 1) {
2063                 warnx("must supply a port");
2064                 return (EINVAL);
2065         }
2066
2067         if (argc > 2) {
2068                 warnx("too many arguments");
2069                 return (EINVAL);
2070         }
2071
2072         p = str_to_number(argv[0], &port, NULL);
2073         if (*p || port > UCHAR_MAX) {
2074                 warnx("invalid port id \"%s\"", argv[0]);
2075                 return (EINVAL);
2076         }
2077
2078         if (argc == 2) {
2079                 if (!strcmp(argv[1], "raw"))
2080                         return (modinfo_raw(port));
2081                 else {
2082                         warnx("second argument can only be \"raw\"");
2083                         return (EINVAL);
2084                 }
2085         }
2086
2087         bzero(&i2cd, sizeof(i2cd));
2088         i2cd.len = 1;
2089         i2cd.port_id = port;
2090         i2cd.dev_addr = SFF_8472_BASE;
2091
2092         i2cd.offset = SFF_8472_ID;
2093         if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2094                 goto fail;
2095
2096         if (i2cd.data[0] > SFF_8472_ID_LAST)
2097                 printf("Unknown ID\n");
2098         else
2099                 printf("ID: %s\n", sff_8472_id[i2cd.data[0]]);
2100
2101         bzero(&string, sizeof(string));
2102         for (i = SFF_8472_VENDOR_START; i < SFF_8472_VENDOR_END; i++) {
2103                 i2cd.offset = i;
2104                 if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2105                         goto fail;
2106                 string[i - SFF_8472_VENDOR_START] = i2cd.data[0];
2107         }
2108         printf("Vendor %s\n", string);
2109
2110         bzero(&string, sizeof(string));
2111         for (i = SFF_8472_SN_START; i < SFF_8472_SN_END; i++) {
2112                 i2cd.offset = i;
2113                 if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2114                         goto fail;
2115                 string[i - SFF_8472_SN_START] = i2cd.data[0];
2116         }
2117         printf("SN %s\n", string);
2118
2119         bzero(&string, sizeof(string));
2120         for (i = SFF_8472_PN_START; i < SFF_8472_PN_END; i++) {
2121                 i2cd.offset = i;
2122                 if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2123                         goto fail;
2124                 string[i - SFF_8472_PN_START] = i2cd.data[0];
2125         }
2126         printf("PN %s\n", string);
2127
2128         bzero(&string, sizeof(string));
2129         for (i = SFF_8472_REV_START; i < SFF_8472_REV_END; i++) {
2130                 i2cd.offset = i;
2131                 if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2132                         goto fail;
2133                 string[i - SFF_8472_REV_START] = i2cd.data[0];
2134         }
2135         printf("Rev %s\n", string);
2136
2137         i2cd.offset = SFF_8472_DIAG_TYPE;
2138         if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2139                 goto fail;
2140
2141         if ((char )i2cd.data[0] & (SFF_8472_DIAG_IMPL |
2142                                    SFF_8472_DIAG_INTERNAL)) {
2143
2144                 /* Switch to reading from the Diagnostic address. */
2145                 i2cd.dev_addr = SFF_8472_DIAG;
2146                 i2cd.len = 1;
2147
2148                 i2cd.offset = SFF_8472_TEMP;
2149                 if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2150                         goto fail;
2151                 temp = i2cd.data[0] << 8;
2152                 printf("Temp: ");
2153                 if ((temp & SFF_8472_TEMP_SIGN) == SFF_8472_TEMP_SIGN)
2154                         printf("-");
2155                 else
2156                         printf("+");
2157                 printf("%dC\n", (temp & SFF_8472_TEMP_MSK) >>
2158                     SFF_8472_TEMP_SHIFT);
2159
2160                 i2cd.offset = SFF_8472_VCC;
2161                 if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2162                         goto fail;
2163                 vcc = i2cd.data[0] << 8;
2164                 printf("Vcc %fV\n", vcc / SFF_8472_VCC_FACTOR);
2165
2166                 i2cd.offset = SFF_8472_TX_BIAS;
2167                 if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2168                         goto fail;
2169                 tx_bias = i2cd.data[0] << 8;
2170                 printf("TX Bias %fuA\n", tx_bias / SFF_8472_BIAS_FACTOR);
2171
2172                 i2cd.offset = SFF_8472_TX_POWER;
2173                 if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2174                         goto fail;
2175                 tx_power = i2cd.data[0] << 8;
2176                 printf("TX Power %fmW\n", tx_power / SFF_8472_POWER_FACTOR);
2177
2178                 i2cd.offset = SFF_8472_RX_POWER;
2179                 if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2180                         goto fail;
2181                 rx_power = i2cd.data[0] << 8;
2182                 printf("RX Power %fmW\n", rx_power / SFF_8472_POWER_FACTOR);
2183
2184         } else
2185                 printf("Diagnostics not supported.\n");
2186
2187         return(0);
2188
2189 fail:
2190         if (rc == EPERM)
2191                 warnx("No module/cable in port %ld", port);
2192         return (rc);
2193
2194 }
2195
2196 /* XXX: pass in a low/high and do range checks as well */
2197 static int
2198 get_sched_param(const char *param, const char *args[], long *val)
2199 {
2200         char *p;
2201
2202         if (strcmp(param, args[0]) != 0)
2203                 return (EINVAL);
2204
2205         p = str_to_number(args[1], val, NULL);
2206         if (*p) {
2207                 warnx("parameter \"%s\" has bad value \"%s\"", args[0],
2208                     args[1]);
2209                 return (EINVAL);
2210         }
2211
2212         return (0);
2213 }
2214
2215 static int
2216 sched_class(int argc, const char *argv[])
2217 {
2218         struct t4_sched_params op;
2219         int errs, i;
2220
2221         memset(&op, 0xff, sizeof(op));
2222         op.subcmd = -1;
2223         op.type = -1;
2224         if (argc == 0) {
2225                 warnx("missing scheduling sub-command");
2226                 return (EINVAL);
2227         }
2228         if (!strcmp(argv[0], "config")) {
2229                 op.subcmd = SCHED_CLASS_SUBCMD_CONFIG;
2230                 op.u.config.minmax = -1;
2231         } else if (!strcmp(argv[0], "params")) {
2232                 op.subcmd = SCHED_CLASS_SUBCMD_PARAMS;
2233                 op.u.params.level = op.u.params.mode = op.u.params.rateunit =
2234                     op.u.params.ratemode = op.u.params.channel =
2235                     op.u.params.cl = op.u.params.minrate = op.u.params.maxrate =
2236                     op.u.params.weight = op.u.params.pktsize = -1;
2237         } else {
2238                 warnx("invalid scheduling sub-command \"%s\"", argv[0]);
2239                 return (EINVAL);
2240         }
2241
2242         /* Decode remaining arguments ... */
2243         errs = 0;
2244         for (i = 1; i < argc; i += 2) {
2245                 const char **args = &argv[i];
2246                 long l;
2247
2248                 if (i + 1 == argc) {
2249                         warnx("missing argument for \"%s\"", args[0]);
2250                         errs++;
2251                         break;
2252                 }
2253
2254                 if (!strcmp(args[0], "type")) {
2255                         if (!strcmp(args[1], "packet"))
2256                                 op.type = SCHED_CLASS_TYPE_PACKET;
2257                         else {
2258                                 warnx("invalid type parameter \"%s\"", args[1]);
2259                                 errs++;
2260                         }
2261
2262                         continue;
2263                 }
2264
2265                 if (op.subcmd == SCHED_CLASS_SUBCMD_CONFIG) {
2266                         if(!get_sched_param("minmax", args, &l))
2267                                 op.u.config.minmax = (int8_t)l;
2268                         else {
2269                                 warnx("unknown scheduler config parameter "
2270                                     "\"%s\"", args[0]);
2271                                 errs++;
2272                         }
2273
2274                         continue;
2275                 }
2276
2277                 /* Rest applies only to SUBCMD_PARAMS */
2278                 if (op.subcmd != SCHED_CLASS_SUBCMD_PARAMS)
2279                         continue;
2280
2281                 if (!strcmp(args[0], "level")) {
2282                         if (!strcmp(args[1], "cl-rl"))
2283                                 op.u.params.level = SCHED_CLASS_LEVEL_CL_RL;
2284                         else if (!strcmp(args[1], "cl-wrr"))
2285                                 op.u.params.level = SCHED_CLASS_LEVEL_CL_WRR;
2286                         else if (!strcmp(args[1], "ch-rl"))
2287                                 op.u.params.level = SCHED_CLASS_LEVEL_CH_RL;
2288                         else {
2289                                 warnx("invalid level parameter \"%s\"",
2290                                     args[1]);
2291                                 errs++;
2292                         }
2293                 } else if (!strcmp(args[0], "mode")) {
2294                         if (!strcmp(args[1], "class"))
2295                                 op.u.params.mode = SCHED_CLASS_MODE_CLASS;
2296                         else if (!strcmp(args[1], "flow"))
2297                                 op.u.params.mode = SCHED_CLASS_MODE_FLOW;
2298                         else {
2299                                 warnx("invalid mode parameter \"%s\"", args[1]);
2300                                 errs++;
2301                         }
2302                 } else if (!strcmp(args[0], "rate-unit")) {
2303                         if (!strcmp(args[1], "bits"))
2304                                 op.u.params.rateunit = SCHED_CLASS_RATEUNIT_BITS;
2305                         else if (!strcmp(args[1], "pkts"))
2306                                 op.u.params.rateunit = SCHED_CLASS_RATEUNIT_PKTS;
2307                         else {
2308                                 warnx("invalid rate-unit parameter \"%s\"",
2309                                     args[1]);
2310                                 errs++;
2311                         }
2312                 } else if (!strcmp(args[0], "rate-mode")) {
2313                         if (!strcmp(args[1], "relative"))
2314                                 op.u.params.ratemode = SCHED_CLASS_RATEMODE_REL;
2315                         else if (!strcmp(args[1], "absolute"))
2316                                 op.u.params.ratemode = SCHED_CLASS_RATEMODE_ABS;
2317                         else {
2318                                 warnx("invalid rate-mode parameter \"%s\"",
2319                                     args[1]);
2320                                 errs++;
2321                         }
2322                 } else if (!get_sched_param("channel", args, &l))
2323                         op.u.params.channel = (int8_t)l;
2324                 else if (!get_sched_param("class", args, &l))
2325                         op.u.params.cl = (int8_t)l;
2326                 else if (!get_sched_param("min-rate", args, &l))
2327                         op.u.params.minrate = (int32_t)l;
2328                 else if (!get_sched_param("max-rate", args, &l))
2329                         op.u.params.maxrate = (int32_t)l;
2330                 else if (!get_sched_param("weight", args, &l))
2331                         op.u.params.weight = (int16_t)l;
2332                 else if (!get_sched_param("pkt-size", args, &l))
2333                         op.u.params.pktsize = (int16_t)l;
2334                 else {
2335                         warnx("unknown scheduler parameter \"%s\"", args[0]);
2336                         errs++;
2337                 }
2338         }
2339
2340         /*
2341          * Catch some logical fallacies in terms of argument combinations here
2342          * so we can offer more than just the EINVAL return from the driver.
2343          * The driver will be able to catch a lot more issues since it knows
2344          * the specifics of the device hardware capabilities like how many
2345          * channels, classes, etc. the device supports.
2346          */
2347         if (op.type < 0) {
2348                 warnx("sched \"type\" parameter missing");
2349                 errs++;
2350         }
2351         if (op.subcmd == SCHED_CLASS_SUBCMD_CONFIG) {
2352                 if (op.u.config.minmax < 0) {
2353                         warnx("sched config \"minmax\" parameter missing");
2354                         errs++;
2355                 }
2356         }
2357         if (op.subcmd == SCHED_CLASS_SUBCMD_PARAMS) {
2358                 if (op.u.params.level < 0) {
2359                         warnx("sched params \"level\" parameter missing");
2360                         errs++;
2361                 }
2362                 if (op.u.params.mode < 0) {
2363                         warnx("sched params \"mode\" parameter missing");
2364                         errs++;
2365                 }
2366                 if (op.u.params.rateunit < 0) {
2367                         warnx("sched params \"rate-unit\" parameter missing");
2368                         errs++;
2369                 }
2370                 if (op.u.params.ratemode < 0) {
2371                         warnx("sched params \"rate-mode\" parameter missing");
2372                         errs++;
2373                 }
2374                 if (op.u.params.channel < 0) {
2375                         warnx("sched params \"channel\" missing");
2376                         errs++;
2377                 }
2378                 if (op.u.params.cl < 0) {
2379                         warnx("sched params \"class\" missing");
2380                         errs++;
2381                 }
2382                 if (op.u.params.maxrate < 0 &&
2383                     (op.u.params.level == SCHED_CLASS_LEVEL_CL_RL ||
2384                     op.u.params.level == SCHED_CLASS_LEVEL_CH_RL)) {
2385                         warnx("sched params \"max-rate\" missing for "
2386                             "rate-limit level");
2387                         errs++;
2388                 }
2389                 if (op.u.params.weight < 0 &&
2390                     op.u.params.level == SCHED_CLASS_LEVEL_CL_WRR) {
2391                         warnx("sched params \"weight\" missing for "
2392                             "weighted-round-robin level");
2393                         errs++;
2394                 }
2395                 if (op.u.params.pktsize < 0 &&
2396                     (op.u.params.level == SCHED_CLASS_LEVEL_CL_RL ||
2397                     op.u.params.level == SCHED_CLASS_LEVEL_CH_RL)) {
2398                         warnx("sched params \"pkt-size\" missing for "
2399                             "rate-limit level");
2400                         errs++;
2401                 }
2402                 if (op.u.params.mode == SCHED_CLASS_MODE_FLOW &&
2403                     op.u.params.ratemode != SCHED_CLASS_RATEMODE_ABS) {
2404                         warnx("sched params mode flow needs rate-mode absolute");
2405                         errs++;
2406                 }
2407                 if (op.u.params.ratemode == SCHED_CLASS_RATEMODE_REL &&
2408                     !in_range(op.u.params.maxrate, 1, 100)) {
2409                         warnx("sched params \"max-rate\" takes "
2410                             "percentage value(1-100) for rate-mode relative");
2411                         errs++;
2412                 }
2413                 if (op.u.params.ratemode == SCHED_CLASS_RATEMODE_ABS &&
2414                     !in_range(op.u.params.maxrate, 1, 10000000)) {
2415                         warnx("sched params \"max-rate\" takes "
2416                             "value(1-10000000) for rate-mode absolute");
2417                         errs++;
2418                 }
2419                 if (op.u.params.maxrate > 0 &&
2420                     op.u.params.maxrate < op.u.params.minrate) {
2421                         warnx("sched params \"max-rate\" is less than "
2422                             "\"min-rate\"");
2423                         errs++;
2424                 }
2425         }
2426
2427         if (errs > 0) {
2428                 warnx("%d error%s in sched-class command", errs,
2429                     errs == 1 ? "" : "s");
2430                 return (EINVAL);
2431         }
2432
2433         return doit(CHELSIO_T4_SCHED_CLASS, &op);
2434 }
2435
2436 static int
2437 sched_queue(int argc, const char *argv[])
2438 {
2439         struct t4_sched_queue op = {0};
2440         char *p;
2441         long val;
2442
2443         if (argc != 3) {
2444                 /* need "<port> <queue> <class> */
2445                 warnx("incorrect number of arguments.");
2446                 return (EINVAL);
2447         }
2448
2449         p = str_to_number(argv[0], &val, NULL);
2450         if (*p || val > UCHAR_MAX) {
2451                 warnx("invalid port id \"%s\"", argv[0]);
2452                 return (EINVAL);
2453         }
2454         op.port = (uint8_t)val;
2455
2456         if (!strcmp(argv[1], "all") || !strcmp(argv[1], "*"))
2457                 op.queue = -1;
2458         else {
2459                 p = str_to_number(argv[1], &val, NULL);
2460                 if (*p || val < -1) {
2461                         warnx("invalid queue \"%s\"", argv[1]);
2462                         return (EINVAL);
2463                 }
2464                 op.queue = (int8_t)val;
2465         }
2466
2467         if (!strcmp(argv[2], "unbind") || !strcmp(argv[2], "clear"))
2468                 op.cl = -1;
2469         else {
2470                 p = str_to_number(argv[2], &val, NULL);
2471                 if (*p || val < -1) {
2472                         warnx("invalid class \"%s\"", argv[2]);
2473                         return (EINVAL);
2474                 }
2475                 op.cl = (int8_t)val;
2476         }
2477
2478         return doit(CHELSIO_T4_SCHED_QUEUE, &op);
2479 }
2480
2481 static int
2482 run_cmd(int argc, const char *argv[])
2483 {
2484         int rc = -1;
2485         const char *cmd = argv[0];
2486
2487         /* command */
2488         argc--;
2489         argv++;
2490
2491         if (!strcmp(cmd, "reg") || !strcmp(cmd, "reg32"))
2492                 rc = register_io(argc, argv, 4);
2493         else if (!strcmp(cmd, "reg64"))
2494                 rc = register_io(argc, argv, 8);
2495         else if (!strcmp(cmd, "regdump"))
2496                 rc = dump_regs(argc, argv);
2497         else if (!strcmp(cmd, "filter"))
2498                 rc = filter_cmd(argc, argv);
2499         else if (!strcmp(cmd, "context"))
2500                 rc = get_sge_context(argc, argv);
2501         else if (!strcmp(cmd, "loadfw"))
2502                 rc = loadfw(argc, argv);
2503         else if (!strcmp(cmd, "memdump"))
2504                 rc = memdump(argc, argv);
2505         else if (!strcmp(cmd, "tcb"))
2506                 rc = read_tcb(argc, argv);
2507         else if (!strcmp(cmd, "i2c"))
2508                 rc = read_i2c(argc, argv);
2509         else if (!strcmp(cmd, "clearstats"))
2510                 rc = clearstats(argc, argv);
2511         else if (!strcmp(cmd, "tracer"))
2512                 rc = tracer_cmd(argc, argv);
2513         else if (!strcmp(cmd, "modinfo"))
2514                 rc = modinfo(argc, argv);
2515         else if (!strcmp(cmd, "sched-class"))
2516                 rc = sched_class(argc, argv);
2517         else if (!strcmp(cmd, "sched-queue"))
2518                 rc = sched_queue(argc, argv);
2519         else {
2520                 rc = EINVAL;
2521                 warnx("invalid command \"%s\"", cmd);
2522         }
2523
2524         return (rc);
2525 }
2526
2527 #define MAX_ARGS 15
2528 static int
2529 run_cmd_loop(void)
2530 {
2531         int i, rc = 0;
2532         char buffer[128], *buf;
2533         const char *args[MAX_ARGS + 1];
2534
2535         /*
2536          * Simple loop: displays a "> " prompt and processes any input as a
2537          * cxgbetool command.  You're supposed to enter only the part after
2538          * "cxgbetool t4nexX".  Use "quit" or "exit" to exit.
2539          */
2540         for (;;) {
2541                 fprintf(stdout, "> ");
2542                 fflush(stdout);
2543                 buf = fgets(buffer, sizeof(buffer), stdin);
2544                 if (buf == NULL) {
2545                         if (ferror(stdin)) {
2546                                 warn("stdin error");
2547                                 rc = errno;     /* errno from fgets */
2548                         }
2549                         break;
2550                 }
2551
2552                 i = 0;
2553                 while ((args[i] = strsep(&buf, " \t\n")) != NULL) {
2554                         if (args[i][0] != 0 && ++i == MAX_ARGS)
2555                                 break;
2556                 }
2557                 args[i] = 0;
2558
2559                 if (i == 0)
2560                         continue;       /* skip empty line */
2561
2562                 if (!strcmp(args[0], "quit") || !strcmp(args[0], "exit"))
2563                         break;
2564
2565                 rc = run_cmd(i, args);
2566         }
2567
2568         /* rc normally comes from the last command (not including quit/exit) */
2569         return (rc);
2570 }
2571
2572 int
2573 main(int argc, const char *argv[])
2574 {
2575         int rc = -1;
2576
2577         progname = argv[0];
2578
2579         if (argc == 2) {
2580                 if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
2581                         usage(stdout);
2582                         exit(0);
2583                 }
2584         }
2585
2586         if (argc < 3) {
2587                 usage(stderr);
2588                 exit(EINVAL);
2589         }
2590
2591         nexus = argv[1];
2592
2593         /* progname and nexus */
2594         argc -= 2;
2595         argv += 2;
2596
2597         if (argc == 1 && !strcmp(argv[0], "stdio"))
2598                 rc = run_cmd_loop();
2599         else
2600                 rc = run_cmd(argc, argv);
2601
2602         return (rc);
2603 }