xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision 28f4385e45a2681c14bd04b83fe1796eaefe8265)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 Chelsio Communications, Inc.
5  * All rights reserved.
6  * Written by: Navdeep Parhar <np@FreeBSD.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include "opt_ddb.h"
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_ratelimit.h"
37 #include "opt_rss.h"
38 
39 #include <sys/param.h>
40 #include <sys/conf.h>
41 #include <sys/priv.h>
42 #include <sys/kernel.h>
43 #include <sys/bus.h>
44 #include <sys/module.h>
45 #include <sys/malloc.h>
46 #include <sys/queue.h>
47 #include <sys/taskqueue.h>
48 #include <sys/pciio.h>
49 #include <dev/pci/pcireg.h>
50 #include <dev/pci/pcivar.h>
51 #include <dev/pci/pci_private.h>
52 #include <sys/firmware.h>
53 #include <sys/sbuf.h>
54 #include <sys/smp.h>
55 #include <sys/socket.h>
56 #include <sys/sockio.h>
57 #include <sys/sysctl.h>
58 #include <net/ethernet.h>
59 #include <net/if.h>
60 #include <net/if_types.h>
61 #include <net/if_dl.h>
62 #include <net/if_vlan_var.h>
63 #ifdef RSS
64 #include <net/rss_config.h>
65 #endif
66 #include <netinet/in.h>
67 #include <netinet/ip.h>
68 #if defined(__i386__) || defined(__amd64__)
69 #include <machine/md_var.h>
70 #include <machine/cputypes.h>
71 #include <vm/vm.h>
72 #include <vm/pmap.h>
73 #endif
74 #include <crypto/rijndael/rijndael.h>
75 #ifdef DDB
76 #include <ddb/ddb.h>
77 #include <ddb/db_lex.h>
78 #endif
79 
80 #include "common/common.h"
81 #include "common/t4_msg.h"
82 #include "common/t4_regs.h"
83 #include "common/t4_regs_values.h"
84 #include "cudbg/cudbg.h"
85 #include "t4_clip.h"
86 #include "t4_ioctl.h"
87 #include "t4_l2t.h"
88 #include "t4_mp_ring.h"
89 #include "t4_if.h"
90 #include "t4_smt.h"
91 
92 /* T4 bus driver interface */
93 static int t4_probe(device_t);
94 static int t4_attach(device_t);
95 static int t4_detach(device_t);
96 static int t4_child_location_str(device_t, device_t, char *, size_t);
97 static int t4_ready(device_t);
98 static int t4_read_port_device(device_t, int, device_t *);
99 static device_method_t t4_methods[] = {
100 	DEVMETHOD(device_probe,		t4_probe),
101 	DEVMETHOD(device_attach,	t4_attach),
102 	DEVMETHOD(device_detach,	t4_detach),
103 
104 	DEVMETHOD(bus_child_location_str, t4_child_location_str),
105 
106 	DEVMETHOD(t4_is_main_ready,	t4_ready),
107 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
108 
109 	DEVMETHOD_END
110 };
111 static driver_t t4_driver = {
112 	"t4nex",
113 	t4_methods,
114 	sizeof(struct adapter)
115 };
116 
117 
118 /* T4 port (cxgbe) interface */
119 static int cxgbe_probe(device_t);
120 static int cxgbe_attach(device_t);
121 static int cxgbe_detach(device_t);
122 device_method_t cxgbe_methods[] = {
123 	DEVMETHOD(device_probe,		cxgbe_probe),
124 	DEVMETHOD(device_attach,	cxgbe_attach),
125 	DEVMETHOD(device_detach,	cxgbe_detach),
126 	{ 0, 0 }
127 };
128 static driver_t cxgbe_driver = {
129 	"cxgbe",
130 	cxgbe_methods,
131 	sizeof(struct port_info)
132 };
133 
134 /* T4 VI (vcxgbe) interface */
135 static int vcxgbe_probe(device_t);
136 static int vcxgbe_attach(device_t);
137 static int vcxgbe_detach(device_t);
138 static device_method_t vcxgbe_methods[] = {
139 	DEVMETHOD(device_probe,		vcxgbe_probe),
140 	DEVMETHOD(device_attach,	vcxgbe_attach),
141 	DEVMETHOD(device_detach,	vcxgbe_detach),
142 	{ 0, 0 }
143 };
144 static driver_t vcxgbe_driver = {
145 	"vcxgbe",
146 	vcxgbe_methods,
147 	sizeof(struct vi_info)
148 };
149 
150 static d_ioctl_t t4_ioctl;
151 
152 static struct cdevsw t4_cdevsw = {
153        .d_version = D_VERSION,
154        .d_ioctl = t4_ioctl,
155        .d_name = "t4nex",
156 };
157 
158 /* T5 bus driver interface */
159 static int t5_probe(device_t);
160 static device_method_t t5_methods[] = {
161 	DEVMETHOD(device_probe,		t5_probe),
162 	DEVMETHOD(device_attach,	t4_attach),
163 	DEVMETHOD(device_detach,	t4_detach),
164 
165 	DEVMETHOD(bus_child_location_str, t4_child_location_str),
166 
167 	DEVMETHOD(t4_is_main_ready,	t4_ready),
168 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
169 
170 	DEVMETHOD_END
171 };
172 static driver_t t5_driver = {
173 	"t5nex",
174 	t5_methods,
175 	sizeof(struct adapter)
176 };
177 
178 
179 /* T5 port (cxl) interface */
180 static driver_t cxl_driver = {
181 	"cxl",
182 	cxgbe_methods,
183 	sizeof(struct port_info)
184 };
185 
186 /* T5 VI (vcxl) interface */
187 static driver_t vcxl_driver = {
188 	"vcxl",
189 	vcxgbe_methods,
190 	sizeof(struct vi_info)
191 };
192 
193 /* T6 bus driver interface */
194 static int t6_probe(device_t);
195 static device_method_t t6_methods[] = {
196 	DEVMETHOD(device_probe,		t6_probe),
197 	DEVMETHOD(device_attach,	t4_attach),
198 	DEVMETHOD(device_detach,	t4_detach),
199 
200 	DEVMETHOD(bus_child_location_str, t4_child_location_str),
201 
202 	DEVMETHOD(t4_is_main_ready,	t4_ready),
203 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
204 
205 	DEVMETHOD_END
206 };
207 static driver_t t6_driver = {
208 	"t6nex",
209 	t6_methods,
210 	sizeof(struct adapter)
211 };
212 
213 
214 /* T6 port (cc) interface */
215 static driver_t cc_driver = {
216 	"cc",
217 	cxgbe_methods,
218 	sizeof(struct port_info)
219 };
220 
221 /* T6 VI (vcc) interface */
222 static driver_t vcc_driver = {
223 	"vcc",
224 	vcxgbe_methods,
225 	sizeof(struct vi_info)
226 };
227 
228 /* ifnet interface */
229 static void cxgbe_init(void *);
230 static int cxgbe_ioctl(struct ifnet *, unsigned long, caddr_t);
231 static int cxgbe_transmit(struct ifnet *, struct mbuf *);
232 static void cxgbe_qflush(struct ifnet *);
233 
234 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
235 
236 /*
237  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
238  * then ADAPTER_LOCK, then t4_uld_list_lock.
239  */
240 static struct sx t4_list_lock;
241 SLIST_HEAD(, adapter) t4_list;
242 #ifdef TCP_OFFLOAD
243 static struct sx t4_uld_list_lock;
244 SLIST_HEAD(, uld_info) t4_uld_list;
245 #endif
246 
247 /*
248  * Tunables.  See tweak_tunables() too.
249  *
250  * Each tunable is set to a default value here if it's known at compile-time.
251  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
252  * provide a reasonable default (upto n) when the driver is loaded.
253  *
254  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
255  * T5 are under hw.cxl.
256  */
257 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD, 0, "cxgbe(4) parameters");
258 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD, 0, "cxgbe(4) T5+ parameters");
259 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD, 0, "cxgbe(4) TOE parameters");
260 
261 /*
262  * Number of queues for tx and rx, NIC and offload.
263  */
264 #define NTXQ 16
265 int t4_ntxq = -NTXQ;
266 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
267     "Number of TX queues per port");
268 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);	/* Old name, undocumented */
269 
270 #define NRXQ 8
271 int t4_nrxq = -NRXQ;
272 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
273     "Number of RX queues per port");
274 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);	/* Old name, undocumented */
275 
276 #define NTXQ_VI 1
277 static int t4_ntxq_vi = -NTXQ_VI;
278 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
279     "Number of TX queues per VI");
280 
281 #define NRXQ_VI 1
282 static int t4_nrxq_vi = -NRXQ_VI;
283 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
284     "Number of RX queues per VI");
285 
286 static int t4_rsrv_noflowq = 0;
287 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
288     0, "Reserve TX queue 0 of each VI for non-flowid packets");
289 
290 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
291 #define NOFLDTXQ 8
292 static int t4_nofldtxq = -NOFLDTXQ;
293 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
294     "Number of offload TX queues per port");
295 
296 #define NOFLDRXQ 2
297 static int t4_nofldrxq = -NOFLDRXQ;
298 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
299     "Number of offload RX queues per port");
300 
301 #define NOFLDTXQ_VI 1
302 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
303 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
304     "Number of offload TX queues per VI");
305 
306 #define NOFLDRXQ_VI 1
307 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
308 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
309     "Number of offload RX queues per VI");
310 
311 #define TMR_IDX_OFLD 1
312 int t4_tmr_idx_ofld = TMR_IDX_OFLD;
313 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
314     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
315 
316 #define PKTC_IDX_OFLD (-1)
317 int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
318 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
319     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
320 
321 /* 0 means chip/fw default, non-zero number is value in microseconds */
322 static u_long t4_toe_keepalive_idle = 0;
323 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
324     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
325 
326 /* 0 means chip/fw default, non-zero number is value in microseconds */
327 static u_long t4_toe_keepalive_interval = 0;
328 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
329     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
330 
331 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
332 static int t4_toe_keepalive_count = 0;
333 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
334     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
335 
336 /* 0 means chip/fw default, non-zero number is value in microseconds */
337 static u_long t4_toe_rexmt_min = 0;
338 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
339     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
340 
341 /* 0 means chip/fw default, non-zero number is value in microseconds */
342 static u_long t4_toe_rexmt_max = 0;
343 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
344     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
345 
346 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
347 static int t4_toe_rexmt_count = 0;
348 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
349     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
350 
351 /* -1 means chip/fw default, other values are raw backoff values to use */
352 static int t4_toe_rexmt_backoff[16] = {
353 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
354 };
355 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff, CTLFLAG_RD, 0,
356     "cxgbe(4) TOE retransmit backoff values");
357 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
358     &t4_toe_rexmt_backoff[0], 0, "");
359 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
360     &t4_toe_rexmt_backoff[1], 0, "");
361 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
362     &t4_toe_rexmt_backoff[2], 0, "");
363 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
364     &t4_toe_rexmt_backoff[3], 0, "");
365 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
366     &t4_toe_rexmt_backoff[4], 0, "");
367 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
368     &t4_toe_rexmt_backoff[5], 0, "");
369 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
370     &t4_toe_rexmt_backoff[6], 0, "");
371 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
372     &t4_toe_rexmt_backoff[7], 0, "");
373 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
374     &t4_toe_rexmt_backoff[8], 0, "");
375 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
376     &t4_toe_rexmt_backoff[9], 0, "");
377 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
378     &t4_toe_rexmt_backoff[10], 0, "");
379 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
380     &t4_toe_rexmt_backoff[11], 0, "");
381 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
382     &t4_toe_rexmt_backoff[12], 0, "");
383 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
384     &t4_toe_rexmt_backoff[13], 0, "");
385 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
386     &t4_toe_rexmt_backoff[14], 0, "");
387 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
388     &t4_toe_rexmt_backoff[15], 0, "");
389 #endif
390 
391 #ifdef DEV_NETMAP
392 #define NNMTXQ_VI 2
393 static int t4_nnmtxq_vi = -NNMTXQ_VI;
394 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
395     "Number of netmap TX queues per VI");
396 
397 #define NNMRXQ_VI 2
398 static int t4_nnmrxq_vi = -NNMRXQ_VI;
399 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
400     "Number of netmap RX queues per VI");
401 #endif
402 
403 /*
404  * Holdoff parameters for ports.
405  */
406 #define TMR_IDX 1
407 int t4_tmr_idx = TMR_IDX;
408 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
409     0, "Holdoff timer index");
410 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);	/* Old name */
411 
412 #define PKTC_IDX (-1)
413 int t4_pktc_idx = PKTC_IDX;
414 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
415     0, "Holdoff packet counter index");
416 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);	/* Old name */
417 
418 /*
419  * Size (# of entries) of each tx and rx queue.
420  */
421 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
422 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
423     "Number of descriptors in each TX queue");
424 
425 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
426 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
427     "Number of descriptors in each RX queue");
428 
429 /*
430  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
431  */
432 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
433 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
434     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
435 
436 /*
437  * Configuration file.  All the _CF names here are special.
438  */
439 #define DEFAULT_CF	"default"
440 #define BUILTIN_CF	"built-in"
441 #define FLASH_CF	"flash"
442 #define UWIRE_CF	"uwire"
443 #define FPGA_CF		"fpga"
444 static char t4_cfg_file[32] = DEFAULT_CF;
445 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
446     sizeof(t4_cfg_file), "Firmware configuration file");
447 
448 /*
449  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
450  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
451  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
452  *            mark or when signalled to do so, 0 to never emit PAUSE.
453  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
454  *                 negotiated settings will override rx_pause/tx_pause.
455  *                 Otherwise rx_pause/tx_pause are applied forcibly.
456  */
457 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
458 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
459     &t4_pause_settings, 0,
460     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
461 
462 /*
463  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
464  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
465  *  0 to disable FEC.
466  */
467 static int t4_fec = -1;
468 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
469     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
470 
471 /*
472  * Link autonegotiation.
473  * -1 to run with the firmware default.
474  *  0 to disable.
475  *  1 to enable.
476  */
477 static int t4_autoneg = -1;
478 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
479     "Link autonegotiation");
480 
481 /*
482  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
483  * encouraged respectively).  '-n' is the same as 'n' except the firmware
484  * version used in the checks is read from the firmware bundled with the driver.
485  */
486 static int t4_fw_install = 1;
487 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
488     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
489 
490 /*
491  * ASIC features that will be used.  Disable the ones you don't want so that the
492  * chip resources aren't wasted on features that will not be used.
493  */
494 static int t4_nbmcaps_allowed = 0;
495 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
496     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
497 
498 static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
499 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
500     &t4_linkcaps_allowed, 0, "Default link capabilities");
501 
502 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
503     FW_CAPS_CONFIG_SWITCH_EGRESS;
504 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
505     &t4_switchcaps_allowed, 0, "Default switch capabilities");
506 
507 #ifdef RATELIMIT
508 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
509 	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
510 #else
511 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
512 	FW_CAPS_CONFIG_NIC_HASHFILTER;
513 #endif
514 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
515     &t4_niccaps_allowed, 0, "Default NIC capabilities");
516 
517 static int t4_toecaps_allowed = -1;
518 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
519     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
520 
521 static int t4_rdmacaps_allowed = -1;
522 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
523     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
524 
525 static int t4_cryptocaps_allowed = -1;
526 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
527     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
528 
529 static int t4_iscsicaps_allowed = -1;
530 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
531     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
532 
533 static int t4_fcoecaps_allowed = 0;
534 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
535     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
536 
537 static int t5_write_combine = 0;
538 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
539     0, "Use WC instead of UC for BAR2");
540 
541 static int t4_num_vis = 1;
542 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
543     "Number of VIs per port");
544 
545 /*
546  * PCIe Relaxed Ordering.
547  * -1: driver should figure out a good value.
548  * 0: disable RO.
549  * 1: enable RO.
550  * 2: leave RO alone.
551  */
552 static int pcie_relaxed_ordering = -1;
553 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
554     &pcie_relaxed_ordering, 0,
555     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
556 
557 static int t4_panic_on_fatal_err = 0;
558 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RDTUN,
559     &t4_panic_on_fatal_err, 0, "panic on fatal firmware errors");
560 
561 #ifdef TCP_OFFLOAD
562 /*
563  * TOE tunables.
564  */
565 static int t4_cop_managed_offloading = 0;
566 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
567     &t4_cop_managed_offloading, 0,
568     "COP (Connection Offload Policy) controls all TOE offload");
569 #endif
570 
571 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
572 static int vi_mac_funcs[] = {
573 	FW_VI_FUNC_ETH,
574 	FW_VI_FUNC_OFLD,
575 	FW_VI_FUNC_IWARP,
576 	FW_VI_FUNC_OPENISCSI,
577 	FW_VI_FUNC_OPENFCOE,
578 	FW_VI_FUNC_FOISCSI,
579 	FW_VI_FUNC_FOFCOE,
580 };
581 
582 struct intrs_and_queues {
583 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
584 	uint16_t num_vis;	/* number of VIs for each port */
585 	uint16_t nirq;		/* Total # of vectors */
586 	uint16_t ntxq;		/* # of NIC txq's for each port */
587 	uint16_t nrxq;		/* # of NIC rxq's for each port */
588 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
589 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
590 
591 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
592 	uint16_t ntxq_vi;	/* # of NIC txq's */
593 	uint16_t nrxq_vi;	/* # of NIC rxq's */
594 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
595 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
596 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
597 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
598 };
599 
600 static void setup_memwin(struct adapter *);
601 static void position_memwin(struct adapter *, int, uint32_t);
602 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
603 static int fwmtype_to_hwmtype(int);
604 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
605     uint32_t *);
606 static int fixup_devlog_params(struct adapter *);
607 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
608 static int contact_firmware(struct adapter *);
609 static int partition_resources(struct adapter *);
610 static int get_params__pre_init(struct adapter *);
611 static int get_params__post_init(struct adapter *);
612 static int set_params__post_init(struct adapter *);
613 static void t4_set_desc(struct adapter *);
614 static bool fixed_ifmedia(struct port_info *);
615 static void build_medialist(struct port_info *);
616 static void init_link_config(struct port_info *);
617 static int fixup_link_config(struct port_info *);
618 static int apply_link_config(struct port_info *);
619 static int cxgbe_init_synchronized(struct vi_info *);
620 static int cxgbe_uninit_synchronized(struct vi_info *);
621 static void quiesce_txq(struct adapter *, struct sge_txq *);
622 static void quiesce_wrq(struct adapter *, struct sge_wrq *);
623 static void quiesce_iq(struct adapter *, struct sge_iq *);
624 static void quiesce_fl(struct adapter *, struct sge_fl *);
625 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
626     driver_intr_t *, void *, char *);
627 static int t4_free_irq(struct adapter *, struct irq *);
628 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
629 static void vi_refresh_stats(struct adapter *, struct vi_info *);
630 static void cxgbe_refresh_stats(struct adapter *, struct port_info *);
631 static void cxgbe_tick(void *);
632 static void cxgbe_sysctls(struct port_info *);
633 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
634 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
635 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
636 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
637 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
638 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
639 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
640 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
641 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
642 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
643 static int sysctl_fec(SYSCTL_HANDLER_ARGS);
644 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
645 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
646 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
647 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
648 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
649 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
650 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
651 static int sysctl_cim_la_t6(SYSCTL_HANDLER_ARGS);
652 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
653 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
654 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
655 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
656 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
657 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
658 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
659 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
660 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
661 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
662 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
663 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
664 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
665 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
666 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
667 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
668 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
669 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
670 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
671 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
672 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
673 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
674 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
675 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
676 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
677 #ifdef TCP_OFFLOAD
678 static int sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS);
679 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
680 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
681 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
682 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
683 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
684 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
685 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
686 #endif
687 static int get_sge_context(struct adapter *, struct t4_sge_context *);
688 static int load_fw(struct adapter *, struct t4_data *);
689 static int load_cfg(struct adapter *, struct t4_data *);
690 static int load_boot(struct adapter *, struct t4_bootrom *);
691 static int load_bootcfg(struct adapter *, struct t4_data *);
692 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
693 static void free_offload_policy(struct t4_offload_policy *);
694 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
695 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
696 static int read_i2c(struct adapter *, struct t4_i2c_data *);
697 #ifdef TCP_OFFLOAD
698 static int toe_capability(struct vi_info *, int);
699 #endif
700 static int mod_event(module_t, int, void *);
701 static int notify_siblings(device_t, int);
702 
703 struct {
704 	uint16_t device;
705 	char *desc;
706 } t4_pciids[] = {
707 	{0xa000, "Chelsio Terminator 4 FPGA"},
708 	{0x4400, "Chelsio T440-dbg"},
709 	{0x4401, "Chelsio T420-CR"},
710 	{0x4402, "Chelsio T422-CR"},
711 	{0x4403, "Chelsio T440-CR"},
712 	{0x4404, "Chelsio T420-BCH"},
713 	{0x4405, "Chelsio T440-BCH"},
714 	{0x4406, "Chelsio T440-CH"},
715 	{0x4407, "Chelsio T420-SO"},
716 	{0x4408, "Chelsio T420-CX"},
717 	{0x4409, "Chelsio T420-BT"},
718 	{0x440a, "Chelsio T404-BT"},
719 	{0x440e, "Chelsio T440-LP-CR"},
720 }, t5_pciids[] = {
721 	{0xb000, "Chelsio Terminator 5 FPGA"},
722 	{0x5400, "Chelsio T580-dbg"},
723 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
724 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
725 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
726 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
727 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
728 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
729 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
730 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
731 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
732 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
733 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
734 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
735 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
736 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
737 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
738 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
739 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
740 
741 	/* Custom */
742 	{0x5483, "Custom T540-CR"},
743 	{0x5484, "Custom T540-BT"},
744 }, t6_pciids[] = {
745 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
746 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
747 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
748 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
749 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
750 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
751 	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
752 	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
753 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
754 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
755 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
756 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
757 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
758 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
759 	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
760 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
761 
762 	/* Custom */
763 	{0x6480, "Custom T6225-CR"},
764 	{0x6481, "Custom T62100-CR"},
765 	{0x6482, "Custom T6225-CR"},
766 	{0x6483, "Custom T62100-CR"},
767 	{0x6484, "Custom T64100-CR"},
768 	{0x6485, "Custom T6240-SO"},
769 	{0x6486, "Custom T6225-SO-CR"},
770 	{0x6487, "Custom T6225-CR"},
771 };
772 
773 #ifdef TCP_OFFLOAD
774 /*
775  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
776  * be exactly the same for both rxq and ofld_rxq.
777  */
778 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
779 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
780 #endif
781 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
782 
783 static int
784 t4_probe(device_t dev)
785 {
786 	int i;
787 	uint16_t v = pci_get_vendor(dev);
788 	uint16_t d = pci_get_device(dev);
789 	uint8_t f = pci_get_function(dev);
790 
791 	if (v != PCI_VENDOR_ID_CHELSIO)
792 		return (ENXIO);
793 
794 	/* Attach only to PF0 of the FPGA */
795 	if (d == 0xa000 && f != 0)
796 		return (ENXIO);
797 
798 	for (i = 0; i < nitems(t4_pciids); i++) {
799 		if (d == t4_pciids[i].device) {
800 			device_set_desc(dev, t4_pciids[i].desc);
801 			return (BUS_PROBE_DEFAULT);
802 		}
803 	}
804 
805 	return (ENXIO);
806 }
807 
808 static int
809 t5_probe(device_t dev)
810 {
811 	int i;
812 	uint16_t v = pci_get_vendor(dev);
813 	uint16_t d = pci_get_device(dev);
814 	uint8_t f = pci_get_function(dev);
815 
816 	if (v != PCI_VENDOR_ID_CHELSIO)
817 		return (ENXIO);
818 
819 	/* Attach only to PF0 of the FPGA */
820 	if (d == 0xb000 && f != 0)
821 		return (ENXIO);
822 
823 	for (i = 0; i < nitems(t5_pciids); i++) {
824 		if (d == t5_pciids[i].device) {
825 			device_set_desc(dev, t5_pciids[i].desc);
826 			return (BUS_PROBE_DEFAULT);
827 		}
828 	}
829 
830 	return (ENXIO);
831 }
832 
833 static int
834 t6_probe(device_t dev)
835 {
836 	int i;
837 	uint16_t v = pci_get_vendor(dev);
838 	uint16_t d = pci_get_device(dev);
839 
840 	if (v != PCI_VENDOR_ID_CHELSIO)
841 		return (ENXIO);
842 
843 	for (i = 0; i < nitems(t6_pciids); i++) {
844 		if (d == t6_pciids[i].device) {
845 			device_set_desc(dev, t6_pciids[i].desc);
846 			return (BUS_PROBE_DEFAULT);
847 		}
848 	}
849 
850 	return (ENXIO);
851 }
852 
853 static void
854 t5_attribute_workaround(device_t dev)
855 {
856 	device_t root_port;
857 	uint32_t v;
858 
859 	/*
860 	 * The T5 chips do not properly echo the No Snoop and Relaxed
861 	 * Ordering attributes when replying to a TLP from a Root
862 	 * Port.  As a workaround, find the parent Root Port and
863 	 * disable No Snoop and Relaxed Ordering.  Note that this
864 	 * affects all devices under this root port.
865 	 */
866 	root_port = pci_find_pcie_root_port(dev);
867 	if (root_port == NULL) {
868 		device_printf(dev, "Unable to find parent root port\n");
869 		return;
870 	}
871 
872 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
873 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
874 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
875 	    0)
876 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
877 		    device_get_nameunit(root_port));
878 }
879 
880 static const struct devnames devnames[] = {
881 	{
882 		.nexus_name = "t4nex",
883 		.ifnet_name = "cxgbe",
884 		.vi_ifnet_name = "vcxgbe",
885 		.pf03_drv_name = "t4iov",
886 		.vf_nexus_name = "t4vf",
887 		.vf_ifnet_name = "cxgbev"
888 	}, {
889 		.nexus_name = "t5nex",
890 		.ifnet_name = "cxl",
891 		.vi_ifnet_name = "vcxl",
892 		.pf03_drv_name = "t5iov",
893 		.vf_nexus_name = "t5vf",
894 		.vf_ifnet_name = "cxlv"
895 	}, {
896 		.nexus_name = "t6nex",
897 		.ifnet_name = "cc",
898 		.vi_ifnet_name = "vcc",
899 		.pf03_drv_name = "t6iov",
900 		.vf_nexus_name = "t6vf",
901 		.vf_ifnet_name = "ccv"
902 	}
903 };
904 
905 void
906 t4_init_devnames(struct adapter *sc)
907 {
908 	int id;
909 
910 	id = chip_id(sc);
911 	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
912 		sc->names = &devnames[id - CHELSIO_T4];
913 	else {
914 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
915 		sc->names = NULL;
916 	}
917 }
918 
919 static int
920 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
921 {
922 	const char *parent, *name;
923 	long value;
924 	int line, unit;
925 
926 	line = 0;
927 	parent = device_get_nameunit(sc->dev);
928 	name = sc->names->ifnet_name;
929 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
930 		if (resource_long_value(name, unit, "port", &value) == 0 &&
931 		    value == pi->port_id)
932 			return (unit);
933 	}
934 	return (-1);
935 }
936 
937 static int
938 t4_attach(device_t dev)
939 {
940 	struct adapter *sc;
941 	int rc = 0, i, j, rqidx, tqidx, nports;
942 	struct make_dev_args mda;
943 	struct intrs_and_queues iaq;
944 	struct sge *s;
945 	uint32_t *buf;
946 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
947 	int ofld_tqidx;
948 #endif
949 #ifdef TCP_OFFLOAD
950 	int ofld_rqidx;
951 #endif
952 #ifdef DEV_NETMAP
953 	int nm_rqidx, nm_tqidx;
954 #endif
955 	int num_vis;
956 
957 	sc = device_get_softc(dev);
958 	sc->dev = dev;
959 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
960 
961 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
962 		t5_attribute_workaround(dev);
963 	pci_enable_busmaster(dev);
964 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
965 		uint32_t v;
966 
967 		pci_set_max_read_req(dev, 4096);
968 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
969 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
970 		if (pcie_relaxed_ordering == 0 &&
971 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
972 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
973 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
974 		} else if (pcie_relaxed_ordering == 1 &&
975 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
976 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
977 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
978 		}
979 	}
980 
981 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
982 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
983 	sc->traceq = -1;
984 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
985 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
986 	    device_get_nameunit(dev));
987 
988 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
989 	    device_get_nameunit(dev));
990 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
991 	t4_add_adapter(sc);
992 
993 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
994 	TAILQ_INIT(&sc->sfl);
995 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
996 
997 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
998 
999 	sc->policy = NULL;
1000 	rw_init(&sc->policy_lock, "connection offload policy");
1001 
1002 	rc = t4_map_bars_0_and_4(sc);
1003 	if (rc != 0)
1004 		goto done; /* error message displayed already */
1005 
1006 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1007 
1008 	/* Prepare the adapter for operation. */
1009 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1010 	rc = -t4_prep_adapter(sc, buf);
1011 	free(buf, M_CXGBE);
1012 	if (rc != 0) {
1013 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1014 		goto done;
1015 	}
1016 
1017 	/*
1018 	 * This is the real PF# to which we're attaching.  Works from within PCI
1019 	 * passthrough environments too, where pci_get_function() could return a
1020 	 * different PF# depending on the passthrough configuration.  We need to
1021 	 * use the real PF# in all our communication with the firmware.
1022 	 */
1023 	j = t4_read_reg(sc, A_PL_WHOAMI);
1024 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1025 	sc->mbox = sc->pf;
1026 
1027 	t4_init_devnames(sc);
1028 	if (sc->names == NULL) {
1029 		rc = ENOTSUP;
1030 		goto done; /* error message displayed already */
1031 	}
1032 
1033 	/*
1034 	 * Do this really early, with the memory windows set up even before the
1035 	 * character device.  The userland tool's register i/o and mem read
1036 	 * will work even in "recovery mode".
1037 	 */
1038 	setup_memwin(sc);
1039 	if (t4_init_devlog_params(sc, 0) == 0)
1040 		fixup_devlog_params(sc);
1041 	make_dev_args_init(&mda);
1042 	mda.mda_devsw = &t4_cdevsw;
1043 	mda.mda_uid = UID_ROOT;
1044 	mda.mda_gid = GID_WHEEL;
1045 	mda.mda_mode = 0600;
1046 	mda.mda_si_drv1 = sc;
1047 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1048 	if (rc != 0)
1049 		device_printf(dev, "failed to create nexus char device: %d.\n",
1050 		    rc);
1051 
1052 	/* Go no further if recovery mode has been requested. */
1053 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1054 		device_printf(dev, "recovery mode.\n");
1055 		goto done;
1056 	}
1057 
1058 #if defined(__i386__)
1059 	if ((cpu_feature & CPUID_CX8) == 0) {
1060 		device_printf(dev, "64 bit atomics not available.\n");
1061 		rc = ENOTSUP;
1062 		goto done;
1063 	}
1064 #endif
1065 
1066 	/* Contact the firmware and try to become the master driver. */
1067 	rc = contact_firmware(sc);
1068 	if (rc != 0)
1069 		goto done; /* error message displayed already */
1070 	MPASS(sc->flags & FW_OK);
1071 
1072 	rc = get_params__pre_init(sc);
1073 	if (rc != 0)
1074 		goto done; /* error message displayed already */
1075 
1076 	if (sc->flags & MASTER_PF) {
1077 		rc = partition_resources(sc);
1078 		if (rc != 0)
1079 			goto done; /* error message displayed already */
1080 	}
1081 
1082 	rc = get_params__post_init(sc);
1083 	if (rc != 0)
1084 		goto done; /* error message displayed already */
1085 
1086 	rc = set_params__post_init(sc);
1087 	if (rc != 0)
1088 		goto done; /* error message displayed already */
1089 
1090 	rc = t4_map_bar_2(sc);
1091 	if (rc != 0)
1092 		goto done; /* error message displayed already */
1093 
1094 	rc = t4_create_dma_tag(sc);
1095 	if (rc != 0)
1096 		goto done; /* error message displayed already */
1097 
1098 	/*
1099 	 * First pass over all the ports - allocate VIs and initialize some
1100 	 * basic parameters like mac address, port type, etc.
1101 	 */
1102 	for_each_port(sc, i) {
1103 		struct port_info *pi;
1104 
1105 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1106 		sc->port[i] = pi;
1107 
1108 		/* These must be set before t4_port_init */
1109 		pi->adapter = sc;
1110 		pi->port_id = i;
1111 		/*
1112 		 * XXX: vi[0] is special so we can't delay this allocation until
1113 		 * pi->nvi's final value is known.
1114 		 */
1115 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1116 		    M_ZERO | M_WAITOK);
1117 
1118 		/*
1119 		 * Allocate the "main" VI and initialize parameters
1120 		 * like mac addr.
1121 		 */
1122 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1123 		if (rc != 0) {
1124 			device_printf(dev, "unable to initialize port %d: %d\n",
1125 			    i, rc);
1126 			free(pi->vi, M_CXGBE);
1127 			free(pi, M_CXGBE);
1128 			sc->port[i] = NULL;
1129 			goto done;
1130 		}
1131 
1132 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1133 		    device_get_nameunit(dev), i);
1134 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1135 		sc->chan_map[pi->tx_chan] = i;
1136 
1137 		/* All VIs on this port share this media. */
1138 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1139 		    cxgbe_media_status);
1140 
1141 		PORT_LOCK(pi);
1142 		init_link_config(pi);
1143 		fixup_link_config(pi);
1144 		build_medialist(pi);
1145 		if (fixed_ifmedia(pi))
1146 			pi->flags |= FIXED_IFMEDIA;
1147 		PORT_UNLOCK(pi);
1148 
1149 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1150 		    t4_ifnet_unit(sc, pi));
1151 		if (pi->dev == NULL) {
1152 			device_printf(dev,
1153 			    "failed to add device for port %d.\n", i);
1154 			rc = ENXIO;
1155 			goto done;
1156 		}
1157 		pi->vi[0].dev = pi->dev;
1158 		device_set_softc(pi->dev, pi);
1159 	}
1160 
1161 	/*
1162 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1163 	 */
1164 	nports = sc->params.nports;
1165 	rc = cfg_itype_and_nqueues(sc, &iaq);
1166 	if (rc != 0)
1167 		goto done; /* error message displayed already */
1168 
1169 	num_vis = iaq.num_vis;
1170 	sc->intr_type = iaq.intr_type;
1171 	sc->intr_count = iaq.nirq;
1172 
1173 	s = &sc->sge;
1174 	s->nrxq = nports * iaq.nrxq;
1175 	s->ntxq = nports * iaq.ntxq;
1176 	if (num_vis > 1) {
1177 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1178 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1179 	}
1180 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1181 	s->neq += nports;		/* ctrl queues: 1 per port */
1182 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1183 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1184 	if (is_offload(sc) || is_ethoffload(sc)) {
1185 		s->nofldtxq = nports * iaq.nofldtxq;
1186 		if (num_vis > 1)
1187 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1188 		s->neq += s->nofldtxq;
1189 
1190 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_wrq),
1191 		    M_CXGBE, M_ZERO | M_WAITOK);
1192 	}
1193 #endif
1194 #ifdef TCP_OFFLOAD
1195 	if (is_offload(sc)) {
1196 		s->nofldrxq = nports * iaq.nofldrxq;
1197 		if (num_vis > 1)
1198 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1199 		s->neq += s->nofldrxq;	/* free list */
1200 		s->niq += s->nofldrxq;
1201 
1202 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1203 		    M_CXGBE, M_ZERO | M_WAITOK);
1204 	}
1205 #endif
1206 #ifdef DEV_NETMAP
1207 	if (num_vis > 1) {
1208 		s->nnmrxq = nports * (num_vis - 1) * iaq.nnmrxq_vi;
1209 		s->nnmtxq = nports * (num_vis - 1) * iaq.nnmtxq_vi;
1210 	}
1211 	s->neq += s->nnmtxq + s->nnmrxq;
1212 	s->niq += s->nnmrxq;
1213 
1214 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1215 	    M_CXGBE, M_ZERO | M_WAITOK);
1216 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1217 	    M_CXGBE, M_ZERO | M_WAITOK);
1218 #endif
1219 
1220 	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1221 	    M_ZERO | M_WAITOK);
1222 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1223 	    M_ZERO | M_WAITOK);
1224 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1225 	    M_ZERO | M_WAITOK);
1226 	s->iqmap = malloc(s->niq * sizeof(struct sge_iq *), M_CXGBE,
1227 	    M_ZERO | M_WAITOK);
1228 	s->eqmap = malloc(s->neq * sizeof(struct sge_eq *), M_CXGBE,
1229 	    M_ZERO | M_WAITOK);
1230 
1231 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1232 	    M_ZERO | M_WAITOK);
1233 
1234 	t4_init_l2t(sc, M_WAITOK);
1235 	t4_init_smt(sc, M_WAITOK);
1236 	t4_init_tx_sched(sc);
1237 #ifdef RATELIMIT
1238 	t4_init_etid_table(sc);
1239 #endif
1240 #ifdef INET6
1241 	t4_init_clip_table(sc);
1242 #endif
1243 	if (sc->vres.key.size != 0)
1244 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1245 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1246 
1247 	/*
1248 	 * Second pass over the ports.  This time we know the number of rx and
1249 	 * tx queues that each port should get.
1250 	 */
1251 	rqidx = tqidx = 0;
1252 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1253 	ofld_tqidx = 0;
1254 #endif
1255 #ifdef TCP_OFFLOAD
1256 	ofld_rqidx = 0;
1257 #endif
1258 #ifdef DEV_NETMAP
1259 	nm_rqidx = nm_tqidx = 0;
1260 #endif
1261 	for_each_port(sc, i) {
1262 		struct port_info *pi = sc->port[i];
1263 		struct vi_info *vi;
1264 
1265 		if (pi == NULL)
1266 			continue;
1267 
1268 		pi->nvi = num_vis;
1269 		for_each_vi(pi, j, vi) {
1270 			vi->pi = pi;
1271 			vi->qsize_rxq = t4_qsize_rxq;
1272 			vi->qsize_txq = t4_qsize_txq;
1273 
1274 			vi->first_rxq = rqidx;
1275 			vi->first_txq = tqidx;
1276 			vi->tmr_idx = t4_tmr_idx;
1277 			vi->pktc_idx = t4_pktc_idx;
1278 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1279 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1280 
1281 			rqidx += vi->nrxq;
1282 			tqidx += vi->ntxq;
1283 
1284 			if (j == 0 && vi->ntxq > 1)
1285 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1286 			else
1287 				vi->rsrv_noflowq = 0;
1288 
1289 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1290 			vi->first_ofld_txq = ofld_tqidx;
1291 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1292 			ofld_tqidx += vi->nofldtxq;
1293 #endif
1294 #ifdef TCP_OFFLOAD
1295 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1296 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1297 			vi->first_ofld_rxq = ofld_rqidx;
1298 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1299 
1300 			ofld_rqidx += vi->nofldrxq;
1301 #endif
1302 #ifdef DEV_NETMAP
1303 			if (j > 0) {
1304 				vi->first_nm_rxq = nm_rqidx;
1305 				vi->first_nm_txq = nm_tqidx;
1306 				vi->nnmrxq = iaq.nnmrxq_vi;
1307 				vi->nnmtxq = iaq.nnmtxq_vi;
1308 				nm_rqidx += vi->nnmrxq;
1309 				nm_tqidx += vi->nnmtxq;
1310 			}
1311 #endif
1312 		}
1313 	}
1314 
1315 	rc = t4_setup_intr_handlers(sc);
1316 	if (rc != 0) {
1317 		device_printf(dev,
1318 		    "failed to setup interrupt handlers: %d\n", rc);
1319 		goto done;
1320 	}
1321 
1322 	rc = bus_generic_probe(dev);
1323 	if (rc != 0) {
1324 		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1325 		goto done;
1326 	}
1327 
1328 	/*
1329 	 * Ensure thread-safe mailbox access (in debug builds).
1330 	 *
1331 	 * So far this was the only thread accessing the mailbox but various
1332 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1333 	 * will access the mailbox from different threads.
1334 	 */
1335 	sc->flags |= CHK_MBOX_ACCESS;
1336 
1337 	rc = bus_generic_attach(dev);
1338 	if (rc != 0) {
1339 		device_printf(dev,
1340 		    "failed to attach all child ports: %d\n", rc);
1341 		goto done;
1342 	}
1343 
1344 	device_printf(dev,
1345 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1346 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1347 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1348 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1349 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1350 
1351 	t4_set_desc(sc);
1352 
1353 	notify_siblings(dev, 0);
1354 
1355 done:
1356 	if (rc != 0 && sc->cdev) {
1357 		/* cdev was created and so cxgbetool works; recover that way. */
1358 		device_printf(dev,
1359 		    "error during attach, adapter is now in recovery mode.\n");
1360 		rc = 0;
1361 	}
1362 
1363 	if (rc != 0)
1364 		t4_detach_common(dev);
1365 	else
1366 		t4_sysctls(sc);
1367 
1368 	return (rc);
1369 }
1370 
1371 static int
1372 t4_child_location_str(device_t bus, device_t dev, char *buf, size_t buflen)
1373 {
1374 	struct port_info *pi;
1375 
1376 	pi = device_get_softc(dev);
1377 	snprintf(buf, buflen, "port=%d", pi->port_id);
1378 	return (0);
1379 }
1380 
1381 static int
1382 t4_ready(device_t dev)
1383 {
1384 	struct adapter *sc;
1385 
1386 	sc = device_get_softc(dev);
1387 	if (sc->flags & FW_OK)
1388 		return (0);
1389 	return (ENXIO);
1390 }
1391 
1392 static int
1393 t4_read_port_device(device_t dev, int port, device_t *child)
1394 {
1395 	struct adapter *sc;
1396 	struct port_info *pi;
1397 
1398 	sc = device_get_softc(dev);
1399 	if (port < 0 || port >= MAX_NPORTS)
1400 		return (EINVAL);
1401 	pi = sc->port[port];
1402 	if (pi == NULL || pi->dev == NULL)
1403 		return (ENXIO);
1404 	*child = pi->dev;
1405 	return (0);
1406 }
1407 
1408 static int
1409 notify_siblings(device_t dev, int detaching)
1410 {
1411 	device_t sibling;
1412 	int error, i;
1413 
1414 	error = 0;
1415 	for (i = 0; i < PCI_FUNCMAX; i++) {
1416 		if (i == pci_get_function(dev))
1417 			continue;
1418 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1419 		    pci_get_slot(dev), i);
1420 		if (sibling == NULL || !device_is_attached(sibling))
1421 			continue;
1422 		if (detaching)
1423 			error = T4_DETACH_CHILD(sibling);
1424 		else
1425 			(void)T4_ATTACH_CHILD(sibling);
1426 		if (error)
1427 			break;
1428 	}
1429 	return (error);
1430 }
1431 
1432 /*
1433  * Idempotent
1434  */
1435 static int
1436 t4_detach(device_t dev)
1437 {
1438 	struct adapter *sc;
1439 	int rc;
1440 
1441 	sc = device_get_softc(dev);
1442 
1443 	rc = notify_siblings(dev, 1);
1444 	if (rc) {
1445 		device_printf(dev,
1446 		    "failed to detach sibling devices: %d\n", rc);
1447 		return (rc);
1448 	}
1449 
1450 	return (t4_detach_common(dev));
1451 }
1452 
1453 int
1454 t4_detach_common(device_t dev)
1455 {
1456 	struct adapter *sc;
1457 	struct port_info *pi;
1458 	int i, rc;
1459 
1460 	sc = device_get_softc(dev);
1461 
1462 	if (sc->cdev) {
1463 		destroy_dev(sc->cdev);
1464 		sc->cdev = NULL;
1465 	}
1466 
1467 	sc->flags &= ~CHK_MBOX_ACCESS;
1468 	if (sc->flags & FULL_INIT_DONE) {
1469 		if (!(sc->flags & IS_VF))
1470 			t4_intr_disable(sc);
1471 	}
1472 
1473 	if (device_is_attached(dev)) {
1474 		rc = bus_generic_detach(dev);
1475 		if (rc) {
1476 			device_printf(dev,
1477 			    "failed to detach child devices: %d\n", rc);
1478 			return (rc);
1479 		}
1480 	}
1481 
1482 	for (i = 0; i < sc->intr_count; i++)
1483 		t4_free_irq(sc, &sc->irq[i]);
1484 
1485 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1486 		t4_free_tx_sched(sc);
1487 
1488 	for (i = 0; i < MAX_NPORTS; i++) {
1489 		pi = sc->port[i];
1490 		if (pi) {
1491 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1492 			if (pi->dev)
1493 				device_delete_child(dev, pi->dev);
1494 
1495 			mtx_destroy(&pi->pi_lock);
1496 			free(pi->vi, M_CXGBE);
1497 			free(pi, M_CXGBE);
1498 		}
1499 	}
1500 
1501 	device_delete_children(dev);
1502 
1503 	if (sc->flags & FULL_INIT_DONE)
1504 		adapter_full_uninit(sc);
1505 
1506 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1507 		t4_fw_bye(sc, sc->mbox);
1508 
1509 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1510 		pci_release_msi(dev);
1511 
1512 	if (sc->regs_res)
1513 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1514 		    sc->regs_res);
1515 
1516 	if (sc->udbs_res)
1517 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1518 		    sc->udbs_res);
1519 
1520 	if (sc->msix_res)
1521 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1522 		    sc->msix_res);
1523 
1524 	if (sc->l2t)
1525 		t4_free_l2t(sc->l2t);
1526 	if (sc->smt)
1527 		t4_free_smt(sc->smt);
1528 #ifdef RATELIMIT
1529 	t4_free_etid_table(sc);
1530 #endif
1531 	if (sc->key_map)
1532 		vmem_destroy(sc->key_map);
1533 #ifdef INET6
1534 	t4_destroy_clip_table(sc);
1535 #endif
1536 
1537 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1538 	free(sc->sge.ofld_txq, M_CXGBE);
1539 #endif
1540 #ifdef TCP_OFFLOAD
1541 	free(sc->sge.ofld_rxq, M_CXGBE);
1542 #endif
1543 #ifdef DEV_NETMAP
1544 	free(sc->sge.nm_rxq, M_CXGBE);
1545 	free(sc->sge.nm_txq, M_CXGBE);
1546 #endif
1547 	free(sc->irq, M_CXGBE);
1548 	free(sc->sge.rxq, M_CXGBE);
1549 	free(sc->sge.txq, M_CXGBE);
1550 	free(sc->sge.ctrlq, M_CXGBE);
1551 	free(sc->sge.iqmap, M_CXGBE);
1552 	free(sc->sge.eqmap, M_CXGBE);
1553 	free(sc->tids.ftid_tab, M_CXGBE);
1554 	free(sc->tids.hpftid_tab, M_CXGBE);
1555 	free_hftid_hash(&sc->tids);
1556 	free(sc->tids.atid_tab, M_CXGBE);
1557 	free(sc->tids.tid_tab, M_CXGBE);
1558 	free(sc->tt.tls_rx_ports, M_CXGBE);
1559 	t4_destroy_dma_tag(sc);
1560 	if (mtx_initialized(&sc->sc_lock)) {
1561 		sx_xlock(&t4_list_lock);
1562 		SLIST_REMOVE(&t4_list, sc, adapter, link);
1563 		sx_xunlock(&t4_list_lock);
1564 		mtx_destroy(&sc->sc_lock);
1565 	}
1566 
1567 	callout_drain(&sc->sfl_callout);
1568 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1569 		mtx_destroy(&sc->tids.ftid_lock);
1570 		cv_destroy(&sc->tids.ftid_cv);
1571 	}
1572 	if (mtx_initialized(&sc->tids.atid_lock))
1573 		mtx_destroy(&sc->tids.atid_lock);
1574 	if (mtx_initialized(&sc->sfl_lock))
1575 		mtx_destroy(&sc->sfl_lock);
1576 	if (mtx_initialized(&sc->ifp_lock))
1577 		mtx_destroy(&sc->ifp_lock);
1578 	if (mtx_initialized(&sc->reg_lock))
1579 		mtx_destroy(&sc->reg_lock);
1580 
1581 	if (rw_initialized(&sc->policy_lock)) {
1582 		rw_destroy(&sc->policy_lock);
1583 #ifdef TCP_OFFLOAD
1584 		if (sc->policy != NULL)
1585 			free_offload_policy(sc->policy);
1586 #endif
1587 	}
1588 
1589 	for (i = 0; i < NUM_MEMWIN; i++) {
1590 		struct memwin *mw = &sc->memwin[i];
1591 
1592 		if (rw_initialized(&mw->mw_lock))
1593 			rw_destroy(&mw->mw_lock);
1594 	}
1595 
1596 	bzero(sc, sizeof(*sc));
1597 
1598 	return (0);
1599 }
1600 
1601 static int
1602 cxgbe_probe(device_t dev)
1603 {
1604 	char buf[128];
1605 	struct port_info *pi = device_get_softc(dev);
1606 
1607 	snprintf(buf, sizeof(buf), "port %d", pi->port_id);
1608 	device_set_desc_copy(dev, buf);
1609 
1610 	return (BUS_PROBE_DEFAULT);
1611 }
1612 
1613 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
1614     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
1615     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
1616     IFCAP_HWRXTSTMP)
1617 #define T4_CAP_ENABLE (T4_CAP)
1618 
1619 static int
1620 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
1621 {
1622 	struct ifnet *ifp;
1623 	struct sbuf *sb;
1624 
1625 	vi->xact_addr_filt = -1;
1626 	callout_init(&vi->tick, 1);
1627 
1628 	/* Allocate an ifnet and set it up */
1629 	ifp = if_alloc(IFT_ETHER);
1630 	if (ifp == NULL) {
1631 		device_printf(dev, "Cannot allocate ifnet\n");
1632 		return (ENOMEM);
1633 	}
1634 	vi->ifp = ifp;
1635 	ifp->if_softc = vi;
1636 
1637 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1638 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1639 
1640 	ifp->if_init = cxgbe_init;
1641 	ifp->if_ioctl = cxgbe_ioctl;
1642 	ifp->if_transmit = cxgbe_transmit;
1643 	ifp->if_qflush = cxgbe_qflush;
1644 	ifp->if_get_counter = cxgbe_get_counter;
1645 #ifdef RATELIMIT
1646 	ifp->if_snd_tag_alloc = cxgbe_snd_tag_alloc;
1647 	ifp->if_snd_tag_modify = cxgbe_snd_tag_modify;
1648 	ifp->if_snd_tag_query = cxgbe_snd_tag_query;
1649 	ifp->if_snd_tag_free = cxgbe_snd_tag_free;
1650 #endif
1651 
1652 	ifp->if_capabilities = T4_CAP;
1653 	ifp->if_capenable = T4_CAP_ENABLE;
1654 #ifdef TCP_OFFLOAD
1655 	if (vi->nofldrxq != 0)
1656 		ifp->if_capabilities |= IFCAP_TOE;
1657 #endif
1658 #ifdef RATELIMIT
1659 	if (is_ethoffload(vi->pi->adapter) && vi->nofldtxq != 0) {
1660 		ifp->if_capabilities |= IFCAP_TXRTLMT;
1661 		ifp->if_capenable |= IFCAP_TXRTLMT;
1662 	}
1663 #endif
1664 	ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
1665 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6;
1666 
1667 	ifp->if_hw_tsomax = IP_MAXPACKET;
1668 	ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
1669 #ifdef RATELIMIT
1670 	if (is_ethoffload(vi->pi->adapter) && vi->nofldtxq != 0)
1671 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_EO_TSO;
1672 #endif
1673 	ifp->if_hw_tsomaxsegsize = 65536;
1674 
1675 	ether_ifattach(ifp, vi->hw_addr);
1676 #ifdef DEV_NETMAP
1677 	if (vi->nnmrxq != 0)
1678 		cxgbe_nm_attach(vi);
1679 #endif
1680 	sb = sbuf_new_auto();
1681 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
1682 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1683 	switch (ifp->if_capabilities & (IFCAP_TOE | IFCAP_TXRTLMT)) {
1684 	case IFCAP_TOE:
1685 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
1686 		break;
1687 	case IFCAP_TOE | IFCAP_TXRTLMT:
1688 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
1689 		break;
1690 	case IFCAP_TXRTLMT:
1691 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
1692 		break;
1693 	}
1694 #endif
1695 #ifdef TCP_OFFLOAD
1696 	if (ifp->if_capabilities & IFCAP_TOE)
1697 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
1698 #endif
1699 #ifdef DEV_NETMAP
1700 	if (ifp->if_capabilities & IFCAP_NETMAP)
1701 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
1702 		    vi->nnmtxq, vi->nnmrxq);
1703 #endif
1704 	sbuf_finish(sb);
1705 	device_printf(dev, "%s\n", sbuf_data(sb));
1706 	sbuf_delete(sb);
1707 
1708 	vi_sysctls(vi);
1709 
1710 	return (0);
1711 }
1712 
1713 static int
1714 cxgbe_attach(device_t dev)
1715 {
1716 	struct port_info *pi = device_get_softc(dev);
1717 	struct adapter *sc = pi->adapter;
1718 	struct vi_info *vi;
1719 	int i, rc;
1720 
1721 	callout_init_mtx(&pi->tick, &pi->pi_lock, 0);
1722 
1723 	rc = cxgbe_vi_attach(dev, &pi->vi[0]);
1724 	if (rc)
1725 		return (rc);
1726 
1727 	for_each_vi(pi, i, vi) {
1728 		if (i == 0)
1729 			continue;
1730 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
1731 		if (vi->dev == NULL) {
1732 			device_printf(dev, "failed to add VI %d\n", i);
1733 			continue;
1734 		}
1735 		device_set_softc(vi->dev, vi);
1736 	}
1737 
1738 	cxgbe_sysctls(pi);
1739 
1740 	bus_generic_attach(dev);
1741 
1742 	return (0);
1743 }
1744 
1745 static void
1746 cxgbe_vi_detach(struct vi_info *vi)
1747 {
1748 	struct ifnet *ifp = vi->ifp;
1749 
1750 	ether_ifdetach(ifp);
1751 
1752 	/* Let detach proceed even if these fail. */
1753 #ifdef DEV_NETMAP
1754 	if (ifp->if_capabilities & IFCAP_NETMAP)
1755 		cxgbe_nm_detach(vi);
1756 #endif
1757 	cxgbe_uninit_synchronized(vi);
1758 	callout_drain(&vi->tick);
1759 	vi_full_uninit(vi);
1760 
1761 	if_free(vi->ifp);
1762 	vi->ifp = NULL;
1763 }
1764 
1765 static int
1766 cxgbe_detach(device_t dev)
1767 {
1768 	struct port_info *pi = device_get_softc(dev);
1769 	struct adapter *sc = pi->adapter;
1770 	int rc;
1771 
1772 	/* Detach the extra VIs first. */
1773 	rc = bus_generic_detach(dev);
1774 	if (rc)
1775 		return (rc);
1776 	device_delete_children(dev);
1777 
1778 	doom_vi(sc, &pi->vi[0]);
1779 
1780 	if (pi->flags & HAS_TRACEQ) {
1781 		sc->traceq = -1;	/* cloner should not create ifnet */
1782 		t4_tracer_port_detach(sc);
1783 	}
1784 
1785 	cxgbe_vi_detach(&pi->vi[0]);
1786 	callout_drain(&pi->tick);
1787 	ifmedia_removeall(&pi->media);
1788 
1789 	end_synchronized_op(sc, 0);
1790 
1791 	return (0);
1792 }
1793 
1794 static void
1795 cxgbe_init(void *arg)
1796 {
1797 	struct vi_info *vi = arg;
1798 	struct adapter *sc = vi->pi->adapter;
1799 
1800 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
1801 		return;
1802 	cxgbe_init_synchronized(vi);
1803 	end_synchronized_op(sc, 0);
1804 }
1805 
1806 static int
1807 cxgbe_ioctl(struct ifnet *ifp, unsigned long cmd, caddr_t data)
1808 {
1809 	int rc = 0, mtu, flags;
1810 	struct vi_info *vi = ifp->if_softc;
1811 	struct port_info *pi = vi->pi;
1812 	struct adapter *sc = pi->adapter;
1813 	struct ifreq *ifr = (struct ifreq *)data;
1814 	uint32_t mask;
1815 
1816 	switch (cmd) {
1817 	case SIOCSIFMTU:
1818 		mtu = ifr->ifr_mtu;
1819 		if (mtu < ETHERMIN || mtu > MAX_MTU)
1820 			return (EINVAL);
1821 
1822 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
1823 		if (rc)
1824 			return (rc);
1825 		ifp->if_mtu = mtu;
1826 		if (vi->flags & VI_INIT_DONE) {
1827 			t4_update_fl_bufsize(ifp);
1828 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1829 				rc = update_mac_settings(ifp, XGMAC_MTU);
1830 		}
1831 		end_synchronized_op(sc, 0);
1832 		break;
1833 
1834 	case SIOCSIFFLAGS:
1835 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
1836 		if (rc)
1837 			return (rc);
1838 
1839 		if (ifp->if_flags & IFF_UP) {
1840 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1841 				flags = vi->if_flags;
1842 				if ((ifp->if_flags ^ flags) &
1843 				    (IFF_PROMISC | IFF_ALLMULTI)) {
1844 					rc = update_mac_settings(ifp,
1845 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
1846 				}
1847 			} else {
1848 				rc = cxgbe_init_synchronized(vi);
1849 			}
1850 			vi->if_flags = ifp->if_flags;
1851 		} else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1852 			rc = cxgbe_uninit_synchronized(vi);
1853 		}
1854 		end_synchronized_op(sc, 0);
1855 		break;
1856 
1857 	case SIOCADDMULTI:
1858 	case SIOCDELMULTI:
1859 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
1860 		if (rc)
1861 			return (rc);
1862 		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1863 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
1864 		end_synchronized_op(sc, 0);
1865 		break;
1866 
1867 	case SIOCSIFCAP:
1868 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
1869 		if (rc)
1870 			return (rc);
1871 
1872 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1873 		if (mask & IFCAP_TXCSUM) {
1874 			ifp->if_capenable ^= IFCAP_TXCSUM;
1875 			ifp->if_hwassist ^= (CSUM_TCP | CSUM_UDP | CSUM_IP);
1876 
1877 			if (IFCAP_TSO4 & ifp->if_capenable &&
1878 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
1879 				ifp->if_capenable &= ~IFCAP_TSO4;
1880 				if_printf(ifp,
1881 				    "tso4 disabled due to -txcsum.\n");
1882 			}
1883 		}
1884 		if (mask & IFCAP_TXCSUM_IPV6) {
1885 			ifp->if_capenable ^= IFCAP_TXCSUM_IPV6;
1886 			ifp->if_hwassist ^= (CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
1887 
1888 			if (IFCAP_TSO6 & ifp->if_capenable &&
1889 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
1890 				ifp->if_capenable &= ~IFCAP_TSO6;
1891 				if_printf(ifp,
1892 				    "tso6 disabled due to -txcsum6.\n");
1893 			}
1894 		}
1895 		if (mask & IFCAP_RXCSUM)
1896 			ifp->if_capenable ^= IFCAP_RXCSUM;
1897 		if (mask & IFCAP_RXCSUM_IPV6)
1898 			ifp->if_capenable ^= IFCAP_RXCSUM_IPV6;
1899 
1900 		/*
1901 		 * Note that we leave CSUM_TSO alone (it is always set).  The
1902 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
1903 		 * sending a TSO request our way, so it's sufficient to toggle
1904 		 * IFCAP_TSOx only.
1905 		 */
1906 		if (mask & IFCAP_TSO4) {
1907 			if (!(IFCAP_TSO4 & ifp->if_capenable) &&
1908 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
1909 				if_printf(ifp, "enable txcsum first.\n");
1910 				rc = EAGAIN;
1911 				goto fail;
1912 			}
1913 			ifp->if_capenable ^= IFCAP_TSO4;
1914 		}
1915 		if (mask & IFCAP_TSO6) {
1916 			if (!(IFCAP_TSO6 & ifp->if_capenable) &&
1917 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
1918 				if_printf(ifp, "enable txcsum6 first.\n");
1919 				rc = EAGAIN;
1920 				goto fail;
1921 			}
1922 			ifp->if_capenable ^= IFCAP_TSO6;
1923 		}
1924 		if (mask & IFCAP_LRO) {
1925 #if defined(INET) || defined(INET6)
1926 			int i;
1927 			struct sge_rxq *rxq;
1928 
1929 			ifp->if_capenable ^= IFCAP_LRO;
1930 			for_each_rxq(vi, i, rxq) {
1931 				if (ifp->if_capenable & IFCAP_LRO)
1932 					rxq->iq.flags |= IQ_LRO_ENABLED;
1933 				else
1934 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
1935 			}
1936 #endif
1937 		}
1938 #ifdef TCP_OFFLOAD
1939 		if (mask & IFCAP_TOE) {
1940 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TOE;
1941 
1942 			rc = toe_capability(vi, enable);
1943 			if (rc != 0)
1944 				goto fail;
1945 
1946 			ifp->if_capenable ^= mask;
1947 		}
1948 #endif
1949 		if (mask & IFCAP_VLAN_HWTAGGING) {
1950 			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
1951 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1952 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
1953 		}
1954 		if (mask & IFCAP_VLAN_MTU) {
1955 			ifp->if_capenable ^= IFCAP_VLAN_MTU;
1956 
1957 			/* Need to find out how to disable auto-mtu-inflation */
1958 		}
1959 		if (mask & IFCAP_VLAN_HWTSO)
1960 			ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
1961 		if (mask & IFCAP_VLAN_HWCSUM)
1962 			ifp->if_capenable ^= IFCAP_VLAN_HWCSUM;
1963 #ifdef RATELIMIT
1964 		if (mask & IFCAP_TXRTLMT)
1965 			ifp->if_capenable ^= IFCAP_TXRTLMT;
1966 #endif
1967 		if (mask & IFCAP_HWRXTSTMP) {
1968 			int i;
1969 			struct sge_rxq *rxq;
1970 
1971 			ifp->if_capenable ^= IFCAP_HWRXTSTMP;
1972 			for_each_rxq(vi, i, rxq) {
1973 				if (ifp->if_capenable & IFCAP_HWRXTSTMP)
1974 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
1975 				else
1976 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
1977 			}
1978 		}
1979 
1980 #ifdef VLAN_CAPABILITIES
1981 		VLAN_CAPABILITIES(ifp);
1982 #endif
1983 fail:
1984 		end_synchronized_op(sc, 0);
1985 		break;
1986 
1987 	case SIOCSIFMEDIA:
1988 	case SIOCGIFMEDIA:
1989 	case SIOCGIFXMEDIA:
1990 		ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
1991 		break;
1992 
1993 	case SIOCGI2C: {
1994 		struct ifi2creq i2c;
1995 
1996 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
1997 		if (rc != 0)
1998 			break;
1999 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
2000 			rc = EPERM;
2001 			break;
2002 		}
2003 		if (i2c.len > sizeof(i2c.data)) {
2004 			rc = EINVAL;
2005 			break;
2006 		}
2007 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
2008 		if (rc)
2009 			return (rc);
2010 		rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
2011 		    i2c.offset, i2c.len, &i2c.data[0]);
2012 		end_synchronized_op(sc, 0);
2013 		if (rc == 0)
2014 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
2015 		break;
2016 	}
2017 
2018 	default:
2019 		rc = ether_ioctl(ifp, cmd, data);
2020 	}
2021 
2022 	return (rc);
2023 }
2024 
2025 static int
2026 cxgbe_transmit(struct ifnet *ifp, struct mbuf *m)
2027 {
2028 	struct vi_info *vi = ifp->if_softc;
2029 	struct port_info *pi = vi->pi;
2030 	struct adapter *sc = pi->adapter;
2031 	struct sge_txq *txq;
2032 	void *items[1];
2033 	int rc;
2034 
2035 	M_ASSERTPKTHDR(m);
2036 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
2037 
2038 	if (__predict_false(pi->link_cfg.link_ok == false)) {
2039 		m_freem(m);
2040 		return (ENETDOWN);
2041 	}
2042 
2043 	rc = parse_pkt(sc, &m);
2044 	if (__predict_false(rc != 0)) {
2045 		MPASS(m == NULL);			/* was freed already */
2046 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
2047 		return (rc);
2048 	}
2049 #ifdef RATELIMIT
2050 	if (m->m_pkthdr.snd_tag != NULL) {
2051 		/* EAGAIN tells the stack we are not the correct interface. */
2052 		if (__predict_false(ifp != m->m_pkthdr.snd_tag->ifp)) {
2053 			m_freem(m);
2054 			return (EAGAIN);
2055 		}
2056 
2057 		return (ethofld_transmit(ifp, m));
2058 	}
2059 #endif
2060 
2061 	/* Select a txq. */
2062 	txq = &sc->sge.txq[vi->first_txq];
2063 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
2064 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
2065 		    vi->rsrv_noflowq);
2066 
2067 	items[0] = m;
2068 	rc = mp_ring_enqueue(txq->r, items, 1, 4096);
2069 	if (__predict_false(rc != 0))
2070 		m_freem(m);
2071 
2072 	return (rc);
2073 }
2074 
2075 static void
2076 cxgbe_qflush(struct ifnet *ifp)
2077 {
2078 	struct vi_info *vi = ifp->if_softc;
2079 	struct sge_txq *txq;
2080 	int i;
2081 
2082 	/* queues do not exist if !VI_INIT_DONE. */
2083 	if (vi->flags & VI_INIT_DONE) {
2084 		for_each_txq(vi, i, txq) {
2085 			TXQ_LOCK(txq);
2086 			txq->eq.flags |= EQ_QFLUSH;
2087 			TXQ_UNLOCK(txq);
2088 			while (!mp_ring_is_idle(txq->r)) {
2089 				mp_ring_check_drainage(txq->r, 0);
2090 				pause("qflush", 1);
2091 			}
2092 			TXQ_LOCK(txq);
2093 			txq->eq.flags &= ~EQ_QFLUSH;
2094 			TXQ_UNLOCK(txq);
2095 		}
2096 	}
2097 	if_qflush(ifp);
2098 }
2099 
2100 static uint64_t
2101 vi_get_counter(struct ifnet *ifp, ift_counter c)
2102 {
2103 	struct vi_info *vi = ifp->if_softc;
2104 	struct fw_vi_stats_vf *s = &vi->stats;
2105 
2106 	vi_refresh_stats(vi->pi->adapter, vi);
2107 
2108 	switch (c) {
2109 	case IFCOUNTER_IPACKETS:
2110 		return (s->rx_bcast_frames + s->rx_mcast_frames +
2111 		    s->rx_ucast_frames);
2112 	case IFCOUNTER_IERRORS:
2113 		return (s->rx_err_frames);
2114 	case IFCOUNTER_OPACKETS:
2115 		return (s->tx_bcast_frames + s->tx_mcast_frames +
2116 		    s->tx_ucast_frames + s->tx_offload_frames);
2117 	case IFCOUNTER_OERRORS:
2118 		return (s->tx_drop_frames);
2119 	case IFCOUNTER_IBYTES:
2120 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
2121 		    s->rx_ucast_bytes);
2122 	case IFCOUNTER_OBYTES:
2123 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
2124 		    s->tx_ucast_bytes + s->tx_offload_bytes);
2125 	case IFCOUNTER_IMCASTS:
2126 		return (s->rx_mcast_frames);
2127 	case IFCOUNTER_OMCASTS:
2128 		return (s->tx_mcast_frames);
2129 	case IFCOUNTER_OQDROPS: {
2130 		uint64_t drops;
2131 
2132 		drops = 0;
2133 		if (vi->flags & VI_INIT_DONE) {
2134 			int i;
2135 			struct sge_txq *txq;
2136 
2137 			for_each_txq(vi, i, txq)
2138 				drops += counter_u64_fetch(txq->r->drops);
2139 		}
2140 
2141 		return (drops);
2142 
2143 	}
2144 
2145 	default:
2146 		return (if_get_counter_default(ifp, c));
2147 	}
2148 }
2149 
2150 uint64_t
2151 cxgbe_get_counter(struct ifnet *ifp, ift_counter c)
2152 {
2153 	struct vi_info *vi = ifp->if_softc;
2154 	struct port_info *pi = vi->pi;
2155 	struct adapter *sc = pi->adapter;
2156 	struct port_stats *s = &pi->stats;
2157 
2158 	if (pi->nvi > 1 || sc->flags & IS_VF)
2159 		return (vi_get_counter(ifp, c));
2160 
2161 	cxgbe_refresh_stats(sc, pi);
2162 
2163 	switch (c) {
2164 	case IFCOUNTER_IPACKETS:
2165 		return (s->rx_frames);
2166 
2167 	case IFCOUNTER_IERRORS:
2168 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
2169 		    s->rx_fcs_err + s->rx_len_err);
2170 
2171 	case IFCOUNTER_OPACKETS:
2172 		return (s->tx_frames);
2173 
2174 	case IFCOUNTER_OERRORS:
2175 		return (s->tx_error_frames);
2176 
2177 	case IFCOUNTER_IBYTES:
2178 		return (s->rx_octets);
2179 
2180 	case IFCOUNTER_OBYTES:
2181 		return (s->tx_octets);
2182 
2183 	case IFCOUNTER_IMCASTS:
2184 		return (s->rx_mcast_frames);
2185 
2186 	case IFCOUNTER_OMCASTS:
2187 		return (s->tx_mcast_frames);
2188 
2189 	case IFCOUNTER_IQDROPS:
2190 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
2191 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
2192 		    s->rx_trunc3 + pi->tnl_cong_drops);
2193 
2194 	case IFCOUNTER_OQDROPS: {
2195 		uint64_t drops;
2196 
2197 		drops = s->tx_drop;
2198 		if (vi->flags & VI_INIT_DONE) {
2199 			int i;
2200 			struct sge_txq *txq;
2201 
2202 			for_each_txq(vi, i, txq)
2203 				drops += counter_u64_fetch(txq->r->drops);
2204 		}
2205 
2206 		return (drops);
2207 
2208 	}
2209 
2210 	default:
2211 		return (if_get_counter_default(ifp, c));
2212 	}
2213 }
2214 
2215 /*
2216  * The kernel picks a media from the list we had provided but we still validate
2217  * the requeste.
2218  */
2219 int
2220 cxgbe_media_change(struct ifnet *ifp)
2221 {
2222 	struct vi_info *vi = ifp->if_softc;
2223 	struct port_info *pi = vi->pi;
2224 	struct ifmedia *ifm = &pi->media;
2225 	struct link_config *lc = &pi->link_cfg;
2226 	struct adapter *sc = pi->adapter;
2227 	int rc;
2228 
2229 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
2230 	if (rc != 0)
2231 		return (rc);
2232 	PORT_LOCK(pi);
2233 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
2234 		/* ifconfig .. media autoselect */
2235 		if (!(lc->supported & FW_PORT_CAP32_ANEG)) {
2236 			rc = ENOTSUP; /* AN not supported by transceiver */
2237 			goto done;
2238 		}
2239 		lc->requested_aneg = AUTONEG_ENABLE;
2240 		lc->requested_speed = 0;
2241 		lc->requested_fc |= PAUSE_AUTONEG;
2242 	} else {
2243 		lc->requested_aneg = AUTONEG_DISABLE;
2244 		lc->requested_speed =
2245 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
2246 		lc->requested_fc = 0;
2247 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
2248 			lc->requested_fc |= PAUSE_RX;
2249 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
2250 			lc->requested_fc |= PAUSE_TX;
2251 	}
2252 	if (pi->up_vis > 0) {
2253 		fixup_link_config(pi);
2254 		rc = apply_link_config(pi);
2255 	}
2256 done:
2257 	PORT_UNLOCK(pi);
2258 	end_synchronized_op(sc, 0);
2259 	return (rc);
2260 }
2261 
2262 /*
2263  * Base media word (without ETHER, pause, link active, etc.) for the port at the
2264  * given speed.
2265  */
2266 static int
2267 port_mword(struct port_info *pi, uint32_t speed)
2268 {
2269 
2270 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
2271 	MPASS(powerof2(speed));
2272 
2273 	switch(pi->port_type) {
2274 	case FW_PORT_TYPE_BT_SGMII:
2275 	case FW_PORT_TYPE_BT_XFI:
2276 	case FW_PORT_TYPE_BT_XAUI:
2277 		/* BaseT */
2278 		switch (speed) {
2279 		case FW_PORT_CAP32_SPEED_100M:
2280 			return (IFM_100_T);
2281 		case FW_PORT_CAP32_SPEED_1G:
2282 			return (IFM_1000_T);
2283 		case FW_PORT_CAP32_SPEED_10G:
2284 			return (IFM_10G_T);
2285 		}
2286 		break;
2287 	case FW_PORT_TYPE_KX4:
2288 		if (speed == FW_PORT_CAP32_SPEED_10G)
2289 			return (IFM_10G_KX4);
2290 		break;
2291 	case FW_PORT_TYPE_CX4:
2292 		if (speed == FW_PORT_CAP32_SPEED_10G)
2293 			return (IFM_10G_CX4);
2294 		break;
2295 	case FW_PORT_TYPE_KX:
2296 		if (speed == FW_PORT_CAP32_SPEED_1G)
2297 			return (IFM_1000_KX);
2298 		break;
2299 	case FW_PORT_TYPE_KR:
2300 	case FW_PORT_TYPE_BP_AP:
2301 	case FW_PORT_TYPE_BP4_AP:
2302 	case FW_PORT_TYPE_BP40_BA:
2303 	case FW_PORT_TYPE_KR4_100G:
2304 	case FW_PORT_TYPE_KR_SFP28:
2305 	case FW_PORT_TYPE_KR_XLAUI:
2306 		switch (speed) {
2307 		case FW_PORT_CAP32_SPEED_1G:
2308 			return (IFM_1000_KX);
2309 		case FW_PORT_CAP32_SPEED_10G:
2310 			return (IFM_10G_KR);
2311 		case FW_PORT_CAP32_SPEED_25G:
2312 			return (IFM_25G_KR);
2313 		case FW_PORT_CAP32_SPEED_40G:
2314 			return (IFM_40G_KR4);
2315 		case FW_PORT_CAP32_SPEED_50G:
2316 			return (IFM_50G_KR2);
2317 		case FW_PORT_CAP32_SPEED_100G:
2318 			return (IFM_100G_KR4);
2319 		}
2320 		break;
2321 	case FW_PORT_TYPE_FIBER_XFI:
2322 	case FW_PORT_TYPE_FIBER_XAUI:
2323 	case FW_PORT_TYPE_SFP:
2324 	case FW_PORT_TYPE_QSFP_10G:
2325 	case FW_PORT_TYPE_QSA:
2326 	case FW_PORT_TYPE_QSFP:
2327 	case FW_PORT_TYPE_CR4_QSFP:
2328 	case FW_PORT_TYPE_CR_QSFP:
2329 	case FW_PORT_TYPE_CR2_QSFP:
2330 	case FW_PORT_TYPE_SFP28:
2331 		/* Pluggable transceiver */
2332 		switch (pi->mod_type) {
2333 		case FW_PORT_MOD_TYPE_LR:
2334 			switch (speed) {
2335 			case FW_PORT_CAP32_SPEED_1G:
2336 				return (IFM_1000_LX);
2337 			case FW_PORT_CAP32_SPEED_10G:
2338 				return (IFM_10G_LR);
2339 			case FW_PORT_CAP32_SPEED_25G:
2340 				return (IFM_25G_LR);
2341 			case FW_PORT_CAP32_SPEED_40G:
2342 				return (IFM_40G_LR4);
2343 			case FW_PORT_CAP32_SPEED_50G:
2344 				return (IFM_50G_LR2);
2345 			case FW_PORT_CAP32_SPEED_100G:
2346 				return (IFM_100G_LR4);
2347 			}
2348 			break;
2349 		case FW_PORT_MOD_TYPE_SR:
2350 			switch (speed) {
2351 			case FW_PORT_CAP32_SPEED_1G:
2352 				return (IFM_1000_SX);
2353 			case FW_PORT_CAP32_SPEED_10G:
2354 				return (IFM_10G_SR);
2355 			case FW_PORT_CAP32_SPEED_25G:
2356 				return (IFM_25G_SR);
2357 			case FW_PORT_CAP32_SPEED_40G:
2358 				return (IFM_40G_SR4);
2359 			case FW_PORT_CAP32_SPEED_50G:
2360 				return (IFM_50G_SR2);
2361 			case FW_PORT_CAP32_SPEED_100G:
2362 				return (IFM_100G_SR4);
2363 			}
2364 			break;
2365 		case FW_PORT_MOD_TYPE_ER:
2366 			if (speed == FW_PORT_CAP32_SPEED_10G)
2367 				return (IFM_10G_ER);
2368 			break;
2369 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
2370 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
2371 			switch (speed) {
2372 			case FW_PORT_CAP32_SPEED_1G:
2373 				return (IFM_1000_CX);
2374 			case FW_PORT_CAP32_SPEED_10G:
2375 				return (IFM_10G_TWINAX);
2376 			case FW_PORT_CAP32_SPEED_25G:
2377 				return (IFM_25G_CR);
2378 			case FW_PORT_CAP32_SPEED_40G:
2379 				return (IFM_40G_CR4);
2380 			case FW_PORT_CAP32_SPEED_50G:
2381 				return (IFM_50G_CR2);
2382 			case FW_PORT_CAP32_SPEED_100G:
2383 				return (IFM_100G_CR4);
2384 			}
2385 			break;
2386 		case FW_PORT_MOD_TYPE_LRM:
2387 			if (speed == FW_PORT_CAP32_SPEED_10G)
2388 				return (IFM_10G_LRM);
2389 			break;
2390 		case FW_PORT_MOD_TYPE_NA:
2391 			MPASS(0);	/* Not pluggable? */
2392 			/* fall throough */
2393 		case FW_PORT_MOD_TYPE_ERROR:
2394 		case FW_PORT_MOD_TYPE_UNKNOWN:
2395 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
2396 			break;
2397 		case FW_PORT_MOD_TYPE_NONE:
2398 			return (IFM_NONE);
2399 		}
2400 		break;
2401 	case FW_PORT_TYPE_NONE:
2402 		return (IFM_NONE);
2403 	}
2404 
2405 	return (IFM_UNKNOWN);
2406 }
2407 
2408 void
2409 cxgbe_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
2410 {
2411 	struct vi_info *vi = ifp->if_softc;
2412 	struct port_info *pi = vi->pi;
2413 	struct adapter *sc = pi->adapter;
2414 	struct link_config *lc = &pi->link_cfg;
2415 
2416 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4med") != 0)
2417 		return;
2418 	PORT_LOCK(pi);
2419 
2420 	if (pi->up_vis == 0) {
2421 		/*
2422 		 * If all the interfaces are administratively down the firmware
2423 		 * does not report transceiver changes.  Refresh port info here
2424 		 * so that ifconfig displays accurate ifmedia at all times.
2425 		 * This is the only reason we have a synchronized op in this
2426 		 * function.  Just PORT_LOCK would have been enough otherwise.
2427 		 */
2428 		t4_update_port_info(pi);
2429 		build_medialist(pi);
2430 	}
2431 
2432 	/* ifm_status */
2433 	ifmr->ifm_status = IFM_AVALID;
2434 	if (lc->link_ok == false)
2435 		goto done;
2436 	ifmr->ifm_status |= IFM_ACTIVE;
2437 
2438 	/* ifm_active */
2439 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
2440 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
2441 	if (lc->fc & PAUSE_RX)
2442 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
2443 	if (lc->fc & PAUSE_TX)
2444 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
2445 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
2446 done:
2447 	PORT_UNLOCK(pi);
2448 	end_synchronized_op(sc, 0);
2449 }
2450 
2451 static int
2452 vcxgbe_probe(device_t dev)
2453 {
2454 	char buf[128];
2455 	struct vi_info *vi = device_get_softc(dev);
2456 
2457 	snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
2458 	    vi - vi->pi->vi);
2459 	device_set_desc_copy(dev, buf);
2460 
2461 	return (BUS_PROBE_DEFAULT);
2462 }
2463 
2464 static int
2465 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
2466 {
2467 	int func, index, rc;
2468 	uint32_t param, val;
2469 
2470 	ASSERT_SYNCHRONIZED_OP(sc);
2471 
2472 	index = vi - pi->vi;
2473 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
2474 	KASSERT(index < nitems(vi_mac_funcs),
2475 	    ("%s: VI %s doesn't have a MAC func", __func__,
2476 	    device_get_nameunit(vi->dev)));
2477 	func = vi_mac_funcs[index];
2478 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
2479 	    vi->hw_addr, &vi->rss_size, func, 0);
2480 	if (rc < 0) {
2481 		device_printf(vi->dev, "failed to allocate virtual interface %d"
2482 		    "for port %d: %d\n", index, pi->port_id, -rc);
2483 		return (-rc);
2484 	}
2485 	vi->viid = rc;
2486 	if (chip_id(sc) <= CHELSIO_T5)
2487 		vi->smt_idx = (rc & 0x7f) << 1;
2488 	else
2489 		vi->smt_idx = (rc & 0x7f);
2490 
2491 	if (vi->rss_size == 1) {
2492 		/*
2493 		 * This VI didn't get a slice of the RSS table.  Reduce the
2494 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
2495 		 * configuration file (nvi, rssnvi for this PF) if this is a
2496 		 * problem.
2497 		 */
2498 		device_printf(vi->dev, "RSS table not available.\n");
2499 		vi->rss_base = 0xffff;
2500 
2501 		return (0);
2502 	}
2503 
2504 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
2505 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
2506 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
2507 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
2508 	if (rc)
2509 		vi->rss_base = 0xffff;
2510 	else {
2511 		MPASS((val >> 16) == vi->rss_size);
2512 		vi->rss_base = val & 0xffff;
2513 	}
2514 
2515 	return (0);
2516 }
2517 
2518 static int
2519 vcxgbe_attach(device_t dev)
2520 {
2521 	struct vi_info *vi;
2522 	struct port_info *pi;
2523 	struct adapter *sc;
2524 	int rc;
2525 
2526 	vi = device_get_softc(dev);
2527 	pi = vi->pi;
2528 	sc = pi->adapter;
2529 
2530 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
2531 	if (rc)
2532 		return (rc);
2533 	rc = alloc_extra_vi(sc, pi, vi);
2534 	end_synchronized_op(sc, 0);
2535 	if (rc)
2536 		return (rc);
2537 
2538 	rc = cxgbe_vi_attach(dev, vi);
2539 	if (rc) {
2540 		t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
2541 		return (rc);
2542 	}
2543 	return (0);
2544 }
2545 
2546 static int
2547 vcxgbe_detach(device_t dev)
2548 {
2549 	struct vi_info *vi;
2550 	struct adapter *sc;
2551 
2552 	vi = device_get_softc(dev);
2553 	sc = vi->pi->adapter;
2554 
2555 	doom_vi(sc, vi);
2556 
2557 	cxgbe_vi_detach(vi);
2558 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
2559 
2560 	end_synchronized_op(sc, 0);
2561 
2562 	return (0);
2563 }
2564 
2565 void
2566 t4_fatal_err(struct adapter *sc)
2567 {
2568 	t4_set_reg_field(sc, A_SGE_CONTROL, F_GLOBALENABLE, 0);
2569 	t4_intr_disable(sc);
2570 	log(LOG_EMERG, "%s: encountered fatal error, adapter stopped.\n",
2571 	    device_get_nameunit(sc->dev));
2572 	if (t4_panic_on_fatal_err)
2573 		panic("panic requested on fatal error");
2574 }
2575 
2576 void
2577 t4_add_adapter(struct adapter *sc)
2578 {
2579 	sx_xlock(&t4_list_lock);
2580 	SLIST_INSERT_HEAD(&t4_list, sc, link);
2581 	sx_xunlock(&t4_list_lock);
2582 }
2583 
2584 int
2585 t4_map_bars_0_and_4(struct adapter *sc)
2586 {
2587 	sc->regs_rid = PCIR_BAR(0);
2588 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
2589 	    &sc->regs_rid, RF_ACTIVE);
2590 	if (sc->regs_res == NULL) {
2591 		device_printf(sc->dev, "cannot map registers.\n");
2592 		return (ENXIO);
2593 	}
2594 	sc->bt = rman_get_bustag(sc->regs_res);
2595 	sc->bh = rman_get_bushandle(sc->regs_res);
2596 	sc->mmio_len = rman_get_size(sc->regs_res);
2597 	setbit(&sc->doorbells, DOORBELL_KDB);
2598 
2599 	sc->msix_rid = PCIR_BAR(4);
2600 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
2601 	    &sc->msix_rid, RF_ACTIVE);
2602 	if (sc->msix_res == NULL) {
2603 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
2604 		return (ENXIO);
2605 	}
2606 
2607 	return (0);
2608 }
2609 
2610 int
2611 t4_map_bar_2(struct adapter *sc)
2612 {
2613 
2614 	/*
2615 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
2616 	 * to map it if RDMA is disabled.
2617 	 */
2618 	if (is_t4(sc) && sc->rdmacaps == 0)
2619 		return (0);
2620 
2621 	sc->udbs_rid = PCIR_BAR(2);
2622 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
2623 	    &sc->udbs_rid, RF_ACTIVE);
2624 	if (sc->udbs_res == NULL) {
2625 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
2626 		return (ENXIO);
2627 	}
2628 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
2629 
2630 	if (chip_id(sc) >= CHELSIO_T5) {
2631 		setbit(&sc->doorbells, DOORBELL_UDB);
2632 #if defined(__i386__) || defined(__amd64__)
2633 		if (t5_write_combine) {
2634 			int rc, mode;
2635 
2636 			/*
2637 			 * Enable write combining on BAR2.  This is the
2638 			 * userspace doorbell BAR and is split into 128B
2639 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
2640 			 * with an egress queue.  The first 64B has the doorbell
2641 			 * and the second 64B can be used to submit a tx work
2642 			 * request with an implicit doorbell.
2643 			 */
2644 
2645 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
2646 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
2647 			if (rc == 0) {
2648 				clrbit(&sc->doorbells, DOORBELL_UDB);
2649 				setbit(&sc->doorbells, DOORBELL_WCWR);
2650 				setbit(&sc->doorbells, DOORBELL_UDBWC);
2651 			} else {
2652 				device_printf(sc->dev,
2653 				    "couldn't enable write combining: %d\n",
2654 				    rc);
2655 			}
2656 
2657 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
2658 			t4_write_reg(sc, A_SGE_STAT_CFG,
2659 			    V_STATSOURCE_T5(7) | mode);
2660 		}
2661 #endif
2662 	}
2663 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
2664 
2665 	return (0);
2666 }
2667 
2668 struct memwin_init {
2669 	uint32_t base;
2670 	uint32_t aperture;
2671 };
2672 
2673 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
2674 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
2675 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
2676 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
2677 };
2678 
2679 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
2680 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
2681 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
2682 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
2683 };
2684 
2685 static void
2686 setup_memwin(struct adapter *sc)
2687 {
2688 	const struct memwin_init *mw_init;
2689 	struct memwin *mw;
2690 	int i;
2691 	uint32_t bar0;
2692 
2693 	if (is_t4(sc)) {
2694 		/*
2695 		 * Read low 32b of bar0 indirectly via the hardware backdoor
2696 		 * mechanism.  Works from within PCI passthrough environments
2697 		 * too, where rman_get_start() can return a different value.  We
2698 		 * need to program the T4 memory window decoders with the actual
2699 		 * addresses that will be coming across the PCIe link.
2700 		 */
2701 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
2702 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
2703 
2704 		mw_init = &t4_memwin[0];
2705 	} else {
2706 		/* T5+ use the relative offset inside the PCIe BAR */
2707 		bar0 = 0;
2708 
2709 		mw_init = &t5_memwin[0];
2710 	}
2711 
2712 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
2713 		rw_init(&mw->mw_lock, "memory window access");
2714 		mw->mw_base = mw_init->base;
2715 		mw->mw_aperture = mw_init->aperture;
2716 		mw->mw_curpos = 0;
2717 		t4_write_reg(sc,
2718 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
2719 		    (mw->mw_base + bar0) | V_BIR(0) |
2720 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
2721 		rw_wlock(&mw->mw_lock);
2722 		position_memwin(sc, i, 0);
2723 		rw_wunlock(&mw->mw_lock);
2724 	}
2725 
2726 	/* flush */
2727 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
2728 }
2729 
2730 /*
2731  * Positions the memory window at the given address in the card's address space.
2732  * There are some alignment requirements and the actual position may be at an
2733  * address prior to the requested address.  mw->mw_curpos always has the actual
2734  * position of the window.
2735  */
2736 static void
2737 position_memwin(struct adapter *sc, int idx, uint32_t addr)
2738 {
2739 	struct memwin *mw;
2740 	uint32_t pf;
2741 	uint32_t reg;
2742 
2743 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
2744 	mw = &sc->memwin[idx];
2745 	rw_assert(&mw->mw_lock, RA_WLOCKED);
2746 
2747 	if (is_t4(sc)) {
2748 		pf = 0;
2749 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
2750 	} else {
2751 		pf = V_PFNUM(sc->pf);
2752 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
2753 	}
2754 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
2755 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
2756 	t4_read_reg(sc, reg);	/* flush */
2757 }
2758 
2759 int
2760 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
2761     int len, int rw)
2762 {
2763 	struct memwin *mw;
2764 	uint32_t mw_end, v;
2765 
2766 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
2767 
2768 	/* Memory can only be accessed in naturally aligned 4 byte units */
2769 	if (addr & 3 || len & 3 || len <= 0)
2770 		return (EINVAL);
2771 
2772 	mw = &sc->memwin[idx];
2773 	while (len > 0) {
2774 		rw_rlock(&mw->mw_lock);
2775 		mw_end = mw->mw_curpos + mw->mw_aperture;
2776 		if (addr >= mw_end || addr < mw->mw_curpos) {
2777 			/* Will need to reposition the window */
2778 			if (!rw_try_upgrade(&mw->mw_lock)) {
2779 				rw_runlock(&mw->mw_lock);
2780 				rw_wlock(&mw->mw_lock);
2781 			}
2782 			rw_assert(&mw->mw_lock, RA_WLOCKED);
2783 			position_memwin(sc, idx, addr);
2784 			rw_downgrade(&mw->mw_lock);
2785 			mw_end = mw->mw_curpos + mw->mw_aperture;
2786 		}
2787 		rw_assert(&mw->mw_lock, RA_RLOCKED);
2788 		while (addr < mw_end && len > 0) {
2789 			if (rw == 0) {
2790 				v = t4_read_reg(sc, mw->mw_base + addr -
2791 				    mw->mw_curpos);
2792 				*val++ = le32toh(v);
2793 			} else {
2794 				v = *val++;
2795 				t4_write_reg(sc, mw->mw_base + addr -
2796 				    mw->mw_curpos, htole32(v));
2797 			}
2798 			addr += 4;
2799 			len -= 4;
2800 		}
2801 		rw_runlock(&mw->mw_lock);
2802 	}
2803 
2804 	return (0);
2805 }
2806 
2807 int
2808 alloc_atid_tab(struct tid_info *t, int flags)
2809 {
2810 	int i;
2811 
2812 	MPASS(t->natids > 0);
2813 	MPASS(t->atid_tab == NULL);
2814 
2815 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
2816 	    M_ZERO | flags);
2817 	if (t->atid_tab == NULL)
2818 		return (ENOMEM);
2819 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
2820 	t->afree = t->atid_tab;
2821 	t->atids_in_use = 0;
2822 	for (i = 1; i < t->natids; i++)
2823 		t->atid_tab[i - 1].next = &t->atid_tab[i];
2824 	t->atid_tab[t->natids - 1].next = NULL;
2825 
2826 	return (0);
2827 }
2828 
2829 void
2830 free_atid_tab(struct tid_info *t)
2831 {
2832 
2833 	KASSERT(t->atids_in_use == 0,
2834 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
2835 
2836 	if (mtx_initialized(&t->atid_lock))
2837 		mtx_destroy(&t->atid_lock);
2838 	free(t->atid_tab, M_CXGBE);
2839 	t->atid_tab = NULL;
2840 }
2841 
2842 int
2843 alloc_atid(struct adapter *sc, void *ctx)
2844 {
2845 	struct tid_info *t = &sc->tids;
2846 	int atid = -1;
2847 
2848 	mtx_lock(&t->atid_lock);
2849 	if (t->afree) {
2850 		union aopen_entry *p = t->afree;
2851 
2852 		atid = p - t->atid_tab;
2853 		MPASS(atid <= M_TID_TID);
2854 		t->afree = p->next;
2855 		p->data = ctx;
2856 		t->atids_in_use++;
2857 	}
2858 	mtx_unlock(&t->atid_lock);
2859 	return (atid);
2860 }
2861 
2862 void *
2863 lookup_atid(struct adapter *sc, int atid)
2864 {
2865 	struct tid_info *t = &sc->tids;
2866 
2867 	return (t->atid_tab[atid].data);
2868 }
2869 
2870 void
2871 free_atid(struct adapter *sc, int atid)
2872 {
2873 	struct tid_info *t = &sc->tids;
2874 	union aopen_entry *p = &t->atid_tab[atid];
2875 
2876 	mtx_lock(&t->atid_lock);
2877 	p->next = t->afree;
2878 	t->afree = p;
2879 	t->atids_in_use--;
2880 	mtx_unlock(&t->atid_lock);
2881 }
2882 
2883 static void
2884 queue_tid_release(struct adapter *sc, int tid)
2885 {
2886 
2887 	CXGBE_UNIMPLEMENTED("deferred tid release");
2888 }
2889 
2890 void
2891 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
2892 {
2893 	struct wrqe *wr;
2894 	struct cpl_tid_release *req;
2895 
2896 	wr = alloc_wrqe(sizeof(*req), ctrlq);
2897 	if (wr == NULL) {
2898 		queue_tid_release(sc, tid);	/* defer */
2899 		return;
2900 	}
2901 	req = wrtod(wr);
2902 
2903 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
2904 
2905 	t4_wrq_tx(sc, wr);
2906 }
2907 
2908 static int
2909 t4_range_cmp(const void *a, const void *b)
2910 {
2911 	return ((const struct t4_range *)a)->start -
2912 	       ((const struct t4_range *)b)->start;
2913 }
2914 
2915 /*
2916  * Verify that the memory range specified by the addr/len pair is valid within
2917  * the card's address space.
2918  */
2919 static int
2920 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
2921 {
2922 	struct t4_range mem_ranges[4], *r, *next;
2923 	uint32_t em, addr_len;
2924 	int i, n, remaining;
2925 
2926 	/* Memory can only be accessed in naturally aligned 4 byte units */
2927 	if (addr & 3 || len & 3 || len == 0)
2928 		return (EINVAL);
2929 
2930 	/* Enabled memories */
2931 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
2932 
2933 	r = &mem_ranges[0];
2934 	n = 0;
2935 	bzero(r, sizeof(mem_ranges));
2936 	if (em & F_EDRAM0_ENABLE) {
2937 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
2938 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
2939 		if (r->size > 0) {
2940 			r->start = G_EDRAM0_BASE(addr_len) << 20;
2941 			if (addr >= r->start &&
2942 			    addr + len <= r->start + r->size)
2943 				return (0);
2944 			r++;
2945 			n++;
2946 		}
2947 	}
2948 	if (em & F_EDRAM1_ENABLE) {
2949 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
2950 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
2951 		if (r->size > 0) {
2952 			r->start = G_EDRAM1_BASE(addr_len) << 20;
2953 			if (addr >= r->start &&
2954 			    addr + len <= r->start + r->size)
2955 				return (0);
2956 			r++;
2957 			n++;
2958 		}
2959 	}
2960 	if (em & F_EXT_MEM_ENABLE) {
2961 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
2962 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
2963 		if (r->size > 0) {
2964 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
2965 			if (addr >= r->start &&
2966 			    addr + len <= r->start + r->size)
2967 				return (0);
2968 			r++;
2969 			n++;
2970 		}
2971 	}
2972 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
2973 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
2974 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
2975 		if (r->size > 0) {
2976 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
2977 			if (addr >= r->start &&
2978 			    addr + len <= r->start + r->size)
2979 				return (0);
2980 			r++;
2981 			n++;
2982 		}
2983 	}
2984 	MPASS(n <= nitems(mem_ranges));
2985 
2986 	if (n > 1) {
2987 		/* Sort and merge the ranges. */
2988 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
2989 
2990 		/* Start from index 0 and examine the next n - 1 entries. */
2991 		r = &mem_ranges[0];
2992 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
2993 
2994 			MPASS(r->size > 0);	/* r is a valid entry. */
2995 			next = r + 1;
2996 			MPASS(next->size > 0);	/* and so is the next one. */
2997 
2998 			while (r->start + r->size >= next->start) {
2999 				/* Merge the next one into the current entry. */
3000 				r->size = max(r->start + r->size,
3001 				    next->start + next->size) - r->start;
3002 				n--;	/* One fewer entry in total. */
3003 				if (--remaining == 0)
3004 					goto done;	/* short circuit */
3005 				next++;
3006 			}
3007 			if (next != r + 1) {
3008 				/*
3009 				 * Some entries were merged into r and next
3010 				 * points to the first valid entry that couldn't
3011 				 * be merged.
3012 				 */
3013 				MPASS(next->size > 0);	/* must be valid */
3014 				memcpy(r + 1, next, remaining * sizeof(*r));
3015 #ifdef INVARIANTS
3016 				/*
3017 				 * This so that the foo->size assertion in the
3018 				 * next iteration of the loop do the right
3019 				 * thing for entries that were pulled up and are
3020 				 * no longer valid.
3021 				 */
3022 				MPASS(n < nitems(mem_ranges));
3023 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
3024 				    sizeof(struct t4_range));
3025 #endif
3026 			}
3027 		}
3028 done:
3029 		/* Done merging the ranges. */
3030 		MPASS(n > 0);
3031 		r = &mem_ranges[0];
3032 		for (i = 0; i < n; i++, r++) {
3033 			if (addr >= r->start &&
3034 			    addr + len <= r->start + r->size)
3035 				return (0);
3036 		}
3037 	}
3038 
3039 	return (EFAULT);
3040 }
3041 
3042 static int
3043 fwmtype_to_hwmtype(int mtype)
3044 {
3045 
3046 	switch (mtype) {
3047 	case FW_MEMTYPE_EDC0:
3048 		return (MEM_EDC0);
3049 	case FW_MEMTYPE_EDC1:
3050 		return (MEM_EDC1);
3051 	case FW_MEMTYPE_EXTMEM:
3052 		return (MEM_MC0);
3053 	case FW_MEMTYPE_EXTMEM1:
3054 		return (MEM_MC1);
3055 	default:
3056 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
3057 	}
3058 }
3059 
3060 /*
3061  * Verify that the memory range specified by the memtype/offset/len pair is
3062  * valid and lies entirely within the memtype specified.  The global address of
3063  * the start of the range is returned in addr.
3064  */
3065 static int
3066 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
3067     uint32_t *addr)
3068 {
3069 	uint32_t em, addr_len, maddr;
3070 
3071 	/* Memory can only be accessed in naturally aligned 4 byte units */
3072 	if (off & 3 || len & 3 || len == 0)
3073 		return (EINVAL);
3074 
3075 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
3076 	switch (fwmtype_to_hwmtype(mtype)) {
3077 	case MEM_EDC0:
3078 		if (!(em & F_EDRAM0_ENABLE))
3079 			return (EINVAL);
3080 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
3081 		maddr = G_EDRAM0_BASE(addr_len) << 20;
3082 		break;
3083 	case MEM_EDC1:
3084 		if (!(em & F_EDRAM1_ENABLE))
3085 			return (EINVAL);
3086 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
3087 		maddr = G_EDRAM1_BASE(addr_len) << 20;
3088 		break;
3089 	case MEM_MC:
3090 		if (!(em & F_EXT_MEM_ENABLE))
3091 			return (EINVAL);
3092 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
3093 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
3094 		break;
3095 	case MEM_MC1:
3096 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
3097 			return (EINVAL);
3098 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
3099 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
3100 		break;
3101 	default:
3102 		return (EINVAL);
3103 	}
3104 
3105 	*addr = maddr + off;	/* global address */
3106 	return (validate_mem_range(sc, *addr, len));
3107 }
3108 
3109 static int
3110 fixup_devlog_params(struct adapter *sc)
3111 {
3112 	struct devlog_params *dparams = &sc->params.devlog;
3113 	int rc;
3114 
3115 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
3116 	    dparams->size, &dparams->addr);
3117 
3118 	return (rc);
3119 }
3120 
3121 static void
3122 update_nirq(struct intrs_and_queues *iaq, int nports)
3123 {
3124 	int extra = T4_EXTRA_INTR;
3125 
3126 	iaq->nirq = extra;
3127 	iaq->nirq += nports * (iaq->nrxq + iaq->nofldrxq);
3128 	iaq->nirq += nports * (iaq->num_vis - 1) *
3129 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
3130 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
3131 }
3132 
3133 /*
3134  * Adjust requirements to fit the number of interrupts available.
3135  */
3136 static void
3137 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
3138     int navail)
3139 {
3140 	int old_nirq;
3141 	const int nports = sc->params.nports;
3142 
3143 	MPASS(nports > 0);
3144 	MPASS(navail > 0);
3145 
3146 	bzero(iaq, sizeof(*iaq));
3147 	iaq->intr_type = itype;
3148 	iaq->num_vis = t4_num_vis;
3149 	iaq->ntxq = t4_ntxq;
3150 	iaq->ntxq_vi = t4_ntxq_vi;
3151 	iaq->nrxq = t4_nrxq;
3152 	iaq->nrxq_vi = t4_nrxq_vi;
3153 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
3154 	if (is_offload(sc) || is_ethoffload(sc)) {
3155 		iaq->nofldtxq = t4_nofldtxq;
3156 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
3157 	}
3158 #endif
3159 #ifdef TCP_OFFLOAD
3160 	if (is_offload(sc)) {
3161 		iaq->nofldrxq = t4_nofldrxq;
3162 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
3163 	}
3164 #endif
3165 #ifdef DEV_NETMAP
3166 	iaq->nnmtxq_vi = t4_nnmtxq_vi;
3167 	iaq->nnmrxq_vi = t4_nnmrxq_vi;
3168 #endif
3169 
3170 	update_nirq(iaq, nports);
3171 	if (iaq->nirq <= navail &&
3172 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
3173 		/*
3174 		 * This is the normal case -- there are enough interrupts for
3175 		 * everything.
3176 		 */
3177 		goto done;
3178 	}
3179 
3180 	/*
3181 	 * If extra VIs have been configured try reducing their count and see if
3182 	 * that works.
3183 	 */
3184 	while (iaq->num_vis > 1) {
3185 		iaq->num_vis--;
3186 		update_nirq(iaq, nports);
3187 		if (iaq->nirq <= navail &&
3188 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
3189 			device_printf(sc->dev, "virtual interfaces per port "
3190 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
3191 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
3192 			    "itype %d, navail %u, nirq %d.\n",
3193 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
3194 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
3195 			    itype, navail, iaq->nirq);
3196 			goto done;
3197 		}
3198 	}
3199 
3200 	/*
3201 	 * Extra VIs will not be created.  Log a message if they were requested.
3202 	 */
3203 	MPASS(iaq->num_vis == 1);
3204 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
3205 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
3206 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
3207 	if (iaq->num_vis != t4_num_vis) {
3208 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
3209 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
3210 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
3211 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
3212 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
3213 	}
3214 
3215 	/*
3216 	 * Keep reducing the number of NIC rx queues to the next lower power of
3217 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
3218 	 * if that works.
3219 	 */
3220 	do {
3221 		if (iaq->nrxq > 1) {
3222 			do {
3223 				iaq->nrxq--;
3224 			} while (!powerof2(iaq->nrxq));
3225 		}
3226 		if (iaq->nofldrxq > 1)
3227 			iaq->nofldrxq >>= 1;
3228 
3229 		old_nirq = iaq->nirq;
3230 		update_nirq(iaq, nports);
3231 		if (iaq->nirq <= navail &&
3232 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
3233 			device_printf(sc->dev, "running with reduced number of "
3234 			    "rx queues because of shortage of interrupts.  "
3235 			    "nrxq=%u, nofldrxq=%u.  "
3236 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
3237 			    iaq->nofldrxq, itype, navail, iaq->nirq);
3238 			goto done;
3239 		}
3240 	} while (old_nirq != iaq->nirq);
3241 
3242 	/* One interrupt for everything.  Ugh. */
3243 	device_printf(sc->dev, "running with minimal number of queues.  "
3244 	    "itype %d, navail %u.\n", itype, navail);
3245 	iaq->nirq = 1;
3246 	MPASS(iaq->nrxq == 1);
3247 	iaq->ntxq = 1;
3248 	if (iaq->nofldrxq > 1)
3249 		iaq->nofldtxq = 1;
3250 done:
3251 	MPASS(iaq->num_vis > 0);
3252 	if (iaq->num_vis > 1) {
3253 		MPASS(iaq->nrxq_vi > 0);
3254 		MPASS(iaq->ntxq_vi > 0);
3255 	}
3256 	MPASS(iaq->nirq > 0);
3257 	MPASS(iaq->nrxq > 0);
3258 	MPASS(iaq->ntxq > 0);
3259 	if (itype == INTR_MSI) {
3260 		MPASS(powerof2(iaq->nirq));
3261 	}
3262 }
3263 
3264 static int
3265 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
3266 {
3267 	int rc, itype, navail, nalloc;
3268 
3269 	for (itype = INTR_MSIX; itype; itype >>= 1) {
3270 
3271 		if ((itype & t4_intr_types) == 0)
3272 			continue;	/* not allowed */
3273 
3274 		if (itype == INTR_MSIX)
3275 			navail = pci_msix_count(sc->dev);
3276 		else if (itype == INTR_MSI)
3277 			navail = pci_msi_count(sc->dev);
3278 		else
3279 			navail = 1;
3280 restart:
3281 		if (navail == 0)
3282 			continue;
3283 
3284 		calculate_iaq(sc, iaq, itype, navail);
3285 		nalloc = iaq->nirq;
3286 		rc = 0;
3287 		if (itype == INTR_MSIX)
3288 			rc = pci_alloc_msix(sc->dev, &nalloc);
3289 		else if (itype == INTR_MSI)
3290 			rc = pci_alloc_msi(sc->dev, &nalloc);
3291 
3292 		if (rc == 0 && nalloc > 0) {
3293 			if (nalloc == iaq->nirq)
3294 				return (0);
3295 
3296 			/*
3297 			 * Didn't get the number requested.  Use whatever number
3298 			 * the kernel is willing to allocate.
3299 			 */
3300 			device_printf(sc->dev, "fewer vectors than requested, "
3301 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
3302 			    itype, iaq->nirq, nalloc);
3303 			pci_release_msi(sc->dev);
3304 			navail = nalloc;
3305 			goto restart;
3306 		}
3307 
3308 		device_printf(sc->dev,
3309 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
3310 		    itype, rc, iaq->nirq, nalloc);
3311 	}
3312 
3313 	device_printf(sc->dev,
3314 	    "failed to find a usable interrupt type.  "
3315 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
3316 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
3317 
3318 	return (ENXIO);
3319 }
3320 
3321 #define FW_VERSION(chip) ( \
3322     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
3323     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
3324     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
3325     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
3326 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
3327 
3328 /* Just enough of fw_hdr to cover all version info. */
3329 struct fw_h {
3330 	__u8	ver;
3331 	__u8	chip;
3332 	__be16	len512;
3333 	__be32	fw_ver;
3334 	__be32	tp_microcode_ver;
3335 	__u8	intfver_nic;
3336 	__u8	intfver_vnic;
3337 	__u8	intfver_ofld;
3338 	__u8	intfver_ri;
3339 	__u8	intfver_iscsipdu;
3340 	__u8	intfver_iscsi;
3341 	__u8	intfver_fcoepdu;
3342 	__u8	intfver_fcoe;
3343 };
3344 /* Spot check a couple of fields. */
3345 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
3346 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
3347 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
3348 
3349 struct fw_info {
3350 	uint8_t chip;
3351 	char *kld_name;
3352 	char *fw_mod_name;
3353 	struct fw_h fw_h;
3354 } fw_info[] = {
3355 	{
3356 		.chip = CHELSIO_T4,
3357 		.kld_name = "t4fw_cfg",
3358 		.fw_mod_name = "t4fw",
3359 		.fw_h = {
3360 			.chip = FW_HDR_CHIP_T4,
3361 			.fw_ver = htobe32(FW_VERSION(T4)),
3362 			.intfver_nic = FW_INTFVER(T4, NIC),
3363 			.intfver_vnic = FW_INTFVER(T4, VNIC),
3364 			.intfver_ofld = FW_INTFVER(T4, OFLD),
3365 			.intfver_ri = FW_INTFVER(T4, RI),
3366 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
3367 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
3368 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
3369 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
3370 		},
3371 	}, {
3372 		.chip = CHELSIO_T5,
3373 		.kld_name = "t5fw_cfg",
3374 		.fw_mod_name = "t5fw",
3375 		.fw_h = {
3376 			.chip = FW_HDR_CHIP_T5,
3377 			.fw_ver = htobe32(FW_VERSION(T5)),
3378 			.intfver_nic = FW_INTFVER(T5, NIC),
3379 			.intfver_vnic = FW_INTFVER(T5, VNIC),
3380 			.intfver_ofld = FW_INTFVER(T5, OFLD),
3381 			.intfver_ri = FW_INTFVER(T5, RI),
3382 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
3383 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
3384 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
3385 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
3386 		},
3387 	}, {
3388 		.chip = CHELSIO_T6,
3389 		.kld_name = "t6fw_cfg",
3390 		.fw_mod_name = "t6fw",
3391 		.fw_h = {
3392 			.chip = FW_HDR_CHIP_T6,
3393 			.fw_ver = htobe32(FW_VERSION(T6)),
3394 			.intfver_nic = FW_INTFVER(T6, NIC),
3395 			.intfver_vnic = FW_INTFVER(T6, VNIC),
3396 			.intfver_ofld = FW_INTFVER(T6, OFLD),
3397 			.intfver_ri = FW_INTFVER(T6, RI),
3398 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
3399 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
3400 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
3401 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
3402 		},
3403 	}
3404 };
3405 
3406 static struct fw_info *
3407 find_fw_info(int chip)
3408 {
3409 	int i;
3410 
3411 	for (i = 0; i < nitems(fw_info); i++) {
3412 		if (fw_info[i].chip == chip)
3413 			return (&fw_info[i]);
3414 	}
3415 	return (NULL);
3416 }
3417 
3418 /*
3419  * Is the given firmware API compatible with the one the driver was compiled
3420  * with?
3421  */
3422 static int
3423 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
3424 {
3425 
3426 	/* short circuit if it's the exact same firmware version */
3427 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
3428 		return (1);
3429 
3430 	/*
3431 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
3432 	 * features that are supported in the driver.
3433 	 */
3434 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
3435 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
3436 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
3437 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
3438 		return (1);
3439 #undef SAME_INTF
3440 
3441 	return (0);
3442 }
3443 
3444 static int
3445 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
3446     const struct firmware **fw)
3447 {
3448 	struct fw_info *fw_info;
3449 
3450 	*dcfg = NULL;
3451 	if (fw != NULL)
3452 		*fw = NULL;
3453 
3454 	fw_info = find_fw_info(chip_id(sc));
3455 	if (fw_info == NULL) {
3456 		device_printf(sc->dev,
3457 		    "unable to look up firmware information for chip %d.\n",
3458 		    chip_id(sc));
3459 		return (EINVAL);
3460 	}
3461 
3462 	*dcfg = firmware_get(fw_info->kld_name);
3463 	if (*dcfg != NULL) {
3464 		if (fw != NULL)
3465 			*fw = firmware_get(fw_info->fw_mod_name);
3466 		return (0);
3467 	}
3468 
3469 	return (ENOENT);
3470 }
3471 
3472 static void
3473 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
3474     const struct firmware *fw)
3475 {
3476 
3477 	if (fw != NULL)
3478 		firmware_put(fw, FIRMWARE_UNLOAD);
3479 	if (dcfg != NULL)
3480 		firmware_put(dcfg, FIRMWARE_UNLOAD);
3481 }
3482 
3483 /*
3484  * Return values:
3485  * 0 means no firmware install attempted.
3486  * ERESTART means a firmware install was attempted and was successful.
3487  * +ve errno means a firmware install was attempted but failed.
3488  */
3489 static int
3490 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
3491     const struct fw_h *drv_fw, const char *reason, int *already)
3492 {
3493 	const struct firmware *cfg, *fw;
3494 	const uint32_t c = be32toh(card_fw->fw_ver);
3495 	uint32_t d, k;
3496 	int rc, fw_install;
3497 	struct fw_h bundled_fw;
3498 	bool load_attempted;
3499 
3500 	cfg = fw = NULL;
3501 	load_attempted = false;
3502 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
3503 
3504 	if (reason != NULL)
3505 		goto install;
3506 
3507 	if ((sc->flags & FW_OK) == 0) {
3508 
3509 		if (c == 0xffffffff) {
3510 			reason = "missing";
3511 			goto install;
3512 		}
3513 
3514 		return (0);
3515 	}
3516 
3517 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
3518 	if (t4_fw_install < 0) {
3519 		rc = load_fw_module(sc, &cfg, &fw);
3520 		if (rc != 0 || fw == NULL) {
3521 			device_printf(sc->dev,
3522 			    "failed to load firmware module: %d. cfg %p, fw %p;"
3523 			    " will use compiled-in firmware version for"
3524 			    "hw.cxgbe.fw_install checks.\n",
3525 			    rc, cfg, fw);
3526 		} else {
3527 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
3528 		}
3529 		load_attempted = true;
3530 	}
3531 	d = be32toh(bundled_fw.fw_ver);
3532 
3533 	if (!fw_compatible(card_fw, &bundled_fw)) {
3534 		reason = "incompatible or unusable";
3535 		goto install;
3536 	}
3537 
3538 	if (d > c) {
3539 		reason = "older than the version bundled with this driver";
3540 		goto install;
3541 	}
3542 
3543 	if (fw_install == 2 && d != c) {
3544 		reason = "different than the version bundled with this driver";
3545 		goto install;
3546 	}
3547 
3548 	/* No reason to do anything to the firmware already on the card. */
3549 	rc = 0;
3550 	goto done;
3551 
3552 install:
3553 	rc = 0;
3554 	if ((*already)++)
3555 		goto done;
3556 
3557 	if (fw_install == 0) {
3558 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
3559 		    "but the driver is prohibited from installing a firmware "
3560 		    "on the card.\n",
3561 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
3562 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
3563 
3564 		goto done;
3565 	}
3566 
3567 	/*
3568 	 * We'll attempt to install a firmware.  Load the module first (if it
3569 	 * hasn't been loaded already).
3570 	 */
3571 	if (!load_attempted) {
3572 		rc = load_fw_module(sc, &cfg, &fw);
3573 		if (rc != 0 || fw == NULL) {
3574 			device_printf(sc->dev,
3575 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
3576 			    rc, cfg, fw);
3577 			/* carry on */
3578 		}
3579 	}
3580 	if (fw == NULL) {
3581 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
3582 		    "but the driver cannot take corrective action because it "
3583 		    "is unable to load the firmware module.\n",
3584 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
3585 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
3586 		rc = sc->flags & FW_OK ? 0 : ENOENT;
3587 		goto done;
3588 	}
3589 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
3590 	if (k != d) {
3591 		MPASS(t4_fw_install > 0);
3592 		device_printf(sc->dev,
3593 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
3594 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
3595 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
3596 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
3597 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
3598 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
3599 		rc = sc->flags & FW_OK ? 0 : EINVAL;
3600 		goto done;
3601 	}
3602 
3603 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
3604 	    "installing firmware %u.%u.%u.%u on card.\n",
3605 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
3606 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
3607 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
3608 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
3609 
3610 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
3611 	if (rc != 0) {
3612 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
3613 	} else {
3614 		/* Installed successfully, update the cached header too. */
3615 		rc = ERESTART;
3616 		memcpy(card_fw, fw->data, sizeof(*card_fw));
3617 	}
3618 done:
3619 	unload_fw_module(sc, cfg, fw);
3620 
3621 	return (rc);
3622 }
3623 
3624 /*
3625  * Establish contact with the firmware and attempt to become the master driver.
3626  *
3627  * A firmware will be installed to the card if needed (if the driver is allowed
3628  * to do so).
3629  */
3630 static int
3631 contact_firmware(struct adapter *sc)
3632 {
3633 	int rc, already = 0;
3634 	enum dev_state state;
3635 	struct fw_info *fw_info;
3636 	struct fw_hdr *card_fw;		/* fw on the card */
3637 	const struct fw_h *drv_fw;
3638 
3639 	fw_info = find_fw_info(chip_id(sc));
3640 	if (fw_info == NULL) {
3641 		device_printf(sc->dev,
3642 		    "unable to look up firmware information for chip %d.\n",
3643 		    chip_id(sc));
3644 		return (EINVAL);
3645 	}
3646 	drv_fw = &fw_info->fw_h;
3647 
3648 	/* Read the header of the firmware on the card */
3649 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
3650 restart:
3651 	rc = -t4_get_fw_hdr(sc, card_fw);
3652 	if (rc != 0) {
3653 		device_printf(sc->dev,
3654 		    "unable to read firmware header from card's flash: %d\n",
3655 		    rc);
3656 		goto done;
3657 	}
3658 
3659 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
3660 	    &already);
3661 	if (rc == ERESTART)
3662 		goto restart;
3663 	if (rc != 0)
3664 		goto done;
3665 
3666 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
3667 	if (rc < 0 || state == DEV_STATE_ERR) {
3668 		rc = -rc;
3669 		device_printf(sc->dev,
3670 		    "failed to connect to the firmware: %d, %d.  "
3671 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
3672 #if 0
3673 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
3674 		    "not responding properly to HELLO", &already) == ERESTART)
3675 			goto restart;
3676 #endif
3677 		goto done;
3678 	}
3679 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
3680 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
3681 
3682 	if (rc == sc->pf) {
3683 		sc->flags |= MASTER_PF;
3684 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
3685 		    NULL, &already);
3686 		if (rc == ERESTART)
3687 			rc = 0;
3688 		else if (rc != 0)
3689 			goto done;
3690 	} else if (state == DEV_STATE_UNINIT) {
3691 		/*
3692 		 * We didn't get to be the master so we definitely won't be
3693 		 * configuring the chip.  It's a bug if someone else hasn't
3694 		 * configured it already.
3695 		 */
3696 		device_printf(sc->dev, "couldn't be master(%d), "
3697 		    "device not already initialized either(%d).  "
3698 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
3699 		rc = EPROTO;
3700 		goto done;
3701 	} else {
3702 		/*
3703 		 * Some other PF is the master and has configured the chip.
3704 		 * This is allowed but untested.
3705 		 */
3706 		device_printf(sc->dev, "PF%d is master, device state %d.  "
3707 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
3708 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
3709 		sc->cfcsum = 0;
3710 		rc = 0;
3711 	}
3712 done:
3713 	if (rc != 0 && sc->flags & FW_OK) {
3714 		t4_fw_bye(sc, sc->mbox);
3715 		sc->flags &= ~FW_OK;
3716 	}
3717 	free(card_fw, M_CXGBE);
3718 	return (rc);
3719 }
3720 
3721 static int
3722 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
3723     uint32_t mtype, uint32_t moff)
3724 {
3725 	struct fw_info *fw_info;
3726 	const struct firmware *dcfg, *rcfg = NULL;
3727 	const uint32_t *cfdata;
3728 	uint32_t cflen, addr;
3729 	int rc;
3730 
3731 	load_fw_module(sc, &dcfg, NULL);
3732 
3733 	/* Card specific interpretation of "default". */
3734 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
3735 		if (pci_get_device(sc->dev) == 0x440a)
3736 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
3737 		if (is_fpga(sc))
3738 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
3739 	}
3740 
3741 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
3742 		if (dcfg == NULL) {
3743 			device_printf(sc->dev,
3744 			    "KLD with default config is not available.\n");
3745 			rc = ENOENT;
3746 			goto done;
3747 		}
3748 		cfdata = dcfg->data;
3749 		cflen = dcfg->datasize & ~3;
3750 	} else {
3751 		char s[32];
3752 
3753 		fw_info = find_fw_info(chip_id(sc));
3754 		if (fw_info == NULL) {
3755 			device_printf(sc->dev,
3756 			    "unable to look up firmware information for chip %d.\n",
3757 			    chip_id(sc));
3758 			rc = EINVAL;
3759 			goto done;
3760 		}
3761 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
3762 
3763 		rcfg = firmware_get(s);
3764 		if (rcfg == NULL) {
3765 			device_printf(sc->dev,
3766 			    "unable to load module \"%s\" for configuration "
3767 			    "profile \"%s\".\n", s, cfg_file);
3768 			rc = ENOENT;
3769 			goto done;
3770 		}
3771 		cfdata = rcfg->data;
3772 		cflen = rcfg->datasize & ~3;
3773 	}
3774 
3775 	if (cflen > FLASH_CFG_MAX_SIZE) {
3776 		device_printf(sc->dev,
3777 		    "config file too long (%d, max allowed is %d).\n",
3778 		    cflen, FLASH_CFG_MAX_SIZE);
3779 		rc = EINVAL;
3780 		goto done;
3781 	}
3782 
3783 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
3784 	if (rc != 0) {
3785 		device_printf(sc->dev,
3786 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
3787 		    __func__, mtype, moff, cflen, rc);
3788 		rc = EINVAL;
3789 		goto done;
3790 	}
3791 	write_via_memwin(sc, 2, addr, cfdata, cflen);
3792 done:
3793 	if (rcfg != NULL)
3794 		firmware_put(rcfg, FIRMWARE_UNLOAD);
3795 	unload_fw_module(sc, dcfg, NULL);
3796 	return (rc);
3797 }
3798 
3799 struct caps_allowed {
3800 	uint16_t nbmcaps;
3801 	uint16_t linkcaps;
3802 	uint16_t switchcaps;
3803 	uint16_t niccaps;
3804 	uint16_t toecaps;
3805 	uint16_t rdmacaps;
3806 	uint16_t cryptocaps;
3807 	uint16_t iscsicaps;
3808 	uint16_t fcoecaps;
3809 };
3810 
3811 #define FW_PARAM_DEV(param) \
3812 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
3813 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
3814 #define FW_PARAM_PFVF(param) \
3815 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
3816 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
3817 
3818 /*
3819  * Provide a configuration profile to the firmware and have it initialize the
3820  * chip accordingly.  This may involve uploading a configuration file to the
3821  * card.
3822  */
3823 static int
3824 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
3825     const struct caps_allowed *caps_allowed)
3826 {
3827 	int rc;
3828 	struct fw_caps_config_cmd caps;
3829 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
3830 
3831 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
3832 	if (rc != 0) {
3833 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
3834 		return (rc);
3835 	}
3836 
3837 	bzero(&caps, sizeof(caps));
3838 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
3839 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
3840 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
3841 		mtype = 0;
3842 		moff = 0;
3843 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
3844 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
3845 		mtype = FW_MEMTYPE_FLASH;
3846 		moff = t4_flash_cfg_addr(sc);
3847 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
3848 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
3849 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
3850 		    FW_LEN16(caps));
3851 	} else {
3852 		/*
3853 		 * Ask the firmware where it wants us to upload the config file.
3854 		 */
3855 		param = FW_PARAM_DEV(CF);
3856 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3857 		if (rc != 0) {
3858 			/* No support for config file?  Shouldn't happen. */
3859 			device_printf(sc->dev,
3860 			    "failed to query config file location: %d.\n", rc);
3861 			goto done;
3862 		}
3863 		mtype = G_FW_PARAMS_PARAM_Y(val);
3864 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
3865 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
3866 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
3867 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
3868 		    FW_LEN16(caps));
3869 
3870 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
3871 		if (rc != 0) {
3872 			device_printf(sc->dev,
3873 			    "failed to upload config file to card: %d.\n", rc);
3874 			goto done;
3875 		}
3876 	}
3877 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
3878 	if (rc != 0) {
3879 		device_printf(sc->dev, "failed to pre-process config file: %d "
3880 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
3881 		goto done;
3882 	}
3883 
3884 	finicsum = be32toh(caps.finicsum);
3885 	cfcsum = be32toh(caps.cfcsum);	/* actual */
3886 	if (finicsum != cfcsum) {
3887 		device_printf(sc->dev,
3888 		    "WARNING: config file checksum mismatch: %08x %08x\n",
3889 		    finicsum, cfcsum);
3890 	}
3891 	sc->cfcsum = cfcsum;
3892 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
3893 
3894 	/*
3895 	 * Let the firmware know what features will (not) be used so it can tune
3896 	 * things accordingly.
3897 	 */
3898 #define LIMIT_CAPS(x) do { \
3899 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
3900 } while (0)
3901 	LIMIT_CAPS(nbm);
3902 	LIMIT_CAPS(link);
3903 	LIMIT_CAPS(switch);
3904 	LIMIT_CAPS(nic);
3905 	LIMIT_CAPS(toe);
3906 	LIMIT_CAPS(rdma);
3907 	LIMIT_CAPS(crypto);
3908 	LIMIT_CAPS(iscsi);
3909 	LIMIT_CAPS(fcoe);
3910 #undef LIMIT_CAPS
3911 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
3912 		/*
3913 		 * TOE and hashfilters are mutually exclusive.  It is a config
3914 		 * file or firmware bug if both are reported as available.  Try
3915 		 * to cope with the situation in non-debug builds by disabling
3916 		 * TOE.
3917 		 */
3918 		MPASS(caps.toecaps == 0);
3919 
3920 		caps.toecaps = 0;
3921 		caps.rdmacaps = 0;
3922 		caps.iscsicaps = 0;
3923 	}
3924 
3925 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
3926 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
3927 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
3928 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
3929 	if (rc != 0) {
3930 		device_printf(sc->dev,
3931 		    "failed to process config file: %d.\n", rc);
3932 		goto done;
3933 	}
3934 
3935 	t4_tweak_chip_settings(sc);
3936 
3937 	/* get basic stuff going */
3938 	rc = -t4_fw_initialize(sc, sc->mbox);
3939 	if (rc != 0) {
3940 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
3941 		goto done;
3942 	}
3943 done:
3944 	return (rc);
3945 }
3946 
3947 /*
3948  * Partition chip resources for use between various PFs, VFs, etc.
3949  */
3950 static int
3951 partition_resources(struct adapter *sc)
3952 {
3953 	char cfg_file[sizeof(t4_cfg_file)];
3954 	struct caps_allowed caps_allowed;
3955 	int rc;
3956 	bool fallback;
3957 
3958 	/* Only the master driver gets to configure the chip resources. */
3959 	MPASS(sc->flags & MASTER_PF);
3960 
3961 #define COPY_CAPS(x) do { \
3962 	caps_allowed.x##caps = t4_##x##caps_allowed; \
3963 } while (0)
3964 	bzero(&caps_allowed, sizeof(caps_allowed));
3965 	COPY_CAPS(nbm);
3966 	COPY_CAPS(link);
3967 	COPY_CAPS(switch);
3968 	COPY_CAPS(nic);
3969 	COPY_CAPS(toe);
3970 	COPY_CAPS(rdma);
3971 	COPY_CAPS(crypto);
3972 	COPY_CAPS(iscsi);
3973 	COPY_CAPS(fcoe);
3974 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
3975 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
3976 retry:
3977 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
3978 	if (rc != 0 && fallback) {
3979 		device_printf(sc->dev,
3980 		    "failed (%d) to configure card with \"%s\" profile, "
3981 		    "will fall back to a basic configuration and retry.\n",
3982 		    rc, cfg_file);
3983 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
3984 		bzero(&caps_allowed, sizeof(caps_allowed));
3985 		COPY_CAPS(nbm);
3986 		COPY_CAPS(link);
3987 		COPY_CAPS(switch);
3988 		COPY_CAPS(nic);
3989 		fallback = false;
3990 		goto retry;
3991 	}
3992 #undef COPY_CAPS
3993 	return (rc);
3994 }
3995 
3996 /*
3997  * Retrieve parameters that are needed (or nice to have) very early.
3998  */
3999 static int
4000 get_params__pre_init(struct adapter *sc)
4001 {
4002 	int rc;
4003 	uint32_t param[2], val[2];
4004 
4005 	t4_get_version_info(sc);
4006 
4007 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
4008 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
4009 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
4010 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
4011 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
4012 
4013 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
4014 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
4015 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
4016 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
4017 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
4018 
4019 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
4020 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
4021 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
4022 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
4023 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
4024 
4025 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
4026 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
4027 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
4028 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
4029 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
4030 
4031 	param[0] = FW_PARAM_DEV(PORTVEC);
4032 	param[1] = FW_PARAM_DEV(CCLK);
4033 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4034 	if (rc != 0) {
4035 		device_printf(sc->dev,
4036 		    "failed to query parameters (pre_init): %d.\n", rc);
4037 		return (rc);
4038 	}
4039 
4040 	sc->params.portvec = val[0];
4041 	sc->params.nports = bitcount32(val[0]);
4042 	sc->params.vpd.cclk = val[1];
4043 
4044 	/* Read device log parameters. */
4045 	rc = -t4_init_devlog_params(sc, 1);
4046 	if (rc == 0)
4047 		fixup_devlog_params(sc);
4048 	else {
4049 		device_printf(sc->dev,
4050 		    "failed to get devlog parameters: %d.\n", rc);
4051 		rc = 0;	/* devlog isn't critical for device operation */
4052 	}
4053 
4054 	return (rc);
4055 }
4056 
4057 /*
4058  * Retrieve various parameters that are of interest to the driver.  The device
4059  * has been initialized by the firmware at this point.
4060  */
4061 static int
4062 get_params__post_init(struct adapter *sc)
4063 {
4064 	int rc;
4065 	uint32_t param[7], val[7];
4066 	struct fw_caps_config_cmd caps;
4067 
4068 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
4069 	param[1] = FW_PARAM_PFVF(EQ_START);
4070 	param[2] = FW_PARAM_PFVF(FILTER_START);
4071 	param[3] = FW_PARAM_PFVF(FILTER_END);
4072 	param[4] = FW_PARAM_PFVF(L2T_START);
4073 	param[5] = FW_PARAM_PFVF(L2T_END);
4074 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
4075 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
4076 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
4077 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
4078 	if (rc != 0) {
4079 		device_printf(sc->dev,
4080 		    "failed to query parameters (post_init): %d.\n", rc);
4081 		return (rc);
4082 	}
4083 
4084 	sc->sge.iq_start = val[0];
4085 	sc->sge.eq_start = val[1];
4086 	if ((int)val[3] > (int)val[2]) {
4087 		sc->tids.ftid_base = val[2];
4088 		sc->tids.ftid_end = val[3];
4089 		sc->tids.nftids = val[3] - val[2] + 1;
4090 	}
4091 	sc->vres.l2t.start = val[4];
4092 	sc->vres.l2t.size = val[5] - val[4] + 1;
4093 	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
4094 	    ("%s: L2 table size (%u) larger than expected (%u)",
4095 	    __func__, sc->vres.l2t.size, L2T_SIZE));
4096 	sc->params.core_vdd = val[6];
4097 
4098 	if (chip_id(sc) >= CHELSIO_T6) {
4099 
4100 #ifdef INVARIANTS
4101 		if (sc->params.fw_vers >=
4102 		    (V_FW_HDR_FW_VER_MAJOR(1) | V_FW_HDR_FW_VER_MINOR(20) |
4103 		    V_FW_HDR_FW_VER_MICRO(1) | V_FW_HDR_FW_VER_BUILD(0))) {
4104 			/*
4105 			 * Note that the code to enable the region should run
4106 			 * before t4_fw_initialize and not here.  This is just a
4107 			 * reminder to add said code.
4108 			 */
4109 			device_printf(sc->dev,
4110 			    "hpfilter region not enabled.\n");
4111 		}
4112 #endif
4113 
4114 		sc->tids.tid_base = t4_read_reg(sc,
4115 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
4116 
4117 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
4118 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
4119 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4120 		if (rc != 0) {
4121 			device_printf(sc->dev,
4122 			   "failed to query hpfilter parameters: %d.\n", rc);
4123 			return (rc);
4124 		}
4125 		if ((int)val[1] > (int)val[0]) {
4126 			sc->tids.hpftid_base = val[0];
4127 			sc->tids.hpftid_end = val[1];
4128 			sc->tids.nhpftids = val[1] - val[0] + 1;
4129 
4130 			/*
4131 			 * These should go off if the layout changes and the
4132 			 * driver needs to catch up.
4133 			 */
4134 			MPASS(sc->tids.hpftid_base == 0);
4135 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
4136 		}
4137 	}
4138 
4139 	/*
4140 	 * MPSBGMAP is queried separately because only recent firmwares support
4141 	 * it as a parameter and we don't want the compound query above to fail
4142 	 * on older firmwares.
4143 	 */
4144 	param[0] = FW_PARAM_DEV(MPSBGMAP);
4145 	val[0] = 0;
4146 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
4147 	if (rc == 0)
4148 		sc->params.mps_bg_map = val[0];
4149 	else
4150 		sc->params.mps_bg_map = 0;
4151 
4152 	/*
4153 	 * Determine whether the firmware supports the filter2 work request.
4154 	 * This is queried separately for the same reason as MPSBGMAP above.
4155 	 */
4156 	param[0] = FW_PARAM_DEV(FILTER2_WR);
4157 	val[0] = 0;
4158 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
4159 	if (rc == 0)
4160 		sc->params.filter2_wr_support = val[0] != 0;
4161 	else
4162 		sc->params.filter2_wr_support = 0;
4163 
4164 	/*
4165 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
4166 	 * This is queried separately for the same reason as other params above.
4167 	 */
4168 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
4169 	val[0] = 0;
4170 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
4171 	if (rc == 0)
4172 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
4173 	else
4174 		sc->params.ulptx_memwrite_dsgl = false;
4175 
4176 	/* get capabilites */
4177 	bzero(&caps, sizeof(caps));
4178 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4179 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
4180 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4181 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
4182 	if (rc != 0) {
4183 		device_printf(sc->dev,
4184 		    "failed to get card capabilities: %d.\n", rc);
4185 		return (rc);
4186 	}
4187 
4188 #define READ_CAPS(x) do { \
4189 	sc->x = htobe16(caps.x); \
4190 } while (0)
4191 	READ_CAPS(nbmcaps);
4192 	READ_CAPS(linkcaps);
4193 	READ_CAPS(switchcaps);
4194 	READ_CAPS(niccaps);
4195 	READ_CAPS(toecaps);
4196 	READ_CAPS(rdmacaps);
4197 	READ_CAPS(cryptocaps);
4198 	READ_CAPS(iscsicaps);
4199 	READ_CAPS(fcoecaps);
4200 
4201 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
4202 		MPASS(chip_id(sc) > CHELSIO_T4);
4203 		MPASS(sc->toecaps == 0);
4204 		sc->toecaps = 0;
4205 
4206 		param[0] = FW_PARAM_DEV(NTID);
4207 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
4208 		if (rc != 0) {
4209 			device_printf(sc->dev,
4210 			    "failed to query HASHFILTER parameters: %d.\n", rc);
4211 			return (rc);
4212 		}
4213 		sc->tids.ntids = val[0];
4214 		if (sc->params.fw_vers <
4215 		    (V_FW_HDR_FW_VER_MAJOR(1) | V_FW_HDR_FW_VER_MINOR(20) |
4216 		    V_FW_HDR_FW_VER_MICRO(5) | V_FW_HDR_FW_VER_BUILD(0))) {
4217 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
4218 			sc->tids.ntids -= sc->tids.nhpftids;
4219 		}
4220 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
4221 		sc->params.hash_filter = 1;
4222 	}
4223 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
4224 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
4225 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
4226 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
4227 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
4228 		if (rc != 0) {
4229 			device_printf(sc->dev,
4230 			    "failed to query NIC parameters: %d.\n", rc);
4231 			return (rc);
4232 		}
4233 		if ((int)val[1] > (int)val[0]) {
4234 			sc->tids.etid_base = val[0];
4235 			sc->tids.etid_end = val[1];
4236 			sc->tids.netids = val[1] - val[0] + 1;
4237 			sc->params.eo_wr_cred = val[2];
4238 			sc->params.ethoffload = 1;
4239 		}
4240 	}
4241 	if (sc->toecaps) {
4242 		/* query offload-related parameters */
4243 		param[0] = FW_PARAM_DEV(NTID);
4244 		param[1] = FW_PARAM_PFVF(SERVER_START);
4245 		param[2] = FW_PARAM_PFVF(SERVER_END);
4246 		param[3] = FW_PARAM_PFVF(TDDP_START);
4247 		param[4] = FW_PARAM_PFVF(TDDP_END);
4248 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
4249 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
4250 		if (rc != 0) {
4251 			device_printf(sc->dev,
4252 			    "failed to query TOE parameters: %d.\n", rc);
4253 			return (rc);
4254 		}
4255 		sc->tids.ntids = val[0];
4256 		if (sc->params.fw_vers <
4257 		    (V_FW_HDR_FW_VER_MAJOR(1) | V_FW_HDR_FW_VER_MINOR(20) |
4258 		    V_FW_HDR_FW_VER_MICRO(5) | V_FW_HDR_FW_VER_BUILD(0))) {
4259 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
4260 			sc->tids.ntids -= sc->tids.nhpftids;
4261 		}
4262 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
4263 		if ((int)val[2] > (int)val[1]) {
4264 			sc->tids.stid_base = val[1];
4265 			sc->tids.nstids = val[2] - val[1] + 1;
4266 		}
4267 		sc->vres.ddp.start = val[3];
4268 		sc->vres.ddp.size = val[4] - val[3] + 1;
4269 		sc->params.ofldq_wr_cred = val[5];
4270 		sc->params.offload = 1;
4271 	} else {
4272 		/*
4273 		 * The firmware attempts memfree TOE configuration for -SO cards
4274 		 * and will report toecaps=0 if it runs out of resources (this
4275 		 * depends on the config file).  It may not report 0 for other
4276 		 * capabilities dependent on the TOE in this case.  Set them to
4277 		 * 0 here so that the driver doesn't bother tracking resources
4278 		 * that will never be used.
4279 		 */
4280 		sc->iscsicaps = 0;
4281 		sc->rdmacaps = 0;
4282 	}
4283 	if (sc->rdmacaps) {
4284 		param[0] = FW_PARAM_PFVF(STAG_START);
4285 		param[1] = FW_PARAM_PFVF(STAG_END);
4286 		param[2] = FW_PARAM_PFVF(RQ_START);
4287 		param[3] = FW_PARAM_PFVF(RQ_END);
4288 		param[4] = FW_PARAM_PFVF(PBL_START);
4289 		param[5] = FW_PARAM_PFVF(PBL_END);
4290 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
4291 		if (rc != 0) {
4292 			device_printf(sc->dev,
4293 			    "failed to query RDMA parameters(1): %d.\n", rc);
4294 			return (rc);
4295 		}
4296 		sc->vres.stag.start = val[0];
4297 		sc->vres.stag.size = val[1] - val[0] + 1;
4298 		sc->vres.rq.start = val[2];
4299 		sc->vres.rq.size = val[3] - val[2] + 1;
4300 		sc->vres.pbl.start = val[4];
4301 		sc->vres.pbl.size = val[5] - val[4] + 1;
4302 
4303 		param[0] = FW_PARAM_PFVF(SQRQ_START);
4304 		param[1] = FW_PARAM_PFVF(SQRQ_END);
4305 		param[2] = FW_PARAM_PFVF(CQ_START);
4306 		param[3] = FW_PARAM_PFVF(CQ_END);
4307 		param[4] = FW_PARAM_PFVF(OCQ_START);
4308 		param[5] = FW_PARAM_PFVF(OCQ_END);
4309 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
4310 		if (rc != 0) {
4311 			device_printf(sc->dev,
4312 			    "failed to query RDMA parameters(2): %d.\n", rc);
4313 			return (rc);
4314 		}
4315 		sc->vres.qp.start = val[0];
4316 		sc->vres.qp.size = val[1] - val[0] + 1;
4317 		sc->vres.cq.start = val[2];
4318 		sc->vres.cq.size = val[3] - val[2] + 1;
4319 		sc->vres.ocq.start = val[4];
4320 		sc->vres.ocq.size = val[5] - val[4] + 1;
4321 
4322 		param[0] = FW_PARAM_PFVF(SRQ_START);
4323 		param[1] = FW_PARAM_PFVF(SRQ_END);
4324 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
4325 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
4326 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
4327 		if (rc != 0) {
4328 			device_printf(sc->dev,
4329 			    "failed to query RDMA parameters(3): %d.\n", rc);
4330 			return (rc);
4331 		}
4332 		sc->vres.srq.start = val[0];
4333 		sc->vres.srq.size = val[1] - val[0] + 1;
4334 		sc->params.max_ordird_qp = val[2];
4335 		sc->params.max_ird_adapter = val[3];
4336 	}
4337 	if (sc->iscsicaps) {
4338 		param[0] = FW_PARAM_PFVF(ISCSI_START);
4339 		param[1] = FW_PARAM_PFVF(ISCSI_END);
4340 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4341 		if (rc != 0) {
4342 			device_printf(sc->dev,
4343 			    "failed to query iSCSI parameters: %d.\n", rc);
4344 			return (rc);
4345 		}
4346 		sc->vres.iscsi.start = val[0];
4347 		sc->vres.iscsi.size = val[1] - val[0] + 1;
4348 	}
4349 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
4350 		param[0] = FW_PARAM_PFVF(TLS_START);
4351 		param[1] = FW_PARAM_PFVF(TLS_END);
4352 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4353 		if (rc != 0) {
4354 			device_printf(sc->dev,
4355 			    "failed to query TLS parameters: %d.\n", rc);
4356 			return (rc);
4357 		}
4358 		sc->vres.key.start = val[0];
4359 		sc->vres.key.size = val[1] - val[0] + 1;
4360 	}
4361 
4362 	t4_init_sge_params(sc);
4363 
4364 	/*
4365 	 * We've got the params we wanted to query via the firmware.  Now grab
4366 	 * some others directly from the chip.
4367 	 */
4368 	rc = t4_read_chip_settings(sc);
4369 
4370 	return (rc);
4371 }
4372 
4373 static int
4374 set_params__post_init(struct adapter *sc)
4375 {
4376 	uint32_t param, val;
4377 #ifdef TCP_OFFLOAD
4378 	int i, v, shift;
4379 #endif
4380 
4381 	/* ask for encapsulated CPLs */
4382 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
4383 	val = 1;
4384 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4385 
4386 	/* Enable 32b port caps if the firmware supports it. */
4387 	param = FW_PARAM_PFVF(PORT_CAPS32);
4388 	val = 1;
4389 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
4390 		sc->params.port_caps32 = 1;
4391 
4392 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
4393 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
4394 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
4395 	    V_MASKFILTER(val - 1));
4396 
4397 #ifdef TCP_OFFLOAD
4398 	/*
4399 	 * Override the TOE timers with user provided tunables.  This is not the
4400 	 * recommended way to change the timers (the firmware config file is) so
4401 	 * these tunables are not documented.
4402 	 *
4403 	 * All the timer tunables are in microseconds.
4404 	 */
4405 	if (t4_toe_keepalive_idle != 0) {
4406 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
4407 		v &= M_KEEPALIVEIDLE;
4408 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
4409 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
4410 	}
4411 	if (t4_toe_keepalive_interval != 0) {
4412 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
4413 		v &= M_KEEPALIVEINTVL;
4414 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
4415 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
4416 	}
4417 	if (t4_toe_keepalive_count != 0) {
4418 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
4419 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
4420 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
4421 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
4422 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
4423 	}
4424 	if (t4_toe_rexmt_min != 0) {
4425 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
4426 		v &= M_RXTMIN;
4427 		t4_set_reg_field(sc, A_TP_RXT_MIN,
4428 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
4429 	}
4430 	if (t4_toe_rexmt_max != 0) {
4431 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
4432 		v &= M_RXTMAX;
4433 		t4_set_reg_field(sc, A_TP_RXT_MAX,
4434 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
4435 	}
4436 	if (t4_toe_rexmt_count != 0) {
4437 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
4438 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
4439 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
4440 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
4441 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
4442 	}
4443 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
4444 		if (t4_toe_rexmt_backoff[i] != -1) {
4445 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
4446 			shift = (i & 3) << 3;
4447 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
4448 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
4449 		}
4450 	}
4451 #endif
4452 	return (0);
4453 }
4454 
4455 #undef FW_PARAM_PFVF
4456 #undef FW_PARAM_DEV
4457 
4458 static void
4459 t4_set_desc(struct adapter *sc)
4460 {
4461 	char buf[128];
4462 	struct adapter_params *p = &sc->params;
4463 
4464 	snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
4465 
4466 	device_set_desc_copy(sc->dev, buf);
4467 }
4468 
4469 static inline void
4470 ifmedia_add4(struct ifmedia *ifm, int m)
4471 {
4472 
4473 	ifmedia_add(ifm, m, 0, NULL);
4474 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
4475 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
4476 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
4477 }
4478 
4479 /*
4480  * This is the selected media, which is not quite the same as the active media.
4481  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
4482  * and active are not the same, and "media: Ethernet selected" otherwise.
4483  */
4484 static void
4485 set_current_media(struct port_info *pi)
4486 {
4487 	struct link_config *lc;
4488 	struct ifmedia *ifm;
4489 	int mword;
4490 	u_int speed;
4491 
4492 	PORT_LOCK_ASSERT_OWNED(pi);
4493 
4494 	/* Leave current media alone if it's already set to IFM_NONE. */
4495 	ifm = &pi->media;
4496 	if (ifm->ifm_cur != NULL &&
4497 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
4498 		return;
4499 
4500 	lc = &pi->link_cfg;
4501 	if (lc->requested_aneg != AUTONEG_DISABLE &&
4502 	    lc->supported & FW_PORT_CAP32_ANEG) {
4503 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
4504 		return;
4505 	}
4506 	mword = IFM_ETHER | IFM_FDX;
4507 	if (lc->requested_fc & PAUSE_TX)
4508 		mword |= IFM_ETH_TXPAUSE;
4509 	if (lc->requested_fc & PAUSE_RX)
4510 		mword |= IFM_ETH_RXPAUSE;
4511 	if (lc->requested_speed == 0)
4512 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
4513 	else
4514 		speed = lc->requested_speed;
4515 	mword |= port_mword(pi, speed_to_fwcap(speed));
4516 	ifmedia_set(ifm, mword);
4517 }
4518 
4519 /*
4520  * Returns true if the ifmedia list for the port cannot change.
4521  */
4522 static bool
4523 fixed_ifmedia(struct port_info *pi)
4524 {
4525 
4526 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
4527 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
4528 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
4529 	    pi->port_type == FW_PORT_TYPE_KX4 ||
4530 	    pi->port_type == FW_PORT_TYPE_KX ||
4531 	    pi->port_type == FW_PORT_TYPE_KR ||
4532 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
4533 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
4534 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
4535 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
4536 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
4537 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
4538 }
4539 
4540 static void
4541 build_medialist(struct port_info *pi)
4542 {
4543 	uint32_t ss, speed;
4544 	int unknown, mword, bit;
4545 	struct link_config *lc;
4546 	struct ifmedia *ifm;
4547 
4548 	PORT_LOCK_ASSERT_OWNED(pi);
4549 
4550 	if (pi->flags & FIXED_IFMEDIA)
4551 		return;
4552 
4553 	/*
4554 	 * Rebuild the ifmedia list.
4555 	 */
4556 	ifm = &pi->media;
4557 	ifmedia_removeall(ifm);
4558 	lc = &pi->link_cfg;
4559 	ss = G_FW_PORT_CAP32_SPEED(lc->supported); /* Supported Speeds */
4560 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
4561 		MPASS(ss != 0);
4562 no_media:
4563 		MPASS(LIST_EMPTY(&ifm->ifm_list));
4564 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
4565 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
4566 		return;
4567 	}
4568 
4569 	unknown = 0;
4570 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
4571 		speed = 1 << bit;
4572 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
4573 		if (ss & speed) {
4574 			mword = port_mword(pi, speed);
4575 			if (mword == IFM_NONE) {
4576 				goto no_media;
4577 			} else if (mword == IFM_UNKNOWN)
4578 				unknown++;
4579 			else
4580 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
4581 		}
4582 	}
4583 	if (unknown > 0) /* Add one unknown for all unknown media types. */
4584 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
4585 	if (lc->supported & FW_PORT_CAP32_ANEG)
4586 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
4587 
4588 	set_current_media(pi);
4589 }
4590 
4591 /*
4592  * Initialize the requested fields in the link config based on driver tunables.
4593  */
4594 static void
4595 init_link_config(struct port_info *pi)
4596 {
4597 	struct link_config *lc = &pi->link_cfg;
4598 
4599 	PORT_LOCK_ASSERT_OWNED(pi);
4600 
4601 	lc->requested_speed = 0;
4602 
4603 	if (t4_autoneg == 0)
4604 		lc->requested_aneg = AUTONEG_DISABLE;
4605 	else if (t4_autoneg == 1)
4606 		lc->requested_aneg = AUTONEG_ENABLE;
4607 	else
4608 		lc->requested_aneg = AUTONEG_AUTO;
4609 
4610 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
4611 	    PAUSE_AUTONEG);
4612 
4613 	if (t4_fec == -1 || t4_fec & FEC_AUTO)
4614 		lc->requested_fec = FEC_AUTO;
4615 	else {
4616 		lc->requested_fec = FEC_NONE;
4617 		if (t4_fec & FEC_RS)
4618 			lc->requested_fec |= FEC_RS;
4619 		if (t4_fec & FEC_BASER_RS)
4620 			lc->requested_fec |= FEC_BASER_RS;
4621 	}
4622 }
4623 
4624 /*
4625  * Makes sure that all requested settings comply with what's supported by the
4626  * port.  Returns the number of settings that were invalid and had to be fixed.
4627  */
4628 static int
4629 fixup_link_config(struct port_info *pi)
4630 {
4631 	int n = 0;
4632 	struct link_config *lc = &pi->link_cfg;
4633 	uint32_t fwspeed;
4634 
4635 	PORT_LOCK_ASSERT_OWNED(pi);
4636 
4637 	/* Speed (when not autonegotiating) */
4638 	if (lc->requested_speed != 0) {
4639 		fwspeed = speed_to_fwcap(lc->requested_speed);
4640 		if ((fwspeed & lc->supported) == 0) {
4641 			n++;
4642 			lc->requested_speed = 0;
4643 		}
4644 	}
4645 
4646 	/* Link autonegotiation */
4647 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
4648 	    lc->requested_aneg == AUTONEG_DISABLE ||
4649 	    lc->requested_aneg == AUTONEG_AUTO);
4650 	if (lc->requested_aneg == AUTONEG_ENABLE &&
4651 	    !(lc->supported & FW_PORT_CAP32_ANEG)) {
4652 		n++;
4653 		lc->requested_aneg = AUTONEG_AUTO;
4654 	}
4655 
4656 	/* Flow control */
4657 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
4658 	if (lc->requested_fc & PAUSE_TX &&
4659 	    !(lc->supported & FW_PORT_CAP32_FC_TX)) {
4660 		n++;
4661 		lc->requested_fc &= ~PAUSE_TX;
4662 	}
4663 	if (lc->requested_fc & PAUSE_RX &&
4664 	    !(lc->supported & FW_PORT_CAP32_FC_RX)) {
4665 		n++;
4666 		lc->requested_fc &= ~PAUSE_RX;
4667 	}
4668 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
4669 	    !(lc->supported & FW_PORT_CAP32_FORCE_PAUSE)) {
4670 		n++;
4671 		lc->requested_fc |= PAUSE_AUTONEG;
4672 	}
4673 
4674 	/* FEC */
4675 	if ((lc->requested_fec & FEC_RS &&
4676 	    !(lc->supported & FW_PORT_CAP32_FEC_RS)) ||
4677 	    (lc->requested_fec & FEC_BASER_RS &&
4678 	    !(lc->supported & FW_PORT_CAP32_FEC_BASER_RS))) {
4679 		n++;
4680 		lc->requested_fec = FEC_AUTO;
4681 	}
4682 
4683 	return (n);
4684 }
4685 
4686 /*
4687  * Apply the requested L1 settings, which are expected to be valid, to the
4688  * hardware.
4689  */
4690 static int
4691 apply_link_config(struct port_info *pi)
4692 {
4693 	struct adapter *sc = pi->adapter;
4694 	struct link_config *lc = &pi->link_cfg;
4695 	int rc;
4696 
4697 #ifdef INVARIANTS
4698 	ASSERT_SYNCHRONIZED_OP(sc);
4699 	PORT_LOCK_ASSERT_OWNED(pi);
4700 
4701 	if (lc->requested_aneg == AUTONEG_ENABLE)
4702 		MPASS(lc->supported & FW_PORT_CAP32_ANEG);
4703 	if (!(lc->requested_fc & PAUSE_AUTONEG))
4704 		MPASS(lc->supported & FW_PORT_CAP32_FORCE_PAUSE);
4705 	if (lc->requested_fc & PAUSE_TX)
4706 		MPASS(lc->supported & FW_PORT_CAP32_FC_TX);
4707 	if (lc->requested_fc & PAUSE_RX)
4708 		MPASS(lc->supported & FW_PORT_CAP32_FC_RX);
4709 	if (lc->requested_fec & FEC_RS)
4710 		MPASS(lc->supported & FW_PORT_CAP32_FEC_RS);
4711 	if (lc->requested_fec & FEC_BASER_RS)
4712 		MPASS(lc->supported & FW_PORT_CAP32_FEC_BASER_RS);
4713 #endif
4714 	rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
4715 	if (rc != 0) {
4716 		/* Don't complain if the VF driver gets back an EPERM. */
4717 		if (!(sc->flags & IS_VF) || rc != FW_EPERM)
4718 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
4719 	} else {
4720 		/*
4721 		 * An L1_CFG will almost always result in a link-change event if
4722 		 * the link is up, and the driver will refresh the actual
4723 		 * fec/fc/etc. when the notification is processed.  If the link
4724 		 * is down then the actual settings are meaningless.
4725 		 *
4726 		 * This takes care of the case where a change in the L1 settings
4727 		 * may not result in a notification.
4728 		 */
4729 		if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
4730 			lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
4731 	}
4732 	return (rc);
4733 }
4734 
4735 #define FW_MAC_EXACT_CHUNK	7
4736 
4737 /*
4738  * Program the port's XGMAC based on parameters in ifnet.  The caller also
4739  * indicates which parameters should be programmed (the rest are left alone).
4740  */
4741 int
4742 update_mac_settings(struct ifnet *ifp, int flags)
4743 {
4744 	int rc = 0;
4745 	struct vi_info *vi = ifp->if_softc;
4746 	struct port_info *pi = vi->pi;
4747 	struct adapter *sc = pi->adapter;
4748 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
4749 
4750 	ASSERT_SYNCHRONIZED_OP(sc);
4751 	KASSERT(flags, ("%s: not told what to update.", __func__));
4752 
4753 	if (flags & XGMAC_MTU)
4754 		mtu = ifp->if_mtu;
4755 
4756 	if (flags & XGMAC_PROMISC)
4757 		promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
4758 
4759 	if (flags & XGMAC_ALLMULTI)
4760 		allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
4761 
4762 	if (flags & XGMAC_VLANEX)
4763 		vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
4764 
4765 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
4766 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
4767 		    allmulti, 1, vlanex, false);
4768 		if (rc) {
4769 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
4770 			    rc);
4771 			return (rc);
4772 		}
4773 	}
4774 
4775 	if (flags & XGMAC_UCADDR) {
4776 		uint8_t ucaddr[ETHER_ADDR_LEN];
4777 
4778 		bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
4779 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
4780 		    ucaddr, true, true);
4781 		if (rc < 0) {
4782 			rc = -rc;
4783 			if_printf(ifp, "change_mac failed: %d\n", rc);
4784 			return (rc);
4785 		} else {
4786 			vi->xact_addr_filt = rc;
4787 			rc = 0;
4788 		}
4789 	}
4790 
4791 	if (flags & XGMAC_MCADDRS) {
4792 		const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
4793 		int del = 1;
4794 		uint64_t hash = 0;
4795 		struct ifmultiaddr *ifma;
4796 		int i = 0, j;
4797 
4798 		if_maddr_rlock(ifp);
4799 		CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
4800 			if (ifma->ifma_addr->sa_family != AF_LINK)
4801 				continue;
4802 			mcaddr[i] =
4803 			    LLADDR((struct sockaddr_dl *)ifma->ifma_addr);
4804 			MPASS(ETHER_IS_MULTICAST(mcaddr[i]));
4805 			i++;
4806 
4807 			if (i == FW_MAC_EXACT_CHUNK) {
4808 				rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
4809 				    del, i, mcaddr, NULL, &hash, 0);
4810 				if (rc < 0) {
4811 					rc = -rc;
4812 					for (j = 0; j < i; j++) {
4813 						if_printf(ifp,
4814 						    "failed to add mc address"
4815 						    " %02x:%02x:%02x:"
4816 						    "%02x:%02x:%02x rc=%d\n",
4817 						    mcaddr[j][0], mcaddr[j][1],
4818 						    mcaddr[j][2], mcaddr[j][3],
4819 						    mcaddr[j][4], mcaddr[j][5],
4820 						    rc);
4821 					}
4822 					goto mcfail;
4823 				}
4824 				del = 0;
4825 				i = 0;
4826 			}
4827 		}
4828 		if (i > 0) {
4829 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, del, i,
4830 			    mcaddr, NULL, &hash, 0);
4831 			if (rc < 0) {
4832 				rc = -rc;
4833 				for (j = 0; j < i; j++) {
4834 					if_printf(ifp,
4835 					    "failed to add mc address"
4836 					    " %02x:%02x:%02x:"
4837 					    "%02x:%02x:%02x rc=%d\n",
4838 					    mcaddr[j][0], mcaddr[j][1],
4839 					    mcaddr[j][2], mcaddr[j][3],
4840 					    mcaddr[j][4], mcaddr[j][5],
4841 					    rc);
4842 				}
4843 				goto mcfail;
4844 			}
4845 		}
4846 
4847 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, hash, 0);
4848 		if (rc != 0)
4849 			if_printf(ifp, "failed to set mc address hash: %d", rc);
4850 mcfail:
4851 		if_maddr_runlock(ifp);
4852 	}
4853 
4854 	return (rc);
4855 }
4856 
4857 /*
4858  * {begin|end}_synchronized_op must be called from the same thread.
4859  */
4860 int
4861 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
4862     char *wmesg)
4863 {
4864 	int rc, pri;
4865 
4866 #ifdef WITNESS
4867 	/* the caller thinks it's ok to sleep, but is it really? */
4868 	if (flags & SLEEP_OK)
4869 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
4870 		    "begin_synchronized_op");
4871 #endif
4872 
4873 	if (INTR_OK)
4874 		pri = PCATCH;
4875 	else
4876 		pri = 0;
4877 
4878 	ADAPTER_LOCK(sc);
4879 	for (;;) {
4880 
4881 		if (vi && IS_DOOMED(vi)) {
4882 			rc = ENXIO;
4883 			goto done;
4884 		}
4885 
4886 		if (!IS_BUSY(sc)) {
4887 			rc = 0;
4888 			break;
4889 		}
4890 
4891 		if (!(flags & SLEEP_OK)) {
4892 			rc = EBUSY;
4893 			goto done;
4894 		}
4895 
4896 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
4897 			rc = EINTR;
4898 			goto done;
4899 		}
4900 	}
4901 
4902 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
4903 	SET_BUSY(sc);
4904 #ifdef INVARIANTS
4905 	sc->last_op = wmesg;
4906 	sc->last_op_thr = curthread;
4907 	sc->last_op_flags = flags;
4908 #endif
4909 
4910 done:
4911 	if (!(flags & HOLD_LOCK) || rc)
4912 		ADAPTER_UNLOCK(sc);
4913 
4914 	return (rc);
4915 }
4916 
4917 /*
4918  * Tell if_ioctl and if_init that the VI is going away.  This is
4919  * special variant of begin_synchronized_op and must be paired with a
4920  * call to end_synchronized_op.
4921  */
4922 void
4923 doom_vi(struct adapter *sc, struct vi_info *vi)
4924 {
4925 
4926 	ADAPTER_LOCK(sc);
4927 	SET_DOOMED(vi);
4928 	wakeup(&sc->flags);
4929 	while (IS_BUSY(sc))
4930 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
4931 	SET_BUSY(sc);
4932 #ifdef INVARIANTS
4933 	sc->last_op = "t4detach";
4934 	sc->last_op_thr = curthread;
4935 	sc->last_op_flags = 0;
4936 #endif
4937 	ADAPTER_UNLOCK(sc);
4938 }
4939 
4940 /*
4941  * {begin|end}_synchronized_op must be called from the same thread.
4942  */
4943 void
4944 end_synchronized_op(struct adapter *sc, int flags)
4945 {
4946 
4947 	if (flags & LOCK_HELD)
4948 		ADAPTER_LOCK_ASSERT_OWNED(sc);
4949 	else
4950 		ADAPTER_LOCK(sc);
4951 
4952 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
4953 	CLR_BUSY(sc);
4954 	wakeup(&sc->flags);
4955 	ADAPTER_UNLOCK(sc);
4956 }
4957 
4958 static int
4959 cxgbe_init_synchronized(struct vi_info *vi)
4960 {
4961 	struct port_info *pi = vi->pi;
4962 	struct adapter *sc = pi->adapter;
4963 	struct ifnet *ifp = vi->ifp;
4964 	int rc = 0, i;
4965 	struct sge_txq *txq;
4966 
4967 	ASSERT_SYNCHRONIZED_OP(sc);
4968 
4969 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
4970 		return (0);	/* already running */
4971 
4972 	if (!(sc->flags & FULL_INIT_DONE) &&
4973 	    ((rc = adapter_full_init(sc)) != 0))
4974 		return (rc);	/* error message displayed already */
4975 
4976 	if (!(vi->flags & VI_INIT_DONE) &&
4977 	    ((rc = vi_full_init(vi)) != 0))
4978 		return (rc); /* error message displayed already */
4979 
4980 	rc = update_mac_settings(ifp, XGMAC_ALL);
4981 	if (rc)
4982 		goto done;	/* error message displayed already */
4983 
4984 	PORT_LOCK(pi);
4985 	if (pi->up_vis == 0) {
4986 		t4_update_port_info(pi);
4987 		fixup_link_config(pi);
4988 		build_medialist(pi);
4989 		apply_link_config(pi);
4990 	}
4991 
4992 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
4993 	if (rc != 0) {
4994 		if_printf(ifp, "enable_vi failed: %d\n", rc);
4995 		PORT_UNLOCK(pi);
4996 		goto done;
4997 	}
4998 
4999 	/*
5000 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
5001 	 * if this changes.
5002 	 */
5003 
5004 	for_each_txq(vi, i, txq) {
5005 		TXQ_LOCK(txq);
5006 		txq->eq.flags |= EQ_ENABLED;
5007 		TXQ_UNLOCK(txq);
5008 	}
5009 
5010 	/*
5011 	 * The first iq of the first port to come up is used for tracing.
5012 	 */
5013 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
5014 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
5015 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
5016 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
5017 		    V_QUEUENUMBER(sc->traceq));
5018 		pi->flags |= HAS_TRACEQ;
5019 	}
5020 
5021 	/* all ok */
5022 	pi->up_vis++;
5023 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
5024 
5025 	if (pi->nvi > 1 || sc->flags & IS_VF)
5026 		callout_reset(&vi->tick, hz, vi_tick, vi);
5027 	else
5028 		callout_reset(&pi->tick, hz, cxgbe_tick, pi);
5029 	PORT_UNLOCK(pi);
5030 done:
5031 	if (rc != 0)
5032 		cxgbe_uninit_synchronized(vi);
5033 
5034 	return (rc);
5035 }
5036 
5037 /*
5038  * Idempotent.
5039  */
5040 static int
5041 cxgbe_uninit_synchronized(struct vi_info *vi)
5042 {
5043 	struct port_info *pi = vi->pi;
5044 	struct adapter *sc = pi->adapter;
5045 	struct ifnet *ifp = vi->ifp;
5046 	int rc, i;
5047 	struct sge_txq *txq;
5048 
5049 	ASSERT_SYNCHRONIZED_OP(sc);
5050 
5051 	if (!(vi->flags & VI_INIT_DONE)) {
5052 		if (__predict_false(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5053 			KASSERT(0, ("uninited VI is running"));
5054 			if_printf(ifp, "uninited VI with running ifnet.  "
5055 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
5056 			    "if_drv_flags 0x%08x\n", vi->flags, ifp->if_flags,
5057 			    ifp->if_drv_flags);
5058 		}
5059 		return (0);
5060 	}
5061 
5062 	/*
5063 	 * Disable the VI so that all its data in either direction is discarded
5064 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
5065 	 * tick) intact as the TP can deliver negative advice or data that it's
5066 	 * holding in its RAM (for an offloaded connection) even after the VI is
5067 	 * disabled.
5068 	 */
5069 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
5070 	if (rc) {
5071 		if_printf(ifp, "disable_vi failed: %d\n", rc);
5072 		return (rc);
5073 	}
5074 
5075 	for_each_txq(vi, i, txq) {
5076 		TXQ_LOCK(txq);
5077 		txq->eq.flags &= ~EQ_ENABLED;
5078 		TXQ_UNLOCK(txq);
5079 	}
5080 
5081 	PORT_LOCK(pi);
5082 	if (pi->nvi > 1 || sc->flags & IS_VF)
5083 		callout_stop(&vi->tick);
5084 	else
5085 		callout_stop(&pi->tick);
5086 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5087 		PORT_UNLOCK(pi);
5088 		return (0);
5089 	}
5090 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
5091 	pi->up_vis--;
5092 	if (pi->up_vis > 0) {
5093 		PORT_UNLOCK(pi);
5094 		return (0);
5095 	}
5096 
5097 	pi->link_cfg.link_ok = false;
5098 	pi->link_cfg.speed = 0;
5099 	pi->link_cfg.link_down_rc = 255;
5100 	t4_os_link_changed(pi);
5101 	PORT_UNLOCK(pi);
5102 
5103 	return (0);
5104 }
5105 
5106 /*
5107  * It is ok for this function to fail midway and return right away.  t4_detach
5108  * will walk the entire sc->irq list and clean up whatever is valid.
5109  */
5110 int
5111 t4_setup_intr_handlers(struct adapter *sc)
5112 {
5113 	int rc, rid, p, q, v;
5114 	char s[8];
5115 	struct irq *irq;
5116 	struct port_info *pi;
5117 	struct vi_info *vi;
5118 	struct sge *sge = &sc->sge;
5119 	struct sge_rxq *rxq;
5120 #ifdef TCP_OFFLOAD
5121 	struct sge_ofld_rxq *ofld_rxq;
5122 #endif
5123 #ifdef DEV_NETMAP
5124 	struct sge_nm_rxq *nm_rxq;
5125 #endif
5126 #ifdef RSS
5127 	int nbuckets = rss_getnumbuckets();
5128 #endif
5129 
5130 	/*
5131 	 * Setup interrupts.
5132 	 */
5133 	irq = &sc->irq[0];
5134 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
5135 	if (forwarding_intr_to_fwq(sc))
5136 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
5137 
5138 	/* Multiple interrupts. */
5139 	if (sc->flags & IS_VF)
5140 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
5141 		    ("%s: too few intr.", __func__));
5142 	else
5143 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
5144 		    ("%s: too few intr.", __func__));
5145 
5146 	/* The first one is always error intr on PFs */
5147 	if (!(sc->flags & IS_VF)) {
5148 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
5149 		if (rc != 0)
5150 			return (rc);
5151 		irq++;
5152 		rid++;
5153 	}
5154 
5155 	/* The second one is always the firmware event queue (first on VFs) */
5156 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
5157 	if (rc != 0)
5158 		return (rc);
5159 	irq++;
5160 	rid++;
5161 
5162 	for_each_port(sc, p) {
5163 		pi = sc->port[p];
5164 		for_each_vi(pi, v, vi) {
5165 			vi->first_intr = rid - 1;
5166 
5167 			if (vi->nnmrxq > 0) {
5168 				int n = max(vi->nrxq, vi->nnmrxq);
5169 
5170 				rxq = &sge->rxq[vi->first_rxq];
5171 #ifdef DEV_NETMAP
5172 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
5173 #endif
5174 				for (q = 0; q < n; q++) {
5175 					snprintf(s, sizeof(s), "%x%c%x", p,
5176 					    'a' + v, q);
5177 					if (q < vi->nrxq)
5178 						irq->rxq = rxq++;
5179 #ifdef DEV_NETMAP
5180 					if (q < vi->nnmrxq)
5181 						irq->nm_rxq = nm_rxq++;
5182 
5183 					if (irq->nm_rxq != NULL &&
5184 					    irq->rxq == NULL) {
5185 						/* Netmap rx only */
5186 						rc = t4_alloc_irq(sc, irq, rid,
5187 						    t4_nm_intr, irq->nm_rxq, s);
5188 					}
5189 					if (irq->nm_rxq != NULL &&
5190 					    irq->rxq != NULL) {
5191 						/* NIC and Netmap rx */
5192 						rc = t4_alloc_irq(sc, irq, rid,
5193 						    t4_vi_intr, irq, s);
5194 					}
5195 #endif
5196 					if (irq->rxq != NULL &&
5197 					    irq->nm_rxq == NULL) {
5198 						/* NIC rx only */
5199 						rc = t4_alloc_irq(sc, irq, rid,
5200 						    t4_intr, irq->rxq, s);
5201 					}
5202 					if (rc != 0)
5203 						return (rc);
5204 #ifdef RSS
5205 					if (q < vi->nrxq) {
5206 						bus_bind_intr(sc->dev, irq->res,
5207 						    rss_getcpu(q % nbuckets));
5208 					}
5209 #endif
5210 					irq++;
5211 					rid++;
5212 					vi->nintr++;
5213 				}
5214 			} else {
5215 				for_each_rxq(vi, q, rxq) {
5216 					snprintf(s, sizeof(s), "%x%c%x", p,
5217 					    'a' + v, q);
5218 					rc = t4_alloc_irq(sc, irq, rid,
5219 					    t4_intr, rxq, s);
5220 					if (rc != 0)
5221 						return (rc);
5222 #ifdef RSS
5223 					bus_bind_intr(sc->dev, irq->res,
5224 					    rss_getcpu(q % nbuckets));
5225 #endif
5226 					irq++;
5227 					rid++;
5228 					vi->nintr++;
5229 				}
5230 			}
5231 #ifdef TCP_OFFLOAD
5232 			for_each_ofld_rxq(vi, q, ofld_rxq) {
5233 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
5234 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
5235 				    ofld_rxq, s);
5236 				if (rc != 0)
5237 					return (rc);
5238 				irq++;
5239 				rid++;
5240 				vi->nintr++;
5241 			}
5242 #endif
5243 		}
5244 	}
5245 	MPASS(irq == &sc->irq[sc->intr_count]);
5246 
5247 	return (0);
5248 }
5249 
5250 int
5251 adapter_full_init(struct adapter *sc)
5252 {
5253 	int rc, i;
5254 #ifdef RSS
5255 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
5256 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
5257 #endif
5258 
5259 	ASSERT_SYNCHRONIZED_OP(sc);
5260 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
5261 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
5262 	    ("%s: FULL_INIT_DONE already", __func__));
5263 
5264 	/*
5265 	 * queues that belong to the adapter (not any particular port).
5266 	 */
5267 	rc = t4_setup_adapter_queues(sc);
5268 	if (rc != 0)
5269 		goto done;
5270 
5271 	for (i = 0; i < nitems(sc->tq); i++) {
5272 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
5273 		    taskqueue_thread_enqueue, &sc->tq[i]);
5274 		if (sc->tq[i] == NULL) {
5275 			device_printf(sc->dev,
5276 			    "failed to allocate task queue %d\n", i);
5277 			rc = ENOMEM;
5278 			goto done;
5279 		}
5280 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
5281 		    device_get_nameunit(sc->dev), i);
5282 	}
5283 #ifdef RSS
5284 	MPASS(RSS_KEYSIZE == 40);
5285 	rss_getkey((void *)&raw_rss_key[0]);
5286 	for (i = 0; i < nitems(rss_key); i++) {
5287 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
5288 	}
5289 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
5290 #endif
5291 
5292 	if (!(sc->flags & IS_VF))
5293 		t4_intr_enable(sc);
5294 	sc->flags |= FULL_INIT_DONE;
5295 done:
5296 	if (rc != 0)
5297 		adapter_full_uninit(sc);
5298 
5299 	return (rc);
5300 }
5301 
5302 int
5303 adapter_full_uninit(struct adapter *sc)
5304 {
5305 	int i;
5306 
5307 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
5308 
5309 	t4_teardown_adapter_queues(sc);
5310 
5311 	for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
5312 		taskqueue_free(sc->tq[i]);
5313 		sc->tq[i] = NULL;
5314 	}
5315 
5316 	sc->flags &= ~FULL_INIT_DONE;
5317 
5318 	return (0);
5319 }
5320 
5321 #ifdef RSS
5322 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
5323     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
5324     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
5325     RSS_HASHTYPE_RSS_UDP_IPV6)
5326 
5327 /* Translates kernel hash types to hardware. */
5328 static int
5329 hashconfig_to_hashen(int hashconfig)
5330 {
5331 	int hashen = 0;
5332 
5333 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
5334 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
5335 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
5336 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
5337 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
5338 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
5339 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
5340 	}
5341 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
5342 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
5343 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
5344 	}
5345 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
5346 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
5347 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
5348 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
5349 
5350 	return (hashen);
5351 }
5352 
5353 /* Translates hardware hash types to kernel. */
5354 static int
5355 hashen_to_hashconfig(int hashen)
5356 {
5357 	int hashconfig = 0;
5358 
5359 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
5360 		/*
5361 		 * If UDP hashing was enabled it must have been enabled for
5362 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
5363 		 * enabling any 4-tuple hash is nonsense configuration.
5364 		 */
5365 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
5366 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
5367 
5368 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
5369 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
5370 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
5371 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
5372 	}
5373 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
5374 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
5375 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
5376 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
5377 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
5378 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
5379 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
5380 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
5381 
5382 	return (hashconfig);
5383 }
5384 #endif
5385 
5386 int
5387 vi_full_init(struct vi_info *vi)
5388 {
5389 	struct adapter *sc = vi->pi->adapter;
5390 	struct ifnet *ifp = vi->ifp;
5391 	uint16_t *rss;
5392 	struct sge_rxq *rxq;
5393 	int rc, i, j;
5394 #ifdef RSS
5395 	int nbuckets = rss_getnumbuckets();
5396 	int hashconfig = rss_gethashconfig();
5397 	int extra;
5398 #endif
5399 
5400 	ASSERT_SYNCHRONIZED_OP(sc);
5401 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
5402 	    ("%s: VI_INIT_DONE already", __func__));
5403 
5404 	sysctl_ctx_init(&vi->ctx);
5405 	vi->flags |= VI_SYSCTL_CTX;
5406 
5407 	/*
5408 	 * Allocate tx/rx/fl queues for this VI.
5409 	 */
5410 	rc = t4_setup_vi_queues(vi);
5411 	if (rc != 0)
5412 		goto done;	/* error message displayed already */
5413 
5414 	/*
5415 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
5416 	 */
5417 	if (vi->nrxq > vi->rss_size) {
5418 		if_printf(ifp, "nrxq (%d) > hw RSS table size (%d); "
5419 		    "some queues will never receive traffic.\n", vi->nrxq,
5420 		    vi->rss_size);
5421 	} else if (vi->rss_size % vi->nrxq) {
5422 		if_printf(ifp, "nrxq (%d), hw RSS table size (%d); "
5423 		    "expect uneven traffic distribution.\n", vi->nrxq,
5424 		    vi->rss_size);
5425 	}
5426 #ifdef RSS
5427 	if (vi->nrxq != nbuckets) {
5428 		if_printf(ifp, "nrxq (%d) != kernel RSS buckets (%d);"
5429 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
5430 	}
5431 #endif
5432 	rss = malloc(vi->rss_size * sizeof (*rss), M_CXGBE, M_ZERO | M_WAITOK);
5433 	for (i = 0; i < vi->rss_size;) {
5434 #ifdef RSS
5435 		j = rss_get_indirection_to_bucket(i);
5436 		j %= vi->nrxq;
5437 		rxq = &sc->sge.rxq[vi->first_rxq + j];
5438 		rss[i++] = rxq->iq.abs_id;
5439 #else
5440 		for_each_rxq(vi, j, rxq) {
5441 			rss[i++] = rxq->iq.abs_id;
5442 			if (i == vi->rss_size)
5443 				break;
5444 		}
5445 #endif
5446 	}
5447 
5448 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size, rss,
5449 	    vi->rss_size);
5450 	if (rc != 0) {
5451 		free(rss, M_CXGBE);
5452 		if_printf(ifp, "rss_config failed: %d\n", rc);
5453 		goto done;
5454 	}
5455 
5456 #ifdef RSS
5457 	vi->hashen = hashconfig_to_hashen(hashconfig);
5458 
5459 	/*
5460 	 * We may have had to enable some hashes even though the global config
5461 	 * wants them disabled.  This is a potential problem that must be
5462 	 * reported to the user.
5463 	 */
5464 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
5465 
5466 	/*
5467 	 * If we consider only the supported hash types, then the enabled hashes
5468 	 * are a superset of the requested hashes.  In other words, there cannot
5469 	 * be any supported hash that was requested but not enabled, but there
5470 	 * can be hashes that were not requested but had to be enabled.
5471 	 */
5472 	extra &= SUPPORTED_RSS_HASHTYPES;
5473 	MPASS((extra & hashconfig) == 0);
5474 
5475 	if (extra) {
5476 		if_printf(ifp,
5477 		    "global RSS config (0x%x) cannot be accommodated.\n",
5478 		    hashconfig);
5479 	}
5480 	if (extra & RSS_HASHTYPE_RSS_IPV4)
5481 		if_printf(ifp, "IPv4 2-tuple hashing forced on.\n");
5482 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
5483 		if_printf(ifp, "TCP/IPv4 4-tuple hashing forced on.\n");
5484 	if (extra & RSS_HASHTYPE_RSS_IPV6)
5485 		if_printf(ifp, "IPv6 2-tuple hashing forced on.\n");
5486 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
5487 		if_printf(ifp, "TCP/IPv6 4-tuple hashing forced on.\n");
5488 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
5489 		if_printf(ifp, "UDP/IPv4 4-tuple hashing forced on.\n");
5490 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
5491 		if_printf(ifp, "UDP/IPv6 4-tuple hashing forced on.\n");
5492 #else
5493 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
5494 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
5495 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
5496 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
5497 #endif
5498 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, rss[0], 0, 0);
5499 	if (rc != 0) {
5500 		free(rss, M_CXGBE);
5501 		if_printf(ifp, "rss hash/defaultq config failed: %d\n", rc);
5502 		goto done;
5503 	}
5504 
5505 	vi->rss = rss;
5506 	vi->flags |= VI_INIT_DONE;
5507 done:
5508 	if (rc != 0)
5509 		vi_full_uninit(vi);
5510 
5511 	return (rc);
5512 }
5513 
5514 /*
5515  * Idempotent.
5516  */
5517 int
5518 vi_full_uninit(struct vi_info *vi)
5519 {
5520 	struct port_info *pi = vi->pi;
5521 	struct adapter *sc = pi->adapter;
5522 	int i;
5523 	struct sge_rxq *rxq;
5524 	struct sge_txq *txq;
5525 #ifdef TCP_OFFLOAD
5526 	struct sge_ofld_rxq *ofld_rxq;
5527 #endif
5528 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
5529 	struct sge_wrq *ofld_txq;
5530 #endif
5531 
5532 	if (vi->flags & VI_INIT_DONE) {
5533 
5534 		/* Need to quiesce queues.  */
5535 
5536 		/* XXX: Only for the first VI? */
5537 		if (IS_MAIN_VI(vi) && !(sc->flags & IS_VF))
5538 			quiesce_wrq(sc, &sc->sge.ctrlq[pi->port_id]);
5539 
5540 		for_each_txq(vi, i, txq) {
5541 			quiesce_txq(sc, txq);
5542 		}
5543 
5544 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
5545 		for_each_ofld_txq(vi, i, ofld_txq) {
5546 			quiesce_wrq(sc, ofld_txq);
5547 		}
5548 #endif
5549 
5550 		for_each_rxq(vi, i, rxq) {
5551 			quiesce_iq(sc, &rxq->iq);
5552 			quiesce_fl(sc, &rxq->fl);
5553 		}
5554 
5555 #ifdef TCP_OFFLOAD
5556 		for_each_ofld_rxq(vi, i, ofld_rxq) {
5557 			quiesce_iq(sc, &ofld_rxq->iq);
5558 			quiesce_fl(sc, &ofld_rxq->fl);
5559 		}
5560 #endif
5561 		free(vi->rss, M_CXGBE);
5562 		free(vi->nm_rss, M_CXGBE);
5563 	}
5564 
5565 	t4_teardown_vi_queues(vi);
5566 	vi->flags &= ~VI_INIT_DONE;
5567 
5568 	return (0);
5569 }
5570 
5571 static void
5572 quiesce_txq(struct adapter *sc, struct sge_txq *txq)
5573 {
5574 	struct sge_eq *eq = &txq->eq;
5575 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
5576 
5577 	(void) sc;	/* unused */
5578 
5579 #ifdef INVARIANTS
5580 	TXQ_LOCK(txq);
5581 	MPASS((eq->flags & EQ_ENABLED) == 0);
5582 	TXQ_UNLOCK(txq);
5583 #endif
5584 
5585 	/* Wait for the mp_ring to empty. */
5586 	while (!mp_ring_is_idle(txq->r)) {
5587 		mp_ring_check_drainage(txq->r, 0);
5588 		pause("rquiesce", 1);
5589 	}
5590 
5591 	/* Then wait for the hardware to finish. */
5592 	while (spg->cidx != htobe16(eq->pidx))
5593 		pause("equiesce", 1);
5594 
5595 	/* Finally, wait for the driver to reclaim all descriptors. */
5596 	while (eq->cidx != eq->pidx)
5597 		pause("dquiesce", 1);
5598 }
5599 
5600 static void
5601 quiesce_wrq(struct adapter *sc, struct sge_wrq *wrq)
5602 {
5603 
5604 	/* XXXTX */
5605 }
5606 
5607 static void
5608 quiesce_iq(struct adapter *sc, struct sge_iq *iq)
5609 {
5610 	(void) sc;	/* unused */
5611 
5612 	/* Synchronize with the interrupt handler */
5613 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
5614 		pause("iqfree", 1);
5615 }
5616 
5617 static void
5618 quiesce_fl(struct adapter *sc, struct sge_fl *fl)
5619 {
5620 	mtx_lock(&sc->sfl_lock);
5621 	FL_LOCK(fl);
5622 	fl->flags |= FL_DOOMED;
5623 	FL_UNLOCK(fl);
5624 	callout_stop(&sc->sfl_callout);
5625 	mtx_unlock(&sc->sfl_lock);
5626 
5627 	KASSERT((fl->flags & FL_STARVING) == 0,
5628 	    ("%s: still starving", __func__));
5629 }
5630 
5631 static int
5632 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
5633     driver_intr_t *handler, void *arg, char *name)
5634 {
5635 	int rc;
5636 
5637 	irq->rid = rid;
5638 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
5639 	    RF_SHAREABLE | RF_ACTIVE);
5640 	if (irq->res == NULL) {
5641 		device_printf(sc->dev,
5642 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
5643 		return (ENOMEM);
5644 	}
5645 
5646 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
5647 	    NULL, handler, arg, &irq->tag);
5648 	if (rc != 0) {
5649 		device_printf(sc->dev,
5650 		    "failed to setup interrupt for rid %d, name %s: %d\n",
5651 		    rid, name, rc);
5652 	} else if (name)
5653 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
5654 
5655 	return (rc);
5656 }
5657 
5658 static int
5659 t4_free_irq(struct adapter *sc, struct irq *irq)
5660 {
5661 	if (irq->tag)
5662 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
5663 	if (irq->res)
5664 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
5665 
5666 	bzero(irq, sizeof(*irq));
5667 
5668 	return (0);
5669 }
5670 
5671 static void
5672 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
5673 {
5674 
5675 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
5676 	t4_get_regs(sc, buf, regs->len);
5677 }
5678 
5679 #define	A_PL_INDIR_CMD	0x1f8
5680 
5681 #define	S_PL_AUTOINC	31
5682 #define	M_PL_AUTOINC	0x1U
5683 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
5684 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
5685 
5686 #define	S_PL_VFID	20
5687 #define	M_PL_VFID	0xffU
5688 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
5689 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
5690 
5691 #define	S_PL_ADDR	0
5692 #define	M_PL_ADDR	0xfffffU
5693 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
5694 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
5695 
5696 #define	A_PL_INDIR_DATA	0x1fc
5697 
5698 static uint64_t
5699 read_vf_stat(struct adapter *sc, unsigned int viid, int reg)
5700 {
5701 	u32 stats[2];
5702 
5703 	mtx_assert(&sc->reg_lock, MA_OWNED);
5704 	if (sc->flags & IS_VF) {
5705 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
5706 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
5707 	} else {
5708 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
5709 		    V_PL_VFID(G_FW_VIID_VIN(viid)) |
5710 		    V_PL_ADDR(VF_MPS_REG(reg)));
5711 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
5712 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
5713 	}
5714 	return (((uint64_t)stats[1]) << 32 | stats[0]);
5715 }
5716 
5717 static void
5718 t4_get_vi_stats(struct adapter *sc, unsigned int viid,
5719     struct fw_vi_stats_vf *stats)
5720 {
5721 
5722 #define GET_STAT(name) \
5723 	read_vf_stat(sc, viid, A_MPS_VF_STAT_##name##_L)
5724 
5725 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
5726 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
5727 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
5728 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
5729 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
5730 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
5731 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
5732 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
5733 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
5734 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
5735 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
5736 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
5737 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
5738 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
5739 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
5740 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
5741 
5742 #undef GET_STAT
5743 }
5744 
5745 static void
5746 t4_clr_vi_stats(struct adapter *sc, unsigned int viid)
5747 {
5748 	int reg;
5749 
5750 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
5751 	    V_PL_VFID(G_FW_VIID_VIN(viid)) |
5752 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
5753 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
5754 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
5755 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
5756 }
5757 
5758 static void
5759 vi_refresh_stats(struct adapter *sc, struct vi_info *vi)
5760 {
5761 	struct timeval tv;
5762 	const struct timeval interval = {0, 250000};	/* 250ms */
5763 
5764 	if (!(vi->flags & VI_INIT_DONE))
5765 		return;
5766 
5767 	getmicrotime(&tv);
5768 	timevalsub(&tv, &interval);
5769 	if (timevalcmp(&tv, &vi->last_refreshed, <))
5770 		return;
5771 
5772 	mtx_lock(&sc->reg_lock);
5773 	t4_get_vi_stats(sc, vi->viid, &vi->stats);
5774 	getmicrotime(&vi->last_refreshed);
5775 	mtx_unlock(&sc->reg_lock);
5776 }
5777 
5778 static void
5779 cxgbe_refresh_stats(struct adapter *sc, struct port_info *pi)
5780 {
5781 	u_int i, v, tnl_cong_drops, bg_map;
5782 	struct timeval tv;
5783 	const struct timeval interval = {0, 250000};	/* 250ms */
5784 
5785 	getmicrotime(&tv);
5786 	timevalsub(&tv, &interval);
5787 	if (timevalcmp(&tv, &pi->last_refreshed, <))
5788 		return;
5789 
5790 	tnl_cong_drops = 0;
5791 	t4_get_port_stats(sc, pi->tx_chan, &pi->stats);
5792 	bg_map = pi->mps_bg_map;
5793 	while (bg_map) {
5794 		i = ffs(bg_map) - 1;
5795 		mtx_lock(&sc->reg_lock);
5796 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
5797 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
5798 		mtx_unlock(&sc->reg_lock);
5799 		tnl_cong_drops += v;
5800 		bg_map &= ~(1 << i);
5801 	}
5802 	pi->tnl_cong_drops = tnl_cong_drops;
5803 	getmicrotime(&pi->last_refreshed);
5804 }
5805 
5806 static void
5807 cxgbe_tick(void *arg)
5808 {
5809 	struct port_info *pi = arg;
5810 	struct adapter *sc = pi->adapter;
5811 
5812 	PORT_LOCK_ASSERT_OWNED(pi);
5813 	cxgbe_refresh_stats(sc, pi);
5814 
5815 	callout_schedule(&pi->tick, hz);
5816 }
5817 
5818 void
5819 vi_tick(void *arg)
5820 {
5821 	struct vi_info *vi = arg;
5822 	struct adapter *sc = vi->pi->adapter;
5823 
5824 	vi_refresh_stats(sc, vi);
5825 
5826 	callout_schedule(&vi->tick, hz);
5827 }
5828 
5829 /*
5830  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
5831  */
5832 static char *caps_decoder[] = {
5833 	"\20\001IPMI\002NCSI",				/* 0: NBM */
5834 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
5835 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
5836 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
5837 	    "\006HASHFILTER\007ETHOFLD",
5838 	"\20\001TOE",					/* 4: TOE */
5839 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
5840 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
5841 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
5842 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
5843 	    "\007T10DIF"
5844 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
5845 	"\20\001LOOKASIDE\002TLSKEYS",			/* 7: Crypto */
5846 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
5847 		    "\004PO_INITIATOR\005PO_TARGET",
5848 };
5849 
5850 void
5851 t4_sysctls(struct adapter *sc)
5852 {
5853 	struct sysctl_ctx_list *ctx;
5854 	struct sysctl_oid *oid;
5855 	struct sysctl_oid_list *children, *c0;
5856 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
5857 
5858 	ctx = device_get_sysctl_ctx(sc->dev);
5859 
5860 	/*
5861 	 * dev.t4nex.X.
5862 	 */
5863 	oid = device_get_sysctl_tree(sc->dev);
5864 	c0 = children = SYSCTL_CHILDREN(oid);
5865 
5866 	sc->sc_do_rxcopy = 1;
5867 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
5868 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
5869 
5870 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
5871 	    sc->params.nports, "# of ports");
5872 
5873 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
5874 	    CTLTYPE_STRING | CTLFLAG_RD, doorbells, (uintptr_t)&sc->doorbells,
5875 	    sysctl_bitfield_8b, "A", "available doorbells");
5876 
5877 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
5878 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
5879 
5880 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
5881 	    CTLTYPE_STRING | CTLFLAG_RD, sc->params.sge.timer_val,
5882 	    sizeof(sc->params.sge.timer_val), sysctl_int_array, "A",
5883 	    "interrupt holdoff timer values (us)");
5884 
5885 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
5886 	    CTLTYPE_STRING | CTLFLAG_RD, sc->params.sge.counter_val,
5887 	    sizeof(sc->params.sge.counter_val), sysctl_int_array, "A",
5888 	    "interrupt holdoff packet counter values");
5889 
5890 	t4_sge_sysctls(sc, ctx, children);
5891 
5892 	sc->lro_timeout = 100;
5893 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
5894 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
5895 
5896 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
5897 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
5898 
5899 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
5900 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
5901 
5902 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
5903 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
5904 
5905 	if (sc->flags & IS_VF)
5906 		return;
5907 
5908 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
5909 	    NULL, chip_rev(sc), "chip hardware revision");
5910 
5911 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
5912 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
5913 
5914 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
5915 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
5916 
5917 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
5918 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
5919 
5920 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
5921 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
5922 
5923 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
5924 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
5925 
5926 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
5927 	    sc->er_version, 0, "expansion ROM version");
5928 
5929 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
5930 	    sc->bs_version, 0, "bootstrap firmware version");
5931 
5932 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
5933 	    NULL, sc->params.scfg_vers, "serial config version");
5934 
5935 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
5936 	    NULL, sc->params.vpd_vers, "VPD version");
5937 
5938 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
5939 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
5940 
5941 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
5942 	    sc->cfcsum, "config file checksum");
5943 
5944 #define SYSCTL_CAP(name, n, text) \
5945 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
5946 	    CTLTYPE_STRING | CTLFLAG_RD, caps_decoder[n], (uintptr_t)&sc->name, \
5947 	    sysctl_bitfield_16b, "A", "available " text " capabilities")
5948 
5949 	SYSCTL_CAP(nbmcaps, 0, "NBM");
5950 	SYSCTL_CAP(linkcaps, 1, "link");
5951 	SYSCTL_CAP(switchcaps, 2, "switch");
5952 	SYSCTL_CAP(niccaps, 3, "NIC");
5953 	SYSCTL_CAP(toecaps, 4, "TCP offload");
5954 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
5955 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
5956 	SYSCTL_CAP(cryptocaps, 7, "crypto");
5957 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
5958 #undef SYSCTL_CAP
5959 
5960 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
5961 	    NULL, sc->tids.nftids, "number of filters");
5962 
5963 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature", CTLTYPE_INT |
5964 	    CTLFLAG_RD, sc, 0, sysctl_temperature, "I",
5965 	    "chip temperature (in Celsius)");
5966 
5967 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg", CTLTYPE_STRING |
5968 	    CTLFLAG_RD, sc, 0, sysctl_loadavg, "A",
5969 	    "microprocessor load averages (debug firmwares only)");
5970 
5971 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_vdd", CTLFLAG_RD,
5972 	    &sc->params.core_vdd, 0, "core Vdd (in mV)");
5973 
5974 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
5975 	    CTLTYPE_STRING | CTLFLAG_RD, sc, LOCAL_CPUS,
5976 	    sysctl_cpus, "A", "local CPUs");
5977 
5978 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
5979 	    CTLTYPE_STRING | CTLFLAG_RD, sc, INTR_CPUS,
5980 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
5981 
5982 	/*
5983 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
5984 	 */
5985 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
5986 	    CTLFLAG_RD | CTLFLAG_SKIP, NULL,
5987 	    "logs and miscellaneous information");
5988 	children = SYSCTL_CHILDREN(oid);
5989 
5990 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
5991 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5992 	    sysctl_cctrl, "A", "congestion control");
5993 
5994 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
5995 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5996 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
5997 
5998 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
5999 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 1,
6000 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
6001 
6002 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
6003 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 2,
6004 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
6005 
6006 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
6007 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 3,
6008 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
6009 
6010 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
6011 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 4,
6012 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
6013 
6014 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
6015 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 5,
6016 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
6017 
6018 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
6019 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6020 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_cim_la : sysctl_cim_la_t6,
6021 	    "A", "CIM logic analyzer");
6022 
6023 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
6024 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6025 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
6026 
6027 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
6028 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0 + CIM_NUM_IBQ,
6029 	    sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
6030 
6031 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
6032 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 1 + CIM_NUM_IBQ,
6033 	    sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
6034 
6035 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
6036 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 2 + CIM_NUM_IBQ,
6037 	    sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
6038 
6039 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
6040 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 3 + CIM_NUM_IBQ,
6041 	    sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
6042 
6043 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
6044 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 4 + CIM_NUM_IBQ,
6045 	    sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
6046 
6047 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
6048 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 5 + CIM_NUM_IBQ,
6049 	    sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
6050 
6051 	if (chip_id(sc) > CHELSIO_T4) {
6052 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
6053 		    CTLTYPE_STRING | CTLFLAG_RD, sc, 6 + CIM_NUM_IBQ,
6054 		    sysctl_cim_ibq_obq, "A", "CIM OBQ 6 (SGE0-RX)");
6055 
6056 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
6057 		    CTLTYPE_STRING | CTLFLAG_RD, sc, 7 + CIM_NUM_IBQ,
6058 		    sysctl_cim_ibq_obq, "A", "CIM OBQ 7 (SGE1-RX)");
6059 	}
6060 
6061 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
6062 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6063 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
6064 
6065 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
6066 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6067 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
6068 
6069 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
6070 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6071 	    sysctl_cpl_stats, "A", "CPL statistics");
6072 
6073 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
6074 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6075 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
6076 
6077 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
6078 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6079 	    sysctl_devlog, "A", "firmware's device log");
6080 
6081 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
6082 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6083 	    sysctl_fcoe_stats, "A", "FCoE statistics");
6084 
6085 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
6086 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6087 	    sysctl_hw_sched, "A", "hardware scheduler ");
6088 
6089 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
6090 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6091 	    sysctl_l2t, "A", "hardware L2 table");
6092 
6093 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
6094 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6095 	    sysctl_smt, "A", "hardware source MAC table");
6096 
6097 #ifdef INET6
6098 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
6099 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6100 	    sysctl_clip, "A", "active CLIP table entries");
6101 #endif
6102 
6103 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
6104 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6105 	    sysctl_lb_stats, "A", "loopback statistics");
6106 
6107 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
6108 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6109 	    sysctl_meminfo, "A", "memory regions");
6110 
6111 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
6112 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6113 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
6114 	    "A", "MPS TCAM entries");
6115 
6116 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
6117 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6118 	    sysctl_path_mtus, "A", "path MTUs");
6119 
6120 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
6121 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6122 	    sysctl_pm_stats, "A", "PM statistics");
6123 
6124 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
6125 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6126 	    sysctl_rdma_stats, "A", "RDMA statistics");
6127 
6128 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
6129 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6130 	    sysctl_tcp_stats, "A", "TCP statistics");
6131 
6132 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
6133 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6134 	    sysctl_tids, "A", "TID information");
6135 
6136 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
6137 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6138 	    sysctl_tp_err_stats, "A", "TP error statistics");
6139 
6140 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
6141 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_tp_la_mask, "I",
6142 	    "TP logic analyzer event capture mask");
6143 
6144 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
6145 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6146 	    sysctl_tp_la, "A", "TP logic analyzer");
6147 
6148 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
6149 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6150 	    sysctl_tx_rate, "A", "Tx rate");
6151 
6152 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
6153 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6154 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
6155 
6156 	if (chip_id(sc) >= CHELSIO_T5) {
6157 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
6158 		    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6159 		    sysctl_wcwr_stats, "A", "write combined work requests");
6160 	}
6161 
6162 #ifdef TCP_OFFLOAD
6163 	if (is_offload(sc)) {
6164 		int i;
6165 		char s[4];
6166 
6167 		/*
6168 		 * dev.t4nex.X.toe.
6169 		 */
6170 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe", CTLFLAG_RD,
6171 		    NULL, "TOE parameters");
6172 		children = SYSCTL_CHILDREN(oid);
6173 
6174 		sc->tt.cong_algorithm = -1;
6175 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
6176 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
6177 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
6178 		    "3 = highspeed)");
6179 
6180 		sc->tt.sndbuf = 256 * 1024;
6181 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
6182 		    &sc->tt.sndbuf, 0, "max hardware send buffer size");
6183 
6184 		sc->tt.ddp = 0;
6185 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp", CTLFLAG_RW,
6186 		    &sc->tt.ddp, 0, "DDP allowed");
6187 
6188 		sc->tt.rx_coalesce = 1;
6189 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
6190 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
6191 
6192 		sc->tt.tls = 0;
6193 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tls", CTLFLAG_RW,
6194 		    &sc->tt.tls, 0, "Inline TLS allowed");
6195 
6196 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_ports",
6197 		    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_tls_rx_ports,
6198 		    "I", "TCP ports that use inline TLS+TOE RX");
6199 
6200 		sc->tt.tx_align = 1;
6201 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
6202 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
6203 
6204 		sc->tt.tx_zcopy = 0;
6205 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
6206 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
6207 		    "Enable zero-copy aio_write(2)");
6208 
6209 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
6210 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
6211 		    "cop_managed_offloading", CTLFLAG_RW,
6212 		    &sc->tt.cop_managed_offloading, 0,
6213 		    "COP (Connection Offload Policy) controls all TOE offload");
6214 
6215 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
6216 		    CTLTYPE_STRING | CTLFLAG_RD, sc, 0, sysctl_tp_tick, "A",
6217 		    "TP timer tick (us)");
6218 
6219 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
6220 		    CTLTYPE_STRING | CTLFLAG_RD, sc, 1, sysctl_tp_tick, "A",
6221 		    "TCP timestamp tick (us)");
6222 
6223 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
6224 		    CTLTYPE_STRING | CTLFLAG_RD, sc, 2, sysctl_tp_tick, "A",
6225 		    "DACK tick (us)");
6226 
6227 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
6228 		    CTLTYPE_UINT | CTLFLAG_RD, sc, 0, sysctl_tp_dack_timer,
6229 		    "IU", "DACK timer (us)");
6230 
6231 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
6232 		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_RXT_MIN,
6233 		    sysctl_tp_timer, "LU", "Minimum retransmit interval (us)");
6234 
6235 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
6236 		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_RXT_MAX,
6237 		    sysctl_tp_timer, "LU", "Maximum retransmit interval (us)");
6238 
6239 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
6240 		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_PERS_MIN,
6241 		    sysctl_tp_timer, "LU", "Persist timer min (us)");
6242 
6243 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
6244 		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_PERS_MAX,
6245 		    sysctl_tp_timer, "LU", "Persist timer max (us)");
6246 
6247 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
6248 		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_KEEP_IDLE,
6249 		    sysctl_tp_timer, "LU", "Keepalive idle timer (us)");
6250 
6251 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
6252 		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_KEEP_INTVL,
6253 		    sysctl_tp_timer, "LU", "Keepalive interval timer (us)");
6254 
6255 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
6256 		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_INIT_SRTT,
6257 		    sysctl_tp_timer, "LU", "Initial SRTT (us)");
6258 
6259 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
6260 		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_FINWAIT2_TIMER,
6261 		    sysctl_tp_timer, "LU", "FINWAIT2 timer (us)");
6262 
6263 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
6264 		    CTLTYPE_UINT | CTLFLAG_RD, sc, S_SYNSHIFTMAX,
6265 		    sysctl_tp_shift_cnt, "IU",
6266 		    "Number of SYN retransmissions before abort");
6267 
6268 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
6269 		    CTLTYPE_UINT | CTLFLAG_RD, sc, S_RXTSHIFTMAXR2,
6270 		    sysctl_tp_shift_cnt, "IU",
6271 		    "Number of retransmissions before abort");
6272 
6273 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
6274 		    CTLTYPE_UINT | CTLFLAG_RD, sc, S_KEEPALIVEMAXR2,
6275 		    sysctl_tp_shift_cnt, "IU",
6276 		    "Number of keepalive probes before abort");
6277 
6278 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
6279 		    CTLFLAG_RD, NULL, "TOE retransmit backoffs");
6280 		children = SYSCTL_CHILDREN(oid);
6281 		for (i = 0; i < 16; i++) {
6282 			snprintf(s, sizeof(s), "%u", i);
6283 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
6284 			    CTLTYPE_UINT | CTLFLAG_RD, sc, i, sysctl_tp_backoff,
6285 			    "IU", "TOE retransmit backoff");
6286 		}
6287 	}
6288 #endif
6289 }
6290 
6291 void
6292 vi_sysctls(struct vi_info *vi)
6293 {
6294 	struct sysctl_ctx_list *ctx;
6295 	struct sysctl_oid *oid;
6296 	struct sysctl_oid_list *children;
6297 
6298 	ctx = device_get_sysctl_ctx(vi->dev);
6299 
6300 	/*
6301 	 * dev.v?(cxgbe|cxl).X.
6302 	 */
6303 	oid = device_get_sysctl_tree(vi->dev);
6304 	children = SYSCTL_CHILDREN(oid);
6305 
6306 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
6307 	    vi->viid, "VI identifer");
6308 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
6309 	    &vi->nrxq, 0, "# of rx queues");
6310 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
6311 	    &vi->ntxq, 0, "# of tx queues");
6312 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
6313 	    &vi->first_rxq, 0, "index of first rx queue");
6314 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
6315 	    &vi->first_txq, 0, "index of first tx queue");
6316 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
6317 	    vi->rss_base, "start of RSS indirection table");
6318 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
6319 	    vi->rss_size, "size of RSS indirection table");
6320 
6321 	if (IS_MAIN_VI(vi)) {
6322 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
6323 		    CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_noflowq, "IU",
6324 		    "Reserve queue 0 for non-flowid packets");
6325 	}
6326 
6327 #ifdef TCP_OFFLOAD
6328 	if (vi->nofldrxq != 0) {
6329 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
6330 		    &vi->nofldrxq, 0,
6331 		    "# of rx queues for offloaded TCP connections");
6332 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
6333 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
6334 		    "index of first TOE rx queue");
6335 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
6336 		    CTLTYPE_INT | CTLFLAG_RW, vi, 0,
6337 		    sysctl_holdoff_tmr_idx_ofld, "I",
6338 		    "holdoff timer index for TOE queues");
6339 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
6340 		    CTLTYPE_INT | CTLFLAG_RW, vi, 0,
6341 		    sysctl_holdoff_pktc_idx_ofld, "I",
6342 		    "holdoff packet counter index for TOE queues");
6343 	}
6344 #endif
6345 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6346 	if (vi->nofldtxq != 0) {
6347 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
6348 		    &vi->nofldtxq, 0,
6349 		    "# of tx queues for TOE/ETHOFLD");
6350 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
6351 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
6352 		    "index of first TOE/ETHOFLD tx queue");
6353 	}
6354 #endif
6355 #ifdef DEV_NETMAP
6356 	if (vi->nnmrxq != 0) {
6357 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
6358 		    &vi->nnmrxq, 0, "# of netmap rx queues");
6359 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
6360 		    &vi->nnmtxq, 0, "# of netmap tx queues");
6361 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
6362 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
6363 		    "index of first netmap rx queue");
6364 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
6365 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
6366 		    "index of first netmap tx queue");
6367 	}
6368 #endif
6369 
6370 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
6371 	    CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_holdoff_tmr_idx, "I",
6372 	    "holdoff timer index");
6373 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
6374 	    CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_holdoff_pktc_idx, "I",
6375 	    "holdoff packet counter index");
6376 
6377 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
6378 	    CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_qsize_rxq, "I",
6379 	    "rx queue size");
6380 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
6381 	    CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_qsize_txq, "I",
6382 	    "tx queue size");
6383 }
6384 
6385 static void
6386 cxgbe_sysctls(struct port_info *pi)
6387 {
6388 	struct sysctl_ctx_list *ctx;
6389 	struct sysctl_oid *oid;
6390 	struct sysctl_oid_list *children, *children2;
6391 	struct adapter *sc = pi->adapter;
6392 	int i;
6393 	char name[16];
6394 	static char *tc_flags = {"\20\1USER\2SYNC\3ASYNC\4ERR"};
6395 
6396 	ctx = device_get_sysctl_ctx(pi->dev);
6397 
6398 	/*
6399 	 * dev.cxgbe.X.
6400 	 */
6401 	oid = device_get_sysctl_tree(pi->dev);
6402 	children = SYSCTL_CHILDREN(oid);
6403 
6404 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc", CTLTYPE_STRING |
6405 	   CTLFLAG_RD, pi, 0, sysctl_linkdnrc, "A", "reason why link is down");
6406 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
6407 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
6408 		    CTLTYPE_INT | CTLFLAG_RD, pi, 0, sysctl_btphy, "I",
6409 		    "PHY temperature (in Celsius)");
6410 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
6411 		    CTLTYPE_INT | CTLFLAG_RD, pi, 1, sysctl_btphy, "I",
6412 		    "PHY firmware version");
6413 	}
6414 
6415 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
6416 	    CTLTYPE_STRING | CTLFLAG_RW, pi, 0, sysctl_pause_settings, "A",
6417     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
6418 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fec",
6419 	    CTLTYPE_STRING | CTLFLAG_RW, pi, 0, sysctl_fec, "A",
6420 	    "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
6421 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
6422 	    CTLTYPE_INT | CTLFLAG_RW, pi, 0, sysctl_autoneg, "I",
6423 	    "autonegotiation (-1 = not supported)");
6424 
6425 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
6426 	    port_top_speed(pi), "max speed (in Gbps)");
6427 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
6428 	    pi->mps_bg_map, "MPS buffer group map");
6429 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
6430 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
6431 
6432 	if (sc->flags & IS_VF)
6433 		return;
6434 
6435 	/*
6436 	 * dev.(cxgbe|cxl).X.tc.
6437 	 */
6438 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc", CTLFLAG_RD, NULL,
6439 	    "Tx scheduler traffic classes (cl_rl)");
6440 	children2 = SYSCTL_CHILDREN(oid);
6441 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
6442 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
6443 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
6444 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
6445 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
6446 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
6447 	for (i = 0; i < sc->chip_params->nsched_cls; i++) {
6448 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
6449 
6450 		snprintf(name, sizeof(name), "%d", i);
6451 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
6452 		    SYSCTL_CHILDREN(oid), OID_AUTO, name, CTLFLAG_RD, NULL,
6453 		    "traffic class"));
6454 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
6455 		    CTLTYPE_STRING | CTLFLAG_RD, tc_flags, (uintptr_t)&tc->flags,
6456 		    sysctl_bitfield_8b, "A", "flags");
6457 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
6458 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
6459 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
6460 		    CTLTYPE_STRING | CTLFLAG_RD, sc, (pi->port_id << 16) | i,
6461 		    sysctl_tc_params, "A", "traffic class parameters");
6462 	}
6463 
6464 	/*
6465 	 * dev.cxgbe.X.stats.
6466 	 */
6467 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats", CTLFLAG_RD,
6468 	    NULL, "port statistics");
6469 	children = SYSCTL_CHILDREN(oid);
6470 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
6471 	    &pi->tx_parse_error, 0,
6472 	    "# of tx packets with invalid length or # of segments");
6473 
6474 #define SYSCTL_ADD_T4_REG64(pi, name, desc, reg) \
6475 	SYSCTL_ADD_OID(ctx, children, OID_AUTO, name, \
6476 	    CTLTYPE_U64 | CTLFLAG_RD, sc, reg, \
6477 	    sysctl_handle_t4_reg64, "QU", desc)
6478 
6479 	SYSCTL_ADD_T4_REG64(pi, "tx_octets", "# of octets in good frames",
6480 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_BYTES_L));
6481 	SYSCTL_ADD_T4_REG64(pi, "tx_frames", "total # of good frames",
6482 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_FRAMES_L));
6483 	SYSCTL_ADD_T4_REG64(pi, "tx_bcast_frames", "# of broadcast frames",
6484 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_BCAST_L));
6485 	SYSCTL_ADD_T4_REG64(pi, "tx_mcast_frames", "# of multicast frames",
6486 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_MCAST_L));
6487 	SYSCTL_ADD_T4_REG64(pi, "tx_ucast_frames", "# of unicast frames",
6488 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_UCAST_L));
6489 	SYSCTL_ADD_T4_REG64(pi, "tx_error_frames", "# of error frames",
6490 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_ERROR_L));
6491 	SYSCTL_ADD_T4_REG64(pi, "tx_frames_64",
6492 	    "# of tx frames in this range",
6493 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_64B_L));
6494 	SYSCTL_ADD_T4_REG64(pi, "tx_frames_65_127",
6495 	    "# of tx frames in this range",
6496 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_65B_127B_L));
6497 	SYSCTL_ADD_T4_REG64(pi, "tx_frames_128_255",
6498 	    "# of tx frames in this range",
6499 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_128B_255B_L));
6500 	SYSCTL_ADD_T4_REG64(pi, "tx_frames_256_511",
6501 	    "# of tx frames in this range",
6502 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_256B_511B_L));
6503 	SYSCTL_ADD_T4_REG64(pi, "tx_frames_512_1023",
6504 	    "# of tx frames in this range",
6505 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_512B_1023B_L));
6506 	SYSCTL_ADD_T4_REG64(pi, "tx_frames_1024_1518",
6507 	    "# of tx frames in this range",
6508 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_1024B_1518B_L));
6509 	SYSCTL_ADD_T4_REG64(pi, "tx_frames_1519_max",
6510 	    "# of tx frames in this range",
6511 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_1519B_MAX_L));
6512 	SYSCTL_ADD_T4_REG64(pi, "tx_drop", "# of dropped tx frames",
6513 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_DROP_L));
6514 	SYSCTL_ADD_T4_REG64(pi, "tx_pause", "# of pause frames transmitted",
6515 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PAUSE_L));
6516 	SYSCTL_ADD_T4_REG64(pi, "tx_ppp0", "# of PPP prio 0 frames transmitted",
6517 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP0_L));
6518 	SYSCTL_ADD_T4_REG64(pi, "tx_ppp1", "# of PPP prio 1 frames transmitted",
6519 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP1_L));
6520 	SYSCTL_ADD_T4_REG64(pi, "tx_ppp2", "# of PPP prio 2 frames transmitted",
6521 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP2_L));
6522 	SYSCTL_ADD_T4_REG64(pi, "tx_ppp3", "# of PPP prio 3 frames transmitted",
6523 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP3_L));
6524 	SYSCTL_ADD_T4_REG64(pi, "tx_ppp4", "# of PPP prio 4 frames transmitted",
6525 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP4_L));
6526 	SYSCTL_ADD_T4_REG64(pi, "tx_ppp5", "# of PPP prio 5 frames transmitted",
6527 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP5_L));
6528 	SYSCTL_ADD_T4_REG64(pi, "tx_ppp6", "# of PPP prio 6 frames transmitted",
6529 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP6_L));
6530 	SYSCTL_ADD_T4_REG64(pi, "tx_ppp7", "# of PPP prio 7 frames transmitted",
6531 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP7_L));
6532 
6533 	SYSCTL_ADD_T4_REG64(pi, "rx_octets", "# of octets in good frames",
6534 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_BYTES_L));
6535 	SYSCTL_ADD_T4_REG64(pi, "rx_frames", "total # of good frames",
6536 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_FRAMES_L));
6537 	SYSCTL_ADD_T4_REG64(pi, "rx_bcast_frames", "# of broadcast frames",
6538 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_BCAST_L));
6539 	SYSCTL_ADD_T4_REG64(pi, "rx_mcast_frames", "# of multicast frames",
6540 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_MCAST_L));
6541 	SYSCTL_ADD_T4_REG64(pi, "rx_ucast_frames", "# of unicast frames",
6542 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_UCAST_L));
6543 	SYSCTL_ADD_T4_REG64(pi, "rx_too_long", "# of frames exceeding MTU",
6544 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_MTU_ERROR_L));
6545 	SYSCTL_ADD_T4_REG64(pi, "rx_jabber", "# of jabber frames",
6546 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_MTU_CRC_ERROR_L));
6547 	SYSCTL_ADD_T4_REG64(pi, "rx_fcs_err",
6548 	    "# of frames received with bad FCS",
6549 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L));
6550 	SYSCTL_ADD_T4_REG64(pi, "rx_len_err",
6551 	    "# of frames received with length error",
6552 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_LEN_ERROR_L));
6553 	SYSCTL_ADD_T4_REG64(pi, "rx_symbol_err", "symbol errors",
6554 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_SYM_ERROR_L));
6555 	SYSCTL_ADD_T4_REG64(pi, "rx_runt", "# of short frames received",
6556 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_LESS_64B_L));
6557 	SYSCTL_ADD_T4_REG64(pi, "rx_frames_64",
6558 	    "# of rx frames in this range",
6559 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_64B_L));
6560 	SYSCTL_ADD_T4_REG64(pi, "rx_frames_65_127",
6561 	    "# of rx frames in this range",
6562 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_65B_127B_L));
6563 	SYSCTL_ADD_T4_REG64(pi, "rx_frames_128_255",
6564 	    "# of rx frames in this range",
6565 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_128B_255B_L));
6566 	SYSCTL_ADD_T4_REG64(pi, "rx_frames_256_511",
6567 	    "# of rx frames in this range",
6568 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_256B_511B_L));
6569 	SYSCTL_ADD_T4_REG64(pi, "rx_frames_512_1023",
6570 	    "# of rx frames in this range",
6571 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_512B_1023B_L));
6572 	SYSCTL_ADD_T4_REG64(pi, "rx_frames_1024_1518",
6573 	    "# of rx frames in this range",
6574 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_1024B_1518B_L));
6575 	SYSCTL_ADD_T4_REG64(pi, "rx_frames_1519_max",
6576 	    "# of rx frames in this range",
6577 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_1519B_MAX_L));
6578 	SYSCTL_ADD_T4_REG64(pi, "rx_pause", "# of pause frames received",
6579 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PAUSE_L));
6580 	SYSCTL_ADD_T4_REG64(pi, "rx_ppp0", "# of PPP prio 0 frames received",
6581 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP0_L));
6582 	SYSCTL_ADD_T4_REG64(pi, "rx_ppp1", "# of PPP prio 1 frames received",
6583 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP1_L));
6584 	SYSCTL_ADD_T4_REG64(pi, "rx_ppp2", "# of PPP prio 2 frames received",
6585 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP2_L));
6586 	SYSCTL_ADD_T4_REG64(pi, "rx_ppp3", "# of PPP prio 3 frames received",
6587 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP3_L));
6588 	SYSCTL_ADD_T4_REG64(pi, "rx_ppp4", "# of PPP prio 4 frames received",
6589 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP4_L));
6590 	SYSCTL_ADD_T4_REG64(pi, "rx_ppp5", "# of PPP prio 5 frames received",
6591 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP5_L));
6592 	SYSCTL_ADD_T4_REG64(pi, "rx_ppp6", "# of PPP prio 6 frames received",
6593 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP6_L));
6594 	SYSCTL_ADD_T4_REG64(pi, "rx_ppp7", "# of PPP prio 7 frames received",
6595 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP7_L));
6596 
6597 #undef SYSCTL_ADD_T4_REG64
6598 
6599 #define SYSCTL_ADD_T4_PORTSTAT(name, desc) \
6600 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
6601 	    &pi->stats.name, desc)
6602 
6603 	/* We get these from port_stats and they may be stale by up to 1s */
6604 	SYSCTL_ADD_T4_PORTSTAT(rx_ovflow0,
6605 	    "# drops due to buffer-group 0 overflows");
6606 	SYSCTL_ADD_T4_PORTSTAT(rx_ovflow1,
6607 	    "# drops due to buffer-group 1 overflows");
6608 	SYSCTL_ADD_T4_PORTSTAT(rx_ovflow2,
6609 	    "# drops due to buffer-group 2 overflows");
6610 	SYSCTL_ADD_T4_PORTSTAT(rx_ovflow3,
6611 	    "# drops due to buffer-group 3 overflows");
6612 	SYSCTL_ADD_T4_PORTSTAT(rx_trunc0,
6613 	    "# of buffer-group 0 truncated packets");
6614 	SYSCTL_ADD_T4_PORTSTAT(rx_trunc1,
6615 	    "# of buffer-group 1 truncated packets");
6616 	SYSCTL_ADD_T4_PORTSTAT(rx_trunc2,
6617 	    "# of buffer-group 2 truncated packets");
6618 	SYSCTL_ADD_T4_PORTSTAT(rx_trunc3,
6619 	    "# of buffer-group 3 truncated packets");
6620 
6621 #undef SYSCTL_ADD_T4_PORTSTAT
6622 
6623 	SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "tx_tls_records",
6624 	    CTLFLAG_RD, &pi->tx_tls_records,
6625 	    "# of TLS records transmitted");
6626 	SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "tx_tls_octets",
6627 	    CTLFLAG_RD, &pi->tx_tls_octets,
6628 	    "# of payload octets in transmitted TLS records");
6629 	SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "rx_tls_records",
6630 	    CTLFLAG_RD, &pi->rx_tls_records,
6631 	    "# of TLS records received");
6632 	SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "rx_tls_octets",
6633 	    CTLFLAG_RD, &pi->rx_tls_octets,
6634 	    "# of payload octets in received TLS records");
6635 }
6636 
6637 static int
6638 sysctl_int_array(SYSCTL_HANDLER_ARGS)
6639 {
6640 	int rc, *i, space = 0;
6641 	struct sbuf sb;
6642 
6643 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
6644 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
6645 		if (space)
6646 			sbuf_printf(&sb, " ");
6647 		sbuf_printf(&sb, "%d", *i);
6648 		space = 1;
6649 	}
6650 	rc = sbuf_finish(&sb);
6651 	sbuf_delete(&sb);
6652 	return (rc);
6653 }
6654 
6655 static int
6656 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
6657 {
6658 	int rc;
6659 	struct sbuf *sb;
6660 
6661 	rc = sysctl_wire_old_buffer(req, 0);
6662 	if (rc != 0)
6663 		return(rc);
6664 
6665 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
6666 	if (sb == NULL)
6667 		return (ENOMEM);
6668 
6669 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
6670 	rc = sbuf_finish(sb);
6671 	sbuf_delete(sb);
6672 
6673 	return (rc);
6674 }
6675 
6676 static int
6677 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
6678 {
6679 	int rc;
6680 	struct sbuf *sb;
6681 
6682 	rc = sysctl_wire_old_buffer(req, 0);
6683 	if (rc != 0)
6684 		return(rc);
6685 
6686 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
6687 	if (sb == NULL)
6688 		return (ENOMEM);
6689 
6690 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
6691 	rc = sbuf_finish(sb);
6692 	sbuf_delete(sb);
6693 
6694 	return (rc);
6695 }
6696 
6697 static int
6698 sysctl_btphy(SYSCTL_HANDLER_ARGS)
6699 {
6700 	struct port_info *pi = arg1;
6701 	int op = arg2;
6702 	struct adapter *sc = pi->adapter;
6703 	u_int v;
6704 	int rc;
6705 
6706 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
6707 	if (rc)
6708 		return (rc);
6709 	/* XXX: magic numbers */
6710 	rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e, op ? 0x20 : 0xc820,
6711 	    &v);
6712 	end_synchronized_op(sc, 0);
6713 	if (rc)
6714 		return (rc);
6715 	if (op == 0)
6716 		v /= 256;
6717 
6718 	rc = sysctl_handle_int(oidp, &v, 0, req);
6719 	return (rc);
6720 }
6721 
6722 static int
6723 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
6724 {
6725 	struct vi_info *vi = arg1;
6726 	int rc, val;
6727 
6728 	val = vi->rsrv_noflowq;
6729 	rc = sysctl_handle_int(oidp, &val, 0, req);
6730 	if (rc != 0 || req->newptr == NULL)
6731 		return (rc);
6732 
6733 	if ((val >= 1) && (vi->ntxq > 1))
6734 		vi->rsrv_noflowq = 1;
6735 	else
6736 		vi->rsrv_noflowq = 0;
6737 
6738 	return (rc);
6739 }
6740 
6741 static int
6742 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
6743 {
6744 	struct vi_info *vi = arg1;
6745 	struct adapter *sc = vi->pi->adapter;
6746 	int idx, rc, i;
6747 	struct sge_rxq *rxq;
6748 	uint8_t v;
6749 
6750 	idx = vi->tmr_idx;
6751 
6752 	rc = sysctl_handle_int(oidp, &idx, 0, req);
6753 	if (rc != 0 || req->newptr == NULL)
6754 		return (rc);
6755 
6756 	if (idx < 0 || idx >= SGE_NTIMERS)
6757 		return (EINVAL);
6758 
6759 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
6760 	    "t4tmr");
6761 	if (rc)
6762 		return (rc);
6763 
6764 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
6765 	for_each_rxq(vi, i, rxq) {
6766 #ifdef atomic_store_rel_8
6767 		atomic_store_rel_8(&rxq->iq.intr_params, v);
6768 #else
6769 		rxq->iq.intr_params = v;
6770 #endif
6771 	}
6772 	vi->tmr_idx = idx;
6773 
6774 	end_synchronized_op(sc, LOCK_HELD);
6775 	return (0);
6776 }
6777 
6778 static int
6779 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
6780 {
6781 	struct vi_info *vi = arg1;
6782 	struct adapter *sc = vi->pi->adapter;
6783 	int idx, rc;
6784 
6785 	idx = vi->pktc_idx;
6786 
6787 	rc = sysctl_handle_int(oidp, &idx, 0, req);
6788 	if (rc != 0 || req->newptr == NULL)
6789 		return (rc);
6790 
6791 	if (idx < -1 || idx >= SGE_NCOUNTERS)
6792 		return (EINVAL);
6793 
6794 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
6795 	    "t4pktc");
6796 	if (rc)
6797 		return (rc);
6798 
6799 	if (vi->flags & VI_INIT_DONE)
6800 		rc = EBUSY; /* cannot be changed once the queues are created */
6801 	else
6802 		vi->pktc_idx = idx;
6803 
6804 	end_synchronized_op(sc, LOCK_HELD);
6805 	return (rc);
6806 }
6807 
6808 static int
6809 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
6810 {
6811 	struct vi_info *vi = arg1;
6812 	struct adapter *sc = vi->pi->adapter;
6813 	int qsize, rc;
6814 
6815 	qsize = vi->qsize_rxq;
6816 
6817 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
6818 	if (rc != 0 || req->newptr == NULL)
6819 		return (rc);
6820 
6821 	if (qsize < 128 || (qsize & 7))
6822 		return (EINVAL);
6823 
6824 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
6825 	    "t4rxqs");
6826 	if (rc)
6827 		return (rc);
6828 
6829 	if (vi->flags & VI_INIT_DONE)
6830 		rc = EBUSY; /* cannot be changed once the queues are created */
6831 	else
6832 		vi->qsize_rxq = qsize;
6833 
6834 	end_synchronized_op(sc, LOCK_HELD);
6835 	return (rc);
6836 }
6837 
6838 static int
6839 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
6840 {
6841 	struct vi_info *vi = arg1;
6842 	struct adapter *sc = vi->pi->adapter;
6843 	int qsize, rc;
6844 
6845 	qsize = vi->qsize_txq;
6846 
6847 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
6848 	if (rc != 0 || req->newptr == NULL)
6849 		return (rc);
6850 
6851 	if (qsize < 128 || qsize > 65536)
6852 		return (EINVAL);
6853 
6854 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
6855 	    "t4txqs");
6856 	if (rc)
6857 		return (rc);
6858 
6859 	if (vi->flags & VI_INIT_DONE)
6860 		rc = EBUSY; /* cannot be changed once the queues are created */
6861 	else
6862 		vi->qsize_txq = qsize;
6863 
6864 	end_synchronized_op(sc, LOCK_HELD);
6865 	return (rc);
6866 }
6867 
6868 static int
6869 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
6870 {
6871 	struct port_info *pi = arg1;
6872 	struct adapter *sc = pi->adapter;
6873 	struct link_config *lc = &pi->link_cfg;
6874 	int rc;
6875 
6876 	if (req->newptr == NULL) {
6877 		struct sbuf *sb;
6878 		static char *bits = "\20\1RX\2TX\3AUTO";
6879 
6880 		rc = sysctl_wire_old_buffer(req, 0);
6881 		if (rc != 0)
6882 			return(rc);
6883 
6884 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
6885 		if (sb == NULL)
6886 			return (ENOMEM);
6887 
6888 		if (lc->link_ok) {
6889 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
6890 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
6891 		} else {
6892 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
6893 			    PAUSE_RX | PAUSE_AUTONEG), bits);
6894 		}
6895 		rc = sbuf_finish(sb);
6896 		sbuf_delete(sb);
6897 	} else {
6898 		char s[2];
6899 		int n;
6900 
6901 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
6902 		    PAUSE_AUTONEG));
6903 		s[1] = 0;
6904 
6905 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
6906 		if (rc != 0)
6907 			return(rc);
6908 
6909 		if (s[1] != 0)
6910 			return (EINVAL);
6911 		if (s[0] < '0' || s[0] > '9')
6912 			return (EINVAL);	/* not a number */
6913 		n = s[0] - '0';
6914 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
6915 			return (EINVAL);	/* some other bit is set too */
6916 
6917 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
6918 		    "t4PAUSE");
6919 		if (rc)
6920 			return (rc);
6921 		PORT_LOCK(pi);
6922 		lc->requested_fc = n;
6923 		fixup_link_config(pi);
6924 		if (pi->up_vis > 0)
6925 			rc = apply_link_config(pi);
6926 		set_current_media(pi);
6927 		PORT_UNLOCK(pi);
6928 		end_synchronized_op(sc, 0);
6929 	}
6930 
6931 	return (rc);
6932 }
6933 
6934 static int
6935 sysctl_fec(SYSCTL_HANDLER_ARGS)
6936 {
6937 	struct port_info *pi = arg1;
6938 	struct adapter *sc = pi->adapter;
6939 	struct link_config *lc = &pi->link_cfg;
6940 	int rc;
6941 	int8_t old;
6942 
6943 	if (req->newptr == NULL) {
6944 		struct sbuf *sb;
6945 		static char *bits = "\20\1RS\2BASE-R\3RSVD1\4RSVD2\5RSVD3\6AUTO";
6946 
6947 		rc = sysctl_wire_old_buffer(req, 0);
6948 		if (rc != 0)
6949 			return(rc);
6950 
6951 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
6952 		if (sb == NULL)
6953 			return (ENOMEM);
6954 
6955 		/*
6956 		 * Display the requested_fec when the link is down -- the actual
6957 		 * FEC makes sense only when the link is up.
6958 		 */
6959 		if (lc->link_ok) {
6960 			sbuf_printf(sb, "%b", (lc->fec & M_FW_PORT_CAP32_FEC) |
6961 			    (lc->requested_fec & FEC_AUTO), bits);
6962 		} else {
6963 			sbuf_printf(sb, "%b", lc->requested_fec, bits);
6964 		}
6965 		rc = sbuf_finish(sb);
6966 		sbuf_delete(sb);
6967 	} else {
6968 		char s[3];
6969 		int n;
6970 
6971 		snprintf(s, sizeof(s), "%d",
6972 		    lc->requested_fec == FEC_AUTO ? -1 :
6973 		    lc->requested_fec & M_FW_PORT_CAP32_FEC);
6974 
6975 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
6976 		if (rc != 0)
6977 			return(rc);
6978 
6979 		n = strtol(&s[0], NULL, 0);
6980 		if (n < 0 || n & FEC_AUTO)
6981 			n = FEC_AUTO;
6982 		else {
6983 			if (n & ~M_FW_PORT_CAP32_FEC)
6984 				return (EINVAL);/* some other bit is set too */
6985 			if (!powerof2(n))
6986 				return (EINVAL);/* one bit can be set at most */
6987 		}
6988 
6989 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
6990 		    "t4fec");
6991 		if (rc)
6992 			return (rc);
6993 		PORT_LOCK(pi);
6994 		old = lc->requested_fec;
6995 		if (n == FEC_AUTO)
6996 			lc->requested_fec = FEC_AUTO;
6997 		else if (n == 0)
6998 			lc->requested_fec = FEC_NONE;
6999 		else {
7000 			if ((lc->supported | V_FW_PORT_CAP32_FEC(n)) !=
7001 			    lc->supported) {
7002 				rc = ENOTSUP;
7003 				goto done;
7004 			}
7005 			lc->requested_fec = n;
7006 		}
7007 		fixup_link_config(pi);
7008 		if (pi->up_vis > 0) {
7009 			rc = apply_link_config(pi);
7010 			if (rc != 0) {
7011 				lc->requested_fec = old;
7012 				if (rc == FW_EPROTO)
7013 					rc = ENOTSUP;
7014 			}
7015 		}
7016 done:
7017 		PORT_UNLOCK(pi);
7018 		end_synchronized_op(sc, 0);
7019 	}
7020 
7021 	return (rc);
7022 }
7023 
7024 static int
7025 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
7026 {
7027 	struct port_info *pi = arg1;
7028 	struct adapter *sc = pi->adapter;
7029 	struct link_config *lc = &pi->link_cfg;
7030 	int rc, val;
7031 
7032 	if (lc->supported & FW_PORT_CAP32_ANEG)
7033 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
7034 	else
7035 		val = -1;
7036 	rc = sysctl_handle_int(oidp, &val, 0, req);
7037 	if (rc != 0 || req->newptr == NULL)
7038 		return (rc);
7039 	if (val == 0)
7040 		val = AUTONEG_DISABLE;
7041 	else if (val == 1)
7042 		val = AUTONEG_ENABLE;
7043 	else
7044 		val = AUTONEG_AUTO;
7045 
7046 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
7047 	    "t4aneg");
7048 	if (rc)
7049 		return (rc);
7050 	PORT_LOCK(pi);
7051 	if (val == AUTONEG_ENABLE && !(lc->supported & FW_PORT_CAP32_ANEG)) {
7052 		rc = ENOTSUP;
7053 		goto done;
7054 	}
7055 	lc->requested_aneg = val;
7056 	fixup_link_config(pi);
7057 	if (pi->up_vis > 0)
7058 		rc = apply_link_config(pi);
7059 	set_current_media(pi);
7060 done:
7061 	PORT_UNLOCK(pi);
7062 	end_synchronized_op(sc, 0);
7063 	return (rc);
7064 }
7065 
7066 static int
7067 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
7068 {
7069 	struct adapter *sc = arg1;
7070 	int reg = arg2;
7071 	uint64_t val;
7072 
7073 	val = t4_read_reg64(sc, reg);
7074 
7075 	return (sysctl_handle_64(oidp, &val, 0, req));
7076 }
7077 
7078 static int
7079 sysctl_temperature(SYSCTL_HANDLER_ARGS)
7080 {
7081 	struct adapter *sc = arg1;
7082 	int rc, t;
7083 	uint32_t param, val;
7084 
7085 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
7086 	if (rc)
7087 		return (rc);
7088 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
7089 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
7090 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
7091 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
7092 	end_synchronized_op(sc, 0);
7093 	if (rc)
7094 		return (rc);
7095 
7096 	/* unknown is returned as 0 but we display -1 in that case */
7097 	t = val == 0 ? -1 : val;
7098 
7099 	rc = sysctl_handle_int(oidp, &t, 0, req);
7100 	return (rc);
7101 }
7102 
7103 static int
7104 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
7105 {
7106 	struct adapter *sc = arg1;
7107 	struct sbuf *sb;
7108 	int rc;
7109 	uint32_t param, val;
7110 
7111 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
7112 	if (rc)
7113 		return (rc);
7114 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
7115 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
7116 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
7117 	end_synchronized_op(sc, 0);
7118 	if (rc)
7119 		return (rc);
7120 
7121 	rc = sysctl_wire_old_buffer(req, 0);
7122 	if (rc != 0)
7123 		return (rc);
7124 
7125 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7126 	if (sb == NULL)
7127 		return (ENOMEM);
7128 
7129 	if (val == 0xffffffff) {
7130 		/* Only debug and custom firmwares report load averages. */
7131 		sbuf_printf(sb, "not available");
7132 	} else {
7133 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
7134 		    (val >> 16) & 0xff);
7135 	}
7136 	rc = sbuf_finish(sb);
7137 	sbuf_delete(sb);
7138 
7139 	return (rc);
7140 }
7141 
7142 static int
7143 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
7144 {
7145 	struct adapter *sc = arg1;
7146 	struct sbuf *sb;
7147 	int rc, i;
7148 	uint16_t incr[NMTUS][NCCTRL_WIN];
7149 	static const char *dec_fac[] = {
7150 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
7151 		"0.9375"
7152 	};
7153 
7154 	rc = sysctl_wire_old_buffer(req, 0);
7155 	if (rc != 0)
7156 		return (rc);
7157 
7158 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7159 	if (sb == NULL)
7160 		return (ENOMEM);
7161 
7162 	t4_read_cong_tbl(sc, incr);
7163 
7164 	for (i = 0; i < NCCTRL_WIN; ++i) {
7165 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
7166 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
7167 		    incr[5][i], incr[6][i], incr[7][i]);
7168 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
7169 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
7170 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
7171 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
7172 	}
7173 
7174 	rc = sbuf_finish(sb);
7175 	sbuf_delete(sb);
7176 
7177 	return (rc);
7178 }
7179 
7180 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
7181 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
7182 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
7183 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
7184 };
7185 
7186 static int
7187 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
7188 {
7189 	struct adapter *sc = arg1;
7190 	struct sbuf *sb;
7191 	int rc, i, n, qid = arg2;
7192 	uint32_t *buf, *p;
7193 	char *qtype;
7194 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
7195 
7196 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
7197 	    ("%s: bad qid %d\n", __func__, qid));
7198 
7199 	if (qid < CIM_NUM_IBQ) {
7200 		/* inbound queue */
7201 		qtype = "IBQ";
7202 		n = 4 * CIM_IBQ_SIZE;
7203 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
7204 		rc = t4_read_cim_ibq(sc, qid, buf, n);
7205 	} else {
7206 		/* outbound queue */
7207 		qtype = "OBQ";
7208 		qid -= CIM_NUM_IBQ;
7209 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
7210 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
7211 		rc = t4_read_cim_obq(sc, qid, buf, n);
7212 	}
7213 
7214 	if (rc < 0) {
7215 		rc = -rc;
7216 		goto done;
7217 	}
7218 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
7219 
7220 	rc = sysctl_wire_old_buffer(req, 0);
7221 	if (rc != 0)
7222 		goto done;
7223 
7224 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
7225 	if (sb == NULL) {
7226 		rc = ENOMEM;
7227 		goto done;
7228 	}
7229 
7230 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
7231 	for (i = 0, p = buf; i < n; i += 16, p += 4)
7232 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
7233 		    p[2], p[3]);
7234 
7235 	rc = sbuf_finish(sb);
7236 	sbuf_delete(sb);
7237 done:
7238 	free(buf, M_CXGBE);
7239 	return (rc);
7240 }
7241 
7242 static int
7243 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
7244 {
7245 	struct adapter *sc = arg1;
7246 	u_int cfg;
7247 	struct sbuf *sb;
7248 	uint32_t *buf, *p;
7249 	int rc;
7250 
7251 	MPASS(chip_id(sc) <= CHELSIO_T5);
7252 
7253 	rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
7254 	if (rc != 0)
7255 		return (rc);
7256 
7257 	rc = sysctl_wire_old_buffer(req, 0);
7258 	if (rc != 0)
7259 		return (rc);
7260 
7261 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7262 	if (sb == NULL)
7263 		return (ENOMEM);
7264 
7265 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
7266 	    M_ZERO | M_WAITOK);
7267 
7268 	rc = -t4_cim_read_la(sc, buf, NULL);
7269 	if (rc != 0)
7270 		goto done;
7271 
7272 	sbuf_printf(sb, "Status   Data      PC%s",
7273 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
7274 	    "     LS0Stat  LS0Addr             LS0Data");
7275 
7276 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
7277 		if (cfg & F_UPDBGLACAPTPCONLY) {
7278 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
7279 			    p[6], p[7]);
7280 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
7281 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
7282 			    p[4] & 0xff, p[5] >> 8);
7283 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
7284 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
7285 			    p[1] & 0xf, p[2] >> 4);
7286 		} else {
7287 			sbuf_printf(sb,
7288 			    "\n  %02x   %x%07x %x%07x %08x %08x "
7289 			    "%08x%08x%08x%08x",
7290 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
7291 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
7292 			    p[6], p[7]);
7293 		}
7294 	}
7295 
7296 	rc = sbuf_finish(sb);
7297 	sbuf_delete(sb);
7298 done:
7299 	free(buf, M_CXGBE);
7300 	return (rc);
7301 }
7302 
7303 static int
7304 sysctl_cim_la_t6(SYSCTL_HANDLER_ARGS)
7305 {
7306 	struct adapter *sc = arg1;
7307 	u_int cfg;
7308 	struct sbuf *sb;
7309 	uint32_t *buf, *p;
7310 	int rc;
7311 
7312 	MPASS(chip_id(sc) > CHELSIO_T5);
7313 
7314 	rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
7315 	if (rc != 0)
7316 		return (rc);
7317 
7318 	rc = sysctl_wire_old_buffer(req, 0);
7319 	if (rc != 0)
7320 		return (rc);
7321 
7322 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7323 	if (sb == NULL)
7324 		return (ENOMEM);
7325 
7326 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
7327 	    M_ZERO | M_WAITOK);
7328 
7329 	rc = -t4_cim_read_la(sc, buf, NULL);
7330 	if (rc != 0)
7331 		goto done;
7332 
7333 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
7334 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
7335 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
7336 
7337 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
7338 		if (cfg & F_UPDBGLACAPTPCONLY) {
7339 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
7340 			    p[3] & 0xff, p[2], p[1], p[0]);
7341 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
7342 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
7343 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
7344 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
7345 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
7346 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
7347 			    p[6] >> 16);
7348 		} else {
7349 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
7350 			    "%08x %08x %08x %08x %08x %08x",
7351 			    (p[9] >> 16) & 0xff,
7352 			    p[9] & 0xffff, p[8] >> 16,
7353 			    p[8] & 0xffff, p[7] >> 16,
7354 			    p[7] & 0xffff, p[6] >> 16,
7355 			    p[2], p[1], p[0], p[5], p[4], p[3]);
7356 		}
7357 	}
7358 
7359 	rc = sbuf_finish(sb);
7360 	sbuf_delete(sb);
7361 done:
7362 	free(buf, M_CXGBE);
7363 	return (rc);
7364 }
7365 
7366 static int
7367 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
7368 {
7369 	struct adapter *sc = arg1;
7370 	u_int i;
7371 	struct sbuf *sb;
7372 	uint32_t *buf, *p;
7373 	int rc;
7374 
7375 	rc = sysctl_wire_old_buffer(req, 0);
7376 	if (rc != 0)
7377 		return (rc);
7378 
7379 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7380 	if (sb == NULL)
7381 		return (ENOMEM);
7382 
7383 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
7384 	    M_ZERO | M_WAITOK);
7385 
7386 	t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
7387 	p = buf;
7388 
7389 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
7390 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
7391 		    p[1], p[0]);
7392 	}
7393 
7394 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
7395 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
7396 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
7397 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
7398 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
7399 		    (p[1] >> 2) | ((p[2] & 3) << 30),
7400 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
7401 		    p[0] & 1);
7402 	}
7403 
7404 	rc = sbuf_finish(sb);
7405 	sbuf_delete(sb);
7406 	free(buf, M_CXGBE);
7407 	return (rc);
7408 }
7409 
7410 static int
7411 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
7412 {
7413 	struct adapter *sc = arg1;
7414 	u_int i;
7415 	struct sbuf *sb;
7416 	uint32_t *buf, *p;
7417 	int rc;
7418 
7419 	rc = sysctl_wire_old_buffer(req, 0);
7420 	if (rc != 0)
7421 		return (rc);
7422 
7423 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7424 	if (sb == NULL)
7425 		return (ENOMEM);
7426 
7427 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
7428 	    M_ZERO | M_WAITOK);
7429 
7430 	t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
7431 	p = buf;
7432 
7433 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
7434 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
7435 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
7436 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
7437 		    p[4], p[3], p[2], p[1], p[0]);
7438 	}
7439 
7440 	sbuf_printf(sb, "\n\nCntl ID               Data");
7441 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
7442 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
7443 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
7444 	}
7445 
7446 	rc = sbuf_finish(sb);
7447 	sbuf_delete(sb);
7448 	free(buf, M_CXGBE);
7449 	return (rc);
7450 }
7451 
7452 static int
7453 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
7454 {
7455 	struct adapter *sc = arg1;
7456 	struct sbuf *sb;
7457 	int rc, i;
7458 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
7459 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
7460 	uint16_t thres[CIM_NUM_IBQ];
7461 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
7462 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
7463 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
7464 
7465 	cim_num_obq = sc->chip_params->cim_num_obq;
7466 	if (is_t4(sc)) {
7467 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
7468 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
7469 	} else {
7470 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
7471 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
7472 	}
7473 	nq = CIM_NUM_IBQ + cim_num_obq;
7474 
7475 	rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
7476 	if (rc == 0)
7477 		rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq, obq_wr);
7478 	if (rc != 0)
7479 		return (rc);
7480 
7481 	t4_read_cimq_cfg(sc, base, size, thres);
7482 
7483 	rc = sysctl_wire_old_buffer(req, 0);
7484 	if (rc != 0)
7485 		return (rc);
7486 
7487 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
7488 	if (sb == NULL)
7489 		return (ENOMEM);
7490 
7491 	sbuf_printf(sb,
7492 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
7493 
7494 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
7495 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
7496 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
7497 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
7498 		    G_QUEREMFLITS(p[2]) * 16);
7499 	for ( ; i < nq; i++, p += 4, wr += 2)
7500 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
7501 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
7502 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
7503 		    G_QUEREMFLITS(p[2]) * 16);
7504 
7505 	rc = sbuf_finish(sb);
7506 	sbuf_delete(sb);
7507 
7508 	return (rc);
7509 }
7510 
7511 static int
7512 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
7513 {
7514 	struct adapter *sc = arg1;
7515 	struct sbuf *sb;
7516 	int rc;
7517 	struct tp_cpl_stats stats;
7518 
7519 	rc = sysctl_wire_old_buffer(req, 0);
7520 	if (rc != 0)
7521 		return (rc);
7522 
7523 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7524 	if (sb == NULL)
7525 		return (ENOMEM);
7526 
7527 	mtx_lock(&sc->reg_lock);
7528 	t4_tp_get_cpl_stats(sc, &stats, 0);
7529 	mtx_unlock(&sc->reg_lock);
7530 
7531 	if (sc->chip_params->nchan > 2) {
7532 		sbuf_printf(sb, "                 channel 0  channel 1"
7533 		    "  channel 2  channel 3");
7534 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
7535 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
7536 		sbuf_printf(sb, "\nCPL responses:   %10u %10u %10u %10u",
7537 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
7538 	} else {
7539 		sbuf_printf(sb, "                 channel 0  channel 1");
7540 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
7541 		    stats.req[0], stats.req[1]);
7542 		sbuf_printf(sb, "\nCPL responses:   %10u %10u",
7543 		    stats.rsp[0], stats.rsp[1]);
7544 	}
7545 
7546 	rc = sbuf_finish(sb);
7547 	sbuf_delete(sb);
7548 
7549 	return (rc);
7550 }
7551 
7552 static int
7553 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
7554 {
7555 	struct adapter *sc = arg1;
7556 	struct sbuf *sb;
7557 	int rc;
7558 	struct tp_usm_stats stats;
7559 
7560 	rc = sysctl_wire_old_buffer(req, 0);
7561 	if (rc != 0)
7562 		return(rc);
7563 
7564 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7565 	if (sb == NULL)
7566 		return (ENOMEM);
7567 
7568 	t4_get_usm_stats(sc, &stats, 1);
7569 
7570 	sbuf_printf(sb, "Frames: %u\n", stats.frames);
7571 	sbuf_printf(sb, "Octets: %ju\n", stats.octets);
7572 	sbuf_printf(sb, "Drops:  %u", stats.drops);
7573 
7574 	rc = sbuf_finish(sb);
7575 	sbuf_delete(sb);
7576 
7577 	return (rc);
7578 }
7579 
7580 static const char * const devlog_level_strings[] = {
7581 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
7582 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
7583 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
7584 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
7585 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
7586 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
7587 };
7588 
7589 static const char * const devlog_facility_strings[] = {
7590 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
7591 	[FW_DEVLOG_FACILITY_CF]		= "CF",
7592 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
7593 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
7594 	[FW_DEVLOG_FACILITY_RES]	= "RES",
7595 	[FW_DEVLOG_FACILITY_HW]		= "HW",
7596 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
7597 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
7598 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
7599 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
7600 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
7601 	[FW_DEVLOG_FACILITY_VI]		= "VI",
7602 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
7603 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
7604 	[FW_DEVLOG_FACILITY_TM]		= "TM",
7605 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
7606 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
7607 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
7608 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
7609 	[FW_DEVLOG_FACILITY_RI]		= "RI",
7610 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
7611 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
7612 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
7613 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
7614 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
7615 };
7616 
7617 static int
7618 sysctl_devlog(SYSCTL_HANDLER_ARGS)
7619 {
7620 	struct adapter *sc = arg1;
7621 	struct devlog_params *dparams = &sc->params.devlog;
7622 	struct fw_devlog_e *buf, *e;
7623 	int i, j, rc, nentries, first = 0;
7624 	struct sbuf *sb;
7625 	uint64_t ftstamp = UINT64_MAX;
7626 
7627 	if (dparams->addr == 0)
7628 		return (ENXIO);
7629 
7630 	buf = malloc(dparams->size, M_CXGBE, M_NOWAIT);
7631 	if (buf == NULL)
7632 		return (ENOMEM);
7633 
7634 	rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf, dparams->size);
7635 	if (rc != 0)
7636 		goto done;
7637 
7638 	nentries = dparams->size / sizeof(struct fw_devlog_e);
7639 	for (i = 0; i < nentries; i++) {
7640 		e = &buf[i];
7641 
7642 		if (e->timestamp == 0)
7643 			break;	/* end */
7644 
7645 		e->timestamp = be64toh(e->timestamp);
7646 		e->seqno = be32toh(e->seqno);
7647 		for (j = 0; j < 8; j++)
7648 			e->params[j] = be32toh(e->params[j]);
7649 
7650 		if (e->timestamp < ftstamp) {
7651 			ftstamp = e->timestamp;
7652 			first = i;
7653 		}
7654 	}
7655 
7656 	if (buf[first].timestamp == 0)
7657 		goto done;	/* nothing in the log */
7658 
7659 	rc = sysctl_wire_old_buffer(req, 0);
7660 	if (rc != 0)
7661 		goto done;
7662 
7663 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7664 	if (sb == NULL) {
7665 		rc = ENOMEM;
7666 		goto done;
7667 	}
7668 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
7669 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
7670 
7671 	i = first;
7672 	do {
7673 		e = &buf[i];
7674 		if (e->timestamp == 0)
7675 			break;	/* end */
7676 
7677 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
7678 		    e->seqno, e->timestamp,
7679 		    (e->level < nitems(devlog_level_strings) ?
7680 			devlog_level_strings[e->level] : "UNKNOWN"),
7681 		    (e->facility < nitems(devlog_facility_strings) ?
7682 			devlog_facility_strings[e->facility] : "UNKNOWN"));
7683 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
7684 		    e->params[2], e->params[3], e->params[4],
7685 		    e->params[5], e->params[6], e->params[7]);
7686 
7687 		if (++i == nentries)
7688 			i = 0;
7689 	} while (i != first);
7690 
7691 	rc = sbuf_finish(sb);
7692 	sbuf_delete(sb);
7693 done:
7694 	free(buf, M_CXGBE);
7695 	return (rc);
7696 }
7697 
7698 static int
7699 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
7700 {
7701 	struct adapter *sc = arg1;
7702 	struct sbuf *sb;
7703 	int rc;
7704 	struct tp_fcoe_stats stats[MAX_NCHAN];
7705 	int i, nchan = sc->chip_params->nchan;
7706 
7707 	rc = sysctl_wire_old_buffer(req, 0);
7708 	if (rc != 0)
7709 		return (rc);
7710 
7711 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7712 	if (sb == NULL)
7713 		return (ENOMEM);
7714 
7715 	for (i = 0; i < nchan; i++)
7716 		t4_get_fcoe_stats(sc, i, &stats[i], 1);
7717 
7718 	if (nchan > 2) {
7719 		sbuf_printf(sb, "                   channel 0        channel 1"
7720 		    "        channel 2        channel 3");
7721 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
7722 		    stats[0].octets_ddp, stats[1].octets_ddp,
7723 		    stats[2].octets_ddp, stats[3].octets_ddp);
7724 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
7725 		    stats[0].frames_ddp, stats[1].frames_ddp,
7726 		    stats[2].frames_ddp, stats[3].frames_ddp);
7727 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
7728 		    stats[0].frames_drop, stats[1].frames_drop,
7729 		    stats[2].frames_drop, stats[3].frames_drop);
7730 	} else {
7731 		sbuf_printf(sb, "                   channel 0        channel 1");
7732 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
7733 		    stats[0].octets_ddp, stats[1].octets_ddp);
7734 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
7735 		    stats[0].frames_ddp, stats[1].frames_ddp);
7736 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
7737 		    stats[0].frames_drop, stats[1].frames_drop);
7738 	}
7739 
7740 	rc = sbuf_finish(sb);
7741 	sbuf_delete(sb);
7742 
7743 	return (rc);
7744 }
7745 
7746 static int
7747 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
7748 {
7749 	struct adapter *sc = arg1;
7750 	struct sbuf *sb;
7751 	int rc, i;
7752 	unsigned int map, kbps, ipg, mode;
7753 	unsigned int pace_tab[NTX_SCHED];
7754 
7755 	rc = sysctl_wire_old_buffer(req, 0);
7756 	if (rc != 0)
7757 		return (rc);
7758 
7759 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7760 	if (sb == NULL)
7761 		return (ENOMEM);
7762 
7763 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
7764 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
7765 	t4_read_pace_tbl(sc, pace_tab);
7766 
7767 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
7768 	    "Class IPG (0.1 ns)   Flow IPG (us)");
7769 
7770 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
7771 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
7772 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
7773 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
7774 		if (kbps)
7775 			sbuf_printf(sb, "%9u     ", kbps);
7776 		else
7777 			sbuf_printf(sb, " disabled     ");
7778 
7779 		if (ipg)
7780 			sbuf_printf(sb, "%13u        ", ipg);
7781 		else
7782 			sbuf_printf(sb, "     disabled        ");
7783 
7784 		if (pace_tab[i])
7785 			sbuf_printf(sb, "%10u", pace_tab[i]);
7786 		else
7787 			sbuf_printf(sb, "  disabled");
7788 	}
7789 
7790 	rc = sbuf_finish(sb);
7791 	sbuf_delete(sb);
7792 
7793 	return (rc);
7794 }
7795 
7796 static int
7797 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
7798 {
7799 	struct adapter *sc = arg1;
7800 	struct sbuf *sb;
7801 	int rc, i, j;
7802 	uint64_t *p0, *p1;
7803 	struct lb_port_stats s[2];
7804 	static const char *stat_name[] = {
7805 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
7806 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
7807 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
7808 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
7809 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
7810 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
7811 		"BG2FramesTrunc:", "BG3FramesTrunc:"
7812 	};
7813 
7814 	rc = sysctl_wire_old_buffer(req, 0);
7815 	if (rc != 0)
7816 		return (rc);
7817 
7818 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7819 	if (sb == NULL)
7820 		return (ENOMEM);
7821 
7822 	memset(s, 0, sizeof(s));
7823 
7824 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
7825 		t4_get_lb_stats(sc, i, &s[0]);
7826 		t4_get_lb_stats(sc, i + 1, &s[1]);
7827 
7828 		p0 = &s[0].octets;
7829 		p1 = &s[1].octets;
7830 		sbuf_printf(sb, "%s                       Loopback %u"
7831 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
7832 
7833 		for (j = 0; j < nitems(stat_name); j++)
7834 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
7835 				   *p0++, *p1++);
7836 	}
7837 
7838 	rc = sbuf_finish(sb);
7839 	sbuf_delete(sb);
7840 
7841 	return (rc);
7842 }
7843 
7844 static int
7845 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
7846 {
7847 	int rc = 0;
7848 	struct port_info *pi = arg1;
7849 	struct link_config *lc = &pi->link_cfg;
7850 	struct sbuf *sb;
7851 
7852 	rc = sysctl_wire_old_buffer(req, 0);
7853 	if (rc != 0)
7854 		return(rc);
7855 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
7856 	if (sb == NULL)
7857 		return (ENOMEM);
7858 
7859 	if (lc->link_ok || lc->link_down_rc == 255)
7860 		sbuf_printf(sb, "n/a");
7861 	else
7862 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
7863 
7864 	rc = sbuf_finish(sb);
7865 	sbuf_delete(sb);
7866 
7867 	return (rc);
7868 }
7869 
7870 struct mem_desc {
7871 	unsigned int base;
7872 	unsigned int limit;
7873 	unsigned int idx;
7874 };
7875 
7876 static int
7877 mem_desc_cmp(const void *a, const void *b)
7878 {
7879 	return ((const struct mem_desc *)a)->base -
7880 	       ((const struct mem_desc *)b)->base;
7881 }
7882 
7883 static void
7884 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
7885     unsigned int to)
7886 {
7887 	unsigned int size;
7888 
7889 	if (from == to)
7890 		return;
7891 
7892 	size = to - from + 1;
7893 	if (size == 0)
7894 		return;
7895 
7896 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
7897 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
7898 }
7899 
7900 static int
7901 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
7902 {
7903 	struct adapter *sc = arg1;
7904 	struct sbuf *sb;
7905 	int rc, i, n;
7906 	uint32_t lo, hi, used, alloc;
7907 	static const char *memory[] = {"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:"};
7908 	static const char *region[] = {
7909 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
7910 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
7911 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
7912 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
7913 		"RQUDP region:", "PBL region:", "TXPBL region:",
7914 		"DBVFIFO region:", "ULPRX state:", "ULPTX state:",
7915 		"On-chip queues:", "TLS keys:",
7916 	};
7917 	struct mem_desc avail[4];
7918 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
7919 	struct mem_desc *md = mem;
7920 
7921 	rc = sysctl_wire_old_buffer(req, 0);
7922 	if (rc != 0)
7923 		return (rc);
7924 
7925 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7926 	if (sb == NULL)
7927 		return (ENOMEM);
7928 
7929 	for (i = 0; i < nitems(mem); i++) {
7930 		mem[i].limit = 0;
7931 		mem[i].idx = i;
7932 	}
7933 
7934 	/* Find and sort the populated memory ranges */
7935 	i = 0;
7936 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
7937 	if (lo & F_EDRAM0_ENABLE) {
7938 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
7939 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
7940 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
7941 		avail[i].idx = 0;
7942 		i++;
7943 	}
7944 	if (lo & F_EDRAM1_ENABLE) {
7945 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
7946 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
7947 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
7948 		avail[i].idx = 1;
7949 		i++;
7950 	}
7951 	if (lo & F_EXT_MEM_ENABLE) {
7952 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
7953 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
7954 		avail[i].limit = avail[i].base +
7955 		    (G_EXT_MEM_SIZE(hi) << 20);
7956 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
7957 		i++;
7958 	}
7959 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
7960 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
7961 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
7962 		avail[i].limit = avail[i].base +
7963 		    (G_EXT_MEM1_SIZE(hi) << 20);
7964 		avail[i].idx = 4;
7965 		i++;
7966 	}
7967 	if (!i)                                    /* no memory available */
7968 		return 0;
7969 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
7970 
7971 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
7972 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
7973 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
7974 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
7975 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
7976 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
7977 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
7978 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
7979 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
7980 
7981 	/* the next few have explicit upper bounds */
7982 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
7983 	md->limit = md->base - 1 +
7984 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
7985 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
7986 	md++;
7987 
7988 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
7989 	md->limit = md->base - 1 +
7990 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
7991 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
7992 	md++;
7993 
7994 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
7995 		if (chip_id(sc) <= CHELSIO_T5)
7996 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
7997 		else
7998 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
7999 		md->limit = 0;
8000 	} else {
8001 		md->base = 0;
8002 		md->idx = nitems(region);  /* hide it */
8003 	}
8004 	md++;
8005 
8006 #define ulp_region(reg) \
8007 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
8008 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
8009 
8010 	ulp_region(RX_ISCSI);
8011 	ulp_region(RX_TDDP);
8012 	ulp_region(TX_TPT);
8013 	ulp_region(RX_STAG);
8014 	ulp_region(RX_RQ);
8015 	ulp_region(RX_RQUDP);
8016 	ulp_region(RX_PBL);
8017 	ulp_region(TX_PBL);
8018 #undef ulp_region
8019 
8020 	md->base = 0;
8021 	md->idx = nitems(region);
8022 	if (!is_t4(sc)) {
8023 		uint32_t size = 0;
8024 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
8025 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
8026 
8027 		if (is_t5(sc)) {
8028 			if (sge_ctrl & F_VFIFO_ENABLE)
8029 				size = G_DBVFIFO_SIZE(fifo_size);
8030 		} else
8031 			size = G_T6_DBVFIFO_SIZE(fifo_size);
8032 
8033 		if (size) {
8034 			md->base = G_BASEADDR(t4_read_reg(sc,
8035 			    A_SGE_DBVFIFO_BADDR));
8036 			md->limit = md->base + (size << 2) - 1;
8037 		}
8038 	}
8039 	md++;
8040 
8041 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
8042 	md->limit = 0;
8043 	md++;
8044 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
8045 	md->limit = 0;
8046 	md++;
8047 
8048 	md->base = sc->vres.ocq.start;
8049 	if (sc->vres.ocq.size)
8050 		md->limit = md->base + sc->vres.ocq.size - 1;
8051 	else
8052 		md->idx = nitems(region);  /* hide it */
8053 	md++;
8054 
8055 	md->base = sc->vres.key.start;
8056 	if (sc->vres.key.size)
8057 		md->limit = md->base + sc->vres.key.size - 1;
8058 	else
8059 		md->idx = nitems(region);  /* hide it */
8060 	md++;
8061 
8062 	/* add any address-space holes, there can be up to 3 */
8063 	for (n = 0; n < i - 1; n++)
8064 		if (avail[n].limit < avail[n + 1].base)
8065 			(md++)->base = avail[n].limit;
8066 	if (avail[n].limit)
8067 		(md++)->base = avail[n].limit;
8068 
8069 	n = md - mem;
8070 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
8071 
8072 	for (lo = 0; lo < i; lo++)
8073 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
8074 				avail[lo].limit - 1);
8075 
8076 	sbuf_printf(sb, "\n");
8077 	for (i = 0; i < n; i++) {
8078 		if (mem[i].idx >= nitems(region))
8079 			continue;                        /* skip holes */
8080 		if (!mem[i].limit)
8081 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
8082 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
8083 				mem[i].limit);
8084 	}
8085 
8086 	sbuf_printf(sb, "\n");
8087 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
8088 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
8089 	mem_region_show(sb, "uP RAM:", lo, hi);
8090 
8091 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
8092 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
8093 	mem_region_show(sb, "uP Extmem2:", lo, hi);
8094 
8095 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
8096 	sbuf_printf(sb, "\n%u Rx pages of size %uKiB for %u channels\n",
8097 		   G_PMRXMAXPAGE(lo),
8098 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
8099 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
8100 
8101 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
8102 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
8103 	sbuf_printf(sb, "%u Tx pages of size %u%ciB for %u channels\n",
8104 		   G_PMTXMAXPAGE(lo),
8105 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
8106 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
8107 	sbuf_printf(sb, "%u p-structs\n",
8108 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT));
8109 
8110 	for (i = 0; i < 4; i++) {
8111 		if (chip_id(sc) > CHELSIO_T5)
8112 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
8113 		else
8114 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
8115 		if (is_t5(sc)) {
8116 			used = G_T5_USED(lo);
8117 			alloc = G_T5_ALLOC(lo);
8118 		} else {
8119 			used = G_USED(lo);
8120 			alloc = G_ALLOC(lo);
8121 		}
8122 		/* For T6 these are MAC buffer groups */
8123 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
8124 		    i, used, alloc);
8125 	}
8126 	for (i = 0; i < sc->chip_params->nchan; i++) {
8127 		if (chip_id(sc) > CHELSIO_T5)
8128 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
8129 		else
8130 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
8131 		if (is_t5(sc)) {
8132 			used = G_T5_USED(lo);
8133 			alloc = G_T5_ALLOC(lo);
8134 		} else {
8135 			used = G_USED(lo);
8136 			alloc = G_ALLOC(lo);
8137 		}
8138 		/* For T6 these are MAC buffer groups */
8139 		sbuf_printf(sb,
8140 		    "\nLoopback %d using %u pages out of %u allocated",
8141 		    i, used, alloc);
8142 	}
8143 
8144 	rc = sbuf_finish(sb);
8145 	sbuf_delete(sb);
8146 
8147 	return (rc);
8148 }
8149 
8150 static inline void
8151 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
8152 {
8153 	*mask = x | y;
8154 	y = htobe64(y);
8155 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
8156 }
8157 
8158 static int
8159 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
8160 {
8161 	struct adapter *sc = arg1;
8162 	struct sbuf *sb;
8163 	int rc, i;
8164 
8165 	MPASS(chip_id(sc) <= CHELSIO_T5);
8166 
8167 	rc = sysctl_wire_old_buffer(req, 0);
8168 	if (rc != 0)
8169 		return (rc);
8170 
8171 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8172 	if (sb == NULL)
8173 		return (ENOMEM);
8174 
8175 	sbuf_printf(sb,
8176 	    "Idx  Ethernet address     Mask     Vld Ports PF"
8177 	    "  VF              Replication             P0 P1 P2 P3  ML");
8178 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
8179 		uint64_t tcamx, tcamy, mask;
8180 		uint32_t cls_lo, cls_hi;
8181 		uint8_t addr[ETHER_ADDR_LEN];
8182 
8183 		tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
8184 		tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
8185 		if (tcamx & tcamy)
8186 			continue;
8187 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
8188 		cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
8189 		cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
8190 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
8191 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
8192 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
8193 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
8194 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
8195 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
8196 
8197 		if (cls_lo & F_REPLICATE) {
8198 			struct fw_ldst_cmd ldst_cmd;
8199 
8200 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
8201 			ldst_cmd.op_to_addrspace =
8202 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
8203 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
8204 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
8205 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
8206 			ldst_cmd.u.mps.rplc.fid_idx =
8207 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
8208 				V_FW_LDST_CMD_IDX(i));
8209 
8210 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8211 			    "t4mps");
8212 			if (rc)
8213 				break;
8214 			rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
8215 			    sizeof(ldst_cmd), &ldst_cmd);
8216 			end_synchronized_op(sc, 0);
8217 
8218 			if (rc != 0) {
8219 				sbuf_printf(sb, "%36d", rc);
8220 				rc = 0;
8221 			} else {
8222 				sbuf_printf(sb, " %08x %08x %08x %08x",
8223 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
8224 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
8225 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
8226 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
8227 			}
8228 		} else
8229 			sbuf_printf(sb, "%36s", "");
8230 
8231 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
8232 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
8233 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
8234 	}
8235 
8236 	if (rc)
8237 		(void) sbuf_finish(sb);
8238 	else
8239 		rc = sbuf_finish(sb);
8240 	sbuf_delete(sb);
8241 
8242 	return (rc);
8243 }
8244 
8245 static int
8246 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
8247 {
8248 	struct adapter *sc = arg1;
8249 	struct sbuf *sb;
8250 	int rc, i;
8251 
8252 	MPASS(chip_id(sc) > CHELSIO_T5);
8253 
8254 	rc = sysctl_wire_old_buffer(req, 0);
8255 	if (rc != 0)
8256 		return (rc);
8257 
8258 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8259 	if (sb == NULL)
8260 		return (ENOMEM);
8261 
8262 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
8263 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
8264 	    "                           Replication"
8265 	    "                                    P0 P1 P2 P3  ML\n");
8266 
8267 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
8268 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
8269 		uint16_t ivlan;
8270 		uint64_t tcamx, tcamy, val, mask;
8271 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
8272 		uint8_t addr[ETHER_ADDR_LEN];
8273 
8274 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
8275 		if (i < 256)
8276 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
8277 		else
8278 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
8279 		t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
8280 		val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
8281 		tcamy = G_DMACH(val) << 32;
8282 		tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
8283 		data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
8284 		lookup_type = G_DATALKPTYPE(data2);
8285 		port_num = G_DATAPORTNUM(data2);
8286 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
8287 			/* Inner header VNI */
8288 			vniy = ((data2 & F_DATAVIDH2) << 23) |
8289 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
8290 			dip_hit = data2 & F_DATADIPHIT;
8291 			vlan_vld = 0;
8292 		} else {
8293 			vniy = 0;
8294 			dip_hit = 0;
8295 			vlan_vld = data2 & F_DATAVIDH2;
8296 			ivlan = G_VIDL(val);
8297 		}
8298 
8299 		ctl |= V_CTLXYBITSEL(1);
8300 		t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
8301 		val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
8302 		tcamx = G_DMACH(val) << 32;
8303 		tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
8304 		data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
8305 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
8306 			/* Inner header VNI mask */
8307 			vnix = ((data2 & F_DATAVIDH2) << 23) |
8308 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
8309 		} else
8310 			vnix = 0;
8311 
8312 		if (tcamx & tcamy)
8313 			continue;
8314 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
8315 
8316 		cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
8317 		cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
8318 
8319 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
8320 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
8321 			    "%012jx %06x %06x    -    -   %3c"
8322 			    "      'I'  %4x   %3c   %#x%4u%4d", i, addr[0],
8323 			    addr[1], addr[2], addr[3], addr[4], addr[5],
8324 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
8325 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
8326 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
8327 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
8328 		} else {
8329 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
8330 			    "%012jx    -       -   ", i, addr[0], addr[1],
8331 			    addr[2], addr[3], addr[4], addr[5],
8332 			    (uintmax_t)mask);
8333 
8334 			if (vlan_vld)
8335 				sbuf_printf(sb, "%4u   Y     ", ivlan);
8336 			else
8337 				sbuf_printf(sb, "  -    N     ");
8338 
8339 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
8340 			    lookup_type ? 'I' : 'O', port_num,
8341 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
8342 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
8343 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
8344 		}
8345 
8346 
8347 		if (cls_lo & F_T6_REPLICATE) {
8348 			struct fw_ldst_cmd ldst_cmd;
8349 
8350 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
8351 			ldst_cmd.op_to_addrspace =
8352 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
8353 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
8354 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
8355 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
8356 			ldst_cmd.u.mps.rplc.fid_idx =
8357 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
8358 				V_FW_LDST_CMD_IDX(i));
8359 
8360 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8361 			    "t6mps");
8362 			if (rc)
8363 				break;
8364 			rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
8365 			    sizeof(ldst_cmd), &ldst_cmd);
8366 			end_synchronized_op(sc, 0);
8367 
8368 			if (rc != 0) {
8369 				sbuf_printf(sb, "%72d", rc);
8370 				rc = 0;
8371 			} else {
8372 				sbuf_printf(sb, " %08x %08x %08x %08x"
8373 				    " %08x %08x %08x %08x",
8374 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
8375 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
8376 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
8377 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
8378 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
8379 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
8380 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
8381 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
8382 			}
8383 		} else
8384 			sbuf_printf(sb, "%72s", "");
8385 
8386 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
8387 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
8388 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
8389 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
8390 	}
8391 
8392 	if (rc)
8393 		(void) sbuf_finish(sb);
8394 	else
8395 		rc = sbuf_finish(sb);
8396 	sbuf_delete(sb);
8397 
8398 	return (rc);
8399 }
8400 
8401 static int
8402 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
8403 {
8404 	struct adapter *sc = arg1;
8405 	struct sbuf *sb;
8406 	int rc;
8407 	uint16_t mtus[NMTUS];
8408 
8409 	rc = sysctl_wire_old_buffer(req, 0);
8410 	if (rc != 0)
8411 		return (rc);
8412 
8413 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8414 	if (sb == NULL)
8415 		return (ENOMEM);
8416 
8417 	t4_read_mtu_tbl(sc, mtus, NULL);
8418 
8419 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
8420 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
8421 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
8422 	    mtus[14], mtus[15]);
8423 
8424 	rc = sbuf_finish(sb);
8425 	sbuf_delete(sb);
8426 
8427 	return (rc);
8428 }
8429 
8430 static int
8431 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
8432 {
8433 	struct adapter *sc = arg1;
8434 	struct sbuf *sb;
8435 	int rc, i;
8436 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
8437 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
8438 	static const char *tx_stats[MAX_PM_NSTATS] = {
8439 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
8440 		"Tx FIFO wait", NULL, "Tx latency"
8441 	};
8442 	static const char *rx_stats[MAX_PM_NSTATS] = {
8443 		"Read:", "Write bypass:", "Write mem:", "Flush:",
8444 		"Rx FIFO wait", NULL, "Rx latency"
8445 	};
8446 
8447 	rc = sysctl_wire_old_buffer(req, 0);
8448 	if (rc != 0)
8449 		return (rc);
8450 
8451 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8452 	if (sb == NULL)
8453 		return (ENOMEM);
8454 
8455 	t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
8456 	t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
8457 
8458 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
8459 	for (i = 0; i < 4; i++) {
8460 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
8461 		    tx_cyc[i]);
8462 	}
8463 
8464 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
8465 	for (i = 0; i < 4; i++) {
8466 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
8467 		    rx_cyc[i]);
8468 	}
8469 
8470 	if (chip_id(sc) > CHELSIO_T5) {
8471 		sbuf_printf(sb,
8472 		    "\n              Total wait      Total occupancy");
8473 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
8474 		    tx_cyc[i]);
8475 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
8476 		    rx_cyc[i]);
8477 
8478 		i += 2;
8479 		MPASS(i < nitems(tx_stats));
8480 
8481 		sbuf_printf(sb,
8482 		    "\n                   Reads           Total wait");
8483 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
8484 		    tx_cyc[i]);
8485 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
8486 		    rx_cyc[i]);
8487 	}
8488 
8489 	rc = sbuf_finish(sb);
8490 	sbuf_delete(sb);
8491 
8492 	return (rc);
8493 }
8494 
8495 static int
8496 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
8497 {
8498 	struct adapter *sc = arg1;
8499 	struct sbuf *sb;
8500 	int rc;
8501 	struct tp_rdma_stats stats;
8502 
8503 	rc = sysctl_wire_old_buffer(req, 0);
8504 	if (rc != 0)
8505 		return (rc);
8506 
8507 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8508 	if (sb == NULL)
8509 		return (ENOMEM);
8510 
8511 	mtx_lock(&sc->reg_lock);
8512 	t4_tp_get_rdma_stats(sc, &stats, 0);
8513 	mtx_unlock(&sc->reg_lock);
8514 
8515 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
8516 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
8517 
8518 	rc = sbuf_finish(sb);
8519 	sbuf_delete(sb);
8520 
8521 	return (rc);
8522 }
8523 
8524 static int
8525 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
8526 {
8527 	struct adapter *sc = arg1;
8528 	struct sbuf *sb;
8529 	int rc;
8530 	struct tp_tcp_stats v4, v6;
8531 
8532 	rc = sysctl_wire_old_buffer(req, 0);
8533 	if (rc != 0)
8534 		return (rc);
8535 
8536 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8537 	if (sb == NULL)
8538 		return (ENOMEM);
8539 
8540 	mtx_lock(&sc->reg_lock);
8541 	t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
8542 	mtx_unlock(&sc->reg_lock);
8543 
8544 	sbuf_printf(sb,
8545 	    "                                IP                 IPv6\n");
8546 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
8547 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
8548 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
8549 	    v4.tcp_in_segs, v6.tcp_in_segs);
8550 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
8551 	    v4.tcp_out_segs, v6.tcp_out_segs);
8552 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
8553 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
8554 
8555 	rc = sbuf_finish(sb);
8556 	sbuf_delete(sb);
8557 
8558 	return (rc);
8559 }
8560 
8561 static int
8562 sysctl_tids(SYSCTL_HANDLER_ARGS)
8563 {
8564 	struct adapter *sc = arg1;
8565 	struct sbuf *sb;
8566 	int rc;
8567 	struct tid_info *t = &sc->tids;
8568 
8569 	rc = sysctl_wire_old_buffer(req, 0);
8570 	if (rc != 0)
8571 		return (rc);
8572 
8573 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8574 	if (sb == NULL)
8575 		return (ENOMEM);
8576 
8577 	if (t->natids) {
8578 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
8579 		    t->atids_in_use);
8580 	}
8581 
8582 	if (t->nhpftids) {
8583 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
8584 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
8585 	}
8586 
8587 	if (t->ntids) {
8588 		sbuf_printf(sb, "TID range: ");
8589 		if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
8590 			uint32_t b, hb;
8591 
8592 			if (chip_id(sc) <= CHELSIO_T5) {
8593 				b = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
8594 				hb = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
8595 			} else {
8596 				b = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
8597 				hb = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
8598 			}
8599 
8600 			if (b)
8601 				sbuf_printf(sb, "%u-%u, ", t->tid_base, b - 1);
8602 			sbuf_printf(sb, "%u-%u", hb, t->ntids - 1);
8603 		} else
8604 			sbuf_printf(sb, "%u-%u", t->tid_base, t->ntids - 1);
8605 		sbuf_printf(sb, ", in use: %u\n",
8606 		    atomic_load_acq_int(&t->tids_in_use));
8607 	}
8608 
8609 	if (t->nstids) {
8610 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
8611 		    t->stid_base + t->nstids - 1, t->stids_in_use);
8612 	}
8613 
8614 	if (t->nftids) {
8615 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
8616 		    t->ftid_end, t->ftids_in_use);
8617 	}
8618 
8619 	if (t->netids) {
8620 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
8621 		    t->etid_base + t->netids - 1, t->etids_in_use);
8622 	}
8623 
8624 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users",
8625 	    t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4),
8626 	    t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6));
8627 
8628 	rc = sbuf_finish(sb);
8629 	sbuf_delete(sb);
8630 
8631 	return (rc);
8632 }
8633 
8634 static int
8635 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
8636 {
8637 	struct adapter *sc = arg1;
8638 	struct sbuf *sb;
8639 	int rc;
8640 	struct tp_err_stats stats;
8641 
8642 	rc = sysctl_wire_old_buffer(req, 0);
8643 	if (rc != 0)
8644 		return (rc);
8645 
8646 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8647 	if (sb == NULL)
8648 		return (ENOMEM);
8649 
8650 	mtx_lock(&sc->reg_lock);
8651 	t4_tp_get_err_stats(sc, &stats, 0);
8652 	mtx_unlock(&sc->reg_lock);
8653 
8654 	if (sc->chip_params->nchan > 2) {
8655 		sbuf_printf(sb, "                 channel 0  channel 1"
8656 		    "  channel 2  channel 3\n");
8657 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
8658 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
8659 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
8660 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
8661 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
8662 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
8663 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
8664 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
8665 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
8666 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
8667 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
8668 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
8669 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
8670 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
8671 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
8672 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
8673 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
8674 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
8675 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
8676 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
8677 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
8678 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
8679 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
8680 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
8681 	} else {
8682 		sbuf_printf(sb, "                 channel 0  channel 1\n");
8683 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
8684 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
8685 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
8686 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
8687 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
8688 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
8689 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
8690 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
8691 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
8692 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
8693 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
8694 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
8695 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
8696 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
8697 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
8698 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
8699 	}
8700 
8701 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
8702 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
8703 
8704 	rc = sbuf_finish(sb);
8705 	sbuf_delete(sb);
8706 
8707 	return (rc);
8708 }
8709 
8710 static int
8711 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
8712 {
8713 	struct adapter *sc = arg1;
8714 	struct tp_params *tpp = &sc->params.tp;
8715 	u_int mask;
8716 	int rc;
8717 
8718 	mask = tpp->la_mask >> 16;
8719 	rc = sysctl_handle_int(oidp, &mask, 0, req);
8720 	if (rc != 0 || req->newptr == NULL)
8721 		return (rc);
8722 	if (mask > 0xffff)
8723 		return (EINVAL);
8724 	tpp->la_mask = mask << 16;
8725 	t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U, tpp->la_mask);
8726 
8727 	return (0);
8728 }
8729 
8730 struct field_desc {
8731 	const char *name;
8732 	u_int start;
8733 	u_int width;
8734 };
8735 
8736 static void
8737 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
8738 {
8739 	char buf[32];
8740 	int line_size = 0;
8741 
8742 	while (f->name) {
8743 		uint64_t mask = (1ULL << f->width) - 1;
8744 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
8745 		    ((uintmax_t)v >> f->start) & mask);
8746 
8747 		if (line_size + len >= 79) {
8748 			line_size = 8;
8749 			sbuf_printf(sb, "\n        ");
8750 		}
8751 		sbuf_printf(sb, "%s ", buf);
8752 		line_size += len + 1;
8753 		f++;
8754 	}
8755 	sbuf_printf(sb, "\n");
8756 }
8757 
8758 static const struct field_desc tp_la0[] = {
8759 	{ "RcfOpCodeOut", 60, 4 },
8760 	{ "State", 56, 4 },
8761 	{ "WcfState", 52, 4 },
8762 	{ "RcfOpcSrcOut", 50, 2 },
8763 	{ "CRxError", 49, 1 },
8764 	{ "ERxError", 48, 1 },
8765 	{ "SanityFailed", 47, 1 },
8766 	{ "SpuriousMsg", 46, 1 },
8767 	{ "FlushInputMsg", 45, 1 },
8768 	{ "FlushInputCpl", 44, 1 },
8769 	{ "RssUpBit", 43, 1 },
8770 	{ "RssFilterHit", 42, 1 },
8771 	{ "Tid", 32, 10 },
8772 	{ "InitTcb", 31, 1 },
8773 	{ "LineNumber", 24, 7 },
8774 	{ "Emsg", 23, 1 },
8775 	{ "EdataOut", 22, 1 },
8776 	{ "Cmsg", 21, 1 },
8777 	{ "CdataOut", 20, 1 },
8778 	{ "EreadPdu", 19, 1 },
8779 	{ "CreadPdu", 18, 1 },
8780 	{ "TunnelPkt", 17, 1 },
8781 	{ "RcfPeerFin", 16, 1 },
8782 	{ "RcfReasonOut", 12, 4 },
8783 	{ "TxCchannel", 10, 2 },
8784 	{ "RcfTxChannel", 8, 2 },
8785 	{ "RxEchannel", 6, 2 },
8786 	{ "RcfRxChannel", 5, 1 },
8787 	{ "RcfDataOutSrdy", 4, 1 },
8788 	{ "RxDvld", 3, 1 },
8789 	{ "RxOoDvld", 2, 1 },
8790 	{ "RxCongestion", 1, 1 },
8791 	{ "TxCongestion", 0, 1 },
8792 	{ NULL }
8793 };
8794 
8795 static const struct field_desc tp_la1[] = {
8796 	{ "CplCmdIn", 56, 8 },
8797 	{ "CplCmdOut", 48, 8 },
8798 	{ "ESynOut", 47, 1 },
8799 	{ "EAckOut", 46, 1 },
8800 	{ "EFinOut", 45, 1 },
8801 	{ "ERstOut", 44, 1 },
8802 	{ "SynIn", 43, 1 },
8803 	{ "AckIn", 42, 1 },
8804 	{ "FinIn", 41, 1 },
8805 	{ "RstIn", 40, 1 },
8806 	{ "DataIn", 39, 1 },
8807 	{ "DataInVld", 38, 1 },
8808 	{ "PadIn", 37, 1 },
8809 	{ "RxBufEmpty", 36, 1 },
8810 	{ "RxDdp", 35, 1 },
8811 	{ "RxFbCongestion", 34, 1 },
8812 	{ "TxFbCongestion", 33, 1 },
8813 	{ "TxPktSumSrdy", 32, 1 },
8814 	{ "RcfUlpType", 28, 4 },
8815 	{ "Eread", 27, 1 },
8816 	{ "Ebypass", 26, 1 },
8817 	{ "Esave", 25, 1 },
8818 	{ "Static0", 24, 1 },
8819 	{ "Cread", 23, 1 },
8820 	{ "Cbypass", 22, 1 },
8821 	{ "Csave", 21, 1 },
8822 	{ "CPktOut", 20, 1 },
8823 	{ "RxPagePoolFull", 18, 2 },
8824 	{ "RxLpbkPkt", 17, 1 },
8825 	{ "TxLpbkPkt", 16, 1 },
8826 	{ "RxVfValid", 15, 1 },
8827 	{ "SynLearned", 14, 1 },
8828 	{ "SetDelEntry", 13, 1 },
8829 	{ "SetInvEntry", 12, 1 },
8830 	{ "CpcmdDvld", 11, 1 },
8831 	{ "CpcmdSave", 10, 1 },
8832 	{ "RxPstructsFull", 8, 2 },
8833 	{ "EpcmdDvld", 7, 1 },
8834 	{ "EpcmdFlush", 6, 1 },
8835 	{ "EpcmdTrimPrefix", 5, 1 },
8836 	{ "EpcmdTrimPostfix", 4, 1 },
8837 	{ "ERssIp4Pkt", 3, 1 },
8838 	{ "ERssIp6Pkt", 2, 1 },
8839 	{ "ERssTcpUdpPkt", 1, 1 },
8840 	{ "ERssFceFipPkt", 0, 1 },
8841 	{ NULL }
8842 };
8843 
8844 static const struct field_desc tp_la2[] = {
8845 	{ "CplCmdIn", 56, 8 },
8846 	{ "MpsVfVld", 55, 1 },
8847 	{ "MpsPf", 52, 3 },
8848 	{ "MpsVf", 44, 8 },
8849 	{ "SynIn", 43, 1 },
8850 	{ "AckIn", 42, 1 },
8851 	{ "FinIn", 41, 1 },
8852 	{ "RstIn", 40, 1 },
8853 	{ "DataIn", 39, 1 },
8854 	{ "DataInVld", 38, 1 },
8855 	{ "PadIn", 37, 1 },
8856 	{ "RxBufEmpty", 36, 1 },
8857 	{ "RxDdp", 35, 1 },
8858 	{ "RxFbCongestion", 34, 1 },
8859 	{ "TxFbCongestion", 33, 1 },
8860 	{ "TxPktSumSrdy", 32, 1 },
8861 	{ "RcfUlpType", 28, 4 },
8862 	{ "Eread", 27, 1 },
8863 	{ "Ebypass", 26, 1 },
8864 	{ "Esave", 25, 1 },
8865 	{ "Static0", 24, 1 },
8866 	{ "Cread", 23, 1 },
8867 	{ "Cbypass", 22, 1 },
8868 	{ "Csave", 21, 1 },
8869 	{ "CPktOut", 20, 1 },
8870 	{ "RxPagePoolFull", 18, 2 },
8871 	{ "RxLpbkPkt", 17, 1 },
8872 	{ "TxLpbkPkt", 16, 1 },
8873 	{ "RxVfValid", 15, 1 },
8874 	{ "SynLearned", 14, 1 },
8875 	{ "SetDelEntry", 13, 1 },
8876 	{ "SetInvEntry", 12, 1 },
8877 	{ "CpcmdDvld", 11, 1 },
8878 	{ "CpcmdSave", 10, 1 },
8879 	{ "RxPstructsFull", 8, 2 },
8880 	{ "EpcmdDvld", 7, 1 },
8881 	{ "EpcmdFlush", 6, 1 },
8882 	{ "EpcmdTrimPrefix", 5, 1 },
8883 	{ "EpcmdTrimPostfix", 4, 1 },
8884 	{ "ERssIp4Pkt", 3, 1 },
8885 	{ "ERssIp6Pkt", 2, 1 },
8886 	{ "ERssTcpUdpPkt", 1, 1 },
8887 	{ "ERssFceFipPkt", 0, 1 },
8888 	{ NULL }
8889 };
8890 
8891 static void
8892 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
8893 {
8894 
8895 	field_desc_show(sb, *p, tp_la0);
8896 }
8897 
8898 static void
8899 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
8900 {
8901 
8902 	if (idx)
8903 		sbuf_printf(sb, "\n");
8904 	field_desc_show(sb, p[0], tp_la0);
8905 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
8906 		field_desc_show(sb, p[1], tp_la0);
8907 }
8908 
8909 static void
8910 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
8911 {
8912 
8913 	if (idx)
8914 		sbuf_printf(sb, "\n");
8915 	field_desc_show(sb, p[0], tp_la0);
8916 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
8917 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
8918 }
8919 
8920 static int
8921 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
8922 {
8923 	struct adapter *sc = arg1;
8924 	struct sbuf *sb;
8925 	uint64_t *buf, *p;
8926 	int rc;
8927 	u_int i, inc;
8928 	void (*show_func)(struct sbuf *, uint64_t *, int);
8929 
8930 	rc = sysctl_wire_old_buffer(req, 0);
8931 	if (rc != 0)
8932 		return (rc);
8933 
8934 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8935 	if (sb == NULL)
8936 		return (ENOMEM);
8937 
8938 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
8939 
8940 	t4_tp_read_la(sc, buf, NULL);
8941 	p = buf;
8942 
8943 	switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
8944 	case 2:
8945 		inc = 2;
8946 		show_func = tp_la_show2;
8947 		break;
8948 	case 3:
8949 		inc = 2;
8950 		show_func = tp_la_show3;
8951 		break;
8952 	default:
8953 		inc = 1;
8954 		show_func = tp_la_show;
8955 	}
8956 
8957 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
8958 		(*show_func)(sb, p, i);
8959 
8960 	rc = sbuf_finish(sb);
8961 	sbuf_delete(sb);
8962 	free(buf, M_CXGBE);
8963 	return (rc);
8964 }
8965 
8966 static int
8967 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
8968 {
8969 	struct adapter *sc = arg1;
8970 	struct sbuf *sb;
8971 	int rc;
8972 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
8973 
8974 	rc = sysctl_wire_old_buffer(req, 0);
8975 	if (rc != 0)
8976 		return (rc);
8977 
8978 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8979 	if (sb == NULL)
8980 		return (ENOMEM);
8981 
8982 	t4_get_chan_txrate(sc, nrate, orate);
8983 
8984 	if (sc->chip_params->nchan > 2) {
8985 		sbuf_printf(sb, "              channel 0   channel 1"
8986 		    "   channel 2   channel 3\n");
8987 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
8988 		    nrate[0], nrate[1], nrate[2], nrate[3]);
8989 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
8990 		    orate[0], orate[1], orate[2], orate[3]);
8991 	} else {
8992 		sbuf_printf(sb, "              channel 0   channel 1\n");
8993 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
8994 		    nrate[0], nrate[1]);
8995 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
8996 		    orate[0], orate[1]);
8997 	}
8998 
8999 	rc = sbuf_finish(sb);
9000 	sbuf_delete(sb);
9001 
9002 	return (rc);
9003 }
9004 
9005 static int
9006 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
9007 {
9008 	struct adapter *sc = arg1;
9009 	struct sbuf *sb;
9010 	uint32_t *buf, *p;
9011 	int rc, i;
9012 
9013 	rc = sysctl_wire_old_buffer(req, 0);
9014 	if (rc != 0)
9015 		return (rc);
9016 
9017 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9018 	if (sb == NULL)
9019 		return (ENOMEM);
9020 
9021 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
9022 	    M_ZERO | M_WAITOK);
9023 
9024 	t4_ulprx_read_la(sc, buf);
9025 	p = buf;
9026 
9027 	sbuf_printf(sb, "      Pcmd        Type   Message"
9028 	    "                Data");
9029 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
9030 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
9031 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
9032 	}
9033 
9034 	rc = sbuf_finish(sb);
9035 	sbuf_delete(sb);
9036 	free(buf, M_CXGBE);
9037 	return (rc);
9038 }
9039 
9040 static int
9041 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
9042 {
9043 	struct adapter *sc = arg1;
9044 	struct sbuf *sb;
9045 	int rc, v;
9046 
9047 	MPASS(chip_id(sc) >= CHELSIO_T5);
9048 
9049 	rc = sysctl_wire_old_buffer(req, 0);
9050 	if (rc != 0)
9051 		return (rc);
9052 
9053 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9054 	if (sb == NULL)
9055 		return (ENOMEM);
9056 
9057 	v = t4_read_reg(sc, A_SGE_STAT_CFG);
9058 	if (G_STATSOURCE_T5(v) == 7) {
9059 		int mode;
9060 
9061 		mode = is_t5(sc) ? G_STATMODE(v) : G_T6_STATMODE(v);
9062 		if (mode == 0) {
9063 			sbuf_printf(sb, "total %d, incomplete %d",
9064 			    t4_read_reg(sc, A_SGE_STAT_TOTAL),
9065 			    t4_read_reg(sc, A_SGE_STAT_MATCH));
9066 		} else if (mode == 1) {
9067 			sbuf_printf(sb, "total %d, data overflow %d",
9068 			    t4_read_reg(sc, A_SGE_STAT_TOTAL),
9069 			    t4_read_reg(sc, A_SGE_STAT_MATCH));
9070 		} else {
9071 			sbuf_printf(sb, "unknown mode %d", mode);
9072 		}
9073 	}
9074 	rc = sbuf_finish(sb);
9075 	sbuf_delete(sb);
9076 
9077 	return (rc);
9078 }
9079 
9080 static int
9081 sysctl_cpus(SYSCTL_HANDLER_ARGS)
9082 {
9083 	struct adapter *sc = arg1;
9084 	enum cpu_sets op = arg2;
9085 	cpuset_t cpuset;
9086 	struct sbuf *sb;
9087 	int i, rc;
9088 
9089 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
9090 
9091 	CPU_ZERO(&cpuset);
9092 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
9093 	if (rc != 0)
9094 		return (rc);
9095 
9096 	rc = sysctl_wire_old_buffer(req, 0);
9097 	if (rc != 0)
9098 		return (rc);
9099 
9100 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9101 	if (sb == NULL)
9102 		return (ENOMEM);
9103 
9104 	CPU_FOREACH(i)
9105 		sbuf_printf(sb, "%d ", i);
9106 	rc = sbuf_finish(sb);
9107 	sbuf_delete(sb);
9108 
9109 	return (rc);
9110 }
9111 
9112 #ifdef TCP_OFFLOAD
9113 static int
9114 sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS)
9115 {
9116 	struct adapter *sc = arg1;
9117 	int *old_ports, *new_ports;
9118 	int i, new_count, rc;
9119 
9120 	if (req->newptr == NULL && req->oldptr == NULL)
9121 		return (SYSCTL_OUT(req, NULL, imax(sc->tt.num_tls_rx_ports, 1) *
9122 		    sizeof(sc->tt.tls_rx_ports[0])));
9123 
9124 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tlsrx");
9125 	if (rc)
9126 		return (rc);
9127 
9128 	if (sc->tt.num_tls_rx_ports == 0) {
9129 		i = -1;
9130 		rc = SYSCTL_OUT(req, &i, sizeof(i));
9131 	} else
9132 		rc = SYSCTL_OUT(req, sc->tt.tls_rx_ports,
9133 		    sc->tt.num_tls_rx_ports * sizeof(sc->tt.tls_rx_ports[0]));
9134 	if (rc == 0 && req->newptr != NULL) {
9135 		new_count = req->newlen / sizeof(new_ports[0]);
9136 		new_ports = malloc(new_count * sizeof(new_ports[0]), M_CXGBE,
9137 		    M_WAITOK);
9138 		rc = SYSCTL_IN(req, new_ports, new_count *
9139 		    sizeof(new_ports[0]));
9140 		if (rc)
9141 			goto err;
9142 
9143 		/* Allow setting to a single '-1' to clear the list. */
9144 		if (new_count == 1 && new_ports[0] == -1) {
9145 			ADAPTER_LOCK(sc);
9146 			old_ports = sc->tt.tls_rx_ports;
9147 			sc->tt.tls_rx_ports = NULL;
9148 			sc->tt.num_tls_rx_ports = 0;
9149 			ADAPTER_UNLOCK(sc);
9150 			free(old_ports, M_CXGBE);
9151 		} else {
9152 			for (i = 0; i < new_count; i++) {
9153 				if (new_ports[i] < 1 ||
9154 				    new_ports[i] > IPPORT_MAX) {
9155 					rc = EINVAL;
9156 					goto err;
9157 				}
9158 			}
9159 
9160 			ADAPTER_LOCK(sc);
9161 			old_ports = sc->tt.tls_rx_ports;
9162 			sc->tt.tls_rx_ports = new_ports;
9163 			sc->tt.num_tls_rx_ports = new_count;
9164 			ADAPTER_UNLOCK(sc);
9165 			free(old_ports, M_CXGBE);
9166 			new_ports = NULL;
9167 		}
9168 	err:
9169 		free(new_ports, M_CXGBE);
9170 	}
9171 	end_synchronized_op(sc, 0);
9172 	return (rc);
9173 }
9174 
9175 static void
9176 unit_conv(char *buf, size_t len, u_int val, u_int factor)
9177 {
9178 	u_int rem = val % factor;
9179 
9180 	if (rem == 0)
9181 		snprintf(buf, len, "%u", val / factor);
9182 	else {
9183 		while (rem % 10 == 0)
9184 			rem /= 10;
9185 		snprintf(buf, len, "%u.%u", val / factor, rem);
9186 	}
9187 }
9188 
9189 static int
9190 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
9191 {
9192 	struct adapter *sc = arg1;
9193 	char buf[16];
9194 	u_int res, re;
9195 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
9196 
9197 	res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
9198 	switch (arg2) {
9199 	case 0:
9200 		/* timer_tick */
9201 		re = G_TIMERRESOLUTION(res);
9202 		break;
9203 	case 1:
9204 		/* TCP timestamp tick */
9205 		re = G_TIMESTAMPRESOLUTION(res);
9206 		break;
9207 	case 2:
9208 		/* DACK tick */
9209 		re = G_DELAYEDACKRESOLUTION(res);
9210 		break;
9211 	default:
9212 		return (EDOOFUS);
9213 	}
9214 
9215 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
9216 
9217 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
9218 }
9219 
9220 static int
9221 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
9222 {
9223 	struct adapter *sc = arg1;
9224 	u_int res, dack_re, v;
9225 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
9226 
9227 	res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
9228 	dack_re = G_DELAYEDACKRESOLUTION(res);
9229 	v = ((cclk_ps << dack_re) / 1000000) * t4_read_reg(sc, A_TP_DACK_TIMER);
9230 
9231 	return (sysctl_handle_int(oidp, &v, 0, req));
9232 }
9233 
9234 static int
9235 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
9236 {
9237 	struct adapter *sc = arg1;
9238 	int reg = arg2;
9239 	u_int tre;
9240 	u_long tp_tick_us, v;
9241 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
9242 
9243 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
9244 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
9245 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
9246 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
9247 
9248 	tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
9249 	tp_tick_us = (cclk_ps << tre) / 1000000;
9250 
9251 	if (reg == A_TP_INIT_SRTT)
9252 		v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
9253 	else
9254 		v = tp_tick_us * t4_read_reg(sc, reg);
9255 
9256 	return (sysctl_handle_long(oidp, &v, 0, req));
9257 }
9258 
9259 /*
9260  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
9261  * passed to this function.
9262  */
9263 static int
9264 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
9265 {
9266 	struct adapter *sc = arg1;
9267 	int idx = arg2;
9268 	u_int v;
9269 
9270 	MPASS(idx >= 0 && idx <= 24);
9271 
9272 	v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
9273 
9274 	return (sysctl_handle_int(oidp, &v, 0, req));
9275 }
9276 
9277 static int
9278 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
9279 {
9280 	struct adapter *sc = arg1;
9281 	int idx = arg2;
9282 	u_int shift, v, r;
9283 
9284 	MPASS(idx >= 0 && idx < 16);
9285 
9286 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
9287 	shift = (idx & 3) << 3;
9288 	v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
9289 
9290 	return (sysctl_handle_int(oidp, &v, 0, req));
9291 }
9292 
9293 static int
9294 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
9295 {
9296 	struct vi_info *vi = arg1;
9297 	struct adapter *sc = vi->pi->adapter;
9298 	int idx, rc, i;
9299 	struct sge_ofld_rxq *ofld_rxq;
9300 	uint8_t v;
9301 
9302 	idx = vi->ofld_tmr_idx;
9303 
9304 	rc = sysctl_handle_int(oidp, &idx, 0, req);
9305 	if (rc != 0 || req->newptr == NULL)
9306 		return (rc);
9307 
9308 	if (idx < 0 || idx >= SGE_NTIMERS)
9309 		return (EINVAL);
9310 
9311 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
9312 	    "t4otmr");
9313 	if (rc)
9314 		return (rc);
9315 
9316 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
9317 	for_each_ofld_rxq(vi, i, ofld_rxq) {
9318 #ifdef atomic_store_rel_8
9319 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
9320 #else
9321 		ofld_rxq->iq.intr_params = v;
9322 #endif
9323 	}
9324 	vi->ofld_tmr_idx = idx;
9325 
9326 	end_synchronized_op(sc, LOCK_HELD);
9327 	return (0);
9328 }
9329 
9330 static int
9331 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
9332 {
9333 	struct vi_info *vi = arg1;
9334 	struct adapter *sc = vi->pi->adapter;
9335 	int idx, rc;
9336 
9337 	idx = vi->ofld_pktc_idx;
9338 
9339 	rc = sysctl_handle_int(oidp, &idx, 0, req);
9340 	if (rc != 0 || req->newptr == NULL)
9341 		return (rc);
9342 
9343 	if (idx < -1 || idx >= SGE_NCOUNTERS)
9344 		return (EINVAL);
9345 
9346 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
9347 	    "t4opktc");
9348 	if (rc)
9349 		return (rc);
9350 
9351 	if (vi->flags & VI_INIT_DONE)
9352 		rc = EBUSY; /* cannot be changed once the queues are created */
9353 	else
9354 		vi->ofld_pktc_idx = idx;
9355 
9356 	end_synchronized_op(sc, LOCK_HELD);
9357 	return (rc);
9358 }
9359 #endif
9360 
9361 static int
9362 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
9363 {
9364 	int rc;
9365 
9366 	if (cntxt->cid > M_CTXTQID)
9367 		return (EINVAL);
9368 
9369 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
9370 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
9371 		return (EINVAL);
9372 
9373 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
9374 	if (rc)
9375 		return (rc);
9376 
9377 	if (sc->flags & FW_OK) {
9378 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
9379 		    &cntxt->data[0]);
9380 		if (rc == 0)
9381 			goto done;
9382 	}
9383 
9384 	/*
9385 	 * Read via firmware failed or wasn't even attempted.  Read directly via
9386 	 * the backdoor.
9387 	 */
9388 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
9389 done:
9390 	end_synchronized_op(sc, 0);
9391 	return (rc);
9392 }
9393 
9394 static int
9395 load_fw(struct adapter *sc, struct t4_data *fw)
9396 {
9397 	int rc;
9398 	uint8_t *fw_data;
9399 
9400 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
9401 	if (rc)
9402 		return (rc);
9403 
9404 	/*
9405 	 * The firmware, with the sole exception of the memory parity error
9406 	 * handler, runs from memory and not flash.  It is almost always safe to
9407 	 * install a new firmware on a running system.  Just set bit 1 in
9408 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
9409 	 */
9410 	if (sc->flags & FULL_INIT_DONE &&
9411 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
9412 		rc = EBUSY;
9413 		goto done;
9414 	}
9415 
9416 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
9417 	if (fw_data == NULL) {
9418 		rc = ENOMEM;
9419 		goto done;
9420 	}
9421 
9422 	rc = copyin(fw->data, fw_data, fw->len);
9423 	if (rc == 0)
9424 		rc = -t4_load_fw(sc, fw_data, fw->len);
9425 
9426 	free(fw_data, M_CXGBE);
9427 done:
9428 	end_synchronized_op(sc, 0);
9429 	return (rc);
9430 }
9431 
9432 static int
9433 load_cfg(struct adapter *sc, struct t4_data *cfg)
9434 {
9435 	int rc;
9436 	uint8_t *cfg_data = NULL;
9437 
9438 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
9439 	if (rc)
9440 		return (rc);
9441 
9442 	if (cfg->len == 0) {
9443 		/* clear */
9444 		rc = -t4_load_cfg(sc, NULL, 0);
9445 		goto done;
9446 	}
9447 
9448 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
9449 	if (cfg_data == NULL) {
9450 		rc = ENOMEM;
9451 		goto done;
9452 	}
9453 
9454 	rc = copyin(cfg->data, cfg_data, cfg->len);
9455 	if (rc == 0)
9456 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
9457 
9458 	free(cfg_data, M_CXGBE);
9459 done:
9460 	end_synchronized_op(sc, 0);
9461 	return (rc);
9462 }
9463 
9464 static int
9465 load_boot(struct adapter *sc, struct t4_bootrom *br)
9466 {
9467 	int rc;
9468 	uint8_t *br_data = NULL;
9469 	u_int offset;
9470 
9471 	if (br->len > 1024 * 1024)
9472 		return (EFBIG);
9473 
9474 	if (br->pf_offset == 0) {
9475 		/* pfidx */
9476 		if (br->pfidx_addr > 7)
9477 			return (EINVAL);
9478 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
9479 		    A_PCIE_PF_EXPROM_OFST)));
9480 	} else if (br->pf_offset == 1) {
9481 		/* offset */
9482 		offset = G_OFFSET(br->pfidx_addr);
9483 	} else {
9484 		return (EINVAL);
9485 	}
9486 
9487 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
9488 	if (rc)
9489 		return (rc);
9490 
9491 	if (br->len == 0) {
9492 		/* clear */
9493 		rc = -t4_load_boot(sc, NULL, offset, 0);
9494 		goto done;
9495 	}
9496 
9497 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
9498 	if (br_data == NULL) {
9499 		rc = ENOMEM;
9500 		goto done;
9501 	}
9502 
9503 	rc = copyin(br->data, br_data, br->len);
9504 	if (rc == 0)
9505 		rc = -t4_load_boot(sc, br_data, offset, br->len);
9506 
9507 	free(br_data, M_CXGBE);
9508 done:
9509 	end_synchronized_op(sc, 0);
9510 	return (rc);
9511 }
9512 
9513 static int
9514 load_bootcfg(struct adapter *sc, struct t4_data *bc)
9515 {
9516 	int rc;
9517 	uint8_t *bc_data = NULL;
9518 
9519 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
9520 	if (rc)
9521 		return (rc);
9522 
9523 	if (bc->len == 0) {
9524 		/* clear */
9525 		rc = -t4_load_bootcfg(sc, NULL, 0);
9526 		goto done;
9527 	}
9528 
9529 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
9530 	if (bc_data == NULL) {
9531 		rc = ENOMEM;
9532 		goto done;
9533 	}
9534 
9535 	rc = copyin(bc->data, bc_data, bc->len);
9536 	if (rc == 0)
9537 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
9538 
9539 	free(bc_data, M_CXGBE);
9540 done:
9541 	end_synchronized_op(sc, 0);
9542 	return (rc);
9543 }
9544 
9545 static int
9546 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
9547 {
9548 	int rc;
9549 	struct cudbg_init *cudbg;
9550 	void *handle, *buf;
9551 
9552 	/* buf is large, don't block if no memory is available */
9553 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
9554 	if (buf == NULL)
9555 		return (ENOMEM);
9556 
9557 	handle = cudbg_alloc_handle();
9558 	if (handle == NULL) {
9559 		rc = ENOMEM;
9560 		goto done;
9561 	}
9562 
9563 	cudbg = cudbg_get_init(handle);
9564 	cudbg->adap = sc;
9565 	cudbg->print = (cudbg_print_cb)printf;
9566 
9567 #ifndef notyet
9568 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
9569 	    __func__, dump->wr_flash, dump->len, dump->data);
9570 #endif
9571 
9572 	if (dump->wr_flash)
9573 		cudbg->use_flash = 1;
9574 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
9575 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
9576 
9577 	rc = cudbg_collect(handle, buf, &dump->len);
9578 	if (rc != 0)
9579 		goto done;
9580 
9581 	rc = copyout(buf, dump->data, dump->len);
9582 done:
9583 	cudbg_free_handle(handle);
9584 	free(buf, M_CXGBE);
9585 	return (rc);
9586 }
9587 
9588 static void
9589 free_offload_policy(struct t4_offload_policy *op)
9590 {
9591 	struct offload_rule *r;
9592 	int i;
9593 
9594 	if (op == NULL)
9595 		return;
9596 
9597 	r = &op->rule[0];
9598 	for (i = 0; i < op->nrules; i++, r++) {
9599 		free(r->bpf_prog.bf_insns, M_CXGBE);
9600 	}
9601 	free(op->rule, M_CXGBE);
9602 	free(op, M_CXGBE);
9603 }
9604 
9605 static int
9606 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
9607 {
9608 	int i, rc, len;
9609 	struct t4_offload_policy *op, *old;
9610 	struct bpf_program *bf;
9611 	const struct offload_settings *s;
9612 	struct offload_rule *r;
9613 	void *u;
9614 
9615 	if (!is_offload(sc))
9616 		return (ENODEV);
9617 
9618 	if (uop->nrules == 0) {
9619 		/* Delete installed policies. */
9620 		op = NULL;
9621 		goto set_policy;
9622 	} if (uop->nrules > 256) { /* arbitrary */
9623 		return (E2BIG);
9624 	}
9625 
9626 	/* Copy userspace offload policy to kernel */
9627 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
9628 	op->nrules = uop->nrules;
9629 	len = op->nrules * sizeof(struct offload_rule);
9630 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
9631 	rc = copyin(uop->rule, op->rule, len);
9632 	if (rc) {
9633 		free(op->rule, M_CXGBE);
9634 		free(op, M_CXGBE);
9635 		return (rc);
9636 	}
9637 
9638 	r = &op->rule[0];
9639 	for (i = 0; i < op->nrules; i++, r++) {
9640 
9641 		/* Validate open_type */
9642 		if (r->open_type != OPEN_TYPE_LISTEN &&
9643 		    r->open_type != OPEN_TYPE_ACTIVE &&
9644 		    r->open_type != OPEN_TYPE_PASSIVE &&
9645 		    r->open_type != OPEN_TYPE_DONTCARE) {
9646 error:
9647 			/*
9648 			 * Rules 0 to i have malloc'd filters that need to be
9649 			 * freed.  Rules i+1 to nrules have userspace pointers
9650 			 * and should be left alone.
9651 			 */
9652 			op->nrules = i;
9653 			free_offload_policy(op);
9654 			return (rc);
9655 		}
9656 
9657 		/* Validate settings */
9658 		s = &r->settings;
9659 		if ((s->offload != 0 && s->offload != 1) ||
9660 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
9661 		    s->sched_class < -1 ||
9662 		    s->sched_class >= sc->chip_params->nsched_cls) {
9663 			rc = EINVAL;
9664 			goto error;
9665 		}
9666 
9667 		bf = &r->bpf_prog;
9668 		u = bf->bf_insns;	/* userspace ptr */
9669 		bf->bf_insns = NULL;
9670 		if (bf->bf_len == 0) {
9671 			/* legal, matches everything */
9672 			continue;
9673 		}
9674 		len = bf->bf_len * sizeof(*bf->bf_insns);
9675 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
9676 		rc = copyin(u, bf->bf_insns, len);
9677 		if (rc != 0)
9678 			goto error;
9679 
9680 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
9681 			rc = EINVAL;
9682 			goto error;
9683 		}
9684 	}
9685 set_policy:
9686 	rw_wlock(&sc->policy_lock);
9687 	old = sc->policy;
9688 	sc->policy = op;
9689 	rw_wunlock(&sc->policy_lock);
9690 	free_offload_policy(old);
9691 
9692 	return (0);
9693 }
9694 
9695 #define MAX_READ_BUF_SIZE (128 * 1024)
9696 static int
9697 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
9698 {
9699 	uint32_t addr, remaining, n;
9700 	uint32_t *buf;
9701 	int rc;
9702 	uint8_t *dst;
9703 
9704 	rc = validate_mem_range(sc, mr->addr, mr->len);
9705 	if (rc != 0)
9706 		return (rc);
9707 
9708 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
9709 	addr = mr->addr;
9710 	remaining = mr->len;
9711 	dst = (void *)mr->data;
9712 
9713 	while (remaining) {
9714 		n = min(remaining, MAX_READ_BUF_SIZE);
9715 		read_via_memwin(sc, 2, addr, buf, n);
9716 
9717 		rc = copyout(buf, dst, n);
9718 		if (rc != 0)
9719 			break;
9720 
9721 		dst += n;
9722 		remaining -= n;
9723 		addr += n;
9724 	}
9725 
9726 	free(buf, M_CXGBE);
9727 	return (rc);
9728 }
9729 #undef MAX_READ_BUF_SIZE
9730 
9731 static int
9732 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
9733 {
9734 	int rc;
9735 
9736 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
9737 		return (EINVAL);
9738 
9739 	if (i2cd->len > sizeof(i2cd->data))
9740 		return (EFBIG);
9741 
9742 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
9743 	if (rc)
9744 		return (rc);
9745 	rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
9746 	    i2cd->offset, i2cd->len, &i2cd->data[0]);
9747 	end_synchronized_op(sc, 0);
9748 
9749 	return (rc);
9750 }
9751 
9752 int
9753 t4_os_find_pci_capability(struct adapter *sc, int cap)
9754 {
9755 	int i;
9756 
9757 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
9758 }
9759 
9760 int
9761 t4_os_pci_save_state(struct adapter *sc)
9762 {
9763 	device_t dev;
9764 	struct pci_devinfo *dinfo;
9765 
9766 	dev = sc->dev;
9767 	dinfo = device_get_ivars(dev);
9768 
9769 	pci_cfg_save(dev, dinfo, 0);
9770 	return (0);
9771 }
9772 
9773 int
9774 t4_os_pci_restore_state(struct adapter *sc)
9775 {
9776 	device_t dev;
9777 	struct pci_devinfo *dinfo;
9778 
9779 	dev = sc->dev;
9780 	dinfo = device_get_ivars(dev);
9781 
9782 	pci_cfg_restore(dev, dinfo);
9783 	return (0);
9784 }
9785 
9786 void
9787 t4_os_portmod_changed(struct port_info *pi)
9788 {
9789 	struct adapter *sc = pi->adapter;
9790 	struct vi_info *vi;
9791 	struct ifnet *ifp;
9792 	static const char *mod_str[] = {
9793 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
9794 	};
9795 
9796 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
9797 	    ("%s: port_type %u", __func__, pi->port_type));
9798 
9799 	vi = &pi->vi[0];
9800 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
9801 		PORT_LOCK(pi);
9802 		build_medialist(pi);
9803 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
9804 			fixup_link_config(pi);
9805 			apply_link_config(pi);
9806 		}
9807 		PORT_UNLOCK(pi);
9808 		end_synchronized_op(sc, LOCK_HELD);
9809 	}
9810 
9811 	ifp = vi->ifp;
9812 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
9813 		if_printf(ifp, "transceiver unplugged.\n");
9814 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
9815 		if_printf(ifp, "unknown transceiver inserted.\n");
9816 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
9817 		if_printf(ifp, "unsupported transceiver inserted.\n");
9818 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
9819 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
9820 		    port_top_speed(pi), mod_str[pi->mod_type]);
9821 	} else {
9822 		if_printf(ifp, "transceiver (type %d) inserted.\n",
9823 		    pi->mod_type);
9824 	}
9825 }
9826 
9827 void
9828 t4_os_link_changed(struct port_info *pi)
9829 {
9830 	struct vi_info *vi;
9831 	struct ifnet *ifp;
9832 	struct link_config *lc;
9833 	int v;
9834 
9835 	PORT_LOCK_ASSERT_OWNED(pi);
9836 
9837 	for_each_vi(pi, v, vi) {
9838 		ifp = vi->ifp;
9839 		if (ifp == NULL)
9840 			continue;
9841 
9842 		lc = &pi->link_cfg;
9843 		if (lc->link_ok) {
9844 			ifp->if_baudrate = IF_Mbps(lc->speed);
9845 			if_link_state_change(ifp, LINK_STATE_UP);
9846 		} else {
9847 			if_link_state_change(ifp, LINK_STATE_DOWN);
9848 		}
9849 	}
9850 }
9851 
9852 void
9853 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
9854 {
9855 	struct adapter *sc;
9856 
9857 	sx_slock(&t4_list_lock);
9858 	SLIST_FOREACH(sc, &t4_list, link) {
9859 		/*
9860 		 * func should not make any assumptions about what state sc is
9861 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
9862 		 */
9863 		func(sc, arg);
9864 	}
9865 	sx_sunlock(&t4_list_lock);
9866 }
9867 
9868 static int
9869 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
9870     struct thread *td)
9871 {
9872 	int rc;
9873 	struct adapter *sc = dev->si_drv1;
9874 
9875 	rc = priv_check(td, PRIV_DRIVER);
9876 	if (rc != 0)
9877 		return (rc);
9878 
9879 	switch (cmd) {
9880 	case CHELSIO_T4_GETREG: {
9881 		struct t4_reg *edata = (struct t4_reg *)data;
9882 
9883 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
9884 			return (EFAULT);
9885 
9886 		if (edata->size == 4)
9887 			edata->val = t4_read_reg(sc, edata->addr);
9888 		else if (edata->size == 8)
9889 			edata->val = t4_read_reg64(sc, edata->addr);
9890 		else
9891 			return (EINVAL);
9892 
9893 		break;
9894 	}
9895 	case CHELSIO_T4_SETREG: {
9896 		struct t4_reg *edata = (struct t4_reg *)data;
9897 
9898 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
9899 			return (EFAULT);
9900 
9901 		if (edata->size == 4) {
9902 			if (edata->val & 0xffffffff00000000)
9903 				return (EINVAL);
9904 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
9905 		} else if (edata->size == 8)
9906 			t4_write_reg64(sc, edata->addr, edata->val);
9907 		else
9908 			return (EINVAL);
9909 		break;
9910 	}
9911 	case CHELSIO_T4_REGDUMP: {
9912 		struct t4_regdump *regs = (struct t4_regdump *)data;
9913 		int reglen = t4_get_regs_len(sc);
9914 		uint8_t *buf;
9915 
9916 		if (regs->len < reglen) {
9917 			regs->len = reglen; /* hint to the caller */
9918 			return (ENOBUFS);
9919 		}
9920 
9921 		regs->len = reglen;
9922 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
9923 		get_regs(sc, regs, buf);
9924 		rc = copyout(buf, regs->data, reglen);
9925 		free(buf, M_CXGBE);
9926 		break;
9927 	}
9928 	case CHELSIO_T4_GET_FILTER_MODE:
9929 		rc = get_filter_mode(sc, (uint32_t *)data);
9930 		break;
9931 	case CHELSIO_T4_SET_FILTER_MODE:
9932 		rc = set_filter_mode(sc, *(uint32_t *)data);
9933 		break;
9934 	case CHELSIO_T4_GET_FILTER:
9935 		rc = get_filter(sc, (struct t4_filter *)data);
9936 		break;
9937 	case CHELSIO_T4_SET_FILTER:
9938 		rc = set_filter(sc, (struct t4_filter *)data);
9939 		break;
9940 	case CHELSIO_T4_DEL_FILTER:
9941 		rc = del_filter(sc, (struct t4_filter *)data);
9942 		break;
9943 	case CHELSIO_T4_GET_SGE_CONTEXT:
9944 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
9945 		break;
9946 	case CHELSIO_T4_LOAD_FW:
9947 		rc = load_fw(sc, (struct t4_data *)data);
9948 		break;
9949 	case CHELSIO_T4_GET_MEM:
9950 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
9951 		break;
9952 	case CHELSIO_T4_GET_I2C:
9953 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
9954 		break;
9955 	case CHELSIO_T4_CLEAR_STATS: {
9956 		int i, v, bg_map;
9957 		u_int port_id = *(uint32_t *)data;
9958 		struct port_info *pi;
9959 		struct vi_info *vi;
9960 
9961 		if (port_id >= sc->params.nports)
9962 			return (EINVAL);
9963 		pi = sc->port[port_id];
9964 		if (pi == NULL)
9965 			return (EIO);
9966 
9967 		/* MAC stats */
9968 		t4_clr_port_stats(sc, pi->tx_chan);
9969 		pi->tx_parse_error = 0;
9970 		pi->tnl_cong_drops = 0;
9971 		mtx_lock(&sc->reg_lock);
9972 		for_each_vi(pi, v, vi) {
9973 			if (vi->flags & VI_INIT_DONE)
9974 				t4_clr_vi_stats(sc, vi->viid);
9975 		}
9976 		bg_map = pi->mps_bg_map;
9977 		v = 0;	/* reuse */
9978 		while (bg_map) {
9979 			i = ffs(bg_map) - 1;
9980 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
9981 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
9982 			bg_map &= ~(1 << i);
9983 		}
9984 		mtx_unlock(&sc->reg_lock);
9985 
9986 		/*
9987 		 * Since this command accepts a port, clear stats for
9988 		 * all VIs on this port.
9989 		 */
9990 		for_each_vi(pi, v, vi) {
9991 			if (vi->flags & VI_INIT_DONE) {
9992 				struct sge_rxq *rxq;
9993 				struct sge_txq *txq;
9994 				struct sge_wrq *wrq;
9995 
9996 				for_each_rxq(vi, i, rxq) {
9997 #if defined(INET) || defined(INET6)
9998 					rxq->lro.lro_queued = 0;
9999 					rxq->lro.lro_flushed = 0;
10000 #endif
10001 					rxq->rxcsum = 0;
10002 					rxq->vlan_extraction = 0;
10003 				}
10004 
10005 				for_each_txq(vi, i, txq) {
10006 					txq->txcsum = 0;
10007 					txq->tso_wrs = 0;
10008 					txq->vlan_insertion = 0;
10009 					txq->imm_wrs = 0;
10010 					txq->sgl_wrs = 0;
10011 					txq->txpkt_wrs = 0;
10012 					txq->txpkts0_wrs = 0;
10013 					txq->txpkts1_wrs = 0;
10014 					txq->txpkts0_pkts = 0;
10015 					txq->txpkts1_pkts = 0;
10016 					txq->raw_wrs = 0;
10017 					mp_ring_reset_stats(txq->r);
10018 				}
10019 
10020 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
10021 				/* nothing to clear for each ofld_rxq */
10022 
10023 				for_each_ofld_txq(vi, i, wrq) {
10024 					wrq->tx_wrs_direct = 0;
10025 					wrq->tx_wrs_copied = 0;
10026 				}
10027 #endif
10028 
10029 				if (IS_MAIN_VI(vi)) {
10030 					wrq = &sc->sge.ctrlq[pi->port_id];
10031 					wrq->tx_wrs_direct = 0;
10032 					wrq->tx_wrs_copied = 0;
10033 				}
10034 			}
10035 		}
10036 		break;
10037 	}
10038 	case CHELSIO_T4_SCHED_CLASS:
10039 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
10040 		break;
10041 	case CHELSIO_T4_SCHED_QUEUE:
10042 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
10043 		break;
10044 	case CHELSIO_T4_GET_TRACER:
10045 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
10046 		break;
10047 	case CHELSIO_T4_SET_TRACER:
10048 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
10049 		break;
10050 	case CHELSIO_T4_LOAD_CFG:
10051 		rc = load_cfg(sc, (struct t4_data *)data);
10052 		break;
10053 	case CHELSIO_T4_LOAD_BOOT:
10054 		rc = load_boot(sc, (struct t4_bootrom *)data);
10055 		break;
10056 	case CHELSIO_T4_LOAD_BOOTCFG:
10057 		rc = load_bootcfg(sc, (struct t4_data *)data);
10058 		break;
10059 	case CHELSIO_T4_CUDBG_DUMP:
10060 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
10061 		break;
10062 	case CHELSIO_T4_SET_OFLD_POLICY:
10063 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
10064 		break;
10065 	default:
10066 		rc = ENOTTY;
10067 	}
10068 
10069 	return (rc);
10070 }
10071 
10072 void
10073 t4_db_full(struct adapter *sc)
10074 {
10075 
10076 	CXGBE_UNIMPLEMENTED(__func__);
10077 }
10078 
10079 void
10080 t4_db_dropped(struct adapter *sc)
10081 {
10082 
10083 	CXGBE_UNIMPLEMENTED(__func__);
10084 }
10085 
10086 #ifdef TCP_OFFLOAD
10087 static int
10088 toe_capability(struct vi_info *vi, int enable)
10089 {
10090 	int rc;
10091 	struct port_info *pi = vi->pi;
10092 	struct adapter *sc = pi->adapter;
10093 
10094 	ASSERT_SYNCHRONIZED_OP(sc);
10095 
10096 	if (!is_offload(sc))
10097 		return (ENODEV);
10098 
10099 	if (enable) {
10100 		if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
10101 			/* TOE is already enabled. */
10102 			return (0);
10103 		}
10104 
10105 		/*
10106 		 * We need the port's queues around so that we're able to send
10107 		 * and receive CPLs to/from the TOE even if the ifnet for this
10108 		 * port has never been UP'd administratively.
10109 		 */
10110 		if (!(vi->flags & VI_INIT_DONE)) {
10111 			rc = vi_full_init(vi);
10112 			if (rc)
10113 				return (rc);
10114 		}
10115 		if (!(pi->vi[0].flags & VI_INIT_DONE)) {
10116 			rc = vi_full_init(&pi->vi[0]);
10117 			if (rc)
10118 				return (rc);
10119 		}
10120 
10121 		if (isset(&sc->offload_map, pi->port_id)) {
10122 			/* TOE is enabled on another VI of this port. */
10123 			pi->uld_vis++;
10124 			return (0);
10125 		}
10126 
10127 		if (!uld_active(sc, ULD_TOM)) {
10128 			rc = t4_activate_uld(sc, ULD_TOM);
10129 			if (rc == EAGAIN) {
10130 				log(LOG_WARNING,
10131 				    "You must kldload t4_tom.ko before trying "
10132 				    "to enable TOE on a cxgbe interface.\n");
10133 			}
10134 			if (rc != 0)
10135 				return (rc);
10136 			KASSERT(sc->tom_softc != NULL,
10137 			    ("%s: TOM activated but softc NULL", __func__));
10138 			KASSERT(uld_active(sc, ULD_TOM),
10139 			    ("%s: TOM activated but flag not set", __func__));
10140 		}
10141 
10142 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
10143 		if (!uld_active(sc, ULD_IWARP))
10144 			(void) t4_activate_uld(sc, ULD_IWARP);
10145 		if (!uld_active(sc, ULD_ISCSI))
10146 			(void) t4_activate_uld(sc, ULD_ISCSI);
10147 
10148 		pi->uld_vis++;
10149 		setbit(&sc->offload_map, pi->port_id);
10150 	} else {
10151 		pi->uld_vis--;
10152 
10153 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
10154 			return (0);
10155 
10156 		KASSERT(uld_active(sc, ULD_TOM),
10157 		    ("%s: TOM never initialized?", __func__));
10158 		clrbit(&sc->offload_map, pi->port_id);
10159 	}
10160 
10161 	return (0);
10162 }
10163 
10164 /*
10165  * Add an upper layer driver to the global list.
10166  */
10167 int
10168 t4_register_uld(struct uld_info *ui)
10169 {
10170 	int rc = 0;
10171 	struct uld_info *u;
10172 
10173 	sx_xlock(&t4_uld_list_lock);
10174 	SLIST_FOREACH(u, &t4_uld_list, link) {
10175 	    if (u->uld_id == ui->uld_id) {
10176 		    rc = EEXIST;
10177 		    goto done;
10178 	    }
10179 	}
10180 
10181 	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
10182 	ui->refcount = 0;
10183 done:
10184 	sx_xunlock(&t4_uld_list_lock);
10185 	return (rc);
10186 }
10187 
10188 int
10189 t4_unregister_uld(struct uld_info *ui)
10190 {
10191 	int rc = EINVAL;
10192 	struct uld_info *u;
10193 
10194 	sx_xlock(&t4_uld_list_lock);
10195 
10196 	SLIST_FOREACH(u, &t4_uld_list, link) {
10197 	    if (u == ui) {
10198 		    if (ui->refcount > 0) {
10199 			    rc = EBUSY;
10200 			    goto done;
10201 		    }
10202 
10203 		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
10204 		    rc = 0;
10205 		    goto done;
10206 	    }
10207 	}
10208 done:
10209 	sx_xunlock(&t4_uld_list_lock);
10210 	return (rc);
10211 }
10212 
10213 int
10214 t4_activate_uld(struct adapter *sc, int id)
10215 {
10216 	int rc;
10217 	struct uld_info *ui;
10218 
10219 	ASSERT_SYNCHRONIZED_OP(sc);
10220 
10221 	if (id < 0 || id > ULD_MAX)
10222 		return (EINVAL);
10223 	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
10224 
10225 	sx_slock(&t4_uld_list_lock);
10226 
10227 	SLIST_FOREACH(ui, &t4_uld_list, link) {
10228 		if (ui->uld_id == id) {
10229 			if (!(sc->flags & FULL_INIT_DONE)) {
10230 				rc = adapter_full_init(sc);
10231 				if (rc != 0)
10232 					break;
10233 			}
10234 
10235 			rc = ui->activate(sc);
10236 			if (rc == 0) {
10237 				setbit(&sc->active_ulds, id);
10238 				ui->refcount++;
10239 			}
10240 			break;
10241 		}
10242 	}
10243 
10244 	sx_sunlock(&t4_uld_list_lock);
10245 
10246 	return (rc);
10247 }
10248 
10249 int
10250 t4_deactivate_uld(struct adapter *sc, int id)
10251 {
10252 	int rc;
10253 	struct uld_info *ui;
10254 
10255 	ASSERT_SYNCHRONIZED_OP(sc);
10256 
10257 	if (id < 0 || id > ULD_MAX)
10258 		return (EINVAL);
10259 	rc = ENXIO;
10260 
10261 	sx_slock(&t4_uld_list_lock);
10262 
10263 	SLIST_FOREACH(ui, &t4_uld_list, link) {
10264 		if (ui->uld_id == id) {
10265 			rc = ui->deactivate(sc);
10266 			if (rc == 0) {
10267 				clrbit(&sc->active_ulds, id);
10268 				ui->refcount--;
10269 			}
10270 			break;
10271 		}
10272 	}
10273 
10274 	sx_sunlock(&t4_uld_list_lock);
10275 
10276 	return (rc);
10277 }
10278 
10279 int
10280 uld_active(struct adapter *sc, int uld_id)
10281 {
10282 
10283 	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
10284 
10285 	return (isset(&sc->active_ulds, uld_id));
10286 }
10287 #endif
10288 
10289 /*
10290  * t  = ptr to tunable.
10291  * nc = number of CPUs.
10292  * c  = compiled in default for that tunable.
10293  */
10294 static void
10295 calculate_nqueues(int *t, int nc, const int c)
10296 {
10297 	int nq;
10298 
10299 	if (*t > 0)
10300 		return;
10301 	nq = *t < 0 ? -*t : c;
10302 	*t = min(nc, nq);
10303 }
10304 
10305 /*
10306  * Come up with reasonable defaults for some of the tunables, provided they're
10307  * not set by the user (in which case we'll use the values as is).
10308  */
10309 static void
10310 tweak_tunables(void)
10311 {
10312 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
10313 
10314 	if (t4_ntxq < 1) {
10315 #ifdef RSS
10316 		t4_ntxq = rss_getnumbuckets();
10317 #else
10318 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
10319 #endif
10320 	}
10321 
10322 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
10323 
10324 	if (t4_nrxq < 1) {
10325 #ifdef RSS
10326 		t4_nrxq = rss_getnumbuckets();
10327 #else
10328 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
10329 #endif
10330 	}
10331 
10332 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
10333 
10334 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
10335 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
10336 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
10337 #endif
10338 #ifdef TCP_OFFLOAD
10339 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
10340 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
10341 
10342 	if (t4_toecaps_allowed == -1)
10343 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
10344 
10345 	if (t4_rdmacaps_allowed == -1) {
10346 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
10347 		    FW_CAPS_CONFIG_RDMA_RDMAC;
10348 	}
10349 
10350 	if (t4_iscsicaps_allowed == -1) {
10351 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
10352 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
10353 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
10354 	}
10355 
10356 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
10357 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
10358 
10359 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
10360 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
10361 #else
10362 	if (t4_toecaps_allowed == -1)
10363 		t4_toecaps_allowed = 0;
10364 
10365 	if (t4_rdmacaps_allowed == -1)
10366 		t4_rdmacaps_allowed = 0;
10367 
10368 	if (t4_iscsicaps_allowed == -1)
10369 		t4_iscsicaps_allowed = 0;
10370 #endif
10371 
10372 #ifdef DEV_NETMAP
10373 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
10374 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
10375 #endif
10376 
10377 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
10378 		t4_tmr_idx = TMR_IDX;
10379 
10380 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
10381 		t4_pktc_idx = PKTC_IDX;
10382 
10383 	if (t4_qsize_txq < 128)
10384 		t4_qsize_txq = 128;
10385 
10386 	if (t4_qsize_rxq < 128)
10387 		t4_qsize_rxq = 128;
10388 	while (t4_qsize_rxq & 7)
10389 		t4_qsize_rxq++;
10390 
10391 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
10392 
10393 	/*
10394 	 * Number of VIs to create per-port.  The first VI is the "main" regular
10395 	 * VI for the port.  The rest are additional virtual interfaces on the
10396 	 * same physical port.  Note that the main VI does not have native
10397 	 * netmap support but the extra VIs do.
10398 	 *
10399 	 * Limit the number of VIs per port to the number of available
10400 	 * MAC addresses per port.
10401 	 */
10402 	if (t4_num_vis < 1)
10403 		t4_num_vis = 1;
10404 	if (t4_num_vis > nitems(vi_mac_funcs)) {
10405 		t4_num_vis = nitems(vi_mac_funcs);
10406 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
10407 	}
10408 
10409 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
10410 		pcie_relaxed_ordering = 1;
10411 #if defined(__i386__) || defined(__amd64__)
10412 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
10413 			pcie_relaxed_ordering = 0;
10414 #endif
10415 	}
10416 }
10417 
10418 #ifdef DDB
10419 static void
10420 t4_dump_tcb(struct adapter *sc, int tid)
10421 {
10422 	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
10423 
10424 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
10425 	save = t4_read_reg(sc, reg);
10426 	base = sc->memwin[2].mw_base;
10427 
10428 	/* Dump TCB for the tid */
10429 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
10430 	tcb_addr += tid * TCB_SIZE;
10431 
10432 	if (is_t4(sc)) {
10433 		pf = 0;
10434 		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
10435 	} else {
10436 		pf = V_PFNUM(sc->pf);
10437 		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
10438 	}
10439 	t4_write_reg(sc, reg, win_pos | pf);
10440 	t4_read_reg(sc, reg);
10441 
10442 	off = tcb_addr - win_pos;
10443 	for (i = 0; i < 4; i++) {
10444 		uint32_t buf[8];
10445 		for (j = 0; j < 8; j++, off += 4)
10446 			buf[j] = htonl(t4_read_reg(sc, base + off));
10447 
10448 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
10449 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
10450 		    buf[7]);
10451 	}
10452 
10453 	t4_write_reg(sc, reg, save);
10454 	t4_read_reg(sc, reg);
10455 }
10456 
10457 static void
10458 t4_dump_devlog(struct adapter *sc)
10459 {
10460 	struct devlog_params *dparams = &sc->params.devlog;
10461 	struct fw_devlog_e e;
10462 	int i, first, j, m, nentries, rc;
10463 	uint64_t ftstamp = UINT64_MAX;
10464 
10465 	if (dparams->start == 0) {
10466 		db_printf("devlog params not valid\n");
10467 		return;
10468 	}
10469 
10470 	nentries = dparams->size / sizeof(struct fw_devlog_e);
10471 	m = fwmtype_to_hwmtype(dparams->memtype);
10472 
10473 	/* Find the first entry. */
10474 	first = -1;
10475 	for (i = 0; i < nentries && !db_pager_quit; i++) {
10476 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
10477 		    sizeof(e), (void *)&e);
10478 		if (rc != 0)
10479 			break;
10480 
10481 		if (e.timestamp == 0)
10482 			break;
10483 
10484 		e.timestamp = be64toh(e.timestamp);
10485 		if (e.timestamp < ftstamp) {
10486 			ftstamp = e.timestamp;
10487 			first = i;
10488 		}
10489 	}
10490 
10491 	if (first == -1)
10492 		return;
10493 
10494 	i = first;
10495 	do {
10496 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
10497 		    sizeof(e), (void *)&e);
10498 		if (rc != 0)
10499 			return;
10500 
10501 		if (e.timestamp == 0)
10502 			return;
10503 
10504 		e.timestamp = be64toh(e.timestamp);
10505 		e.seqno = be32toh(e.seqno);
10506 		for (j = 0; j < 8; j++)
10507 			e.params[j] = be32toh(e.params[j]);
10508 
10509 		db_printf("%10d  %15ju  %8s  %8s  ",
10510 		    e.seqno, e.timestamp,
10511 		    (e.level < nitems(devlog_level_strings) ?
10512 			devlog_level_strings[e.level] : "UNKNOWN"),
10513 		    (e.facility < nitems(devlog_facility_strings) ?
10514 			devlog_facility_strings[e.facility] : "UNKNOWN"));
10515 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
10516 		    e.params[3], e.params[4], e.params[5], e.params[6],
10517 		    e.params[7]);
10518 
10519 		if (++i == nentries)
10520 			i = 0;
10521 	} while (i != first && !db_pager_quit);
10522 }
10523 
10524 static struct command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
10525 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
10526 
10527 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
10528 {
10529 	device_t dev;
10530 	int t;
10531 	bool valid;
10532 
10533 	valid = false;
10534 	t = db_read_token();
10535 	if (t == tIDENT) {
10536 		dev = device_lookup_by_name(db_tok_string);
10537 		valid = true;
10538 	}
10539 	db_skip_to_eol();
10540 	if (!valid) {
10541 		db_printf("usage: show t4 devlog <nexus>\n");
10542 		return;
10543 	}
10544 
10545 	if (dev == NULL) {
10546 		db_printf("device not found\n");
10547 		return;
10548 	}
10549 
10550 	t4_dump_devlog(device_get_softc(dev));
10551 }
10552 
10553 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
10554 {
10555 	device_t dev;
10556 	int radix, tid, t;
10557 	bool valid;
10558 
10559 	valid = false;
10560 	radix = db_radix;
10561 	db_radix = 10;
10562 	t = db_read_token();
10563 	if (t == tIDENT) {
10564 		dev = device_lookup_by_name(db_tok_string);
10565 		t = db_read_token();
10566 		if (t == tNUMBER) {
10567 			tid = db_tok_number;
10568 			valid = true;
10569 		}
10570 	}
10571 	db_radix = radix;
10572 	db_skip_to_eol();
10573 	if (!valid) {
10574 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
10575 		return;
10576 	}
10577 
10578 	if (dev == NULL) {
10579 		db_printf("device not found\n");
10580 		return;
10581 	}
10582 	if (tid < 0) {
10583 		db_printf("invalid tid\n");
10584 		return;
10585 	}
10586 
10587 	t4_dump_tcb(device_get_softc(dev), tid);
10588 }
10589 #endif
10590 
10591 /*
10592  * Borrowed from cesa_prep_aes_key().
10593  *
10594  * NB: The crypto engine wants the words in the decryption key in reverse
10595  * order.
10596  */
10597 void
10598 t4_aes_getdeckey(void *dec_key, const void *enc_key, unsigned int kbits)
10599 {
10600 	uint32_t ek[4 * (RIJNDAEL_MAXNR + 1)];
10601 	uint32_t *dkey;
10602 	int i;
10603 
10604 	rijndaelKeySetupEnc(ek, enc_key, kbits);
10605 	dkey = dec_key;
10606 	dkey += (kbits / 8) / 4;
10607 
10608 	switch (kbits) {
10609 	case 128:
10610 		for (i = 0; i < 4; i++)
10611 			*--dkey = htobe32(ek[4 * 10 + i]);
10612 		break;
10613 	case 192:
10614 		for (i = 0; i < 2; i++)
10615 			*--dkey = htobe32(ek[4 * 11 + 2 + i]);
10616 		for (i = 0; i < 4; i++)
10617 			*--dkey = htobe32(ek[4 * 12 + i]);
10618 		break;
10619 	case 256:
10620 		for (i = 0; i < 4; i++)
10621 			*--dkey = htobe32(ek[4 * 13 + i]);
10622 		for (i = 0; i < 4; i++)
10623 			*--dkey = htobe32(ek[4 * 14 + i]);
10624 		break;
10625 	}
10626 	MPASS(dkey == dec_key);
10627 }
10628 
10629 static struct sx mlu;	/* mod load unload */
10630 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
10631 
10632 static int
10633 mod_event(module_t mod, int cmd, void *arg)
10634 {
10635 	int rc = 0;
10636 	static int loaded = 0;
10637 
10638 	switch (cmd) {
10639 	case MOD_LOAD:
10640 		sx_xlock(&mlu);
10641 		if (loaded++ == 0) {
10642 			t4_sge_modload();
10643 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
10644 			    t4_filter_rpl, CPL_COOKIE_FILTER);
10645 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
10646 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
10647 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
10648 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
10649 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
10650 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
10651 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
10652 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
10653 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
10654 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
10655 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
10656 			    do_smt_write_rpl);
10657 			sx_init(&t4_list_lock, "T4/T5 adapters");
10658 			SLIST_INIT(&t4_list);
10659 #ifdef TCP_OFFLOAD
10660 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
10661 			SLIST_INIT(&t4_uld_list);
10662 #endif
10663 #ifdef INET6
10664 			t4_clip_modload();
10665 #endif
10666 			t4_tracer_modload();
10667 			tweak_tunables();
10668 		}
10669 		sx_xunlock(&mlu);
10670 		break;
10671 
10672 	case MOD_UNLOAD:
10673 		sx_xlock(&mlu);
10674 		if (--loaded == 0) {
10675 			int tries;
10676 
10677 			sx_slock(&t4_list_lock);
10678 			if (!SLIST_EMPTY(&t4_list)) {
10679 				rc = EBUSY;
10680 				sx_sunlock(&t4_list_lock);
10681 				goto done_unload;
10682 			}
10683 #ifdef TCP_OFFLOAD
10684 			sx_slock(&t4_uld_list_lock);
10685 			if (!SLIST_EMPTY(&t4_uld_list)) {
10686 				rc = EBUSY;
10687 				sx_sunlock(&t4_uld_list_lock);
10688 				sx_sunlock(&t4_list_lock);
10689 				goto done_unload;
10690 			}
10691 #endif
10692 			tries = 0;
10693 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
10694 				uprintf("%ju clusters with custom free routine "
10695 				    "still is use.\n", t4_sge_extfree_refs());
10696 				pause("t4unload", 2 * hz);
10697 			}
10698 #ifdef TCP_OFFLOAD
10699 			sx_sunlock(&t4_uld_list_lock);
10700 #endif
10701 			sx_sunlock(&t4_list_lock);
10702 
10703 			if (t4_sge_extfree_refs() == 0) {
10704 				t4_tracer_modunload();
10705 #ifdef INET6
10706 				t4_clip_modunload();
10707 #endif
10708 #ifdef TCP_OFFLOAD
10709 				sx_destroy(&t4_uld_list_lock);
10710 #endif
10711 				sx_destroy(&t4_list_lock);
10712 				t4_sge_modunload();
10713 				loaded = 0;
10714 			} else {
10715 				rc = EBUSY;
10716 				loaded++;	/* undo earlier decrement */
10717 			}
10718 		}
10719 done_unload:
10720 		sx_xunlock(&mlu);
10721 		break;
10722 	}
10723 
10724 	return (rc);
10725 }
10726 
10727 static devclass_t t4_devclass, t5_devclass, t6_devclass;
10728 static devclass_t cxgbe_devclass, cxl_devclass, cc_devclass;
10729 static devclass_t vcxgbe_devclass, vcxl_devclass, vcc_devclass;
10730 
10731 DRIVER_MODULE(t4nex, pci, t4_driver, t4_devclass, mod_event, 0);
10732 MODULE_VERSION(t4nex, 1);
10733 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
10734 #ifdef DEV_NETMAP
10735 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
10736 #endif /* DEV_NETMAP */
10737 
10738 DRIVER_MODULE(t5nex, pci, t5_driver, t5_devclass, mod_event, 0);
10739 MODULE_VERSION(t5nex, 1);
10740 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
10741 #ifdef DEV_NETMAP
10742 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
10743 #endif /* DEV_NETMAP */
10744 
10745 DRIVER_MODULE(t6nex, pci, t6_driver, t6_devclass, mod_event, 0);
10746 MODULE_VERSION(t6nex, 1);
10747 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
10748 #ifdef DEV_NETMAP
10749 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
10750 #endif /* DEV_NETMAP */
10751 
10752 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, cxgbe_devclass, 0, 0);
10753 MODULE_VERSION(cxgbe, 1);
10754 
10755 DRIVER_MODULE(cxl, t5nex, cxl_driver, cxl_devclass, 0, 0);
10756 MODULE_VERSION(cxl, 1);
10757 
10758 DRIVER_MODULE(cc, t6nex, cc_driver, cc_devclass, 0, 0);
10759 MODULE_VERSION(cc, 1);
10760 
10761 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, vcxgbe_devclass, 0, 0);
10762 MODULE_VERSION(vcxgbe, 1);
10763 
10764 DRIVER_MODULE(vcxl, cxl, vcxl_driver, vcxl_devclass, 0, 0);
10765 MODULE_VERSION(vcxl, 1);
10766 
10767 DRIVER_MODULE(vcc, cc, vcc_driver, vcc_devclass, 0, 0);
10768 MODULE_VERSION(vcc, 1);
10769