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