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