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