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