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