xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision 84823cc70824c8d842f503d8c2e6d7b0c2d95b61)
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(device_t, device_t, struct sbuf *);
101 static int t4_ready(device_t);
102 static int t4_read_port_device(device_t, int, device_t *);
103 static int t4_suspend(device_t);
104 static int t4_resume(device_t);
105 static int t4_reset_prepare(device_t, device_t);
106 static int t4_reset_post(device_t, device_t);
107 static device_method_t t4_methods[] = {
108 	DEVMETHOD(device_probe,		t4_probe),
109 	DEVMETHOD(device_attach,	t4_attach),
110 	DEVMETHOD(device_detach,	t4_detach),
111 	DEVMETHOD(device_suspend,	t4_suspend),
112 	DEVMETHOD(device_resume,	t4_resume),
113 
114 	DEVMETHOD(bus_child_location,	t4_child_location),
115 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
116 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
117 
118 	DEVMETHOD(t4_is_main_ready,	t4_ready),
119 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
120 
121 	DEVMETHOD_END
122 };
123 static driver_t t4_driver = {
124 	"t4nex",
125 	t4_methods,
126 	sizeof(struct adapter)
127 };
128 
129 
130 /* T4 port (cxgbe) interface */
131 static int cxgbe_probe(device_t);
132 static int cxgbe_attach(device_t);
133 static int cxgbe_detach(device_t);
134 device_method_t cxgbe_methods[] = {
135 	DEVMETHOD(device_probe,		cxgbe_probe),
136 	DEVMETHOD(device_attach,	cxgbe_attach),
137 	DEVMETHOD(device_detach,	cxgbe_detach),
138 	{ 0, 0 }
139 };
140 static driver_t cxgbe_driver = {
141 	"cxgbe",
142 	cxgbe_methods,
143 	sizeof(struct port_info)
144 };
145 
146 /* T4 VI (vcxgbe) interface */
147 static int vcxgbe_probe(device_t);
148 static int vcxgbe_attach(device_t);
149 static int vcxgbe_detach(device_t);
150 static device_method_t vcxgbe_methods[] = {
151 	DEVMETHOD(device_probe,		vcxgbe_probe),
152 	DEVMETHOD(device_attach,	vcxgbe_attach),
153 	DEVMETHOD(device_detach,	vcxgbe_detach),
154 	{ 0, 0 }
155 };
156 static driver_t vcxgbe_driver = {
157 	"vcxgbe",
158 	vcxgbe_methods,
159 	sizeof(struct vi_info)
160 };
161 
162 static d_ioctl_t t4_ioctl;
163 
164 static struct cdevsw t4_cdevsw = {
165        .d_version = D_VERSION,
166        .d_ioctl = t4_ioctl,
167        .d_name = "t4nex",
168 };
169 
170 /* T5 bus driver interface */
171 static int t5_probe(device_t);
172 static device_method_t t5_methods[] = {
173 	DEVMETHOD(device_probe,		t5_probe),
174 	DEVMETHOD(device_attach,	t4_attach),
175 	DEVMETHOD(device_detach,	t4_detach),
176 	DEVMETHOD(device_suspend,	t4_suspend),
177 	DEVMETHOD(device_resume,	t4_resume),
178 
179 	DEVMETHOD(bus_child_location,	t4_child_location),
180 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
181 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
182 
183 	DEVMETHOD(t4_is_main_ready,	t4_ready),
184 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
185 
186 	DEVMETHOD_END
187 };
188 static driver_t t5_driver = {
189 	"t5nex",
190 	t5_methods,
191 	sizeof(struct adapter)
192 };
193 
194 
195 /* T5 port (cxl) interface */
196 static driver_t cxl_driver = {
197 	"cxl",
198 	cxgbe_methods,
199 	sizeof(struct port_info)
200 };
201 
202 /* T5 VI (vcxl) interface */
203 static driver_t vcxl_driver = {
204 	"vcxl",
205 	vcxgbe_methods,
206 	sizeof(struct vi_info)
207 };
208 
209 /* T6 bus driver interface */
210 static int t6_probe(device_t);
211 static device_method_t t6_methods[] = {
212 	DEVMETHOD(device_probe,		t6_probe),
213 	DEVMETHOD(device_attach,	t4_attach),
214 	DEVMETHOD(device_detach,	t4_detach),
215 	DEVMETHOD(device_suspend,	t4_suspend),
216 	DEVMETHOD(device_resume,	t4_resume),
217 
218 	DEVMETHOD(bus_child_location,	t4_child_location),
219 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
220 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
221 
222 	DEVMETHOD(t4_is_main_ready,	t4_ready),
223 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
224 
225 	DEVMETHOD_END
226 };
227 static driver_t t6_driver = {
228 	"t6nex",
229 	t6_methods,
230 	sizeof(struct adapter)
231 };
232 
233 
234 /* T6 port (cc) interface */
235 static driver_t cc_driver = {
236 	"cc",
237 	cxgbe_methods,
238 	sizeof(struct port_info)
239 };
240 
241 /* T6 VI (vcc) interface */
242 static driver_t vcc_driver = {
243 	"vcc",
244 	vcxgbe_methods,
245 	sizeof(struct vi_info)
246 };
247 
248 /* ifnet interface */
249 static void cxgbe_init(void *);
250 static int cxgbe_ioctl(struct ifnet *, unsigned long, caddr_t);
251 static int cxgbe_transmit(struct ifnet *, struct mbuf *);
252 static void cxgbe_qflush(struct ifnet *);
253 #if defined(KERN_TLS) || defined(RATELIMIT)
254 static int cxgbe_snd_tag_alloc(struct ifnet *, union if_snd_tag_alloc_params *,
255     struct m_snd_tag **);
256 #endif
257 
258 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
259 
260 /*
261  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
262  * then ADAPTER_LOCK, then t4_uld_list_lock.
263  */
264 static struct sx t4_list_lock;
265 SLIST_HEAD(, adapter) t4_list;
266 #ifdef TCP_OFFLOAD
267 static struct sx t4_uld_list_lock;
268 SLIST_HEAD(, uld_info) t4_uld_list;
269 #endif
270 
271 /*
272  * Tunables.  See tweak_tunables() too.
273  *
274  * Each tunable is set to a default value here if it's known at compile-time.
275  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
276  * provide a reasonable default (upto n) when the driver is loaded.
277  *
278  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
279  * T5 are under hw.cxl.
280  */
281 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
282     "cxgbe(4) parameters");
283 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
284     "cxgbe(4) T5+ parameters");
285 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
286     "cxgbe(4) TOE parameters");
287 
288 /*
289  * Number of queues for tx and rx, NIC and offload.
290  */
291 #define NTXQ 16
292 int t4_ntxq = -NTXQ;
293 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
294     "Number of TX queues per port");
295 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);	/* Old name, undocumented */
296 
297 #define NRXQ 8
298 int t4_nrxq = -NRXQ;
299 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
300     "Number of RX queues per port");
301 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);	/* Old name, undocumented */
302 
303 #define NTXQ_VI 1
304 static int t4_ntxq_vi = -NTXQ_VI;
305 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
306     "Number of TX queues per VI");
307 
308 #define NRXQ_VI 1
309 static int t4_nrxq_vi = -NRXQ_VI;
310 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
311     "Number of RX queues per VI");
312 
313 static int t4_rsrv_noflowq = 0;
314 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
315     0, "Reserve TX queue 0 of each VI for non-flowid packets");
316 
317 static int t4_clocksync_fast = 1;
318 SYSCTL_INT(_hw_cxgbe, OID_AUTO, csfast, CTLFLAG_RW | CTLFLAG_MPSAFE, &t4_clocksync_fast, 0,
319     "During initial clock sync how fast do we update in seconds");
320 
321 static int t4_clocksync_normal = 30;
322 SYSCTL_INT(_hw_cxgbe, OID_AUTO, csnormal, CTLFLAG_RW | CTLFLAG_MPSAFE, &t4_clocksync_normal, 0,
323     "During normal clock sync how fast do we update in seconds");
324 
325 static int t4_fast_2_normal = 30;
326 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cscount, CTLFLAG_RW | CTLFLAG_MPSAFE, &t4_fast_2_normal, 0,
327     "How many clock syncs do we need to do to transition to slow");
328 
329 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
330 #define NOFLDTXQ 8
331 static int t4_nofldtxq = -NOFLDTXQ;
332 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
333     "Number of offload TX queues per port");
334 
335 #define NOFLDRXQ 2
336 static int t4_nofldrxq = -NOFLDRXQ;
337 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
338     "Number of offload RX queues per port");
339 
340 #define NOFLDTXQ_VI 1
341 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
342 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
343     "Number of offload TX queues per VI");
344 
345 #define NOFLDRXQ_VI 1
346 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
347 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
348     "Number of offload RX queues per VI");
349 
350 #define TMR_IDX_OFLD 1
351 int t4_tmr_idx_ofld = TMR_IDX_OFLD;
352 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
353     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
354 
355 #define PKTC_IDX_OFLD (-1)
356 int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
357 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
358     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
359 
360 /* 0 means chip/fw default, non-zero number is value in microseconds */
361 static u_long t4_toe_keepalive_idle = 0;
362 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
363     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
364 
365 /* 0 means chip/fw default, non-zero number is value in microseconds */
366 static u_long t4_toe_keepalive_interval = 0;
367 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
368     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
369 
370 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
371 static int t4_toe_keepalive_count = 0;
372 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
373     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
374 
375 /* 0 means chip/fw default, non-zero number is value in microseconds */
376 static u_long t4_toe_rexmt_min = 0;
377 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
378     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
379 
380 /* 0 means chip/fw default, non-zero number is value in microseconds */
381 static u_long t4_toe_rexmt_max = 0;
382 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
383     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
384 
385 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
386 static int t4_toe_rexmt_count = 0;
387 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
388     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
389 
390 /* -1 means chip/fw default, other values are raw backoff values to use */
391 static int t4_toe_rexmt_backoff[16] = {
392 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
393 };
394 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
395     CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
396     "cxgbe(4) TOE retransmit backoff values");
397 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
398     &t4_toe_rexmt_backoff[0], 0, "");
399 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
400     &t4_toe_rexmt_backoff[1], 0, "");
401 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
402     &t4_toe_rexmt_backoff[2], 0, "");
403 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
404     &t4_toe_rexmt_backoff[3], 0, "");
405 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
406     &t4_toe_rexmt_backoff[4], 0, "");
407 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
408     &t4_toe_rexmt_backoff[5], 0, "");
409 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
410     &t4_toe_rexmt_backoff[6], 0, "");
411 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
412     &t4_toe_rexmt_backoff[7], 0, "");
413 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
414     &t4_toe_rexmt_backoff[8], 0, "");
415 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
416     &t4_toe_rexmt_backoff[9], 0, "");
417 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
418     &t4_toe_rexmt_backoff[10], 0, "");
419 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
420     &t4_toe_rexmt_backoff[11], 0, "");
421 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
422     &t4_toe_rexmt_backoff[12], 0, "");
423 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
424     &t4_toe_rexmt_backoff[13], 0, "");
425 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
426     &t4_toe_rexmt_backoff[14], 0, "");
427 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
428     &t4_toe_rexmt_backoff[15], 0, "");
429 
430 static int t4_toe_tls_rx_timeout = 5;
431 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, tls_rx_timeout, CTLFLAG_RDTUN,
432     &t4_toe_tls_rx_timeout, 0,
433     "Timeout in seconds to downgrade TLS sockets to plain TOE");
434 #endif
435 
436 #ifdef DEV_NETMAP
437 #define NN_MAIN_VI	(1 << 0)	/* Native netmap on the main VI */
438 #define NN_EXTRA_VI	(1 << 1)	/* Native netmap on the extra VI(s) */
439 static int t4_native_netmap = NN_EXTRA_VI;
440 SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
441     0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
442 
443 #define NNMTXQ 8
444 static int t4_nnmtxq = -NNMTXQ;
445 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
446     "Number of netmap TX queues");
447 
448 #define NNMRXQ 8
449 static int t4_nnmrxq = -NNMRXQ;
450 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
451     "Number of netmap RX queues");
452 
453 #define NNMTXQ_VI 2
454 static int t4_nnmtxq_vi = -NNMTXQ_VI;
455 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
456     "Number of netmap TX queues per VI");
457 
458 #define NNMRXQ_VI 2
459 static int t4_nnmrxq_vi = -NNMRXQ_VI;
460 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
461     "Number of netmap RX queues per VI");
462 #endif
463 
464 /*
465  * Holdoff parameters for ports.
466  */
467 #define TMR_IDX 1
468 int t4_tmr_idx = TMR_IDX;
469 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
470     0, "Holdoff timer index");
471 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);	/* Old name */
472 
473 #define PKTC_IDX (-1)
474 int t4_pktc_idx = PKTC_IDX;
475 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
476     0, "Holdoff packet counter index");
477 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);	/* Old name */
478 
479 /*
480  * Size (# of entries) of each tx and rx queue.
481  */
482 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
483 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
484     "Number of descriptors in each TX queue");
485 
486 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
487 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
488     "Number of descriptors in each RX queue");
489 
490 /*
491  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
492  */
493 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
494 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
495     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
496 
497 /*
498  * Configuration file.  All the _CF names here are special.
499  */
500 #define DEFAULT_CF	"default"
501 #define BUILTIN_CF	"built-in"
502 #define FLASH_CF	"flash"
503 #define UWIRE_CF	"uwire"
504 #define FPGA_CF		"fpga"
505 static char t4_cfg_file[32] = DEFAULT_CF;
506 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
507     sizeof(t4_cfg_file), "Firmware configuration file");
508 
509 /*
510  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
511  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
512  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
513  *            mark or when signalled to do so, 0 to never emit PAUSE.
514  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
515  *                 negotiated settings will override rx_pause/tx_pause.
516  *                 Otherwise rx_pause/tx_pause are applied forcibly.
517  */
518 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
519 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
520     &t4_pause_settings, 0,
521     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
522 
523 /*
524  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
525  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
526  *  0 to disable FEC.
527  */
528 static int t4_fec = -1;
529 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
530     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
531 
532 /*
533  * Controls when the driver sets the FORCE_FEC bit in the L1_CFG32 that it
534  * issues to the firmware.  If the firmware doesn't support FORCE_FEC then the
535  * driver runs as if this is set to 0.
536  * -1 to set FORCE_FEC iff requested_fec != AUTO. Multiple FEC bits are okay.
537  *  0 to never set FORCE_FEC. requested_fec = AUTO means use the hint from the
538  *    transceiver. Multiple FEC bits may not be okay but will be passed on to
539  *    the firmware anyway (may result in l1cfg errors with old firmwares).
540  *  1 to always set FORCE_FEC. Multiple FEC bits are okay. requested_fec = AUTO
541  *    means set all FEC bits that are valid for the speed.
542  */
543 static int t4_force_fec = -1;
544 SYSCTL_INT(_hw_cxgbe, OID_AUTO, force_fec, CTLFLAG_RDTUN, &t4_force_fec, 0,
545     "Controls the use of FORCE_FEC bit in L1 configuration.");
546 
547 /*
548  * Link autonegotiation.
549  * -1 to run with the firmware default.
550  *  0 to disable.
551  *  1 to enable.
552  */
553 static int t4_autoneg = -1;
554 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
555     "Link autonegotiation");
556 
557 /*
558  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
559  * encouraged respectively).  '-n' is the same as 'n' except the firmware
560  * version used in the checks is read from the firmware bundled with the driver.
561  */
562 static int t4_fw_install = 1;
563 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
564     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
565 
566 /*
567  * ASIC features that will be used.  Disable the ones you don't want so that the
568  * chip resources aren't wasted on features that will not be used.
569  */
570 static int t4_nbmcaps_allowed = 0;
571 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
572     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
573 
574 static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
575 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
576     &t4_linkcaps_allowed, 0, "Default link capabilities");
577 
578 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
579     FW_CAPS_CONFIG_SWITCH_EGRESS;
580 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
581     &t4_switchcaps_allowed, 0, "Default switch capabilities");
582 
583 #ifdef RATELIMIT
584 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
585 	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
586 #else
587 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
588 	FW_CAPS_CONFIG_NIC_HASHFILTER;
589 #endif
590 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
591     &t4_niccaps_allowed, 0, "Default NIC capabilities");
592 
593 static int t4_toecaps_allowed = -1;
594 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
595     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
596 
597 static int t4_rdmacaps_allowed = -1;
598 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
599     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
600 
601 static int t4_cryptocaps_allowed = -1;
602 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
603     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
604 
605 static int t4_iscsicaps_allowed = -1;
606 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
607     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
608 
609 static int t4_fcoecaps_allowed = 0;
610 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
611     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
612 
613 static int t5_write_combine = 0;
614 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
615     0, "Use WC instead of UC for BAR2");
616 
617 static int t4_num_vis = 1;
618 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
619     "Number of VIs per port");
620 
621 /*
622  * PCIe Relaxed Ordering.
623  * -1: driver should figure out a good value.
624  * 0: disable RO.
625  * 1: enable RO.
626  * 2: leave RO alone.
627  */
628 static int pcie_relaxed_ordering = -1;
629 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
630     &pcie_relaxed_ordering, 0,
631     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
632 
633 static int t4_panic_on_fatal_err = 0;
634 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
635     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
636 
637 static int t4_reset_on_fatal_err = 0;
638 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
639     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
640 
641 static int t4_clock_gate_on_suspend = 0;
642 SYSCTL_INT(_hw_cxgbe, OID_AUTO, clock_gate_on_suspend, CTLFLAG_RWTUN,
643     &t4_clock_gate_on_suspend, 0, "gate the clock on suspend");
644 
645 static int t4_tx_vm_wr = 0;
646 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
647     "Use VM work requests to transmit packets.");
648 
649 /*
650  * Set to non-zero to enable the attack filter.  A packet that matches any of
651  * these conditions will get dropped on ingress:
652  * 1) IP && source address == destination address.
653  * 2) TCP/IP && source address is not a unicast address.
654  * 3) TCP/IP && destination address is not a unicast address.
655  * 4) IP && source address is loopback (127.x.y.z).
656  * 5) IP && destination address is loopback (127.x.y.z).
657  * 6) IPv6 && source address == destination address.
658  * 7) IPv6 && source address is not a unicast address.
659  * 8) IPv6 && source address is loopback (::1/128).
660  * 9) IPv6 && destination address is loopback (::1/128).
661  * 10) IPv6 && source address is unspecified (::/128).
662  * 11) IPv6 && destination address is unspecified (::/128).
663  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
664  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
665  */
666 static int t4_attack_filter = 0;
667 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
668     &t4_attack_filter, 0, "Drop suspicious traffic");
669 
670 static int t4_drop_ip_fragments = 0;
671 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
672     &t4_drop_ip_fragments, 0, "Drop IP fragments");
673 
674 static int t4_drop_pkts_with_l2_errors = 1;
675 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
676     &t4_drop_pkts_with_l2_errors, 0,
677     "Drop all frames with Layer 2 length or checksum errors");
678 
679 static int t4_drop_pkts_with_l3_errors = 0;
680 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
681     &t4_drop_pkts_with_l3_errors, 0,
682     "Drop all frames with IP version, length, or checksum errors");
683 
684 static int t4_drop_pkts_with_l4_errors = 0;
685 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
686     &t4_drop_pkts_with_l4_errors, 0,
687     "Drop all frames with Layer 4 length, checksum, or other errors");
688 
689 #ifdef TCP_OFFLOAD
690 /*
691  * TOE tunables.
692  */
693 static int t4_cop_managed_offloading = 0;
694 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
695     &t4_cop_managed_offloading, 0,
696     "COP (Connection Offload Policy) controls all TOE offload");
697 #endif
698 
699 #ifdef KERN_TLS
700 /*
701  * This enables KERN_TLS for all adapters if set.
702  */
703 static int t4_kern_tls = 0;
704 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
705     "Enable KERN_TLS mode for T6 adapters");
706 
707 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
708     "cxgbe(4) KERN_TLS parameters");
709 
710 static int t4_tls_inline_keys = 0;
711 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
712     &t4_tls_inline_keys, 0,
713     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
714     "in card memory.");
715 
716 static int t4_tls_combo_wrs = 0;
717 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
718     0, "Attempt to combine TCB field updates with TLS record work requests.");
719 #endif
720 
721 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
722 static int vi_mac_funcs[] = {
723 	FW_VI_FUNC_ETH,
724 	FW_VI_FUNC_OFLD,
725 	FW_VI_FUNC_IWARP,
726 	FW_VI_FUNC_OPENISCSI,
727 	FW_VI_FUNC_OPENFCOE,
728 	FW_VI_FUNC_FOISCSI,
729 	FW_VI_FUNC_FOFCOE,
730 };
731 
732 struct intrs_and_queues {
733 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
734 	uint16_t num_vis;	/* number of VIs for each port */
735 	uint16_t nirq;		/* Total # of vectors */
736 	uint16_t ntxq;		/* # of NIC txq's for each port */
737 	uint16_t nrxq;		/* # of NIC rxq's for each port */
738 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
739 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
740 	uint16_t nnmtxq;	/* # of netmap txq's */
741 	uint16_t nnmrxq;	/* # of netmap rxq's */
742 
743 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
744 	uint16_t ntxq_vi;	/* # of NIC txq's */
745 	uint16_t nrxq_vi;	/* # of NIC rxq's */
746 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
747 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
748 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
749 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
750 };
751 
752 static void setup_memwin(struct adapter *);
753 static void position_memwin(struct adapter *, int, uint32_t);
754 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
755 static int fwmtype_to_hwmtype(int);
756 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
757     uint32_t *);
758 static int fixup_devlog_params(struct adapter *);
759 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
760 static int contact_firmware(struct adapter *);
761 static int partition_resources(struct adapter *);
762 static int get_params__pre_init(struct adapter *);
763 static int set_params__pre_init(struct adapter *);
764 static int get_params__post_init(struct adapter *);
765 static int set_params__post_init(struct adapter *);
766 static void t4_set_desc(struct adapter *);
767 static bool fixed_ifmedia(struct port_info *);
768 static void build_medialist(struct port_info *);
769 static void init_link_config(struct port_info *);
770 static int fixup_link_config(struct port_info *);
771 static int apply_link_config(struct port_info *);
772 static int cxgbe_init_synchronized(struct vi_info *);
773 static int cxgbe_uninit_synchronized(struct vi_info *);
774 static int adapter_full_init(struct adapter *);
775 static void adapter_full_uninit(struct adapter *);
776 static int vi_full_init(struct vi_info *);
777 static void vi_full_uninit(struct vi_info *);
778 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
779 static void quiesce_txq(struct sge_txq *);
780 static void quiesce_wrq(struct sge_wrq *);
781 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
782 static void quiesce_vi(struct vi_info *);
783 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
784     driver_intr_t *, void *, char *);
785 static int t4_free_irq(struct adapter *, struct irq *);
786 static void t4_init_atid_table(struct adapter *);
787 static void t4_free_atid_table(struct adapter *);
788 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
789 static void vi_refresh_stats(struct vi_info *);
790 static void cxgbe_refresh_stats(struct vi_info *);
791 static void cxgbe_tick(void *);
792 static void vi_tick(void *);
793 static void cxgbe_sysctls(struct port_info *);
794 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
795 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
796 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
797 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
798 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
799 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
800 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
801 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
802 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
803 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
804 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
805 static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
806 static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
807 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
808 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
809 static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
810 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
811 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
812 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
813 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
814 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
815 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
816 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
817 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
818 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
819 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
820 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
821 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
822 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
823 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
824 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
825 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
826 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
827 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
828 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
829 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
830 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
831 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
832 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
833 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
834 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
835 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
836 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
837 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
838 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
839 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
840 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
841 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
842 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
843 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
844 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
845 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
846 #ifdef TCP_OFFLOAD
847 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
848 static int sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS);
849 static int sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS);
850 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
851 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
852 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
853 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
854 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
855 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
856 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
857 #endif
858 static int get_sge_context(struct adapter *, struct t4_sge_context *);
859 static int load_fw(struct adapter *, struct t4_data *);
860 static int load_cfg(struct adapter *, struct t4_data *);
861 static int load_boot(struct adapter *, struct t4_bootrom *);
862 static int load_bootcfg(struct adapter *, struct t4_data *);
863 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
864 static void free_offload_policy(struct t4_offload_policy *);
865 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
866 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
867 static int read_i2c(struct adapter *, struct t4_i2c_data *);
868 static int clear_stats(struct adapter *, u_int);
869 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
870 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
871 #ifdef TCP_OFFLOAD
872 static int toe_capability(struct vi_info *, bool);
873 static int t4_deactivate_all_uld(struct adapter *);
874 static void t4_async_event(struct adapter *);
875 #endif
876 #ifdef KERN_TLS
877 static int ktls_capability(struct adapter *, bool);
878 #endif
879 static int mod_event(module_t, int, void *);
880 static int notify_siblings(device_t, int);
881 static uint64_t vi_get_counter(struct ifnet *, ift_counter);
882 static uint64_t cxgbe_get_counter(struct ifnet *, ift_counter);
883 static void enable_vxlan_rx(struct adapter *);
884 static void reset_adapter_task(void *, int);
885 static void fatal_error_task(void *, int);
886 static void dump_devlog(struct adapter *);
887 static void dump_cim_regs(struct adapter *);
888 static void dump_cimla(struct adapter *);
889 
890 struct {
891 	uint16_t device;
892 	char *desc;
893 } t4_pciids[] = {
894 	{0xa000, "Chelsio Terminator 4 FPGA"},
895 	{0x4400, "Chelsio T440-dbg"},
896 	{0x4401, "Chelsio T420-CR"},
897 	{0x4402, "Chelsio T422-CR"},
898 	{0x4403, "Chelsio T440-CR"},
899 	{0x4404, "Chelsio T420-BCH"},
900 	{0x4405, "Chelsio T440-BCH"},
901 	{0x4406, "Chelsio T440-CH"},
902 	{0x4407, "Chelsio T420-SO"},
903 	{0x4408, "Chelsio T420-CX"},
904 	{0x4409, "Chelsio T420-BT"},
905 	{0x440a, "Chelsio T404-BT"},
906 	{0x440e, "Chelsio T440-LP-CR"},
907 }, t5_pciids[] = {
908 	{0xb000, "Chelsio Terminator 5 FPGA"},
909 	{0x5400, "Chelsio T580-dbg"},
910 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
911 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
912 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
913 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
914 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
915 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
916 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
917 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
918 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
919 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
920 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
921 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
922 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
923 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
924 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
925 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
926 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
927 
928 	/* Custom */
929 	{0x5483, "Custom T540-CR"},
930 	{0x5484, "Custom T540-BT"},
931 }, t6_pciids[] = {
932 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
933 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
934 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
935 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
936 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
937 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
938 	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
939 	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
940 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
941 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
942 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
943 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
944 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
945 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
946 	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
947 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
948 
949 	/* Custom */
950 	{0x6480, "Custom T6225-CR"},
951 	{0x6481, "Custom T62100-CR"},
952 	{0x6482, "Custom T6225-CR"},
953 	{0x6483, "Custom T62100-CR"},
954 	{0x6484, "Custom T64100-CR"},
955 	{0x6485, "Custom T6240-SO"},
956 	{0x6486, "Custom T6225-SO-CR"},
957 	{0x6487, "Custom T6225-CR"},
958 };
959 
960 #ifdef TCP_OFFLOAD
961 /*
962  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
963  * be exactly the same for both rxq and ofld_rxq.
964  */
965 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
966 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
967 #endif
968 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
969 
970 static int
971 t4_probe(device_t dev)
972 {
973 	int i;
974 	uint16_t v = pci_get_vendor(dev);
975 	uint16_t d = pci_get_device(dev);
976 	uint8_t f = pci_get_function(dev);
977 
978 	if (v != PCI_VENDOR_ID_CHELSIO)
979 		return (ENXIO);
980 
981 	/* Attach only to PF0 of the FPGA */
982 	if (d == 0xa000 && f != 0)
983 		return (ENXIO);
984 
985 	for (i = 0; i < nitems(t4_pciids); i++) {
986 		if (d == t4_pciids[i].device) {
987 			device_set_desc(dev, t4_pciids[i].desc);
988 			return (BUS_PROBE_DEFAULT);
989 		}
990 	}
991 
992 	return (ENXIO);
993 }
994 
995 static int
996 t5_probe(device_t dev)
997 {
998 	int i;
999 	uint16_t v = pci_get_vendor(dev);
1000 	uint16_t d = pci_get_device(dev);
1001 	uint8_t f = pci_get_function(dev);
1002 
1003 	if (v != PCI_VENDOR_ID_CHELSIO)
1004 		return (ENXIO);
1005 
1006 	/* Attach only to PF0 of the FPGA */
1007 	if (d == 0xb000 && f != 0)
1008 		return (ENXIO);
1009 
1010 	for (i = 0; i < nitems(t5_pciids); i++) {
1011 		if (d == t5_pciids[i].device) {
1012 			device_set_desc(dev, t5_pciids[i].desc);
1013 			return (BUS_PROBE_DEFAULT);
1014 		}
1015 	}
1016 
1017 	return (ENXIO);
1018 }
1019 
1020 static int
1021 t6_probe(device_t dev)
1022 {
1023 	int i;
1024 	uint16_t v = pci_get_vendor(dev);
1025 	uint16_t d = pci_get_device(dev);
1026 
1027 	if (v != PCI_VENDOR_ID_CHELSIO)
1028 		return (ENXIO);
1029 
1030 	for (i = 0; i < nitems(t6_pciids); i++) {
1031 		if (d == t6_pciids[i].device) {
1032 			device_set_desc(dev, t6_pciids[i].desc);
1033 			return (BUS_PROBE_DEFAULT);
1034 		}
1035 	}
1036 
1037 	return (ENXIO);
1038 }
1039 
1040 static void
1041 t5_attribute_workaround(device_t dev)
1042 {
1043 	device_t root_port;
1044 	uint32_t v;
1045 
1046 	/*
1047 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1048 	 * Ordering attributes when replying to a TLP from a Root
1049 	 * Port.  As a workaround, find the parent Root Port and
1050 	 * disable No Snoop and Relaxed Ordering.  Note that this
1051 	 * affects all devices under this root port.
1052 	 */
1053 	root_port = pci_find_pcie_root_port(dev);
1054 	if (root_port == NULL) {
1055 		device_printf(dev, "Unable to find parent root port\n");
1056 		return;
1057 	}
1058 
1059 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1060 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1061 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1062 	    0)
1063 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1064 		    device_get_nameunit(root_port));
1065 }
1066 
1067 static const struct devnames devnames[] = {
1068 	{
1069 		.nexus_name = "t4nex",
1070 		.ifnet_name = "cxgbe",
1071 		.vi_ifnet_name = "vcxgbe",
1072 		.pf03_drv_name = "t4iov",
1073 		.vf_nexus_name = "t4vf",
1074 		.vf_ifnet_name = "cxgbev"
1075 	}, {
1076 		.nexus_name = "t5nex",
1077 		.ifnet_name = "cxl",
1078 		.vi_ifnet_name = "vcxl",
1079 		.pf03_drv_name = "t5iov",
1080 		.vf_nexus_name = "t5vf",
1081 		.vf_ifnet_name = "cxlv"
1082 	}, {
1083 		.nexus_name = "t6nex",
1084 		.ifnet_name = "cc",
1085 		.vi_ifnet_name = "vcc",
1086 		.pf03_drv_name = "t6iov",
1087 		.vf_nexus_name = "t6vf",
1088 		.vf_ifnet_name = "ccv"
1089 	}
1090 };
1091 
1092 void
1093 t4_init_devnames(struct adapter *sc)
1094 {
1095 	int id;
1096 
1097 	id = chip_id(sc);
1098 	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1099 		sc->names = &devnames[id - CHELSIO_T4];
1100 	else {
1101 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1102 		sc->names = NULL;
1103 	}
1104 }
1105 
1106 static int
1107 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1108 {
1109 	const char *parent, *name;
1110 	long value;
1111 	int line, unit;
1112 
1113 	line = 0;
1114 	parent = device_get_nameunit(sc->dev);
1115 	name = sc->names->ifnet_name;
1116 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1117 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1118 		    value == pi->port_id)
1119 			return (unit);
1120 	}
1121 	return (-1);
1122 }
1123 
1124 static inline uint64_t
1125 t4_get_ns_timestamp(struct timespec *ts)
1126 {
1127 	return ((ts->tv_sec * 1000000000) + ts->tv_nsec);
1128 }
1129 
1130 static void
1131 t4_calibration(void *arg)
1132 {
1133 	struct adapter *sc;
1134 	struct timespec ts;
1135 	struct clock_sync *cur, *nex;
1136 	int next_up;
1137 
1138 	sc = (struct adapter *)arg;
1139 
1140 	cur = &sc->cal_info[sc->cal_current];
1141 	next_up = (sc->cal_current + 1) % CNT_CAL_INFO;
1142        	nex = &sc->cal_info[next_up];
1143 	if (__predict_false(sc->cal_count == 0)) {
1144 		/* First time in, just get the values in */
1145 		cur->hw_cur = t4_read_reg64(sc, A_SGE_TIMESTAMP_LO);
1146 		nanouptime(&ts);
1147 		cur->rt_cur = t4_get_ns_timestamp(&ts);
1148 		sc->cal_count++;
1149 		goto done;
1150 	}
1151 	nex->hw_prev = cur->hw_cur;
1152 	nex->rt_prev = cur->rt_cur;
1153 	KASSERT((hw_off_limits(sc) == 0), ("hw_off_limits at t4_calibtration"));
1154 	nex->hw_cur = t4_read_reg64(sc, A_SGE_TIMESTAMP_LO);
1155 	nanouptime(&ts);
1156 	nex->rt_cur = t4_get_ns_timestamp(&ts);
1157 	if ((nex->hw_cur - nex->hw_prev) == 0) {
1158 		/* The clock is not advancing? */
1159 		sc->cal_count = 0;
1160 		atomic_store_rel_int(&cur->gen, 0);
1161 		goto done;
1162 	}
1163 	atomic_store_rel_int(&cur->gen, 0);
1164 	sc->cal_current = next_up;
1165 	sc->cal_gen++;
1166 	atomic_store_rel_int(&nex->gen, sc->cal_gen);
1167 	if (sc->cal_count < t4_fast_2_normal)
1168 		sc->cal_count++;
1169 done:
1170 	callout_reset_sbt_curcpu(&sc->cal_callout,
1171 				 ((sc->cal_count < t4_fast_2_normal)  ?
1172 				 t4_clocksync_fast : t4_clocksync_normal) * SBT_1S, 0,
1173 				 t4_calibration, sc, C_DIRECT_EXEC);
1174 }
1175 
1176 
1177 
1178 static void
1179 t4_calibration_start(struct adapter *sc)
1180 {
1181 	/*
1182 	 * Here if we have not done a calibration
1183 	 * then do so otherwise start the appropriate
1184 	 * timer.
1185 	 */
1186 	int i;
1187 
1188 	for (i = 0; i < CNT_CAL_INFO; i++) {
1189 		sc->cal_info[i].gen = 0;
1190 	}
1191 	sc->cal_current = 0;
1192 	sc->cal_count = 0;
1193 	sc->cal_gen = 0;
1194 	t4_calibration(sc);
1195 }
1196 
1197 static int
1198 t4_attach(device_t dev)
1199 {
1200 	struct adapter *sc;
1201 	int rc = 0, i, j, rqidx, tqidx, nports;
1202 	struct make_dev_args mda;
1203 	struct intrs_and_queues iaq;
1204 	struct sge *s;
1205 	uint32_t *buf;
1206 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1207 	int ofld_tqidx;
1208 #endif
1209 #ifdef TCP_OFFLOAD
1210 	int ofld_rqidx;
1211 #endif
1212 #ifdef DEV_NETMAP
1213 	int nm_rqidx, nm_tqidx;
1214 #endif
1215 	int num_vis;
1216 
1217 	sc = device_get_softc(dev);
1218 	sc->dev = dev;
1219 	sysctl_ctx_init(&sc->ctx);
1220 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1221 
1222 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1223 		t5_attribute_workaround(dev);
1224 	pci_enable_busmaster(dev);
1225 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1226 		uint32_t v;
1227 
1228 		pci_set_max_read_req(dev, 4096);
1229 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1230 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1231 		if (pcie_relaxed_ordering == 0 &&
1232 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1233 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1234 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1235 		} else if (pcie_relaxed_ordering == 1 &&
1236 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1237 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1238 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1239 		}
1240 	}
1241 
1242 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1243 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1244 	sc->traceq = -1;
1245 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1246 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1247 	    device_get_nameunit(dev));
1248 
1249 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1250 	    device_get_nameunit(dev));
1251 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1252 	t4_add_adapter(sc);
1253 
1254 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1255 	TAILQ_INIT(&sc->sfl);
1256 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1257 
1258 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1259 
1260 	sc->policy = NULL;
1261 	rw_init(&sc->policy_lock, "connection offload policy");
1262 
1263 	callout_init(&sc->ktls_tick, 1);
1264 
1265 	callout_init(&sc->cal_callout, 1);
1266 
1267 	refcount_init(&sc->vxlan_refcount, 0);
1268 
1269 	TASK_INIT(&sc->reset_task, 0, reset_adapter_task, sc);
1270 	TASK_INIT(&sc->fatal_error_task, 0, fatal_error_task, sc);
1271 
1272 	sc->ctrlq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1273 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1274 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1275 	sc->fwq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1276 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1277 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1278 
1279 	rc = t4_map_bars_0_and_4(sc);
1280 	if (rc != 0)
1281 		goto done; /* error message displayed already */
1282 
1283 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1284 
1285 	/* Prepare the adapter for operation. */
1286 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1287 	rc = -t4_prep_adapter(sc, buf);
1288 	free(buf, M_CXGBE);
1289 	if (rc != 0) {
1290 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1291 		goto done;
1292 	}
1293 
1294 	/*
1295 	 * This is the real PF# to which we're attaching.  Works from within PCI
1296 	 * passthrough environments too, where pci_get_function() could return a
1297 	 * different PF# depending on the passthrough configuration.  We need to
1298 	 * use the real PF# in all our communication with the firmware.
1299 	 */
1300 	j = t4_read_reg(sc, A_PL_WHOAMI);
1301 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1302 	sc->mbox = sc->pf;
1303 
1304 	t4_init_devnames(sc);
1305 	if (sc->names == NULL) {
1306 		rc = ENOTSUP;
1307 		goto done; /* error message displayed already */
1308 	}
1309 
1310 	/*
1311 	 * Do this really early, with the memory windows set up even before the
1312 	 * character device.  The userland tool's register i/o and mem read
1313 	 * will work even in "recovery mode".
1314 	 */
1315 	setup_memwin(sc);
1316 	if (t4_init_devlog_params(sc, 0) == 0)
1317 		fixup_devlog_params(sc);
1318 	make_dev_args_init(&mda);
1319 	mda.mda_devsw = &t4_cdevsw;
1320 	mda.mda_uid = UID_ROOT;
1321 	mda.mda_gid = GID_WHEEL;
1322 	mda.mda_mode = 0600;
1323 	mda.mda_si_drv1 = sc;
1324 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1325 	if (rc != 0)
1326 		device_printf(dev, "failed to create nexus char device: %d.\n",
1327 		    rc);
1328 
1329 	/* Go no further if recovery mode has been requested. */
1330 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1331 		device_printf(dev, "recovery mode.\n");
1332 		goto done;
1333 	}
1334 
1335 #if defined(__i386__)
1336 	if ((cpu_feature & CPUID_CX8) == 0) {
1337 		device_printf(dev, "64 bit atomics not available.\n");
1338 		rc = ENOTSUP;
1339 		goto done;
1340 	}
1341 #endif
1342 
1343 	/* Contact the firmware and try to become the master driver. */
1344 	rc = contact_firmware(sc);
1345 	if (rc != 0)
1346 		goto done; /* error message displayed already */
1347 	MPASS(sc->flags & FW_OK);
1348 
1349 	rc = get_params__pre_init(sc);
1350 	if (rc != 0)
1351 		goto done; /* error message displayed already */
1352 
1353 	if (sc->flags & MASTER_PF) {
1354 		rc = partition_resources(sc);
1355 		if (rc != 0)
1356 			goto done; /* error message displayed already */
1357 		t4_intr_clear(sc);
1358 	}
1359 
1360 	rc = get_params__post_init(sc);
1361 	if (rc != 0)
1362 		goto done; /* error message displayed already */
1363 
1364 	rc = set_params__post_init(sc);
1365 	if (rc != 0)
1366 		goto done; /* error message displayed already */
1367 
1368 	rc = t4_map_bar_2(sc);
1369 	if (rc != 0)
1370 		goto done; /* error message displayed already */
1371 
1372 	rc = t4_create_dma_tag(sc);
1373 	if (rc != 0)
1374 		goto done; /* error message displayed already */
1375 
1376 	/*
1377 	 * First pass over all the ports - allocate VIs and initialize some
1378 	 * basic parameters like mac address, port type, etc.
1379 	 */
1380 	for_each_port(sc, i) {
1381 		struct port_info *pi;
1382 
1383 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1384 		sc->port[i] = pi;
1385 
1386 		/* These must be set before t4_port_init */
1387 		pi->adapter = sc;
1388 		pi->port_id = i;
1389 		/*
1390 		 * XXX: vi[0] is special so we can't delay this allocation until
1391 		 * pi->nvi's final value is known.
1392 		 */
1393 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1394 		    M_ZERO | M_WAITOK);
1395 
1396 		/*
1397 		 * Allocate the "main" VI and initialize parameters
1398 		 * like mac addr.
1399 		 */
1400 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1401 		if (rc != 0) {
1402 			device_printf(dev, "unable to initialize port %d: %d\n",
1403 			    i, rc);
1404 			free(pi->vi, M_CXGBE);
1405 			free(pi, M_CXGBE);
1406 			sc->port[i] = NULL;
1407 			goto done;
1408 		}
1409 
1410 		if (is_bt(pi->port_type))
1411 			setbit(&sc->bt_map, pi->tx_chan);
1412 		else
1413 			MPASS(!isset(&sc->bt_map, pi->tx_chan));
1414 
1415 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1416 		    device_get_nameunit(dev), i);
1417 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1418 		sc->chan_map[pi->tx_chan] = i;
1419 
1420 		/*
1421 		 * The MPS counter for FCS errors doesn't work correctly on the
1422 		 * T6 so we use the MAC counter here.  Which MAC is in use
1423 		 * depends on the link settings which will be known when the
1424 		 * link comes up.
1425 		 */
1426 		if (is_t6(sc)) {
1427 			pi->fcs_reg = -1;
1428 		} else if (is_t4(sc)) {
1429 			pi->fcs_reg = PORT_REG(pi->tx_chan,
1430 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1431 		} else {
1432 			pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
1433 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1434 		}
1435 		pi->fcs_base = 0;
1436 
1437 		/* All VIs on this port share this media. */
1438 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1439 		    cxgbe_media_status);
1440 
1441 		PORT_LOCK(pi);
1442 		init_link_config(pi);
1443 		fixup_link_config(pi);
1444 		build_medialist(pi);
1445 		if (fixed_ifmedia(pi))
1446 			pi->flags |= FIXED_IFMEDIA;
1447 		PORT_UNLOCK(pi);
1448 
1449 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1450 		    t4_ifnet_unit(sc, pi));
1451 		if (pi->dev == NULL) {
1452 			device_printf(dev,
1453 			    "failed to add device for port %d.\n", i);
1454 			rc = ENXIO;
1455 			goto done;
1456 		}
1457 		pi->vi[0].dev = pi->dev;
1458 		device_set_softc(pi->dev, pi);
1459 	}
1460 
1461 	/*
1462 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1463 	 */
1464 	nports = sc->params.nports;
1465 	rc = cfg_itype_and_nqueues(sc, &iaq);
1466 	if (rc != 0)
1467 		goto done; /* error message displayed already */
1468 
1469 	num_vis = iaq.num_vis;
1470 	sc->intr_type = iaq.intr_type;
1471 	sc->intr_count = iaq.nirq;
1472 
1473 	s = &sc->sge;
1474 	s->nrxq = nports * iaq.nrxq;
1475 	s->ntxq = nports * iaq.ntxq;
1476 	if (num_vis > 1) {
1477 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1478 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1479 	}
1480 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1481 	s->neq += nports;		/* ctrl queues: 1 per port */
1482 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1483 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1484 	if (is_offload(sc) || is_ethoffload(sc)) {
1485 		s->nofldtxq = nports * iaq.nofldtxq;
1486 		if (num_vis > 1)
1487 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1488 		s->neq += s->nofldtxq;
1489 
1490 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1491 		    M_CXGBE, M_ZERO | M_WAITOK);
1492 	}
1493 #endif
1494 #ifdef TCP_OFFLOAD
1495 	if (is_offload(sc)) {
1496 		s->nofldrxq = nports * iaq.nofldrxq;
1497 		if (num_vis > 1)
1498 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1499 		s->neq += s->nofldrxq;	/* free list */
1500 		s->niq += s->nofldrxq;
1501 
1502 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1503 		    M_CXGBE, M_ZERO | M_WAITOK);
1504 	}
1505 #endif
1506 #ifdef DEV_NETMAP
1507 	s->nnmrxq = 0;
1508 	s->nnmtxq = 0;
1509 	if (t4_native_netmap & NN_MAIN_VI) {
1510 		s->nnmrxq += nports * iaq.nnmrxq;
1511 		s->nnmtxq += nports * iaq.nnmtxq;
1512 	}
1513 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1514 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1515 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1516 	}
1517 	s->neq += s->nnmtxq + s->nnmrxq;
1518 	s->niq += s->nnmrxq;
1519 
1520 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1521 	    M_CXGBE, M_ZERO | M_WAITOK);
1522 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1523 	    M_CXGBE, M_ZERO | M_WAITOK);
1524 #endif
1525 	MPASS(s->niq <= s->iqmap_sz);
1526 	MPASS(s->neq <= s->eqmap_sz);
1527 
1528 	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1529 	    M_ZERO | M_WAITOK);
1530 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1531 	    M_ZERO | M_WAITOK);
1532 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1533 	    M_ZERO | M_WAITOK);
1534 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1535 	    M_ZERO | M_WAITOK);
1536 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1537 	    M_ZERO | M_WAITOK);
1538 
1539 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1540 	    M_ZERO | M_WAITOK);
1541 
1542 	t4_init_l2t(sc, M_WAITOK);
1543 	t4_init_smt(sc, M_WAITOK);
1544 	t4_init_tx_sched(sc);
1545 	t4_init_atid_table(sc);
1546 #ifdef RATELIMIT
1547 	t4_init_etid_table(sc);
1548 #endif
1549 #ifdef INET6
1550 	t4_init_clip_table(sc);
1551 #endif
1552 	if (sc->vres.key.size != 0)
1553 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1554 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1555 
1556 	/*
1557 	 * Second pass over the ports.  This time we know the number of rx and
1558 	 * tx queues that each port should get.
1559 	 */
1560 	rqidx = tqidx = 0;
1561 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1562 	ofld_tqidx = 0;
1563 #endif
1564 #ifdef TCP_OFFLOAD
1565 	ofld_rqidx = 0;
1566 #endif
1567 #ifdef DEV_NETMAP
1568 	nm_rqidx = nm_tqidx = 0;
1569 #endif
1570 	for_each_port(sc, i) {
1571 		struct port_info *pi = sc->port[i];
1572 		struct vi_info *vi;
1573 
1574 		if (pi == NULL)
1575 			continue;
1576 
1577 		pi->nvi = num_vis;
1578 		for_each_vi(pi, j, vi) {
1579 			vi->pi = pi;
1580 			vi->adapter = sc;
1581 			vi->first_intr = -1;
1582 			vi->qsize_rxq = t4_qsize_rxq;
1583 			vi->qsize_txq = t4_qsize_txq;
1584 
1585 			vi->first_rxq = rqidx;
1586 			vi->first_txq = tqidx;
1587 			vi->tmr_idx = t4_tmr_idx;
1588 			vi->pktc_idx = t4_pktc_idx;
1589 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1590 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1591 
1592 			rqidx += vi->nrxq;
1593 			tqidx += vi->ntxq;
1594 
1595 			if (j == 0 && vi->ntxq > 1)
1596 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1597 			else
1598 				vi->rsrv_noflowq = 0;
1599 
1600 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1601 			vi->first_ofld_txq = ofld_tqidx;
1602 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1603 			ofld_tqidx += vi->nofldtxq;
1604 #endif
1605 #ifdef TCP_OFFLOAD
1606 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1607 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1608 			vi->first_ofld_rxq = ofld_rqidx;
1609 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1610 
1611 			ofld_rqidx += vi->nofldrxq;
1612 #endif
1613 #ifdef DEV_NETMAP
1614 			vi->first_nm_rxq = nm_rqidx;
1615 			vi->first_nm_txq = nm_tqidx;
1616 			if (j == 0) {
1617 				vi->nnmrxq = iaq.nnmrxq;
1618 				vi->nnmtxq = iaq.nnmtxq;
1619 			} else {
1620 				vi->nnmrxq = iaq.nnmrxq_vi;
1621 				vi->nnmtxq = iaq.nnmtxq_vi;
1622 			}
1623 			nm_rqidx += vi->nnmrxq;
1624 			nm_tqidx += vi->nnmtxq;
1625 #endif
1626 		}
1627 	}
1628 
1629 	rc = t4_setup_intr_handlers(sc);
1630 	if (rc != 0) {
1631 		device_printf(dev,
1632 		    "failed to setup interrupt handlers: %d\n", rc);
1633 		goto done;
1634 	}
1635 
1636 	rc = bus_generic_probe(dev);
1637 	if (rc != 0) {
1638 		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1639 		goto done;
1640 	}
1641 
1642 	/*
1643 	 * Ensure thread-safe mailbox access (in debug builds).
1644 	 *
1645 	 * So far this was the only thread accessing the mailbox but various
1646 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1647 	 * will access the mailbox from different threads.
1648 	 */
1649 	sc->flags |= CHK_MBOX_ACCESS;
1650 
1651 	rc = bus_generic_attach(dev);
1652 	if (rc != 0) {
1653 		device_printf(dev,
1654 		    "failed to attach all child ports: %d\n", rc);
1655 		goto done;
1656 	}
1657 	t4_calibration_start(sc);
1658 
1659 	device_printf(dev,
1660 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1661 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1662 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1663 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1664 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1665 
1666 	t4_set_desc(sc);
1667 
1668 	notify_siblings(dev, 0);
1669 
1670 done:
1671 	if (rc != 0 && sc->cdev) {
1672 		/* cdev was created and so cxgbetool works; recover that way. */
1673 		device_printf(dev,
1674 		    "error during attach, adapter is now in recovery mode.\n");
1675 		rc = 0;
1676 	}
1677 
1678 	if (rc != 0)
1679 		t4_detach_common(dev);
1680 	else
1681 		t4_sysctls(sc);
1682 
1683 	return (rc);
1684 }
1685 
1686 static int
1687 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1688 {
1689 	struct adapter *sc;
1690 	struct port_info *pi;
1691 	int i;
1692 
1693 	sc = device_get_softc(bus);
1694 	for_each_port(sc, i) {
1695 		pi = sc->port[i];
1696 		if (pi != NULL && pi->dev == dev) {
1697 			sbuf_printf(sb, "port=%d", pi->port_id);
1698 			break;
1699 		}
1700 	}
1701 	return (0);
1702 }
1703 
1704 static int
1705 t4_ready(device_t dev)
1706 {
1707 	struct adapter *sc;
1708 
1709 	sc = device_get_softc(dev);
1710 	if (sc->flags & FW_OK)
1711 		return (0);
1712 	return (ENXIO);
1713 }
1714 
1715 static int
1716 t4_read_port_device(device_t dev, int port, device_t *child)
1717 {
1718 	struct adapter *sc;
1719 	struct port_info *pi;
1720 
1721 	sc = device_get_softc(dev);
1722 	if (port < 0 || port >= MAX_NPORTS)
1723 		return (EINVAL);
1724 	pi = sc->port[port];
1725 	if (pi == NULL || pi->dev == NULL)
1726 		return (ENXIO);
1727 	*child = pi->dev;
1728 	return (0);
1729 }
1730 
1731 static int
1732 notify_siblings(device_t dev, int detaching)
1733 {
1734 	device_t sibling;
1735 	int error, i;
1736 
1737 	error = 0;
1738 	for (i = 0; i < PCI_FUNCMAX; i++) {
1739 		if (i == pci_get_function(dev))
1740 			continue;
1741 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1742 		    pci_get_slot(dev), i);
1743 		if (sibling == NULL || !device_is_attached(sibling))
1744 			continue;
1745 		if (detaching)
1746 			error = T4_DETACH_CHILD(sibling);
1747 		else
1748 			(void)T4_ATTACH_CHILD(sibling);
1749 		if (error)
1750 			break;
1751 	}
1752 	return (error);
1753 }
1754 
1755 /*
1756  * Idempotent
1757  */
1758 static int
1759 t4_detach(device_t dev)
1760 {
1761 	int rc;
1762 
1763 	rc = notify_siblings(dev, 1);
1764 	if (rc) {
1765 		device_printf(dev,
1766 		    "failed to detach sibling devices: %d\n", rc);
1767 		return (rc);
1768 	}
1769 
1770 	return (t4_detach_common(dev));
1771 }
1772 
1773 int
1774 t4_detach_common(device_t dev)
1775 {
1776 	struct adapter *sc;
1777 	struct port_info *pi;
1778 	int i, rc;
1779 
1780 	sc = device_get_softc(dev);
1781 
1782 #ifdef TCP_OFFLOAD
1783 	rc = t4_deactivate_all_uld(sc);
1784 	if (rc) {
1785 		device_printf(dev,
1786 		    "failed to detach upper layer drivers: %d\n", rc);
1787 		return (rc);
1788 	}
1789 #endif
1790 
1791 	if (sc->cdev) {
1792 		destroy_dev(sc->cdev);
1793 		sc->cdev = NULL;
1794 	}
1795 
1796 	sx_xlock(&t4_list_lock);
1797 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1798 	sx_xunlock(&t4_list_lock);
1799 
1800 	sc->flags &= ~CHK_MBOX_ACCESS;
1801 	if (sc->flags & FULL_INIT_DONE) {
1802 		if (!(sc->flags & IS_VF))
1803 			t4_intr_disable(sc);
1804 	}
1805 
1806 	if (device_is_attached(dev)) {
1807 		rc = bus_generic_detach(dev);
1808 		if (rc) {
1809 			device_printf(dev,
1810 			    "failed to detach child devices: %d\n", rc);
1811 			return (rc);
1812 		}
1813 	}
1814 
1815 	for (i = 0; i < sc->intr_count; i++)
1816 		t4_free_irq(sc, &sc->irq[i]);
1817 
1818 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1819 		t4_free_tx_sched(sc);
1820 
1821 	for (i = 0; i < MAX_NPORTS; i++) {
1822 		pi = sc->port[i];
1823 		if (pi) {
1824 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1825 			if (pi->dev)
1826 				device_delete_child(dev, pi->dev);
1827 
1828 			mtx_destroy(&pi->pi_lock);
1829 			free(pi->vi, M_CXGBE);
1830 			free(pi, M_CXGBE);
1831 		}
1832 	}
1833 	callout_stop(&sc->cal_callout);
1834 	callout_drain(&sc->cal_callout);
1835 	device_delete_children(dev);
1836 	sysctl_ctx_free(&sc->ctx);
1837 	adapter_full_uninit(sc);
1838 
1839 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1840 		t4_fw_bye(sc, sc->mbox);
1841 
1842 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1843 		pci_release_msi(dev);
1844 
1845 	if (sc->regs_res)
1846 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1847 		    sc->regs_res);
1848 
1849 	if (sc->udbs_res)
1850 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1851 		    sc->udbs_res);
1852 
1853 	if (sc->msix_res)
1854 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1855 		    sc->msix_res);
1856 
1857 	if (sc->l2t)
1858 		t4_free_l2t(sc->l2t);
1859 	if (sc->smt)
1860 		t4_free_smt(sc->smt);
1861 	t4_free_atid_table(sc);
1862 #ifdef RATELIMIT
1863 	t4_free_etid_table(sc);
1864 #endif
1865 	if (sc->key_map)
1866 		vmem_destroy(sc->key_map);
1867 #ifdef INET6
1868 	t4_destroy_clip_table(sc);
1869 #endif
1870 
1871 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1872 	free(sc->sge.ofld_txq, M_CXGBE);
1873 #endif
1874 #ifdef TCP_OFFLOAD
1875 	free(sc->sge.ofld_rxq, M_CXGBE);
1876 #endif
1877 #ifdef DEV_NETMAP
1878 	free(sc->sge.nm_rxq, M_CXGBE);
1879 	free(sc->sge.nm_txq, M_CXGBE);
1880 #endif
1881 	free(sc->irq, M_CXGBE);
1882 	free(sc->sge.rxq, M_CXGBE);
1883 	free(sc->sge.txq, M_CXGBE);
1884 	free(sc->sge.ctrlq, M_CXGBE);
1885 	free(sc->sge.iqmap, M_CXGBE);
1886 	free(sc->sge.eqmap, M_CXGBE);
1887 	free(sc->tids.ftid_tab, M_CXGBE);
1888 	free(sc->tids.hpftid_tab, M_CXGBE);
1889 	free_hftid_hash(&sc->tids);
1890 	free(sc->tids.tid_tab, M_CXGBE);
1891 	free(sc->tt.tls_rx_ports, M_CXGBE);
1892 	t4_destroy_dma_tag(sc);
1893 
1894 	callout_drain(&sc->ktls_tick);
1895 	callout_drain(&sc->sfl_callout);
1896 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1897 		mtx_destroy(&sc->tids.ftid_lock);
1898 		cv_destroy(&sc->tids.ftid_cv);
1899 	}
1900 	if (mtx_initialized(&sc->tids.atid_lock))
1901 		mtx_destroy(&sc->tids.atid_lock);
1902 	if (mtx_initialized(&sc->ifp_lock))
1903 		mtx_destroy(&sc->ifp_lock);
1904 
1905 	if (rw_initialized(&sc->policy_lock)) {
1906 		rw_destroy(&sc->policy_lock);
1907 #ifdef TCP_OFFLOAD
1908 		if (sc->policy != NULL)
1909 			free_offload_policy(sc->policy);
1910 #endif
1911 	}
1912 
1913 	for (i = 0; i < NUM_MEMWIN; i++) {
1914 		struct memwin *mw = &sc->memwin[i];
1915 
1916 		if (rw_initialized(&mw->mw_lock))
1917 			rw_destroy(&mw->mw_lock);
1918 	}
1919 
1920 	mtx_destroy(&sc->sfl_lock);
1921 	mtx_destroy(&sc->reg_lock);
1922 	mtx_destroy(&sc->sc_lock);
1923 
1924 	bzero(sc, sizeof(*sc));
1925 
1926 	return (0);
1927 }
1928 
1929 static inline bool
1930 ok_to_reset(struct adapter *sc)
1931 {
1932 	struct tid_info *t = &sc->tids;
1933 	struct port_info *pi;
1934 	struct vi_info *vi;
1935 	int i, j;
1936 	int caps = IFCAP_TOE | IFCAP_NETMAP | IFCAP_TXRTLMT;
1937 
1938 	if (is_t6(sc))
1939 		caps |= IFCAP_TXTLS;
1940 
1941 	ASSERT_SYNCHRONIZED_OP(sc);
1942 	MPASS(!(sc->flags & IS_VF));
1943 
1944 	for_each_port(sc, i) {
1945 		pi = sc->port[i];
1946 		for_each_vi(pi, j, vi) {
1947 			if (vi->ifp->if_capenable & caps)
1948 				return (false);
1949 		}
1950 	}
1951 
1952 	if (atomic_load_int(&t->tids_in_use) > 0)
1953 		return (false);
1954 	if (atomic_load_int(&t->stids_in_use) > 0)
1955 		return (false);
1956 	if (atomic_load_int(&t->atids_in_use) > 0)
1957 		return (false);
1958 	if (atomic_load_int(&t->ftids_in_use) > 0)
1959 		return (false);
1960 	if (atomic_load_int(&t->hpftids_in_use) > 0)
1961 		return (false);
1962 	if (atomic_load_int(&t->etids_in_use) > 0)
1963 		return (false);
1964 
1965 	return (true);
1966 }
1967 
1968 static inline int
1969 stop_adapter(struct adapter *sc)
1970 {
1971 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_STOPPED)))
1972 		return (1);		/* Already stopped. */
1973 	return (t4_shutdown_adapter(sc));
1974 }
1975 
1976 static int
1977 t4_suspend(device_t dev)
1978 {
1979 	struct adapter *sc = device_get_softc(dev);
1980 	struct port_info *pi;
1981 	struct vi_info *vi;
1982 	struct ifnet *ifp;
1983 	struct sge_rxq *rxq;
1984 	struct sge_txq *txq;
1985 	struct sge_wrq *wrq;
1986 #ifdef TCP_OFFLOAD
1987 	struct sge_ofld_rxq *ofld_rxq;
1988 #endif
1989 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1990 	struct sge_ofld_txq *ofld_txq;
1991 #endif
1992 	int rc, i, j, k;
1993 
1994 	CH_ALERT(sc, "suspend requested\n");
1995 
1996 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4sus");
1997 	if (rc != 0)
1998 		return (ENXIO);
1999 
2000 	/* XXX: Can the kernel call suspend repeatedly without resume? */
2001 	MPASS(!hw_off_limits(sc));
2002 
2003 	if (!ok_to_reset(sc)) {
2004 		/* XXX: should list what resource is preventing suspend. */
2005 		CH_ERR(sc, "not safe to suspend.\n");
2006 		rc = EBUSY;
2007 		goto done;
2008 	}
2009 
2010 	/* No more DMA or interrupts. */
2011 	stop_adapter(sc);
2012 	/* Quiesce all activity. */
2013 	for_each_port(sc, i) {
2014 		pi = sc->port[i];
2015 		pi->vxlan_tcam_entry = false;
2016 
2017 		PORT_LOCK(pi);
2018 		if (pi->up_vis > 0) {
2019 			/*
2020 			 * t4_shutdown_adapter has already shut down all the
2021 			 * PHYs but it also disables interrupts and DMA so there
2022 			 * won't be a link interrupt.  So we update the state
2023 			 * manually and inform the kernel.
2024 			 */
2025 			pi->link_cfg.link_ok = false;
2026 			t4_os_link_changed(pi);
2027 		}
2028 		PORT_UNLOCK(pi);
2029 
2030 		for_each_vi(pi, j, vi) {
2031 			vi->xact_addr_filt = -1;
2032 			mtx_lock(&vi->tick_mtx);
2033 			vi->flags |= VI_SKIP_STATS;
2034 			mtx_unlock(&vi->tick_mtx);
2035 			if (!(vi->flags & VI_INIT_DONE))
2036 				continue;
2037 
2038 			ifp = vi->ifp;
2039 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2040 				mtx_lock(&vi->tick_mtx);
2041 				callout_stop(&vi->tick);
2042 				mtx_unlock(&vi->tick_mtx);
2043 				callout_drain(&vi->tick);
2044 			}
2045 
2046 			/*
2047 			 * Note that the HW is not available.
2048 			 */
2049 			for_each_txq(vi, k, txq) {
2050 				TXQ_LOCK(txq);
2051 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
2052 				TXQ_UNLOCK(txq);
2053 			}
2054 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2055 			for_each_ofld_txq(vi, k, ofld_txq) {
2056 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
2057 			}
2058 #endif
2059 			for_each_rxq(vi, k, rxq) {
2060 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2061 			}
2062 #if defined(TCP_OFFLOAD)
2063 			for_each_ofld_rxq(vi, k, ofld_rxq) {
2064 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2065 			}
2066 #endif
2067 
2068 			quiesce_vi(vi);
2069 		}
2070 
2071 		if (sc->flags & FULL_INIT_DONE) {
2072 			/* Control queue */
2073 			wrq = &sc->sge.ctrlq[i];
2074 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
2075 			quiesce_wrq(wrq);
2076 		}
2077 	}
2078 	if (sc->flags & FULL_INIT_DONE) {
2079 		/* Firmware event queue */
2080 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
2081 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
2082 	}
2083 
2084 	/* Stop calibration */
2085 	callout_stop(&sc->cal_callout);
2086 	callout_drain(&sc->cal_callout);
2087 
2088 	/* Mark the adapter totally off limits. */
2089 	mtx_lock(&sc->reg_lock);
2090 	atomic_set_int(&sc->error_flags, HW_OFF_LIMITS);
2091 	sc->flags &= ~(FW_OK | MASTER_PF);
2092 	sc->reset_thread = NULL;
2093 	mtx_unlock(&sc->reg_lock);
2094 
2095 	if (t4_clock_gate_on_suspend) {
2096 		t4_set_reg_field(sc, A_PMU_PART_CG_PWRMODE, F_MA_PART_CGEN |
2097 		    F_LE_PART_CGEN | F_EDC1_PART_CGEN | F_EDC0_PART_CGEN |
2098 		    F_TP_PART_CGEN | F_PDP_PART_CGEN | F_SGE_PART_CGEN, 0);
2099 	}
2100 
2101 	CH_ALERT(sc, "suspend completed.\n");
2102 done:
2103 	end_synchronized_op(sc, 0);
2104 	return (rc);
2105 }
2106 
2107 struct adapter_pre_reset_state {
2108 	u_int flags;
2109 	uint16_t nbmcaps;
2110 	uint16_t linkcaps;
2111 	uint16_t switchcaps;
2112 	uint16_t niccaps;
2113 	uint16_t toecaps;
2114 	uint16_t rdmacaps;
2115 	uint16_t cryptocaps;
2116 	uint16_t iscsicaps;
2117 	uint16_t fcoecaps;
2118 
2119 	u_int cfcsum;
2120 	char cfg_file[32];
2121 
2122 	struct adapter_params params;
2123 	struct t4_virt_res vres;
2124 	struct tid_info tids;
2125 	struct sge sge;
2126 
2127 	int rawf_base;
2128 	int nrawf;
2129 
2130 };
2131 
2132 static void
2133 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2134 {
2135 
2136 	ASSERT_SYNCHRONIZED_OP(sc);
2137 
2138 	o->flags = sc->flags;
2139 
2140 	o->nbmcaps =  sc->nbmcaps;
2141 	o->linkcaps = sc->linkcaps;
2142 	o->switchcaps = sc->switchcaps;
2143 	o->niccaps = sc->niccaps;
2144 	o->toecaps = sc->toecaps;
2145 	o->rdmacaps = sc->rdmacaps;
2146 	o->cryptocaps = sc->cryptocaps;
2147 	o->iscsicaps = sc->iscsicaps;
2148 	o->fcoecaps = sc->fcoecaps;
2149 
2150 	o->cfcsum = sc->cfcsum;
2151 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2152 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2153 
2154 	o->params = sc->params;
2155 	o->vres = sc->vres;
2156 	o->tids = sc->tids;
2157 	o->sge = sc->sge;
2158 
2159 	o->rawf_base = sc->rawf_base;
2160 	o->nrawf = sc->nrawf;
2161 }
2162 
2163 static int
2164 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2165 {
2166 	int rc = 0;
2167 
2168 	ASSERT_SYNCHRONIZED_OP(sc);
2169 
2170 	/* Capabilities */
2171 #define COMPARE_CAPS(c) do { \
2172 	if (o->c##caps != sc->c##caps) { \
2173 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2174 		    sc->c##caps); \
2175 		rc = EINVAL; \
2176 	} \
2177 } while (0)
2178 	COMPARE_CAPS(nbm);
2179 	COMPARE_CAPS(link);
2180 	COMPARE_CAPS(switch);
2181 	COMPARE_CAPS(nic);
2182 	COMPARE_CAPS(toe);
2183 	COMPARE_CAPS(rdma);
2184 	COMPARE_CAPS(crypto);
2185 	COMPARE_CAPS(iscsi);
2186 	COMPARE_CAPS(fcoe);
2187 #undef COMPARE_CAPS
2188 
2189 	/* Firmware config file */
2190 	if (o->cfcsum != sc->cfcsum) {
2191 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2192 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2193 		rc = EINVAL;
2194 	}
2195 
2196 #define COMPARE_PARAM(p, name) do { \
2197 	if (o->p != sc->p) { \
2198 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2199 		rc = EINVAL; \
2200 	} \
2201 } while (0)
2202 	COMPARE_PARAM(sge.iq_start, iq_start);
2203 	COMPARE_PARAM(sge.eq_start, eq_start);
2204 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2205 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2206 	COMPARE_PARAM(tids.nftids, nftids);
2207 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2208 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2209 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2210 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2211 	COMPARE_PARAM(tids.tid_base, tid_base);
2212 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2213 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2214 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2215 	COMPARE_PARAM(rawf_base, rawf_base);
2216 	COMPARE_PARAM(nrawf, nrawf);
2217 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2218 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2219 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2220 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2221 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2222 	COMPARE_PARAM(tids.ntids, ntids);
2223 	COMPARE_PARAM(tids.etid_base, etid_base);
2224 	COMPARE_PARAM(tids.etid_end, etid_end);
2225 	COMPARE_PARAM(tids.netids, netids);
2226 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2227 	COMPARE_PARAM(params.ethoffload, ethoffload);
2228 	COMPARE_PARAM(tids.natids, natids);
2229 	COMPARE_PARAM(tids.stid_base, stid_base);
2230 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2231 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2232 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2233 	COMPARE_PARAM(vres.stag.start, stag_start);
2234 	COMPARE_PARAM(vres.stag.size, stag_size);
2235 	COMPARE_PARAM(vres.rq.start, rq_start);
2236 	COMPARE_PARAM(vres.rq.size, rq_size);
2237 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2238 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2239 	COMPARE_PARAM(vres.qp.start, qp_start);
2240 	COMPARE_PARAM(vres.qp.size, qp_size);
2241 	COMPARE_PARAM(vres.cq.start, cq_start);
2242 	COMPARE_PARAM(vres.cq.size, cq_size);
2243 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2244 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2245 	COMPARE_PARAM(vres.srq.start, srq_start);
2246 	COMPARE_PARAM(vres.srq.size, srq_size);
2247 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2248 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2249 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2250 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2251 	COMPARE_PARAM(vres.key.start, key_start);
2252 	COMPARE_PARAM(vres.key.size, key_size);
2253 #undef COMPARE_PARAM
2254 
2255 	return (rc);
2256 }
2257 
2258 static int
2259 t4_resume(device_t dev)
2260 {
2261 	struct adapter *sc = device_get_softc(dev);
2262 	struct adapter_pre_reset_state *old_state = NULL;
2263 	struct port_info *pi;
2264 	struct vi_info *vi;
2265 	struct ifnet *ifp;
2266 	struct sge_txq *txq;
2267 	int rc, i, j, k;
2268 
2269 	CH_ALERT(sc, "resume requested.\n");
2270 
2271 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4res");
2272 	if (rc != 0)
2273 		return (ENXIO);
2274 	MPASS(hw_off_limits(sc));
2275 	MPASS((sc->flags & FW_OK) == 0);
2276 	MPASS((sc->flags & MASTER_PF) == 0);
2277 	MPASS(sc->reset_thread == NULL);
2278 	sc->reset_thread = curthread;
2279 
2280 	/* Register access is expected to work by the time we're here. */
2281 	if (t4_read_reg(sc, A_PL_WHOAMI) == 0xffffffff) {
2282 		CH_ERR(sc, "%s: can't read device registers\n", __func__);
2283 		rc = ENXIO;
2284 		goto done;
2285 	}
2286 
2287 	/* Note that HW_OFF_LIMITS is cleared a bit later. */
2288 	atomic_clear_int(&sc->error_flags, ADAP_FATAL_ERR | ADAP_STOPPED);
2289 
2290 	/* Restore memory window. */
2291 	setup_memwin(sc);
2292 
2293 	/* Go no further if recovery mode has been requested. */
2294 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2295 		CH_ALERT(sc, "recovery mode on resume.\n");
2296 		rc = 0;
2297 		mtx_lock(&sc->reg_lock);
2298 		atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2299 		mtx_unlock(&sc->reg_lock);
2300 		goto done;
2301 	}
2302 
2303 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2304 	save_caps_and_params(sc, old_state);
2305 
2306 	/* Reestablish contact with firmware and become the primary PF. */
2307 	rc = contact_firmware(sc);
2308 	if (rc != 0)
2309 		goto done; /* error message displayed already */
2310 	MPASS(sc->flags & FW_OK);
2311 
2312 	if (sc->flags & MASTER_PF) {
2313 		rc = partition_resources(sc);
2314 		if (rc != 0)
2315 			goto done; /* error message displayed already */
2316 		t4_intr_clear(sc);
2317 	}
2318 
2319 	rc = get_params__post_init(sc);
2320 	if (rc != 0)
2321 		goto done; /* error message displayed already */
2322 
2323 	rc = set_params__post_init(sc);
2324 	if (rc != 0)
2325 		goto done; /* error message displayed already */
2326 
2327 	rc = compare_caps_and_params(sc, old_state);
2328 	if (rc != 0)
2329 		goto done; /* error message displayed already */
2330 
2331 	for_each_port(sc, i) {
2332 		pi = sc->port[i];
2333 		MPASS(pi != NULL);
2334 		MPASS(pi->vi != NULL);
2335 		MPASS(pi->vi[0].dev == pi->dev);
2336 
2337 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2338 		if (rc != 0) {
2339 			CH_ERR(sc,
2340 			    "failed to re-initialize port %d: %d\n", i, rc);
2341 			goto done;
2342 		}
2343 		MPASS(sc->chan_map[pi->tx_chan] == i);
2344 
2345 		PORT_LOCK(pi);
2346 		fixup_link_config(pi);
2347 		build_medialist(pi);
2348 		PORT_UNLOCK(pi);
2349 		for_each_vi(pi, j, vi) {
2350 			if (IS_MAIN_VI(vi))
2351 				continue;
2352 			rc = alloc_extra_vi(sc, pi, vi);
2353 			if (rc != 0) {
2354 				CH_ERR(vi,
2355 				    "failed to re-allocate extra VI: %d\n", rc);
2356 				goto done;
2357 			}
2358 		}
2359 	}
2360 
2361 	/*
2362 	 * Interrupts and queues are about to be enabled and other threads will
2363 	 * want to access the hardware too.  It is safe to do so.  Note that
2364 	 * this thread is still in the middle of a synchronized_op.
2365 	 */
2366 	mtx_lock(&sc->reg_lock);
2367 	atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2368 	mtx_unlock(&sc->reg_lock);
2369 
2370 	if (sc->flags & FULL_INIT_DONE) {
2371 		rc = adapter_full_init(sc);
2372 		if (rc != 0) {
2373 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2374 			goto done;
2375 		}
2376 
2377 		if (sc->vxlan_refcount > 0)
2378 			enable_vxlan_rx(sc);
2379 
2380 		for_each_port(sc, i) {
2381 			pi = sc->port[i];
2382 			for_each_vi(pi, j, vi) {
2383 				mtx_lock(&vi->tick_mtx);
2384 				vi->flags &= ~VI_SKIP_STATS;
2385 				mtx_unlock(&vi->tick_mtx);
2386 				if (!(vi->flags & VI_INIT_DONE))
2387 					continue;
2388 				rc = vi_full_init(vi);
2389 				if (rc != 0) {
2390 					CH_ERR(vi, "failed to re-initialize "
2391 					    "interface: %d\n", rc);
2392 					goto done;
2393 				}
2394 
2395 				ifp = vi->ifp;
2396 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2397 					continue;
2398 				/*
2399 				 * Note that we do not setup multicast addresses
2400 				 * in the first pass.  This ensures that the
2401 				 * unicast DMACs for all VIs on all ports get an
2402 				 * MPS TCAM entry.
2403 				 */
2404 				rc = update_mac_settings(ifp, XGMAC_ALL &
2405 				    ~XGMAC_MCADDRS);
2406 				if (rc != 0) {
2407 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2408 					goto done;
2409 				}
2410 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2411 				    true);
2412 				if (rc != 0) {
2413 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2414 					goto done;
2415 				}
2416 				for_each_txq(vi, k, txq) {
2417 					TXQ_LOCK(txq);
2418 					txq->eq.flags |= EQ_ENABLED;
2419 					TXQ_UNLOCK(txq);
2420 				}
2421 				mtx_lock(&vi->tick_mtx);
2422 				callout_schedule(&vi->tick, hz);
2423 				mtx_unlock(&vi->tick_mtx);
2424 			}
2425 			PORT_LOCK(pi);
2426 			if (pi->up_vis > 0) {
2427 				t4_update_port_info(pi);
2428 				fixup_link_config(pi);
2429 				build_medialist(pi);
2430 				apply_link_config(pi);
2431 				if (pi->link_cfg.link_ok)
2432 					t4_os_link_changed(pi);
2433 			}
2434 			PORT_UNLOCK(pi);
2435 		}
2436 
2437 		/* Now reprogram the L2 multicast addresses. */
2438 		for_each_port(sc, i) {
2439 			pi = sc->port[i];
2440 			for_each_vi(pi, j, vi) {
2441 				if (!(vi->flags & VI_INIT_DONE))
2442 					continue;
2443 				ifp = vi->ifp;
2444 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2445 					continue;
2446 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2447 				if (rc != 0) {
2448 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2449 					rc = 0;	/* carry on */
2450 				}
2451 			}
2452 		}
2453 	}
2454 
2455 	/* Reset all calibration */
2456 	t4_calibration_start(sc);
2457 
2458 done:
2459 	if (rc == 0) {
2460 		sc->incarnation++;
2461 		CH_ALERT(sc, "resume completed.\n");
2462 	}
2463 	end_synchronized_op(sc, 0);
2464 	free(old_state, M_CXGBE);
2465 	return (rc);
2466 }
2467 
2468 static int
2469 t4_reset_prepare(device_t dev, device_t child)
2470 {
2471 	struct adapter *sc = device_get_softc(dev);
2472 
2473 	CH_ALERT(sc, "reset_prepare.\n");
2474 	return (0);
2475 }
2476 
2477 static int
2478 t4_reset_post(device_t dev, device_t child)
2479 {
2480 	struct adapter *sc = device_get_softc(dev);
2481 
2482 	CH_ALERT(sc, "reset_post.\n");
2483 	return (0);
2484 }
2485 
2486 static int
2487 reset_adapter(struct adapter *sc)
2488 {
2489 	int rc, oldinc, error_flags;
2490 
2491 	CH_ALERT(sc, "reset requested.\n");
2492 
2493 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst1");
2494 	if (rc != 0)
2495 		return (EBUSY);
2496 
2497 	if (hw_off_limits(sc)) {
2498 		CH_ERR(sc, "adapter is suspended, use resume (not reset).\n");
2499 		rc = ENXIO;
2500 		goto done;
2501 	}
2502 
2503 	if (!ok_to_reset(sc)) {
2504 		/* XXX: should list what resource is preventing reset. */
2505 		CH_ERR(sc, "not safe to reset.\n");
2506 		rc = EBUSY;
2507 		goto done;
2508 	}
2509 
2510 done:
2511 	oldinc = sc->incarnation;
2512 	end_synchronized_op(sc, 0);
2513 	if (rc != 0)
2514 		return (rc);	/* Error logged already. */
2515 
2516 	atomic_add_int(&sc->num_resets, 1);
2517 	mtx_lock(&Giant);
2518 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2519 	mtx_unlock(&Giant);
2520 	if (rc != 0)
2521 		CH_ERR(sc, "bus_reset_child failed: %d.\n", rc);
2522 	else {
2523 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst2");
2524 		if (rc != 0)
2525 			return (EBUSY);
2526 		error_flags = atomic_load_int(&sc->error_flags);
2527 		if (sc->incarnation > oldinc && error_flags == 0) {
2528 			CH_ALERT(sc, "bus_reset_child succeeded.\n");
2529 		} else {
2530 			CH_ERR(sc, "adapter did not reset properly, flags "
2531 			    "0x%08x, error_flags 0x%08x.\n", sc->flags,
2532 			    error_flags);
2533 			rc = ENXIO;
2534 		}
2535 		end_synchronized_op(sc, 0);
2536 	}
2537 
2538 	return (rc);
2539 }
2540 
2541 static void
2542 reset_adapter_task(void *arg, int pending)
2543 {
2544 	/* XXX: t4_async_event here? */
2545 	reset_adapter(arg);
2546 }
2547 
2548 static int
2549 cxgbe_probe(device_t dev)
2550 {
2551 	char buf[128];
2552 	struct port_info *pi = device_get_softc(dev);
2553 
2554 	snprintf(buf, sizeof(buf), "port %d", pi->port_id);
2555 	device_set_desc_copy(dev, buf);
2556 
2557 	return (BUS_PROBE_DEFAULT);
2558 }
2559 
2560 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2561     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2562     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2563     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2564 #define T4_CAP_ENABLE (T4_CAP)
2565 
2566 static int
2567 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2568 {
2569 	struct ifnet *ifp;
2570 	struct sbuf *sb;
2571 	struct sysctl_ctx_list *ctx = &vi->ctx;
2572 	struct sysctl_oid_list *children;
2573 	struct pfil_head_args pa;
2574 	struct adapter *sc = vi->adapter;
2575 
2576 	sysctl_ctx_init(ctx);
2577 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2578 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2579 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2580 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2581 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2582 #ifdef DEV_NETMAP
2583 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2584 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2585 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2586 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2587 #endif
2588 #ifdef TCP_OFFLOAD
2589 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2590 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2591 #endif
2592 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2593 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2594 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2595 #endif
2596 
2597 	vi->xact_addr_filt = -1;
2598 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2599 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2600 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2601 		vi->flags |= TX_USES_VM_WR;
2602 
2603 	/* Allocate an ifnet and set it up */
2604 	ifp = if_alloc_dev(IFT_ETHER, dev);
2605 	if (ifp == NULL) {
2606 		device_printf(dev, "Cannot allocate ifnet\n");
2607 		return (ENOMEM);
2608 	}
2609 	vi->ifp = ifp;
2610 	ifp->if_softc = vi;
2611 
2612 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2613 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
2614 
2615 	ifp->if_init = cxgbe_init;
2616 	ifp->if_ioctl = cxgbe_ioctl;
2617 	ifp->if_transmit = cxgbe_transmit;
2618 	ifp->if_qflush = cxgbe_qflush;
2619 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2620 		ifp->if_get_counter = vi_get_counter;
2621 	else
2622 		ifp->if_get_counter = cxgbe_get_counter;
2623 #if defined(KERN_TLS) || defined(RATELIMIT)
2624 	ifp->if_snd_tag_alloc = cxgbe_snd_tag_alloc;
2625 #endif
2626 #ifdef RATELIMIT
2627 	ifp->if_ratelimit_query = cxgbe_ratelimit_query;
2628 #endif
2629 
2630 	ifp->if_capabilities = T4_CAP;
2631 	ifp->if_capenable = T4_CAP_ENABLE;
2632 	ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2633 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6;
2634 	if (chip_id(sc) >= CHELSIO_T6) {
2635 		ifp->if_capabilities |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2636 		ifp->if_capenable |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2637 		ifp->if_hwassist |= CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2638 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2639 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN;
2640 	}
2641 
2642 #ifdef TCP_OFFLOAD
2643 	if (vi->nofldrxq != 0)
2644 		ifp->if_capabilities |= IFCAP_TOE;
2645 #endif
2646 #ifdef RATELIMIT
2647 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2648 		ifp->if_capabilities |= IFCAP_TXRTLMT;
2649 		ifp->if_capenable |= IFCAP_TXRTLMT;
2650 	}
2651 #endif
2652 
2653 	ifp->if_hw_tsomax = IP_MAXPACKET;
2654 	if (vi->flags & TX_USES_VM_WR)
2655 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
2656 	else
2657 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
2658 #ifdef RATELIMIT
2659 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2660 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_EO_TSO;
2661 #endif
2662 	ifp->if_hw_tsomaxsegsize = 65536;
2663 #ifdef KERN_TLS
2664 	if (is_ktls(sc)) {
2665 		ifp->if_capabilities |= IFCAP_TXTLS;
2666 		if (sc->flags & KERN_TLS_ON || !is_t6(sc))
2667 			ifp->if_capenable |= IFCAP_TXTLS;
2668 	}
2669 #endif
2670 
2671 	ether_ifattach(ifp, vi->hw_addr);
2672 #ifdef DEV_NETMAP
2673 	if (vi->nnmrxq != 0)
2674 		cxgbe_nm_attach(vi);
2675 #endif
2676 	sb = sbuf_new_auto();
2677 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2678 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2679 	switch (ifp->if_capabilities & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2680 	case IFCAP_TOE:
2681 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2682 		break;
2683 	case IFCAP_TOE | IFCAP_TXRTLMT:
2684 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2685 		break;
2686 	case IFCAP_TXRTLMT:
2687 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2688 		break;
2689 	}
2690 #endif
2691 #ifdef TCP_OFFLOAD
2692 	if (ifp->if_capabilities & IFCAP_TOE)
2693 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2694 #endif
2695 #ifdef DEV_NETMAP
2696 	if (ifp->if_capabilities & IFCAP_NETMAP)
2697 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2698 		    vi->nnmtxq, vi->nnmrxq);
2699 #endif
2700 	sbuf_finish(sb);
2701 	device_printf(dev, "%s\n", sbuf_data(sb));
2702 	sbuf_delete(sb);
2703 
2704 	vi_sysctls(vi);
2705 
2706 	pa.pa_version = PFIL_VERSION;
2707 	pa.pa_flags = PFIL_IN;
2708 	pa.pa_type = PFIL_TYPE_ETHERNET;
2709 	pa.pa_headname = ifp->if_xname;
2710 	vi->pfil = pfil_head_register(&pa);
2711 
2712 	return (0);
2713 }
2714 
2715 static int
2716 cxgbe_attach(device_t dev)
2717 {
2718 	struct port_info *pi = device_get_softc(dev);
2719 	struct adapter *sc = pi->adapter;
2720 	struct vi_info *vi;
2721 	int i, rc;
2722 
2723 	sysctl_ctx_init(&pi->ctx);
2724 
2725 	rc = cxgbe_vi_attach(dev, &pi->vi[0]);
2726 	if (rc)
2727 		return (rc);
2728 
2729 	for_each_vi(pi, i, vi) {
2730 		if (i == 0)
2731 			continue;
2732 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
2733 		if (vi->dev == NULL) {
2734 			device_printf(dev, "failed to add VI %d\n", i);
2735 			continue;
2736 		}
2737 		device_set_softc(vi->dev, vi);
2738 	}
2739 
2740 	cxgbe_sysctls(pi);
2741 
2742 	bus_generic_attach(dev);
2743 
2744 	return (0);
2745 }
2746 
2747 static void
2748 cxgbe_vi_detach(struct vi_info *vi)
2749 {
2750 	struct ifnet *ifp = vi->ifp;
2751 
2752 	if (vi->pfil != NULL) {
2753 		pfil_head_unregister(vi->pfil);
2754 		vi->pfil = NULL;
2755 	}
2756 
2757 	ether_ifdetach(ifp);
2758 
2759 	/* Let detach proceed even if these fail. */
2760 #ifdef DEV_NETMAP
2761 	if (ifp->if_capabilities & IFCAP_NETMAP)
2762 		cxgbe_nm_detach(vi);
2763 #endif
2764 	cxgbe_uninit_synchronized(vi);
2765 	callout_drain(&vi->tick);
2766 	sysctl_ctx_free(&vi->ctx);
2767 	vi_full_uninit(vi);
2768 
2769 	if_free(vi->ifp);
2770 	vi->ifp = NULL;
2771 }
2772 
2773 static int
2774 cxgbe_detach(device_t dev)
2775 {
2776 	struct port_info *pi = device_get_softc(dev);
2777 	struct adapter *sc = pi->adapter;
2778 	int rc;
2779 
2780 	/* Detach the extra VIs first. */
2781 	rc = bus_generic_detach(dev);
2782 	if (rc)
2783 		return (rc);
2784 	device_delete_children(dev);
2785 
2786 	sysctl_ctx_free(&pi->ctx);
2787 	doom_vi(sc, &pi->vi[0]);
2788 
2789 	if (pi->flags & HAS_TRACEQ) {
2790 		sc->traceq = -1;	/* cloner should not create ifnet */
2791 		t4_tracer_port_detach(sc);
2792 	}
2793 
2794 	cxgbe_vi_detach(&pi->vi[0]);
2795 	ifmedia_removeall(&pi->media);
2796 
2797 	end_synchronized_op(sc, 0);
2798 
2799 	return (0);
2800 }
2801 
2802 static void
2803 cxgbe_init(void *arg)
2804 {
2805 	struct vi_info *vi = arg;
2806 	struct adapter *sc = vi->adapter;
2807 
2808 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2809 		return;
2810 	cxgbe_init_synchronized(vi);
2811 	end_synchronized_op(sc, 0);
2812 }
2813 
2814 static int
2815 cxgbe_ioctl(struct ifnet *ifp, unsigned long cmd, caddr_t data)
2816 {
2817 	int rc = 0, mtu, flags;
2818 	struct vi_info *vi = ifp->if_softc;
2819 	struct port_info *pi = vi->pi;
2820 	struct adapter *sc = pi->adapter;
2821 	struct ifreq *ifr = (struct ifreq *)data;
2822 	uint32_t mask;
2823 
2824 	switch (cmd) {
2825 	case SIOCSIFMTU:
2826 		mtu = ifr->ifr_mtu;
2827 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2828 			return (EINVAL);
2829 
2830 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2831 		if (rc)
2832 			return (rc);
2833 		ifp->if_mtu = mtu;
2834 		if (vi->flags & VI_INIT_DONE) {
2835 			t4_update_fl_bufsize(ifp);
2836 			if (!hw_off_limits(sc) &&
2837 			    ifp->if_drv_flags & IFF_DRV_RUNNING)
2838 				rc = update_mac_settings(ifp, XGMAC_MTU);
2839 		}
2840 		end_synchronized_op(sc, 0);
2841 		break;
2842 
2843 	case SIOCSIFFLAGS:
2844 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2845 		if (rc)
2846 			return (rc);
2847 
2848 		if (hw_off_limits(sc)) {
2849 			rc = ENXIO;
2850 			goto fail;
2851 		}
2852 
2853 		if (ifp->if_flags & IFF_UP) {
2854 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2855 				flags = vi->if_flags;
2856 				if ((ifp->if_flags ^ flags) &
2857 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2858 					rc = update_mac_settings(ifp,
2859 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2860 				}
2861 			} else {
2862 				rc = cxgbe_init_synchronized(vi);
2863 			}
2864 			vi->if_flags = ifp->if_flags;
2865 		} else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2866 			rc = cxgbe_uninit_synchronized(vi);
2867 		}
2868 		end_synchronized_op(sc, 0);
2869 		break;
2870 
2871 	case SIOCADDMULTI:
2872 	case SIOCDELMULTI:
2873 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2874 		if (rc)
2875 			return (rc);
2876 		if (!hw_off_limits(sc) && ifp->if_drv_flags & IFF_DRV_RUNNING)
2877 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2878 		end_synchronized_op(sc, 0);
2879 		break;
2880 
2881 	case SIOCSIFCAP:
2882 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2883 		if (rc)
2884 			return (rc);
2885 
2886 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
2887 		if (mask & IFCAP_TXCSUM) {
2888 			ifp->if_capenable ^= IFCAP_TXCSUM;
2889 			ifp->if_hwassist ^= (CSUM_TCP | CSUM_UDP | CSUM_IP);
2890 
2891 			if (IFCAP_TSO4 & ifp->if_capenable &&
2892 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2893 				mask &= ~IFCAP_TSO4;
2894 				ifp->if_capenable &= ~IFCAP_TSO4;
2895 				if_printf(ifp,
2896 				    "tso4 disabled due to -txcsum.\n");
2897 			}
2898 		}
2899 		if (mask & IFCAP_TXCSUM_IPV6) {
2900 			ifp->if_capenable ^= IFCAP_TXCSUM_IPV6;
2901 			ifp->if_hwassist ^= (CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2902 
2903 			if (IFCAP_TSO6 & ifp->if_capenable &&
2904 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2905 				mask &= ~IFCAP_TSO6;
2906 				ifp->if_capenable &= ~IFCAP_TSO6;
2907 				if_printf(ifp,
2908 				    "tso6 disabled due to -txcsum6.\n");
2909 			}
2910 		}
2911 		if (mask & IFCAP_RXCSUM)
2912 			ifp->if_capenable ^= IFCAP_RXCSUM;
2913 		if (mask & IFCAP_RXCSUM_IPV6)
2914 			ifp->if_capenable ^= IFCAP_RXCSUM_IPV6;
2915 
2916 		/*
2917 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2918 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2919 		 * sending a TSO request our way, so it's sufficient to toggle
2920 		 * IFCAP_TSOx only.
2921 		 */
2922 		if (mask & IFCAP_TSO4) {
2923 			if (!(IFCAP_TSO4 & ifp->if_capenable) &&
2924 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2925 				if_printf(ifp, "enable txcsum first.\n");
2926 				rc = EAGAIN;
2927 				goto fail;
2928 			}
2929 			ifp->if_capenable ^= IFCAP_TSO4;
2930 		}
2931 		if (mask & IFCAP_TSO6) {
2932 			if (!(IFCAP_TSO6 & ifp->if_capenable) &&
2933 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2934 				if_printf(ifp, "enable txcsum6 first.\n");
2935 				rc = EAGAIN;
2936 				goto fail;
2937 			}
2938 			ifp->if_capenable ^= IFCAP_TSO6;
2939 		}
2940 		if (mask & IFCAP_LRO) {
2941 #if defined(INET) || defined(INET6)
2942 			int i;
2943 			struct sge_rxq *rxq;
2944 
2945 			ifp->if_capenable ^= IFCAP_LRO;
2946 			for_each_rxq(vi, i, rxq) {
2947 				if (ifp->if_capenable & IFCAP_LRO)
2948 					rxq->iq.flags |= IQ_LRO_ENABLED;
2949 				else
2950 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2951 			}
2952 #endif
2953 		}
2954 #ifdef TCP_OFFLOAD
2955 		if (mask & IFCAP_TOE) {
2956 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TOE;
2957 
2958 			rc = toe_capability(vi, enable);
2959 			if (rc != 0)
2960 				goto fail;
2961 
2962 			ifp->if_capenable ^= mask;
2963 		}
2964 #endif
2965 		if (mask & IFCAP_VLAN_HWTAGGING) {
2966 			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
2967 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2968 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2969 		}
2970 		if (mask & IFCAP_VLAN_MTU) {
2971 			ifp->if_capenable ^= IFCAP_VLAN_MTU;
2972 
2973 			/* Need to find out how to disable auto-mtu-inflation */
2974 		}
2975 		if (mask & IFCAP_VLAN_HWTSO)
2976 			ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
2977 		if (mask & IFCAP_VLAN_HWCSUM)
2978 			ifp->if_capenable ^= IFCAP_VLAN_HWCSUM;
2979 #ifdef RATELIMIT
2980 		if (mask & IFCAP_TXRTLMT)
2981 			ifp->if_capenable ^= IFCAP_TXRTLMT;
2982 #endif
2983 		if (mask & IFCAP_HWRXTSTMP) {
2984 			int i;
2985 			struct sge_rxq *rxq;
2986 
2987 			ifp->if_capenable ^= IFCAP_HWRXTSTMP;
2988 			for_each_rxq(vi, i, rxq) {
2989 				if (ifp->if_capenable & IFCAP_HWRXTSTMP)
2990 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2991 				else
2992 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2993 			}
2994 		}
2995 		if (mask & IFCAP_MEXTPG)
2996 			ifp->if_capenable ^= IFCAP_MEXTPG;
2997 
2998 #ifdef KERN_TLS
2999 		if (mask & IFCAP_TXTLS) {
3000 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TXTLS;
3001 
3002 			rc = ktls_capability(sc, enable);
3003 			if (rc != 0)
3004 				goto fail;
3005 
3006 			ifp->if_capenable ^= (mask & IFCAP_TXTLS);
3007 		}
3008 #endif
3009 		if (mask & IFCAP_VXLAN_HWCSUM) {
3010 			ifp->if_capenable ^= IFCAP_VXLAN_HWCSUM;
3011 			ifp->if_hwassist ^= CSUM_INNER_IP6_UDP |
3012 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
3013 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP;
3014 		}
3015 		if (mask & IFCAP_VXLAN_HWTSO) {
3016 			ifp->if_capenable ^= IFCAP_VXLAN_HWTSO;
3017 			ifp->if_hwassist ^= CSUM_INNER_IP6_TSO |
3018 			    CSUM_INNER_IP_TSO;
3019 		}
3020 
3021 #ifdef VLAN_CAPABILITIES
3022 		VLAN_CAPABILITIES(ifp);
3023 #endif
3024 fail:
3025 		end_synchronized_op(sc, 0);
3026 		break;
3027 
3028 	case SIOCSIFMEDIA:
3029 	case SIOCGIFMEDIA:
3030 	case SIOCGIFXMEDIA:
3031 		rc = ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
3032 		break;
3033 
3034 	case SIOCGI2C: {
3035 		struct ifi2creq i2c;
3036 
3037 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
3038 		if (rc != 0)
3039 			break;
3040 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
3041 			rc = EPERM;
3042 			break;
3043 		}
3044 		if (i2c.len > sizeof(i2c.data)) {
3045 			rc = EINVAL;
3046 			break;
3047 		}
3048 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
3049 		if (rc)
3050 			return (rc);
3051 		if (hw_off_limits(sc))
3052 			rc = ENXIO;
3053 		else
3054 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
3055 			    i2c.offset, i2c.len, &i2c.data[0]);
3056 		end_synchronized_op(sc, 0);
3057 		if (rc == 0)
3058 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
3059 		break;
3060 	}
3061 
3062 	default:
3063 		rc = ether_ioctl(ifp, cmd, data);
3064 	}
3065 
3066 	return (rc);
3067 }
3068 
3069 static int
3070 cxgbe_transmit(struct ifnet *ifp, struct mbuf *m)
3071 {
3072 	struct vi_info *vi = ifp->if_softc;
3073 	struct port_info *pi = vi->pi;
3074 	struct adapter *sc;
3075 	struct sge_txq *txq;
3076 	void *items[1];
3077 	int rc;
3078 
3079 	M_ASSERTPKTHDR(m);
3080 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
3081 #if defined(KERN_TLS) || defined(RATELIMIT)
3082 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
3083 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
3084 #endif
3085 
3086 	if (__predict_false(pi->link_cfg.link_ok == false)) {
3087 		m_freem(m);
3088 		return (ENETDOWN);
3089 	}
3090 
3091 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
3092 	if (__predict_false(rc != 0)) {
3093 		MPASS(m == NULL);			/* was freed already */
3094 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
3095 		return (rc);
3096 	}
3097 #ifdef RATELIMIT
3098 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG) {
3099 		if (m->m_pkthdr.snd_tag->sw->type == IF_SND_TAG_TYPE_RATE_LIMIT)
3100 			return (ethofld_transmit(ifp, m));
3101 	}
3102 #endif
3103 
3104 	/* Select a txq. */
3105 	sc = vi->adapter;
3106 	txq = &sc->sge.txq[vi->first_txq];
3107 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
3108 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
3109 		    vi->rsrv_noflowq);
3110 
3111 	items[0] = m;
3112 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
3113 	if (__predict_false(rc != 0))
3114 		m_freem(m);
3115 
3116 	return (rc);
3117 }
3118 
3119 static void
3120 cxgbe_qflush(struct ifnet *ifp)
3121 {
3122 	struct vi_info *vi = ifp->if_softc;
3123 	struct sge_txq *txq;
3124 	int i;
3125 
3126 	/* queues do not exist if !VI_INIT_DONE. */
3127 	if (vi->flags & VI_INIT_DONE) {
3128 		for_each_txq(vi, i, txq) {
3129 			TXQ_LOCK(txq);
3130 			txq->eq.flags |= EQ_QFLUSH;
3131 			TXQ_UNLOCK(txq);
3132 			while (!mp_ring_is_idle(txq->r)) {
3133 				mp_ring_check_drainage(txq->r, 4096);
3134 				pause("qflush", 1);
3135 			}
3136 			TXQ_LOCK(txq);
3137 			txq->eq.flags &= ~EQ_QFLUSH;
3138 			TXQ_UNLOCK(txq);
3139 		}
3140 	}
3141 	if_qflush(ifp);
3142 }
3143 
3144 static uint64_t
3145 vi_get_counter(struct ifnet *ifp, ift_counter c)
3146 {
3147 	struct vi_info *vi = ifp->if_softc;
3148 	struct fw_vi_stats_vf *s = &vi->stats;
3149 
3150 	mtx_lock(&vi->tick_mtx);
3151 	vi_refresh_stats(vi);
3152 	mtx_unlock(&vi->tick_mtx);
3153 
3154 	switch (c) {
3155 	case IFCOUNTER_IPACKETS:
3156 		return (s->rx_bcast_frames + s->rx_mcast_frames +
3157 		    s->rx_ucast_frames);
3158 	case IFCOUNTER_IERRORS:
3159 		return (s->rx_err_frames);
3160 	case IFCOUNTER_OPACKETS:
3161 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3162 		    s->tx_ucast_frames + s->tx_offload_frames);
3163 	case IFCOUNTER_OERRORS:
3164 		return (s->tx_drop_frames);
3165 	case IFCOUNTER_IBYTES:
3166 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3167 		    s->rx_ucast_bytes);
3168 	case IFCOUNTER_OBYTES:
3169 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3170 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3171 	case IFCOUNTER_IMCASTS:
3172 		return (s->rx_mcast_frames);
3173 	case IFCOUNTER_OMCASTS:
3174 		return (s->tx_mcast_frames);
3175 	case IFCOUNTER_OQDROPS: {
3176 		uint64_t drops;
3177 
3178 		drops = 0;
3179 		if (vi->flags & VI_INIT_DONE) {
3180 			int i;
3181 			struct sge_txq *txq;
3182 
3183 			for_each_txq(vi, i, txq)
3184 				drops += counter_u64_fetch(txq->r->dropped);
3185 		}
3186 
3187 		return (drops);
3188 
3189 	}
3190 
3191 	default:
3192 		return (if_get_counter_default(ifp, c));
3193 	}
3194 }
3195 
3196 static uint64_t
3197 cxgbe_get_counter(struct ifnet *ifp, ift_counter c)
3198 {
3199 	struct vi_info *vi = ifp->if_softc;
3200 	struct port_info *pi = vi->pi;
3201 	struct port_stats *s = &pi->stats;
3202 
3203 	mtx_lock(&vi->tick_mtx);
3204 	cxgbe_refresh_stats(vi);
3205 	mtx_unlock(&vi->tick_mtx);
3206 
3207 	switch (c) {
3208 	case IFCOUNTER_IPACKETS:
3209 		return (s->rx_frames);
3210 
3211 	case IFCOUNTER_IERRORS:
3212 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3213 		    s->rx_fcs_err + s->rx_len_err);
3214 
3215 	case IFCOUNTER_OPACKETS:
3216 		return (s->tx_frames);
3217 
3218 	case IFCOUNTER_OERRORS:
3219 		return (s->tx_error_frames);
3220 
3221 	case IFCOUNTER_IBYTES:
3222 		return (s->rx_octets);
3223 
3224 	case IFCOUNTER_OBYTES:
3225 		return (s->tx_octets);
3226 
3227 	case IFCOUNTER_IMCASTS:
3228 		return (s->rx_mcast_frames);
3229 
3230 	case IFCOUNTER_OMCASTS:
3231 		return (s->tx_mcast_frames);
3232 
3233 	case IFCOUNTER_IQDROPS:
3234 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3235 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3236 		    s->rx_trunc3 + pi->tnl_cong_drops);
3237 
3238 	case IFCOUNTER_OQDROPS: {
3239 		uint64_t drops;
3240 
3241 		drops = s->tx_drop;
3242 		if (vi->flags & VI_INIT_DONE) {
3243 			int i;
3244 			struct sge_txq *txq;
3245 
3246 			for_each_txq(vi, i, txq)
3247 				drops += counter_u64_fetch(txq->r->dropped);
3248 		}
3249 
3250 		return (drops);
3251 
3252 	}
3253 
3254 	default:
3255 		return (if_get_counter_default(ifp, c));
3256 	}
3257 }
3258 
3259 #if defined(KERN_TLS) || defined(RATELIMIT)
3260 static int
3261 cxgbe_snd_tag_alloc(struct ifnet *ifp, union if_snd_tag_alloc_params *params,
3262     struct m_snd_tag **pt)
3263 {
3264 	int error;
3265 
3266 	switch (params->hdr.type) {
3267 #ifdef RATELIMIT
3268 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3269 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3270 		break;
3271 #endif
3272 #ifdef KERN_TLS
3273 	case IF_SND_TAG_TYPE_TLS:
3274 	{
3275 		struct vi_info *vi = ifp->if_softc;
3276 
3277 		if (is_t6(vi->pi->adapter))
3278 			error = t6_tls_tag_alloc(ifp, params, pt);
3279 		else
3280 			error = EOPNOTSUPP;
3281 		break;
3282 	}
3283 #endif
3284 	default:
3285 		error = EOPNOTSUPP;
3286 	}
3287 	return (error);
3288 }
3289 #endif
3290 
3291 /*
3292  * The kernel picks a media from the list we had provided but we still validate
3293  * the requeste.
3294  */
3295 int
3296 cxgbe_media_change(struct ifnet *ifp)
3297 {
3298 	struct vi_info *vi = ifp->if_softc;
3299 	struct port_info *pi = vi->pi;
3300 	struct ifmedia *ifm = &pi->media;
3301 	struct link_config *lc = &pi->link_cfg;
3302 	struct adapter *sc = pi->adapter;
3303 	int rc;
3304 
3305 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3306 	if (rc != 0)
3307 		return (rc);
3308 	PORT_LOCK(pi);
3309 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3310 		/* ifconfig .. media autoselect */
3311 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3312 			rc = ENOTSUP; /* AN not supported by transceiver */
3313 			goto done;
3314 		}
3315 		lc->requested_aneg = AUTONEG_ENABLE;
3316 		lc->requested_speed = 0;
3317 		lc->requested_fc |= PAUSE_AUTONEG;
3318 	} else {
3319 		lc->requested_aneg = AUTONEG_DISABLE;
3320 		lc->requested_speed =
3321 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3322 		lc->requested_fc = 0;
3323 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3324 			lc->requested_fc |= PAUSE_RX;
3325 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3326 			lc->requested_fc |= PAUSE_TX;
3327 	}
3328 	if (pi->up_vis > 0 && !hw_off_limits(sc)) {
3329 		fixup_link_config(pi);
3330 		rc = apply_link_config(pi);
3331 	}
3332 done:
3333 	PORT_UNLOCK(pi);
3334 	end_synchronized_op(sc, 0);
3335 	return (rc);
3336 }
3337 
3338 /*
3339  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3340  * given speed.
3341  */
3342 static int
3343 port_mword(struct port_info *pi, uint32_t speed)
3344 {
3345 
3346 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3347 	MPASS(powerof2(speed));
3348 
3349 	switch(pi->port_type) {
3350 	case FW_PORT_TYPE_BT_SGMII:
3351 	case FW_PORT_TYPE_BT_XFI:
3352 	case FW_PORT_TYPE_BT_XAUI:
3353 		/* BaseT */
3354 		switch (speed) {
3355 		case FW_PORT_CAP32_SPEED_100M:
3356 			return (IFM_100_T);
3357 		case FW_PORT_CAP32_SPEED_1G:
3358 			return (IFM_1000_T);
3359 		case FW_PORT_CAP32_SPEED_10G:
3360 			return (IFM_10G_T);
3361 		}
3362 		break;
3363 	case FW_PORT_TYPE_KX4:
3364 		if (speed == FW_PORT_CAP32_SPEED_10G)
3365 			return (IFM_10G_KX4);
3366 		break;
3367 	case FW_PORT_TYPE_CX4:
3368 		if (speed == FW_PORT_CAP32_SPEED_10G)
3369 			return (IFM_10G_CX4);
3370 		break;
3371 	case FW_PORT_TYPE_KX:
3372 		if (speed == FW_PORT_CAP32_SPEED_1G)
3373 			return (IFM_1000_KX);
3374 		break;
3375 	case FW_PORT_TYPE_KR:
3376 	case FW_PORT_TYPE_BP_AP:
3377 	case FW_PORT_TYPE_BP4_AP:
3378 	case FW_PORT_TYPE_BP40_BA:
3379 	case FW_PORT_TYPE_KR4_100G:
3380 	case FW_PORT_TYPE_KR_SFP28:
3381 	case FW_PORT_TYPE_KR_XLAUI:
3382 		switch (speed) {
3383 		case FW_PORT_CAP32_SPEED_1G:
3384 			return (IFM_1000_KX);
3385 		case FW_PORT_CAP32_SPEED_10G:
3386 			return (IFM_10G_KR);
3387 		case FW_PORT_CAP32_SPEED_25G:
3388 			return (IFM_25G_KR);
3389 		case FW_PORT_CAP32_SPEED_40G:
3390 			return (IFM_40G_KR4);
3391 		case FW_PORT_CAP32_SPEED_50G:
3392 			return (IFM_50G_KR2);
3393 		case FW_PORT_CAP32_SPEED_100G:
3394 			return (IFM_100G_KR4);
3395 		}
3396 		break;
3397 	case FW_PORT_TYPE_FIBER_XFI:
3398 	case FW_PORT_TYPE_FIBER_XAUI:
3399 	case FW_PORT_TYPE_SFP:
3400 	case FW_PORT_TYPE_QSFP_10G:
3401 	case FW_PORT_TYPE_QSA:
3402 	case FW_PORT_TYPE_QSFP:
3403 	case FW_PORT_TYPE_CR4_QSFP:
3404 	case FW_PORT_TYPE_CR_QSFP:
3405 	case FW_PORT_TYPE_CR2_QSFP:
3406 	case FW_PORT_TYPE_SFP28:
3407 		/* Pluggable transceiver */
3408 		switch (pi->mod_type) {
3409 		case FW_PORT_MOD_TYPE_LR:
3410 			switch (speed) {
3411 			case FW_PORT_CAP32_SPEED_1G:
3412 				return (IFM_1000_LX);
3413 			case FW_PORT_CAP32_SPEED_10G:
3414 				return (IFM_10G_LR);
3415 			case FW_PORT_CAP32_SPEED_25G:
3416 				return (IFM_25G_LR);
3417 			case FW_PORT_CAP32_SPEED_40G:
3418 				return (IFM_40G_LR4);
3419 			case FW_PORT_CAP32_SPEED_50G:
3420 				return (IFM_50G_LR2);
3421 			case FW_PORT_CAP32_SPEED_100G:
3422 				return (IFM_100G_LR4);
3423 			}
3424 			break;
3425 		case FW_PORT_MOD_TYPE_SR:
3426 			switch (speed) {
3427 			case FW_PORT_CAP32_SPEED_1G:
3428 				return (IFM_1000_SX);
3429 			case FW_PORT_CAP32_SPEED_10G:
3430 				return (IFM_10G_SR);
3431 			case FW_PORT_CAP32_SPEED_25G:
3432 				return (IFM_25G_SR);
3433 			case FW_PORT_CAP32_SPEED_40G:
3434 				return (IFM_40G_SR4);
3435 			case FW_PORT_CAP32_SPEED_50G:
3436 				return (IFM_50G_SR2);
3437 			case FW_PORT_CAP32_SPEED_100G:
3438 				return (IFM_100G_SR4);
3439 			}
3440 			break;
3441 		case FW_PORT_MOD_TYPE_ER:
3442 			if (speed == FW_PORT_CAP32_SPEED_10G)
3443 				return (IFM_10G_ER);
3444 			break;
3445 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3446 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3447 			switch (speed) {
3448 			case FW_PORT_CAP32_SPEED_1G:
3449 				return (IFM_1000_CX);
3450 			case FW_PORT_CAP32_SPEED_10G:
3451 				return (IFM_10G_TWINAX);
3452 			case FW_PORT_CAP32_SPEED_25G:
3453 				return (IFM_25G_CR);
3454 			case FW_PORT_CAP32_SPEED_40G:
3455 				return (IFM_40G_CR4);
3456 			case FW_PORT_CAP32_SPEED_50G:
3457 				return (IFM_50G_CR2);
3458 			case FW_PORT_CAP32_SPEED_100G:
3459 				return (IFM_100G_CR4);
3460 			}
3461 			break;
3462 		case FW_PORT_MOD_TYPE_LRM:
3463 			if (speed == FW_PORT_CAP32_SPEED_10G)
3464 				return (IFM_10G_LRM);
3465 			break;
3466 		case FW_PORT_MOD_TYPE_NA:
3467 			MPASS(0);	/* Not pluggable? */
3468 			/* fall throough */
3469 		case FW_PORT_MOD_TYPE_ERROR:
3470 		case FW_PORT_MOD_TYPE_UNKNOWN:
3471 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3472 			break;
3473 		case FW_PORT_MOD_TYPE_NONE:
3474 			return (IFM_NONE);
3475 		}
3476 		break;
3477 	case FW_PORT_TYPE_NONE:
3478 		return (IFM_NONE);
3479 	}
3480 
3481 	return (IFM_UNKNOWN);
3482 }
3483 
3484 void
3485 cxgbe_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
3486 {
3487 	struct vi_info *vi = ifp->if_softc;
3488 	struct port_info *pi = vi->pi;
3489 	struct adapter *sc = pi->adapter;
3490 	struct link_config *lc = &pi->link_cfg;
3491 
3492 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4med") != 0)
3493 		return;
3494 	PORT_LOCK(pi);
3495 
3496 	if (pi->up_vis == 0 && !hw_off_limits(sc)) {
3497 		/*
3498 		 * If all the interfaces are administratively down the firmware
3499 		 * does not report transceiver changes.  Refresh port info here
3500 		 * so that ifconfig displays accurate ifmedia at all times.
3501 		 * This is the only reason we have a synchronized op in this
3502 		 * function.  Just PORT_LOCK would have been enough otherwise.
3503 		 */
3504 		t4_update_port_info(pi);
3505 		build_medialist(pi);
3506 	}
3507 
3508 	/* ifm_status */
3509 	ifmr->ifm_status = IFM_AVALID;
3510 	if (lc->link_ok == false)
3511 		goto done;
3512 	ifmr->ifm_status |= IFM_ACTIVE;
3513 
3514 	/* ifm_active */
3515 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3516 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3517 	if (lc->fc & PAUSE_RX)
3518 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3519 	if (lc->fc & PAUSE_TX)
3520 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3521 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3522 done:
3523 	PORT_UNLOCK(pi);
3524 	end_synchronized_op(sc, 0);
3525 }
3526 
3527 static int
3528 vcxgbe_probe(device_t dev)
3529 {
3530 	char buf[128];
3531 	struct vi_info *vi = device_get_softc(dev);
3532 
3533 	snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
3534 	    vi - vi->pi->vi);
3535 	device_set_desc_copy(dev, buf);
3536 
3537 	return (BUS_PROBE_DEFAULT);
3538 }
3539 
3540 static int
3541 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3542 {
3543 	int func, index, rc;
3544 	uint32_t param, val;
3545 
3546 	ASSERT_SYNCHRONIZED_OP(sc);
3547 
3548 	index = vi - pi->vi;
3549 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3550 	KASSERT(index < nitems(vi_mac_funcs),
3551 	    ("%s: VI %s doesn't have a MAC func", __func__,
3552 	    device_get_nameunit(vi->dev)));
3553 	func = vi_mac_funcs[index];
3554 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3555 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3556 	if (rc < 0) {
3557 		CH_ERR(vi, "failed to allocate virtual interface %d"
3558 		    "for port %d: %d\n", index, pi->port_id, -rc);
3559 		return (-rc);
3560 	}
3561 	vi->viid = rc;
3562 
3563 	if (vi->rss_size == 1) {
3564 		/*
3565 		 * This VI didn't get a slice of the RSS table.  Reduce the
3566 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3567 		 * configuration file (nvi, rssnvi for this PF) if this is a
3568 		 * problem.
3569 		 */
3570 		device_printf(vi->dev, "RSS table not available.\n");
3571 		vi->rss_base = 0xffff;
3572 
3573 		return (0);
3574 	}
3575 
3576 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3577 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3578 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3579 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3580 	if (rc)
3581 		vi->rss_base = 0xffff;
3582 	else {
3583 		MPASS((val >> 16) == vi->rss_size);
3584 		vi->rss_base = val & 0xffff;
3585 	}
3586 
3587 	return (0);
3588 }
3589 
3590 static int
3591 vcxgbe_attach(device_t dev)
3592 {
3593 	struct vi_info *vi;
3594 	struct port_info *pi;
3595 	struct adapter *sc;
3596 	int rc;
3597 
3598 	vi = device_get_softc(dev);
3599 	pi = vi->pi;
3600 	sc = pi->adapter;
3601 
3602 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3603 	if (rc)
3604 		return (rc);
3605 	rc = alloc_extra_vi(sc, pi, vi);
3606 	end_synchronized_op(sc, 0);
3607 	if (rc)
3608 		return (rc);
3609 
3610 	rc = cxgbe_vi_attach(dev, vi);
3611 	if (rc) {
3612 		t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3613 		return (rc);
3614 	}
3615 	return (0);
3616 }
3617 
3618 static int
3619 vcxgbe_detach(device_t dev)
3620 {
3621 	struct vi_info *vi;
3622 	struct adapter *sc;
3623 
3624 	vi = device_get_softc(dev);
3625 	sc = vi->adapter;
3626 
3627 	doom_vi(sc, vi);
3628 
3629 	cxgbe_vi_detach(vi);
3630 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3631 
3632 	end_synchronized_op(sc, 0);
3633 
3634 	return (0);
3635 }
3636 
3637 static struct callout fatal_callout;
3638 static struct taskqueue *reset_tq;
3639 
3640 static void
3641 delayed_panic(void *arg)
3642 {
3643 	struct adapter *sc = arg;
3644 
3645 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3646 }
3647 
3648 static void
3649 fatal_error_task(void *arg, int pending)
3650 {
3651 	struct adapter *sc = arg;
3652 	int rc;
3653 
3654 #ifdef TCP_OFFLOAD
3655 	t4_async_event(sc);
3656 #endif
3657 	if (atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_CIM_ERR))) {
3658 		dump_cim_regs(sc);
3659 		dump_cimla(sc);
3660 		dump_devlog(sc);
3661 	}
3662 
3663 	if (t4_reset_on_fatal_err) {
3664 		CH_ALERT(sc, "resetting on fatal error.\n");
3665 		rc = reset_adapter(sc);
3666 		if (rc == 0 && t4_panic_on_fatal_err) {
3667 			CH_ALERT(sc, "reset was successful, "
3668 			    "system will NOT panic.\n");
3669 			return;
3670 		}
3671 	}
3672 
3673 	if (t4_panic_on_fatal_err) {
3674 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3675 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3676 	}
3677 }
3678 
3679 void
3680 t4_fatal_err(struct adapter *sc, bool fw_error)
3681 {
3682 	const bool verbose = (sc->debug_flags & DF_VERBOSE_SLOWINTR) != 0;
3683 
3684 	stop_adapter(sc);
3685 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_FATAL_ERR)))
3686 		return;
3687 	if (fw_error) {
3688 		/*
3689 		 * We are here because of a firmware error/timeout and not
3690 		 * because of a hardware interrupt.  It is possible (although
3691 		 * not very likely) that an error interrupt was also raised but
3692 		 * this thread ran first and inhibited t4_intr_err.  We walk the
3693 		 * main INT_CAUSE registers here to make sure we haven't missed
3694 		 * anything interesting.
3695 		 */
3696 		t4_slow_intr_handler(sc, verbose);
3697 		atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
3698 	}
3699 	t4_report_fw_error(sc);
3700 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped (%d).\n",
3701 	    device_get_nameunit(sc->dev), fw_error);
3702 	taskqueue_enqueue(reset_tq, &sc->fatal_error_task);
3703 }
3704 
3705 void
3706 t4_add_adapter(struct adapter *sc)
3707 {
3708 	sx_xlock(&t4_list_lock);
3709 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3710 	sx_xunlock(&t4_list_lock);
3711 }
3712 
3713 int
3714 t4_map_bars_0_and_4(struct adapter *sc)
3715 {
3716 	sc->regs_rid = PCIR_BAR(0);
3717 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3718 	    &sc->regs_rid, RF_ACTIVE);
3719 	if (sc->regs_res == NULL) {
3720 		device_printf(sc->dev, "cannot map registers.\n");
3721 		return (ENXIO);
3722 	}
3723 	sc->bt = rman_get_bustag(sc->regs_res);
3724 	sc->bh = rman_get_bushandle(sc->regs_res);
3725 	sc->mmio_len = rman_get_size(sc->regs_res);
3726 	setbit(&sc->doorbells, DOORBELL_KDB);
3727 
3728 	sc->msix_rid = PCIR_BAR(4);
3729 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3730 	    &sc->msix_rid, RF_ACTIVE);
3731 	if (sc->msix_res == NULL) {
3732 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3733 		return (ENXIO);
3734 	}
3735 
3736 	return (0);
3737 }
3738 
3739 int
3740 t4_map_bar_2(struct adapter *sc)
3741 {
3742 
3743 	/*
3744 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3745 	 * to map it if RDMA is disabled.
3746 	 */
3747 	if (is_t4(sc) && sc->rdmacaps == 0)
3748 		return (0);
3749 
3750 	sc->udbs_rid = PCIR_BAR(2);
3751 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3752 	    &sc->udbs_rid, RF_ACTIVE);
3753 	if (sc->udbs_res == NULL) {
3754 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3755 		return (ENXIO);
3756 	}
3757 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3758 
3759 	if (chip_id(sc) >= CHELSIO_T5) {
3760 		setbit(&sc->doorbells, DOORBELL_UDB);
3761 #if defined(__i386__) || defined(__amd64__)
3762 		if (t5_write_combine) {
3763 			int rc, mode;
3764 
3765 			/*
3766 			 * Enable write combining on BAR2.  This is the
3767 			 * userspace doorbell BAR and is split into 128B
3768 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3769 			 * with an egress queue.  The first 64B has the doorbell
3770 			 * and the second 64B can be used to submit a tx work
3771 			 * request with an implicit doorbell.
3772 			 */
3773 
3774 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3775 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3776 			if (rc == 0) {
3777 				clrbit(&sc->doorbells, DOORBELL_UDB);
3778 				setbit(&sc->doorbells, DOORBELL_WCWR);
3779 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3780 			} else {
3781 				device_printf(sc->dev,
3782 				    "couldn't enable write combining: %d\n",
3783 				    rc);
3784 			}
3785 
3786 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3787 			t4_write_reg(sc, A_SGE_STAT_CFG,
3788 			    V_STATSOURCE_T5(7) | mode);
3789 		}
3790 #endif
3791 	}
3792 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3793 
3794 	return (0);
3795 }
3796 
3797 struct memwin_init {
3798 	uint32_t base;
3799 	uint32_t aperture;
3800 };
3801 
3802 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3803 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3804 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3805 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3806 };
3807 
3808 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3809 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3810 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3811 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3812 };
3813 
3814 static void
3815 setup_memwin(struct adapter *sc)
3816 {
3817 	const struct memwin_init *mw_init;
3818 	struct memwin *mw;
3819 	int i;
3820 	uint32_t bar0;
3821 
3822 	if (is_t4(sc)) {
3823 		/*
3824 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3825 		 * mechanism.  Works from within PCI passthrough environments
3826 		 * too, where rman_get_start() can return a different value.  We
3827 		 * need to program the T4 memory window decoders with the actual
3828 		 * addresses that will be coming across the PCIe link.
3829 		 */
3830 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3831 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3832 
3833 		mw_init = &t4_memwin[0];
3834 	} else {
3835 		/* T5+ use the relative offset inside the PCIe BAR */
3836 		bar0 = 0;
3837 
3838 		mw_init = &t5_memwin[0];
3839 	}
3840 
3841 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3842 		if (!rw_initialized(&mw->mw_lock)) {
3843 			rw_init(&mw->mw_lock, "memory window access");
3844 			mw->mw_base = mw_init->base;
3845 			mw->mw_aperture = mw_init->aperture;
3846 			mw->mw_curpos = 0;
3847 		}
3848 		t4_write_reg(sc,
3849 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3850 		    (mw->mw_base + bar0) | V_BIR(0) |
3851 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3852 		rw_wlock(&mw->mw_lock);
3853 		position_memwin(sc, i, mw->mw_curpos);
3854 		rw_wunlock(&mw->mw_lock);
3855 	}
3856 
3857 	/* flush */
3858 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3859 }
3860 
3861 /*
3862  * Positions the memory window at the given address in the card's address space.
3863  * There are some alignment requirements and the actual position may be at an
3864  * address prior to the requested address.  mw->mw_curpos always has the actual
3865  * position of the window.
3866  */
3867 static void
3868 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3869 {
3870 	struct memwin *mw;
3871 	uint32_t pf;
3872 	uint32_t reg;
3873 
3874 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3875 	mw = &sc->memwin[idx];
3876 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3877 
3878 	if (is_t4(sc)) {
3879 		pf = 0;
3880 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3881 	} else {
3882 		pf = V_PFNUM(sc->pf);
3883 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3884 	}
3885 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3886 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3887 	t4_read_reg(sc, reg);	/* flush */
3888 }
3889 
3890 int
3891 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3892     int len, int rw)
3893 {
3894 	struct memwin *mw;
3895 	uint32_t mw_end, v;
3896 
3897 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3898 
3899 	/* Memory can only be accessed in naturally aligned 4 byte units */
3900 	if (addr & 3 || len & 3 || len <= 0)
3901 		return (EINVAL);
3902 
3903 	mw = &sc->memwin[idx];
3904 	while (len > 0) {
3905 		rw_rlock(&mw->mw_lock);
3906 		mw_end = mw->mw_curpos + mw->mw_aperture;
3907 		if (addr >= mw_end || addr < mw->mw_curpos) {
3908 			/* Will need to reposition the window */
3909 			if (!rw_try_upgrade(&mw->mw_lock)) {
3910 				rw_runlock(&mw->mw_lock);
3911 				rw_wlock(&mw->mw_lock);
3912 			}
3913 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3914 			position_memwin(sc, idx, addr);
3915 			rw_downgrade(&mw->mw_lock);
3916 			mw_end = mw->mw_curpos + mw->mw_aperture;
3917 		}
3918 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3919 		while (addr < mw_end && len > 0) {
3920 			if (rw == 0) {
3921 				v = t4_read_reg(sc, mw->mw_base + addr -
3922 				    mw->mw_curpos);
3923 				*val++ = le32toh(v);
3924 			} else {
3925 				v = *val++;
3926 				t4_write_reg(sc, mw->mw_base + addr -
3927 				    mw->mw_curpos, htole32(v));
3928 			}
3929 			addr += 4;
3930 			len -= 4;
3931 		}
3932 		rw_runlock(&mw->mw_lock);
3933 	}
3934 
3935 	return (0);
3936 }
3937 
3938 static void
3939 t4_init_atid_table(struct adapter *sc)
3940 {
3941 	struct tid_info *t;
3942 	int i;
3943 
3944 	t = &sc->tids;
3945 	if (t->natids == 0)
3946 		return;
3947 
3948 	MPASS(t->atid_tab == NULL);
3949 
3950 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3951 	    M_ZERO | M_WAITOK);
3952 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3953 	t->afree = t->atid_tab;
3954 	t->atids_in_use = 0;
3955 	for (i = 1; i < t->natids; i++)
3956 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3957 	t->atid_tab[t->natids - 1].next = NULL;
3958 }
3959 
3960 static void
3961 t4_free_atid_table(struct adapter *sc)
3962 {
3963 	struct tid_info *t;
3964 
3965 	t = &sc->tids;
3966 
3967 	KASSERT(t->atids_in_use == 0,
3968 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3969 
3970 	if (mtx_initialized(&t->atid_lock))
3971 		mtx_destroy(&t->atid_lock);
3972 	free(t->atid_tab, M_CXGBE);
3973 	t->atid_tab = NULL;
3974 }
3975 
3976 int
3977 alloc_atid(struct adapter *sc, void *ctx)
3978 {
3979 	struct tid_info *t = &sc->tids;
3980 	int atid = -1;
3981 
3982 	mtx_lock(&t->atid_lock);
3983 	if (t->afree) {
3984 		union aopen_entry *p = t->afree;
3985 
3986 		atid = p - t->atid_tab;
3987 		MPASS(atid <= M_TID_TID);
3988 		t->afree = p->next;
3989 		p->data = ctx;
3990 		t->atids_in_use++;
3991 	}
3992 	mtx_unlock(&t->atid_lock);
3993 	return (atid);
3994 }
3995 
3996 void *
3997 lookup_atid(struct adapter *sc, int atid)
3998 {
3999 	struct tid_info *t = &sc->tids;
4000 
4001 	return (t->atid_tab[atid].data);
4002 }
4003 
4004 void
4005 free_atid(struct adapter *sc, int atid)
4006 {
4007 	struct tid_info *t = &sc->tids;
4008 	union aopen_entry *p = &t->atid_tab[atid];
4009 
4010 	mtx_lock(&t->atid_lock);
4011 	p->next = t->afree;
4012 	t->afree = p;
4013 	t->atids_in_use--;
4014 	mtx_unlock(&t->atid_lock);
4015 }
4016 
4017 static void
4018 queue_tid_release(struct adapter *sc, int tid)
4019 {
4020 
4021 	CXGBE_UNIMPLEMENTED("deferred tid release");
4022 }
4023 
4024 void
4025 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
4026 {
4027 	struct wrqe *wr;
4028 	struct cpl_tid_release *req;
4029 
4030 	wr = alloc_wrqe(sizeof(*req), ctrlq);
4031 	if (wr == NULL) {
4032 		queue_tid_release(sc, tid);	/* defer */
4033 		return;
4034 	}
4035 	req = wrtod(wr);
4036 
4037 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
4038 
4039 	t4_wrq_tx(sc, wr);
4040 }
4041 
4042 static int
4043 t4_range_cmp(const void *a, const void *b)
4044 {
4045 	return ((const struct t4_range *)a)->start -
4046 	       ((const struct t4_range *)b)->start;
4047 }
4048 
4049 /*
4050  * Verify that the memory range specified by the addr/len pair is valid within
4051  * the card's address space.
4052  */
4053 static int
4054 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
4055 {
4056 	struct t4_range mem_ranges[4], *r, *next;
4057 	uint32_t em, addr_len;
4058 	int i, n, remaining;
4059 
4060 	/* Memory can only be accessed in naturally aligned 4 byte units */
4061 	if (addr & 3 || len & 3 || len == 0)
4062 		return (EINVAL);
4063 
4064 	/* Enabled memories */
4065 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4066 
4067 	r = &mem_ranges[0];
4068 	n = 0;
4069 	bzero(r, sizeof(mem_ranges));
4070 	if (em & F_EDRAM0_ENABLE) {
4071 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4072 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
4073 		if (r->size > 0) {
4074 			r->start = G_EDRAM0_BASE(addr_len) << 20;
4075 			if (addr >= r->start &&
4076 			    addr + len <= r->start + r->size)
4077 				return (0);
4078 			r++;
4079 			n++;
4080 		}
4081 	}
4082 	if (em & F_EDRAM1_ENABLE) {
4083 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4084 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
4085 		if (r->size > 0) {
4086 			r->start = G_EDRAM1_BASE(addr_len) << 20;
4087 			if (addr >= r->start &&
4088 			    addr + len <= r->start + r->size)
4089 				return (0);
4090 			r++;
4091 			n++;
4092 		}
4093 	}
4094 	if (em & F_EXT_MEM_ENABLE) {
4095 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4096 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
4097 		if (r->size > 0) {
4098 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
4099 			if (addr >= r->start &&
4100 			    addr + len <= r->start + r->size)
4101 				return (0);
4102 			r++;
4103 			n++;
4104 		}
4105 	}
4106 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
4107 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4108 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
4109 		if (r->size > 0) {
4110 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
4111 			if (addr >= r->start &&
4112 			    addr + len <= r->start + r->size)
4113 				return (0);
4114 			r++;
4115 			n++;
4116 		}
4117 	}
4118 	MPASS(n <= nitems(mem_ranges));
4119 
4120 	if (n > 1) {
4121 		/* Sort and merge the ranges. */
4122 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
4123 
4124 		/* Start from index 0 and examine the next n - 1 entries. */
4125 		r = &mem_ranges[0];
4126 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
4127 
4128 			MPASS(r->size > 0);	/* r is a valid entry. */
4129 			next = r + 1;
4130 			MPASS(next->size > 0);	/* and so is the next one. */
4131 
4132 			while (r->start + r->size >= next->start) {
4133 				/* Merge the next one into the current entry. */
4134 				r->size = max(r->start + r->size,
4135 				    next->start + next->size) - r->start;
4136 				n--;	/* One fewer entry in total. */
4137 				if (--remaining == 0)
4138 					goto done;	/* short circuit */
4139 				next++;
4140 			}
4141 			if (next != r + 1) {
4142 				/*
4143 				 * Some entries were merged into r and next
4144 				 * points to the first valid entry that couldn't
4145 				 * be merged.
4146 				 */
4147 				MPASS(next->size > 0);	/* must be valid */
4148 				memcpy(r + 1, next, remaining * sizeof(*r));
4149 #ifdef INVARIANTS
4150 				/*
4151 				 * This so that the foo->size assertion in the
4152 				 * next iteration of the loop do the right
4153 				 * thing for entries that were pulled up and are
4154 				 * no longer valid.
4155 				 */
4156 				MPASS(n < nitems(mem_ranges));
4157 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4158 				    sizeof(struct t4_range));
4159 #endif
4160 			}
4161 		}
4162 done:
4163 		/* Done merging the ranges. */
4164 		MPASS(n > 0);
4165 		r = &mem_ranges[0];
4166 		for (i = 0; i < n; i++, r++) {
4167 			if (addr >= r->start &&
4168 			    addr + len <= r->start + r->size)
4169 				return (0);
4170 		}
4171 	}
4172 
4173 	return (EFAULT);
4174 }
4175 
4176 static int
4177 fwmtype_to_hwmtype(int mtype)
4178 {
4179 
4180 	switch (mtype) {
4181 	case FW_MEMTYPE_EDC0:
4182 		return (MEM_EDC0);
4183 	case FW_MEMTYPE_EDC1:
4184 		return (MEM_EDC1);
4185 	case FW_MEMTYPE_EXTMEM:
4186 		return (MEM_MC0);
4187 	case FW_MEMTYPE_EXTMEM1:
4188 		return (MEM_MC1);
4189 	default:
4190 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4191 	}
4192 }
4193 
4194 /*
4195  * Verify that the memory range specified by the memtype/offset/len pair is
4196  * valid and lies entirely within the memtype specified.  The global address of
4197  * the start of the range is returned in addr.
4198  */
4199 static int
4200 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4201     uint32_t *addr)
4202 {
4203 	uint32_t em, addr_len, maddr;
4204 
4205 	/* Memory can only be accessed in naturally aligned 4 byte units */
4206 	if (off & 3 || len & 3 || len == 0)
4207 		return (EINVAL);
4208 
4209 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4210 	switch (fwmtype_to_hwmtype(mtype)) {
4211 	case MEM_EDC0:
4212 		if (!(em & F_EDRAM0_ENABLE))
4213 			return (EINVAL);
4214 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4215 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4216 		break;
4217 	case MEM_EDC1:
4218 		if (!(em & F_EDRAM1_ENABLE))
4219 			return (EINVAL);
4220 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4221 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4222 		break;
4223 	case MEM_MC:
4224 		if (!(em & F_EXT_MEM_ENABLE))
4225 			return (EINVAL);
4226 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4227 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4228 		break;
4229 	case MEM_MC1:
4230 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4231 			return (EINVAL);
4232 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4233 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4234 		break;
4235 	default:
4236 		return (EINVAL);
4237 	}
4238 
4239 	*addr = maddr + off;	/* global address */
4240 	return (validate_mem_range(sc, *addr, len));
4241 }
4242 
4243 static int
4244 fixup_devlog_params(struct adapter *sc)
4245 {
4246 	struct devlog_params *dparams = &sc->params.devlog;
4247 	int rc;
4248 
4249 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4250 	    dparams->size, &dparams->addr);
4251 
4252 	return (rc);
4253 }
4254 
4255 static void
4256 update_nirq(struct intrs_and_queues *iaq, int nports)
4257 {
4258 
4259 	iaq->nirq = T4_EXTRA_INTR;
4260 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4261 	iaq->nirq += nports * iaq->nofldrxq;
4262 	iaq->nirq += nports * (iaq->num_vis - 1) *
4263 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4264 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4265 }
4266 
4267 /*
4268  * Adjust requirements to fit the number of interrupts available.
4269  */
4270 static void
4271 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4272     int navail)
4273 {
4274 	int old_nirq;
4275 	const int nports = sc->params.nports;
4276 
4277 	MPASS(nports > 0);
4278 	MPASS(navail > 0);
4279 
4280 	bzero(iaq, sizeof(*iaq));
4281 	iaq->intr_type = itype;
4282 	iaq->num_vis = t4_num_vis;
4283 	iaq->ntxq = t4_ntxq;
4284 	iaq->ntxq_vi = t4_ntxq_vi;
4285 	iaq->nrxq = t4_nrxq;
4286 	iaq->nrxq_vi = t4_nrxq_vi;
4287 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4288 	if (is_offload(sc) || is_ethoffload(sc)) {
4289 		iaq->nofldtxq = t4_nofldtxq;
4290 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4291 	}
4292 #endif
4293 #ifdef TCP_OFFLOAD
4294 	if (is_offload(sc)) {
4295 		iaq->nofldrxq = t4_nofldrxq;
4296 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4297 	}
4298 #endif
4299 #ifdef DEV_NETMAP
4300 	if (t4_native_netmap & NN_MAIN_VI) {
4301 		iaq->nnmtxq = t4_nnmtxq;
4302 		iaq->nnmrxq = t4_nnmrxq;
4303 	}
4304 	if (t4_native_netmap & NN_EXTRA_VI) {
4305 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4306 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4307 	}
4308 #endif
4309 
4310 	update_nirq(iaq, nports);
4311 	if (iaq->nirq <= navail &&
4312 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4313 		/*
4314 		 * This is the normal case -- there are enough interrupts for
4315 		 * everything.
4316 		 */
4317 		goto done;
4318 	}
4319 
4320 	/*
4321 	 * If extra VIs have been configured try reducing their count and see if
4322 	 * that works.
4323 	 */
4324 	while (iaq->num_vis > 1) {
4325 		iaq->num_vis--;
4326 		update_nirq(iaq, nports);
4327 		if (iaq->nirq <= navail &&
4328 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4329 			device_printf(sc->dev, "virtual interfaces per port "
4330 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4331 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4332 			    "itype %d, navail %u, nirq %d.\n",
4333 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4334 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4335 			    itype, navail, iaq->nirq);
4336 			goto done;
4337 		}
4338 	}
4339 
4340 	/*
4341 	 * Extra VIs will not be created.  Log a message if they were requested.
4342 	 */
4343 	MPASS(iaq->num_vis == 1);
4344 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4345 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4346 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4347 	if (iaq->num_vis != t4_num_vis) {
4348 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4349 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4350 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4351 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4352 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4353 	}
4354 
4355 	/*
4356 	 * Keep reducing the number of NIC rx queues to the next lower power of
4357 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4358 	 * if that works.
4359 	 */
4360 	do {
4361 		if (iaq->nrxq > 1) {
4362 			do {
4363 				iaq->nrxq--;
4364 			} while (!powerof2(iaq->nrxq));
4365 			if (iaq->nnmrxq > iaq->nrxq)
4366 				iaq->nnmrxq = iaq->nrxq;
4367 		}
4368 		if (iaq->nofldrxq > 1)
4369 			iaq->nofldrxq >>= 1;
4370 
4371 		old_nirq = iaq->nirq;
4372 		update_nirq(iaq, nports);
4373 		if (iaq->nirq <= navail &&
4374 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4375 			device_printf(sc->dev, "running with reduced number of "
4376 			    "rx queues because of shortage of interrupts.  "
4377 			    "nrxq=%u, nofldrxq=%u.  "
4378 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4379 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4380 			goto done;
4381 		}
4382 	} while (old_nirq != iaq->nirq);
4383 
4384 	/* One interrupt for everything.  Ugh. */
4385 	device_printf(sc->dev, "running with minimal number of queues.  "
4386 	    "itype %d, navail %u.\n", itype, navail);
4387 	iaq->nirq = 1;
4388 	iaq->nrxq = 1;
4389 	iaq->ntxq = 1;
4390 	if (iaq->nofldrxq > 0) {
4391 		iaq->nofldrxq = 1;
4392 		iaq->nofldtxq = 1;
4393 	}
4394 	iaq->nnmtxq = 0;
4395 	iaq->nnmrxq = 0;
4396 done:
4397 	MPASS(iaq->num_vis > 0);
4398 	if (iaq->num_vis > 1) {
4399 		MPASS(iaq->nrxq_vi > 0);
4400 		MPASS(iaq->ntxq_vi > 0);
4401 	}
4402 	MPASS(iaq->nirq > 0);
4403 	MPASS(iaq->nrxq > 0);
4404 	MPASS(iaq->ntxq > 0);
4405 	if (itype == INTR_MSI) {
4406 		MPASS(powerof2(iaq->nirq));
4407 	}
4408 }
4409 
4410 static int
4411 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4412 {
4413 	int rc, itype, navail, nalloc;
4414 
4415 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4416 
4417 		if ((itype & t4_intr_types) == 0)
4418 			continue;	/* not allowed */
4419 
4420 		if (itype == INTR_MSIX)
4421 			navail = pci_msix_count(sc->dev);
4422 		else if (itype == INTR_MSI)
4423 			navail = pci_msi_count(sc->dev);
4424 		else
4425 			navail = 1;
4426 restart:
4427 		if (navail == 0)
4428 			continue;
4429 
4430 		calculate_iaq(sc, iaq, itype, navail);
4431 		nalloc = iaq->nirq;
4432 		rc = 0;
4433 		if (itype == INTR_MSIX)
4434 			rc = pci_alloc_msix(sc->dev, &nalloc);
4435 		else if (itype == INTR_MSI)
4436 			rc = pci_alloc_msi(sc->dev, &nalloc);
4437 
4438 		if (rc == 0 && nalloc > 0) {
4439 			if (nalloc == iaq->nirq)
4440 				return (0);
4441 
4442 			/*
4443 			 * Didn't get the number requested.  Use whatever number
4444 			 * the kernel is willing to allocate.
4445 			 */
4446 			device_printf(sc->dev, "fewer vectors than requested, "
4447 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4448 			    itype, iaq->nirq, nalloc);
4449 			pci_release_msi(sc->dev);
4450 			navail = nalloc;
4451 			goto restart;
4452 		}
4453 
4454 		device_printf(sc->dev,
4455 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4456 		    itype, rc, iaq->nirq, nalloc);
4457 	}
4458 
4459 	device_printf(sc->dev,
4460 	    "failed to find a usable interrupt type.  "
4461 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4462 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4463 
4464 	return (ENXIO);
4465 }
4466 
4467 #define FW_VERSION(chip) ( \
4468     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4469     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4470     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4471     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4472 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4473 
4474 /* Just enough of fw_hdr to cover all version info. */
4475 struct fw_h {
4476 	__u8	ver;
4477 	__u8	chip;
4478 	__be16	len512;
4479 	__be32	fw_ver;
4480 	__be32	tp_microcode_ver;
4481 	__u8	intfver_nic;
4482 	__u8	intfver_vnic;
4483 	__u8	intfver_ofld;
4484 	__u8	intfver_ri;
4485 	__u8	intfver_iscsipdu;
4486 	__u8	intfver_iscsi;
4487 	__u8	intfver_fcoepdu;
4488 	__u8	intfver_fcoe;
4489 };
4490 /* Spot check a couple of fields. */
4491 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4492 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4493 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4494 
4495 struct fw_info {
4496 	uint8_t chip;
4497 	char *kld_name;
4498 	char *fw_mod_name;
4499 	struct fw_h fw_h;
4500 } fw_info[] = {
4501 	{
4502 		.chip = CHELSIO_T4,
4503 		.kld_name = "t4fw_cfg",
4504 		.fw_mod_name = "t4fw",
4505 		.fw_h = {
4506 			.chip = FW_HDR_CHIP_T4,
4507 			.fw_ver = htobe32(FW_VERSION(T4)),
4508 			.intfver_nic = FW_INTFVER(T4, NIC),
4509 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4510 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4511 			.intfver_ri = FW_INTFVER(T4, RI),
4512 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4513 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4514 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4515 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4516 		},
4517 	}, {
4518 		.chip = CHELSIO_T5,
4519 		.kld_name = "t5fw_cfg",
4520 		.fw_mod_name = "t5fw",
4521 		.fw_h = {
4522 			.chip = FW_HDR_CHIP_T5,
4523 			.fw_ver = htobe32(FW_VERSION(T5)),
4524 			.intfver_nic = FW_INTFVER(T5, NIC),
4525 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4526 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4527 			.intfver_ri = FW_INTFVER(T5, RI),
4528 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4529 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4530 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4531 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4532 		},
4533 	}, {
4534 		.chip = CHELSIO_T6,
4535 		.kld_name = "t6fw_cfg",
4536 		.fw_mod_name = "t6fw",
4537 		.fw_h = {
4538 			.chip = FW_HDR_CHIP_T6,
4539 			.fw_ver = htobe32(FW_VERSION(T6)),
4540 			.intfver_nic = FW_INTFVER(T6, NIC),
4541 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4542 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4543 			.intfver_ri = FW_INTFVER(T6, RI),
4544 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4545 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4546 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4547 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4548 		},
4549 	}
4550 };
4551 
4552 static struct fw_info *
4553 find_fw_info(int chip)
4554 {
4555 	int i;
4556 
4557 	for (i = 0; i < nitems(fw_info); i++) {
4558 		if (fw_info[i].chip == chip)
4559 			return (&fw_info[i]);
4560 	}
4561 	return (NULL);
4562 }
4563 
4564 /*
4565  * Is the given firmware API compatible with the one the driver was compiled
4566  * with?
4567  */
4568 static int
4569 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4570 {
4571 
4572 	/* short circuit if it's the exact same firmware version */
4573 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4574 		return (1);
4575 
4576 	/*
4577 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4578 	 * features that are supported in the driver.
4579 	 */
4580 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4581 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4582 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4583 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4584 		return (1);
4585 #undef SAME_INTF
4586 
4587 	return (0);
4588 }
4589 
4590 static int
4591 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4592     const struct firmware **fw)
4593 {
4594 	struct fw_info *fw_info;
4595 
4596 	*dcfg = NULL;
4597 	if (fw != NULL)
4598 		*fw = NULL;
4599 
4600 	fw_info = find_fw_info(chip_id(sc));
4601 	if (fw_info == NULL) {
4602 		device_printf(sc->dev,
4603 		    "unable to look up firmware information for chip %d.\n",
4604 		    chip_id(sc));
4605 		return (EINVAL);
4606 	}
4607 
4608 	*dcfg = firmware_get(fw_info->kld_name);
4609 	if (*dcfg != NULL) {
4610 		if (fw != NULL)
4611 			*fw = firmware_get(fw_info->fw_mod_name);
4612 		return (0);
4613 	}
4614 
4615 	return (ENOENT);
4616 }
4617 
4618 static void
4619 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4620     const struct firmware *fw)
4621 {
4622 
4623 	if (fw != NULL)
4624 		firmware_put(fw, FIRMWARE_UNLOAD);
4625 	if (dcfg != NULL)
4626 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4627 }
4628 
4629 /*
4630  * Return values:
4631  * 0 means no firmware install attempted.
4632  * ERESTART means a firmware install was attempted and was successful.
4633  * +ve errno means a firmware install was attempted but failed.
4634  */
4635 static int
4636 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4637     const struct fw_h *drv_fw, const char *reason, int *already)
4638 {
4639 	const struct firmware *cfg, *fw;
4640 	const uint32_t c = be32toh(card_fw->fw_ver);
4641 	uint32_t d, k;
4642 	int rc, fw_install;
4643 	struct fw_h bundled_fw;
4644 	bool load_attempted;
4645 
4646 	cfg = fw = NULL;
4647 	load_attempted = false;
4648 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4649 
4650 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4651 	if (t4_fw_install < 0) {
4652 		rc = load_fw_module(sc, &cfg, &fw);
4653 		if (rc != 0 || fw == NULL) {
4654 			device_printf(sc->dev,
4655 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4656 			    " will use compiled-in firmware version for"
4657 			    "hw.cxgbe.fw_install checks.\n",
4658 			    rc, cfg, fw);
4659 		} else {
4660 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4661 		}
4662 		load_attempted = true;
4663 	}
4664 	d = be32toh(bundled_fw.fw_ver);
4665 
4666 	if (reason != NULL)
4667 		goto install;
4668 
4669 	if ((sc->flags & FW_OK) == 0) {
4670 
4671 		if (c == 0xffffffff) {
4672 			reason = "missing";
4673 			goto install;
4674 		}
4675 
4676 		rc = 0;
4677 		goto done;
4678 	}
4679 
4680 	if (!fw_compatible(card_fw, &bundled_fw)) {
4681 		reason = "incompatible or unusable";
4682 		goto install;
4683 	}
4684 
4685 	if (d > c) {
4686 		reason = "older than the version bundled with this driver";
4687 		goto install;
4688 	}
4689 
4690 	if (fw_install == 2 && d != c) {
4691 		reason = "different than the version bundled with this driver";
4692 		goto install;
4693 	}
4694 
4695 	/* No reason to do anything to the firmware already on the card. */
4696 	rc = 0;
4697 	goto done;
4698 
4699 install:
4700 	rc = 0;
4701 	if ((*already)++)
4702 		goto done;
4703 
4704 	if (fw_install == 0) {
4705 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4706 		    "but the driver is prohibited from installing a firmware "
4707 		    "on the card.\n",
4708 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4709 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4710 
4711 		goto done;
4712 	}
4713 
4714 	/*
4715 	 * We'll attempt to install a firmware.  Load the module first (if it
4716 	 * hasn't been loaded already).
4717 	 */
4718 	if (!load_attempted) {
4719 		rc = load_fw_module(sc, &cfg, &fw);
4720 		if (rc != 0 || fw == NULL) {
4721 			device_printf(sc->dev,
4722 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4723 			    rc, cfg, fw);
4724 			/* carry on */
4725 		}
4726 	}
4727 	if (fw == NULL) {
4728 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4729 		    "but the driver cannot take corrective action because it "
4730 		    "is unable to load the firmware module.\n",
4731 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4732 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4733 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4734 		goto done;
4735 	}
4736 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4737 	if (k != d) {
4738 		MPASS(t4_fw_install > 0);
4739 		device_printf(sc->dev,
4740 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4741 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4742 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4743 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4744 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4745 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4746 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4747 		goto done;
4748 	}
4749 
4750 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4751 	    "installing firmware %u.%u.%u.%u on card.\n",
4752 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4753 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4754 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4755 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4756 
4757 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4758 	if (rc != 0) {
4759 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4760 	} else {
4761 		/* Installed successfully, update the cached header too. */
4762 		rc = ERESTART;
4763 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4764 	}
4765 done:
4766 	unload_fw_module(sc, cfg, fw);
4767 
4768 	return (rc);
4769 }
4770 
4771 /*
4772  * Establish contact with the firmware and attempt to become the master driver.
4773  *
4774  * A firmware will be installed to the card if needed (if the driver is allowed
4775  * to do so).
4776  */
4777 static int
4778 contact_firmware(struct adapter *sc)
4779 {
4780 	int rc, already = 0;
4781 	enum dev_state state;
4782 	struct fw_info *fw_info;
4783 	struct fw_hdr *card_fw;		/* fw on the card */
4784 	const struct fw_h *drv_fw;
4785 
4786 	fw_info = find_fw_info(chip_id(sc));
4787 	if (fw_info == NULL) {
4788 		device_printf(sc->dev,
4789 		    "unable to look up firmware information for chip %d.\n",
4790 		    chip_id(sc));
4791 		return (EINVAL);
4792 	}
4793 	drv_fw = &fw_info->fw_h;
4794 
4795 	/* Read the header of the firmware on the card */
4796 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4797 restart:
4798 	rc = -t4_get_fw_hdr(sc, card_fw);
4799 	if (rc != 0) {
4800 		device_printf(sc->dev,
4801 		    "unable to read firmware header from card's flash: %d\n",
4802 		    rc);
4803 		goto done;
4804 	}
4805 
4806 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4807 	    &already);
4808 	if (rc == ERESTART)
4809 		goto restart;
4810 	if (rc != 0)
4811 		goto done;
4812 
4813 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4814 	if (rc < 0 || state == DEV_STATE_ERR) {
4815 		rc = -rc;
4816 		device_printf(sc->dev,
4817 		    "failed to connect to the firmware: %d, %d.  "
4818 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4819 #if 0
4820 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4821 		    "not responding properly to HELLO", &already) == ERESTART)
4822 			goto restart;
4823 #endif
4824 		goto done;
4825 	}
4826 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4827 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4828 
4829 	if (rc == sc->pf) {
4830 		sc->flags |= MASTER_PF;
4831 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4832 		    NULL, &already);
4833 		if (rc == ERESTART)
4834 			rc = 0;
4835 		else if (rc != 0)
4836 			goto done;
4837 	} else if (state == DEV_STATE_UNINIT) {
4838 		/*
4839 		 * We didn't get to be the master so we definitely won't be
4840 		 * configuring the chip.  It's a bug if someone else hasn't
4841 		 * configured it already.
4842 		 */
4843 		device_printf(sc->dev, "couldn't be master(%d), "
4844 		    "device not already initialized either(%d).  "
4845 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4846 		rc = EPROTO;
4847 		goto done;
4848 	} else {
4849 		/*
4850 		 * Some other PF is the master and has configured the chip.
4851 		 * This is allowed but untested.
4852 		 */
4853 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4854 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4855 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4856 		sc->cfcsum = 0;
4857 		rc = 0;
4858 	}
4859 done:
4860 	if (rc != 0 && sc->flags & FW_OK) {
4861 		t4_fw_bye(sc, sc->mbox);
4862 		sc->flags &= ~FW_OK;
4863 	}
4864 	free(card_fw, M_CXGBE);
4865 	return (rc);
4866 }
4867 
4868 static int
4869 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4870     uint32_t mtype, uint32_t moff)
4871 {
4872 	struct fw_info *fw_info;
4873 	const struct firmware *dcfg, *rcfg = NULL;
4874 	const uint32_t *cfdata;
4875 	uint32_t cflen, addr;
4876 	int rc;
4877 
4878 	load_fw_module(sc, &dcfg, NULL);
4879 
4880 	/* Card specific interpretation of "default". */
4881 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4882 		if (pci_get_device(sc->dev) == 0x440a)
4883 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4884 		if (is_fpga(sc))
4885 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4886 	}
4887 
4888 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4889 		if (dcfg == NULL) {
4890 			device_printf(sc->dev,
4891 			    "KLD with default config is not available.\n");
4892 			rc = ENOENT;
4893 			goto done;
4894 		}
4895 		cfdata = dcfg->data;
4896 		cflen = dcfg->datasize & ~3;
4897 	} else {
4898 		char s[32];
4899 
4900 		fw_info = find_fw_info(chip_id(sc));
4901 		if (fw_info == NULL) {
4902 			device_printf(sc->dev,
4903 			    "unable to look up firmware information for chip %d.\n",
4904 			    chip_id(sc));
4905 			rc = EINVAL;
4906 			goto done;
4907 		}
4908 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4909 
4910 		rcfg = firmware_get(s);
4911 		if (rcfg == NULL) {
4912 			device_printf(sc->dev,
4913 			    "unable to load module \"%s\" for configuration "
4914 			    "profile \"%s\".\n", s, cfg_file);
4915 			rc = ENOENT;
4916 			goto done;
4917 		}
4918 		cfdata = rcfg->data;
4919 		cflen = rcfg->datasize & ~3;
4920 	}
4921 
4922 	if (cflen > FLASH_CFG_MAX_SIZE) {
4923 		device_printf(sc->dev,
4924 		    "config file too long (%d, max allowed is %d).\n",
4925 		    cflen, FLASH_CFG_MAX_SIZE);
4926 		rc = EINVAL;
4927 		goto done;
4928 	}
4929 
4930 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4931 	if (rc != 0) {
4932 		device_printf(sc->dev,
4933 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4934 		    __func__, mtype, moff, cflen, rc);
4935 		rc = EINVAL;
4936 		goto done;
4937 	}
4938 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4939 done:
4940 	if (rcfg != NULL)
4941 		firmware_put(rcfg, FIRMWARE_UNLOAD);
4942 	unload_fw_module(sc, dcfg, NULL);
4943 	return (rc);
4944 }
4945 
4946 struct caps_allowed {
4947 	uint16_t nbmcaps;
4948 	uint16_t linkcaps;
4949 	uint16_t switchcaps;
4950 	uint16_t niccaps;
4951 	uint16_t toecaps;
4952 	uint16_t rdmacaps;
4953 	uint16_t cryptocaps;
4954 	uint16_t iscsicaps;
4955 	uint16_t fcoecaps;
4956 };
4957 
4958 #define FW_PARAM_DEV(param) \
4959 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4960 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4961 #define FW_PARAM_PFVF(param) \
4962 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4963 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4964 
4965 /*
4966  * Provide a configuration profile to the firmware and have it initialize the
4967  * chip accordingly.  This may involve uploading a configuration file to the
4968  * card.
4969  */
4970 static int
4971 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4972     const struct caps_allowed *caps_allowed)
4973 {
4974 	int rc;
4975 	struct fw_caps_config_cmd caps;
4976 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
4977 
4978 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4979 	if (rc != 0) {
4980 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
4981 		return (rc);
4982 	}
4983 
4984 	bzero(&caps, sizeof(caps));
4985 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4986 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
4987 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
4988 		mtype = 0;
4989 		moff = 0;
4990 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4991 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
4992 		mtype = FW_MEMTYPE_FLASH;
4993 		moff = t4_flash_cfg_addr(sc);
4994 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4995 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4996 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4997 		    FW_LEN16(caps));
4998 	} else {
4999 		/*
5000 		 * Ask the firmware where it wants us to upload the config file.
5001 		 */
5002 		param = FW_PARAM_DEV(CF);
5003 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5004 		if (rc != 0) {
5005 			/* No support for config file?  Shouldn't happen. */
5006 			device_printf(sc->dev,
5007 			    "failed to query config file location: %d.\n", rc);
5008 			goto done;
5009 		}
5010 		mtype = G_FW_PARAMS_PARAM_Y(val);
5011 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
5012 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5013 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5014 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5015 		    FW_LEN16(caps));
5016 
5017 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
5018 		if (rc != 0) {
5019 			device_printf(sc->dev,
5020 			    "failed to upload config file to card: %d.\n", rc);
5021 			goto done;
5022 		}
5023 	}
5024 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5025 	if (rc != 0) {
5026 		device_printf(sc->dev, "failed to pre-process config file: %d "
5027 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
5028 		goto done;
5029 	}
5030 
5031 	finicsum = be32toh(caps.finicsum);
5032 	cfcsum = be32toh(caps.cfcsum);	/* actual */
5033 	if (finicsum != cfcsum) {
5034 		device_printf(sc->dev,
5035 		    "WARNING: config file checksum mismatch: %08x %08x\n",
5036 		    finicsum, cfcsum);
5037 	}
5038 	sc->cfcsum = cfcsum;
5039 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
5040 
5041 	/*
5042 	 * Let the firmware know what features will (not) be used so it can tune
5043 	 * things accordingly.
5044 	 */
5045 #define LIMIT_CAPS(x) do { \
5046 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
5047 } while (0)
5048 	LIMIT_CAPS(nbm);
5049 	LIMIT_CAPS(link);
5050 	LIMIT_CAPS(switch);
5051 	LIMIT_CAPS(nic);
5052 	LIMIT_CAPS(toe);
5053 	LIMIT_CAPS(rdma);
5054 	LIMIT_CAPS(crypto);
5055 	LIMIT_CAPS(iscsi);
5056 	LIMIT_CAPS(fcoe);
5057 #undef LIMIT_CAPS
5058 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
5059 		/*
5060 		 * TOE and hashfilters are mutually exclusive.  It is a config
5061 		 * file or firmware bug if both are reported as available.  Try
5062 		 * to cope with the situation in non-debug builds by disabling
5063 		 * TOE.
5064 		 */
5065 		MPASS(caps.toecaps == 0);
5066 
5067 		caps.toecaps = 0;
5068 		caps.rdmacaps = 0;
5069 		caps.iscsicaps = 0;
5070 	}
5071 
5072 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5073 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
5074 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5075 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
5076 	if (rc != 0) {
5077 		device_printf(sc->dev,
5078 		    "failed to process config file: %d.\n", rc);
5079 		goto done;
5080 	}
5081 
5082 	t4_tweak_chip_settings(sc);
5083 	set_params__pre_init(sc);
5084 
5085 	/* get basic stuff going */
5086 	rc = -t4_fw_initialize(sc, sc->mbox);
5087 	if (rc != 0) {
5088 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
5089 		goto done;
5090 	}
5091 done:
5092 	return (rc);
5093 }
5094 
5095 /*
5096  * Partition chip resources for use between various PFs, VFs, etc.
5097  */
5098 static int
5099 partition_resources(struct adapter *sc)
5100 {
5101 	char cfg_file[sizeof(t4_cfg_file)];
5102 	struct caps_allowed caps_allowed;
5103 	int rc;
5104 	bool fallback;
5105 
5106 	/* Only the master driver gets to configure the chip resources. */
5107 	MPASS(sc->flags & MASTER_PF);
5108 
5109 #define COPY_CAPS(x) do { \
5110 	caps_allowed.x##caps = t4_##x##caps_allowed; \
5111 } while (0)
5112 	bzero(&caps_allowed, sizeof(caps_allowed));
5113 	COPY_CAPS(nbm);
5114 	COPY_CAPS(link);
5115 	COPY_CAPS(switch);
5116 	COPY_CAPS(nic);
5117 	COPY_CAPS(toe);
5118 	COPY_CAPS(rdma);
5119 	COPY_CAPS(crypto);
5120 	COPY_CAPS(iscsi);
5121 	COPY_CAPS(fcoe);
5122 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
5123 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
5124 retry:
5125 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
5126 	if (rc != 0 && fallback) {
5127 		device_printf(sc->dev,
5128 		    "failed (%d) to configure card with \"%s\" profile, "
5129 		    "will fall back to a basic configuration and retry.\n",
5130 		    rc, cfg_file);
5131 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
5132 		bzero(&caps_allowed, sizeof(caps_allowed));
5133 		COPY_CAPS(switch);
5134 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
5135 		fallback = false;
5136 		goto retry;
5137 	}
5138 #undef COPY_CAPS
5139 	return (rc);
5140 }
5141 
5142 /*
5143  * Retrieve parameters that are needed (or nice to have) very early.
5144  */
5145 static int
5146 get_params__pre_init(struct adapter *sc)
5147 {
5148 	int rc;
5149 	uint32_t param[2], val[2];
5150 
5151 	t4_get_version_info(sc);
5152 
5153 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5154 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5155 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5156 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5157 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5158 
5159 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5160 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5161 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5162 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5163 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5164 
5165 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5166 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5167 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5168 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5169 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5170 
5171 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5172 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5173 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5174 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5175 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5176 
5177 	param[0] = FW_PARAM_DEV(PORTVEC);
5178 	param[1] = FW_PARAM_DEV(CCLK);
5179 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5180 	if (rc != 0) {
5181 		device_printf(sc->dev,
5182 		    "failed to query parameters (pre_init): %d.\n", rc);
5183 		return (rc);
5184 	}
5185 
5186 	sc->params.portvec = val[0];
5187 	sc->params.nports = bitcount32(val[0]);
5188 	sc->params.vpd.cclk = val[1];
5189 
5190 	/* Read device log parameters. */
5191 	rc = -t4_init_devlog_params(sc, 1);
5192 	if (rc == 0)
5193 		fixup_devlog_params(sc);
5194 	else {
5195 		device_printf(sc->dev,
5196 		    "failed to get devlog parameters: %d.\n", rc);
5197 		rc = 0;	/* devlog isn't critical for device operation */
5198 	}
5199 
5200 	return (rc);
5201 }
5202 
5203 /*
5204  * Any params that need to be set before FW_INITIALIZE.
5205  */
5206 static int
5207 set_params__pre_init(struct adapter *sc)
5208 {
5209 	int rc = 0;
5210 	uint32_t param, val;
5211 
5212 	if (chip_id(sc) >= CHELSIO_T6) {
5213 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5214 		val = 1;
5215 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5216 		/* firmwares < 1.20.1.0 do not have this param. */
5217 		if (rc == FW_EINVAL &&
5218 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5219 			rc = 0;
5220 		}
5221 		if (rc != 0) {
5222 			device_printf(sc->dev,
5223 			    "failed to enable high priority filters :%d.\n",
5224 			    rc);
5225 		}
5226 
5227 		param = FW_PARAM_DEV(PPOD_EDRAM);
5228 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5229 		if (rc == 0 && val == 1) {
5230 			rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param,
5231 			    &val);
5232 			if (rc != 0) {
5233 				device_printf(sc->dev,
5234 				    "failed to set PPOD_EDRAM: %d.\n", rc);
5235 			}
5236 		}
5237 	}
5238 
5239 	/* Enable opaque VIIDs with firmwares that support it. */
5240 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5241 	val = 1;
5242 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5243 	if (rc == 0 && val == 1)
5244 		sc->params.viid_smt_extn_support = true;
5245 	else
5246 		sc->params.viid_smt_extn_support = false;
5247 
5248 	return (rc);
5249 }
5250 
5251 /*
5252  * Retrieve various parameters that are of interest to the driver.  The device
5253  * has been initialized by the firmware at this point.
5254  */
5255 static int
5256 get_params__post_init(struct adapter *sc)
5257 {
5258 	int rc;
5259 	uint32_t param[7], val[7];
5260 	struct fw_caps_config_cmd caps;
5261 
5262 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5263 	param[1] = FW_PARAM_PFVF(EQ_START);
5264 	param[2] = FW_PARAM_PFVF(FILTER_START);
5265 	param[3] = FW_PARAM_PFVF(FILTER_END);
5266 	param[4] = FW_PARAM_PFVF(L2T_START);
5267 	param[5] = FW_PARAM_PFVF(L2T_END);
5268 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5269 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5270 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5271 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5272 	if (rc != 0) {
5273 		device_printf(sc->dev,
5274 		    "failed to query parameters (post_init): %d.\n", rc);
5275 		return (rc);
5276 	}
5277 
5278 	sc->sge.iq_start = val[0];
5279 	sc->sge.eq_start = val[1];
5280 	if ((int)val[3] > (int)val[2]) {
5281 		sc->tids.ftid_base = val[2];
5282 		sc->tids.ftid_end = val[3];
5283 		sc->tids.nftids = val[3] - val[2] + 1;
5284 	}
5285 	sc->vres.l2t.start = val[4];
5286 	sc->vres.l2t.size = val[5] - val[4] + 1;
5287 	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
5288 	    ("%s: L2 table size (%u) larger than expected (%u)",
5289 	    __func__, sc->vres.l2t.size, L2T_SIZE));
5290 	sc->params.core_vdd = val[6];
5291 
5292 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5293 	param[1] = FW_PARAM_PFVF(EQ_END);
5294 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5295 	if (rc != 0) {
5296 		device_printf(sc->dev,
5297 		    "failed to query parameters (post_init2): %d.\n", rc);
5298 		return (rc);
5299 	}
5300 	MPASS((int)val[0] >= sc->sge.iq_start);
5301 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5302 	MPASS((int)val[1] >= sc->sge.eq_start);
5303 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5304 
5305 	if (chip_id(sc) >= CHELSIO_T6) {
5306 
5307 		sc->tids.tid_base = t4_read_reg(sc,
5308 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5309 
5310 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5311 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5312 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5313 		if (rc != 0) {
5314 			device_printf(sc->dev,
5315 			   "failed to query hpfilter parameters: %d.\n", rc);
5316 			return (rc);
5317 		}
5318 		if ((int)val[1] > (int)val[0]) {
5319 			sc->tids.hpftid_base = val[0];
5320 			sc->tids.hpftid_end = val[1];
5321 			sc->tids.nhpftids = val[1] - val[0] + 1;
5322 
5323 			/*
5324 			 * These should go off if the layout changes and the
5325 			 * driver needs to catch up.
5326 			 */
5327 			MPASS(sc->tids.hpftid_base == 0);
5328 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5329 		}
5330 
5331 		param[0] = FW_PARAM_PFVF(RAWF_START);
5332 		param[1] = FW_PARAM_PFVF(RAWF_END);
5333 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5334 		if (rc != 0) {
5335 			device_printf(sc->dev,
5336 			   "failed to query rawf parameters: %d.\n", rc);
5337 			return (rc);
5338 		}
5339 		if ((int)val[1] > (int)val[0]) {
5340 			sc->rawf_base = val[0];
5341 			sc->nrawf = val[1] - val[0] + 1;
5342 		}
5343 	}
5344 
5345 	/*
5346 	 * MPSBGMAP is queried separately because only recent firmwares support
5347 	 * it as a parameter and we don't want the compound query above to fail
5348 	 * on older firmwares.
5349 	 */
5350 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5351 	val[0] = 0;
5352 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5353 	if (rc == 0)
5354 		sc->params.mps_bg_map = val[0];
5355 	else
5356 		sc->params.mps_bg_map = 0;
5357 
5358 	/*
5359 	 * Determine whether the firmware supports the filter2 work request.
5360 	 * This is queried separately for the same reason as MPSBGMAP above.
5361 	 */
5362 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5363 	val[0] = 0;
5364 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5365 	if (rc == 0)
5366 		sc->params.filter2_wr_support = val[0] != 0;
5367 	else
5368 		sc->params.filter2_wr_support = 0;
5369 
5370 	/*
5371 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5372 	 * This is queried separately for the same reason as other params above.
5373 	 */
5374 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5375 	val[0] = 0;
5376 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5377 	if (rc == 0)
5378 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5379 	else
5380 		sc->params.ulptx_memwrite_dsgl = false;
5381 
5382 	/* FW_RI_FR_NSMR_TPTE_WR support */
5383 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5384 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5385 	if (rc == 0)
5386 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5387 	else
5388 		sc->params.fr_nsmr_tpte_wr_support = false;
5389 
5390 	/* Support for 512 SGL entries per FR MR. */
5391 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5392 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5393 	if (rc == 0)
5394 		sc->params.dev_512sgl_mr = val[0] != 0;
5395 	else
5396 		sc->params.dev_512sgl_mr = false;
5397 
5398 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5399 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5400 	if (rc == 0)
5401 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5402 	else
5403 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5404 
5405 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5406 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5407 	if (rc == 0) {
5408 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5409 		sc->params.nsched_cls = val[0];
5410 	} else
5411 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5412 
5413 	/* get capabilites */
5414 	bzero(&caps, sizeof(caps));
5415 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5416 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5417 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5418 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5419 	if (rc != 0) {
5420 		device_printf(sc->dev,
5421 		    "failed to get card capabilities: %d.\n", rc);
5422 		return (rc);
5423 	}
5424 
5425 #define READ_CAPS(x) do { \
5426 	sc->x = htobe16(caps.x); \
5427 } while (0)
5428 	READ_CAPS(nbmcaps);
5429 	READ_CAPS(linkcaps);
5430 	READ_CAPS(switchcaps);
5431 	READ_CAPS(niccaps);
5432 	READ_CAPS(toecaps);
5433 	READ_CAPS(rdmacaps);
5434 	READ_CAPS(cryptocaps);
5435 	READ_CAPS(iscsicaps);
5436 	READ_CAPS(fcoecaps);
5437 
5438 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5439 		MPASS(chip_id(sc) > CHELSIO_T4);
5440 		MPASS(sc->toecaps == 0);
5441 		sc->toecaps = 0;
5442 
5443 		param[0] = FW_PARAM_DEV(NTID);
5444 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5445 		if (rc != 0) {
5446 			device_printf(sc->dev,
5447 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5448 			return (rc);
5449 		}
5450 		sc->tids.ntids = val[0];
5451 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5452 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5453 			sc->tids.ntids -= sc->tids.nhpftids;
5454 		}
5455 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5456 		sc->params.hash_filter = 1;
5457 	}
5458 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5459 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5460 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5461 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5462 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5463 		if (rc != 0) {
5464 			device_printf(sc->dev,
5465 			    "failed to query NIC parameters: %d.\n", rc);
5466 			return (rc);
5467 		}
5468 		if ((int)val[1] > (int)val[0]) {
5469 			sc->tids.etid_base = val[0];
5470 			sc->tids.etid_end = val[1];
5471 			sc->tids.netids = val[1] - val[0] + 1;
5472 			sc->params.eo_wr_cred = val[2];
5473 			sc->params.ethoffload = 1;
5474 		}
5475 	}
5476 	if (sc->toecaps) {
5477 		/* query offload-related parameters */
5478 		param[0] = FW_PARAM_DEV(NTID);
5479 		param[1] = FW_PARAM_PFVF(SERVER_START);
5480 		param[2] = FW_PARAM_PFVF(SERVER_END);
5481 		param[3] = FW_PARAM_PFVF(TDDP_START);
5482 		param[4] = FW_PARAM_PFVF(TDDP_END);
5483 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5484 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5485 		if (rc != 0) {
5486 			device_printf(sc->dev,
5487 			    "failed to query TOE parameters: %d.\n", rc);
5488 			return (rc);
5489 		}
5490 		sc->tids.ntids = val[0];
5491 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5492 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5493 			sc->tids.ntids -= sc->tids.nhpftids;
5494 		}
5495 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5496 		if ((int)val[2] > (int)val[1]) {
5497 			sc->tids.stid_base = val[1];
5498 			sc->tids.nstids = val[2] - val[1] + 1;
5499 		}
5500 		sc->vres.ddp.start = val[3];
5501 		sc->vres.ddp.size = val[4] - val[3] + 1;
5502 		sc->params.ofldq_wr_cred = val[5];
5503 		sc->params.offload = 1;
5504 	} else {
5505 		/*
5506 		 * The firmware attempts memfree TOE configuration for -SO cards
5507 		 * and will report toecaps=0 if it runs out of resources (this
5508 		 * depends on the config file).  It may not report 0 for other
5509 		 * capabilities dependent on the TOE in this case.  Set them to
5510 		 * 0 here so that the driver doesn't bother tracking resources
5511 		 * that will never be used.
5512 		 */
5513 		sc->iscsicaps = 0;
5514 		sc->rdmacaps = 0;
5515 	}
5516 	if (sc->rdmacaps) {
5517 		param[0] = FW_PARAM_PFVF(STAG_START);
5518 		param[1] = FW_PARAM_PFVF(STAG_END);
5519 		param[2] = FW_PARAM_PFVF(RQ_START);
5520 		param[3] = FW_PARAM_PFVF(RQ_END);
5521 		param[4] = FW_PARAM_PFVF(PBL_START);
5522 		param[5] = FW_PARAM_PFVF(PBL_END);
5523 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5524 		if (rc != 0) {
5525 			device_printf(sc->dev,
5526 			    "failed to query RDMA parameters(1): %d.\n", rc);
5527 			return (rc);
5528 		}
5529 		sc->vres.stag.start = val[0];
5530 		sc->vres.stag.size = val[1] - val[0] + 1;
5531 		sc->vres.rq.start = val[2];
5532 		sc->vres.rq.size = val[3] - val[2] + 1;
5533 		sc->vres.pbl.start = val[4];
5534 		sc->vres.pbl.size = val[5] - val[4] + 1;
5535 
5536 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5537 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5538 		param[2] = FW_PARAM_PFVF(CQ_START);
5539 		param[3] = FW_PARAM_PFVF(CQ_END);
5540 		param[4] = FW_PARAM_PFVF(OCQ_START);
5541 		param[5] = FW_PARAM_PFVF(OCQ_END);
5542 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5543 		if (rc != 0) {
5544 			device_printf(sc->dev,
5545 			    "failed to query RDMA parameters(2): %d.\n", rc);
5546 			return (rc);
5547 		}
5548 		sc->vres.qp.start = val[0];
5549 		sc->vres.qp.size = val[1] - val[0] + 1;
5550 		sc->vres.cq.start = val[2];
5551 		sc->vres.cq.size = val[3] - val[2] + 1;
5552 		sc->vres.ocq.start = val[4];
5553 		sc->vres.ocq.size = val[5] - val[4] + 1;
5554 
5555 		param[0] = FW_PARAM_PFVF(SRQ_START);
5556 		param[1] = FW_PARAM_PFVF(SRQ_END);
5557 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5558 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5559 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5560 		if (rc != 0) {
5561 			device_printf(sc->dev,
5562 			    "failed to query RDMA parameters(3): %d.\n", rc);
5563 			return (rc);
5564 		}
5565 		sc->vres.srq.start = val[0];
5566 		sc->vres.srq.size = val[1] - val[0] + 1;
5567 		sc->params.max_ordird_qp = val[2];
5568 		sc->params.max_ird_adapter = val[3];
5569 	}
5570 	if (sc->iscsicaps) {
5571 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5572 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5573 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5574 		if (rc != 0) {
5575 			device_printf(sc->dev,
5576 			    "failed to query iSCSI parameters: %d.\n", rc);
5577 			return (rc);
5578 		}
5579 		sc->vres.iscsi.start = val[0];
5580 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5581 	}
5582 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5583 		param[0] = FW_PARAM_PFVF(TLS_START);
5584 		param[1] = FW_PARAM_PFVF(TLS_END);
5585 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5586 		if (rc != 0) {
5587 			device_printf(sc->dev,
5588 			    "failed to query TLS parameters: %d.\n", rc);
5589 			return (rc);
5590 		}
5591 		sc->vres.key.start = val[0];
5592 		sc->vres.key.size = val[1] - val[0] + 1;
5593 	}
5594 
5595 	/*
5596 	 * We've got the params we wanted to query directly from the firmware.
5597 	 * Grab some others via other means.
5598 	 */
5599 	t4_init_sge_params(sc);
5600 	t4_init_tp_params(sc);
5601 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5602 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5603 
5604 	rc = t4_verify_chip_settings(sc);
5605 	if (rc != 0)
5606 		return (rc);
5607 	t4_init_rx_buf_info(sc);
5608 
5609 	return (rc);
5610 }
5611 
5612 #ifdef KERN_TLS
5613 static void
5614 ktls_tick(void *arg)
5615 {
5616 	struct adapter *sc;
5617 	uint32_t tstamp;
5618 
5619 	sc = arg;
5620 	tstamp = tcp_ts_getticks();
5621 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5622 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5623 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5624 }
5625 
5626 static int
5627 t6_config_kern_tls(struct adapter *sc, bool enable)
5628 {
5629 	int rc;
5630 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5631 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5632 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5633 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5634 
5635 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5636 	if (rc != 0) {
5637 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5638 		    enable ?  "enable" : "disable", rc);
5639 		return (rc);
5640 	}
5641 
5642 	if (enable) {
5643 		sc->flags |= KERN_TLS_ON;
5644 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5645 		    C_HARDCLOCK);
5646 	} else {
5647 		sc->flags &= ~KERN_TLS_ON;
5648 		callout_stop(&sc->ktls_tick);
5649 	}
5650 
5651 	return (rc);
5652 }
5653 #endif
5654 
5655 static int
5656 set_params__post_init(struct adapter *sc)
5657 {
5658 	uint32_t mask, param, val;
5659 #ifdef TCP_OFFLOAD
5660 	int i, v, shift;
5661 #endif
5662 
5663 	/* ask for encapsulated CPLs */
5664 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5665 	val = 1;
5666 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5667 
5668 	/* Enable 32b port caps if the firmware supports it. */
5669 	param = FW_PARAM_PFVF(PORT_CAPS32);
5670 	val = 1;
5671 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5672 		sc->params.port_caps32 = 1;
5673 
5674 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5675 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5676 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5677 	    V_MASKFILTER(val - 1));
5678 
5679 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5680 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5681 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5682 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5683 	val = 0;
5684 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5685 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5686 		    F_ATTACKFILTERENABLE);
5687 		val |= F_DROPERRORATTACK;
5688 	}
5689 	if (t4_drop_ip_fragments != 0) {
5690 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5691 		    F_FRAGMENTDROP);
5692 		val |= F_DROPERRORFRAG;
5693 	}
5694 	if (t4_drop_pkts_with_l2_errors != 0)
5695 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5696 	if (t4_drop_pkts_with_l3_errors != 0) {
5697 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5698 		    F_DROPERRORCSUMIP;
5699 	}
5700 	if (t4_drop_pkts_with_l4_errors != 0) {
5701 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5702 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5703 	}
5704 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5705 
5706 #ifdef TCP_OFFLOAD
5707 	/*
5708 	 * Override the TOE timers with user provided tunables.  This is not the
5709 	 * recommended way to change the timers (the firmware config file is) so
5710 	 * these tunables are not documented.
5711 	 *
5712 	 * All the timer tunables are in microseconds.
5713 	 */
5714 	if (t4_toe_keepalive_idle != 0) {
5715 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5716 		v &= M_KEEPALIVEIDLE;
5717 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5718 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5719 	}
5720 	if (t4_toe_keepalive_interval != 0) {
5721 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5722 		v &= M_KEEPALIVEINTVL;
5723 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5724 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5725 	}
5726 	if (t4_toe_keepalive_count != 0) {
5727 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5728 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5729 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5730 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5731 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5732 	}
5733 	if (t4_toe_rexmt_min != 0) {
5734 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5735 		v &= M_RXTMIN;
5736 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5737 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5738 	}
5739 	if (t4_toe_rexmt_max != 0) {
5740 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5741 		v &= M_RXTMAX;
5742 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5743 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5744 	}
5745 	if (t4_toe_rexmt_count != 0) {
5746 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5747 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5748 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5749 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5750 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5751 	}
5752 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5753 		if (t4_toe_rexmt_backoff[i] != -1) {
5754 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5755 			shift = (i & 3) << 3;
5756 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5757 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5758 		}
5759 	}
5760 #endif
5761 
5762 #ifdef KERN_TLS
5763 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS &&
5764 	    sc->toecaps & FW_CAPS_CONFIG_TOE) {
5765 		/*
5766 		 * Limit TOE connections to 2 reassembly "islands".  This is
5767 		 * required for TOE TLS connections to downgrade to plain TOE
5768 		 * connections if an unsupported TLS version or ciphersuite is
5769 		 * used.
5770 		 */
5771 		t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG,
5772 		    V_PASSMODE(M_PASSMODE), V_PASSMODE(2));
5773 	}
5774 
5775 	if (is_ktls(sc)) {
5776 		sc->tlst.inline_keys = t4_tls_inline_keys;
5777 		sc->tlst.combo_wrs = t4_tls_combo_wrs;
5778 		if (t4_kern_tls != 0 && is_t6(sc))
5779 			t6_config_kern_tls(sc, true);
5780 	}
5781 #endif
5782 	return (0);
5783 }
5784 
5785 #undef FW_PARAM_PFVF
5786 #undef FW_PARAM_DEV
5787 
5788 static void
5789 t4_set_desc(struct adapter *sc)
5790 {
5791 	char buf[128];
5792 	struct adapter_params *p = &sc->params;
5793 
5794 	snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
5795 
5796 	device_set_desc_copy(sc->dev, buf);
5797 }
5798 
5799 static inline void
5800 ifmedia_add4(struct ifmedia *ifm, int m)
5801 {
5802 
5803 	ifmedia_add(ifm, m, 0, NULL);
5804 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5805 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5806 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5807 }
5808 
5809 /*
5810  * This is the selected media, which is not quite the same as the active media.
5811  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5812  * and active are not the same, and "media: Ethernet selected" otherwise.
5813  */
5814 static void
5815 set_current_media(struct port_info *pi)
5816 {
5817 	struct link_config *lc;
5818 	struct ifmedia *ifm;
5819 	int mword;
5820 	u_int speed;
5821 
5822 	PORT_LOCK_ASSERT_OWNED(pi);
5823 
5824 	/* Leave current media alone if it's already set to IFM_NONE. */
5825 	ifm = &pi->media;
5826 	if (ifm->ifm_cur != NULL &&
5827 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5828 		return;
5829 
5830 	lc = &pi->link_cfg;
5831 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5832 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5833 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5834 		return;
5835 	}
5836 	mword = IFM_ETHER | IFM_FDX;
5837 	if (lc->requested_fc & PAUSE_TX)
5838 		mword |= IFM_ETH_TXPAUSE;
5839 	if (lc->requested_fc & PAUSE_RX)
5840 		mword |= IFM_ETH_RXPAUSE;
5841 	if (lc->requested_speed == 0)
5842 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5843 	else
5844 		speed = lc->requested_speed;
5845 	mword |= port_mword(pi, speed_to_fwcap(speed));
5846 	ifmedia_set(ifm, mword);
5847 }
5848 
5849 /*
5850  * Returns true if the ifmedia list for the port cannot change.
5851  */
5852 static bool
5853 fixed_ifmedia(struct port_info *pi)
5854 {
5855 
5856 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5857 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5858 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5859 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5860 	    pi->port_type == FW_PORT_TYPE_KX ||
5861 	    pi->port_type == FW_PORT_TYPE_KR ||
5862 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5863 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5864 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5865 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5866 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5867 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5868 }
5869 
5870 static void
5871 build_medialist(struct port_info *pi)
5872 {
5873 	uint32_t ss, speed;
5874 	int unknown, mword, bit;
5875 	struct link_config *lc;
5876 	struct ifmedia *ifm;
5877 
5878 	PORT_LOCK_ASSERT_OWNED(pi);
5879 
5880 	if (pi->flags & FIXED_IFMEDIA)
5881 		return;
5882 
5883 	/*
5884 	 * Rebuild the ifmedia list.
5885 	 */
5886 	ifm = &pi->media;
5887 	ifmedia_removeall(ifm);
5888 	lc = &pi->link_cfg;
5889 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5890 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5891 		MPASS(ss != 0);
5892 no_media:
5893 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5894 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5895 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5896 		return;
5897 	}
5898 
5899 	unknown = 0;
5900 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5901 		speed = 1 << bit;
5902 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5903 		if (ss & speed) {
5904 			mword = port_mword(pi, speed);
5905 			if (mword == IFM_NONE) {
5906 				goto no_media;
5907 			} else if (mword == IFM_UNKNOWN)
5908 				unknown++;
5909 			else
5910 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5911 		}
5912 	}
5913 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5914 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5915 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5916 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5917 
5918 	set_current_media(pi);
5919 }
5920 
5921 /*
5922  * Initialize the requested fields in the link config based on driver tunables.
5923  */
5924 static void
5925 init_link_config(struct port_info *pi)
5926 {
5927 	struct link_config *lc = &pi->link_cfg;
5928 
5929 	PORT_LOCK_ASSERT_OWNED(pi);
5930 
5931 	lc->requested_caps = 0;
5932 	lc->requested_speed = 0;
5933 
5934 	if (t4_autoneg == 0)
5935 		lc->requested_aneg = AUTONEG_DISABLE;
5936 	else if (t4_autoneg == 1)
5937 		lc->requested_aneg = AUTONEG_ENABLE;
5938 	else
5939 		lc->requested_aneg = AUTONEG_AUTO;
5940 
5941 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5942 	    PAUSE_AUTONEG);
5943 
5944 	if (t4_fec & FEC_AUTO)
5945 		lc->requested_fec = FEC_AUTO;
5946 	else if (t4_fec == 0)
5947 		lc->requested_fec = FEC_NONE;
5948 	else {
5949 		/* -1 is handled by the FEC_AUTO block above and not here. */
5950 		lc->requested_fec = t4_fec &
5951 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5952 		if (lc->requested_fec == 0)
5953 			lc->requested_fec = FEC_AUTO;
5954 	}
5955 	if (t4_force_fec < 0)
5956 		lc->force_fec = -1;
5957 	else if (t4_force_fec > 0)
5958 		lc->force_fec = 1;
5959 	else
5960 		lc->force_fec = 0;
5961 }
5962 
5963 /*
5964  * Makes sure that all requested settings comply with what's supported by the
5965  * port.  Returns the number of settings that were invalid and had to be fixed.
5966  */
5967 static int
5968 fixup_link_config(struct port_info *pi)
5969 {
5970 	int n = 0;
5971 	struct link_config *lc = &pi->link_cfg;
5972 	uint32_t fwspeed;
5973 
5974 	PORT_LOCK_ASSERT_OWNED(pi);
5975 
5976 	/* Speed (when not autonegotiating) */
5977 	if (lc->requested_speed != 0) {
5978 		fwspeed = speed_to_fwcap(lc->requested_speed);
5979 		if ((fwspeed & lc->pcaps) == 0) {
5980 			n++;
5981 			lc->requested_speed = 0;
5982 		}
5983 	}
5984 
5985 	/* Link autonegotiation */
5986 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5987 	    lc->requested_aneg == AUTONEG_DISABLE ||
5988 	    lc->requested_aneg == AUTONEG_AUTO);
5989 	if (lc->requested_aneg == AUTONEG_ENABLE &&
5990 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5991 		n++;
5992 		lc->requested_aneg = AUTONEG_AUTO;
5993 	}
5994 
5995 	/* Flow control */
5996 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5997 	if (lc->requested_fc & PAUSE_TX &&
5998 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5999 		n++;
6000 		lc->requested_fc &= ~PAUSE_TX;
6001 	}
6002 	if (lc->requested_fc & PAUSE_RX &&
6003 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
6004 		n++;
6005 		lc->requested_fc &= ~PAUSE_RX;
6006 	}
6007 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
6008 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
6009 		n++;
6010 		lc->requested_fc |= PAUSE_AUTONEG;
6011 	}
6012 
6013 	/* FEC */
6014 	if ((lc->requested_fec & FEC_RS &&
6015 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
6016 	    (lc->requested_fec & FEC_BASER_RS &&
6017 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
6018 		n++;
6019 		lc->requested_fec = FEC_AUTO;
6020 	}
6021 
6022 	return (n);
6023 }
6024 
6025 /*
6026  * Apply the requested L1 settings, which are expected to be valid, to the
6027  * hardware.
6028  */
6029 static int
6030 apply_link_config(struct port_info *pi)
6031 {
6032 	struct adapter *sc = pi->adapter;
6033 	struct link_config *lc = &pi->link_cfg;
6034 	int rc;
6035 
6036 #ifdef INVARIANTS
6037 	ASSERT_SYNCHRONIZED_OP(sc);
6038 	PORT_LOCK_ASSERT_OWNED(pi);
6039 
6040 	if (lc->requested_aneg == AUTONEG_ENABLE)
6041 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
6042 	if (!(lc->requested_fc & PAUSE_AUTONEG))
6043 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
6044 	if (lc->requested_fc & PAUSE_TX)
6045 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
6046 	if (lc->requested_fc & PAUSE_RX)
6047 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
6048 	if (lc->requested_fec & FEC_RS)
6049 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
6050 	if (lc->requested_fec & FEC_BASER_RS)
6051 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
6052 #endif
6053 	rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
6054 	if (rc != 0) {
6055 		/* Don't complain if the VF driver gets back an EPERM. */
6056 		if (!(sc->flags & IS_VF) || rc != FW_EPERM)
6057 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
6058 	} else {
6059 		/*
6060 		 * An L1_CFG will almost always result in a link-change event if
6061 		 * the link is up, and the driver will refresh the actual
6062 		 * fec/fc/etc. when the notification is processed.  If the link
6063 		 * is down then the actual settings are meaningless.
6064 		 *
6065 		 * This takes care of the case where a change in the L1 settings
6066 		 * may not result in a notification.
6067 		 */
6068 		if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
6069 			lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
6070 	}
6071 	return (rc);
6072 }
6073 
6074 #define FW_MAC_EXACT_CHUNK	7
6075 struct mcaddr_ctx {
6076 	struct ifnet *ifp;
6077 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
6078 	uint64_t hash;
6079 	int i;
6080 	int del;
6081 	int rc;
6082 };
6083 
6084 static u_int
6085 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
6086 {
6087 	struct mcaddr_ctx *ctx = arg;
6088 	struct vi_info *vi = ctx->ifp->if_softc;
6089 	struct port_info *pi = vi->pi;
6090 	struct adapter *sc = pi->adapter;
6091 
6092 	if (ctx->rc < 0)
6093 		return (0);
6094 
6095 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
6096 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
6097 	ctx->i++;
6098 
6099 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
6100 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
6101 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
6102 		if (ctx->rc < 0) {
6103 			int j;
6104 
6105 			for (j = 0; j < ctx->i; j++) {
6106 				if_printf(ctx->ifp,
6107 				    "failed to add mc address"
6108 				    " %02x:%02x:%02x:"
6109 				    "%02x:%02x:%02x rc=%d\n",
6110 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
6111 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
6112 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
6113 				    -ctx->rc);
6114 			}
6115 			return (0);
6116 		}
6117 		ctx->del = 0;
6118 		ctx->i = 0;
6119 	}
6120 
6121 	return (1);
6122 }
6123 
6124 /*
6125  * Program the port's XGMAC based on parameters in ifnet.  The caller also
6126  * indicates which parameters should be programmed (the rest are left alone).
6127  */
6128 int
6129 update_mac_settings(struct ifnet *ifp, int flags)
6130 {
6131 	int rc = 0;
6132 	struct vi_info *vi = ifp->if_softc;
6133 	struct port_info *pi = vi->pi;
6134 	struct adapter *sc = pi->adapter;
6135 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
6136 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
6137 
6138 	ASSERT_SYNCHRONIZED_OP(sc);
6139 	KASSERT(flags, ("%s: not told what to update.", __func__));
6140 
6141 	if (flags & XGMAC_MTU)
6142 		mtu = ifp->if_mtu;
6143 
6144 	if (flags & XGMAC_PROMISC)
6145 		promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
6146 
6147 	if (flags & XGMAC_ALLMULTI)
6148 		allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
6149 
6150 	if (flags & XGMAC_VLANEX)
6151 		vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
6152 
6153 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
6154 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
6155 		    allmulti, 1, vlanex, false);
6156 		if (rc) {
6157 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
6158 			    rc);
6159 			return (rc);
6160 		}
6161 	}
6162 
6163 	if (flags & XGMAC_UCADDR) {
6164 		uint8_t ucaddr[ETHER_ADDR_LEN];
6165 
6166 		bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
6167 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
6168 		    ucaddr, true, &vi->smt_idx);
6169 		if (rc < 0) {
6170 			rc = -rc;
6171 			if_printf(ifp, "change_mac failed: %d\n", rc);
6172 			return (rc);
6173 		} else {
6174 			vi->xact_addr_filt = rc;
6175 			rc = 0;
6176 		}
6177 	}
6178 
6179 	if (flags & XGMAC_MCADDRS) {
6180 		struct epoch_tracker et;
6181 		struct mcaddr_ctx ctx;
6182 		int j;
6183 
6184 		ctx.ifp = ifp;
6185 		ctx.hash = 0;
6186 		ctx.i = 0;
6187 		ctx.del = 1;
6188 		ctx.rc = 0;
6189 		/*
6190 		 * Unlike other drivers, we accumulate list of pointers into
6191 		 * interface address lists and we need to keep it safe even
6192 		 * after if_foreach_llmaddr() returns, thus we must enter the
6193 		 * network epoch.
6194 		 */
6195 		NET_EPOCH_ENTER(et);
6196 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6197 		if (ctx.rc < 0) {
6198 			NET_EPOCH_EXIT(et);
6199 			rc = -ctx.rc;
6200 			return (rc);
6201 		}
6202 		if (ctx.i > 0) {
6203 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6204 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6205 			NET_EPOCH_EXIT(et);
6206 			if (rc < 0) {
6207 				rc = -rc;
6208 				for (j = 0; j < ctx.i; j++) {
6209 					if_printf(ifp,
6210 					    "failed to add mcast address"
6211 					    " %02x:%02x:%02x:"
6212 					    "%02x:%02x:%02x rc=%d\n",
6213 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6214 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6215 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6216 					    rc);
6217 				}
6218 				return (rc);
6219 			}
6220 			ctx.del = 0;
6221 		} else
6222 			NET_EPOCH_EXIT(et);
6223 
6224 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6225 		if (rc != 0)
6226 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6227 			    rc);
6228 		if (ctx.del == 0) {
6229 			/* We clobbered the VXLAN entry if there was one. */
6230 			pi->vxlan_tcam_entry = false;
6231 		}
6232 	}
6233 
6234 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6235 	    pi->vxlan_tcam_entry == false) {
6236 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6237 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6238 		    true);
6239 		if (rc < 0) {
6240 			rc = -rc;
6241 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6242 			    rc);
6243 		} else {
6244 			MPASS(rc == sc->rawf_base + pi->port_id);
6245 			rc = 0;
6246 			pi->vxlan_tcam_entry = true;
6247 		}
6248 	}
6249 
6250 	return (rc);
6251 }
6252 
6253 /*
6254  * {begin|end}_synchronized_op must be called from the same thread.
6255  */
6256 int
6257 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6258     char *wmesg)
6259 {
6260 	int rc, pri;
6261 
6262 #ifdef WITNESS
6263 	/* the caller thinks it's ok to sleep, but is it really? */
6264 	if (flags & SLEEP_OK)
6265 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6266 		    "begin_synchronized_op");
6267 #endif
6268 
6269 	if (INTR_OK)
6270 		pri = PCATCH;
6271 	else
6272 		pri = 0;
6273 
6274 	ADAPTER_LOCK(sc);
6275 	for (;;) {
6276 
6277 		if (vi && IS_DOOMED(vi)) {
6278 			rc = ENXIO;
6279 			goto done;
6280 		}
6281 
6282 		if (!IS_BUSY(sc)) {
6283 			rc = 0;
6284 			break;
6285 		}
6286 
6287 		if (!(flags & SLEEP_OK)) {
6288 			rc = EBUSY;
6289 			goto done;
6290 		}
6291 
6292 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6293 			rc = EINTR;
6294 			goto done;
6295 		}
6296 	}
6297 
6298 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6299 	SET_BUSY(sc);
6300 #ifdef INVARIANTS
6301 	sc->last_op = wmesg;
6302 	sc->last_op_thr = curthread;
6303 	sc->last_op_flags = flags;
6304 #endif
6305 
6306 done:
6307 	if (!(flags & HOLD_LOCK) || rc)
6308 		ADAPTER_UNLOCK(sc);
6309 
6310 	return (rc);
6311 }
6312 
6313 /*
6314  * Tell if_ioctl and if_init that the VI is going away.  This is
6315  * special variant of begin_synchronized_op and must be paired with a
6316  * call to end_synchronized_op.
6317  */
6318 void
6319 doom_vi(struct adapter *sc, struct vi_info *vi)
6320 {
6321 
6322 	ADAPTER_LOCK(sc);
6323 	SET_DOOMED(vi);
6324 	wakeup(&sc->flags);
6325 	while (IS_BUSY(sc))
6326 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6327 	SET_BUSY(sc);
6328 #ifdef INVARIANTS
6329 	sc->last_op = "t4detach";
6330 	sc->last_op_thr = curthread;
6331 	sc->last_op_flags = 0;
6332 #endif
6333 	ADAPTER_UNLOCK(sc);
6334 }
6335 
6336 /*
6337  * {begin|end}_synchronized_op must be called from the same thread.
6338  */
6339 void
6340 end_synchronized_op(struct adapter *sc, int flags)
6341 {
6342 
6343 	if (flags & LOCK_HELD)
6344 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6345 	else
6346 		ADAPTER_LOCK(sc);
6347 
6348 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6349 	CLR_BUSY(sc);
6350 	wakeup(&sc->flags);
6351 	ADAPTER_UNLOCK(sc);
6352 }
6353 
6354 static int
6355 cxgbe_init_synchronized(struct vi_info *vi)
6356 {
6357 	struct port_info *pi = vi->pi;
6358 	struct adapter *sc = pi->adapter;
6359 	struct ifnet *ifp = vi->ifp;
6360 	int rc = 0, i;
6361 	struct sge_txq *txq;
6362 
6363 	ASSERT_SYNCHRONIZED_OP(sc);
6364 
6365 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
6366 		return (0);	/* already running */
6367 
6368 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6369 		return (rc);	/* error message displayed already */
6370 
6371 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6372 		return (rc); /* error message displayed already */
6373 
6374 	rc = update_mac_settings(ifp, XGMAC_ALL);
6375 	if (rc)
6376 		goto done;	/* error message displayed already */
6377 
6378 	PORT_LOCK(pi);
6379 	if (pi->up_vis == 0) {
6380 		t4_update_port_info(pi);
6381 		fixup_link_config(pi);
6382 		build_medialist(pi);
6383 		apply_link_config(pi);
6384 	}
6385 
6386 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6387 	if (rc != 0) {
6388 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6389 		PORT_UNLOCK(pi);
6390 		goto done;
6391 	}
6392 
6393 	/*
6394 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6395 	 * if this changes.
6396 	 */
6397 
6398 	for_each_txq(vi, i, txq) {
6399 		TXQ_LOCK(txq);
6400 		txq->eq.flags |= EQ_ENABLED;
6401 		TXQ_UNLOCK(txq);
6402 	}
6403 
6404 	/*
6405 	 * The first iq of the first port to come up is used for tracing.
6406 	 */
6407 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6408 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6409 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6410 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6411 		    V_QUEUENUMBER(sc->traceq));
6412 		pi->flags |= HAS_TRACEQ;
6413 	}
6414 
6415 	/* all ok */
6416 	pi->up_vis++;
6417 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
6418 	if (pi->link_cfg.link_ok)
6419 		t4_os_link_changed(pi);
6420 	PORT_UNLOCK(pi);
6421 
6422 	mtx_lock(&vi->tick_mtx);
6423 	if (ifp->if_get_counter == vi_get_counter)
6424 		callout_reset(&vi->tick, hz, vi_tick, vi);
6425 	else
6426 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6427 	mtx_unlock(&vi->tick_mtx);
6428 done:
6429 	if (rc != 0)
6430 		cxgbe_uninit_synchronized(vi);
6431 
6432 	return (rc);
6433 }
6434 
6435 /*
6436  * Idempotent.
6437  */
6438 static int
6439 cxgbe_uninit_synchronized(struct vi_info *vi)
6440 {
6441 	struct port_info *pi = vi->pi;
6442 	struct adapter *sc = pi->adapter;
6443 	struct ifnet *ifp = vi->ifp;
6444 	int rc, i;
6445 	struct sge_txq *txq;
6446 
6447 	ASSERT_SYNCHRONIZED_OP(sc);
6448 
6449 	if (!(vi->flags & VI_INIT_DONE)) {
6450 		if (__predict_false(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6451 			KASSERT(0, ("uninited VI is running"));
6452 			if_printf(ifp, "uninited VI with running ifnet.  "
6453 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6454 			    "if_drv_flags 0x%08x\n", vi->flags, ifp->if_flags,
6455 			    ifp->if_drv_flags);
6456 		}
6457 		return (0);
6458 	}
6459 
6460 	/*
6461 	 * Disable the VI so that all its data in either direction is discarded
6462 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6463 	 * tick) intact as the TP can deliver negative advice or data that it's
6464 	 * holding in its RAM (for an offloaded connection) even after the VI is
6465 	 * disabled.
6466 	 */
6467 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6468 	if (rc) {
6469 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6470 		return (rc);
6471 	}
6472 
6473 	for_each_txq(vi, i, txq) {
6474 		TXQ_LOCK(txq);
6475 		txq->eq.flags &= ~EQ_ENABLED;
6476 		TXQ_UNLOCK(txq);
6477 	}
6478 
6479 	mtx_lock(&vi->tick_mtx);
6480 	callout_stop(&vi->tick);
6481 	mtx_unlock(&vi->tick_mtx);
6482 
6483 	PORT_LOCK(pi);
6484 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6485 		PORT_UNLOCK(pi);
6486 		return (0);
6487 	}
6488 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
6489 	pi->up_vis--;
6490 	if (pi->up_vis > 0) {
6491 		PORT_UNLOCK(pi);
6492 		return (0);
6493 	}
6494 
6495 	pi->link_cfg.link_ok = false;
6496 	pi->link_cfg.speed = 0;
6497 	pi->link_cfg.link_down_rc = 255;
6498 	t4_os_link_changed(pi);
6499 	PORT_UNLOCK(pi);
6500 
6501 	return (0);
6502 }
6503 
6504 /*
6505  * It is ok for this function to fail midway and return right away.  t4_detach
6506  * will walk the entire sc->irq list and clean up whatever is valid.
6507  */
6508 int
6509 t4_setup_intr_handlers(struct adapter *sc)
6510 {
6511 	int rc, rid, p, q, v;
6512 	char s[8];
6513 	struct irq *irq;
6514 	struct port_info *pi;
6515 	struct vi_info *vi;
6516 	struct sge *sge = &sc->sge;
6517 	struct sge_rxq *rxq;
6518 #ifdef TCP_OFFLOAD
6519 	struct sge_ofld_rxq *ofld_rxq;
6520 #endif
6521 #ifdef DEV_NETMAP
6522 	struct sge_nm_rxq *nm_rxq;
6523 #endif
6524 #ifdef RSS
6525 	int nbuckets = rss_getnumbuckets();
6526 #endif
6527 
6528 	/*
6529 	 * Setup interrupts.
6530 	 */
6531 	irq = &sc->irq[0];
6532 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6533 	if (forwarding_intr_to_fwq(sc))
6534 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6535 
6536 	/* Multiple interrupts. */
6537 	if (sc->flags & IS_VF)
6538 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6539 		    ("%s: too few intr.", __func__));
6540 	else
6541 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6542 		    ("%s: too few intr.", __func__));
6543 
6544 	/* The first one is always error intr on PFs */
6545 	if (!(sc->flags & IS_VF)) {
6546 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6547 		if (rc != 0)
6548 			return (rc);
6549 		irq++;
6550 		rid++;
6551 	}
6552 
6553 	/* The second one is always the firmware event queue (first on VFs) */
6554 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6555 	if (rc != 0)
6556 		return (rc);
6557 	irq++;
6558 	rid++;
6559 
6560 	for_each_port(sc, p) {
6561 		pi = sc->port[p];
6562 		for_each_vi(pi, v, vi) {
6563 			vi->first_intr = rid - 1;
6564 
6565 			if (vi->nnmrxq > 0) {
6566 				int n = max(vi->nrxq, vi->nnmrxq);
6567 
6568 				rxq = &sge->rxq[vi->first_rxq];
6569 #ifdef DEV_NETMAP
6570 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6571 #endif
6572 				for (q = 0; q < n; q++) {
6573 					snprintf(s, sizeof(s), "%x%c%x", p,
6574 					    'a' + v, q);
6575 					if (q < vi->nrxq)
6576 						irq->rxq = rxq++;
6577 #ifdef DEV_NETMAP
6578 					if (q < vi->nnmrxq)
6579 						irq->nm_rxq = nm_rxq++;
6580 
6581 					if (irq->nm_rxq != NULL &&
6582 					    irq->rxq == NULL) {
6583 						/* Netmap rx only */
6584 						rc = t4_alloc_irq(sc, irq, rid,
6585 						    t4_nm_intr, irq->nm_rxq, s);
6586 					}
6587 					if (irq->nm_rxq != NULL &&
6588 					    irq->rxq != NULL) {
6589 						/* NIC and Netmap rx */
6590 						rc = t4_alloc_irq(sc, irq, rid,
6591 						    t4_vi_intr, irq, s);
6592 					}
6593 #endif
6594 					if (irq->rxq != NULL &&
6595 					    irq->nm_rxq == NULL) {
6596 						/* NIC rx only */
6597 						rc = t4_alloc_irq(sc, irq, rid,
6598 						    t4_intr, irq->rxq, s);
6599 					}
6600 					if (rc != 0)
6601 						return (rc);
6602 #ifdef RSS
6603 					if (q < vi->nrxq) {
6604 						bus_bind_intr(sc->dev, irq->res,
6605 						    rss_getcpu(q % nbuckets));
6606 					}
6607 #endif
6608 					irq++;
6609 					rid++;
6610 					vi->nintr++;
6611 				}
6612 			} else {
6613 				for_each_rxq(vi, q, rxq) {
6614 					snprintf(s, sizeof(s), "%x%c%x", p,
6615 					    'a' + v, q);
6616 					rc = t4_alloc_irq(sc, irq, rid,
6617 					    t4_intr, rxq, s);
6618 					if (rc != 0)
6619 						return (rc);
6620 #ifdef RSS
6621 					bus_bind_intr(sc->dev, irq->res,
6622 					    rss_getcpu(q % nbuckets));
6623 #endif
6624 					irq++;
6625 					rid++;
6626 					vi->nintr++;
6627 				}
6628 			}
6629 #ifdef TCP_OFFLOAD
6630 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6631 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6632 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6633 				    ofld_rxq, s);
6634 				if (rc != 0)
6635 					return (rc);
6636 				irq++;
6637 				rid++;
6638 				vi->nintr++;
6639 			}
6640 #endif
6641 		}
6642 	}
6643 	MPASS(irq == &sc->irq[sc->intr_count]);
6644 
6645 	return (0);
6646 }
6647 
6648 static void
6649 write_global_rss_key(struct adapter *sc)
6650 {
6651 #ifdef RSS
6652 	int i;
6653 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6654 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6655 
6656 	CTASSERT(RSS_KEYSIZE == 40);
6657 
6658 	rss_getkey((void *)&raw_rss_key[0]);
6659 	for (i = 0; i < nitems(rss_key); i++) {
6660 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6661 	}
6662 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6663 #endif
6664 }
6665 
6666 /*
6667  * Idempotent.
6668  */
6669 static int
6670 adapter_full_init(struct adapter *sc)
6671 {
6672 	int rc, i;
6673 
6674 	ASSERT_SYNCHRONIZED_OP(sc);
6675 
6676 	/*
6677 	 * queues that belong to the adapter (not any particular port).
6678 	 */
6679 	rc = t4_setup_adapter_queues(sc);
6680 	if (rc != 0)
6681 		return (rc);
6682 
6683 	for (i = 0; i < nitems(sc->tq); i++) {
6684 		if (sc->tq[i] != NULL)
6685 			continue;
6686 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6687 		    taskqueue_thread_enqueue, &sc->tq[i]);
6688 		if (sc->tq[i] == NULL) {
6689 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6690 			return (ENOMEM);
6691 		}
6692 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6693 		    device_get_nameunit(sc->dev), i);
6694 	}
6695 
6696 	if (!(sc->flags & IS_VF)) {
6697 		write_global_rss_key(sc);
6698 		t4_intr_enable(sc);
6699 	}
6700 	return (0);
6701 }
6702 
6703 int
6704 adapter_init(struct adapter *sc)
6705 {
6706 	int rc;
6707 
6708 	ASSERT_SYNCHRONIZED_OP(sc);
6709 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6710 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6711 	    ("%s: FULL_INIT_DONE already", __func__));
6712 
6713 	rc = adapter_full_init(sc);
6714 	if (rc != 0)
6715 		adapter_full_uninit(sc);
6716 	else
6717 		sc->flags |= FULL_INIT_DONE;
6718 
6719 	return (rc);
6720 }
6721 
6722 /*
6723  * Idempotent.
6724  */
6725 static void
6726 adapter_full_uninit(struct adapter *sc)
6727 {
6728 	int i;
6729 
6730 	t4_teardown_adapter_queues(sc);
6731 
6732 	for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
6733 		taskqueue_free(sc->tq[i]);
6734 		sc->tq[i] = NULL;
6735 	}
6736 
6737 	sc->flags &= ~FULL_INIT_DONE;
6738 }
6739 
6740 #ifdef RSS
6741 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6742     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6743     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6744     RSS_HASHTYPE_RSS_UDP_IPV6)
6745 
6746 /* Translates kernel hash types to hardware. */
6747 static int
6748 hashconfig_to_hashen(int hashconfig)
6749 {
6750 	int hashen = 0;
6751 
6752 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6753 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6754 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6755 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6756 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6757 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6758 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6759 	}
6760 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6761 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6762 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6763 	}
6764 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6765 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6766 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6767 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6768 
6769 	return (hashen);
6770 }
6771 
6772 /* Translates hardware hash types to kernel. */
6773 static int
6774 hashen_to_hashconfig(int hashen)
6775 {
6776 	int hashconfig = 0;
6777 
6778 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6779 		/*
6780 		 * If UDP hashing was enabled it must have been enabled for
6781 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6782 		 * enabling any 4-tuple hash is nonsense configuration.
6783 		 */
6784 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6785 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6786 
6787 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6788 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6789 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6790 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6791 	}
6792 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6793 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6794 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6795 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6796 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6797 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6798 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6799 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6800 
6801 	return (hashconfig);
6802 }
6803 #endif
6804 
6805 /*
6806  * Idempotent.
6807  */
6808 static int
6809 vi_full_init(struct vi_info *vi)
6810 {
6811 	struct adapter *sc = vi->adapter;
6812 	struct sge_rxq *rxq;
6813 	int rc, i, j;
6814 #ifdef RSS
6815 	int nbuckets = rss_getnumbuckets();
6816 	int hashconfig = rss_gethashconfig();
6817 	int extra;
6818 #endif
6819 
6820 	ASSERT_SYNCHRONIZED_OP(sc);
6821 
6822 	/*
6823 	 * Allocate tx/rx/fl queues for this VI.
6824 	 */
6825 	rc = t4_setup_vi_queues(vi);
6826 	if (rc != 0)
6827 		return (rc);
6828 
6829 	/*
6830 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6831 	 */
6832 	if (vi->nrxq > vi->rss_size) {
6833 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6834 		    "some queues will never receive traffic.\n", vi->nrxq,
6835 		    vi->rss_size);
6836 	} else if (vi->rss_size % vi->nrxq) {
6837 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6838 		    "expect uneven traffic distribution.\n", vi->nrxq,
6839 		    vi->rss_size);
6840 	}
6841 #ifdef RSS
6842 	if (vi->nrxq != nbuckets) {
6843 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6844 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6845 	}
6846 #endif
6847 	if (vi->rss == NULL)
6848 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6849 		    M_ZERO | M_WAITOK);
6850 	for (i = 0; i < vi->rss_size;) {
6851 #ifdef RSS
6852 		j = rss_get_indirection_to_bucket(i);
6853 		j %= vi->nrxq;
6854 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6855 		vi->rss[i++] = rxq->iq.abs_id;
6856 #else
6857 		for_each_rxq(vi, j, rxq) {
6858 			vi->rss[i++] = rxq->iq.abs_id;
6859 			if (i == vi->rss_size)
6860 				break;
6861 		}
6862 #endif
6863 	}
6864 
6865 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6866 	    vi->rss, vi->rss_size);
6867 	if (rc != 0) {
6868 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6869 		return (rc);
6870 	}
6871 
6872 #ifdef RSS
6873 	vi->hashen = hashconfig_to_hashen(hashconfig);
6874 
6875 	/*
6876 	 * We may have had to enable some hashes even though the global config
6877 	 * wants them disabled.  This is a potential problem that must be
6878 	 * reported to the user.
6879 	 */
6880 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6881 
6882 	/*
6883 	 * If we consider only the supported hash types, then the enabled hashes
6884 	 * are a superset of the requested hashes.  In other words, there cannot
6885 	 * be any supported hash that was requested but not enabled, but there
6886 	 * can be hashes that were not requested but had to be enabled.
6887 	 */
6888 	extra &= SUPPORTED_RSS_HASHTYPES;
6889 	MPASS((extra & hashconfig) == 0);
6890 
6891 	if (extra) {
6892 		CH_ALERT(vi,
6893 		    "global RSS config (0x%x) cannot be accommodated.\n",
6894 		    hashconfig);
6895 	}
6896 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6897 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6898 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6899 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6900 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6901 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6902 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6903 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6904 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6905 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6906 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6907 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6908 #else
6909 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6910 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6911 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6912 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6913 #endif
6914 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6915 	    0, 0);
6916 	if (rc != 0) {
6917 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6918 		return (rc);
6919 	}
6920 
6921 	return (0);
6922 }
6923 
6924 int
6925 vi_init(struct vi_info *vi)
6926 {
6927 	int rc;
6928 
6929 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6930 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6931 	    ("%s: VI_INIT_DONE already", __func__));
6932 
6933 	rc = vi_full_init(vi);
6934 	if (rc != 0)
6935 		vi_full_uninit(vi);
6936 	else
6937 		vi->flags |= VI_INIT_DONE;
6938 
6939 	return (rc);
6940 }
6941 
6942 /*
6943  * Idempotent.
6944  */
6945 static void
6946 vi_full_uninit(struct vi_info *vi)
6947 {
6948 
6949 	if (vi->flags & VI_INIT_DONE) {
6950 		quiesce_vi(vi);
6951 		free(vi->rss, M_CXGBE);
6952 		free(vi->nm_rss, M_CXGBE);
6953 	}
6954 
6955 	t4_teardown_vi_queues(vi);
6956 	vi->flags &= ~VI_INIT_DONE;
6957 }
6958 
6959 static void
6960 quiesce_txq(struct sge_txq *txq)
6961 {
6962 	struct sge_eq *eq = &txq->eq;
6963 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6964 
6965 	MPASS(eq->flags & EQ_SW_ALLOCATED);
6966 	MPASS(!(eq->flags & EQ_ENABLED));
6967 
6968 	/* Wait for the mp_ring to empty. */
6969 	while (!mp_ring_is_idle(txq->r)) {
6970 		mp_ring_check_drainage(txq->r, 4096);
6971 		pause("rquiesce", 1);
6972 	}
6973 	MPASS(txq->txp.npkt == 0);
6974 
6975 	if (eq->flags & EQ_HW_ALLOCATED) {
6976 		/*
6977 		 * Hardware is alive and working normally.  Wait for it to
6978 		 * finish and then wait for the driver to catch up and reclaim
6979 		 * all descriptors.
6980 		 */
6981 		while (spg->cidx != htobe16(eq->pidx))
6982 			pause("equiesce", 1);
6983 		while (eq->cidx != eq->pidx)
6984 			pause("dquiesce", 1);
6985 	} else {
6986 		/*
6987 		 * Hardware is unavailable.  Discard all pending tx and reclaim
6988 		 * descriptors directly.
6989 		 */
6990 		TXQ_LOCK(txq);
6991 		while (eq->cidx != eq->pidx) {
6992 			struct mbuf *m, *nextpkt;
6993 			struct tx_sdesc *txsd;
6994 
6995 			txsd = &txq->sdesc[eq->cidx];
6996 			for (m = txsd->m; m != NULL; m = nextpkt) {
6997 				nextpkt = m->m_nextpkt;
6998 				m->m_nextpkt = NULL;
6999 				m_freem(m);
7000 			}
7001 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
7002 		}
7003 		spg->pidx = spg->cidx = htobe16(eq->cidx);
7004 		TXQ_UNLOCK(txq);
7005 	}
7006 }
7007 
7008 static void
7009 quiesce_wrq(struct sge_wrq *wrq)
7010 {
7011 
7012 	/* XXXTX */
7013 }
7014 
7015 static void
7016 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
7017 {
7018 	/* Synchronize with the interrupt handler */
7019 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
7020 		pause("iqfree", 1);
7021 
7022 	if (fl != NULL) {
7023 		MPASS(iq->flags & IQ_HAS_FL);
7024 
7025 		mtx_lock(&sc->sfl_lock);
7026 		FL_LOCK(fl);
7027 		fl->flags |= FL_DOOMED;
7028 		FL_UNLOCK(fl);
7029 		callout_stop(&sc->sfl_callout);
7030 		mtx_unlock(&sc->sfl_lock);
7031 
7032 		KASSERT((fl->flags & FL_STARVING) == 0,
7033 		    ("%s: still starving", __func__));
7034 
7035 		/* Release all buffers if hardware is no longer available. */
7036 		if (!(iq->flags & IQ_HW_ALLOCATED))
7037 			free_fl_buffers(sc, fl);
7038 	}
7039 }
7040 
7041 /*
7042  * Wait for all activity on all the queues of the VI to complete.  It is assumed
7043  * that no new work is being enqueued by the hardware or the driver.  That part
7044  * should be arranged before calling this function.
7045  */
7046 static void
7047 quiesce_vi(struct vi_info *vi)
7048 {
7049 	int i;
7050 	struct adapter *sc = vi->adapter;
7051 	struct sge_rxq *rxq;
7052 	struct sge_txq *txq;
7053 #ifdef TCP_OFFLOAD
7054 	struct sge_ofld_rxq *ofld_rxq;
7055 #endif
7056 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7057 	struct sge_ofld_txq *ofld_txq;
7058 #endif
7059 
7060 	if (!(vi->flags & VI_INIT_DONE))
7061 		return;
7062 
7063 	for_each_txq(vi, i, txq) {
7064 		quiesce_txq(txq);
7065 	}
7066 
7067 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7068 	for_each_ofld_txq(vi, i, ofld_txq) {
7069 		quiesce_wrq(&ofld_txq->wrq);
7070 	}
7071 #endif
7072 
7073 	for_each_rxq(vi, i, rxq) {
7074 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
7075 	}
7076 
7077 #ifdef TCP_OFFLOAD
7078 	for_each_ofld_rxq(vi, i, ofld_rxq) {
7079 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
7080 	}
7081 #endif
7082 }
7083 
7084 static int
7085 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
7086     driver_intr_t *handler, void *arg, char *name)
7087 {
7088 	int rc;
7089 
7090 	irq->rid = rid;
7091 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
7092 	    RF_SHAREABLE | RF_ACTIVE);
7093 	if (irq->res == NULL) {
7094 		device_printf(sc->dev,
7095 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
7096 		return (ENOMEM);
7097 	}
7098 
7099 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
7100 	    NULL, handler, arg, &irq->tag);
7101 	if (rc != 0) {
7102 		device_printf(sc->dev,
7103 		    "failed to setup interrupt for rid %d, name %s: %d\n",
7104 		    rid, name, rc);
7105 	} else if (name)
7106 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
7107 
7108 	return (rc);
7109 }
7110 
7111 static int
7112 t4_free_irq(struct adapter *sc, struct irq *irq)
7113 {
7114 	if (irq->tag)
7115 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
7116 	if (irq->res)
7117 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
7118 
7119 	bzero(irq, sizeof(*irq));
7120 
7121 	return (0);
7122 }
7123 
7124 static void
7125 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
7126 {
7127 
7128 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
7129 	t4_get_regs(sc, buf, regs->len);
7130 }
7131 
7132 #define	A_PL_INDIR_CMD	0x1f8
7133 
7134 #define	S_PL_AUTOINC	31
7135 #define	M_PL_AUTOINC	0x1U
7136 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
7137 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
7138 
7139 #define	S_PL_VFID	20
7140 #define	M_PL_VFID	0xffU
7141 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
7142 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
7143 
7144 #define	S_PL_ADDR	0
7145 #define	M_PL_ADDR	0xfffffU
7146 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
7147 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
7148 
7149 #define	A_PL_INDIR_DATA	0x1fc
7150 
7151 static uint64_t
7152 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7153 {
7154 	u32 stats[2];
7155 
7156 	if (sc->flags & IS_VF) {
7157 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7158 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7159 	} else {
7160 		mtx_assert(&sc->reg_lock, MA_OWNED);
7161 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7162 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7163 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7164 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7165 	}
7166 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7167 }
7168 
7169 static void
7170 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7171 {
7172 
7173 #define GET_STAT(name) \
7174 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7175 
7176 	if (!(sc->flags & IS_VF))
7177 		mtx_lock(&sc->reg_lock);
7178 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7179 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7180 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7181 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7182 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7183 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7184 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7185 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7186 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7187 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7188 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7189 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7190 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7191 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7192 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7193 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7194 	if (!(sc->flags & IS_VF))
7195 		mtx_unlock(&sc->reg_lock);
7196 
7197 #undef GET_STAT
7198 }
7199 
7200 static void
7201 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7202 {
7203 	int reg;
7204 
7205 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7206 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7207 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7208 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7209 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7210 }
7211 
7212 static void
7213 vi_refresh_stats(struct vi_info *vi)
7214 {
7215 	struct timeval tv;
7216 	const struct timeval interval = {0, 250000};	/* 250ms */
7217 
7218 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7219 
7220 	if (vi->flags & VI_SKIP_STATS)
7221 		return;
7222 
7223 	getmicrotime(&tv);
7224 	timevalsub(&tv, &interval);
7225 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7226 		return;
7227 
7228 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7229 	getmicrotime(&vi->last_refreshed);
7230 }
7231 
7232 static void
7233 cxgbe_refresh_stats(struct vi_info *vi)
7234 {
7235 	u_int i, v, tnl_cong_drops, chan_map;
7236 	struct timeval tv;
7237 	const struct timeval interval = {0, 250000};	/* 250ms */
7238 	struct port_info *pi;
7239 	struct adapter *sc;
7240 
7241 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7242 
7243 	if (vi->flags & VI_SKIP_STATS)
7244 		return;
7245 
7246 	getmicrotime(&tv);
7247 	timevalsub(&tv, &interval);
7248 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7249 		return;
7250 
7251 	pi = vi->pi;
7252 	sc = vi->adapter;
7253 	tnl_cong_drops = 0;
7254 	t4_get_port_stats(sc, pi->port_id, &pi->stats);
7255 	chan_map = pi->rx_e_chan_map;
7256 	while (chan_map) {
7257 		i = ffs(chan_map) - 1;
7258 		mtx_lock(&sc->reg_lock);
7259 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7260 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7261 		mtx_unlock(&sc->reg_lock);
7262 		tnl_cong_drops += v;
7263 		chan_map &= ~(1 << i);
7264 	}
7265 	pi->tnl_cong_drops = tnl_cong_drops;
7266 	getmicrotime(&vi->last_refreshed);
7267 }
7268 
7269 static void
7270 cxgbe_tick(void *arg)
7271 {
7272 	struct vi_info *vi = arg;
7273 
7274 	MPASS(IS_MAIN_VI(vi));
7275 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7276 
7277 	cxgbe_refresh_stats(vi);
7278 	callout_schedule(&vi->tick, hz);
7279 }
7280 
7281 static void
7282 vi_tick(void *arg)
7283 {
7284 	struct vi_info *vi = arg;
7285 
7286 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7287 
7288 	vi_refresh_stats(vi);
7289 	callout_schedule(&vi->tick, hz);
7290 }
7291 
7292 /*
7293  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7294  */
7295 static char *caps_decoder[] = {
7296 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7297 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7298 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7299 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7300 	    "\006HASHFILTER\007ETHOFLD",
7301 	"\20\001TOE",					/* 4: TOE */
7302 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7303 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7304 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7305 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7306 	    "\007T10DIF"
7307 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7308 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7309 	    "\004TLS_HW",
7310 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7311 		    "\004PO_INITIATOR\005PO_TARGET",
7312 };
7313 
7314 void
7315 t4_sysctls(struct adapter *sc)
7316 {
7317 	struct sysctl_ctx_list *ctx = &sc->ctx;
7318 	struct sysctl_oid *oid;
7319 	struct sysctl_oid_list *children, *c0;
7320 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7321 
7322 	/*
7323 	 * dev.t4nex.X.
7324 	 */
7325 	oid = device_get_sysctl_tree(sc->dev);
7326 	c0 = children = SYSCTL_CHILDREN(oid);
7327 
7328 	sc->sc_do_rxcopy = 1;
7329 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7330 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7331 
7332 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7333 	    sc->params.nports, "# of ports");
7334 
7335 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7336 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7337 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7338 	    "available doorbells");
7339 
7340 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7341 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7342 
7343 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7344 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7345 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7346 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7347 
7348 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7349 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7350 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7351 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7352 
7353 	t4_sge_sysctls(sc, ctx, children);
7354 
7355 	sc->lro_timeout = 100;
7356 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7357 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7358 
7359 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7360 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7361 
7362 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7363 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7364 
7365 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7366 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7367 
7368 	if (sc->flags & IS_VF)
7369 		return;
7370 
7371 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7372 	    NULL, chip_rev(sc), "chip hardware revision");
7373 
7374 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7375 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7376 
7377 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7378 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7379 
7380 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7381 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7382 
7383 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7384 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7385 
7386 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7387 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7388 
7389 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7390 	    sc->er_version, 0, "expansion ROM version");
7391 
7392 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7393 	    sc->bs_version, 0, "bootstrap firmware version");
7394 
7395 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7396 	    NULL, sc->params.scfg_vers, "serial config version");
7397 
7398 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7399 	    NULL, sc->params.vpd_vers, "VPD version");
7400 
7401 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7402 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7403 
7404 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7405 	    sc->cfcsum, "config file checksum");
7406 
7407 #define SYSCTL_CAP(name, n, text) \
7408 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7409 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7410 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7411 	    "available " text " capabilities")
7412 
7413 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7414 	SYSCTL_CAP(linkcaps, 1, "link");
7415 	SYSCTL_CAP(switchcaps, 2, "switch");
7416 	SYSCTL_CAP(niccaps, 3, "NIC");
7417 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7418 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7419 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7420 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7421 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7422 #undef SYSCTL_CAP
7423 
7424 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7425 	    NULL, sc->tids.nftids, "number of filters");
7426 
7427 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7428 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7429 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7430 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7431 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7432 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7433 
7434 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7435 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7436 	    sysctl_loadavg, "A",
7437 	    "microprocessor load averages (debug firmwares only)");
7438 
7439 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7440 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7441 	    "I", "core Vdd (in mV)");
7442 
7443 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7444 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7445 	    sysctl_cpus, "A", "local CPUs");
7446 
7447 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7448 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7449 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7450 
7451 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7452 	    &sc->swintr, 0, "software triggered interrupts");
7453 
7454 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7455 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7456 	    "1 = reset adapter, 0 = zero reset counter");
7457 
7458 	/*
7459 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7460 	 */
7461 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7462 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7463 	    "logs and miscellaneous information");
7464 	children = SYSCTL_CHILDREN(oid);
7465 
7466 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7467 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7468 	    sysctl_cctrl, "A", "congestion control");
7469 
7470 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7471 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7472 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7473 
7474 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7475 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7476 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7477 
7478 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7479 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7480 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7481 
7482 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7483 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7484 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7485 
7486 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7487 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7488 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7489 
7490 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7491 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7492 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7493 
7494 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7495 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7496 	    sysctl_cim_la, "A", "CIM logic analyzer");
7497 
7498 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7499 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7500 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7501 
7502 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7503 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7504 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7505 
7506 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7507 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7508 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7509 
7510 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7511 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7512 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7513 
7514 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7515 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7516 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7517 
7518 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7519 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7520 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7521 
7522 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7523 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7524 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7525 
7526 	if (chip_id(sc) > CHELSIO_T4) {
7527 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7528 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7529 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7530 		    "CIM OBQ 6 (SGE0-RX)");
7531 
7532 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7533 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7534 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7535 		    "CIM OBQ 7 (SGE1-RX)");
7536 	}
7537 
7538 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7539 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7540 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7541 
7542 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7543 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7544 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7545 
7546 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7547 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7548 	    sysctl_cpl_stats, "A", "CPL statistics");
7549 
7550 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7551 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7552 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7553 
7554 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7555 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7556 	    sysctl_tid_stats, "A", "tid stats");
7557 
7558 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7559 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7560 	    sysctl_devlog, "A", "firmware's device log");
7561 
7562 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7563 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7564 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7565 
7566 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7567 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7568 	    sysctl_hw_sched, "A", "hardware scheduler ");
7569 
7570 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7571 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7572 	    sysctl_l2t, "A", "hardware L2 table");
7573 
7574 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7575 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7576 	    sysctl_smt, "A", "hardware source MAC table");
7577 
7578 #ifdef INET6
7579 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7580 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7581 	    sysctl_clip, "A", "active CLIP table entries");
7582 #endif
7583 
7584 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7585 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7586 	    sysctl_lb_stats, "A", "loopback statistics");
7587 
7588 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7589 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7590 	    sysctl_meminfo, "A", "memory regions");
7591 
7592 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7593 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7594 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7595 	    "A", "MPS TCAM entries");
7596 
7597 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7598 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7599 	    sysctl_path_mtus, "A", "path MTUs");
7600 
7601 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7602 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7603 	    sysctl_pm_stats, "A", "PM statistics");
7604 
7605 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7606 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7607 	    sysctl_rdma_stats, "A", "RDMA statistics");
7608 
7609 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7610 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7611 	    sysctl_tcp_stats, "A", "TCP statistics");
7612 
7613 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7614 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7615 	    sysctl_tids, "A", "TID information");
7616 
7617 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7618 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7619 	    sysctl_tp_err_stats, "A", "TP error statistics");
7620 
7621 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7622 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7623 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7624 
7625 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7626 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7627 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7628 
7629 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7630 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7631 	    sysctl_tp_la, "A", "TP logic analyzer");
7632 
7633 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7634 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7635 	    sysctl_tx_rate, "A", "Tx rate");
7636 
7637 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7638 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7639 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7640 
7641 	if (chip_id(sc) >= CHELSIO_T5) {
7642 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7643 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7644 		    sysctl_wcwr_stats, "A", "write combined work requests");
7645 	}
7646 
7647 #ifdef KERN_TLS
7648 	if (is_ktls(sc)) {
7649 		/*
7650 		 * dev.t4nex.0.tls.
7651 		 */
7652 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7653 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7654 		children = SYSCTL_CHILDREN(oid);
7655 
7656 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7657 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7658 		    "keys in work requests (1) or attempt to store TLS keys "
7659 		    "in card memory.");
7660 
7661 		if (is_t6(sc))
7662 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7663 			    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to "
7664 			    "combine TCB field updates with TLS record work "
7665 			    "requests.");
7666 	}
7667 #endif
7668 
7669 #ifdef TCP_OFFLOAD
7670 	if (is_offload(sc)) {
7671 		int i;
7672 		char s[4];
7673 
7674 		/*
7675 		 * dev.t4nex.X.toe.
7676 		 */
7677 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7678 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7679 		children = SYSCTL_CHILDREN(oid);
7680 
7681 		sc->tt.cong_algorithm = -1;
7682 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7683 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7684 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7685 		    "3 = highspeed)");
7686 
7687 		sc->tt.sndbuf = -1;
7688 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7689 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7690 
7691 		sc->tt.ddp = 0;
7692 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7693 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7694 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7695 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7696 
7697 		sc->tt.rx_coalesce = -1;
7698 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7699 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7700 
7701 		sc->tt.tls = 0;
7702 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7703 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7704 		    "Inline TLS allowed");
7705 
7706 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_ports",
7707 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7708 		    sysctl_tls_rx_ports, "I",
7709 		    "TCP ports that use inline TLS+TOE RX");
7710 
7711 		sc->tt.tls_rx_timeout = t4_toe_tls_rx_timeout;
7712 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_timeout",
7713 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7714 		    sysctl_tls_rx_timeout, "I",
7715 		    "Timeout in seconds to downgrade TLS sockets to plain TOE");
7716 
7717 		sc->tt.tx_align = -1;
7718 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7719 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7720 
7721 		sc->tt.tx_zcopy = 0;
7722 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7723 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7724 		    "Enable zero-copy aio_write(2)");
7725 
7726 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7727 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7728 		    "cop_managed_offloading", CTLFLAG_RW,
7729 		    &sc->tt.cop_managed_offloading, 0,
7730 		    "COP (Connection Offload Policy) controls all TOE offload");
7731 
7732 		sc->tt.autorcvbuf_inc = 16 * 1024;
7733 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7734 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7735 		    "autorcvbuf increment");
7736 
7737 		sc->tt.update_hc_on_pmtu_change = 1;
7738 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7739 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7740 		    &sc->tt.update_hc_on_pmtu_change, 0,
7741 		    "Update hostcache entry if the PMTU changes");
7742 
7743 		sc->tt.iso = 1;
7744 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7745 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7746 
7747 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7748 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7749 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7750 
7751 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7752 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7753 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7754 
7755 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7756 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7757 		    sysctl_tp_tick, "A", "DACK tick (us)");
7758 
7759 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7760 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7761 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7762 
7763 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7764 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7765 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7766 		    "Minimum retransmit interval (us)");
7767 
7768 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7769 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7770 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7771 		    "Maximum retransmit interval (us)");
7772 
7773 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7774 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7775 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7776 		    "Persist timer min (us)");
7777 
7778 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7779 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7780 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7781 		    "Persist timer max (us)");
7782 
7783 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7784 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7785 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7786 		    "Keepalive idle timer (us)");
7787 
7788 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7789 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7790 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7791 		    "Keepalive interval timer (us)");
7792 
7793 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7794 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7795 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7796 
7797 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7798 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7799 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7800 		    "FINWAIT2 timer (us)");
7801 
7802 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7803 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7804 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7805 		    "Number of SYN retransmissions before abort");
7806 
7807 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7808 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7809 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7810 		    "Number of retransmissions before abort");
7811 
7812 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7813 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7814 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7815 		    "Number of keepalive probes before abort");
7816 
7817 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7818 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7819 		    "TOE retransmit backoffs");
7820 		children = SYSCTL_CHILDREN(oid);
7821 		for (i = 0; i < 16; i++) {
7822 			snprintf(s, sizeof(s), "%u", i);
7823 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7824 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7825 			    i, sysctl_tp_backoff, "IU",
7826 			    "TOE retransmit backoff");
7827 		}
7828 	}
7829 #endif
7830 }
7831 
7832 void
7833 vi_sysctls(struct vi_info *vi)
7834 {
7835 	struct sysctl_ctx_list *ctx = &vi->ctx;
7836 	struct sysctl_oid *oid;
7837 	struct sysctl_oid_list *children;
7838 
7839 	/*
7840 	 * dev.v?(cxgbe|cxl).X.
7841 	 */
7842 	oid = device_get_sysctl_tree(vi->dev);
7843 	children = SYSCTL_CHILDREN(oid);
7844 
7845 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7846 	    vi->viid, "VI identifer");
7847 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7848 	    &vi->nrxq, 0, "# of rx queues");
7849 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7850 	    &vi->ntxq, 0, "# of tx queues");
7851 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7852 	    &vi->first_rxq, 0, "index of first rx queue");
7853 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7854 	    &vi->first_txq, 0, "index of first tx queue");
7855 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7856 	    vi->rss_base, "start of RSS indirection table");
7857 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7858 	    vi->rss_size, "size of RSS indirection table");
7859 
7860 	if (IS_MAIN_VI(vi)) {
7861 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7862 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7863 		    sysctl_noflowq, "IU",
7864 		    "Reserve queue 0 for non-flowid packets");
7865 	}
7866 
7867 	if (vi->adapter->flags & IS_VF) {
7868 		MPASS(vi->flags & TX_USES_VM_WR);
7869 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7870 		    NULL, 1, "use VM work requests for transmit");
7871 	} else {
7872 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7873 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7874 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7875 	}
7876 
7877 #ifdef TCP_OFFLOAD
7878 	if (vi->nofldrxq != 0) {
7879 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7880 		    &vi->nofldrxq, 0,
7881 		    "# of rx queues for offloaded TCP connections");
7882 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7883 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7884 		    "index of first TOE rx queue");
7885 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7886 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7887 		    sysctl_holdoff_tmr_idx_ofld, "I",
7888 		    "holdoff timer index for TOE queues");
7889 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7890 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7891 		    sysctl_holdoff_pktc_idx_ofld, "I",
7892 		    "holdoff packet counter index for TOE queues");
7893 	}
7894 #endif
7895 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7896 	if (vi->nofldtxq != 0) {
7897 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7898 		    &vi->nofldtxq, 0,
7899 		    "# of tx queues for TOE/ETHOFLD");
7900 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7901 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7902 		    "index of first TOE/ETHOFLD tx queue");
7903 	}
7904 #endif
7905 #ifdef DEV_NETMAP
7906 	if (vi->nnmrxq != 0) {
7907 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7908 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7909 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7910 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7911 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7912 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7913 		    "index of first netmap rx queue");
7914 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7915 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7916 		    "index of first netmap tx queue");
7917 	}
7918 #endif
7919 
7920 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7921 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7922 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7923 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7924 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7925 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7926 
7927 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7928 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7929 	    sysctl_qsize_rxq, "I", "rx queue size");
7930 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7931 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7932 	    sysctl_qsize_txq, "I", "tx queue size");
7933 }
7934 
7935 static void
7936 cxgbe_sysctls(struct port_info *pi)
7937 {
7938 	struct sysctl_ctx_list *ctx = &pi->ctx;
7939 	struct sysctl_oid *oid;
7940 	struct sysctl_oid_list *children, *children2;
7941 	struct adapter *sc = pi->adapter;
7942 	int i;
7943 	char name[16];
7944 	static char *tc_flags = {"\20\1USER"};
7945 
7946 	/*
7947 	 * dev.cxgbe.X.
7948 	 */
7949 	oid = device_get_sysctl_tree(pi->dev);
7950 	children = SYSCTL_CHILDREN(oid);
7951 
7952 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7953 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7954 	    sysctl_linkdnrc, "A", "reason why link is down");
7955 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7956 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7957 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7958 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
7959 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7960 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7961 		    sysctl_btphy, "I", "PHY firmware version");
7962 	}
7963 
7964 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7965 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7966 	    sysctl_pause_settings, "A",
7967 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7968 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
7969 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
7970 	    "FEC in use on the link");
7971 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
7972 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7973 	    sysctl_requested_fec, "A",
7974 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7975 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7976 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7977 	    "FEC recommended by the cable/transceiver");
7978 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7979 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7980 	    sysctl_autoneg, "I",
7981 	    "autonegotiation (-1 = not supported)");
7982 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
7983 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7984 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
7985 
7986 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
7987 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
7988 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7989 	    &pi->link_cfg.pcaps, 0, "port capabilities");
7990 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7991 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
7992 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7993 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7994 
7995 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7996 	    port_top_speed(pi), "max speed (in Gbps)");
7997 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7998 	    pi->mps_bg_map, "MPS buffer group map");
7999 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
8000 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
8001 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_c_chan", CTLFLAG_RD, NULL,
8002 	    pi->rx_c_chan, "TP rx c-channel");
8003 
8004 	if (sc->flags & IS_VF)
8005 		return;
8006 
8007 	/*
8008 	 * dev.(cxgbe|cxl).X.tc.
8009 	 */
8010 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
8011 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
8012 	    "Tx scheduler traffic classes (cl_rl)");
8013 	children2 = SYSCTL_CHILDREN(oid);
8014 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
8015 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
8016 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
8017 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
8018 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
8019 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
8020 	for (i = 0; i < sc->params.nsched_cls; i++) {
8021 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
8022 
8023 		snprintf(name, sizeof(name), "%d", i);
8024 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
8025 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
8026 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
8027 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
8028 		    CTLFLAG_RD, &tc->state, 0, "current state");
8029 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
8030 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
8031 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
8032 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
8033 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
8034 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
8035 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8036 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
8037 		    "traffic class parameters");
8038 	}
8039 
8040 	/*
8041 	 * dev.cxgbe.X.stats.
8042 	 */
8043 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
8044 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
8045 	children = SYSCTL_CHILDREN(oid);
8046 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
8047 	    &pi->tx_parse_error, 0,
8048 	    "# of tx packets with invalid length or # of segments");
8049 
8050 #define T4_REGSTAT(name, stat, desc) \
8051     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8052         CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8053 	(is_t4(sc) ? PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L) : \
8054 	T5_PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L)), \
8055         sysctl_handle_t4_reg64, "QU", desc)
8056 
8057 /* We get these from port_stats and they may be stale by up to 1s */
8058 #define T4_PORTSTAT(name, desc) \
8059 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
8060 	    &pi->stats.name, desc)
8061 
8062 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
8063 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
8064 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
8065 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
8066 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
8067 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
8068 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
8069 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
8070 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
8071 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
8072 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
8073 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
8074 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
8075 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
8076 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
8077 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
8078 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
8079 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
8080 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
8081 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
8082 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
8083 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
8084 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
8085 
8086 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
8087 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
8088 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
8089 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
8090 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
8091 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
8092 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
8093 	if (is_t6(sc)) {
8094 		T4_PORTSTAT(rx_fcs_err,
8095 		    "# of frames received with bad FCS since last link up");
8096 	} else {
8097 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
8098 		    "# of frames received with bad FCS");
8099 	}
8100 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
8101 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
8102 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
8103 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
8104 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
8105 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
8106 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
8107 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
8108 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
8109 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
8110 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
8111 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
8112 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
8113 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
8114 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
8115 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
8116 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
8117 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
8118 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
8119 
8120 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
8121 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
8122 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
8123 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
8124 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
8125 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
8126 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
8127 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
8128 
8129 #undef T4_REGSTAT
8130 #undef T4_PORTSTAT
8131 }
8132 
8133 static int
8134 sysctl_int_array(SYSCTL_HANDLER_ARGS)
8135 {
8136 	int rc, *i, space = 0;
8137 	struct sbuf sb;
8138 
8139 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
8140 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
8141 		if (space)
8142 			sbuf_printf(&sb, " ");
8143 		sbuf_printf(&sb, "%d", *i);
8144 		space = 1;
8145 	}
8146 	rc = sbuf_finish(&sb);
8147 	sbuf_delete(&sb);
8148 	return (rc);
8149 }
8150 
8151 static int
8152 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
8153 {
8154 	int rc;
8155 	struct sbuf *sb;
8156 
8157 	rc = sysctl_wire_old_buffer(req, 0);
8158 	if (rc != 0)
8159 		return(rc);
8160 
8161 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8162 	if (sb == NULL)
8163 		return (ENOMEM);
8164 
8165 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8166 	rc = sbuf_finish(sb);
8167 	sbuf_delete(sb);
8168 
8169 	return (rc);
8170 }
8171 
8172 static int
8173 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8174 {
8175 	int rc;
8176 	struct sbuf *sb;
8177 
8178 	rc = sysctl_wire_old_buffer(req, 0);
8179 	if (rc != 0)
8180 		return(rc);
8181 
8182 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8183 	if (sb == NULL)
8184 		return (ENOMEM);
8185 
8186 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8187 	rc = sbuf_finish(sb);
8188 	sbuf_delete(sb);
8189 
8190 	return (rc);
8191 }
8192 
8193 static int
8194 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8195 {
8196 	struct port_info *pi = arg1;
8197 	int op = arg2;
8198 	struct adapter *sc = pi->adapter;
8199 	u_int v;
8200 	int rc;
8201 
8202 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8203 	if (rc)
8204 		return (rc);
8205 	if (hw_off_limits(sc))
8206 		rc = ENXIO;
8207 	else {
8208 		/* XXX: magic numbers */
8209 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8210 		    op ? 0x20 : 0xc820, &v);
8211 	}
8212 	end_synchronized_op(sc, 0);
8213 	if (rc)
8214 		return (rc);
8215 	if (op == 0)
8216 		v /= 256;
8217 
8218 	rc = sysctl_handle_int(oidp, &v, 0, req);
8219 	return (rc);
8220 }
8221 
8222 static int
8223 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8224 {
8225 	struct vi_info *vi = arg1;
8226 	int rc, val;
8227 
8228 	val = vi->rsrv_noflowq;
8229 	rc = sysctl_handle_int(oidp, &val, 0, req);
8230 	if (rc != 0 || req->newptr == NULL)
8231 		return (rc);
8232 
8233 	if ((val >= 1) && (vi->ntxq > 1))
8234 		vi->rsrv_noflowq = 1;
8235 	else
8236 		vi->rsrv_noflowq = 0;
8237 
8238 	return (rc);
8239 }
8240 
8241 static int
8242 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8243 {
8244 	struct vi_info *vi = arg1;
8245 	struct adapter *sc = vi->adapter;
8246 	int rc, val, i;
8247 
8248 	MPASS(!(sc->flags & IS_VF));
8249 
8250 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8251 	rc = sysctl_handle_int(oidp, &val, 0, req);
8252 	if (rc != 0 || req->newptr == NULL)
8253 		return (rc);
8254 
8255 	if (val != 0 && val != 1)
8256 		return (EINVAL);
8257 
8258 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8259 	    "t4txvm");
8260 	if (rc)
8261 		return (rc);
8262 	if (hw_off_limits(sc))
8263 		rc = ENXIO;
8264 	else if (vi->ifp->if_drv_flags & IFF_DRV_RUNNING) {
8265 		/*
8266 		 * We don't want parse_pkt to run with one setting (VF or PF)
8267 		 * and then eth_tx to see a different setting but still use
8268 		 * stale information calculated by parse_pkt.
8269 		 */
8270 		rc = EBUSY;
8271 	} else {
8272 		struct port_info *pi = vi->pi;
8273 		struct sge_txq *txq;
8274 		uint32_t ctrl0;
8275 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8276 
8277 		if (val) {
8278 			vi->flags |= TX_USES_VM_WR;
8279 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
8280 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8281 			    V_TXPKT_INTF(pi->tx_chan));
8282 			if (!(sc->flags & IS_VF))
8283 				npkt--;
8284 		} else {
8285 			vi->flags &= ~TX_USES_VM_WR;
8286 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
8287 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8288 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8289 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8290 		}
8291 		for_each_txq(vi, i, txq) {
8292 			txq->cpl_ctrl0 = ctrl0;
8293 			txq->txp.max_npkt = npkt;
8294 		}
8295 	}
8296 	end_synchronized_op(sc, LOCK_HELD);
8297 	return (rc);
8298 }
8299 
8300 static int
8301 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8302 {
8303 	struct vi_info *vi = arg1;
8304 	struct adapter *sc = vi->adapter;
8305 	int idx, rc, i;
8306 	struct sge_rxq *rxq;
8307 	uint8_t v;
8308 
8309 	idx = vi->tmr_idx;
8310 
8311 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8312 	if (rc != 0 || req->newptr == NULL)
8313 		return (rc);
8314 
8315 	if (idx < 0 || idx >= SGE_NTIMERS)
8316 		return (EINVAL);
8317 
8318 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8319 	    "t4tmr");
8320 	if (rc)
8321 		return (rc);
8322 
8323 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8324 	for_each_rxq(vi, i, rxq) {
8325 #ifdef atomic_store_rel_8
8326 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8327 #else
8328 		rxq->iq.intr_params = v;
8329 #endif
8330 	}
8331 	vi->tmr_idx = idx;
8332 
8333 	end_synchronized_op(sc, LOCK_HELD);
8334 	return (0);
8335 }
8336 
8337 static int
8338 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8339 {
8340 	struct vi_info *vi = arg1;
8341 	struct adapter *sc = vi->adapter;
8342 	int idx, rc;
8343 
8344 	idx = vi->pktc_idx;
8345 
8346 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8347 	if (rc != 0 || req->newptr == NULL)
8348 		return (rc);
8349 
8350 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8351 		return (EINVAL);
8352 
8353 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8354 	    "t4pktc");
8355 	if (rc)
8356 		return (rc);
8357 
8358 	if (vi->flags & VI_INIT_DONE)
8359 		rc = EBUSY; /* cannot be changed once the queues are created */
8360 	else
8361 		vi->pktc_idx = idx;
8362 
8363 	end_synchronized_op(sc, LOCK_HELD);
8364 	return (rc);
8365 }
8366 
8367 static int
8368 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8369 {
8370 	struct vi_info *vi = arg1;
8371 	struct adapter *sc = vi->adapter;
8372 	int qsize, rc;
8373 
8374 	qsize = vi->qsize_rxq;
8375 
8376 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8377 	if (rc != 0 || req->newptr == NULL)
8378 		return (rc);
8379 
8380 	if (qsize < 128 || (qsize & 7))
8381 		return (EINVAL);
8382 
8383 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8384 	    "t4rxqs");
8385 	if (rc)
8386 		return (rc);
8387 
8388 	if (vi->flags & VI_INIT_DONE)
8389 		rc = EBUSY; /* cannot be changed once the queues are created */
8390 	else
8391 		vi->qsize_rxq = qsize;
8392 
8393 	end_synchronized_op(sc, LOCK_HELD);
8394 	return (rc);
8395 }
8396 
8397 static int
8398 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8399 {
8400 	struct vi_info *vi = arg1;
8401 	struct adapter *sc = vi->adapter;
8402 	int qsize, rc;
8403 
8404 	qsize = vi->qsize_txq;
8405 
8406 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8407 	if (rc != 0 || req->newptr == NULL)
8408 		return (rc);
8409 
8410 	if (qsize < 128 || qsize > 65536)
8411 		return (EINVAL);
8412 
8413 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8414 	    "t4txqs");
8415 	if (rc)
8416 		return (rc);
8417 
8418 	if (vi->flags & VI_INIT_DONE)
8419 		rc = EBUSY; /* cannot be changed once the queues are created */
8420 	else
8421 		vi->qsize_txq = qsize;
8422 
8423 	end_synchronized_op(sc, LOCK_HELD);
8424 	return (rc);
8425 }
8426 
8427 static int
8428 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8429 {
8430 	struct port_info *pi = arg1;
8431 	struct adapter *sc = pi->adapter;
8432 	struct link_config *lc = &pi->link_cfg;
8433 	int rc;
8434 
8435 	if (req->newptr == NULL) {
8436 		struct sbuf *sb;
8437 		static char *bits = "\20\1RX\2TX\3AUTO";
8438 
8439 		rc = sysctl_wire_old_buffer(req, 0);
8440 		if (rc != 0)
8441 			return(rc);
8442 
8443 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8444 		if (sb == NULL)
8445 			return (ENOMEM);
8446 
8447 		if (lc->link_ok) {
8448 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8449 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8450 		} else {
8451 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8452 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8453 		}
8454 		rc = sbuf_finish(sb);
8455 		sbuf_delete(sb);
8456 	} else {
8457 		char s[2];
8458 		int n;
8459 
8460 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8461 		    PAUSE_AUTONEG));
8462 		s[1] = 0;
8463 
8464 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8465 		if (rc != 0)
8466 			return(rc);
8467 
8468 		if (s[1] != 0)
8469 			return (EINVAL);
8470 		if (s[0] < '0' || s[0] > '9')
8471 			return (EINVAL);	/* not a number */
8472 		n = s[0] - '0';
8473 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8474 			return (EINVAL);	/* some other bit is set too */
8475 
8476 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8477 		    "t4PAUSE");
8478 		if (rc)
8479 			return (rc);
8480 		if (!hw_off_limits(sc)) {
8481 			PORT_LOCK(pi);
8482 			lc->requested_fc = n;
8483 			fixup_link_config(pi);
8484 			if (pi->up_vis > 0)
8485 				rc = apply_link_config(pi);
8486 			set_current_media(pi);
8487 			PORT_UNLOCK(pi);
8488 		}
8489 		end_synchronized_op(sc, 0);
8490 	}
8491 
8492 	return (rc);
8493 }
8494 
8495 static int
8496 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
8497 {
8498 	struct port_info *pi = arg1;
8499 	struct link_config *lc = &pi->link_cfg;
8500 	int rc;
8501 	struct sbuf *sb;
8502 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2";
8503 
8504 	rc = sysctl_wire_old_buffer(req, 0);
8505 	if (rc != 0)
8506 		return(rc);
8507 
8508 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8509 	if (sb == NULL)
8510 		return (ENOMEM);
8511 	if (lc->link_ok)
8512 		sbuf_printf(sb, "%b", lc->fec, bits);
8513 	else
8514 		sbuf_printf(sb, "no link");
8515 	rc = sbuf_finish(sb);
8516 	sbuf_delete(sb);
8517 
8518 	return (rc);
8519 }
8520 
8521 static int
8522 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
8523 {
8524 	struct port_info *pi = arg1;
8525 	struct adapter *sc = pi->adapter;
8526 	struct link_config *lc = &pi->link_cfg;
8527 	int rc;
8528 	int8_t old;
8529 
8530 	if (req->newptr == NULL) {
8531 		struct sbuf *sb;
8532 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8533 		    "\5RSVD3\6auto\7module";
8534 
8535 		rc = sysctl_wire_old_buffer(req, 0);
8536 		if (rc != 0)
8537 			return(rc);
8538 
8539 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8540 		if (sb == NULL)
8541 			return (ENOMEM);
8542 
8543 		sbuf_printf(sb, "%b", lc->requested_fec, bits);
8544 		rc = sbuf_finish(sb);
8545 		sbuf_delete(sb);
8546 	} else {
8547 		char s[8];
8548 		int n;
8549 
8550 		snprintf(s, sizeof(s), "%d",
8551 		    lc->requested_fec == FEC_AUTO ? -1 :
8552 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8553 
8554 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8555 		if (rc != 0)
8556 			return(rc);
8557 
8558 		n = strtol(&s[0], NULL, 0);
8559 		if (n < 0 || n & FEC_AUTO)
8560 			n = FEC_AUTO;
8561 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8562 			return (EINVAL);/* some other bit is set too */
8563 
8564 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8565 		    "t4reqf");
8566 		if (rc)
8567 			return (rc);
8568 		PORT_LOCK(pi);
8569 		old = lc->requested_fec;
8570 		if (n == FEC_AUTO)
8571 			lc->requested_fec = FEC_AUTO;
8572 		else if (n == 0 || n == FEC_NONE)
8573 			lc->requested_fec = FEC_NONE;
8574 		else {
8575 			if ((lc->pcaps |
8576 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8577 			    lc->pcaps) {
8578 				rc = ENOTSUP;
8579 				goto done;
8580 			}
8581 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8582 			    FEC_MODULE);
8583 		}
8584 		if (!hw_off_limits(sc)) {
8585 			fixup_link_config(pi);
8586 			if (pi->up_vis > 0) {
8587 				rc = apply_link_config(pi);
8588 				if (rc != 0) {
8589 					lc->requested_fec = old;
8590 					if (rc == FW_EPROTO)
8591 						rc = ENOTSUP;
8592 				}
8593 			}
8594 		}
8595 done:
8596 		PORT_UNLOCK(pi);
8597 		end_synchronized_op(sc, 0);
8598 	}
8599 
8600 	return (rc);
8601 }
8602 
8603 static int
8604 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8605 {
8606 	struct port_info *pi = arg1;
8607 	struct adapter *sc = pi->adapter;
8608 	struct link_config *lc = &pi->link_cfg;
8609 	int rc;
8610 	int8_t fec;
8611 	struct sbuf *sb;
8612 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8613 
8614 	rc = sysctl_wire_old_buffer(req, 0);
8615 	if (rc != 0)
8616 		return (rc);
8617 
8618 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8619 	if (sb == NULL)
8620 		return (ENOMEM);
8621 
8622 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8623 		rc = EBUSY;
8624 		goto done;
8625 	}
8626 	if (hw_off_limits(sc)) {
8627 		rc = ENXIO;
8628 		goto done;
8629 	}
8630 	PORT_LOCK(pi);
8631 	if (pi->up_vis == 0) {
8632 		/*
8633 		 * If all the interfaces are administratively down the firmware
8634 		 * does not report transceiver changes.  Refresh port info here.
8635 		 * This is the only reason we have a synchronized op in this
8636 		 * function.  Just PORT_LOCK would have been enough otherwise.
8637 		 */
8638 		t4_update_port_info(pi);
8639 	}
8640 
8641 	fec = lc->fec_hint;
8642 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8643 	    !fec_supported(lc->pcaps)) {
8644 		sbuf_printf(sb, "n/a");
8645 	} else {
8646 		if (fec == 0)
8647 			fec = FEC_NONE;
8648 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8649 	}
8650 	rc = sbuf_finish(sb);
8651 	PORT_UNLOCK(pi);
8652 done:
8653 	sbuf_delete(sb);
8654 	end_synchronized_op(sc, 0);
8655 
8656 	return (rc);
8657 }
8658 
8659 static int
8660 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8661 {
8662 	struct port_info *pi = arg1;
8663 	struct adapter *sc = pi->adapter;
8664 	struct link_config *lc = &pi->link_cfg;
8665 	int rc, val;
8666 
8667 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8668 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8669 	else
8670 		val = -1;
8671 	rc = sysctl_handle_int(oidp, &val, 0, req);
8672 	if (rc != 0 || req->newptr == NULL)
8673 		return (rc);
8674 	if (val == 0)
8675 		val = AUTONEG_DISABLE;
8676 	else if (val == 1)
8677 		val = AUTONEG_ENABLE;
8678 	else
8679 		val = AUTONEG_AUTO;
8680 
8681 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8682 	    "t4aneg");
8683 	if (rc)
8684 		return (rc);
8685 	PORT_LOCK(pi);
8686 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8687 		rc = ENOTSUP;
8688 		goto done;
8689 	}
8690 	lc->requested_aneg = val;
8691 	if (!hw_off_limits(sc)) {
8692 		fixup_link_config(pi);
8693 		if (pi->up_vis > 0)
8694 			rc = apply_link_config(pi);
8695 		set_current_media(pi);
8696 	}
8697 done:
8698 	PORT_UNLOCK(pi);
8699 	end_synchronized_op(sc, 0);
8700 	return (rc);
8701 }
8702 
8703 static int
8704 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
8705 {
8706 	struct port_info *pi = arg1;
8707 	struct adapter *sc = pi->adapter;
8708 	struct link_config *lc = &pi->link_cfg;
8709 	int rc, val;
8710 
8711 	val = lc->force_fec;
8712 	MPASS(val >= -1 && val <= 1);
8713 	rc = sysctl_handle_int(oidp, &val, 0, req);
8714 	if (rc != 0 || req->newptr == NULL)
8715 		return (rc);
8716 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
8717 		return (ENOTSUP);
8718 	if (val < -1 || val > 1)
8719 		return (EINVAL);
8720 
8721 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
8722 	if (rc)
8723 		return (rc);
8724 	PORT_LOCK(pi);
8725 	lc->force_fec = val;
8726 	if (!hw_off_limits(sc)) {
8727 		fixup_link_config(pi);
8728 		if (pi->up_vis > 0)
8729 			rc = apply_link_config(pi);
8730 	}
8731 	PORT_UNLOCK(pi);
8732 	end_synchronized_op(sc, 0);
8733 	return (rc);
8734 }
8735 
8736 static int
8737 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8738 {
8739 	struct adapter *sc = arg1;
8740 	int rc, reg = arg2;
8741 	uint64_t val;
8742 
8743 	mtx_lock(&sc->reg_lock);
8744 	if (hw_off_limits(sc))
8745 		rc = ENXIO;
8746 	else {
8747 		rc = 0;
8748 		val = t4_read_reg64(sc, reg);
8749 	}
8750 	mtx_unlock(&sc->reg_lock);
8751 	if (rc == 0)
8752 		rc = sysctl_handle_64(oidp, &val, 0, req);
8753 	return (rc);
8754 }
8755 
8756 static int
8757 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8758 {
8759 	struct adapter *sc = arg1;
8760 	int rc, t;
8761 	uint32_t param, val;
8762 
8763 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8764 	if (rc)
8765 		return (rc);
8766 	if (hw_off_limits(sc))
8767 		rc = ENXIO;
8768 	else {
8769 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8770 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8771 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8772 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8773 	}
8774 	end_synchronized_op(sc, 0);
8775 	if (rc)
8776 		return (rc);
8777 
8778 	/* unknown is returned as 0 but we display -1 in that case */
8779 	t = val == 0 ? -1 : val;
8780 
8781 	rc = sysctl_handle_int(oidp, &t, 0, req);
8782 	return (rc);
8783 }
8784 
8785 static int
8786 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8787 {
8788 	struct adapter *sc = arg1;
8789 	int rc;
8790 	uint32_t param, val;
8791 
8792 	if (sc->params.core_vdd == 0) {
8793 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8794 		    "t4vdd");
8795 		if (rc)
8796 			return (rc);
8797 		if (hw_off_limits(sc))
8798 			rc = ENXIO;
8799 		else {
8800 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8801 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8802 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8803 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8804 			    &param, &val);
8805 		}
8806 		end_synchronized_op(sc, 0);
8807 		if (rc)
8808 			return (rc);
8809 		sc->params.core_vdd = val;
8810 	}
8811 
8812 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8813 }
8814 
8815 static int
8816 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8817 {
8818 	struct adapter *sc = arg1;
8819 	int rc, v;
8820 	uint32_t param, val;
8821 
8822 	v = sc->sensor_resets;
8823 	rc = sysctl_handle_int(oidp, &v, 0, req);
8824 	if (rc != 0 || req->newptr == NULL || v <= 0)
8825 		return (rc);
8826 
8827 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8828 	    chip_id(sc) < CHELSIO_T5)
8829 		return (ENOTSUP);
8830 
8831 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8832 	if (rc)
8833 		return (rc);
8834 	if (hw_off_limits(sc))
8835 		rc = ENXIO;
8836 	else {
8837 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8838 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8839 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8840 		val = 1;
8841 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8842 	}
8843 	end_synchronized_op(sc, 0);
8844 	if (rc == 0)
8845 		sc->sensor_resets++;
8846 	return (rc);
8847 }
8848 
8849 static int
8850 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8851 {
8852 	struct adapter *sc = arg1;
8853 	struct sbuf *sb;
8854 	int rc;
8855 	uint32_t param, val;
8856 
8857 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8858 	if (rc)
8859 		return (rc);
8860 	if (hw_off_limits(sc))
8861 		rc = ENXIO;
8862 	else {
8863 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8864 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8865 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8866 	}
8867 	end_synchronized_op(sc, 0);
8868 	if (rc)
8869 		return (rc);
8870 
8871 	rc = sysctl_wire_old_buffer(req, 0);
8872 	if (rc != 0)
8873 		return (rc);
8874 
8875 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8876 	if (sb == NULL)
8877 		return (ENOMEM);
8878 
8879 	if (val == 0xffffffff) {
8880 		/* Only debug and custom firmwares report load averages. */
8881 		sbuf_printf(sb, "not available");
8882 	} else {
8883 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8884 		    (val >> 16) & 0xff);
8885 	}
8886 	rc = sbuf_finish(sb);
8887 	sbuf_delete(sb);
8888 
8889 	return (rc);
8890 }
8891 
8892 static int
8893 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8894 {
8895 	struct adapter *sc = arg1;
8896 	struct sbuf *sb;
8897 	int rc, i;
8898 	uint16_t incr[NMTUS][NCCTRL_WIN];
8899 	static const char *dec_fac[] = {
8900 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8901 		"0.9375"
8902 	};
8903 
8904 	rc = sysctl_wire_old_buffer(req, 0);
8905 	if (rc != 0)
8906 		return (rc);
8907 
8908 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8909 	if (sb == NULL)
8910 		return (ENOMEM);
8911 
8912 	mtx_lock(&sc->reg_lock);
8913 	if (hw_off_limits(sc))
8914 		rc = ENXIO;
8915 	else
8916 		t4_read_cong_tbl(sc, incr);
8917 	mtx_unlock(&sc->reg_lock);
8918 	if (rc)
8919 		goto done;
8920 
8921 	for (i = 0; i < NCCTRL_WIN; ++i) {
8922 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8923 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8924 		    incr[5][i], incr[6][i], incr[7][i]);
8925 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8926 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8927 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8928 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8929 	}
8930 
8931 	rc = sbuf_finish(sb);
8932 done:
8933 	sbuf_delete(sb);
8934 	return (rc);
8935 }
8936 
8937 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8938 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8939 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8940 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8941 };
8942 
8943 static int
8944 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8945 {
8946 	struct adapter *sc = arg1;
8947 	struct sbuf *sb;
8948 	int rc, i, n, qid = arg2;
8949 	uint32_t *buf, *p;
8950 	char *qtype;
8951 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8952 
8953 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8954 	    ("%s: bad qid %d\n", __func__, qid));
8955 
8956 	if (qid < CIM_NUM_IBQ) {
8957 		/* inbound queue */
8958 		qtype = "IBQ";
8959 		n = 4 * CIM_IBQ_SIZE;
8960 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8961 		mtx_lock(&sc->reg_lock);
8962 		if (hw_off_limits(sc))
8963 			rc = -ENXIO;
8964 		else
8965 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8966 		mtx_unlock(&sc->reg_lock);
8967 	} else {
8968 		/* outbound queue */
8969 		qtype = "OBQ";
8970 		qid -= CIM_NUM_IBQ;
8971 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8972 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8973 		mtx_lock(&sc->reg_lock);
8974 		if (hw_off_limits(sc))
8975 			rc = -ENXIO;
8976 		else
8977 			rc = t4_read_cim_obq(sc, qid, buf, n);
8978 		mtx_unlock(&sc->reg_lock);
8979 	}
8980 
8981 	if (rc < 0) {
8982 		rc = -rc;
8983 		goto done;
8984 	}
8985 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
8986 
8987 	rc = sysctl_wire_old_buffer(req, 0);
8988 	if (rc != 0)
8989 		goto done;
8990 
8991 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8992 	if (sb == NULL) {
8993 		rc = ENOMEM;
8994 		goto done;
8995 	}
8996 
8997 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8998 	for (i = 0, p = buf; i < n; i += 16, p += 4)
8999 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
9000 		    p[2], p[3]);
9001 
9002 	rc = sbuf_finish(sb);
9003 	sbuf_delete(sb);
9004 done:
9005 	free(buf, M_CXGBE);
9006 	return (rc);
9007 }
9008 
9009 static void
9010 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9011 {
9012 	uint32_t *p;
9013 
9014 	sbuf_printf(sb, "Status   Data      PC%s",
9015 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9016 	    "     LS0Stat  LS0Addr             LS0Data");
9017 
9018 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
9019 		if (cfg & F_UPDBGLACAPTPCONLY) {
9020 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
9021 			    p[6], p[7]);
9022 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
9023 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
9024 			    p[4] & 0xff, p[5] >> 8);
9025 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
9026 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9027 			    p[1] & 0xf, p[2] >> 4);
9028 		} else {
9029 			sbuf_printf(sb,
9030 			    "\n  %02x   %x%07x %x%07x %08x %08x "
9031 			    "%08x%08x%08x%08x",
9032 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9033 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
9034 			    p[6], p[7]);
9035 		}
9036 	}
9037 }
9038 
9039 static void
9040 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9041 {
9042 	uint32_t *p;
9043 
9044 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
9045 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9046 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
9047 
9048 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
9049 		if (cfg & F_UPDBGLACAPTPCONLY) {
9050 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
9051 			    p[3] & 0xff, p[2], p[1], p[0]);
9052 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
9053 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
9054 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
9055 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
9056 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
9057 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
9058 			    p[6] >> 16);
9059 		} else {
9060 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
9061 			    "%08x %08x %08x %08x %08x %08x",
9062 			    (p[9] >> 16) & 0xff,
9063 			    p[9] & 0xffff, p[8] >> 16,
9064 			    p[8] & 0xffff, p[7] >> 16,
9065 			    p[7] & 0xffff, p[6] >> 16,
9066 			    p[2], p[1], p[0], p[5], p[4], p[3]);
9067 		}
9068 	}
9069 }
9070 
9071 static int
9072 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
9073 {
9074 	uint32_t cfg, *buf;
9075 	int rc;
9076 
9077 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9078 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
9079 	    M_ZERO | flags);
9080 	if (buf == NULL)
9081 		return (ENOMEM);
9082 
9083 	mtx_lock(&sc->reg_lock);
9084 	if (hw_off_limits(sc))
9085 		rc = ENXIO;
9086 	else {
9087 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
9088 		if (rc == 0)
9089 			rc = -t4_cim_read_la(sc, buf, NULL);
9090 	}
9091 	mtx_unlock(&sc->reg_lock);
9092 	if (rc == 0) {
9093 		if (chip_id(sc) < CHELSIO_T6)
9094 			sbuf_cim_la4(sc, sb, buf, cfg);
9095 		else
9096 			sbuf_cim_la6(sc, sb, buf, cfg);
9097 	}
9098 	free(buf, M_CXGBE);
9099 	return (rc);
9100 }
9101 
9102 static int
9103 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
9104 {
9105 	struct adapter *sc = arg1;
9106 	struct sbuf *sb;
9107 	int rc;
9108 
9109 	rc = sysctl_wire_old_buffer(req, 0);
9110 	if (rc != 0)
9111 		return (rc);
9112 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9113 	if (sb == NULL)
9114 		return (ENOMEM);
9115 
9116 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
9117 	if (rc == 0)
9118 		rc = sbuf_finish(sb);
9119 	sbuf_delete(sb);
9120 	return (rc);
9121 }
9122 
9123 static void
9124 dump_cim_regs(struct adapter *sc)
9125 {
9126 	log(LOG_DEBUG, "%s: CIM debug regs1 %08x %08x %08x %08x %08x\n",
9127 	    device_get_nameunit(sc->dev),
9128 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9129 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9130 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA2),
9131 	    t4_read_reg(sc, A_EDC_H_BIST_DATA_PATTERN),
9132 	    t4_read_reg(sc, A_EDC_H_BIST_STATUS_RDATA));
9133 	log(LOG_DEBUG, "%s: CIM debug regs2 %08x %08x %08x %08x %08x\n",
9134 	    device_get_nameunit(sc->dev),
9135 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9136 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9137 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0 + 0x800),
9138 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1 + 0x800),
9139 	    t4_read_reg(sc, A_EDC_H_BIST_CMD_LEN));
9140 }
9141 
9142 static void
9143 dump_cimla(struct adapter *sc)
9144 {
9145 	struct sbuf sb;
9146 	int rc;
9147 
9148 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9149 		log(LOG_DEBUG, "%s: failed to generate CIM LA dump.\n",
9150 		    device_get_nameunit(sc->dev));
9151 		return;
9152 	}
9153 	rc = sbuf_cim_la(sc, &sb, M_WAITOK);
9154 	if (rc == 0) {
9155 		rc = sbuf_finish(&sb);
9156 		if (rc == 0) {
9157 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s\n",
9158 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
9159 		}
9160 	}
9161 	sbuf_delete(&sb);
9162 }
9163 
9164 void
9165 t4_os_cim_err(struct adapter *sc)
9166 {
9167 	atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
9168 }
9169 
9170 static int
9171 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
9172 {
9173 	struct adapter *sc = arg1;
9174 	u_int i;
9175 	struct sbuf *sb;
9176 	uint32_t *buf, *p;
9177 	int rc;
9178 
9179 	rc = sysctl_wire_old_buffer(req, 0);
9180 	if (rc != 0)
9181 		return (rc);
9182 
9183 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9184 	if (sb == NULL)
9185 		return (ENOMEM);
9186 
9187 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
9188 	    M_ZERO | M_WAITOK);
9189 
9190 	mtx_lock(&sc->reg_lock);
9191 	if (hw_off_limits(sc))
9192 		rc = ENXIO;
9193 	else
9194 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
9195 	mtx_unlock(&sc->reg_lock);
9196 	if (rc)
9197 		goto done;
9198 
9199 	p = buf;
9200 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9201 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
9202 		    p[1], p[0]);
9203 	}
9204 
9205 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9206 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9207 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9208 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9209 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9210 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9211 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9212 		    p[0] & 1);
9213 	}
9214 	rc = sbuf_finish(sb);
9215 done:
9216 	sbuf_delete(sb);
9217 	free(buf, M_CXGBE);
9218 	return (rc);
9219 }
9220 
9221 static int
9222 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9223 {
9224 	struct adapter *sc = arg1;
9225 	u_int i;
9226 	struct sbuf *sb;
9227 	uint32_t *buf, *p;
9228 	int rc;
9229 
9230 	rc = sysctl_wire_old_buffer(req, 0);
9231 	if (rc != 0)
9232 		return (rc);
9233 
9234 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9235 	if (sb == NULL)
9236 		return (ENOMEM);
9237 
9238 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9239 	    M_ZERO | M_WAITOK);
9240 
9241 	mtx_lock(&sc->reg_lock);
9242 	if (hw_off_limits(sc))
9243 		rc = ENXIO;
9244 	else
9245 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9246 	mtx_unlock(&sc->reg_lock);
9247 	if (rc)
9248 		goto done;
9249 
9250 	p = buf;
9251 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9252 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9253 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9254 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9255 		    p[4], p[3], p[2], p[1], p[0]);
9256 	}
9257 
9258 	sbuf_printf(sb, "\n\nCntl ID               Data");
9259 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9260 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9261 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9262 	}
9263 
9264 	rc = sbuf_finish(sb);
9265 done:
9266 	sbuf_delete(sb);
9267 	free(buf, M_CXGBE);
9268 	return (rc);
9269 }
9270 
9271 static int
9272 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9273 {
9274 	struct adapter *sc = arg1;
9275 	struct sbuf *sb;
9276 	int rc, i;
9277 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9278 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9279 	uint16_t thres[CIM_NUM_IBQ];
9280 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9281 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9282 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9283 
9284 	cim_num_obq = sc->chip_params->cim_num_obq;
9285 	if (is_t4(sc)) {
9286 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9287 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9288 	} else {
9289 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9290 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9291 	}
9292 	nq = CIM_NUM_IBQ + cim_num_obq;
9293 
9294 	mtx_lock(&sc->reg_lock);
9295 	if (hw_off_limits(sc))
9296 		rc = ENXIO;
9297 	else {
9298 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9299 		if (rc == 0) {
9300 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9301 			    obq_wr);
9302 			if (rc == 0)
9303 				t4_read_cimq_cfg(sc, base, size, thres);
9304 		}
9305 	}
9306 	mtx_unlock(&sc->reg_lock);
9307 	if (rc)
9308 		return (rc);
9309 
9310 	rc = sysctl_wire_old_buffer(req, 0);
9311 	if (rc != 0)
9312 		return (rc);
9313 
9314 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9315 	if (sb == NULL)
9316 		return (ENOMEM);
9317 
9318 	sbuf_printf(sb,
9319 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9320 
9321 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9322 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9323 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9324 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9325 		    G_QUEREMFLITS(p[2]) * 16);
9326 	for ( ; i < nq; i++, p += 4, wr += 2)
9327 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9328 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9329 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9330 		    G_QUEREMFLITS(p[2]) * 16);
9331 
9332 	rc = sbuf_finish(sb);
9333 	sbuf_delete(sb);
9334 
9335 	return (rc);
9336 }
9337 
9338 static int
9339 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9340 {
9341 	struct adapter *sc = arg1;
9342 	struct sbuf *sb;
9343 	int rc;
9344 	struct tp_cpl_stats stats;
9345 
9346 	rc = sysctl_wire_old_buffer(req, 0);
9347 	if (rc != 0)
9348 		return (rc);
9349 
9350 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9351 	if (sb == NULL)
9352 		return (ENOMEM);
9353 
9354 	mtx_lock(&sc->reg_lock);
9355 	if (hw_off_limits(sc))
9356 		rc = ENXIO;
9357 	else
9358 		t4_tp_get_cpl_stats(sc, &stats, 0);
9359 	mtx_unlock(&sc->reg_lock);
9360 	if (rc)
9361 		goto done;
9362 
9363 	if (sc->chip_params->nchan > 2) {
9364 		sbuf_printf(sb, "                 channel 0  channel 1"
9365 		    "  channel 2  channel 3");
9366 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9367 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9368 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9369 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9370 	} else {
9371 		sbuf_printf(sb, "                 channel 0  channel 1");
9372 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9373 		    stats.req[0], stats.req[1]);
9374 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9375 		    stats.rsp[0], stats.rsp[1]);
9376 	}
9377 
9378 	rc = sbuf_finish(sb);
9379 done:
9380 	sbuf_delete(sb);
9381 	return (rc);
9382 }
9383 
9384 static int
9385 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9386 {
9387 	struct adapter *sc = arg1;
9388 	struct sbuf *sb;
9389 	int rc;
9390 	struct tp_usm_stats stats;
9391 
9392 	rc = sysctl_wire_old_buffer(req, 0);
9393 	if (rc != 0)
9394 		return(rc);
9395 
9396 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9397 	if (sb == NULL)
9398 		return (ENOMEM);
9399 
9400 	mtx_lock(&sc->reg_lock);
9401 	if (hw_off_limits(sc))
9402 		rc = ENXIO;
9403 	else
9404 		t4_get_usm_stats(sc, &stats, 1);
9405 	mtx_unlock(&sc->reg_lock);
9406 	if (rc == 0) {
9407 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9408 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9409 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9410 		rc = sbuf_finish(sb);
9411 	}
9412 	sbuf_delete(sb);
9413 
9414 	return (rc);
9415 }
9416 
9417 static int
9418 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9419 {
9420 	struct adapter *sc = arg1;
9421 	struct sbuf *sb;
9422 	int rc;
9423 	struct tp_tid_stats stats;
9424 
9425 	rc = sysctl_wire_old_buffer(req, 0);
9426 	if (rc != 0)
9427 		return(rc);
9428 
9429 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9430 	if (sb == NULL)
9431 		return (ENOMEM);
9432 
9433 	mtx_lock(&sc->reg_lock);
9434 	if (hw_off_limits(sc))
9435 		rc = ENXIO;
9436 	else
9437 		t4_tp_get_tid_stats(sc, &stats, 1);
9438 	mtx_unlock(&sc->reg_lock);
9439 	if (rc == 0) {
9440 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9441 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9442 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9443 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9444 		rc = sbuf_finish(sb);
9445 	}
9446 	sbuf_delete(sb);
9447 
9448 	return (rc);
9449 }
9450 
9451 static const char * const devlog_level_strings[] = {
9452 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9453 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9454 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9455 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9456 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9457 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9458 };
9459 
9460 static const char * const devlog_facility_strings[] = {
9461 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9462 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9463 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9464 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9465 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9466 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9467 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9468 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9469 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9470 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9471 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9472 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9473 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9474 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9475 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9476 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9477 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9478 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9479 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9480 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9481 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9482 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9483 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9484 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9485 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9486 };
9487 
9488 static int
9489 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9490 {
9491 	int i, j, rc, nentries, first = 0;
9492 	struct devlog_params *dparams = &sc->params.devlog;
9493 	struct fw_devlog_e *buf, *e;
9494 	uint64_t ftstamp = UINT64_MAX;
9495 
9496 	if (dparams->addr == 0)
9497 		return (ENXIO);
9498 
9499 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9500 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9501 	if (buf == NULL)
9502 		return (ENOMEM);
9503 
9504 	mtx_lock(&sc->reg_lock);
9505 	if (hw_off_limits(sc))
9506 		rc = ENXIO;
9507 	else
9508 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9509 		    dparams->size);
9510 	mtx_unlock(&sc->reg_lock);
9511 	if (rc != 0)
9512 		goto done;
9513 
9514 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9515 	for (i = 0; i < nentries; i++) {
9516 		e = &buf[i];
9517 
9518 		if (e->timestamp == 0)
9519 			break;	/* end */
9520 
9521 		e->timestamp = be64toh(e->timestamp);
9522 		e->seqno = be32toh(e->seqno);
9523 		for (j = 0; j < 8; j++)
9524 			e->params[j] = be32toh(e->params[j]);
9525 
9526 		if (e->timestamp < ftstamp) {
9527 			ftstamp = e->timestamp;
9528 			first = i;
9529 		}
9530 	}
9531 
9532 	if (buf[first].timestamp == 0)
9533 		goto done;	/* nothing in the log */
9534 
9535 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9536 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9537 
9538 	i = first;
9539 	do {
9540 		e = &buf[i];
9541 		if (e->timestamp == 0)
9542 			break;	/* end */
9543 
9544 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9545 		    e->seqno, e->timestamp,
9546 		    (e->level < nitems(devlog_level_strings) ?
9547 			devlog_level_strings[e->level] : "UNKNOWN"),
9548 		    (e->facility < nitems(devlog_facility_strings) ?
9549 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9550 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9551 		    e->params[2], e->params[3], e->params[4],
9552 		    e->params[5], e->params[6], e->params[7]);
9553 
9554 		if (++i == nentries)
9555 			i = 0;
9556 	} while (i != first);
9557 done:
9558 	free(buf, M_CXGBE);
9559 	return (rc);
9560 }
9561 
9562 static int
9563 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9564 {
9565 	struct adapter *sc = arg1;
9566 	int rc;
9567 	struct sbuf *sb;
9568 
9569 	rc = sysctl_wire_old_buffer(req, 0);
9570 	if (rc != 0)
9571 		return (rc);
9572 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9573 	if (sb == NULL)
9574 		return (ENOMEM);
9575 
9576 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9577 	if (rc == 0)
9578 		rc = sbuf_finish(sb);
9579 	sbuf_delete(sb);
9580 	return (rc);
9581 }
9582 
9583 static void
9584 dump_devlog(struct adapter *sc)
9585 {
9586 	int rc;
9587 	struct sbuf sb;
9588 
9589 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9590 		log(LOG_DEBUG, "%s: failed to generate devlog dump.\n",
9591 		    device_get_nameunit(sc->dev));
9592 		return;
9593 	}
9594 	rc = sbuf_devlog(sc, &sb, M_WAITOK);
9595 	if (rc == 0) {
9596 		rc = sbuf_finish(&sb);
9597 		if (rc == 0) {
9598 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9599 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
9600 		}
9601 	}
9602 	sbuf_delete(&sb);
9603 }
9604 
9605 static int
9606 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9607 {
9608 	struct adapter *sc = arg1;
9609 	struct sbuf *sb;
9610 	int rc;
9611 	struct tp_fcoe_stats stats[MAX_NCHAN];
9612 	int i, nchan = sc->chip_params->nchan;
9613 
9614 	rc = sysctl_wire_old_buffer(req, 0);
9615 	if (rc != 0)
9616 		return (rc);
9617 
9618 	mtx_lock(&sc->reg_lock);
9619 	if (hw_off_limits(sc))
9620 		rc = ENXIO;
9621 	else {
9622 		for (i = 0; i < nchan; i++)
9623 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9624 	}
9625 	mtx_unlock(&sc->reg_lock);
9626 	if (rc != 0)
9627 		return (rc);
9628 
9629 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9630 	if (sb == NULL)
9631 		return (ENOMEM);
9632 
9633 	if (nchan > 2) {
9634 		sbuf_printf(sb, "                   channel 0        channel 1"
9635 		    "        channel 2        channel 3");
9636 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9637 		    stats[0].octets_ddp, stats[1].octets_ddp,
9638 		    stats[2].octets_ddp, stats[3].octets_ddp);
9639 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9640 		    stats[0].frames_ddp, stats[1].frames_ddp,
9641 		    stats[2].frames_ddp, stats[3].frames_ddp);
9642 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9643 		    stats[0].frames_drop, stats[1].frames_drop,
9644 		    stats[2].frames_drop, stats[3].frames_drop);
9645 	} else {
9646 		sbuf_printf(sb, "                   channel 0        channel 1");
9647 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9648 		    stats[0].octets_ddp, stats[1].octets_ddp);
9649 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9650 		    stats[0].frames_ddp, stats[1].frames_ddp);
9651 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9652 		    stats[0].frames_drop, stats[1].frames_drop);
9653 	}
9654 
9655 	rc = sbuf_finish(sb);
9656 	sbuf_delete(sb);
9657 
9658 	return (rc);
9659 }
9660 
9661 static int
9662 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9663 {
9664 	struct adapter *sc = arg1;
9665 	struct sbuf *sb;
9666 	int rc, i;
9667 	unsigned int map, kbps, ipg, mode;
9668 	unsigned int pace_tab[NTX_SCHED];
9669 
9670 	rc = sysctl_wire_old_buffer(req, 0);
9671 	if (rc != 0)
9672 		return (rc);
9673 
9674 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9675 	if (sb == NULL)
9676 		return (ENOMEM);
9677 
9678 	mtx_lock(&sc->reg_lock);
9679 	if (hw_off_limits(sc)) {
9680 		rc = ENXIO;
9681 		goto done;
9682 	}
9683 
9684 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9685 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9686 	t4_read_pace_tbl(sc, pace_tab);
9687 
9688 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9689 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9690 
9691 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9692 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9693 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9694 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9695 		if (kbps)
9696 			sbuf_printf(sb, "%9u     ", kbps);
9697 		else
9698 			sbuf_printf(sb, " disabled     ");
9699 
9700 		if (ipg)
9701 			sbuf_printf(sb, "%13u        ", ipg);
9702 		else
9703 			sbuf_printf(sb, "     disabled        ");
9704 
9705 		if (pace_tab[i])
9706 			sbuf_printf(sb, "%10u", pace_tab[i]);
9707 		else
9708 			sbuf_printf(sb, "  disabled");
9709 	}
9710 	rc = sbuf_finish(sb);
9711 done:
9712 	mtx_unlock(&sc->reg_lock);
9713 	sbuf_delete(sb);
9714 	return (rc);
9715 }
9716 
9717 static int
9718 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9719 {
9720 	struct adapter *sc = arg1;
9721 	struct sbuf *sb;
9722 	int rc, i, j;
9723 	uint64_t *p0, *p1;
9724 	struct lb_port_stats s[2];
9725 	static const char *stat_name[] = {
9726 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9727 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9728 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9729 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9730 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9731 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9732 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9733 	};
9734 
9735 	rc = sysctl_wire_old_buffer(req, 0);
9736 	if (rc != 0)
9737 		return (rc);
9738 
9739 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9740 	if (sb == NULL)
9741 		return (ENOMEM);
9742 
9743 	memset(s, 0, sizeof(s));
9744 
9745 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9746 		mtx_lock(&sc->reg_lock);
9747 		if (hw_off_limits(sc))
9748 			rc = ENXIO;
9749 		else {
9750 			t4_get_lb_stats(sc, i, &s[0]);
9751 			t4_get_lb_stats(sc, i + 1, &s[1]);
9752 		}
9753 		mtx_unlock(&sc->reg_lock);
9754 		if (rc != 0)
9755 			break;
9756 
9757 		p0 = &s[0].octets;
9758 		p1 = &s[1].octets;
9759 		sbuf_printf(sb, "%s                       Loopback %u"
9760 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9761 
9762 		for (j = 0; j < nitems(stat_name); j++)
9763 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9764 				   *p0++, *p1++);
9765 	}
9766 
9767 	rc = sbuf_finish(sb);
9768 	sbuf_delete(sb);
9769 
9770 	return (rc);
9771 }
9772 
9773 static int
9774 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9775 {
9776 	int rc = 0;
9777 	struct port_info *pi = arg1;
9778 	struct link_config *lc = &pi->link_cfg;
9779 	struct sbuf *sb;
9780 
9781 	rc = sysctl_wire_old_buffer(req, 0);
9782 	if (rc != 0)
9783 		return(rc);
9784 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9785 	if (sb == NULL)
9786 		return (ENOMEM);
9787 
9788 	if (lc->link_ok || lc->link_down_rc == 255)
9789 		sbuf_printf(sb, "n/a");
9790 	else
9791 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9792 
9793 	rc = sbuf_finish(sb);
9794 	sbuf_delete(sb);
9795 
9796 	return (rc);
9797 }
9798 
9799 struct mem_desc {
9800 	u_int base;
9801 	u_int limit;
9802 	u_int idx;
9803 };
9804 
9805 static int
9806 mem_desc_cmp(const void *a, const void *b)
9807 {
9808 	const u_int v1 = ((const struct mem_desc *)a)->base;
9809 	const u_int v2 = ((const struct mem_desc *)b)->base;
9810 
9811 	if (v1 < v2)
9812 		return (-1);
9813 	else if (v1 > v2)
9814 		return (1);
9815 
9816 	return (0);
9817 }
9818 
9819 static void
9820 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9821     unsigned int to)
9822 {
9823 	unsigned int size;
9824 
9825 	if (from == to)
9826 		return;
9827 
9828 	size = to - from + 1;
9829 	if (size == 0)
9830 		return;
9831 
9832 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9833 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9834 }
9835 
9836 static int
9837 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9838 {
9839 	struct adapter *sc = arg1;
9840 	struct sbuf *sb;
9841 	int rc, i, n;
9842 	uint32_t lo, hi, used, free, alloc;
9843 	static const char *memory[] = {
9844 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9845 	};
9846 	static const char *region[] = {
9847 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9848 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9849 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9850 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9851 		"RQUDP region:", "PBL region:", "TXPBL region:",
9852 		"TLSKey region:", "DBVFIFO region:", "ULPRX state:",
9853 		"ULPTX state:", "On-chip queues:",
9854 	};
9855 	struct mem_desc avail[4];
9856 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9857 	struct mem_desc *md = mem;
9858 
9859 	rc = sysctl_wire_old_buffer(req, 0);
9860 	if (rc != 0)
9861 		return (rc);
9862 
9863 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9864 	if (sb == NULL)
9865 		return (ENOMEM);
9866 
9867 	for (i = 0; i < nitems(mem); i++) {
9868 		mem[i].limit = 0;
9869 		mem[i].idx = i;
9870 	}
9871 
9872 	mtx_lock(&sc->reg_lock);
9873 	if (hw_off_limits(sc)) {
9874 		rc = ENXIO;
9875 		goto done;
9876 	}
9877 
9878 	/* Find and sort the populated memory ranges */
9879 	i = 0;
9880 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9881 	if (lo & F_EDRAM0_ENABLE) {
9882 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9883 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9884 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9885 		avail[i].idx = 0;
9886 		i++;
9887 	}
9888 	if (lo & F_EDRAM1_ENABLE) {
9889 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9890 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9891 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9892 		avail[i].idx = 1;
9893 		i++;
9894 	}
9895 	if (lo & F_EXT_MEM_ENABLE) {
9896 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9897 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9898 		avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9899 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9900 		i++;
9901 	}
9902 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9903 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9904 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9905 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9906 		avail[i].idx = 4;
9907 		i++;
9908 	}
9909 	if (is_t6(sc) && lo & F_HMA_MUX) {
9910 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9911 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9912 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9913 		avail[i].idx = 5;
9914 		i++;
9915 	}
9916 	MPASS(i <= nitems(avail));
9917 	if (!i)                                    /* no memory available */
9918 		goto done;
9919 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9920 
9921 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9922 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9923 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9924 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9925 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9926 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9927 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9928 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9929 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9930 
9931 	/* the next few have explicit upper bounds */
9932 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9933 	md->limit = md->base - 1 +
9934 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9935 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9936 	md++;
9937 
9938 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9939 	md->limit = md->base - 1 +
9940 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9941 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9942 	md++;
9943 
9944 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9945 		if (chip_id(sc) <= CHELSIO_T5)
9946 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9947 		else
9948 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9949 		md->limit = 0;
9950 	} else {
9951 		md->base = 0;
9952 		md->idx = nitems(region);  /* hide it */
9953 	}
9954 	md++;
9955 
9956 #define ulp_region(reg) \
9957 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9958 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9959 
9960 	ulp_region(RX_ISCSI);
9961 	ulp_region(RX_TDDP);
9962 	ulp_region(TX_TPT);
9963 	ulp_region(RX_STAG);
9964 	ulp_region(RX_RQ);
9965 	ulp_region(RX_RQUDP);
9966 	ulp_region(RX_PBL);
9967 	ulp_region(TX_PBL);
9968 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
9969 		ulp_region(RX_TLS_KEY);
9970 	}
9971 #undef ulp_region
9972 
9973 	md->base = 0;
9974 	if (is_t4(sc))
9975 		md->idx = nitems(region);
9976 	else {
9977 		uint32_t size = 0;
9978 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9979 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9980 
9981 		if (is_t5(sc)) {
9982 			if (sge_ctrl & F_VFIFO_ENABLE)
9983 				size = fifo_size << 2;
9984 		} else
9985 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9986 
9987 		if (size) {
9988 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
9989 			md->limit = md->base + size - 1;
9990 		} else
9991 			md->idx = nitems(region);
9992 	}
9993 	md++;
9994 
9995 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9996 	md->limit = 0;
9997 	md++;
9998 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9999 	md->limit = 0;
10000 	md++;
10001 
10002 	md->base = sc->vres.ocq.start;
10003 	if (sc->vres.ocq.size)
10004 		md->limit = md->base + sc->vres.ocq.size - 1;
10005 	else
10006 		md->idx = nitems(region);  /* hide it */
10007 	md++;
10008 
10009 	/* add any address-space holes, there can be up to 3 */
10010 	for (n = 0; n < i - 1; n++)
10011 		if (avail[n].limit < avail[n + 1].base)
10012 			(md++)->base = avail[n].limit;
10013 	if (avail[n].limit)
10014 		(md++)->base = avail[n].limit;
10015 
10016 	n = md - mem;
10017 	MPASS(n <= nitems(mem));
10018 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
10019 
10020 	for (lo = 0; lo < i; lo++)
10021 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
10022 				avail[lo].limit - 1);
10023 
10024 	sbuf_printf(sb, "\n");
10025 	for (i = 0; i < n; i++) {
10026 		if (mem[i].idx >= nitems(region))
10027 			continue;                        /* skip holes */
10028 		if (!mem[i].limit)
10029 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
10030 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
10031 				mem[i].limit);
10032 	}
10033 
10034 	sbuf_printf(sb, "\n");
10035 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
10036 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
10037 	mem_region_show(sb, "uP RAM:", lo, hi);
10038 
10039 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
10040 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
10041 	mem_region_show(sb, "uP Extmem2:", lo, hi);
10042 
10043 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
10044 	for (i = 0, free = 0; i < 2; i++)
10045 		free += G_FREERXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_RX_CNT));
10046 	sbuf_printf(sb, "\n%u Rx pages (%u free) of size %uKiB for %u channels\n",
10047 		   G_PMRXMAXPAGE(lo), free,
10048 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
10049 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
10050 
10051 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
10052 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
10053 	for (i = 0, free = 0; i < 4; i++)
10054 		free += G_FREETXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_TX_CNT));
10055 	sbuf_printf(sb, "%u Tx pages (%u free) of size %u%ciB for %u channels\n",
10056 		   G_PMTXMAXPAGE(lo), free,
10057 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
10058 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
10059 	sbuf_printf(sb, "%u p-structs (%u free)\n",
10060 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT),
10061 		   G_FREEPSTRUCTCOUNT(t4_read_reg(sc, A_TP_FLM_FREE_PS_CNT)));
10062 
10063 	for (i = 0; i < 4; i++) {
10064 		if (chip_id(sc) > CHELSIO_T5)
10065 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
10066 		else
10067 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
10068 		if (is_t5(sc)) {
10069 			used = G_T5_USED(lo);
10070 			alloc = G_T5_ALLOC(lo);
10071 		} else {
10072 			used = G_USED(lo);
10073 			alloc = G_ALLOC(lo);
10074 		}
10075 		/* For T6 these are MAC buffer groups */
10076 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
10077 		    i, used, alloc);
10078 	}
10079 	for (i = 0; i < sc->chip_params->nchan; i++) {
10080 		if (chip_id(sc) > CHELSIO_T5)
10081 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
10082 		else
10083 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
10084 		if (is_t5(sc)) {
10085 			used = G_T5_USED(lo);
10086 			alloc = G_T5_ALLOC(lo);
10087 		} else {
10088 			used = G_USED(lo);
10089 			alloc = G_ALLOC(lo);
10090 		}
10091 		/* For T6 these are MAC buffer groups */
10092 		sbuf_printf(sb,
10093 		    "\nLoopback %d using %u pages out of %u allocated",
10094 		    i, used, alloc);
10095 	}
10096 done:
10097 	mtx_unlock(&sc->reg_lock);
10098 	if (rc == 0)
10099 		rc = sbuf_finish(sb);
10100 	sbuf_delete(sb);
10101 	return (rc);
10102 }
10103 
10104 static inline void
10105 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
10106 {
10107 	*mask = x | y;
10108 	y = htobe64(y);
10109 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
10110 }
10111 
10112 static int
10113 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
10114 {
10115 	struct adapter *sc = arg1;
10116 	struct sbuf *sb;
10117 	int rc, i;
10118 
10119 	MPASS(chip_id(sc) <= CHELSIO_T5);
10120 
10121 	rc = sysctl_wire_old_buffer(req, 0);
10122 	if (rc != 0)
10123 		return (rc);
10124 
10125 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10126 	if (sb == NULL)
10127 		return (ENOMEM);
10128 
10129 	sbuf_printf(sb,
10130 	    "Idx  Ethernet address     Mask     Vld Ports PF"
10131 	    "  VF              Replication             P0 P1 P2 P3  ML");
10132 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10133 		uint64_t tcamx, tcamy, mask;
10134 		uint32_t cls_lo, cls_hi;
10135 		uint8_t addr[ETHER_ADDR_LEN];
10136 
10137 		mtx_lock(&sc->reg_lock);
10138 		if (hw_off_limits(sc))
10139 			rc = ENXIO;
10140 		else {
10141 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
10142 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
10143 		}
10144 		mtx_unlock(&sc->reg_lock);
10145 		if (rc != 0)
10146 			break;
10147 		if (tcamx & tcamy)
10148 			continue;
10149 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10150 		mtx_lock(&sc->reg_lock);
10151 		if (hw_off_limits(sc))
10152 			rc = ENXIO;
10153 		else {
10154 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10155 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10156 		}
10157 		mtx_unlock(&sc->reg_lock);
10158 		if (rc != 0)
10159 			break;
10160 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
10161 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
10162 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
10163 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
10164 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
10165 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
10166 
10167 		if (cls_lo & F_REPLICATE) {
10168 			struct fw_ldst_cmd ldst_cmd;
10169 
10170 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10171 			ldst_cmd.op_to_addrspace =
10172 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10173 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10174 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10175 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10176 			ldst_cmd.u.mps.rplc.fid_idx =
10177 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10178 				V_FW_LDST_CMD_IDX(i));
10179 
10180 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10181 			    "t4mps");
10182 			if (rc)
10183 				break;
10184 			if (hw_off_limits(sc))
10185 				rc = ENXIO;
10186 			else
10187 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10188 				    sizeof(ldst_cmd), &ldst_cmd);
10189 			end_synchronized_op(sc, 0);
10190 			if (rc != 0)
10191 				break;
10192 			else {
10193 				sbuf_printf(sb, " %08x %08x %08x %08x",
10194 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10195 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10196 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10197 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10198 			}
10199 		} else
10200 			sbuf_printf(sb, "%36s", "");
10201 
10202 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
10203 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
10204 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
10205 	}
10206 
10207 	if (rc)
10208 		(void) sbuf_finish(sb);
10209 	else
10210 		rc = sbuf_finish(sb);
10211 	sbuf_delete(sb);
10212 
10213 	return (rc);
10214 }
10215 
10216 static int
10217 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
10218 {
10219 	struct adapter *sc = arg1;
10220 	struct sbuf *sb;
10221 	int rc, i;
10222 
10223 	MPASS(chip_id(sc) > CHELSIO_T5);
10224 
10225 	rc = sysctl_wire_old_buffer(req, 0);
10226 	if (rc != 0)
10227 		return (rc);
10228 
10229 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10230 	if (sb == NULL)
10231 		return (ENOMEM);
10232 
10233 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
10234 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
10235 	    "                           Replication"
10236 	    "                                    P0 P1 P2 P3  ML\n");
10237 
10238 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10239 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
10240 		uint16_t ivlan;
10241 		uint64_t tcamx, tcamy, val, mask;
10242 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10243 		uint8_t addr[ETHER_ADDR_LEN];
10244 
10245 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10246 		if (i < 256)
10247 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10248 		else
10249 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10250 		mtx_lock(&sc->reg_lock);
10251 		if (hw_off_limits(sc))
10252 			rc = ENXIO;
10253 		else {
10254 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10255 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10256 			tcamy = G_DMACH(val) << 32;
10257 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10258 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10259 		}
10260 		mtx_unlock(&sc->reg_lock);
10261 		if (rc != 0)
10262 			break;
10263 
10264 		lookup_type = G_DATALKPTYPE(data2);
10265 		port_num = G_DATAPORTNUM(data2);
10266 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10267 			/* Inner header VNI */
10268 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10269 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10270 			dip_hit = data2 & F_DATADIPHIT;
10271 			vlan_vld = 0;
10272 		} else {
10273 			vniy = 0;
10274 			dip_hit = 0;
10275 			vlan_vld = data2 & F_DATAVIDH2;
10276 			ivlan = G_VIDL(val);
10277 		}
10278 
10279 		ctl |= V_CTLXYBITSEL(1);
10280 		mtx_lock(&sc->reg_lock);
10281 		if (hw_off_limits(sc))
10282 			rc = ENXIO;
10283 		else {
10284 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10285 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10286 			tcamx = G_DMACH(val) << 32;
10287 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10288 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10289 		}
10290 		mtx_unlock(&sc->reg_lock);
10291 		if (rc != 0)
10292 			break;
10293 
10294 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10295 			/* Inner header VNI mask */
10296 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10297 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10298 		} else
10299 			vnix = 0;
10300 
10301 		if (tcamx & tcamy)
10302 			continue;
10303 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10304 
10305 		mtx_lock(&sc->reg_lock);
10306 		if (hw_off_limits(sc))
10307 			rc = ENXIO;
10308 		else {
10309 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10310 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10311 		}
10312 		mtx_unlock(&sc->reg_lock);
10313 		if (rc != 0)
10314 			break;
10315 
10316 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10317 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10318 			    "%012jx %06x %06x    -    -   %3c"
10319 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10320 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10321 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10322 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10323 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10324 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10325 		} else {
10326 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10327 			    "%012jx    -       -   ", i, addr[0], addr[1],
10328 			    addr[2], addr[3], addr[4], addr[5],
10329 			    (uintmax_t)mask);
10330 
10331 			if (vlan_vld)
10332 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10333 			else
10334 				sbuf_printf(sb, "  -    N     ");
10335 
10336 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10337 			    lookup_type ? 'I' : 'O', port_num,
10338 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10339 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10340 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10341 		}
10342 
10343 
10344 		if (cls_lo & F_T6_REPLICATE) {
10345 			struct fw_ldst_cmd ldst_cmd;
10346 
10347 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10348 			ldst_cmd.op_to_addrspace =
10349 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10350 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10351 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10352 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10353 			ldst_cmd.u.mps.rplc.fid_idx =
10354 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10355 				V_FW_LDST_CMD_IDX(i));
10356 
10357 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10358 			    "t6mps");
10359 			if (rc)
10360 				break;
10361 			if (hw_off_limits(sc))
10362 				rc = ENXIO;
10363 			else
10364 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10365 				    sizeof(ldst_cmd), &ldst_cmd);
10366 			end_synchronized_op(sc, 0);
10367 			if (rc != 0)
10368 				break;
10369 			else {
10370 				sbuf_printf(sb, " %08x %08x %08x %08x"
10371 				    " %08x %08x %08x %08x",
10372 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10373 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10374 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10375 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10376 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10377 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10378 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10379 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10380 			}
10381 		} else
10382 			sbuf_printf(sb, "%72s", "");
10383 
10384 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10385 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10386 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10387 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10388 	}
10389 
10390 	if (rc)
10391 		(void) sbuf_finish(sb);
10392 	else
10393 		rc = sbuf_finish(sb);
10394 	sbuf_delete(sb);
10395 
10396 	return (rc);
10397 }
10398 
10399 static int
10400 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10401 {
10402 	struct adapter *sc = arg1;
10403 	struct sbuf *sb;
10404 	int rc;
10405 	uint16_t mtus[NMTUS];
10406 
10407 	rc = sysctl_wire_old_buffer(req, 0);
10408 	if (rc != 0)
10409 		return (rc);
10410 
10411 	mtx_lock(&sc->reg_lock);
10412 	if (hw_off_limits(sc))
10413 		rc = ENXIO;
10414 	else
10415 		t4_read_mtu_tbl(sc, mtus, NULL);
10416 	mtx_unlock(&sc->reg_lock);
10417 	if (rc != 0)
10418 		return (rc);
10419 
10420 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10421 	if (sb == NULL)
10422 		return (ENOMEM);
10423 
10424 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10425 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10426 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10427 	    mtus[14], mtus[15]);
10428 
10429 	rc = sbuf_finish(sb);
10430 	sbuf_delete(sb);
10431 
10432 	return (rc);
10433 }
10434 
10435 static int
10436 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10437 {
10438 	struct adapter *sc = arg1;
10439 	struct sbuf *sb;
10440 	int rc, i;
10441 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10442 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10443 	static const char *tx_stats[MAX_PM_NSTATS] = {
10444 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10445 		"Tx FIFO wait", NULL, "Tx latency"
10446 	};
10447 	static const char *rx_stats[MAX_PM_NSTATS] = {
10448 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10449 		"Rx FIFO wait", NULL, "Rx latency"
10450 	};
10451 
10452 	rc = sysctl_wire_old_buffer(req, 0);
10453 	if (rc != 0)
10454 		return (rc);
10455 
10456 	mtx_lock(&sc->reg_lock);
10457 	if (hw_off_limits(sc))
10458 		rc = ENXIO;
10459 	else {
10460 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10461 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10462 	}
10463 	mtx_unlock(&sc->reg_lock);
10464 	if (rc != 0)
10465 		return (rc);
10466 
10467 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10468 	if (sb == NULL)
10469 		return (ENOMEM);
10470 
10471 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10472 	for (i = 0; i < 4; i++) {
10473 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10474 		    tx_cyc[i]);
10475 	}
10476 
10477 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10478 	for (i = 0; i < 4; i++) {
10479 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10480 		    rx_cyc[i]);
10481 	}
10482 
10483 	if (chip_id(sc) > CHELSIO_T5) {
10484 		sbuf_printf(sb,
10485 		    "\n              Total wait      Total occupancy");
10486 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10487 		    tx_cyc[i]);
10488 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10489 		    rx_cyc[i]);
10490 
10491 		i += 2;
10492 		MPASS(i < nitems(tx_stats));
10493 
10494 		sbuf_printf(sb,
10495 		    "\n                   Reads           Total wait");
10496 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10497 		    tx_cyc[i]);
10498 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10499 		    rx_cyc[i]);
10500 	}
10501 
10502 	rc = sbuf_finish(sb);
10503 	sbuf_delete(sb);
10504 
10505 	return (rc);
10506 }
10507 
10508 static int
10509 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10510 {
10511 	struct adapter *sc = arg1;
10512 	struct sbuf *sb;
10513 	int rc;
10514 	struct tp_rdma_stats stats;
10515 
10516 	rc = sysctl_wire_old_buffer(req, 0);
10517 	if (rc != 0)
10518 		return (rc);
10519 
10520 	mtx_lock(&sc->reg_lock);
10521 	if (hw_off_limits(sc))
10522 		rc = ENXIO;
10523 	else
10524 		t4_tp_get_rdma_stats(sc, &stats, 0);
10525 	mtx_unlock(&sc->reg_lock);
10526 	if (rc != 0)
10527 		return (rc);
10528 
10529 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10530 	if (sb == NULL)
10531 		return (ENOMEM);
10532 
10533 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10534 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10535 
10536 	rc = sbuf_finish(sb);
10537 	sbuf_delete(sb);
10538 
10539 	return (rc);
10540 }
10541 
10542 static int
10543 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10544 {
10545 	struct adapter *sc = arg1;
10546 	struct sbuf *sb;
10547 	int rc;
10548 	struct tp_tcp_stats v4, v6;
10549 
10550 	rc = sysctl_wire_old_buffer(req, 0);
10551 	if (rc != 0)
10552 		return (rc);
10553 
10554 	mtx_lock(&sc->reg_lock);
10555 	if (hw_off_limits(sc))
10556 		rc = ENXIO;
10557 	else
10558 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10559 	mtx_unlock(&sc->reg_lock);
10560 	if (rc != 0)
10561 		return (rc);
10562 
10563 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10564 	if (sb == NULL)
10565 		return (ENOMEM);
10566 
10567 	sbuf_printf(sb,
10568 	    "                                IP                 IPv6\n");
10569 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10570 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10571 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10572 	    v4.tcp_in_segs, v6.tcp_in_segs);
10573 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10574 	    v4.tcp_out_segs, v6.tcp_out_segs);
10575 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10576 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10577 
10578 	rc = sbuf_finish(sb);
10579 	sbuf_delete(sb);
10580 
10581 	return (rc);
10582 }
10583 
10584 static int
10585 sysctl_tids(SYSCTL_HANDLER_ARGS)
10586 {
10587 	struct adapter *sc = arg1;
10588 	struct sbuf *sb;
10589 	int rc;
10590 	uint32_t x, y;
10591 	struct tid_info *t = &sc->tids;
10592 
10593 	rc = sysctl_wire_old_buffer(req, 0);
10594 	if (rc != 0)
10595 		return (rc);
10596 
10597 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10598 	if (sb == NULL)
10599 		return (ENOMEM);
10600 
10601 	if (t->natids) {
10602 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10603 		    t->atids_in_use);
10604 	}
10605 
10606 	if (t->nhpftids) {
10607 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10608 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10609 	}
10610 
10611 	if (t->ntids) {
10612 		bool hashen = false;
10613 
10614 		mtx_lock(&sc->reg_lock);
10615 		if (hw_off_limits(sc))
10616 			rc = ENXIO;
10617 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10618 			hashen = true;
10619 			if (chip_id(sc) <= CHELSIO_T5) {
10620 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10621 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10622 			} else {
10623 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10624 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10625 			}
10626 		}
10627 		mtx_unlock(&sc->reg_lock);
10628 		if (rc != 0)
10629 			goto done;
10630 
10631 		sbuf_printf(sb, "TID range: ");
10632 		if (hashen) {
10633 			if (x)
10634 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10635 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10636 		} else {
10637 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10638 			    t->ntids - 1);
10639 		}
10640 		sbuf_printf(sb, ", in use: %u\n",
10641 		    atomic_load_acq_int(&t->tids_in_use));
10642 	}
10643 
10644 	if (t->nstids) {
10645 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10646 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10647 	}
10648 
10649 	if (t->nftids) {
10650 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10651 		    t->ftid_end, t->ftids_in_use);
10652 	}
10653 
10654 	if (t->netids) {
10655 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10656 		    t->etid_base + t->netids - 1, t->etids_in_use);
10657 	}
10658 
10659 	mtx_lock(&sc->reg_lock);
10660 	if (hw_off_limits(sc))
10661 		rc = ENXIO;
10662 	else {
10663 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10664 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10665 	}
10666 	mtx_unlock(&sc->reg_lock);
10667 	if (rc != 0)
10668 		goto done;
10669 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10670 done:
10671 	if (rc == 0)
10672 		rc = sbuf_finish(sb);
10673 	else
10674 		(void)sbuf_finish(sb);
10675 	sbuf_delete(sb);
10676 
10677 	return (rc);
10678 }
10679 
10680 static int
10681 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10682 {
10683 	struct adapter *sc = arg1;
10684 	struct sbuf *sb;
10685 	int rc;
10686 	struct tp_err_stats stats;
10687 
10688 	rc = sysctl_wire_old_buffer(req, 0);
10689 	if (rc != 0)
10690 		return (rc);
10691 
10692 	mtx_lock(&sc->reg_lock);
10693 	if (hw_off_limits(sc))
10694 		rc = ENXIO;
10695 	else
10696 		t4_tp_get_err_stats(sc, &stats, 0);
10697 	mtx_unlock(&sc->reg_lock);
10698 	if (rc != 0)
10699 		return (rc);
10700 
10701 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10702 	if (sb == NULL)
10703 		return (ENOMEM);
10704 
10705 	if (sc->chip_params->nchan > 2) {
10706 		sbuf_printf(sb, "                 channel 0  channel 1"
10707 		    "  channel 2  channel 3\n");
10708 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10709 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10710 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10711 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10712 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10713 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10714 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10715 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10716 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10717 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10718 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10719 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10720 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10721 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10722 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10723 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10724 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10725 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10726 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10727 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10728 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10729 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10730 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10731 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10732 	} else {
10733 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10734 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10735 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10736 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10737 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10738 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10739 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10740 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10741 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10742 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10743 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10744 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10745 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10746 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10747 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10748 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10749 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10750 	}
10751 
10752 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10753 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10754 
10755 	rc = sbuf_finish(sb);
10756 	sbuf_delete(sb);
10757 
10758 	return (rc);
10759 }
10760 
10761 static int
10762 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10763 {
10764 	struct adapter *sc = arg1;
10765 	struct sbuf *sb;
10766 	int rc;
10767 	struct tp_tnl_stats stats;
10768 
10769 	rc = sysctl_wire_old_buffer(req, 0);
10770 	if (rc != 0)
10771 		return(rc);
10772 
10773 	mtx_lock(&sc->reg_lock);
10774 	if (hw_off_limits(sc))
10775 		rc = ENXIO;
10776 	else
10777 		t4_tp_get_tnl_stats(sc, &stats, 1);
10778 	mtx_unlock(&sc->reg_lock);
10779 	if (rc != 0)
10780 		return (rc);
10781 
10782 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10783 	if (sb == NULL)
10784 		return (ENOMEM);
10785 
10786 	if (sc->chip_params->nchan > 2) {
10787 		sbuf_printf(sb, "           channel 0  channel 1"
10788 		    "  channel 2  channel 3\n");
10789 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10790 		    stats.out_pkt[0], stats.out_pkt[1],
10791 		    stats.out_pkt[2], stats.out_pkt[3]);
10792 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10793 		    stats.in_pkt[0], stats.in_pkt[1],
10794 		    stats.in_pkt[2], stats.in_pkt[3]);
10795 	} else {
10796 		sbuf_printf(sb, "           channel 0  channel 1\n");
10797 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10798 		    stats.out_pkt[0], stats.out_pkt[1]);
10799 		sbuf_printf(sb, "InPkts:   %10u %10u",
10800 		    stats.in_pkt[0], stats.in_pkt[1]);
10801 	}
10802 
10803 	rc = sbuf_finish(sb);
10804 	sbuf_delete(sb);
10805 
10806 	return (rc);
10807 }
10808 
10809 static int
10810 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10811 {
10812 	struct adapter *sc = arg1;
10813 	struct tp_params *tpp = &sc->params.tp;
10814 	u_int mask;
10815 	int rc;
10816 
10817 	mask = tpp->la_mask >> 16;
10818 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10819 	if (rc != 0 || req->newptr == NULL)
10820 		return (rc);
10821 	if (mask > 0xffff)
10822 		return (EINVAL);
10823 	mtx_lock(&sc->reg_lock);
10824 	if (hw_off_limits(sc))
10825 		rc = ENXIO;
10826 	else {
10827 		tpp->la_mask = mask << 16;
10828 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10829 		    tpp->la_mask);
10830 	}
10831 	mtx_unlock(&sc->reg_lock);
10832 
10833 	return (rc);
10834 }
10835 
10836 struct field_desc {
10837 	const char *name;
10838 	u_int start;
10839 	u_int width;
10840 };
10841 
10842 static void
10843 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10844 {
10845 	char buf[32];
10846 	int line_size = 0;
10847 
10848 	while (f->name) {
10849 		uint64_t mask = (1ULL << f->width) - 1;
10850 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10851 		    ((uintmax_t)v >> f->start) & mask);
10852 
10853 		if (line_size + len >= 79) {
10854 			line_size = 8;
10855 			sbuf_printf(sb, "\n        ");
10856 		}
10857 		sbuf_printf(sb, "%s ", buf);
10858 		line_size += len + 1;
10859 		f++;
10860 	}
10861 	sbuf_printf(sb, "\n");
10862 }
10863 
10864 static const struct field_desc tp_la0[] = {
10865 	{ "RcfOpCodeOut", 60, 4 },
10866 	{ "State", 56, 4 },
10867 	{ "WcfState", 52, 4 },
10868 	{ "RcfOpcSrcOut", 50, 2 },
10869 	{ "CRxError", 49, 1 },
10870 	{ "ERxError", 48, 1 },
10871 	{ "SanityFailed", 47, 1 },
10872 	{ "SpuriousMsg", 46, 1 },
10873 	{ "FlushInputMsg", 45, 1 },
10874 	{ "FlushInputCpl", 44, 1 },
10875 	{ "RssUpBit", 43, 1 },
10876 	{ "RssFilterHit", 42, 1 },
10877 	{ "Tid", 32, 10 },
10878 	{ "InitTcb", 31, 1 },
10879 	{ "LineNumber", 24, 7 },
10880 	{ "Emsg", 23, 1 },
10881 	{ "EdataOut", 22, 1 },
10882 	{ "Cmsg", 21, 1 },
10883 	{ "CdataOut", 20, 1 },
10884 	{ "EreadPdu", 19, 1 },
10885 	{ "CreadPdu", 18, 1 },
10886 	{ "TunnelPkt", 17, 1 },
10887 	{ "RcfPeerFin", 16, 1 },
10888 	{ "RcfReasonOut", 12, 4 },
10889 	{ "TxCchannel", 10, 2 },
10890 	{ "RcfTxChannel", 8, 2 },
10891 	{ "RxEchannel", 6, 2 },
10892 	{ "RcfRxChannel", 5, 1 },
10893 	{ "RcfDataOutSrdy", 4, 1 },
10894 	{ "RxDvld", 3, 1 },
10895 	{ "RxOoDvld", 2, 1 },
10896 	{ "RxCongestion", 1, 1 },
10897 	{ "TxCongestion", 0, 1 },
10898 	{ NULL }
10899 };
10900 
10901 static const struct field_desc tp_la1[] = {
10902 	{ "CplCmdIn", 56, 8 },
10903 	{ "CplCmdOut", 48, 8 },
10904 	{ "ESynOut", 47, 1 },
10905 	{ "EAckOut", 46, 1 },
10906 	{ "EFinOut", 45, 1 },
10907 	{ "ERstOut", 44, 1 },
10908 	{ "SynIn", 43, 1 },
10909 	{ "AckIn", 42, 1 },
10910 	{ "FinIn", 41, 1 },
10911 	{ "RstIn", 40, 1 },
10912 	{ "DataIn", 39, 1 },
10913 	{ "DataInVld", 38, 1 },
10914 	{ "PadIn", 37, 1 },
10915 	{ "RxBufEmpty", 36, 1 },
10916 	{ "RxDdp", 35, 1 },
10917 	{ "RxFbCongestion", 34, 1 },
10918 	{ "TxFbCongestion", 33, 1 },
10919 	{ "TxPktSumSrdy", 32, 1 },
10920 	{ "RcfUlpType", 28, 4 },
10921 	{ "Eread", 27, 1 },
10922 	{ "Ebypass", 26, 1 },
10923 	{ "Esave", 25, 1 },
10924 	{ "Static0", 24, 1 },
10925 	{ "Cread", 23, 1 },
10926 	{ "Cbypass", 22, 1 },
10927 	{ "Csave", 21, 1 },
10928 	{ "CPktOut", 20, 1 },
10929 	{ "RxPagePoolFull", 18, 2 },
10930 	{ "RxLpbkPkt", 17, 1 },
10931 	{ "TxLpbkPkt", 16, 1 },
10932 	{ "RxVfValid", 15, 1 },
10933 	{ "SynLearned", 14, 1 },
10934 	{ "SetDelEntry", 13, 1 },
10935 	{ "SetInvEntry", 12, 1 },
10936 	{ "CpcmdDvld", 11, 1 },
10937 	{ "CpcmdSave", 10, 1 },
10938 	{ "RxPstructsFull", 8, 2 },
10939 	{ "EpcmdDvld", 7, 1 },
10940 	{ "EpcmdFlush", 6, 1 },
10941 	{ "EpcmdTrimPrefix", 5, 1 },
10942 	{ "EpcmdTrimPostfix", 4, 1 },
10943 	{ "ERssIp4Pkt", 3, 1 },
10944 	{ "ERssIp6Pkt", 2, 1 },
10945 	{ "ERssTcpUdpPkt", 1, 1 },
10946 	{ "ERssFceFipPkt", 0, 1 },
10947 	{ NULL }
10948 };
10949 
10950 static const struct field_desc tp_la2[] = {
10951 	{ "CplCmdIn", 56, 8 },
10952 	{ "MpsVfVld", 55, 1 },
10953 	{ "MpsPf", 52, 3 },
10954 	{ "MpsVf", 44, 8 },
10955 	{ "SynIn", 43, 1 },
10956 	{ "AckIn", 42, 1 },
10957 	{ "FinIn", 41, 1 },
10958 	{ "RstIn", 40, 1 },
10959 	{ "DataIn", 39, 1 },
10960 	{ "DataInVld", 38, 1 },
10961 	{ "PadIn", 37, 1 },
10962 	{ "RxBufEmpty", 36, 1 },
10963 	{ "RxDdp", 35, 1 },
10964 	{ "RxFbCongestion", 34, 1 },
10965 	{ "TxFbCongestion", 33, 1 },
10966 	{ "TxPktSumSrdy", 32, 1 },
10967 	{ "RcfUlpType", 28, 4 },
10968 	{ "Eread", 27, 1 },
10969 	{ "Ebypass", 26, 1 },
10970 	{ "Esave", 25, 1 },
10971 	{ "Static0", 24, 1 },
10972 	{ "Cread", 23, 1 },
10973 	{ "Cbypass", 22, 1 },
10974 	{ "Csave", 21, 1 },
10975 	{ "CPktOut", 20, 1 },
10976 	{ "RxPagePoolFull", 18, 2 },
10977 	{ "RxLpbkPkt", 17, 1 },
10978 	{ "TxLpbkPkt", 16, 1 },
10979 	{ "RxVfValid", 15, 1 },
10980 	{ "SynLearned", 14, 1 },
10981 	{ "SetDelEntry", 13, 1 },
10982 	{ "SetInvEntry", 12, 1 },
10983 	{ "CpcmdDvld", 11, 1 },
10984 	{ "CpcmdSave", 10, 1 },
10985 	{ "RxPstructsFull", 8, 2 },
10986 	{ "EpcmdDvld", 7, 1 },
10987 	{ "EpcmdFlush", 6, 1 },
10988 	{ "EpcmdTrimPrefix", 5, 1 },
10989 	{ "EpcmdTrimPostfix", 4, 1 },
10990 	{ "ERssIp4Pkt", 3, 1 },
10991 	{ "ERssIp6Pkt", 2, 1 },
10992 	{ "ERssTcpUdpPkt", 1, 1 },
10993 	{ "ERssFceFipPkt", 0, 1 },
10994 	{ NULL }
10995 };
10996 
10997 static void
10998 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10999 {
11000 
11001 	field_desc_show(sb, *p, tp_la0);
11002 }
11003 
11004 static void
11005 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
11006 {
11007 
11008 	if (idx)
11009 		sbuf_printf(sb, "\n");
11010 	field_desc_show(sb, p[0], tp_la0);
11011 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
11012 		field_desc_show(sb, p[1], tp_la0);
11013 }
11014 
11015 static void
11016 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
11017 {
11018 
11019 	if (idx)
11020 		sbuf_printf(sb, "\n");
11021 	field_desc_show(sb, p[0], tp_la0);
11022 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
11023 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
11024 }
11025 
11026 static int
11027 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
11028 {
11029 	struct adapter *sc = arg1;
11030 	struct sbuf *sb;
11031 	uint64_t *buf, *p;
11032 	int rc;
11033 	u_int i, inc;
11034 	void (*show_func)(struct sbuf *, uint64_t *, int);
11035 
11036 	rc = sysctl_wire_old_buffer(req, 0);
11037 	if (rc != 0)
11038 		return (rc);
11039 
11040 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11041 	if (sb == NULL)
11042 		return (ENOMEM);
11043 
11044 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
11045 
11046 	mtx_lock(&sc->reg_lock);
11047 	if (hw_off_limits(sc))
11048 		rc = ENXIO;
11049 	else {
11050 		t4_tp_read_la(sc, buf, NULL);
11051 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
11052 		case 2:
11053 			inc = 2;
11054 			show_func = tp_la_show2;
11055 			break;
11056 		case 3:
11057 			inc = 2;
11058 			show_func = tp_la_show3;
11059 			break;
11060 		default:
11061 			inc = 1;
11062 			show_func = tp_la_show;
11063 		}
11064 	}
11065 	mtx_unlock(&sc->reg_lock);
11066 	if (rc != 0)
11067 		goto done;
11068 
11069 	p = buf;
11070 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
11071 		(*show_func)(sb, p, i);
11072 	rc = sbuf_finish(sb);
11073 done:
11074 	sbuf_delete(sb);
11075 	free(buf, M_CXGBE);
11076 	return (rc);
11077 }
11078 
11079 static int
11080 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
11081 {
11082 	struct adapter *sc = arg1;
11083 	struct sbuf *sb;
11084 	int rc;
11085 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
11086 
11087 	rc = sysctl_wire_old_buffer(req, 0);
11088 	if (rc != 0)
11089 		return (rc);
11090 
11091 	mtx_lock(&sc->reg_lock);
11092 	if (hw_off_limits(sc))
11093 		rc = ENXIO;
11094 	else
11095 		t4_get_chan_txrate(sc, nrate, orate);
11096 	mtx_unlock(&sc->reg_lock);
11097 	if (rc != 0)
11098 		return (rc);
11099 
11100 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11101 	if (sb == NULL)
11102 		return (ENOMEM);
11103 
11104 	if (sc->chip_params->nchan > 2) {
11105 		sbuf_printf(sb, "              channel 0   channel 1"
11106 		    "   channel 2   channel 3\n");
11107 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
11108 		    nrate[0], nrate[1], nrate[2], nrate[3]);
11109 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
11110 		    orate[0], orate[1], orate[2], orate[3]);
11111 	} else {
11112 		sbuf_printf(sb, "              channel 0   channel 1\n");
11113 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
11114 		    nrate[0], nrate[1]);
11115 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
11116 		    orate[0], orate[1]);
11117 	}
11118 
11119 	rc = sbuf_finish(sb);
11120 	sbuf_delete(sb);
11121 
11122 	return (rc);
11123 }
11124 
11125 static int
11126 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
11127 {
11128 	struct adapter *sc = arg1;
11129 	struct sbuf *sb;
11130 	uint32_t *buf, *p;
11131 	int rc, i;
11132 
11133 	rc = sysctl_wire_old_buffer(req, 0);
11134 	if (rc != 0)
11135 		return (rc);
11136 
11137 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11138 	if (sb == NULL)
11139 		return (ENOMEM);
11140 
11141 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
11142 	    M_ZERO | M_WAITOK);
11143 
11144 	mtx_lock(&sc->reg_lock);
11145 	if (hw_off_limits(sc))
11146 		rc = ENXIO;
11147 	else
11148 		t4_ulprx_read_la(sc, buf);
11149 	mtx_unlock(&sc->reg_lock);
11150 	if (rc != 0)
11151 		goto done;
11152 
11153 	p = buf;
11154 	sbuf_printf(sb, "      Pcmd        Type   Message"
11155 	    "                Data");
11156 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
11157 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
11158 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
11159 	}
11160 	rc = sbuf_finish(sb);
11161 done:
11162 	sbuf_delete(sb);
11163 	free(buf, M_CXGBE);
11164 	return (rc);
11165 }
11166 
11167 static int
11168 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
11169 {
11170 	struct adapter *sc = arg1;
11171 	struct sbuf *sb;
11172 	int rc;
11173 	uint32_t cfg, s1, s2;
11174 
11175 	MPASS(chip_id(sc) >= CHELSIO_T5);
11176 
11177 	rc = sysctl_wire_old_buffer(req, 0);
11178 	if (rc != 0)
11179 		return (rc);
11180 
11181 	mtx_lock(&sc->reg_lock);
11182 	if (hw_off_limits(sc))
11183 		rc = ENXIO;
11184 	else {
11185 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
11186 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
11187 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
11188 	}
11189 	mtx_unlock(&sc->reg_lock);
11190 	if (rc != 0)
11191 		return (rc);
11192 
11193 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11194 	if (sb == NULL)
11195 		return (ENOMEM);
11196 
11197 	if (G_STATSOURCE_T5(cfg) == 7) {
11198 		int mode;
11199 
11200 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
11201 		if (mode == 0)
11202 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
11203 		else if (mode == 1)
11204 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
11205 		else
11206 			sbuf_printf(sb, "unknown mode %d", mode);
11207 	}
11208 	rc = sbuf_finish(sb);
11209 	sbuf_delete(sb);
11210 
11211 	return (rc);
11212 }
11213 
11214 static int
11215 sysctl_cpus(SYSCTL_HANDLER_ARGS)
11216 {
11217 	struct adapter *sc = arg1;
11218 	enum cpu_sets op = arg2;
11219 	cpuset_t cpuset;
11220 	struct sbuf *sb;
11221 	int i, rc;
11222 
11223 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
11224 
11225 	CPU_ZERO(&cpuset);
11226 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
11227 	if (rc != 0)
11228 		return (rc);
11229 
11230 	rc = sysctl_wire_old_buffer(req, 0);
11231 	if (rc != 0)
11232 		return (rc);
11233 
11234 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11235 	if (sb == NULL)
11236 		return (ENOMEM);
11237 
11238 	CPU_FOREACH(i)
11239 		sbuf_printf(sb, "%d ", i);
11240 	rc = sbuf_finish(sb);
11241 	sbuf_delete(sb);
11242 
11243 	return (rc);
11244 }
11245 
11246 static int
11247 sysctl_reset(SYSCTL_HANDLER_ARGS)
11248 {
11249 	struct adapter *sc = arg1;
11250 	u_int val;
11251 	int rc;
11252 
11253 	val = atomic_load_int(&sc->num_resets);
11254 	rc = sysctl_handle_int(oidp, &val, 0, req);
11255 	if (rc != 0 || req->newptr == NULL)
11256 		return (rc);
11257 
11258 	if (val == 0) {
11259 		/* Zero out the counter that tracks reset. */
11260 		atomic_store_int(&sc->num_resets, 0);
11261 		return (0);
11262 	}
11263 
11264 	if (val != 1)
11265 		return (EINVAL);	/* 0 or 1 are the only legal values */
11266 
11267 	if (hw_off_limits(sc))		/* harmless race */
11268 		return (EALREADY);
11269 
11270 	taskqueue_enqueue(reset_tq, &sc->reset_task);
11271 	return (0);
11272 }
11273 
11274 #ifdef TCP_OFFLOAD
11275 static int
11276 sysctl_tls(SYSCTL_HANDLER_ARGS)
11277 {
11278 	struct adapter *sc = arg1;
11279 	int i, j, v, rc;
11280 	struct vi_info *vi;
11281 
11282 	v = sc->tt.tls;
11283 	rc = sysctl_handle_int(oidp, &v, 0, req);
11284 	if (rc != 0 || req->newptr == NULL)
11285 		return (rc);
11286 
11287 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11288 		return (ENOTSUP);
11289 
11290 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11291 	if (rc)
11292 		return (rc);
11293 	if (hw_off_limits(sc))
11294 		rc = ENXIO;
11295 	else {
11296 		sc->tt.tls = !!v;
11297 		for_each_port(sc, i) {
11298 			for_each_vi(sc->port[i], j, vi) {
11299 				if (vi->flags & VI_INIT_DONE)
11300 					t4_update_fl_bufsize(vi->ifp);
11301 			}
11302 		}
11303 	}
11304 	end_synchronized_op(sc, 0);
11305 
11306 	return (rc);
11307 
11308 }
11309 
11310 static int
11311 sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS)
11312 {
11313 	struct adapter *sc = arg1;
11314 	int *old_ports, *new_ports;
11315 	int i, new_count, rc;
11316 
11317 	if (req->newptr == NULL && req->oldptr == NULL)
11318 		return (SYSCTL_OUT(req, NULL, imax(sc->tt.num_tls_rx_ports, 1) *
11319 		    sizeof(sc->tt.tls_rx_ports[0])));
11320 
11321 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tlsrx");
11322 	if (rc)
11323 		return (rc);
11324 
11325 	if (hw_off_limits(sc)) {
11326 		rc = ENXIO;
11327 		goto done;
11328 	}
11329 
11330 	if (sc->tt.num_tls_rx_ports == 0) {
11331 		i = -1;
11332 		rc = SYSCTL_OUT(req, &i, sizeof(i));
11333 	} else
11334 		rc = SYSCTL_OUT(req, sc->tt.tls_rx_ports,
11335 		    sc->tt.num_tls_rx_ports * sizeof(sc->tt.tls_rx_ports[0]));
11336 	if (rc == 0 && req->newptr != NULL) {
11337 		new_count = req->newlen / sizeof(new_ports[0]);
11338 		new_ports = malloc(new_count * sizeof(new_ports[0]), M_CXGBE,
11339 		    M_WAITOK);
11340 		rc = SYSCTL_IN(req, new_ports, new_count *
11341 		    sizeof(new_ports[0]));
11342 		if (rc)
11343 			goto err;
11344 
11345 		/* Allow setting to a single '-1' to clear the list. */
11346 		if (new_count == 1 && new_ports[0] == -1) {
11347 			ADAPTER_LOCK(sc);
11348 			old_ports = sc->tt.tls_rx_ports;
11349 			sc->tt.tls_rx_ports = NULL;
11350 			sc->tt.num_tls_rx_ports = 0;
11351 			ADAPTER_UNLOCK(sc);
11352 			free(old_ports, M_CXGBE);
11353 		} else {
11354 			for (i = 0; i < new_count; i++) {
11355 				if (new_ports[i] < 1 ||
11356 				    new_ports[i] > IPPORT_MAX) {
11357 					rc = EINVAL;
11358 					goto err;
11359 				}
11360 			}
11361 
11362 			ADAPTER_LOCK(sc);
11363 			old_ports = sc->tt.tls_rx_ports;
11364 			sc->tt.tls_rx_ports = new_ports;
11365 			sc->tt.num_tls_rx_ports = new_count;
11366 			ADAPTER_UNLOCK(sc);
11367 			free(old_ports, M_CXGBE);
11368 			new_ports = NULL;
11369 		}
11370 	err:
11371 		free(new_ports, M_CXGBE);
11372 	}
11373 done:
11374 	end_synchronized_op(sc, 0);
11375 	return (rc);
11376 }
11377 
11378 static int
11379 sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS)
11380 {
11381 	struct adapter *sc = arg1;
11382 	int v, rc;
11383 
11384 	v = sc->tt.tls_rx_timeout;
11385 	rc = sysctl_handle_int(oidp, &v, 0, req);
11386 	if (rc != 0 || req->newptr == NULL)
11387 		return (rc);
11388 
11389 	if (v < 0)
11390 		return (EINVAL);
11391 
11392 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11393 		return (ENOTSUP);
11394 
11395 	sc->tt.tls_rx_timeout = v;
11396 
11397 	return (0);
11398 
11399 }
11400 
11401 static void
11402 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11403 {
11404 	u_int rem = val % factor;
11405 
11406 	if (rem == 0)
11407 		snprintf(buf, len, "%u", val / factor);
11408 	else {
11409 		while (rem % 10 == 0)
11410 			rem /= 10;
11411 		snprintf(buf, len, "%u.%u", val / factor, rem);
11412 	}
11413 }
11414 
11415 static int
11416 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11417 {
11418 	struct adapter *sc = arg1;
11419 	char buf[16];
11420 	u_int res, re;
11421 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11422 
11423 	mtx_lock(&sc->reg_lock);
11424 	if (hw_off_limits(sc))
11425 		res = (u_int)-1;
11426 	else
11427 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11428 	mtx_unlock(&sc->reg_lock);
11429 	if (res == (u_int)-1)
11430 		return (ENXIO);
11431 
11432 	switch (arg2) {
11433 	case 0:
11434 		/* timer_tick */
11435 		re = G_TIMERRESOLUTION(res);
11436 		break;
11437 	case 1:
11438 		/* TCP timestamp tick */
11439 		re = G_TIMESTAMPRESOLUTION(res);
11440 		break;
11441 	case 2:
11442 		/* DACK tick */
11443 		re = G_DELAYEDACKRESOLUTION(res);
11444 		break;
11445 	default:
11446 		return (EDOOFUS);
11447 	}
11448 
11449 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11450 
11451 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11452 }
11453 
11454 static int
11455 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11456 {
11457 	struct adapter *sc = arg1;
11458 	int rc;
11459 	u_int dack_tmr, dack_re, v;
11460 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11461 
11462 	mtx_lock(&sc->reg_lock);
11463 	if (hw_off_limits(sc))
11464 		rc = ENXIO;
11465 	else {
11466 		rc = 0;
11467 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11468 		    A_TP_TIMER_RESOLUTION));
11469 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11470 	}
11471 	mtx_unlock(&sc->reg_lock);
11472 	if (rc != 0)
11473 		return (rc);
11474 
11475 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11476 
11477 	return (sysctl_handle_int(oidp, &v, 0, req));
11478 }
11479 
11480 static int
11481 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11482 {
11483 	struct adapter *sc = arg1;
11484 	int rc, reg = arg2;
11485 	u_int tre;
11486 	u_long tp_tick_us, v;
11487 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11488 
11489 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11490 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11491 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11492 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11493 
11494 	mtx_lock(&sc->reg_lock);
11495 	if (hw_off_limits(sc))
11496 		rc = ENXIO;
11497 	else {
11498 		rc = 0;
11499 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11500 		tp_tick_us = (cclk_ps << tre) / 1000000;
11501 		if (reg == A_TP_INIT_SRTT)
11502 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11503 		else
11504 			v = tp_tick_us * t4_read_reg(sc, reg);
11505 	}
11506 	mtx_unlock(&sc->reg_lock);
11507 	if (rc != 0)
11508 		return (rc);
11509 	else
11510 		return (sysctl_handle_long(oidp, &v, 0, req));
11511 }
11512 
11513 /*
11514  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11515  * passed to this function.
11516  */
11517 static int
11518 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11519 {
11520 	struct adapter *sc = arg1;
11521 	int rc, idx = arg2;
11522 	u_int v;
11523 
11524 	MPASS(idx >= 0 && idx <= 24);
11525 
11526 	mtx_lock(&sc->reg_lock);
11527 	if (hw_off_limits(sc))
11528 		rc = ENXIO;
11529 	else {
11530 		rc = 0;
11531 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11532 	}
11533 	mtx_unlock(&sc->reg_lock);
11534 	if (rc != 0)
11535 		return (rc);
11536 	else
11537 		return (sysctl_handle_int(oidp, &v, 0, req));
11538 }
11539 
11540 static int
11541 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11542 {
11543 	struct adapter *sc = arg1;
11544 	int rc, idx = arg2;
11545 	u_int shift, v, r;
11546 
11547 	MPASS(idx >= 0 && idx < 16);
11548 
11549 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11550 	shift = (idx & 3) << 3;
11551 	mtx_lock(&sc->reg_lock);
11552 	if (hw_off_limits(sc))
11553 		rc = ENXIO;
11554 	else {
11555 		rc = 0;
11556 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11557 	}
11558 	mtx_unlock(&sc->reg_lock);
11559 	if (rc != 0)
11560 		return (rc);
11561 	else
11562 		return (sysctl_handle_int(oidp, &v, 0, req));
11563 }
11564 
11565 static int
11566 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11567 {
11568 	struct vi_info *vi = arg1;
11569 	struct adapter *sc = vi->adapter;
11570 	int idx, rc, i;
11571 	struct sge_ofld_rxq *ofld_rxq;
11572 	uint8_t v;
11573 
11574 	idx = vi->ofld_tmr_idx;
11575 
11576 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11577 	if (rc != 0 || req->newptr == NULL)
11578 		return (rc);
11579 
11580 	if (idx < 0 || idx >= SGE_NTIMERS)
11581 		return (EINVAL);
11582 
11583 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11584 	    "t4otmr");
11585 	if (rc)
11586 		return (rc);
11587 
11588 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11589 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11590 #ifdef atomic_store_rel_8
11591 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11592 #else
11593 		ofld_rxq->iq.intr_params = v;
11594 #endif
11595 	}
11596 	vi->ofld_tmr_idx = idx;
11597 
11598 	end_synchronized_op(sc, LOCK_HELD);
11599 	return (0);
11600 }
11601 
11602 static int
11603 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11604 {
11605 	struct vi_info *vi = arg1;
11606 	struct adapter *sc = vi->adapter;
11607 	int idx, rc;
11608 
11609 	idx = vi->ofld_pktc_idx;
11610 
11611 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11612 	if (rc != 0 || req->newptr == NULL)
11613 		return (rc);
11614 
11615 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11616 		return (EINVAL);
11617 
11618 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11619 	    "t4opktc");
11620 	if (rc)
11621 		return (rc);
11622 
11623 	if (vi->flags & VI_INIT_DONE)
11624 		rc = EBUSY; /* cannot be changed once the queues are created */
11625 	else
11626 		vi->ofld_pktc_idx = idx;
11627 
11628 	end_synchronized_op(sc, LOCK_HELD);
11629 	return (rc);
11630 }
11631 #endif
11632 
11633 static int
11634 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11635 {
11636 	int rc;
11637 
11638 	if (cntxt->cid > M_CTXTQID)
11639 		return (EINVAL);
11640 
11641 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11642 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11643 		return (EINVAL);
11644 
11645 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11646 	if (rc)
11647 		return (rc);
11648 
11649 	if (hw_off_limits(sc)) {
11650 		rc = ENXIO;
11651 		goto done;
11652 	}
11653 
11654 	if (sc->flags & FW_OK) {
11655 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11656 		    &cntxt->data[0]);
11657 		if (rc == 0)
11658 			goto done;
11659 	}
11660 
11661 	/*
11662 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11663 	 * the backdoor.
11664 	 */
11665 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11666 done:
11667 	end_synchronized_op(sc, 0);
11668 	return (rc);
11669 }
11670 
11671 static int
11672 load_fw(struct adapter *sc, struct t4_data *fw)
11673 {
11674 	int rc;
11675 	uint8_t *fw_data;
11676 
11677 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11678 	if (rc)
11679 		return (rc);
11680 
11681 	if (hw_off_limits(sc)) {
11682 		rc = ENXIO;
11683 		goto done;
11684 	}
11685 
11686 	/*
11687 	 * The firmware, with the sole exception of the memory parity error
11688 	 * handler, runs from memory and not flash.  It is almost always safe to
11689 	 * install a new firmware on a running system.  Just set bit 1 in
11690 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11691 	 */
11692 	if (sc->flags & FULL_INIT_DONE &&
11693 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11694 		rc = EBUSY;
11695 		goto done;
11696 	}
11697 
11698 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11699 
11700 	rc = copyin(fw->data, fw_data, fw->len);
11701 	if (rc == 0)
11702 		rc = -t4_load_fw(sc, fw_data, fw->len);
11703 
11704 	free(fw_data, M_CXGBE);
11705 done:
11706 	end_synchronized_op(sc, 0);
11707 	return (rc);
11708 }
11709 
11710 static int
11711 load_cfg(struct adapter *sc, struct t4_data *cfg)
11712 {
11713 	int rc;
11714 	uint8_t *cfg_data = NULL;
11715 
11716 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11717 	if (rc)
11718 		return (rc);
11719 
11720 	if (hw_off_limits(sc)) {
11721 		rc = ENXIO;
11722 		goto done;
11723 	}
11724 
11725 	if (cfg->len == 0) {
11726 		/* clear */
11727 		rc = -t4_load_cfg(sc, NULL, 0);
11728 		goto done;
11729 	}
11730 
11731 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11732 
11733 	rc = copyin(cfg->data, cfg_data, cfg->len);
11734 	if (rc == 0)
11735 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11736 
11737 	free(cfg_data, M_CXGBE);
11738 done:
11739 	end_synchronized_op(sc, 0);
11740 	return (rc);
11741 }
11742 
11743 static int
11744 load_boot(struct adapter *sc, struct t4_bootrom *br)
11745 {
11746 	int rc;
11747 	uint8_t *br_data = NULL;
11748 	u_int offset;
11749 
11750 	if (br->len > 1024 * 1024)
11751 		return (EFBIG);
11752 
11753 	if (br->pf_offset == 0) {
11754 		/* pfidx */
11755 		if (br->pfidx_addr > 7)
11756 			return (EINVAL);
11757 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11758 		    A_PCIE_PF_EXPROM_OFST)));
11759 	} else if (br->pf_offset == 1) {
11760 		/* offset */
11761 		offset = G_OFFSET(br->pfidx_addr);
11762 	} else {
11763 		return (EINVAL);
11764 	}
11765 
11766 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11767 	if (rc)
11768 		return (rc);
11769 
11770 	if (hw_off_limits(sc)) {
11771 		rc = ENXIO;
11772 		goto done;
11773 	}
11774 
11775 	if (br->len == 0) {
11776 		/* clear */
11777 		rc = -t4_load_boot(sc, NULL, offset, 0);
11778 		goto done;
11779 	}
11780 
11781 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11782 
11783 	rc = copyin(br->data, br_data, br->len);
11784 	if (rc == 0)
11785 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11786 
11787 	free(br_data, M_CXGBE);
11788 done:
11789 	end_synchronized_op(sc, 0);
11790 	return (rc);
11791 }
11792 
11793 static int
11794 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11795 {
11796 	int rc;
11797 	uint8_t *bc_data = NULL;
11798 
11799 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11800 	if (rc)
11801 		return (rc);
11802 
11803 	if (hw_off_limits(sc)) {
11804 		rc = ENXIO;
11805 		goto done;
11806 	}
11807 
11808 	if (bc->len == 0) {
11809 		/* clear */
11810 		rc = -t4_load_bootcfg(sc, NULL, 0);
11811 		goto done;
11812 	}
11813 
11814 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11815 
11816 	rc = copyin(bc->data, bc_data, bc->len);
11817 	if (rc == 0)
11818 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11819 
11820 	free(bc_data, M_CXGBE);
11821 done:
11822 	end_synchronized_op(sc, 0);
11823 	return (rc);
11824 }
11825 
11826 static int
11827 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11828 {
11829 	int rc;
11830 	struct cudbg_init *cudbg;
11831 	void *handle, *buf;
11832 
11833 	/* buf is large, don't block if no memory is available */
11834 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11835 	if (buf == NULL)
11836 		return (ENOMEM);
11837 
11838 	handle = cudbg_alloc_handle();
11839 	if (handle == NULL) {
11840 		rc = ENOMEM;
11841 		goto done;
11842 	}
11843 
11844 	cudbg = cudbg_get_init(handle);
11845 	cudbg->adap = sc;
11846 	cudbg->print = (cudbg_print_cb)printf;
11847 
11848 #ifndef notyet
11849 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11850 	    __func__, dump->wr_flash, dump->len, dump->data);
11851 #endif
11852 
11853 	if (dump->wr_flash)
11854 		cudbg->use_flash = 1;
11855 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11856 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11857 
11858 	rc = cudbg_collect(handle, buf, &dump->len);
11859 	if (rc != 0)
11860 		goto done;
11861 
11862 	rc = copyout(buf, dump->data, dump->len);
11863 done:
11864 	cudbg_free_handle(handle);
11865 	free(buf, M_CXGBE);
11866 	return (rc);
11867 }
11868 
11869 static void
11870 free_offload_policy(struct t4_offload_policy *op)
11871 {
11872 	struct offload_rule *r;
11873 	int i;
11874 
11875 	if (op == NULL)
11876 		return;
11877 
11878 	r = &op->rule[0];
11879 	for (i = 0; i < op->nrules; i++, r++) {
11880 		free(r->bpf_prog.bf_insns, M_CXGBE);
11881 	}
11882 	free(op->rule, M_CXGBE);
11883 	free(op, M_CXGBE);
11884 }
11885 
11886 static int
11887 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11888 {
11889 	int i, rc, len;
11890 	struct t4_offload_policy *op, *old;
11891 	struct bpf_program *bf;
11892 	const struct offload_settings *s;
11893 	struct offload_rule *r;
11894 	void *u;
11895 
11896 	if (!is_offload(sc))
11897 		return (ENODEV);
11898 
11899 	if (uop->nrules == 0) {
11900 		/* Delete installed policies. */
11901 		op = NULL;
11902 		goto set_policy;
11903 	} else if (uop->nrules > 256) { /* arbitrary */
11904 		return (E2BIG);
11905 	}
11906 
11907 	/* Copy userspace offload policy to kernel */
11908 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11909 	op->nrules = uop->nrules;
11910 	len = op->nrules * sizeof(struct offload_rule);
11911 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11912 	rc = copyin(uop->rule, op->rule, len);
11913 	if (rc) {
11914 		free(op->rule, M_CXGBE);
11915 		free(op, M_CXGBE);
11916 		return (rc);
11917 	}
11918 
11919 	r = &op->rule[0];
11920 	for (i = 0; i < op->nrules; i++, r++) {
11921 
11922 		/* Validate open_type */
11923 		if (r->open_type != OPEN_TYPE_LISTEN &&
11924 		    r->open_type != OPEN_TYPE_ACTIVE &&
11925 		    r->open_type != OPEN_TYPE_PASSIVE &&
11926 		    r->open_type != OPEN_TYPE_DONTCARE) {
11927 error:
11928 			/*
11929 			 * Rules 0 to i have malloc'd filters that need to be
11930 			 * freed.  Rules i+1 to nrules have userspace pointers
11931 			 * and should be left alone.
11932 			 */
11933 			op->nrules = i;
11934 			free_offload_policy(op);
11935 			return (rc);
11936 		}
11937 
11938 		/* Validate settings */
11939 		s = &r->settings;
11940 		if ((s->offload != 0 && s->offload != 1) ||
11941 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11942 		    s->sched_class < -1 ||
11943 		    s->sched_class >= sc->params.nsched_cls) {
11944 			rc = EINVAL;
11945 			goto error;
11946 		}
11947 
11948 		bf = &r->bpf_prog;
11949 		u = bf->bf_insns;	/* userspace ptr */
11950 		bf->bf_insns = NULL;
11951 		if (bf->bf_len == 0) {
11952 			/* legal, matches everything */
11953 			continue;
11954 		}
11955 		len = bf->bf_len * sizeof(*bf->bf_insns);
11956 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11957 		rc = copyin(u, bf->bf_insns, len);
11958 		if (rc != 0)
11959 			goto error;
11960 
11961 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11962 			rc = EINVAL;
11963 			goto error;
11964 		}
11965 	}
11966 set_policy:
11967 	rw_wlock(&sc->policy_lock);
11968 	old = sc->policy;
11969 	sc->policy = op;
11970 	rw_wunlock(&sc->policy_lock);
11971 	free_offload_policy(old);
11972 
11973 	return (0);
11974 }
11975 
11976 #define MAX_READ_BUF_SIZE (128 * 1024)
11977 static int
11978 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11979 {
11980 	uint32_t addr, remaining, n;
11981 	uint32_t *buf;
11982 	int rc;
11983 	uint8_t *dst;
11984 
11985 	mtx_lock(&sc->reg_lock);
11986 	if (hw_off_limits(sc))
11987 		rc = ENXIO;
11988 	else
11989 		rc = validate_mem_range(sc, mr->addr, mr->len);
11990 	mtx_unlock(&sc->reg_lock);
11991 	if (rc != 0)
11992 		return (rc);
11993 
11994 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11995 	addr = mr->addr;
11996 	remaining = mr->len;
11997 	dst = (void *)mr->data;
11998 
11999 	while (remaining) {
12000 		n = min(remaining, MAX_READ_BUF_SIZE);
12001 		mtx_lock(&sc->reg_lock);
12002 		if (hw_off_limits(sc))
12003 			rc = ENXIO;
12004 		else
12005 			read_via_memwin(sc, 2, addr, buf, n);
12006 		mtx_unlock(&sc->reg_lock);
12007 		if (rc != 0)
12008 			break;
12009 
12010 		rc = copyout(buf, dst, n);
12011 		if (rc != 0)
12012 			break;
12013 
12014 		dst += n;
12015 		remaining -= n;
12016 		addr += n;
12017 	}
12018 
12019 	free(buf, M_CXGBE);
12020 	return (rc);
12021 }
12022 #undef MAX_READ_BUF_SIZE
12023 
12024 static int
12025 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
12026 {
12027 	int rc;
12028 
12029 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
12030 		return (EINVAL);
12031 
12032 	if (i2cd->len > sizeof(i2cd->data))
12033 		return (EFBIG);
12034 
12035 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
12036 	if (rc)
12037 		return (rc);
12038 	if (hw_off_limits(sc))
12039 		rc = ENXIO;
12040 	else
12041 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
12042 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
12043 	end_synchronized_op(sc, 0);
12044 
12045 	return (rc);
12046 }
12047 
12048 static int
12049 clear_stats(struct adapter *sc, u_int port_id)
12050 {
12051 	int i, v, chan_map;
12052 	struct port_info *pi;
12053 	struct vi_info *vi;
12054 	struct sge_rxq *rxq;
12055 	struct sge_txq *txq;
12056 	struct sge_wrq *wrq;
12057 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12058 	struct sge_ofld_txq *ofld_txq;
12059 #endif
12060 #ifdef TCP_OFFLOAD
12061 	struct sge_ofld_rxq *ofld_rxq;
12062 #endif
12063 
12064 	if (port_id >= sc->params.nports)
12065 		return (EINVAL);
12066 	pi = sc->port[port_id];
12067 	if (pi == NULL)
12068 		return (EIO);
12069 
12070 	mtx_lock(&sc->reg_lock);
12071 	if (!hw_off_limits(sc)) {
12072 		/* MAC stats */
12073 		t4_clr_port_stats(sc, pi->tx_chan);
12074 		if (is_t6(sc)) {
12075 			if (pi->fcs_reg != -1)
12076 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12077 			else
12078 				pi->stats.rx_fcs_err = 0;
12079 		}
12080 		for_each_vi(pi, v, vi) {
12081 			if (vi->flags & VI_INIT_DONE)
12082 				t4_clr_vi_stats(sc, vi->vin);
12083 		}
12084 		chan_map = pi->rx_e_chan_map;
12085 		v = 0;	/* reuse */
12086 		while (chan_map) {
12087 			i = ffs(chan_map) - 1;
12088 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
12089 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
12090 			chan_map &= ~(1 << i);
12091 		}
12092 	}
12093 	mtx_unlock(&sc->reg_lock);
12094 	pi->tx_parse_error = 0;
12095 	pi->tnl_cong_drops = 0;
12096 
12097 	/*
12098 	 * Since this command accepts a port, clear stats for
12099 	 * all VIs on this port.
12100 	 */
12101 	for_each_vi(pi, v, vi) {
12102 		if (vi->flags & VI_INIT_DONE) {
12103 
12104 			for_each_rxq(vi, i, rxq) {
12105 #if defined(INET) || defined(INET6)
12106 				rxq->lro.lro_queued = 0;
12107 				rxq->lro.lro_flushed = 0;
12108 #endif
12109 				rxq->rxcsum = 0;
12110 				rxq->vlan_extraction = 0;
12111 				rxq->vxlan_rxcsum = 0;
12112 
12113 				rxq->fl.cl_allocated = 0;
12114 				rxq->fl.cl_recycled = 0;
12115 				rxq->fl.cl_fast_recycled = 0;
12116 			}
12117 
12118 			for_each_txq(vi, i, txq) {
12119 				txq->txcsum = 0;
12120 				txq->tso_wrs = 0;
12121 				txq->vlan_insertion = 0;
12122 				txq->imm_wrs = 0;
12123 				txq->sgl_wrs = 0;
12124 				txq->txpkt_wrs = 0;
12125 				txq->txpkts0_wrs = 0;
12126 				txq->txpkts1_wrs = 0;
12127 				txq->txpkts0_pkts = 0;
12128 				txq->txpkts1_pkts = 0;
12129 				txq->txpkts_flush = 0;
12130 				txq->raw_wrs = 0;
12131 				txq->vxlan_tso_wrs = 0;
12132 				txq->vxlan_txcsum = 0;
12133 				txq->kern_tls_records = 0;
12134 				txq->kern_tls_short = 0;
12135 				txq->kern_tls_partial = 0;
12136 				txq->kern_tls_full = 0;
12137 				txq->kern_tls_octets = 0;
12138 				txq->kern_tls_waste = 0;
12139 				txq->kern_tls_options = 0;
12140 				txq->kern_tls_header = 0;
12141 				txq->kern_tls_fin = 0;
12142 				txq->kern_tls_fin_short = 0;
12143 				txq->kern_tls_cbc = 0;
12144 				txq->kern_tls_gcm = 0;
12145 				mp_ring_reset_stats(txq->r);
12146 			}
12147 
12148 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12149 			for_each_ofld_txq(vi, i, ofld_txq) {
12150 				ofld_txq->wrq.tx_wrs_direct = 0;
12151 				ofld_txq->wrq.tx_wrs_copied = 0;
12152 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
12153 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
12154 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
12155 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
12156 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
12157 			}
12158 #endif
12159 #ifdef TCP_OFFLOAD
12160 			for_each_ofld_rxq(vi, i, ofld_rxq) {
12161 				ofld_rxq->fl.cl_allocated = 0;
12162 				ofld_rxq->fl.cl_recycled = 0;
12163 				ofld_rxq->fl.cl_fast_recycled = 0;
12164 				counter_u64_zero(
12165 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
12166 				counter_u64_zero(
12167 				    ofld_rxq->rx_iscsi_ddp_setup_error);
12168 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
12169 				ofld_rxq->rx_iscsi_ddp_octets = 0;
12170 				ofld_rxq->rx_iscsi_fl_pdus = 0;
12171 				ofld_rxq->rx_iscsi_fl_octets = 0;
12172 				ofld_rxq->rx_toe_tls_records = 0;
12173 				ofld_rxq->rx_toe_tls_octets = 0;
12174 			}
12175 #endif
12176 
12177 			if (IS_MAIN_VI(vi)) {
12178 				wrq = &sc->sge.ctrlq[pi->port_id];
12179 				wrq->tx_wrs_direct = 0;
12180 				wrq->tx_wrs_copied = 0;
12181 			}
12182 		}
12183 	}
12184 
12185 	return (0);
12186 }
12187 
12188 static int
12189 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12190 {
12191 #ifdef INET6
12192 	struct in6_addr in6;
12193 
12194 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12195 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
12196 		return (0);
12197 	else
12198 		return (EIO);
12199 #else
12200 	return (ENOTSUP);
12201 #endif
12202 }
12203 
12204 static int
12205 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12206 {
12207 #ifdef INET6
12208 	struct in6_addr in6;
12209 
12210 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12211 	return (t4_release_clip_addr(sc, &in6));
12212 #else
12213 	return (ENOTSUP);
12214 #endif
12215 }
12216 
12217 int
12218 t4_os_find_pci_capability(struct adapter *sc, int cap)
12219 {
12220 	int i;
12221 
12222 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
12223 }
12224 
12225 int
12226 t4_os_pci_save_state(struct adapter *sc)
12227 {
12228 	device_t dev;
12229 	struct pci_devinfo *dinfo;
12230 
12231 	dev = sc->dev;
12232 	dinfo = device_get_ivars(dev);
12233 
12234 	pci_cfg_save(dev, dinfo, 0);
12235 	return (0);
12236 }
12237 
12238 int
12239 t4_os_pci_restore_state(struct adapter *sc)
12240 {
12241 	device_t dev;
12242 	struct pci_devinfo *dinfo;
12243 
12244 	dev = sc->dev;
12245 	dinfo = device_get_ivars(dev);
12246 
12247 	pci_cfg_restore(dev, dinfo);
12248 	return (0);
12249 }
12250 
12251 void
12252 t4_os_portmod_changed(struct port_info *pi)
12253 {
12254 	struct adapter *sc = pi->adapter;
12255 	struct vi_info *vi;
12256 	struct ifnet *ifp;
12257 	static const char *mod_str[] = {
12258 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
12259 	};
12260 
12261 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
12262 	    ("%s: port_type %u", __func__, pi->port_type));
12263 
12264 	vi = &pi->vi[0];
12265 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12266 		PORT_LOCK(pi);
12267 		build_medialist(pi);
12268 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12269 			fixup_link_config(pi);
12270 			apply_link_config(pi);
12271 		}
12272 		PORT_UNLOCK(pi);
12273 		end_synchronized_op(sc, LOCK_HELD);
12274 	}
12275 
12276 	ifp = vi->ifp;
12277 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12278 		if_printf(ifp, "transceiver unplugged.\n");
12279 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12280 		if_printf(ifp, "unknown transceiver inserted.\n");
12281 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12282 		if_printf(ifp, "unsupported transceiver inserted.\n");
12283 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12284 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12285 		    port_top_speed(pi), mod_str[pi->mod_type]);
12286 	} else {
12287 		if_printf(ifp, "transceiver (type %d) inserted.\n",
12288 		    pi->mod_type);
12289 	}
12290 }
12291 
12292 void
12293 t4_os_link_changed(struct port_info *pi)
12294 {
12295 	struct vi_info *vi;
12296 	struct ifnet *ifp;
12297 	struct link_config *lc = &pi->link_cfg;
12298 	struct adapter *sc = pi->adapter;
12299 	int v;
12300 
12301 	PORT_LOCK_ASSERT_OWNED(pi);
12302 
12303 	if (is_t6(sc)) {
12304 		if (lc->link_ok) {
12305 			if (lc->speed > 25000 ||
12306 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12307 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12308 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12309 			} else {
12310 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12311 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12312 			}
12313 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12314 			pi->stats.rx_fcs_err = 0;
12315 		} else {
12316 			pi->fcs_reg = -1;
12317 		}
12318 	} else {
12319 		MPASS(pi->fcs_reg != -1);
12320 		MPASS(pi->fcs_base == 0);
12321 	}
12322 
12323 	for_each_vi(pi, v, vi) {
12324 		ifp = vi->ifp;
12325 		if (ifp == NULL)
12326 			continue;
12327 
12328 		if (lc->link_ok) {
12329 			ifp->if_baudrate = IF_Mbps(lc->speed);
12330 			if_link_state_change(ifp, LINK_STATE_UP);
12331 		} else {
12332 			if_link_state_change(ifp, LINK_STATE_DOWN);
12333 		}
12334 	}
12335 }
12336 
12337 void
12338 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12339 {
12340 	struct adapter *sc;
12341 
12342 	sx_slock(&t4_list_lock);
12343 	SLIST_FOREACH(sc, &t4_list, link) {
12344 		/*
12345 		 * func should not make any assumptions about what state sc is
12346 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12347 		 */
12348 		func(sc, arg);
12349 	}
12350 	sx_sunlock(&t4_list_lock);
12351 }
12352 
12353 static int
12354 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12355     struct thread *td)
12356 {
12357 	int rc;
12358 	struct adapter *sc = dev->si_drv1;
12359 
12360 	rc = priv_check(td, PRIV_DRIVER);
12361 	if (rc != 0)
12362 		return (rc);
12363 
12364 	switch (cmd) {
12365 	case CHELSIO_T4_GETREG: {
12366 		struct t4_reg *edata = (struct t4_reg *)data;
12367 
12368 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12369 			return (EFAULT);
12370 
12371 		mtx_lock(&sc->reg_lock);
12372 		if (hw_off_limits(sc))
12373 			rc = ENXIO;
12374 		else if (edata->size == 4)
12375 			edata->val = t4_read_reg(sc, edata->addr);
12376 		else if (edata->size == 8)
12377 			edata->val = t4_read_reg64(sc, edata->addr);
12378 		else
12379 			rc = EINVAL;
12380 		mtx_unlock(&sc->reg_lock);
12381 
12382 		break;
12383 	}
12384 	case CHELSIO_T4_SETREG: {
12385 		struct t4_reg *edata = (struct t4_reg *)data;
12386 
12387 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12388 			return (EFAULT);
12389 
12390 		mtx_lock(&sc->reg_lock);
12391 		if (hw_off_limits(sc))
12392 			rc = ENXIO;
12393 		else if (edata->size == 4) {
12394 			if (edata->val & 0xffffffff00000000)
12395 				rc = EINVAL;
12396 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12397 		} else if (edata->size == 8)
12398 			t4_write_reg64(sc, edata->addr, edata->val);
12399 		else
12400 			rc = EINVAL;
12401 		mtx_unlock(&sc->reg_lock);
12402 
12403 		break;
12404 	}
12405 	case CHELSIO_T4_REGDUMP: {
12406 		struct t4_regdump *regs = (struct t4_regdump *)data;
12407 		int reglen = t4_get_regs_len(sc);
12408 		uint8_t *buf;
12409 
12410 		if (regs->len < reglen) {
12411 			regs->len = reglen; /* hint to the caller */
12412 			return (ENOBUFS);
12413 		}
12414 
12415 		regs->len = reglen;
12416 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12417 		mtx_lock(&sc->reg_lock);
12418 		if (hw_off_limits(sc))
12419 			rc = ENXIO;
12420 		else
12421 			get_regs(sc, regs, buf);
12422 		mtx_unlock(&sc->reg_lock);
12423 		if (rc == 0)
12424 			rc = copyout(buf, regs->data, reglen);
12425 		free(buf, M_CXGBE);
12426 		break;
12427 	}
12428 	case CHELSIO_T4_GET_FILTER_MODE:
12429 		rc = get_filter_mode(sc, (uint32_t *)data);
12430 		break;
12431 	case CHELSIO_T4_SET_FILTER_MODE:
12432 		rc = set_filter_mode(sc, *(uint32_t *)data);
12433 		break;
12434 	case CHELSIO_T4_SET_FILTER_MASK:
12435 		rc = set_filter_mask(sc, *(uint32_t *)data);
12436 		break;
12437 	case CHELSIO_T4_GET_FILTER:
12438 		rc = get_filter(sc, (struct t4_filter *)data);
12439 		break;
12440 	case CHELSIO_T4_SET_FILTER:
12441 		rc = set_filter(sc, (struct t4_filter *)data);
12442 		break;
12443 	case CHELSIO_T4_DEL_FILTER:
12444 		rc = del_filter(sc, (struct t4_filter *)data);
12445 		break;
12446 	case CHELSIO_T4_GET_SGE_CONTEXT:
12447 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12448 		break;
12449 	case CHELSIO_T4_LOAD_FW:
12450 		rc = load_fw(sc, (struct t4_data *)data);
12451 		break;
12452 	case CHELSIO_T4_GET_MEM:
12453 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12454 		break;
12455 	case CHELSIO_T4_GET_I2C:
12456 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12457 		break;
12458 	case CHELSIO_T4_CLEAR_STATS:
12459 		rc = clear_stats(sc, *(uint32_t *)data);
12460 		break;
12461 	case CHELSIO_T4_SCHED_CLASS:
12462 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12463 		break;
12464 	case CHELSIO_T4_SCHED_QUEUE:
12465 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12466 		break;
12467 	case CHELSIO_T4_GET_TRACER:
12468 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12469 		break;
12470 	case CHELSIO_T4_SET_TRACER:
12471 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12472 		break;
12473 	case CHELSIO_T4_LOAD_CFG:
12474 		rc = load_cfg(sc, (struct t4_data *)data);
12475 		break;
12476 	case CHELSIO_T4_LOAD_BOOT:
12477 		rc = load_boot(sc, (struct t4_bootrom *)data);
12478 		break;
12479 	case CHELSIO_T4_LOAD_BOOTCFG:
12480 		rc = load_bootcfg(sc, (struct t4_data *)data);
12481 		break;
12482 	case CHELSIO_T4_CUDBG_DUMP:
12483 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12484 		break;
12485 	case CHELSIO_T4_SET_OFLD_POLICY:
12486 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12487 		break;
12488 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12489 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12490 		break;
12491 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12492 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12493 		break;
12494 	default:
12495 		rc = ENOTTY;
12496 	}
12497 
12498 	return (rc);
12499 }
12500 
12501 #ifdef TCP_OFFLOAD
12502 static int
12503 toe_capability(struct vi_info *vi, bool enable)
12504 {
12505 	int rc;
12506 	struct port_info *pi = vi->pi;
12507 	struct adapter *sc = pi->adapter;
12508 
12509 	ASSERT_SYNCHRONIZED_OP(sc);
12510 
12511 	if (!is_offload(sc))
12512 		return (ENODEV);
12513 	if (hw_off_limits(sc))
12514 		return (ENXIO);
12515 
12516 	if (enable) {
12517 #ifdef KERN_TLS
12518 		if (sc->flags & KERN_TLS_ON && is_t6(sc)) {
12519 			int i, j, n;
12520 			struct port_info *p;
12521 			struct vi_info *v;
12522 
12523 			/*
12524 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12525 			 * on any ifnet.
12526 			 */
12527 			n = 0;
12528 			for_each_port(sc, i) {
12529 				p = sc->port[i];
12530 				for_each_vi(p, j, v) {
12531 					if (v->ifp->if_capenable & IFCAP_TXTLS) {
12532 						CH_WARN(sc,
12533 						    "%s has NIC TLS enabled.\n",
12534 						    device_get_nameunit(v->dev));
12535 						n++;
12536 					}
12537 				}
12538 			}
12539 			if (n > 0) {
12540 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12541 				    "associated with this adapter before "
12542 				    "trying to enable TOE.\n");
12543 				return (EAGAIN);
12544 			}
12545 			rc = t6_config_kern_tls(sc, false);
12546 			if (rc)
12547 				return (rc);
12548 		}
12549 #endif
12550 		if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
12551 			/* TOE is already enabled. */
12552 			return (0);
12553 		}
12554 
12555 		/*
12556 		 * We need the port's queues around so that we're able to send
12557 		 * and receive CPLs to/from the TOE even if the ifnet for this
12558 		 * port has never been UP'd administratively.
12559 		 */
12560 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12561 			return (rc);
12562 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12563 		    ((rc = vi_init(&pi->vi[0])) != 0))
12564 			return (rc);
12565 
12566 		if (isset(&sc->offload_map, pi->port_id)) {
12567 			/* TOE is enabled on another VI of this port. */
12568 			pi->uld_vis++;
12569 			return (0);
12570 		}
12571 
12572 		if (!uld_active(sc, ULD_TOM)) {
12573 			rc = t4_activate_uld(sc, ULD_TOM);
12574 			if (rc == EAGAIN) {
12575 				log(LOG_WARNING,
12576 				    "You must kldload t4_tom.ko before trying "
12577 				    "to enable TOE on a cxgbe interface.\n");
12578 			}
12579 			if (rc != 0)
12580 				return (rc);
12581 			KASSERT(sc->tom_softc != NULL,
12582 			    ("%s: TOM activated but softc NULL", __func__));
12583 			KASSERT(uld_active(sc, ULD_TOM),
12584 			    ("%s: TOM activated but flag not set", __func__));
12585 		}
12586 
12587 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12588 		if (!uld_active(sc, ULD_IWARP))
12589 			(void) t4_activate_uld(sc, ULD_IWARP);
12590 		if (!uld_active(sc, ULD_ISCSI))
12591 			(void) t4_activate_uld(sc, ULD_ISCSI);
12592 
12593 		pi->uld_vis++;
12594 		setbit(&sc->offload_map, pi->port_id);
12595 	} else {
12596 		pi->uld_vis--;
12597 
12598 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12599 			return (0);
12600 
12601 		KASSERT(uld_active(sc, ULD_TOM),
12602 		    ("%s: TOM never initialized?", __func__));
12603 		clrbit(&sc->offload_map, pi->port_id);
12604 	}
12605 
12606 	return (0);
12607 }
12608 
12609 /*
12610  * Add an upper layer driver to the global list.
12611  */
12612 int
12613 t4_register_uld(struct uld_info *ui)
12614 {
12615 	int rc = 0;
12616 	struct uld_info *u;
12617 
12618 	sx_xlock(&t4_uld_list_lock);
12619 	SLIST_FOREACH(u, &t4_uld_list, link) {
12620 	    if (u->uld_id == ui->uld_id) {
12621 		    rc = EEXIST;
12622 		    goto done;
12623 	    }
12624 	}
12625 
12626 	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
12627 	ui->refcount = 0;
12628 done:
12629 	sx_xunlock(&t4_uld_list_lock);
12630 	return (rc);
12631 }
12632 
12633 int
12634 t4_unregister_uld(struct uld_info *ui)
12635 {
12636 	int rc = EINVAL;
12637 	struct uld_info *u;
12638 
12639 	sx_xlock(&t4_uld_list_lock);
12640 
12641 	SLIST_FOREACH(u, &t4_uld_list, link) {
12642 	    if (u == ui) {
12643 		    if (ui->refcount > 0) {
12644 			    rc = EBUSY;
12645 			    goto done;
12646 		    }
12647 
12648 		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
12649 		    rc = 0;
12650 		    goto done;
12651 	    }
12652 	}
12653 done:
12654 	sx_xunlock(&t4_uld_list_lock);
12655 	return (rc);
12656 }
12657 
12658 int
12659 t4_activate_uld(struct adapter *sc, int id)
12660 {
12661 	int rc;
12662 	struct uld_info *ui;
12663 
12664 	ASSERT_SYNCHRONIZED_OP(sc);
12665 
12666 	if (id < 0 || id > ULD_MAX)
12667 		return (EINVAL);
12668 	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
12669 
12670 	sx_slock(&t4_uld_list_lock);
12671 
12672 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12673 		if (ui->uld_id == id) {
12674 			if (!(sc->flags & FULL_INIT_DONE)) {
12675 				rc = adapter_init(sc);
12676 				if (rc != 0)
12677 					break;
12678 			}
12679 
12680 			rc = ui->activate(sc);
12681 			if (rc == 0) {
12682 				setbit(&sc->active_ulds, id);
12683 				ui->refcount++;
12684 			}
12685 			break;
12686 		}
12687 	}
12688 
12689 	sx_sunlock(&t4_uld_list_lock);
12690 
12691 	return (rc);
12692 }
12693 
12694 int
12695 t4_deactivate_uld(struct adapter *sc, int id)
12696 {
12697 	int rc;
12698 	struct uld_info *ui;
12699 
12700 	ASSERT_SYNCHRONIZED_OP(sc);
12701 
12702 	if (id < 0 || id > ULD_MAX)
12703 		return (EINVAL);
12704 	rc = ENXIO;
12705 
12706 	sx_slock(&t4_uld_list_lock);
12707 
12708 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12709 		if (ui->uld_id == id) {
12710 			rc = ui->deactivate(sc);
12711 			if (rc == 0) {
12712 				clrbit(&sc->active_ulds, id);
12713 				ui->refcount--;
12714 			}
12715 			break;
12716 		}
12717 	}
12718 
12719 	sx_sunlock(&t4_uld_list_lock);
12720 
12721 	return (rc);
12722 }
12723 
12724 static int
12725 t4_deactivate_all_uld(struct adapter *sc)
12726 {
12727 	int rc;
12728 	struct uld_info *ui;
12729 
12730 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4detuld");
12731 	if (rc != 0)
12732 		return (ENXIO);
12733 
12734 	sx_slock(&t4_uld_list_lock);
12735 
12736 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12737 		if (isset(&sc->active_ulds, ui->uld_id)) {
12738 			rc = ui->deactivate(sc);
12739 			if (rc != 0)
12740 				break;
12741 			clrbit(&sc->active_ulds, ui->uld_id);
12742 			ui->refcount--;
12743 		}
12744 	}
12745 
12746 	sx_sunlock(&t4_uld_list_lock);
12747 	end_synchronized_op(sc, 0);
12748 
12749 	return (rc);
12750 }
12751 
12752 static void
12753 t4_async_event(struct adapter *sc)
12754 {
12755 	struct uld_info *ui;
12756 
12757 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
12758 		return;
12759 	sx_slock(&t4_uld_list_lock);
12760 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12761 		if (ui->uld_id == ULD_IWARP) {
12762 			ui->async_event(sc);
12763 			break;
12764 		}
12765 	}
12766 	sx_sunlock(&t4_uld_list_lock);
12767 	end_synchronized_op(sc, 0);
12768 }
12769 
12770 int
12771 uld_active(struct adapter *sc, int uld_id)
12772 {
12773 
12774 	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
12775 
12776 	return (isset(&sc->active_ulds, uld_id));
12777 }
12778 #endif
12779 
12780 #ifdef KERN_TLS
12781 static int
12782 ktls_capability(struct adapter *sc, bool enable)
12783 {
12784 	ASSERT_SYNCHRONIZED_OP(sc);
12785 
12786 	if (!is_ktls(sc))
12787 		return (ENODEV);
12788 	if (!is_t6(sc))
12789 		return (0);
12790 	if (hw_off_limits(sc))
12791 		return (ENXIO);
12792 
12793 	if (enable) {
12794 		if (sc->flags & KERN_TLS_ON)
12795 			return (0);	/* already on */
12796 		if (sc->offload_map != 0) {
12797 			CH_WARN(sc,
12798 			    "Disable TOE on all interfaces associated with "
12799 			    "this adapter before trying to enable NIC TLS.\n");
12800 			return (EAGAIN);
12801 		}
12802 		return (t6_config_kern_tls(sc, true));
12803 	} else {
12804 		/*
12805 		 * Nothing to do for disable.  If TOE is enabled sometime later
12806 		 * then toe_capability will reconfigure the hardware.
12807 		 */
12808 		return (0);
12809 	}
12810 }
12811 #endif
12812 
12813 /*
12814  * t  = ptr to tunable.
12815  * nc = number of CPUs.
12816  * c  = compiled in default for that tunable.
12817  */
12818 static void
12819 calculate_nqueues(int *t, int nc, const int c)
12820 {
12821 	int nq;
12822 
12823 	if (*t > 0)
12824 		return;
12825 	nq = *t < 0 ? -*t : c;
12826 	*t = min(nc, nq);
12827 }
12828 
12829 /*
12830  * Come up with reasonable defaults for some of the tunables, provided they're
12831  * not set by the user (in which case we'll use the values as is).
12832  */
12833 static void
12834 tweak_tunables(void)
12835 {
12836 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12837 
12838 	if (t4_ntxq < 1) {
12839 #ifdef RSS
12840 		t4_ntxq = rss_getnumbuckets();
12841 #else
12842 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12843 #endif
12844 	}
12845 
12846 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12847 
12848 	if (t4_nrxq < 1) {
12849 #ifdef RSS
12850 		t4_nrxq = rss_getnumbuckets();
12851 #else
12852 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12853 #endif
12854 	}
12855 
12856 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12857 
12858 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12859 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12860 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12861 #endif
12862 #ifdef TCP_OFFLOAD
12863 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12864 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12865 #endif
12866 
12867 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12868 	if (t4_toecaps_allowed == -1)
12869 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12870 #else
12871 	if (t4_toecaps_allowed == -1)
12872 		t4_toecaps_allowed = 0;
12873 #endif
12874 
12875 #ifdef TCP_OFFLOAD
12876 	if (t4_rdmacaps_allowed == -1) {
12877 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12878 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12879 	}
12880 
12881 	if (t4_iscsicaps_allowed == -1) {
12882 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12883 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12884 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12885 	}
12886 
12887 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12888 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12889 
12890 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12891 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12892 
12893 	if (t4_toe_tls_rx_timeout < 0)
12894 		t4_toe_tls_rx_timeout = 0;
12895 #else
12896 	if (t4_rdmacaps_allowed == -1)
12897 		t4_rdmacaps_allowed = 0;
12898 
12899 	if (t4_iscsicaps_allowed == -1)
12900 		t4_iscsicaps_allowed = 0;
12901 #endif
12902 
12903 #ifdef DEV_NETMAP
12904 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12905 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12906 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12907 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12908 #endif
12909 
12910 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12911 		t4_tmr_idx = TMR_IDX;
12912 
12913 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12914 		t4_pktc_idx = PKTC_IDX;
12915 
12916 	if (t4_qsize_txq < 128)
12917 		t4_qsize_txq = 128;
12918 
12919 	if (t4_qsize_rxq < 128)
12920 		t4_qsize_rxq = 128;
12921 	while (t4_qsize_rxq & 7)
12922 		t4_qsize_rxq++;
12923 
12924 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12925 
12926 	/*
12927 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12928 	 * VI for the port.  The rest are additional virtual interfaces on the
12929 	 * same physical port.  Note that the main VI does not have native
12930 	 * netmap support but the extra VIs do.
12931 	 *
12932 	 * Limit the number of VIs per port to the number of available
12933 	 * MAC addresses per port.
12934 	 */
12935 	if (t4_num_vis < 1)
12936 		t4_num_vis = 1;
12937 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12938 		t4_num_vis = nitems(vi_mac_funcs);
12939 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12940 	}
12941 
12942 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12943 		pcie_relaxed_ordering = 1;
12944 #if defined(__i386__) || defined(__amd64__)
12945 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12946 			pcie_relaxed_ordering = 0;
12947 #endif
12948 	}
12949 }
12950 
12951 #ifdef DDB
12952 static void
12953 t4_dump_tcb(struct adapter *sc, int tid)
12954 {
12955 	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
12956 
12957 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12958 	save = t4_read_reg(sc, reg);
12959 	base = sc->memwin[2].mw_base;
12960 
12961 	/* Dump TCB for the tid */
12962 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12963 	tcb_addr += tid * TCB_SIZE;
12964 
12965 	if (is_t4(sc)) {
12966 		pf = 0;
12967 		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
12968 	} else {
12969 		pf = V_PFNUM(sc->pf);
12970 		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
12971 	}
12972 	t4_write_reg(sc, reg, win_pos | pf);
12973 	t4_read_reg(sc, reg);
12974 
12975 	off = tcb_addr - win_pos;
12976 	for (i = 0; i < 4; i++) {
12977 		uint32_t buf[8];
12978 		for (j = 0; j < 8; j++, off += 4)
12979 			buf[j] = htonl(t4_read_reg(sc, base + off));
12980 
12981 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12982 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12983 		    buf[7]);
12984 	}
12985 
12986 	t4_write_reg(sc, reg, save);
12987 	t4_read_reg(sc, reg);
12988 }
12989 
12990 static void
12991 t4_dump_devlog(struct adapter *sc)
12992 {
12993 	struct devlog_params *dparams = &sc->params.devlog;
12994 	struct fw_devlog_e e;
12995 	int i, first, j, m, nentries, rc;
12996 	uint64_t ftstamp = UINT64_MAX;
12997 
12998 	if (dparams->start == 0) {
12999 		db_printf("devlog params not valid\n");
13000 		return;
13001 	}
13002 
13003 	nentries = dparams->size / sizeof(struct fw_devlog_e);
13004 	m = fwmtype_to_hwmtype(dparams->memtype);
13005 
13006 	/* Find the first entry. */
13007 	first = -1;
13008 	for (i = 0; i < nentries && !db_pager_quit; i++) {
13009 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
13010 		    sizeof(e), (void *)&e);
13011 		if (rc != 0)
13012 			break;
13013 
13014 		if (e.timestamp == 0)
13015 			break;
13016 
13017 		e.timestamp = be64toh(e.timestamp);
13018 		if (e.timestamp < ftstamp) {
13019 			ftstamp = e.timestamp;
13020 			first = i;
13021 		}
13022 	}
13023 
13024 	if (first == -1)
13025 		return;
13026 
13027 	i = first;
13028 	do {
13029 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
13030 		    sizeof(e), (void *)&e);
13031 		if (rc != 0)
13032 			return;
13033 
13034 		if (e.timestamp == 0)
13035 			return;
13036 
13037 		e.timestamp = be64toh(e.timestamp);
13038 		e.seqno = be32toh(e.seqno);
13039 		for (j = 0; j < 8; j++)
13040 			e.params[j] = be32toh(e.params[j]);
13041 
13042 		db_printf("%10d  %15ju  %8s  %8s  ",
13043 		    e.seqno, e.timestamp,
13044 		    (e.level < nitems(devlog_level_strings) ?
13045 			devlog_level_strings[e.level] : "UNKNOWN"),
13046 		    (e.facility < nitems(devlog_facility_strings) ?
13047 			devlog_facility_strings[e.facility] : "UNKNOWN"));
13048 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
13049 		    e.params[3], e.params[4], e.params[5], e.params[6],
13050 		    e.params[7]);
13051 
13052 		if (++i == nentries)
13053 			i = 0;
13054 	} while (i != first && !db_pager_quit);
13055 }
13056 
13057 static struct db_command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
13058 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
13059 
13060 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
13061 {
13062 	device_t dev;
13063 	int t;
13064 	bool valid;
13065 
13066 	valid = false;
13067 	t = db_read_token();
13068 	if (t == tIDENT) {
13069 		dev = device_lookup_by_name(db_tok_string);
13070 		valid = true;
13071 	}
13072 	db_skip_to_eol();
13073 	if (!valid) {
13074 		db_printf("usage: show t4 devlog <nexus>\n");
13075 		return;
13076 	}
13077 
13078 	if (dev == NULL) {
13079 		db_printf("device not found\n");
13080 		return;
13081 	}
13082 
13083 	t4_dump_devlog(device_get_softc(dev));
13084 }
13085 
13086 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
13087 {
13088 	device_t dev;
13089 	int radix, tid, t;
13090 	bool valid;
13091 
13092 	valid = false;
13093 	radix = db_radix;
13094 	db_radix = 10;
13095 	t = db_read_token();
13096 	if (t == tIDENT) {
13097 		dev = device_lookup_by_name(db_tok_string);
13098 		t = db_read_token();
13099 		if (t == tNUMBER) {
13100 			tid = db_tok_number;
13101 			valid = true;
13102 		}
13103 	}
13104 	db_radix = radix;
13105 	db_skip_to_eol();
13106 	if (!valid) {
13107 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
13108 		return;
13109 	}
13110 
13111 	if (dev == NULL) {
13112 		db_printf("device not found\n");
13113 		return;
13114 	}
13115 	if (tid < 0) {
13116 		db_printf("invalid tid\n");
13117 		return;
13118 	}
13119 
13120 	t4_dump_tcb(device_get_softc(dev), tid);
13121 }
13122 #endif
13123 
13124 static eventhandler_tag vxlan_start_evtag;
13125 static eventhandler_tag vxlan_stop_evtag;
13126 
13127 struct vxlan_evargs {
13128 	struct ifnet *ifp;
13129 	uint16_t port;
13130 };
13131 
13132 static void
13133 enable_vxlan_rx(struct adapter *sc)
13134 {
13135 	int i, rc;
13136 	struct port_info *pi;
13137 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
13138 
13139 	ASSERT_SYNCHRONIZED_OP(sc);
13140 
13141 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
13142 	    F_VXLAN_EN);
13143 	for_each_port(sc, i) {
13144 		pi = sc->port[i];
13145 		if (pi->vxlan_tcam_entry == true)
13146 			continue;
13147 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
13148 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
13149 		    true);
13150 		if (rc < 0) {
13151 			rc = -rc;
13152 			CH_ERR(&pi->vi[0],
13153 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
13154 		} else {
13155 			MPASS(rc == sc->rawf_base + pi->port_id);
13156 			pi->vxlan_tcam_entry = true;
13157 		}
13158 	}
13159 }
13160 
13161 static void
13162 t4_vxlan_start(struct adapter *sc, void *arg)
13163 {
13164 	struct vxlan_evargs *v = arg;
13165 
13166 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13167 		return;
13168 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
13169 		return;
13170 
13171 	if (sc->vxlan_refcount == 0) {
13172 		sc->vxlan_port = v->port;
13173 		sc->vxlan_refcount = 1;
13174 		if (!hw_off_limits(sc))
13175 			enable_vxlan_rx(sc);
13176 	} else if (sc->vxlan_port == v->port) {
13177 		sc->vxlan_refcount++;
13178 	} else {
13179 		CH_ERR(sc, "VXLAN already configured on port  %d; "
13180 		    "ignoring attempt to configure it on port %d\n",
13181 		    sc->vxlan_port, v->port);
13182 	}
13183 	end_synchronized_op(sc, 0);
13184 }
13185 
13186 static void
13187 t4_vxlan_stop(struct adapter *sc, void *arg)
13188 {
13189 	struct vxlan_evargs *v = arg;
13190 
13191 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13192 		return;
13193 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
13194 		return;
13195 
13196 	/*
13197 	 * VXLANs may have been configured before the driver was loaded so we
13198 	 * may see more stops than starts.  This is not handled cleanly but at
13199 	 * least we keep the refcount sane.
13200 	 */
13201 	if (sc->vxlan_port != v->port)
13202 		goto done;
13203 	if (sc->vxlan_refcount == 0) {
13204 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
13205 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
13206 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
13207 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
13208 done:
13209 	end_synchronized_op(sc, 0);
13210 }
13211 
13212 static void
13213 t4_vxlan_start_handler(void *arg __unused, struct ifnet *ifp,
13214     sa_family_t family, u_int port)
13215 {
13216 	struct vxlan_evargs v;
13217 
13218 	MPASS(family == AF_INET || family == AF_INET6);
13219 	v.ifp = ifp;
13220 	v.port = port;
13221 
13222 	t4_iterate(t4_vxlan_start, &v);
13223 }
13224 
13225 static void
13226 t4_vxlan_stop_handler(void *arg __unused, struct ifnet *ifp, sa_family_t family,
13227     u_int port)
13228 {
13229 	struct vxlan_evargs v;
13230 
13231 	MPASS(family == AF_INET || family == AF_INET6);
13232 	v.ifp = ifp;
13233 	v.port = port;
13234 
13235 	t4_iterate(t4_vxlan_stop, &v);
13236 }
13237 
13238 
13239 static struct sx mlu;	/* mod load unload */
13240 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
13241 
13242 static int
13243 mod_event(module_t mod, int cmd, void *arg)
13244 {
13245 	int rc = 0;
13246 	static int loaded = 0;
13247 
13248 	switch (cmd) {
13249 	case MOD_LOAD:
13250 		sx_xlock(&mlu);
13251 		if (loaded++ == 0) {
13252 			t4_sge_modload();
13253 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13254 			    t4_filter_rpl, CPL_COOKIE_FILTER);
13255 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
13256 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
13257 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
13258 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
13259 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13260 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
13261 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
13262 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
13263 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
13264 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
13265 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
13266 			    do_smt_write_rpl);
13267 			sx_init(&t4_list_lock, "T4/T5 adapters");
13268 			SLIST_INIT(&t4_list);
13269 			callout_init(&fatal_callout, 1);
13270 #ifdef TCP_OFFLOAD
13271 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
13272 			SLIST_INIT(&t4_uld_list);
13273 #endif
13274 #ifdef INET6
13275 			t4_clip_modload();
13276 #endif
13277 #ifdef KERN_TLS
13278 			t6_ktls_modload();
13279 #endif
13280 			t4_tracer_modload();
13281 			tweak_tunables();
13282 			vxlan_start_evtag =
13283 			    EVENTHANDLER_REGISTER(vxlan_start,
13284 				t4_vxlan_start_handler, NULL,
13285 				EVENTHANDLER_PRI_ANY);
13286 			vxlan_stop_evtag =
13287 			    EVENTHANDLER_REGISTER(vxlan_stop,
13288 				t4_vxlan_stop_handler, NULL,
13289 				EVENTHANDLER_PRI_ANY);
13290 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
13291 			    taskqueue_thread_enqueue, &reset_tq);
13292 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
13293 			    "t4_rst_thr");
13294 		}
13295 		sx_xunlock(&mlu);
13296 		break;
13297 
13298 	case MOD_UNLOAD:
13299 		sx_xlock(&mlu);
13300 		if (--loaded == 0) {
13301 			int tries;
13302 
13303 			taskqueue_free(reset_tq);
13304 			sx_slock(&t4_list_lock);
13305 			if (!SLIST_EMPTY(&t4_list)) {
13306 				rc = EBUSY;
13307 				sx_sunlock(&t4_list_lock);
13308 				goto done_unload;
13309 			}
13310 #ifdef TCP_OFFLOAD
13311 			sx_slock(&t4_uld_list_lock);
13312 			if (!SLIST_EMPTY(&t4_uld_list)) {
13313 				rc = EBUSY;
13314 				sx_sunlock(&t4_uld_list_lock);
13315 				sx_sunlock(&t4_list_lock);
13316 				goto done_unload;
13317 			}
13318 #endif
13319 			tries = 0;
13320 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13321 				uprintf("%ju clusters with custom free routine "
13322 				    "still is use.\n", t4_sge_extfree_refs());
13323 				pause("t4unload", 2 * hz);
13324 			}
13325 #ifdef TCP_OFFLOAD
13326 			sx_sunlock(&t4_uld_list_lock);
13327 #endif
13328 			sx_sunlock(&t4_list_lock);
13329 
13330 			if (t4_sge_extfree_refs() == 0) {
13331 				EVENTHANDLER_DEREGISTER(vxlan_start,
13332 				    vxlan_start_evtag);
13333 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13334 				    vxlan_stop_evtag);
13335 				t4_tracer_modunload();
13336 #ifdef KERN_TLS
13337 				t6_ktls_modunload();
13338 #endif
13339 #ifdef INET6
13340 				t4_clip_modunload();
13341 #endif
13342 #ifdef TCP_OFFLOAD
13343 				sx_destroy(&t4_uld_list_lock);
13344 #endif
13345 				sx_destroy(&t4_list_lock);
13346 				t4_sge_modunload();
13347 				loaded = 0;
13348 			} else {
13349 				rc = EBUSY;
13350 				loaded++;	/* undo earlier decrement */
13351 			}
13352 		}
13353 done_unload:
13354 		sx_xunlock(&mlu);
13355 		break;
13356 	}
13357 
13358 	return (rc);
13359 }
13360 
13361 DRIVER_MODULE(t4nex, pci, t4_driver, mod_event, 0);
13362 MODULE_VERSION(t4nex, 1);
13363 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13364 #ifdef DEV_NETMAP
13365 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13366 #endif /* DEV_NETMAP */
13367 
13368 DRIVER_MODULE(t5nex, pci, t5_driver, mod_event, 0);
13369 MODULE_VERSION(t5nex, 1);
13370 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13371 #ifdef DEV_NETMAP
13372 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13373 #endif /* DEV_NETMAP */
13374 
13375 DRIVER_MODULE(t6nex, pci, t6_driver, mod_event, 0);
13376 MODULE_VERSION(t6nex, 1);
13377 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13378 #ifdef DEV_NETMAP
13379 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13380 #endif /* DEV_NETMAP */
13381 
13382 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, 0, 0);
13383 MODULE_VERSION(cxgbe, 1);
13384 
13385 DRIVER_MODULE(cxl, t5nex, cxl_driver, 0, 0);
13386 MODULE_VERSION(cxl, 1);
13387 
13388 DRIVER_MODULE(cc, t6nex, cc_driver, 0, 0);
13389 MODULE_VERSION(cc, 1);
13390 
13391 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, 0, 0);
13392 MODULE_VERSION(vcxgbe, 1);
13393 
13394 DRIVER_MODULE(vcxl, cxl, vcxl_driver, 0, 0);
13395 MODULE_VERSION(vcxl, 1);
13396 
13397 DRIVER_MODULE(vcc, cc, vcc_driver, 0, 0);
13398 MODULE_VERSION(vcc, 1);
13399