]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/cxgbetool/cxgbetool.c
Import mandoc 1.14.4
[FreeBSD/FreeBSD.git] / usr.sbin / 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 #include <pcap.h>
53
54 #include "t4_ioctl.h"
55 #include "tcb_common.h"
56
57 #define in_range(val, lo, hi) ( val < 0 || (val <= hi && val >= lo))
58 #define max(x, y) ((x) > (y) ? (x) : (y))
59
60 static const char *progname, *nexus;
61 static int chip_id;     /* 4 for T4, 5 for T5 */
62
63 struct reg_info {
64         const char *name;
65         uint32_t addr;
66         uint32_t len;
67 };
68
69 struct mod_regs {
70         const char *name;
71         const struct reg_info *ri;
72 };
73
74 struct field_desc {
75         const char *name;     /* Field name */
76         unsigned short start; /* Start bit position */
77         unsigned short end;   /* End bit position */
78         unsigned char shift;  /* # of low order bits omitted and implicitly 0 */
79         unsigned char hex;    /* Print field in hex instead of decimal */
80         unsigned char islog2; /* Field contains the base-2 log of the value */
81 };
82
83 #include "reg_defs_t4.c"
84 #include "reg_defs_t5.c"
85 #include "reg_defs_t6.c"
86 #include "reg_defs_t4vf.c"
87
88 static void
89 usage(FILE *fp)
90 {
91         fprintf(fp, "Usage: %s <nexus> [operation]\n", progname);
92         fprintf(fp,
93             "\tclearstats <port>                   clear port statistics\n"
94             "\tcontext <type> <id>                 show an SGE context\n"
95             "\tdumpstate <dump.bin>                dump chip state\n"
96             "\tfilter <idx> [<param> <val>] ...    set a filter\n"
97             "\tfilter <idx> delete|clear [prio 1]  delete a filter\n"
98             "\tfilter list                         list all filters\n"
99             "\tfilter mode [<match>] ...           get/set global filter mode\n"
100             "\thashfilter [<param> <val>] ...      set a hashfilter\n"
101             "\thashfilter <idx> delete|clear       delete a hashfilter\n"
102             "\thashfilter list                     list all hashfilters\n"
103             "\thashfilter mode                     get global hashfilter mode\n"
104             "\ti2c <port> <devaddr> <addr> [<len>] read from i2c device\n"
105             "\tloadboot <bi.bin> [pf|offset <val>] install boot image\n"
106             "\tloadboot clear [pf|offset <val>]    remove boot image\n"
107             "\tloadboot-cfg <bc.bin>               install boot config\n"
108             "\tloadboot-cfg clear                  remove boot config\n"
109             "\tloadcfg <fw-config.txt>             install configuration file\n"
110             "\tloadcfg clear                       remove configuration file\n"
111             "\tloadfw <fw-image.bin>               install firmware\n"
112             "\tmemdump <addr> <len>                dump a memory range\n"
113             "\tmodinfo <port> [raw]                optics/cable information\n"
114             "\tpolicy <policy.txt>                 install offload policy\n"
115             "\tpolicy clear                        remove offload policy\n"
116             "\treg <address>[=<val>]               read/write register\n"
117             "\treg64 <address>[=<val>]             read/write 64 bit register\n"
118             "\tregdump [<module>] ...              dump registers\n"
119             "\tsched-class params <param> <val> .. configure TX scheduler class\n"
120             "\tsched-queue <port> <queue> <class>  bind NIC queues to TX Scheduling class\n"
121             "\tstdio                               interactive mode\n"
122             "\ttcb <tid>                           read TCB\n"
123             "\ttracer <idx> tx<n>|rx<n>            set and enable a tracer\n"
124             "\ttracer <idx> disable|enable         disable or enable a tracer\n"
125             "\ttracer list                         list all tracers\n"
126             );
127 }
128
129 static inline unsigned int
130 get_card_vers(unsigned int version)
131 {
132         return (version & 0x3ff);
133 }
134
135 static int
136 real_doit(unsigned long cmd, void *data, const char *cmdstr)
137 {
138         static int fd = -1;
139         int rc = 0;
140
141         if (fd == -1) {
142                 char buf[64];
143
144                 snprintf(buf, sizeof(buf), "/dev/%s", nexus);
145                 if ((fd = open(buf, O_RDWR)) < 0) {
146                         warn("open(%s)", nexus);
147                         rc = errno;
148                         return (rc);
149                 }
150         }
151
152         rc = ioctl(fd, cmd, data);
153         if (rc < 0) {
154                 warn("%s", cmdstr);
155                 rc = errno;
156         }
157
158         return (rc);
159 }
160 #define doit(x, y) real_doit(x, y, #x)
161
162 static char *
163 str_to_number(const char *s, long *val, long long *vall)
164 {
165         char *p;
166
167         if (vall)
168                 *vall = strtoll(s, &p, 0);
169         else if (val)
170                 *val = strtol(s, &p, 0);
171         else
172                 p = NULL;
173
174         return (p);
175 }
176
177 static int
178 read_reg(long addr, int size, long long *val)
179 {
180         struct t4_reg reg;
181         int rc;
182
183         reg.addr = (uint32_t) addr;
184         reg.size = (uint32_t) size;
185         reg.val = 0;
186
187         rc = doit(CHELSIO_T4_GETREG, &reg);
188
189         *val = reg.val;
190
191         return (rc);
192 }
193
194 static int
195 write_reg(long addr, int size, long long val)
196 {
197         struct t4_reg reg;
198
199         reg.addr = (uint32_t) addr;
200         reg.size = (uint32_t) size;
201         reg.val = (uint64_t) val;
202
203         return doit(CHELSIO_T4_SETREG, &reg);
204 }
205
206 static int
207 register_io(int argc, const char *argv[], int size)
208 {
209         char *p, *v;
210         long addr;
211         long long val;
212         int w = 0, rc;
213
214         if (argc == 1) {
215                 /* <reg> OR <reg>=<value> */
216
217                 p = str_to_number(argv[0], &addr, NULL);
218                 if (*p) {
219                         if (*p != '=') {
220                                 warnx("invalid register \"%s\"", argv[0]);
221                                 return (EINVAL);
222                         }
223
224                         w = 1;
225                         v = p + 1;
226                         p = str_to_number(v, NULL, &val);
227
228                         if (*p) {
229                                 warnx("invalid value \"%s\"", v);
230                                 return (EINVAL);
231                         }
232                 }
233
234         } else if (argc == 2) {
235                 /* <reg> <value> */
236
237                 w = 1;
238
239                 p = str_to_number(argv[0], &addr, NULL);
240                 if (*p) {
241                         warnx("invalid register \"%s\"", argv[0]);
242                         return (EINVAL);
243                 }
244
245                 p = str_to_number(argv[1], NULL, &val);
246                 if (*p) {
247                         warnx("invalid value \"%s\"", argv[1]);
248                         return (EINVAL);
249                 }
250         } else {
251                 warnx("reg: invalid number of arguments (%d)", argc);
252                 return (EINVAL);
253         }
254
255         if (w)
256                 rc = write_reg(addr, size, val);
257         else {
258                 rc = read_reg(addr, size, &val);
259                 if (rc == 0)
260                         printf("0x%llx [%llu]\n", val, val);
261         }
262
263         return (rc);
264 }
265
266 static inline uint32_t
267 xtract(uint32_t val, int shift, int len)
268 {
269         return (val >> shift) & ((1 << len) - 1);
270 }
271
272 static int
273 dump_block_regs(const struct reg_info *reg_array, const uint32_t *regs)
274 {
275         uint32_t reg_val = 0;
276
277         for ( ; reg_array->name; ++reg_array)
278                 if (!reg_array->len) {
279                         reg_val = regs[reg_array->addr / 4];
280                         printf("[%#7x] %-47s %#-10x %u\n", reg_array->addr,
281                                reg_array->name, reg_val, reg_val);
282                 } else {
283                         uint32_t v = xtract(reg_val, reg_array->addr,
284                                             reg_array->len);
285
286                         printf("    %*u:%u %-47s %#-10x %u\n",
287                                reg_array->addr < 10 ? 3 : 2,
288                                reg_array->addr + reg_array->len - 1,
289                                reg_array->addr, reg_array->name, v, v);
290                 }
291
292         return (1);
293 }
294
295 static int
296 dump_regs_table(int argc, const char *argv[], const uint32_t *regs,
297     const struct mod_regs *modtab, int nmodules)
298 {
299         int i, j, match;
300
301         for (i = 0; i < argc; i++) {
302                 for (j = 0; j < nmodules; j++) {
303                         if (!strcmp(argv[i], modtab[j].name))
304                                 break;
305                 }
306
307                 if (j == nmodules) {
308                         warnx("invalid register block \"%s\"", argv[i]);
309                         fprintf(stderr, "\nAvailable blocks:");
310                         for ( ; nmodules; nmodules--, modtab++)
311                                 fprintf(stderr, " %s", modtab->name);
312                         fprintf(stderr, "\n");
313                         return (EINVAL);
314                 }
315         }
316
317         for ( ; nmodules; nmodules--, modtab++) {
318
319                 match = argc == 0 ? 1 : 0;
320                 for (i = 0; !match && i < argc; i++) {
321                         if (!strcmp(argv[i], modtab->name))
322                                 match = 1;
323                 }
324
325                 if (match)
326                         dump_block_regs(modtab->ri, regs);
327         }
328
329         return (0);
330 }
331
332 #define T4_MODREGS(name) { #name, t4_##name##_regs }
333 static int
334 dump_regs_t4(int argc, const char *argv[], const uint32_t *regs)
335 {
336         static struct mod_regs t4_mod[] = {
337                 T4_MODREGS(sge),
338                 { "pci", t4_pcie_regs },
339                 T4_MODREGS(dbg),
340                 T4_MODREGS(mc),
341                 T4_MODREGS(ma),
342                 { "edc0", t4_edc_0_regs },
343                 { "edc1", t4_edc_1_regs },
344                 T4_MODREGS(cim),
345                 T4_MODREGS(tp),
346                 T4_MODREGS(ulp_rx),
347                 T4_MODREGS(ulp_tx),
348                 { "pmrx", t4_pm_rx_regs },
349                 { "pmtx", t4_pm_tx_regs },
350                 T4_MODREGS(mps),
351                 { "cplsw", t4_cpl_switch_regs },
352                 T4_MODREGS(smb),
353                 { "i2c", t4_i2cm_regs },
354                 T4_MODREGS(mi),
355                 T4_MODREGS(uart),
356                 T4_MODREGS(pmu),
357                 T4_MODREGS(sf),
358                 T4_MODREGS(pl),
359                 T4_MODREGS(le),
360                 T4_MODREGS(ncsi),
361                 T4_MODREGS(xgmac)
362         };
363
364         return dump_regs_table(argc, argv, regs, t4_mod, nitems(t4_mod));
365 }
366 #undef T4_MODREGS
367
368 #define T5_MODREGS(name) { #name, t5_##name##_regs }
369 static int
370 dump_regs_t5(int argc, const char *argv[], const uint32_t *regs)
371 {
372         static struct mod_regs t5_mod[] = {
373                 T5_MODREGS(sge),
374                 { "pci", t5_pcie_regs },
375                 T5_MODREGS(dbg),
376                 { "mc0", t5_mc_0_regs },
377                 { "mc1", t5_mc_1_regs },
378                 T5_MODREGS(ma),
379                 { "edc0", t5_edc_t50_regs },
380                 { "edc1", t5_edc_t51_regs },
381                 T5_MODREGS(cim),
382                 T5_MODREGS(tp),
383                 { "ulprx", t5_ulp_rx_regs },
384                 { "ulptx", t5_ulp_tx_regs },
385                 { "pmrx", t5_pm_rx_regs },
386                 { "pmtx", t5_pm_tx_regs },
387                 T5_MODREGS(mps),
388                 { "cplsw", t5_cpl_switch_regs },
389                 T5_MODREGS(smb),
390                 { "i2c", t5_i2cm_regs },
391                 T5_MODREGS(mi),
392                 T5_MODREGS(uart),
393                 T5_MODREGS(pmu),
394                 T5_MODREGS(sf),
395                 T5_MODREGS(pl),
396                 T5_MODREGS(le),
397                 T5_MODREGS(ncsi),
398                 T5_MODREGS(mac),
399                 { "hma", t5_hma_t5_regs }
400         };
401
402         return dump_regs_table(argc, argv, regs, t5_mod, nitems(t5_mod));
403 }
404 #undef T5_MODREGS
405
406 #define T6_MODREGS(name) { #name, t6_##name##_regs }
407 static int
408 dump_regs_t6(int argc, const char *argv[], const uint32_t *regs)
409 {
410         static struct mod_regs t6_mod[] = {
411                 T6_MODREGS(sge),
412                 { "pci", t6_pcie_regs },
413                 T6_MODREGS(dbg),
414                 { "mc0", t6_mc_0_regs },
415                 T6_MODREGS(ma),
416                 { "edc0", t6_edc_t60_regs },
417                 { "edc1", t6_edc_t61_regs },
418                 T6_MODREGS(cim),
419                 T6_MODREGS(tp),
420                 { "ulprx", t6_ulp_rx_regs },
421                 { "ulptx", t6_ulp_tx_regs },
422                 { "pmrx", t6_pm_rx_regs },
423                 { "pmtx", t6_pm_tx_regs },
424                 T6_MODREGS(mps),
425                 { "cplsw", t6_cpl_switch_regs },
426                 T6_MODREGS(smb),
427                 { "i2c", t6_i2cm_regs },
428                 T6_MODREGS(mi),
429                 T6_MODREGS(uart),
430                 T6_MODREGS(pmu),
431                 T6_MODREGS(sf),
432                 T6_MODREGS(pl),
433                 T6_MODREGS(le),
434                 T6_MODREGS(ncsi),
435                 T6_MODREGS(mac),
436                 { "hma", t6_hma_t6_regs }
437         };
438
439         return dump_regs_table(argc, argv, regs, t6_mod, nitems(t6_mod));
440 }
441 #undef T6_MODREGS
442
443 static int
444 dump_regs_t4vf(int argc, const char *argv[], const uint32_t *regs)
445 {
446         static struct mod_regs t4vf_mod[] = {
447                 { "sge", t4vf_sge_regs },
448                 { "mps", t4vf_mps_regs },
449                 { "pl", t4vf_pl_regs },
450                 { "mbdata", t4vf_mbdata_regs },
451                 { "cim", t4vf_cim_regs },
452         };
453
454         return dump_regs_table(argc, argv, regs, t4vf_mod, nitems(t4vf_mod));
455 }
456
457 static int
458 dump_regs_t5vf(int argc, const char *argv[], const uint32_t *regs)
459 {
460         static struct mod_regs t5vf_mod[] = {
461                 { "sge", t5vf_sge_regs },
462                 { "mps", t4vf_mps_regs },
463                 { "pl", t5vf_pl_regs },
464                 { "mbdata", t4vf_mbdata_regs },
465                 { "cim", t4vf_cim_regs },
466         };
467
468         return dump_regs_table(argc, argv, regs, t5vf_mod, nitems(t5vf_mod));
469 }
470
471 static int
472 dump_regs_t6vf(int argc, const char *argv[], const uint32_t *regs)
473 {
474         static struct mod_regs t6vf_mod[] = {
475                 { "sge", t5vf_sge_regs },
476                 { "mps", t4vf_mps_regs },
477                 { "pl", t6vf_pl_regs },
478                 { "mbdata", t4vf_mbdata_regs },
479                 { "cim", t4vf_cim_regs },
480         };
481
482         return dump_regs_table(argc, argv, regs, t6vf_mod, nitems(t6vf_mod));
483 }
484
485 static int
486 dump_regs(int argc, const char *argv[])
487 {
488         int vers, revision, rc;
489         struct t4_regdump regs;
490         uint32_t len;
491
492         len = max(T4_REGDUMP_SIZE, T5_REGDUMP_SIZE);
493         regs.data = calloc(1, len);
494         if (regs.data == NULL) {
495                 warnc(ENOMEM, "regdump");
496                 return (ENOMEM);
497         }
498
499         regs.len = len;
500         rc = doit(CHELSIO_T4_REGDUMP, &regs);
501         if (rc != 0)
502                 return (rc);
503
504         vers = get_card_vers(regs.version);
505         revision = (regs.version >> 10) & 0x3f;
506
507         if (vers == 4) {
508                 if (revision == 0x3f)
509                         rc = dump_regs_t4vf(argc, argv, regs.data);
510                 else
511                         rc = dump_regs_t4(argc, argv, regs.data);
512         } else if (vers == 5) {
513                 if (revision == 0x3f)
514                         rc = dump_regs_t5vf(argc, argv, regs.data);
515                 else
516                         rc = dump_regs_t5(argc, argv, regs.data);
517         } else if (vers == 6) {
518                 if (revision == 0x3f)
519                         rc = dump_regs_t6vf(argc, argv, regs.data);
520                 else
521                         rc = dump_regs_t6(argc, argv, regs.data);
522         } else {
523                 warnx("%s (type %d, rev %d) is not a known card.",
524                     nexus, vers, revision);
525                 return (ENOTSUP);
526         }
527
528         free(regs.data);
529         return (rc);
530 }
531
532 static void
533 do_show_info_header(uint32_t mode)
534 {
535         uint32_t i;
536
537         printf("%4s %8s", "Idx", "Hits");
538         for (i = T4_FILTER_FCoE; i <= T4_FILTER_IP_FRAGMENT; i <<= 1) {
539                 switch (mode & i) {
540                 case T4_FILTER_FCoE:
541                         printf(" FCoE");
542                         break;
543
544                 case T4_FILTER_PORT:
545                         printf(" Port");
546                         break;
547
548                 case T4_FILTER_VNIC:
549                         if (mode & T4_FILTER_IC_VNIC)
550                                 printf("   VFvld:PF:VF");
551                         else
552                                 printf("     vld:oVLAN");
553                         break;
554
555                 case T4_FILTER_VLAN:
556                         printf("      vld:VLAN");
557                         break;
558
559                 case T4_FILTER_IP_TOS:
560                         printf("   TOS");
561                         break;
562
563                 case T4_FILTER_IP_PROTO:
564                         printf("  Prot");
565                         break;
566
567                 case T4_FILTER_ETH_TYPE:
568                         printf("   EthType");
569                         break;
570
571                 case T4_FILTER_MAC_IDX:
572                         printf("  MACIdx");
573                         break;
574
575                 case T4_FILTER_MPS_HIT_TYPE:
576                         printf(" MPS");
577                         break;
578
579                 case T4_FILTER_IP_FRAGMENT:
580                         printf(" Frag");
581                         break;
582
583                 default:
584                         /* compressed filter field not enabled */
585                         break;
586                 }
587         }
588         printf(" %20s %20s %9s %9s %s\n",
589             "DIP", "SIP", "DPORT", "SPORT", "Action");
590 }
591
592 /*
593  * Parse an argument sub-vector as a { <parameter name> <value>[:<mask>] }
594  * ordered tuple.  If the parameter name in the argument sub-vector does not
595  * match the passed in parameter name, then a zero is returned for the
596  * function and no parsing is performed.  If there is a match, then the value
597  * and optional mask are parsed and returned in the provided return value
598  * pointers.  If no optional mask is specified, then a default mask of all 1s
599  * will be returned.
600  *
601  * An error in parsing the value[:mask] will result in an error message and
602  * program termination.
603  */
604 static int
605 parse_val_mask(const char *param, const char *args[], uint32_t *val,
606     uint32_t *mask, int hashfilter)
607 {
608         long l;
609         char *p;
610
611         if (strcmp(param, args[0]) != 0)
612                 return (EINVAL);
613
614         p = str_to_number(args[1], &l, NULL);
615         if (l >= 0 && l <= UINT32_MAX) {
616                 *val = (uint32_t)l;
617                 if (p > args[1]) {
618                         if (p[0] == 0) {
619                                 *mask = ~0;
620                                 return (0);
621                         }
622
623                         if (p[0] == ':' && p[1] != 0) {
624                                 if (hashfilter) {
625                                         warnx("param %s: mask not allowed for "
626                                             "hashfilter or nat params", param);
627                                         return (EINVAL);
628                                 }
629                                 p = str_to_number(p + 1, &l, NULL);
630                                 if (l >= 0 && l <= UINT32_MAX && p[0] == 0) {
631                                         *mask = (uint32_t)l;
632                                         return (0);
633                                 }
634                         }
635                 }
636         }
637
638         warnx("parameter \"%s\" has bad \"value[:mask]\" %s",
639             args[0], args[1]);
640
641         return (EINVAL);
642 }
643
644 /*
645  * Parse an argument sub-vector as a { <parameter name> <addr>[/<mask>] }
646  * ordered tuple.  If the parameter name in the argument sub-vector does not
647  * match the passed in parameter name, then a zero is returned for the
648  * function and no parsing is performed.  If there is a match, then the value
649  * and optional mask are parsed and returned in the provided return value
650  * pointers.  If no optional mask is specified, then a default mask of all 1s
651  * will be returned.
652  *
653  * The value return parameter "afp" is used to specify the expected address
654  * family -- IPv4 or IPv6 -- of the address[/mask] and return its actual
655  * format.  A passed in value of AF_UNSPEC indicates that either IPv4 or IPv6
656  * is acceptable; AF_INET means that only IPv4 addresses are acceptable; and
657  * AF_INET6 means that only IPv6 are acceptable.  AF_INET is returned for IPv4
658  * and AF_INET6 for IPv6 addresses, respectively.  IPv4 address/mask pairs are
659  * returned in the first four bytes of the address and mask return values with
660  * the address A.B.C.D returned with { A, B, C, D } returned in addresses { 0,
661  * 1, 2, 3}, respectively.
662  *
663  * An error in parsing the value[:mask] will result in an error message and
664  * program termination.
665  */
666 static int
667 parse_ipaddr(const char *param, const char *args[], int *afp, uint8_t addr[],
668     uint8_t mask[], int maskless)
669 {
670         const char *colon, *afn;
671         char *slash;
672         uint8_t *m;
673         int af, ret;
674         unsigned int masksize;
675
676         /*
677          * Is this our parameter?
678          */
679         if (strcmp(param, args[0]) != 0)
680                 return (EINVAL);
681
682         /*
683          * Fundamental IPv4 versus IPv6 selection.
684          */
685         colon = strchr(args[1], ':');
686         if (!colon) {
687                 afn = "IPv4";
688                 af = AF_INET;
689                 masksize = 32;
690         } else {
691                 afn = "IPv6";
692                 af = AF_INET6;
693                 masksize = 128;
694         }
695         if (*afp == AF_UNSPEC)
696                 *afp = af;
697         else if (*afp != af) {
698                 warnx("address %s is not of expected family %s",
699                     args[1], *afp == AF_INET ? "IP" : "IPv6");
700                 return (EINVAL);
701         }
702
703         /*
704          * Parse address (temporarily stripping off any "/mask"
705          * specification).
706          */
707         slash = strchr(args[1], '/');
708         if (slash)
709                 *slash = 0;
710         ret = inet_pton(af, args[1], addr);
711         if (slash)
712                 *slash = '/';
713         if (ret <= 0) {
714                 warnx("Cannot parse %s %s address %s", param, afn, args[1]);
715                 return (EINVAL);
716         }
717
718         /*
719          * Parse optional mask specification.
720          */
721         if (slash) {
722                 char *p;
723                 unsigned int prefix = strtoul(slash + 1, &p, 10);
724
725                 if (maskless) {
726                         warnx("mask cannot be provided for maskless specification");
727                         return (EINVAL);
728                 }
729
730                 if (p == slash + 1) {
731                         warnx("missing address prefix for %s", param);
732                         return (EINVAL);
733                 }
734                 if (*p) {
735                         warnx("%s is not a valid address prefix", slash + 1);
736                         return (EINVAL);
737                 }
738                 if (prefix > masksize) {
739                         warnx("prefix %u is too long for an %s address",
740                              prefix, afn);
741                         return (EINVAL);
742                 }
743                 memset(mask, 0, masksize / 8);
744                 masksize = prefix;
745         }
746
747         if (mask != NULL) {
748                 /*
749                  * Fill in mask.
750                  */
751                 for (m = mask; masksize >= 8; m++, masksize -= 8)
752                         *m = ~0;
753                 if (masksize)
754                         *m = ~0 << (8 - masksize);
755         }
756
757         return (0);
758 }
759
760 /*
761  * Parse an argument sub-vector as a { <parameter name> <value> } ordered
762  * tuple.  If the parameter name in the argument sub-vector does not match the
763  * passed in parameter name, then a zero is returned for the function and no
764  * parsing is performed.  If there is a match, then the value is parsed and
765  * returned in the provided return value pointer.
766  */
767 static int
768 parse_val(const char *param, const char *args[], uint32_t *val)
769 {
770         char *p;
771         long l;
772
773         if (strcmp(param, args[0]) != 0)
774                 return (EINVAL);
775
776         p = str_to_number(args[1], &l, NULL);
777         if (*p || l < 0 || l > UINT32_MAX) {
778                 warnx("parameter \"%s\" has bad \"value\" %s", args[0], args[1]);
779                 return (EINVAL);
780         }
781
782         *val = (uint32_t)l;
783         return (0);
784 }
785
786 static void
787 filters_show_ipaddr(int type, uint8_t *addr, uint8_t *addrm)
788 {
789         int noctets, octet;
790
791         printf(" ");
792         if (type == 0) {
793                 noctets = 4;
794                 printf("%3s", " ");
795         } else
796         noctets = 16;
797
798         for (octet = 0; octet < noctets; octet++)
799                 printf("%02x", addr[octet]);
800         printf("/");
801         for (octet = 0; octet < noctets; octet++)
802                 printf("%02x", addrm[octet]);
803 }
804
805 static void
806 do_show_one_filter_info(struct t4_filter *t, uint32_t mode)
807 {
808         uint32_t i;
809
810         printf("%4d", t->idx);
811         if (t->hits == UINT64_MAX)
812                 printf(" %8s", "-");
813         else
814                 printf(" %8ju", t->hits);
815
816         /*
817          * Compressed header portion of filter.
818          */
819         for (i = T4_FILTER_FCoE; i <= T4_FILTER_IP_FRAGMENT; i <<= 1) {
820                 switch (mode & i) {
821                 case T4_FILTER_FCoE:
822                         printf("  %1d/%1d", t->fs.val.fcoe, t->fs.mask.fcoe);
823                         break;
824
825                 case T4_FILTER_PORT:
826                         printf("  %1d/%1d", t->fs.val.iport, t->fs.mask.iport);
827                         break;
828
829                 case T4_FILTER_VNIC:
830                         if (mode & T4_FILTER_IC_VNIC) {
831                                 printf(" %1d:%1x:%02x/%1d:%1x:%02x",
832                                     t->fs.val.pfvf_vld,
833                                     (t->fs.val.vnic >> 13) & 0x7,
834                                     t->fs.val.vnic & 0x1fff,
835                                     t->fs.mask.pfvf_vld,
836                                     (t->fs.mask.vnic >> 13) & 0x7,
837                                     t->fs.mask.vnic & 0x1fff);
838                         } else {
839                                 printf(" %1d:%04x/%1d:%04x",
840                                     t->fs.val.ovlan_vld, t->fs.val.vnic,
841                                     t->fs.mask.ovlan_vld, t->fs.mask.vnic);
842                         }
843                         break;
844
845                 case T4_FILTER_VLAN:
846                         printf(" %1d:%04x/%1d:%04x",
847                             t->fs.val.vlan_vld, t->fs.val.vlan,
848                             t->fs.mask.vlan_vld, t->fs.mask.vlan);
849                         break;
850
851                 case T4_FILTER_IP_TOS:
852                         printf(" %02x/%02x", t->fs.val.tos, t->fs.mask.tos);
853                         break;
854
855                 case T4_FILTER_IP_PROTO:
856                         printf(" %02x/%02x", t->fs.val.proto, t->fs.mask.proto);
857                         break;
858
859                 case T4_FILTER_ETH_TYPE:
860                         printf(" %04x/%04x", t->fs.val.ethtype,
861                             t->fs.mask.ethtype);
862                         break;
863
864                 case T4_FILTER_MAC_IDX:
865                         printf(" %03x/%03x", t->fs.val.macidx,
866                             t->fs.mask.macidx);
867                         break;
868
869                 case T4_FILTER_MPS_HIT_TYPE:
870                         printf(" %1x/%1x", t->fs.val.matchtype,
871                             t->fs.mask.matchtype);
872                         break;
873
874                 case T4_FILTER_IP_FRAGMENT:
875                         printf("  %1d/%1d", t->fs.val.frag, t->fs.mask.frag);
876                         break;
877
878                 default:
879                         /* compressed filter field not enabled */
880                         break;
881                 }
882         }
883
884         /*
885          * Fixed portion of filter.
886          */
887         filters_show_ipaddr(t->fs.type, t->fs.val.dip, t->fs.mask.dip);
888         filters_show_ipaddr(t->fs.type, t->fs.val.sip, t->fs.mask.sip);
889         printf(" %04x/%04x %04x/%04x",
890                  t->fs.val.dport, t->fs.mask.dport,
891                  t->fs.val.sport, t->fs.mask.sport);
892
893         /*
894          * Variable length filter action.
895          */
896         if (t->fs.action == FILTER_DROP)
897                 printf(" Drop");
898         else if (t->fs.action == FILTER_SWITCH) {
899                 printf(" Switch: port=%d", t->fs.eport);
900         if (t->fs.newdmac)
901                 printf(
902                         ", dmac=%02x:%02x:%02x:%02x:%02x:%02x "
903                         ", l2tidx=%d",
904                         t->fs.dmac[0], t->fs.dmac[1],
905                         t->fs.dmac[2], t->fs.dmac[3],
906                         t->fs.dmac[4], t->fs.dmac[5],
907                         t->l2tidx);
908         if (t->fs.newsmac)
909                 printf(
910                         ", smac=%02x:%02x:%02x:%02x:%02x:%02x "
911                         ", smtidx=%d",
912                         t->fs.smac[0], t->fs.smac[1],
913                         t->fs.smac[2], t->fs.smac[3],
914                         t->fs.smac[4], t->fs.smac[5],
915                         t->smtidx);
916         if (t->fs.newvlan == VLAN_REMOVE)
917                 printf(", vlan=none");
918         else if (t->fs.newvlan == VLAN_INSERT)
919                 printf(", vlan=insert(%x)", t->fs.vlan);
920         else if (t->fs.newvlan == VLAN_REWRITE)
921                 printf(", vlan=rewrite(%x)", t->fs.vlan);
922         } else {
923                 printf(" Pass: Q=");
924                 if (t->fs.dirsteer == 0) {
925                         printf("RSS");
926                         if (t->fs.maskhash)
927                                 printf("(TCB=hash)");
928                 } else {
929                         printf("%d", t->fs.iq);
930                         if (t->fs.dirsteerhash == 0)
931                                 printf("(QID)");
932                         else
933                                 printf("(hash)");
934                 }
935         }
936         if (chip_id <= 5 && t->fs.prio)
937                 printf(" Prio");
938         if (t->fs.rpttid)
939                 printf(" RptTID");
940         printf("\n");
941 }
942
943 static int
944 show_filters(int hash)
945 {
946         uint32_t mode = 0, header, hpfilter = 0;
947         struct t4_filter t;
948         int rc;
949
950         /* Get the global filter mode first */
951         rc = doit(CHELSIO_T4_GET_FILTER_MODE, &mode);
952         if (rc != 0)
953                 return (rc);
954
955         if (!hash && chip_id >= 6) {
956                 header = 0;
957                 bzero(&t, sizeof (t));
958                 t.idx = 0;
959                 t.fs.hash = 0;
960                 t.fs.prio = 1;
961                 for (t.idx = 0; ; t.idx++) {
962                         rc = doit(CHELSIO_T4_GET_FILTER, &t);
963                         if (rc != 0 || t.idx == 0xffffffff)
964                                 break;
965
966                         if (!header) {
967                                 printf("High Priority TCAM Region:\n");
968                                 do_show_info_header(mode);
969                                 header = 1;
970                                 hpfilter = 1;
971                         }
972                         do_show_one_filter_info(&t, mode);
973                 }
974         }
975
976         header = 0;
977         bzero(&t, sizeof (t));
978         t.idx = 0;
979         t.fs.hash = hash;
980         for (t.idx = 0; ; t.idx++) {
981                 rc = doit(CHELSIO_T4_GET_FILTER, &t);
982                 if (rc != 0 || t.idx == 0xffffffff)
983                         break;
984
985                 if (!header) {
986                         if (hpfilter)
987                                 printf("\nNormal Priority TCAM Region:\n");
988                         do_show_info_header(mode);
989                         header = 1;
990                 }
991                 do_show_one_filter_info(&t, mode);
992         }
993
994         return (rc);
995 }
996
997 static int
998 get_filter_mode(int hashfilter)
999 {
1000         uint32_t mode = hashfilter;
1001         int rc;
1002
1003         rc = doit(CHELSIO_T4_GET_FILTER_MODE, &mode);
1004         if (rc != 0)
1005                 return (rc);
1006
1007         if (mode & T4_FILTER_IPv4)
1008                 printf("ipv4 ");
1009
1010         if (mode & T4_FILTER_IPv6)
1011                 printf("ipv6 ");
1012
1013         if (mode & T4_FILTER_IP_SADDR)
1014                 printf("sip ");
1015
1016         if (mode & T4_FILTER_IP_DADDR)
1017                 printf("dip ");
1018
1019         if (mode & T4_FILTER_IP_SPORT)
1020                 printf("sport ");
1021
1022         if (mode & T4_FILTER_IP_DPORT)
1023                 printf("dport ");
1024
1025         if (mode & T4_FILTER_IP_FRAGMENT)
1026                 printf("frag ");
1027
1028         if (mode & T4_FILTER_MPS_HIT_TYPE)
1029                 printf("matchtype ");
1030
1031         if (mode & T4_FILTER_MAC_IDX)
1032                 printf("macidx ");
1033
1034         if (mode & T4_FILTER_ETH_TYPE)
1035                 printf("ethtype ");
1036
1037         if (mode & T4_FILTER_IP_PROTO)
1038                 printf("proto ");
1039
1040         if (mode & T4_FILTER_IP_TOS)
1041                 printf("tos ");
1042
1043         if (mode & T4_FILTER_VLAN)
1044                 printf("vlan ");
1045
1046         if (mode & T4_FILTER_VNIC) {
1047                 if (mode & T4_FILTER_IC_VNIC)
1048                         printf("vnic_id ");
1049                 else
1050                         printf("ovlan ");
1051         }
1052
1053         if (mode & T4_FILTER_PORT)
1054                 printf("iport ");
1055
1056         if (mode & T4_FILTER_FCoE)
1057                 printf("fcoe ");
1058
1059         printf("\n");
1060
1061         return (0);
1062 }
1063
1064 static int
1065 set_filter_mode(int argc, const char *argv[])
1066 {
1067         uint32_t mode = 0;
1068         int vnic = 0, ovlan = 0;
1069
1070         for (; argc; argc--, argv++) {
1071                 if (!strcmp(argv[0], "frag"))
1072                         mode |= T4_FILTER_IP_FRAGMENT;
1073
1074                 if (!strcmp(argv[0], "matchtype"))
1075                         mode |= T4_FILTER_MPS_HIT_TYPE;
1076
1077                 if (!strcmp(argv[0], "macidx"))
1078                         mode |= T4_FILTER_MAC_IDX;
1079
1080                 if (!strcmp(argv[0], "ethtype"))
1081                         mode |= T4_FILTER_ETH_TYPE;
1082
1083                 if (!strcmp(argv[0], "proto"))
1084                         mode |= T4_FILTER_IP_PROTO;
1085
1086                 if (!strcmp(argv[0], "tos"))
1087                         mode |= T4_FILTER_IP_TOS;
1088
1089                 if (!strcmp(argv[0], "vlan"))
1090                         mode |= T4_FILTER_VLAN;
1091
1092                 if (!strcmp(argv[0], "ovlan")) {
1093                         mode |= T4_FILTER_VNIC;
1094                         ovlan++;
1095                 }
1096
1097                 if (!strcmp(argv[0], "vnic_id")) {
1098                         mode |= T4_FILTER_VNIC;
1099                         mode |= T4_FILTER_IC_VNIC;
1100                         vnic++;
1101                 }
1102
1103                 if (!strcmp(argv[0], "iport"))
1104                         mode |= T4_FILTER_PORT;
1105
1106                 if (!strcmp(argv[0], "fcoe"))
1107                         mode |= T4_FILTER_FCoE;
1108         }
1109
1110         if (vnic > 0 && ovlan > 0) {
1111                 warnx("\"vnic_id\" and \"ovlan\" are mutually exclusive.");
1112                 return (EINVAL);
1113         }
1114
1115         return doit(CHELSIO_T4_SET_FILTER_MODE, &mode);
1116 }
1117
1118 static int
1119 del_filter(uint32_t idx, int prio, int hashfilter)
1120 {
1121         struct t4_filter t;
1122
1123         t.fs.prio = prio;
1124         t.fs.hash = hashfilter;
1125         t.idx = idx;
1126
1127         return doit(CHELSIO_T4_DEL_FILTER, &t);
1128 }
1129
1130 #define MAX_VLANID (4095)
1131
1132 static int
1133 set_filter(uint32_t idx, int argc, const char *argv[], int hash)
1134 {
1135         int rc, af = AF_UNSPEC, start_arg = 0;
1136         struct t4_filter t;
1137
1138         if (argc < 2) {
1139                 warnc(EINVAL, "%s", __func__);
1140                 return (EINVAL);
1141         };
1142         bzero(&t, sizeof (t));
1143         t.idx = idx;
1144         t.fs.hitcnts = 1;
1145         t.fs.hash = hash;
1146
1147         for (start_arg = 0; start_arg + 2 <= argc; start_arg += 2) {
1148                 const char **args = &argv[start_arg];
1149                 uint32_t val, mask;
1150
1151                 if (!strcmp(argv[start_arg], "type")) {
1152                         int newaf;
1153                         if (!strcasecmp(argv[start_arg + 1], "ipv4"))
1154                                 newaf = AF_INET;
1155                         else if (!strcasecmp(argv[start_arg + 1], "ipv6"))
1156                                 newaf = AF_INET6;
1157                         else {
1158                                 warnx("invalid type \"%s\"; "
1159                                     "must be one of \"ipv4\" or \"ipv6\"",
1160                                     argv[start_arg + 1]);
1161                                 return (EINVAL);
1162                         }
1163
1164                         if (af != AF_UNSPEC && af != newaf) {
1165                                 warnx("conflicting IPv4/IPv6 specifications.");
1166                                 return (EINVAL);
1167                         }
1168                         af = newaf;
1169                 } else if (!parse_val_mask("fcoe", args, &val, &mask, hash)) {
1170                         t.fs.val.fcoe = val;
1171                         t.fs.mask.fcoe = mask;
1172                 } else if (!parse_val_mask("iport", args, &val, &mask, hash)) {
1173                         t.fs.val.iport = val;
1174                         t.fs.mask.iport = mask;
1175                 } else if (!parse_val_mask("ovlan", args, &val, &mask, hash)) {
1176                         t.fs.val.vnic = val;
1177                         t.fs.mask.vnic = mask;
1178                         t.fs.val.ovlan_vld = 1;
1179                         t.fs.mask.ovlan_vld = 1;
1180                 } else if (!parse_val_mask("ivlan", args, &val, &mask, hash)) {
1181                         t.fs.val.vlan = val;
1182                         t.fs.mask.vlan = mask;
1183                         t.fs.val.vlan_vld = 1;
1184                         t.fs.mask.vlan_vld = 1;
1185                 } else if (!parse_val_mask("pf", args, &val, &mask, hash)) {
1186                         t.fs.val.vnic &= 0x1fff;
1187                         t.fs.val.vnic |= (val & 0x7) << 13;
1188                         t.fs.mask.vnic &= 0x1fff;
1189                         t.fs.mask.vnic |= (mask & 0x7) << 13;
1190                         t.fs.val.pfvf_vld = 1;
1191                         t.fs.mask.pfvf_vld = 1;
1192                 } else if (!parse_val_mask("vf", args, &val, &mask, hash)) {
1193                         t.fs.val.vnic &= 0xe000;
1194                         t.fs.val.vnic |= val & 0x1fff;
1195                         t.fs.mask.vnic &= 0xe000;
1196                         t.fs.mask.vnic |= mask & 0x1fff;
1197                         t.fs.val.pfvf_vld = 1;
1198                         t.fs.mask.pfvf_vld = 1;
1199                 } else if (!parse_val_mask("tos", args, &val, &mask, hash)) {
1200                         t.fs.val.tos = val;
1201                         t.fs.mask.tos = mask;
1202                 } else if (!parse_val_mask("proto", args, &val, &mask, hash)) {
1203                         t.fs.val.proto = val;
1204                         t.fs.mask.proto = mask;
1205                 } else if (!parse_val_mask("ethtype", args, &val, &mask, hash)) {
1206                         t.fs.val.ethtype = val;
1207                         t.fs.mask.ethtype = mask;
1208                 } else if (!parse_val_mask("macidx", args, &val, &mask, hash)) {
1209                         t.fs.val.macidx = val;
1210                         t.fs.mask.macidx = mask;
1211                 } else if (!parse_val_mask("matchtype", args, &val, &mask, hash)) {
1212                         t.fs.val.matchtype = val;
1213                         t.fs.mask.matchtype = mask;
1214                 } else if (!parse_val_mask("frag", args, &val, &mask, hash)) {
1215                         t.fs.val.frag = val;
1216                         t.fs.mask.frag = mask;
1217                 } else if (!parse_val_mask("dport", args, &val, &mask, hash)) {
1218                         t.fs.val.dport = val;
1219                         t.fs.mask.dport = mask;
1220                 } else if (!parse_val_mask("sport", args, &val, &mask, hash)) {
1221                         t.fs.val.sport = val;
1222                         t.fs.mask.sport = mask;
1223                 } else if (!parse_ipaddr("dip", args, &af, t.fs.val.dip,
1224                     t.fs.mask.dip, hash)) {
1225                         /* nada */;
1226                 } else if (!parse_ipaddr("sip", args, &af, t.fs.val.sip,
1227                     t.fs.mask.sip, hash)) {
1228                         /* nada */;
1229                 } else if (!parse_ipaddr("nat_dip", args, &af, t.fs.nat_dip, NULL, 1)) {
1230                         /*nada*/;
1231                 } else if (!parse_ipaddr("nat_sip", args, &af, t.fs.nat_sip, NULL, 1)) {
1232                         /*nada*/
1233                 } else if (!parse_val_mask("nat_dport", args, &val, &mask, 1)) {
1234                         t.fs.nat_dport = val;
1235                 } else if (!parse_val_mask("nat_sport", args, &val, &mask, 1)) {
1236                         t.fs.nat_sport = val;
1237                 } else if (!strcmp(argv[start_arg], "action")) {
1238                         if (!strcmp(argv[start_arg + 1], "pass"))
1239                                 t.fs.action = FILTER_PASS;
1240                         else if (!strcmp(argv[start_arg + 1], "drop"))
1241                                 t.fs.action = FILTER_DROP;
1242                         else if (!strcmp(argv[start_arg + 1], "switch"))
1243                                 t.fs.action = FILTER_SWITCH;
1244                         else {
1245                                 warnx("invalid action \"%s\"; must be one of"
1246                                      " \"pass\", \"drop\" or \"switch\"",
1247                                      argv[start_arg + 1]);
1248                                 return (EINVAL);
1249                         }
1250                 } else if (!parse_val("hitcnts", args, &val)) {
1251                         t.fs.hitcnts = val;
1252                 } else if (!parse_val("prio", args, &val)) {
1253                         if (hash) {
1254                                 warnx("Hashfilters doesn't support \"prio\"\n");
1255                                 return (EINVAL);
1256                         }
1257                         if (val != 0 && val != 1) {
1258                                 warnx("invalid priority \"%s\"; must be"
1259                                      " \"0\" or \"1\"", argv[start_arg + 1]);
1260                                 return (EINVAL);
1261                         }
1262                         t.fs.prio = val;
1263                 } else if (!parse_val("rpttid", args, &val)) {
1264                         t.fs.rpttid = 1;
1265                 } else if (!parse_val("queue", args, &val)) {
1266                         t.fs.dirsteer = 1;
1267                         t.fs.iq = val;
1268                 } else if (!parse_val("tcbhash", args, &val)) {
1269                         t.fs.maskhash = 1;
1270                         t.fs.dirsteerhash = 1;
1271                 } else if (!parse_val("eport", args, &val)) {
1272                         t.fs.eport = val;
1273                 } else if (!parse_val("swapmac", args, &val)) {
1274                         t.fs.swapmac = 1;
1275                 } else if (!strcmp(argv[start_arg], "nat")) {
1276                         if (!strcmp(argv[start_arg + 1], "dip"))
1277                                 t.fs.nat_mode = NAT_MODE_DIP;
1278                         else if (!strcmp(argv[start_arg + 1], "dip-dp"))
1279                                 t.fs.nat_mode = NAT_MODE_DIP_DP;
1280                         else if (!strcmp(argv[start_arg + 1], "dip-dp-sip"))
1281                                 t.fs.nat_mode = NAT_MODE_DIP_DP_SIP;
1282                         else if (!strcmp(argv[start_arg + 1], "dip-dp-sp"))
1283                                 t.fs.nat_mode = NAT_MODE_DIP_DP_SP;
1284                         else if (!strcmp(argv[start_arg + 1], "sip-sp"))
1285                                 t.fs.nat_mode = NAT_MODE_SIP_SP;
1286                         else if (!strcmp(argv[start_arg + 1], "dip-sip-sp"))
1287                                 t.fs.nat_mode = NAT_MODE_DIP_SIP_SP;
1288                         else if (!strcmp(argv[start_arg + 1], "all"))
1289                                 t.fs.nat_mode = NAT_MODE_ALL;
1290                         else {
1291                                 warnx("unknown nat type \"%s\"; known types are dip, "
1292                                       "dip-dp, dip-dp-sip, dip-dp-sp, sip-sp, "
1293                                       "dip-sip-sp, and all", argv[start_arg + 1]);
1294                                 return (EINVAL);
1295                         }
1296                 } else if (!parse_val("natseq", args, &val)) {
1297                         t.fs.nat_seq_chk = val;
1298                 } else if (!parse_val("natflag", args, &val)) {
1299                         t.fs.nat_flag_chk = 1;
1300                 } else if (!strcmp(argv[start_arg], "dmac")) {
1301                         struct ether_addr *daddr;
1302
1303                         daddr = ether_aton(argv[start_arg + 1]);
1304                         if (daddr == NULL) {
1305                                 warnx("invalid dmac address \"%s\"",
1306                                     argv[start_arg + 1]);
1307                                 return (EINVAL);
1308                         }
1309                         memcpy(t.fs.dmac, daddr, ETHER_ADDR_LEN);
1310                         t.fs.newdmac = 1;
1311                 } else if (!strcmp(argv[start_arg], "smac")) {
1312                         struct ether_addr *saddr;
1313
1314                         saddr = ether_aton(argv[start_arg + 1]);
1315                         if (saddr == NULL) {
1316                                 warnx("invalid smac address \"%s\"",
1317                                     argv[start_arg + 1]);
1318                                 return (EINVAL);
1319                         }
1320                         memcpy(t.fs.smac, saddr, ETHER_ADDR_LEN);
1321                         t.fs.newsmac = 1;
1322                 } else if (!strcmp(argv[start_arg], "vlan")) {
1323                         char *p;
1324                         if (!strcmp(argv[start_arg + 1], "none")) {
1325                                 t.fs.newvlan = VLAN_REMOVE;
1326                         } else if (argv[start_arg + 1][0] == '=') {
1327                                 t.fs.newvlan = VLAN_REWRITE;
1328                         } else if (argv[start_arg + 1][0] == '+') {
1329                                 t.fs.newvlan = VLAN_INSERT;
1330                         } else if (isdigit(argv[start_arg + 1][0]) &&
1331                             !parse_val_mask("vlan", args, &val, &mask, hash)) {
1332                                 t.fs.val.vlan = val;
1333                                 t.fs.mask.vlan = mask;
1334                                 t.fs.val.vlan_vld = 1;
1335                                 t.fs.mask.vlan_vld = 1;
1336                         } else {
1337                                 warnx("unknown vlan parameter \"%s\"; must"
1338                                      " be one of \"none\", \"=<vlan>\", "
1339                                      " \"+<vlan>\", or \"<vlan>\"",
1340                                      argv[start_arg + 1]);
1341                                 return (EINVAL);
1342                         }
1343                         if (t.fs.newvlan == VLAN_REWRITE ||
1344                             t.fs.newvlan == VLAN_INSERT) {
1345                                 t.fs.vlan = strtoul(argv[start_arg + 1] + 1,
1346                                     &p, 0);
1347                                 if (p == argv[start_arg + 1] + 1 || p[0] != 0 ||
1348                                     t.fs.vlan > MAX_VLANID) {
1349                                         warnx("invalid vlan \"%s\"",
1350                                              argv[start_arg + 1]);
1351                                         return (EINVAL);
1352                                 }
1353                         }
1354                 } else {
1355                         warnx("invalid parameter \"%s\"", argv[start_arg]);
1356                         return (EINVAL);
1357                 }
1358         }
1359         if (start_arg != argc) {
1360                 warnx("no value for \"%s\"", argv[start_arg]);
1361                 return (EINVAL);
1362         }
1363
1364         /*
1365          * Check basic sanity of option combinations.
1366          */
1367         if (t.fs.action != FILTER_SWITCH &&
1368             (t.fs.eport || t.fs.newdmac || t.fs.newsmac || t.fs.newvlan ||
1369             t.fs.swapmac || t.fs.nat_mode)) {
1370                 warnx("port, dmac, smac, vlan, and nat only make sense with"
1371                      " \"action switch\"");
1372                 return (EINVAL);
1373         }
1374         if (!t.fs.nat_mode && (t.fs.nat_seq_chk || t.fs.nat_flag_chk ||
1375             *t.fs.nat_dip || *t.fs.nat_sip || t.fs.nat_dport || t.fs.nat_sport)) {
1376                 warnx("nat params only make sense with valid nat mode");
1377                 return (EINVAL);
1378         }
1379         if (t.fs.action != FILTER_PASS &&
1380             (t.fs.rpttid || t.fs.dirsteer || t.fs.maskhash)) {
1381                 warnx("rpttid, queue and tcbhash don't make sense with"
1382                      " action \"drop\" or \"switch\"");
1383                 return (EINVAL);
1384         }
1385         if (t.fs.val.ovlan_vld && t.fs.val.pfvf_vld) {
1386                 warnx("ovlan and vnic_id (pf/vf) are mutually exclusive");
1387                 return (EINVAL);
1388         }
1389
1390         t.fs.type = (af == AF_INET6 ? 1 : 0); /* default IPv4 */
1391         rc = doit(CHELSIO_T4_SET_FILTER, &t);
1392         if (hash && rc == 0)
1393                 printf("%d\n", t.idx);
1394         return (rc);
1395 }
1396
1397 static int
1398 filter_cmd(int argc, const char *argv[], int hashfilter)
1399 {
1400         long long val;
1401         uint32_t idx;
1402         char *s;
1403
1404         if (argc == 0) {
1405                 warnx("%sfilter: no arguments.", hashfilter ? "hash" : "");
1406                 return (EINVAL);
1407         };
1408
1409         /* list */
1410         if (strcmp(argv[0], "list") == 0) {
1411                 if (argc != 1)
1412                         warnx("trailing arguments after \"list\" ignored.");
1413
1414                 return show_filters(hashfilter);
1415         }
1416
1417         /* mode */
1418         if (argc == 1 && strcmp(argv[0], "mode") == 0)
1419                 return get_filter_mode(hashfilter);
1420
1421         /* mode <mode> */
1422         if (!hashfilter && strcmp(argv[0], "mode") == 0)
1423                 return set_filter_mode(argc - 1, argv + 1);
1424
1425         /* <idx> ... */
1426         s = str_to_number(argv[0], NULL, &val);
1427         if (*s || val < 0 || val > 0xffffffffU) {
1428                 if (hashfilter) {
1429                         /*
1430                          * No numeric index means this must be a request to
1431                          * create a new hashfilter and we are already at the
1432                          * paramter/value list.
1433                          */
1434                         idx = (uint32_t) -1;
1435                         goto setf;
1436                 }
1437                 warnx("\"%s\" is neither an index nor a filter subcommand.",
1438                     argv[0]);
1439                 return (EINVAL);
1440         }
1441         idx = (uint32_t) val;
1442
1443         /* <idx> delete|clear [prio 0|1] */
1444         if ((argc == 2 || argc == 4) &&
1445             (strcmp(argv[1], "delete") == 0 || strcmp(argv[1], "clear") == 0)) {
1446                 int prio = 0;
1447
1448                 if (argc == 4) {
1449                         if (hashfilter) {
1450                                 warnx("stray arguments after \"%s\".", argv[1]);
1451                                 return (EINVAL);
1452                         }
1453
1454                         if (strcmp(argv[2], "prio") != 0) {
1455                                 warnx("\"prio\" is the only valid keyword "
1456                                     "after \"%s\", found \"%s\" instead.",
1457                                     argv[1], argv[2]);
1458                                 return (EINVAL);
1459                         }
1460
1461                         s = str_to_number(argv[3], NULL, &val);
1462                         if (*s || val < 0 || val > 1) {
1463                                 warnx("%s \"%s\"; must be \"0\" or \"1\".",
1464                                     argv[2], argv[3]);
1465                                 return (EINVAL);
1466                         }
1467                         prio = (int)val;
1468                 }
1469                 return del_filter(idx, prio, hashfilter);
1470         }
1471
1472         /* skip <idx> */
1473         argc--;
1474         argv++;
1475
1476 setf:
1477         /* [<param> <val>] ... */
1478         return set_filter(idx, argc, argv, hashfilter);
1479 }
1480
1481 /*
1482  * Shows the fields of a multi-word structure.  The structure is considered to
1483  * consist of @nwords 32-bit words (i.e, it's an (@nwords * 32)-bit structure)
1484  * whose fields are described by @fd.  The 32-bit words are given in @words
1485  * starting with the least significant 32-bit word.
1486  */
1487 static void
1488 show_struct(const uint32_t *words, int nwords, const struct field_desc *fd)
1489 {
1490         unsigned int w = 0;
1491         const struct field_desc *p;
1492
1493         for (p = fd; p->name; p++)
1494                 w = max(w, strlen(p->name));
1495
1496         while (fd->name) {
1497                 unsigned long long data;
1498                 int first_word = fd->start / 32;
1499                 int shift = fd->start % 32;
1500                 int width = fd->end - fd->start + 1;
1501                 unsigned long long mask = (1ULL << width) - 1;
1502
1503                 data = (words[first_word] >> shift) |
1504                        ((uint64_t)words[first_word + 1] << (32 - shift));
1505                 if (shift)
1506                        data |= ((uint64_t)words[first_word + 2] << (64 - shift));
1507                 data &= mask;
1508                 if (fd->islog2)
1509                         data = 1 << data;
1510                 printf("%-*s ", w, fd->name);
1511                 printf(fd->hex ? "%#llx\n" : "%llu\n", data << fd->shift);
1512                 fd++;
1513         }
1514 }
1515
1516 #define FIELD(name, start, end) { name, start, end, 0, 0, 0 }
1517 #define FIELD1(name, start) FIELD(name, start, start)
1518
1519 static void
1520 show_t5t6_ctxt(const struct t4_sge_context *p, int vers)
1521 {
1522         static struct field_desc egress_t5[] = {
1523                 FIELD("DCA_ST:", 181, 191),
1524                 FIELD1("StatusPgNS:", 180),
1525                 FIELD1("StatusPgRO:", 179),
1526                 FIELD1("FetchNS:", 178),
1527                 FIELD1("FetchRO:", 177),
1528                 FIELD1("Valid:", 176),
1529                 FIELD("PCIeDataChannel:", 174, 175),
1530                 FIELD1("StatusPgTPHintEn:", 173),
1531                 FIELD("StatusPgTPHint:", 171, 172),
1532                 FIELD1("FetchTPHintEn:", 170),
1533                 FIELD("FetchTPHint:", 168, 169),
1534                 FIELD1("FCThreshOverride:", 167),
1535                 { "WRLength:", 162, 166, 9, 0, 1 },
1536                 FIELD1("WRLengthKnown:", 161),
1537                 FIELD1("ReschedulePending:", 160),
1538                 FIELD1("OnChipQueue:", 159),
1539                 FIELD1("FetchSizeMode:", 158),
1540                 { "FetchBurstMin:", 156, 157, 4, 0, 1 },
1541                 FIELD1("FLMPacking:", 155),
1542                 FIELD("FetchBurstMax:", 153, 154),
1543                 FIELD("uPToken:", 133, 152),
1544                 FIELD1("uPTokenEn:", 132),
1545                 FIELD1("UserModeIO:", 131),
1546                 FIELD("uPFLCredits:", 123, 130),
1547                 FIELD1("uPFLCreditEn:", 122),
1548                 FIELD("FID:", 111, 121),
1549                 FIELD("HostFCMode:", 109, 110),
1550                 FIELD1("HostFCOwner:", 108),
1551                 { "CIDXFlushThresh:", 105, 107, 0, 0, 1 },
1552                 FIELD("CIDX:", 89, 104),
1553                 FIELD("PIDX:", 73, 88),
1554                 { "BaseAddress:", 18, 72, 9, 1 },
1555                 FIELD("QueueSize:", 2, 17),
1556                 FIELD1("QueueType:", 1),
1557                 FIELD1("CachePriority:", 0),
1558                 { NULL }
1559         };
1560         static struct field_desc egress_t6[] = {
1561                 FIELD("DCA_ST:", 181, 191),
1562                 FIELD1("StatusPgNS:", 180),
1563                 FIELD1("StatusPgRO:", 179),
1564                 FIELD1("FetchNS:", 178),
1565                 FIELD1("FetchRO:", 177),
1566                 FIELD1("Valid:", 176),
1567                 FIELD1("ReschedulePending_1:", 175),
1568                 FIELD1("PCIeDataChannel:", 174),
1569                 FIELD1("StatusPgTPHintEn:", 173),
1570                 FIELD("StatusPgTPHint:", 171, 172),
1571                 FIELD1("FetchTPHintEn:", 170),
1572                 FIELD("FetchTPHint:", 168, 169),
1573                 FIELD1("FCThreshOverride:", 167),
1574                 { "WRLength:", 162, 166, 9, 0, 1 },
1575                 FIELD1("WRLengthKnown:", 161),
1576                 FIELD1("ReschedulePending:", 160),
1577                 FIELD("TimerIx:", 157, 159),
1578                 FIELD1("FetchBurstMin:", 156),
1579                 FIELD1("FLMPacking:", 155),
1580                 FIELD("FetchBurstMax:", 153, 154),
1581                 FIELD("uPToken:", 133, 152),
1582                 FIELD1("uPTokenEn:", 132),
1583                 FIELD1("UserModeIO:", 131),
1584                 FIELD("uPFLCredits:", 123, 130),
1585                 FIELD1("uPFLCreditEn:", 122),
1586                 FIELD("FID:", 111, 121),
1587                 FIELD("HostFCMode:", 109, 110),
1588                 FIELD1("HostFCOwner:", 108),
1589                 { "CIDXFlushThresh:", 105, 107, 0, 0, 1 },
1590                 FIELD("CIDX:", 89, 104),
1591                 FIELD("PIDX:", 73, 88),
1592                 { "BaseAddress:", 18, 72, 9, 1 },
1593                 FIELD("QueueSize:", 2, 17),
1594                 FIELD1("QueueType:", 1),
1595                 FIELD1("FetchSizeMode:", 0),
1596                 { NULL }
1597         };
1598         static struct field_desc fl_t5[] = {
1599                 FIELD("DCA_ST:", 181, 191),
1600                 FIELD1("StatusPgNS:", 180),
1601                 FIELD1("StatusPgRO:", 179),
1602                 FIELD1("FetchNS:", 178),
1603                 FIELD1("FetchRO:", 177),
1604                 FIELD1("Valid:", 176),
1605                 FIELD("PCIeDataChannel:", 174, 175),
1606                 FIELD1("StatusPgTPHintEn:", 173),
1607                 FIELD("StatusPgTPHint:", 171, 172),
1608                 FIELD1("FetchTPHintEn:", 170),
1609                 FIELD("FetchTPHint:", 168, 169),
1610                 FIELD1("FCThreshOverride:", 167),
1611                 FIELD1("ReschedulePending:", 160),
1612                 FIELD1("OnChipQueue:", 159),
1613                 FIELD1("FetchSizeMode:", 158),
1614                 { "FetchBurstMin:", 156, 157, 4, 0, 1 },
1615                 FIELD1("FLMPacking:", 155),
1616                 FIELD("FetchBurstMax:", 153, 154),
1617                 FIELD1("FLMcongMode:", 152),
1618                 FIELD("MaxuPFLCredits:", 144, 151),
1619                 FIELD("FLMcontextID:", 133, 143),
1620                 FIELD1("uPTokenEn:", 132),
1621                 FIELD1("UserModeIO:", 131),
1622                 FIELD("uPFLCredits:", 123, 130),
1623                 FIELD1("uPFLCreditEn:", 122),
1624                 FIELD("FID:", 111, 121),
1625                 FIELD("HostFCMode:", 109, 110),
1626                 FIELD1("HostFCOwner:", 108),
1627                 { "CIDXFlushThresh:", 105, 107, 0, 0, 1 },
1628                 FIELD("CIDX:", 89, 104),
1629                 FIELD("PIDX:", 73, 88),
1630                 { "BaseAddress:", 18, 72, 9, 1 },
1631                 FIELD("QueueSize:", 2, 17),
1632                 FIELD1("QueueType:", 1),
1633                 FIELD1("CachePriority:", 0),
1634                 { NULL }
1635         };
1636         static struct field_desc ingress_t5[] = {
1637                 FIELD("DCA_ST:", 143, 153),
1638                 FIELD1("ISCSICoalescing:", 142),
1639                 FIELD1("Queue_Valid:", 141),
1640                 FIELD1("TimerPending:", 140),
1641                 FIELD1("DropRSS:", 139),
1642                 FIELD("PCIeChannel:", 137, 138),
1643                 FIELD1("SEInterruptArmed:", 136),
1644                 FIELD1("CongestionMgtEnable:", 135),
1645                 FIELD1("NoSnoop:", 134),
1646                 FIELD1("RelaxedOrdering:", 133),
1647                 FIELD1("GTSmode:", 132),
1648                 FIELD1("TPHintEn:", 131),
1649                 FIELD("TPHint:", 129, 130),
1650                 FIELD1("UpdateScheduling:", 128),
1651                 FIELD("UpdateDelivery:", 126, 127),
1652                 FIELD1("InterruptSent:", 125),
1653                 FIELD("InterruptIDX:", 114, 124),
1654                 FIELD1("InterruptDestination:", 113),
1655                 FIELD1("InterruptArmed:", 112),
1656                 FIELD("RxIntCounter:", 106, 111),
1657                 FIELD("RxIntCounterThreshold:", 104, 105),
1658                 FIELD1("Generation:", 103),
1659                 { "BaseAddress:", 48, 102, 9, 1 },
1660                 FIELD("PIDX:", 32, 47),
1661                 FIELD("CIDX:", 16, 31),
1662                 { "QueueSize:", 4, 15, 4, 0 },
1663                 { "QueueEntrySize:", 2, 3, 4, 0, 1 },
1664                 FIELD1("QueueEntryOverride:", 1),
1665                 FIELD1("CachePriority:", 0),
1666                 { NULL }
1667         };
1668         static struct field_desc ingress_t6[] = {
1669                 FIELD1("SP_NS:", 158),
1670                 FIELD1("SP_RO:", 157),
1671                 FIELD1("SP_TPHintEn:", 156),
1672                 FIELD("SP_TPHint:", 154, 155),
1673                 FIELD("DCA_ST:", 143, 153),
1674                 FIELD1("ISCSICoalescing:", 142),
1675                 FIELD1("Queue_Valid:", 141),
1676                 FIELD1("TimerPending:", 140),
1677                 FIELD1("DropRSS:", 139),
1678                 FIELD("PCIeChannel:", 137, 138),
1679                 FIELD1("SEInterruptArmed:", 136),
1680                 FIELD1("CongestionMgtEnable:", 135),
1681                 FIELD1("NoSnoop:", 134),
1682                 FIELD1("RelaxedOrdering:", 133),
1683                 FIELD1("GTSmode:", 132),
1684                 FIELD1("TPHintEn:", 131),
1685                 FIELD("TPHint:", 129, 130),
1686                 FIELD1("UpdateScheduling:", 128),
1687                 FIELD("UpdateDelivery:", 126, 127),
1688                 FIELD1("InterruptSent:", 125),
1689                 FIELD("InterruptIDX:", 114, 124),
1690                 FIELD1("InterruptDestination:", 113),
1691                 FIELD1("InterruptArmed:", 112),
1692                 FIELD("RxIntCounter:", 106, 111),
1693                 FIELD("RxIntCounterThreshold:", 104, 105),
1694                 FIELD1("Generation:", 103),
1695                 { "BaseAddress:", 48, 102, 9, 1 },
1696                 FIELD("PIDX:", 32, 47),
1697                 FIELD("CIDX:", 16, 31),
1698                 { "QueueSize:", 4, 15, 4, 0 },
1699                 { "QueueEntrySize:", 2, 3, 4, 0, 1 },
1700                 FIELD1("QueueEntryOverride:", 1),
1701                 FIELD1("CachePriority:", 0),
1702                 { NULL }
1703         };
1704         static struct field_desc flm_t5[] = {
1705                 FIELD1("Valid:", 89),
1706                 FIELD("SplitLenMode:", 87, 88),
1707                 FIELD1("TPHintEn:", 86),
1708                 FIELD("TPHint:", 84, 85),
1709                 FIELD1("NoSnoop:", 83),
1710                 FIELD1("RelaxedOrdering:", 82),
1711                 FIELD("DCA_ST:", 71, 81),
1712                 FIELD("EQid:", 54, 70),
1713                 FIELD("SplitEn:", 52, 53),
1714                 FIELD1("PadEn:", 51),
1715                 FIELD1("PackEn:", 50),
1716                 FIELD1("Cache_Lock :", 49),
1717                 FIELD1("CongDrop:", 48),
1718                 FIELD("PackOffset:", 16, 47),
1719                 FIELD("CIDX:", 8, 15),
1720                 FIELD("PIDX:", 0, 7),
1721                 { NULL }
1722         };
1723         static struct field_desc flm_t6[] = {
1724                 FIELD1("Valid:", 89),
1725                 FIELD("SplitLenMode:", 87, 88),
1726                 FIELD1("TPHintEn:", 86),
1727                 FIELD("TPHint:", 84, 85),
1728                 FIELD1("NoSnoop:", 83),
1729                 FIELD1("RelaxedOrdering:", 82),
1730                 FIELD("DCA_ST:", 71, 81),
1731                 FIELD("EQid:", 54, 70),
1732                 FIELD("SplitEn:", 52, 53),
1733                 FIELD1("PadEn:", 51),
1734                 FIELD1("PackEn:", 50),
1735                 FIELD1("Cache_Lock :", 49),
1736                 FIELD1("CongDrop:", 48),
1737                 FIELD1("Inflight:", 47),
1738                 FIELD1("CongEn:", 46),
1739                 FIELD1("CongMode:", 45),
1740                 FIELD("PackOffset:", 20, 39),
1741                 FIELD("CIDX:", 8, 15),
1742                 FIELD("PIDX:", 0, 7),
1743                 { NULL }
1744         };
1745         static struct field_desc conm_t5[] = {
1746                 FIELD1("CngMPSEnable:", 21),
1747                 FIELD("CngTPMode:", 19, 20),
1748                 FIELD1("CngDBPHdr:", 18),
1749                 FIELD1("CngDBPData:", 17),
1750                 FIELD1("CngIMSG:", 16),
1751                 { "CngChMap:", 0, 15, 0, 1, 0 },
1752                 { NULL }
1753         };
1754
1755         if (p->mem_id == SGE_CONTEXT_EGRESS) {
1756                 if (p->data[0] & 2)
1757                         show_struct(p->data, 6, fl_t5);
1758                 else if (vers == 5)
1759                         show_struct(p->data, 6, egress_t5);
1760                 else
1761                         show_struct(p->data, 6, egress_t6);
1762         } else if (p->mem_id == SGE_CONTEXT_FLM)
1763                 show_struct(p->data, 3, vers == 5 ? flm_t5 : flm_t6);
1764         else if (p->mem_id == SGE_CONTEXT_INGRESS)
1765                 show_struct(p->data, 5, vers == 5 ? ingress_t5 : ingress_t6);
1766         else if (p->mem_id == SGE_CONTEXT_CNM)
1767                 show_struct(p->data, 1, conm_t5);
1768 }
1769
1770 static void
1771 show_t4_ctxt(const struct t4_sge_context *p)
1772 {
1773         static struct field_desc egress_t4[] = {
1774                 FIELD1("StatusPgNS:", 180),
1775                 FIELD1("StatusPgRO:", 179),
1776                 FIELD1("FetchNS:", 178),
1777                 FIELD1("FetchRO:", 177),
1778                 FIELD1("Valid:", 176),
1779                 FIELD("PCIeDataChannel:", 174, 175),
1780                 FIELD1("DCAEgrQEn:", 173),
1781                 FIELD("DCACPUID:", 168, 172),
1782                 FIELD1("FCThreshOverride:", 167),
1783                 FIELD("WRLength:", 162, 166),
1784                 FIELD1("WRLengthKnown:", 161),
1785                 FIELD1("ReschedulePending:", 160),
1786                 FIELD1("OnChipQueue:", 159),
1787                 FIELD1("FetchSizeMode", 158),
1788                 { "FetchBurstMin:", 156, 157, 4, 0, 1 },
1789                 { "FetchBurstMax:", 153, 154, 6, 0, 1 },
1790                 FIELD("uPToken:", 133, 152),
1791                 FIELD1("uPTokenEn:", 132),
1792                 FIELD1("UserModeIO:", 131),
1793                 FIELD("uPFLCredits:", 123, 130),
1794                 FIELD1("uPFLCreditEn:", 122),
1795                 FIELD("FID:", 111, 121),
1796                 FIELD("HostFCMode:", 109, 110),
1797                 FIELD1("HostFCOwner:", 108),
1798                 { "CIDXFlushThresh:", 105, 107, 0, 0, 1 },
1799                 FIELD("CIDX:", 89, 104),
1800                 FIELD("PIDX:", 73, 88),
1801                 { "BaseAddress:", 18, 72, 9, 1 },
1802                 FIELD("QueueSize:", 2, 17),
1803                 FIELD1("QueueType:", 1),
1804                 FIELD1("CachePriority:", 0),
1805                 { NULL }
1806         };
1807         static struct field_desc fl_t4[] = {
1808                 FIELD1("StatusPgNS:", 180),
1809                 FIELD1("StatusPgRO:", 179),
1810                 FIELD1("FetchNS:", 178),
1811                 FIELD1("FetchRO:", 177),
1812                 FIELD1("Valid:", 176),
1813                 FIELD("PCIeDataChannel:", 174, 175),
1814                 FIELD1("DCAEgrQEn:", 173),
1815                 FIELD("DCACPUID:", 168, 172),
1816                 FIELD1("FCThreshOverride:", 167),
1817                 FIELD1("ReschedulePending:", 160),
1818                 FIELD1("OnChipQueue:", 159),
1819                 FIELD1("FetchSizeMode", 158),
1820                 { "FetchBurstMin:", 156, 157, 4, 0, 1 },
1821                 { "FetchBurstMax:", 153, 154, 6, 0, 1 },
1822                 FIELD1("FLMcongMode:", 152),
1823                 FIELD("MaxuPFLCredits:", 144, 151),
1824                 FIELD("FLMcontextID:", 133, 143),
1825                 FIELD1("uPTokenEn:", 132),
1826                 FIELD1("UserModeIO:", 131),
1827                 FIELD("uPFLCredits:", 123, 130),
1828                 FIELD1("uPFLCreditEn:", 122),
1829                 FIELD("FID:", 111, 121),
1830                 FIELD("HostFCMode:", 109, 110),
1831                 FIELD1("HostFCOwner:", 108),
1832                 { "CIDXFlushThresh:", 105, 107, 0, 0, 1 },
1833                 FIELD("CIDX:", 89, 104),
1834                 FIELD("PIDX:", 73, 88),
1835                 { "BaseAddress:", 18, 72, 9, 1 },
1836                 FIELD("QueueSize:", 2, 17),
1837                 FIELD1("QueueType:", 1),
1838                 FIELD1("CachePriority:", 0),
1839                 { NULL }
1840         };
1841         static struct field_desc ingress_t4[] = {
1842                 FIELD1("NoSnoop:", 145),
1843                 FIELD1("RelaxedOrdering:", 144),
1844                 FIELD1("GTSmode:", 143),
1845                 FIELD1("ISCSICoalescing:", 142),
1846                 FIELD1("Valid:", 141),
1847                 FIELD1("TimerPending:", 140),
1848                 FIELD1("DropRSS:", 139),
1849                 FIELD("PCIeChannel:", 137, 138),
1850                 FIELD1("SEInterruptArmed:", 136),
1851                 FIELD1("CongestionMgtEnable:", 135),
1852                 FIELD1("DCAIngQEnable:", 134),
1853                 FIELD("DCACPUID:", 129, 133),
1854                 FIELD1("UpdateScheduling:", 128),
1855                 FIELD("UpdateDelivery:", 126, 127),
1856                 FIELD1("InterruptSent:", 125),
1857                 FIELD("InterruptIDX:", 114, 124),
1858                 FIELD1("InterruptDestination:", 113),
1859                 FIELD1("InterruptArmed:", 112),
1860                 FIELD("RxIntCounter:", 106, 111),
1861                 FIELD("RxIntCounterThreshold:", 104, 105),
1862                 FIELD1("Generation:", 103),
1863                 { "BaseAddress:", 48, 102, 9, 1 },
1864                 FIELD("PIDX:", 32, 47),
1865                 FIELD("CIDX:", 16, 31),
1866                 { "QueueSize:", 4, 15, 4, 0 },
1867                 { "QueueEntrySize:", 2, 3, 4, 0, 1 },
1868                 FIELD1("QueueEntryOverride:", 1),
1869                 FIELD1("CachePriority:", 0),
1870                 { NULL }
1871         };
1872         static struct field_desc flm_t4[] = {
1873                 FIELD1("NoSnoop:", 79),
1874                 FIELD1("RelaxedOrdering:", 78),
1875                 FIELD1("Valid:", 77),
1876                 FIELD("DCACPUID:", 72, 76),
1877                 FIELD1("DCAFLEn:", 71),
1878                 FIELD("EQid:", 54, 70),
1879                 FIELD("SplitEn:", 52, 53),
1880                 FIELD1("PadEn:", 51),
1881                 FIELD1("PackEn:", 50),
1882                 FIELD1("DBpriority:", 48),
1883                 FIELD("PackOffset:", 16, 47),
1884                 FIELD("CIDX:", 8, 15),
1885                 FIELD("PIDX:", 0, 7),
1886                 { NULL }
1887         };
1888         static struct field_desc conm_t4[] = {
1889                 FIELD1("CngDBPHdr:", 6),
1890                 FIELD1("CngDBPData:", 5),
1891                 FIELD1("CngIMSG:", 4),
1892                 { "CngChMap:", 0, 3, 0, 1, 0},
1893                 { NULL }
1894         };
1895
1896         if (p->mem_id == SGE_CONTEXT_EGRESS)
1897                 show_struct(p->data, 6, (p->data[0] & 2) ? fl_t4 : egress_t4);
1898         else if (p->mem_id == SGE_CONTEXT_FLM)
1899                 show_struct(p->data, 3, flm_t4);
1900         else if (p->mem_id == SGE_CONTEXT_INGRESS)
1901                 show_struct(p->data, 5, ingress_t4);
1902         else if (p->mem_id == SGE_CONTEXT_CNM)
1903                 show_struct(p->data, 1, conm_t4);
1904 }
1905
1906 #undef FIELD
1907 #undef FIELD1
1908
1909 static int
1910 get_sge_context(int argc, const char *argv[])
1911 {
1912         int rc;
1913         char *p;
1914         long cid;
1915         struct t4_sge_context cntxt = {0};
1916
1917         if (argc != 2) {
1918                 warnx("sge_context: incorrect number of arguments.");
1919                 return (EINVAL);
1920         }
1921
1922         if (!strcmp(argv[0], "egress"))
1923                 cntxt.mem_id = SGE_CONTEXT_EGRESS;
1924         else if (!strcmp(argv[0], "ingress"))
1925                 cntxt.mem_id = SGE_CONTEXT_INGRESS;
1926         else if (!strcmp(argv[0], "fl"))
1927                 cntxt.mem_id = SGE_CONTEXT_FLM;
1928         else if (!strcmp(argv[0], "cong"))
1929                 cntxt.mem_id = SGE_CONTEXT_CNM;
1930         else {
1931                 warnx("unknown context type \"%s\"; known types are egress, "
1932                     "ingress, fl, and cong.", argv[0]);
1933                 return (EINVAL);
1934         }
1935
1936         p = str_to_number(argv[1], &cid, NULL);
1937         if (*p) {
1938                 warnx("invalid context id \"%s\"", argv[1]);
1939                 return (EINVAL);
1940         }
1941         cntxt.cid = cid;
1942
1943         rc = doit(CHELSIO_T4_GET_SGE_CONTEXT, &cntxt);
1944         if (rc != 0)
1945                 return (rc);
1946
1947         if (chip_id == 4)
1948                 show_t4_ctxt(&cntxt);
1949         else
1950                 show_t5t6_ctxt(&cntxt, chip_id);
1951
1952         return (0);
1953 }
1954
1955 static int
1956 loadfw(int argc, const char *argv[])
1957 {
1958         int rc, fd;
1959         struct t4_data data = {0};
1960         const char *fname = argv[0];
1961         struct stat st = {0};
1962
1963         if (argc != 1) {
1964                 warnx("loadfw: incorrect number of arguments.");
1965                 return (EINVAL);
1966         }
1967
1968         fd = open(fname, O_RDONLY);
1969         if (fd < 0) {
1970                 warn("open(%s)", fname);
1971                 return (errno);
1972         }
1973
1974         if (fstat(fd, &st) < 0) {
1975                 warn("fstat");
1976                 close(fd);
1977                 return (errno);
1978         }
1979
1980         data.len = st.st_size;
1981         data.data = mmap(0, data.len, PROT_READ, MAP_PRIVATE, fd, 0);
1982         if (data.data == MAP_FAILED) {
1983                 warn("mmap");
1984                 close(fd);
1985                 return (errno);
1986         }
1987
1988         rc = doit(CHELSIO_T4_LOAD_FW, &data);
1989         munmap(data.data, data.len);
1990         close(fd);
1991         return (rc);
1992 }
1993
1994 static int
1995 loadcfg(int argc, const char *argv[])
1996 {
1997         int rc, fd;
1998         struct t4_data data = {0};
1999         const char *fname = argv[0];
2000         struct stat st = {0};
2001
2002         if (argc != 1) {
2003                 warnx("loadcfg: incorrect number of arguments.");
2004                 return (EINVAL);
2005         }
2006
2007         if (strcmp(fname, "clear") == 0)
2008                 return (doit(CHELSIO_T4_LOAD_CFG, &data));
2009
2010         fd = open(fname, O_RDONLY);
2011         if (fd < 0) {
2012                 warn("open(%s)", fname);
2013                 return (errno);
2014         }
2015
2016         if (fstat(fd, &st) < 0) {
2017                 warn("fstat");
2018                 close(fd);
2019                 return (errno);
2020         }
2021
2022         data.len = st.st_size;
2023         data.len &= ~3;         /* Clip off to make it a multiple of 4 */
2024         data.data = mmap(0, data.len, PROT_READ, MAP_PRIVATE, fd, 0);
2025         if (data.data == MAP_FAILED) {
2026                 warn("mmap");
2027                 close(fd);
2028                 return (errno);
2029         }
2030
2031         rc = doit(CHELSIO_T4_LOAD_CFG, &data);
2032         munmap(data.data, data.len);
2033         close(fd);
2034         return (rc);
2035 }
2036
2037 static int
2038 dumpstate(int argc, const char *argv[])
2039 {
2040         int rc, fd;
2041         struct t4_cudbg_dump dump = {0};
2042         const char *fname = argv[0];
2043
2044         if (argc != 1) {
2045                 warnx("dumpstate: incorrect number of arguments.");
2046                 return (EINVAL);
2047         }
2048
2049         dump.wr_flash = 0;
2050         memset(&dump.bitmap, 0xff, sizeof(dump.bitmap));
2051         dump.len = 8 * 1024 * 1024;
2052         dump.data = malloc(dump.len);
2053         if (dump.data == NULL) {
2054                 return (ENOMEM);
2055         }
2056
2057         rc = doit(CHELSIO_T4_CUDBG_DUMP, &dump);
2058         if (rc != 0)
2059                 goto done;
2060
2061         fd = open(fname, O_CREAT | O_TRUNC | O_EXCL | O_WRONLY,
2062             S_IRUSR | S_IRGRP | S_IROTH);
2063         if (fd < 0) {
2064                 warn("open(%s)", fname);
2065                 rc = errno;
2066                 goto done;
2067         }
2068         write(fd, dump.data, dump.len);
2069         close(fd);
2070 done:
2071         free(dump.data);
2072         return (rc);
2073 }
2074
2075 static int
2076 read_mem(uint32_t addr, uint32_t len, void (*output)(uint32_t *, uint32_t))
2077 {
2078         int rc;
2079         struct t4_mem_range mr;
2080
2081         mr.addr = addr;
2082         mr.len = len;
2083         mr.data = malloc(mr.len);
2084
2085         if (mr.data == 0) {
2086                 warn("read_mem: malloc");
2087                 return (errno);
2088         }
2089
2090         rc = doit(CHELSIO_T4_GET_MEM, &mr);
2091         if (rc != 0)
2092                 goto done;
2093
2094         if (output)
2095                 (*output)(mr.data, mr.len);
2096 done:
2097         free(mr.data);
2098         return (rc);
2099 }
2100
2101 static int
2102 loadboot(int argc, const char *argv[])
2103 {
2104         int rc, fd;
2105         long l;
2106         char *p;
2107         struct t4_bootrom br = {0};
2108         const char *fname = argv[0];
2109         struct stat st = {0};
2110
2111         if (argc == 1) {
2112                 br.pf_offset = 0;
2113                 br.pfidx_addr = 0;
2114         } else if (argc == 3) {
2115                 if (!strcmp(argv[1], "pf"))
2116                         br.pf_offset = 0;
2117                 else if (!strcmp(argv[1], "offset"))
2118                         br.pf_offset = 1;
2119                 else
2120                         return (EINVAL);
2121
2122                 p = str_to_number(argv[2], &l, NULL);
2123                 if (*p)
2124                         return (EINVAL);
2125                 br.pfidx_addr = l;
2126         } else {
2127                 warnx("loadboot: incorrect number of arguments.");
2128                 return (EINVAL);
2129         }
2130
2131         if (strcmp(fname, "clear") == 0)
2132                 return (doit(CHELSIO_T4_LOAD_BOOT, &br));
2133
2134         fd = open(fname, O_RDONLY);
2135         if (fd < 0) {
2136                 warn("open(%s)", fname);
2137                 return (errno);
2138         }
2139
2140         if (fstat(fd, &st) < 0) {
2141                 warn("fstat");
2142                 close(fd);
2143                 return (errno);
2144         }
2145
2146         br.len = st.st_size;
2147         br.data = mmap(0, br.len, PROT_READ, MAP_PRIVATE, fd, 0);
2148         if (br.data == MAP_FAILED) {
2149                 warn("mmap");
2150                 close(fd);
2151                 return (errno);
2152         }
2153
2154         rc = doit(CHELSIO_T4_LOAD_BOOT, &br);
2155         munmap(br.data, br.len);
2156         close(fd);
2157         return (rc);
2158 }
2159
2160 static int
2161 loadbootcfg(int argc, const char *argv[])
2162 {
2163         int rc, fd;
2164         struct t4_data bc = {0};
2165         const char *fname = argv[0];
2166         struct stat st = {0};
2167
2168         if (argc != 1) {
2169                 warnx("loadbootcfg: incorrect number of arguments.");
2170                 return (EINVAL);
2171         }
2172
2173         if (strcmp(fname, "clear") == 0)
2174                 return (doit(CHELSIO_T4_LOAD_BOOTCFG, &bc));
2175
2176         fd = open(fname, O_RDONLY);
2177         if (fd < 0) {
2178                 warn("open(%s)", fname);
2179                 return (errno);
2180         }
2181
2182         if (fstat(fd, &st) < 0) {
2183                 warn("fstat");
2184                 close(fd);
2185                 return (errno);
2186         }
2187
2188         bc.len = st.st_size;
2189         bc.data = mmap(0, bc.len, PROT_READ, MAP_PRIVATE, fd, 0);
2190         if (bc.data == MAP_FAILED) {
2191                 warn("mmap");
2192                 close(fd);
2193                 return (errno);
2194         }
2195
2196         rc = doit(CHELSIO_T4_LOAD_BOOTCFG, &bc);
2197         munmap(bc.data, bc.len);
2198         close(fd);
2199         return (rc);
2200 }
2201
2202 /*
2203  * Display memory as list of 'n' 4-byte values per line.
2204  */
2205 static void
2206 show_mem(uint32_t *buf, uint32_t len)
2207 {
2208         const char *s;
2209         int i, n = 8;
2210
2211         while (len) {
2212                 for (i = 0; len && i < n; i++, buf++, len -= 4) {
2213                         s = i ? " " : "";
2214                         printf("%s%08x", s, htonl(*buf));
2215                 }
2216                 printf("\n");
2217         }
2218 }
2219
2220 static int
2221 memdump(int argc, const char *argv[])
2222 {
2223         char *p;
2224         long l;
2225         uint32_t addr, len;
2226
2227         if (argc != 2) {
2228                 warnx("incorrect number of arguments.");
2229                 return (EINVAL);
2230         }
2231
2232         p = str_to_number(argv[0], &l, NULL);
2233         if (*p) {
2234                 warnx("invalid address \"%s\"", argv[0]);
2235                 return (EINVAL);
2236         }
2237         addr = l;
2238
2239         p = str_to_number(argv[1], &l, NULL);
2240         if (*p) {
2241                 warnx("memdump: invalid length \"%s\"", argv[1]);
2242                 return (EINVAL);
2243         }
2244         len = l;
2245
2246         return (read_mem(addr, len, show_mem));
2247 }
2248
2249 /*
2250  * Display TCB as list of 'n' 4-byte values per line.
2251  */
2252 static void
2253 show_tcb(uint32_t *buf, uint32_t len)
2254 {
2255         unsigned char *tcb = (unsigned char *)buf;
2256         const char *s;
2257         int i, n = 8;
2258
2259         while (len) {
2260                 for (i = 0; len && i < n; i++, buf++, len -= 4) {
2261                         s = i ? " " : "";
2262                         printf("%s%08x", s, htonl(*buf));
2263                 }
2264                 printf("\n");
2265         }
2266         set_tcb_info(TIDTYPE_TCB, chip_id);
2267         set_print_style(PRNTSTYL_COMP);
2268         swizzle_tcb(tcb);
2269         parse_n_display_xcb(tcb);
2270 }
2271
2272 #define A_TP_CMM_TCB_BASE 0x7d10
2273 #define TCB_SIZE 128
2274 static int
2275 read_tcb(int argc, const char *argv[])
2276 {
2277         char *p;
2278         long l;
2279         long long val;
2280         unsigned int tid;
2281         uint32_t addr;
2282         int rc;
2283
2284         if (argc != 1) {
2285                 warnx("incorrect number of arguments.");
2286                 return (EINVAL);
2287         }
2288
2289         p = str_to_number(argv[0], &l, NULL);
2290         if (*p) {
2291                 warnx("invalid tid \"%s\"", argv[0]);
2292                 return (EINVAL);
2293         }
2294         tid = l;
2295
2296         rc = read_reg(A_TP_CMM_TCB_BASE, 4, &val);
2297         if (rc != 0)
2298                 return (rc);
2299
2300         addr = val + tid * TCB_SIZE;
2301
2302         return (read_mem(addr, TCB_SIZE, show_tcb));
2303 }
2304
2305 static int
2306 read_i2c(int argc, const char *argv[])
2307 {
2308         char *p;
2309         long l;
2310         struct t4_i2c_data i2cd;
2311         int rc, i;
2312
2313         if (argc < 3 || argc > 4) {
2314                 warnx("incorrect number of arguments.");
2315                 return (EINVAL);
2316         }
2317
2318         p = str_to_number(argv[0], &l, NULL);
2319         if (*p || l > UCHAR_MAX) {
2320                 warnx("invalid port id \"%s\"", argv[0]);
2321                 return (EINVAL);
2322         }
2323         i2cd.port_id = l;
2324
2325         p = str_to_number(argv[1], &l, NULL);
2326         if (*p || l > UCHAR_MAX) {
2327                 warnx("invalid i2c device address \"%s\"", argv[1]);
2328                 return (EINVAL);
2329         }
2330         i2cd.dev_addr = l;
2331
2332         p = str_to_number(argv[2], &l, NULL);
2333         if (*p || l > UCHAR_MAX) {
2334                 warnx("invalid byte offset \"%s\"", argv[2]);
2335                 return (EINVAL);
2336         }
2337         i2cd.offset = l;
2338
2339         if (argc == 4) {
2340                 p = str_to_number(argv[3], &l, NULL);
2341                 if (*p || l > sizeof(i2cd.data)) {
2342                         warnx("invalid number of bytes \"%s\"", argv[3]);
2343                         return (EINVAL);
2344                 }
2345                 i2cd.len = l;
2346         } else
2347                 i2cd.len = 1;
2348
2349         rc = doit(CHELSIO_T4_GET_I2C, &i2cd);
2350         if (rc != 0)
2351                 return (rc);
2352
2353         for (i = 0; i < i2cd.len; i++)
2354                 printf("0x%x [%u]\n", i2cd.data[i], i2cd.data[i]);
2355
2356         return (0);
2357 }
2358
2359 static int
2360 clearstats(int argc, const char *argv[])
2361 {
2362         char *p;
2363         long l;
2364         uint32_t port;
2365
2366         if (argc != 1) {
2367                 warnx("incorrect number of arguments.");
2368                 return (EINVAL);
2369         }
2370
2371         p = str_to_number(argv[0], &l, NULL);
2372         if (*p) {
2373                 warnx("invalid port id \"%s\"", argv[0]);
2374                 return (EINVAL);
2375         }
2376         port = l;
2377
2378         return doit(CHELSIO_T4_CLEAR_STATS, &port);
2379 }
2380
2381 static int
2382 show_tracers(void)
2383 {
2384         struct t4_tracer t;
2385         char *s;
2386         int rc, port_idx, i;
2387         long long val;
2388
2389         /* Magic values: MPS_TRC_CFG = 0x9800. MPS_TRC_CFG[1:1] = TrcEn */
2390         rc = read_reg(0x9800, 4, &val);
2391         if (rc != 0)
2392                 return (rc);
2393         printf("tracing is %s\n", val & 2 ? "ENABLED" : "DISABLED");
2394
2395         t.idx = 0;
2396         for (t.idx = 0; ; t.idx++) {
2397                 rc = doit(CHELSIO_T4_GET_TRACER, &t);
2398                 if (rc != 0 || t.idx == 0xff)
2399                         break;
2400
2401                 if (t.tp.port < 4) {
2402                         s = "Rx";
2403                         port_idx = t.tp.port;
2404                 } else if (t.tp.port < 8) {
2405                         s = "Tx";
2406                         port_idx = t.tp.port - 4;
2407                 } else if (t.tp.port < 12) {
2408                         s = "loopback";
2409                         port_idx = t.tp.port - 8;
2410                 } else if (t.tp.port < 16) {
2411                         s = "MPS Rx";
2412                         port_idx = t.tp.port - 12;
2413                 } else if (t.tp.port < 20) {
2414                         s = "MPS Tx";
2415                         port_idx = t.tp.port - 16;
2416                 } else {
2417                         s = "unknown";
2418                         port_idx = t.tp.port;
2419                 }
2420
2421                 printf("\ntracer %u (currently %s) captures ", t.idx,
2422                     t.enabled ? "ENABLED" : "DISABLED");
2423                 if (t.tp.port < 8)
2424                         printf("port %u %s, ", port_idx, s);
2425                 else
2426                         printf("%s %u, ", s, port_idx);
2427                 printf("snap length: %u, min length: %u\n", t.tp.snap_len,
2428                     t.tp.min_len);
2429                 printf("packets captured %smatch filter\n",
2430                     t.tp.invert ? "do not " : "");
2431                 if (t.tp.skip_ofst) {
2432                         printf("filter pattern: ");
2433                         for (i = 0; i < t.tp.skip_ofst * 2; i += 2)
2434                                 printf("%08x%08x", t.tp.data[i],
2435                                     t.tp.data[i + 1]);
2436                         printf("/");
2437                         for (i = 0; i < t.tp.skip_ofst * 2; i += 2)
2438                                 printf("%08x%08x", t.tp.mask[i],
2439                                     t.tp.mask[i + 1]);
2440                         printf("@0\n");
2441                 }
2442                 printf("filter pattern: ");
2443                 for (i = t.tp.skip_ofst * 2; i < T4_TRACE_LEN / 4; i += 2)
2444                         printf("%08x%08x", t.tp.data[i], t.tp.data[i + 1]);
2445                 printf("/");
2446                 for (i = t.tp.skip_ofst * 2; i < T4_TRACE_LEN / 4; i += 2)
2447                         printf("%08x%08x", t.tp.mask[i], t.tp.mask[i + 1]);
2448                 printf("@%u\n", (t.tp.skip_ofst + t.tp.skip_len) * 8);
2449         }
2450
2451         return (rc);
2452 }
2453
2454 static int
2455 tracer_onoff(uint8_t idx, int enabled)
2456 {
2457         struct t4_tracer t;
2458
2459         t.idx = idx;
2460         t.enabled = enabled;
2461         t.valid = 0;
2462
2463         return doit(CHELSIO_T4_SET_TRACER, &t);
2464 }
2465
2466 static void
2467 create_tracing_ifnet()
2468 {
2469         char *cmd[] = {
2470                 "/sbin/ifconfig", __DECONST(char *, nexus), "create", NULL
2471         };
2472         char *env[] = {NULL};
2473
2474         if (vfork() == 0) {
2475                 close(STDERR_FILENO);
2476                 execve(cmd[0], cmd, env);
2477                 _exit(0);
2478         }
2479 }
2480
2481 /*
2482  * XXX: Allow user to specify snaplen, minlen, and pattern (including inverted
2483  * matching).  Right now this is a quick-n-dirty implementation that traces the
2484  * first 128B of all tx or rx on a port
2485  */
2486 static int
2487 set_tracer(uint8_t idx, int argc, const char *argv[])
2488 {
2489         struct t4_tracer t;
2490         int len, port;
2491
2492         bzero(&t, sizeof (t));
2493         t.idx = idx;
2494         t.enabled = 1;
2495         t.valid = 1;
2496
2497         if (argc != 1) {
2498                 warnx("must specify tx<n> or rx<n>.");
2499                 return (EINVAL);
2500         }
2501
2502         len = strlen(argv[0]);
2503         if (len != 3) {
2504                 warnx("argument must be 3 characters (tx<n> or rx<n>)");
2505                 return (EINVAL);
2506         }
2507
2508         if (strncmp(argv[0], "tx", 2) == 0) {
2509                 port = argv[0][2] - '0';
2510                 if (port < 0 || port > 3) {
2511                         warnx("'%c' in %s is invalid", argv[0][2], argv[0]);
2512                         return (EINVAL);
2513                 }
2514                 port += 4;
2515         } else if (strncmp(argv[0], "rx", 2) == 0) {
2516                 port = argv[0][2] - '0';
2517                 if (port < 0 || port > 3) {
2518                         warnx("'%c' in %s is invalid", argv[0][2], argv[0]);
2519                         return (EINVAL);
2520                 }
2521         } else {
2522                 warnx("argument '%s' isn't tx<n> or rx<n>", argv[0]);
2523                 return (EINVAL);
2524         }
2525
2526         t.tp.snap_len = 128;
2527         t.tp.min_len = 0;
2528         t.tp.skip_ofst = 0;
2529         t.tp.skip_len = 0;
2530         t.tp.invert = 0;
2531         t.tp.port = port;
2532
2533         create_tracing_ifnet();
2534         return doit(CHELSIO_T4_SET_TRACER, &t);
2535 }
2536
2537 static int
2538 tracer_cmd(int argc, const char *argv[])
2539 {
2540         long long val;
2541         uint8_t idx;
2542         char *s;
2543
2544         if (argc == 0) {
2545                 warnx("tracer: no arguments.");
2546                 return (EINVAL);
2547         };
2548
2549         /* list */
2550         if (strcmp(argv[0], "list") == 0) {
2551                 if (argc != 1)
2552                         warnx("trailing arguments after \"list\" ignored.");
2553
2554                 return show_tracers();
2555         }
2556
2557         /* <idx> ... */
2558         s = str_to_number(argv[0], NULL, &val);
2559         if (*s || val > 0xff) {
2560                 warnx("\"%s\" is neither an index nor a tracer subcommand.",
2561                     argv[0]);
2562                 return (EINVAL);
2563         }
2564         idx = (int8_t)val;
2565
2566         /* <idx> disable */
2567         if (argc == 2 && strcmp(argv[1], "disable") == 0)
2568                 return tracer_onoff(idx, 0);
2569
2570         /* <idx> enable */
2571         if (argc == 2 && strcmp(argv[1], "enable") == 0)
2572                 return tracer_onoff(idx, 1);
2573
2574         /* <idx> ... */
2575         return set_tracer(idx, argc - 1, argv + 1);
2576 }
2577
2578 static int
2579 modinfo_raw(int port_id)
2580 {
2581         uint8_t offset;
2582         struct t4_i2c_data i2cd;
2583         int rc;
2584
2585         for (offset = 0; offset < 96; offset += sizeof(i2cd.data)) {
2586                 bzero(&i2cd, sizeof(i2cd));
2587                 i2cd.port_id = port_id;
2588                 i2cd.dev_addr = 0xa0;
2589                 i2cd.offset = offset;
2590                 i2cd.len = sizeof(i2cd.data);
2591                 rc = doit(CHELSIO_T4_GET_I2C, &i2cd);
2592                 if (rc != 0)
2593                         return (rc);
2594                 printf("%02x:  %02x %02x %02x %02x  %02x %02x %02x %02x",
2595                     offset, i2cd.data[0], i2cd.data[1], i2cd.data[2],
2596                     i2cd.data[3], i2cd.data[4], i2cd.data[5], i2cd.data[6],
2597                     i2cd.data[7]);
2598
2599                 printf("  %c%c%c%c %c%c%c%c\n",
2600                     isprint(i2cd.data[0]) ? i2cd.data[0] : '.',
2601                     isprint(i2cd.data[1]) ? i2cd.data[1] : '.',
2602                     isprint(i2cd.data[2]) ? i2cd.data[2] : '.',
2603                     isprint(i2cd.data[3]) ? i2cd.data[3] : '.',
2604                     isprint(i2cd.data[4]) ? i2cd.data[4] : '.',
2605                     isprint(i2cd.data[5]) ? i2cd.data[5] : '.',
2606                     isprint(i2cd.data[6]) ? i2cd.data[6] : '.',
2607                     isprint(i2cd.data[7]) ? i2cd.data[7] : '.');
2608         }
2609
2610         return (0);
2611 }
2612
2613 static int
2614 modinfo(int argc, const char *argv[])
2615 {
2616         long port;
2617         char string[16], *p;
2618         struct t4_i2c_data i2cd;
2619         int rc, i;
2620         uint16_t temp, vcc, tx_bias, tx_power, rx_power;
2621
2622         if (argc < 1) {
2623                 warnx("must supply a port");
2624                 return (EINVAL);
2625         }
2626
2627         if (argc > 2) {
2628                 warnx("too many arguments");
2629                 return (EINVAL);
2630         }
2631
2632         p = str_to_number(argv[0], &port, NULL);
2633         if (*p || port > UCHAR_MAX) {
2634                 warnx("invalid port id \"%s\"", argv[0]);
2635                 return (EINVAL);
2636         }
2637
2638         if (argc == 2) {
2639                 if (!strcmp(argv[1], "raw"))
2640                         return (modinfo_raw(port));
2641                 else {
2642                         warnx("second argument can only be \"raw\"");
2643                         return (EINVAL);
2644                 }
2645         }
2646
2647         bzero(&i2cd, sizeof(i2cd));
2648         i2cd.len = 1;
2649         i2cd.port_id = port;
2650         i2cd.dev_addr = SFF_8472_BASE;
2651
2652         i2cd.offset = SFF_8472_ID;
2653         if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2654                 goto fail;
2655
2656         if (i2cd.data[0] > SFF_8472_ID_LAST)
2657                 printf("Unknown ID\n");
2658         else
2659                 printf("ID: %s\n", sff_8472_id[i2cd.data[0]]);
2660
2661         bzero(&string, sizeof(string));
2662         for (i = SFF_8472_VENDOR_START; i < SFF_8472_VENDOR_END; i++) {
2663                 i2cd.offset = i;
2664                 if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2665                         goto fail;
2666                 string[i - SFF_8472_VENDOR_START] = i2cd.data[0];
2667         }
2668         printf("Vendor %s\n", string);
2669
2670         bzero(&string, sizeof(string));
2671         for (i = SFF_8472_SN_START; i < SFF_8472_SN_END; i++) {
2672                 i2cd.offset = i;
2673                 if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2674                         goto fail;
2675                 string[i - SFF_8472_SN_START] = i2cd.data[0];
2676         }
2677         printf("SN %s\n", string);
2678
2679         bzero(&string, sizeof(string));
2680         for (i = SFF_8472_PN_START; i < SFF_8472_PN_END; i++) {
2681                 i2cd.offset = i;
2682                 if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2683                         goto fail;
2684                 string[i - SFF_8472_PN_START] = i2cd.data[0];
2685         }
2686         printf("PN %s\n", string);
2687
2688         bzero(&string, sizeof(string));
2689         for (i = SFF_8472_REV_START; i < SFF_8472_REV_END; i++) {
2690                 i2cd.offset = i;
2691                 if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2692                         goto fail;
2693                 string[i - SFF_8472_REV_START] = i2cd.data[0];
2694         }
2695         printf("Rev %s\n", string);
2696
2697         i2cd.offset = SFF_8472_DIAG_TYPE;
2698         if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2699                 goto fail;
2700
2701         if ((char )i2cd.data[0] & (SFF_8472_DIAG_IMPL |
2702                                    SFF_8472_DIAG_INTERNAL)) {
2703
2704                 /* Switch to reading from the Diagnostic address. */
2705                 i2cd.dev_addr = SFF_8472_DIAG;
2706                 i2cd.len = 1;
2707
2708                 i2cd.offset = SFF_8472_TEMP;
2709                 if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2710                         goto fail;
2711                 temp = i2cd.data[0] << 8;
2712                 printf("Temp: ");
2713                 if ((temp & SFF_8472_TEMP_SIGN) == SFF_8472_TEMP_SIGN)
2714                         printf("-");
2715                 else
2716                         printf("+");
2717                 printf("%dC\n", (temp & SFF_8472_TEMP_MSK) >>
2718                     SFF_8472_TEMP_SHIFT);
2719
2720                 i2cd.offset = SFF_8472_VCC;
2721                 if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2722                         goto fail;
2723                 vcc = i2cd.data[0] << 8;
2724                 printf("Vcc %fV\n", vcc / SFF_8472_VCC_FACTOR);
2725
2726                 i2cd.offset = SFF_8472_TX_BIAS;
2727                 if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2728                         goto fail;
2729                 tx_bias = i2cd.data[0] << 8;
2730                 printf("TX Bias %fuA\n", tx_bias / SFF_8472_BIAS_FACTOR);
2731
2732                 i2cd.offset = SFF_8472_TX_POWER;
2733                 if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2734                         goto fail;
2735                 tx_power = i2cd.data[0] << 8;
2736                 printf("TX Power %fmW\n", tx_power / SFF_8472_POWER_FACTOR);
2737
2738                 i2cd.offset = SFF_8472_RX_POWER;
2739                 if ((rc = doit(CHELSIO_T4_GET_I2C, &i2cd)) != 0)
2740                         goto fail;
2741                 rx_power = i2cd.data[0] << 8;
2742                 printf("RX Power %fmW\n", rx_power / SFF_8472_POWER_FACTOR);
2743
2744         } else
2745                 printf("Diagnostics not supported.\n");
2746
2747         return(0);
2748
2749 fail:
2750         if (rc == EPERM)
2751                 warnx("No module/cable in port %ld", port);
2752         return (rc);
2753
2754 }
2755
2756 /* XXX: pass in a low/high and do range checks as well */
2757 static int
2758 get_sched_param(const char *param, const char *args[], long *val)
2759 {
2760         char *p;
2761
2762         if (strcmp(param, args[0]) != 0)
2763                 return (EINVAL);
2764
2765         p = str_to_number(args[1], val, NULL);
2766         if (*p) {
2767                 warnx("parameter \"%s\" has bad value \"%s\"", args[0],
2768                     args[1]);
2769                 return (EINVAL);
2770         }
2771
2772         return (0);
2773 }
2774
2775 static int
2776 sched_class(int argc, const char *argv[])
2777 {
2778         struct t4_sched_params op;
2779         int errs, i;
2780
2781         memset(&op, 0xff, sizeof(op));
2782         op.subcmd = -1;
2783         op.type = -1;
2784         if (argc == 0) {
2785                 warnx("missing scheduling sub-command");
2786                 return (EINVAL);
2787         }
2788         if (!strcmp(argv[0], "config")) {
2789                 op.subcmd = SCHED_CLASS_SUBCMD_CONFIG;
2790                 op.u.config.minmax = -1;
2791         } else if (!strcmp(argv[0], "params")) {
2792                 op.subcmd = SCHED_CLASS_SUBCMD_PARAMS;
2793                 op.u.params.level = op.u.params.mode = op.u.params.rateunit =
2794                     op.u.params.ratemode = op.u.params.channel =
2795                     op.u.params.cl = op.u.params.minrate = op.u.params.maxrate =
2796                     op.u.params.weight = op.u.params.pktsize = -1;
2797         } else {
2798                 warnx("invalid scheduling sub-command \"%s\"", argv[0]);
2799                 return (EINVAL);
2800         }
2801
2802         /* Decode remaining arguments ... */
2803         errs = 0;
2804         for (i = 1; i < argc; i += 2) {
2805                 const char **args = &argv[i];
2806                 long l;
2807
2808                 if (i + 1 == argc) {
2809                         warnx("missing argument for \"%s\"", args[0]);
2810                         errs++;
2811                         break;
2812                 }
2813
2814                 if (!strcmp(args[0], "type")) {
2815                         if (!strcmp(args[1], "packet"))
2816                                 op.type = SCHED_CLASS_TYPE_PACKET;
2817                         else {
2818                                 warnx("invalid type parameter \"%s\"", args[1]);
2819                                 errs++;
2820                         }
2821
2822                         continue;
2823                 }
2824
2825                 if (op.subcmd == SCHED_CLASS_SUBCMD_CONFIG) {
2826                         if(!get_sched_param("minmax", args, &l))
2827                                 op.u.config.minmax = (int8_t)l;
2828                         else {
2829                                 warnx("unknown scheduler config parameter "
2830                                     "\"%s\"", args[0]);
2831                                 errs++;
2832                         }
2833
2834                         continue;
2835                 }
2836
2837                 /* Rest applies only to SUBCMD_PARAMS */
2838                 if (op.subcmd != SCHED_CLASS_SUBCMD_PARAMS)
2839                         continue;
2840
2841                 if (!strcmp(args[0], "level")) {
2842                         if (!strcmp(args[1], "cl-rl"))
2843                                 op.u.params.level = SCHED_CLASS_LEVEL_CL_RL;
2844                         else if (!strcmp(args[1], "cl-wrr"))
2845                                 op.u.params.level = SCHED_CLASS_LEVEL_CL_WRR;
2846                         else if (!strcmp(args[1], "ch-rl"))
2847                                 op.u.params.level = SCHED_CLASS_LEVEL_CH_RL;
2848                         else {
2849                                 warnx("invalid level parameter \"%s\"",
2850                                     args[1]);
2851                                 errs++;
2852                         }
2853                 } else if (!strcmp(args[0], "mode")) {
2854                         if (!strcmp(args[1], "class"))
2855                                 op.u.params.mode = SCHED_CLASS_MODE_CLASS;
2856                         else if (!strcmp(args[1], "flow"))
2857                                 op.u.params.mode = SCHED_CLASS_MODE_FLOW;
2858                         else {
2859                                 warnx("invalid mode parameter \"%s\"", args[1]);
2860                                 errs++;
2861                         }
2862                 } else if (!strcmp(args[0], "rate-unit")) {
2863                         if (!strcmp(args[1], "bits"))
2864                                 op.u.params.rateunit = SCHED_CLASS_RATEUNIT_BITS;
2865                         else if (!strcmp(args[1], "pkts"))
2866                                 op.u.params.rateunit = SCHED_CLASS_RATEUNIT_PKTS;
2867                         else {
2868                                 warnx("invalid rate-unit parameter \"%s\"",
2869                                     args[1]);
2870                                 errs++;
2871                         }
2872                 } else if (!strcmp(args[0], "rate-mode")) {
2873                         if (!strcmp(args[1], "relative"))
2874                                 op.u.params.ratemode = SCHED_CLASS_RATEMODE_REL;
2875                         else if (!strcmp(args[1], "absolute"))
2876                                 op.u.params.ratemode = SCHED_CLASS_RATEMODE_ABS;
2877                         else {
2878                                 warnx("invalid rate-mode parameter \"%s\"",
2879                                     args[1]);
2880                                 errs++;
2881                         }
2882                 } else if (!get_sched_param("channel", args, &l))
2883                         op.u.params.channel = (int8_t)l;
2884                 else if (!get_sched_param("class", args, &l))
2885                         op.u.params.cl = (int8_t)l;
2886                 else if (!get_sched_param("min-rate", args, &l))
2887                         op.u.params.minrate = (int32_t)l;
2888                 else if (!get_sched_param("max-rate", args, &l))
2889                         op.u.params.maxrate = (int32_t)l;
2890                 else if (!get_sched_param("weight", args, &l))
2891                         op.u.params.weight = (int16_t)l;
2892                 else if (!get_sched_param("pkt-size", args, &l))
2893                         op.u.params.pktsize = (int16_t)l;
2894                 else {
2895                         warnx("unknown scheduler parameter \"%s\"", args[0]);
2896                         errs++;
2897                 }
2898         }
2899
2900         /*
2901          * Catch some logical fallacies in terms of argument combinations here
2902          * so we can offer more than just the EINVAL return from the driver.
2903          * The driver will be able to catch a lot more issues since it knows
2904          * the specifics of the device hardware capabilities like how many
2905          * channels, classes, etc. the device supports.
2906          */
2907         if (op.type < 0) {
2908                 warnx("sched \"type\" parameter missing");
2909                 errs++;
2910         }
2911         if (op.subcmd == SCHED_CLASS_SUBCMD_CONFIG) {
2912                 if (op.u.config.minmax < 0) {
2913                         warnx("sched config \"minmax\" parameter missing");
2914                         errs++;
2915                 }
2916         }
2917         if (op.subcmd == SCHED_CLASS_SUBCMD_PARAMS) {
2918                 if (op.u.params.level < 0) {
2919                         warnx("sched params \"level\" parameter missing");
2920                         errs++;
2921                 }
2922                 if (op.u.params.mode < 0 &&
2923                     op.u.params.level == SCHED_CLASS_LEVEL_CL_RL) {
2924                         warnx("sched params \"mode\" parameter missing");
2925                         errs++;
2926                 }
2927                 if (op.u.params.rateunit < 0 &&
2928                     (op.u.params.level == SCHED_CLASS_LEVEL_CL_RL ||
2929                     op.u.params.level == SCHED_CLASS_LEVEL_CH_RL)) {
2930                         warnx("sched params \"rate-unit\" parameter missing");
2931                         errs++;
2932                 }
2933                 if (op.u.params.ratemode < 0 &&
2934                     (op.u.params.level == SCHED_CLASS_LEVEL_CL_RL ||
2935                     op.u.params.level == SCHED_CLASS_LEVEL_CH_RL)) {
2936                         warnx("sched params \"rate-mode\" parameter missing");
2937                         errs++;
2938                 }
2939                 if (op.u.params.channel < 0) {
2940                         warnx("sched params \"channel\" missing");
2941                         errs++;
2942                 }
2943                 if (op.u.params.cl < 0 &&
2944                     (op.u.params.level == SCHED_CLASS_LEVEL_CL_RL ||
2945                     op.u.params.level == SCHED_CLASS_LEVEL_CL_WRR)) {
2946                         warnx("sched params \"class\" missing");
2947                         errs++;
2948                 }
2949                 if (op.u.params.maxrate < 0 &&
2950                     (op.u.params.level == SCHED_CLASS_LEVEL_CL_RL ||
2951                     op.u.params.level == SCHED_CLASS_LEVEL_CH_RL)) {
2952                         warnx("sched params \"max-rate\" missing for "
2953                             "rate-limit level");
2954                         errs++;
2955                 }
2956                 if (op.u.params.level == SCHED_CLASS_LEVEL_CL_WRR &&
2957                     (op.u.params.weight < 1 || op.u.params.weight > 99)) {
2958                         warnx("sched params \"weight\" missing or invalid "
2959                             "(not 1-99) for weighted-round-robin level");
2960                         errs++;
2961                 }
2962                 if (op.u.params.pktsize < 0 &&
2963                     op.u.params.level == SCHED_CLASS_LEVEL_CL_RL) {
2964                         warnx("sched params \"pkt-size\" missing for "
2965                             "rate-limit level");
2966                         errs++;
2967                 }
2968                 if (op.u.params.mode == SCHED_CLASS_MODE_FLOW &&
2969                     op.u.params.ratemode != SCHED_CLASS_RATEMODE_ABS) {
2970                         warnx("sched params mode flow needs rate-mode absolute");
2971                         errs++;
2972                 }
2973                 if (op.u.params.ratemode == SCHED_CLASS_RATEMODE_REL &&
2974                     !in_range(op.u.params.maxrate, 1, 100)) {
2975                         warnx("sched params \"max-rate\" takes "
2976                             "percentage value(1-100) for rate-mode relative");
2977                         errs++;
2978                 }
2979                 if (op.u.params.ratemode == SCHED_CLASS_RATEMODE_ABS &&
2980                     !in_range(op.u.params.maxrate, 1, 100000000)) {
2981                         warnx("sched params \"max-rate\" takes "
2982                             "value(1-100000000) for rate-mode absolute");
2983                         errs++;
2984                 }
2985                 if (op.u.params.maxrate > 0 &&
2986                     op.u.params.maxrate < op.u.params.minrate) {
2987                         warnx("sched params \"max-rate\" is less than "
2988                             "\"min-rate\"");
2989                         errs++;
2990                 }
2991         }
2992
2993         if (errs > 0) {
2994                 warnx("%d error%s in sched-class command", errs,
2995                     errs == 1 ? "" : "s");
2996                 return (EINVAL);
2997         }
2998
2999         return doit(CHELSIO_T4_SCHED_CLASS, &op);
3000 }
3001
3002 static int
3003 sched_queue(int argc, const char *argv[])
3004 {
3005         struct t4_sched_queue op = {0};
3006         char *p;
3007         long val;
3008
3009         if (argc != 3) {
3010                 /* need "<port> <queue> <class> */
3011                 warnx("incorrect number of arguments.");
3012                 return (EINVAL);
3013         }
3014
3015         p = str_to_number(argv[0], &val, NULL);
3016         if (*p || val > UCHAR_MAX) {
3017                 warnx("invalid port id \"%s\"", argv[0]);
3018                 return (EINVAL);
3019         }
3020         op.port = (uint8_t)val;
3021
3022         if (!strcmp(argv[1], "all") || !strcmp(argv[1], "*"))
3023                 op.queue = -1;
3024         else {
3025                 p = str_to_number(argv[1], &val, NULL);
3026                 if (*p || val < -1) {
3027                         warnx("invalid queue \"%s\"", argv[1]);
3028                         return (EINVAL);
3029                 }
3030                 op.queue = (int8_t)val;
3031         }
3032
3033         if (!strcmp(argv[2], "unbind") || !strcmp(argv[2], "clear"))
3034                 op.cl = -1;
3035         else {
3036                 p = str_to_number(argv[2], &val, NULL);
3037                 if (*p || val < -1) {
3038                         warnx("invalid class \"%s\"", argv[2]);
3039                         return (EINVAL);
3040                 }
3041                 op.cl = (int8_t)val;
3042         }
3043
3044         return doit(CHELSIO_T4_SCHED_QUEUE, &op);
3045 }
3046
3047 static int
3048 parse_offload_settings_word(const char *s, char **pnext, const char *ws,
3049     int *pneg, struct offload_settings *os)
3050 {
3051
3052         while (*s == '!') {
3053                 (*pneg)++;
3054                 s++;
3055         }
3056
3057         if (!strcmp(s, "not")) {
3058                 (*pneg)++;
3059                 return (0);
3060         }
3061
3062         if (!strcmp(s, "offload")) {
3063                 os->offload = (*pneg + 1) & 1;
3064                 *pneg = 0;
3065         } else if (!strcmp(s , "coalesce")) {
3066                 os->rx_coalesce = (*pneg + 1) & 1;
3067                 *pneg = 0;
3068         } else if (!strcmp(s, "timestamp") || !strcmp(s, "tstamp")) {
3069                 os->tstamp = (*pneg + 1) & 1;
3070                 *pneg = 0;
3071         } else if (!strcmp(s, "sack")) {
3072                 os->sack = (*pneg + 1) & 1;
3073                 *pneg = 0;
3074         } else if (!strcmp(s, "nagle")) {
3075                 os->nagle = (*pneg + 1) & 1;
3076                 *pneg = 0;
3077         } else if (!strcmp(s, "ecn")) {
3078                 os->ecn = (*pneg + 1) & 1;
3079                 *pneg = 0;
3080         } else if (!strcmp(s, "ddp")) {
3081                 os->ddp = (*pneg + 1) & 1;
3082                 *pneg = 0;
3083         } else if (!strcmp(s, "tls")) {
3084                 os->tls = (*pneg + 1) & 1;
3085                 *pneg = 0;
3086         } else {
3087                 char *param, *p;
3088                 long val;
3089
3090                 /* Settings with additional parameter handled here. */
3091
3092                 if (*pneg) {
3093                         warnx("\"%s\" is not a valid keyword, or it does not "
3094                             "support negation.", s);
3095                         return (EINVAL);
3096                 }
3097
3098                 while ((param = strsep(pnext, ws)) != NULL) {
3099                         if (*param != '\0')
3100                                 break;
3101                 }
3102                 if (param == NULL) {
3103                         warnx("\"%s\" is not a valid keyword, or it requires a "
3104                             "parameter that has not been provided.", s);
3105                         return (EINVAL);
3106                 }
3107
3108                 if (!strcmp(s, "cong")) {
3109                         if (!strcmp(param, "reno"))
3110                                 os->cong_algo = 0;
3111                         else if (!strcmp(param, "tahoe"))
3112                                 os->cong_algo = 1;
3113                         else if (!strcmp(param, "newreno"))
3114                                 os->cong_algo = 2;
3115                         else if (!strcmp(param, "highspeed"))
3116                                 os->cong_algo = 3;
3117                         else {
3118                                 warnx("unknown congestion algorithm \"%s\".", s);
3119                                 return (EINVAL);
3120                         }
3121                 } else if (!strcmp(s, "class")) {
3122                         val = -1;
3123                         p = str_to_number(param, &val, NULL);
3124                         /* (nsched_cls - 1) is spelled 15 here. */
3125                         if (*p || val < 0 || val > 15) {
3126                                 warnx("invalid scheduling class \"%s\".  "
3127                                     "\"class\" needs an integer value where "
3128                                     "0 <= value <= 15", param);
3129                                 return (EINVAL);
3130                         }
3131                         os->sched_class = val;
3132                 } else if (!strcmp(s, "bind") || !strcmp(s, "txq") ||
3133                     !strcmp(s, "rxq")) {
3134                         val = -1;
3135                         if (strcmp(param, "random")) {
3136                                 p = str_to_number(param, &val, NULL);
3137                                 if (*p || val < 0 || val > 0xffff) {
3138                                         warnx("invalid queue specification "
3139                                             "\"%s\".  \"%s\" needs an integer"
3140                                             " value, or \"random\".",
3141                                             param, s);
3142                                         return (EINVAL);
3143                                 }
3144                         }
3145                         if (!strcmp(s, "bind")) {
3146                                 os->txq = val;
3147                                 os->rxq = val;
3148                         } else if (!strcmp(s, "txq")) {
3149                                 os->txq = val;
3150                         } else if (!strcmp(s, "rxq")) {
3151                                 os->rxq = val;
3152                         } else {
3153                                 return (EDOOFUS);
3154                         }
3155                 } else if (!strcmp(s, "mss")) {
3156                         val = -1;
3157                         p = str_to_number(param, &val, NULL);
3158                         if (*p || val <= 0) {
3159                                 warnx("invalid MSS specification \"%s\".  "
3160                                     "\"mss\" needs a positive integer value",
3161                                     param);
3162                                 return (EINVAL);
3163                         }
3164                         os->mss = val;
3165                 } else  {
3166                         warnx("unknown settings keyword: \"%s\"", s);
3167                         return (EINVAL);
3168                 }
3169         }
3170
3171         return (0);
3172 }
3173
3174 static int
3175 parse_offload_settings(const char *settings_ro, struct offload_settings *os)
3176 {
3177         const char *ws = " \f\n\r\v\t";
3178         char *settings, *s, *next;
3179         int rc, nsettings, neg;
3180         static const struct offload_settings default_settings = {
3181                 .offload = 0,   /* No settings imply !offload */
3182                 .rx_coalesce = -1,
3183                 .cong_algo = -1,
3184                 .sched_class = -1,
3185                 .tstamp = -1,
3186                 .sack = -1,
3187                 .nagle = -1,
3188                 .ecn = -1,
3189                 .ddp = -1,
3190                 .tls = -1,
3191                 .txq = -1,
3192                 .rxq = -1,
3193                 .mss = -1,
3194         };
3195
3196         *os = default_settings;
3197
3198         next = settings = strdup(settings_ro);
3199         if (settings == NULL) {
3200                 warn (NULL);
3201                 return (errno);
3202         }
3203
3204         nsettings = 0;
3205         rc = 0;
3206         neg = 0;
3207         while ((s = strsep(&next, ws)) != NULL) {
3208                 if (*s == '\0')
3209                         continue;
3210                 nsettings++;
3211                 rc = parse_offload_settings_word(s, &next, ws, &neg, os);
3212                 if (rc != 0)
3213                         goto done;
3214         }
3215         if (nsettings == 0) {
3216                 warnx("no settings provided");
3217                 rc = EINVAL;
3218                 goto done;
3219         }
3220         if (neg > 0) {
3221                 warnx("%d stray negation(s) at end of offload settings", neg);
3222                 rc = EINVAL;
3223                 goto done;
3224         }
3225 done:
3226         free(settings);
3227         return (rc);
3228 }
3229
3230 static int
3231 isempty_line(char *line, size_t llen)
3232 {
3233
3234         /* skip leading whitespace */
3235         while (isspace(*line)) {
3236                 line++;
3237                 llen--;
3238         }
3239         if (llen == 0 || *line == '#' || *line == '\n')
3240                 return (1);
3241
3242         return (0);
3243 }
3244
3245 static int
3246 special_offload_rule(char *str)
3247 {
3248
3249         /* skip leading whitespaces */
3250         while (isspace(*str))
3251                 str++;
3252
3253         /* check for special strings: "-", "all", "any" */
3254         if (*str == '-') {
3255                 str++;
3256         } else if (!strncmp(str, "all", 3) || !strncmp(str, "any", 3)) {
3257                 str += 3;
3258         } else {
3259                 return (0);
3260         }
3261
3262         /* skip trailing whitespaces */
3263         while (isspace(*str))
3264                 str++;
3265
3266         return (*str == '\0');
3267 }
3268
3269 /*
3270  * A rule has 3 parts: an open-type, a match expression, and offload settings.
3271  *
3272  * [<open-type>] <expr> => <settings>
3273  */
3274 static int
3275 parse_offload_policy_line(size_t lno, char *line, size_t llen, pcap_t *pd,
3276     struct offload_rule *r)
3277 {
3278         char *expr, *settings, *s;
3279
3280         bzero(r, sizeof(*r));
3281
3282         /* Skip leading whitespace. */
3283         while (isspace(*line))
3284                 line++;
3285         /* Trim trailing whitespace */
3286         s = &line[llen - 1];
3287         while (isspace(*s)) {
3288                 *s-- = '\0';
3289                 llen--;
3290         }
3291
3292         /*
3293          * First part of the rule: '[X]' where X = A/D/L/P
3294          */
3295         if (*line++ != '[') {
3296                 warnx("missing \"[\" on line %zd", lno);
3297                 return (EINVAL);
3298         }
3299         switch (*line) {
3300         case 'A':
3301         case 'D':
3302         case 'L':
3303         case 'P':
3304                 r->open_type = *line;
3305                 break;
3306         default:
3307                 warnx("invalid socket-type \"%c\" on line %zd.", *line, lno);
3308                 return (EINVAL);
3309         }
3310         line++;
3311         if (*line++ != ']') {
3312                 warnx("missing \"]\" after \"[%c\" on line %zd",
3313                     r->open_type, lno);
3314                 return (EINVAL);
3315         }
3316
3317         /* Skip whitespace. */
3318         while (isspace(*line))
3319                 line++;
3320
3321         /*
3322          * Rest of the rule: <expr> => <settings>
3323          */
3324         expr = line;
3325         s = strstr(line, "=>");
3326         if (s == NULL)
3327                 return (EINVAL);
3328         settings = s + 2;
3329         while (isspace(*settings))
3330                 settings++;
3331         *s = '\0';
3332
3333         /*
3334          * <expr> is either a special name (all, any) or a pcap-filter(7).
3335          * In case of a special name the bpf_prog stays all-zero.
3336          */
3337         if (!special_offload_rule(expr)) {
3338                 if (pcap_compile(pd, &r->bpf_prog, expr, 1,
3339                     PCAP_NETMASK_UNKNOWN) < 0) {
3340                         warnx("failed to compile \"%s\" on line %zd: %s", expr,
3341                             lno, pcap_geterr(pd));
3342                         return (EINVAL);
3343                 }
3344         }
3345
3346         /* settings to apply on a match. */
3347         if (parse_offload_settings(settings, &r->settings) != 0) {
3348                 warnx("failed to parse offload settings \"%s\" on line %zd",
3349                     settings, lno);
3350                 pcap_freecode(&r->bpf_prog);
3351                 return (EINVAL);
3352         }
3353
3354         return (0);
3355
3356 }
3357
3358 /*
3359  * Note that op itself is not dynamically allocated.
3360  */
3361 static void
3362 free_offload_policy(struct t4_offload_policy *op)
3363 {
3364         int i;
3365
3366         for (i = 0; i < op->nrules; i++) {
3367                 /*
3368                  * pcap_freecode can cope with empty bpf_prog, which is the case
3369                  * for an rule that matches on 'any/all/-'.
3370                  */
3371                 pcap_freecode(&op->rule[i].bpf_prog);
3372         }
3373         free(op->rule);
3374         op->nrules = 0;
3375         op->rule = NULL;
3376 }
3377
3378 #define REALLOC_STRIDE 32
3379
3380 /*
3381  * Fills up op->nrules and op->rule.
3382  */
3383 static int
3384 parse_offload_policy(const char *fname, struct t4_offload_policy *op)
3385 {
3386         FILE *fp;
3387         char *line;
3388         int lno, maxrules, rc;
3389         size_t lcap, llen;
3390         struct offload_rule *r;
3391         pcap_t *pd;
3392
3393         fp = fopen(fname, "r");
3394         if (fp == NULL) {
3395                 warn("Unable to open file \"%s\"", fname);
3396                 return (errno);
3397         }
3398         pd = pcap_open_dead(DLT_EN10MB, 128);
3399         if (pd == NULL) {
3400                 warnx("Failed to open pcap device");
3401                 fclose(fp);
3402                 return (EIO);
3403         }
3404
3405         rc = 0;
3406         lno = 0;
3407         lcap = 0;
3408         maxrules = 0;
3409         op->nrules = 0;
3410         op->rule = NULL;
3411         line = NULL;
3412
3413         while ((llen = getline(&line, &lcap, fp)) != -1) {
3414                 lno++;
3415
3416                 /* Skip empty lines. */
3417                 if (isempty_line(line, llen))
3418                         continue;
3419
3420                 if (op->nrules == maxrules) {
3421                         maxrules += REALLOC_STRIDE;
3422                         r = realloc(op->rule,
3423                             maxrules * sizeof(struct offload_rule));
3424                         if (r == NULL) {
3425                                 warnx("failed to allocate memory for %d rules",
3426                                     maxrules);
3427                                 rc = ENOMEM;
3428                                 goto done;
3429                         }
3430                         op->rule = r;
3431                 }
3432
3433                 r = &op->rule[op->nrules];
3434                 rc = parse_offload_policy_line(lno, line, llen, pd, r);
3435                 if (rc != 0) {
3436                         warnx("Error parsing line %d of \"%s\"", lno, fname);
3437                         goto done;
3438                 }
3439
3440                 op->nrules++;
3441         }
3442         free(line);
3443
3444         if (!feof(fp)) {
3445                 warn("Error while reading from file \"%s\" at line %d",
3446                     fname, lno);
3447                 rc = errno;
3448                 goto done;
3449         }
3450
3451         if (op->nrules == 0) {
3452                 warnx("No valid rules found in \"%s\"", fname);
3453                 rc = EINVAL;
3454         }
3455 done:
3456         pcap_close(pd);
3457         fclose(fp);
3458         if (rc != 0) {
3459                 free_offload_policy(op);
3460         }
3461
3462         return (rc);
3463 }
3464
3465 static int
3466 load_offload_policy(int argc, const char *argv[])
3467 {
3468         int rc = 0;
3469         const char *fname = argv[0];
3470         struct t4_offload_policy op = {0};
3471
3472         if (argc != 1) {
3473                 warnx("incorrect number of arguments.");
3474                 return (EINVAL);
3475         }
3476
3477         if (!strcmp(fname, "clear") || !strcmp(fname, "none")) {
3478                 /* op.nrules is 0 and that means clear policy */
3479                 return (doit(CHELSIO_T4_SET_OFLD_POLICY, &op));
3480         }
3481
3482         rc = parse_offload_policy(fname, &op);
3483         if (rc != 0) {
3484                 /* Error message displayed already */
3485                 return (EINVAL);
3486         }
3487
3488         rc = doit(CHELSIO_T4_SET_OFLD_POLICY, &op);
3489         free_offload_policy(&op);
3490
3491         return (rc);
3492 }
3493
3494 static int
3495 run_cmd(int argc, const char *argv[])
3496 {
3497         int rc = -1;
3498         const char *cmd = argv[0];
3499
3500         /* command */
3501         argc--;
3502         argv++;
3503
3504         if (!strcmp(cmd, "reg") || !strcmp(cmd, "reg32"))
3505                 rc = register_io(argc, argv, 4);
3506         else if (!strcmp(cmd, "reg64"))
3507                 rc = register_io(argc, argv, 8);
3508         else if (!strcmp(cmd, "regdump"))
3509                 rc = dump_regs(argc, argv);
3510         else if (!strcmp(cmd, "filter"))
3511                 rc = filter_cmd(argc, argv, 0);
3512         else if (!strcmp(cmd, "context"))
3513                 rc = get_sge_context(argc, argv);
3514         else if (!strcmp(cmd, "loadfw"))
3515                 rc = loadfw(argc, argv);
3516         else if (!strcmp(cmd, "memdump"))
3517                 rc = memdump(argc, argv);
3518         else if (!strcmp(cmd, "tcb"))
3519                 rc = read_tcb(argc, argv);
3520         else if (!strcmp(cmd, "i2c"))
3521                 rc = read_i2c(argc, argv);
3522         else if (!strcmp(cmd, "clearstats"))
3523                 rc = clearstats(argc, argv);
3524         else if (!strcmp(cmd, "tracer"))
3525                 rc = tracer_cmd(argc, argv);
3526         else if (!strcmp(cmd, "modinfo"))
3527                 rc = modinfo(argc, argv);
3528         else if (!strcmp(cmd, "sched-class"))
3529                 rc = sched_class(argc, argv);
3530         else if (!strcmp(cmd, "sched-queue"))
3531                 rc = sched_queue(argc, argv);
3532         else if (!strcmp(cmd, "loadcfg"))
3533                 rc = loadcfg(argc, argv);
3534         else if (!strcmp(cmd, "loadboot"))
3535                 rc = loadboot(argc, argv);
3536         else if (!strcmp(cmd, "loadboot-cfg"))
3537                 rc = loadbootcfg(argc, argv);
3538         else if (!strcmp(cmd, "dumpstate"))
3539                 rc = dumpstate(argc, argv);
3540         else if (!strcmp(cmd, "policy"))
3541                 rc = load_offload_policy(argc, argv);
3542         else if (!strcmp(cmd, "hashfilter"))
3543                 rc = filter_cmd(argc, argv, 1);
3544         else {
3545                 rc = EINVAL;
3546                 warnx("invalid command \"%s\"", cmd);
3547         }
3548
3549         return (rc);
3550 }
3551
3552 #define MAX_ARGS 15
3553 static int
3554 run_cmd_loop(void)
3555 {
3556         int i, rc = 0;
3557         char buffer[128], *buf;
3558         const char *args[MAX_ARGS + 1];
3559
3560         /*
3561          * Simple loop: displays a "> " prompt and processes any input as a
3562          * cxgbetool command.  You're supposed to enter only the part after
3563          * "cxgbetool t4nexX".  Use "quit" or "exit" to exit.
3564          */
3565         for (;;) {
3566                 fprintf(stdout, "> ");
3567                 fflush(stdout);
3568                 buf = fgets(buffer, sizeof(buffer), stdin);
3569                 if (buf == NULL) {
3570                         if (ferror(stdin)) {
3571                                 warn("stdin error");
3572                                 rc = errno;     /* errno from fgets */
3573                         }
3574                         break;
3575                 }
3576
3577                 i = 0;
3578                 while ((args[i] = strsep(&buf, " \t\n")) != NULL) {
3579                         if (args[i][0] != 0 && ++i == MAX_ARGS)
3580                                 break;
3581                 }
3582                 args[i] = 0;
3583
3584                 if (i == 0)
3585                         continue;       /* skip empty line */
3586
3587                 if (!strcmp(args[0], "quit") || !strcmp(args[0], "exit"))
3588                         break;
3589
3590                 rc = run_cmd(i, args);
3591         }
3592
3593         /* rc normally comes from the last command (not including quit/exit) */
3594         return (rc);
3595 }
3596
3597 int
3598 main(int argc, const char *argv[])
3599 {
3600         int rc = -1;
3601
3602         progname = argv[0];
3603
3604         if (argc == 2) {
3605                 if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
3606                         usage(stdout);
3607                         exit(0);
3608                 }
3609         }
3610
3611         if (argc < 3) {
3612                 usage(stderr);
3613                 exit(EINVAL);
3614         }
3615
3616         nexus = argv[1];
3617         chip_id = nexus[1] - '0';
3618
3619         /* progname and nexus */
3620         argc -= 2;
3621         argv += 2;
3622
3623         if (argc == 1 && !strcmp(argv[0], "stdio"))
3624                 rc = run_cmd_loop();
3625         else
3626                 rc = run_cmd(argc, argv);
3627
3628         return (rc);
3629 }