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