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