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