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