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