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