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