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