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