xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision 98f6f6e4f4bb7b19e12de89fc8cc034915f7a759)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2011, 2025 Chelsio Communications.
5  * Written by: Navdeep Parhar <np@FreeBSD.org>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 #include "opt_ddb.h"
31 #include "opt_inet.h"
32 #include "opt_inet6.h"
33 #include "opt_kern_tls.h"
34 #include "opt_ratelimit.h"
35 #include "opt_rss.h"
36 
37 #include <sys/param.h>
38 #include <sys/conf.h>
39 #include <sys/priv.h>
40 #include <sys/kernel.h>
41 #include <sys/bus.h>
42 #include <sys/eventhandler.h>
43 #include <sys/module.h>
44 #include <sys/malloc.h>
45 #include <sys/queue.h>
46 #include <sys/taskqueue.h>
47 #include <dev/pci/pcireg.h>
48 #include <dev/pci/pcivar.h>
49 #include <sys/firmware.h>
50 #include <sys/sbuf.h>
51 #include <sys/smp.h>
52 #include <sys/socket.h>
53 #include <sys/sockio.h>
54 #include <sys/sysctl.h>
55 #include <net/ethernet.h>
56 #include <net/if.h>
57 #include <net/if_types.h>
58 #include <net/if_dl.h>
59 #include <net/if_vlan_var.h>
60 #include <net/rss_config.h>
61 #include <netinet/in.h>
62 #include <netinet/ip.h>
63 #ifdef KERN_TLS
64 #include <netinet/tcp_seq.h>
65 #endif
66 #if defined(__i386__) || defined(__amd64__)
67 #include <machine/md_var.h>
68 #include <machine/cputypes.h>
69 #include <vm/vm.h>
70 #include <vm/pmap.h>
71 #endif
72 #ifdef DDB
73 #include <ddb/ddb.h>
74 #include <ddb/db_lex.h>
75 #endif
76 
77 #include "common/common.h"
78 #include "common/t4_msg.h"
79 #include "common/t4_regs.h"
80 #include "common/t4_regs_values.h"
81 #include "cudbg/cudbg.h"
82 #include "t4_clip.h"
83 #include "t4_ioctl.h"
84 #include "t4_l2t.h"
85 #include "t4_mp_ring.h"
86 #include "t4_if.h"
87 #include "t4_smt.h"
88 
89 /* T4 bus driver interface */
90 static int t4_probe(device_t);
91 static int t4_attach(device_t);
92 static int t4_detach(device_t);
93 static int t4_child_location(device_t, device_t, struct sbuf *);
94 static int t4_ready(device_t);
95 static int t4_read_port_device(device_t, int, device_t *);
96 static int t4_suspend(device_t);
97 static int t4_resume(device_t);
98 static int t4_reset_prepare(device_t, device_t);
99 static int t4_reset_post(device_t, device_t);
100 static device_method_t t4_methods[] = {
101 	DEVMETHOD(device_probe,		t4_probe),
102 	DEVMETHOD(device_attach,	t4_attach),
103 	DEVMETHOD(device_detach,	t4_detach),
104 	DEVMETHOD(device_suspend,	t4_suspend),
105 	DEVMETHOD(device_resume,	t4_resume),
106 
107 	DEVMETHOD(bus_child_location,	t4_child_location),
108 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
109 	DEVMETHOD(bus_reset_post,	t4_reset_post),
110 
111 	DEVMETHOD(t4_is_main_ready,	t4_ready),
112 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
113 
114 	DEVMETHOD_END
115 };
116 static driver_t t4_driver = {
117 	"t4nex",
118 	t4_methods,
119 	sizeof(struct adapter)
120 };
121 
122 
123 /* T4 port (cxgbe) interface */
124 static int cxgbe_probe(device_t);
125 static int cxgbe_attach(device_t);
126 static int cxgbe_detach(device_t);
127 device_method_t cxgbe_methods[] = {
128 	DEVMETHOD(device_probe,		cxgbe_probe),
129 	DEVMETHOD(device_attach,	cxgbe_attach),
130 	DEVMETHOD(device_detach,	cxgbe_detach),
131 	{ 0, 0 }
132 };
133 static driver_t cxgbe_driver = {
134 	"cxgbe",
135 	cxgbe_methods,
136 	sizeof(struct port_info)
137 };
138 
139 /* T4 VI (vcxgbe) interface */
140 static int vcxgbe_probe(device_t);
141 static int vcxgbe_attach(device_t);
142 static int vcxgbe_detach(device_t);
143 static device_method_t vcxgbe_methods[] = {
144 	DEVMETHOD(device_probe,		vcxgbe_probe),
145 	DEVMETHOD(device_attach,	vcxgbe_attach),
146 	DEVMETHOD(device_detach,	vcxgbe_detach),
147 	{ 0, 0 }
148 };
149 static driver_t vcxgbe_driver = {
150 	"vcxgbe",
151 	vcxgbe_methods,
152 	sizeof(struct vi_info)
153 };
154 
155 static d_ioctl_t t4_ioctl;
156 
157 static struct cdevsw t4_cdevsw = {
158        .d_version = D_VERSION,
159        .d_ioctl = t4_ioctl,
160        .d_name = "t4nex",
161 };
162 
163 /* T5 bus driver interface */
164 static int t5_probe(device_t);
165 static device_method_t t5_methods[] = {
166 	DEVMETHOD(device_probe,		t5_probe),
167 	DEVMETHOD(device_attach,	t4_attach),
168 	DEVMETHOD(device_detach,	t4_detach),
169 	DEVMETHOD(device_suspend,	t4_suspend),
170 	DEVMETHOD(device_resume,	t4_resume),
171 
172 	DEVMETHOD(bus_child_location,	t4_child_location),
173 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
174 	DEVMETHOD(bus_reset_post,	t4_reset_post),
175 
176 	DEVMETHOD(t4_is_main_ready,	t4_ready),
177 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
178 
179 	DEVMETHOD_END
180 };
181 static driver_t t5_driver = {
182 	"t5nex",
183 	t5_methods,
184 	sizeof(struct adapter)
185 };
186 
187 
188 /* T5 port (cxl) interface */
189 static driver_t cxl_driver = {
190 	"cxl",
191 	cxgbe_methods,
192 	sizeof(struct port_info)
193 };
194 
195 /* T5 VI (vcxl) interface */
196 static driver_t vcxl_driver = {
197 	"vcxl",
198 	vcxgbe_methods,
199 	sizeof(struct vi_info)
200 };
201 
202 /* T6 bus driver interface */
203 static int t6_probe(device_t);
204 static device_method_t t6_methods[] = {
205 	DEVMETHOD(device_probe,		t6_probe),
206 	DEVMETHOD(device_attach,	t4_attach),
207 	DEVMETHOD(device_detach,	t4_detach),
208 	DEVMETHOD(device_suspend,	t4_suspend),
209 	DEVMETHOD(device_resume,	t4_resume),
210 
211 	DEVMETHOD(bus_child_location,	t4_child_location),
212 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
213 	DEVMETHOD(bus_reset_post,	t4_reset_post),
214 
215 	DEVMETHOD(t4_is_main_ready,	t4_ready),
216 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
217 
218 	DEVMETHOD_END
219 };
220 static driver_t t6_driver = {
221 	"t6nex",
222 	t6_methods,
223 	sizeof(struct adapter)
224 };
225 
226 
227 /* T6 port (cc) interface */
228 static driver_t cc_driver = {
229 	"cc",
230 	cxgbe_methods,
231 	sizeof(struct port_info)
232 };
233 
234 /* T6 VI (vcc) interface */
235 static driver_t vcc_driver = {
236 	"vcc",
237 	vcxgbe_methods,
238 	sizeof(struct vi_info)
239 };
240 
241 /* T7+ bus driver interface */
242 static int ch_probe(device_t);
243 static device_method_t ch_methods[] = {
244 	DEVMETHOD(device_probe,		ch_probe),
245 	DEVMETHOD(device_attach,	t4_attach),
246 	DEVMETHOD(device_detach,	t4_detach),
247 	DEVMETHOD(device_suspend,	t4_suspend),
248 	DEVMETHOD(device_resume,	t4_resume),
249 
250 	DEVMETHOD(bus_child_location,	t4_child_location),
251 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
252 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
253 
254 	DEVMETHOD(t4_is_main_ready,	t4_ready),
255 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
256 
257 	DEVMETHOD_END
258 };
259 static driver_t ch_driver = {
260 	"chnex",
261 	ch_methods,
262 	sizeof(struct adapter)
263 };
264 
265 
266 /* T7+ port (che) interface */
267 static driver_t che_driver = {
268 	"che",
269 	cxgbe_methods,
270 	sizeof(struct port_info)
271 };
272 
273 /* T7+ VI (vche) interface */
274 static driver_t vche_driver = {
275 	"vche",
276 	vcxgbe_methods,
277 	sizeof(struct vi_info)
278 };
279 
280 /* ifnet interface */
281 static void cxgbe_init(void *);
282 static int cxgbe_ioctl(if_t, unsigned long, caddr_t);
283 static int cxgbe_transmit(if_t, struct mbuf *);
284 static void cxgbe_qflush(if_t);
285 #if defined(KERN_TLS) || defined(RATELIMIT)
286 static int cxgbe_snd_tag_alloc(if_t, union if_snd_tag_alloc_params *,
287     struct m_snd_tag **);
288 #endif
289 
290 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
291 
292 /*
293  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
294  * then ADAPTER_LOCK, then t4_uld_list_lock.
295  */
296 static struct sx t4_list_lock;
297 SLIST_HEAD(, adapter) t4_list;
298 #ifdef TCP_OFFLOAD
299 static struct sx t4_uld_list_lock;
300 struct uld_info *t4_uld_list[ULD_MAX + 1];
301 #endif
302 
303 /*
304  * Tunables.  See tweak_tunables() too.
305  *
306  * Each tunable is set to a default value here if it's known at compile-time.
307  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
308  * provide a reasonable default (upto n) when the driver is loaded.
309  *
310  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
311  * T5 are under hw.cxl.
312  */
313 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
314     "cxgbe(4) parameters");
315 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
316     "cxgbe(4) T5+ parameters");
317 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
318     "cxgbe(4) TOE parameters");
319 
320 /*
321  * Number of queues for tx and rx, NIC and offload.
322  */
323 #define NTXQ 16
324 int t4_ntxq = -NTXQ;
325 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
326     "Number of TX queues per port");
327 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);	/* Old name, undocumented */
328 
329 #define NRXQ 8
330 int t4_nrxq = -NRXQ;
331 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
332     "Number of RX queues per port");
333 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);	/* Old name, undocumented */
334 
335 #define NTXQ_VI 1
336 static int t4_ntxq_vi = -NTXQ_VI;
337 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
338     "Number of TX queues per VI");
339 
340 #define NRXQ_VI 1
341 static int t4_nrxq_vi = -NRXQ_VI;
342 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
343     "Number of RX queues per VI");
344 
345 static int t4_rsrv_noflowq = 0;
346 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
347     0, "Reserve TX queue 0 of each VI for non-flowid packets");
348 
349 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
350 #define NOFLDTXQ 8
351 static int t4_nofldtxq = -NOFLDTXQ;
352 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
353     "Number of offload TX queues per port");
354 
355 #define NOFLDTXQ_VI 1
356 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
357 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
358     "Number of offload TX queues per VI");
359 #endif
360 
361 #if defined(TCP_OFFLOAD)
362 #define NOFLDRXQ 2
363 static int t4_nofldrxq = -NOFLDRXQ;
364 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
365     "Number of offload RX queues per port");
366 
367 #define NOFLDRXQ_VI 1
368 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
369 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
370     "Number of offload RX queues per VI");
371 
372 #define TMR_IDX_OFLD 1
373 static int t4_tmr_idx_ofld = TMR_IDX_OFLD;
374 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
375     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
376 
377 #define PKTC_IDX_OFLD (-1)
378 static int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
379 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
380     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
381 
382 /* 0 means chip/fw default, non-zero number is value in microseconds */
383 static u_long t4_toe_keepalive_idle = 0;
384 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
385     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
386 
387 /* 0 means chip/fw default, non-zero number is value in microseconds */
388 static u_long t4_toe_keepalive_interval = 0;
389 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
390     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
391 
392 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
393 static int t4_toe_keepalive_count = 0;
394 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
395     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
396 
397 /* 0 means chip/fw default, non-zero number is value in microseconds */
398 static u_long t4_toe_rexmt_min = 0;
399 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
400     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
401 
402 /* 0 means chip/fw default, non-zero number is value in microseconds */
403 static u_long t4_toe_rexmt_max = 0;
404 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
405     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
406 
407 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
408 static int t4_toe_rexmt_count = 0;
409 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
410     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
411 
412 /* -1 means chip/fw default, other values are raw backoff values to use */
413 static int t4_toe_rexmt_backoff[16] = {
414 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
415 };
416 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
417     CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
418     "cxgbe(4) TOE retransmit backoff values");
419 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
420     &t4_toe_rexmt_backoff[0], 0, "");
421 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
422     &t4_toe_rexmt_backoff[1], 0, "");
423 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
424     &t4_toe_rexmt_backoff[2], 0, "");
425 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
426     &t4_toe_rexmt_backoff[3], 0, "");
427 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
428     &t4_toe_rexmt_backoff[4], 0, "");
429 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
430     &t4_toe_rexmt_backoff[5], 0, "");
431 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
432     &t4_toe_rexmt_backoff[6], 0, "");
433 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
434     &t4_toe_rexmt_backoff[7], 0, "");
435 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
436     &t4_toe_rexmt_backoff[8], 0, "");
437 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
438     &t4_toe_rexmt_backoff[9], 0, "");
439 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
440     &t4_toe_rexmt_backoff[10], 0, "");
441 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
442     &t4_toe_rexmt_backoff[11], 0, "");
443 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
444     &t4_toe_rexmt_backoff[12], 0, "");
445 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
446     &t4_toe_rexmt_backoff[13], 0, "");
447 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
448     &t4_toe_rexmt_backoff[14], 0, "");
449 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
450     &t4_toe_rexmt_backoff[15], 0, "");
451 
452 int t4_ddp_rcvbuf_len = 256 * 1024;
453 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, ddp_rcvbuf_len, CTLFLAG_RWTUN,
454     &t4_ddp_rcvbuf_len, 0, "length of each DDP RX buffer");
455 
456 unsigned int t4_ddp_rcvbuf_cache = 4;
457 SYSCTL_UINT(_hw_cxgbe_toe, OID_AUTO, ddp_rcvbuf_cache, CTLFLAG_RWTUN,
458     &t4_ddp_rcvbuf_cache, 0,
459     "maximum number of free DDP RX buffers to cache per connection");
460 #endif
461 
462 #ifdef DEV_NETMAP
463 #define NN_MAIN_VI	(1 << 0)	/* Native netmap on the main VI */
464 #define NN_EXTRA_VI	(1 << 1)	/* Native netmap on the extra VI(s) */
465 static int t4_native_netmap = NN_EXTRA_VI;
466 SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
467     0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
468 
469 #define NNMTXQ 8
470 static int t4_nnmtxq = -NNMTXQ;
471 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
472     "Number of netmap TX queues");
473 
474 #define NNMRXQ 8
475 static int t4_nnmrxq = -NNMRXQ;
476 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
477     "Number of netmap RX queues");
478 
479 #define NNMTXQ_VI 2
480 static int t4_nnmtxq_vi = -NNMTXQ_VI;
481 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
482     "Number of netmap TX queues per VI");
483 
484 #define NNMRXQ_VI 2
485 static int t4_nnmrxq_vi = -NNMRXQ_VI;
486 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
487     "Number of netmap RX queues per VI");
488 #endif
489 
490 /*
491  * Holdoff parameters for ports.
492  */
493 #define TMR_IDX 1
494 int t4_tmr_idx = TMR_IDX;
495 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
496     0, "Holdoff timer index");
497 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);	/* Old name */
498 
499 #define PKTC_IDX (-1)
500 int t4_pktc_idx = PKTC_IDX;
501 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
502     0, "Holdoff packet counter index");
503 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);	/* Old name */
504 
505 /*
506  * Size (# of entries) of each tx and rx queue.
507  */
508 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
509 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
510     "Number of descriptors in each TX queue");
511 
512 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
513 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
514     "Number of descriptors in each RX queue");
515 
516 /*
517  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
518  */
519 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
520 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
521     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
522 
523 /*
524  * Configuration file.  All the _CF names here are special.
525  */
526 #define DEFAULT_CF	"default"
527 #define BUILTIN_CF	"built-in"
528 #define FLASH_CF	"flash"
529 #define UWIRE_CF	"uwire"
530 #define FPGA_CF		"fpga"
531 static char t4_cfg_file[32] = DEFAULT_CF;
532 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
533     sizeof(t4_cfg_file), "Firmware configuration file");
534 
535 /*
536  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
537  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
538  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
539  *            mark or when signalled to do so, 0 to never emit PAUSE.
540  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
541  *                 negotiated settings will override rx_pause/tx_pause.
542  *                 Otherwise rx_pause/tx_pause are applied forcibly.
543  */
544 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
545 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
546     &t4_pause_settings, 0,
547     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
548 
549 /*
550  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
551  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
552  *  0 to disable FEC.
553  */
554 static int t4_fec = -1;
555 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
556     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
557 
558 static const char *
559 t4_fec_bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2\6auto\7module";
560 
561 /*
562  * Controls when the driver sets the FORCE_FEC bit in the L1_CFG32 that it
563  * issues to the firmware.  If the firmware doesn't support FORCE_FEC then the
564  * driver runs as if this is set to 0.
565  * -1 to set FORCE_FEC iff requested_fec != AUTO. Multiple FEC bits are okay.
566  *  0 to never set FORCE_FEC. requested_fec = AUTO means use the hint from the
567  *    transceiver. Multiple FEC bits may not be okay but will be passed on to
568  *    the firmware anyway (may result in l1cfg errors with old firmwares).
569  *  1 to always set FORCE_FEC. Multiple FEC bits are okay. requested_fec = AUTO
570  *    means set all FEC bits that are valid for the speed.
571  */
572 static int t4_force_fec = -1;
573 SYSCTL_INT(_hw_cxgbe, OID_AUTO, force_fec, CTLFLAG_RDTUN, &t4_force_fec, 0,
574     "Controls the use of FORCE_FEC bit in L1 configuration.");
575 
576 /*
577  * Link autonegotiation.
578  * -1 to run with the firmware default.
579  *  0 to disable.
580  *  1 to enable.
581  */
582 static int t4_autoneg = -1;
583 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
584     "Link autonegotiation");
585 
586 /*
587  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
588  * encouraged respectively).  '-n' is the same as 'n' except the firmware
589  * version used in the checks is read from the firmware bundled with the driver.
590  */
591 static int t4_fw_install = 1;
592 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
593     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
594 
595 /*
596  * ASIC features that will be used.  Disable the ones you don't want so that the
597  * chip resources aren't wasted on features that will not be used.
598  */
599 static int t4_nbmcaps_allowed = 0;
600 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
601     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
602 
603 static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
604 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
605     &t4_linkcaps_allowed, 0, "Default link capabilities");
606 
607 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
608     FW_CAPS_CONFIG_SWITCH_EGRESS;
609 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
610     &t4_switchcaps_allowed, 0, "Default switch capabilities");
611 
612 static int t4_nvmecaps_allowed = -1;
613 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nvmecaps_allowed, CTLFLAG_RDTUN,
614     &t4_nvmecaps_allowed, 0, "Default NVMe capabilities");
615 
616 #ifdef RATELIMIT
617 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
618 	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
619 #else
620 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
621 	FW_CAPS_CONFIG_NIC_HASHFILTER;
622 #endif
623 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
624     &t4_niccaps_allowed, 0, "Default NIC capabilities");
625 
626 static int t4_toecaps_allowed = -1;
627 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
628     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
629 
630 static int t4_rdmacaps_allowed = -1;
631 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
632     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
633 
634 static int t4_cryptocaps_allowed = -1;
635 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
636     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
637 
638 static int t4_iscsicaps_allowed = -1;
639 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
640     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
641 
642 static int t4_fcoecaps_allowed = 0;
643 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
644     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
645 
646 static int t5_write_combine = 0;
647 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
648     0, "Use WC instead of UC for BAR2");
649 
650 /* From t4_sysctls: doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"} */
651 static int t4_doorbells_allowed = 0xf;
652 SYSCTL_INT(_hw_cxgbe, OID_AUTO, doorbells_allowed, CTLFLAG_RDTUN,
653 	   &t4_doorbells_allowed, 0, "Limit tx queues to these doorbells");
654 
655 static int t4_num_vis = 1;
656 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
657     "Number of VIs per port");
658 
659 /*
660  * PCIe Relaxed Ordering.
661  * -1: driver should figure out a good value.
662  * 0: disable RO.
663  * 1: enable RO.
664  * 2: leave RO alone.
665  */
666 static int pcie_relaxed_ordering = -1;
667 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
668     &pcie_relaxed_ordering, 0,
669     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
670 
671 static int t4_panic_on_fatal_err = 0;
672 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
673     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
674 
675 static int t4_reset_on_fatal_err = 0;
676 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
677     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
678 
679 static int t4_reset_method = 1;
680 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_method, CTLFLAG_RWTUN, &t4_reset_method,
681     0, "reset method: 0 = PL_RST, 1 = PCIe secondary bus reset, 2 = PCIe link bounce");
682 
683 static int t4_clock_gate_on_suspend = 0;
684 SYSCTL_INT(_hw_cxgbe, OID_AUTO, clock_gate_on_suspend, CTLFLAG_RWTUN,
685     &t4_clock_gate_on_suspend, 0, "gate the clock on suspend");
686 
687 static int t4_tx_vm_wr = 0;
688 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
689     "Use VM work requests to transmit packets.");
690 
691 /*
692  * Set to non-zero to enable the attack filter.  A packet that matches any of
693  * these conditions will get dropped on ingress:
694  * 1) IP && source address == destination address.
695  * 2) TCP/IP && source address is not a unicast address.
696  * 3) TCP/IP && destination address is not a unicast address.
697  * 4) IP && source address is loopback (127.x.y.z).
698  * 5) IP && destination address is loopback (127.x.y.z).
699  * 6) IPv6 && source address == destination address.
700  * 7) IPv6 && source address is not a unicast address.
701  * 8) IPv6 && source address is loopback (::1/128).
702  * 9) IPv6 && destination address is loopback (::1/128).
703  * 10) IPv6 && source address is unspecified (::/128).
704  * 11) IPv6 && destination address is unspecified (::/128).
705  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
706  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
707  */
708 static int t4_attack_filter = 0;
709 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
710     &t4_attack_filter, 0, "Drop suspicious traffic");
711 
712 static int t4_drop_ip_fragments = 0;
713 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
714     &t4_drop_ip_fragments, 0, "Drop IP fragments");
715 
716 static int t4_drop_pkts_with_l2_errors = 1;
717 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
718     &t4_drop_pkts_with_l2_errors, 0,
719     "Drop all frames with Layer 2 length or checksum errors");
720 
721 static int t4_drop_pkts_with_l3_errors = 0;
722 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
723     &t4_drop_pkts_with_l3_errors, 0,
724     "Drop all frames with IP version, length, or checksum errors");
725 
726 static int t4_drop_pkts_with_l4_errors = 0;
727 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
728     &t4_drop_pkts_with_l4_errors, 0,
729     "Drop all frames with Layer 4 length, checksum, or other errors");
730 
731 #ifdef TCP_OFFLOAD
732 /*
733  * TOE tunables.
734  */
735 static int t4_cop_managed_offloading = 0;
736 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
737     &t4_cop_managed_offloading, 0,
738     "COP (Connection Offload Policy) controls all TOE offload");
739 TUNABLE_INT("hw.cxgbe.cop_managed_offloading", &t4_cop_managed_offloading);
740 #endif
741 
742 #ifdef KERN_TLS
743 /*
744  * This enables KERN_TLS for all adapters if set.
745  */
746 static int t4_kern_tls = 0;
747 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
748     "Enable KERN_TLS mode for T6 adapters");
749 
750 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
751     "cxgbe(4) KERN_TLS parameters");
752 
753 static int t4_tls_inline_keys = 0;
754 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
755     &t4_tls_inline_keys, 0,
756     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
757     "in card memory.");
758 
759 static int t4_tls_combo_wrs = 0;
760 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
761     0, "Attempt to combine TCB field updates with TLS record work requests.");
762 
763 static int t4_tls_short_records = 1;
764 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, short_records, CTLFLAG_RDTUN,
765     &t4_tls_short_records, 0, "Use cipher-only mode for short records.");
766 
767 static int t4_tls_partial_ghash = 1;
768 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, partial_ghash, CTLFLAG_RDTUN,
769     &t4_tls_partial_ghash, 0, "Use partial GHASH for AES-GCM records.");
770 #endif
771 
772 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
773 static int vi_mac_funcs[] = {
774 	FW_VI_FUNC_ETH,
775 	FW_VI_FUNC_OFLD,
776 	FW_VI_FUNC_IWARP,
777 	FW_VI_FUNC_OPENISCSI,
778 	FW_VI_FUNC_OPENFCOE,
779 	FW_VI_FUNC_FOISCSI,
780 	FW_VI_FUNC_FOFCOE,
781 };
782 
783 struct intrs_and_queues {
784 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
785 	uint16_t num_vis;	/* number of VIs for each port */
786 	uint16_t nirq;		/* Total # of vectors */
787 	uint16_t ntxq;		/* # of NIC txq's for each port */
788 	uint16_t nrxq;		/* # of NIC rxq's for each port */
789 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
790 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
791 	uint16_t nnmtxq;	/* # of netmap txq's */
792 	uint16_t nnmrxq;	/* # of netmap rxq's */
793 
794 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
795 	uint16_t ntxq_vi;	/* # of NIC txq's */
796 	uint16_t nrxq_vi;	/* # of NIC rxq's */
797 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
798 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
799 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
800 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
801 };
802 
803 static void setup_memwin(struct adapter *);
804 static void position_memwin(struct adapter *, int, uint32_t);
805 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
806 static int fwmtype_to_hwmtype(int);
807 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
808     uint32_t *);
809 static int fixup_devlog_params(struct adapter *);
810 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
811 static int contact_firmware(struct adapter *);
812 static int partition_resources(struct adapter *);
813 static int get_params__pre_init(struct adapter *);
814 static int set_params__pre_init(struct adapter *);
815 static int get_params__post_init(struct adapter *);
816 static int set_params__post_init(struct adapter *);
817 static void t4_set_desc(struct adapter *);
818 static bool fixed_ifmedia(struct port_info *);
819 static void build_medialist(struct port_info *);
820 static void init_link_config(struct port_info *);
821 static int fixup_link_config(struct port_info *);
822 static int apply_link_config(struct port_info *);
823 static int cxgbe_init_synchronized(struct vi_info *);
824 static int cxgbe_uninit_synchronized(struct vi_info *);
825 static int adapter_full_init(struct adapter *);
826 static void adapter_full_uninit(struct adapter *);
827 static int vi_full_init(struct vi_info *);
828 static void vi_full_uninit(struct vi_info *);
829 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
830 static void quiesce_txq(struct sge_txq *);
831 static void quiesce_wrq(struct sge_wrq *);
832 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
833 static void quiesce_vi(struct vi_info *);
834 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
835     driver_intr_t *, void *, char *);
836 static int t4_free_irq(struct adapter *, struct irq *);
837 static void t4_init_atid_table(struct adapter *);
838 static void t4_free_atid_table(struct adapter *);
839 static void stop_atid_allocator(struct adapter *);
840 static void restart_atid_allocator(struct adapter *);
841 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
842 static void vi_refresh_stats(struct vi_info *);
843 static void cxgbe_refresh_stats(struct vi_info *);
844 static void cxgbe_tick(void *);
845 static void vi_tick(void *);
846 static void cxgbe_sysctls(struct port_info *);
847 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
848 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
849 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
850 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
851 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
852 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
853 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
854 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
855 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
856 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
857 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
858 static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
859 static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
860 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
861 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
862 static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
863 static int sysctl_handle_t4_portstat64(SYSCTL_HANDLER_ARGS);
864 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
865 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
866 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
867 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
868 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
869 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
870 static int sysctl_cim_ibq(SYSCTL_HANDLER_ARGS);
871 static int sysctl_cim_obq(SYSCTL_HANDLER_ARGS);
872 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
873 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
874 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
875 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
876 static int sysctl_cim_qcfg_t7(SYSCTL_HANDLER_ARGS);
877 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
878 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
879 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
880 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
881 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
882 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
883 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
884 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
885 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
886 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
887 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
888 static int sysctl_mps_tcam_t7(SYSCTL_HANDLER_ARGS);
889 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
890 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
891 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
892 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
893 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
894 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
895 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
896 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
897 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
898 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
899 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
900 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
901 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
902 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
903 #ifdef TCP_OFFLOAD
904 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
905 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
906 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
907 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
908 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
909 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
910 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
911 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
912 #endif
913 static int get_sge_context(struct adapter *, int, uint32_t, int, uint32_t *);
914 static int load_fw(struct adapter *, struct t4_data *);
915 static int load_cfg(struct adapter *, struct t4_data *);
916 static int load_boot(struct adapter *, struct t4_bootrom *);
917 static int load_bootcfg(struct adapter *, struct t4_data *);
918 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
919 static void free_offload_policy(struct t4_offload_policy *);
920 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
921 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
922 static int read_i2c(struct adapter *, struct t4_i2c_data *);
923 static int clear_stats(struct adapter *, u_int);
924 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
925 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
926 static inline int stop_adapter(struct adapter *);
927 static inline void set_adapter_hwstatus(struct adapter *, const bool);
928 static int stop_lld(struct adapter *);
929 static inline int restart_adapter(struct adapter *);
930 static int restart_lld(struct adapter *);
931 #ifdef TCP_OFFLOAD
932 static int deactivate_all_uld(struct adapter *);
933 static void stop_all_uld(struct adapter *);
934 static void restart_all_uld(struct adapter *);
935 #endif
936 #ifdef KERN_TLS
937 static int ktls_capability(struct adapter *, bool);
938 #endif
939 static int mod_event(module_t, int, void *);
940 static int notify_siblings(device_t, int);
941 static uint64_t vi_get_counter(if_t, ift_counter);
942 static uint64_t cxgbe_get_counter(if_t, ift_counter);
943 static void enable_vxlan_rx(struct adapter *);
944 static void reset_adapter_task(void *, int);
945 static void fatal_error_task(void *, int);
946 static void dump_devlog(struct adapter *);
947 static void dump_cim_regs(struct adapter *);
948 static void dump_cimla(struct adapter *);
949 
950 struct {
951 	uint16_t device;
952 	char *desc;
953 } t4_pciids[] = {
954 	{0xa000, "Chelsio Terminator 4 FPGA"},
955 	{0x4400, "Chelsio T440-dbg"},
956 	{0x4401, "Chelsio T420-CR"},
957 	{0x4402, "Chelsio T422-CR"},
958 	{0x4403, "Chelsio T440-CR"},
959 	{0x4404, "Chelsio T420-BCH"},
960 	{0x4405, "Chelsio T440-BCH"},
961 	{0x4406, "Chelsio T440-CH"},
962 	{0x4407, "Chelsio T420-SO"},
963 	{0x4408, "Chelsio T420-CX"},
964 	{0x4409, "Chelsio T420-BT"},
965 	{0x440a, "Chelsio T404-BT"},
966 	{0x440e, "Chelsio T440-LP-CR"},
967 }, t5_pciids[] = {
968 	{0xb000, "Chelsio Terminator 5 FPGA"},
969 	{0x5400, "Chelsio T580-dbg"},
970 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
971 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
972 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
973 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
974 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
975 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
976 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
977 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
978 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
979 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
980 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
981 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
982 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
983 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
984 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
985 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
986 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
987 
988 	/* Custom */
989 	{0x5483, "Custom T540-CR"},
990 	{0x5484, "Custom T540-BT"},
991 }, t6_pciids[] = {
992 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
993 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
994 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
995 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
996 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
997 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
998 	{0x6405, "Chelsio T6225-SO-OCP3"},	/* 2 x 10/25G, nomem */
999 	{0x6406, "Chelsio T6225-OCP3"},		/* 2 x 10/25G */
1000 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
1001 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
1002 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
1003 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
1004 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
1005 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
1006 	{0x6414, "Chelsio T62100-SO-OCP3"},	/* 2 x 40/50/100G, nomem */
1007 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
1008 
1009 	/* Custom */
1010 	{0x6480, "Custom T6225-CR"},
1011 	{0x6481, "Custom T62100-CR"},
1012 	{0x6482, "Custom T6225-CR"},
1013 	{0x6483, "Custom T62100-CR"},
1014 	{0x6484, "Custom T64100-CR"},
1015 	{0x6485, "Custom T6240-SO"},
1016 	{0x6486, "Custom T6225-SO-CR"},
1017 	{0x6487, "Custom T6225-CR"},
1018 }, t7_pciids[] = {
1019 	{0xd000, "Chelsio Terminator 7 FPGA"},	/* T7 PE12K FPGA */
1020 	{0x7400, "Chelsio T72200-DBG"},		/* 2 x 200G, debug */
1021 	{0x7401, "Chelsio T7250"},		/* 2 x 10/25/50G, 1 mem */
1022 	{0x7402, "Chelsio S7250"},		/* 2 x 10/25/50G, nomem */
1023 	{0x7403, "Chelsio T7450"},		/* 4 x 10/25/50G, 1 mem */
1024 	{0x7404, "Chelsio S7450"},		/* 4 x 10/25/50G, nomem */
1025 	{0x7405, "Chelsio T72200"},		/* 2 x 40/100/200G, 1 mem */
1026 	{0x7406, "Chelsio S72200"},		/* 2 x 40/100/200G, nomem */
1027 	{0x7407, "Chelsio T72200-FH"},		/* 2 x 40/100/200G, 2 mem */
1028 	{0x7408, "Chelsio S71400"},		/* 1 x 400G, nomem */
1029 	{0x7409, "Chelsio S7210-BT"},		/* 2 x 10GBASE-T, nomem */
1030 	{0x740a, "Chelsio T7450-RC"},		/* 4 x 10/25/50G, 1 mem, RC */
1031 	{0x740b, "Chelsio T72200-RC"},		/* 2 x 40/100/200G, 1 mem, RC */
1032 	{0x740c, "Chelsio T72200-FH-RC"},	/* 2 x 40/100/200G, 2 mem, RC */
1033 	{0x740d, "Chelsio S72200-OCP3"},	/* 2 x 40/100/200G OCP3 */
1034 	{0x740e, "Chelsio S7450-OCP3"},		/* 4 x 1/20/25/50G OCP3 */
1035 	{0x740f, "Chelsio S7410-BT-OCP3"},	/* 4 x 10GBASE-T OCP3 */
1036 	{0x7410, "Chelsio S7210-BT-A"},		/* 2 x 10GBASE-T */
1037 	{0x7411, "Chelsio T7_MAYRA_7"},		/* Motherboard */
1038 
1039 	/* Custom */
1040 	{0x7480, "Custom T7"},
1041 };
1042 
1043 #ifdef TCP_OFFLOAD
1044 /*
1045  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
1046  * be exactly the same for both rxq and ofld_rxq.
1047  */
1048 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
1049 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
1050 #endif
1051 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
1052 
1053 static int
1054 t4_probe(device_t dev)
1055 {
1056 	int i;
1057 	uint16_t v = pci_get_vendor(dev);
1058 	uint16_t d = pci_get_device(dev);
1059 	uint8_t f = pci_get_function(dev);
1060 
1061 	if (v != PCI_VENDOR_ID_CHELSIO)
1062 		return (ENXIO);
1063 
1064 	/* Attach only to PF0 of the FPGA */
1065 	if (d == 0xa000 && f != 0)
1066 		return (ENXIO);
1067 
1068 	for (i = 0; i < nitems(t4_pciids); i++) {
1069 		if (d == t4_pciids[i].device) {
1070 			device_set_desc(dev, t4_pciids[i].desc);
1071 			return (BUS_PROBE_DEFAULT);
1072 		}
1073 	}
1074 
1075 	return (ENXIO);
1076 }
1077 
1078 static int
1079 t5_probe(device_t dev)
1080 {
1081 	int i;
1082 	uint16_t v = pci_get_vendor(dev);
1083 	uint16_t d = pci_get_device(dev);
1084 	uint8_t f = pci_get_function(dev);
1085 
1086 	if (v != PCI_VENDOR_ID_CHELSIO)
1087 		return (ENXIO);
1088 
1089 	/* Attach only to PF0 of the FPGA */
1090 	if (d == 0xb000 && f != 0)
1091 		return (ENXIO);
1092 
1093 	for (i = 0; i < nitems(t5_pciids); i++) {
1094 		if (d == t5_pciids[i].device) {
1095 			device_set_desc(dev, t5_pciids[i].desc);
1096 			return (BUS_PROBE_DEFAULT);
1097 		}
1098 	}
1099 
1100 	return (ENXIO);
1101 }
1102 
1103 static int
1104 t6_probe(device_t dev)
1105 {
1106 	int i;
1107 	uint16_t v = pci_get_vendor(dev);
1108 	uint16_t d = pci_get_device(dev);
1109 
1110 	if (v != PCI_VENDOR_ID_CHELSIO)
1111 		return (ENXIO);
1112 
1113 	for (i = 0; i < nitems(t6_pciids); i++) {
1114 		if (d == t6_pciids[i].device) {
1115 			device_set_desc(dev, t6_pciids[i].desc);
1116 			return (BUS_PROBE_DEFAULT);
1117 		}
1118 	}
1119 
1120 	return (ENXIO);
1121 }
1122 
1123 static int
1124 ch_probe(device_t dev)
1125 {
1126 	int i;
1127 	uint16_t v = pci_get_vendor(dev);
1128 	uint16_t d = pci_get_device(dev);
1129 	uint8_t f = pci_get_function(dev);
1130 
1131 	if (v != PCI_VENDOR_ID_CHELSIO)
1132 		return (ENXIO);
1133 
1134 	/* Attach only to PF0 of the FPGA */
1135 	if (d == 0xd000 && f != 0)
1136 		return (ENXIO);
1137 
1138 	for (i = 0; i < nitems(t7_pciids); i++) {
1139 		if (d == t7_pciids[i].device) {
1140 			device_set_desc(dev, t7_pciids[i].desc);
1141 			return (BUS_PROBE_DEFAULT);
1142 		}
1143 	}
1144 
1145 	return (ENXIO);
1146 }
1147 
1148 static void
1149 t5_attribute_workaround(device_t dev)
1150 {
1151 	device_t root_port;
1152 	uint32_t v;
1153 
1154 	/*
1155 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1156 	 * Ordering attributes when replying to a TLP from a Root
1157 	 * Port.  As a workaround, find the parent Root Port and
1158 	 * disable No Snoop and Relaxed Ordering.  Note that this
1159 	 * affects all devices under this root port.
1160 	 */
1161 	root_port = pci_find_pcie_root_port(dev);
1162 	if (root_port == NULL) {
1163 		device_printf(dev, "Unable to find parent root port\n");
1164 		return;
1165 	}
1166 
1167 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1168 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1169 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1170 	    0)
1171 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1172 		    device_get_nameunit(root_port));
1173 }
1174 
1175 static const struct devnames devnames[] = {
1176 	{
1177 		.nexus_name = "t4nex",
1178 		.ifnet_name = "cxgbe",
1179 		.vi_ifnet_name = "vcxgbe",
1180 		.pf03_drv_name = "t4iov",
1181 		.vf_nexus_name = "t4vf",
1182 		.vf_ifnet_name = "cxgbev"
1183 	}, {
1184 		.nexus_name = "t5nex",
1185 		.ifnet_name = "cxl",
1186 		.vi_ifnet_name = "vcxl",
1187 		.pf03_drv_name = "t5iov",
1188 		.vf_nexus_name = "t5vf",
1189 		.vf_ifnet_name = "cxlv"
1190 	}, {
1191 		.nexus_name = "t6nex",
1192 		.ifnet_name = "cc",
1193 		.vi_ifnet_name = "vcc",
1194 		.pf03_drv_name = "t6iov",
1195 		.vf_nexus_name = "t6vf",
1196 		.vf_ifnet_name = "ccv"
1197 	}, {
1198 		.nexus_name = "chnex",
1199 		.ifnet_name = "che",
1200 		.vi_ifnet_name = "vche",
1201 		.pf03_drv_name = "chiov",
1202 		.vf_nexus_name = "chvf",
1203 		.vf_ifnet_name = "chev"
1204 	}
1205 };
1206 
1207 void
1208 t4_init_devnames(struct adapter *sc)
1209 {
1210 	int id;
1211 
1212 	id = chip_id(sc);
1213 	if (id < CHELSIO_T4) {
1214 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1215 		sc->names = NULL;
1216 	} else if (id - CHELSIO_T4 < nitems(devnames))
1217 		sc->names = &devnames[id - CHELSIO_T4];
1218 	else
1219 		sc->names = &devnames[nitems(devnames) - 1];
1220 }
1221 
1222 static int
1223 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1224 {
1225 	const char *parent, *name;
1226 	long value;
1227 	int line, unit;
1228 
1229 	line = 0;
1230 	parent = device_get_nameunit(sc->dev);
1231 	name = sc->names->ifnet_name;
1232 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1233 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1234 		    value == pi->port_id)
1235 			return (unit);
1236 	}
1237 	return (-1);
1238 }
1239 
1240 static void
1241 t4_calibration(void *arg)
1242 {
1243 	struct adapter *sc;
1244 	struct clock_sync *cur, *nex;
1245 	uint64_t hw;
1246 	sbintime_t sbt;
1247 	int next_up;
1248 
1249 	sc = (struct adapter *)arg;
1250 
1251 	KASSERT(hw_all_ok(sc), ("!hw_all_ok at t4_calibration"));
1252 	hw = t4_read_reg64(sc, A_SGE_TIMESTAMP_LO);
1253 	sbt = sbinuptime();
1254 
1255 	cur = &sc->cal_info[sc->cal_current];
1256 	next_up = (sc->cal_current + 1) % CNT_CAL_INFO;
1257 	nex = &sc->cal_info[next_up];
1258 	if (__predict_false(sc->cal_count == 0)) {
1259 		/* First time in, just get the values in */
1260 		cur->hw_cur = hw;
1261 		cur->sbt_cur = sbt;
1262 		sc->cal_count++;
1263 		goto done;
1264 	}
1265 
1266 	if (cur->hw_cur == hw) {
1267 		/* The clock is not advancing? */
1268 		sc->cal_count = 0;
1269 		atomic_store_rel_int(&cur->gen, 0);
1270 		goto done;
1271 	}
1272 
1273 	seqc_write_begin(&nex->gen);
1274 	nex->hw_prev = cur->hw_cur;
1275 	nex->sbt_prev = cur->sbt_cur;
1276 	nex->hw_cur = hw;
1277 	nex->sbt_cur = sbt;
1278 	seqc_write_end(&nex->gen);
1279 	sc->cal_current = next_up;
1280 done:
1281 	callout_reset_sbt_curcpu(&sc->cal_callout, SBT_1S, 0, t4_calibration,
1282 	    sc, C_DIRECT_EXEC);
1283 }
1284 
1285 static void
1286 t4_calibration_start(struct adapter *sc)
1287 {
1288 	/*
1289 	 * Here if we have not done a calibration
1290 	 * then do so otherwise start the appropriate
1291 	 * timer.
1292 	 */
1293 	int i;
1294 
1295 	for (i = 0; i < CNT_CAL_INFO; i++) {
1296 		sc->cal_info[i].gen = 0;
1297 	}
1298 	sc->cal_current = 0;
1299 	sc->cal_count = 0;
1300 	sc->cal_gen = 0;
1301 	t4_calibration(sc);
1302 }
1303 
1304 static int
1305 t4_attach(device_t dev)
1306 {
1307 	struct adapter *sc;
1308 	int rc = 0, i, j, rqidx, tqidx, nports;
1309 	struct make_dev_args mda;
1310 	struct intrs_and_queues iaq;
1311 	struct sge *s;
1312 	uint32_t *buf;
1313 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1314 	int ofld_tqidx;
1315 #endif
1316 #ifdef TCP_OFFLOAD
1317 	int ofld_rqidx;
1318 #endif
1319 #ifdef DEV_NETMAP
1320 	int nm_rqidx, nm_tqidx;
1321 #endif
1322 	int num_vis;
1323 
1324 	sc = device_get_softc(dev);
1325 	sc->dev = dev;
1326 	sysctl_ctx_init(&sc->ctx);
1327 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1328 	if (TUNABLE_INT_FETCH("hw.cxgbe.iflags", &sc->intr_flags) == 0)
1329 		sc->intr_flags = IHF_INTR_CLEAR_ON_INIT | IHF_CLR_ALL_UNIGNORED;
1330 
1331 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1332 		t5_attribute_workaround(dev);
1333 	pci_enable_busmaster(dev);
1334 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1335 		uint32_t v;
1336 
1337 		pci_set_max_read_req(dev, 4096);
1338 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1339 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1340 		if (pcie_relaxed_ordering == 0 &&
1341 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1342 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1343 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1344 		} else if (pcie_relaxed_ordering == 1 &&
1345 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1346 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1347 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1348 		}
1349 	}
1350 
1351 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1352 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1353 	sc->traceq = -1;
1354 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1355 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1356 	    device_get_nameunit(dev));
1357 
1358 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1359 	    device_get_nameunit(dev));
1360 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1361 	t4_add_adapter(sc);
1362 
1363 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1364 	TAILQ_INIT(&sc->sfl);
1365 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1366 
1367 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1368 
1369 	sc->policy = NULL;
1370 	rw_init(&sc->policy_lock, "connection offload policy");
1371 
1372 	callout_init(&sc->ktls_tick, 1);
1373 
1374 	callout_init(&sc->cal_callout, 1);
1375 
1376 	refcount_init(&sc->vxlan_refcount, 0);
1377 
1378 	TASK_INIT(&sc->reset_task, 0, reset_adapter_task, sc);
1379 	TASK_INIT(&sc->fatal_error_task, 0, fatal_error_task, sc);
1380 
1381 	sc->ctrlq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1382 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1383 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1384 	sc->fwq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1385 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1386 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1387 
1388 	rc = t4_map_bars_0_and_4(sc);
1389 	if (rc != 0)
1390 		goto done; /* error message displayed already */
1391 
1392 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1393 	memset(sc->port_map, 0xff, sizeof(sc->port_map));
1394 
1395 	/* Prepare the adapter for operation. */
1396 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1397 	rc = -t4_prep_adapter(sc, buf);
1398 	free(buf, M_CXGBE);
1399 	if (rc != 0) {
1400 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1401 		goto done;
1402 	}
1403 
1404 	/*
1405 	 * This is the real PF# to which we're attaching.  Works from within PCI
1406 	 * passthrough environments too, where pci_get_function() could return a
1407 	 * different PF# depending on the passthrough configuration.  We need to
1408 	 * use the real PF# in all our communication with the firmware.
1409 	 */
1410 	j = t4_read_reg(sc, A_PL_WHOAMI);
1411 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1412 	sc->mbox = sc->pf;
1413 
1414 	t4_init_devnames(sc);
1415 	if (sc->names == NULL) {
1416 		rc = ENOTSUP;
1417 		goto done; /* error message displayed already */
1418 	}
1419 
1420 	/*
1421 	 * Do this really early, with the memory windows set up even before the
1422 	 * character device.  The userland tool's register i/o and mem read
1423 	 * will work even in "recovery mode".
1424 	 */
1425 	setup_memwin(sc);
1426 	if (t4_init_devlog_ncores_params(sc, 0) == 0)
1427 		fixup_devlog_params(sc);
1428 	make_dev_args_init(&mda);
1429 	mda.mda_devsw = &t4_cdevsw;
1430 	mda.mda_uid = UID_ROOT;
1431 	mda.mda_gid = GID_WHEEL;
1432 	mda.mda_mode = 0600;
1433 	mda.mda_si_drv1 = sc;
1434 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1435 	if (rc != 0)
1436 		device_printf(dev, "failed to create nexus char device: %d.\n",
1437 		    rc);
1438 
1439 	/* Go no further if recovery mode has been requested. */
1440 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1441 		device_printf(dev, "recovery mode.\n");
1442 		goto done;
1443 	}
1444 
1445 #if defined(__i386__)
1446 	if ((cpu_feature & CPUID_CX8) == 0) {
1447 		device_printf(dev, "64 bit atomics not available.\n");
1448 		rc = ENOTSUP;
1449 		goto done;
1450 	}
1451 #endif
1452 
1453 	/* Contact the firmware and try to become the master driver. */
1454 	rc = contact_firmware(sc);
1455 	if (rc != 0)
1456 		goto done; /* error message displayed already */
1457 	MPASS(sc->flags & FW_OK);
1458 
1459 	rc = get_params__pre_init(sc);
1460 	if (rc != 0)
1461 		goto done; /* error message displayed already */
1462 
1463 	if (sc->flags & MASTER_PF) {
1464 		rc = partition_resources(sc);
1465 		if (rc != 0)
1466 			goto done; /* error message displayed already */
1467 	}
1468 
1469 	rc = get_params__post_init(sc);
1470 	if (rc != 0)
1471 		goto done; /* error message displayed already */
1472 
1473 	rc = set_params__post_init(sc);
1474 	if (rc != 0)
1475 		goto done; /* error message displayed already */
1476 
1477 	rc = t4_map_bar_2(sc);
1478 	if (rc != 0)
1479 		goto done; /* error message displayed already */
1480 
1481 	rc = t4_adj_doorbells(sc);
1482 	if (rc != 0)
1483 		goto done; /* error message displayed already */
1484 
1485 	rc = t4_create_dma_tag(sc);
1486 	if (rc != 0)
1487 		goto done; /* error message displayed already */
1488 
1489 	/*
1490 	 * First pass over all the ports - allocate VIs and initialize some
1491 	 * basic parameters like mac address, port type, etc.
1492 	 */
1493 	for_each_port(sc, i) {
1494 		struct port_info *pi;
1495 
1496 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1497 		sc->port[i] = pi;
1498 
1499 		/* These must be set before t4_port_init */
1500 		pi->adapter = sc;
1501 		pi->port_id = i;
1502 		/*
1503 		 * XXX: vi[0] is special so we can't delay this allocation until
1504 		 * pi->nvi's final value is known.
1505 		 */
1506 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1507 		    M_ZERO | M_WAITOK);
1508 
1509 		/*
1510 		 * Allocate the "main" VI and initialize parameters
1511 		 * like mac addr.
1512 		 */
1513 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1514 		if (rc != 0) {
1515 			device_printf(dev, "unable to initialize port %d: %d\n",
1516 			    i, rc);
1517 			free(pi->vi, M_CXGBE);
1518 			free(pi, M_CXGBE);
1519 			sc->port[i] = NULL;
1520 			goto done;
1521 		}
1522 
1523 		if (is_bt(pi->port_type))
1524 			setbit(&sc->bt_map, pi->hw_port);
1525 		else
1526 			MPASS(!isset(&sc->bt_map, pi->hw_port));
1527 
1528 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1529 		    device_get_nameunit(dev), i);
1530 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1531 		for (j = 0; j < sc->params.tp.lb_nchan; j++)
1532 			sc->chan_map[pi->tx_chan + j] = i;
1533 		sc->port_map[pi->hw_port] = i;
1534 
1535 		/*
1536 		 * The MPS counter for FCS errors doesn't work correctly on the
1537 		 * T6 so we use the MAC counter here.  Which MAC is in use
1538 		 * depends on the link settings which will be known when the
1539 		 * link comes up.
1540 		 */
1541 		if (is_t6(sc))
1542 			pi->fcs_reg = -1;
1543 		else
1544 			pi->fcs_reg = A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L;
1545 		pi->fcs_base = 0;
1546 
1547 		/* All VIs on this port share this media. */
1548 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1549 		    cxgbe_media_status);
1550 
1551 		PORT_LOCK(pi);
1552 		init_link_config(pi);
1553 		fixup_link_config(pi);
1554 		build_medialist(pi);
1555 		if (fixed_ifmedia(pi))
1556 			pi->flags |= FIXED_IFMEDIA;
1557 		PORT_UNLOCK(pi);
1558 
1559 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1560 		    t4_ifnet_unit(sc, pi));
1561 		if (pi->dev == NULL) {
1562 			device_printf(dev,
1563 			    "failed to add device for port %d.\n", i);
1564 			rc = ENXIO;
1565 			goto done;
1566 		}
1567 		pi->vi[0].dev = pi->dev;
1568 		device_set_softc(pi->dev, pi);
1569 	}
1570 
1571 	/*
1572 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1573 	 */
1574 	nports = sc->params.nports;
1575 	rc = cfg_itype_and_nqueues(sc, &iaq);
1576 	if (rc != 0)
1577 		goto done; /* error message displayed already */
1578 
1579 	num_vis = iaq.num_vis;
1580 	sc->intr_type = iaq.intr_type;
1581 	sc->intr_count = iaq.nirq;
1582 
1583 	s = &sc->sge;
1584 	s->nctrlq = max(sc->params.nports, sc->params.ncores);
1585 	s->nrxq = nports * iaq.nrxq;
1586 	s->ntxq = nports * iaq.ntxq;
1587 	if (num_vis > 1) {
1588 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1589 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1590 	}
1591 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1592 	s->neq += nports;		/* ctrl queues: 1 per port */
1593 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1594 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1595 	if (is_offload(sc) || is_ethoffload(sc)) {
1596 		s->nofldtxq = nports * iaq.nofldtxq;
1597 		if (num_vis > 1)
1598 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1599 		s->neq += s->nofldtxq;
1600 
1601 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1602 		    M_CXGBE, M_ZERO | M_WAITOK);
1603 	}
1604 #endif
1605 #ifdef TCP_OFFLOAD
1606 	if (is_offload(sc)) {
1607 		s->nofldrxq = nports * iaq.nofldrxq;
1608 		if (num_vis > 1)
1609 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1610 		s->neq += s->nofldrxq;	/* free list */
1611 		s->niq += s->nofldrxq;
1612 
1613 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1614 		    M_CXGBE, M_ZERO | M_WAITOK);
1615 	}
1616 #endif
1617 #ifdef DEV_NETMAP
1618 	s->nnmrxq = 0;
1619 	s->nnmtxq = 0;
1620 	if (t4_native_netmap & NN_MAIN_VI) {
1621 		s->nnmrxq += nports * iaq.nnmrxq;
1622 		s->nnmtxq += nports * iaq.nnmtxq;
1623 	}
1624 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1625 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1626 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1627 	}
1628 	s->neq += s->nnmtxq + s->nnmrxq;
1629 	s->niq += s->nnmrxq;
1630 
1631 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1632 	    M_CXGBE, M_ZERO | M_WAITOK);
1633 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1634 	    M_CXGBE, M_ZERO | M_WAITOK);
1635 #endif
1636 	MPASS(s->niq <= s->iqmap_sz);
1637 	MPASS(s->neq <= s->eqmap_sz);
1638 
1639 	s->ctrlq = malloc(s->nctrlq * sizeof(struct sge_wrq), M_CXGBE,
1640 	    M_ZERO | M_WAITOK);
1641 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1642 	    M_ZERO | M_WAITOK);
1643 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1644 	    M_ZERO | M_WAITOK);
1645 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1646 	    M_ZERO | M_WAITOK);
1647 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1648 	    M_ZERO | M_WAITOK);
1649 
1650 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1651 	    M_ZERO | M_WAITOK);
1652 
1653 	t4_init_l2t(sc, M_WAITOK);
1654 	t4_init_smt(sc, M_WAITOK);
1655 	t4_init_tx_sched(sc);
1656 	t4_init_atid_table(sc);
1657 #ifdef RATELIMIT
1658 	t4_init_etid_table(sc);
1659 #endif
1660 #ifdef INET6
1661 	t4_init_clip_table(sc);
1662 #endif
1663 	if (sc->vres.key.size != 0)
1664 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1665 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1666 	t4_init_tpt(sc);
1667 
1668 	/*
1669 	 * Second pass over the ports.  This time we know the number of rx and
1670 	 * tx queues that each port should get.
1671 	 */
1672 	rqidx = tqidx = 0;
1673 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1674 	ofld_tqidx = 0;
1675 #endif
1676 #ifdef TCP_OFFLOAD
1677 	ofld_rqidx = 0;
1678 #endif
1679 #ifdef DEV_NETMAP
1680 	nm_rqidx = nm_tqidx = 0;
1681 #endif
1682 	for_each_port(sc, i) {
1683 		struct port_info *pi = sc->port[i];
1684 		struct vi_info *vi;
1685 
1686 		if (pi == NULL)
1687 			continue;
1688 
1689 		pi->nvi = num_vis;
1690 		for_each_vi(pi, j, vi) {
1691 			vi->pi = pi;
1692 			vi->adapter = sc;
1693 			vi->first_intr = -1;
1694 			vi->qsize_rxq = t4_qsize_rxq;
1695 			vi->qsize_txq = t4_qsize_txq;
1696 
1697 			vi->first_rxq = rqidx;
1698 			vi->first_txq = tqidx;
1699 			vi->tmr_idx = t4_tmr_idx;
1700 			vi->pktc_idx = t4_pktc_idx;
1701 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1702 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1703 
1704 			rqidx += vi->nrxq;
1705 			tqidx += vi->ntxq;
1706 
1707 			if (j == 0 && vi->ntxq > 1)
1708 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1709 			else
1710 				vi->rsrv_noflowq = 0;
1711 
1712 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1713 			vi->first_ofld_txq = ofld_tqidx;
1714 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1715 			ofld_tqidx += vi->nofldtxq;
1716 #endif
1717 #ifdef TCP_OFFLOAD
1718 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1719 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1720 			vi->first_ofld_rxq = ofld_rqidx;
1721 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1722 
1723 			ofld_rqidx += vi->nofldrxq;
1724 #endif
1725 #ifdef DEV_NETMAP
1726 			vi->first_nm_rxq = nm_rqidx;
1727 			vi->first_nm_txq = nm_tqidx;
1728 			if (j == 0) {
1729 				vi->nnmrxq = iaq.nnmrxq;
1730 				vi->nnmtxq = iaq.nnmtxq;
1731 			} else {
1732 				vi->nnmrxq = iaq.nnmrxq_vi;
1733 				vi->nnmtxq = iaq.nnmtxq_vi;
1734 			}
1735 			nm_rqidx += vi->nnmrxq;
1736 			nm_tqidx += vi->nnmtxq;
1737 #endif
1738 		}
1739 	}
1740 
1741 	rc = t4_setup_intr_handlers(sc);
1742 	if (rc != 0) {
1743 		device_printf(dev,
1744 		    "failed to setup interrupt handlers: %d\n", rc);
1745 		goto done;
1746 	}
1747 
1748 	bus_identify_children(dev);
1749 
1750 	/*
1751 	 * Ensure thread-safe mailbox access (in debug builds).
1752 	 *
1753 	 * So far this was the only thread accessing the mailbox but various
1754 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1755 	 * will access the mailbox from different threads.
1756 	 */
1757 	sc->flags |= CHK_MBOX_ACCESS;
1758 
1759 	bus_attach_children(dev);
1760 	t4_calibration_start(sc);
1761 
1762 	device_printf(dev,
1763 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1764 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1765 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1766 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1767 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1768 
1769 	t4_set_desc(sc);
1770 
1771 	notify_siblings(dev, 0);
1772 
1773 done:
1774 	if (rc != 0 && sc->cdev) {
1775 		/* cdev was created and so cxgbetool works; recover that way. */
1776 		device_printf(dev,
1777 		    "error during attach, adapter is now in recovery mode.\n");
1778 		rc = 0;
1779 	}
1780 
1781 	if (rc != 0)
1782 		t4_detach_common(dev);
1783 	else
1784 		t4_sysctls(sc);
1785 
1786 	return (rc);
1787 }
1788 
1789 static int
1790 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1791 {
1792 	struct adapter *sc;
1793 	struct port_info *pi;
1794 	int i;
1795 
1796 	sc = device_get_softc(bus);
1797 	for_each_port(sc, i) {
1798 		pi = sc->port[i];
1799 		if (pi != NULL && pi->dev == dev) {
1800 			sbuf_printf(sb, "port=%d", pi->port_id);
1801 			break;
1802 		}
1803 	}
1804 	return (0);
1805 }
1806 
1807 static int
1808 t4_ready(device_t dev)
1809 {
1810 	struct adapter *sc;
1811 
1812 	sc = device_get_softc(dev);
1813 	if (sc->flags & FW_OK)
1814 		return (0);
1815 	return (ENXIO);
1816 }
1817 
1818 static int
1819 t4_read_port_device(device_t dev, int port, device_t *child)
1820 {
1821 	struct adapter *sc;
1822 	struct port_info *pi;
1823 
1824 	sc = device_get_softc(dev);
1825 	if (port < 0 || port >= MAX_NPORTS)
1826 		return (EINVAL);
1827 	pi = sc->port[port];
1828 	if (pi == NULL || pi->dev == NULL)
1829 		return (ENXIO);
1830 	*child = pi->dev;
1831 	return (0);
1832 }
1833 
1834 static int
1835 notify_siblings(device_t dev, int detaching)
1836 {
1837 	device_t sibling;
1838 	int error, i;
1839 
1840 	error = 0;
1841 	for (i = 0; i < PCI_FUNCMAX; i++) {
1842 		if (i == pci_get_function(dev))
1843 			continue;
1844 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1845 		    pci_get_slot(dev), i);
1846 		if (sibling == NULL || !device_is_attached(sibling))
1847 			continue;
1848 		if (detaching)
1849 			error = T4_DETACH_CHILD(sibling);
1850 		else
1851 			(void)T4_ATTACH_CHILD(sibling);
1852 		if (error)
1853 			break;
1854 	}
1855 	return (error);
1856 }
1857 
1858 /*
1859  * Idempotent
1860  */
1861 static int
1862 t4_detach(device_t dev)
1863 {
1864 	int rc;
1865 
1866 	rc = notify_siblings(dev, 1);
1867 	if (rc) {
1868 		device_printf(dev,
1869 		    "failed to detach sibling devices: %d\n", rc);
1870 		return (rc);
1871 	}
1872 
1873 	return (t4_detach_common(dev));
1874 }
1875 
1876 int
1877 t4_detach_common(device_t dev)
1878 {
1879 	struct adapter *sc;
1880 	struct port_info *pi;
1881 	int i, rc;
1882 
1883 	sc = device_get_softc(dev);
1884 
1885 #ifdef TCP_OFFLOAD
1886 	rc = deactivate_all_uld(sc);
1887 	if (rc) {
1888 		device_printf(dev,
1889 		    "failed to detach upper layer drivers: %d\n", rc);
1890 		return (rc);
1891 	}
1892 #endif
1893 
1894 	if (sc->cdev) {
1895 		destroy_dev(sc->cdev);
1896 		sc->cdev = NULL;
1897 	}
1898 
1899 	sx_xlock(&t4_list_lock);
1900 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1901 	sx_xunlock(&t4_list_lock);
1902 
1903 	sc->flags &= ~CHK_MBOX_ACCESS;
1904 	if (sc->flags & FULL_INIT_DONE) {
1905 		if (!(sc->flags & IS_VF))
1906 			t4_intr_disable(sc);
1907 	}
1908 
1909 	if (device_is_attached(dev)) {
1910 		rc = bus_detach_children(dev);
1911 		if (rc) {
1912 			device_printf(dev,
1913 			    "failed to detach child devices: %d\n", rc);
1914 			return (rc);
1915 		}
1916 	}
1917 
1918 	for (i = 0; i < sc->intr_count; i++)
1919 		t4_free_irq(sc, &sc->irq[i]);
1920 
1921 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1922 		t4_free_tx_sched(sc);
1923 
1924 	for (i = 0; i < MAX_NPORTS; i++) {
1925 		pi = sc->port[i];
1926 		if (pi) {
1927 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1928 
1929 			mtx_destroy(&pi->pi_lock);
1930 			free(pi->vi, M_CXGBE);
1931 			free(pi, M_CXGBE);
1932 		}
1933 	}
1934 	callout_stop(&sc->cal_callout);
1935 	callout_drain(&sc->cal_callout);
1936 	device_delete_children(dev);
1937 	sysctl_ctx_free(&sc->ctx);
1938 	adapter_full_uninit(sc);
1939 
1940 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1941 		t4_fw_bye(sc, sc->mbox);
1942 
1943 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1944 		pci_release_msi(dev);
1945 
1946 	if (sc->regs_res)
1947 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1948 		    sc->regs_res);
1949 
1950 	if (sc->udbs_res)
1951 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1952 		    sc->udbs_res);
1953 
1954 	if (sc->msix_res)
1955 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1956 		    sc->msix_res);
1957 
1958 	if (sc->l2t)
1959 		t4_free_l2t(sc);
1960 	if (sc->smt)
1961 		t4_free_smt(sc->smt);
1962 	t4_free_atid_table(sc);
1963 #ifdef RATELIMIT
1964 	t4_free_etid_table(sc);
1965 #endif
1966 	if (sc->key_map)
1967 		vmem_destroy(sc->key_map);
1968 	t4_free_tpt(sc);
1969 #ifdef INET6
1970 	t4_destroy_clip_table(sc);
1971 #endif
1972 
1973 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1974 	free(sc->sge.ofld_txq, M_CXGBE);
1975 #endif
1976 #ifdef TCP_OFFLOAD
1977 	free(sc->sge.ofld_rxq, M_CXGBE);
1978 #endif
1979 #ifdef DEV_NETMAP
1980 	free(sc->sge.nm_rxq, M_CXGBE);
1981 	free(sc->sge.nm_txq, M_CXGBE);
1982 #endif
1983 	free(sc->irq, M_CXGBE);
1984 	free(sc->sge.rxq, M_CXGBE);
1985 	free(sc->sge.txq, M_CXGBE);
1986 	free(sc->sge.ctrlq, M_CXGBE);
1987 	free(sc->sge.iqmap, M_CXGBE);
1988 	free(sc->sge.eqmap, M_CXGBE);
1989 	free(sc->tids.ftid_tab, M_CXGBE);
1990 	free(sc->tids.hpftid_tab, M_CXGBE);
1991 	free_hftid_hash(&sc->tids);
1992 	free(sc->tids.tid_tab, M_CXGBE);
1993 	t4_destroy_dma_tag(sc);
1994 
1995 	callout_drain(&sc->ktls_tick);
1996 	callout_drain(&sc->sfl_callout);
1997 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1998 		mtx_destroy(&sc->tids.ftid_lock);
1999 		cv_destroy(&sc->tids.ftid_cv);
2000 	}
2001 	if (mtx_initialized(&sc->tids.atid_lock))
2002 		mtx_destroy(&sc->tids.atid_lock);
2003 	if (mtx_initialized(&sc->ifp_lock))
2004 		mtx_destroy(&sc->ifp_lock);
2005 
2006 	if (rw_initialized(&sc->policy_lock)) {
2007 		rw_destroy(&sc->policy_lock);
2008 #ifdef TCP_OFFLOAD
2009 		if (sc->policy != NULL)
2010 			free_offload_policy(sc->policy);
2011 #endif
2012 	}
2013 
2014 	for (i = 0; i < NUM_MEMWIN; i++) {
2015 		struct memwin *mw = &sc->memwin[i];
2016 
2017 		if (rw_initialized(&mw->mw_lock))
2018 			rw_destroy(&mw->mw_lock);
2019 	}
2020 
2021 	mtx_destroy(&sc->sfl_lock);
2022 	mtx_destroy(&sc->reg_lock);
2023 	mtx_destroy(&sc->sc_lock);
2024 
2025 	bzero(sc, sizeof(*sc));
2026 
2027 	return (0);
2028 }
2029 
2030 static inline int
2031 stop_adapter(struct adapter *sc)
2032 {
2033 	struct port_info *pi;
2034 	int i;
2035 
2036 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_STOPPED))) {
2037 		CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x, EALREADY\n",
2038 			 __func__, curthread, sc->flags, sc->error_flags);
2039 		return (EALREADY);
2040 	}
2041 	CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x\n", __func__, curthread,
2042 		 sc->flags, sc->error_flags);
2043 	t4_shutdown_adapter(sc);
2044 	for_each_port(sc, i) {
2045 		pi = sc->port[i];
2046 		if (pi == NULL)
2047 			continue;
2048 		PORT_LOCK(pi);
2049 		if (pi->up_vis > 0 && pi->link_cfg.link_ok) {
2050 			/*
2051 			 * t4_shutdown_adapter has already shut down all the
2052 			 * PHYs but it also disables interrupts and DMA so there
2053 			 * won't be a link interrupt.  Update the state manually
2054 			 * if the link was up previously and inform the kernel.
2055 			 */
2056 			pi->link_cfg.link_ok = false;
2057 			t4_os_link_changed(pi);
2058 		}
2059 		PORT_UNLOCK(pi);
2060 	}
2061 
2062 	return (0);
2063 }
2064 
2065 static inline int
2066 restart_adapter(struct adapter *sc)
2067 {
2068 	uint32_t val;
2069 
2070 	if (!atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_STOPPED))) {
2071 		CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x, EALREADY\n",
2072 			 __func__, curthread, sc->flags, sc->error_flags);
2073 		return (EALREADY);
2074 	}
2075 	CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x\n", __func__, curthread,
2076 		 sc->flags, sc->error_flags);
2077 
2078 	MPASS(hw_off_limits(sc));
2079 	MPASS((sc->flags & FW_OK) == 0);
2080 	MPASS((sc->flags & MASTER_PF) == 0);
2081 	MPASS(sc->reset_thread == NULL);
2082 
2083 	/*
2084 	 * The adapter is supposed to be back on PCIE with its config space and
2085 	 * BARs restored to their state before reset.  Register access via
2086 	 * t4_read_reg BAR0 should just work.
2087 	 */
2088 	sc->reset_thread = curthread;
2089 	val = t4_read_reg(sc, A_PL_WHOAMI);
2090 	if (val == 0xffffffff || val == 0xeeeeeeee) {
2091 		CH_ERR(sc, "%s: device registers not readable.\n", __func__);
2092 		sc->reset_thread = NULL;
2093 		atomic_set_int(&sc->error_flags, ADAP_STOPPED);
2094 		return (ENXIO);
2095 	}
2096 	atomic_clear_int(&sc->error_flags, ADAP_FATAL_ERR);
2097 	atomic_add_int(&sc->incarnation, 1);
2098 	atomic_add_int(&sc->num_resets, 1);
2099 
2100 	return (0);
2101 }
2102 
2103 static inline void
2104 set_adapter_hwstatus(struct adapter *sc, const bool usable)
2105 {
2106 	if (usable) {
2107 		/* Must be marked reusable by the designated thread. */
2108 		ASSERT_SYNCHRONIZED_OP(sc);
2109 		MPASS(sc->reset_thread == curthread);
2110 		mtx_lock(&sc->reg_lock);
2111 		atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2112 		mtx_unlock(&sc->reg_lock);
2113 	} else {
2114 		/* Mark the adapter totally off limits. */
2115 		begin_synchronized_op(sc, NULL, SLEEP_OK, "t4hwsts");
2116 		mtx_lock(&sc->reg_lock);
2117 		atomic_set_int(&sc->error_flags, HW_OFF_LIMITS);
2118 		mtx_unlock(&sc->reg_lock);
2119 		sc->flags &= ~(FW_OK | MASTER_PF);
2120 		sc->reset_thread = NULL;
2121 		end_synchronized_op(sc, 0);
2122 	}
2123 }
2124 
2125 static int
2126 stop_lld(struct adapter *sc)
2127 {
2128 	struct port_info *pi;
2129 	struct vi_info *vi;
2130 	if_t ifp;
2131 	struct sge_rxq *rxq;
2132 	struct sge_txq *txq;
2133 	struct sge_wrq *wrq;
2134 #ifdef TCP_OFFLOAD
2135 	struct sge_ofld_rxq *ofld_rxq;
2136 #endif
2137 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2138 	struct sge_ofld_txq *ofld_txq;
2139 #endif
2140 	int rc, i, j, k;
2141 
2142 	/*
2143 	 * XXX: Can there be a synch_op in progress that will hang because
2144 	 * hardware has been stopped?  We'll hang too and the solution will be
2145 	 * to use a version of begin_synch_op that wakes up existing synch_op
2146 	 * with errors.  Maybe stop_adapter should do this wakeup?
2147 	 *
2148 	 * I don't think any synch_op could get stranded waiting for DMA or
2149 	 * interrupt so I think we're okay here.  Remove this comment block
2150 	 * after testing.
2151 	 */
2152 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4slld");
2153 	if (rc != 0)
2154 		return (ENXIO);
2155 
2156 	/* Quiesce all activity. */
2157 	for_each_port(sc, i) {
2158 		pi = sc->port[i];
2159 		if (pi == NULL)
2160 			continue;
2161 		pi->vxlan_tcam_entry = false;
2162 		for_each_vi(pi, j, vi) {
2163 			vi->xact_addr_filt = -1;
2164 			mtx_lock(&vi->tick_mtx);
2165 			vi->flags |= VI_SKIP_STATS;
2166 			mtx_unlock(&vi->tick_mtx);
2167 			if (!(vi->flags & VI_INIT_DONE))
2168 				continue;
2169 
2170 			ifp = vi->ifp;
2171 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2172 				mtx_lock(&vi->tick_mtx);
2173 				callout_stop(&vi->tick);
2174 				mtx_unlock(&vi->tick_mtx);
2175 				callout_drain(&vi->tick);
2176 			}
2177 
2178 			/*
2179 			 * Note that the HW is not available.
2180 			 */
2181 			for_each_txq(vi, k, txq) {
2182 				TXQ_LOCK(txq);
2183 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
2184 				TXQ_UNLOCK(txq);
2185 			}
2186 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2187 			for_each_ofld_txq(vi, k, ofld_txq) {
2188 				TXQ_LOCK(&ofld_txq->wrq);
2189 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
2190 				TXQ_UNLOCK(&ofld_txq->wrq);
2191 			}
2192 #endif
2193 			for_each_rxq(vi, k, rxq) {
2194 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2195 			}
2196 #if defined(TCP_OFFLOAD)
2197 			for_each_ofld_rxq(vi, k, ofld_rxq) {
2198 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2199 			}
2200 #endif
2201 
2202 			quiesce_vi(vi);
2203 		}
2204 
2205 		if (sc->flags & FULL_INIT_DONE) {
2206 			/* Control queue */
2207 			wrq = &sc->sge.ctrlq[i];
2208 			TXQ_LOCK(wrq);
2209 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
2210 			TXQ_UNLOCK(wrq);
2211 			quiesce_wrq(wrq);
2212 		}
2213 
2214 		if (pi->flags & HAS_TRACEQ) {
2215 			pi->flags &= ~HAS_TRACEQ;
2216 			sc->traceq = -1;
2217 			sc->tracer_valid = 0;
2218 			sc->tracer_enabled = 0;
2219 		}
2220 	}
2221 	if (sc->flags & FULL_INIT_DONE) {
2222 		/* Firmware event queue */
2223 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
2224 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
2225 	}
2226 
2227 	/* Stop calibration */
2228 	callout_stop(&sc->cal_callout);
2229 	callout_drain(&sc->cal_callout);
2230 
2231 	if (t4_clock_gate_on_suspend) {
2232 		t4_set_reg_field(sc, A_PMU_PART_CG_PWRMODE, F_MA_PART_CGEN |
2233 		    F_LE_PART_CGEN | F_EDC1_PART_CGEN | F_EDC0_PART_CGEN |
2234 		    F_TP_PART_CGEN | F_PDP_PART_CGEN | F_SGE_PART_CGEN, 0);
2235 	}
2236 
2237 	end_synchronized_op(sc, 0);
2238 
2239 	stop_atid_allocator(sc);
2240 	t4_stop_l2t(sc);
2241 
2242 	return (rc);
2243 }
2244 
2245 int
2246 suspend_adapter(struct adapter *sc)
2247 {
2248 	stop_adapter(sc);
2249 	stop_lld(sc);
2250 #ifdef TCP_OFFLOAD
2251 	stop_all_uld(sc);
2252 #endif
2253 	set_adapter_hwstatus(sc, false);
2254 
2255 	return (0);
2256 }
2257 
2258 static int
2259 t4_suspend(device_t dev)
2260 {
2261 	struct adapter *sc = device_get_softc(dev);
2262 	int rc;
2263 
2264 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2265 	rc = suspend_adapter(sc);
2266 	CH_ALERT(sc, "%s end (thread %p).\n", __func__, curthread);
2267 
2268 	return (rc);
2269 }
2270 
2271 struct adapter_pre_reset_state {
2272 	u_int flags;
2273 	uint16_t nbmcaps;
2274 	uint16_t linkcaps;
2275 	uint16_t switchcaps;
2276 	uint16_t nvmecaps;
2277 	uint16_t niccaps;
2278 	uint16_t toecaps;
2279 	uint16_t rdmacaps;
2280 	uint16_t cryptocaps;
2281 	uint16_t iscsicaps;
2282 	uint16_t fcoecaps;
2283 
2284 	u_int cfcsum;
2285 	char cfg_file[32];
2286 
2287 	struct adapter_params params;
2288 	struct t4_virt_res vres;
2289 	struct tid_info tids;
2290 	struct sge sge;
2291 
2292 	int rawf_base;
2293 	int nrawf;
2294 
2295 };
2296 
2297 static void
2298 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2299 {
2300 
2301 	ASSERT_SYNCHRONIZED_OP(sc);
2302 
2303 	o->flags = sc->flags;
2304 
2305 	o->nbmcaps =  sc->nbmcaps;
2306 	o->linkcaps = sc->linkcaps;
2307 	o->switchcaps = sc->switchcaps;
2308 	o->nvmecaps = sc->nvmecaps;
2309 	o->niccaps = sc->niccaps;
2310 	o->toecaps = sc->toecaps;
2311 	o->rdmacaps = sc->rdmacaps;
2312 	o->cryptocaps = sc->cryptocaps;
2313 	o->iscsicaps = sc->iscsicaps;
2314 	o->fcoecaps = sc->fcoecaps;
2315 
2316 	o->cfcsum = sc->cfcsum;
2317 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2318 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2319 
2320 	o->params = sc->params;
2321 	o->vres = sc->vres;
2322 	o->tids = sc->tids;
2323 	o->sge = sc->sge;
2324 
2325 	o->rawf_base = sc->rawf_base;
2326 	o->nrawf = sc->nrawf;
2327 }
2328 
2329 static int
2330 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2331 {
2332 	int rc = 0;
2333 
2334 	ASSERT_SYNCHRONIZED_OP(sc);
2335 
2336 	/* Capabilities */
2337 #define COMPARE_CAPS(c) do { \
2338 	if (o->c##caps != sc->c##caps) { \
2339 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2340 		    sc->c##caps); \
2341 		rc = EINVAL; \
2342 	} \
2343 } while (0)
2344 	COMPARE_CAPS(nbm);
2345 	COMPARE_CAPS(link);
2346 	COMPARE_CAPS(switch);
2347 	COMPARE_CAPS(nvme);
2348 	COMPARE_CAPS(nic);
2349 	COMPARE_CAPS(toe);
2350 	COMPARE_CAPS(rdma);
2351 	COMPARE_CAPS(crypto);
2352 	COMPARE_CAPS(iscsi);
2353 	COMPARE_CAPS(fcoe);
2354 #undef COMPARE_CAPS
2355 
2356 	/* Firmware config file */
2357 	if (o->cfcsum != sc->cfcsum) {
2358 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2359 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2360 		rc = EINVAL;
2361 	}
2362 
2363 #define COMPARE_PARAM(p, name) do { \
2364 	if (o->p != sc->p) { \
2365 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2366 		rc = EINVAL; \
2367 	} \
2368 } while (0)
2369 	COMPARE_PARAM(sge.iq_start, iq_start);
2370 	COMPARE_PARAM(sge.eq_start, eq_start);
2371 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2372 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2373 	COMPARE_PARAM(tids.nftids, nftids);
2374 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2375 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2376 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2377 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2378 	COMPARE_PARAM(tids.tid_base, tid_base);
2379 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2380 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2381 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2382 	COMPARE_PARAM(rawf_base, rawf_base);
2383 	COMPARE_PARAM(nrawf, nrawf);
2384 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2385 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2386 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2387 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2388 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2389 	COMPARE_PARAM(tids.ntids, ntids);
2390 	COMPARE_PARAM(tids.etid_base, etid_base);
2391 	COMPARE_PARAM(tids.etid_end, etid_end);
2392 	COMPARE_PARAM(tids.netids, netids);
2393 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2394 	COMPARE_PARAM(params.ethoffload, ethoffload);
2395 	COMPARE_PARAM(tids.natids, natids);
2396 	COMPARE_PARAM(tids.stid_base, stid_base);
2397 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2398 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2399 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2400 	COMPARE_PARAM(vres.stag.start, stag_start);
2401 	COMPARE_PARAM(vres.stag.size, stag_size);
2402 	COMPARE_PARAM(vres.rq.start, rq_start);
2403 	COMPARE_PARAM(vres.rq.size, rq_size);
2404 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2405 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2406 	COMPARE_PARAM(vres.qp.start, qp_start);
2407 	COMPARE_PARAM(vres.qp.size, qp_size);
2408 	COMPARE_PARAM(vres.cq.start, cq_start);
2409 	COMPARE_PARAM(vres.cq.size, cq_size);
2410 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2411 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2412 	COMPARE_PARAM(vres.srq.start, srq_start);
2413 	COMPARE_PARAM(vres.srq.size, srq_size);
2414 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2415 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2416 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2417 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2418 	COMPARE_PARAM(vres.key.start, key_start);
2419 	COMPARE_PARAM(vres.key.size, key_size);
2420 #undef COMPARE_PARAM
2421 
2422 	return (rc);
2423 }
2424 
2425 static int
2426 restart_lld(struct adapter *sc)
2427 {
2428 	struct adapter_pre_reset_state *old_state = NULL;
2429 	struct port_info *pi;
2430 	struct vi_info *vi;
2431 	if_t ifp;
2432 	struct sge_txq *txq;
2433 	int rc, i, j, k;
2434 
2435 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rlld");
2436 	if (rc != 0)
2437 		return (ENXIO);
2438 
2439 	/* Restore memory window. */
2440 	setup_memwin(sc);
2441 
2442 	/* Go no further if recovery mode has been requested. */
2443 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2444 		CH_ALERT(sc, "%s: recovery mode during restart.\n", __func__);
2445 		rc = 0;
2446 		set_adapter_hwstatus(sc, true);
2447 		goto done;
2448 	}
2449 
2450 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2451 	save_caps_and_params(sc, old_state);
2452 
2453 	/* Reestablish contact with firmware and become the primary PF. */
2454 	rc = contact_firmware(sc);
2455 	if (rc != 0)
2456 		goto done; /* error message displayed already */
2457 	MPASS(sc->flags & FW_OK);
2458 
2459 	if (sc->flags & MASTER_PF) {
2460 		rc = partition_resources(sc);
2461 		if (rc != 0)
2462 			goto done; /* error message displayed already */
2463 	}
2464 
2465 	rc = get_params__post_init(sc);
2466 	if (rc != 0)
2467 		goto done; /* error message displayed already */
2468 
2469 	rc = set_params__post_init(sc);
2470 	if (rc != 0)
2471 		goto done; /* error message displayed already */
2472 
2473 	rc = compare_caps_and_params(sc, old_state);
2474 	if (rc != 0)
2475 		goto done; /* error message displayed already */
2476 
2477 	for_each_port(sc, i) {
2478 		pi = sc->port[i];
2479 		MPASS(pi != NULL);
2480 		MPASS(pi->vi != NULL);
2481 		MPASS(pi->vi[0].dev == pi->dev);
2482 
2483 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2484 		if (rc != 0) {
2485 			CH_ERR(sc,
2486 			    "failed to re-initialize port %d: %d\n", i, rc);
2487 			goto done;
2488 		}
2489 		MPASS(sc->chan_map[pi->tx_chan] == i);
2490 
2491 		PORT_LOCK(pi);
2492 		fixup_link_config(pi);
2493 		build_medialist(pi);
2494 		PORT_UNLOCK(pi);
2495 		for_each_vi(pi, j, vi) {
2496 			if (IS_MAIN_VI(vi))
2497 				continue;
2498 			rc = alloc_extra_vi(sc, pi, vi);
2499 			if (rc != 0) {
2500 				CH_ERR(vi,
2501 				    "failed to re-allocate extra VI: %d\n", rc);
2502 				goto done;
2503 			}
2504 		}
2505 	}
2506 
2507 	/*
2508 	 * Interrupts and queues are about to be enabled and other threads will
2509 	 * want to access the hardware too.  It is safe to do so.  Note that
2510 	 * this thread is still in the middle of a synchronized_op.
2511 	 */
2512 	set_adapter_hwstatus(sc, true);
2513 
2514 	if (sc->flags & FULL_INIT_DONE) {
2515 		rc = adapter_full_init(sc);
2516 		if (rc != 0) {
2517 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2518 			goto done;
2519 		}
2520 
2521 		if (sc->vxlan_refcount > 0)
2522 			enable_vxlan_rx(sc);
2523 
2524 		for_each_port(sc, i) {
2525 			pi = sc->port[i];
2526 			for_each_vi(pi, j, vi) {
2527 				mtx_lock(&vi->tick_mtx);
2528 				vi->flags &= ~VI_SKIP_STATS;
2529 				mtx_unlock(&vi->tick_mtx);
2530 				if (!(vi->flags & VI_INIT_DONE))
2531 					continue;
2532 				rc = vi_full_init(vi);
2533 				if (rc != 0) {
2534 					CH_ERR(vi, "failed to re-initialize "
2535 					    "interface: %d\n", rc);
2536 					goto done;
2537 				}
2538 				if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
2539 					sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
2540 					t4_set_trace_rss_control(sc, pi->tx_chan, sc->traceq);
2541 					pi->flags |= HAS_TRACEQ;
2542 				}
2543 
2544 				ifp = vi->ifp;
2545 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2546 					continue;
2547 				/*
2548 				 * Note that we do not setup multicast addresses
2549 				 * in the first pass.  This ensures that the
2550 				 * unicast DMACs for all VIs on all ports get an
2551 				 * MPS TCAM entry.
2552 				 */
2553 				rc = update_mac_settings(ifp, XGMAC_ALL &
2554 				    ~XGMAC_MCADDRS);
2555 				if (rc != 0) {
2556 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2557 					goto done;
2558 				}
2559 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2560 				    true);
2561 				if (rc != 0) {
2562 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2563 					goto done;
2564 				}
2565 				for_each_txq(vi, k, txq) {
2566 					TXQ_LOCK(txq);
2567 					txq->eq.flags |= EQ_ENABLED;
2568 					TXQ_UNLOCK(txq);
2569 				}
2570 				mtx_lock(&vi->tick_mtx);
2571 				callout_schedule(&vi->tick, hz);
2572 				mtx_unlock(&vi->tick_mtx);
2573 			}
2574 			PORT_LOCK(pi);
2575 			if (pi->up_vis > 0) {
2576 				t4_update_port_info(pi);
2577 				fixup_link_config(pi);
2578 				build_medialist(pi);
2579 				apply_link_config(pi);
2580 				if (pi->link_cfg.link_ok)
2581 					t4_os_link_changed(pi);
2582 			}
2583 			PORT_UNLOCK(pi);
2584 		}
2585 
2586 		/* Now reprogram the L2 multicast addresses. */
2587 		for_each_port(sc, i) {
2588 			pi = sc->port[i];
2589 			for_each_vi(pi, j, vi) {
2590 				if (!(vi->flags & VI_INIT_DONE))
2591 					continue;
2592 				ifp = vi->ifp;
2593 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2594 					continue;
2595 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2596 				if (rc != 0) {
2597 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2598 					rc = 0;	/* carry on */
2599 				}
2600 			}
2601 		}
2602 	}
2603 
2604 	/* Reset all calibration */
2605 	t4_calibration_start(sc);
2606 done:
2607 	end_synchronized_op(sc, 0);
2608 	free(old_state, M_CXGBE);
2609 
2610 	restart_atid_allocator(sc);
2611 	t4_restart_l2t(sc);
2612 
2613 	return (rc);
2614 }
2615 
2616 int
2617 resume_adapter(struct adapter *sc)
2618 {
2619 	restart_adapter(sc);
2620 	restart_lld(sc);
2621 #ifdef TCP_OFFLOAD
2622 	restart_all_uld(sc);
2623 #endif
2624 	return (0);
2625 }
2626 
2627 static int
2628 t4_resume(device_t dev)
2629 {
2630 	struct adapter *sc = device_get_softc(dev);
2631 	int rc;
2632 
2633 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2634 	rc = resume_adapter(sc);
2635 	CH_ALERT(sc, "%s end (thread %p).\n", __func__, curthread);
2636 
2637 	return (rc);
2638 }
2639 
2640 static int
2641 t4_reset_prepare(device_t dev, device_t child)
2642 {
2643 	struct adapter *sc = device_get_softc(dev);
2644 
2645 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2646 	return (0);
2647 }
2648 
2649 static int
2650 t4_reset_post(device_t dev, device_t child)
2651 {
2652 	struct adapter *sc = device_get_softc(dev);
2653 
2654 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2655 	return (0);
2656 }
2657 
2658 static int
2659 reset_adapter_with_pl_rst(struct adapter *sc)
2660 {
2661 	/* This is a t4_write_reg without the hw_off_limits check. */
2662 	MPASS(sc->error_flags & HW_OFF_LIMITS);
2663 	bus_space_write_4(sc->bt, sc->bh, A_PL_RST,
2664 			  F_PIORSTMODE | F_PIORST | F_AUTOPCIEPAUSE);
2665 	pause("pl_rst", 1 * hz);		/* Wait 1s for reset */
2666 	return (0);
2667 }
2668 
2669 static int
2670 reset_adapter_with_pcie_sbr(struct adapter *sc)
2671 {
2672 	device_t pdev = device_get_parent(sc->dev);
2673 	device_t gpdev = device_get_parent(pdev);
2674 	device_t *children;
2675 	int rc, i, lcap, lsta, nchildren;
2676 	uint32_t v;
2677 
2678 	rc = pci_find_cap(gpdev, PCIY_EXPRESS, &v);
2679 	if (rc != 0) {
2680 		CH_ERR(sc, "%s: pci_find_cap(%s, pcie) failed: %d\n", __func__,
2681 		    device_get_nameunit(gpdev), rc);
2682 		return (ENOTSUP);
2683 	}
2684 	lcap = v + PCIER_LINK_CAP;
2685 	lsta = v + PCIER_LINK_STA;
2686 
2687 	nchildren = 0;
2688 	device_get_children(pdev, &children, &nchildren);
2689 	for (i = 0; i < nchildren; i++)
2690 		pci_save_state(children[i]);
2691 	v = pci_read_config(gpdev, PCIR_BRIDGECTL_1, 2);
2692 	pci_write_config(gpdev, PCIR_BRIDGECTL_1, v | PCIB_BCR_SECBUS_RESET, 2);
2693 	pause("pcie_sbr1", hz / 10);	/* 100ms */
2694 	pci_write_config(gpdev, PCIR_BRIDGECTL_1, v, 2);
2695 	pause("pcie_sbr2", hz);		/* Wait 1s before restore_state. */
2696 	v = pci_read_config(gpdev, lsta, 2);
2697 	if (pci_read_config(gpdev, lcap, 2) & PCIEM_LINK_CAP_DL_ACTIVE)
2698 		rc = v & PCIEM_LINK_STA_DL_ACTIVE ? 0 : ETIMEDOUT;
2699 	else if (v & (PCIEM_LINK_STA_TRAINING_ERROR | PCIEM_LINK_STA_TRAINING))
2700 		rc = ETIMEDOUT;
2701 	else
2702 		rc = 0;
2703 	if (rc != 0)
2704 		CH_ERR(sc, "%s: PCIe link is down after reset, LINK_STA 0x%x\n",
2705 		    __func__, v);
2706 	else {
2707 		for (i = 0; i < nchildren; i++)
2708 			pci_restore_state(children[i]);
2709 	}
2710 	free(children, M_TEMP);
2711 
2712 	return (rc);
2713 }
2714 
2715 static int
2716 reset_adapter_with_pcie_link_bounce(struct adapter *sc)
2717 {
2718 	device_t pdev = device_get_parent(sc->dev);
2719 	device_t gpdev = device_get_parent(pdev);
2720 	device_t *children;
2721 	int rc, i, lcap, lctl, lsta, nchildren;
2722 	uint32_t v;
2723 
2724 	rc = pci_find_cap(gpdev, PCIY_EXPRESS, &v);
2725 	if (rc != 0) {
2726 		CH_ERR(sc, "%s: pci_find_cap(%s, pcie) failed: %d\n", __func__,
2727 		    device_get_nameunit(gpdev), rc);
2728 		return (ENOTSUP);
2729 	}
2730 	lcap = v + PCIER_LINK_CAP;
2731 	lctl = v + PCIER_LINK_CTL;
2732 	lsta = v + PCIER_LINK_STA;
2733 
2734 	nchildren = 0;
2735 	device_get_children(pdev, &children, &nchildren);
2736 	for (i = 0; i < nchildren; i++)
2737 		pci_save_state(children[i]);
2738 	v = pci_read_config(gpdev, lctl, 2);
2739 	pci_write_config(gpdev, lctl, v | PCIEM_LINK_CTL_LINK_DIS, 2);
2740 	pause("pcie_lnk1", 100 * hz / 1000);	/* 100ms */
2741 	pci_write_config(gpdev, lctl, v | PCIEM_LINK_CTL_RETRAIN_LINK, 2);
2742 	pause("pcie_lnk2", hz);		/* Wait 1s before restore_state. */
2743 	v = pci_read_config(gpdev, lsta, 2);
2744 	if (pci_read_config(gpdev, lcap, 2) & PCIEM_LINK_CAP_DL_ACTIVE)
2745 		rc = v & PCIEM_LINK_STA_DL_ACTIVE ? 0 : ETIMEDOUT;
2746 	else if (v & (PCIEM_LINK_STA_TRAINING_ERROR | PCIEM_LINK_STA_TRAINING))
2747 		rc = ETIMEDOUT;
2748 	else
2749 		rc = 0;
2750 	if (rc != 0)
2751 		CH_ERR(sc, "%s: PCIe link is down after reset, LINK_STA 0x%x\n",
2752 		    __func__, v);
2753 	else {
2754 		for (i = 0; i < nchildren; i++)
2755 			pci_restore_state(children[i]);
2756 	}
2757 	free(children, M_TEMP);
2758 
2759 	return (rc);
2760 }
2761 
2762 static inline int
2763 reset_adapter(struct adapter *sc)
2764 {
2765 	int rc;
2766 	const int reset_method = vm_guest == VM_GUEST_NO ? t4_reset_method : 0;
2767 
2768 	rc = suspend_adapter(sc);
2769 	if (rc != 0)
2770 		return (rc);
2771 
2772 	switch (reset_method) {
2773 	case 1:
2774 		rc = reset_adapter_with_pcie_sbr(sc);
2775 		break;
2776 	case 2:
2777 		rc = reset_adapter_with_pcie_link_bounce(sc);
2778 		break;
2779 	case 0:
2780 	default:
2781 		rc = reset_adapter_with_pl_rst(sc);
2782 		break;
2783 	}
2784 	if (rc == 0)
2785 		rc = resume_adapter(sc);
2786 	return (rc);
2787 }
2788 
2789 static void
2790 reset_adapter_task(void *arg, int pending)
2791 {
2792 	struct adapter *sc = arg;
2793 	const int flags = sc->flags;
2794 	const int eflags = sc->error_flags;
2795 	int rc;
2796 
2797 	if (pending > 1)
2798 		CH_ALERT(sc, "%s: pending %d\n", __func__, pending);
2799 	rc = reset_adapter(sc);
2800 	if (rc != 0) {
2801 		CH_ERR(sc, "adapter did not reset properly, rc = %d, "
2802 		       "flags 0x%08x -> 0x%08x, err_flags 0x%08x -> 0x%08x.\n",
2803 		       rc, flags, sc->flags, eflags, sc->error_flags);
2804 	}
2805 }
2806 
2807 static int
2808 cxgbe_probe(device_t dev)
2809 {
2810 	struct port_info *pi = device_get_softc(dev);
2811 
2812 	device_set_descf(dev, "port %d", pi->port_id);
2813 
2814 	return (BUS_PROBE_DEFAULT);
2815 }
2816 
2817 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2818     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2819     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2820     IFCAP_HWRXTSTMP | IFCAP_MEXTPG | IFCAP_NV)
2821 #define T4_CAP_ENABLE (T4_CAP)
2822 
2823 static void
2824 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2825 {
2826 	if_t ifp;
2827 	struct sbuf *sb;
2828 	struct sysctl_ctx_list *ctx = &vi->ctx;
2829 	struct sysctl_oid_list *children;
2830 	struct pfil_head_args pa;
2831 	struct adapter *sc = vi->adapter;
2832 
2833 	sysctl_ctx_init(ctx);
2834 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2835 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2836 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2837 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2838 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2839 #ifdef DEV_NETMAP
2840 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2841 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2842 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2843 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2844 #endif
2845 #ifdef TCP_OFFLOAD
2846 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2847 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2848 #endif
2849 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2850 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2851 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2852 #endif
2853 
2854 	vi->xact_addr_filt = -1;
2855 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2856 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2857 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2858 		vi->flags |= TX_USES_VM_WR;
2859 
2860 	/* Allocate an ifnet and set it up */
2861 	ifp = if_alloc_dev(IFT_ETHER, dev);
2862 	vi->ifp = ifp;
2863 	if_setsoftc(ifp, vi);
2864 
2865 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2866 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2867 
2868 	if_setinitfn(ifp, cxgbe_init);
2869 	if_setioctlfn(ifp, cxgbe_ioctl);
2870 	if_settransmitfn(ifp, cxgbe_transmit);
2871 	if_setqflushfn(ifp, cxgbe_qflush);
2872 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2873 		if_setgetcounterfn(ifp, vi_get_counter);
2874 	else
2875 		if_setgetcounterfn(ifp, cxgbe_get_counter);
2876 #if defined(KERN_TLS) || defined(RATELIMIT)
2877 	if_setsndtagallocfn(ifp, cxgbe_snd_tag_alloc);
2878 #endif
2879 #ifdef RATELIMIT
2880 	if_setratelimitqueryfn(ifp, cxgbe_ratelimit_query);
2881 #endif
2882 
2883 	if_setcapabilities(ifp, T4_CAP);
2884 	if_setcapenable(ifp, T4_CAP_ENABLE);
2885 	if_sethwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2886 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2887 	if (chip_id(sc) >= CHELSIO_T6) {
2888 		if_setcapabilitiesbit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2889 		if_setcapenablebit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2890 		if_sethwassistbits(ifp, CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2891 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2892 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN, 0);
2893 	}
2894 
2895 #ifdef TCP_OFFLOAD
2896 	if (vi->nofldrxq != 0)
2897 		if_setcapabilitiesbit(ifp, IFCAP_TOE, 0);
2898 #endif
2899 #ifdef RATELIMIT
2900 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2901 		if_setcapabilitiesbit(ifp, IFCAP_TXRTLMT, 0);
2902 		if_setcapenablebit(ifp, IFCAP_TXRTLMT, 0);
2903 	}
2904 #endif
2905 
2906 	if_sethwtsomax(ifp, IP_MAXPACKET);
2907 	if (vi->flags & TX_USES_VM_WR)
2908 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_VM_TSO);
2909 	else
2910 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_TSO);
2911 #ifdef RATELIMIT
2912 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2913 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_EO_TSO);
2914 #endif
2915 	if_sethwtsomaxsegsize(ifp, 65536);
2916 #ifdef KERN_TLS
2917 	if (is_ktls(sc)) {
2918 		if_setcapabilitiesbit(ifp, IFCAP_TXTLS, 0);
2919 		if (sc->flags & KERN_TLS_ON || !is_t6(sc))
2920 			if_setcapenablebit(ifp, IFCAP_TXTLS, 0);
2921 	}
2922 #endif
2923 
2924 	ether_ifattach(ifp, vi->hw_addr);
2925 #ifdef DEV_NETMAP
2926 	if (vi->nnmrxq != 0)
2927 		cxgbe_nm_attach(vi);
2928 #endif
2929 	sb = sbuf_new_auto();
2930 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2931 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2932 	switch (if_getcapabilities(ifp) & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2933 	case IFCAP_TOE:
2934 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2935 		break;
2936 	case IFCAP_TOE | IFCAP_TXRTLMT:
2937 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2938 		break;
2939 	case IFCAP_TXRTLMT:
2940 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2941 		break;
2942 	}
2943 #endif
2944 #ifdef TCP_OFFLOAD
2945 	if (if_getcapabilities(ifp) & IFCAP_TOE)
2946 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2947 #endif
2948 #ifdef DEV_NETMAP
2949 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2950 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2951 		    vi->nnmtxq, vi->nnmrxq);
2952 #endif
2953 	sbuf_finish(sb);
2954 	device_printf(dev, "%s\n", sbuf_data(sb));
2955 	sbuf_delete(sb);
2956 
2957 	vi_sysctls(vi);
2958 
2959 	pa.pa_version = PFIL_VERSION;
2960 	pa.pa_flags = PFIL_IN;
2961 	pa.pa_type = PFIL_TYPE_ETHERNET;
2962 	pa.pa_headname = if_name(ifp);
2963 	vi->pfil = pfil_head_register(&pa);
2964 }
2965 
2966 static int
2967 cxgbe_attach(device_t dev)
2968 {
2969 	struct port_info *pi = device_get_softc(dev);
2970 	struct adapter *sc = pi->adapter;
2971 	struct vi_info *vi;
2972 	int i;
2973 
2974 	sysctl_ctx_init(&pi->ctx);
2975 
2976 	cxgbe_vi_attach(dev, &pi->vi[0]);
2977 
2978 	for_each_vi(pi, i, vi) {
2979 		if (i == 0)
2980 			continue;
2981 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, DEVICE_UNIT_ANY);
2982 		if (vi->dev == NULL) {
2983 			device_printf(dev, "failed to add VI %d\n", i);
2984 			continue;
2985 		}
2986 		device_set_softc(vi->dev, vi);
2987 	}
2988 
2989 	cxgbe_sysctls(pi);
2990 
2991 	bus_attach_children(dev);
2992 
2993 	return (0);
2994 }
2995 
2996 static void
2997 cxgbe_vi_detach(struct vi_info *vi)
2998 {
2999 	if_t ifp = vi->ifp;
3000 
3001 	if (vi->pfil != NULL) {
3002 		pfil_head_unregister(vi->pfil);
3003 		vi->pfil = NULL;
3004 	}
3005 
3006 	ether_ifdetach(ifp);
3007 
3008 	/* Let detach proceed even if these fail. */
3009 #ifdef DEV_NETMAP
3010 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
3011 		cxgbe_nm_detach(vi);
3012 #endif
3013 	cxgbe_uninit_synchronized(vi);
3014 	callout_drain(&vi->tick);
3015 	mtx_destroy(&vi->tick_mtx);
3016 	sysctl_ctx_free(&vi->ctx);
3017 	vi_full_uninit(vi);
3018 
3019 	if_free(vi->ifp);
3020 	vi->ifp = NULL;
3021 }
3022 
3023 static int
3024 cxgbe_detach(device_t dev)
3025 {
3026 	struct port_info *pi = device_get_softc(dev);
3027 	struct adapter *sc = pi->adapter;
3028 	int rc;
3029 
3030 	/* Detach the extra VIs first. */
3031 	rc = bus_generic_detach(dev);
3032 	if (rc)
3033 		return (rc);
3034 
3035 	sysctl_ctx_free(&pi->ctx);
3036 	begin_vi_detach(sc, &pi->vi[0]);
3037 	if (pi->flags & HAS_TRACEQ) {
3038 		sc->traceq = -1;	/* cloner should not create ifnet */
3039 		t4_tracer_port_detach(sc);
3040 	}
3041 	cxgbe_vi_detach(&pi->vi[0]);
3042 	ifmedia_removeall(&pi->media);
3043 	end_vi_detach(sc, &pi->vi[0]);
3044 
3045 	return (0);
3046 }
3047 
3048 static void
3049 cxgbe_init(void *arg)
3050 {
3051 	struct vi_info *vi = arg;
3052 	struct adapter *sc = vi->adapter;
3053 
3054 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
3055 		return;
3056 	cxgbe_init_synchronized(vi);
3057 	end_synchronized_op(sc, 0);
3058 }
3059 
3060 static int
3061 cxgbe_ioctl(if_t ifp, unsigned long cmd, caddr_t data)
3062 {
3063 	int rc = 0, mtu, flags;
3064 	struct vi_info *vi = if_getsoftc(ifp);
3065 	struct port_info *pi = vi->pi;
3066 	struct adapter *sc = pi->adapter;
3067 	struct ifreq *ifr = (struct ifreq *)data;
3068 	uint32_t mask, mask2;
3069 
3070 	switch (cmd) {
3071 	case SIOCSIFMTU:
3072 		mtu = ifr->ifr_mtu;
3073 		if (mtu < ETHERMIN || mtu > MAX_MTU)
3074 			return (EINVAL);
3075 
3076 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
3077 		if (rc)
3078 			return (rc);
3079 		if_setmtu(ifp, mtu);
3080 		if (vi->flags & VI_INIT_DONE) {
3081 			t4_update_fl_bufsize(ifp);
3082 			if (hw_all_ok(sc) &&
3083 			    if_getdrvflags(ifp) & IFF_DRV_RUNNING)
3084 				rc = update_mac_settings(ifp, XGMAC_MTU);
3085 		}
3086 		end_synchronized_op(sc, 0);
3087 		break;
3088 
3089 	case SIOCSIFFLAGS:
3090 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
3091 		if (rc)
3092 			return (rc);
3093 
3094 		if (!hw_all_ok(sc)) {
3095 			rc = ENXIO;
3096 			goto fail;
3097 		}
3098 
3099 		if (if_getflags(ifp) & IFF_UP) {
3100 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
3101 				flags = vi->if_flags;
3102 				if ((if_getflags(ifp) ^ flags) &
3103 				    (IFF_PROMISC | IFF_ALLMULTI)) {
3104 					rc = update_mac_settings(ifp,
3105 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
3106 				}
3107 			} else {
3108 				rc = cxgbe_init_synchronized(vi);
3109 			}
3110 			vi->if_flags = if_getflags(ifp);
3111 		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
3112 			rc = cxgbe_uninit_synchronized(vi);
3113 		}
3114 		end_synchronized_op(sc, 0);
3115 		break;
3116 
3117 	case SIOCADDMULTI:
3118 	case SIOCDELMULTI:
3119 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
3120 		if (rc)
3121 			return (rc);
3122 		if (hw_all_ok(sc) && if_getdrvflags(ifp) & IFF_DRV_RUNNING)
3123 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
3124 		end_synchronized_op(sc, 0);
3125 		break;
3126 
3127 	case SIOCGIFCAPNV:
3128 		break;
3129 	case SIOCSIFCAPNV:
3130 	case SIOCSIFCAP:
3131 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
3132 		if (rc)
3133 			return (rc);
3134 
3135 		if (cmd == SIOCSIFCAPNV) {
3136 			const struct siocsifcapnv_driver_data *ifr_nv =
3137 			    (struct siocsifcapnv_driver_data *)data;
3138 
3139 			mask = ifr_nv->reqcap ^ if_getcapenable(ifp);
3140 			mask2 = ifr_nv->reqcap2 ^ if_getcapenable2(ifp);
3141 		} else {
3142 			mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
3143 			mask2 = 0;
3144 		}
3145 		if (mask & IFCAP_TXCSUM) {
3146 			if_togglecapenable(ifp, IFCAP_TXCSUM);
3147 			if_togglehwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP);
3148 
3149 			if (IFCAP_TSO4 & if_getcapenable(ifp) &&
3150 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
3151 				mask &= ~IFCAP_TSO4;
3152 				if_setcapenablebit(ifp, 0, IFCAP_TSO4);
3153 				if_printf(ifp,
3154 				    "tso4 disabled due to -txcsum.\n");
3155 			}
3156 		}
3157 		if (mask & IFCAP_TXCSUM_IPV6) {
3158 			if_togglecapenable(ifp, IFCAP_TXCSUM_IPV6);
3159 			if_togglehwassist(ifp, CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
3160 
3161 			if (IFCAP_TSO6 & if_getcapenable(ifp) &&
3162 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
3163 				mask &= ~IFCAP_TSO6;
3164 				if_setcapenablebit(ifp, 0, IFCAP_TSO6);
3165 				if_printf(ifp,
3166 				    "tso6 disabled due to -txcsum6.\n");
3167 			}
3168 		}
3169 		if (mask & IFCAP_RXCSUM)
3170 			if_togglecapenable(ifp, IFCAP_RXCSUM);
3171 		if (mask & IFCAP_RXCSUM_IPV6)
3172 			if_togglecapenable(ifp, IFCAP_RXCSUM_IPV6);
3173 
3174 		/*
3175 		 * Note that we leave CSUM_TSO alone (it is always set).  The
3176 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
3177 		 * sending a TSO request our way, so it's sufficient to toggle
3178 		 * IFCAP_TSOx only.
3179 		 */
3180 		if (mask & IFCAP_TSO4) {
3181 			if (!(IFCAP_TSO4 & if_getcapenable(ifp)) &&
3182 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
3183 				if_printf(ifp, "enable txcsum first.\n");
3184 				rc = EAGAIN;
3185 				goto fail;
3186 			}
3187 			if_togglecapenable(ifp, IFCAP_TSO4);
3188 		}
3189 		if (mask & IFCAP_TSO6) {
3190 			if (!(IFCAP_TSO6 & if_getcapenable(ifp)) &&
3191 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
3192 				if_printf(ifp, "enable txcsum6 first.\n");
3193 				rc = EAGAIN;
3194 				goto fail;
3195 			}
3196 			if_togglecapenable(ifp, IFCAP_TSO6);
3197 		}
3198 		if (mask & IFCAP_LRO) {
3199 #if defined(INET) || defined(INET6)
3200 			int i;
3201 			struct sge_rxq *rxq;
3202 
3203 			if_togglecapenable(ifp, IFCAP_LRO);
3204 			for_each_rxq(vi, i, rxq) {
3205 				if (if_getcapenable(ifp) & IFCAP_LRO)
3206 					rxq->iq.flags |= IQ_LRO_ENABLED;
3207 				else
3208 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
3209 			}
3210 #endif
3211 		}
3212 #ifdef TCP_OFFLOAD
3213 		if (mask & IFCAP_TOE) {
3214 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TOE;
3215 
3216 			rc = toe_capability(vi, enable);
3217 			if (rc != 0)
3218 				goto fail;
3219 
3220 			if_togglecapenable(ifp, mask);
3221 		}
3222 #endif
3223 		if (mask & IFCAP_VLAN_HWTAGGING) {
3224 			if_togglecapenable(ifp, IFCAP_VLAN_HWTAGGING);
3225 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
3226 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
3227 		}
3228 		if (mask & IFCAP_VLAN_MTU) {
3229 			if_togglecapenable(ifp, IFCAP_VLAN_MTU);
3230 
3231 			/* Need to find out how to disable auto-mtu-inflation */
3232 		}
3233 		if (mask & IFCAP_VLAN_HWTSO)
3234 			if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
3235 		if (mask & IFCAP_VLAN_HWCSUM)
3236 			if_togglecapenable(ifp, IFCAP_VLAN_HWCSUM);
3237 #ifdef RATELIMIT
3238 		if (mask & IFCAP_TXRTLMT)
3239 			if_togglecapenable(ifp, IFCAP_TXRTLMT);
3240 #endif
3241 		if (mask & IFCAP_HWRXTSTMP) {
3242 			int i;
3243 			struct sge_rxq *rxq;
3244 
3245 			if_togglecapenable(ifp, IFCAP_HWRXTSTMP);
3246 			for_each_rxq(vi, i, rxq) {
3247 				if (if_getcapenable(ifp) & IFCAP_HWRXTSTMP)
3248 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
3249 				else
3250 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
3251 			}
3252 		}
3253 		if (mask & IFCAP_MEXTPG)
3254 			if_togglecapenable(ifp, IFCAP_MEXTPG);
3255 
3256 #ifdef KERN_TLS
3257 		if (mask & IFCAP_TXTLS) {
3258 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TXTLS;
3259 
3260 			rc = ktls_capability(sc, enable);
3261 			if (rc != 0)
3262 				goto fail;
3263 
3264 			if_togglecapenable(ifp, mask & IFCAP_TXTLS);
3265 		}
3266 #endif
3267 		if (mask & IFCAP_VXLAN_HWCSUM) {
3268 			if_togglecapenable(ifp, IFCAP_VXLAN_HWCSUM);
3269 			if_togglehwassist(ifp, CSUM_INNER_IP6_UDP |
3270 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
3271 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP);
3272 		}
3273 		if (mask & IFCAP_VXLAN_HWTSO) {
3274 			if_togglecapenable(ifp, IFCAP_VXLAN_HWTSO);
3275 			if_togglehwassist(ifp, CSUM_INNER_IP6_TSO |
3276 			    CSUM_INNER_IP_TSO);
3277 		}
3278 
3279 		MPASS(mask2 == 0);
3280 		(void)mask2;
3281 
3282 #ifdef VLAN_CAPABILITIES
3283 		VLAN_CAPABILITIES(ifp);
3284 #endif
3285 fail:
3286 		end_synchronized_op(sc, 0);
3287 		break;
3288 
3289 	case SIOCSIFMEDIA:
3290 	case SIOCGIFMEDIA:
3291 	case SIOCGIFXMEDIA:
3292 		rc = ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
3293 		break;
3294 
3295 	case SIOCGI2C: {
3296 		struct ifi2creq i2c;
3297 
3298 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
3299 		if (rc != 0)
3300 			break;
3301 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
3302 			rc = EPERM;
3303 			break;
3304 		}
3305 		if (i2c.len > sizeof(i2c.data)) {
3306 			rc = EINVAL;
3307 			break;
3308 		}
3309 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
3310 		if (rc)
3311 			return (rc);
3312 		if (!hw_all_ok(sc))
3313 			rc = ENXIO;
3314 		else
3315 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
3316 			    i2c.offset, i2c.len, &i2c.data[0]);
3317 		end_synchronized_op(sc, 0);
3318 		if (rc == 0)
3319 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
3320 		break;
3321 	}
3322 
3323 	default:
3324 		rc = ether_ioctl(ifp, cmd, data);
3325 	}
3326 
3327 	return (rc);
3328 }
3329 
3330 static int
3331 cxgbe_transmit(if_t ifp, struct mbuf *m)
3332 {
3333 	struct vi_info *vi = if_getsoftc(ifp);
3334 	struct port_info *pi = vi->pi;
3335 	struct adapter *sc;
3336 	struct sge_txq *txq;
3337 	void *items[1];
3338 	int rc;
3339 
3340 	M_ASSERTPKTHDR(m);
3341 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
3342 #if defined(KERN_TLS) || defined(RATELIMIT)
3343 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
3344 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
3345 #endif
3346 
3347 	if (__predict_false(pi->link_cfg.link_ok == false)) {
3348 		m_freem(m);
3349 		return (ENETDOWN);
3350 	}
3351 
3352 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
3353 	if (__predict_false(rc != 0)) {
3354 		if (__predict_true(rc == EINPROGRESS)) {
3355 			/* queued by parse_pkt */
3356 			MPASS(m != NULL);
3357 			return (0);
3358 		}
3359 
3360 		MPASS(m == NULL);			/* was freed already */
3361 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
3362 		return (rc);
3363 	}
3364 
3365 	/* Select a txq. */
3366 	sc = vi->adapter;
3367 	txq = &sc->sge.txq[vi->first_txq];
3368 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
3369 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
3370 		    vi->rsrv_noflowq);
3371 
3372 	items[0] = m;
3373 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
3374 	if (__predict_false(rc != 0))
3375 		m_freem(m);
3376 
3377 	return (rc);
3378 }
3379 
3380 static void
3381 cxgbe_qflush(if_t ifp)
3382 {
3383 	struct vi_info *vi = if_getsoftc(ifp);
3384 	struct sge_txq *txq;
3385 	int i;
3386 
3387 	/* queues do not exist if !VI_INIT_DONE. */
3388 	if (vi->flags & VI_INIT_DONE) {
3389 		for_each_txq(vi, i, txq) {
3390 			TXQ_LOCK(txq);
3391 			txq->eq.flags |= EQ_QFLUSH;
3392 			TXQ_UNLOCK(txq);
3393 			while (!mp_ring_is_idle(txq->r)) {
3394 				mp_ring_check_drainage(txq->r, 4096);
3395 				pause("qflush", 1);
3396 			}
3397 			TXQ_LOCK(txq);
3398 			txq->eq.flags &= ~EQ_QFLUSH;
3399 			TXQ_UNLOCK(txq);
3400 		}
3401 	}
3402 	if_qflush(ifp);
3403 }
3404 
3405 static uint64_t
3406 vi_get_counter(if_t ifp, ift_counter c)
3407 {
3408 	struct vi_info *vi = if_getsoftc(ifp);
3409 	struct fw_vi_stats_vf *s = &vi->stats;
3410 
3411 	mtx_lock(&vi->tick_mtx);
3412 	vi_refresh_stats(vi);
3413 	mtx_unlock(&vi->tick_mtx);
3414 
3415 	switch (c) {
3416 	case IFCOUNTER_IPACKETS:
3417 		return (s->rx_bcast_frames + s->rx_mcast_frames +
3418 		    s->rx_ucast_frames);
3419 	case IFCOUNTER_IERRORS:
3420 		return (s->rx_err_frames);
3421 	case IFCOUNTER_OPACKETS:
3422 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3423 		    s->tx_ucast_frames + s->tx_offload_frames);
3424 	case IFCOUNTER_OERRORS:
3425 		return (s->tx_drop_frames);
3426 	case IFCOUNTER_IBYTES:
3427 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3428 		    s->rx_ucast_bytes);
3429 	case IFCOUNTER_OBYTES:
3430 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3431 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3432 	case IFCOUNTER_IMCASTS:
3433 		return (s->rx_mcast_frames);
3434 	case IFCOUNTER_OMCASTS:
3435 		return (s->tx_mcast_frames);
3436 	case IFCOUNTER_OQDROPS: {
3437 		uint64_t drops;
3438 
3439 		drops = 0;
3440 		if (vi->flags & VI_INIT_DONE) {
3441 			int i;
3442 			struct sge_txq *txq;
3443 
3444 			for_each_txq(vi, i, txq)
3445 				drops += counter_u64_fetch(txq->r->dropped);
3446 		}
3447 
3448 		return (drops);
3449 
3450 	}
3451 
3452 	default:
3453 		return (if_get_counter_default(ifp, c));
3454 	}
3455 }
3456 
3457 static uint64_t
3458 cxgbe_get_counter(if_t ifp, ift_counter c)
3459 {
3460 	struct vi_info *vi = if_getsoftc(ifp);
3461 	struct port_info *pi = vi->pi;
3462 	struct port_stats *s = &pi->stats;
3463 
3464 	mtx_lock(&vi->tick_mtx);
3465 	cxgbe_refresh_stats(vi);
3466 	mtx_unlock(&vi->tick_mtx);
3467 
3468 	switch (c) {
3469 	case IFCOUNTER_IPACKETS:
3470 		return (s->rx_frames);
3471 
3472 	case IFCOUNTER_IERRORS:
3473 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3474 		    s->rx_fcs_err + s->rx_len_err);
3475 
3476 	case IFCOUNTER_OPACKETS:
3477 		return (s->tx_frames);
3478 
3479 	case IFCOUNTER_OERRORS:
3480 		return (s->tx_error_frames);
3481 
3482 	case IFCOUNTER_IBYTES:
3483 		return (s->rx_octets);
3484 
3485 	case IFCOUNTER_OBYTES:
3486 		return (s->tx_octets);
3487 
3488 	case IFCOUNTER_IMCASTS:
3489 		return (s->rx_mcast_frames);
3490 
3491 	case IFCOUNTER_OMCASTS:
3492 		return (s->tx_mcast_frames);
3493 
3494 	case IFCOUNTER_IQDROPS:
3495 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3496 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3497 		    s->rx_trunc3 + pi->tnl_cong_drops);
3498 
3499 	case IFCOUNTER_OQDROPS: {
3500 		uint64_t drops;
3501 
3502 		drops = s->tx_drop;
3503 		if (vi->flags & VI_INIT_DONE) {
3504 			int i;
3505 			struct sge_txq *txq;
3506 
3507 			for_each_txq(vi, i, txq)
3508 				drops += counter_u64_fetch(txq->r->dropped);
3509 		}
3510 
3511 		return (drops);
3512 
3513 	}
3514 
3515 	default:
3516 		return (if_get_counter_default(ifp, c));
3517 	}
3518 }
3519 
3520 #if defined(KERN_TLS) || defined(RATELIMIT)
3521 static int
3522 cxgbe_snd_tag_alloc(if_t ifp, union if_snd_tag_alloc_params *params,
3523     struct m_snd_tag **pt)
3524 {
3525 	int error;
3526 
3527 	switch (params->hdr.type) {
3528 #ifdef RATELIMIT
3529 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3530 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3531 		break;
3532 #endif
3533 #ifdef KERN_TLS
3534 	case IF_SND_TAG_TYPE_TLS:
3535 	{
3536 		struct vi_info *vi = if_getsoftc(ifp);
3537 
3538 		if (is_t6(vi->pi->adapter))
3539 			error = t6_tls_tag_alloc(ifp, params, pt);
3540 		else
3541 			error = t7_tls_tag_alloc(ifp, params, pt);
3542 		break;
3543 	}
3544 #endif
3545 	default:
3546 		error = EOPNOTSUPP;
3547 	}
3548 	return (error);
3549 }
3550 #endif
3551 
3552 /*
3553  * The kernel picks a media from the list we had provided but we still validate
3554  * the requeste.
3555  */
3556 int
3557 cxgbe_media_change(if_t ifp)
3558 {
3559 	struct vi_info *vi = if_getsoftc(ifp);
3560 	struct port_info *pi = vi->pi;
3561 	struct ifmedia *ifm = &pi->media;
3562 	struct link_config *lc = &pi->link_cfg;
3563 	struct adapter *sc = pi->adapter;
3564 	int rc;
3565 
3566 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3567 	if (rc != 0)
3568 		return (rc);
3569 	PORT_LOCK(pi);
3570 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3571 		/* ifconfig .. media autoselect */
3572 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3573 			rc = ENOTSUP; /* AN not supported by transceiver */
3574 			goto done;
3575 		}
3576 		lc->requested_aneg = AUTONEG_ENABLE;
3577 		lc->requested_speed = 0;
3578 		lc->requested_fc |= PAUSE_AUTONEG;
3579 	} else {
3580 		lc->requested_aneg = AUTONEG_DISABLE;
3581 		lc->requested_speed =
3582 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3583 		lc->requested_fc = 0;
3584 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3585 			lc->requested_fc |= PAUSE_RX;
3586 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3587 			lc->requested_fc |= PAUSE_TX;
3588 	}
3589 	if (pi->up_vis > 0 && hw_all_ok(sc)) {
3590 		fixup_link_config(pi);
3591 		rc = apply_link_config(pi);
3592 	}
3593 done:
3594 	PORT_UNLOCK(pi);
3595 	end_synchronized_op(sc, 0);
3596 	return (rc);
3597 }
3598 
3599 /*
3600  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3601  * given speed.
3602  */
3603 static int
3604 port_mword(struct port_info *pi, uint32_t speed)
3605 {
3606 
3607 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3608 	MPASS(powerof2(speed));
3609 
3610 	switch(pi->port_type) {
3611 	case FW_PORT_TYPE_BT_SGMII:
3612 	case FW_PORT_TYPE_BT_XFI:
3613 	case FW_PORT_TYPE_BT_XAUI:
3614 		/* BaseT */
3615 		switch (speed) {
3616 		case FW_PORT_CAP32_SPEED_100M:
3617 			return (IFM_100_T);
3618 		case FW_PORT_CAP32_SPEED_1G:
3619 			return (IFM_1000_T);
3620 		case FW_PORT_CAP32_SPEED_10G:
3621 			return (IFM_10G_T);
3622 		}
3623 		break;
3624 	case FW_PORT_TYPE_KX4:
3625 		if (speed == FW_PORT_CAP32_SPEED_10G)
3626 			return (IFM_10G_KX4);
3627 		break;
3628 	case FW_PORT_TYPE_CX4:
3629 		if (speed == FW_PORT_CAP32_SPEED_10G)
3630 			return (IFM_10G_CX4);
3631 		break;
3632 	case FW_PORT_TYPE_KX:
3633 		if (speed == FW_PORT_CAP32_SPEED_1G)
3634 			return (IFM_1000_KX);
3635 		break;
3636 	case FW_PORT_TYPE_KR:
3637 	case FW_PORT_TYPE_BP_AP:
3638 	case FW_PORT_TYPE_BP4_AP:
3639 	case FW_PORT_TYPE_BP40_BA:
3640 	case FW_PORT_TYPE_KR4_100G:
3641 	case FW_PORT_TYPE_KR_SFP28:
3642 	case FW_PORT_TYPE_KR_XLAUI:
3643 		switch (speed) {
3644 		case FW_PORT_CAP32_SPEED_1G:
3645 			return (IFM_1000_KX);
3646 		case FW_PORT_CAP32_SPEED_10G:
3647 			return (IFM_10G_KR);
3648 		case FW_PORT_CAP32_SPEED_25G:
3649 			return (IFM_25G_KR);
3650 		case FW_PORT_CAP32_SPEED_40G:
3651 			return (IFM_40G_KR4);
3652 		case FW_PORT_CAP32_SPEED_50G:
3653 			return (IFM_50G_KR2);
3654 		case FW_PORT_CAP32_SPEED_100G:
3655 			return (IFM_100G_KR4);
3656 		}
3657 		break;
3658 	case FW_PORT_TYPE_FIBER_XFI:
3659 	case FW_PORT_TYPE_FIBER_XAUI:
3660 	case FW_PORT_TYPE_SFP:
3661 	case FW_PORT_TYPE_QSFP_10G:
3662 	case FW_PORT_TYPE_QSA:
3663 	case FW_PORT_TYPE_QSFP:
3664 	case FW_PORT_TYPE_CR4_QSFP:
3665 	case FW_PORT_TYPE_CR_QSFP:
3666 	case FW_PORT_TYPE_CR2_QSFP:
3667 	case FW_PORT_TYPE_SFP28:
3668 	case FW_PORT_TYPE_SFP56:
3669 	case FW_PORT_TYPE_QSFP56:
3670 	case FW_PORT_TYPE_QSFPDD:
3671 		/* Pluggable transceiver */
3672 		switch (pi->mod_type) {
3673 		case FW_PORT_MOD_TYPE_LR:
3674 		case FW_PORT_MOD_TYPE_LR_SIMPLEX:
3675 			switch (speed) {
3676 			case FW_PORT_CAP32_SPEED_1G:
3677 				return (IFM_1000_LX);
3678 			case FW_PORT_CAP32_SPEED_10G:
3679 				return (IFM_10G_LR);
3680 			case FW_PORT_CAP32_SPEED_25G:
3681 				return (IFM_25G_LR);
3682 			case FW_PORT_CAP32_SPEED_40G:
3683 				return (IFM_40G_LR4);
3684 			case FW_PORT_CAP32_SPEED_50G:
3685 				return (IFM_50G_LR2);
3686 			case FW_PORT_CAP32_SPEED_100G:
3687 				return (IFM_100G_LR4);
3688 			case FW_PORT_CAP32_SPEED_200G:
3689 				return (IFM_200G_LR4);
3690 			case FW_PORT_CAP32_SPEED_400G:
3691 				return (IFM_400G_LR8);
3692 			}
3693 			break;
3694 		case FW_PORT_MOD_TYPE_SR:
3695 			switch (speed) {
3696 			case FW_PORT_CAP32_SPEED_1G:
3697 				return (IFM_1000_SX);
3698 			case FW_PORT_CAP32_SPEED_10G:
3699 				return (IFM_10G_SR);
3700 			case FW_PORT_CAP32_SPEED_25G:
3701 				return (IFM_25G_SR);
3702 			case FW_PORT_CAP32_SPEED_40G:
3703 				return (IFM_40G_SR4);
3704 			case FW_PORT_CAP32_SPEED_50G:
3705 				return (IFM_50G_SR2);
3706 			case FW_PORT_CAP32_SPEED_100G:
3707 				return (IFM_100G_SR4);
3708 			case FW_PORT_CAP32_SPEED_200G:
3709 				return (IFM_200G_SR4);
3710 			case FW_PORT_CAP32_SPEED_400G:
3711 				return (IFM_400G_SR8);
3712 			}
3713 			break;
3714 		case FW_PORT_MOD_TYPE_ER:
3715 			if (speed == FW_PORT_CAP32_SPEED_10G)
3716 				return (IFM_10G_ER);
3717 			break;
3718 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3719 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3720 			switch (speed) {
3721 			case FW_PORT_CAP32_SPEED_1G:
3722 				return (IFM_1000_CX);
3723 			case FW_PORT_CAP32_SPEED_10G:
3724 				return (IFM_10G_TWINAX);
3725 			case FW_PORT_CAP32_SPEED_25G:
3726 				return (IFM_25G_CR);
3727 			case FW_PORT_CAP32_SPEED_40G:
3728 				return (IFM_40G_CR4);
3729 			case FW_PORT_CAP32_SPEED_50G:
3730 				return (IFM_50G_CR2);
3731 			case FW_PORT_CAP32_SPEED_100G:
3732 				return (IFM_100G_CR4);
3733 			case FW_PORT_CAP32_SPEED_200G:
3734 				return (IFM_200G_CR4_PAM4);
3735 			case FW_PORT_CAP32_SPEED_400G:
3736 				return (IFM_400G_CR8);
3737 			}
3738 			break;
3739 		case FW_PORT_MOD_TYPE_LRM:
3740 			if (speed == FW_PORT_CAP32_SPEED_10G)
3741 				return (IFM_10G_LRM);
3742 			break;
3743 		case FW_PORT_MOD_TYPE_DR:
3744 			if (speed == FW_PORT_CAP32_SPEED_100G)
3745 				return (IFM_100G_DR);
3746 			if (speed == FW_PORT_CAP32_SPEED_200G)
3747 				return (IFM_200G_DR4);
3748 			if (speed == FW_PORT_CAP32_SPEED_400G)
3749 				return (IFM_400G_DR4);
3750 			break;
3751 		case FW_PORT_MOD_TYPE_NA:
3752 			MPASS(0);	/* Not pluggable? */
3753 			/* fall through */
3754 		case FW_PORT_MOD_TYPE_ERROR:
3755 		case FW_PORT_MOD_TYPE_UNKNOWN:
3756 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3757 			break;
3758 		case FW_PORT_MOD_TYPE_NONE:
3759 			return (IFM_NONE);
3760 		}
3761 		break;
3762 	case M_FW_PORT_CMD_PTYPE:	/* FW_PORT_TYPE_NONE for old firmware */
3763 		if (chip_id(pi->adapter) >= CHELSIO_T7)
3764 			return (IFM_UNKNOWN);
3765 		/* fall through */
3766 	case FW_PORT_TYPE_NONE:
3767 		return (IFM_NONE);
3768 	}
3769 
3770 	return (IFM_UNKNOWN);
3771 }
3772 
3773 void
3774 cxgbe_media_status(if_t ifp, struct ifmediareq *ifmr)
3775 {
3776 	struct vi_info *vi = if_getsoftc(ifp);
3777 	struct port_info *pi = vi->pi;
3778 	struct adapter *sc = pi->adapter;
3779 	struct link_config *lc = &pi->link_cfg;
3780 
3781 	if (begin_synchronized_op(sc, vi , SLEEP_OK | INTR_OK, "t4med") != 0)
3782 		return;
3783 	PORT_LOCK(pi);
3784 
3785 	if (pi->up_vis == 0 && hw_all_ok(sc)) {
3786 		/*
3787 		 * If all the interfaces are administratively down the firmware
3788 		 * does not report transceiver changes.  Refresh port info here
3789 		 * so that ifconfig displays accurate ifmedia at all times.
3790 		 * This is the only reason we have a synchronized op in this
3791 		 * function.  Just PORT_LOCK would have been enough otherwise.
3792 		 */
3793 		t4_update_port_info(pi);
3794 		build_medialist(pi);
3795 	}
3796 
3797 	/* ifm_status */
3798 	ifmr->ifm_status = IFM_AVALID;
3799 	if (lc->link_ok == false)
3800 		goto done;
3801 	ifmr->ifm_status |= IFM_ACTIVE;
3802 
3803 	/* ifm_active */
3804 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3805 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3806 	if (lc->fc & PAUSE_RX)
3807 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3808 	if (lc->fc & PAUSE_TX)
3809 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3810 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3811 done:
3812 	PORT_UNLOCK(pi);
3813 	end_synchronized_op(sc, 0);
3814 }
3815 
3816 static int
3817 vcxgbe_probe(device_t dev)
3818 {
3819 	struct vi_info *vi = device_get_softc(dev);
3820 
3821 	device_set_descf(dev, "port %d vi %td", vi->pi->port_id,
3822 	    vi - vi->pi->vi);
3823 
3824 	return (BUS_PROBE_DEFAULT);
3825 }
3826 
3827 static int
3828 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3829 {
3830 	int func, index, rc;
3831 	uint32_t param, val;
3832 
3833 	ASSERT_SYNCHRONIZED_OP(sc);
3834 
3835 	index = vi - pi->vi;
3836 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3837 	KASSERT(index < nitems(vi_mac_funcs),
3838 	    ("%s: VI %s doesn't have a MAC func", __func__,
3839 	    device_get_nameunit(vi->dev)));
3840 	func = vi_mac_funcs[index];
3841 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->hw_port, sc->pf, 0, 1,
3842 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3843 	if (rc < 0) {
3844 		CH_ERR(vi, "failed to allocate virtual interface %d"
3845 		    "for port %d: %d\n", index, pi->port_id, -rc);
3846 		return (-rc);
3847 	}
3848 	vi->viid = rc;
3849 
3850 	if (vi->rss_size == 1) {
3851 		/*
3852 		 * This VI didn't get a slice of the RSS table.  Reduce the
3853 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3854 		 * configuration file (nvi, rssnvi for this PF) if this is a
3855 		 * problem.
3856 		 */
3857 		device_printf(vi->dev, "RSS table not available.\n");
3858 		vi->rss_base = 0xffff;
3859 
3860 		return (0);
3861 	}
3862 
3863 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3864 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3865 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3866 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3867 	if (rc)
3868 		vi->rss_base = 0xffff;
3869 	else {
3870 		MPASS((val >> 16) == vi->rss_size);
3871 		vi->rss_base = val & 0xffff;
3872 	}
3873 
3874 	return (0);
3875 }
3876 
3877 static int
3878 vcxgbe_attach(device_t dev)
3879 {
3880 	struct vi_info *vi;
3881 	struct port_info *pi;
3882 	struct adapter *sc;
3883 	int rc;
3884 
3885 	vi = device_get_softc(dev);
3886 	pi = vi->pi;
3887 	sc = pi->adapter;
3888 
3889 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3890 	if (rc)
3891 		return (rc);
3892 	rc = alloc_extra_vi(sc, pi, vi);
3893 	end_synchronized_op(sc, 0);
3894 	if (rc)
3895 		return (rc);
3896 
3897 	cxgbe_vi_attach(dev, vi);
3898 
3899 	return (0);
3900 }
3901 
3902 static int
3903 vcxgbe_detach(device_t dev)
3904 {
3905 	struct vi_info *vi;
3906 	struct adapter *sc;
3907 
3908 	vi = device_get_softc(dev);
3909 	sc = vi->adapter;
3910 
3911 	begin_vi_detach(sc, vi);
3912 	cxgbe_vi_detach(vi);
3913 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3914 	end_vi_detach(sc, vi);
3915 
3916 	return (0);
3917 }
3918 
3919 static struct callout fatal_callout;
3920 static struct taskqueue *reset_tq;
3921 
3922 static void
3923 delayed_panic(void *arg)
3924 {
3925 	struct adapter *sc = arg;
3926 
3927 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3928 }
3929 
3930 static void
3931 fatal_error_task(void *arg, int pending)
3932 {
3933 	struct adapter *sc = arg;
3934 	int rc;
3935 
3936 	if (atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_CIM_ERR))) {
3937 		dump_cim_regs(sc);
3938 		dump_cimla(sc);
3939 		dump_devlog(sc);
3940 	}
3941 
3942 	if (t4_reset_on_fatal_err) {
3943 		CH_ALERT(sc, "resetting adapter after fatal error.\n");
3944 		rc = reset_adapter(sc);
3945 		if (rc == 0 && t4_panic_on_fatal_err) {
3946 			CH_ALERT(sc, "reset was successful, "
3947 			    "system will NOT panic.\n");
3948 			return;
3949 		}
3950 	}
3951 
3952 	if (t4_panic_on_fatal_err) {
3953 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3954 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3955 	}
3956 }
3957 
3958 void
3959 t4_fatal_err(struct adapter *sc, bool fw_error)
3960 {
3961 	stop_adapter(sc);
3962 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_FATAL_ERR)))
3963 		return;
3964 	if (fw_error) {
3965 		/*
3966 		 * We are here because of a firmware error/timeout and not
3967 		 * because of a hardware interrupt.  It is possible (although
3968 		 * not very likely) that an error interrupt was also raised but
3969 		 * this thread ran first and inhibited t4_intr_err.  We walk the
3970 		 * main INT_CAUSE registers here to make sure we haven't missed
3971 		 * anything interesting.
3972 		 */
3973 		t4_slow_intr_handler(sc, sc->intr_flags);
3974 		atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
3975 	}
3976 	t4_report_fw_error(sc);
3977 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped (%d).\n",
3978 	    device_get_nameunit(sc->dev), fw_error);
3979 	taskqueue_enqueue(reset_tq, &sc->fatal_error_task);
3980 }
3981 
3982 void
3983 t4_add_adapter(struct adapter *sc)
3984 {
3985 	sx_xlock(&t4_list_lock);
3986 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3987 	sx_xunlock(&t4_list_lock);
3988 }
3989 
3990 int
3991 t4_map_bars_0_and_4(struct adapter *sc)
3992 {
3993 	sc->regs_rid = PCIR_BAR(0);
3994 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3995 	    &sc->regs_rid, RF_ACTIVE);
3996 	if (sc->regs_res == NULL) {
3997 		device_printf(sc->dev, "cannot map registers.\n");
3998 		return (ENXIO);
3999 	}
4000 	sc->bt = rman_get_bustag(sc->regs_res);
4001 	sc->bh = rman_get_bushandle(sc->regs_res);
4002 	sc->mmio_len = rman_get_size(sc->regs_res);
4003 	setbit(&sc->doorbells, DOORBELL_KDB);
4004 
4005 	sc->msix_rid = PCIR_BAR(4);
4006 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
4007 	    &sc->msix_rid, RF_ACTIVE);
4008 	if (sc->msix_res == NULL) {
4009 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
4010 		return (ENXIO);
4011 	}
4012 
4013 	return (0);
4014 }
4015 
4016 int
4017 t4_map_bar_2(struct adapter *sc)
4018 {
4019 
4020 	/*
4021 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
4022 	 * to map it if RDMA is disabled.
4023 	 */
4024 	if (is_t4(sc) && sc->rdmacaps == 0)
4025 		return (0);
4026 
4027 	sc->udbs_rid = PCIR_BAR(2);
4028 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
4029 	    &sc->udbs_rid, RF_ACTIVE);
4030 	if (sc->udbs_res == NULL) {
4031 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
4032 		return (ENXIO);
4033 	}
4034 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
4035 
4036 	if (chip_id(sc) >= CHELSIO_T5) {
4037 		setbit(&sc->doorbells, DOORBELL_UDB);
4038 #if defined(__i386__) || defined(__amd64__)
4039 		if (t5_write_combine) {
4040 			int rc, mode;
4041 
4042 			/*
4043 			 * Enable write combining on BAR2.  This is the
4044 			 * userspace doorbell BAR and is split into 128B
4045 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
4046 			 * with an egress queue.  The first 64B has the doorbell
4047 			 * and the second 64B can be used to submit a tx work
4048 			 * request with an implicit doorbell.
4049 			 */
4050 
4051 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
4052 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
4053 			if (rc == 0) {
4054 				clrbit(&sc->doorbells, DOORBELL_UDB);
4055 				setbit(&sc->doorbells, DOORBELL_WCWR);
4056 				setbit(&sc->doorbells, DOORBELL_UDBWC);
4057 			} else {
4058 				device_printf(sc->dev,
4059 				    "couldn't enable write combining: %d\n",
4060 				    rc);
4061 			}
4062 
4063 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
4064 			t4_write_reg(sc, A_SGE_STAT_CFG,
4065 			    V_STATSOURCE_T5(7) | mode);
4066 		}
4067 #endif
4068 	}
4069 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
4070 
4071 	return (0);
4072 }
4073 
4074 int
4075 t4_adj_doorbells(struct adapter *sc)
4076 {
4077 	if ((sc->doorbells & t4_doorbells_allowed) != 0) {
4078 		sc->doorbells &= t4_doorbells_allowed;
4079 		return (0);
4080 	}
4081 	CH_ERR(sc, "No usable doorbell (available = 0x%x, allowed = 0x%x).\n",
4082 	       sc->doorbells, t4_doorbells_allowed);
4083 	return (EINVAL);
4084 }
4085 
4086 struct memwin_init {
4087 	uint32_t base;
4088 	uint32_t aperture;
4089 };
4090 
4091 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
4092 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
4093 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
4094 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
4095 };
4096 
4097 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
4098 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
4099 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
4100 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
4101 };
4102 
4103 static void
4104 setup_memwin(struct adapter *sc)
4105 {
4106 	const struct memwin_init *mw_init;
4107 	struct memwin *mw;
4108 	int i;
4109 	uint32_t bar0, reg;
4110 
4111 	if (is_t4(sc)) {
4112 		/*
4113 		 * Read low 32b of bar0 indirectly via the hardware backdoor
4114 		 * mechanism.  Works from within PCI passthrough environments
4115 		 * too, where rman_get_start() can return a different value.  We
4116 		 * need to program the T4 memory window decoders with the actual
4117 		 * addresses that will be coming across the PCIe link.
4118 		 */
4119 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
4120 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
4121 
4122 		mw_init = &t4_memwin[0];
4123 	} else {
4124 		/* T5+ use the relative offset inside the PCIe BAR */
4125 		bar0 = 0;
4126 
4127 		mw_init = &t5_memwin[0];
4128 	}
4129 
4130 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
4131 		if (!rw_initialized(&mw->mw_lock)) {
4132 			rw_init(&mw->mw_lock, "memory window access");
4133 			mw->mw_base = mw_init->base;
4134 			mw->mw_aperture = mw_init->aperture;
4135 			mw->mw_curpos = 0;
4136 		}
4137 		reg = chip_id(sc) > CHELSIO_T6 ?
4138 		    PCIE_MEM_ACCESS_T7_REG(A_T7_PCIE_MEM_ACCESS_BASE_WIN, i) :
4139 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i);
4140 		t4_write_reg(sc, reg, (mw->mw_base + bar0) | V_BIR(0) |
4141 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
4142 		rw_wlock(&mw->mw_lock);
4143 		position_memwin(sc, i, mw->mw_curpos);
4144 		rw_wunlock(&mw->mw_lock);
4145 	}
4146 
4147 	/* flush */
4148 	t4_read_reg(sc, reg);
4149 }
4150 
4151 /*
4152  * Positions the memory window at the given address in the card's address space.
4153  * There are some alignment requirements and the actual position may be at an
4154  * address prior to the requested address.  mw->mw_curpos always has the actual
4155  * position of the window.
4156  */
4157 static void
4158 position_memwin(struct adapter *sc, int idx, uint32_t addr)
4159 {
4160 	struct memwin *mw;
4161 	uint32_t pf, reg, val;
4162 
4163 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
4164 	mw = &sc->memwin[idx];
4165 	rw_assert(&mw->mw_lock, RA_WLOCKED);
4166 
4167 	if (is_t4(sc)) {
4168 		pf = 0;
4169 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
4170 	} else {
4171 		pf = V_PFNUM(sc->pf);
4172 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
4173 	}
4174 	if (chip_id(sc) > CHELSIO_T6) {
4175 		reg = PCIE_MEM_ACCESS_T7_REG(A_PCIE_MEM_ACCESS_OFFSET0, idx);
4176 		val = (mw->mw_curpos >> X_T7_MEMOFST_SHIFT) | pf;
4177 	} else {
4178 		reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
4179 		val = mw->mw_curpos | pf;
4180 	}
4181 	t4_write_reg(sc, reg, val);
4182 	t4_read_reg(sc, reg);	/* flush */
4183 }
4184 
4185 int
4186 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
4187     int len, int rw)
4188 {
4189 	struct memwin *mw;
4190 	uint32_t mw_end, v;
4191 
4192 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
4193 
4194 	/* Memory can only be accessed in naturally aligned 4 byte units */
4195 	if (addr & 3 || len & 3 || len <= 0)
4196 		return (EINVAL);
4197 
4198 	mw = &sc->memwin[idx];
4199 	while (len > 0) {
4200 		rw_rlock(&mw->mw_lock);
4201 		mw_end = mw->mw_curpos + mw->mw_aperture;
4202 		if (addr >= mw_end || addr < mw->mw_curpos) {
4203 			/* Will need to reposition the window */
4204 			if (!rw_try_upgrade(&mw->mw_lock)) {
4205 				rw_runlock(&mw->mw_lock);
4206 				rw_wlock(&mw->mw_lock);
4207 			}
4208 			rw_assert(&mw->mw_lock, RA_WLOCKED);
4209 			position_memwin(sc, idx, addr);
4210 			rw_downgrade(&mw->mw_lock);
4211 			mw_end = mw->mw_curpos + mw->mw_aperture;
4212 		}
4213 		rw_assert(&mw->mw_lock, RA_RLOCKED);
4214 		while (addr < mw_end && len > 0) {
4215 			if (rw == 0) {
4216 				v = t4_read_reg(sc, mw->mw_base + addr -
4217 				    mw->mw_curpos);
4218 				*val++ = le32toh(v);
4219 			} else {
4220 				v = *val++;
4221 				t4_write_reg(sc, mw->mw_base + addr -
4222 				    mw->mw_curpos, htole32(v));
4223 			}
4224 			addr += 4;
4225 			len -= 4;
4226 		}
4227 		rw_runlock(&mw->mw_lock);
4228 	}
4229 
4230 	return (0);
4231 }
4232 
4233 CTASSERT(M_TID_COOKIE == M_COOKIE);
4234 CTASSERT(MAX_ATIDS <= (M_TID_TID + 1));
4235 
4236 static void
4237 t4_init_atid_table(struct adapter *sc)
4238 {
4239 	struct tid_info *t;
4240 	int i;
4241 
4242 	t = &sc->tids;
4243 	if (t->natids == 0)
4244 		return;
4245 
4246 	MPASS(t->atid_tab == NULL);
4247 
4248 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
4249 	    M_ZERO | M_WAITOK);
4250 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
4251 	t->afree = t->atid_tab;
4252 	t->atids_in_use = 0;
4253 	t->atid_alloc_stopped = false;
4254 	for (i = 1; i < t->natids; i++)
4255 		t->atid_tab[i - 1].next = &t->atid_tab[i];
4256 	t->atid_tab[t->natids - 1].next = NULL;
4257 }
4258 
4259 static void
4260 t4_free_atid_table(struct adapter *sc)
4261 {
4262 	struct tid_info *t;
4263 
4264 	t = &sc->tids;
4265 
4266 	KASSERT(t->atids_in_use == 0,
4267 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
4268 
4269 	if (mtx_initialized(&t->atid_lock))
4270 		mtx_destroy(&t->atid_lock);
4271 	free(t->atid_tab, M_CXGBE);
4272 	t->atid_tab = NULL;
4273 }
4274 
4275 static void
4276 stop_atid_allocator(struct adapter *sc)
4277 {
4278 	struct tid_info *t = &sc->tids;
4279 
4280 	if (t->natids == 0)
4281 		return;
4282 	mtx_lock(&t->atid_lock);
4283 	t->atid_alloc_stopped = true;
4284 	mtx_unlock(&t->atid_lock);
4285 }
4286 
4287 static void
4288 restart_atid_allocator(struct adapter *sc)
4289 {
4290 	struct tid_info *t = &sc->tids;
4291 
4292 	if (t->natids == 0)
4293 		return;
4294 	mtx_lock(&t->atid_lock);
4295 	KASSERT(t->atids_in_use == 0,
4296 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
4297 	t->atid_alloc_stopped = false;
4298 	mtx_unlock(&t->atid_lock);
4299 }
4300 
4301 int
4302 alloc_atid(struct adapter *sc, void *ctx)
4303 {
4304 	struct tid_info *t = &sc->tids;
4305 	int atid = -1;
4306 
4307 	mtx_lock(&t->atid_lock);
4308 	if (t->afree && !t->atid_alloc_stopped) {
4309 		union aopen_entry *p = t->afree;
4310 
4311 		atid = p - t->atid_tab;
4312 		MPASS(atid <= M_TID_TID);
4313 		t->afree = p->next;
4314 		p->data = ctx;
4315 		t->atids_in_use++;
4316 	}
4317 	mtx_unlock(&t->atid_lock);
4318 	return (atid);
4319 }
4320 
4321 void *
4322 lookup_atid(struct adapter *sc, int atid)
4323 {
4324 	struct tid_info *t = &sc->tids;
4325 
4326 	return (t->atid_tab[atid].data);
4327 }
4328 
4329 void
4330 free_atid(struct adapter *sc, int atid)
4331 {
4332 	struct tid_info *t = &sc->tids;
4333 	union aopen_entry *p = &t->atid_tab[atid];
4334 
4335 	mtx_lock(&t->atid_lock);
4336 	p->next = t->afree;
4337 	t->afree = p;
4338 	t->atids_in_use--;
4339 	mtx_unlock(&t->atid_lock);
4340 }
4341 
4342 static void
4343 queue_tid_release(struct adapter *sc, int tid)
4344 {
4345 
4346 	CXGBE_UNIMPLEMENTED("deferred tid release");
4347 }
4348 
4349 void
4350 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
4351 {
4352 	struct wrqe *wr;
4353 	struct cpl_tid_release *req;
4354 
4355 	wr = alloc_wrqe(sizeof(*req), ctrlq);
4356 	if (wr == NULL) {
4357 		queue_tid_release(sc, tid);	/* defer */
4358 		return;
4359 	}
4360 	req = wrtod(wr);
4361 
4362 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
4363 
4364 	t4_wrq_tx(sc, wr);
4365 }
4366 
4367 static int
4368 t4_range_cmp(const void *a, const void *b)
4369 {
4370 	return ((const struct t4_range *)a)->start -
4371 	       ((const struct t4_range *)b)->start;
4372 }
4373 
4374 /*
4375  * Verify that the memory range specified by the addr/len pair is valid within
4376  * the card's address space.
4377  */
4378 static int
4379 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
4380 {
4381 	struct t4_range mem_ranges[4], *r, *next;
4382 	uint32_t em, addr_len;
4383 	int i, n, remaining;
4384 
4385 	/* Memory can only be accessed in naturally aligned 4 byte units */
4386 	if (addr & 3 || len & 3 || len == 0)
4387 		return (EINVAL);
4388 
4389 	/* Enabled memories */
4390 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4391 
4392 	r = &mem_ranges[0];
4393 	n = 0;
4394 	bzero(r, sizeof(mem_ranges));
4395 	if (em & F_EDRAM0_ENABLE) {
4396 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4397 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
4398 		if (r->size > 0) {
4399 			r->start = G_EDRAM0_BASE(addr_len) << 20;
4400 			if (addr >= r->start &&
4401 			    addr + len <= r->start + r->size)
4402 				return (0);
4403 			r++;
4404 			n++;
4405 		}
4406 	}
4407 	if (em & F_EDRAM1_ENABLE) {
4408 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4409 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
4410 		if (r->size > 0) {
4411 			r->start = G_EDRAM1_BASE(addr_len) << 20;
4412 			if (addr >= r->start &&
4413 			    addr + len <= r->start + r->size)
4414 				return (0);
4415 			r++;
4416 			n++;
4417 		}
4418 	}
4419 	if (em & F_EXT_MEM_ENABLE) {
4420 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4421 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
4422 		if (r->size > 0) {
4423 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
4424 			if (addr >= r->start &&
4425 			    addr + len <= r->start + r->size)
4426 				return (0);
4427 			r++;
4428 			n++;
4429 		}
4430 	}
4431 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
4432 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4433 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
4434 		if (r->size > 0) {
4435 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
4436 			if (addr >= r->start &&
4437 			    addr + len <= r->start + r->size)
4438 				return (0);
4439 			r++;
4440 			n++;
4441 		}
4442 	}
4443 	MPASS(n <= nitems(mem_ranges));
4444 
4445 	if (n > 1) {
4446 		/* Sort and merge the ranges. */
4447 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
4448 
4449 		/* Start from index 0 and examine the next n - 1 entries. */
4450 		r = &mem_ranges[0];
4451 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
4452 
4453 			MPASS(r->size > 0);	/* r is a valid entry. */
4454 			next = r + 1;
4455 			MPASS(next->size > 0);	/* and so is the next one. */
4456 
4457 			while (r->start + r->size >= next->start) {
4458 				/* Merge the next one into the current entry. */
4459 				r->size = max(r->start + r->size,
4460 				    next->start + next->size) - r->start;
4461 				n--;	/* One fewer entry in total. */
4462 				if (--remaining == 0)
4463 					goto done;	/* short circuit */
4464 				next++;
4465 			}
4466 			if (next != r + 1) {
4467 				/*
4468 				 * Some entries were merged into r and next
4469 				 * points to the first valid entry that couldn't
4470 				 * be merged.
4471 				 */
4472 				MPASS(next->size > 0);	/* must be valid */
4473 				memcpy(r + 1, next, remaining * sizeof(*r));
4474 #ifdef INVARIANTS
4475 				/*
4476 				 * This so that the foo->size assertion in the
4477 				 * next iteration of the loop do the right
4478 				 * thing for entries that were pulled up and are
4479 				 * no longer valid.
4480 				 */
4481 				MPASS(n < nitems(mem_ranges));
4482 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4483 				    sizeof(struct t4_range));
4484 #endif
4485 			}
4486 		}
4487 done:
4488 		/* Done merging the ranges. */
4489 		MPASS(n > 0);
4490 		r = &mem_ranges[0];
4491 		for (i = 0; i < n; i++, r++) {
4492 			if (addr >= r->start &&
4493 			    addr + len <= r->start + r->size)
4494 				return (0);
4495 		}
4496 	}
4497 
4498 	return (EFAULT);
4499 }
4500 
4501 static int
4502 fwmtype_to_hwmtype(int mtype)
4503 {
4504 
4505 	switch (mtype) {
4506 	case FW_MEMTYPE_EDC0:
4507 		return (MEM_EDC0);
4508 	case FW_MEMTYPE_EDC1:
4509 		return (MEM_EDC1);
4510 	case FW_MEMTYPE_EXTMEM:
4511 		return (MEM_MC0);
4512 	case FW_MEMTYPE_EXTMEM1:
4513 		return (MEM_MC1);
4514 	default:
4515 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4516 	}
4517 }
4518 
4519 /*
4520  * Verify that the memory range specified by the memtype/offset/len pair is
4521  * valid and lies entirely within the memtype specified.  The global address of
4522  * the start of the range is returned in addr.
4523  */
4524 static int
4525 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4526     uint32_t *addr)
4527 {
4528 	uint32_t em, addr_len, maddr;
4529 
4530 	/* Memory can only be accessed in naturally aligned 4 byte units */
4531 	if (off & 3 || len & 3 || len == 0)
4532 		return (EINVAL);
4533 
4534 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4535 	switch (fwmtype_to_hwmtype(mtype)) {
4536 	case MEM_EDC0:
4537 		if (!(em & F_EDRAM0_ENABLE))
4538 			return (EINVAL);
4539 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4540 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4541 		break;
4542 	case MEM_EDC1:
4543 		if (!(em & F_EDRAM1_ENABLE))
4544 			return (EINVAL);
4545 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4546 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4547 		break;
4548 	case MEM_MC:
4549 		if (!(em & F_EXT_MEM_ENABLE))
4550 			return (EINVAL);
4551 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4552 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4553 		break;
4554 	case MEM_MC1:
4555 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4556 			return (EINVAL);
4557 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4558 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4559 		break;
4560 	default:
4561 		return (EINVAL);
4562 	}
4563 
4564 	*addr = maddr + off;	/* global address */
4565 	return (validate_mem_range(sc, *addr, len));
4566 }
4567 
4568 static int
4569 fixup_devlog_params(struct adapter *sc)
4570 {
4571 	struct devlog_params *dparams = &sc->params.devlog;
4572 	int rc;
4573 
4574 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4575 	    dparams->size, &dparams->addr);
4576 
4577 	return (rc);
4578 }
4579 
4580 static void
4581 update_nirq(struct intrs_and_queues *iaq, int nports)
4582 {
4583 
4584 	iaq->nirq = T4_EXTRA_INTR;
4585 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4586 	iaq->nirq += nports * iaq->nofldrxq;
4587 	iaq->nirq += nports * (iaq->num_vis - 1) *
4588 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4589 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4590 }
4591 
4592 /*
4593  * Adjust requirements to fit the number of interrupts available.
4594  */
4595 static void
4596 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4597     int navail)
4598 {
4599 	int old_nirq;
4600 	const int nports = sc->params.nports;
4601 
4602 	MPASS(nports > 0);
4603 	MPASS(navail > 0);
4604 
4605 	bzero(iaq, sizeof(*iaq));
4606 	iaq->intr_type = itype;
4607 	iaq->num_vis = t4_num_vis;
4608 	iaq->ntxq = t4_ntxq;
4609 	iaq->ntxq_vi = t4_ntxq_vi;
4610 	iaq->nrxq = t4_nrxq;
4611 	iaq->nrxq_vi = t4_nrxq_vi;
4612 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4613 	if (is_offload(sc) || is_ethoffload(sc)) {
4614 		if (sc->params.tid_qid_sel_mask == 0) {
4615 			iaq->nofldtxq = t4_nofldtxq;
4616 			iaq->nofldtxq_vi = t4_nofldtxq_vi;
4617 		} else {
4618 			iaq->nofldtxq = roundup(t4_nofldtxq, sc->params.ncores);
4619 			iaq->nofldtxq_vi = roundup(t4_nofldtxq_vi,
4620 			    sc->params.ncores);
4621 			if (iaq->nofldtxq != t4_nofldtxq)
4622 				device_printf(sc->dev,
4623 				    "nofldtxq updated (%d -> %d) for correct"
4624 				    " operation with %d firmware cores.\n",
4625 				    t4_nofldtxq, iaq->nofldtxq,
4626 				    sc->params.ncores);
4627 			if (iaq->num_vis > 1 &&
4628 			    iaq->nofldtxq_vi != t4_nofldtxq_vi)
4629 				device_printf(sc->dev,
4630 				    "nofldtxq_vi updated (%d -> %d) for correct"
4631 				    " operation with %d firmware cores.\n",
4632 				    t4_nofldtxq_vi, iaq->nofldtxq_vi,
4633 				    sc->params.ncores);
4634 		}
4635 	}
4636 #endif
4637 #ifdef TCP_OFFLOAD
4638 	if (is_offload(sc)) {
4639 		iaq->nofldrxq = t4_nofldrxq;
4640 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4641 	}
4642 #endif
4643 #ifdef DEV_NETMAP
4644 	if (t4_native_netmap & NN_MAIN_VI) {
4645 		iaq->nnmtxq = t4_nnmtxq;
4646 		iaq->nnmrxq = t4_nnmrxq;
4647 	}
4648 	if (t4_native_netmap & NN_EXTRA_VI) {
4649 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4650 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4651 	}
4652 #endif
4653 
4654 	update_nirq(iaq, nports);
4655 	if (iaq->nirq <= navail &&
4656 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4657 		/*
4658 		 * This is the normal case -- there are enough interrupts for
4659 		 * everything.
4660 		 */
4661 		goto done;
4662 	}
4663 
4664 	/*
4665 	 * If extra VIs have been configured try reducing their count and see if
4666 	 * that works.
4667 	 */
4668 	while (iaq->num_vis > 1) {
4669 		iaq->num_vis--;
4670 		update_nirq(iaq, nports);
4671 		if (iaq->nirq <= navail &&
4672 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4673 			device_printf(sc->dev, "virtual interfaces per port "
4674 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4675 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4676 			    "itype %d, navail %u, nirq %d.\n",
4677 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4678 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4679 			    itype, navail, iaq->nirq);
4680 			goto done;
4681 		}
4682 	}
4683 
4684 	/*
4685 	 * Extra VIs will not be created.  Log a message if they were requested.
4686 	 */
4687 	MPASS(iaq->num_vis == 1);
4688 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4689 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4690 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4691 	if (iaq->num_vis != t4_num_vis) {
4692 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4693 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4694 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4695 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4696 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4697 	}
4698 
4699 	/*
4700 	 * Keep reducing the number of NIC rx queues to the next lower power of
4701 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4702 	 * if that works.
4703 	 */
4704 	do {
4705 		if (iaq->nrxq > 1) {
4706 			iaq->nrxq = rounddown_pow_of_two(iaq->nrxq - 1);
4707 			if (iaq->nnmrxq > iaq->nrxq)
4708 				iaq->nnmrxq = iaq->nrxq;
4709 		}
4710 		if (iaq->nofldrxq > 1)
4711 			iaq->nofldrxq >>= 1;
4712 
4713 		old_nirq = iaq->nirq;
4714 		update_nirq(iaq, nports);
4715 		if (iaq->nirq <= navail &&
4716 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4717 			device_printf(sc->dev, "running with reduced number of "
4718 			    "rx queues because of shortage of interrupts.  "
4719 			    "nrxq=%u, nofldrxq=%u.  "
4720 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4721 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4722 			goto done;
4723 		}
4724 	} while (old_nirq != iaq->nirq);
4725 
4726 	/* One interrupt for everything.  Ugh. */
4727 	device_printf(sc->dev, "running with minimal number of queues.  "
4728 	    "itype %d, navail %u.\n", itype, navail);
4729 	iaq->nirq = 1;
4730 	iaq->nrxq = 1;
4731 	iaq->ntxq = 1;
4732 	if (iaq->nofldrxq > 0) {
4733 		iaq->nofldrxq = 1;
4734 		iaq->nofldtxq = 1;
4735 		if (sc->params.tid_qid_sel_mask == 0)
4736 			iaq->nofldtxq = 1;
4737 		else
4738 			iaq->nofldtxq = sc->params.ncores;
4739 	}
4740 	iaq->nnmtxq = 0;
4741 	iaq->nnmrxq = 0;
4742 done:
4743 	MPASS(iaq->num_vis > 0);
4744 	if (iaq->num_vis > 1) {
4745 		MPASS(iaq->nrxq_vi > 0);
4746 		MPASS(iaq->ntxq_vi > 0);
4747 	}
4748 	MPASS(iaq->nirq > 0);
4749 	MPASS(iaq->nrxq > 0);
4750 	MPASS(iaq->ntxq > 0);
4751 	if (itype == INTR_MSI)
4752 		MPASS(powerof2(iaq->nirq));
4753 	if (sc->params.tid_qid_sel_mask != 0)
4754 		MPASS(iaq->nofldtxq % sc->params.ncores == 0);
4755 }
4756 
4757 static int
4758 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4759 {
4760 	int rc, itype, navail, nalloc;
4761 
4762 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4763 
4764 		if ((itype & t4_intr_types) == 0)
4765 			continue;	/* not allowed */
4766 
4767 		if (itype == INTR_MSIX)
4768 			navail = pci_msix_count(sc->dev);
4769 		else if (itype == INTR_MSI)
4770 			navail = pci_msi_count(sc->dev);
4771 		else
4772 			navail = 1;
4773 restart:
4774 		if (navail == 0)
4775 			continue;
4776 
4777 		calculate_iaq(sc, iaq, itype, navail);
4778 		nalloc = iaq->nirq;
4779 		rc = 0;
4780 		if (itype == INTR_MSIX)
4781 			rc = pci_alloc_msix(sc->dev, &nalloc);
4782 		else if (itype == INTR_MSI)
4783 			rc = pci_alloc_msi(sc->dev, &nalloc);
4784 
4785 		if (rc == 0 && nalloc > 0) {
4786 			if (nalloc == iaq->nirq)
4787 				return (0);
4788 
4789 			/*
4790 			 * Didn't get the number requested.  Use whatever number
4791 			 * the kernel is willing to allocate.
4792 			 */
4793 			device_printf(sc->dev, "fewer vectors than requested, "
4794 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4795 			    itype, iaq->nirq, nalloc);
4796 			pci_release_msi(sc->dev);
4797 			navail = nalloc;
4798 			goto restart;
4799 		}
4800 
4801 		device_printf(sc->dev,
4802 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4803 		    itype, rc, iaq->nirq, nalloc);
4804 	}
4805 
4806 	device_printf(sc->dev,
4807 	    "failed to find a usable interrupt type.  "
4808 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4809 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4810 
4811 	return (ENXIO);
4812 }
4813 
4814 #define FW_VERSION(chip) ( \
4815     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4816     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4817     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4818     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4819 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4820 
4821 /* Just enough of fw_hdr to cover all version info. */
4822 struct fw_h {
4823 	__u8	ver;
4824 	__u8	chip;
4825 	__be16	len512;
4826 	__be32	fw_ver;
4827 	__be32	tp_microcode_ver;
4828 	__u8	intfver_nic;
4829 	__u8	intfver_vnic;
4830 	__u8	intfver_ofld;
4831 	__u8	intfver_ri;
4832 	__u8	intfver_iscsipdu;
4833 	__u8	intfver_iscsi;
4834 	__u8	intfver_fcoepdu;
4835 	__u8	intfver_fcoe;
4836 };
4837 /* Spot check a couple of fields. */
4838 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4839 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4840 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4841 
4842 struct fw_info {
4843 	uint8_t chip;
4844 	char *kld_name;
4845 	char *fw_mod_name;
4846 	struct fw_h fw_h;
4847 } fw_info[] = {
4848 	{
4849 		.chip = CHELSIO_T4,
4850 		.kld_name = "t4fw_cfg",
4851 		.fw_mod_name = "t4fw",
4852 		.fw_h = {
4853 			.chip = FW_HDR_CHIP_T4,
4854 			.fw_ver = htobe32(FW_VERSION(T4)),
4855 			.intfver_nic = FW_INTFVER(T4, NIC),
4856 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4857 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4858 			.intfver_ri = FW_INTFVER(T4, RI),
4859 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4860 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4861 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4862 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4863 		},
4864 	}, {
4865 		.chip = CHELSIO_T5,
4866 		.kld_name = "t5fw_cfg",
4867 		.fw_mod_name = "t5fw",
4868 		.fw_h = {
4869 			.chip = FW_HDR_CHIP_T5,
4870 			.fw_ver = htobe32(FW_VERSION(T5)),
4871 			.intfver_nic = FW_INTFVER(T5, NIC),
4872 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4873 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4874 			.intfver_ri = FW_INTFVER(T5, RI),
4875 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4876 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4877 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4878 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4879 		},
4880 	}, {
4881 		.chip = CHELSIO_T6,
4882 		.kld_name = "t6fw_cfg",
4883 		.fw_mod_name = "t6fw",
4884 		.fw_h = {
4885 			.chip = FW_HDR_CHIP_T6,
4886 			.fw_ver = htobe32(FW_VERSION(T6)),
4887 			.intfver_nic = FW_INTFVER(T6, NIC),
4888 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4889 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4890 			.intfver_ri = FW_INTFVER(T6, RI),
4891 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4892 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4893 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4894 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4895 		},
4896 	}, {
4897 		.chip = CHELSIO_T7,
4898 		.kld_name = "t7fw_cfg",
4899 		.fw_mod_name = "t7fw",
4900 		.fw_h = {
4901 			.chip = FW_HDR_CHIP_T7,
4902 			.fw_ver = htobe32(FW_VERSION(T7)),
4903 			.intfver_nic = FW_INTFVER(T7, NIC),
4904 			.intfver_vnic = FW_INTFVER(T7, VNIC),
4905 			.intfver_ofld = FW_INTFVER(T7, OFLD),
4906 			.intfver_ri = FW_INTFVER(T7, RI),
4907 			.intfver_iscsipdu = FW_INTFVER(T7, ISCSIPDU),
4908 			.intfver_iscsi = FW_INTFVER(T7, ISCSI),
4909 			.intfver_fcoepdu = FW_INTFVER(T7, FCOEPDU),
4910 			.intfver_fcoe = FW_INTFVER(T7, FCOE),
4911 		},
4912 	}
4913 };
4914 
4915 static struct fw_info *
4916 find_fw_info(int chip)
4917 {
4918 	int i;
4919 
4920 	for (i = 0; i < nitems(fw_info); i++) {
4921 		if (fw_info[i].chip == chip)
4922 			return (&fw_info[i]);
4923 	}
4924 	return (NULL);
4925 }
4926 
4927 /*
4928  * Is the given firmware API compatible with the one the driver was compiled
4929  * with?
4930  */
4931 static int
4932 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4933 {
4934 
4935 	/* short circuit if it's the exact same firmware version */
4936 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4937 		return (1);
4938 
4939 	/*
4940 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4941 	 * features that are supported in the driver.
4942 	 */
4943 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4944 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4945 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4946 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4947 		return (1);
4948 #undef SAME_INTF
4949 
4950 	return (0);
4951 }
4952 
4953 static int
4954 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4955     const struct firmware **fw)
4956 {
4957 	struct fw_info *fw_info;
4958 
4959 	*dcfg = NULL;
4960 	if (fw != NULL)
4961 		*fw = NULL;
4962 
4963 	fw_info = find_fw_info(chip_id(sc));
4964 	if (fw_info == NULL) {
4965 		device_printf(sc->dev,
4966 		    "unable to look up firmware information for chip %d.\n",
4967 		    chip_id(sc));
4968 		return (EINVAL);
4969 	}
4970 
4971 	*dcfg = firmware_get(fw_info->kld_name);
4972 	if (*dcfg != NULL) {
4973 		if (fw != NULL)
4974 			*fw = firmware_get(fw_info->fw_mod_name);
4975 		return (0);
4976 	}
4977 
4978 	return (ENOENT);
4979 }
4980 
4981 static void
4982 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4983     const struct firmware *fw)
4984 {
4985 
4986 	if (fw != NULL)
4987 		firmware_put(fw, FIRMWARE_UNLOAD);
4988 	if (dcfg != NULL)
4989 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4990 }
4991 
4992 /*
4993  * Return values:
4994  * 0 means no firmware install attempted.
4995  * ERESTART means a firmware install was attempted and was successful.
4996  * +ve errno means a firmware install was attempted but failed.
4997  */
4998 static int
4999 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
5000     const struct fw_h *drv_fw, const char *reason, int *already)
5001 {
5002 	const struct firmware *cfg, *fw;
5003 	const uint32_t c = be32toh(card_fw->fw_ver);
5004 	uint32_t d, k;
5005 	int rc, fw_install;
5006 	struct fw_h bundled_fw;
5007 	bool load_attempted;
5008 
5009 	cfg = fw = NULL;
5010 	load_attempted = false;
5011 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
5012 
5013 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
5014 	if (t4_fw_install < 0) {
5015 		rc = load_fw_module(sc, &cfg, &fw);
5016 		if (rc != 0 || fw == NULL) {
5017 			device_printf(sc->dev,
5018 			    "failed to load firmware module: %d. cfg %p, fw %p;"
5019 			    " will use compiled-in firmware version for"
5020 			    "hw.cxgbe.fw_install checks.\n",
5021 			    rc, cfg, fw);
5022 		} else {
5023 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
5024 		}
5025 		load_attempted = true;
5026 	}
5027 	d = be32toh(bundled_fw.fw_ver);
5028 
5029 	if (reason != NULL)
5030 		goto install;
5031 
5032 	if ((sc->flags & FW_OK) == 0) {
5033 
5034 		if (c == 0xffffffff) {
5035 			reason = "missing";
5036 			goto install;
5037 		}
5038 
5039 		rc = 0;
5040 		goto done;
5041 	}
5042 
5043 	if (!fw_compatible(card_fw, &bundled_fw)) {
5044 		reason = "incompatible or unusable";
5045 		goto install;
5046 	}
5047 
5048 	if (d > c) {
5049 		reason = "older than the version bundled with this driver";
5050 		goto install;
5051 	}
5052 
5053 	if (fw_install == 2 && d != c) {
5054 		reason = "different than the version bundled with this driver";
5055 		goto install;
5056 	}
5057 
5058 	/* No reason to do anything to the firmware already on the card. */
5059 	rc = 0;
5060 	goto done;
5061 
5062 install:
5063 	rc = 0;
5064 	if ((*already)++)
5065 		goto done;
5066 
5067 	if (fw_install == 0) {
5068 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
5069 		    "but the driver is prohibited from installing a firmware "
5070 		    "on the card.\n",
5071 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
5072 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
5073 
5074 		goto done;
5075 	}
5076 
5077 	/*
5078 	 * We'll attempt to install a firmware.  Load the module first (if it
5079 	 * hasn't been loaded already).
5080 	 */
5081 	if (!load_attempted) {
5082 		rc = load_fw_module(sc, &cfg, &fw);
5083 		if (rc != 0 || fw == NULL) {
5084 			device_printf(sc->dev,
5085 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
5086 			    rc, cfg, fw);
5087 			/* carry on */
5088 		}
5089 	}
5090 	if (fw == NULL) {
5091 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
5092 		    "but the driver cannot take corrective action because it "
5093 		    "is unable to load the firmware module.\n",
5094 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
5095 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
5096 		rc = sc->flags & FW_OK ? 0 : ENOENT;
5097 		goto done;
5098 	}
5099 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
5100 	if (k != d) {
5101 		MPASS(t4_fw_install > 0);
5102 		device_printf(sc->dev,
5103 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
5104 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
5105 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
5106 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
5107 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
5108 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
5109 		rc = sc->flags & FW_OK ? 0 : EINVAL;
5110 		goto done;
5111 	}
5112 
5113 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
5114 	    "installing firmware %u.%u.%u.%u on card.\n",
5115 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
5116 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
5117 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
5118 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
5119 
5120 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
5121 	if (rc != 0) {
5122 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
5123 	} else {
5124 		/* Installed successfully, update the cached header too. */
5125 		rc = ERESTART;
5126 		memcpy(card_fw, fw->data, sizeof(*card_fw));
5127 	}
5128 done:
5129 	unload_fw_module(sc, cfg, fw);
5130 
5131 	return (rc);
5132 }
5133 
5134 /*
5135  * Establish contact with the firmware and attempt to become the master driver.
5136  *
5137  * A firmware will be installed to the card if needed (if the driver is allowed
5138  * to do so).
5139  */
5140 static int
5141 contact_firmware(struct adapter *sc)
5142 {
5143 	int rc, already = 0;
5144 	enum dev_state state;
5145 	struct fw_info *fw_info;
5146 	struct fw_hdr *card_fw;		/* fw on the card */
5147 	const struct fw_h *drv_fw;
5148 
5149 	fw_info = find_fw_info(chip_id(sc));
5150 	if (fw_info == NULL) {
5151 		device_printf(sc->dev,
5152 		    "unable to look up firmware information for chip %d.\n",
5153 		    chip_id(sc));
5154 		return (EINVAL);
5155 	}
5156 	drv_fw = &fw_info->fw_h;
5157 
5158 	/* Read the header of the firmware on the card */
5159 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
5160 restart:
5161 	rc = -t4_get_fw_hdr(sc, card_fw);
5162 	if (rc != 0) {
5163 		device_printf(sc->dev,
5164 		    "unable to read firmware header from card's flash: %d\n",
5165 		    rc);
5166 		goto done;
5167 	}
5168 
5169 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
5170 	    &already);
5171 	if (rc == ERESTART)
5172 		goto restart;
5173 	if (rc != 0)
5174 		goto done;
5175 
5176 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
5177 	if (rc < 0 || state == DEV_STATE_ERR) {
5178 		rc = -rc;
5179 		device_printf(sc->dev,
5180 		    "failed to connect to the firmware: %d, %d.  "
5181 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
5182 #if 0
5183 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
5184 		    "not responding properly to HELLO", &already) == ERESTART)
5185 			goto restart;
5186 #endif
5187 		goto done;
5188 	}
5189 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
5190 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
5191 
5192 	if (rc == sc->pf) {
5193 		sc->flags |= MASTER_PF;
5194 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
5195 		    NULL, &already);
5196 		if (rc == ERESTART)
5197 			rc = 0;
5198 		else if (rc != 0)
5199 			goto done;
5200 	} else if (state == DEV_STATE_UNINIT) {
5201 		/*
5202 		 * We didn't get to be the master so we definitely won't be
5203 		 * configuring the chip.  It's a bug if someone else hasn't
5204 		 * configured it already.
5205 		 */
5206 		device_printf(sc->dev, "couldn't be master(%d), "
5207 		    "device not already initialized either(%d).  "
5208 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
5209 		rc = EPROTO;
5210 		goto done;
5211 	} else {
5212 		/*
5213 		 * Some other PF is the master and has configured the chip.
5214 		 * This is allowed but untested.
5215 		 */
5216 		device_printf(sc->dev, "PF%d is master, device state %d.  "
5217 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
5218 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
5219 		sc->cfcsum = 0;
5220 		rc = 0;
5221 	}
5222 done:
5223 	if (rc != 0 && sc->flags & FW_OK) {
5224 		t4_fw_bye(sc, sc->mbox);
5225 		sc->flags &= ~FW_OK;
5226 	}
5227 	free(card_fw, M_CXGBE);
5228 	return (rc);
5229 }
5230 
5231 static int
5232 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
5233     uint32_t mtype, uint32_t moff, u_int maxlen)
5234 {
5235 	struct fw_info *fw_info;
5236 	const struct firmware *dcfg, *rcfg = NULL;
5237 	const uint32_t *cfdata;
5238 	uint32_t cflen, addr;
5239 	int rc;
5240 
5241 	load_fw_module(sc, &dcfg, NULL);
5242 
5243 	/* Card specific interpretation of "default". */
5244 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
5245 		if (pci_get_device(sc->dev) == 0x440a)
5246 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
5247 		if (is_fpga(sc))
5248 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
5249 	}
5250 
5251 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
5252 		if (dcfg == NULL) {
5253 			device_printf(sc->dev,
5254 			    "KLD with default config is not available.\n");
5255 			rc = ENOENT;
5256 			goto done;
5257 		}
5258 		cfdata = dcfg->data;
5259 		cflen = dcfg->datasize & ~3;
5260 	} else {
5261 		char s[32];
5262 
5263 		fw_info = find_fw_info(chip_id(sc));
5264 		if (fw_info == NULL) {
5265 			device_printf(sc->dev,
5266 			    "unable to look up firmware information for chip %d.\n",
5267 			    chip_id(sc));
5268 			rc = EINVAL;
5269 			goto done;
5270 		}
5271 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
5272 
5273 		rcfg = firmware_get(s);
5274 		if (rcfg == NULL) {
5275 			device_printf(sc->dev,
5276 			    "unable to load module \"%s\" for configuration "
5277 			    "profile \"%s\".\n", s, cfg_file);
5278 			rc = ENOENT;
5279 			goto done;
5280 		}
5281 		cfdata = rcfg->data;
5282 		cflen = rcfg->datasize & ~3;
5283 	}
5284 
5285 	if (cflen > maxlen) {
5286 		device_printf(sc->dev,
5287 		    "config file too long (%d, max allowed is %d).\n",
5288 		    cflen, maxlen);
5289 		rc = EINVAL;
5290 		goto done;
5291 	}
5292 
5293 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
5294 	if (rc != 0) {
5295 		device_printf(sc->dev,
5296 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
5297 		    __func__, mtype, moff, cflen, rc);
5298 		rc = EINVAL;
5299 		goto done;
5300 	}
5301 	write_via_memwin(sc, 2, addr, cfdata, cflen);
5302 done:
5303 	if (rcfg != NULL)
5304 		firmware_put(rcfg, FIRMWARE_UNLOAD);
5305 	unload_fw_module(sc, dcfg, NULL);
5306 	return (rc);
5307 }
5308 
5309 struct caps_allowed {
5310 	uint16_t nbmcaps;
5311 	uint16_t linkcaps;
5312 	uint16_t switchcaps;
5313 	uint16_t nvmecaps;
5314 	uint16_t niccaps;
5315 	uint16_t toecaps;
5316 	uint16_t rdmacaps;
5317 	uint16_t cryptocaps;
5318 	uint16_t iscsicaps;
5319 	uint16_t fcoecaps;
5320 };
5321 
5322 #define FW_PARAM_DEV(param) \
5323 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
5324 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
5325 #define FW_PARAM_PFVF(param) \
5326 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
5327 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
5328 
5329 /*
5330  * Provide a configuration profile to the firmware and have it initialize the
5331  * chip accordingly.  This may involve uploading a configuration file to the
5332  * card.
5333  */
5334 static int
5335 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
5336     const struct caps_allowed *caps_allowed)
5337 {
5338 	int rc;
5339 	struct fw_caps_config_cmd caps;
5340 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
5341 	unsigned int maxlen = 0;
5342 	const int cfg_addr = t4_flash_cfg_addr(sc, &maxlen);
5343 
5344 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
5345 	if (rc != 0) {
5346 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
5347 		return (rc);
5348 	}
5349 
5350 	bzero(&caps, sizeof(caps));
5351 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5352 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5353 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
5354 		mtype = 0;
5355 		moff = 0;
5356 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5357 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
5358 		mtype = FW_MEMTYPE_FLASH;
5359 		moff = cfg_addr;
5360 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5361 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5362 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5363 		    FW_LEN16(caps));
5364 	} else {
5365 		/*
5366 		 * Ask the firmware where it wants us to upload the config file.
5367 		 */
5368 		param = FW_PARAM_DEV(CF);
5369 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5370 		if (rc != 0) {
5371 			/* No support for config file?  Shouldn't happen. */
5372 			device_printf(sc->dev,
5373 			    "failed to query config file location: %d.\n", rc);
5374 			goto done;
5375 		}
5376 		mtype = G_FW_PARAMS_PARAM_Y(val);
5377 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
5378 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5379 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5380 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5381 		    FW_LEN16(caps));
5382 
5383 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff, maxlen);
5384 		if (rc != 0) {
5385 			device_printf(sc->dev,
5386 			    "failed to upload config file to card: %d.\n", rc);
5387 			goto done;
5388 		}
5389 	}
5390 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5391 	if (rc != 0) {
5392 		device_printf(sc->dev, "failed to pre-process config file: %d "
5393 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
5394 		goto done;
5395 	}
5396 
5397 	finicsum = be32toh(caps.finicsum);
5398 	cfcsum = be32toh(caps.cfcsum);	/* actual */
5399 	if (finicsum != cfcsum) {
5400 		device_printf(sc->dev,
5401 		    "WARNING: config file checksum mismatch: %08x %08x\n",
5402 		    finicsum, cfcsum);
5403 	}
5404 	sc->cfcsum = cfcsum;
5405 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
5406 
5407 	/*
5408 	 * Let the firmware know what features will (not) be used so it can tune
5409 	 * things accordingly.
5410 	 */
5411 #define LIMIT_CAPS(x) do { \
5412 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
5413 } while (0)
5414 	LIMIT_CAPS(nbm);
5415 	LIMIT_CAPS(link);
5416 	LIMIT_CAPS(switch);
5417 	LIMIT_CAPS(nvme);
5418 	LIMIT_CAPS(nic);
5419 	LIMIT_CAPS(toe);
5420 	LIMIT_CAPS(rdma);
5421 	LIMIT_CAPS(crypto);
5422 	LIMIT_CAPS(iscsi);
5423 	LIMIT_CAPS(fcoe);
5424 #undef LIMIT_CAPS
5425 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
5426 		/*
5427 		 * TOE and hashfilters are mutually exclusive.  It is a config
5428 		 * file or firmware bug if both are reported as available.  Try
5429 		 * to cope with the situation in non-debug builds by disabling
5430 		 * TOE.
5431 		 */
5432 		MPASS(caps.toecaps == 0);
5433 
5434 		caps.toecaps = 0;
5435 		caps.rdmacaps = 0;
5436 		caps.iscsicaps = 0;
5437 		caps.nvmecaps = 0;
5438 	}
5439 
5440 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5441 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
5442 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5443 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
5444 	if (rc != 0) {
5445 		device_printf(sc->dev,
5446 		    "failed to process config file: %d.\n", rc);
5447 		goto done;
5448 	}
5449 
5450 	t4_tweak_chip_settings(sc);
5451 	set_params__pre_init(sc);
5452 
5453 	/* get basic stuff going */
5454 	rc = -t4_fw_initialize(sc, sc->mbox);
5455 	if (rc != 0) {
5456 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
5457 		goto done;
5458 	}
5459 done:
5460 	return (rc);
5461 }
5462 
5463 /*
5464  * Partition chip resources for use between various PFs, VFs, etc.
5465  */
5466 static int
5467 partition_resources(struct adapter *sc)
5468 {
5469 	char cfg_file[sizeof(t4_cfg_file)];
5470 	struct caps_allowed caps_allowed;
5471 	int rc;
5472 	bool fallback;
5473 
5474 	/* Only the master driver gets to configure the chip resources. */
5475 	MPASS(sc->flags & MASTER_PF);
5476 
5477 #define COPY_CAPS(x) do { \
5478 	caps_allowed.x##caps = t4_##x##caps_allowed; \
5479 } while (0)
5480 	bzero(&caps_allowed, sizeof(caps_allowed));
5481 	COPY_CAPS(nbm);
5482 	COPY_CAPS(link);
5483 	COPY_CAPS(switch);
5484 	COPY_CAPS(nvme);
5485 	COPY_CAPS(nic);
5486 	COPY_CAPS(toe);
5487 	COPY_CAPS(rdma);
5488 	COPY_CAPS(crypto);
5489 	COPY_CAPS(iscsi);
5490 	COPY_CAPS(fcoe);
5491 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
5492 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
5493 retry:
5494 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
5495 	if (rc != 0 && fallback) {
5496 		dump_devlog(sc);
5497 		device_printf(sc->dev,
5498 		    "failed (%d) to configure card with \"%s\" profile, "
5499 		    "will fall back to a basic configuration and retry.\n",
5500 		    rc, cfg_file);
5501 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
5502 		bzero(&caps_allowed, sizeof(caps_allowed));
5503 		COPY_CAPS(switch);
5504 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
5505 		fallback = false;
5506 		goto retry;
5507 	}
5508 #undef COPY_CAPS
5509 	return (rc);
5510 }
5511 
5512 /*
5513  * Retrieve parameters that are needed (or nice to have) very early.
5514  */
5515 static int
5516 get_params__pre_init(struct adapter *sc)
5517 {
5518 	int rc;
5519 	uint32_t param[2], val[2];
5520 
5521 	t4_get_version_info(sc);
5522 
5523 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5524 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5525 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5526 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5527 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5528 
5529 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5530 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5531 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5532 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5533 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5534 
5535 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5536 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5537 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5538 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5539 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5540 
5541 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5542 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5543 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5544 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5545 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5546 
5547 	param[0] = FW_PARAM_DEV(PORTVEC);
5548 	param[1] = FW_PARAM_DEV(CCLK);
5549 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5550 	if (rc != 0) {
5551 		device_printf(sc->dev,
5552 		    "failed to query parameters (pre_init): %d.\n", rc);
5553 		return (rc);
5554 	}
5555 
5556 	sc->params.portvec = val[0];
5557 	sc->params.nports = bitcount32(val[0]);
5558 	sc->params.vpd.cclk = val[1];
5559 
5560 	/* Read device log parameters. */
5561 	rc = -t4_init_devlog_ncores_params(sc, 1);
5562 	if (rc == 0)
5563 		fixup_devlog_params(sc);
5564 	else {
5565 		device_printf(sc->dev,
5566 		    "failed to get devlog parameters: %d.\n", rc);
5567 		rc = 0;	/* devlog isn't critical for device operation */
5568 	}
5569 
5570 	return (rc);
5571 }
5572 
5573 /*
5574  * Any params that need to be set before FW_INITIALIZE.
5575  */
5576 static int
5577 set_params__pre_init(struct adapter *sc)
5578 {
5579 	int rc = 0;
5580 	uint32_t param, val;
5581 
5582 	if (chip_id(sc) >= CHELSIO_T6) {
5583 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5584 		val = 1;
5585 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5586 		/* firmwares < 1.20.1.0 do not have this param. */
5587 		if (rc == FW_EINVAL &&
5588 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5589 			rc = 0;
5590 		}
5591 		if (rc != 0) {
5592 			device_printf(sc->dev,
5593 			    "failed to enable high priority filters :%d.\n",
5594 			    rc);
5595 		}
5596 
5597 		param = FW_PARAM_DEV(PPOD_EDRAM);
5598 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5599 		if (rc == 0 && val == 1) {
5600 			rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param,
5601 			    &val);
5602 			if (rc != 0) {
5603 				device_printf(sc->dev,
5604 				    "failed to set PPOD_EDRAM: %d.\n", rc);
5605 			}
5606 		}
5607 	}
5608 
5609 	/* Enable opaque VIIDs with firmwares that support it. */
5610 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5611 	val = 1;
5612 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5613 	if (rc == 0 && val == 1)
5614 		sc->params.viid_smt_extn_support = true;
5615 	else
5616 		sc->params.viid_smt_extn_support = false;
5617 
5618 	return (rc);
5619 }
5620 
5621 /*
5622  * Retrieve various parameters that are of interest to the driver.  The device
5623  * has been initialized by the firmware at this point.
5624  */
5625 static int
5626 get_params__post_init(struct adapter *sc)
5627 {
5628 	int rc;
5629 	uint32_t param[7], val[7];
5630 	struct fw_caps_config_cmd caps;
5631 
5632 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5633 	param[1] = FW_PARAM_PFVF(EQ_START);
5634 	param[2] = FW_PARAM_PFVF(FILTER_START);
5635 	param[3] = FW_PARAM_PFVF(FILTER_END);
5636 	param[4] = FW_PARAM_PFVF(L2T_START);
5637 	param[5] = FW_PARAM_PFVF(L2T_END);
5638 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5639 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5640 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5641 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5642 	if (rc != 0) {
5643 		device_printf(sc->dev,
5644 		    "failed to query parameters (post_init): %d.\n", rc);
5645 		return (rc);
5646 	}
5647 
5648 	sc->sge.iq_start = val[0];
5649 	sc->sge.eq_start = val[1];
5650 	if ((int)val[3] > (int)val[2]) {
5651 		sc->tids.ftid_base = val[2];
5652 		sc->tids.ftid_end = val[3];
5653 		sc->tids.nftids = val[3] - val[2] + 1;
5654 	}
5655 	sc->vres.l2t.start = val[4];
5656 	sc->vres.l2t.size = val[5] - val[4] + 1;
5657 	/* val[5] is the last hwidx and it must not collide with F_SYNC_WR */
5658 	if (sc->vres.l2t.size > 0)
5659 		MPASS(fls(val[5]) <= S_SYNC_WR);
5660 	sc->params.core_vdd = val[6];
5661 
5662 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5663 	param[1] = FW_PARAM_PFVF(EQ_END);
5664 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5665 	if (rc != 0) {
5666 		device_printf(sc->dev,
5667 		    "failed to query parameters (post_init2): %d.\n", rc);
5668 		return (rc);
5669 	}
5670 	MPASS((int)val[0] >= sc->sge.iq_start);
5671 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5672 	MPASS((int)val[1] >= sc->sge.eq_start);
5673 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5674 
5675 	if (chip_id(sc) >= CHELSIO_T6) {
5676 
5677 		sc->tids.tid_base = t4_read_reg(sc,
5678 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5679 
5680 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5681 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5682 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5683 		if (rc != 0) {
5684 			device_printf(sc->dev,
5685 			   "failed to query hpfilter parameters: %d.\n", rc);
5686 			return (rc);
5687 		}
5688 		if ((int)val[1] > (int)val[0]) {
5689 			sc->tids.hpftid_base = val[0];
5690 			sc->tids.hpftid_end = val[1];
5691 			sc->tids.nhpftids = val[1] - val[0] + 1;
5692 
5693 			/*
5694 			 * These should go off if the layout changes and the
5695 			 * driver needs to catch up.
5696 			 */
5697 			MPASS(sc->tids.hpftid_base == 0);
5698 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5699 		}
5700 
5701 		param[0] = FW_PARAM_PFVF(RAWF_START);
5702 		param[1] = FW_PARAM_PFVF(RAWF_END);
5703 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5704 		if (rc != 0) {
5705 			device_printf(sc->dev,
5706 			   "failed to query rawf parameters: %d.\n", rc);
5707 			return (rc);
5708 		}
5709 		if ((int)val[1] > (int)val[0]) {
5710 			sc->rawf_base = val[0];
5711 			sc->nrawf = val[1] - val[0] + 1;
5712 		}
5713 	}
5714 
5715 	if (sc->params.ncores > 1) {
5716 		MPASS(chip_id(sc) >= CHELSIO_T7);
5717 
5718 		param[0] = FW_PARAM_DEV(TID_QID_SEL_MASK);
5719 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5720 		sc->params.tid_qid_sel_mask = rc == 0 ? val[0] : 0;
5721 	}
5722 
5723 	/*
5724 	 * The parameters that follow may not be available on all firmwares.  We
5725 	 * query them individually rather than in a compound query because old
5726 	 * firmwares fail the entire query if an unknown parameter is queried.
5727 	 */
5728 
5729 	/*
5730 	 * MPS buffer group configuration.
5731 	 */
5732 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5733 	val[0] = 0;
5734 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5735 	if (rc == 0)
5736 		sc->params.mps_bg_map = val[0];
5737 	else
5738 		sc->params.mps_bg_map = UINT32_MAX;	/* Not a legal value. */
5739 
5740 	param[0] = FW_PARAM_DEV(TPCHMAP);
5741 	val[0] = 0;
5742 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5743 	if (rc == 0)
5744 		sc->params.tp_ch_map = val[0];
5745 	else
5746 		sc->params.tp_ch_map = UINT32_MAX;	/* Not a legal value. */
5747 
5748 	param[0] = FW_PARAM_DEV(TX_TPCHMAP);
5749 	val[0] = 0;
5750 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5751 	if (rc == 0)
5752 		sc->params.tx_tp_ch_map = val[0];
5753 	else
5754 		sc->params.tx_tp_ch_map = UINT32_MAX;	/* Not a legal value. */
5755 
5756 	/*
5757 	 * Determine whether the firmware supports the filter2 work request.
5758 	 */
5759 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5760 	val[0] = 0;
5761 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5762 	if (rc == 0)
5763 		sc->params.filter2_wr_support = val[0] != 0;
5764 	else
5765 		sc->params.filter2_wr_support = 0;
5766 
5767 	/*
5768 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5769 	 */
5770 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5771 	val[0] = 0;
5772 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5773 	if (rc == 0)
5774 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5775 	else
5776 		sc->params.ulptx_memwrite_dsgl = false;
5777 
5778 	/* FW_RI_FR_NSMR_TPTE_WR support */
5779 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5780 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5781 	if (rc == 0)
5782 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5783 	else
5784 		sc->params.fr_nsmr_tpte_wr_support = false;
5785 
5786 	/* Support for 512 SGL entries per FR MR. */
5787 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5788 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5789 	if (rc == 0)
5790 		sc->params.dev_512sgl_mr = val[0] != 0;
5791 	else
5792 		sc->params.dev_512sgl_mr = false;
5793 
5794 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5795 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5796 	if (rc == 0)
5797 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5798 	else
5799 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5800 
5801 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5802 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5803 	if (rc == 0) {
5804 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5805 		sc->params.nsched_cls = val[0];
5806 	} else
5807 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5808 
5809 	/* get capabilites */
5810 	bzero(&caps, sizeof(caps));
5811 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5812 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5813 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5814 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5815 	if (rc != 0) {
5816 		device_printf(sc->dev,
5817 		    "failed to get card capabilities: %d.\n", rc);
5818 		return (rc);
5819 	}
5820 
5821 #define READ_CAPS(x) do { \
5822 	sc->x = htobe16(caps.x); \
5823 } while (0)
5824 	READ_CAPS(nbmcaps);
5825 	READ_CAPS(linkcaps);
5826 	READ_CAPS(switchcaps);
5827 	READ_CAPS(nvmecaps);
5828 	READ_CAPS(niccaps);
5829 	READ_CAPS(toecaps);
5830 	READ_CAPS(rdmacaps);
5831 	READ_CAPS(cryptocaps);
5832 	READ_CAPS(iscsicaps);
5833 	READ_CAPS(fcoecaps);
5834 
5835 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5836 		MPASS(chip_id(sc) > CHELSIO_T4);
5837 		MPASS(sc->toecaps == 0);
5838 		sc->toecaps = 0;
5839 
5840 		param[0] = FW_PARAM_DEV(NTID);
5841 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5842 		if (rc != 0) {
5843 			device_printf(sc->dev,
5844 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5845 			return (rc);
5846 		}
5847 		sc->tids.ntids = val[0];
5848 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5849 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5850 			sc->tids.ntids -= sc->tids.nhpftids;
5851 		}
5852 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5853 		sc->params.hash_filter = 1;
5854 	}
5855 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5856 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5857 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5858 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5859 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5860 		if (rc != 0) {
5861 			device_printf(sc->dev,
5862 			    "failed to query NIC parameters: %d.\n", rc);
5863 			return (rc);
5864 		}
5865 		if ((int)val[1] > (int)val[0]) {
5866 			sc->tids.etid_base = val[0];
5867 			sc->tids.etid_end = val[1];
5868 			sc->tids.netids = val[1] - val[0] + 1;
5869 			sc->params.eo_wr_cred = val[2];
5870 			sc->params.ethoffload = 1;
5871 		}
5872 	}
5873 	if (sc->toecaps) {
5874 		/* query offload-related parameters */
5875 		param[0] = FW_PARAM_DEV(NTID);
5876 		param[1] = FW_PARAM_PFVF(SERVER_START);
5877 		param[2] = FW_PARAM_PFVF(SERVER_END);
5878 		param[3] = FW_PARAM_PFVF(TDDP_START);
5879 		param[4] = FW_PARAM_PFVF(TDDP_END);
5880 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5881 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5882 		if (rc != 0) {
5883 			device_printf(sc->dev,
5884 			    "failed to query TOE parameters: %d.\n", rc);
5885 			return (rc);
5886 		}
5887 		sc->tids.ntids = val[0];
5888 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5889 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5890 			sc->tids.ntids -= sc->tids.nhpftids;
5891 		}
5892 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5893 		if ((int)val[2] > (int)val[1]) {
5894 			sc->tids.stid_base = val[1];
5895 			sc->tids.nstids = val[2] - val[1] + 1;
5896 		}
5897 		sc->vres.ddp.start = val[3];
5898 		sc->vres.ddp.size = val[4] - val[3] + 1;
5899 		sc->params.ofldq_wr_cred = val[5];
5900 		sc->params.offload = 1;
5901 	} else {
5902 		/*
5903 		 * The firmware attempts memfree TOE configuration for -SO cards
5904 		 * and will report toecaps=0 if it runs out of resources (this
5905 		 * depends on the config file).  It may not report 0 for other
5906 		 * capabilities dependent on the TOE in this case.  Set them to
5907 		 * 0 here so that the driver doesn't bother tracking resources
5908 		 * that will never be used.
5909 		 */
5910 		sc->iscsicaps = 0;
5911 		sc->nvmecaps = 0;
5912 		sc->rdmacaps = 0;
5913 	}
5914 	if (sc->nvmecaps || sc->rdmacaps) {
5915 		param[0] = FW_PARAM_PFVF(STAG_START);
5916 		param[1] = FW_PARAM_PFVF(STAG_END);
5917 		param[2] = FW_PARAM_PFVF(PBL_START);
5918 		param[3] = FW_PARAM_PFVF(PBL_END);
5919 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5920 		if (rc != 0) {
5921 			device_printf(sc->dev,
5922 			    "failed to query NVMe/RDMA parameters: %d.\n", rc);
5923 			return (rc);
5924 		}
5925 		sc->vres.stag.start = val[0];
5926 		sc->vres.stag.size = val[1] - val[0] + 1;
5927 		sc->vres.pbl.start = val[2];
5928 		sc->vres.pbl.size = val[3] - val[2] + 1;
5929 	}
5930 	if (sc->rdmacaps) {
5931 		param[0] = FW_PARAM_PFVF(RQ_START);
5932 		param[1] = FW_PARAM_PFVF(RQ_END);
5933 		param[2] = FW_PARAM_PFVF(SQRQ_START);
5934 		param[3] = FW_PARAM_PFVF(SQRQ_END);
5935 		param[4] = FW_PARAM_PFVF(CQ_START);
5936 		param[5] = FW_PARAM_PFVF(CQ_END);
5937 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5938 		if (rc != 0) {
5939 			device_printf(sc->dev,
5940 			    "failed to query RDMA parameters(1): %d.\n", rc);
5941 			return (rc);
5942 		}
5943 		sc->vres.rq.start = val[0];
5944 		sc->vres.rq.size = val[1] - val[0] + 1;
5945 		sc->vres.qp.start = val[2];
5946 		sc->vres.qp.size = val[3] - val[2] + 1;
5947 		sc->vres.cq.start = val[4];
5948 		sc->vres.cq.size = val[5] - val[4] + 1;
5949 
5950 		param[0] = FW_PARAM_PFVF(OCQ_START);
5951 		param[1] = FW_PARAM_PFVF(OCQ_END);
5952 		param[2] = FW_PARAM_PFVF(SRQ_START);
5953 		param[3] = FW_PARAM_PFVF(SRQ_END);
5954 		param[4] = FW_PARAM_DEV(MAXORDIRD_QP);
5955 		param[5] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5956 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5957 		if (rc != 0) {
5958 			device_printf(sc->dev,
5959 			    "failed to query RDMA parameters(2): %d.\n", rc);
5960 			return (rc);
5961 		}
5962 		sc->vres.ocq.start = val[0];
5963 		sc->vres.ocq.size = val[1] - val[0] + 1;
5964 		sc->vres.srq.start = val[2];
5965 		sc->vres.srq.size = val[3] - val[2] + 1;
5966 		sc->params.max_ordird_qp = val[4];
5967 		sc->params.max_ird_adapter = val[5];
5968 	}
5969 	if (sc->iscsicaps) {
5970 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5971 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5972 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5973 		if (rc != 0) {
5974 			device_printf(sc->dev,
5975 			    "failed to query iSCSI parameters: %d.\n", rc);
5976 			return (rc);
5977 		}
5978 		sc->vres.iscsi.start = val[0];
5979 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5980 	}
5981 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5982 		param[0] = FW_PARAM_PFVF(TLS_START);
5983 		param[1] = FW_PARAM_PFVF(TLS_END);
5984 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5985 		if (rc != 0) {
5986 			device_printf(sc->dev,
5987 			    "failed to query TLS parameters: %d.\n", rc);
5988 			return (rc);
5989 		}
5990 		sc->vres.key.start = val[0];
5991 		sc->vres.key.size = val[1] - val[0] + 1;
5992 	}
5993 
5994 	/*
5995 	 * We've got the params we wanted to query directly from the firmware.
5996 	 * Grab some others via other means.
5997 	 */
5998 	t4_init_sge_params(sc);
5999 	t4_init_tp_params(sc);
6000 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
6001 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
6002 
6003 	rc = t4_verify_chip_settings(sc);
6004 	if (rc != 0)
6005 		return (rc);
6006 	t4_init_rx_buf_info(sc);
6007 
6008 	return (rc);
6009 }
6010 
6011 #ifdef KERN_TLS
6012 static void
6013 ktls_tick(void *arg)
6014 {
6015 	struct adapter *sc;
6016 	uint32_t tstamp;
6017 
6018 	sc = arg;
6019 	tstamp = tcp_ts_getticks();
6020 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
6021 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
6022 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
6023 }
6024 
6025 static int
6026 t6_config_kern_tls(struct adapter *sc, bool enable)
6027 {
6028 	int rc;
6029 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
6030 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
6031 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
6032 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
6033 
6034 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
6035 	if (rc != 0) {
6036 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
6037 		    enable ?  "enable" : "disable", rc);
6038 		return (rc);
6039 	}
6040 
6041 	if (enable) {
6042 		sc->flags |= KERN_TLS_ON;
6043 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
6044 		    C_HARDCLOCK);
6045 	} else {
6046 		sc->flags &= ~KERN_TLS_ON;
6047 		callout_stop(&sc->ktls_tick);
6048 	}
6049 
6050 	return (rc);
6051 }
6052 #endif
6053 
6054 static int
6055 set_params__post_init(struct adapter *sc)
6056 {
6057 	uint32_t mask, param, val;
6058 #ifdef TCP_OFFLOAD
6059 	int i, v, shift;
6060 #endif
6061 
6062 	/* ask for encapsulated CPLs */
6063 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
6064 	val = 1;
6065 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
6066 
6067 	/* Enable 32b port caps if the firmware supports it. */
6068 	param = FW_PARAM_PFVF(PORT_CAPS32);
6069 	val = 1;
6070 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
6071 		sc->params.port_caps32 = 1;
6072 
6073 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
6074 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
6075 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
6076 	    V_MASKFILTER(val - 1));
6077 
6078 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
6079 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
6080 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
6081 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
6082 	val = 0;
6083 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
6084 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
6085 		    F_ATTACKFILTERENABLE);
6086 		val |= F_DROPERRORATTACK;
6087 	}
6088 	if (t4_drop_ip_fragments != 0) {
6089 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
6090 		    F_FRAGMENTDROP);
6091 		val |= F_DROPERRORFRAG;
6092 	}
6093 	if (t4_drop_pkts_with_l2_errors != 0)
6094 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
6095 	if (t4_drop_pkts_with_l3_errors != 0) {
6096 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
6097 		    F_DROPERRORCSUMIP;
6098 	}
6099 	if (t4_drop_pkts_with_l4_errors != 0) {
6100 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
6101 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
6102 	}
6103 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
6104 
6105 #ifdef TCP_OFFLOAD
6106 	/*
6107 	 * Override the TOE timers with user provided tunables.  This is not the
6108 	 * recommended way to change the timers (the firmware config file is) so
6109 	 * these tunables are not documented.
6110 	 *
6111 	 * All the timer tunables are in microseconds.
6112 	 */
6113 	if (t4_toe_keepalive_idle != 0) {
6114 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
6115 		v &= M_KEEPALIVEIDLE;
6116 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
6117 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
6118 	}
6119 	if (t4_toe_keepalive_interval != 0) {
6120 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
6121 		v &= M_KEEPALIVEINTVL;
6122 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
6123 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
6124 	}
6125 	if (t4_toe_keepalive_count != 0) {
6126 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
6127 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
6128 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
6129 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
6130 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
6131 	}
6132 	if (t4_toe_rexmt_min != 0) {
6133 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
6134 		v &= M_RXTMIN;
6135 		t4_set_reg_field(sc, A_TP_RXT_MIN,
6136 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
6137 	}
6138 	if (t4_toe_rexmt_max != 0) {
6139 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
6140 		v &= M_RXTMAX;
6141 		t4_set_reg_field(sc, A_TP_RXT_MAX,
6142 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
6143 	}
6144 	if (t4_toe_rexmt_count != 0) {
6145 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
6146 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
6147 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
6148 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
6149 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
6150 	}
6151 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
6152 		if (t4_toe_rexmt_backoff[i] != -1) {
6153 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
6154 			shift = (i & 3) << 3;
6155 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
6156 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
6157 		}
6158 	}
6159 #endif
6160 
6161 	/*
6162 	 * Limit TOE connections to 2 reassembly "islands".  This is
6163 	 * required to permit migrating TOE connections to either
6164 	 * ULP_MODE_TCPDDP or UPL_MODE_TLS.
6165 	 */
6166 	t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG, V_PASSMODE(M_PASSMODE),
6167 	    V_PASSMODE(2));
6168 
6169 #ifdef KERN_TLS
6170 	if (is_ktls(sc)) {
6171 		sc->tlst.inline_keys = t4_tls_inline_keys;
6172 		if (t4_kern_tls != 0 && is_t6(sc)) {
6173 			sc->tlst.combo_wrs = t4_tls_combo_wrs;
6174 			t6_config_kern_tls(sc, true);
6175 		} else {
6176 			sc->tlst.short_records = t4_tls_short_records;
6177 			sc->tlst.partial_ghash = t4_tls_partial_ghash;
6178 		}
6179 	}
6180 #endif
6181 	return (0);
6182 }
6183 
6184 #undef FW_PARAM_PFVF
6185 #undef FW_PARAM_DEV
6186 
6187 static void
6188 t4_set_desc(struct adapter *sc)
6189 {
6190 	struct adapter_params *p = &sc->params;
6191 
6192 	device_set_descf(sc->dev, "Chelsio %s", p->vpd.id);
6193 }
6194 
6195 static inline void
6196 ifmedia_add4(struct ifmedia *ifm, int m)
6197 {
6198 
6199 	ifmedia_add(ifm, m, 0, NULL);
6200 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
6201 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
6202 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
6203 }
6204 
6205 /*
6206  * This is the selected media, which is not quite the same as the active media.
6207  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
6208  * and active are not the same, and "media: Ethernet selected" otherwise.
6209  */
6210 static void
6211 set_current_media(struct port_info *pi)
6212 {
6213 	struct link_config *lc;
6214 	struct ifmedia *ifm;
6215 	int mword;
6216 	u_int speed;
6217 
6218 	PORT_LOCK_ASSERT_OWNED(pi);
6219 
6220 	/* Leave current media alone if it's already set to IFM_NONE. */
6221 	ifm = &pi->media;
6222 	if (ifm->ifm_cur != NULL &&
6223 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
6224 		return;
6225 
6226 	lc = &pi->link_cfg;
6227 	if (lc->requested_aneg != AUTONEG_DISABLE &&
6228 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
6229 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
6230 		return;
6231 	}
6232 	mword = IFM_ETHER | IFM_FDX;
6233 	if (lc->requested_fc & PAUSE_TX)
6234 		mword |= IFM_ETH_TXPAUSE;
6235 	if (lc->requested_fc & PAUSE_RX)
6236 		mword |= IFM_ETH_RXPAUSE;
6237 	if (lc->requested_speed == 0)
6238 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
6239 	else
6240 		speed = lc->requested_speed;
6241 	mword |= port_mword(pi, speed_to_fwcap(speed));
6242 	ifmedia_set(ifm, mword);
6243 }
6244 
6245 /*
6246  * Returns true if the ifmedia list for the port cannot change.
6247  */
6248 static bool
6249 fixed_ifmedia(struct port_info *pi)
6250 {
6251 
6252 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
6253 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
6254 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
6255 	    pi->port_type == FW_PORT_TYPE_KX4 ||
6256 	    pi->port_type == FW_PORT_TYPE_KX ||
6257 	    pi->port_type == FW_PORT_TYPE_KR ||
6258 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
6259 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
6260 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
6261 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
6262 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
6263 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
6264 }
6265 
6266 static void
6267 build_medialist(struct port_info *pi)
6268 {
6269 	uint32_t ss, speed;
6270 	int unknown, mword, bit;
6271 	struct link_config *lc;
6272 	struct ifmedia *ifm;
6273 
6274 	PORT_LOCK_ASSERT_OWNED(pi);
6275 
6276 	if (pi->flags & FIXED_IFMEDIA)
6277 		return;
6278 
6279 	/*
6280 	 * Rebuild the ifmedia list.
6281 	 */
6282 	ifm = &pi->media;
6283 	ifmedia_removeall(ifm);
6284 	lc = &pi->link_cfg;
6285 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
6286 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
6287 		MPASS(ss != 0);
6288 no_media:
6289 		MPASS(LIST_EMPTY(&ifm->ifm_list));
6290 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
6291 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
6292 		return;
6293 	}
6294 
6295 	unknown = 0;
6296 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
6297 		speed = 1 << bit;
6298 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
6299 		if (ss & speed) {
6300 			mword = port_mword(pi, speed);
6301 			if (mword == IFM_NONE) {
6302 				goto no_media;
6303 			} else if (mword == IFM_UNKNOWN)
6304 				unknown++;
6305 			else
6306 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
6307 		}
6308 	}
6309 	if (unknown > 0) /* Add one unknown for all unknown media types. */
6310 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
6311 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
6312 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
6313 
6314 	set_current_media(pi);
6315 }
6316 
6317 /*
6318  * Initialize the requested fields in the link config based on driver tunables.
6319  */
6320 static void
6321 init_link_config(struct port_info *pi)
6322 {
6323 	struct link_config *lc = &pi->link_cfg;
6324 
6325 	PORT_LOCK_ASSERT_OWNED(pi);
6326 
6327 	lc->requested_caps = 0;
6328 	lc->requested_speed = 0;
6329 
6330 	if (t4_autoneg == 0)
6331 		lc->requested_aneg = AUTONEG_DISABLE;
6332 	else if (t4_autoneg == 1)
6333 		lc->requested_aneg = AUTONEG_ENABLE;
6334 	else
6335 		lc->requested_aneg = AUTONEG_AUTO;
6336 
6337 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
6338 	    PAUSE_AUTONEG);
6339 
6340 	if (t4_fec & FEC_AUTO)
6341 		lc->requested_fec = FEC_AUTO;
6342 	else if (t4_fec == 0)
6343 		lc->requested_fec = FEC_NONE;
6344 	else {
6345 		/* -1 is handled by the FEC_AUTO block above and not here. */
6346 		lc->requested_fec = t4_fec &
6347 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
6348 		if (lc->requested_fec == 0)
6349 			lc->requested_fec = FEC_AUTO;
6350 	}
6351 	if (t4_force_fec < 0)
6352 		lc->force_fec = -1;
6353 	else if (t4_force_fec > 0)
6354 		lc->force_fec = 1;
6355 	else
6356 		lc->force_fec = 0;
6357 }
6358 
6359 /*
6360  * Makes sure that all requested settings comply with what's supported by the
6361  * port.  Returns the number of settings that were invalid and had to be fixed.
6362  */
6363 static int
6364 fixup_link_config(struct port_info *pi)
6365 {
6366 	int n = 0;
6367 	struct link_config *lc = &pi->link_cfg;
6368 	uint32_t fwspeed;
6369 
6370 	PORT_LOCK_ASSERT_OWNED(pi);
6371 
6372 	/* Speed (when not autonegotiating) */
6373 	if (lc->requested_speed != 0) {
6374 		fwspeed = speed_to_fwcap(lc->requested_speed);
6375 		if ((fwspeed & lc->pcaps) == 0) {
6376 			n++;
6377 			lc->requested_speed = 0;
6378 		}
6379 	}
6380 
6381 	/* Link autonegotiation */
6382 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
6383 	    lc->requested_aneg == AUTONEG_DISABLE ||
6384 	    lc->requested_aneg == AUTONEG_AUTO);
6385 	if (lc->requested_aneg == AUTONEG_ENABLE &&
6386 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
6387 		n++;
6388 		lc->requested_aneg = AUTONEG_AUTO;
6389 	}
6390 
6391 	/* Flow control */
6392 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
6393 	if (lc->requested_fc & PAUSE_TX &&
6394 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
6395 		n++;
6396 		lc->requested_fc &= ~PAUSE_TX;
6397 	}
6398 	if (lc->requested_fc & PAUSE_RX &&
6399 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
6400 		n++;
6401 		lc->requested_fc &= ~PAUSE_RX;
6402 	}
6403 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
6404 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
6405 		n++;
6406 		lc->requested_fc |= PAUSE_AUTONEG;
6407 	}
6408 
6409 	/* FEC */
6410 	if ((lc->requested_fec & FEC_RS &&
6411 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
6412 	    (lc->requested_fec & FEC_BASER_RS &&
6413 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
6414 		n++;
6415 		lc->requested_fec = FEC_AUTO;
6416 	}
6417 
6418 	return (n);
6419 }
6420 
6421 /*
6422  * Apply the requested L1 settings, which are expected to be valid, to the
6423  * hardware.
6424  */
6425 static int
6426 apply_link_config(struct port_info *pi)
6427 {
6428 	struct adapter *sc = pi->adapter;
6429 	struct link_config *lc = &pi->link_cfg;
6430 	int rc;
6431 
6432 #ifdef INVARIANTS
6433 	ASSERT_SYNCHRONIZED_OP(sc);
6434 	PORT_LOCK_ASSERT_OWNED(pi);
6435 
6436 	if (lc->requested_aneg == AUTONEG_ENABLE)
6437 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
6438 	if (!(lc->requested_fc & PAUSE_AUTONEG))
6439 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
6440 	if (lc->requested_fc & PAUSE_TX)
6441 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
6442 	if (lc->requested_fc & PAUSE_RX)
6443 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
6444 	if (lc->requested_fec & FEC_RS)
6445 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
6446 	if (lc->requested_fec & FEC_BASER_RS)
6447 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
6448 #endif
6449 	if (!(sc->flags & IS_VF)) {
6450 		rc = -t4_link_l1cfg(sc, sc->mbox, pi->hw_port, lc);
6451 		if (rc != 0) {
6452 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
6453 			return (rc);
6454 		}
6455 	}
6456 
6457 	/*
6458 	 * An L1_CFG will almost always result in a link-change event if the
6459 	 * link is up, and the driver will refresh the actual fec/fc/etc. when
6460 	 * the notification is processed.  If the link is down then the actual
6461 	 * settings are meaningless.
6462 	 *
6463 	 * This takes care of the case where a change in the L1 settings may not
6464 	 * result in a notification.
6465 	 */
6466 	if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
6467 		lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
6468 
6469 	return (0);
6470 }
6471 
6472 #define FW_MAC_EXACT_CHUNK	7
6473 struct mcaddr_ctx {
6474 	if_t ifp;
6475 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
6476 	uint64_t hash;
6477 	int i;
6478 	int del;
6479 	int rc;
6480 };
6481 
6482 static u_int
6483 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
6484 {
6485 	struct mcaddr_ctx *ctx = arg;
6486 	struct vi_info *vi = if_getsoftc(ctx->ifp);
6487 	struct port_info *pi = vi->pi;
6488 	struct adapter *sc = pi->adapter;
6489 
6490 	if (ctx->rc < 0)
6491 		return (0);
6492 
6493 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
6494 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
6495 	ctx->i++;
6496 
6497 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
6498 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
6499 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
6500 		if (ctx->rc < 0) {
6501 			int j;
6502 
6503 			for (j = 0; j < ctx->i; j++) {
6504 				if_printf(ctx->ifp,
6505 				    "failed to add mc address"
6506 				    " %02x:%02x:%02x:"
6507 				    "%02x:%02x:%02x rc=%d\n",
6508 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
6509 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
6510 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
6511 				    -ctx->rc);
6512 			}
6513 			return (0);
6514 		}
6515 		ctx->del = 0;
6516 		ctx->i = 0;
6517 	}
6518 
6519 	return (1);
6520 }
6521 
6522 /*
6523  * Program the port's XGMAC based on parameters in ifnet.  The caller also
6524  * indicates which parameters should be programmed (the rest are left alone).
6525  */
6526 int
6527 update_mac_settings(if_t ifp, int flags)
6528 {
6529 	int rc = 0;
6530 	struct vi_info *vi = if_getsoftc(ifp);
6531 	struct port_info *pi = vi->pi;
6532 	struct adapter *sc = pi->adapter;
6533 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
6534 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
6535 
6536 	ASSERT_SYNCHRONIZED_OP(sc);
6537 	KASSERT(flags, ("%s: not told what to update.", __func__));
6538 
6539 	if (flags & XGMAC_MTU)
6540 		mtu = if_getmtu(ifp);
6541 
6542 	if (flags & XGMAC_PROMISC)
6543 		promisc = if_getflags(ifp) & IFF_PROMISC ? 1 : 0;
6544 
6545 	if (flags & XGMAC_ALLMULTI)
6546 		allmulti = if_getflags(ifp) & IFF_ALLMULTI ? 1 : 0;
6547 
6548 	if (flags & XGMAC_VLANEX)
6549 		vlanex = if_getcapenable(ifp) & IFCAP_VLAN_HWTAGGING ? 1 : 0;
6550 
6551 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
6552 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
6553 		    allmulti, 1, vlanex, false);
6554 		if (rc) {
6555 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
6556 			    rc);
6557 			return (rc);
6558 		}
6559 	}
6560 
6561 	if (flags & XGMAC_UCADDR) {
6562 		uint8_t ucaddr[ETHER_ADDR_LEN];
6563 
6564 		bcopy(if_getlladdr(ifp), ucaddr, sizeof(ucaddr));
6565 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
6566 		    ucaddr, true, &vi->smt_idx);
6567 		if (rc < 0) {
6568 			rc = -rc;
6569 			if_printf(ifp, "change_mac failed: %d\n", rc);
6570 			return (rc);
6571 		} else {
6572 			vi->xact_addr_filt = rc;
6573 			rc = 0;
6574 		}
6575 	}
6576 
6577 	if (flags & XGMAC_MCADDRS) {
6578 		struct epoch_tracker et;
6579 		struct mcaddr_ctx ctx;
6580 		int j;
6581 
6582 		ctx.ifp = ifp;
6583 		ctx.hash = 0;
6584 		ctx.i = 0;
6585 		ctx.del = 1;
6586 		ctx.rc = 0;
6587 		/*
6588 		 * Unlike other drivers, we accumulate list of pointers into
6589 		 * interface address lists and we need to keep it safe even
6590 		 * after if_foreach_llmaddr() returns, thus we must enter the
6591 		 * network epoch.
6592 		 */
6593 		NET_EPOCH_ENTER(et);
6594 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6595 		if (ctx.rc < 0) {
6596 			NET_EPOCH_EXIT(et);
6597 			rc = -ctx.rc;
6598 			return (rc);
6599 		}
6600 		if (ctx.i > 0) {
6601 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6602 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6603 			NET_EPOCH_EXIT(et);
6604 			if (rc < 0) {
6605 				rc = -rc;
6606 				for (j = 0; j < ctx.i; j++) {
6607 					if_printf(ifp,
6608 					    "failed to add mcast address"
6609 					    " %02x:%02x:%02x:"
6610 					    "%02x:%02x:%02x rc=%d\n",
6611 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6612 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6613 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6614 					    rc);
6615 				}
6616 				return (rc);
6617 			}
6618 			ctx.del = 0;
6619 		} else
6620 			NET_EPOCH_EXIT(et);
6621 
6622 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6623 		if (rc != 0)
6624 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6625 			    rc);
6626 		if (ctx.del == 0) {
6627 			/* We clobbered the VXLAN entry if there was one. */
6628 			pi->vxlan_tcam_entry = false;
6629 		}
6630 	}
6631 
6632 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6633 	    pi->vxlan_tcam_entry == false) {
6634 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6635 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6636 		    true);
6637 		if (rc < 0) {
6638 			rc = -rc;
6639 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6640 			    rc);
6641 		} else {
6642 			MPASS(rc == sc->rawf_base + pi->port_id);
6643 			rc = 0;
6644 			pi->vxlan_tcam_entry = true;
6645 		}
6646 	}
6647 
6648 	return (rc);
6649 }
6650 
6651 /*
6652  * {begin|end}_synchronized_op must be called from the same thread.
6653  */
6654 int
6655 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6656     char *wmesg)
6657 {
6658 	int rc;
6659 
6660 #ifdef WITNESS
6661 	/* the caller thinks it's ok to sleep, but is it really? */
6662 	if (flags & SLEEP_OK)
6663 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, __func__);
6664 #endif
6665 	ADAPTER_LOCK(sc);
6666 	for (;;) {
6667 
6668 		if (vi && IS_DETACHING(vi)) {
6669 			rc = ENXIO;
6670 			goto done;
6671 		}
6672 
6673 		if (!IS_BUSY(sc)) {
6674 			rc = 0;
6675 			break;
6676 		}
6677 
6678 		if (!(flags & SLEEP_OK)) {
6679 			rc = EBUSY;
6680 			goto done;
6681 		}
6682 
6683 		if (mtx_sleep(&sc->flags, &sc->sc_lock,
6684 		    flags & INTR_OK ? PCATCH : 0, wmesg, 0)) {
6685 			rc = EINTR;
6686 			goto done;
6687 		}
6688 	}
6689 
6690 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6691 	SET_BUSY(sc);
6692 #ifdef INVARIANTS
6693 	sc->last_op = wmesg;
6694 	sc->last_op_thr = curthread;
6695 	sc->last_op_flags = flags;
6696 #endif
6697 
6698 done:
6699 	if (!(flags & HOLD_LOCK) || rc)
6700 		ADAPTER_UNLOCK(sc);
6701 
6702 	return (rc);
6703 }
6704 
6705 /*
6706  * Tell if_ioctl and if_init that the VI is going away.  This is
6707  * special variant of begin_synchronized_op and must be paired with a
6708  * call to end_vi_detach.
6709  */
6710 void
6711 begin_vi_detach(struct adapter *sc, struct vi_info *vi)
6712 {
6713 	ADAPTER_LOCK(sc);
6714 	SET_DETACHING(vi);
6715 	wakeup(&sc->flags);
6716 	while (IS_BUSY(sc))
6717 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6718 	SET_BUSY(sc);
6719 #ifdef INVARIANTS
6720 	sc->last_op = "t4detach";
6721 	sc->last_op_thr = curthread;
6722 	sc->last_op_flags = 0;
6723 #endif
6724 	ADAPTER_UNLOCK(sc);
6725 }
6726 
6727 void
6728 end_vi_detach(struct adapter *sc, struct vi_info *vi)
6729 {
6730 	ADAPTER_LOCK(sc);
6731 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6732 	CLR_BUSY(sc);
6733 	CLR_DETACHING(vi);
6734 	wakeup(&sc->flags);
6735 	ADAPTER_UNLOCK(sc);
6736 }
6737 
6738 /*
6739  * {begin|end}_synchronized_op must be called from the same thread.
6740  */
6741 void
6742 end_synchronized_op(struct adapter *sc, int flags)
6743 {
6744 
6745 	if (flags & LOCK_HELD)
6746 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6747 	else
6748 		ADAPTER_LOCK(sc);
6749 
6750 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6751 	CLR_BUSY(sc);
6752 	wakeup(&sc->flags);
6753 	ADAPTER_UNLOCK(sc);
6754 }
6755 
6756 static int
6757 cxgbe_init_synchronized(struct vi_info *vi)
6758 {
6759 	struct port_info *pi = vi->pi;
6760 	struct adapter *sc = pi->adapter;
6761 	if_t ifp = vi->ifp;
6762 	int rc = 0, i;
6763 	struct sge_txq *txq;
6764 
6765 	ASSERT_SYNCHRONIZED_OP(sc);
6766 
6767 	if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
6768 		return (0);	/* already running */
6769 
6770 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6771 		return (rc);	/* error message displayed already */
6772 
6773 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6774 		return (rc); /* error message displayed already */
6775 
6776 	rc = update_mac_settings(ifp, XGMAC_ALL);
6777 	if (rc)
6778 		goto done;	/* error message displayed already */
6779 
6780 	PORT_LOCK(pi);
6781 	if (pi->up_vis == 0) {
6782 		t4_update_port_info(pi);
6783 		fixup_link_config(pi);
6784 		build_medialist(pi);
6785 		apply_link_config(pi);
6786 	}
6787 
6788 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6789 	if (rc != 0) {
6790 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6791 		PORT_UNLOCK(pi);
6792 		goto done;
6793 	}
6794 
6795 	/*
6796 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6797 	 * if this changes.
6798 	 */
6799 
6800 	for_each_txq(vi, i, txq) {
6801 		TXQ_LOCK(txq);
6802 		txq->eq.flags |= EQ_ENABLED;
6803 		TXQ_UNLOCK(txq);
6804 	}
6805 
6806 	/*
6807 	 * The first iq of the first port to come up is used for tracing.
6808 	 */
6809 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6810 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6811 		t4_set_trace_rss_control(sc, pi->tx_chan, sc->traceq);
6812 		pi->flags |= HAS_TRACEQ;
6813 	}
6814 
6815 	/* all ok */
6816 	pi->up_vis++;
6817 	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
6818 	if (pi->link_cfg.link_ok)
6819 		t4_os_link_changed(pi);
6820 	PORT_UNLOCK(pi);
6821 
6822 	mtx_lock(&vi->tick_mtx);
6823 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
6824 		callout_reset(&vi->tick, hz, vi_tick, vi);
6825 	else
6826 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6827 	mtx_unlock(&vi->tick_mtx);
6828 done:
6829 	if (rc != 0)
6830 		cxgbe_uninit_synchronized(vi);
6831 
6832 	return (rc);
6833 }
6834 
6835 /*
6836  * Idempotent.
6837  */
6838 static int
6839 cxgbe_uninit_synchronized(struct vi_info *vi)
6840 {
6841 	struct port_info *pi = vi->pi;
6842 	struct adapter *sc = pi->adapter;
6843 	if_t ifp = vi->ifp;
6844 	int rc, i;
6845 	struct sge_txq *txq;
6846 
6847 	ASSERT_SYNCHRONIZED_OP(sc);
6848 
6849 	if (!(vi->flags & VI_INIT_DONE)) {
6850 		if (__predict_false(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6851 			KASSERT(0, ("uninited VI is running"));
6852 			if_printf(ifp, "uninited VI with running ifnet.  "
6853 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6854 			    "if_drv_flags 0x%08x\n", vi->flags, if_getflags(ifp),
6855 			    if_getdrvflags(ifp));
6856 		}
6857 		return (0);
6858 	}
6859 
6860 	/*
6861 	 * Disable the VI so that all its data in either direction is discarded
6862 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6863 	 * tick) intact as the TP can deliver negative advice or data that it's
6864 	 * holding in its RAM (for an offloaded connection) even after the VI is
6865 	 * disabled.
6866 	 */
6867 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6868 	if (rc) {
6869 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6870 		return (rc);
6871 	}
6872 
6873 	for_each_txq(vi, i, txq) {
6874 		TXQ_LOCK(txq);
6875 		txq->eq.flags &= ~EQ_ENABLED;
6876 		TXQ_UNLOCK(txq);
6877 	}
6878 
6879 	mtx_lock(&vi->tick_mtx);
6880 	callout_stop(&vi->tick);
6881 	mtx_unlock(&vi->tick_mtx);
6882 
6883 	PORT_LOCK(pi);
6884 	if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6885 		PORT_UNLOCK(pi);
6886 		return (0);
6887 	}
6888 	if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
6889 	pi->up_vis--;
6890 	if (pi->up_vis > 0) {
6891 		PORT_UNLOCK(pi);
6892 		return (0);
6893 	}
6894 
6895 	pi->link_cfg.link_ok = false;
6896 	pi->link_cfg.speed = 0;
6897 	pi->link_cfg.link_down_rc = 255;
6898 	t4_os_link_changed(pi);
6899 	PORT_UNLOCK(pi);
6900 
6901 	return (0);
6902 }
6903 
6904 /*
6905  * It is ok for this function to fail midway and return right away.  t4_detach
6906  * will walk the entire sc->irq list and clean up whatever is valid.
6907  */
6908 int
6909 t4_setup_intr_handlers(struct adapter *sc)
6910 {
6911 	int rc, rid, p, q, v;
6912 	char s[8];
6913 	struct irq *irq;
6914 	struct port_info *pi;
6915 	struct vi_info *vi;
6916 	struct sge *sge = &sc->sge;
6917 	struct sge_rxq *rxq;
6918 #ifdef TCP_OFFLOAD
6919 	struct sge_ofld_rxq *ofld_rxq;
6920 #endif
6921 #ifdef DEV_NETMAP
6922 	struct sge_nm_rxq *nm_rxq;
6923 #endif
6924 #ifdef RSS
6925 	int nbuckets = rss_getnumbuckets();
6926 #endif
6927 
6928 	/*
6929 	 * Setup interrupts.
6930 	 */
6931 	irq = &sc->irq[0];
6932 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6933 	if (forwarding_intr_to_fwq(sc))
6934 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6935 
6936 	/* Multiple interrupts. */
6937 	if (sc->flags & IS_VF)
6938 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6939 		    ("%s: too few intr.", __func__));
6940 	else
6941 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6942 		    ("%s: too few intr.", __func__));
6943 
6944 	/* The first one is always error intr on PFs */
6945 	if (!(sc->flags & IS_VF)) {
6946 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6947 		if (rc != 0)
6948 			return (rc);
6949 		irq++;
6950 		rid++;
6951 	}
6952 
6953 	/* The second one is always the firmware event queue (first on VFs) */
6954 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6955 	if (rc != 0)
6956 		return (rc);
6957 	irq++;
6958 	rid++;
6959 
6960 	for_each_port(sc, p) {
6961 		pi = sc->port[p];
6962 		for_each_vi(pi, v, vi) {
6963 			vi->first_intr = rid - 1;
6964 
6965 			if (vi->nnmrxq > 0) {
6966 				int n = max(vi->nrxq, vi->nnmrxq);
6967 
6968 				rxq = &sge->rxq[vi->first_rxq];
6969 #ifdef DEV_NETMAP
6970 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6971 #endif
6972 				for (q = 0; q < n; q++) {
6973 					snprintf(s, sizeof(s), "%x%c%x", p,
6974 					    'a' + v, q);
6975 					if (q < vi->nrxq)
6976 						irq->rxq = rxq++;
6977 #ifdef DEV_NETMAP
6978 					if (q < vi->nnmrxq)
6979 						irq->nm_rxq = nm_rxq++;
6980 
6981 					if (irq->nm_rxq != NULL &&
6982 					    irq->rxq == NULL) {
6983 						/* Netmap rx only */
6984 						rc = t4_alloc_irq(sc, irq, rid,
6985 						    t4_nm_intr, irq->nm_rxq, s);
6986 					}
6987 					if (irq->nm_rxq != NULL &&
6988 					    irq->rxq != NULL) {
6989 						/* NIC and Netmap rx */
6990 						rc = t4_alloc_irq(sc, irq, rid,
6991 						    t4_vi_intr, irq, s);
6992 					}
6993 #endif
6994 					if (irq->rxq != NULL &&
6995 					    irq->nm_rxq == NULL) {
6996 						/* NIC rx only */
6997 						rc = t4_alloc_irq(sc, irq, rid,
6998 						    t4_intr, irq->rxq, s);
6999 					}
7000 					if (rc != 0)
7001 						return (rc);
7002 #ifdef RSS
7003 					if (q < vi->nrxq) {
7004 						bus_bind_intr(sc->dev, irq->res,
7005 						    rss_getcpu(q % nbuckets));
7006 					}
7007 #endif
7008 					irq++;
7009 					rid++;
7010 					vi->nintr++;
7011 				}
7012 			} else {
7013 				for_each_rxq(vi, q, rxq) {
7014 					snprintf(s, sizeof(s), "%x%c%x", p,
7015 					    'a' + v, q);
7016 					rc = t4_alloc_irq(sc, irq, rid,
7017 					    t4_intr, rxq, s);
7018 					if (rc != 0)
7019 						return (rc);
7020 #ifdef RSS
7021 					bus_bind_intr(sc->dev, irq->res,
7022 					    rss_getcpu(q % nbuckets));
7023 #endif
7024 					irq++;
7025 					rid++;
7026 					vi->nintr++;
7027 				}
7028 			}
7029 #ifdef TCP_OFFLOAD
7030 			for_each_ofld_rxq(vi, q, ofld_rxq) {
7031 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
7032 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
7033 				    ofld_rxq, s);
7034 				if (rc != 0)
7035 					return (rc);
7036 				irq++;
7037 				rid++;
7038 				vi->nintr++;
7039 			}
7040 #endif
7041 		}
7042 	}
7043 	MPASS(irq == &sc->irq[sc->intr_count]);
7044 
7045 	return (0);
7046 }
7047 
7048 static void
7049 write_global_rss_key(struct adapter *sc)
7050 {
7051 	int i;
7052 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
7053 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
7054 
7055 	CTASSERT(RSS_KEYSIZE == 40);
7056 
7057 	rss_getkey((void *)&raw_rss_key[0]);
7058 	for (i = 0; i < nitems(rss_key); i++) {
7059 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
7060 	}
7061 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
7062 }
7063 
7064 /*
7065  * Idempotent.
7066  */
7067 static int
7068 adapter_full_init(struct adapter *sc)
7069 {
7070 	int rc, i;
7071 
7072 	ASSERT_SYNCHRONIZED_OP(sc);
7073 
7074 	/*
7075 	 * queues that belong to the adapter (not any particular port).
7076 	 */
7077 	rc = t4_setup_adapter_queues(sc);
7078 	if (rc != 0)
7079 		return (rc);
7080 
7081 	MPASS(sc->params.nports <= nitems(sc->tq));
7082 	for (i = 0; i < sc->params.nports; i++) {
7083 		if (sc->tq[i] != NULL)
7084 			continue;
7085 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
7086 		    taskqueue_thread_enqueue, &sc->tq[i]);
7087 		if (sc->tq[i] == NULL) {
7088 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
7089 			return (ENOMEM);
7090 		}
7091 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
7092 		    device_get_nameunit(sc->dev), i);
7093 	}
7094 
7095 	if (!(sc->flags & IS_VF)) {
7096 		write_global_rss_key(sc);
7097 		t4_intr_enable(sc);
7098 	}
7099 	return (0);
7100 }
7101 
7102 int
7103 adapter_init(struct adapter *sc)
7104 {
7105 	int rc;
7106 
7107 	ASSERT_SYNCHRONIZED_OP(sc);
7108 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
7109 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
7110 	    ("%s: FULL_INIT_DONE already", __func__));
7111 
7112 	rc = adapter_full_init(sc);
7113 	if (rc != 0)
7114 		adapter_full_uninit(sc);
7115 	else
7116 		sc->flags |= FULL_INIT_DONE;
7117 
7118 	return (rc);
7119 }
7120 
7121 /*
7122  * Idempotent.
7123  */
7124 static void
7125 adapter_full_uninit(struct adapter *sc)
7126 {
7127 	int i;
7128 
7129 	t4_teardown_adapter_queues(sc);
7130 
7131 	for (i = 0; i < nitems(sc->tq); i++) {
7132 		if (sc->tq[i] == NULL)
7133 			continue;
7134 		taskqueue_free(sc->tq[i]);
7135 		sc->tq[i] = NULL;
7136 	}
7137 
7138 	sc->flags &= ~FULL_INIT_DONE;
7139 }
7140 
7141 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
7142     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
7143     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
7144     RSS_HASHTYPE_RSS_UDP_IPV6)
7145 
7146 /* Translates kernel hash types to hardware. */
7147 static int
7148 hashconfig_to_hashen(int hashconfig)
7149 {
7150 	int hashen = 0;
7151 
7152 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
7153 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
7154 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
7155 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
7156 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
7157 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
7158 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
7159 	}
7160 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
7161 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
7162 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
7163 	}
7164 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
7165 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
7166 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
7167 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
7168 
7169 	return (hashen);
7170 }
7171 
7172 /* Translates hardware hash types to kernel. */
7173 static int
7174 hashen_to_hashconfig(int hashen)
7175 {
7176 	int hashconfig = 0;
7177 
7178 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
7179 		/*
7180 		 * If UDP hashing was enabled it must have been enabled for
7181 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
7182 		 * enabling any 4-tuple hash is nonsense configuration.
7183 		 */
7184 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
7185 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
7186 
7187 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
7188 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
7189 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
7190 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
7191 	}
7192 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
7193 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
7194 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
7195 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
7196 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
7197 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
7198 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
7199 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
7200 
7201 	return (hashconfig);
7202 }
7203 
7204 /*
7205  * Idempotent.
7206  */
7207 static int
7208 vi_full_init(struct vi_info *vi)
7209 {
7210 	struct adapter *sc = vi->adapter;
7211 	struct sge_rxq *rxq;
7212 	int rc, i, j, extra;
7213 	int hashconfig = rss_gethashconfig();
7214 #ifdef RSS
7215 	int nbuckets = rss_getnumbuckets();
7216 #endif
7217 
7218 	ASSERT_SYNCHRONIZED_OP(sc);
7219 
7220 	/*
7221 	 * Allocate tx/rx/fl queues for this VI.
7222 	 */
7223 	rc = t4_setup_vi_queues(vi);
7224 	if (rc != 0)
7225 		return (rc);
7226 
7227 	/*
7228 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
7229 	 */
7230 	if (vi->nrxq > vi->rss_size) {
7231 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
7232 		    "some queues will never receive traffic.\n", vi->nrxq,
7233 		    vi->rss_size);
7234 	} else if (vi->rss_size % vi->nrxq) {
7235 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
7236 		    "expect uneven traffic distribution.\n", vi->nrxq,
7237 		    vi->rss_size);
7238 	}
7239 #ifdef RSS
7240 	if (vi->nrxq != nbuckets) {
7241 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
7242 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
7243 	}
7244 #endif
7245 	if (vi->rss == NULL)
7246 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
7247 		    M_ZERO | M_WAITOK);
7248 	for (i = 0; i < vi->rss_size;) {
7249 #ifdef RSS
7250 		j = rss_get_indirection_to_bucket(i);
7251 		j %= vi->nrxq;
7252 		rxq = &sc->sge.rxq[vi->first_rxq + j];
7253 		vi->rss[i++] = rxq->iq.abs_id;
7254 #else
7255 		for_each_rxq(vi, j, rxq) {
7256 			vi->rss[i++] = rxq->iq.abs_id;
7257 			if (i == vi->rss_size)
7258 				break;
7259 		}
7260 #endif
7261 	}
7262 
7263 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
7264 	    vi->rss, vi->rss_size);
7265 	if (rc != 0) {
7266 		CH_ERR(vi, "rss_config failed: %d\n", rc);
7267 		return (rc);
7268 	}
7269 
7270 	vi->hashen = hashconfig_to_hashen(hashconfig);
7271 
7272 	/*
7273 	 * We may have had to enable some hashes even though the global config
7274 	 * wants them disabled.  This is a potential problem that must be
7275 	 * reported to the user.
7276 	 */
7277 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
7278 
7279 	/*
7280 	 * If we consider only the supported hash types, then the enabled hashes
7281 	 * are a superset of the requested hashes.  In other words, there cannot
7282 	 * be any supported hash that was requested but not enabled, but there
7283 	 * can be hashes that were not requested but had to be enabled.
7284 	 */
7285 	extra &= SUPPORTED_RSS_HASHTYPES;
7286 	MPASS((extra & hashconfig) == 0);
7287 
7288 	if (extra) {
7289 		CH_ALERT(vi,
7290 		    "global RSS config (0x%x) cannot be accommodated.\n",
7291 		    hashconfig);
7292 	}
7293 	if (extra & RSS_HASHTYPE_RSS_IPV4)
7294 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
7295 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
7296 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
7297 	if (extra & RSS_HASHTYPE_RSS_IPV6)
7298 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
7299 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
7300 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
7301 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
7302 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
7303 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
7304 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
7305 
7306 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
7307 	    0, 0);
7308 	if (rc != 0) {
7309 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
7310 		return (rc);
7311 	}
7312 
7313 	return (0);
7314 }
7315 
7316 int
7317 vi_init(struct vi_info *vi)
7318 {
7319 	int rc;
7320 
7321 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
7322 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
7323 	    ("%s: VI_INIT_DONE already", __func__));
7324 
7325 	rc = vi_full_init(vi);
7326 	if (rc != 0)
7327 		vi_full_uninit(vi);
7328 	else
7329 		vi->flags |= VI_INIT_DONE;
7330 
7331 	return (rc);
7332 }
7333 
7334 /*
7335  * Idempotent.
7336  */
7337 static void
7338 vi_full_uninit(struct vi_info *vi)
7339 {
7340 
7341 	if (vi->flags & VI_INIT_DONE) {
7342 		quiesce_vi(vi);
7343 		free(vi->rss, M_CXGBE);
7344 		free(vi->nm_rss, M_CXGBE);
7345 	}
7346 
7347 	t4_teardown_vi_queues(vi);
7348 	vi->flags &= ~VI_INIT_DONE;
7349 }
7350 
7351 static void
7352 quiesce_txq(struct sge_txq *txq)
7353 {
7354 	struct sge_eq *eq = &txq->eq;
7355 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
7356 
7357 	MPASS(eq->flags & EQ_SW_ALLOCATED);
7358 	MPASS(!(eq->flags & EQ_ENABLED));
7359 
7360 	/* Wait for the mp_ring to empty. */
7361 	while (!mp_ring_is_idle(txq->r)) {
7362 		mp_ring_check_drainage(txq->r, 4096);
7363 		pause("rquiesce", 1);
7364 	}
7365 	MPASS(txq->txp.npkt == 0);
7366 
7367 	if (eq->flags & EQ_HW_ALLOCATED) {
7368 		/*
7369 		 * Hardware is alive and working normally.  Wait for it to
7370 		 * finish and then wait for the driver to catch up and reclaim
7371 		 * all descriptors.
7372 		 */
7373 		while (spg->cidx != htobe16(eq->pidx))
7374 			pause("equiesce", 1);
7375 		while (eq->cidx != eq->pidx)
7376 			pause("dquiesce", 1);
7377 	} else {
7378 		/*
7379 		 * Hardware is unavailable.  Discard all pending tx and reclaim
7380 		 * descriptors directly.
7381 		 */
7382 		TXQ_LOCK(txq);
7383 		while (eq->cidx != eq->pidx) {
7384 			struct mbuf *m, *nextpkt;
7385 			struct tx_sdesc *txsd;
7386 
7387 			txsd = &txq->sdesc[eq->cidx];
7388 			for (m = txsd->m; m != NULL; m = nextpkt) {
7389 				nextpkt = m->m_nextpkt;
7390 				m->m_nextpkt = NULL;
7391 				m_freem(m);
7392 			}
7393 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
7394 		}
7395 		spg->pidx = spg->cidx = htobe16(eq->cidx);
7396 		TXQ_UNLOCK(txq);
7397 	}
7398 }
7399 
7400 static void
7401 quiesce_wrq(struct sge_wrq *wrq)
7402 {
7403 	struct wrqe *wr;
7404 
7405 	TXQ_LOCK(wrq);
7406 	while ((wr = STAILQ_FIRST(&wrq->wr_list)) != NULL) {
7407 		STAILQ_REMOVE_HEAD(&wrq->wr_list, link);
7408 #ifdef INVARIANTS
7409 		wrq->nwr_pending--;
7410 		wrq->ndesc_needed -= howmany(wr->wr_len, EQ_ESIZE);
7411 #endif
7412 		free(wr, M_CXGBE);
7413 	}
7414 	MPASS(wrq->nwr_pending == 0);
7415 	MPASS(wrq->ndesc_needed == 0);
7416 	wrq->nwr_pending = 0;
7417 	wrq->ndesc_needed = 0;
7418 	TXQ_UNLOCK(wrq);
7419 }
7420 
7421 static void
7422 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
7423 {
7424 	/* Synchronize with the interrupt handler */
7425 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
7426 		pause("iqfree", 1);
7427 
7428 	if (fl != NULL) {
7429 		MPASS(iq->flags & IQ_HAS_FL);
7430 
7431 		mtx_lock(&sc->sfl_lock);
7432 		FL_LOCK(fl);
7433 		fl->flags |= FL_DOOMED;
7434 		FL_UNLOCK(fl);
7435 		callout_stop(&sc->sfl_callout);
7436 		mtx_unlock(&sc->sfl_lock);
7437 
7438 		KASSERT((fl->flags & FL_STARVING) == 0,
7439 		    ("%s: still starving", __func__));
7440 
7441 		/* Release all buffers if hardware is no longer available. */
7442 		if (!(iq->flags & IQ_HW_ALLOCATED))
7443 			free_fl_buffers(sc, fl);
7444 	}
7445 }
7446 
7447 /*
7448  * Wait for all activity on all the queues of the VI to complete.  It is assumed
7449  * that no new work is being enqueued by the hardware or the driver.  That part
7450  * should be arranged before calling this function.
7451  */
7452 static void
7453 quiesce_vi(struct vi_info *vi)
7454 {
7455 	int i;
7456 	struct adapter *sc = vi->adapter;
7457 	struct sge_rxq *rxq;
7458 	struct sge_txq *txq;
7459 #ifdef TCP_OFFLOAD
7460 	struct sge_ofld_rxq *ofld_rxq;
7461 #endif
7462 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7463 	struct sge_ofld_txq *ofld_txq;
7464 #endif
7465 
7466 	if (!(vi->flags & VI_INIT_DONE))
7467 		return;
7468 
7469 	for_each_txq(vi, i, txq) {
7470 		quiesce_txq(txq);
7471 	}
7472 
7473 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7474 	for_each_ofld_txq(vi, i, ofld_txq) {
7475 		quiesce_wrq(&ofld_txq->wrq);
7476 	}
7477 #endif
7478 
7479 	for_each_rxq(vi, i, rxq) {
7480 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
7481 	}
7482 
7483 #ifdef TCP_OFFLOAD
7484 	for_each_ofld_rxq(vi, i, ofld_rxq) {
7485 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
7486 	}
7487 #endif
7488 }
7489 
7490 static int
7491 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
7492     driver_intr_t *handler, void *arg, char *name)
7493 {
7494 	int rc;
7495 
7496 	irq->rid = rid;
7497 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
7498 	    RF_SHAREABLE | RF_ACTIVE);
7499 	if (irq->res == NULL) {
7500 		device_printf(sc->dev,
7501 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
7502 		return (ENOMEM);
7503 	}
7504 
7505 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
7506 	    NULL, handler, arg, &irq->tag);
7507 	if (rc != 0) {
7508 		device_printf(sc->dev,
7509 		    "failed to setup interrupt for rid %d, name %s: %d\n",
7510 		    rid, name, rc);
7511 	} else if (name)
7512 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
7513 
7514 	return (rc);
7515 }
7516 
7517 static int
7518 t4_free_irq(struct adapter *sc, struct irq *irq)
7519 {
7520 	if (irq->tag)
7521 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
7522 	if (irq->res)
7523 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
7524 
7525 	bzero(irq, sizeof(*irq));
7526 
7527 	return (0);
7528 }
7529 
7530 static void
7531 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
7532 {
7533 
7534 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
7535 	t4_get_regs(sc, buf, regs->len);
7536 }
7537 
7538 #define	A_PL_INDIR_CMD	0x1f8
7539 
7540 #define	S_PL_AUTOINC	31
7541 #define	M_PL_AUTOINC	0x1U
7542 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
7543 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
7544 
7545 #define	S_PL_VFID	20
7546 #define	M_PL_VFID	0xffU
7547 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
7548 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
7549 
7550 #define	S_PL_ADDR	0
7551 #define	M_PL_ADDR	0xfffffU
7552 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
7553 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
7554 
7555 #define	A_PL_INDIR_DATA	0x1fc
7556 
7557 static uint64_t
7558 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7559 {
7560 	u32 stats[2];
7561 
7562 	if (sc->flags & IS_VF) {
7563 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7564 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7565 	} else {
7566 		mtx_assert(&sc->reg_lock, MA_OWNED);
7567 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7568 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7569 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7570 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7571 	}
7572 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7573 }
7574 
7575 static void
7576 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7577 {
7578 
7579 #define GET_STAT(name) \
7580 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7581 
7582 	if (!(sc->flags & IS_VF))
7583 		mtx_lock(&sc->reg_lock);
7584 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7585 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7586 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7587 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7588 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7589 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7590 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7591 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7592 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7593 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7594 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7595 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7596 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7597 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7598 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7599 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7600 	if (!(sc->flags & IS_VF))
7601 		mtx_unlock(&sc->reg_lock);
7602 
7603 #undef GET_STAT
7604 }
7605 
7606 static void
7607 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7608 {
7609 	int reg;
7610 
7611 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7612 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7613 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7614 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7615 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7616 }
7617 
7618 static void
7619 vi_refresh_stats(struct vi_info *vi)
7620 {
7621 	struct timeval tv;
7622 	const struct timeval interval = {0, 250000};	/* 250ms */
7623 
7624 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7625 
7626 	if (vi->flags & VI_SKIP_STATS)
7627 		return;
7628 
7629 	getmicrotime(&tv);
7630 	timevalsub(&tv, &interval);
7631 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7632 		return;
7633 
7634 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7635 	getmicrotime(&vi->last_refreshed);
7636 }
7637 
7638 static void
7639 cxgbe_refresh_stats(struct vi_info *vi)
7640 {
7641 	u_int i, v, tnl_cong_drops, chan_map;
7642 	struct timeval tv;
7643 	const struct timeval interval = {0, 250000};	/* 250ms */
7644 	struct port_info *pi;
7645 	struct adapter *sc;
7646 
7647 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7648 
7649 	if (vi->flags & VI_SKIP_STATS)
7650 		return;
7651 
7652 	getmicrotime(&tv);
7653 	timevalsub(&tv, &interval);
7654 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7655 		return;
7656 
7657 	pi = vi->pi;
7658 	sc = vi->adapter;
7659 	tnl_cong_drops = 0;
7660 	t4_get_port_stats(sc, pi->hw_port, &pi->stats);
7661 	chan_map = pi->rx_e_chan_map;
7662 	while (chan_map) {
7663 		i = ffs(chan_map) - 1;
7664 		mtx_lock(&sc->reg_lock);
7665 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7666 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7667 		mtx_unlock(&sc->reg_lock);
7668 		tnl_cong_drops += v;
7669 		chan_map &= ~(1 << i);
7670 	}
7671 	pi->tnl_cong_drops = tnl_cong_drops;
7672 	getmicrotime(&vi->last_refreshed);
7673 }
7674 
7675 static void
7676 cxgbe_tick(void *arg)
7677 {
7678 	struct vi_info *vi = arg;
7679 
7680 	MPASS(IS_MAIN_VI(vi));
7681 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7682 
7683 	cxgbe_refresh_stats(vi);
7684 	callout_schedule(&vi->tick, hz);
7685 }
7686 
7687 static void
7688 vi_tick(void *arg)
7689 {
7690 	struct vi_info *vi = arg;
7691 
7692 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7693 
7694 	vi_refresh_stats(vi);
7695 	callout_schedule(&vi->tick, hz);
7696 }
7697 
7698 /* CIM inbound queues */
7699 static const char *t4_ibq[CIM_NUM_IBQ] = {
7700 	"ibq_tp0", "ibq_tp1", "ibq_ulp", "ibq_sge0", "ibq_sge1", "ibq_ncsi"
7701 };
7702 static const char *t7_ibq[CIM_NUM_IBQ_T7] = {
7703 	"ibq_tp0", "ibq_tp1", "ibq_tp2", "ibq_tp3", "ibq_ulp", "ibq_sge0",
7704 	"ibq_sge1", "ibq_ncsi", NULL, "ibq_ipc1", "ibq_ipc2", "ibq_ipc3",
7705 	"ibq_ipc4", "ibq_ipc5", "ibq_ipc6", "ibq_ipc7"
7706 };
7707 static const char *t7_ibq_sec[] = {
7708 	"ibq_tp0", "ibq_tp1", "ibq_tp2", "ibq_tp3", "ibq_ulp", "ibq_sge0",
7709 	NULL, NULL, NULL, "ibq_ipc0"
7710 };
7711 
7712 /* CIM outbound queues */
7713 static const char *t4_obq[CIM_NUM_OBQ_T5] = {
7714 	"obq_ulp0", "obq_ulp1", "obq_ulp2", "obq_ulp3", "obq_sge", "obq_ncsi",
7715 	"obq_sge_rx_q0", "obq_sge_rx_q1" /* These two are T5/T6 only */
7716 };
7717 static const char *t7_obq[CIM_NUM_OBQ_T7] = {
7718 	"obq_ulp0", "obq_ulp1", "obq_ulp2", "obq_ulp3", "obq_sge", "obq_ncsi",
7719 	"obq_sge_rx_q0", NULL, NULL, "obq_ipc1", "obq_ipc2", "obq_ipc3",
7720 	"obq_ipc4", "obq_ipc5", "obq_ipc6", "obq_ipc7"
7721 };
7722 static const char *t7_obq_sec[] = {
7723 	"obq_ulp0", "obq_ulp1", "obq_ulp2", "obq_ulp3", "obq_sge", NULL,
7724 	"obq_sge_rx_q0", NULL, NULL, "obq_ipc0"
7725 };
7726 
7727 static void
7728 cim_sysctls(struct adapter *sc, struct sysctl_ctx_list *ctx,
7729     struct sysctl_oid_list *c0)
7730 {
7731 	struct sysctl_oid *oid;
7732 	struct sysctl_oid_list *children1;
7733 	int i, j, qcount;
7734 	char s[16];
7735 	const char **qname;
7736 
7737 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "cim",
7738 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "CIM block");
7739 	c0 = SYSCTL_CHILDREN(oid);
7740 
7741 	SYSCTL_ADD_U8(ctx, c0, OID_AUTO, "ncores", CTLFLAG_RD, NULL,
7742 	    sc->params.ncores, "# of active CIM cores");
7743 
7744 	for (i = 0; i < sc->params.ncores; i++) {
7745 		snprintf(s, sizeof(s), "%u", i);
7746 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, s,
7747 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "CIM core");
7748 		children1 = SYSCTL_CHILDREN(oid);
7749 
7750 		/*
7751 		 * CTLFLAG_SKIP because the misc.devlog sysctl already displays
7752 		 * the log for all cores.  Use this sysctl to get the log for a
7753 		 * particular core only.
7754 		 */
7755 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "devlog",
7756 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
7757 		    sc, i, sysctl_devlog, "A", "firmware's device log");
7758 
7759 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "loadavg",
7760 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7761 		    sysctl_loadavg, "A",
7762 		    "microprocessor load averages (select firmwares only)");
7763 
7764 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "qcfg",
7765 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7766 		    chip_id(sc) > CHELSIO_T6 ? sysctl_cim_qcfg_t7 : sysctl_cim_qcfg,
7767 		    "A", "Queue configuration");
7768 
7769 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "la",
7770 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7771 		    sysctl_cim_la, "A", "Logic analyzer");
7772 
7773 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "ma_la",
7774 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7775 		    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7776 
7777 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "pif_la",
7778 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7779 		    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7780 
7781 		/* IBQs */
7782 		switch (chip_id(sc)) {
7783 		case CHELSIO_T4:
7784 		case CHELSIO_T5:
7785 		case CHELSIO_T6:
7786 			qname = &t4_ibq[0];
7787 			qcount = nitems(t4_ibq);
7788 			break;
7789 		case CHELSIO_T7:
7790 		default:
7791 			if (i == 0) {
7792 				qname = &t7_ibq[0];
7793 				qcount = nitems(t7_ibq);
7794 			} else {
7795 				qname = &t7_ibq_sec[0];
7796 				qcount = nitems(t7_ibq_sec);
7797 			}
7798 			break;
7799 		}
7800 		MPASS(qcount <= sc->chip_params->cim_num_ibq);
7801 		for (j = 0; j < qcount; j++) {
7802 			if (qname[j] == NULL)
7803 				continue;
7804 			SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, qname[j],
7805 			    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7806 			    (i << 16) | j, sysctl_cim_ibq, "A", NULL);
7807 		}
7808 
7809 		/* OBQs */
7810 		switch (chip_id(sc)) {
7811 		case CHELSIO_T4:
7812 			qname = t4_obq;
7813 			qcount = CIM_NUM_OBQ;
7814 			break;
7815 		case CHELSIO_T5:
7816 		case CHELSIO_T6:
7817 			qname = t4_obq;
7818 			qcount = nitems(t4_obq);
7819 			break;
7820 		case CHELSIO_T7:
7821 		default:
7822 			if (i == 0) {
7823 				qname = t7_obq;
7824 				qcount = nitems(t7_obq);
7825 			} else {
7826 				qname = t7_obq_sec;
7827 				qcount = nitems(t7_obq_sec);
7828 			}
7829 			break;
7830 		}
7831 		MPASS(qcount <= sc->chip_params->cim_num_obq);
7832 		for (j = 0; j < qcount; j++) {
7833 			if (qname[j] == NULL)
7834 				continue;
7835 			SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, qname[j],
7836 			    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7837 			    (i << 16) | j, sysctl_cim_obq, "A", NULL);
7838 		}
7839 	}
7840 }
7841 
7842 /*
7843  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7844  */
7845 static char *caps_decoder[] = {
7846 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7847 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7848 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7849 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7850 	    "\006HASHFILTER\007ETHOFLD",
7851 	"\20\001TOE\002SENDPATH",			/* 4: TOE */
7852 	"\20\001RDDP\002RDMAC\003ROCEv2",		/* 5: RDMA */
7853 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7854 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7855 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7856 	    "\007T10DIF"
7857 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7858 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7859 	    "\004TLS_HW,\005TOE_IPSEC",
7860 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7861 		    "\004PO_INITIATOR\005PO_TARGET",
7862 	"\20\001NVMe_TCP",				/* 9: NVMe */
7863 };
7864 
7865 void
7866 t4_sysctls(struct adapter *sc)
7867 {
7868 	struct sysctl_ctx_list *ctx = &sc->ctx;
7869 	struct sysctl_oid *oid;
7870 	struct sysctl_oid_list *children, *c0;
7871 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7872 
7873 	/*
7874 	 * dev.t4nex.X.
7875 	 */
7876 	oid = device_get_sysctl_tree(sc->dev);
7877 	c0 = children = SYSCTL_CHILDREN(oid);
7878 
7879 	sc->sc_do_rxcopy = 1;
7880 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7881 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7882 
7883 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7884 	    sc->params.nports, "# of ports");
7885 
7886 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7887 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7888 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7889 	    "available doorbells");
7890 
7891 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7892 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7893 
7894 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7895 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7896 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7897 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7898 
7899 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7900 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7901 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7902 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7903 
7904 	t4_sge_sysctls(sc, ctx, children);
7905 
7906 	sc->lro_timeout = 100;
7907 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7908 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7909 
7910 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7911 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7912 
7913 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iflags", CTLFLAG_RW,
7914 	    &sc->intr_flags, 0, "flags for the slow interrupt handler");
7915 
7916 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7917 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7918 
7919 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7920 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7921 
7922 	if (sc->flags & IS_VF)
7923 		return;
7924 
7925 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7926 	    NULL, chip_rev(sc), "chip hardware revision");
7927 
7928 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7929 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7930 
7931 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7932 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7933 
7934 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7935 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7936 
7937 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7938 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7939 
7940 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7941 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7942 
7943 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7944 	    sc->er_version, 0, "expansion ROM version");
7945 
7946 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7947 	    sc->bs_version, 0, "bootstrap firmware version");
7948 
7949 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7950 	    NULL, sc->params.scfg_vers, "serial config version");
7951 
7952 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7953 	    NULL, sc->params.vpd_vers, "VPD version");
7954 
7955 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7956 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7957 
7958 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7959 	    sc->cfcsum, "config file checksum");
7960 
7961 #define SYSCTL_CAP(name, n, text) \
7962 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7963 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7964 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7965 	    "available " text " capabilities")
7966 
7967 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7968 	SYSCTL_CAP(linkcaps, 1, "link");
7969 	SYSCTL_CAP(switchcaps, 2, "switch");
7970 	SYSCTL_CAP(nvmecaps, 9, "NVMe");
7971 	SYSCTL_CAP(niccaps, 3, "NIC");
7972 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7973 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7974 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7975 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7976 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7977 #undef SYSCTL_CAP
7978 
7979 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7980 	    NULL, sc->tids.nftids, "number of filters");
7981 
7982 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7983 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7984 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7985 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7986 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7987 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7988 
7989 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7990 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7991 	    "I", "core Vdd (in mV)");
7992 
7993 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7994 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7995 	    sysctl_cpus, "A", "local CPUs");
7996 
7997 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7998 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7999 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
8000 
8001 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
8002 	    &sc->swintr, 0, "software triggered interrupts");
8003 
8004 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
8005 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
8006 	    "1 = reset adapter, 0 = zero reset counter");
8007 
8008 	/*
8009 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
8010 	 */
8011 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
8012 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
8013 	    "logs and miscellaneous information");
8014 	children = SYSCTL_CHILDREN(oid);
8015 
8016 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
8017 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8018 	    sysctl_cctrl, "A", "congestion control");
8019 
8020 	cim_sysctls(sc, ctx, children);
8021 
8022 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
8023 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8024 	    sysctl_cpl_stats, "A", "CPL statistics");
8025 
8026 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
8027 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8028 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
8029 
8030 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
8031 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8032 	    sysctl_tid_stats, "A", "tid stats");
8033 
8034 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
8035 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, -1,
8036 	    sysctl_devlog, "A", "firmware's device log (all cores)");
8037 
8038 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
8039 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8040 	    sysctl_fcoe_stats, "A", "FCoE statistics");
8041 
8042 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
8043 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8044 	    sysctl_hw_sched, "A", "hardware scheduler ");
8045 
8046 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
8047 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8048 	    sysctl_l2t, "A", "hardware L2 table");
8049 
8050 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
8051 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8052 	    sysctl_smt, "A", "hardware source MAC table");
8053 
8054 #ifdef INET6
8055 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
8056 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8057 	    sysctl_clip, "A", "active CLIP table entries");
8058 #endif
8059 
8060 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
8061 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8062 	    sysctl_lb_stats, "A", "loopback statistics");
8063 
8064 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
8065 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8066 	    sysctl_meminfo, "A", "memory regions");
8067 
8068 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
8069 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8070 	    chip_id(sc) >= CHELSIO_T7 ? sysctl_mps_tcam_t7 :
8071 	    (chip_id(sc) >= CHELSIO_T6 ? sysctl_mps_tcam_t6 : sysctl_mps_tcam),
8072 	    "A", "MPS TCAM entries");
8073 
8074 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
8075 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8076 	    sysctl_path_mtus, "A", "path MTUs");
8077 
8078 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
8079 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8080 	    sysctl_pm_stats, "A", "PM statistics");
8081 
8082 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
8083 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8084 	    sysctl_rdma_stats, "A", "RDMA statistics");
8085 
8086 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
8087 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8088 	    sysctl_tcp_stats, "A", "TCP statistics");
8089 
8090 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
8091 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8092 	    sysctl_tids, "A", "TID information");
8093 
8094 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
8095 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8096 	    sysctl_tp_err_stats, "A", "TP error statistics");
8097 
8098 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
8099 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8100 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
8101 
8102 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
8103 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
8104 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
8105 
8106 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
8107 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8108 	    sysctl_tp_la, "A", "TP logic analyzer");
8109 
8110 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
8111 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8112 	    sysctl_tx_rate, "A", "Tx rate");
8113 
8114 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
8115 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8116 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
8117 
8118 	if (chip_id(sc) >= CHELSIO_T5) {
8119 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
8120 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8121 		    sysctl_wcwr_stats, "A", "write combined work requests");
8122 	}
8123 
8124 #ifdef KERN_TLS
8125 	if (is_ktls(sc)) {
8126 		/*
8127 		 * dev.t4nex.0.tls.
8128 		 */
8129 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
8130 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
8131 		children = SYSCTL_CHILDREN(oid);
8132 
8133 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
8134 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
8135 		    "keys in work requests (1) or attempt to store TLS keys "
8136 		    "in card memory.");
8137 
8138 		if (is_t6(sc))
8139 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
8140 			    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to "
8141 			    "combine TCB field updates with TLS record work "
8142 			    "requests.");
8143 		else {
8144 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "short_records",
8145 			    CTLFLAG_RW, &sc->tlst.short_records, 0,
8146 			    "Use cipher-only mode for short records.");
8147 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "partial_ghash",
8148 			    CTLFLAG_RW, &sc->tlst.partial_ghash, 0,
8149 			    "Use partial GHASH for AES-GCM records.");
8150 		}
8151 	}
8152 #endif
8153 
8154 #ifdef TCP_OFFLOAD
8155 	if (is_offload(sc)) {
8156 		int i;
8157 		char s[4];
8158 
8159 		/*
8160 		 * dev.t4nex.X.toe.
8161 		 */
8162 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
8163 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
8164 		children = SYSCTL_CHILDREN(oid);
8165 
8166 		sc->tt.cong_algorithm = -1;
8167 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
8168 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
8169 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
8170 		    "3 = highspeed)");
8171 
8172 		sc->tt.sndbuf = -1;
8173 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
8174 		    &sc->tt.sndbuf, 0, "hardware send buffer");
8175 
8176 		sc->tt.ddp = 0;
8177 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
8178 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
8179 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
8180 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
8181 
8182 		sc->tt.rx_coalesce = -1;
8183 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
8184 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
8185 
8186 		sc->tt.tls = 1;
8187 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
8188 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
8189 		    "Inline TLS allowed");
8190 
8191 		sc->tt.tx_align = -1;
8192 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
8193 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
8194 
8195 		sc->tt.tx_zcopy = 0;
8196 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
8197 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
8198 		    "Enable zero-copy aio_write(2)");
8199 
8200 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
8201 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
8202 		    "cop_managed_offloading", CTLFLAG_RW,
8203 		    &sc->tt.cop_managed_offloading, 0,
8204 		    "COP (Connection Offload Policy) controls all TOE offload");
8205 
8206 		sc->tt.autorcvbuf_inc = 16 * 1024;
8207 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
8208 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
8209 		    "autorcvbuf increment");
8210 
8211 		sc->tt.update_hc_on_pmtu_change = 1;
8212 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
8213 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
8214 		    &sc->tt.update_hc_on_pmtu_change, 0,
8215 		    "Update hostcache entry if the PMTU changes");
8216 
8217 		sc->tt.iso = 1;
8218 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
8219 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
8220 
8221 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
8222 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8223 		    sysctl_tp_tick, "A", "TP timer tick (us)");
8224 
8225 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
8226 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
8227 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
8228 
8229 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
8230 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
8231 		    sysctl_tp_tick, "A", "DACK tick (us)");
8232 
8233 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
8234 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8235 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
8236 
8237 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
8238 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8239 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
8240 		    "Minimum retransmit interval (us)");
8241 
8242 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
8243 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8244 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
8245 		    "Maximum retransmit interval (us)");
8246 
8247 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
8248 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8249 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
8250 		    "Persist timer min (us)");
8251 
8252 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
8253 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8254 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
8255 		    "Persist timer max (us)");
8256 
8257 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
8258 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8259 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
8260 		    "Keepalive idle timer (us)");
8261 
8262 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
8263 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8264 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
8265 		    "Keepalive interval timer (us)");
8266 
8267 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
8268 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8269 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
8270 
8271 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
8272 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8273 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
8274 		    "FINWAIT2 timer (us)");
8275 
8276 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
8277 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8278 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
8279 		    "Number of SYN retransmissions before abort");
8280 
8281 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
8282 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8283 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
8284 		    "Number of retransmissions before abort");
8285 
8286 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
8287 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8288 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
8289 		    "Number of keepalive probes before abort");
8290 
8291 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
8292 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
8293 		    "TOE retransmit backoffs");
8294 		children = SYSCTL_CHILDREN(oid);
8295 		for (i = 0; i < 16; i++) {
8296 			snprintf(s, sizeof(s), "%u", i);
8297 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
8298 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8299 			    i, sysctl_tp_backoff, "IU",
8300 			    "TOE retransmit backoff");
8301 		}
8302 	}
8303 #endif
8304 }
8305 
8306 void
8307 vi_sysctls(struct vi_info *vi)
8308 {
8309 	struct sysctl_ctx_list *ctx = &vi->ctx;
8310 	struct sysctl_oid *oid;
8311 	struct sysctl_oid_list *children;
8312 
8313 	/*
8314 	 * dev.v?(cxgbe|cxl).X.
8315 	 */
8316 	oid = device_get_sysctl_tree(vi->dev);
8317 	children = SYSCTL_CHILDREN(oid);
8318 
8319 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
8320 	    vi->viid, "VI identifer");
8321 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
8322 	    &vi->nrxq, 0, "# of rx queues");
8323 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
8324 	    &vi->ntxq, 0, "# of tx queues");
8325 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
8326 	    &vi->first_rxq, 0, "index of first rx queue");
8327 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
8328 	    &vi->first_txq, 0, "index of first tx queue");
8329 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
8330 	    vi->rss_base, "start of RSS indirection table");
8331 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
8332 	    vi->rss_size, "size of RSS indirection table");
8333 
8334 	if (IS_MAIN_VI(vi)) {
8335 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
8336 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8337 		    sysctl_noflowq, "IU",
8338 		    "Reserve queue 0 for non-flowid packets");
8339 	}
8340 
8341 	if (vi->adapter->flags & IS_VF) {
8342 		MPASS(vi->flags & TX_USES_VM_WR);
8343 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
8344 		    NULL, 1, "use VM work requests for transmit");
8345 	} else {
8346 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
8347 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8348 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
8349 	}
8350 
8351 #ifdef TCP_OFFLOAD
8352 	if (vi->nofldrxq != 0) {
8353 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
8354 		    &vi->nofldrxq, 0,
8355 		    "# of rx queues for offloaded TCP connections");
8356 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
8357 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
8358 		    "index of first TOE rx queue");
8359 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
8360 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8361 		    sysctl_holdoff_tmr_idx_ofld, "I",
8362 		    "holdoff timer index for TOE queues");
8363 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
8364 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8365 		    sysctl_holdoff_pktc_idx_ofld, "I",
8366 		    "holdoff packet counter index for TOE queues");
8367 	}
8368 #endif
8369 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
8370 	if (vi->nofldtxq != 0) {
8371 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
8372 		    &vi->nofldtxq, 0,
8373 		    "# of tx queues for TOE/ETHOFLD");
8374 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
8375 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
8376 		    "index of first TOE/ETHOFLD tx queue");
8377 	}
8378 #endif
8379 #ifdef DEV_NETMAP
8380 	if (vi->nnmrxq != 0) {
8381 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
8382 		    &vi->nnmrxq, 0, "# of netmap rx queues");
8383 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
8384 		    &vi->nnmtxq, 0, "# of netmap tx queues");
8385 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
8386 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
8387 		    "index of first netmap rx queue");
8388 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
8389 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
8390 		    "index of first netmap tx queue");
8391 	}
8392 #endif
8393 
8394 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
8395 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8396 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
8397 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
8398 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8399 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
8400 
8401 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
8402 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8403 	    sysctl_qsize_rxq, "I", "rx queue size");
8404 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
8405 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8406 	    sysctl_qsize_txq, "I", "tx queue size");
8407 }
8408 
8409 static void
8410 cxgbe_sysctls(struct port_info *pi)
8411 {
8412 	struct sysctl_ctx_list *ctx = &pi->ctx;
8413 	struct sysctl_oid *oid;
8414 	struct sysctl_oid_list *children, *children2;
8415 	struct adapter *sc = pi->adapter;
8416 	int i;
8417 	char name[16];
8418 	static char *tc_flags = {"\20\1USER"};
8419 
8420 	/*
8421 	 * dev.cxgbe.X.
8422 	 */
8423 	oid = device_get_sysctl_tree(pi->dev);
8424 	children = SYSCTL_CHILDREN(oid);
8425 
8426 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
8427 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
8428 	    sysctl_linkdnrc, "A", "reason why link is down");
8429 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
8430 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
8431 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
8432 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
8433 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
8434 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
8435 		    sysctl_btphy, "I", "PHY firmware version");
8436 	}
8437 
8438 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
8439 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8440 	    sysctl_pause_settings, "A",
8441 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
8442 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
8443 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
8444 	    "FEC in use on the link");
8445 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
8446 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8447 	    sysctl_requested_fec, "A",
8448 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
8449 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
8450 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
8451 	    "FEC recommended by the cable/transceiver");
8452 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
8453 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8454 	    sysctl_autoneg, "I",
8455 	    "autonegotiation (-1 = not supported)");
8456 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
8457 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8458 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
8459 
8460 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
8461 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
8462 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
8463 	    &pi->link_cfg.pcaps, 0, "port capabilities");
8464 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
8465 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
8466 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
8467 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
8468 
8469 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
8470 	    port_top_speed(pi), "max speed (in Gbps)");
8471 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
8472 	    pi->mps_bg_map, "MPS buffer group map");
8473 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
8474 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
8475 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_chan", CTLFLAG_RD, NULL,
8476 	    pi->tx_chan, "TP tx c-channel");
8477 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_chan", CTLFLAG_RD, NULL,
8478 	    pi->rx_chan, "TP rx c-channel");
8479 
8480 	if (sc->flags & IS_VF)
8481 		return;
8482 
8483 	/*
8484 	 * dev.(cxgbe|cxl).X.tc.
8485 	 */
8486 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
8487 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
8488 	    "Tx scheduler traffic classes (cl_rl)");
8489 	children2 = SYSCTL_CHILDREN(oid);
8490 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
8491 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
8492 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
8493 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
8494 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
8495 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
8496 	for (i = 0; i < sc->params.nsched_cls; i++) {
8497 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
8498 
8499 		snprintf(name, sizeof(name), "%d", i);
8500 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
8501 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
8502 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
8503 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
8504 		    CTLFLAG_RD, &tc->state, 0, "current state");
8505 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
8506 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
8507 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
8508 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
8509 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
8510 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
8511 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8512 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
8513 		    "traffic class parameters");
8514 	}
8515 
8516 	/*
8517 	 * dev.cxgbe.X.stats.
8518 	 */
8519 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
8520 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
8521 	children = SYSCTL_CHILDREN(oid);
8522 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
8523 	    &pi->tx_parse_error, 0,
8524 	    "# of tx packets with invalid length or # of segments");
8525 
8526 #define T4_LBSTAT(name, stat, desc) do { \
8527 	if (sc->params.tp.lb_mode) { \
8528 		SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8529 		    CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, \
8530 		    A_MPS_PORT_STAT_##stat##_L, \
8531 		    sysctl_handle_t4_portstat64, "QU", desc); \
8532 	} else { \
8533 		SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8534 		    CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8535 		    t4_port_reg(sc, pi->tx_chan, A_MPS_PORT_STAT_##stat##_L), \
8536 		    sysctl_handle_t4_reg64, "QU", desc); \
8537 	} \
8538 } while (0)
8539 
8540 	T4_LBSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
8541 	T4_LBSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
8542 	T4_LBSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
8543 	T4_LBSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
8544 	T4_LBSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
8545 	T4_LBSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
8546 	T4_LBSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
8547 	T4_LBSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
8548 	T4_LBSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
8549 	T4_LBSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
8550 	T4_LBSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
8551 	T4_LBSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
8552 	T4_LBSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
8553 	T4_LBSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
8554 	T4_LBSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
8555 	T4_LBSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
8556 	T4_LBSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
8557 	T4_LBSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
8558 	T4_LBSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
8559 	T4_LBSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
8560 	T4_LBSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
8561 	T4_LBSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
8562 	T4_LBSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
8563 
8564 	T4_LBSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
8565 	T4_LBSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
8566 	T4_LBSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
8567 	T4_LBSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
8568 	T4_LBSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
8569 	T4_LBSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
8570 	T4_LBSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
8571 	if (is_t6(sc)) {
8572 		/* Read from port_stats and may be stale by up to 1s */
8573 		SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, "rx_fcs_err",
8574 		    CTLFLAG_RD, &pi->stats.rx_fcs_err,
8575 		    "# of frames received with bad FCS since last link up");
8576 	} else {
8577 		T4_LBSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
8578 		    "# of frames received with bad FCS");
8579 	}
8580 	T4_LBSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
8581 	T4_LBSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
8582 	T4_LBSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
8583 	T4_LBSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
8584 	T4_LBSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
8585 	T4_LBSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
8586 	T4_LBSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
8587 	T4_LBSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
8588 	T4_LBSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
8589 	T4_LBSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
8590 	T4_LBSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
8591 	T4_LBSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
8592 	T4_LBSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
8593 	T4_LBSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
8594 	T4_LBSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
8595 	T4_LBSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
8596 	T4_LBSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
8597 	T4_LBSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
8598 	T4_LBSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
8599 #undef T4_LBSTAT
8600 
8601 #define T4_REGSTAT(name, stat, desc) do { \
8602 	SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8603 	    CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8604 	    A_MPS_STAT_##stat##_L, sysctl_handle_t4_reg64, "QU", desc); \
8605 } while (0)
8606 
8607 	if (pi->mps_bg_map & 1) {
8608 		T4_REGSTAT(rx_ovflow0, RX_BG_0_MAC_DROP_FRAME,
8609 		    "# drops due to buffer-group 0 overflows");
8610 		T4_REGSTAT(rx_trunc0, RX_BG_0_MAC_TRUNC_FRAME,
8611 		    "# of buffer-group 0 truncated packets");
8612 	}
8613 	if (pi->mps_bg_map & 2) {
8614 		T4_REGSTAT(rx_ovflow1, RX_BG_1_MAC_DROP_FRAME,
8615 		    "# drops due to buffer-group 1 overflows");
8616 		T4_REGSTAT(rx_trunc1, RX_BG_1_MAC_TRUNC_FRAME,
8617 		    "# of buffer-group 1 truncated packets");
8618 	}
8619 	if (pi->mps_bg_map & 4) {
8620 		T4_REGSTAT(rx_ovflow2, RX_BG_2_MAC_DROP_FRAME,
8621 		    "# drops due to buffer-group 2 overflows");
8622 		T4_REGSTAT(rx_trunc2, RX_BG_2_MAC_TRUNC_FRAME,
8623 		    "# of buffer-group 2 truncated packets");
8624 	}
8625 	if (pi->mps_bg_map & 8) {
8626 		T4_REGSTAT(rx_ovflow3, RX_BG_3_MAC_DROP_FRAME,
8627 		    "# drops due to buffer-group 3 overflows");
8628 		T4_REGSTAT(rx_trunc3, RX_BG_3_MAC_TRUNC_FRAME,
8629 		    "# of buffer-group 3 truncated packets");
8630 	}
8631 #undef T4_REGSTAT
8632 }
8633 
8634 static int
8635 sysctl_int_array(SYSCTL_HANDLER_ARGS)
8636 {
8637 	int rc, *i, space = 0;
8638 	struct sbuf sb;
8639 
8640 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
8641 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
8642 		if (space)
8643 			sbuf_printf(&sb, " ");
8644 		sbuf_printf(&sb, "%d", *i);
8645 		space = 1;
8646 	}
8647 	rc = sbuf_finish(&sb);
8648 	sbuf_delete(&sb);
8649 	return (rc);
8650 }
8651 
8652 static int
8653 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
8654 {
8655 	int rc;
8656 	struct sbuf *sb;
8657 
8658 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8659 	if (sb == NULL)
8660 		return (ENOMEM);
8661 
8662 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8663 	rc = sbuf_finish(sb);
8664 	sbuf_delete(sb);
8665 
8666 	return (rc);
8667 }
8668 
8669 static int
8670 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8671 {
8672 	int rc;
8673 	struct sbuf *sb;
8674 
8675 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8676 	if (sb == NULL)
8677 		return (ENOMEM);
8678 
8679 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8680 	rc = sbuf_finish(sb);
8681 	sbuf_delete(sb);
8682 
8683 	return (rc);
8684 }
8685 
8686 static int
8687 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8688 {
8689 	struct port_info *pi = arg1;
8690 	int op = arg2;
8691 	struct adapter *sc = pi->adapter;
8692 	u_int v;
8693 	int rc;
8694 
8695 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8696 	if (rc)
8697 		return (rc);
8698 	if (!hw_all_ok(sc))
8699 		rc = ENXIO;
8700 	else {
8701 		/* XXX: magic numbers */
8702 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8703 		    op ? 0x20 : 0xc820, &v);
8704 	}
8705 	end_synchronized_op(sc, 0);
8706 	if (rc)
8707 		return (rc);
8708 	if (op == 0)
8709 		v /= 256;
8710 
8711 	rc = sysctl_handle_int(oidp, &v, 0, req);
8712 	return (rc);
8713 }
8714 
8715 static int
8716 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8717 {
8718 	struct vi_info *vi = arg1;
8719 	int rc, val;
8720 
8721 	val = vi->rsrv_noflowq;
8722 	rc = sysctl_handle_int(oidp, &val, 0, req);
8723 	if (rc != 0 || req->newptr == NULL)
8724 		return (rc);
8725 
8726 	if ((val >= 1) && (vi->ntxq > 1))
8727 		vi->rsrv_noflowq = 1;
8728 	else
8729 		vi->rsrv_noflowq = 0;
8730 
8731 	return (rc);
8732 }
8733 
8734 static int
8735 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8736 {
8737 	struct vi_info *vi = arg1;
8738 	struct adapter *sc = vi->adapter;
8739 	int rc, val, i;
8740 
8741 	MPASS(!(sc->flags & IS_VF));
8742 
8743 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8744 	rc = sysctl_handle_int(oidp, &val, 0, req);
8745 	if (rc != 0 || req->newptr == NULL)
8746 		return (rc);
8747 
8748 	if (val != 0 && val != 1)
8749 		return (EINVAL);
8750 
8751 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8752 	    "t4txvm");
8753 	if (rc)
8754 		return (rc);
8755 	if (!hw_all_ok(sc))
8756 		rc = ENXIO;
8757 	else if (if_getdrvflags(vi->ifp) & IFF_DRV_RUNNING) {
8758 		/*
8759 		 * We don't want parse_pkt to run with one setting (VF or PF)
8760 		 * and then eth_tx to see a different setting but still use
8761 		 * stale information calculated by parse_pkt.
8762 		 */
8763 		rc = EBUSY;
8764 	} else {
8765 		struct port_info *pi = vi->pi;
8766 		struct sge_txq *txq;
8767 		uint32_t ctrl0;
8768 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8769 
8770 		if (val) {
8771 			vi->flags |= TX_USES_VM_WR;
8772 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_VM_TSO);
8773 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8774 			    V_TXPKT_INTF(pi->hw_port));
8775 			if (!(sc->flags & IS_VF))
8776 				npkt--;
8777 		} else {
8778 			vi->flags &= ~TX_USES_VM_WR;
8779 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_TSO);
8780 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8781 			    V_TXPKT_INTF(pi->hw_port) | V_TXPKT_PF(sc->pf) |
8782 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8783 		}
8784 		for_each_txq(vi, i, txq) {
8785 			txq->cpl_ctrl0 = ctrl0;
8786 			txq->txp.max_npkt = npkt;
8787 		}
8788 	}
8789 	end_synchronized_op(sc, LOCK_HELD);
8790 	return (rc);
8791 }
8792 
8793 static int
8794 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8795 {
8796 	struct vi_info *vi = arg1;
8797 	struct adapter *sc = vi->adapter;
8798 	int idx, rc, i;
8799 	struct sge_rxq *rxq;
8800 	uint8_t v;
8801 
8802 	idx = vi->tmr_idx;
8803 
8804 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8805 	if (rc != 0 || req->newptr == NULL)
8806 		return (rc);
8807 
8808 	if (idx < 0 || idx >= SGE_NTIMERS)
8809 		return (EINVAL);
8810 
8811 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8812 	    "t4tmr");
8813 	if (rc)
8814 		return (rc);
8815 
8816 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8817 	for_each_rxq(vi, i, rxq) {
8818 #ifdef atomic_store_rel_8
8819 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8820 #else
8821 		rxq->iq.intr_params = v;
8822 #endif
8823 	}
8824 	vi->tmr_idx = idx;
8825 
8826 	end_synchronized_op(sc, LOCK_HELD);
8827 	return (0);
8828 }
8829 
8830 static int
8831 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8832 {
8833 	struct vi_info *vi = arg1;
8834 	struct adapter *sc = vi->adapter;
8835 	int idx, rc;
8836 
8837 	idx = vi->pktc_idx;
8838 
8839 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8840 	if (rc != 0 || req->newptr == NULL)
8841 		return (rc);
8842 
8843 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8844 		return (EINVAL);
8845 
8846 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8847 	    "t4pktc");
8848 	if (rc)
8849 		return (rc);
8850 
8851 	if (vi->flags & VI_INIT_DONE)
8852 		rc = EBUSY; /* cannot be changed once the queues are created */
8853 	else
8854 		vi->pktc_idx = idx;
8855 
8856 	end_synchronized_op(sc, LOCK_HELD);
8857 	return (rc);
8858 }
8859 
8860 static int
8861 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8862 {
8863 	struct vi_info *vi = arg1;
8864 	struct adapter *sc = vi->adapter;
8865 	int qsize, rc;
8866 
8867 	qsize = vi->qsize_rxq;
8868 
8869 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8870 	if (rc != 0 || req->newptr == NULL)
8871 		return (rc);
8872 
8873 	if (qsize < 128 || (qsize & 7))
8874 		return (EINVAL);
8875 
8876 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8877 	    "t4rxqs");
8878 	if (rc)
8879 		return (rc);
8880 
8881 	if (vi->flags & VI_INIT_DONE)
8882 		rc = EBUSY; /* cannot be changed once the queues are created */
8883 	else
8884 		vi->qsize_rxq = qsize;
8885 
8886 	end_synchronized_op(sc, LOCK_HELD);
8887 	return (rc);
8888 }
8889 
8890 static int
8891 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8892 {
8893 	struct vi_info *vi = arg1;
8894 	struct adapter *sc = vi->adapter;
8895 	int qsize, rc;
8896 
8897 	qsize = vi->qsize_txq;
8898 
8899 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8900 	if (rc != 0 || req->newptr == NULL)
8901 		return (rc);
8902 
8903 	if (qsize < 128 || qsize > 65536)
8904 		return (EINVAL);
8905 
8906 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8907 	    "t4txqs");
8908 	if (rc)
8909 		return (rc);
8910 
8911 	if (vi->flags & VI_INIT_DONE)
8912 		rc = EBUSY; /* cannot be changed once the queues are created */
8913 	else
8914 		vi->qsize_txq = qsize;
8915 
8916 	end_synchronized_op(sc, LOCK_HELD);
8917 	return (rc);
8918 }
8919 
8920 static int
8921 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8922 {
8923 	struct port_info *pi = arg1;
8924 	struct adapter *sc = pi->adapter;
8925 	struct link_config *lc = &pi->link_cfg;
8926 	int rc;
8927 
8928 	if (req->newptr == NULL) {
8929 		struct sbuf *sb;
8930 		static char *bits = "\20\1RX\2TX\3AUTO";
8931 
8932 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8933 		if (sb == NULL)
8934 			return (ENOMEM);
8935 
8936 		if (lc->link_ok) {
8937 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8938 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8939 		} else {
8940 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8941 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8942 		}
8943 		rc = sbuf_finish(sb);
8944 		sbuf_delete(sb);
8945 	} else {
8946 		char s[2];
8947 		int n;
8948 
8949 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8950 		    PAUSE_AUTONEG));
8951 		s[1] = 0;
8952 
8953 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8954 		if (rc != 0)
8955 			return(rc);
8956 
8957 		if (s[1] != 0)
8958 			return (EINVAL);
8959 		if (s[0] < '0' || s[0] > '9')
8960 			return (EINVAL);	/* not a number */
8961 		n = s[0] - '0';
8962 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8963 			return (EINVAL);	/* some other bit is set too */
8964 
8965 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8966 		    "t4PAUSE");
8967 		if (rc)
8968 			return (rc);
8969 		if (hw_all_ok(sc)) {
8970 			PORT_LOCK(pi);
8971 			lc->requested_fc = n;
8972 			fixup_link_config(pi);
8973 			if (pi->up_vis > 0)
8974 				rc = apply_link_config(pi);
8975 			set_current_media(pi);
8976 			PORT_UNLOCK(pi);
8977 		}
8978 		end_synchronized_op(sc, 0);
8979 	}
8980 
8981 	return (rc);
8982 }
8983 
8984 static int
8985 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
8986 {
8987 	struct port_info *pi = arg1;
8988 	struct link_config *lc = &pi->link_cfg;
8989 	int rc;
8990 	struct sbuf *sb;
8991 
8992 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8993 	if (sb == NULL)
8994 		return (ENOMEM);
8995 	if (lc->link_ok)
8996 		sbuf_printf(sb, "%b", lc->fec, t4_fec_bits);
8997 	else
8998 		sbuf_printf(sb, "no link");
8999 	rc = sbuf_finish(sb);
9000 	sbuf_delete(sb);
9001 
9002 	return (rc);
9003 }
9004 
9005 static int
9006 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
9007 {
9008 	struct port_info *pi = arg1;
9009 	struct adapter *sc = pi->adapter;
9010 	struct link_config *lc = &pi->link_cfg;
9011 	int rc;
9012 	int8_t old = lc->requested_fec;
9013 
9014 	if (req->newptr == NULL) {
9015 		struct sbuf *sb;
9016 
9017 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
9018 		if (sb == NULL)
9019 			return (ENOMEM);
9020 
9021 		sbuf_printf(sb, "%b", old, t4_fec_bits);
9022 		rc = sbuf_finish(sb);
9023 		sbuf_delete(sb);
9024 	} else {
9025 		char s[8];
9026 		int n;
9027 
9028 		snprintf(s, sizeof(s), "%d", old == FEC_AUTO ? -1 :
9029 		    old & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
9030 
9031 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
9032 		if (rc != 0)
9033 			return(rc);
9034 
9035 		n = strtol(&s[0], NULL, 0);
9036 		if (n < 0 || n & FEC_AUTO)
9037 			n = FEC_AUTO;
9038 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
9039 			return (EINVAL);/* some other bit is set too */
9040 
9041 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
9042 		    "t4reqf");
9043 		if (rc)
9044 			return (rc);
9045 		PORT_LOCK(pi);
9046 		if (lc->requested_fec != old) {
9047 			rc = EBUSY;
9048 			goto done;
9049 		}
9050 		if (n == FEC_AUTO)
9051 			lc->requested_fec = FEC_AUTO;
9052 		else if (n == 0 || n == FEC_NONE)
9053 			lc->requested_fec = FEC_NONE;
9054 		else {
9055 			if ((lc->pcaps |
9056 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
9057 			    lc->pcaps) {
9058 				rc = ENOTSUP;
9059 				goto done;
9060 			}
9061 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
9062 			    FEC_MODULE);
9063 		}
9064 		if (hw_all_ok(sc)) {
9065 			fixup_link_config(pi);
9066 			if (pi->up_vis > 0) {
9067 				rc = apply_link_config(pi);
9068 				if (rc != 0) {
9069 					lc->requested_fec = old;
9070 					if (rc == FW_EPROTO)
9071 						rc = ENOTSUP;
9072 				}
9073 			}
9074 		}
9075 done:
9076 		PORT_UNLOCK(pi);
9077 		end_synchronized_op(sc, 0);
9078 	}
9079 
9080 	return (rc);
9081 }
9082 
9083 static int
9084 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
9085 {
9086 	struct port_info *pi = arg1;
9087 	struct adapter *sc = pi->adapter;
9088 	struct link_config *lc = &pi->link_cfg;
9089 	int rc;
9090 	int8_t fec;
9091 	struct sbuf *sb;
9092 
9093 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
9094 	if (sb == NULL)
9095 		return (ENOMEM);
9096 
9097 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
9098 		rc = EBUSY;
9099 		goto done;
9100 	}
9101 	if (!hw_all_ok(sc)) {
9102 		rc = ENXIO;
9103 		goto done;
9104 	}
9105 	PORT_LOCK(pi);
9106 	if (pi->up_vis == 0) {
9107 		/*
9108 		 * If all the interfaces are administratively down the firmware
9109 		 * does not report transceiver changes.  Refresh port info here.
9110 		 * This is the only reason we have a synchronized op in this
9111 		 * function.  Just PORT_LOCK would have been enough otherwise.
9112 		 */
9113 		t4_update_port_info(pi);
9114 	}
9115 
9116 	fec = lc->fec_hint;
9117 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
9118 	    !fec_supported(lc->pcaps)) {
9119 		PORT_UNLOCK(pi);
9120 		sbuf_printf(sb, "n/a");
9121 	} else {
9122 		if (fec == 0)
9123 			fec = FEC_NONE;
9124 		PORT_UNLOCK(pi);
9125 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, t4_fec_bits);
9126 	}
9127 	rc = sbuf_finish(sb);
9128 done:
9129 	sbuf_delete(sb);
9130 	end_synchronized_op(sc, 0);
9131 
9132 	return (rc);
9133 }
9134 
9135 static int
9136 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
9137 {
9138 	struct port_info *pi = arg1;
9139 	struct adapter *sc = pi->adapter;
9140 	struct link_config *lc = &pi->link_cfg;
9141 	int rc, val;
9142 
9143 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
9144 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
9145 	else
9146 		val = -1;
9147 	rc = sysctl_handle_int(oidp, &val, 0, req);
9148 	if (rc != 0 || req->newptr == NULL)
9149 		return (rc);
9150 	if (val == 0)
9151 		val = AUTONEG_DISABLE;
9152 	else if (val == 1)
9153 		val = AUTONEG_ENABLE;
9154 	else
9155 		val = AUTONEG_AUTO;
9156 
9157 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
9158 	    "t4aneg");
9159 	if (rc)
9160 		return (rc);
9161 	PORT_LOCK(pi);
9162 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
9163 		rc = ENOTSUP;
9164 		goto done;
9165 	}
9166 	lc->requested_aneg = val;
9167 	if (hw_all_ok(sc)) {
9168 		fixup_link_config(pi);
9169 		if (pi->up_vis > 0)
9170 			rc = apply_link_config(pi);
9171 		set_current_media(pi);
9172 	}
9173 done:
9174 	PORT_UNLOCK(pi);
9175 	end_synchronized_op(sc, 0);
9176 	return (rc);
9177 }
9178 
9179 static int
9180 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
9181 {
9182 	struct port_info *pi = arg1;
9183 	struct adapter *sc = pi->adapter;
9184 	struct link_config *lc = &pi->link_cfg;
9185 	int rc, val;
9186 
9187 	val = lc->force_fec;
9188 	MPASS(val >= -1 && val <= 1);
9189 	rc = sysctl_handle_int(oidp, &val, 0, req);
9190 	if (rc != 0 || req->newptr == NULL)
9191 		return (rc);
9192 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
9193 		return (ENOTSUP);
9194 	if (val < -1 || val > 1)
9195 		return (EINVAL);
9196 
9197 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
9198 	if (rc)
9199 		return (rc);
9200 	PORT_LOCK(pi);
9201 	lc->force_fec = val;
9202 	if (hw_all_ok(sc)) {
9203 		fixup_link_config(pi);
9204 		if (pi->up_vis > 0)
9205 			rc = apply_link_config(pi);
9206 	}
9207 	PORT_UNLOCK(pi);
9208 	end_synchronized_op(sc, 0);
9209 	return (rc);
9210 }
9211 
9212 static int
9213 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
9214 {
9215 	struct adapter *sc = arg1;
9216 	int rc, reg = arg2;
9217 	uint64_t val;
9218 
9219 	mtx_lock(&sc->reg_lock);
9220 	if (hw_off_limits(sc))
9221 		rc = ENXIO;
9222 	else {
9223 		rc = 0;
9224 		val = t4_read_reg64(sc, reg);
9225 	}
9226 	mtx_unlock(&sc->reg_lock);
9227 	if (rc == 0)
9228 		rc = sysctl_handle_64(oidp, &val, 0, req);
9229 	return (rc);
9230 }
9231 
9232 static int
9233 sysctl_handle_t4_portstat64(SYSCTL_HANDLER_ARGS)
9234 {
9235 	struct port_info *pi = arg1;
9236 	struct adapter *sc = pi->adapter;
9237 	int rc, i, reg = arg2;
9238 	uint64_t val;
9239 
9240 	mtx_lock(&sc->reg_lock);
9241 	if (hw_off_limits(sc))
9242 		rc = ENXIO;
9243 	else {
9244 		val = 0;
9245 		for (i = 0; i < sc->params.tp.lb_nchan; i++) {
9246 			val += t4_read_reg64(sc,
9247 			    t4_port_reg(sc, pi->tx_chan + i, reg));
9248 		}
9249 		rc = 0;
9250 	}
9251 	mtx_unlock(&sc->reg_lock);
9252 	if (rc == 0)
9253 		rc = sysctl_handle_64(oidp, &val, 0, req);
9254 	return (rc);
9255 }
9256 
9257 static int
9258 sysctl_temperature(SYSCTL_HANDLER_ARGS)
9259 {
9260 	struct adapter *sc = arg1;
9261 	int rc, t;
9262 	uint32_t param, val;
9263 
9264 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
9265 	if (rc)
9266 		return (rc);
9267 	if (!hw_all_ok(sc))
9268 		rc = ENXIO;
9269 	else {
9270 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9271 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
9272 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
9273 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
9274 	}
9275 	end_synchronized_op(sc, 0);
9276 	if (rc)
9277 		return (rc);
9278 
9279 	/* unknown is returned as 0 but we display -1 in that case */
9280 	t = val == 0 ? -1 : val;
9281 
9282 	rc = sysctl_handle_int(oidp, &t, 0, req);
9283 	return (rc);
9284 }
9285 
9286 static int
9287 sysctl_vdd(SYSCTL_HANDLER_ARGS)
9288 {
9289 	struct adapter *sc = arg1;
9290 	int rc;
9291 	uint32_t param, val;
9292 
9293 	if (sc->params.core_vdd == 0) {
9294 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
9295 		    "t4vdd");
9296 		if (rc)
9297 			return (rc);
9298 		if (!hw_all_ok(sc))
9299 			rc = ENXIO;
9300 		else {
9301 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9302 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
9303 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
9304 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
9305 			    &param, &val);
9306 		}
9307 		end_synchronized_op(sc, 0);
9308 		if (rc)
9309 			return (rc);
9310 		sc->params.core_vdd = val;
9311 	}
9312 
9313 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
9314 }
9315 
9316 static int
9317 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
9318 {
9319 	struct adapter *sc = arg1;
9320 	int rc, v;
9321 	uint32_t param, val;
9322 
9323 	v = sc->sensor_resets;
9324 	rc = sysctl_handle_int(oidp, &v, 0, req);
9325 	if (rc != 0 || req->newptr == NULL || v <= 0)
9326 		return (rc);
9327 
9328 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
9329 	    chip_id(sc) < CHELSIO_T5)
9330 		return (ENOTSUP);
9331 
9332 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
9333 	if (rc)
9334 		return (rc);
9335 	if (!hw_all_ok(sc))
9336 		rc = ENXIO;
9337 	else {
9338 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9339 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
9340 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
9341 		val = 1;
9342 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
9343 	}
9344 	end_synchronized_op(sc, 0);
9345 	if (rc == 0)
9346 		sc->sensor_resets++;
9347 	return (rc);
9348 }
9349 
9350 static int
9351 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
9352 {
9353 	struct adapter *sc = arg1;
9354 	struct sbuf *sb;
9355 	int rc;
9356 	uint32_t param, val;
9357 	uint8_t coreid = (uint8_t)arg2;
9358 
9359 	KASSERT(coreid < sc->params.ncores,
9360 	    ("%s: bad coreid %u\n", __func__, coreid));
9361 
9362 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
9363 	if (rc)
9364 		return (rc);
9365 	if (!hw_all_ok(sc))
9366 		rc = ENXIO;
9367 	else {
9368 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9369 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD) |
9370 		    V_FW_PARAMS_PARAM_Y(coreid);
9371 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
9372 	}
9373 	end_synchronized_op(sc, 0);
9374 	if (rc)
9375 		return (rc);
9376 
9377 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9378 	if (sb == NULL)
9379 		return (ENOMEM);
9380 
9381 	if (val == 0xffffffff) {
9382 		/* Only debug and custom firmwares report load averages. */
9383 		sbuf_printf(sb, "not available");
9384 	} else {
9385 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
9386 		    (val >> 16) & 0xff);
9387 	}
9388 	rc = sbuf_finish(sb);
9389 	sbuf_delete(sb);
9390 
9391 	return (rc);
9392 }
9393 
9394 static int
9395 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
9396 {
9397 	struct adapter *sc = arg1;
9398 	struct sbuf *sb;
9399 	int rc, i;
9400 	uint16_t incr[NMTUS][NCCTRL_WIN];
9401 	static const char *dec_fac[] = {
9402 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
9403 		"0.9375"
9404 	};
9405 
9406 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9407 	if (sb == NULL)
9408 		return (ENOMEM);
9409 
9410 	rc = 0;
9411 	mtx_lock(&sc->reg_lock);
9412 	if (hw_off_limits(sc))
9413 		rc = ENXIO;
9414 	else
9415 		t4_read_cong_tbl(sc, incr);
9416 	mtx_unlock(&sc->reg_lock);
9417 	if (rc)
9418 		goto done;
9419 
9420 	for (i = 0; i < NCCTRL_WIN; ++i) {
9421 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
9422 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
9423 		    incr[5][i], incr[6][i], incr[7][i]);
9424 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
9425 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
9426 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
9427 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
9428 	}
9429 
9430 	rc = sbuf_finish(sb);
9431 done:
9432 	sbuf_delete(sb);
9433 	return (rc);
9434 }
9435 
9436 static int
9437 sysctl_cim_ibq(SYSCTL_HANDLER_ARGS)
9438 {
9439 	struct adapter *sc = arg1;
9440 	struct sbuf *sb;
9441 	int rc, i, n, qid, coreid;
9442 	uint32_t *buf, *p;
9443 
9444 	qid = arg2 & 0xffff;
9445 	coreid = arg2 >> 16;
9446 
9447 	KASSERT(qid >= 0 && qid < sc->chip_params->cim_num_ibq,
9448 	    ("%s: bad ibq qid %d\n", __func__, qid));
9449 	KASSERT(coreid >= 0 && coreid < sc->params.ncores,
9450 	    ("%s: bad coreid %d\n", __func__, coreid));
9451 
9452 	n = 4 * CIM_IBQ_SIZE;
9453 	buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
9454 	mtx_lock(&sc->reg_lock);
9455 	if (hw_off_limits(sc))
9456 		rc = -ENXIO;
9457 	else
9458 		rc = t4_read_cim_ibq_core(sc, coreid, qid, buf, n);
9459 	mtx_unlock(&sc->reg_lock);
9460 	if (rc < 0) {
9461 		rc = -rc;
9462 		goto done;
9463 	}
9464 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
9465 
9466 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9467 	if (sb == NULL) {
9468 		rc = ENOMEM;
9469 		goto done;
9470 	}
9471 	for (i = 0, p = buf; i < n; i += 16, p += 4)
9472 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
9473 		    p[2], p[3]);
9474 	rc = sbuf_finish(sb);
9475 	sbuf_delete(sb);
9476 done:
9477 	free(buf, M_CXGBE);
9478 	return (rc);
9479 }
9480 
9481 static int
9482 sysctl_cim_obq(SYSCTL_HANDLER_ARGS)
9483 {
9484 	struct adapter *sc = arg1;
9485 	struct sbuf *sb;
9486 	int rc, i, n, qid, coreid;
9487 	uint32_t *buf, *p;
9488 
9489 	qid = arg2 & 0xffff;
9490 	coreid = arg2 >> 16;
9491 
9492 	KASSERT(qid >= 0 && qid < sc->chip_params->cim_num_obq,
9493 	    ("%s: bad obq qid %d\n", __func__, qid));
9494 	KASSERT(coreid >= 0 && coreid < sc->params.ncores,
9495 	    ("%s: bad coreid %d\n", __func__, coreid));
9496 
9497 	n = 6 * CIM_OBQ_SIZE * 4;
9498 	buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
9499 	mtx_lock(&sc->reg_lock);
9500 	if (hw_off_limits(sc))
9501 		rc = -ENXIO;
9502 	else
9503 		rc = t4_read_cim_obq_core(sc, coreid, qid, buf, n);
9504 	mtx_unlock(&sc->reg_lock);
9505 	if (rc < 0) {
9506 		rc = -rc;
9507 		goto done;
9508 	}
9509 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
9510 
9511 	rc = sysctl_wire_old_buffer(req, 0);
9512 	if (rc != 0)
9513 		goto done;
9514 
9515 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9516 	if (sb == NULL) {
9517 		rc = ENOMEM;
9518 		goto done;
9519 	}
9520 	for (i = 0, p = buf; i < n; i += 16, p += 4)
9521 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
9522 		    p[2], p[3]);
9523 	rc = sbuf_finish(sb);
9524 	sbuf_delete(sb);
9525 done:
9526 	free(buf, M_CXGBE);
9527 	return (rc);
9528 }
9529 
9530 static void
9531 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9532 {
9533 	uint32_t *p;
9534 
9535 	sbuf_printf(sb, "Status   Data      PC%s",
9536 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9537 	    "     LS0Stat  LS0Addr             LS0Data");
9538 
9539 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
9540 		if (cfg & F_UPDBGLACAPTPCONLY) {
9541 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
9542 			    p[6], p[7]);
9543 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
9544 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
9545 			    p[4] & 0xff, p[5] >> 8);
9546 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
9547 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9548 			    p[1] & 0xf, p[2] >> 4);
9549 		} else {
9550 			sbuf_printf(sb,
9551 			    "\n  %02x   %x%07x %x%07x %08x %08x "
9552 			    "%08x%08x%08x%08x",
9553 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9554 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
9555 			    p[6], p[7]);
9556 		}
9557 	}
9558 }
9559 
9560 static void
9561 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9562 {
9563 	uint32_t *p;
9564 
9565 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
9566 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9567 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
9568 
9569 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
9570 		if (cfg & F_UPDBGLACAPTPCONLY) {
9571 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
9572 			    p[3] & 0xff, p[2], p[1], p[0]);
9573 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
9574 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
9575 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
9576 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
9577 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
9578 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
9579 			    p[6] >> 16);
9580 		} else {
9581 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
9582 			    "%08x %08x %08x %08x %08x %08x",
9583 			    (p[9] >> 16) & 0xff,
9584 			    p[9] & 0xffff, p[8] >> 16,
9585 			    p[8] & 0xffff, p[7] >> 16,
9586 			    p[7] & 0xffff, p[6] >> 16,
9587 			    p[2], p[1], p[0], p[5], p[4], p[3]);
9588 		}
9589 	}
9590 }
9591 
9592 static int
9593 sbuf_cim_la(struct adapter *sc, int coreid, struct sbuf *sb, int flags)
9594 {
9595 	uint32_t cfg, *buf;
9596 	int rc;
9597 
9598 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9599 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
9600 	    M_ZERO | flags);
9601 	if (buf == NULL)
9602 		return (ENOMEM);
9603 
9604 	mtx_lock(&sc->reg_lock);
9605 	if (hw_off_limits(sc))
9606 		rc = ENXIO;
9607 	else {
9608 		rc = -t4_cim_read_core(sc, 1, coreid, A_UP_UP_DBG_LA_CFG, 1,
9609 		    &cfg);
9610 		if (rc == 0)
9611 			rc = -t4_cim_read_la_core(sc, coreid, buf, NULL);
9612 	}
9613 	mtx_unlock(&sc->reg_lock);
9614 	if (rc == 0) {
9615 		if (chip_id(sc) < CHELSIO_T6)
9616 			sbuf_cim_la4(sc, sb, buf, cfg);
9617 		else
9618 			sbuf_cim_la6(sc, sb, buf, cfg);
9619 	}
9620 	free(buf, M_CXGBE);
9621 	return (rc);
9622 }
9623 
9624 static int
9625 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
9626 {
9627 	struct adapter *sc = arg1;
9628 	int coreid = arg2;
9629 	struct sbuf *sb;
9630 	int rc;
9631 
9632 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9633 	if (sb == NULL)
9634 		return (ENOMEM);
9635 
9636 	rc = sbuf_cim_la(sc, coreid, sb, M_WAITOK);
9637 	if (rc == 0)
9638 		rc = sbuf_finish(sb);
9639 	sbuf_delete(sb);
9640 	return (rc);
9641 }
9642 
9643 static void
9644 dump_cim_regs(struct adapter *sc)
9645 {
9646 	log(LOG_DEBUG, "%s: CIM debug regs1 %08x %08x %08x %08x %08x\n",
9647 	    device_get_nameunit(sc->dev),
9648 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9649 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9650 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA2),
9651 	    t4_read_reg(sc, A_EDC_H_BIST_DATA_PATTERN),
9652 	    t4_read_reg(sc, A_EDC_H_BIST_STATUS_RDATA));
9653 	log(LOG_DEBUG, "%s: CIM debug regs2 %08x %08x %08x %08x %08x\n",
9654 	    device_get_nameunit(sc->dev),
9655 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9656 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9657 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0 + 0x800),
9658 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1 + 0x800),
9659 	    t4_read_reg(sc, A_EDC_H_BIST_CMD_LEN));
9660 }
9661 
9662 static void
9663 dump_cimla(struct adapter *sc)
9664 {
9665 	struct sbuf sb;
9666 	int rc;
9667 
9668 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9669 		log(LOG_DEBUG, "%s: failed to generate CIM LA dump.\n",
9670 		    device_get_nameunit(sc->dev));
9671 		return;
9672 	}
9673 	rc = sbuf_cim_la(sc, 0, &sb, M_WAITOK);
9674 	if (rc == 0) {
9675 		rc = sbuf_finish(&sb);
9676 		if (rc == 0) {
9677 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s\n",
9678 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9679 		}
9680 	}
9681 	sbuf_delete(&sb);
9682 }
9683 
9684 void
9685 t4_os_cim_err(struct adapter *sc)
9686 {
9687 	atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
9688 }
9689 
9690 static int
9691 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
9692 {
9693 	struct adapter *sc = arg1;
9694 	u_int i;
9695 	struct sbuf *sb;
9696 	uint32_t *buf, *p;
9697 	int rc;
9698 
9699 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9700 	if (sb == NULL)
9701 		return (ENOMEM);
9702 
9703 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
9704 	    M_ZERO | M_WAITOK);
9705 
9706 	rc = 0;
9707 	mtx_lock(&sc->reg_lock);
9708 	if (hw_off_limits(sc))
9709 		rc = ENXIO;
9710 	else
9711 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
9712 	mtx_unlock(&sc->reg_lock);
9713 	if (rc)
9714 		goto done;
9715 
9716 	p = buf;
9717 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9718 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
9719 		    p[1], p[0]);
9720 	}
9721 
9722 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9723 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9724 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9725 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9726 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9727 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9728 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9729 		    p[0] & 1);
9730 	}
9731 	rc = sbuf_finish(sb);
9732 done:
9733 	sbuf_delete(sb);
9734 	free(buf, M_CXGBE);
9735 	return (rc);
9736 }
9737 
9738 static int
9739 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9740 {
9741 	struct adapter *sc = arg1;
9742 	u_int i;
9743 	struct sbuf *sb;
9744 	uint32_t *buf, *p;
9745 	int rc;
9746 
9747 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9748 	if (sb == NULL)
9749 		return (ENOMEM);
9750 
9751 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9752 	    M_ZERO | M_WAITOK);
9753 
9754 	rc = 0;
9755 	mtx_lock(&sc->reg_lock);
9756 	if (hw_off_limits(sc))
9757 		rc = ENXIO;
9758 	else
9759 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9760 	mtx_unlock(&sc->reg_lock);
9761 	if (rc)
9762 		goto done;
9763 
9764 	p = buf;
9765 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9766 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9767 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9768 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9769 		    p[4], p[3], p[2], p[1], p[0]);
9770 	}
9771 
9772 	sbuf_printf(sb, "\n\nCntl ID               Data");
9773 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9774 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9775 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9776 	}
9777 
9778 	rc = sbuf_finish(sb);
9779 done:
9780 	sbuf_delete(sb);
9781 	free(buf, M_CXGBE);
9782 	return (rc);
9783 }
9784 
9785 static int
9786 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9787 {
9788 	struct adapter *sc = arg1;
9789 	struct sbuf *sb;
9790 	int rc, i;
9791 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9792 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9793 	uint16_t thres[CIM_NUM_IBQ];
9794 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9795 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9796 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9797 	static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
9798 		"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
9799 		"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
9800 		"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
9801 	};
9802 
9803 	MPASS(chip_id(sc) < CHELSIO_T7);
9804 
9805 	cim_num_obq = sc->chip_params->cim_num_obq;
9806 	if (is_t4(sc)) {
9807 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9808 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9809 	} else {
9810 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9811 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9812 	}
9813 	nq = CIM_NUM_IBQ + cim_num_obq;
9814 
9815 	mtx_lock(&sc->reg_lock);
9816 	if (hw_off_limits(sc))
9817 		rc = ENXIO;
9818 	else {
9819 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9820 		if (rc == 0) {
9821 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9822 			    obq_wr);
9823 			if (rc == 0)
9824 				t4_read_cimq_cfg(sc, base, size, thres);
9825 		}
9826 	}
9827 	mtx_unlock(&sc->reg_lock);
9828 	if (rc)
9829 		return (rc);
9830 
9831 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9832 	if (sb == NULL)
9833 		return (ENOMEM);
9834 
9835 	sbuf_printf(sb,
9836 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9837 
9838 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9839 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9840 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9841 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9842 		    G_QUEREMFLITS(p[2]) * 16);
9843 	for ( ; i < nq; i++, p += 4, wr += 2)
9844 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9845 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9846 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9847 		    G_QUEREMFLITS(p[2]) * 16);
9848 
9849 	rc = sbuf_finish(sb);
9850 	sbuf_delete(sb);
9851 
9852 	return (rc);
9853 }
9854 
9855 static int
9856 sysctl_cim_qcfg_t7(SYSCTL_HANDLER_ARGS)
9857 {
9858 	struct adapter *sc = arg1;
9859 	u_int coreid = arg2;
9860 	struct sbuf *sb;
9861 	int rc, i;
9862 	u_int addr;
9863 	uint16_t base[CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7];
9864 	uint16_t size[CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7];
9865 	uint16_t thres[CIM_NUM_IBQ_T7];
9866 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T7], *wr = obq_wr;
9867 	uint32_t stat[4 * (CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7)], *p = stat;
9868 	static const char * const qname_ibq_t7[] = {
9869 		"TP0", "TP1", "TP2", "TP3", "ULP", "SGE0", "SGE1", "NC-SI",
9870 		"RSVD", "IPC1", "IPC2", "IPC3", "IPC4", "IPC5", "IPC6", "IPC7",
9871 	};
9872 	static const char * const qname_obq_t7[] = {
9873 		"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI", "SGE0-RX",
9874 		"RSVD", "RSVD", "IPC1", "IPC2", "IPC3", "IPC4", "IPC5",
9875 		"IPC6", "IPC7"
9876 	};
9877 	static const char * const qname_ibq_sec_t7[] = {
9878 		"TP0", "TP1", "TP2", "TP3", "ULP", "SGE0", "RSVD", "RSVD",
9879 		"RSVD", "IPC0", "RSVD", "RSVD", "RSVD", "RSVD",	"RSVD", "RSVD",
9880 	};
9881 	static const char * const qname_obq_sec_t7[] = {
9882 		"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "RSVD", "SGE0-RX",
9883 		"RSVD", "RSVD", "IPC0", "RSVD", "RSVD", "RSVD", "RSVD",
9884 		"RSVD", "RSVD",
9885 	};
9886 
9887 	MPASS(chip_id(sc) >= CHELSIO_T7);
9888 
9889 	mtx_lock(&sc->reg_lock);
9890 	if (hw_off_limits(sc))
9891 		rc = ENXIO;
9892 	else {
9893 		rc = -t4_cim_read_core(sc, 1, coreid,
9894 		    A_T7_UP_IBQ_0_SHADOW_RDADDR, 4 * CIM_NUM_IBQ_T7, stat);
9895 		if (rc != 0)
9896 			goto unlock;
9897 
9898 		rc = -t4_cim_read_core(sc, 1, coreid,
9899 		    A_T7_UP_OBQ_0_SHADOW_RDADDR, 4 * CIM_NUM_OBQ_T7,
9900 		    &stat[4 * CIM_NUM_IBQ_T7]);
9901 		if (rc != 0)
9902 			goto unlock;
9903 
9904 		addr = A_T7_UP_OBQ_0_SHADOW_REALADDR;
9905 		for (i = 0; i < CIM_NUM_OBQ_T7 * 2; i++, addr += 8) {
9906 			rc = -t4_cim_read_core(sc, 1, coreid, addr, 1,
9907 			    &obq_wr[i]);
9908 			if (rc != 0)
9909 				goto unlock;
9910 		}
9911 		t4_read_cimq_cfg_core(sc, coreid, base, size, thres);
9912 	}
9913 unlock:
9914 	mtx_unlock(&sc->reg_lock);
9915 	if (rc)
9916 		return (rc);
9917 
9918 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9919 	if (sb == NULL)
9920 		return (ENOMEM);
9921 
9922 	sbuf_printf(sb,
9923 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9924 
9925 	for (i = 0; i < CIM_NUM_IBQ_T7; i++, p += 4) {
9926 		if (!size[i])
9927 			continue;
9928 
9929 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9930 		    coreid == 0 ? qname_ibq_t7[i] : qname_ibq_sec_t7[i],
9931 		    base[i], size[i], thres[i], G_IBQRDADDR(p[0]) & 0xfff,
9932 		    G_IBQWRADDR(p[1]) & 0xfff, G_QUESOPCNT(p[3]),
9933 		    G_QUEEOPCNT(p[3]), G_T7_QUEREMFLITS(p[2]) * 16);
9934 	}
9935 
9936 	for ( ; i < CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7; i++, p += 4, wr += 2) {
9937 		if (!size[i])
9938 			continue;
9939 
9940 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u",
9941 		    coreid == 0 ? qname_obq_t7[i - CIM_NUM_IBQ_T7] :
9942 		    qname_obq_sec_t7[i - CIM_NUM_IBQ_T7],
9943 		    base[i], size[i], G_QUERDADDR(p[0]) & 0xfff,
9944 		    wr[0] << 1, G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9945 		    G_T7_QUEREMFLITS(p[2]) * 16);
9946 	}
9947 
9948 	rc = sbuf_finish(sb);
9949 	sbuf_delete(sb);
9950 	return (rc);
9951 }
9952 
9953 static int
9954 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9955 {
9956 	struct adapter *sc = arg1;
9957 	struct sbuf *sb;
9958 	int rc;
9959 	struct tp_cpl_stats stats;
9960 
9961 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9962 	if (sb == NULL)
9963 		return (ENOMEM);
9964 
9965 	rc = 0;
9966 	mtx_lock(&sc->reg_lock);
9967 	if (hw_off_limits(sc))
9968 		rc = ENXIO;
9969 	else
9970 		t4_tp_get_cpl_stats(sc, &stats, 0);
9971 	mtx_unlock(&sc->reg_lock);
9972 	if (rc)
9973 		goto done;
9974 
9975 	if (sc->chip_params->nchan > 2) {
9976 		sbuf_printf(sb, "                 channel 0  channel 1"
9977 		    "  channel 2  channel 3");
9978 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9979 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9980 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9981 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9982 	} else {
9983 		sbuf_printf(sb, "                 channel 0  channel 1");
9984 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9985 		    stats.req[0], stats.req[1]);
9986 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9987 		    stats.rsp[0], stats.rsp[1]);
9988 	}
9989 
9990 	rc = sbuf_finish(sb);
9991 done:
9992 	sbuf_delete(sb);
9993 	return (rc);
9994 }
9995 
9996 static int
9997 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9998 {
9999 	struct adapter *sc = arg1;
10000 	struct sbuf *sb;
10001 	int rc;
10002 	struct tp_usm_stats stats;
10003 
10004 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10005 	if (sb == NULL)
10006 		return (ENOMEM);
10007 
10008 	rc = 0;
10009 	mtx_lock(&sc->reg_lock);
10010 	if (hw_off_limits(sc))
10011 		rc = ENXIO;
10012 	else
10013 		t4_get_usm_stats(sc, &stats, 1);
10014 	mtx_unlock(&sc->reg_lock);
10015 	if (rc == 0) {
10016 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
10017 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
10018 		sbuf_printf(sb, "Drops:  %u", stats.drops);
10019 		rc = sbuf_finish(sb);
10020 	}
10021 	sbuf_delete(sb);
10022 
10023 	return (rc);
10024 }
10025 
10026 static int
10027 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
10028 {
10029 	struct adapter *sc = arg1;
10030 	struct sbuf *sb;
10031 	int rc;
10032 	struct tp_tid_stats stats;
10033 
10034 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10035 	if (sb == NULL)
10036 		return (ENOMEM);
10037 
10038 	rc = 0;
10039 	mtx_lock(&sc->reg_lock);
10040 	if (hw_off_limits(sc))
10041 		rc = ENXIO;
10042 	else
10043 		t4_tp_get_tid_stats(sc, &stats, 1);
10044 	mtx_unlock(&sc->reg_lock);
10045 	if (rc == 0) {
10046 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
10047 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
10048 		sbuf_printf(sb, "Active:     %u\n", stats.act);
10049 		sbuf_printf(sb, "Passive:    %u", stats.pas);
10050 		rc = sbuf_finish(sb);
10051 	}
10052 	sbuf_delete(sb);
10053 
10054 	return (rc);
10055 }
10056 
10057 static const char * const devlog_level_strings[] = {
10058 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
10059 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
10060 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
10061 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
10062 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
10063 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
10064 };
10065 
10066 static const char * const devlog_facility_strings[] = {
10067 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
10068 	[FW_DEVLOG_FACILITY_CF]		= "CF",
10069 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
10070 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
10071 	[FW_DEVLOG_FACILITY_RES]	= "RES",
10072 	[FW_DEVLOG_FACILITY_HW]		= "HW",
10073 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
10074 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
10075 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
10076 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
10077 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
10078 	[FW_DEVLOG_FACILITY_VI]		= "VI",
10079 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
10080 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
10081 	[FW_DEVLOG_FACILITY_TM]		= "TM",
10082 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
10083 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
10084 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
10085 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
10086 	[FW_DEVLOG_FACILITY_RI]		= "RI",
10087 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
10088 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
10089 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
10090 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
10091 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
10092 };
10093 
10094 static int
10095 sbuf_devlog(struct adapter *sc, int coreid, struct sbuf *sb, int flags)
10096 {
10097 	int i, j, rc, nentries, first = 0;
10098 	struct devlog_params *dparams = &sc->params.devlog;
10099 	struct fw_devlog_e *buf, *e;
10100 	uint32_t addr, size;
10101 	uint64_t ftstamp = UINT64_MAX;
10102 
10103 	KASSERT(coreid >= 0 && coreid < sc->params.ncores,
10104 	    ("%s: bad coreid %d\n", __func__, coreid));
10105 
10106 	if (dparams->addr == 0)
10107 		return (ENXIO);
10108 
10109 	size = dparams->size / sc->params.ncores;
10110 	addr = dparams->addr + coreid * size;
10111 
10112 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
10113 	buf = malloc(size, M_CXGBE, M_ZERO | flags);
10114 	if (buf == NULL)
10115 		return (ENOMEM);
10116 
10117 	mtx_lock(&sc->reg_lock);
10118 	if (hw_off_limits(sc))
10119 		rc = ENXIO;
10120 	else
10121 		rc = read_via_memwin(sc, 1, addr, (void *)buf, size);
10122 	mtx_unlock(&sc->reg_lock);
10123 	if (rc != 0)
10124 		goto done;
10125 
10126 	nentries = size / sizeof(struct fw_devlog_e);
10127 	for (i = 0; i < nentries; i++) {
10128 		e = &buf[i];
10129 
10130 		if (e->timestamp == 0)
10131 			break;	/* end */
10132 
10133 		e->timestamp = be64toh(e->timestamp);
10134 		e->seqno = be32toh(e->seqno);
10135 		for (j = 0; j < 8; j++)
10136 			e->params[j] = be32toh(e->params[j]);
10137 
10138 		if (e->timestamp < ftstamp) {
10139 			ftstamp = e->timestamp;
10140 			first = i;
10141 		}
10142 	}
10143 
10144 	if (buf[first].timestamp == 0)
10145 		goto done;	/* nothing in the log */
10146 
10147 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
10148 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
10149 
10150 	i = first;
10151 	do {
10152 		e = &buf[i];
10153 		if (e->timestamp == 0)
10154 			break;	/* end */
10155 
10156 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
10157 		    e->seqno, e->timestamp,
10158 		    (e->level < nitems(devlog_level_strings) ?
10159 			devlog_level_strings[e->level] : "UNKNOWN"),
10160 		    (e->facility < nitems(devlog_facility_strings) ?
10161 			devlog_facility_strings[e->facility] : "UNKNOWN"));
10162 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
10163 		    e->params[2], e->params[3], e->params[4],
10164 		    e->params[5], e->params[6], e->params[7]);
10165 
10166 		if (++i == nentries)
10167 			i = 0;
10168 	} while (i != first);
10169 done:
10170 	free(buf, M_CXGBE);
10171 	return (rc);
10172 }
10173 
10174 static int
10175 sysctl_devlog(SYSCTL_HANDLER_ARGS)
10176 {
10177 	struct adapter *sc = arg1;
10178 	int rc, i, coreid = arg2;
10179 	struct sbuf *sb;
10180 
10181 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10182 	if (sb == NULL)
10183 		return (ENOMEM);
10184 	if (coreid == -1) {
10185 		/* -1 means all cores */
10186 		for (i = rc = 0; i < sc->params.ncores && rc == 0; i++) {
10187 			if (sc->params.ncores > 0)
10188 				sbuf_printf(sb, "=== CIM core %u ===\n", i);
10189 			rc = sbuf_devlog(sc, i, sb, M_WAITOK);
10190 		}
10191 	} else {
10192 		KASSERT(coreid >= 0 && coreid < sc->params.ncores,
10193 		    ("%s: bad coreid %d\n", __func__, coreid));
10194 		rc = sbuf_devlog(sc, coreid, sb, M_WAITOK);
10195 	}
10196 	if (rc == 0)
10197 		rc = sbuf_finish(sb);
10198 	sbuf_delete(sb);
10199 	return (rc);
10200 }
10201 
10202 static void
10203 dump_devlog(struct adapter *sc)
10204 {
10205 	int rc, i;
10206 	struct sbuf sb;
10207 
10208 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
10209 		log(LOG_DEBUG, "%s: failed to generate devlog dump.\n",
10210 		    device_get_nameunit(sc->dev));
10211 		return;
10212 	}
10213 	for (i = rc = 0; i < sc->params.ncores && rc == 0; i++) {
10214 		if (sc->params.ncores > 0)
10215 			sbuf_printf(&sb, "=== CIM core %u ===\n", i);
10216 		rc = sbuf_devlog(sc, i, &sb, M_WAITOK);
10217 	}
10218 	if (rc == 0) {
10219 		sbuf_finish(&sb);
10220 		log(LOG_DEBUG, "%s: device log follows.\n%s",
10221 		    device_get_nameunit(sc->dev), sbuf_data(&sb));
10222 	}
10223 	sbuf_delete(&sb);
10224 }
10225 
10226 static int
10227 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
10228 {
10229 	struct adapter *sc = arg1;
10230 	struct sbuf *sb;
10231 	int rc;
10232 	struct tp_fcoe_stats stats[MAX_NCHAN];
10233 	int i, nchan = sc->chip_params->nchan;
10234 
10235 	rc = 0;
10236 	mtx_lock(&sc->reg_lock);
10237 	if (hw_off_limits(sc))
10238 		rc = ENXIO;
10239 	else {
10240 		for (i = 0; i < nchan; i++)
10241 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
10242 	}
10243 	mtx_unlock(&sc->reg_lock);
10244 	if (rc != 0)
10245 		return (rc);
10246 
10247 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10248 	if (sb == NULL)
10249 		return (ENOMEM);
10250 
10251 	if (nchan > 2) {
10252 		sbuf_printf(sb, "                   channel 0        channel 1"
10253 		    "        channel 2        channel 3");
10254 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
10255 		    stats[0].octets_ddp, stats[1].octets_ddp,
10256 		    stats[2].octets_ddp, stats[3].octets_ddp);
10257 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
10258 		    stats[0].frames_ddp, stats[1].frames_ddp,
10259 		    stats[2].frames_ddp, stats[3].frames_ddp);
10260 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
10261 		    stats[0].frames_drop, stats[1].frames_drop,
10262 		    stats[2].frames_drop, stats[3].frames_drop);
10263 	} else {
10264 		sbuf_printf(sb, "                   channel 0        channel 1");
10265 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
10266 		    stats[0].octets_ddp, stats[1].octets_ddp);
10267 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
10268 		    stats[0].frames_ddp, stats[1].frames_ddp);
10269 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
10270 		    stats[0].frames_drop, stats[1].frames_drop);
10271 	}
10272 
10273 	rc = sbuf_finish(sb);
10274 	sbuf_delete(sb);
10275 
10276 	return (rc);
10277 }
10278 
10279 static int
10280 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
10281 {
10282 	struct adapter *sc = arg1;
10283 	struct sbuf *sb;
10284 	int rc, i;
10285 	unsigned int map, kbps, ipg, mode;
10286 	unsigned int pace_tab[NTX_SCHED];
10287 
10288 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
10289 	if (sb == NULL)
10290 		return (ENOMEM);
10291 
10292 	mtx_lock(&sc->reg_lock);
10293 	if (hw_off_limits(sc)) {
10294 		mtx_unlock(&sc->reg_lock);
10295 		rc = ENXIO;
10296 		goto done;
10297 	}
10298 
10299 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
10300 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
10301 	t4_read_pace_tbl(sc, pace_tab);
10302 	mtx_unlock(&sc->reg_lock);
10303 
10304 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
10305 	    "Class IPG (0.1 ns)   Flow IPG (us)");
10306 
10307 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
10308 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
10309 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
10310 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
10311 		if (kbps)
10312 			sbuf_printf(sb, "%9u     ", kbps);
10313 		else
10314 			sbuf_printf(sb, " disabled     ");
10315 
10316 		if (ipg)
10317 			sbuf_printf(sb, "%13u        ", ipg);
10318 		else
10319 			sbuf_printf(sb, "     disabled        ");
10320 
10321 		if (pace_tab[i])
10322 			sbuf_printf(sb, "%10u", pace_tab[i]);
10323 		else
10324 			sbuf_printf(sb, "  disabled");
10325 	}
10326 	rc = sbuf_finish(sb);
10327 done:
10328 	sbuf_delete(sb);
10329 	return (rc);
10330 }
10331 
10332 static int
10333 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
10334 {
10335 	struct adapter *sc = arg1;
10336 	struct sbuf *sb;
10337 	int rc, i, j;
10338 	uint64_t *p0, *p1;
10339 	struct lb_port_stats s[2];
10340 	static const char *stat_name[] = {
10341 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
10342 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
10343 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
10344 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
10345 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
10346 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
10347 		"BG2FramesTrunc:", "BG3FramesTrunc:"
10348 	};
10349 
10350 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10351 	if (sb == NULL)
10352 		return (ENOMEM);
10353 
10354 	memset(s, 0, sizeof(s));
10355 
10356 	rc = 0;
10357 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
10358 		mtx_lock(&sc->reg_lock);
10359 		if (hw_off_limits(sc))
10360 			rc = ENXIO;
10361 		else {
10362 			t4_get_lb_stats(sc, i, &s[0]);
10363 			t4_get_lb_stats(sc, i + 1, &s[1]);
10364 		}
10365 		mtx_unlock(&sc->reg_lock);
10366 		if (rc != 0)
10367 			break;
10368 
10369 		p0 = &s[0].octets;
10370 		p1 = &s[1].octets;
10371 		sbuf_printf(sb, "%s                       Loopback %u"
10372 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
10373 
10374 		for (j = 0; j < nitems(stat_name); j++)
10375 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
10376 				   *p0++, *p1++);
10377 	}
10378 
10379 	if (rc == 0)
10380 		rc = sbuf_finish(sb);
10381 	sbuf_delete(sb);
10382 
10383 	return (rc);
10384 }
10385 
10386 static int
10387 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
10388 {
10389 	int rc = 0;
10390 	struct port_info *pi = arg1;
10391 	struct link_config *lc = &pi->link_cfg;
10392 	struct sbuf *sb;
10393 
10394 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
10395 	if (sb == NULL)
10396 		return (ENOMEM);
10397 
10398 	if (lc->link_ok || lc->link_down_rc == 255)
10399 		sbuf_printf(sb, "n/a");
10400 	else
10401 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
10402 
10403 	rc = sbuf_finish(sb);
10404 	sbuf_delete(sb);
10405 
10406 	return (rc);
10407 }
10408 
10409 struct mem_desc {
10410 	uint64_t base;
10411 	uint64_t limit;
10412 	u_int idx;
10413 };
10414 
10415 static int
10416 mem_desc_cmp(const void *a, const void *b)
10417 {
10418 	const uint64_t v1 = ((const struct mem_desc *)a)->base;
10419 	const uint64_t v2 = ((const struct mem_desc *)b)->base;
10420 
10421 	if (v1 < v2)
10422 		return (-1);
10423 	else if (v1 > v2)
10424 		return (1);
10425 
10426 	return (0);
10427 }
10428 
10429 static void
10430 mem_region_show(struct sbuf *sb, const char *name, uint64_t from, uint64_t to)
10431 {
10432 	uintmax_t size;
10433 
10434 	if (from == to)
10435 		return;
10436 
10437 	size = to - from + 1;
10438 	if (size == 0)
10439 		return;
10440 
10441 	if (from > UINT32_MAX || to > UINT32_MAX)
10442 		sbuf_printf(sb, "%-18s 0x%012jx-0x%012jx [%ju]\n", name,
10443 		    (uintmax_t)from, (uintmax_t)to, size);
10444 	else
10445 		sbuf_printf(sb, "%-18s 0x%08jx-0x%08jx [%ju]\n", name,
10446 		    (uintmax_t)from, (uintmax_t)to, size);
10447 }
10448 
10449 static int
10450 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
10451 {
10452 	struct adapter *sc = arg1;
10453 	struct sbuf *sb;
10454 	int rc, i, n, nchan;
10455 	uint32_t lo, hi, used, free, alloc;
10456 	static const char *memory[] = {
10457 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
10458 	};
10459 	static const char *region[] = {
10460 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
10461 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
10462 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
10463 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
10464 		"RQUDP region:", "PBL region:", "TXPBL region:",
10465 		"TLSKey region:", "RRQ region:", "NVMe STAG region:",
10466 		"NVMe RQ region:", "NVMe RXPBL region:", "NVMe TPT region:",
10467 		"NVMe TXPBL region:", "DBVFIFO region:", "ULPRX state:",
10468 		"ULPTX state:", "RoCE RRQ region:", "On-chip queues:",
10469 	};
10470 	struct mem_desc avail[4];
10471 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
10472 	struct mem_desc *md;
10473 
10474 	rc = sysctl_wire_old_buffer(req, 0);
10475 	if (rc != 0)
10476 		return (rc);
10477 
10478 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10479 	if (sb == NULL)
10480 		return (ENOMEM);
10481 
10482 	for (i = 0; i < nitems(mem); i++) {
10483 		mem[i].limit = 0;
10484 		mem[i].idx = i;
10485 	}
10486 
10487 	mtx_lock(&sc->reg_lock);
10488 	if (hw_off_limits(sc)) {
10489 		rc = ENXIO;
10490 		goto done;
10491 	}
10492 
10493 	/* Find and sort the populated memory ranges */
10494 	i = 0;
10495 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
10496 	if (lo & F_EDRAM0_ENABLE) {
10497 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
10498 		if (chip_id(sc) >= CHELSIO_T7) {
10499 			avail[i].base = (uint64_t)G_T7_EDRAM0_BASE(hi) << 20;
10500 			avail[i].limit = avail[i].base +
10501 			    (G_T7_EDRAM0_SIZE(hi) << 20);
10502 		} else {
10503 			avail[i].base = (uint64_t)G_EDRAM0_BASE(hi) << 20;
10504 			avail[i].limit = avail[i].base +
10505 			    (G_EDRAM0_SIZE(hi) << 20);
10506 		}
10507 		avail[i].idx = 0;
10508 		i++;
10509 	}
10510 	if (lo & F_EDRAM1_ENABLE) {
10511 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
10512 		if (chip_id(sc) >= CHELSIO_T7) {
10513 			avail[i].base = (uint64_t)G_T7_EDRAM1_BASE(hi) << 20;
10514 			avail[i].limit = avail[i].base +
10515 			    (G_T7_EDRAM1_SIZE(hi) << 20);
10516 		} else {
10517 			avail[i].base = (uint64_t)G_EDRAM1_BASE(hi) << 20;
10518 			avail[i].limit = avail[i].base +
10519 			    (G_EDRAM1_SIZE(hi) << 20);
10520 		}
10521 		avail[i].idx = 1;
10522 		i++;
10523 	}
10524 	if (lo & F_EXT_MEM_ENABLE) {
10525 		switch (chip_id(sc)) {
10526 		case CHELSIO_T4:
10527 		case CHELSIO_T6:
10528 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
10529 			avail[i].base = (uint64_t)G_EXT_MEM_BASE(hi) << 20;
10530 			avail[i].limit = avail[i].base +
10531 			    (G_EXT_MEM_SIZE(hi) << 20);
10532 			avail[i].idx = 2;
10533 			break;
10534 		case CHELSIO_T5:
10535 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY0_BAR);
10536 			avail[i].base = (uint64_t)G_EXT_MEM0_BASE(hi) << 20;
10537 			avail[i].limit = avail[i].base +
10538 			    (G_EXT_MEM0_SIZE(hi) << 20);
10539 			avail[i].idx = 3;	/* Call it MC0 for T5 */
10540 			break;
10541 		default:
10542 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY0_BAR);
10543 			avail[i].base = (uint64_t)G_T7_EXT_MEM0_BASE(hi) << 20;
10544 			avail[i].limit = avail[i].base +
10545 			    (G_T7_EXT_MEM0_SIZE(hi) << 20);
10546 			avail[i].idx = 3;	/* Call it MC0 for T7+ */
10547 			break;
10548 		}
10549 		i++;
10550 	}
10551 	if (lo & F_EXT_MEM1_ENABLE && !(lo & F_MC_SPLIT)) {
10552 		/* Only T5 and T7+ have 2 MCs. */
10553 		MPASS(is_t5(sc) || chip_id(sc) >= CHELSIO_T7);
10554 
10555 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
10556 		if (chip_id(sc) >= CHELSIO_T7) {
10557 			avail[i].base = (uint64_t)G_T7_EXT_MEM1_BASE(hi) << 20;
10558 			avail[i].limit = avail[i].base +
10559 			    (G_T7_EXT_MEM1_SIZE(hi) << 20);
10560 		} else {
10561 			avail[i].base = (uint64_t)G_EXT_MEM1_BASE(hi) << 20;
10562 			avail[i].limit = avail[i].base +
10563 			    (G_EXT_MEM1_SIZE(hi) << 20);
10564 		}
10565 		avail[i].idx = 4;
10566 		i++;
10567 	}
10568 	if (lo & F_HMA_MUX) {
10569 		/* Only T6+ have HMA. */
10570 		MPASS(chip_id(sc) >= CHELSIO_T6);
10571 
10572 		if (chip_id(sc) >= CHELSIO_T7) {
10573 			hi = t4_read_reg(sc, A_MA_HOST_MEMORY_BAR);
10574 			avail[i].base = (uint64_t)G_HMATARGETBASE(hi) << 20;
10575 			avail[i].limit = avail[i].base +
10576 			    (G_T7_HMA_SIZE(hi) << 20);
10577 		} else {
10578 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
10579 			avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
10580 			avail[i].limit = avail[i].base +
10581 			    (G_EXT_MEM1_SIZE(hi) << 20);
10582 		}
10583 		avail[i].idx = 5;
10584 		i++;
10585 	}
10586 	MPASS(i <= nitems(avail));
10587 	if (!i)                                    /* no memory available */
10588 		goto done;
10589 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
10590 
10591 	md = &mem[0];
10592 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
10593 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
10594 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
10595 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
10596 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
10597 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
10598 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
10599 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
10600 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
10601 
10602 	/* the next few have explicit upper bounds */
10603 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
10604 	md->limit = md->base - 1 +
10605 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
10606 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
10607 	md++;
10608 
10609 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
10610 	md->limit = md->base - 1 +
10611 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
10612 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
10613 	md++;
10614 
10615 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10616 		if (chip_id(sc) <= CHELSIO_T5)
10617 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
10618 		else
10619 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
10620 		md->limit = 0;
10621 	} else {
10622 		md->base = 0;
10623 		md->idx = nitems(region);  /* hide it */
10624 	}
10625 	md++;
10626 
10627 #define ulp_region(reg) do {\
10628 		const u_int shift = chip_id(sc) >= CHELSIO_T7 ? 4 : 0; \
10629 		md->base = (uint64_t)t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT) << shift; \
10630 		md->limit = (uint64_t)t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT) << shift; \
10631 		md->limit += (1 << shift) - 1; \
10632 		md++; \
10633 	} while (0)
10634 
10635 #define	hide_ulp_region() do { \
10636 		md->base = 0; \
10637 		md->idx = nitems(region); \
10638 		md++; \
10639 	} while (0)
10640 
10641 	ulp_region(RX_ISCSI);
10642 	ulp_region(RX_TDDP);
10643 	ulp_region(TX_TPT);
10644 	ulp_region(RX_STAG);
10645 	ulp_region(RX_RQ);
10646 	if (chip_id(sc) < CHELSIO_T7)
10647 		ulp_region(RX_RQUDP);
10648 	else
10649 		hide_ulp_region();
10650 	ulp_region(RX_PBL);
10651 	ulp_region(TX_PBL);
10652 	if (chip_id(sc) >= CHELSIO_T6)
10653 		ulp_region(RX_TLS_KEY);
10654 	else
10655 		hide_ulp_region();
10656 	if (chip_id(sc) >= CHELSIO_T7) {
10657 		ulp_region(RX_RRQ);
10658 		ulp_region(RX_NVME_TCP_STAG);
10659 		ulp_region(RX_NVME_TCP_RQ);
10660 		ulp_region(RX_NVME_TCP_PBL);
10661 		ulp_region(TX_NVME_TCP_TPT);
10662 		ulp_region(TX_NVME_TCP_PBL);
10663 	} else {
10664 		hide_ulp_region();
10665 		hide_ulp_region();
10666 		hide_ulp_region();
10667 		hide_ulp_region();
10668 		hide_ulp_region();
10669 		hide_ulp_region();
10670 	}
10671 #undef ulp_region
10672 #undef hide_ulp_region
10673 
10674 	md->base = 0;
10675 	if (is_t4(sc))
10676 		md->idx = nitems(region);
10677 	else {
10678 		uint32_t size = 0;
10679 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
10680 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
10681 
10682 		if (is_t5(sc)) {
10683 			if (sge_ctrl & F_VFIFO_ENABLE)
10684 				size = fifo_size << 2;
10685 		} else
10686 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
10687 
10688 		if (size) {
10689 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
10690 			md->limit = md->base + size - 1;
10691 		} else
10692 			md->idx = nitems(region);
10693 	}
10694 	md++;
10695 
10696 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
10697 	md->limit = 0;
10698 	md++;
10699 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
10700 	md->limit = 0;
10701 	md++;
10702 
10703 	if (chip_id(sc) >= CHELSIO_T7) {
10704 		t4_tp_pio_read(sc, &lo, 1, A_TP_ROCE_RRQ_BASE, false);
10705 		md->base = lo;
10706 	} else {
10707 		md->base = 0;
10708 		md->idx = nitems(region);
10709 	}
10710 	md++;
10711 
10712 	md->base = sc->vres.ocq.start;
10713 	if (sc->vres.ocq.size)
10714 		md->limit = md->base + sc->vres.ocq.size - 1;
10715 	else
10716 		md->idx = nitems(region);  /* hide it */
10717 	md++;
10718 
10719 	/* add any address-space holes, there can be up to 3 */
10720 	for (n = 0; n < i - 1; n++)
10721 		if (avail[n].limit < avail[n + 1].base)
10722 			(md++)->base = avail[n].limit;
10723 	if (avail[n].limit)
10724 		(md++)->base = avail[n].limit;
10725 
10726 	n = md - mem;
10727 	MPASS(n <= nitems(mem));
10728 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
10729 
10730 	for (lo = 0; lo < i; lo++)
10731 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
10732 				avail[lo].limit - 1);
10733 
10734 	sbuf_printf(sb, "\n");
10735 	for (i = 0; i < n; i++) {
10736 		if (mem[i].idx >= nitems(region))
10737 			continue;                        /* skip holes */
10738 		if (!mem[i].limit)
10739 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
10740 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
10741 				mem[i].limit);
10742 	}
10743 
10744 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
10745 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
10746 	if (hi != lo  - 1) {
10747 		sbuf_printf(sb, "\n");
10748 		mem_region_show(sb, "uP RAM:", lo, hi);
10749 	}
10750 
10751 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
10752 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
10753 	if (hi != lo  - 1)
10754 		mem_region_show(sb, "uP Extmem2:", lo, hi);
10755 
10756 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
10757 	if (chip_id(sc) >= CHELSIO_T7)
10758 		nchan = 1 << G_T7_PMRXNUMCHN(lo);
10759 	else
10760 		nchan = lo & F_PMRXNUMCHN ? 2 : 1;
10761 	for (i = 0, free = 0; i < nchan; i++)
10762 		free += G_FREERXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_RX_CNT));
10763 	sbuf_printf(sb, "\n%u Rx pages (%u free) of size %uKiB for %u channels\n",
10764 		   G_PMRXMAXPAGE(lo), free,
10765 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10, nchan);
10766 
10767 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
10768 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
10769 	if (chip_id(sc) >= CHELSIO_T7)
10770 		nchan = 1 << G_T7_PMTXNUMCHN(lo);
10771 	else
10772 		nchan = 1 << G_PMTXNUMCHN(lo);
10773 	for (i = 0, free = 0; i < nchan; i++)
10774 		free += G_FREETXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_TX_CNT));
10775 	sbuf_printf(sb, "%u Tx pages (%u free) of size %u%ciB for %u channels\n",
10776 		   G_PMTXMAXPAGE(lo), free,
10777 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
10778 		   hi >= (1 << 20) ? 'M' : 'K', nchan);
10779 	sbuf_printf(sb, "%u p-structs (%u free)\n",
10780 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT),
10781 		   G_FREEPSTRUCTCOUNT(t4_read_reg(sc, A_TP_FLM_FREE_PS_CNT)));
10782 
10783 	for (i = 0; i < 4; i++) {
10784 		if (chip_id(sc) > CHELSIO_T5)
10785 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
10786 		else
10787 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
10788 		if (is_t5(sc)) {
10789 			used = G_T5_USED(lo);
10790 			alloc = G_T5_ALLOC(lo);
10791 		} else {
10792 			used = G_USED(lo);
10793 			alloc = G_ALLOC(lo);
10794 		}
10795 		/* For T6+ these are MAC buffer groups */
10796 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
10797 		    i, used, alloc);
10798 	}
10799 	for (i = 0; i < sc->chip_params->nchan; i++) {
10800 		if (chip_id(sc) > CHELSIO_T5)
10801 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
10802 		else
10803 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
10804 		if (is_t5(sc)) {
10805 			used = G_T5_USED(lo);
10806 			alloc = G_T5_ALLOC(lo);
10807 		} else {
10808 			used = G_USED(lo);
10809 			alloc = G_ALLOC(lo);
10810 		}
10811 		/* For T6+ these are MAC buffer groups */
10812 		sbuf_printf(sb,
10813 		    "\nLoopback %d using %u pages out of %u allocated",
10814 		    i, used, alloc);
10815 	}
10816 done:
10817 	mtx_unlock(&sc->reg_lock);
10818 	if (rc == 0)
10819 		rc = sbuf_finish(sb);
10820 	sbuf_delete(sb);
10821 	return (rc);
10822 }
10823 
10824 static inline void
10825 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
10826 {
10827 	*mask = x | y;
10828 	y = htobe64(y);
10829 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
10830 }
10831 
10832 static int
10833 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
10834 {
10835 	struct adapter *sc = arg1;
10836 	struct sbuf *sb;
10837 	int rc, i;
10838 
10839 	MPASS(chip_id(sc) <= CHELSIO_T5);
10840 
10841 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10842 	if (sb == NULL)
10843 		return (ENOMEM);
10844 
10845 	sbuf_printf(sb,
10846 	    "Idx  Ethernet address     Mask     Vld Ports PF"
10847 	    "  VF              Replication             P0 P1 P2 P3  ML");
10848 	rc = 0;
10849 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10850 		uint64_t tcamx, tcamy, mask;
10851 		uint32_t cls_lo, cls_hi;
10852 		uint8_t addr[ETHER_ADDR_LEN];
10853 
10854 		mtx_lock(&sc->reg_lock);
10855 		if (hw_off_limits(sc))
10856 			rc = ENXIO;
10857 		else {
10858 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
10859 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
10860 		}
10861 		mtx_unlock(&sc->reg_lock);
10862 		if (rc != 0)
10863 			break;
10864 		if (tcamx & tcamy)
10865 			continue;
10866 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10867 		mtx_lock(&sc->reg_lock);
10868 		if (hw_off_limits(sc))
10869 			rc = ENXIO;
10870 		else {
10871 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10872 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10873 		}
10874 		mtx_unlock(&sc->reg_lock);
10875 		if (rc != 0)
10876 			break;
10877 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
10878 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
10879 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
10880 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
10881 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
10882 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
10883 
10884 		if (cls_lo & F_REPLICATE) {
10885 			struct fw_ldst_cmd ldst_cmd;
10886 
10887 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10888 			ldst_cmd.op_to_addrspace =
10889 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10890 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10891 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10892 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10893 			ldst_cmd.u.mps.rplc.fid_idx =
10894 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10895 				V_FW_LDST_CMD_IDX(i));
10896 
10897 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10898 			    "t4mps");
10899 			if (rc)
10900 				break;
10901 			if (hw_off_limits(sc))
10902 				rc = ENXIO;
10903 			else
10904 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10905 				    sizeof(ldst_cmd), &ldst_cmd);
10906 			end_synchronized_op(sc, 0);
10907 			if (rc != 0)
10908 				break;
10909 			else {
10910 				sbuf_printf(sb, " %08x %08x %08x %08x",
10911 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10912 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10913 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10914 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10915 			}
10916 		} else
10917 			sbuf_printf(sb, "%36s", "");
10918 
10919 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
10920 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
10921 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
10922 	}
10923 
10924 	if (rc)
10925 		(void) sbuf_finish(sb);
10926 	else
10927 		rc = sbuf_finish(sb);
10928 	sbuf_delete(sb);
10929 
10930 	return (rc);
10931 }
10932 
10933 static int
10934 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
10935 {
10936 	struct adapter *sc = arg1;
10937 	struct sbuf *sb;
10938 	int rc, i;
10939 
10940 	MPASS(chip_id(sc) == CHELSIO_T6);
10941 
10942 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10943 	if (sb == NULL)
10944 		return (ENOMEM);
10945 
10946 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
10947 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
10948 	    "                           Replication"
10949 	    "                                    P0 P1 P2 P3  ML");
10950 
10951 	rc = 0;
10952 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10953 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
10954 		uint16_t ivlan;
10955 		uint64_t tcamx, tcamy, val, mask;
10956 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10957 		uint8_t addr[ETHER_ADDR_LEN];
10958 
10959 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10960 		if (i < 256)
10961 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10962 		else
10963 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10964 		mtx_lock(&sc->reg_lock);
10965 		if (hw_off_limits(sc))
10966 			rc = ENXIO;
10967 		else {
10968 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10969 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10970 			tcamy = G_DMACH(val) << 32;
10971 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10972 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10973 		}
10974 		mtx_unlock(&sc->reg_lock);
10975 		if (rc != 0)
10976 			break;
10977 
10978 		lookup_type = G_DATALKPTYPE(data2);
10979 		port_num = G_DATAPORTNUM(data2);
10980 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10981 			/* Inner header VNI */
10982 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10983 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10984 			dip_hit = data2 & F_DATADIPHIT;
10985 			vlan_vld = 0;
10986 		} else {
10987 			vniy = 0;
10988 			dip_hit = 0;
10989 			vlan_vld = data2 & F_DATAVIDH2;
10990 			ivlan = G_VIDL(val);
10991 		}
10992 
10993 		ctl |= V_CTLXYBITSEL(1);
10994 		mtx_lock(&sc->reg_lock);
10995 		if (hw_off_limits(sc))
10996 			rc = ENXIO;
10997 		else {
10998 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10999 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
11000 			tcamx = G_DMACH(val) << 32;
11001 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
11002 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
11003 		}
11004 		mtx_unlock(&sc->reg_lock);
11005 		if (rc != 0)
11006 			break;
11007 
11008 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11009 			/* Inner header VNI mask */
11010 			vnix = ((data2 & F_DATAVIDH2) << 23) |
11011 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
11012 		} else
11013 			vnix = 0;
11014 
11015 		if (tcamx & tcamy)
11016 			continue;
11017 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
11018 
11019 		mtx_lock(&sc->reg_lock);
11020 		if (hw_off_limits(sc))
11021 			rc = ENXIO;
11022 		else {
11023 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
11024 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
11025 		}
11026 		mtx_unlock(&sc->reg_lock);
11027 		if (rc != 0)
11028 			break;
11029 
11030 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11031 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11032 			    "%012jx %06x %06x    -    -   %3c"
11033 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
11034 			    addr[1], addr[2], addr[3], addr[4], addr[5],
11035 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
11036 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11037 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11038 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11039 		} else {
11040 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11041 			    "%012jx    -       -   ", i, addr[0], addr[1],
11042 			    addr[2], addr[3], addr[4], addr[5],
11043 			    (uintmax_t)mask);
11044 
11045 			if (vlan_vld)
11046 				sbuf_printf(sb, "%4u   Y     ", ivlan);
11047 			else
11048 				sbuf_printf(sb, "  -    N     ");
11049 
11050 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
11051 			    lookup_type ? 'I' : 'O', port_num,
11052 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11053 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11054 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11055 		}
11056 
11057 
11058 		if (cls_lo & F_T6_REPLICATE) {
11059 			struct fw_ldst_cmd ldst_cmd;
11060 
11061 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
11062 			ldst_cmd.op_to_addrspace =
11063 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
11064 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
11065 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
11066 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
11067 			ldst_cmd.u.mps.rplc.fid_idx =
11068 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
11069 				V_FW_LDST_CMD_IDX(i));
11070 
11071 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
11072 			    "t6mps");
11073 			if (rc)
11074 				break;
11075 			if (hw_off_limits(sc))
11076 				rc = ENXIO;
11077 			else
11078 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
11079 				    sizeof(ldst_cmd), &ldst_cmd);
11080 			end_synchronized_op(sc, 0);
11081 			if (rc != 0)
11082 				break;
11083 			else {
11084 				sbuf_printf(sb, " %08x %08x %08x %08x"
11085 				    " %08x %08x %08x %08x",
11086 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
11087 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
11088 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
11089 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
11090 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
11091 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
11092 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
11093 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
11094 			}
11095 		} else
11096 			sbuf_printf(sb, "%72s", "");
11097 
11098 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
11099 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
11100 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
11101 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
11102 	}
11103 
11104 	if (rc)
11105 		(void) sbuf_finish(sb);
11106 	else
11107 		rc = sbuf_finish(sb);
11108 	sbuf_delete(sb);
11109 
11110 	return (rc);
11111 }
11112 
11113 static int
11114 sysctl_mps_tcam_t7(SYSCTL_HANDLER_ARGS)
11115 {
11116 	struct adapter *sc = arg1;
11117 	struct sbuf *sb;
11118 	int rc, i;
11119 
11120 	MPASS(chip_id(sc) >= CHELSIO_T7);
11121 
11122 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11123 	if (sb == NULL)
11124 		return (ENOMEM);
11125 
11126 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
11127 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
11128 	    "                           Replication"
11129 	    "                                    P0 P1 P2 P3  ML");
11130 
11131 	rc = 0;
11132 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
11133 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
11134 		uint16_t ivlan;
11135 		uint64_t tcamx, tcamy, val, mask;
11136 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
11137 		uint8_t addr[ETHER_ADDR_LEN];
11138 
11139 		/* Read tcamy */
11140 		ctl = (V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0));
11141 		if (chip_rev(sc) == 0) {
11142 			if (i < 256)
11143 				ctl |= V_CTLTCAMINDEX(i) | V_T7_CTLTCAMSEL(0);
11144 			else
11145 				ctl |= V_CTLTCAMINDEX(i - 256) | V_T7_CTLTCAMSEL(1);
11146 		} else {
11147 #if 0
11148 			ctl = (V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0));
11149 #endif
11150 			if (i < 512)
11151 				ctl |= V_CTLTCAMINDEX(i) | V_T7_CTLTCAMSEL(0);
11152 			else if (i < 1024)
11153 				ctl |= V_CTLTCAMINDEX(i - 512) | V_T7_CTLTCAMSEL(1);
11154 			else
11155 				ctl |= V_CTLTCAMINDEX(i - 1024) | V_T7_CTLTCAMSEL(2);
11156 		}
11157 
11158 		mtx_lock(&sc->reg_lock);
11159 		if (hw_off_limits(sc))
11160 			rc = ENXIO;
11161 		else {
11162 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
11163 			val = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA1_REQ_ID1);
11164 			tcamy = G_DMACH(val) << 32;
11165 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA0_REQ_ID1);
11166 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA2_REQ_ID1);
11167 		}
11168 		mtx_unlock(&sc->reg_lock);
11169 		if (rc != 0)
11170 			break;
11171 
11172 		lookup_type = G_DATALKPTYPE(data2);
11173 		port_num = G_DATAPORTNUM(data2);
11174 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11175 			/* Inner header VNI */
11176 			vniy = (((data2 & F_DATAVIDH2) |
11177 			    G_DATAVIDH1(data2)) << 16) | G_VIDL(val);
11178 			dip_hit = data2 & F_DATADIPHIT;
11179 			vlan_vld = 0;
11180 		} else {
11181 			vniy = 0;
11182 			dip_hit = 0;
11183 			vlan_vld = data2 & F_DATAVIDH2;
11184 			ivlan = G_VIDL(val);
11185 		}
11186 
11187 		ctl |= V_CTLXYBITSEL(1);
11188 		mtx_lock(&sc->reg_lock);
11189 		if (hw_off_limits(sc))
11190 			rc = ENXIO;
11191 		else {
11192 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
11193 			val = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA1_REQ_ID1);
11194 			tcamx = G_DMACH(val) << 32;
11195 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA0_REQ_ID1);
11196 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA2_REQ_ID1);
11197 		}
11198 		mtx_unlock(&sc->reg_lock);
11199 		if (rc != 0)
11200 			break;
11201 
11202 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11203 			/* Inner header VNI mask */
11204 			vnix = (((data2 & F_DATAVIDH2) |
11205 			    G_DATAVIDH1(data2)) << 16) | G_VIDL(val);
11206 		} else
11207 			vnix = 0;
11208 
11209 		if (tcamx & tcamy)
11210 			continue;
11211 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
11212 
11213 		mtx_lock(&sc->reg_lock);
11214 		if (hw_off_limits(sc))
11215 			rc = ENXIO;
11216 		else {
11217 			if (chip_rev(sc) == 0) {
11218 				cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
11219 				cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
11220 			} else {
11221 				t4_write_reg(sc, A_MPS_CLS_SRAM_H,
11222 				    V_SRAMWRN(0) | V_SRAMINDEX(i));
11223 				cls_lo = t4_read_reg(sc, A_MPS_CLS_SRAM_L);
11224 				cls_hi = t4_read_reg(sc, A_MPS_CLS_SRAM_H);
11225 			}
11226 		}
11227 		mtx_unlock(&sc->reg_lock);
11228 		if (rc != 0)
11229 			break;
11230 
11231 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11232 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11233 			    "%012jx %06x %06x    -    -   %3c"
11234 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
11235 			    addr[1], addr[2], addr[3], addr[4], addr[5],
11236 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
11237 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11238 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11239 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11240 		} else {
11241 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11242 			    "%012jx    -       -   ", i, addr[0], addr[1],
11243 			    addr[2], addr[3], addr[4], addr[5],
11244 			    (uintmax_t)mask);
11245 
11246 			if (vlan_vld)
11247 				sbuf_printf(sb, "%4u   Y     ", ivlan);
11248 			else
11249 				sbuf_printf(sb, "  -    N     ");
11250 
11251 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
11252 			    lookup_type ? 'I' : 'O', port_num,
11253 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11254 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11255 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11256 		}
11257 
11258 		if (cls_lo & F_T6_REPLICATE) {
11259 			struct fw_ldst_cmd ldst_cmd;
11260 
11261 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
11262 			ldst_cmd.op_to_addrspace =
11263 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
11264 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
11265 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
11266 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
11267 			ldst_cmd.u.mps.rplc.fid_idx =
11268 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
11269 				V_FW_LDST_CMD_IDX(i));
11270 
11271 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
11272 			    "t6mps");
11273 			if (rc)
11274 				break;
11275 			if (hw_off_limits(sc))
11276 				rc = ENXIO;
11277 			else
11278 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
11279 				    sizeof(ldst_cmd), &ldst_cmd);
11280 			end_synchronized_op(sc, 0);
11281 			if (rc != 0)
11282 				break;
11283 			else {
11284 				sbuf_printf(sb, " %08x %08x %08x %08x"
11285 				    " %08x %08x %08x %08x",
11286 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
11287 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
11288 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
11289 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
11290 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
11291 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
11292 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
11293 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
11294 			}
11295 		} else
11296 			sbuf_printf(sb, "%72s", "");
11297 
11298 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
11299 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
11300 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
11301 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
11302 	}
11303 
11304 	if (rc)
11305 		(void) sbuf_finish(sb);
11306 	else
11307 		rc = sbuf_finish(sb);
11308 	sbuf_delete(sb);
11309 
11310 	return (rc);
11311 }
11312 
11313 static int
11314 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
11315 {
11316 	struct adapter *sc = arg1;
11317 	struct sbuf *sb;
11318 	int rc;
11319 	uint16_t mtus[NMTUS];
11320 
11321 	rc = 0;
11322 	mtx_lock(&sc->reg_lock);
11323 	if (hw_off_limits(sc))
11324 		rc = ENXIO;
11325 	else
11326 		t4_read_mtu_tbl(sc, mtus, NULL);
11327 	mtx_unlock(&sc->reg_lock);
11328 	if (rc != 0)
11329 		return (rc);
11330 
11331 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11332 	if (sb == NULL)
11333 		return (ENOMEM);
11334 
11335 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
11336 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
11337 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
11338 	    mtus[14], mtus[15]);
11339 
11340 	rc = sbuf_finish(sb);
11341 	sbuf_delete(sb);
11342 
11343 	return (rc);
11344 }
11345 
11346 static int
11347 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
11348 {
11349 	struct adapter *sc = arg1;
11350 	struct sbuf *sb;
11351 	int rc, i;
11352 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
11353 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
11354 	uint32_t stats[T7_PM_RX_CACHE_NSTATS];
11355 	static const char *tx_stats[MAX_PM_NSTATS] = {
11356 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
11357 		"Tx FIFO wait", NULL, "Tx latency"
11358 	};
11359 	static const char *rx_stats[MAX_PM_NSTATS] = {
11360 		"Read:", "Write bypass:", "Write mem:", "Flush:",
11361 		"Rx FIFO wait", NULL, "Rx latency"
11362 	};
11363 
11364 	rc = 0;
11365 	mtx_lock(&sc->reg_lock);
11366 	if (hw_off_limits(sc))
11367 		rc = ENXIO;
11368 	else {
11369 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
11370 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
11371 		if (chip_id(sc) >= CHELSIO_T7)
11372 			t4_pmrx_cache_get_stats(sc, stats);
11373 	}
11374 	mtx_unlock(&sc->reg_lock);
11375 	if (rc != 0)
11376 		return (rc);
11377 
11378 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11379 	if (sb == NULL)
11380 		return (ENOMEM);
11381 
11382 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
11383 	for (i = 0; i < 4; i++) {
11384 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
11385 		    tx_cyc[i]);
11386 	}
11387 
11388 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
11389 	for (i = 0; i < 4; i++) {
11390 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
11391 		    rx_cyc[i]);
11392 	}
11393 
11394 	if (chip_id(sc) > CHELSIO_T5) {
11395 		sbuf_printf(sb,
11396 		    "\n              Total wait      Total occupancy");
11397 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
11398 		    tx_cyc[i]);
11399 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
11400 		    rx_cyc[i]);
11401 
11402 		i += 2;
11403 		MPASS(i < nitems(tx_stats));
11404 
11405 		sbuf_printf(sb,
11406 		    "\n                   Reads           Total wait");
11407 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
11408 		    tx_cyc[i]);
11409 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
11410 		    rx_cyc[i]);
11411 	}
11412 
11413 	if (chip_id(sc) >= CHELSIO_T7) {
11414 		i = 0;
11415 		sbuf_printf(sb, "\n\nPM RX Cache Stats\n");
11416 		sbuf_printf(sb, "%-40s    %u\n", "ReqWrite", stats[i++]);
11417 		sbuf_printf(sb, "%-40s    %u\n", "ReqReadInv", stats[i++]);
11418 		sbuf_printf(sb, "%-40s    %u\n", "ReqReadNoInv", stats[i++]);
11419 		sbuf_printf(sb, "%-40s    %u\n", "Write Split Request",
11420 			   stats[i++]);
11421 		sbuf_printf(sb, "%-40s    %u\n",
11422 			   "Normal Read Split (Read Invalidate)", stats[i++]);
11423 		sbuf_printf(sb, "%-40s    %u\n",
11424 			   "Feedback Read Split (Read NoInvalidate)",
11425 			   stats[i++]);
11426 		sbuf_printf(sb, "%-40s    %u\n", "Write Hit", stats[i++]);
11427 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Hit",
11428 			   stats[i++]);
11429 		sbuf_printf(sb, "%-40s    %u\n", "Feedback Read Hit",
11430 			   stats[i++]);
11431 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Hit Full Avail",
11432 			   stats[i++]);
11433 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Hit Full UnAvail",
11434 			   stats[i++]);
11435 		sbuf_printf(sb, "%-40s    %u\n",
11436 			   "Normal Read Hit Partial Avail",
11437 			   stats[i++]);
11438 		sbuf_printf(sb, "%-40s    %u\n", "FB Read Hit Full Avail",
11439 			   stats[i++]);
11440 		sbuf_printf(sb, "%-40s    %u\n", "FB Read Hit Full UnAvail",
11441 			   stats[i++]);
11442 		sbuf_printf(sb, "%-40s    %u\n", "FB Read Hit Partial Avail",
11443 			   stats[i++]);
11444 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Full Free",
11445 			   stats[i++]);
11446 		sbuf_printf(sb, "%-40s    %u\n",
11447 			   "Normal Read Part-avail Mul-Regions",
11448 			   stats[i++]);
11449 		sbuf_printf(sb, "%-40s    %u\n",
11450 			   "FB Read Part-avail Mul-Regions",
11451 			   stats[i++]);
11452 		sbuf_printf(sb, "%-40s    %u\n", "Write Miss FL Used",
11453 			   stats[i++]);
11454 		sbuf_printf(sb, "%-40s    %u\n", "Write Miss LRU Used",
11455 			   stats[i++]);
11456 		sbuf_printf(sb, "%-40s    %u\n",
11457 			   "Write Miss LRU-Multiple Evict", stats[i++]);
11458 		sbuf_printf(sb, "%-40s    %u\n",
11459 			   "Write Hit Increasing Islands", stats[i++]);
11460 		sbuf_printf(sb, "%-40s    %u\n",
11461 			   "Normal Read Island Read split", stats[i++]);
11462 		sbuf_printf(sb, "%-40s    %u\n", "Write Overflow Eviction",
11463 			   stats[i++]);
11464 		sbuf_printf(sb, "%-40s    %u", "Read Overflow Eviction",
11465 			   stats[i++]);
11466 	}
11467 
11468 	rc = sbuf_finish(sb);
11469 	sbuf_delete(sb);
11470 
11471 	return (rc);
11472 }
11473 
11474 static int
11475 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
11476 {
11477 	struct adapter *sc = arg1;
11478 	struct sbuf *sb;
11479 	int rc;
11480 	struct tp_rdma_stats stats;
11481 
11482 	rc = 0;
11483 	mtx_lock(&sc->reg_lock);
11484 	if (hw_off_limits(sc))
11485 		rc = ENXIO;
11486 	else
11487 		t4_tp_get_rdma_stats(sc, &stats, 0);
11488 	mtx_unlock(&sc->reg_lock);
11489 	if (rc != 0)
11490 		return (rc);
11491 
11492 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11493 	if (sb == NULL)
11494 		return (ENOMEM);
11495 
11496 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
11497 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
11498 
11499 	rc = sbuf_finish(sb);
11500 	sbuf_delete(sb);
11501 
11502 	return (rc);
11503 }
11504 
11505 static int
11506 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
11507 {
11508 	struct adapter *sc = arg1;
11509 	struct sbuf *sb;
11510 	int rc;
11511 	struct tp_tcp_stats v4, v6;
11512 
11513 	rc = 0;
11514 	mtx_lock(&sc->reg_lock);
11515 	if (hw_off_limits(sc))
11516 		rc = ENXIO;
11517 	else
11518 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
11519 	mtx_unlock(&sc->reg_lock);
11520 	if (rc != 0)
11521 		return (rc);
11522 
11523 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11524 	if (sb == NULL)
11525 		return (ENOMEM);
11526 
11527 	sbuf_printf(sb,
11528 	    "                                IP                 IPv6\n");
11529 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
11530 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
11531 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
11532 	    v4.tcp_in_segs, v6.tcp_in_segs);
11533 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
11534 	    v4.tcp_out_segs, v6.tcp_out_segs);
11535 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
11536 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
11537 
11538 	rc = sbuf_finish(sb);
11539 	sbuf_delete(sb);
11540 
11541 	return (rc);
11542 }
11543 
11544 static int
11545 sysctl_tids(SYSCTL_HANDLER_ARGS)
11546 {
11547 	struct adapter *sc = arg1;
11548 	struct sbuf *sb;
11549 	int rc;
11550 	uint32_t x, y;
11551 	struct tid_info *t = &sc->tids;
11552 
11553 	rc = 0;
11554 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11555 	if (sb == NULL)
11556 		return (ENOMEM);
11557 
11558 	if (t->natids) {
11559 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
11560 		    t->atids_in_use);
11561 	}
11562 
11563 	if (t->nhpftids) {
11564 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
11565 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
11566 	}
11567 
11568 	if (t->ntids) {
11569 		bool hashen = false;
11570 
11571 		mtx_lock(&sc->reg_lock);
11572 		if (hw_off_limits(sc))
11573 			rc = ENXIO;
11574 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
11575 			hashen = true;
11576 			if (chip_id(sc) <= CHELSIO_T5) {
11577 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
11578 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
11579 			} else {
11580 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
11581 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
11582 			}
11583 		}
11584 		mtx_unlock(&sc->reg_lock);
11585 		if (rc != 0)
11586 			goto done;
11587 
11588 		sbuf_printf(sb, "TID range: ");
11589 		if (hashen) {
11590 			if (x)
11591 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
11592 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
11593 		} else {
11594 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
11595 			    t->ntids - 1);
11596 		}
11597 		sbuf_printf(sb, ", in use: %u\n",
11598 		    atomic_load_acq_int(&t->tids_in_use));
11599 	}
11600 
11601 	if (t->nstids) {
11602 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
11603 		    t->stid_base + t->nstids - 1, t->stids_in_use);
11604 	}
11605 
11606 	if (t->nftids) {
11607 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
11608 		    t->ftid_end, t->ftids_in_use);
11609 	}
11610 
11611 	if (t->netids) {
11612 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
11613 		    t->etid_base + t->netids - 1, t->etids_in_use);
11614 	}
11615 
11616 	mtx_lock(&sc->reg_lock);
11617 	if (hw_off_limits(sc))
11618 		rc = ENXIO;
11619 	else {
11620 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
11621 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
11622 	}
11623 	mtx_unlock(&sc->reg_lock);
11624 	if (rc != 0)
11625 		goto done;
11626 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
11627 done:
11628 	if (rc == 0)
11629 		rc = sbuf_finish(sb);
11630 	else
11631 		(void)sbuf_finish(sb);
11632 	sbuf_delete(sb);
11633 
11634 	return (rc);
11635 }
11636 
11637 static int
11638 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
11639 {
11640 	struct adapter *sc = arg1;
11641 	struct sbuf *sb;
11642 	int rc;
11643 	struct tp_err_stats stats;
11644 
11645 	rc = 0;
11646 	mtx_lock(&sc->reg_lock);
11647 	if (hw_off_limits(sc))
11648 		rc = ENXIO;
11649 	else
11650 		t4_tp_get_err_stats(sc, &stats, 0);
11651 	mtx_unlock(&sc->reg_lock);
11652 	if (rc != 0)
11653 		return (rc);
11654 
11655 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11656 	if (sb == NULL)
11657 		return (ENOMEM);
11658 
11659 	if (sc->chip_params->nchan > 2) {
11660 		sbuf_printf(sb, "                 channel 0  channel 1"
11661 		    "  channel 2  channel 3\n");
11662 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
11663 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
11664 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
11665 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
11666 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
11667 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
11668 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
11669 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
11670 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
11671 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
11672 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
11673 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
11674 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
11675 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
11676 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
11677 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
11678 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
11679 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
11680 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
11681 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
11682 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
11683 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
11684 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
11685 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
11686 	} else {
11687 		sbuf_printf(sb, "                 channel 0  channel 1\n");
11688 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
11689 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
11690 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
11691 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
11692 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
11693 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
11694 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
11695 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
11696 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
11697 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
11698 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
11699 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
11700 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
11701 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
11702 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
11703 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
11704 	}
11705 
11706 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
11707 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
11708 
11709 	rc = sbuf_finish(sb);
11710 	sbuf_delete(sb);
11711 
11712 	return (rc);
11713 }
11714 
11715 static int
11716 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
11717 {
11718 	struct adapter *sc = arg1;
11719 	struct sbuf *sb;
11720 	int rc;
11721 	struct tp_tnl_stats stats;
11722 
11723 	rc = 0;
11724 	mtx_lock(&sc->reg_lock);
11725 	if (hw_off_limits(sc))
11726 		rc = ENXIO;
11727 	else
11728 		t4_tp_get_tnl_stats(sc, &stats, 1);
11729 	mtx_unlock(&sc->reg_lock);
11730 	if (rc != 0)
11731 		return (rc);
11732 
11733 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11734 	if (sb == NULL)
11735 		return (ENOMEM);
11736 
11737 	if (sc->chip_params->nchan > 2) {
11738 		sbuf_printf(sb, "           channel 0  channel 1"
11739 		    "  channel 2  channel 3\n");
11740 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
11741 		    stats.out_pkt[0], stats.out_pkt[1],
11742 		    stats.out_pkt[2], stats.out_pkt[3]);
11743 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
11744 		    stats.in_pkt[0], stats.in_pkt[1],
11745 		    stats.in_pkt[2], stats.in_pkt[3]);
11746 	} else {
11747 		sbuf_printf(sb, "           channel 0  channel 1\n");
11748 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
11749 		    stats.out_pkt[0], stats.out_pkt[1]);
11750 		sbuf_printf(sb, "InPkts:   %10u %10u",
11751 		    stats.in_pkt[0], stats.in_pkt[1]);
11752 	}
11753 
11754 	rc = sbuf_finish(sb);
11755 	sbuf_delete(sb);
11756 
11757 	return (rc);
11758 }
11759 
11760 static int
11761 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
11762 {
11763 	struct adapter *sc = arg1;
11764 	struct tp_params *tpp = &sc->params.tp;
11765 	u_int mask;
11766 	int rc;
11767 
11768 	mask = tpp->la_mask >> 16;
11769 	rc = sysctl_handle_int(oidp, &mask, 0, req);
11770 	if (rc != 0 || req->newptr == NULL)
11771 		return (rc);
11772 	if (mask > 0xffff)
11773 		return (EINVAL);
11774 	mtx_lock(&sc->reg_lock);
11775 	if (hw_off_limits(sc))
11776 		rc = ENXIO;
11777 	else {
11778 		tpp->la_mask = mask << 16;
11779 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
11780 		    tpp->la_mask);
11781 	}
11782 	mtx_unlock(&sc->reg_lock);
11783 
11784 	return (rc);
11785 }
11786 
11787 struct field_desc {
11788 	const char *name;
11789 	u_int start;
11790 	u_int width;
11791 };
11792 
11793 static void
11794 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
11795 {
11796 	char buf[32];
11797 	int line_size = 0;
11798 
11799 	while (f->name) {
11800 		uint64_t mask = (1ULL << f->width) - 1;
11801 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
11802 		    ((uintmax_t)v >> f->start) & mask);
11803 
11804 		if (line_size + len >= 79) {
11805 			line_size = 8;
11806 			sbuf_printf(sb, "\n        ");
11807 		}
11808 		sbuf_printf(sb, "%s ", buf);
11809 		line_size += len + 1;
11810 		f++;
11811 	}
11812 	sbuf_printf(sb, "\n");
11813 }
11814 
11815 static const struct field_desc tp_la0[] = {
11816 	{ "RcfOpCodeOut", 60, 4 },
11817 	{ "State", 56, 4 },
11818 	{ "WcfState", 52, 4 },
11819 	{ "RcfOpcSrcOut", 50, 2 },
11820 	{ "CRxError", 49, 1 },
11821 	{ "ERxError", 48, 1 },
11822 	{ "SanityFailed", 47, 1 },
11823 	{ "SpuriousMsg", 46, 1 },
11824 	{ "FlushInputMsg", 45, 1 },
11825 	{ "FlushInputCpl", 44, 1 },
11826 	{ "RssUpBit", 43, 1 },
11827 	{ "RssFilterHit", 42, 1 },
11828 	{ "Tid", 32, 10 },
11829 	{ "InitTcb", 31, 1 },
11830 	{ "LineNumber", 24, 7 },
11831 	{ "Emsg", 23, 1 },
11832 	{ "EdataOut", 22, 1 },
11833 	{ "Cmsg", 21, 1 },
11834 	{ "CdataOut", 20, 1 },
11835 	{ "EreadPdu", 19, 1 },
11836 	{ "CreadPdu", 18, 1 },
11837 	{ "TunnelPkt", 17, 1 },
11838 	{ "RcfPeerFin", 16, 1 },
11839 	{ "RcfReasonOut", 12, 4 },
11840 	{ "TxCchannel", 10, 2 },
11841 	{ "RcfTxChannel", 8, 2 },
11842 	{ "RxEchannel", 6, 2 },
11843 	{ "RcfRxChannel", 5, 1 },
11844 	{ "RcfDataOutSrdy", 4, 1 },
11845 	{ "RxDvld", 3, 1 },
11846 	{ "RxOoDvld", 2, 1 },
11847 	{ "RxCongestion", 1, 1 },
11848 	{ "TxCongestion", 0, 1 },
11849 	{ NULL }
11850 };
11851 
11852 static const struct field_desc tp_la1[] = {
11853 	{ "CplCmdIn", 56, 8 },
11854 	{ "CplCmdOut", 48, 8 },
11855 	{ "ESynOut", 47, 1 },
11856 	{ "EAckOut", 46, 1 },
11857 	{ "EFinOut", 45, 1 },
11858 	{ "ERstOut", 44, 1 },
11859 	{ "SynIn", 43, 1 },
11860 	{ "AckIn", 42, 1 },
11861 	{ "FinIn", 41, 1 },
11862 	{ "RstIn", 40, 1 },
11863 	{ "DataIn", 39, 1 },
11864 	{ "DataInVld", 38, 1 },
11865 	{ "PadIn", 37, 1 },
11866 	{ "RxBufEmpty", 36, 1 },
11867 	{ "RxDdp", 35, 1 },
11868 	{ "RxFbCongestion", 34, 1 },
11869 	{ "TxFbCongestion", 33, 1 },
11870 	{ "TxPktSumSrdy", 32, 1 },
11871 	{ "RcfUlpType", 28, 4 },
11872 	{ "Eread", 27, 1 },
11873 	{ "Ebypass", 26, 1 },
11874 	{ "Esave", 25, 1 },
11875 	{ "Static0", 24, 1 },
11876 	{ "Cread", 23, 1 },
11877 	{ "Cbypass", 22, 1 },
11878 	{ "Csave", 21, 1 },
11879 	{ "CPktOut", 20, 1 },
11880 	{ "RxPagePoolFull", 18, 2 },
11881 	{ "RxLpbkPkt", 17, 1 },
11882 	{ "TxLpbkPkt", 16, 1 },
11883 	{ "RxVfValid", 15, 1 },
11884 	{ "SynLearned", 14, 1 },
11885 	{ "SetDelEntry", 13, 1 },
11886 	{ "SetInvEntry", 12, 1 },
11887 	{ "CpcmdDvld", 11, 1 },
11888 	{ "CpcmdSave", 10, 1 },
11889 	{ "RxPstructsFull", 8, 2 },
11890 	{ "EpcmdDvld", 7, 1 },
11891 	{ "EpcmdFlush", 6, 1 },
11892 	{ "EpcmdTrimPrefix", 5, 1 },
11893 	{ "EpcmdTrimPostfix", 4, 1 },
11894 	{ "ERssIp4Pkt", 3, 1 },
11895 	{ "ERssIp6Pkt", 2, 1 },
11896 	{ "ERssTcpUdpPkt", 1, 1 },
11897 	{ "ERssFceFipPkt", 0, 1 },
11898 	{ NULL }
11899 };
11900 
11901 static const struct field_desc tp_la2[] = {
11902 	{ "CplCmdIn", 56, 8 },
11903 	{ "MpsVfVld", 55, 1 },
11904 	{ "MpsPf", 52, 3 },
11905 	{ "MpsVf", 44, 8 },
11906 	{ "SynIn", 43, 1 },
11907 	{ "AckIn", 42, 1 },
11908 	{ "FinIn", 41, 1 },
11909 	{ "RstIn", 40, 1 },
11910 	{ "DataIn", 39, 1 },
11911 	{ "DataInVld", 38, 1 },
11912 	{ "PadIn", 37, 1 },
11913 	{ "RxBufEmpty", 36, 1 },
11914 	{ "RxDdp", 35, 1 },
11915 	{ "RxFbCongestion", 34, 1 },
11916 	{ "TxFbCongestion", 33, 1 },
11917 	{ "TxPktSumSrdy", 32, 1 },
11918 	{ "RcfUlpType", 28, 4 },
11919 	{ "Eread", 27, 1 },
11920 	{ "Ebypass", 26, 1 },
11921 	{ "Esave", 25, 1 },
11922 	{ "Static0", 24, 1 },
11923 	{ "Cread", 23, 1 },
11924 	{ "Cbypass", 22, 1 },
11925 	{ "Csave", 21, 1 },
11926 	{ "CPktOut", 20, 1 },
11927 	{ "RxPagePoolFull", 18, 2 },
11928 	{ "RxLpbkPkt", 17, 1 },
11929 	{ "TxLpbkPkt", 16, 1 },
11930 	{ "RxVfValid", 15, 1 },
11931 	{ "SynLearned", 14, 1 },
11932 	{ "SetDelEntry", 13, 1 },
11933 	{ "SetInvEntry", 12, 1 },
11934 	{ "CpcmdDvld", 11, 1 },
11935 	{ "CpcmdSave", 10, 1 },
11936 	{ "RxPstructsFull", 8, 2 },
11937 	{ "EpcmdDvld", 7, 1 },
11938 	{ "EpcmdFlush", 6, 1 },
11939 	{ "EpcmdTrimPrefix", 5, 1 },
11940 	{ "EpcmdTrimPostfix", 4, 1 },
11941 	{ "ERssIp4Pkt", 3, 1 },
11942 	{ "ERssIp6Pkt", 2, 1 },
11943 	{ "ERssTcpUdpPkt", 1, 1 },
11944 	{ "ERssFceFipPkt", 0, 1 },
11945 	{ NULL }
11946 };
11947 
11948 static void
11949 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
11950 {
11951 
11952 	field_desc_show(sb, *p, tp_la0);
11953 }
11954 
11955 static void
11956 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
11957 {
11958 
11959 	if (idx)
11960 		sbuf_printf(sb, "\n");
11961 	field_desc_show(sb, p[0], tp_la0);
11962 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
11963 		field_desc_show(sb, p[1], tp_la0);
11964 }
11965 
11966 static void
11967 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
11968 {
11969 
11970 	if (idx)
11971 		sbuf_printf(sb, "\n");
11972 	field_desc_show(sb, p[0], tp_la0);
11973 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
11974 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
11975 }
11976 
11977 static int
11978 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
11979 {
11980 	struct adapter *sc = arg1;
11981 	struct sbuf *sb;
11982 	uint64_t *buf, *p;
11983 	int rc;
11984 	u_int i, inc;
11985 	void (*show_func)(struct sbuf *, uint64_t *, int);
11986 
11987 	rc = 0;
11988 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11989 	if (sb == NULL)
11990 		return (ENOMEM);
11991 
11992 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
11993 
11994 	mtx_lock(&sc->reg_lock);
11995 	if (hw_off_limits(sc))
11996 		rc = ENXIO;
11997 	else {
11998 		t4_tp_read_la(sc, buf, NULL);
11999 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
12000 		case 2:
12001 			inc = 2;
12002 			show_func = tp_la_show2;
12003 			break;
12004 		case 3:
12005 			inc = 2;
12006 			show_func = tp_la_show3;
12007 			break;
12008 		default:
12009 			inc = 1;
12010 			show_func = tp_la_show;
12011 		}
12012 	}
12013 	mtx_unlock(&sc->reg_lock);
12014 	if (rc != 0)
12015 		goto done;
12016 
12017 	p = buf;
12018 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
12019 		(*show_func)(sb, p, i);
12020 	rc = sbuf_finish(sb);
12021 done:
12022 	sbuf_delete(sb);
12023 	free(buf, M_CXGBE);
12024 	return (rc);
12025 }
12026 
12027 static int
12028 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
12029 {
12030 	struct adapter *sc = arg1;
12031 	struct sbuf *sb;
12032 	int rc;
12033 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
12034 
12035 	rc = 0;
12036 	mtx_lock(&sc->reg_lock);
12037 	if (hw_off_limits(sc))
12038 		rc = ENXIO;
12039 	else
12040 		t4_get_chan_txrate(sc, nrate, orate);
12041 	mtx_unlock(&sc->reg_lock);
12042 	if (rc != 0)
12043 		return (rc);
12044 
12045 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
12046 	if (sb == NULL)
12047 		return (ENOMEM);
12048 
12049 	if (sc->chip_params->nchan > 2) {
12050 		sbuf_printf(sb, "              channel 0   channel 1"
12051 		    "   channel 2   channel 3\n");
12052 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
12053 		    nrate[0], nrate[1], nrate[2], nrate[3]);
12054 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
12055 		    orate[0], orate[1], orate[2], orate[3]);
12056 	} else {
12057 		sbuf_printf(sb, "              channel 0   channel 1\n");
12058 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
12059 		    nrate[0], nrate[1]);
12060 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
12061 		    orate[0], orate[1]);
12062 	}
12063 
12064 	rc = sbuf_finish(sb);
12065 	sbuf_delete(sb);
12066 
12067 	return (rc);
12068 }
12069 
12070 static int
12071 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
12072 {
12073 	struct adapter *sc = arg1;
12074 	struct sbuf *sb;
12075 	uint32_t *buf, *p;
12076 	int rc, i;
12077 
12078 	rc = 0;
12079 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
12080 	if (sb == NULL)
12081 		return (ENOMEM);
12082 
12083 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
12084 	    M_ZERO | M_WAITOK);
12085 
12086 	mtx_lock(&sc->reg_lock);
12087 	if (hw_off_limits(sc))
12088 		rc = ENXIO;
12089 	else
12090 		t4_ulprx_read_la(sc, buf);
12091 	mtx_unlock(&sc->reg_lock);
12092 	if (rc != 0)
12093 		goto done;
12094 
12095 	p = buf;
12096 	sbuf_printf(sb, "      Pcmd        Type   Message"
12097 	    "                Data");
12098 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
12099 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
12100 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
12101 	}
12102 	rc = sbuf_finish(sb);
12103 done:
12104 	sbuf_delete(sb);
12105 	free(buf, M_CXGBE);
12106 	return (rc);
12107 }
12108 
12109 static int
12110 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
12111 {
12112 	struct adapter *sc = arg1;
12113 	struct sbuf *sb;
12114 	int rc;
12115 	uint32_t cfg, s1, s2;
12116 
12117 	MPASS(chip_id(sc) >= CHELSIO_T5);
12118 
12119 	rc = 0;
12120 	mtx_lock(&sc->reg_lock);
12121 	if (hw_off_limits(sc))
12122 		rc = ENXIO;
12123 	else {
12124 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
12125 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
12126 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
12127 	}
12128 	mtx_unlock(&sc->reg_lock);
12129 	if (rc != 0)
12130 		return (rc);
12131 
12132 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
12133 	if (sb == NULL)
12134 		return (ENOMEM);
12135 
12136 	if (G_STATSOURCE_T5(cfg) == 7) {
12137 		int mode;
12138 
12139 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
12140 		if (mode == 0)
12141 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
12142 		else if (mode == 1)
12143 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
12144 		else
12145 			sbuf_printf(sb, "unknown mode %d", mode);
12146 	}
12147 	rc = sbuf_finish(sb);
12148 	sbuf_delete(sb);
12149 
12150 	return (rc);
12151 }
12152 
12153 static int
12154 sysctl_cpus(SYSCTL_HANDLER_ARGS)
12155 {
12156 	struct adapter *sc = arg1;
12157 	enum cpu_sets op = arg2;
12158 	cpuset_t cpuset;
12159 	struct sbuf *sb;
12160 	int i, rc;
12161 
12162 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
12163 
12164 	CPU_ZERO(&cpuset);
12165 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
12166 	if (rc != 0)
12167 		return (rc);
12168 
12169 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
12170 	if (sb == NULL)
12171 		return (ENOMEM);
12172 
12173 	CPU_FOREACH(i)
12174 		sbuf_printf(sb, "%d ", i);
12175 	rc = sbuf_finish(sb);
12176 	sbuf_delete(sb);
12177 
12178 	return (rc);
12179 }
12180 
12181 static int
12182 sysctl_reset(SYSCTL_HANDLER_ARGS)
12183 {
12184 	struct adapter *sc = arg1;
12185 	u_int val;
12186 	int rc;
12187 
12188 	val = atomic_load_int(&sc->num_resets);
12189 	rc = sysctl_handle_int(oidp, &val, 0, req);
12190 	if (rc != 0 || req->newptr == NULL)
12191 		return (rc);
12192 
12193 	if (val == 0) {
12194 		/* Zero out the counter that tracks reset. */
12195 		atomic_store_int(&sc->num_resets, 0);
12196 		return (0);
12197 	}
12198 
12199 	if (val != 1)
12200 		return (EINVAL);	/* 0 or 1 are the only legal values */
12201 
12202 	if (hw_off_limits(sc))		/* harmless race */
12203 		return (EALREADY);
12204 
12205 	taskqueue_enqueue(reset_tq, &sc->reset_task);
12206 	return (0);
12207 }
12208 
12209 #ifdef TCP_OFFLOAD
12210 static int
12211 sysctl_tls(SYSCTL_HANDLER_ARGS)
12212 {
12213 	struct adapter *sc = arg1;
12214 	int i, j, v, rc;
12215 	struct vi_info *vi;
12216 
12217 	v = sc->tt.tls;
12218 	rc = sysctl_handle_int(oidp, &v, 0, req);
12219 	if (rc != 0 || req->newptr == NULL)
12220 		return (rc);
12221 
12222 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
12223 		return (ENOTSUP);
12224 
12225 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
12226 	if (rc)
12227 		return (rc);
12228 	if (hw_off_limits(sc))
12229 		rc = ENXIO;
12230 	else {
12231 		sc->tt.tls = !!v;
12232 		for_each_port(sc, i) {
12233 			for_each_vi(sc->port[i], j, vi) {
12234 				if (vi->flags & VI_INIT_DONE)
12235 					t4_update_fl_bufsize(vi->ifp);
12236 			}
12237 		}
12238 	}
12239 	end_synchronized_op(sc, 0);
12240 
12241 	return (rc);
12242 
12243 }
12244 
12245 static void
12246 unit_conv(char *buf, size_t len, u_int val, u_int factor)
12247 {
12248 	u_int rem = val % factor;
12249 
12250 	if (rem == 0)
12251 		snprintf(buf, len, "%u", val / factor);
12252 	else {
12253 		while (rem % 10 == 0)
12254 			rem /= 10;
12255 		snprintf(buf, len, "%u.%u", val / factor, rem);
12256 	}
12257 }
12258 
12259 static int
12260 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
12261 {
12262 	struct adapter *sc = arg1;
12263 	char buf[16];
12264 	u_int res, re;
12265 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
12266 
12267 	mtx_lock(&sc->reg_lock);
12268 	if (hw_off_limits(sc))
12269 		res = (u_int)-1;
12270 	else
12271 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
12272 	mtx_unlock(&sc->reg_lock);
12273 	if (res == (u_int)-1)
12274 		return (ENXIO);
12275 
12276 	switch (arg2) {
12277 	case 0:
12278 		/* timer_tick */
12279 		re = G_TIMERRESOLUTION(res);
12280 		break;
12281 	case 1:
12282 		/* TCP timestamp tick */
12283 		re = G_TIMESTAMPRESOLUTION(res);
12284 		break;
12285 	case 2:
12286 		/* DACK tick */
12287 		re = G_DELAYEDACKRESOLUTION(res);
12288 		break;
12289 	default:
12290 		return (EDOOFUS);
12291 	}
12292 
12293 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
12294 
12295 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
12296 }
12297 
12298 static int
12299 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
12300 {
12301 	struct adapter *sc = arg1;
12302 	int rc;
12303 	u_int dack_tmr, dack_re, v;
12304 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
12305 
12306 	mtx_lock(&sc->reg_lock);
12307 	if (hw_off_limits(sc))
12308 		rc = ENXIO;
12309 	else {
12310 		rc = 0;
12311 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
12312 		    A_TP_TIMER_RESOLUTION));
12313 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
12314 	}
12315 	mtx_unlock(&sc->reg_lock);
12316 	if (rc != 0)
12317 		return (rc);
12318 
12319 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
12320 
12321 	return (sysctl_handle_int(oidp, &v, 0, req));
12322 }
12323 
12324 static int
12325 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
12326 {
12327 	struct adapter *sc = arg1;
12328 	int rc, reg = arg2;
12329 	u_int tre;
12330 	u_long tp_tick_us, v;
12331 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
12332 
12333 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
12334 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
12335 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
12336 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
12337 
12338 	mtx_lock(&sc->reg_lock);
12339 	if (hw_off_limits(sc))
12340 		rc = ENXIO;
12341 	else {
12342 		rc = 0;
12343 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
12344 		tp_tick_us = (cclk_ps << tre) / 1000000;
12345 		if (reg == A_TP_INIT_SRTT)
12346 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
12347 		else
12348 			v = tp_tick_us * t4_read_reg(sc, reg);
12349 	}
12350 	mtx_unlock(&sc->reg_lock);
12351 	if (rc != 0)
12352 		return (rc);
12353 	else
12354 		return (sysctl_handle_long(oidp, &v, 0, req));
12355 }
12356 
12357 /*
12358  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
12359  * passed to this function.
12360  */
12361 static int
12362 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
12363 {
12364 	struct adapter *sc = arg1;
12365 	int rc, idx = arg2;
12366 	u_int v;
12367 
12368 	MPASS(idx >= 0 && idx <= 24);
12369 
12370 	mtx_lock(&sc->reg_lock);
12371 	if (hw_off_limits(sc))
12372 		rc = ENXIO;
12373 	else {
12374 		rc = 0;
12375 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
12376 	}
12377 	mtx_unlock(&sc->reg_lock);
12378 	if (rc != 0)
12379 		return (rc);
12380 	else
12381 		return (sysctl_handle_int(oidp, &v, 0, req));
12382 }
12383 
12384 static int
12385 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
12386 {
12387 	struct adapter *sc = arg1;
12388 	int rc, idx = arg2;
12389 	u_int shift, v, r;
12390 
12391 	MPASS(idx >= 0 && idx < 16);
12392 
12393 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
12394 	shift = (idx & 3) << 3;
12395 	mtx_lock(&sc->reg_lock);
12396 	if (hw_off_limits(sc))
12397 		rc = ENXIO;
12398 	else {
12399 		rc = 0;
12400 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
12401 	}
12402 	mtx_unlock(&sc->reg_lock);
12403 	if (rc != 0)
12404 		return (rc);
12405 	else
12406 		return (sysctl_handle_int(oidp, &v, 0, req));
12407 }
12408 
12409 static int
12410 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
12411 {
12412 	struct vi_info *vi = arg1;
12413 	struct adapter *sc = vi->adapter;
12414 	int idx, rc, i;
12415 	struct sge_ofld_rxq *ofld_rxq;
12416 	uint8_t v;
12417 
12418 	idx = vi->ofld_tmr_idx;
12419 
12420 	rc = sysctl_handle_int(oidp, &idx, 0, req);
12421 	if (rc != 0 || req->newptr == NULL)
12422 		return (rc);
12423 
12424 	if (idx < 0 || idx >= SGE_NTIMERS)
12425 		return (EINVAL);
12426 
12427 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
12428 	    "t4otmr");
12429 	if (rc)
12430 		return (rc);
12431 
12432 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
12433 	for_each_ofld_rxq(vi, i, ofld_rxq) {
12434 #ifdef atomic_store_rel_8
12435 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
12436 #else
12437 		ofld_rxq->iq.intr_params = v;
12438 #endif
12439 	}
12440 	vi->ofld_tmr_idx = idx;
12441 
12442 	end_synchronized_op(sc, LOCK_HELD);
12443 	return (0);
12444 }
12445 
12446 static int
12447 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
12448 {
12449 	struct vi_info *vi = arg1;
12450 	struct adapter *sc = vi->adapter;
12451 	int idx, rc;
12452 
12453 	idx = vi->ofld_pktc_idx;
12454 
12455 	rc = sysctl_handle_int(oidp, &idx, 0, req);
12456 	if (rc != 0 || req->newptr == NULL)
12457 		return (rc);
12458 
12459 	if (idx < -1 || idx >= SGE_NCOUNTERS)
12460 		return (EINVAL);
12461 
12462 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
12463 	    "t4opktc");
12464 	if (rc)
12465 		return (rc);
12466 
12467 	if (vi->flags & VI_INIT_DONE)
12468 		rc = EBUSY; /* cannot be changed once the queues are created */
12469 	else
12470 		vi->ofld_pktc_idx = idx;
12471 
12472 	end_synchronized_op(sc, LOCK_HELD);
12473 	return (rc);
12474 }
12475 #endif
12476 
12477 static int
12478 get_sge_context(struct adapter *sc, int mem_id, uint32_t cid, int len,
12479     uint32_t *data)
12480 {
12481 	int rc;
12482 
12483 	if (len < sc->chip_params->sge_ctxt_size)
12484 		return (ENOBUFS);
12485 	if (cid > M_CTXTQID)
12486 		return (EINVAL);
12487 	if (mem_id != CTXT_EGRESS && mem_id != CTXT_INGRESS &&
12488 	    mem_id != CTXT_FLM && mem_id != CTXT_CNM)
12489 		return (EINVAL);
12490 
12491 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
12492 	if (rc)
12493 		return (rc);
12494 
12495 	if (hw_off_limits(sc)) {
12496 		rc = ENXIO;
12497 		goto done;
12498 	}
12499 
12500 	if (sc->flags & FW_OK) {
12501 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cid, mem_id, data);
12502 		if (rc == 0)
12503 			goto done;
12504 	}
12505 
12506 	/*
12507 	 * Read via firmware failed or wasn't even attempted.  Read directly via
12508 	 * the backdoor.
12509 	 */
12510 	rc = -t4_sge_ctxt_rd_bd(sc, cid, mem_id, data);
12511 done:
12512 	end_synchronized_op(sc, 0);
12513 	return (rc);
12514 }
12515 
12516 static int
12517 load_fw(struct adapter *sc, struct t4_data *fw)
12518 {
12519 	int rc;
12520 	uint8_t *fw_data;
12521 
12522 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
12523 	if (rc)
12524 		return (rc);
12525 
12526 	if (hw_off_limits(sc)) {
12527 		rc = ENXIO;
12528 		goto done;
12529 	}
12530 
12531 	/*
12532 	 * The firmware, with the sole exception of the memory parity error
12533 	 * handler, runs from memory and not flash.  It is almost always safe to
12534 	 * install a new firmware on a running system.  Just set bit 1 in
12535 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
12536 	 */
12537 	if (sc->flags & FULL_INIT_DONE &&
12538 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
12539 		rc = EBUSY;
12540 		goto done;
12541 	}
12542 
12543 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
12544 
12545 	rc = copyin(fw->data, fw_data, fw->len);
12546 	if (rc == 0)
12547 		rc = -t4_load_fw(sc, fw_data, fw->len);
12548 
12549 	free(fw_data, M_CXGBE);
12550 done:
12551 	end_synchronized_op(sc, 0);
12552 	return (rc);
12553 }
12554 
12555 static int
12556 load_cfg(struct adapter *sc, struct t4_data *cfg)
12557 {
12558 	int rc;
12559 	uint8_t *cfg_data = NULL;
12560 
12561 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
12562 	if (rc)
12563 		return (rc);
12564 
12565 	if (hw_off_limits(sc)) {
12566 		rc = ENXIO;
12567 		goto done;
12568 	}
12569 
12570 	if (cfg->len == 0) {
12571 		/* clear */
12572 		rc = -t4_load_cfg(sc, NULL, 0);
12573 		goto done;
12574 	}
12575 
12576 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
12577 
12578 	rc = copyin(cfg->data, cfg_data, cfg->len);
12579 	if (rc == 0)
12580 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
12581 
12582 	free(cfg_data, M_CXGBE);
12583 done:
12584 	end_synchronized_op(sc, 0);
12585 	return (rc);
12586 }
12587 
12588 static int
12589 load_boot(struct adapter *sc, struct t4_bootrom *br)
12590 {
12591 	int rc;
12592 	uint8_t *br_data = NULL;
12593 	u_int offset;
12594 
12595 	if (br->len > 1024 * 1024)
12596 		return (EFBIG);
12597 
12598 	if (br->pf_offset == 0) {
12599 		/* pfidx */
12600 		if (br->pfidx_addr > 7)
12601 			return (EINVAL);
12602 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
12603 		    A_PCIE_PF_EXPROM_OFST)));
12604 	} else if (br->pf_offset == 1) {
12605 		/* offset */
12606 		offset = G_OFFSET(br->pfidx_addr);
12607 	} else {
12608 		return (EINVAL);
12609 	}
12610 
12611 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
12612 	if (rc)
12613 		return (rc);
12614 
12615 	if (hw_off_limits(sc)) {
12616 		rc = ENXIO;
12617 		goto done;
12618 	}
12619 
12620 	if (br->len == 0) {
12621 		/* clear */
12622 		rc = -t4_load_boot(sc, NULL, offset, 0);
12623 		goto done;
12624 	}
12625 
12626 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
12627 
12628 	rc = copyin(br->data, br_data, br->len);
12629 	if (rc == 0)
12630 		rc = -t4_load_boot(sc, br_data, offset, br->len);
12631 
12632 	free(br_data, M_CXGBE);
12633 done:
12634 	end_synchronized_op(sc, 0);
12635 	return (rc);
12636 }
12637 
12638 static int
12639 load_bootcfg(struct adapter *sc, struct t4_data *bc)
12640 {
12641 	int rc;
12642 	uint8_t *bc_data = NULL;
12643 
12644 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
12645 	if (rc)
12646 		return (rc);
12647 
12648 	if (hw_off_limits(sc)) {
12649 		rc = ENXIO;
12650 		goto done;
12651 	}
12652 
12653 	if (bc->len == 0) {
12654 		/* clear */
12655 		rc = -t4_load_bootcfg(sc, NULL, 0);
12656 		goto done;
12657 	}
12658 
12659 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
12660 
12661 	rc = copyin(bc->data, bc_data, bc->len);
12662 	if (rc == 0)
12663 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
12664 
12665 	free(bc_data, M_CXGBE);
12666 done:
12667 	end_synchronized_op(sc, 0);
12668 	return (rc);
12669 }
12670 
12671 static int
12672 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
12673 {
12674 	int rc;
12675 	struct cudbg_init *cudbg;
12676 	void *handle, *buf;
12677 
12678 	/* buf is large, don't block if no memory is available */
12679 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
12680 	if (buf == NULL)
12681 		return (ENOMEM);
12682 
12683 	handle = cudbg_alloc_handle();
12684 	if (handle == NULL) {
12685 		rc = ENOMEM;
12686 		goto done;
12687 	}
12688 
12689 	cudbg = cudbg_get_init(handle);
12690 	cudbg->adap = sc;
12691 	cudbg->print = (cudbg_print_cb)printf;
12692 
12693 #ifndef notyet
12694 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
12695 	    __func__, dump->wr_flash, dump->len, dump->data);
12696 #endif
12697 
12698 	if (dump->wr_flash)
12699 		cudbg->use_flash = 1;
12700 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
12701 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
12702 
12703 	rc = cudbg_collect(handle, buf, &dump->len);
12704 	if (rc != 0)
12705 		goto done;
12706 
12707 	rc = copyout(buf, dump->data, dump->len);
12708 done:
12709 	cudbg_free_handle(handle);
12710 	free(buf, M_CXGBE);
12711 	return (rc);
12712 }
12713 
12714 static void
12715 free_offload_policy(struct t4_offload_policy *op)
12716 {
12717 	struct offload_rule *r;
12718 	int i;
12719 
12720 	if (op == NULL)
12721 		return;
12722 
12723 	r = &op->rule[0];
12724 	for (i = 0; i < op->nrules; i++, r++) {
12725 		free(r->bpf_prog.bf_insns, M_CXGBE);
12726 	}
12727 	free(op->rule, M_CXGBE);
12728 	free(op, M_CXGBE);
12729 }
12730 
12731 static int
12732 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
12733 {
12734 	int i, rc, len;
12735 	struct t4_offload_policy *op, *old;
12736 	struct bpf_program *bf;
12737 	const struct offload_settings *s;
12738 	struct offload_rule *r;
12739 	void *u;
12740 
12741 	if (!is_offload(sc))
12742 		return (ENODEV);
12743 
12744 	if (uop->nrules == 0) {
12745 		/* Delete installed policies. */
12746 		op = NULL;
12747 		goto set_policy;
12748 	} else if (uop->nrules > 256) { /* arbitrary */
12749 		return (E2BIG);
12750 	}
12751 
12752 	/* Copy userspace offload policy to kernel */
12753 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
12754 	op->nrules = uop->nrules;
12755 	len = op->nrules * sizeof(struct offload_rule);
12756 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
12757 	rc = copyin(uop->rule, op->rule, len);
12758 	if (rc) {
12759 		free(op->rule, M_CXGBE);
12760 		free(op, M_CXGBE);
12761 		return (rc);
12762 	}
12763 
12764 	r = &op->rule[0];
12765 	for (i = 0; i < op->nrules; i++, r++) {
12766 
12767 		/* Validate open_type */
12768 		if (r->open_type != OPEN_TYPE_LISTEN &&
12769 		    r->open_type != OPEN_TYPE_ACTIVE &&
12770 		    r->open_type != OPEN_TYPE_PASSIVE &&
12771 		    r->open_type != OPEN_TYPE_DONTCARE) {
12772 error:
12773 			/*
12774 			 * Rules 0 to i have malloc'd filters that need to be
12775 			 * freed.  Rules i+1 to nrules have userspace pointers
12776 			 * and should be left alone.
12777 			 */
12778 			op->nrules = i;
12779 			free_offload_policy(op);
12780 			return (rc);
12781 		}
12782 
12783 		/* Validate settings */
12784 		s = &r->settings;
12785 		if ((s->offload != 0 && s->offload != 1) ||
12786 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
12787 		    s->sched_class < -1 ||
12788 		    s->sched_class >= sc->params.nsched_cls) {
12789 			rc = EINVAL;
12790 			goto error;
12791 		}
12792 
12793 		bf = &r->bpf_prog;
12794 		u = bf->bf_insns;	/* userspace ptr */
12795 		bf->bf_insns = NULL;
12796 		if (bf->bf_len == 0) {
12797 			/* legal, matches everything */
12798 			continue;
12799 		}
12800 		len = bf->bf_len * sizeof(*bf->bf_insns);
12801 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
12802 		rc = copyin(u, bf->bf_insns, len);
12803 		if (rc != 0)
12804 			goto error;
12805 
12806 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
12807 			rc = EINVAL;
12808 			goto error;
12809 		}
12810 	}
12811 set_policy:
12812 	rw_wlock(&sc->policy_lock);
12813 	old = sc->policy;
12814 	sc->policy = op;
12815 	rw_wunlock(&sc->policy_lock);
12816 	free_offload_policy(old);
12817 
12818 	return (0);
12819 }
12820 
12821 #define MAX_READ_BUF_SIZE (128 * 1024)
12822 static int
12823 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
12824 {
12825 	uint32_t addr, remaining, n;
12826 	uint32_t *buf;
12827 	int rc;
12828 	uint8_t *dst;
12829 
12830 	mtx_lock(&sc->reg_lock);
12831 	if (hw_off_limits(sc))
12832 		rc = ENXIO;
12833 	else
12834 		rc = validate_mem_range(sc, mr->addr, mr->len);
12835 	mtx_unlock(&sc->reg_lock);
12836 	if (rc != 0)
12837 		return (rc);
12838 
12839 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
12840 	addr = mr->addr;
12841 	remaining = mr->len;
12842 	dst = (void *)mr->data;
12843 
12844 	while (remaining) {
12845 		n = min(remaining, MAX_READ_BUF_SIZE);
12846 		mtx_lock(&sc->reg_lock);
12847 		if (hw_off_limits(sc))
12848 			rc = ENXIO;
12849 		else
12850 			read_via_memwin(sc, 2, addr, buf, n);
12851 		mtx_unlock(&sc->reg_lock);
12852 		if (rc != 0)
12853 			break;
12854 
12855 		rc = copyout(buf, dst, n);
12856 		if (rc != 0)
12857 			break;
12858 
12859 		dst += n;
12860 		remaining -= n;
12861 		addr += n;
12862 	}
12863 
12864 	free(buf, M_CXGBE);
12865 	return (rc);
12866 }
12867 #undef MAX_READ_BUF_SIZE
12868 
12869 static int
12870 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
12871 {
12872 	int rc;
12873 
12874 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
12875 		return (EINVAL);
12876 
12877 	if (i2cd->len > sizeof(i2cd->data))
12878 		return (EFBIG);
12879 
12880 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
12881 	if (rc)
12882 		return (rc);
12883 	if (hw_off_limits(sc))
12884 		rc = ENXIO;
12885 	else
12886 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
12887 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
12888 	end_synchronized_op(sc, 0);
12889 
12890 	return (rc);
12891 }
12892 
12893 static int
12894 clear_stats(struct adapter *sc, u_int port_id)
12895 {
12896 	int i, v, chan_map;
12897 	struct port_info *pi;
12898 	struct vi_info *vi;
12899 	struct sge_rxq *rxq;
12900 	struct sge_txq *txq;
12901 	struct sge_wrq *wrq;
12902 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12903 	struct sge_ofld_txq *ofld_txq;
12904 #endif
12905 #ifdef TCP_OFFLOAD
12906 	struct sge_ofld_rxq *ofld_rxq;
12907 #endif
12908 
12909 	if (port_id >= sc->params.nports)
12910 		return (EINVAL);
12911 	pi = sc->port[port_id];
12912 	if (pi == NULL)
12913 		return (EIO);
12914 
12915 	mtx_lock(&sc->reg_lock);
12916 	if (!hw_off_limits(sc)) {
12917 		/* MAC stats */
12918 		t4_clr_port_stats(sc, pi->hw_port);
12919 		if (is_t6(sc)) {
12920 			if (pi->fcs_reg != -1)
12921 				pi->fcs_base = t4_read_reg64(sc,
12922 				    t4_port_reg(sc, pi->tx_chan, pi->fcs_reg));
12923 			else
12924 				pi->stats.rx_fcs_err = 0;
12925 		}
12926 		for_each_vi(pi, v, vi) {
12927 			if (vi->flags & VI_INIT_DONE)
12928 				t4_clr_vi_stats(sc, vi->vin);
12929 		}
12930 		chan_map = pi->rx_e_chan_map;
12931 		v = 0;	/* reuse */
12932 		while (chan_map) {
12933 			i = ffs(chan_map) - 1;
12934 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
12935 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
12936 			chan_map &= ~(1 << i);
12937 		}
12938 	}
12939 	mtx_unlock(&sc->reg_lock);
12940 	pi->tx_parse_error = 0;
12941 	pi->tnl_cong_drops = 0;
12942 
12943 	/*
12944 	 * Since this command accepts a port, clear stats for
12945 	 * all VIs on this port.
12946 	 */
12947 	for_each_vi(pi, v, vi) {
12948 		if (vi->flags & VI_INIT_DONE) {
12949 
12950 			for_each_rxq(vi, i, rxq) {
12951 #if defined(INET) || defined(INET6)
12952 				rxq->lro.lro_queued = 0;
12953 				rxq->lro.lro_flushed = 0;
12954 #endif
12955 				rxq->rxcsum = 0;
12956 				rxq->vlan_extraction = 0;
12957 				rxq->vxlan_rxcsum = 0;
12958 
12959 				rxq->fl.cl_allocated = 0;
12960 				rxq->fl.cl_recycled = 0;
12961 				rxq->fl.cl_fast_recycled = 0;
12962 			}
12963 
12964 			for_each_txq(vi, i, txq) {
12965 				txq->txcsum = 0;
12966 				txq->tso_wrs = 0;
12967 				txq->vlan_insertion = 0;
12968 				txq->imm_wrs = 0;
12969 				txq->sgl_wrs = 0;
12970 				txq->txpkt_wrs = 0;
12971 				txq->txpkts0_wrs = 0;
12972 				txq->txpkts1_wrs = 0;
12973 				txq->txpkts0_pkts = 0;
12974 				txq->txpkts1_pkts = 0;
12975 				txq->txpkts_flush = 0;
12976 				txq->raw_wrs = 0;
12977 				txq->vxlan_tso_wrs = 0;
12978 				txq->vxlan_txcsum = 0;
12979 				txq->kern_tls_records = 0;
12980 				txq->kern_tls_short = 0;
12981 				txq->kern_tls_partial = 0;
12982 				txq->kern_tls_full = 0;
12983 				txq->kern_tls_octets = 0;
12984 				txq->kern_tls_waste = 0;
12985 				txq->kern_tls_header = 0;
12986 				txq->kern_tls_fin_short = 0;
12987 				txq->kern_tls_cbc = 0;
12988 				txq->kern_tls_gcm = 0;
12989 				if (is_t6(sc)) {
12990 					txq->kern_tls_options = 0;
12991 					txq->kern_tls_fin = 0;
12992 				} else {
12993 					txq->kern_tls_ghash_received = 0;
12994 					txq->kern_tls_ghash_requested = 0;
12995 					txq->kern_tls_lso = 0;
12996 					txq->kern_tls_partial_ghash = 0;
12997 					txq->kern_tls_splitmode = 0;
12998 					txq->kern_tls_trailer = 0;
12999 				}
13000 				mp_ring_reset_stats(txq->r);
13001 			}
13002 
13003 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
13004 			for_each_ofld_txq(vi, i, ofld_txq) {
13005 				ofld_txq->wrq.tx_wrs_direct = 0;
13006 				ofld_txq->wrq.tx_wrs_copied = 0;
13007 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
13008 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
13009 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
13010 				counter_u64_zero(ofld_txq->tx_nvme_pdus);
13011 				counter_u64_zero(ofld_txq->tx_nvme_octets);
13012 				counter_u64_zero(ofld_txq->tx_nvme_iso_wrs);
13013 				counter_u64_zero(ofld_txq->tx_aio_jobs);
13014 				counter_u64_zero(ofld_txq->tx_aio_octets);
13015 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
13016 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
13017 			}
13018 #endif
13019 #ifdef TCP_OFFLOAD
13020 			for_each_ofld_rxq(vi, i, ofld_rxq) {
13021 				ofld_rxq->fl.cl_allocated = 0;
13022 				ofld_rxq->fl.cl_recycled = 0;
13023 				ofld_rxq->fl.cl_fast_recycled = 0;
13024 				counter_u64_zero(
13025 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
13026 				counter_u64_zero(
13027 				    ofld_rxq->rx_iscsi_ddp_setup_error);
13028 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
13029 				ofld_rxq->rx_iscsi_ddp_octets = 0;
13030 				ofld_rxq->rx_iscsi_fl_pdus = 0;
13031 				ofld_rxq->rx_iscsi_fl_octets = 0;
13032 				counter_u64_zero(
13033 				    ofld_rxq->rx_nvme_ddp_setup_ok);
13034 				counter_u64_zero(
13035 				    ofld_rxq->rx_nvme_ddp_setup_no_stag);
13036 				counter_u64_zero(
13037 				    ofld_rxq->rx_nvme_ddp_setup_error);
13038 				counter_u64_zero(ofld_rxq->rx_nvme_ddp_pdus);
13039 				counter_u64_zero(ofld_rxq->rx_nvme_ddp_octets);
13040 				counter_u64_zero(ofld_rxq->rx_nvme_fl_pdus);
13041 				counter_u64_zero(ofld_rxq->rx_nvme_fl_octets);
13042 				counter_u64_zero(
13043 				    ofld_rxq->rx_nvme_invalid_headers);
13044 				counter_u64_zero(
13045 				    ofld_rxq->rx_nvme_header_digest_errors);
13046 				counter_u64_zero(
13047 				    ofld_rxq->rx_nvme_data_digest_errors);
13048 				ofld_rxq->rx_aio_ddp_jobs = 0;
13049 				ofld_rxq->rx_aio_ddp_octets = 0;
13050 				ofld_rxq->rx_toe_tls_records = 0;
13051 				ofld_rxq->rx_toe_tls_octets = 0;
13052 				ofld_rxq->rx_toe_ddp_octets = 0;
13053 				counter_u64_zero(ofld_rxq->ddp_buffer_alloc);
13054 				counter_u64_zero(ofld_rxq->ddp_buffer_reuse);
13055 				counter_u64_zero(ofld_rxq->ddp_buffer_free);
13056 			}
13057 #endif
13058 
13059 			if (IS_MAIN_VI(vi)) {
13060 				wrq = &sc->sge.ctrlq[pi->port_id];
13061 				wrq->tx_wrs_direct = 0;
13062 				wrq->tx_wrs_copied = 0;
13063 			}
13064 		}
13065 	}
13066 
13067 	return (0);
13068 }
13069 
13070 static int
13071 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
13072 {
13073 #ifdef INET6
13074 	struct in6_addr in6;
13075 
13076 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
13077 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
13078 		return (0);
13079 	else
13080 		return (EIO);
13081 #else
13082 	return (ENOTSUP);
13083 #endif
13084 }
13085 
13086 static int
13087 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
13088 {
13089 #ifdef INET6
13090 	struct in6_addr in6;
13091 
13092 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
13093 	return (t4_release_clip_addr(sc, &in6));
13094 #else
13095 	return (ENOTSUP);
13096 #endif
13097 }
13098 
13099 int
13100 t4_os_find_pci_capability(struct adapter *sc, int cap)
13101 {
13102 	int i;
13103 
13104 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
13105 }
13106 
13107 void
13108 t4_os_portmod_changed(struct port_info *pi)
13109 {
13110 	struct adapter *sc = pi->adapter;
13111 	struct vi_info *vi;
13112 	if_t ifp;
13113 	static const char *mod_str[] = {
13114 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM",
13115 		"LR_SIMPLEX", "DR"
13116 	};
13117 
13118 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
13119 	    ("%s: port_type %u", __func__, pi->port_type));
13120 
13121 	vi = &pi->vi[0];
13122 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
13123 		PORT_LOCK(pi);
13124 		build_medialist(pi);
13125 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
13126 			fixup_link_config(pi);
13127 			apply_link_config(pi);
13128 		}
13129 		PORT_UNLOCK(pi);
13130 		end_synchronized_op(sc, LOCK_HELD);
13131 	}
13132 
13133 	ifp = vi->ifp;
13134 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
13135 		if_printf(ifp, "transceiver unplugged.\n");
13136 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
13137 		if_printf(ifp, "unknown transceiver inserted.\n");
13138 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
13139 		if_printf(ifp, "unsupported transceiver inserted.\n");
13140 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
13141 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
13142 		    port_top_speed(pi), mod_str[pi->mod_type]);
13143 	} else {
13144 		if_printf(ifp, "transceiver (type %d) inserted.\n",
13145 		    pi->mod_type);
13146 	}
13147 }
13148 
13149 void
13150 t4_os_link_changed(struct port_info *pi)
13151 {
13152 	struct vi_info *vi;
13153 	if_t ifp;
13154 	struct link_config *lc = &pi->link_cfg;
13155 	struct adapter *sc = pi->adapter;
13156 	int v;
13157 
13158 	PORT_LOCK_ASSERT_OWNED(pi);
13159 
13160 	if (is_t6(sc)) {
13161 		if (lc->link_ok) {
13162 			if (lc->speed > 25000 ||
13163 			    (lc->speed == 25000 && lc->fec == FEC_RS))
13164 				pi->fcs_reg = A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS;
13165 			else
13166 				pi->fcs_reg = A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS;
13167 			pi->fcs_base = t4_read_reg64(sc,
13168 			    t4_port_reg(sc, pi->tx_chan, pi->fcs_reg));
13169 			pi->stats.rx_fcs_err = 0;
13170 		} else {
13171 			pi->fcs_reg = -1;
13172 		}
13173 	} else {
13174 		MPASS(pi->fcs_reg != -1);
13175 		MPASS(pi->fcs_base == 0);
13176 	}
13177 
13178 	for_each_vi(pi, v, vi) {
13179 		ifp = vi->ifp;
13180 		if (ifp == NULL || IS_DETACHING(vi))
13181 			continue;
13182 
13183 		if (lc->link_ok) {
13184 			if_setbaudrate(ifp, IF_Mbps(lc->speed));
13185 			if_link_state_change(ifp, LINK_STATE_UP);
13186 		} else {
13187 			if_link_state_change(ifp, LINK_STATE_DOWN);
13188 		}
13189 	}
13190 }
13191 
13192 void
13193 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
13194 {
13195 	struct adapter *sc;
13196 
13197 	sx_slock(&t4_list_lock);
13198 	SLIST_FOREACH(sc, &t4_list, link) {
13199 		/*
13200 		 * func should not make any assumptions about what state sc is
13201 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
13202 		 */
13203 		func(sc, arg);
13204 	}
13205 	sx_sunlock(&t4_list_lock);
13206 }
13207 
13208 static int
13209 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
13210     struct thread *td)
13211 {
13212 	int rc;
13213 	struct adapter *sc = dev->si_drv1;
13214 
13215 	rc = priv_check(td, PRIV_DRIVER);
13216 	if (rc != 0)
13217 		return (rc);
13218 
13219 	switch (cmd) {
13220 	case CHELSIO_T4_GETREG: {
13221 		struct t4_reg *edata = (struct t4_reg *)data;
13222 
13223 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
13224 			return (EFAULT);
13225 
13226 		mtx_lock(&sc->reg_lock);
13227 		if (hw_off_limits(sc))
13228 			rc = ENXIO;
13229 		else if (edata->size == 4)
13230 			edata->val = t4_read_reg(sc, edata->addr);
13231 		else if (edata->size == 8)
13232 			edata->val = t4_read_reg64(sc, edata->addr);
13233 		else
13234 			rc = EINVAL;
13235 		mtx_unlock(&sc->reg_lock);
13236 
13237 		break;
13238 	}
13239 	case CHELSIO_T4_SETREG: {
13240 		struct t4_reg *edata = (struct t4_reg *)data;
13241 
13242 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
13243 			return (EFAULT);
13244 
13245 		mtx_lock(&sc->reg_lock);
13246 		if (hw_off_limits(sc))
13247 			rc = ENXIO;
13248 		else if (edata->size == 4) {
13249 			if (edata->val & 0xffffffff00000000)
13250 				rc = EINVAL;
13251 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
13252 		} else if (edata->size == 8)
13253 			t4_write_reg64(sc, edata->addr, edata->val);
13254 		else
13255 			rc = EINVAL;
13256 		mtx_unlock(&sc->reg_lock);
13257 
13258 		break;
13259 	}
13260 	case CHELSIO_T4_REGDUMP: {
13261 		struct t4_regdump *regs = (struct t4_regdump *)data;
13262 		int reglen = t4_get_regs_len(sc);
13263 		uint8_t *buf;
13264 
13265 		if (regs->len < reglen) {
13266 			regs->len = reglen; /* hint to the caller */
13267 			return (ENOBUFS);
13268 		}
13269 
13270 		regs->len = reglen;
13271 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
13272 		mtx_lock(&sc->reg_lock);
13273 		if (hw_off_limits(sc))
13274 			rc = ENXIO;
13275 		else
13276 			get_regs(sc, regs, buf);
13277 		mtx_unlock(&sc->reg_lock);
13278 		if (rc == 0)
13279 			rc = copyout(buf, regs->data, reglen);
13280 		free(buf, M_CXGBE);
13281 		break;
13282 	}
13283 	case CHELSIO_T4_GET_FILTER_MODE:
13284 		rc = get_filter_mode(sc, (uint32_t *)data);
13285 		break;
13286 	case CHELSIO_T4_SET_FILTER_MODE:
13287 		rc = set_filter_mode(sc, *(uint32_t *)data);
13288 		break;
13289 	case CHELSIO_T4_SET_FILTER_MASK:
13290 		rc = set_filter_mask(sc, *(uint32_t *)data);
13291 		break;
13292 	case CHELSIO_T4_GET_FILTER:
13293 		rc = get_filter(sc, (struct t4_filter *)data);
13294 		break;
13295 	case CHELSIO_T4_SET_FILTER:
13296 		rc = set_filter(sc, (struct t4_filter *)data);
13297 		break;
13298 	case CHELSIO_T4_DEL_FILTER:
13299 		rc = del_filter(sc, (struct t4_filter *)data);
13300 		break;
13301 	case CHELSIO_T4_GET_SGE_CONTEXT: {
13302 		struct t4_sge_context *ctxt = (struct t4_sge_context *)data;
13303 
13304 		rc = get_sge_context(sc, ctxt->mem_id, ctxt->cid,
13305 		    sizeof(ctxt->data), &ctxt->data[0]);
13306 		break;
13307 	}
13308 	case CHELSIO_T4_LOAD_FW:
13309 		rc = load_fw(sc, (struct t4_data *)data);
13310 		break;
13311 	case CHELSIO_T4_GET_MEM:
13312 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
13313 		break;
13314 	case CHELSIO_T4_GET_I2C:
13315 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
13316 		break;
13317 	case CHELSIO_T4_CLEAR_STATS:
13318 		rc = clear_stats(sc, *(uint32_t *)data);
13319 		break;
13320 	case CHELSIO_T4_SCHED_CLASS:
13321 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
13322 		break;
13323 	case CHELSIO_T4_SCHED_QUEUE:
13324 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
13325 		break;
13326 	case CHELSIO_T4_GET_TRACER:
13327 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
13328 		break;
13329 	case CHELSIO_T4_SET_TRACER:
13330 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
13331 		break;
13332 	case CHELSIO_T4_LOAD_CFG:
13333 		rc = load_cfg(sc, (struct t4_data *)data);
13334 		break;
13335 	case CHELSIO_T4_LOAD_BOOT:
13336 		rc = load_boot(sc, (struct t4_bootrom *)data);
13337 		break;
13338 	case CHELSIO_T4_LOAD_BOOTCFG:
13339 		rc = load_bootcfg(sc, (struct t4_data *)data);
13340 		break;
13341 	case CHELSIO_T4_CUDBG_DUMP:
13342 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
13343 		break;
13344 	case CHELSIO_T4_SET_OFLD_POLICY:
13345 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
13346 		break;
13347 	case CHELSIO_T4_HOLD_CLIP_ADDR:
13348 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
13349 		break;
13350 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
13351 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
13352 		break;
13353 	case CHELSIO_T4_GET_SGE_CTXT: {
13354 		struct t4_sge_ctxt *ctxt = (struct t4_sge_ctxt *)data;
13355 
13356 		rc = get_sge_context(sc, ctxt->mem_id, ctxt->cid,
13357 		    sizeof(ctxt->data), &ctxt->data[0]);
13358 		break;
13359 	}
13360 	default:
13361 		rc = ENOTTY;
13362 	}
13363 
13364 	return (rc);
13365 }
13366 
13367 #ifdef TCP_OFFLOAD
13368 int
13369 toe_capability(struct vi_info *vi, bool enable)
13370 {
13371 	int rc;
13372 	struct port_info *pi = vi->pi;
13373 	struct adapter *sc = pi->adapter;
13374 
13375 	ASSERT_SYNCHRONIZED_OP(sc);
13376 
13377 	if (!is_offload(sc))
13378 		return (ENODEV);
13379 	if (!hw_all_ok(sc))
13380 		return (ENXIO);
13381 
13382 	if (enable) {
13383 #ifdef KERN_TLS
13384 		if (sc->flags & KERN_TLS_ON && is_t6(sc)) {
13385 			int i, j, n;
13386 			struct port_info *p;
13387 			struct vi_info *v;
13388 
13389 			/*
13390 			 * Reconfigure hardware for TOE if TXTLS is not enabled
13391 			 * on any ifnet.
13392 			 */
13393 			n = 0;
13394 			for_each_port(sc, i) {
13395 				p = sc->port[i];
13396 				for_each_vi(p, j, v) {
13397 					if (if_getcapenable(v->ifp) & IFCAP_TXTLS) {
13398 						CH_WARN(sc,
13399 						    "%s has NIC TLS enabled.\n",
13400 						    device_get_nameunit(v->dev));
13401 						n++;
13402 					}
13403 				}
13404 			}
13405 			if (n > 0) {
13406 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
13407 				    "associated with this adapter before "
13408 				    "trying to enable TOE.\n");
13409 				return (EAGAIN);
13410 			}
13411 			rc = t6_config_kern_tls(sc, false);
13412 			if (rc)
13413 				return (rc);
13414 		}
13415 #endif
13416 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) != 0) {
13417 			/* TOE is already enabled. */
13418 			return (0);
13419 		}
13420 
13421 		/*
13422 		 * We need the port's queues around so that we're able to send
13423 		 * and receive CPLs to/from the TOE even if the ifnet for this
13424 		 * port has never been UP'd administratively.
13425 		 */
13426 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
13427 			return (rc);
13428 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
13429 		    ((rc = vi_init(&pi->vi[0])) != 0))
13430 			return (rc);
13431 
13432 		if (isset(&sc->offload_map, pi->port_id)) {
13433 			/* TOE is enabled on another VI of this port. */
13434 			MPASS(pi->uld_vis > 0);
13435 			pi->uld_vis++;
13436 			return (0);
13437 		}
13438 
13439 		if (!uld_active(sc, ULD_TOM)) {
13440 			rc = t4_activate_uld(sc, ULD_TOM);
13441 			if (rc == EAGAIN) {
13442 				log(LOG_WARNING,
13443 				    "You must kldload t4_tom.ko before trying "
13444 				    "to enable TOE on a cxgbe interface.\n");
13445 			}
13446 			if (rc != 0)
13447 				return (rc);
13448 			KASSERT(sc->tom_softc != NULL,
13449 			    ("%s: TOM activated but softc NULL", __func__));
13450 			KASSERT(uld_active(sc, ULD_TOM),
13451 			    ("%s: TOM activated but flag not set", __func__));
13452 		}
13453 
13454 		/*
13455 		 * Activate iWARP, iSCSI, and NVMe too, if the modules
13456 		 * are loaded.
13457 		 */
13458 		if (!uld_active(sc, ULD_IWARP))
13459 			(void) t4_activate_uld(sc, ULD_IWARP);
13460 		if (!uld_active(sc, ULD_ISCSI))
13461 			(void) t4_activate_uld(sc, ULD_ISCSI);
13462 		if (!uld_active(sc, ULD_NVME))
13463 			(void) t4_activate_uld(sc, ULD_NVME);
13464 
13465 		if (pi->uld_vis++ == 0)
13466 			setbit(&sc->offload_map, pi->port_id);
13467 	} else {
13468 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) == 0) {
13469 			/* TOE is already disabled. */
13470 			return (0);
13471 		}
13472 		MPASS(isset(&sc->offload_map, pi->port_id));
13473 		MPASS(pi->uld_vis > 0);
13474 		if (--pi->uld_vis == 0)
13475 			clrbit(&sc->offload_map, pi->port_id);
13476 	}
13477 
13478 	return (0);
13479 }
13480 
13481 /*
13482  * Add an upper layer driver to the global list.
13483  */
13484 int
13485 t4_register_uld(struct uld_info *ui, int id)
13486 {
13487 	int rc;
13488 
13489 	if (id < 0 || id > ULD_MAX)
13490 		return (EINVAL);
13491 	sx_xlock(&t4_uld_list_lock);
13492 	if (t4_uld_list[id] != NULL)
13493 		rc = EEXIST;
13494 	else {
13495 		t4_uld_list[id] = ui;
13496 		rc = 0;
13497 	}
13498 	sx_xunlock(&t4_uld_list_lock);
13499 	return (rc);
13500 }
13501 
13502 int
13503 t4_unregister_uld(struct uld_info *ui, int id)
13504 {
13505 
13506 	if (id < 0 || id > ULD_MAX)
13507 		return (EINVAL);
13508 	sx_xlock(&t4_uld_list_lock);
13509 	MPASS(t4_uld_list[id] == ui);
13510 	t4_uld_list[id] = NULL;
13511 	sx_xunlock(&t4_uld_list_lock);
13512 	return (0);
13513 }
13514 
13515 int
13516 t4_activate_uld(struct adapter *sc, int id)
13517 {
13518 	int rc;
13519 
13520 	ASSERT_SYNCHRONIZED_OP(sc);
13521 
13522 	if (id < 0 || id > ULD_MAX)
13523 		return (EINVAL);
13524 
13525 	/* Adapter needs to be initialized before any ULD can be activated. */
13526 	if (!(sc->flags & FULL_INIT_DONE)) {
13527 		rc = adapter_init(sc);
13528 		if (rc != 0)
13529 			return (rc);
13530 	}
13531 
13532 	sx_slock(&t4_uld_list_lock);
13533 	if (t4_uld_list[id] == NULL)
13534 		rc = EAGAIN;	/* load the KLD with this ULD and try again. */
13535 	else {
13536 		rc = t4_uld_list[id]->uld_activate(sc);
13537 		if (rc == 0)
13538 			setbit(&sc->active_ulds, id);
13539 	}
13540 	sx_sunlock(&t4_uld_list_lock);
13541 
13542 	return (rc);
13543 }
13544 
13545 int
13546 t4_deactivate_uld(struct adapter *sc, int id)
13547 {
13548 	int rc;
13549 
13550 	ASSERT_SYNCHRONIZED_OP(sc);
13551 
13552 	if (id < 0 || id > ULD_MAX)
13553 		return (EINVAL);
13554 
13555 	sx_slock(&t4_uld_list_lock);
13556 	if (t4_uld_list[id] == NULL)
13557 		rc = ENXIO;
13558 	else {
13559 		rc = t4_uld_list[id]->uld_deactivate(sc);
13560 		if (rc == 0)
13561 			clrbit(&sc->active_ulds, id);
13562 	}
13563 	sx_sunlock(&t4_uld_list_lock);
13564 
13565 	return (rc);
13566 }
13567 
13568 static int
13569 deactivate_all_uld(struct adapter *sc)
13570 {
13571 	int i, rc;
13572 
13573 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4detuld");
13574 	if (rc != 0)
13575 		return (ENXIO);
13576 	sx_slock(&t4_uld_list_lock);
13577 	for (i = 0; i <= ULD_MAX; i++) {
13578 		if (t4_uld_list[i] == NULL || !uld_active(sc, i))
13579 			continue;
13580 		rc = t4_uld_list[i]->uld_deactivate(sc);
13581 		if (rc != 0)
13582 			break;
13583 		clrbit(&sc->active_ulds, i);
13584 	}
13585 	sx_sunlock(&t4_uld_list_lock);
13586 	end_synchronized_op(sc, 0);
13587 
13588 	return (rc);
13589 }
13590 
13591 static void
13592 stop_all_uld(struct adapter *sc)
13593 {
13594 	int i;
13595 
13596 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4uldst") != 0)
13597 		return;
13598 	sx_slock(&t4_uld_list_lock);
13599 	for (i = 0; i <= ULD_MAX; i++) {
13600 		if (t4_uld_list[i] == NULL || !uld_active(sc, i) ||
13601 		    t4_uld_list[i]->uld_stop == NULL)
13602 			continue;
13603 		(void) t4_uld_list[i]->uld_stop(sc);
13604 	}
13605 	sx_sunlock(&t4_uld_list_lock);
13606 	end_synchronized_op(sc, 0);
13607 }
13608 
13609 static void
13610 restart_all_uld(struct adapter *sc)
13611 {
13612 	int i;
13613 
13614 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4uldre") != 0)
13615 		return;
13616 	sx_slock(&t4_uld_list_lock);
13617 	for (i = 0; i <= ULD_MAX; i++) {
13618 		if (t4_uld_list[i] == NULL || !uld_active(sc, i) ||
13619 		    t4_uld_list[i]->uld_restart == NULL)
13620 			continue;
13621 		(void) t4_uld_list[i]->uld_restart(sc);
13622 	}
13623 	sx_sunlock(&t4_uld_list_lock);
13624 	end_synchronized_op(sc, 0);
13625 }
13626 
13627 int
13628 uld_active(struct adapter *sc, int id)
13629 {
13630 
13631 	MPASS(id >= 0 && id <= ULD_MAX);
13632 
13633 	return (isset(&sc->active_ulds, id));
13634 }
13635 #endif
13636 
13637 #ifdef KERN_TLS
13638 static int
13639 ktls_capability(struct adapter *sc, bool enable)
13640 {
13641 	ASSERT_SYNCHRONIZED_OP(sc);
13642 
13643 	if (!is_ktls(sc))
13644 		return (ENODEV);
13645 	if (!is_t6(sc))
13646 		return (0);
13647 	if (!hw_all_ok(sc))
13648 		return (ENXIO);
13649 
13650 	if (enable) {
13651 		if (sc->flags & KERN_TLS_ON)
13652 			return (0);	/* already on */
13653 		if (sc->offload_map != 0) {
13654 			CH_WARN(sc,
13655 			    "Disable TOE on all interfaces associated with "
13656 			    "this adapter before trying to enable NIC TLS.\n");
13657 			return (EAGAIN);
13658 		}
13659 		return (t6_config_kern_tls(sc, true));
13660 	} else {
13661 		/*
13662 		 * Nothing to do for disable.  If TOE is enabled sometime later
13663 		 * then toe_capability will reconfigure the hardware.
13664 		 */
13665 		return (0);
13666 	}
13667 }
13668 #endif
13669 
13670 /*
13671  * t  = ptr to tunable.
13672  * nc = number of CPUs.
13673  * c  = compiled in default for that tunable.
13674  */
13675 static void
13676 calculate_nqueues(int *t, int nc, const int c)
13677 {
13678 	int nq;
13679 
13680 	if (*t > 0)
13681 		return;
13682 	nq = *t < 0 ? -*t : c;
13683 	*t = min(nc, nq);
13684 }
13685 
13686 /*
13687  * Come up with reasonable defaults for some of the tunables, provided they're
13688  * not set by the user (in which case we'll use the values as is).
13689  */
13690 static void
13691 tweak_tunables(void)
13692 {
13693 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
13694 
13695 	if (t4_ntxq < 1) {
13696 #ifdef RSS
13697 		t4_ntxq = rss_getnumbuckets();
13698 #else
13699 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
13700 #endif
13701 	}
13702 
13703 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
13704 
13705 	if (t4_nrxq < 1) {
13706 #ifdef RSS
13707 		t4_nrxq = rss_getnumbuckets();
13708 #else
13709 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
13710 #endif
13711 	}
13712 
13713 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
13714 
13715 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
13716 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
13717 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
13718 #endif
13719 #ifdef TCP_OFFLOAD
13720 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
13721 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
13722 #endif
13723 
13724 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
13725 	if (t4_toecaps_allowed == -1)
13726 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
13727 #else
13728 	if (t4_toecaps_allowed == -1)
13729 		t4_toecaps_allowed = 0;
13730 #endif
13731 
13732 #ifdef TCP_OFFLOAD
13733 	if (t4_rdmacaps_allowed == -1) {
13734 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
13735 		    FW_CAPS_CONFIG_RDMA_RDMAC;
13736 	}
13737 
13738 	if (t4_iscsicaps_allowed == -1) {
13739 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
13740 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
13741 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
13742 	}
13743 
13744 	if (t4_nvmecaps_allowed == -1)
13745 		t4_nvmecaps_allowed = FW_CAPS_CONFIG_NVME_TCP;
13746 
13747 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
13748 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
13749 
13750 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
13751 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
13752 #else
13753 	if (t4_rdmacaps_allowed == -1)
13754 		t4_rdmacaps_allowed = 0;
13755 
13756 	if (t4_iscsicaps_allowed == -1)
13757 		t4_iscsicaps_allowed = 0;
13758 
13759 	if (t4_nvmecaps_allowed == -1)
13760 		t4_nvmecaps_allowed = 0;
13761 #endif
13762 
13763 #ifdef DEV_NETMAP
13764 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
13765 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
13766 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
13767 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
13768 #endif
13769 
13770 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
13771 		t4_tmr_idx = TMR_IDX;
13772 
13773 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
13774 		t4_pktc_idx = PKTC_IDX;
13775 
13776 	if (t4_qsize_txq < 128)
13777 		t4_qsize_txq = 128;
13778 
13779 	if (t4_qsize_rxq < 128)
13780 		t4_qsize_rxq = 128;
13781 	while (t4_qsize_rxq & 7)
13782 		t4_qsize_rxq++;
13783 
13784 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
13785 
13786 	/*
13787 	 * Number of VIs to create per-port.  The first VI is the "main" regular
13788 	 * VI for the port.  The rest are additional virtual interfaces on the
13789 	 * same physical port.  Note that the main VI does not have native
13790 	 * netmap support but the extra VIs do.
13791 	 *
13792 	 * Limit the number of VIs per port to the number of available
13793 	 * MAC addresses per port.
13794 	 */
13795 	if (t4_num_vis < 1)
13796 		t4_num_vis = 1;
13797 	if (t4_num_vis > nitems(vi_mac_funcs)) {
13798 		t4_num_vis = nitems(vi_mac_funcs);
13799 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
13800 	}
13801 
13802 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
13803 		pcie_relaxed_ordering = 1;
13804 #if defined(__i386__) || defined(__amd64__)
13805 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
13806 			pcie_relaxed_ordering = 0;
13807 #endif
13808 	}
13809 }
13810 
13811 #ifdef DDB
13812 static void
13813 t4_dump_mem(struct adapter *sc, u_int addr, u_int len)
13814 {
13815 	uint32_t base, j, off, pf, reg, save, win_pos;
13816 
13817 	reg = chip_id(sc) > CHELSIO_T6 ?
13818 	    PCIE_MEM_ACCESS_T7_REG(A_PCIE_MEM_ACCESS_OFFSET0, 2) :
13819 	    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
13820 	save = t4_read_reg(sc, reg);
13821 	base = sc->memwin[2].mw_base;
13822 
13823 	if (is_t4(sc)) {
13824 		pf = 0;
13825 		win_pos = addr & ~0xf;	/* start must be 16B aligned */
13826 	} else {
13827 		pf = V_PFNUM(sc->pf);
13828 		win_pos = addr & ~0x7f;	/* start must be 128B aligned */
13829 	}
13830 	off = addr - win_pos;
13831 	if (chip_id(sc) > CHELSIO_T6)
13832 		win_pos >>= X_T7_MEMOFST_SHIFT;
13833 	t4_write_reg(sc, reg, win_pos | pf);
13834 	t4_read_reg(sc, reg);
13835 
13836 	while (len > 0 && !db_pager_quit) {
13837 		uint32_t buf[8];
13838 		for (j = 0; j < 8; j++, off += 4)
13839 			buf[j] = htonl(t4_read_reg(sc, base + off));
13840 
13841 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
13842 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
13843 		    buf[7]);
13844 		if (len <= sizeof(buf))
13845 			len = 0;
13846 		else
13847 			len -= sizeof(buf);
13848 	}
13849 
13850 	t4_write_reg(sc, reg, save);
13851 	t4_read_reg(sc, reg);
13852 }
13853 
13854 static void
13855 t4_dump_tcb(struct adapter *sc, int tid)
13856 {
13857 	uint32_t tcb_addr;
13858 
13859 	/* Dump TCB for the tid */
13860 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
13861 	tcb_addr += tid * TCB_SIZE;
13862 	t4_dump_mem(sc, tcb_addr, TCB_SIZE);
13863 }
13864 
13865 static void
13866 t4_dump_devlog(struct adapter *sc)
13867 {
13868 	struct devlog_params *dparams = &sc->params.devlog;
13869 	struct fw_devlog_e e;
13870 	int i, first, j, m, nentries, rc;
13871 	uint64_t ftstamp = UINT64_MAX;
13872 
13873 	if (dparams->start == 0) {
13874 		db_printf("devlog params not valid\n");
13875 		return;
13876 	}
13877 
13878 	nentries = dparams->size / sizeof(struct fw_devlog_e);
13879 	m = fwmtype_to_hwmtype(dparams->memtype);
13880 
13881 	/* Find the first entry. */
13882 	first = -1;
13883 	for (i = 0; i < nentries && !db_pager_quit; i++) {
13884 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
13885 		    sizeof(e), (void *)&e);
13886 		if (rc != 0)
13887 			break;
13888 
13889 		if (e.timestamp == 0)
13890 			break;
13891 
13892 		e.timestamp = be64toh(e.timestamp);
13893 		if (e.timestamp < ftstamp) {
13894 			ftstamp = e.timestamp;
13895 			first = i;
13896 		}
13897 	}
13898 
13899 	if (first == -1)
13900 		return;
13901 
13902 	i = first;
13903 	do {
13904 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
13905 		    sizeof(e), (void *)&e);
13906 		if (rc != 0)
13907 			return;
13908 
13909 		if (e.timestamp == 0)
13910 			return;
13911 
13912 		e.timestamp = be64toh(e.timestamp);
13913 		e.seqno = be32toh(e.seqno);
13914 		for (j = 0; j < 8; j++)
13915 			e.params[j] = be32toh(e.params[j]);
13916 
13917 		db_printf("%10d  %15ju  %8s  %8s  ",
13918 		    e.seqno, e.timestamp,
13919 		    (e.level < nitems(devlog_level_strings) ?
13920 			devlog_level_strings[e.level] : "UNKNOWN"),
13921 		    (e.facility < nitems(devlog_facility_strings) ?
13922 			devlog_facility_strings[e.facility] : "UNKNOWN"));
13923 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
13924 		    e.params[3], e.params[4], e.params[5], e.params[6],
13925 		    e.params[7]);
13926 
13927 		if (++i == nentries)
13928 			i = 0;
13929 	} while (i != first && !db_pager_quit);
13930 }
13931 
13932 static DB_DEFINE_TABLE(show, t4, show_t4);
13933 
13934 DB_TABLE_COMMAND_FLAGS(show_t4, devlog, db_show_devlog, CS_OWN)
13935 {
13936 	device_t dev;
13937 	int t;
13938 	bool valid;
13939 
13940 	valid = false;
13941 	t = db_read_token();
13942 	if (t == tIDENT) {
13943 		dev = device_lookup_by_name(db_tok_string);
13944 		valid = true;
13945 	}
13946 	db_skip_to_eol();
13947 	if (!valid) {
13948 		db_printf("usage: show t4 devlog <nexus>\n");
13949 		return;
13950 	}
13951 
13952 	if (dev == NULL) {
13953 		db_printf("device not found\n");
13954 		return;
13955 	}
13956 
13957 	t4_dump_devlog(device_get_softc(dev));
13958 }
13959 
13960 DB_TABLE_COMMAND_FLAGS(show_t4, tcb, db_show_t4tcb, CS_OWN)
13961 {
13962 	device_t dev;
13963 	int radix, tid, t;
13964 	bool valid;
13965 
13966 	valid = false;
13967 	radix = db_radix;
13968 	db_radix = 10;
13969 	t = db_read_token();
13970 	if (t == tIDENT) {
13971 		dev = device_lookup_by_name(db_tok_string);
13972 		t = db_read_token();
13973 		if (t == tNUMBER) {
13974 			tid = db_tok_number;
13975 			valid = true;
13976 		}
13977 	}
13978 	db_radix = radix;
13979 	db_skip_to_eol();
13980 	if (!valid) {
13981 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
13982 		return;
13983 	}
13984 
13985 	if (dev == NULL) {
13986 		db_printf("device not found\n");
13987 		return;
13988 	}
13989 	if (tid < 0) {
13990 		db_printf("invalid tid\n");
13991 		return;
13992 	}
13993 
13994 	t4_dump_tcb(device_get_softc(dev), tid);
13995 }
13996 
13997 DB_TABLE_COMMAND_FLAGS(show_t4, memdump, db_show_memdump, CS_OWN)
13998 {
13999 	device_t dev;
14000 	int radix, t;
14001 	bool valid;
14002 
14003 	valid = false;
14004 	radix = db_radix;
14005 	db_radix = 10;
14006 	t = db_read_token();
14007 	if (t == tIDENT) {
14008 		dev = device_lookup_by_name(db_tok_string);
14009 		t = db_read_token();
14010 		if (t == tNUMBER) {
14011 			addr = db_tok_number;
14012 			t = db_read_token();
14013 			if (t == tNUMBER) {
14014 				count = db_tok_number;
14015 				valid = true;
14016 			}
14017 		}
14018 	}
14019 	db_radix = radix;
14020 	db_skip_to_eol();
14021 	if (!valid) {
14022 		db_printf("usage: show t4 memdump <nexus> <addr> <len>\n");
14023 		return;
14024 	}
14025 
14026 	if (dev == NULL) {
14027 		db_printf("device not found\n");
14028 		return;
14029 	}
14030 	if (addr < 0) {
14031 		db_printf("invalid address\n");
14032 		return;
14033 	}
14034 	if (count <= 0) {
14035 		db_printf("invalid length\n");
14036 		return;
14037 	}
14038 
14039 	t4_dump_mem(device_get_softc(dev), addr, count);
14040 }
14041 #endif
14042 
14043 static eventhandler_tag vxlan_start_evtag;
14044 static eventhandler_tag vxlan_stop_evtag;
14045 
14046 struct vxlan_evargs {
14047 	if_t ifp;
14048 	uint16_t port;
14049 };
14050 
14051 static void
14052 enable_vxlan_rx(struct adapter *sc)
14053 {
14054 	int i, rc;
14055 	struct port_info *pi;
14056 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
14057 
14058 	ASSERT_SYNCHRONIZED_OP(sc);
14059 
14060 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
14061 	    F_VXLAN_EN);
14062 	for_each_port(sc, i) {
14063 		pi = sc->port[i];
14064 		if (pi->vxlan_tcam_entry == true)
14065 			continue;
14066 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
14067 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
14068 		    true);
14069 		if (rc < 0) {
14070 			rc = -rc;
14071 			CH_ERR(&pi->vi[0],
14072 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
14073 		} else {
14074 			MPASS(rc == sc->rawf_base + pi->port_id);
14075 			pi->vxlan_tcam_entry = true;
14076 		}
14077 	}
14078 }
14079 
14080 static void
14081 t4_vxlan_start(struct adapter *sc, void *arg)
14082 {
14083 	struct vxlan_evargs *v = arg;
14084 
14085 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
14086 		return;
14087 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
14088 		return;
14089 
14090 	if (sc->vxlan_refcount == 0) {
14091 		sc->vxlan_port = v->port;
14092 		sc->vxlan_refcount = 1;
14093 		if (!hw_off_limits(sc))
14094 			enable_vxlan_rx(sc);
14095 	} else if (sc->vxlan_port == v->port) {
14096 		sc->vxlan_refcount++;
14097 	} else {
14098 		CH_ERR(sc, "VXLAN already configured on port  %d; "
14099 		    "ignoring attempt to configure it on port %d\n",
14100 		    sc->vxlan_port, v->port);
14101 	}
14102 	end_synchronized_op(sc, 0);
14103 }
14104 
14105 static void
14106 t4_vxlan_stop(struct adapter *sc, void *arg)
14107 {
14108 	struct vxlan_evargs *v = arg;
14109 
14110 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
14111 		return;
14112 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
14113 		return;
14114 
14115 	/*
14116 	 * VXLANs may have been configured before the driver was loaded so we
14117 	 * may see more stops than starts.  This is not handled cleanly but at
14118 	 * least we keep the refcount sane.
14119 	 */
14120 	if (sc->vxlan_port != v->port)
14121 		goto done;
14122 	if (sc->vxlan_refcount == 0) {
14123 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
14124 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
14125 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
14126 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
14127 done:
14128 	end_synchronized_op(sc, 0);
14129 }
14130 
14131 static void
14132 t4_vxlan_start_handler(void *arg __unused, if_t ifp,
14133     sa_family_t family, u_int port)
14134 {
14135 	struct vxlan_evargs v;
14136 
14137 	MPASS(family == AF_INET || family == AF_INET6);
14138 	v.ifp = ifp;
14139 	v.port = port;
14140 
14141 	t4_iterate(t4_vxlan_start, &v);
14142 }
14143 
14144 static void
14145 t4_vxlan_stop_handler(void *arg __unused, if_t ifp, sa_family_t family,
14146     u_int port)
14147 {
14148 	struct vxlan_evargs v;
14149 
14150 	MPASS(family == AF_INET || family == AF_INET6);
14151 	v.ifp = ifp;
14152 	v.port = port;
14153 
14154 	t4_iterate(t4_vxlan_stop, &v);
14155 }
14156 
14157 
14158 static struct sx mlu;	/* mod load unload */
14159 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
14160 
14161 static int
14162 mod_event(module_t mod, int cmd, void *arg)
14163 {
14164 	int rc = 0;
14165 	static int loaded = 0;
14166 
14167 	switch (cmd) {
14168 	case MOD_LOAD:
14169 		sx_xlock(&mlu);
14170 		if (loaded++ == 0) {
14171 			t4_sge_modload();
14172 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
14173 			    t4_filter_rpl, CPL_COOKIE_FILTER);
14174 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
14175 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
14176 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
14177 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
14178 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
14179 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
14180 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
14181 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
14182 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
14183 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
14184 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
14185 			    do_smt_write_rpl);
14186 			sx_init(&t4_list_lock, "T4/T5 adapters");
14187 			SLIST_INIT(&t4_list);
14188 			callout_init(&fatal_callout, 1);
14189 #ifdef TCP_OFFLOAD
14190 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
14191 #endif
14192 #ifdef INET6
14193 			t4_clip_modload();
14194 #endif
14195 #ifdef KERN_TLS
14196 			t6_ktls_modload();
14197 			t7_ktls_modload();
14198 #endif
14199 			t4_tracer_modload();
14200 			tweak_tunables();
14201 			vxlan_start_evtag =
14202 			    EVENTHANDLER_REGISTER(vxlan_start,
14203 				t4_vxlan_start_handler, NULL,
14204 				EVENTHANDLER_PRI_ANY);
14205 			vxlan_stop_evtag =
14206 			    EVENTHANDLER_REGISTER(vxlan_stop,
14207 				t4_vxlan_stop_handler, NULL,
14208 				EVENTHANDLER_PRI_ANY);
14209 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
14210 			    taskqueue_thread_enqueue, &reset_tq);
14211 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
14212 			    "t4_rst_thr");
14213 		}
14214 		sx_xunlock(&mlu);
14215 		break;
14216 
14217 	case MOD_UNLOAD:
14218 		sx_xlock(&mlu);
14219 		if (--loaded == 0) {
14220 #ifdef TCP_OFFLOAD
14221 			int i;
14222 #endif
14223 			int tries;
14224 
14225 			taskqueue_free(reset_tq);
14226 
14227 			tries = 0;
14228 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
14229 				uprintf("%ju clusters with custom free routine "
14230 				    "still is use.\n", t4_sge_extfree_refs());
14231 				pause("t4unload", 2 * hz);
14232 			}
14233 
14234 			sx_slock(&t4_list_lock);
14235 			if (!SLIST_EMPTY(&t4_list)) {
14236 				rc = EBUSY;
14237 				sx_sunlock(&t4_list_lock);
14238 				goto done_unload;
14239 			}
14240 #ifdef TCP_OFFLOAD
14241 			sx_slock(&t4_uld_list_lock);
14242 			for (i = 0; i <= ULD_MAX; i++) {
14243 				if (t4_uld_list[i] != NULL) {
14244 					rc = EBUSY;
14245 					sx_sunlock(&t4_uld_list_lock);
14246 					sx_sunlock(&t4_list_lock);
14247 					goto done_unload;
14248 				}
14249 			}
14250 			sx_sunlock(&t4_uld_list_lock);
14251 #endif
14252 			sx_sunlock(&t4_list_lock);
14253 
14254 			if (t4_sge_extfree_refs() == 0) {
14255 				EVENTHANDLER_DEREGISTER(vxlan_start,
14256 				    vxlan_start_evtag);
14257 				EVENTHANDLER_DEREGISTER(vxlan_stop,
14258 				    vxlan_stop_evtag);
14259 				t4_tracer_modunload();
14260 #ifdef KERN_TLS
14261 				t7_ktls_modunload();
14262 				t6_ktls_modunload();
14263 #endif
14264 #ifdef INET6
14265 				t4_clip_modunload();
14266 #endif
14267 #ifdef TCP_OFFLOAD
14268 				sx_destroy(&t4_uld_list_lock);
14269 #endif
14270 				sx_destroy(&t4_list_lock);
14271 				t4_sge_modunload();
14272 				loaded = 0;
14273 			} else {
14274 				rc = EBUSY;
14275 				loaded++;	/* undo earlier decrement */
14276 			}
14277 		}
14278 done_unload:
14279 		sx_xunlock(&mlu);
14280 		break;
14281 	}
14282 
14283 	return (rc);
14284 }
14285 
14286 DRIVER_MODULE(t4nex, pci, t4_driver, mod_event, 0);
14287 MODULE_VERSION(t4nex, 1);
14288 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
14289 #ifdef DEV_NETMAP
14290 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
14291 #endif /* DEV_NETMAP */
14292 
14293 DRIVER_MODULE(t5nex, pci, t5_driver, mod_event, 0);
14294 MODULE_VERSION(t5nex, 1);
14295 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
14296 #ifdef DEV_NETMAP
14297 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
14298 #endif /* DEV_NETMAP */
14299 
14300 DRIVER_MODULE(t6nex, pci, t6_driver, mod_event, 0);
14301 MODULE_VERSION(t6nex, 1);
14302 MODULE_DEPEND(t6nex, crypto, 1, 1, 1);
14303 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
14304 #ifdef DEV_NETMAP
14305 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
14306 #endif /* DEV_NETMAP */
14307 
14308 DRIVER_MODULE(chnex, pci, ch_driver, mod_event, 0);
14309 MODULE_VERSION(chnex, 1);
14310 MODULE_DEPEND(chnex, crypto, 1, 1, 1);
14311 MODULE_DEPEND(chnex, firmware, 1, 1, 1);
14312 #ifdef DEV_NETMAP
14313 MODULE_DEPEND(chnex, netmap, 1, 1, 1);
14314 #endif /* DEV_NETMAP */
14315 
14316 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, 0, 0);
14317 MODULE_VERSION(cxgbe, 1);
14318 
14319 DRIVER_MODULE(cxl, t5nex, cxl_driver, 0, 0);
14320 MODULE_VERSION(cxl, 1);
14321 
14322 DRIVER_MODULE(cc, t6nex, cc_driver, 0, 0);
14323 MODULE_VERSION(cc, 1);
14324 
14325 DRIVER_MODULE(che, chnex, che_driver, 0, 0);
14326 MODULE_VERSION(che, 1);
14327 
14328 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, 0, 0);
14329 MODULE_VERSION(vcxgbe, 1);
14330 
14331 DRIVER_MODULE(vcxl, cxl, vcxl_driver, 0, 0);
14332 MODULE_VERSION(vcxl, 1);
14333 
14334 DRIVER_MODULE(vcc, cc, vcc_driver, 0, 0);
14335 MODULE_VERSION(vcc, 1);
14336 
14337 DRIVER_MODULE(vche, che, vche_driver, 0, 0);
14338 MODULE_VERSION(vche, 1);
14339