xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision 0d635085b8e7d70beaa7a0fe3a1c865c26da2d2f)
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 	DEVMETHOD_END
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 	DEVMETHOD_END
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_ncores_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 static int sysctl_tcb_cache(SYSCTL_HANDLER_ARGS);
904 #ifdef TCP_OFFLOAD
905 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
906 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
907 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
908 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
909 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
910 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
911 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
912 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
913 #endif
914 static int get_sge_context(struct adapter *, int, uint32_t, int, uint32_t *);
915 static int load_fw(struct adapter *, struct t4_data *);
916 static int load_cfg(struct adapter *, struct t4_data *);
917 static int load_boot(struct adapter *, struct t4_bootrom *);
918 static int load_bootcfg(struct adapter *, struct t4_data *);
919 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
920 static void free_offload_policy(struct t4_offload_policy *);
921 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
922 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
923 static int read_i2c(struct adapter *, struct t4_i2c_data *);
924 static int clear_stats(struct adapter *, u_int);
925 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
926 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
927 static inline int stop_adapter(struct adapter *);
928 static inline void set_adapter_hwstatus(struct adapter *, const bool);
929 static int stop_lld(struct adapter *);
930 static inline int restart_adapter(struct adapter *);
931 static int restart_lld(struct adapter *);
932 #ifdef TCP_OFFLOAD
933 static int deactivate_all_uld(struct adapter *);
934 static void stop_all_uld(struct adapter *);
935 static void restart_all_uld(struct adapter *);
936 #endif
937 #ifdef KERN_TLS
938 static int ktls_capability(struct adapter *, bool);
939 #endif
940 static int mod_event(module_t, int, void *);
941 static int notify_siblings(device_t, int);
942 static uint64_t vi_get_counter(if_t, ift_counter);
943 static uint64_t cxgbe_get_counter(if_t, ift_counter);
944 static void enable_vxlan_rx(struct adapter *);
945 static void reset_adapter_task(void *, int);
946 static void fatal_error_task(void *, int);
947 static void dump_devlog(struct adapter *);
948 static void dump_cim_regs(struct adapter *);
949 static void dump_cimla(struct adapter *);
950 
951 struct {
952 	uint16_t device;
953 	char *desc;
954 } t4_pciids[] = {
955 	{0xa000, "Chelsio Terminator 4 FPGA"},
956 	{0x4400, "Chelsio T440-dbg"},
957 	{0x4401, "Chelsio T420-CR"},
958 	{0x4402, "Chelsio T422-CR"},
959 	{0x4403, "Chelsio T440-CR"},
960 	{0x4404, "Chelsio T420-BCH"},
961 	{0x4405, "Chelsio T440-BCH"},
962 	{0x4406, "Chelsio T440-CH"},
963 	{0x4407, "Chelsio T420-SO"},
964 	{0x4408, "Chelsio T420-CX"},
965 	{0x4409, "Chelsio T420-BT"},
966 	{0x440a, "Chelsio T404-BT"},
967 	{0x440e, "Chelsio T440-LP-CR"},
968 }, t5_pciids[] = {
969 	{0xb000, "Chelsio Terminator 5 FPGA"},
970 	{0x5400, "Chelsio T580-dbg"},
971 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
972 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
973 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
974 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
975 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
976 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
977 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
978 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
979 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
980 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
981 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
982 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
983 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
984 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
985 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
986 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
987 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
988 
989 	/* Custom */
990 	{0x5483, "Custom T540-CR"},
991 	{0x5484, "Custom T540-BT"},
992 }, t6_pciids[] = {
993 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
994 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
995 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
996 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
997 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
998 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
999 	{0x6405, "Chelsio T6225-SO-OCP3"},	/* 2 x 10/25G, nomem */
1000 	{0x6406, "Chelsio T6225-OCP3"},		/* 2 x 10/25G */
1001 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
1002 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
1003 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
1004 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
1005 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
1006 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
1007 	{0x6414, "Chelsio T62100-SO-OCP3"},	/* 2 x 40/50/100G, nomem */
1008 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
1009 
1010 	/* Custom */
1011 	{0x6480, "Custom T6225-CR"},
1012 	{0x6481, "Custom T62100-CR"},
1013 	{0x6482, "Custom T6225-CR"},
1014 	{0x6483, "Custom T62100-CR"},
1015 	{0x6484, "Custom T64100-CR"},
1016 	{0x6485, "Custom T6240-SO"},
1017 	{0x6486, "Custom T6225-SO-CR"},
1018 	{0x6487, "Custom T6225-CR"},
1019 }, t7_pciids[] = {
1020 	{0xd000, "Chelsio Terminator 7 FPGA"},	/* T7 PE12K FPGA */
1021 	{0x7400, "Chelsio T72200-DBG"},		/* 2 x 200G, debug */
1022 	{0x7401, "Chelsio T7250"},		/* 2 x 10/25/50G, 1 mem */
1023 	{0x7402, "Chelsio S7250"},		/* 2 x 10/25/50G, nomem */
1024 	{0x7403, "Chelsio T7450"},		/* 4 x 10/25/50G, 1 mem */
1025 	{0x7404, "Chelsio S7450"},		/* 4 x 10/25/50G, nomem */
1026 	{0x7405, "Chelsio T72200"},		/* 2 x 40/100/200G, 1 mem */
1027 	{0x7406, "Chelsio S72200"},		/* 2 x 40/100/200G, nomem */
1028 	{0x7407, "Chelsio T72200-FH"},		/* 2 x 40/100/200G, 2 mem */
1029 	{0x7408, "Chelsio S71400"},		/* 1 x 400G, nomem */
1030 	{0x7409, "Chelsio S7210-BT"},		/* 2 x 10GBASE-T, nomem */
1031 	{0x740a, "Chelsio T7450-RC"},		/* 4 x 10/25/50G, 1 mem, RC */
1032 	{0x740b, "Chelsio T72200-RC"},		/* 2 x 40/100/200G, 1 mem, RC */
1033 	{0x740c, "Chelsio T72200-FH-RC"},	/* 2 x 40/100/200G, 2 mem, RC */
1034 	{0x740d, "Chelsio S72200-OCP3"},	/* 2 x 40/100/200G OCP3 */
1035 	{0x740e, "Chelsio S7450-OCP3"},		/* 4 x 1/20/25/50G OCP3 */
1036 	{0x740f, "Chelsio S7410-BT-OCP3"},	/* 4 x 10GBASE-T OCP3 */
1037 	{0x7410, "Chelsio S7210-BT-A"},		/* 2 x 10GBASE-T */
1038 	{0x7411, "Chelsio T7_MAYRA_7"},		/* Motherboard */
1039 
1040 	/* Custom */
1041 	{0x7480, "Custom T7"},
1042 };
1043 
1044 #ifdef TCP_OFFLOAD
1045 /*
1046  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
1047  * be exactly the same for both rxq and ofld_rxq.
1048  */
1049 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
1050 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
1051 #endif
1052 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
1053 
1054 static int
1055 t4_probe(device_t dev)
1056 {
1057 	int i;
1058 	uint16_t v = pci_get_vendor(dev);
1059 	uint16_t d = pci_get_device(dev);
1060 	uint8_t f = pci_get_function(dev);
1061 
1062 	if (v != PCI_VENDOR_ID_CHELSIO)
1063 		return (ENXIO);
1064 
1065 	/* Attach only to PF0 of the FPGA */
1066 	if (d == 0xa000 && f != 0)
1067 		return (ENXIO);
1068 
1069 	for (i = 0; i < nitems(t4_pciids); i++) {
1070 		if (d == t4_pciids[i].device) {
1071 			device_set_desc(dev, t4_pciids[i].desc);
1072 			return (BUS_PROBE_DEFAULT);
1073 		}
1074 	}
1075 
1076 	return (ENXIO);
1077 }
1078 
1079 static int
1080 t5_probe(device_t dev)
1081 {
1082 	int i;
1083 	uint16_t v = pci_get_vendor(dev);
1084 	uint16_t d = pci_get_device(dev);
1085 	uint8_t f = pci_get_function(dev);
1086 
1087 	if (v != PCI_VENDOR_ID_CHELSIO)
1088 		return (ENXIO);
1089 
1090 	/* Attach only to PF0 of the FPGA */
1091 	if (d == 0xb000 && f != 0)
1092 		return (ENXIO);
1093 
1094 	for (i = 0; i < nitems(t5_pciids); i++) {
1095 		if (d == t5_pciids[i].device) {
1096 			device_set_desc(dev, t5_pciids[i].desc);
1097 			return (BUS_PROBE_DEFAULT);
1098 		}
1099 	}
1100 
1101 	return (ENXIO);
1102 }
1103 
1104 static int
1105 t6_probe(device_t dev)
1106 {
1107 	int i;
1108 	uint16_t v = pci_get_vendor(dev);
1109 	uint16_t d = pci_get_device(dev);
1110 
1111 	if (v != PCI_VENDOR_ID_CHELSIO)
1112 		return (ENXIO);
1113 
1114 	for (i = 0; i < nitems(t6_pciids); i++) {
1115 		if (d == t6_pciids[i].device) {
1116 			device_set_desc(dev, t6_pciids[i].desc);
1117 			return (BUS_PROBE_DEFAULT);
1118 		}
1119 	}
1120 
1121 	return (ENXIO);
1122 }
1123 
1124 static int
1125 ch_probe(device_t dev)
1126 {
1127 	int i;
1128 	uint16_t v = pci_get_vendor(dev);
1129 	uint16_t d = pci_get_device(dev);
1130 	uint8_t f = pci_get_function(dev);
1131 
1132 	if (v != PCI_VENDOR_ID_CHELSIO)
1133 		return (ENXIO);
1134 
1135 	/* Attach only to PF0 of the FPGA */
1136 	if (d == 0xd000 && f != 0)
1137 		return (ENXIO);
1138 
1139 	for (i = 0; i < nitems(t7_pciids); i++) {
1140 		if (d == t7_pciids[i].device) {
1141 			device_set_desc(dev, t7_pciids[i].desc);
1142 			return (BUS_PROBE_DEFAULT);
1143 		}
1144 	}
1145 
1146 	return (ENXIO);
1147 }
1148 
1149 static void
1150 t5_attribute_workaround(device_t dev)
1151 {
1152 	device_t root_port;
1153 	uint32_t v;
1154 
1155 	/*
1156 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1157 	 * Ordering attributes when replying to a TLP from a Root
1158 	 * Port.  As a workaround, find the parent Root Port and
1159 	 * disable No Snoop and Relaxed Ordering.  Note that this
1160 	 * affects all devices under this root port.
1161 	 */
1162 	root_port = pci_find_pcie_root_port(dev);
1163 	if (root_port == NULL) {
1164 		device_printf(dev, "Unable to find parent root port\n");
1165 		return;
1166 	}
1167 
1168 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1169 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1170 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1171 	    0)
1172 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1173 		    device_get_nameunit(root_port));
1174 }
1175 
1176 static const struct devnames devnames[] = {
1177 	{
1178 		.nexus_name = "t4nex",
1179 		.ifnet_name = "cxgbe",
1180 		.vi_ifnet_name = "vcxgbe",
1181 		.pf03_drv_name = "t4iov",
1182 		.vf_nexus_name = "t4vf",
1183 		.vf_ifnet_name = "cxgbev"
1184 	}, {
1185 		.nexus_name = "t5nex",
1186 		.ifnet_name = "cxl",
1187 		.vi_ifnet_name = "vcxl",
1188 		.pf03_drv_name = "t5iov",
1189 		.vf_nexus_name = "t5vf",
1190 		.vf_ifnet_name = "cxlv"
1191 	}, {
1192 		.nexus_name = "t6nex",
1193 		.ifnet_name = "cc",
1194 		.vi_ifnet_name = "vcc",
1195 		.pf03_drv_name = "t6iov",
1196 		.vf_nexus_name = "t6vf",
1197 		.vf_ifnet_name = "ccv"
1198 	}, {
1199 		.nexus_name = "chnex",
1200 		.ifnet_name = "che",
1201 		.vi_ifnet_name = "vche",
1202 		.pf03_drv_name = "chiov",
1203 		.vf_nexus_name = "chvf",
1204 		.vf_ifnet_name = "chev"
1205 	}
1206 };
1207 
1208 void
1209 t4_init_devnames(struct adapter *sc)
1210 {
1211 	int id;
1212 
1213 	id = chip_id(sc);
1214 	if (id < CHELSIO_T4) {
1215 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1216 		sc->names = NULL;
1217 	} else if (id - CHELSIO_T4 < nitems(devnames))
1218 		sc->names = &devnames[id - CHELSIO_T4];
1219 	else
1220 		sc->names = &devnames[nitems(devnames) - 1];
1221 }
1222 
1223 static int
1224 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1225 {
1226 	const char *parent, *name;
1227 	long value;
1228 	int line, unit;
1229 
1230 	line = 0;
1231 	parent = device_get_nameunit(sc->dev);
1232 	name = sc->names->ifnet_name;
1233 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1234 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1235 		    value == pi->port_id)
1236 			return (unit);
1237 	}
1238 	return (-1);
1239 }
1240 
1241 static void
1242 t4_calibration(void *arg)
1243 {
1244 	struct adapter *sc;
1245 	struct clock_sync *cur, *nex;
1246 	uint64_t hw;
1247 	sbintime_t sbt;
1248 	int next_up;
1249 
1250 	sc = (struct adapter *)arg;
1251 
1252 	KASSERT(!hw_off_limits(sc), ("hw_off_limits at t4_calibration"));
1253 	hw = t4_read_reg64(sc, A_SGE_TIMESTAMP_LO);
1254 	sbt = sbinuptime();
1255 
1256 	cur = &sc->cal_info[sc->cal_current];
1257 	next_up = (sc->cal_current + 1) % CNT_CAL_INFO;
1258 	nex = &sc->cal_info[next_up];
1259 	if (__predict_false(sc->cal_count == 0)) {
1260 		/* First time in, just get the values in */
1261 		cur->hw_cur = hw;
1262 		cur->sbt_cur = sbt;
1263 		sc->cal_count++;
1264 		goto done;
1265 	}
1266 
1267 	if (cur->hw_cur == hw) {
1268 		/* The clock is not advancing? */
1269 		sc->cal_count = 0;
1270 		atomic_store_rel_int(&cur->gen, 0);
1271 		goto done;
1272 	}
1273 
1274 	seqc_write_begin(&nex->gen);
1275 	nex->hw_prev = cur->hw_cur;
1276 	nex->sbt_prev = cur->sbt_cur;
1277 	nex->hw_cur = hw;
1278 	nex->sbt_cur = sbt;
1279 	seqc_write_end(&nex->gen);
1280 	sc->cal_current = next_up;
1281 done:
1282 	callout_reset_sbt_curcpu(&sc->cal_callout, SBT_1S, 0, t4_calibration,
1283 	    sc, C_DIRECT_EXEC);
1284 }
1285 
1286 static void
1287 t4_calibration_start(struct adapter *sc)
1288 {
1289 	/*
1290 	 * Here if we have not done a calibration
1291 	 * then do so otherwise start the appropriate
1292 	 * timer.
1293 	 */
1294 	int i;
1295 
1296 	for (i = 0; i < CNT_CAL_INFO; i++) {
1297 		sc->cal_info[i].gen = 0;
1298 	}
1299 	sc->cal_current = 0;
1300 	sc->cal_count = 0;
1301 	sc->cal_gen = 0;
1302 	t4_calibration(sc);
1303 }
1304 
1305 static int
1306 t4_attach(device_t dev)
1307 {
1308 	struct adapter *sc;
1309 	int rc = 0, i, j, rqidx, tqidx, nports;
1310 	struct make_dev_args mda;
1311 	struct intrs_and_queues iaq;
1312 	struct sge *s;
1313 	uint32_t *buf;
1314 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1315 	int ofld_tqidx;
1316 #endif
1317 #ifdef TCP_OFFLOAD
1318 	int ofld_rqidx;
1319 #endif
1320 #ifdef DEV_NETMAP
1321 	int nm_rqidx, nm_tqidx;
1322 #endif
1323 	int num_vis;
1324 
1325 	sc = device_get_softc(dev);
1326 	sc->dev = dev;
1327 	sysctl_ctx_init(&sc->ctx);
1328 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1329 	if (TUNABLE_INT_FETCH("hw.cxgbe.iflags", &sc->intr_flags) == 0)
1330 		sc->intr_flags = IHF_INTR_CLEAR_ON_INIT | IHF_CLR_ALL_UNIGNORED;
1331 
1332 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1333 		t5_attribute_workaround(dev);
1334 	pci_enable_busmaster(dev);
1335 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1336 		uint32_t v;
1337 
1338 		pci_set_max_read_req(dev, 4096);
1339 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1340 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1341 		if (pcie_relaxed_ordering == 0 &&
1342 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1343 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1344 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1345 		} else if (pcie_relaxed_ordering == 1 &&
1346 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1347 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1348 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1349 		}
1350 	}
1351 
1352 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1353 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1354 	sc->traceq = -1;
1355 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1356 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1357 	    device_get_nameunit(dev));
1358 
1359 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1360 	    device_get_nameunit(dev));
1361 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1362 	t4_add_adapter(sc);
1363 
1364 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1365 	TAILQ_INIT(&sc->sfl);
1366 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1367 
1368 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1369 
1370 	sc->policy = NULL;
1371 	rw_init(&sc->policy_lock, "connection offload policy");
1372 
1373 	callout_init(&sc->ktls_tick, 1);
1374 
1375 	callout_init(&sc->cal_callout, 1);
1376 
1377 	refcount_init(&sc->vxlan_refcount, 0);
1378 
1379 	TASK_INIT(&sc->reset_task, 0, reset_adapter_task, sc);
1380 	TASK_INIT(&sc->fatal_error_task, 0, fatal_error_task, sc);
1381 
1382 	sc->ctrlq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1383 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1384 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1385 	sc->fwq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1386 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1387 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1388 
1389 	rc = t4_map_bars_0_and_4(sc);
1390 	if (rc != 0)
1391 		goto done; /* error message displayed already */
1392 
1393 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1394 	memset(sc->port_map, 0xff, sizeof(sc->port_map));
1395 
1396 	/* Prepare the adapter for operation. */
1397 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1398 	rc = -t4_prep_adapter(sc, buf);
1399 	free(buf, M_CXGBE);
1400 	if (rc != 0) {
1401 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1402 		goto done;
1403 	}
1404 
1405 	/*
1406 	 * This is the real PF# to which we're attaching.  Works from within PCI
1407 	 * passthrough environments too, where pci_get_function() could return a
1408 	 * different PF# depending on the passthrough configuration.  We need to
1409 	 * use the real PF# in all our communication with the firmware.
1410 	 */
1411 	j = t4_read_reg(sc, A_PL_WHOAMI);
1412 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1413 	sc->mbox = sc->pf;
1414 
1415 	t4_init_devnames(sc);
1416 	if (sc->names == NULL) {
1417 		rc = ENOTSUP;
1418 		goto done; /* error message displayed already */
1419 	}
1420 
1421 	/*
1422 	 * Do this really early, with the memory windows set up even before the
1423 	 * character device.  The userland tool's register i/o and mem read
1424 	 * will work even in "recovery mode".
1425 	 */
1426 	setup_memwin(sc);
1427 	if (t4_init_devlog_ncores_params(sc, 0) == 0)
1428 		fixup_devlog_ncores_params(sc);
1429 	make_dev_args_init(&mda);
1430 	mda.mda_devsw = &t4_cdevsw;
1431 	mda.mda_uid = UID_ROOT;
1432 	mda.mda_gid = GID_WHEEL;
1433 	mda.mda_mode = 0600;
1434 	mda.mda_si_drv1 = sc;
1435 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1436 	if (rc != 0)
1437 		device_printf(dev, "failed to create nexus char device: %d.\n",
1438 		    rc);
1439 
1440 	/* Go no further if recovery mode has been requested. */
1441 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1442 		device_printf(dev, "recovery mode.\n");
1443 		goto done;
1444 	}
1445 
1446 #if defined(__i386__)
1447 	if ((cpu_feature & CPUID_CX8) == 0) {
1448 		device_printf(dev, "64 bit atomics not available.\n");
1449 		rc = ENOTSUP;
1450 		goto done;
1451 	}
1452 #endif
1453 
1454 	/* Contact the firmware and try to become the master driver. */
1455 	rc = contact_firmware(sc);
1456 	if (rc != 0)
1457 		goto done; /* error message displayed already */
1458 	MPASS(sc->flags & FW_OK);
1459 
1460 	rc = get_params__pre_init(sc);
1461 	if (rc != 0)
1462 		goto done; /* error message displayed already */
1463 
1464 	if (sc->flags & MASTER_PF) {
1465 		rc = partition_resources(sc);
1466 		if (rc != 0)
1467 			goto done; /* error message displayed already */
1468 	}
1469 
1470 	rc = get_params__post_init(sc);
1471 	if (rc != 0)
1472 		goto done; /* error message displayed already */
1473 
1474 	rc = set_params__post_init(sc);
1475 	if (rc != 0)
1476 		goto done; /* error message displayed already */
1477 
1478 	rc = t4_map_bar_2(sc);
1479 	if (rc != 0)
1480 		goto done; /* error message displayed already */
1481 
1482 	rc = t4_adj_doorbells(sc);
1483 	if (rc != 0)
1484 		goto done; /* error message displayed already */
1485 
1486 	rc = t4_create_dma_tag(sc);
1487 	if (rc != 0)
1488 		goto done; /* error message displayed already */
1489 
1490 	/*
1491 	 * First pass over all the ports - allocate VIs and initialize some
1492 	 * basic parameters like mac address, port type, etc.
1493 	 */
1494 	for_each_port(sc, i) {
1495 		struct port_info *pi;
1496 
1497 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1498 		sc->port[i] = pi;
1499 
1500 		/* These must be set before t4_port_init */
1501 		pi->adapter = sc;
1502 		pi->port_id = i;
1503 		/*
1504 		 * XXX: vi[0] is special so we can't delay this allocation until
1505 		 * pi->nvi's final value is known.
1506 		 */
1507 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1508 		    M_ZERO | M_WAITOK);
1509 
1510 		/*
1511 		 * Allocate the "main" VI and initialize parameters
1512 		 * like mac addr.
1513 		 */
1514 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1515 		if (rc != 0) {
1516 			device_printf(dev, "unable to initialize port %d: %d\n",
1517 			    i, rc);
1518 			free(pi->vi, M_CXGBE);
1519 			free(pi, M_CXGBE);
1520 			sc->port[i] = NULL;
1521 			goto done;
1522 		}
1523 
1524 		if (is_bt(pi->port_type))
1525 			setbit(&sc->bt_map, pi->hw_port);
1526 		else
1527 			MPASS(!isset(&sc->bt_map, pi->hw_port));
1528 
1529 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1530 		    device_get_nameunit(dev), i);
1531 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1532 		for (j = 0; j < sc->params.tp.lb_nchan; j++)
1533 			sc->chan_map[pi->tx_chan + j] = i;
1534 		sc->port_map[pi->hw_port] = i;
1535 
1536 		/*
1537 		 * The MPS counter for FCS errors doesn't work correctly on the
1538 		 * T6 so we use the MAC counter here.  Which MAC is in use
1539 		 * depends on the link settings which will be known when the
1540 		 * link comes up.
1541 		 */
1542 		if (is_t6(sc))
1543 			pi->fcs_reg = -1;
1544 		else
1545 			pi->fcs_reg = A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L;
1546 		pi->fcs_base = 0;
1547 
1548 		/* All VIs on this port share this media. */
1549 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1550 		    cxgbe_media_status);
1551 
1552 		PORT_LOCK(pi);
1553 		init_link_config(pi);
1554 		fixup_link_config(pi);
1555 		build_medialist(pi);
1556 		if (fixed_ifmedia(pi))
1557 			pi->flags |= FIXED_IFMEDIA;
1558 		PORT_UNLOCK(pi);
1559 
1560 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1561 		    t4_ifnet_unit(sc, pi));
1562 		if (pi->dev == NULL) {
1563 			device_printf(dev,
1564 			    "failed to add device for port %d.\n", i);
1565 			rc = ENXIO;
1566 			goto done;
1567 		}
1568 		pi->vi[0].dev = pi->dev;
1569 		device_set_softc(pi->dev, pi);
1570 	}
1571 
1572 	/*
1573 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1574 	 */
1575 	nports = sc->params.nports;
1576 	rc = cfg_itype_and_nqueues(sc, &iaq);
1577 	if (rc != 0)
1578 		goto done; /* error message displayed already */
1579 
1580 	num_vis = iaq.num_vis;
1581 	sc->intr_type = iaq.intr_type;
1582 	sc->intr_count = iaq.nirq;
1583 
1584 	s = &sc->sge;
1585 	s->nctrlq = max(sc->params.nports, sc->params.ncores);
1586 	s->nrxq = nports * iaq.nrxq;
1587 	s->ntxq = nports * iaq.ntxq;
1588 	if (num_vis > 1) {
1589 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1590 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1591 	}
1592 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1593 	s->neq += nports;		/* ctrl queues: 1 per port */
1594 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1595 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1596 	if (is_offload(sc) || is_ethoffload(sc)) {
1597 		s->nofldtxq = nports * iaq.nofldtxq;
1598 		if (num_vis > 1)
1599 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1600 		s->neq += s->nofldtxq;
1601 
1602 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1603 		    M_CXGBE, M_ZERO | M_WAITOK);
1604 	}
1605 #endif
1606 #ifdef TCP_OFFLOAD
1607 	if (is_offload(sc)) {
1608 		s->nofldrxq = nports * iaq.nofldrxq;
1609 		if (num_vis > 1)
1610 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1611 		s->neq += s->nofldrxq;	/* free list */
1612 		s->niq += s->nofldrxq;
1613 
1614 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1615 		    M_CXGBE, M_ZERO | M_WAITOK);
1616 	}
1617 #endif
1618 #ifdef DEV_NETMAP
1619 	s->nnmrxq = 0;
1620 	s->nnmtxq = 0;
1621 	if (t4_native_netmap & NN_MAIN_VI) {
1622 		s->nnmrxq += nports * iaq.nnmrxq;
1623 		s->nnmtxq += nports * iaq.nnmtxq;
1624 	}
1625 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1626 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1627 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1628 	}
1629 	s->neq += s->nnmtxq + s->nnmrxq;
1630 	s->niq += s->nnmrxq;
1631 
1632 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1633 	    M_CXGBE, M_ZERO | M_WAITOK);
1634 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1635 	    M_CXGBE, M_ZERO | M_WAITOK);
1636 #endif
1637 	MPASS(s->niq <= s->iqmap_sz);
1638 	MPASS(s->neq <= s->eqmap_sz);
1639 
1640 	s->ctrlq = malloc(s->nctrlq * sizeof(struct sge_wrq), M_CXGBE,
1641 	    M_ZERO | M_WAITOK);
1642 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1643 	    M_ZERO | M_WAITOK);
1644 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1645 	    M_ZERO | M_WAITOK);
1646 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1647 	    M_ZERO | M_WAITOK);
1648 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1649 	    M_ZERO | M_WAITOK);
1650 
1651 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1652 	    M_ZERO | M_WAITOK);
1653 
1654 	t4_init_l2t(sc, M_WAITOK);
1655 	t4_init_smt(sc, M_WAITOK);
1656 	t4_init_tx_sched(sc);
1657 	t4_init_atid_table(sc);
1658 #ifdef RATELIMIT
1659 	t4_init_etid_table(sc);
1660 #endif
1661 #ifdef INET6
1662 	t4_init_clip_table(sc);
1663 #endif
1664 	if (sc->vres.key.size != 0)
1665 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1666 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1667 	t4_init_tpt(sc);
1668 
1669 	/*
1670 	 * Second pass over the ports.  This time we know the number of rx and
1671 	 * tx queues that each port should get.
1672 	 */
1673 	rqidx = tqidx = 0;
1674 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1675 	ofld_tqidx = 0;
1676 #endif
1677 #ifdef TCP_OFFLOAD
1678 	ofld_rqidx = 0;
1679 #endif
1680 #ifdef DEV_NETMAP
1681 	nm_rqidx = nm_tqidx = 0;
1682 #endif
1683 	for_each_port(sc, i) {
1684 		struct port_info *pi = sc->port[i];
1685 		struct vi_info *vi;
1686 
1687 		if (pi == NULL)
1688 			continue;
1689 
1690 		pi->nvi = num_vis;
1691 		for_each_vi(pi, j, vi) {
1692 			vi->pi = pi;
1693 			vi->adapter = sc;
1694 			vi->first_intr = -1;
1695 			vi->qsize_rxq = t4_qsize_rxq;
1696 			vi->qsize_txq = t4_qsize_txq;
1697 
1698 			vi->first_rxq = rqidx;
1699 			vi->first_txq = tqidx;
1700 			vi->tmr_idx = t4_tmr_idx;
1701 			vi->pktc_idx = t4_pktc_idx;
1702 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1703 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1704 
1705 			rqidx += vi->nrxq;
1706 			tqidx += vi->ntxq;
1707 
1708 			if (j == 0 && vi->ntxq > 1)
1709 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1710 			else
1711 				vi->rsrv_noflowq = 0;
1712 
1713 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1714 			vi->first_ofld_txq = ofld_tqidx;
1715 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1716 			ofld_tqidx += vi->nofldtxq;
1717 #endif
1718 #ifdef TCP_OFFLOAD
1719 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1720 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1721 			vi->first_ofld_rxq = ofld_rqidx;
1722 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1723 
1724 			ofld_rqidx += vi->nofldrxq;
1725 #endif
1726 #ifdef DEV_NETMAP
1727 			vi->first_nm_rxq = nm_rqidx;
1728 			vi->first_nm_txq = nm_tqidx;
1729 			if (j == 0) {
1730 				vi->nnmrxq = iaq.nnmrxq;
1731 				vi->nnmtxq = iaq.nnmtxq;
1732 			} else {
1733 				vi->nnmrxq = iaq.nnmrxq_vi;
1734 				vi->nnmtxq = iaq.nnmtxq_vi;
1735 			}
1736 			nm_rqidx += vi->nnmrxq;
1737 			nm_tqidx += vi->nnmtxq;
1738 #endif
1739 		}
1740 	}
1741 
1742 	rc = t4_setup_intr_handlers(sc);
1743 	if (rc != 0) {
1744 		device_printf(dev,
1745 		    "failed to setup interrupt handlers: %d\n", rc);
1746 		goto done;
1747 	}
1748 
1749 	bus_identify_children(dev);
1750 
1751 	/*
1752 	 * Ensure thread-safe mailbox access (in debug builds).
1753 	 *
1754 	 * So far this was the only thread accessing the mailbox but various
1755 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1756 	 * will access the mailbox from different threads.
1757 	 */
1758 	sc->flags |= CHK_MBOX_ACCESS;
1759 
1760 	bus_attach_children(dev);
1761 	t4_calibration_start(sc);
1762 
1763 	device_printf(dev,
1764 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1765 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1766 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1767 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1768 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1769 
1770 	t4_set_desc(sc);
1771 
1772 	notify_siblings(dev, 0);
1773 
1774 done:
1775 	if (rc != 0 && sc->cdev) {
1776 		/* cdev was created and so cxgbetool works; recover that way. */
1777 		device_printf(dev,
1778 		    "error during attach, adapter is now in recovery mode.\n");
1779 		rc = 0;
1780 	}
1781 
1782 	if (rc != 0)
1783 		t4_detach_common(dev);
1784 	else
1785 		t4_sysctls(sc);
1786 
1787 	return (rc);
1788 }
1789 
1790 static int
1791 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1792 {
1793 	struct adapter *sc;
1794 	struct port_info *pi;
1795 	int i;
1796 
1797 	sc = device_get_softc(bus);
1798 	for_each_port(sc, i) {
1799 		pi = sc->port[i];
1800 		if (pi != NULL && pi->dev == dev) {
1801 			sbuf_printf(sb, "port=%d", pi->port_id);
1802 			break;
1803 		}
1804 	}
1805 	return (0);
1806 }
1807 
1808 static int
1809 t4_ready(device_t dev)
1810 {
1811 	struct adapter *sc;
1812 
1813 	sc = device_get_softc(dev);
1814 	if (sc->flags & FW_OK)
1815 		return (0);
1816 	return (ENXIO);
1817 }
1818 
1819 static int
1820 t4_read_port_device(device_t dev, int port, device_t *child)
1821 {
1822 	struct adapter *sc;
1823 	struct port_info *pi;
1824 
1825 	sc = device_get_softc(dev);
1826 	if (port < 0 || port >= MAX_NPORTS)
1827 		return (EINVAL);
1828 	pi = sc->port[port];
1829 	if (pi == NULL || pi->dev == NULL)
1830 		return (ENXIO);
1831 	*child = pi->dev;
1832 	return (0);
1833 }
1834 
1835 static int
1836 notify_siblings(device_t dev, int detaching)
1837 {
1838 	device_t sibling;
1839 	int error, i;
1840 
1841 	error = 0;
1842 	for (i = 0; i < PCI_FUNCMAX; i++) {
1843 		if (i == pci_get_function(dev))
1844 			continue;
1845 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1846 		    pci_get_slot(dev), i);
1847 		if (sibling == NULL || !device_is_attached(sibling))
1848 			continue;
1849 		if (detaching)
1850 			error = T4_DETACH_CHILD(sibling);
1851 		else
1852 			(void)T4_ATTACH_CHILD(sibling);
1853 		if (error)
1854 			break;
1855 	}
1856 	return (error);
1857 }
1858 
1859 /*
1860  * Idempotent
1861  */
1862 static int
1863 t4_detach(device_t dev)
1864 {
1865 	int rc;
1866 
1867 	rc = notify_siblings(dev, 1);
1868 	if (rc) {
1869 		device_printf(dev,
1870 		    "failed to detach sibling devices: %d\n", rc);
1871 		return (rc);
1872 	}
1873 
1874 	return (t4_detach_common(dev));
1875 }
1876 
1877 int
1878 t4_detach_common(device_t dev)
1879 {
1880 	struct adapter *sc;
1881 	struct port_info *pi;
1882 	int i, rc;
1883 
1884 	sc = device_get_softc(dev);
1885 
1886 #ifdef TCP_OFFLOAD
1887 	rc = deactivate_all_uld(sc);
1888 	if (rc) {
1889 		device_printf(dev,
1890 		    "failed to detach upper layer drivers: %d\n", rc);
1891 		return (rc);
1892 	}
1893 #endif
1894 
1895 	if (sc->cdev) {
1896 		destroy_dev(sc->cdev);
1897 		sc->cdev = NULL;
1898 	}
1899 
1900 	sx_xlock(&t4_list_lock);
1901 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1902 	sx_xunlock(&t4_list_lock);
1903 
1904 	sc->flags &= ~CHK_MBOX_ACCESS;
1905 	if (sc->flags & FULL_INIT_DONE) {
1906 		if (!(sc->flags & IS_VF))
1907 			t4_intr_disable(sc);
1908 	}
1909 
1910 	if (device_is_attached(dev)) {
1911 		rc = bus_detach_children(dev);
1912 		if (rc) {
1913 			device_printf(dev,
1914 			    "failed to detach child devices: %d\n", rc);
1915 			return (rc);
1916 		}
1917 	}
1918 
1919 	for (i = 0; i < sc->intr_count; i++)
1920 		t4_free_irq(sc, &sc->irq[i]);
1921 
1922 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1923 		t4_free_tx_sched(sc);
1924 
1925 	for (i = 0; i < MAX_NPORTS; i++) {
1926 		pi = sc->port[i];
1927 		if (pi) {
1928 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1929 
1930 			mtx_destroy(&pi->pi_lock);
1931 			free(pi->vi, M_CXGBE);
1932 			free(pi, M_CXGBE);
1933 		}
1934 	}
1935 	callout_stop(&sc->cal_callout);
1936 	callout_drain(&sc->cal_callout);
1937 	device_delete_children(dev);
1938 	sysctl_ctx_free(&sc->ctx);
1939 	adapter_full_uninit(sc);
1940 
1941 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1942 		t4_fw_bye(sc, sc->mbox);
1943 
1944 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1945 		pci_release_msi(dev);
1946 
1947 	if (sc->regs_res)
1948 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1949 		    sc->regs_res);
1950 
1951 	if (sc->udbs_res)
1952 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1953 		    sc->udbs_res);
1954 
1955 	if (sc->msix_res)
1956 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1957 		    sc->msix_res);
1958 
1959 	if (sc->l2t)
1960 		t4_free_l2t(sc);
1961 	if (sc->smt)
1962 		t4_free_smt(sc->smt);
1963 	t4_free_atid_table(sc);
1964 #ifdef RATELIMIT
1965 	t4_free_etid_table(sc);
1966 #endif
1967 	if (sc->key_map)
1968 		vmem_destroy(sc->key_map);
1969 	t4_free_tpt(sc);
1970 #ifdef INET6
1971 	t4_destroy_clip_table(sc);
1972 #endif
1973 
1974 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1975 	free(sc->sge.ofld_txq, M_CXGBE);
1976 #endif
1977 #ifdef TCP_OFFLOAD
1978 	free(sc->sge.ofld_rxq, M_CXGBE);
1979 #endif
1980 #ifdef DEV_NETMAP
1981 	free(sc->sge.nm_rxq, M_CXGBE);
1982 	free(sc->sge.nm_txq, M_CXGBE);
1983 #endif
1984 	free(sc->irq, M_CXGBE);
1985 	free(sc->sge.rxq, M_CXGBE);
1986 	free(sc->sge.txq, M_CXGBE);
1987 	free(sc->sge.ctrlq, M_CXGBE);
1988 	free(sc->sge.iqmap, M_CXGBE);
1989 	free(sc->sge.eqmap, M_CXGBE);
1990 	free(sc->tids.ftid_tab, M_CXGBE);
1991 	free(sc->tids.hpftid_tab, M_CXGBE);
1992 	free_hftid_hash(&sc->tids);
1993 	free(sc->tids.tid_tab, M_CXGBE);
1994 	t4_destroy_dma_tag(sc);
1995 
1996 	callout_drain(&sc->ktls_tick);
1997 	callout_drain(&sc->sfl_callout);
1998 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1999 		mtx_destroy(&sc->tids.ftid_lock);
2000 		cv_destroy(&sc->tids.ftid_cv);
2001 	}
2002 	if (mtx_initialized(&sc->tids.atid_lock))
2003 		mtx_destroy(&sc->tids.atid_lock);
2004 	if (mtx_initialized(&sc->ifp_lock))
2005 		mtx_destroy(&sc->ifp_lock);
2006 
2007 	if (rw_initialized(&sc->policy_lock)) {
2008 		rw_destroy(&sc->policy_lock);
2009 #ifdef TCP_OFFLOAD
2010 		if (sc->policy != NULL)
2011 			free_offload_policy(sc->policy);
2012 #endif
2013 	}
2014 
2015 	for (i = 0; i < NUM_MEMWIN; i++) {
2016 		struct memwin *mw = &sc->memwin[i];
2017 
2018 		if (rw_initialized(&mw->mw_lock))
2019 			rw_destroy(&mw->mw_lock);
2020 	}
2021 
2022 	mtx_destroy(&sc->sfl_lock);
2023 	mtx_destroy(&sc->reg_lock);
2024 	mtx_destroy(&sc->sc_lock);
2025 
2026 	bzero(sc, sizeof(*sc));
2027 
2028 	return (0);
2029 }
2030 
2031 static inline int
2032 stop_adapter(struct adapter *sc)
2033 {
2034 	struct port_info *pi;
2035 	int i;
2036 
2037 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_STOPPED))) {
2038 		CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x, EALREADY\n",
2039 			 __func__, curthread, sc->flags, sc->error_flags);
2040 		return (EALREADY);
2041 	}
2042 	CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x\n", __func__, curthread,
2043 		 sc->flags, sc->error_flags);
2044 	t4_shutdown_adapter(sc);
2045 	for_each_port(sc, i) {
2046 		pi = sc->port[i];
2047 		if (pi == NULL)
2048 			continue;
2049 		PORT_LOCK(pi);
2050 		if (pi->up_vis > 0 && pi->link_cfg.link_ok) {
2051 			/*
2052 			 * t4_shutdown_adapter has already shut down all the
2053 			 * PHYs but it also disables interrupts and DMA so there
2054 			 * won't be a link interrupt.  Update the state manually
2055 			 * if the link was up previously and inform the kernel.
2056 			 */
2057 			pi->link_cfg.link_ok = false;
2058 			t4_os_link_changed(pi);
2059 		}
2060 		PORT_UNLOCK(pi);
2061 	}
2062 
2063 	return (0);
2064 }
2065 
2066 static inline int
2067 restart_adapter(struct adapter *sc)
2068 {
2069 	uint32_t val;
2070 
2071 	if (!atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_STOPPED))) {
2072 		CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x, EALREADY\n",
2073 			 __func__, curthread, sc->flags, sc->error_flags);
2074 		return (EALREADY);
2075 	}
2076 	CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x\n", __func__, curthread,
2077 		 sc->flags, sc->error_flags);
2078 
2079 	MPASS(hw_off_limits(sc));
2080 	MPASS((sc->flags & FW_OK) == 0);
2081 	MPASS((sc->flags & MASTER_PF) == 0);
2082 	MPASS(sc->reset_thread == NULL);
2083 
2084 	/*
2085 	 * The adapter is supposed to be back on PCIE with its config space and
2086 	 * BARs restored to their state before reset.  Register access via
2087 	 * t4_read_reg BAR0 should just work.
2088 	 */
2089 	sc->reset_thread = curthread;
2090 	val = t4_read_reg(sc, A_PL_WHOAMI);
2091 	if (val == 0xffffffff || val == 0xeeeeeeee) {
2092 		CH_ERR(sc, "%s: device registers not readable.\n", __func__);
2093 		sc->reset_thread = NULL;
2094 		atomic_set_int(&sc->error_flags, ADAP_STOPPED);
2095 		return (ENXIO);
2096 	}
2097 	atomic_clear_int(&sc->error_flags, ADAP_FATAL_ERR);
2098 	atomic_add_int(&sc->incarnation, 1);
2099 	atomic_add_int(&sc->num_resets, 1);
2100 
2101 	return (0);
2102 }
2103 
2104 static inline void
2105 set_adapter_hwstatus(struct adapter *sc, const bool usable)
2106 {
2107 	if (usable) {
2108 		/* Must be marked reusable by the designated thread. */
2109 		ASSERT_SYNCHRONIZED_OP(sc);
2110 		MPASS(sc->reset_thread == curthread);
2111 		mtx_lock(&sc->reg_lock);
2112 		atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2113 		mtx_unlock(&sc->reg_lock);
2114 	} else {
2115 		/* Mark the adapter totally off limits. */
2116 		begin_synchronized_op(sc, NULL, SLEEP_OK, "t4hwsts");
2117 		mtx_lock(&sc->reg_lock);
2118 		atomic_set_int(&sc->error_flags, HW_OFF_LIMITS);
2119 		mtx_unlock(&sc->reg_lock);
2120 		sc->flags &= ~(FW_OK | MASTER_PF);
2121 		sc->reset_thread = NULL;
2122 		end_synchronized_op(sc, 0);
2123 	}
2124 }
2125 
2126 static int
2127 stop_lld(struct adapter *sc)
2128 {
2129 	struct port_info *pi;
2130 	struct vi_info *vi;
2131 	if_t ifp;
2132 	struct sge_rxq *rxq;
2133 	struct sge_txq *txq;
2134 	struct sge_wrq *wrq;
2135 #ifdef TCP_OFFLOAD
2136 	struct sge_ofld_rxq *ofld_rxq;
2137 #endif
2138 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2139 	struct sge_ofld_txq *ofld_txq;
2140 #endif
2141 	int rc, i, j, k;
2142 
2143 	/*
2144 	 * XXX: Can there be a synch_op in progress that will hang because
2145 	 * hardware has been stopped?  We'll hang too and the solution will be
2146 	 * to use a version of begin_synch_op that wakes up existing synch_op
2147 	 * with errors.  Maybe stop_adapter should do this wakeup?
2148 	 *
2149 	 * I don't think any synch_op could get stranded waiting for DMA or
2150 	 * interrupt so I think we're okay here.  Remove this comment block
2151 	 * after testing.
2152 	 */
2153 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4slld");
2154 	if (rc != 0)
2155 		return (ENXIO);
2156 
2157 	/* Quiesce all activity. */
2158 	for_each_port(sc, i) {
2159 		pi = sc->port[i];
2160 		if (pi == NULL)
2161 			continue;
2162 		pi->vxlan_tcam_entry = false;
2163 		for_each_vi(pi, j, vi) {
2164 			vi->xact_addr_filt = -1;
2165 			mtx_lock(&vi->tick_mtx);
2166 			vi->flags |= VI_SKIP_STATS;
2167 			mtx_unlock(&vi->tick_mtx);
2168 			if (!(vi->flags & VI_INIT_DONE))
2169 				continue;
2170 
2171 			ifp = vi->ifp;
2172 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2173 				mtx_lock(&vi->tick_mtx);
2174 				callout_stop(&vi->tick);
2175 				mtx_unlock(&vi->tick_mtx);
2176 				callout_drain(&vi->tick);
2177 			}
2178 
2179 			/*
2180 			 * Note that the HW is not available.
2181 			 */
2182 			for_each_txq(vi, k, txq) {
2183 				TXQ_LOCK(txq);
2184 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
2185 				TXQ_UNLOCK(txq);
2186 			}
2187 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2188 			for_each_ofld_txq(vi, k, ofld_txq) {
2189 				TXQ_LOCK(&ofld_txq->wrq);
2190 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
2191 				TXQ_UNLOCK(&ofld_txq->wrq);
2192 			}
2193 #endif
2194 			for_each_rxq(vi, k, rxq) {
2195 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2196 			}
2197 #if defined(TCP_OFFLOAD)
2198 			for_each_ofld_rxq(vi, k, ofld_rxq) {
2199 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2200 			}
2201 #endif
2202 
2203 			quiesce_vi(vi);
2204 		}
2205 
2206 		if (sc->flags & FULL_INIT_DONE) {
2207 			/* Control queue */
2208 			wrq = &sc->sge.ctrlq[i];
2209 			TXQ_LOCK(wrq);
2210 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
2211 			TXQ_UNLOCK(wrq);
2212 			quiesce_wrq(wrq);
2213 		}
2214 
2215 		if (pi->flags & HAS_TRACEQ) {
2216 			pi->flags &= ~HAS_TRACEQ;
2217 			sc->traceq = -1;
2218 			sc->tracer_valid = 0;
2219 			sc->tracer_enabled = 0;
2220 		}
2221 	}
2222 	if (sc->flags & FULL_INIT_DONE) {
2223 		/* Firmware event queue */
2224 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
2225 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
2226 	}
2227 
2228 	/* Stop calibration */
2229 	callout_stop(&sc->cal_callout);
2230 	callout_drain(&sc->cal_callout);
2231 
2232 	if (t4_clock_gate_on_suspend) {
2233 		t4_set_reg_field(sc, A_PMU_PART_CG_PWRMODE, F_MA_PART_CGEN |
2234 		    F_LE_PART_CGEN | F_EDC1_PART_CGEN | F_EDC0_PART_CGEN |
2235 		    F_TP_PART_CGEN | F_PDP_PART_CGEN | F_SGE_PART_CGEN, 0);
2236 	}
2237 
2238 	end_synchronized_op(sc, 0);
2239 
2240 	stop_atid_allocator(sc);
2241 	t4_stop_l2t(sc);
2242 
2243 	return (rc);
2244 }
2245 
2246 int
2247 suspend_adapter(struct adapter *sc)
2248 {
2249 	stop_adapter(sc);
2250 	stop_lld(sc);
2251 #ifdef TCP_OFFLOAD
2252 	stop_all_uld(sc);
2253 #endif
2254 	set_adapter_hwstatus(sc, false);
2255 
2256 	return (0);
2257 }
2258 
2259 static int
2260 t4_suspend(device_t dev)
2261 {
2262 	struct adapter *sc = device_get_softc(dev);
2263 	int rc;
2264 
2265 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2266 	rc = suspend_adapter(sc);
2267 	CH_ALERT(sc, "%s end (thread %p).\n", __func__, curthread);
2268 
2269 	return (rc);
2270 }
2271 
2272 struct adapter_pre_reset_state {
2273 	u_int flags;
2274 	uint16_t nbmcaps;
2275 	uint16_t linkcaps;
2276 	uint16_t switchcaps;
2277 	uint16_t nvmecaps;
2278 	uint16_t niccaps;
2279 	uint16_t toecaps;
2280 	uint16_t rdmacaps;
2281 	uint16_t cryptocaps;
2282 	uint16_t iscsicaps;
2283 	uint16_t fcoecaps;
2284 
2285 	u_int cfcsum;
2286 	char cfg_file[32];
2287 
2288 	struct adapter_params params;
2289 	struct t4_virt_res vres;
2290 	struct tid_info tids;
2291 	struct sge sge;
2292 
2293 	int rawf_base;
2294 	int nrawf;
2295 
2296 };
2297 
2298 static void
2299 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2300 {
2301 
2302 	ASSERT_SYNCHRONIZED_OP(sc);
2303 
2304 	o->flags = sc->flags;
2305 
2306 	o->nbmcaps =  sc->nbmcaps;
2307 	o->linkcaps = sc->linkcaps;
2308 	o->switchcaps = sc->switchcaps;
2309 	o->nvmecaps = sc->nvmecaps;
2310 	o->niccaps = sc->niccaps;
2311 	o->toecaps = sc->toecaps;
2312 	o->rdmacaps = sc->rdmacaps;
2313 	o->cryptocaps = sc->cryptocaps;
2314 	o->iscsicaps = sc->iscsicaps;
2315 	o->fcoecaps = sc->fcoecaps;
2316 
2317 	o->cfcsum = sc->cfcsum;
2318 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2319 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2320 
2321 	o->params = sc->params;
2322 	o->vres = sc->vres;
2323 	o->tids = sc->tids;
2324 	o->sge = sc->sge;
2325 
2326 	o->rawf_base = sc->rawf_base;
2327 	o->nrawf = sc->nrawf;
2328 }
2329 
2330 static int
2331 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2332 {
2333 	int rc = 0;
2334 
2335 	ASSERT_SYNCHRONIZED_OP(sc);
2336 
2337 	/* Capabilities */
2338 #define COMPARE_CAPS(c) do { \
2339 	if (o->c##caps != sc->c##caps) { \
2340 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2341 		    sc->c##caps); \
2342 		rc = EINVAL; \
2343 	} \
2344 } while (0)
2345 	COMPARE_CAPS(nbm);
2346 	COMPARE_CAPS(link);
2347 	COMPARE_CAPS(switch);
2348 	COMPARE_CAPS(nvme);
2349 	COMPARE_CAPS(nic);
2350 	COMPARE_CAPS(toe);
2351 	COMPARE_CAPS(rdma);
2352 	COMPARE_CAPS(crypto);
2353 	COMPARE_CAPS(iscsi);
2354 	COMPARE_CAPS(fcoe);
2355 #undef COMPARE_CAPS
2356 
2357 	/* Firmware config file */
2358 	if (o->cfcsum != sc->cfcsum) {
2359 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2360 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2361 		rc = EINVAL;
2362 	}
2363 
2364 #define COMPARE_PARAM(p, name) do { \
2365 	if (o->p != sc->p) { \
2366 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2367 		rc = EINVAL; \
2368 	} \
2369 } while (0)
2370 	COMPARE_PARAM(sge.iq_start, iq_start);
2371 	COMPARE_PARAM(sge.eq_start, eq_start);
2372 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2373 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2374 	COMPARE_PARAM(tids.nftids, nftids);
2375 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2376 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2377 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2378 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2379 	COMPARE_PARAM(tids.tid_base, tid_base);
2380 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2381 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2382 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2383 	COMPARE_PARAM(rawf_base, rawf_base);
2384 	COMPARE_PARAM(nrawf, nrawf);
2385 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2386 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2387 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2388 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2389 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2390 	COMPARE_PARAM(tids.ntids, ntids);
2391 	COMPARE_PARAM(tids.etid_base, etid_base);
2392 	COMPARE_PARAM(tids.etid_end, etid_end);
2393 	COMPARE_PARAM(tids.netids, netids);
2394 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2395 	COMPARE_PARAM(params.ethoffload, ethoffload);
2396 	COMPARE_PARAM(tids.natids, natids);
2397 	COMPARE_PARAM(tids.stid_base, stid_base);
2398 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2399 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2400 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2401 	COMPARE_PARAM(vres.stag.start, stag_start);
2402 	COMPARE_PARAM(vres.stag.size, stag_size);
2403 	COMPARE_PARAM(vres.rq.start, rq_start);
2404 	COMPARE_PARAM(vres.rq.size, rq_size);
2405 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2406 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2407 	COMPARE_PARAM(vres.qp.start, qp_start);
2408 	COMPARE_PARAM(vres.qp.size, qp_size);
2409 	COMPARE_PARAM(vres.cq.start, cq_start);
2410 	COMPARE_PARAM(vres.cq.size, cq_size);
2411 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2412 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2413 	COMPARE_PARAM(vres.srq.start, srq_start);
2414 	COMPARE_PARAM(vres.srq.size, srq_size);
2415 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2416 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2417 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2418 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2419 	COMPARE_PARAM(vres.key.start, key_start);
2420 	COMPARE_PARAM(vres.key.size, key_size);
2421 #undef COMPARE_PARAM
2422 
2423 	return (rc);
2424 }
2425 
2426 static int
2427 restart_lld(struct adapter *sc)
2428 {
2429 	struct adapter_pre_reset_state *old_state = NULL;
2430 	struct port_info *pi;
2431 	struct vi_info *vi;
2432 	if_t ifp;
2433 	struct sge_txq *txq;
2434 	int rc, i, j, k;
2435 
2436 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rlld");
2437 	if (rc != 0)
2438 		return (ENXIO);
2439 
2440 	/* Restore memory window. */
2441 	setup_memwin(sc);
2442 
2443 	/* Go no further if recovery mode has been requested. */
2444 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2445 		CH_ALERT(sc, "%s: recovery mode during restart.\n", __func__);
2446 		rc = 0;
2447 		set_adapter_hwstatus(sc, true);
2448 		goto done;
2449 	}
2450 
2451 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2452 	save_caps_and_params(sc, old_state);
2453 
2454 	/* Reestablish contact with firmware and become the primary PF. */
2455 	rc = contact_firmware(sc);
2456 	if (rc != 0)
2457 		goto done; /* error message displayed already */
2458 	MPASS(sc->flags & FW_OK);
2459 
2460 	if (sc->flags & MASTER_PF) {
2461 		rc = partition_resources(sc);
2462 		if (rc != 0)
2463 			goto done; /* error message displayed already */
2464 	}
2465 
2466 	rc = get_params__post_init(sc);
2467 	if (rc != 0)
2468 		goto done; /* error message displayed already */
2469 
2470 	rc = set_params__post_init(sc);
2471 	if (rc != 0)
2472 		goto done; /* error message displayed already */
2473 
2474 	rc = compare_caps_and_params(sc, old_state);
2475 	if (rc != 0)
2476 		goto done; /* error message displayed already */
2477 
2478 	for_each_port(sc, i) {
2479 		pi = sc->port[i];
2480 		MPASS(pi != NULL);
2481 		MPASS(pi->vi != NULL);
2482 		MPASS(pi->vi[0].dev == pi->dev);
2483 
2484 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2485 		if (rc != 0) {
2486 			CH_ERR(sc,
2487 			    "failed to re-initialize port %d: %d\n", i, rc);
2488 			goto done;
2489 		}
2490 		MPASS(sc->chan_map[pi->tx_chan] == i);
2491 
2492 		PORT_LOCK(pi);
2493 		fixup_link_config(pi);
2494 		build_medialist(pi);
2495 		PORT_UNLOCK(pi);
2496 		for_each_vi(pi, j, vi) {
2497 			if (IS_MAIN_VI(vi))
2498 				continue;
2499 			rc = alloc_extra_vi(sc, pi, vi);
2500 			if (rc != 0) {
2501 				CH_ERR(vi,
2502 				    "failed to re-allocate extra VI: %d\n", rc);
2503 				goto done;
2504 			}
2505 		}
2506 	}
2507 
2508 	/*
2509 	 * Interrupts and queues are about to be enabled and other threads will
2510 	 * want to access the hardware too.  It is safe to do so.  Note that
2511 	 * this thread is still in the middle of a synchronized_op.
2512 	 */
2513 	set_adapter_hwstatus(sc, true);
2514 
2515 	if (sc->flags & FULL_INIT_DONE) {
2516 		rc = adapter_full_init(sc);
2517 		if (rc != 0) {
2518 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2519 			goto done;
2520 		}
2521 
2522 		if (sc->vxlan_refcount > 0)
2523 			enable_vxlan_rx(sc);
2524 
2525 		for_each_port(sc, i) {
2526 			pi = sc->port[i];
2527 			for_each_vi(pi, j, vi) {
2528 				mtx_lock(&vi->tick_mtx);
2529 				vi->flags &= ~VI_SKIP_STATS;
2530 				mtx_unlock(&vi->tick_mtx);
2531 				if (!(vi->flags & VI_INIT_DONE))
2532 					continue;
2533 				rc = vi_full_init(vi);
2534 				if (rc != 0) {
2535 					CH_ERR(vi, "failed to re-initialize "
2536 					    "interface: %d\n", rc);
2537 					goto done;
2538 				}
2539 				if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
2540 					sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
2541 					t4_set_trace_rss_control(sc, pi->tx_chan, sc->traceq);
2542 					pi->flags |= HAS_TRACEQ;
2543 				}
2544 
2545 				ifp = vi->ifp;
2546 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2547 					continue;
2548 				/*
2549 				 * Note that we do not setup multicast addresses
2550 				 * in the first pass.  This ensures that the
2551 				 * unicast DMACs for all VIs on all ports get an
2552 				 * MPS TCAM entry.
2553 				 */
2554 				rc = update_mac_settings(ifp, XGMAC_ALL &
2555 				    ~XGMAC_MCADDRS);
2556 				if (rc != 0) {
2557 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2558 					goto done;
2559 				}
2560 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2561 				    true);
2562 				if (rc != 0) {
2563 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2564 					goto done;
2565 				}
2566 				for_each_txq(vi, k, txq) {
2567 					TXQ_LOCK(txq);
2568 					txq->eq.flags |= EQ_ENABLED;
2569 					TXQ_UNLOCK(txq);
2570 				}
2571 				mtx_lock(&vi->tick_mtx);
2572 				callout_schedule(&vi->tick, hz);
2573 				mtx_unlock(&vi->tick_mtx);
2574 			}
2575 			PORT_LOCK(pi);
2576 			if (pi->up_vis > 0) {
2577 				t4_update_port_info(pi);
2578 				fixup_link_config(pi);
2579 				build_medialist(pi);
2580 				apply_link_config(pi);
2581 				if (pi->link_cfg.link_ok)
2582 					t4_os_link_changed(pi);
2583 			}
2584 			PORT_UNLOCK(pi);
2585 		}
2586 
2587 		/* Now reprogram the L2 multicast addresses. */
2588 		for_each_port(sc, i) {
2589 			pi = sc->port[i];
2590 			for_each_vi(pi, j, vi) {
2591 				if (!(vi->flags & VI_INIT_DONE))
2592 					continue;
2593 				ifp = vi->ifp;
2594 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2595 					continue;
2596 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2597 				if (rc != 0) {
2598 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2599 					rc = 0;	/* carry on */
2600 				}
2601 			}
2602 		}
2603 	}
2604 
2605 	/* Reset all calibration */
2606 	t4_calibration_start(sc);
2607 done:
2608 	end_synchronized_op(sc, 0);
2609 	free(old_state, M_CXGBE);
2610 
2611 	restart_atid_allocator(sc);
2612 	t4_restart_l2t(sc);
2613 
2614 	return (rc);
2615 }
2616 
2617 int
2618 resume_adapter(struct adapter *sc)
2619 {
2620 	restart_adapter(sc);
2621 	restart_lld(sc);
2622 #ifdef TCP_OFFLOAD
2623 	restart_all_uld(sc);
2624 #endif
2625 	return (0);
2626 }
2627 
2628 static int
2629 t4_resume(device_t dev)
2630 {
2631 	struct adapter *sc = device_get_softc(dev);
2632 	int rc;
2633 
2634 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2635 	rc = resume_adapter(sc);
2636 	CH_ALERT(sc, "%s end (thread %p).\n", __func__, curthread);
2637 
2638 	return (rc);
2639 }
2640 
2641 static int
2642 t4_reset_prepare(device_t dev, device_t child)
2643 {
2644 	struct adapter *sc = device_get_softc(dev);
2645 
2646 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2647 	return (0);
2648 }
2649 
2650 static int
2651 t4_reset_post(device_t dev, device_t child)
2652 {
2653 	struct adapter *sc = device_get_softc(dev);
2654 
2655 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2656 	return (0);
2657 }
2658 
2659 static int
2660 reset_adapter_with_pl_rst(struct adapter *sc)
2661 {
2662 	/* This is a t4_write_reg without the hw_off_limits check. */
2663 	MPASS(sc->error_flags & HW_OFF_LIMITS);
2664 	bus_write_4(sc->regs_res, A_PL_RST,
2665 	    F_PIORSTMODE | F_PIORST | F_AUTOPCIEPAUSE);
2666 	pause("pl_rst", 1 * hz);		/* Wait 1s for reset */
2667 	return (0);
2668 }
2669 
2670 static int
2671 reset_adapter_with_pcie_sbr(struct adapter *sc)
2672 {
2673 	device_t pdev = device_get_parent(sc->dev);
2674 	device_t gpdev = device_get_parent(pdev);
2675 	device_t *children;
2676 	int rc, i, lcap, lsta, nchildren;
2677 	uint32_t v;
2678 
2679 	rc = pci_find_cap(gpdev, PCIY_EXPRESS, &v);
2680 	if (rc != 0) {
2681 		CH_ERR(sc, "%s: pci_find_cap(%s, pcie) failed: %d\n", __func__,
2682 		    device_get_nameunit(gpdev), rc);
2683 		return (ENOTSUP);
2684 	}
2685 	lcap = v + PCIER_LINK_CAP;
2686 	lsta = v + PCIER_LINK_STA;
2687 
2688 	nchildren = 0;
2689 	device_get_children(pdev, &children, &nchildren);
2690 	for (i = 0; i < nchildren; i++)
2691 		pci_save_state(children[i]);
2692 	v = pci_read_config(gpdev, PCIR_BRIDGECTL_1, 2);
2693 	pci_write_config(gpdev, PCIR_BRIDGECTL_1, v | PCIB_BCR_SECBUS_RESET, 2);
2694 	pause("pcie_sbr1", hz / 10);	/* 100ms */
2695 	pci_write_config(gpdev, PCIR_BRIDGECTL_1, v, 2);
2696 	pause("pcie_sbr2", hz);		/* Wait 1s before restore_state. */
2697 	v = pci_read_config(gpdev, lsta, 2);
2698 	if (pci_read_config(gpdev, lcap, 2) & PCIEM_LINK_CAP_DL_ACTIVE)
2699 		rc = v & PCIEM_LINK_STA_DL_ACTIVE ? 0 : ETIMEDOUT;
2700 	else if (v & (PCIEM_LINK_STA_TRAINING_ERROR | PCIEM_LINK_STA_TRAINING))
2701 		rc = ETIMEDOUT;
2702 	else
2703 		rc = 0;
2704 	if (rc != 0)
2705 		CH_ERR(sc, "%s: PCIe link is down after reset, LINK_STA 0x%x\n",
2706 		    __func__, v);
2707 	else {
2708 		for (i = 0; i < nchildren; i++)
2709 			pci_restore_state(children[i]);
2710 	}
2711 	free(children, M_TEMP);
2712 
2713 	return (rc);
2714 }
2715 
2716 static int
2717 reset_adapter_with_pcie_link_bounce(struct adapter *sc)
2718 {
2719 	device_t pdev = device_get_parent(sc->dev);
2720 	device_t gpdev = device_get_parent(pdev);
2721 	device_t *children;
2722 	int rc, i, lcap, lctl, lsta, nchildren;
2723 	uint32_t v;
2724 
2725 	rc = pci_find_cap(gpdev, PCIY_EXPRESS, &v);
2726 	if (rc != 0) {
2727 		CH_ERR(sc, "%s: pci_find_cap(%s, pcie) failed: %d\n", __func__,
2728 		    device_get_nameunit(gpdev), rc);
2729 		return (ENOTSUP);
2730 	}
2731 	lcap = v + PCIER_LINK_CAP;
2732 	lctl = v + PCIER_LINK_CTL;
2733 	lsta = v + PCIER_LINK_STA;
2734 
2735 	nchildren = 0;
2736 	device_get_children(pdev, &children, &nchildren);
2737 	for (i = 0; i < nchildren; i++)
2738 		pci_save_state(children[i]);
2739 	v = pci_read_config(gpdev, lctl, 2);
2740 	pci_write_config(gpdev, lctl, v | PCIEM_LINK_CTL_LINK_DIS, 2);
2741 	pause("pcie_lnk1", 100 * hz / 1000);	/* 100ms */
2742 	pci_write_config(gpdev, lctl, v | PCIEM_LINK_CTL_RETRAIN_LINK, 2);
2743 	pause("pcie_lnk2", hz);		/* Wait 1s before restore_state. */
2744 	v = pci_read_config(gpdev, lsta, 2);
2745 	if (pci_read_config(gpdev, lcap, 2) & PCIEM_LINK_CAP_DL_ACTIVE)
2746 		rc = v & PCIEM_LINK_STA_DL_ACTIVE ? 0 : ETIMEDOUT;
2747 	else if (v & (PCIEM_LINK_STA_TRAINING_ERROR | PCIEM_LINK_STA_TRAINING))
2748 		rc = ETIMEDOUT;
2749 	else
2750 		rc = 0;
2751 	if (rc != 0)
2752 		CH_ERR(sc, "%s: PCIe link is down after reset, LINK_STA 0x%x\n",
2753 		    __func__, v);
2754 	else {
2755 		for (i = 0; i < nchildren; i++)
2756 			pci_restore_state(children[i]);
2757 	}
2758 	free(children, M_TEMP);
2759 
2760 	return (rc);
2761 }
2762 
2763 static inline int
2764 reset_adapter(struct adapter *sc)
2765 {
2766 	int rc;
2767 	const int reset_method = vm_guest == VM_GUEST_NO ? t4_reset_method : 0;
2768 
2769 	rc = suspend_adapter(sc);
2770 	if (rc != 0)
2771 		return (rc);
2772 
2773 	switch (reset_method) {
2774 	case 1:
2775 		rc = reset_adapter_with_pcie_sbr(sc);
2776 		break;
2777 	case 2:
2778 		rc = reset_adapter_with_pcie_link_bounce(sc);
2779 		break;
2780 	case 0:
2781 	default:
2782 		rc = reset_adapter_with_pl_rst(sc);
2783 		break;
2784 	}
2785 	if (rc == 0)
2786 		rc = resume_adapter(sc);
2787 	return (rc);
2788 }
2789 
2790 static void
2791 reset_adapter_task(void *arg, int pending)
2792 {
2793 	struct adapter *sc = arg;
2794 	const int flags = sc->flags;
2795 	const int eflags = sc->error_flags;
2796 	int rc;
2797 
2798 	if (pending > 1)
2799 		CH_ALERT(sc, "%s: pending %d\n", __func__, pending);
2800 	rc = reset_adapter(sc);
2801 	if (rc != 0) {
2802 		CH_ERR(sc, "adapter did not reset properly, rc = %d, "
2803 		       "flags 0x%08x -> 0x%08x, err_flags 0x%08x -> 0x%08x.\n",
2804 		       rc, flags, sc->flags, eflags, sc->error_flags);
2805 	}
2806 }
2807 
2808 static int
2809 cxgbe_probe(device_t dev)
2810 {
2811 	struct port_info *pi = device_get_softc(dev);
2812 
2813 	device_set_descf(dev, "port %d", pi->port_id);
2814 
2815 	return (BUS_PROBE_DEFAULT);
2816 }
2817 
2818 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2819     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2820     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2821     IFCAP_HWRXTSTMP | IFCAP_MEXTPG | IFCAP_NV)
2822 #define T4_CAP_ENABLE (T4_CAP)
2823 
2824 static void
2825 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2826 {
2827 	if_t ifp;
2828 	struct sbuf *sb;
2829 	struct sysctl_ctx_list *ctx = &vi->ctx;
2830 	struct sysctl_oid_list *children;
2831 	struct pfil_head_args pa;
2832 	struct adapter *sc = vi->adapter;
2833 
2834 	sysctl_ctx_init(ctx);
2835 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2836 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2837 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2838 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2839 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2840 #ifdef DEV_NETMAP
2841 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2842 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2843 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2844 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2845 #endif
2846 #ifdef TCP_OFFLOAD
2847 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2848 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2849 #endif
2850 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2851 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2852 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2853 #endif
2854 
2855 	vi->xact_addr_filt = -1;
2856 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2857 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2858 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2859 		vi->flags |= TX_USES_VM_WR;
2860 
2861 	/* Allocate an ifnet and set it up */
2862 	ifp = if_alloc_dev(IFT_ETHER, dev);
2863 	vi->ifp = ifp;
2864 	if_setsoftc(ifp, vi);
2865 
2866 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2867 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2868 
2869 	if_setinitfn(ifp, cxgbe_init);
2870 	if_setioctlfn(ifp, cxgbe_ioctl);
2871 	if_settransmitfn(ifp, cxgbe_transmit);
2872 	if_setqflushfn(ifp, cxgbe_qflush);
2873 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2874 		if_setgetcounterfn(ifp, vi_get_counter);
2875 	else
2876 		if_setgetcounterfn(ifp, cxgbe_get_counter);
2877 #if defined(KERN_TLS) || defined(RATELIMIT)
2878 	if_setsndtagallocfn(ifp, cxgbe_snd_tag_alloc);
2879 #endif
2880 #ifdef RATELIMIT
2881 	if_setratelimitqueryfn(ifp, cxgbe_ratelimit_query);
2882 #endif
2883 
2884 	if_setcapabilities(ifp, T4_CAP);
2885 	if_setcapenable(ifp, T4_CAP_ENABLE);
2886 	if_sethwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2887 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2888 	if (chip_id(sc) >= CHELSIO_T6) {
2889 		if_setcapabilitiesbit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2890 		if_setcapenablebit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2891 		if_sethwassistbits(ifp, CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2892 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2893 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN, 0);
2894 	}
2895 
2896 #ifdef TCP_OFFLOAD
2897 	if (vi->nofldrxq != 0)
2898 		if_setcapabilitiesbit(ifp, IFCAP_TOE, 0);
2899 #endif
2900 #ifdef RATELIMIT
2901 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2902 		if_setcapabilitiesbit(ifp, IFCAP_TXRTLMT, 0);
2903 		if_setcapenablebit(ifp, IFCAP_TXRTLMT, 0);
2904 	}
2905 #endif
2906 
2907 	if_sethwtsomax(ifp, IP_MAXPACKET);
2908 	if (vi->flags & TX_USES_VM_WR)
2909 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_VM_TSO);
2910 	else
2911 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_TSO);
2912 #ifdef RATELIMIT
2913 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2914 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_EO_TSO);
2915 #endif
2916 	if_sethwtsomaxsegsize(ifp, 65536);
2917 #ifdef KERN_TLS
2918 	if (is_ktls(sc)) {
2919 		if_setcapabilitiesbit(ifp, IFCAP_TXTLS, 0);
2920 		if (sc->flags & KERN_TLS_ON || !is_t6(sc))
2921 			if_setcapenablebit(ifp, IFCAP_TXTLS, 0);
2922 	}
2923 #endif
2924 
2925 	ether_ifattach(ifp, vi->hw_addr);
2926 #ifdef DEV_NETMAP
2927 	if (vi->nnmrxq != 0)
2928 		cxgbe_nm_attach(vi);
2929 #endif
2930 	sb = sbuf_new_auto();
2931 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2932 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2933 	switch (if_getcapabilities(ifp) & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2934 	case IFCAP_TOE:
2935 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2936 		break;
2937 	case IFCAP_TOE | IFCAP_TXRTLMT:
2938 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2939 		break;
2940 	case IFCAP_TXRTLMT:
2941 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2942 		break;
2943 	}
2944 #endif
2945 #ifdef TCP_OFFLOAD
2946 	if (if_getcapabilities(ifp) & IFCAP_TOE)
2947 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2948 #endif
2949 #ifdef DEV_NETMAP
2950 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2951 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2952 		    vi->nnmtxq, vi->nnmrxq);
2953 #endif
2954 	sbuf_finish(sb);
2955 	device_printf(dev, "%s\n", sbuf_data(sb));
2956 	sbuf_delete(sb);
2957 
2958 	vi_sysctls(vi);
2959 
2960 	pa.pa_version = PFIL_VERSION;
2961 	pa.pa_flags = PFIL_IN;
2962 	pa.pa_type = PFIL_TYPE_ETHERNET;
2963 	pa.pa_headname = if_name(ifp);
2964 	vi->pfil = pfil_head_register(&pa);
2965 }
2966 
2967 static int
2968 cxgbe_attach(device_t dev)
2969 {
2970 	struct port_info *pi = device_get_softc(dev);
2971 	struct adapter *sc = pi->adapter;
2972 	struct vi_info *vi;
2973 	int i;
2974 
2975 	sysctl_ctx_init(&pi->ctx);
2976 
2977 	cxgbe_vi_attach(dev, &pi->vi[0]);
2978 
2979 	for_each_vi(pi, i, vi) {
2980 		if (i == 0)
2981 			continue;
2982 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, DEVICE_UNIT_ANY);
2983 		if (vi->dev == NULL) {
2984 			device_printf(dev, "failed to add VI %d\n", i);
2985 			continue;
2986 		}
2987 		device_set_softc(vi->dev, vi);
2988 	}
2989 
2990 	cxgbe_sysctls(pi);
2991 
2992 	bus_attach_children(dev);
2993 
2994 	return (0);
2995 }
2996 
2997 static void
2998 cxgbe_vi_detach(struct vi_info *vi)
2999 {
3000 	if_t ifp = vi->ifp;
3001 
3002 	if (vi->pfil != NULL) {
3003 		pfil_head_unregister(vi->pfil);
3004 		vi->pfil = NULL;
3005 	}
3006 
3007 	ether_ifdetach(ifp);
3008 
3009 	/* Let detach proceed even if these fail. */
3010 #ifdef DEV_NETMAP
3011 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
3012 		cxgbe_nm_detach(vi);
3013 #endif
3014 	cxgbe_uninit_synchronized(vi);
3015 	callout_drain(&vi->tick);
3016 	mtx_destroy(&vi->tick_mtx);
3017 	sysctl_ctx_free(&vi->ctx);
3018 	vi_full_uninit(vi);
3019 
3020 	if_free(vi->ifp);
3021 	vi->ifp = NULL;
3022 }
3023 
3024 static int
3025 cxgbe_detach(device_t dev)
3026 {
3027 	struct port_info *pi = device_get_softc(dev);
3028 	struct adapter *sc = pi->adapter;
3029 	int rc;
3030 
3031 	/* Detach the extra VIs first. */
3032 	rc = bus_generic_detach(dev);
3033 	if (rc)
3034 		return (rc);
3035 
3036 	sysctl_ctx_free(&pi->ctx);
3037 	begin_vi_detach(sc, &pi->vi[0]);
3038 	if (pi->flags & HAS_TRACEQ) {
3039 		sc->traceq = -1;	/* cloner should not create ifnet */
3040 		t4_tracer_port_detach(sc);
3041 	}
3042 	cxgbe_vi_detach(&pi->vi[0]);
3043 	ifmedia_removeall(&pi->media);
3044 	end_vi_detach(sc, &pi->vi[0]);
3045 
3046 	return (0);
3047 }
3048 
3049 static void
3050 cxgbe_init(void *arg)
3051 {
3052 	struct vi_info *vi = arg;
3053 	struct adapter *sc = vi->adapter;
3054 
3055 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
3056 		return;
3057 	cxgbe_init_synchronized(vi);
3058 	end_synchronized_op(sc, 0);
3059 }
3060 
3061 static int
3062 cxgbe_ioctl(if_t ifp, unsigned long cmd, caddr_t data)
3063 {
3064 	int rc = 0, mtu, flags;
3065 	struct vi_info *vi = if_getsoftc(ifp);
3066 	struct port_info *pi = vi->pi;
3067 	struct adapter *sc = pi->adapter;
3068 	struct ifreq *ifr = (struct ifreq *)data;
3069 	uint32_t mask, mask2;
3070 
3071 	switch (cmd) {
3072 	case SIOCSIFMTU:
3073 		mtu = ifr->ifr_mtu;
3074 		if (mtu < ETHERMIN || mtu > MAX_MTU)
3075 			return (EINVAL);
3076 
3077 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
3078 		if (rc)
3079 			return (rc);
3080 		if_setmtu(ifp, mtu);
3081 		if (vi->flags & VI_INIT_DONE) {
3082 			t4_update_fl_bufsize(ifp);
3083 			if (hw_all_ok(sc) &&
3084 			    if_getdrvflags(ifp) & IFF_DRV_RUNNING)
3085 				rc = update_mac_settings(ifp, XGMAC_MTU);
3086 		}
3087 		end_synchronized_op(sc, 0);
3088 		break;
3089 
3090 	case SIOCSIFFLAGS:
3091 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
3092 		if (rc)
3093 			return (rc);
3094 
3095 		if (!hw_all_ok(sc)) {
3096 			rc = ENXIO;
3097 			goto fail;
3098 		}
3099 
3100 		if (if_getflags(ifp) & IFF_UP) {
3101 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
3102 				flags = vi->if_flags;
3103 				if ((if_getflags(ifp) ^ flags) &
3104 				    (IFF_PROMISC | IFF_ALLMULTI)) {
3105 					rc = update_mac_settings(ifp,
3106 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
3107 				}
3108 			} else {
3109 				rc = cxgbe_init_synchronized(vi);
3110 			}
3111 			vi->if_flags = if_getflags(ifp);
3112 		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
3113 			rc = cxgbe_uninit_synchronized(vi);
3114 		}
3115 		end_synchronized_op(sc, 0);
3116 		break;
3117 
3118 	case SIOCADDMULTI:
3119 	case SIOCDELMULTI:
3120 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
3121 		if (rc)
3122 			return (rc);
3123 		if (hw_all_ok(sc) && if_getdrvflags(ifp) & IFF_DRV_RUNNING)
3124 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
3125 		end_synchronized_op(sc, 0);
3126 		break;
3127 
3128 	case SIOCGIFCAPNV:
3129 		break;
3130 	case SIOCSIFCAPNV:
3131 	case SIOCSIFCAP:
3132 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
3133 		if (rc)
3134 			return (rc);
3135 
3136 		if (cmd == SIOCSIFCAPNV) {
3137 			const struct siocsifcapnv_driver_data *ifr_nv =
3138 			    (struct siocsifcapnv_driver_data *)data;
3139 
3140 			mask = ifr_nv->reqcap ^ if_getcapenable(ifp);
3141 			mask2 = ifr_nv->reqcap2 ^ if_getcapenable2(ifp);
3142 		} else {
3143 			mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
3144 			mask2 = 0;
3145 		}
3146 		if (mask & IFCAP_TXCSUM) {
3147 			if_togglecapenable(ifp, IFCAP_TXCSUM);
3148 			if_togglehwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP);
3149 
3150 			if (IFCAP_TSO4 & if_getcapenable(ifp) &&
3151 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
3152 				mask &= ~IFCAP_TSO4;
3153 				if_setcapenablebit(ifp, 0, IFCAP_TSO4);
3154 				if_printf(ifp,
3155 				    "tso4 disabled due to -txcsum.\n");
3156 			}
3157 		}
3158 		if (mask & IFCAP_TXCSUM_IPV6) {
3159 			if_togglecapenable(ifp, IFCAP_TXCSUM_IPV6);
3160 			if_togglehwassist(ifp, CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
3161 
3162 			if (IFCAP_TSO6 & if_getcapenable(ifp) &&
3163 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
3164 				mask &= ~IFCAP_TSO6;
3165 				if_setcapenablebit(ifp, 0, IFCAP_TSO6);
3166 				if_printf(ifp,
3167 				    "tso6 disabled due to -txcsum6.\n");
3168 			}
3169 		}
3170 		if (mask & IFCAP_RXCSUM)
3171 			if_togglecapenable(ifp, IFCAP_RXCSUM);
3172 		if (mask & IFCAP_RXCSUM_IPV6)
3173 			if_togglecapenable(ifp, IFCAP_RXCSUM_IPV6);
3174 
3175 		/*
3176 		 * Note that we leave CSUM_TSO alone (it is always set).  The
3177 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
3178 		 * sending a TSO request our way, so it's sufficient to toggle
3179 		 * IFCAP_TSOx only.
3180 		 */
3181 		if (mask & IFCAP_TSO4) {
3182 			if (!(IFCAP_TSO4 & if_getcapenable(ifp)) &&
3183 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
3184 				if_printf(ifp, "enable txcsum first.\n");
3185 				rc = EAGAIN;
3186 				goto fail;
3187 			}
3188 			if_togglecapenable(ifp, IFCAP_TSO4);
3189 		}
3190 		if (mask & IFCAP_TSO6) {
3191 			if (!(IFCAP_TSO6 & if_getcapenable(ifp)) &&
3192 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
3193 				if_printf(ifp, "enable txcsum6 first.\n");
3194 				rc = EAGAIN;
3195 				goto fail;
3196 			}
3197 			if_togglecapenable(ifp, IFCAP_TSO6);
3198 		}
3199 		if (mask & IFCAP_LRO) {
3200 #if defined(INET) || defined(INET6)
3201 			int i;
3202 			struct sge_rxq *rxq;
3203 
3204 			if_togglecapenable(ifp, IFCAP_LRO);
3205 			for_each_rxq(vi, i, rxq) {
3206 				if (if_getcapenable(ifp) & IFCAP_LRO)
3207 					rxq->iq.flags |= IQ_LRO_ENABLED;
3208 				else
3209 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
3210 			}
3211 #endif
3212 		}
3213 #ifdef TCP_OFFLOAD
3214 		if (mask & IFCAP_TOE) {
3215 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TOE;
3216 
3217 			rc = toe_capability(vi, enable);
3218 			if (rc != 0)
3219 				goto fail;
3220 
3221 			if_togglecapenable(ifp, mask);
3222 		}
3223 #endif
3224 		if (mask & IFCAP_VLAN_HWTAGGING) {
3225 			if_togglecapenable(ifp, IFCAP_VLAN_HWTAGGING);
3226 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
3227 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
3228 		}
3229 		if (mask & IFCAP_VLAN_MTU) {
3230 			if_togglecapenable(ifp, IFCAP_VLAN_MTU);
3231 
3232 			/* Need to find out how to disable auto-mtu-inflation */
3233 		}
3234 		if (mask & IFCAP_VLAN_HWTSO)
3235 			if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
3236 		if (mask & IFCAP_VLAN_HWCSUM)
3237 			if_togglecapenable(ifp, IFCAP_VLAN_HWCSUM);
3238 #ifdef RATELIMIT
3239 		if (mask & IFCAP_TXRTLMT)
3240 			if_togglecapenable(ifp, IFCAP_TXRTLMT);
3241 #endif
3242 		if (mask & IFCAP_HWRXTSTMP) {
3243 			int i;
3244 			struct sge_rxq *rxq;
3245 
3246 			if_togglecapenable(ifp, IFCAP_HWRXTSTMP);
3247 			for_each_rxq(vi, i, rxq) {
3248 				if (if_getcapenable(ifp) & IFCAP_HWRXTSTMP)
3249 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
3250 				else
3251 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
3252 			}
3253 		}
3254 		if (mask & IFCAP_MEXTPG)
3255 			if_togglecapenable(ifp, IFCAP_MEXTPG);
3256 
3257 #ifdef KERN_TLS
3258 		if (mask & IFCAP_TXTLS) {
3259 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TXTLS;
3260 
3261 			rc = ktls_capability(sc, enable);
3262 			if (rc != 0)
3263 				goto fail;
3264 
3265 			if_togglecapenable(ifp, mask & IFCAP_TXTLS);
3266 		}
3267 #endif
3268 		if (mask & IFCAP_VXLAN_HWCSUM) {
3269 			if_togglecapenable(ifp, IFCAP_VXLAN_HWCSUM);
3270 			if_togglehwassist(ifp, CSUM_INNER_IP6_UDP |
3271 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
3272 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP);
3273 		}
3274 		if (mask & IFCAP_VXLAN_HWTSO) {
3275 			if_togglecapenable(ifp, IFCAP_VXLAN_HWTSO);
3276 			if_togglehwassist(ifp, CSUM_INNER_IP6_TSO |
3277 			    CSUM_INNER_IP_TSO);
3278 		}
3279 
3280 		MPASS(mask2 == 0);
3281 		(void)mask2;
3282 
3283 #ifdef VLAN_CAPABILITIES
3284 		VLAN_CAPABILITIES(ifp);
3285 #endif
3286 fail:
3287 		end_synchronized_op(sc, 0);
3288 		break;
3289 
3290 	case SIOCSIFMEDIA:
3291 	case SIOCGIFMEDIA:
3292 	case SIOCGIFXMEDIA:
3293 		rc = ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
3294 		break;
3295 
3296 	case SIOCGI2C: {
3297 		struct ifi2creq i2c;
3298 
3299 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
3300 		if (rc != 0)
3301 			break;
3302 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
3303 			rc = EPERM;
3304 			break;
3305 		}
3306 		if (i2c.len > sizeof(i2c.data)) {
3307 			rc = EINVAL;
3308 			break;
3309 		}
3310 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
3311 		if (rc)
3312 			return (rc);
3313 		if (!hw_all_ok(sc))
3314 			rc = ENXIO;
3315 		else
3316 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
3317 			    i2c.offset, i2c.len, &i2c.data[0]);
3318 		end_synchronized_op(sc, 0);
3319 		if (rc == 0)
3320 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
3321 		break;
3322 	}
3323 
3324 	default:
3325 		rc = ether_ioctl(ifp, cmd, data);
3326 	}
3327 
3328 	return (rc);
3329 }
3330 
3331 static int
3332 cxgbe_transmit(if_t ifp, struct mbuf *m)
3333 {
3334 	struct vi_info *vi = if_getsoftc(ifp);
3335 	struct port_info *pi = vi->pi;
3336 	struct adapter *sc;
3337 	struct sge_txq *txq;
3338 	void *items[1];
3339 	int rc;
3340 
3341 	M_ASSERTPKTHDR(m);
3342 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
3343 #if defined(KERN_TLS) || defined(RATELIMIT)
3344 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
3345 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
3346 #endif
3347 
3348 	if (__predict_false(pi->link_cfg.link_ok == false)) {
3349 		m_freem(m);
3350 		return (ENETDOWN);
3351 	}
3352 
3353 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
3354 	if (__predict_false(rc != 0)) {
3355 		if (__predict_true(rc == EINPROGRESS)) {
3356 			/* queued by parse_pkt */
3357 			MPASS(m != NULL);
3358 			return (0);
3359 		}
3360 
3361 		MPASS(m == NULL);			/* was freed already */
3362 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
3363 		return (rc);
3364 	}
3365 
3366 	/* Select a txq. */
3367 	sc = vi->adapter;
3368 	txq = &sc->sge.txq[vi->first_txq];
3369 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
3370 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
3371 		    vi->rsrv_noflowq);
3372 
3373 	items[0] = m;
3374 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
3375 	if (__predict_false(rc != 0))
3376 		m_freem(m);
3377 
3378 	return (rc);
3379 }
3380 
3381 static void
3382 cxgbe_qflush(if_t ifp)
3383 {
3384 	struct vi_info *vi = if_getsoftc(ifp);
3385 	struct sge_txq *txq;
3386 	int i;
3387 
3388 	/* queues do not exist if !VI_INIT_DONE. */
3389 	if (vi->flags & VI_INIT_DONE) {
3390 		for_each_txq(vi, i, txq) {
3391 			TXQ_LOCK(txq);
3392 			txq->eq.flags |= EQ_QFLUSH;
3393 			TXQ_UNLOCK(txq);
3394 			while (!mp_ring_is_idle(txq->r)) {
3395 				mp_ring_check_drainage(txq->r, 4096);
3396 				pause("qflush", 1);
3397 			}
3398 			TXQ_LOCK(txq);
3399 			txq->eq.flags &= ~EQ_QFLUSH;
3400 			TXQ_UNLOCK(txq);
3401 		}
3402 	}
3403 	if_qflush(ifp);
3404 }
3405 
3406 static uint64_t
3407 vi_get_counter(if_t ifp, ift_counter c)
3408 {
3409 	struct vi_info *vi = if_getsoftc(ifp);
3410 	struct fw_vi_stats_vf *s = &vi->stats;
3411 
3412 	mtx_lock(&vi->tick_mtx);
3413 	vi_refresh_stats(vi);
3414 	mtx_unlock(&vi->tick_mtx);
3415 
3416 	switch (c) {
3417 	case IFCOUNTER_IPACKETS:
3418 		return (s->rx_bcast_frames + s->rx_mcast_frames +
3419 		    s->rx_ucast_frames);
3420 	case IFCOUNTER_IERRORS:
3421 		return (s->rx_err_frames);
3422 	case IFCOUNTER_OPACKETS:
3423 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3424 		    s->tx_ucast_frames + s->tx_offload_frames);
3425 	case IFCOUNTER_OERRORS:
3426 		return (s->tx_drop_frames);
3427 	case IFCOUNTER_IBYTES:
3428 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3429 		    s->rx_ucast_bytes);
3430 	case IFCOUNTER_OBYTES:
3431 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3432 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3433 	case IFCOUNTER_IMCASTS:
3434 		return (s->rx_mcast_frames);
3435 	case IFCOUNTER_OMCASTS:
3436 		return (s->tx_mcast_frames);
3437 	case IFCOUNTER_OQDROPS: {
3438 		uint64_t drops;
3439 
3440 		drops = 0;
3441 		if (vi->flags & VI_INIT_DONE) {
3442 			int i;
3443 			struct sge_txq *txq;
3444 
3445 			for_each_txq(vi, i, txq)
3446 				drops += counter_u64_fetch(txq->r->dropped);
3447 		}
3448 
3449 		return (drops);
3450 
3451 	}
3452 
3453 	default:
3454 		return (if_get_counter_default(ifp, c));
3455 	}
3456 }
3457 
3458 static uint64_t
3459 cxgbe_get_counter(if_t ifp, ift_counter c)
3460 {
3461 	struct vi_info *vi = if_getsoftc(ifp);
3462 	struct port_info *pi = vi->pi;
3463 	struct port_stats *s = &pi->stats;
3464 
3465 	mtx_lock(&vi->tick_mtx);
3466 	cxgbe_refresh_stats(vi);
3467 	mtx_unlock(&vi->tick_mtx);
3468 
3469 	switch (c) {
3470 	case IFCOUNTER_IPACKETS:
3471 		return (s->rx_frames);
3472 
3473 	case IFCOUNTER_IERRORS:
3474 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3475 		    s->rx_fcs_err + s->rx_len_err);
3476 
3477 	case IFCOUNTER_OPACKETS:
3478 		return (s->tx_frames);
3479 
3480 	case IFCOUNTER_OERRORS:
3481 		return (s->tx_error_frames);
3482 
3483 	case IFCOUNTER_IBYTES:
3484 		return (s->rx_octets);
3485 
3486 	case IFCOUNTER_OBYTES:
3487 		return (s->tx_octets);
3488 
3489 	case IFCOUNTER_IMCASTS:
3490 		return (s->rx_mcast_frames);
3491 
3492 	case IFCOUNTER_OMCASTS:
3493 		return (s->tx_mcast_frames);
3494 
3495 	case IFCOUNTER_IQDROPS:
3496 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3497 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3498 		    s->rx_trunc3 + pi->tnl_cong_drops);
3499 
3500 	case IFCOUNTER_OQDROPS: {
3501 		uint64_t drops;
3502 
3503 		drops = s->tx_drop;
3504 		if (vi->flags & VI_INIT_DONE) {
3505 			int i;
3506 			struct sge_txq *txq;
3507 
3508 			for_each_txq(vi, i, txq)
3509 				drops += counter_u64_fetch(txq->r->dropped);
3510 		}
3511 
3512 		return (drops);
3513 
3514 	}
3515 
3516 	default:
3517 		return (if_get_counter_default(ifp, c));
3518 	}
3519 }
3520 
3521 #if defined(KERN_TLS) || defined(RATELIMIT)
3522 static int
3523 cxgbe_snd_tag_alloc(if_t ifp, union if_snd_tag_alloc_params *params,
3524     struct m_snd_tag **pt)
3525 {
3526 	int error;
3527 
3528 	switch (params->hdr.type) {
3529 #ifdef RATELIMIT
3530 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3531 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3532 		break;
3533 #endif
3534 #ifdef KERN_TLS
3535 	case IF_SND_TAG_TYPE_TLS:
3536 	{
3537 		struct vi_info *vi = if_getsoftc(ifp);
3538 
3539 		if (is_t6(vi->pi->adapter))
3540 			error = t6_tls_tag_alloc(ifp, params, pt);
3541 		else
3542 			error = t7_tls_tag_alloc(ifp, params, pt);
3543 		break;
3544 	}
3545 #endif
3546 	default:
3547 		error = EOPNOTSUPP;
3548 	}
3549 	return (error);
3550 }
3551 #endif
3552 
3553 /*
3554  * The kernel picks a media from the list we had provided but we still validate
3555  * the requeste.
3556  */
3557 int
3558 cxgbe_media_change(if_t ifp)
3559 {
3560 	struct vi_info *vi = if_getsoftc(ifp);
3561 	struct port_info *pi = vi->pi;
3562 	struct ifmedia *ifm = &pi->media;
3563 	struct link_config *lc = &pi->link_cfg;
3564 	struct adapter *sc = pi->adapter;
3565 	int rc;
3566 
3567 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3568 	if (rc != 0)
3569 		return (rc);
3570 	PORT_LOCK(pi);
3571 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3572 		/* ifconfig .. media autoselect */
3573 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3574 			rc = ENOTSUP; /* AN not supported by transceiver */
3575 			goto done;
3576 		}
3577 		lc->requested_aneg = AUTONEG_ENABLE;
3578 		lc->requested_speed = 0;
3579 		lc->requested_fc |= PAUSE_AUTONEG;
3580 	} else {
3581 		lc->requested_aneg = AUTONEG_DISABLE;
3582 		lc->requested_speed =
3583 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3584 		lc->requested_fc = 0;
3585 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3586 			lc->requested_fc |= PAUSE_RX;
3587 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3588 			lc->requested_fc |= PAUSE_TX;
3589 	}
3590 	if (pi->up_vis > 0 && hw_all_ok(sc)) {
3591 		fixup_link_config(pi);
3592 		rc = apply_link_config(pi);
3593 	}
3594 done:
3595 	PORT_UNLOCK(pi);
3596 	end_synchronized_op(sc, 0);
3597 	return (rc);
3598 }
3599 
3600 /*
3601  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3602  * given speed.
3603  */
3604 static int
3605 port_mword(struct port_info *pi, uint32_t speed)
3606 {
3607 
3608 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3609 	MPASS(powerof2(speed));
3610 
3611 	switch(pi->port_type) {
3612 	case FW_PORT_TYPE_BT_SGMII:
3613 	case FW_PORT_TYPE_BT_XFI:
3614 	case FW_PORT_TYPE_BT_XAUI:
3615 		/* BaseT */
3616 		switch (speed) {
3617 		case FW_PORT_CAP32_SPEED_100M:
3618 			return (IFM_100_T);
3619 		case FW_PORT_CAP32_SPEED_1G:
3620 			return (IFM_1000_T);
3621 		case FW_PORT_CAP32_SPEED_10G:
3622 			return (IFM_10G_T);
3623 		}
3624 		break;
3625 	case FW_PORT_TYPE_KX4:
3626 		if (speed == FW_PORT_CAP32_SPEED_10G)
3627 			return (IFM_10G_KX4);
3628 		break;
3629 	case FW_PORT_TYPE_CX4:
3630 		if (speed == FW_PORT_CAP32_SPEED_10G)
3631 			return (IFM_10G_CX4);
3632 		break;
3633 	case FW_PORT_TYPE_KX:
3634 		if (speed == FW_PORT_CAP32_SPEED_1G)
3635 			return (IFM_1000_KX);
3636 		break;
3637 	case FW_PORT_TYPE_KR:
3638 	case FW_PORT_TYPE_BP_AP:
3639 	case FW_PORT_TYPE_BP4_AP:
3640 	case FW_PORT_TYPE_BP40_BA:
3641 	case FW_PORT_TYPE_KR4_100G:
3642 	case FW_PORT_TYPE_KR_SFP28:
3643 	case FW_PORT_TYPE_KR_XLAUI:
3644 		switch (speed) {
3645 		case FW_PORT_CAP32_SPEED_1G:
3646 			return (IFM_1000_KX);
3647 		case FW_PORT_CAP32_SPEED_10G:
3648 			return (IFM_10G_KR);
3649 		case FW_PORT_CAP32_SPEED_25G:
3650 			return (IFM_25G_KR);
3651 		case FW_PORT_CAP32_SPEED_40G:
3652 			return (IFM_40G_KR4);
3653 		case FW_PORT_CAP32_SPEED_50G:
3654 			return (IFM_50G_KR2);
3655 		case FW_PORT_CAP32_SPEED_100G:
3656 			return (IFM_100G_KR4);
3657 		}
3658 		break;
3659 	case FW_PORT_TYPE_FIBER_XFI:
3660 	case FW_PORT_TYPE_FIBER_XAUI:
3661 	case FW_PORT_TYPE_SFP:
3662 	case FW_PORT_TYPE_QSFP_10G:
3663 	case FW_PORT_TYPE_QSA:
3664 	case FW_PORT_TYPE_QSFP:
3665 	case FW_PORT_TYPE_CR4_QSFP:
3666 	case FW_PORT_TYPE_CR_QSFP:
3667 	case FW_PORT_TYPE_CR2_QSFP:
3668 	case FW_PORT_TYPE_SFP28:
3669 	case FW_PORT_TYPE_SFP56:
3670 	case FW_PORT_TYPE_QSFP56:
3671 	case FW_PORT_TYPE_QSFPDD:
3672 		/* Pluggable transceiver */
3673 		switch (pi->mod_type) {
3674 		case FW_PORT_MOD_TYPE_LR:
3675 		case FW_PORT_MOD_TYPE_LR_SIMPLEX:
3676 			switch (speed) {
3677 			case FW_PORT_CAP32_SPEED_1G:
3678 				return (IFM_1000_LX);
3679 			case FW_PORT_CAP32_SPEED_10G:
3680 				return (IFM_10G_LR);
3681 			case FW_PORT_CAP32_SPEED_25G:
3682 				return (IFM_25G_LR);
3683 			case FW_PORT_CAP32_SPEED_40G:
3684 				return (IFM_40G_LR4);
3685 			case FW_PORT_CAP32_SPEED_50G:
3686 				return (IFM_50G_LR2);
3687 			case FW_PORT_CAP32_SPEED_100G:
3688 				return (IFM_100G_LR4);
3689 			case FW_PORT_CAP32_SPEED_200G:
3690 				return (IFM_200G_LR4);
3691 			case FW_PORT_CAP32_SPEED_400G:
3692 				return (IFM_400G_LR8);
3693 			}
3694 			break;
3695 		case FW_PORT_MOD_TYPE_SR:
3696 			switch (speed) {
3697 			case FW_PORT_CAP32_SPEED_1G:
3698 				return (IFM_1000_SX);
3699 			case FW_PORT_CAP32_SPEED_10G:
3700 				return (IFM_10G_SR);
3701 			case FW_PORT_CAP32_SPEED_25G:
3702 				return (IFM_25G_SR);
3703 			case FW_PORT_CAP32_SPEED_40G:
3704 				return (IFM_40G_SR4);
3705 			case FW_PORT_CAP32_SPEED_50G:
3706 				return (IFM_50G_SR2);
3707 			case FW_PORT_CAP32_SPEED_100G:
3708 				return (IFM_100G_SR4);
3709 			case FW_PORT_CAP32_SPEED_200G:
3710 				return (IFM_200G_SR4);
3711 			case FW_PORT_CAP32_SPEED_400G:
3712 				return (IFM_400G_SR8);
3713 			}
3714 			break;
3715 		case FW_PORT_MOD_TYPE_ER:
3716 			if (speed == FW_PORT_CAP32_SPEED_10G)
3717 				return (IFM_10G_ER);
3718 			break;
3719 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3720 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3721 			switch (speed) {
3722 			case FW_PORT_CAP32_SPEED_1G:
3723 				return (IFM_1000_CX);
3724 			case FW_PORT_CAP32_SPEED_10G:
3725 				return (IFM_10G_TWINAX);
3726 			case FW_PORT_CAP32_SPEED_25G:
3727 				return (IFM_25G_CR);
3728 			case FW_PORT_CAP32_SPEED_40G:
3729 				return (IFM_40G_CR4);
3730 			case FW_PORT_CAP32_SPEED_50G:
3731 				return (IFM_50G_CR2);
3732 			case FW_PORT_CAP32_SPEED_100G:
3733 				return (IFM_100G_CR4);
3734 			case FW_PORT_CAP32_SPEED_200G:
3735 				return (IFM_200G_CR4_PAM4);
3736 			case FW_PORT_CAP32_SPEED_400G:
3737 				return (IFM_400G_CR8);
3738 			}
3739 			break;
3740 		case FW_PORT_MOD_TYPE_LRM:
3741 			if (speed == FW_PORT_CAP32_SPEED_10G)
3742 				return (IFM_10G_LRM);
3743 			break;
3744 		case FW_PORT_MOD_TYPE_DR:
3745 			if (speed == FW_PORT_CAP32_SPEED_100G)
3746 				return (IFM_100G_DR);
3747 			if (speed == FW_PORT_CAP32_SPEED_200G)
3748 				return (IFM_200G_DR4);
3749 			if (speed == FW_PORT_CAP32_SPEED_400G)
3750 				return (IFM_400G_DR4);
3751 			break;
3752 		case FW_PORT_MOD_TYPE_NA:
3753 			MPASS(0);	/* Not pluggable? */
3754 			/* fall through */
3755 		case FW_PORT_MOD_TYPE_ERROR:
3756 		case FW_PORT_MOD_TYPE_UNKNOWN:
3757 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3758 			break;
3759 		case FW_PORT_MOD_TYPE_NONE:
3760 			return (IFM_NONE);
3761 		}
3762 		break;
3763 	case FW_PORT_TYPE_KR4_200G: {
3764 		/*
3765 		 * Pre-T7 firmware used M_FW_PORT_CMD_PTYPE for PORT_TYPE_NONE
3766 		 * and driver needs to deal with both.
3767 		 */
3768 		_Static_assert(M_FW_PORT_CMD_PTYPE == FW_PORT_TYPE_KR4_200G,
3769 		    "driver/firmware mismatch");
3770 		if (chip_id(pi->adapter) < CHELSIO_T7)
3771 			return (IFM_NONE);
3772 		return (IFM_200G_KR4_PAM4);
3773 	}
3774 	case FW_PORT_TYPE_NONE:
3775 		return (IFM_NONE);
3776 	}
3777 
3778 	return (IFM_UNKNOWN);
3779 }
3780 
3781 void
3782 cxgbe_media_status(if_t ifp, struct ifmediareq *ifmr)
3783 {
3784 	struct vi_info *vi = if_getsoftc(ifp);
3785 	struct port_info *pi = vi->pi;
3786 	struct adapter *sc = pi->adapter;
3787 	struct link_config *lc = &pi->link_cfg;
3788 
3789 	if (begin_synchronized_op(sc, vi , SLEEP_OK | INTR_OK, "t4med") != 0)
3790 		return;
3791 	PORT_LOCK(pi);
3792 
3793 	if (pi->up_vis == 0 && hw_all_ok(sc)) {
3794 		/*
3795 		 * If all the interfaces are administratively down the firmware
3796 		 * does not report transceiver changes.  Refresh port info here
3797 		 * so that ifconfig displays accurate ifmedia at all times.
3798 		 * This is the only reason we have a synchronized op in this
3799 		 * function.  Just PORT_LOCK would have been enough otherwise.
3800 		 */
3801 		t4_update_port_info(pi);
3802 		build_medialist(pi);
3803 	}
3804 
3805 	/* ifm_status */
3806 	ifmr->ifm_status = IFM_AVALID;
3807 	if (lc->link_ok == false)
3808 		goto done;
3809 	ifmr->ifm_status |= IFM_ACTIVE;
3810 
3811 	/* ifm_active */
3812 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3813 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3814 	if (lc->fc & PAUSE_RX)
3815 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3816 	if (lc->fc & PAUSE_TX)
3817 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3818 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3819 done:
3820 	PORT_UNLOCK(pi);
3821 	end_synchronized_op(sc, 0);
3822 }
3823 
3824 static int
3825 vcxgbe_probe(device_t dev)
3826 {
3827 	struct vi_info *vi = device_get_softc(dev);
3828 
3829 	device_set_descf(dev, "port %d vi %td", vi->pi->port_id,
3830 	    vi - vi->pi->vi);
3831 
3832 	return (BUS_PROBE_DEFAULT);
3833 }
3834 
3835 static int
3836 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3837 {
3838 	int func, index, rc;
3839 	uint32_t param, val;
3840 
3841 	ASSERT_SYNCHRONIZED_OP(sc);
3842 
3843 	index = vi - pi->vi;
3844 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3845 	KASSERT(index < nitems(vi_mac_funcs),
3846 	    ("%s: VI %s doesn't have a MAC func", __func__,
3847 	    device_get_nameunit(vi->dev)));
3848 	func = vi_mac_funcs[index];
3849 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->hw_port, sc->pf, 0, 1,
3850 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3851 	if (rc < 0) {
3852 		CH_ERR(vi, "failed to allocate virtual interface %d"
3853 		    "for port %d: %d\n", index, pi->port_id, -rc);
3854 		return (-rc);
3855 	}
3856 	vi->viid = rc;
3857 
3858 	if (vi->rss_size == 1) {
3859 		/*
3860 		 * This VI didn't get a slice of the RSS table.  Reduce the
3861 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3862 		 * configuration file (nvi, rssnvi for this PF) if this is a
3863 		 * problem.
3864 		 */
3865 		device_printf(vi->dev, "RSS table not available.\n");
3866 		vi->rss_base = 0xffff;
3867 
3868 		return (0);
3869 	}
3870 
3871 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3872 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3873 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3874 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3875 	if (rc)
3876 		vi->rss_base = 0xffff;
3877 	else {
3878 		MPASS((val >> 16) == vi->rss_size);
3879 		vi->rss_base = val & 0xffff;
3880 	}
3881 
3882 	return (0);
3883 }
3884 
3885 static int
3886 vcxgbe_attach(device_t dev)
3887 {
3888 	struct vi_info *vi;
3889 	struct port_info *pi;
3890 	struct adapter *sc;
3891 	int rc;
3892 
3893 	vi = device_get_softc(dev);
3894 	pi = vi->pi;
3895 	sc = pi->adapter;
3896 
3897 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3898 	if (rc)
3899 		return (rc);
3900 	rc = alloc_extra_vi(sc, pi, vi);
3901 	end_synchronized_op(sc, 0);
3902 	if (rc)
3903 		return (rc);
3904 
3905 	cxgbe_vi_attach(dev, vi);
3906 
3907 	return (0);
3908 }
3909 
3910 static int
3911 vcxgbe_detach(device_t dev)
3912 {
3913 	struct vi_info *vi;
3914 	struct adapter *sc;
3915 
3916 	vi = device_get_softc(dev);
3917 	sc = vi->adapter;
3918 
3919 	begin_vi_detach(sc, vi);
3920 	cxgbe_vi_detach(vi);
3921 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3922 	end_vi_detach(sc, vi);
3923 
3924 	return (0);
3925 }
3926 
3927 static struct callout fatal_callout;
3928 static struct taskqueue *reset_tq;
3929 
3930 static void
3931 delayed_panic(void *arg)
3932 {
3933 	struct adapter *sc = arg;
3934 
3935 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3936 }
3937 
3938 static void
3939 fatal_error_task(void *arg, int pending)
3940 {
3941 	struct adapter *sc = arg;
3942 	int rc;
3943 
3944 	if (atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_CIM_ERR))) {
3945 		dump_cim_regs(sc);
3946 		dump_cimla(sc);
3947 		dump_devlog(sc);
3948 	}
3949 
3950 	if (t4_reset_on_fatal_err) {
3951 		CH_ALERT(sc, "resetting adapter after fatal error.\n");
3952 		rc = reset_adapter(sc);
3953 		if (rc == 0 && t4_panic_on_fatal_err) {
3954 			CH_ALERT(sc, "reset was successful, "
3955 			    "system will NOT panic.\n");
3956 			return;
3957 		}
3958 	}
3959 
3960 	if (t4_panic_on_fatal_err) {
3961 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3962 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3963 	}
3964 }
3965 
3966 void
3967 t4_fatal_err(struct adapter *sc, bool fw_error)
3968 {
3969 	stop_adapter(sc);
3970 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_FATAL_ERR)))
3971 		return;
3972 	if (fw_error) {
3973 		/*
3974 		 * We are here because of a firmware error/timeout and not
3975 		 * because of a hardware interrupt.  It is possible (although
3976 		 * not very likely) that an error interrupt was also raised but
3977 		 * this thread ran first and inhibited t4_intr_err.  We walk the
3978 		 * main INT_CAUSE registers here to make sure we haven't missed
3979 		 * anything interesting.
3980 		 */
3981 		t4_slow_intr_handler(sc, sc->intr_flags);
3982 		atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
3983 	}
3984 	t4_report_fw_error(sc);
3985 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped (%d).\n",
3986 	    device_get_nameunit(sc->dev), fw_error);
3987 	taskqueue_enqueue(reset_tq, &sc->fatal_error_task);
3988 }
3989 
3990 void
3991 t4_add_adapter(struct adapter *sc)
3992 {
3993 	sx_xlock(&t4_list_lock);
3994 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3995 	sx_xunlock(&t4_list_lock);
3996 }
3997 
3998 int
3999 t4_map_bars_0_and_4(struct adapter *sc)
4000 {
4001 	sc->regs_rid = PCIR_BAR(0);
4002 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
4003 	    &sc->regs_rid, RF_ACTIVE);
4004 	if (sc->regs_res == NULL) {
4005 		device_printf(sc->dev, "cannot map registers.\n");
4006 		return (ENXIO);
4007 	}
4008 	sc->mmio_len = rman_get_size(sc->regs_res);
4009 	setbit(&sc->doorbells, DOORBELL_KDB);
4010 
4011 	sc->msix_rid = PCIR_BAR(4);
4012 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
4013 	    &sc->msix_rid, RF_ACTIVE);
4014 	if (sc->msix_res == NULL) {
4015 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
4016 		return (ENXIO);
4017 	}
4018 
4019 	return (0);
4020 }
4021 
4022 int
4023 t4_map_bar_2(struct adapter *sc)
4024 {
4025 
4026 	/*
4027 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
4028 	 * to map it if RDMA is disabled.
4029 	 */
4030 	if (is_t4(sc) && sc->rdmacaps == 0)
4031 		return (0);
4032 
4033 	sc->udbs_rid = PCIR_BAR(2);
4034 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
4035 	    &sc->udbs_rid, RF_ACTIVE);
4036 	if (sc->udbs_res == NULL) {
4037 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
4038 		return (ENXIO);
4039 	}
4040 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
4041 
4042 	if (chip_id(sc) >= CHELSIO_T5) {
4043 		setbit(&sc->doorbells, DOORBELL_UDB);
4044 #if defined(__i386__) || defined(__amd64__)
4045 		if (t5_write_combine) {
4046 			int rc, mode;
4047 
4048 			/*
4049 			 * Enable write combining on BAR2.  This is the
4050 			 * userspace doorbell BAR and is split into 128B
4051 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
4052 			 * with an egress queue.  The first 64B has the doorbell
4053 			 * and the second 64B can be used to submit a tx work
4054 			 * request with an implicit doorbell.
4055 			 */
4056 
4057 			rc = pmap_change_attr(__DEVOLATILE(void *, sc->udbs_base),
4058 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
4059 			if (rc == 0) {
4060 				clrbit(&sc->doorbells, DOORBELL_UDB);
4061 				setbit(&sc->doorbells, DOORBELL_WCWR);
4062 				setbit(&sc->doorbells, DOORBELL_UDBWC);
4063 			} else {
4064 				device_printf(sc->dev,
4065 				    "couldn't enable write combining: %d\n",
4066 				    rc);
4067 			}
4068 
4069 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
4070 			t4_write_reg(sc, A_SGE_STAT_CFG,
4071 			    V_STATSOURCE_T5(7) | mode);
4072 		}
4073 #endif
4074 	}
4075 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
4076 
4077 	return (0);
4078 }
4079 
4080 int
4081 t4_adj_doorbells(struct adapter *sc)
4082 {
4083 	if ((sc->doorbells & t4_doorbells_allowed) != 0) {
4084 		sc->doorbells &= t4_doorbells_allowed;
4085 		return (0);
4086 	}
4087 	CH_ERR(sc, "No usable doorbell (available = 0x%x, allowed = 0x%x).\n",
4088 	       sc->doorbells, t4_doorbells_allowed);
4089 	return (EINVAL);
4090 }
4091 
4092 struct memwin_init {
4093 	uint32_t base;
4094 	uint32_t aperture;
4095 };
4096 
4097 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
4098 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
4099 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
4100 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
4101 };
4102 
4103 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
4104 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
4105 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
4106 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
4107 };
4108 
4109 static void
4110 setup_memwin(struct adapter *sc)
4111 {
4112 	const struct memwin_init *mw_init;
4113 	struct memwin *mw;
4114 	int i;
4115 	uint32_t bar0, reg;
4116 
4117 	if (is_t4(sc)) {
4118 		/*
4119 		 * Read low 32b of bar0 indirectly via the hardware backdoor
4120 		 * mechanism.  Works from within PCI passthrough environments
4121 		 * too, where rman_get_start() can return a different value.  We
4122 		 * need to program the T4 memory window decoders with the actual
4123 		 * addresses that will be coming across the PCIe link.
4124 		 */
4125 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
4126 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
4127 
4128 		mw_init = &t4_memwin[0];
4129 	} else {
4130 		/* T5+ use the relative offset inside the PCIe BAR */
4131 		bar0 = 0;
4132 
4133 		mw_init = &t5_memwin[0];
4134 	}
4135 
4136 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
4137 		if (!rw_initialized(&mw->mw_lock)) {
4138 			rw_init(&mw->mw_lock, "memory window access");
4139 			mw->mw_base = mw_init->base;
4140 			mw->mw_aperture = mw_init->aperture;
4141 			mw->mw_curpos = 0;
4142 		}
4143 		reg = chip_id(sc) > CHELSIO_T6 ?
4144 		    PCIE_MEM_ACCESS_T7_REG(A_T7_PCIE_MEM_ACCESS_BASE_WIN, i) :
4145 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i);
4146 		t4_write_reg(sc, reg, (mw->mw_base + bar0) | V_BIR(0) |
4147 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
4148 		rw_wlock(&mw->mw_lock);
4149 		position_memwin(sc, i, mw->mw_curpos);
4150 		rw_wunlock(&mw->mw_lock);
4151 	}
4152 
4153 	/* flush */
4154 	t4_read_reg(sc, reg);
4155 }
4156 
4157 /*
4158  * Positions the memory window at the given address in the card's address space.
4159  * There are some alignment requirements and the actual position may be at an
4160  * address prior to the requested address.  mw->mw_curpos always has the actual
4161  * position of the window.
4162  */
4163 static void
4164 position_memwin(struct adapter *sc, int idx, uint32_t addr)
4165 {
4166 	struct memwin *mw;
4167 	uint32_t pf, reg, val;
4168 
4169 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
4170 	mw = &sc->memwin[idx];
4171 	rw_assert(&mw->mw_lock, RA_WLOCKED);
4172 
4173 	if (is_t4(sc)) {
4174 		pf = 0;
4175 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
4176 	} else {
4177 		pf = V_PFNUM(sc->pf);
4178 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
4179 	}
4180 	if (chip_id(sc) > CHELSIO_T6) {
4181 		reg = PCIE_MEM_ACCESS_T7_REG(A_PCIE_MEM_ACCESS_OFFSET0, idx);
4182 		val = (mw->mw_curpos >> X_T7_MEMOFST_SHIFT) | pf;
4183 	} else {
4184 		reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
4185 		val = mw->mw_curpos | pf;
4186 	}
4187 	t4_write_reg(sc, reg, val);
4188 	t4_read_reg(sc, reg);	/* flush */
4189 }
4190 
4191 int
4192 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
4193     int len, int rw)
4194 {
4195 	struct memwin *mw;
4196 	uint32_t mw_end, v;
4197 
4198 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
4199 
4200 	/* Memory can only be accessed in naturally aligned 4 byte units */
4201 	if (addr & 3 || len & 3 || len <= 0)
4202 		return (EINVAL);
4203 
4204 	mw = &sc->memwin[idx];
4205 	while (len > 0) {
4206 		rw_rlock(&mw->mw_lock);
4207 		mw_end = mw->mw_curpos + mw->mw_aperture;
4208 		if (addr >= mw_end || addr < mw->mw_curpos) {
4209 			/* Will need to reposition the window */
4210 			if (!rw_try_upgrade(&mw->mw_lock)) {
4211 				rw_runlock(&mw->mw_lock);
4212 				rw_wlock(&mw->mw_lock);
4213 			}
4214 			rw_assert(&mw->mw_lock, RA_WLOCKED);
4215 			position_memwin(sc, idx, addr);
4216 			rw_downgrade(&mw->mw_lock);
4217 			mw_end = mw->mw_curpos + mw->mw_aperture;
4218 		}
4219 		rw_assert(&mw->mw_lock, RA_RLOCKED);
4220 		while (addr < mw_end && len > 0) {
4221 			if (rw == 0) {
4222 				v = t4_read_reg(sc, mw->mw_base + addr -
4223 				    mw->mw_curpos);
4224 				*val++ = le32toh(v);
4225 			} else {
4226 				v = *val++;
4227 				t4_write_reg(sc, mw->mw_base + addr -
4228 				    mw->mw_curpos, htole32(v));
4229 			}
4230 			addr += 4;
4231 			len -= 4;
4232 		}
4233 		rw_runlock(&mw->mw_lock);
4234 	}
4235 
4236 	return (0);
4237 }
4238 
4239 CTASSERT(M_TID_COOKIE == M_COOKIE);
4240 CTASSERT(MAX_ATIDS <= (M_TID_TID + 1));
4241 
4242 static void
4243 t4_init_atid_table(struct adapter *sc)
4244 {
4245 	struct tid_info *t;
4246 	int i;
4247 
4248 	t = &sc->tids;
4249 	if (t->natids == 0)
4250 		return;
4251 
4252 	MPASS(t->atid_tab == NULL);
4253 
4254 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
4255 	    M_ZERO | M_WAITOK);
4256 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
4257 	t->afree = t->atid_tab;
4258 	t->atids_in_use = 0;
4259 	t->atid_alloc_stopped = false;
4260 	for (i = 1; i < t->natids; i++)
4261 		t->atid_tab[i - 1].next = &t->atid_tab[i];
4262 	t->atid_tab[t->natids - 1].next = NULL;
4263 }
4264 
4265 static void
4266 t4_free_atid_table(struct adapter *sc)
4267 {
4268 	struct tid_info *t;
4269 
4270 	t = &sc->tids;
4271 
4272 	KASSERT(t->atids_in_use == 0,
4273 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
4274 
4275 	if (mtx_initialized(&t->atid_lock))
4276 		mtx_destroy(&t->atid_lock);
4277 	free(t->atid_tab, M_CXGBE);
4278 	t->atid_tab = NULL;
4279 }
4280 
4281 static void
4282 stop_atid_allocator(struct adapter *sc)
4283 {
4284 	struct tid_info *t = &sc->tids;
4285 
4286 	if (t->natids == 0)
4287 		return;
4288 	mtx_lock(&t->atid_lock);
4289 	t->atid_alloc_stopped = true;
4290 	mtx_unlock(&t->atid_lock);
4291 }
4292 
4293 static void
4294 restart_atid_allocator(struct adapter *sc)
4295 {
4296 	struct tid_info *t = &sc->tids;
4297 
4298 	if (t->natids == 0)
4299 		return;
4300 	mtx_lock(&t->atid_lock);
4301 	KASSERT(t->atids_in_use == 0,
4302 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
4303 	t->atid_alloc_stopped = false;
4304 	mtx_unlock(&t->atid_lock);
4305 }
4306 
4307 int
4308 alloc_atid(struct adapter *sc, void *ctx)
4309 {
4310 	struct tid_info *t = &sc->tids;
4311 	int atid = -1;
4312 
4313 	mtx_lock(&t->atid_lock);
4314 	if (t->afree && !t->atid_alloc_stopped) {
4315 		union aopen_entry *p = t->afree;
4316 
4317 		atid = p - t->atid_tab;
4318 		MPASS(atid <= M_TID_TID);
4319 		t->afree = p->next;
4320 		p->data = ctx;
4321 		t->atids_in_use++;
4322 	}
4323 	mtx_unlock(&t->atid_lock);
4324 	return (atid);
4325 }
4326 
4327 void *
4328 lookup_atid(struct adapter *sc, int atid)
4329 {
4330 	struct tid_info *t = &sc->tids;
4331 
4332 	return (t->atid_tab[atid].data);
4333 }
4334 
4335 void
4336 free_atid(struct adapter *sc, int atid)
4337 {
4338 	struct tid_info *t = &sc->tids;
4339 	union aopen_entry *p = &t->atid_tab[atid];
4340 
4341 	mtx_lock(&t->atid_lock);
4342 	p->next = t->afree;
4343 	t->afree = p;
4344 	t->atids_in_use--;
4345 	mtx_unlock(&t->atid_lock);
4346 }
4347 
4348 static void
4349 queue_tid_release(struct adapter *sc, int tid)
4350 {
4351 
4352 	CXGBE_UNIMPLEMENTED("deferred tid release");
4353 }
4354 
4355 void
4356 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
4357 {
4358 	struct wrqe *wr;
4359 	struct cpl_tid_release *req;
4360 
4361 	wr = alloc_wrqe(sizeof(*req), ctrlq);
4362 	if (wr == NULL) {
4363 		queue_tid_release(sc, tid);	/* defer */
4364 		return;
4365 	}
4366 	req = wrtod(wr);
4367 
4368 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
4369 
4370 	t4_wrq_tx(sc, wr);
4371 }
4372 
4373 static int
4374 t4_range_cmp(const void *a, const void *b)
4375 {
4376 	return ((const struct t4_range *)a)->start -
4377 	       ((const struct t4_range *)b)->start;
4378 }
4379 
4380 /*
4381  * Verify that the memory range specified by the addr/len pair is valid within
4382  * the card's address space.
4383  */
4384 static int
4385 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
4386 {
4387 	struct t4_range mem_ranges[4], *r, *next;
4388 	uint32_t em, addr_len;
4389 	int i, n, remaining;
4390 
4391 	/* Memory can only be accessed in naturally aligned 4 byte units */
4392 	if (addr & 3 || len & 3 || len == 0)
4393 		return (EINVAL);
4394 
4395 	/* Enabled memories */
4396 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4397 
4398 	r = &mem_ranges[0];
4399 	n = 0;
4400 	bzero(r, sizeof(mem_ranges));
4401 	if (em & F_EDRAM0_ENABLE) {
4402 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4403 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
4404 		if (r->size > 0) {
4405 			r->start = G_EDRAM0_BASE(addr_len) << 20;
4406 			if (addr >= r->start &&
4407 			    addr + len <= r->start + r->size)
4408 				return (0);
4409 			r++;
4410 			n++;
4411 		}
4412 	}
4413 	if (em & F_EDRAM1_ENABLE) {
4414 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4415 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
4416 		if (r->size > 0) {
4417 			r->start = G_EDRAM1_BASE(addr_len) << 20;
4418 			if (addr >= r->start &&
4419 			    addr + len <= r->start + r->size)
4420 				return (0);
4421 			r++;
4422 			n++;
4423 		}
4424 	}
4425 	if (em & F_EXT_MEM_ENABLE) {
4426 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4427 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
4428 		if (r->size > 0) {
4429 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
4430 			if (addr >= r->start &&
4431 			    addr + len <= r->start + r->size)
4432 				return (0);
4433 			r++;
4434 			n++;
4435 		}
4436 	}
4437 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
4438 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4439 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
4440 		if (r->size > 0) {
4441 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
4442 			if (addr >= r->start &&
4443 			    addr + len <= r->start + r->size)
4444 				return (0);
4445 			r++;
4446 			n++;
4447 		}
4448 	}
4449 	MPASS(n <= nitems(mem_ranges));
4450 
4451 	if (n > 1) {
4452 		/* Sort and merge the ranges. */
4453 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
4454 
4455 		/* Start from index 0 and examine the next n - 1 entries. */
4456 		r = &mem_ranges[0];
4457 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
4458 
4459 			MPASS(r->size > 0);	/* r is a valid entry. */
4460 			next = r + 1;
4461 			MPASS(next->size > 0);	/* and so is the next one. */
4462 
4463 			while (r->start + r->size >= next->start) {
4464 				/* Merge the next one into the current entry. */
4465 				r->size = max(r->start + r->size,
4466 				    next->start + next->size) - r->start;
4467 				n--;	/* One fewer entry in total. */
4468 				if (--remaining == 0)
4469 					goto done;	/* short circuit */
4470 				next++;
4471 			}
4472 			if (next != r + 1) {
4473 				/*
4474 				 * Some entries were merged into r and next
4475 				 * points to the first valid entry that couldn't
4476 				 * be merged.
4477 				 */
4478 				MPASS(next->size > 0);	/* must be valid */
4479 				memcpy(r + 1, next, remaining * sizeof(*r));
4480 #ifdef INVARIANTS
4481 				/*
4482 				 * This so that the foo->size assertion in the
4483 				 * next iteration of the loop do the right
4484 				 * thing for entries that were pulled up and are
4485 				 * no longer valid.
4486 				 */
4487 				MPASS(n < nitems(mem_ranges));
4488 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4489 				    sizeof(struct t4_range));
4490 #endif
4491 			}
4492 		}
4493 done:
4494 		/* Done merging the ranges. */
4495 		MPASS(n > 0);
4496 		r = &mem_ranges[0];
4497 		for (i = 0; i < n; i++, r++) {
4498 			if (addr >= r->start &&
4499 			    addr + len <= r->start + r->size)
4500 				return (0);
4501 		}
4502 	}
4503 
4504 	return (EFAULT);
4505 }
4506 
4507 static int
4508 fwmtype_to_hwmtype(int mtype)
4509 {
4510 
4511 	switch (mtype) {
4512 	case FW_MEMTYPE_EDC0:
4513 		return (MEM_EDC0);
4514 	case FW_MEMTYPE_EDC1:
4515 		return (MEM_EDC1);
4516 	case FW_MEMTYPE_EXTMEM:
4517 		return (MEM_MC0);
4518 	case FW_MEMTYPE_EXTMEM1:
4519 		return (MEM_MC1);
4520 	default:
4521 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4522 	}
4523 }
4524 
4525 /*
4526  * Verify that the memory range specified by the memtype/offset/len pair is
4527  * valid and lies entirely within the memtype specified.  The global address of
4528  * the start of the range is returned in addr.
4529  */
4530 static int
4531 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4532     uint32_t *addr)
4533 {
4534 	uint32_t em, addr_len, maddr;
4535 
4536 	/* Memory can only be accessed in naturally aligned 4 byte units */
4537 	if (off & 3 || len & 3 || len == 0)
4538 		return (EINVAL);
4539 
4540 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4541 	switch (fwmtype_to_hwmtype(mtype)) {
4542 	case MEM_EDC0:
4543 		if (!(em & F_EDRAM0_ENABLE))
4544 			return (EINVAL);
4545 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4546 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4547 		break;
4548 	case MEM_EDC1:
4549 		if (!(em & F_EDRAM1_ENABLE))
4550 			return (EINVAL);
4551 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4552 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4553 		break;
4554 	case MEM_MC:
4555 		if (!(em & F_EXT_MEM_ENABLE))
4556 			return (EINVAL);
4557 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4558 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4559 		break;
4560 	case MEM_MC1:
4561 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4562 			return (EINVAL);
4563 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4564 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4565 		break;
4566 	default:
4567 		return (EINVAL);
4568 	}
4569 
4570 	*addr = maddr + off;	/* global address */
4571 	return (validate_mem_range(sc, *addr, len));
4572 }
4573 
4574 static int
4575 fixup_devlog_ncores_params(struct adapter *sc)
4576 {
4577 	struct devlog_params *dparams = &sc->params.devlog;
4578 	int rc;
4579 
4580 #ifdef INVARIANTS
4581 	if (sc->params.ncores > 1)
4582 		MPASS(chip_id(sc) >= CHELSIO_T7);
4583 #endif
4584 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4585 	    dparams->size, &dparams->addr);
4586 
4587 	return (rc);
4588 }
4589 
4590 static void
4591 update_nirq(struct intrs_and_queues *iaq, int nports)
4592 {
4593 
4594 	iaq->nirq = T4_EXTRA_INTR;
4595 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4596 	iaq->nirq += nports * iaq->nofldrxq;
4597 	iaq->nirq += nports * (iaq->num_vis - 1) *
4598 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4599 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4600 }
4601 
4602 /*
4603  * Adjust requirements to fit the number of interrupts available.
4604  */
4605 static void
4606 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4607     int navail)
4608 {
4609 	int old_nirq;
4610 	const int nports = sc->params.nports;
4611 
4612 	MPASS(nports > 0);
4613 	MPASS(navail > 0);
4614 
4615 	bzero(iaq, sizeof(*iaq));
4616 	iaq->intr_type = itype;
4617 	iaq->num_vis = t4_num_vis;
4618 	iaq->ntxq = t4_ntxq;
4619 	iaq->ntxq_vi = t4_ntxq_vi;
4620 	iaq->nrxq = t4_nrxq;
4621 	iaq->nrxq_vi = t4_nrxq_vi;
4622 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4623 	if (is_offload(sc) || is_ethoffload(sc)) {
4624 		if (sc->params.tid_qid_sel_mask == 0) {
4625 			iaq->nofldtxq = t4_nofldtxq;
4626 			iaq->nofldtxq_vi = t4_nofldtxq_vi;
4627 		} else {
4628 			iaq->nofldtxq = roundup(t4_nofldtxq, sc->params.ncores);
4629 			iaq->nofldtxq_vi = roundup(t4_nofldtxq_vi,
4630 			    sc->params.ncores);
4631 			if (iaq->nofldtxq != t4_nofldtxq)
4632 				device_printf(sc->dev,
4633 				    "nofldtxq updated (%d -> %d) for correct"
4634 				    " operation with %d firmware cores.\n",
4635 				    t4_nofldtxq, iaq->nofldtxq,
4636 				    sc->params.ncores);
4637 			if (iaq->num_vis > 1 &&
4638 			    iaq->nofldtxq_vi != t4_nofldtxq_vi)
4639 				device_printf(sc->dev,
4640 				    "nofldtxq_vi updated (%d -> %d) for correct"
4641 				    " operation with %d firmware cores.\n",
4642 				    t4_nofldtxq_vi, iaq->nofldtxq_vi,
4643 				    sc->params.ncores);
4644 		}
4645 	}
4646 #endif
4647 #ifdef TCP_OFFLOAD
4648 	if (is_offload(sc)) {
4649 		iaq->nofldrxq = t4_nofldrxq;
4650 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4651 	}
4652 #endif
4653 #ifdef DEV_NETMAP
4654 	if (t4_native_netmap & NN_MAIN_VI) {
4655 		iaq->nnmtxq = t4_nnmtxq;
4656 		iaq->nnmrxq = t4_nnmrxq;
4657 	}
4658 	if (t4_native_netmap & NN_EXTRA_VI) {
4659 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4660 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4661 	}
4662 #endif
4663 
4664 	update_nirq(iaq, nports);
4665 	if (iaq->nirq <= navail &&
4666 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4667 		/*
4668 		 * This is the normal case -- there are enough interrupts for
4669 		 * everything.
4670 		 */
4671 		goto done;
4672 	}
4673 
4674 	/*
4675 	 * If extra VIs have been configured try reducing their count and see if
4676 	 * that works.
4677 	 */
4678 	while (iaq->num_vis > 1) {
4679 		iaq->num_vis--;
4680 		update_nirq(iaq, nports);
4681 		if (iaq->nirq <= navail &&
4682 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4683 			device_printf(sc->dev, "virtual interfaces per port "
4684 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4685 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4686 			    "itype %d, navail %u, nirq %d.\n",
4687 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4688 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4689 			    itype, navail, iaq->nirq);
4690 			goto done;
4691 		}
4692 	}
4693 
4694 	/*
4695 	 * Extra VIs will not be created.  Log a message if they were requested.
4696 	 */
4697 	MPASS(iaq->num_vis == 1);
4698 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4699 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4700 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4701 	if (iaq->num_vis != t4_num_vis) {
4702 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4703 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4704 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4705 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4706 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4707 	}
4708 
4709 	/*
4710 	 * Keep reducing the number of NIC rx queues to the next lower power of
4711 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4712 	 * if that works.
4713 	 */
4714 	do {
4715 		if (iaq->nrxq > 1) {
4716 			iaq->nrxq = rounddown_pow_of_two(iaq->nrxq - 1);
4717 			if (iaq->nnmrxq > iaq->nrxq)
4718 				iaq->nnmrxq = iaq->nrxq;
4719 		}
4720 		if (iaq->nofldrxq > 1)
4721 			iaq->nofldrxq >>= 1;
4722 
4723 		old_nirq = iaq->nirq;
4724 		update_nirq(iaq, nports);
4725 		if (iaq->nirq <= navail &&
4726 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4727 			device_printf(sc->dev, "running with reduced number of "
4728 			    "rx queues because of shortage of interrupts.  "
4729 			    "nrxq=%u, nofldrxq=%u.  "
4730 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4731 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4732 			goto done;
4733 		}
4734 	} while (old_nirq != iaq->nirq);
4735 
4736 	/* One interrupt for everything.  Ugh. */
4737 	device_printf(sc->dev, "running with minimal number of queues.  "
4738 	    "itype %d, navail %u.\n", itype, navail);
4739 	iaq->nirq = 1;
4740 	iaq->nrxq = 1;
4741 	iaq->ntxq = 1;
4742 	if (iaq->nofldrxq > 0) {
4743 		iaq->nofldrxq = 1;
4744 		iaq->nofldtxq = 1;
4745 		if (sc->params.tid_qid_sel_mask == 0)
4746 			iaq->nofldtxq = 1;
4747 		else
4748 			iaq->nofldtxq = sc->params.ncores;
4749 	}
4750 	iaq->nnmtxq = 0;
4751 	iaq->nnmrxq = 0;
4752 done:
4753 	MPASS(iaq->num_vis > 0);
4754 	if (iaq->num_vis > 1) {
4755 		MPASS(iaq->nrxq_vi > 0);
4756 		MPASS(iaq->ntxq_vi > 0);
4757 	}
4758 	MPASS(iaq->nirq > 0);
4759 	MPASS(iaq->nrxq > 0);
4760 	MPASS(iaq->ntxq > 0);
4761 	if (itype == INTR_MSI)
4762 		MPASS(powerof2(iaq->nirq));
4763 	if (sc->params.tid_qid_sel_mask != 0)
4764 		MPASS(iaq->nofldtxq % sc->params.ncores == 0);
4765 }
4766 
4767 static int
4768 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4769 {
4770 	int rc, itype, navail, nalloc;
4771 
4772 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4773 
4774 		if ((itype & t4_intr_types) == 0)
4775 			continue;	/* not allowed */
4776 
4777 		if (itype == INTR_MSIX)
4778 			navail = pci_msix_count(sc->dev);
4779 		else if (itype == INTR_MSI)
4780 			navail = pci_msi_count(sc->dev);
4781 		else
4782 			navail = 1;
4783 restart:
4784 		if (navail == 0)
4785 			continue;
4786 
4787 		calculate_iaq(sc, iaq, itype, navail);
4788 		nalloc = iaq->nirq;
4789 		rc = 0;
4790 		if (itype == INTR_MSIX)
4791 			rc = pci_alloc_msix(sc->dev, &nalloc);
4792 		else if (itype == INTR_MSI)
4793 			rc = pci_alloc_msi(sc->dev, &nalloc);
4794 
4795 		if (rc == 0 && nalloc > 0) {
4796 			if (nalloc == iaq->nirq)
4797 				return (0);
4798 
4799 			/*
4800 			 * Didn't get the number requested.  Use whatever number
4801 			 * the kernel is willing to allocate.
4802 			 */
4803 			device_printf(sc->dev, "fewer vectors than requested, "
4804 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4805 			    itype, iaq->nirq, nalloc);
4806 			pci_release_msi(sc->dev);
4807 			navail = nalloc;
4808 			goto restart;
4809 		}
4810 
4811 		device_printf(sc->dev,
4812 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4813 		    itype, rc, iaq->nirq, nalloc);
4814 	}
4815 
4816 	device_printf(sc->dev,
4817 	    "failed to find a usable interrupt type.  "
4818 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4819 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4820 
4821 	return (ENXIO);
4822 }
4823 
4824 #define FW_VERSION(chip) ( \
4825     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4826     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4827     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4828     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4829 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4830 
4831 /* Just enough of fw_hdr to cover all version info. */
4832 struct fw_h {
4833 	__u8	ver;
4834 	__u8	chip;
4835 	__be16	len512;
4836 	__be32	fw_ver;
4837 	__be32	tp_microcode_ver;
4838 	__u8	intfver_nic;
4839 	__u8	intfver_vnic;
4840 	__u8	intfver_ofld;
4841 	__u8	intfver_ri;
4842 	__u8	intfver_iscsipdu;
4843 	__u8	intfver_iscsi;
4844 	__u8	intfver_fcoepdu;
4845 	__u8	intfver_fcoe;
4846 };
4847 /* Spot check a couple of fields. */
4848 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4849 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4850 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4851 
4852 struct fw_info {
4853 	uint8_t chip;
4854 	char *kld_name;
4855 	char *fw_mod_name;
4856 	struct fw_h fw_h;
4857 } fw_info[] = {
4858 	{
4859 		.chip = CHELSIO_T4,
4860 		.kld_name = "t4fw_cfg",
4861 		.fw_mod_name = "t4fw",
4862 		.fw_h = {
4863 			.chip = FW_HDR_CHIP_T4,
4864 			.fw_ver = htobe32(FW_VERSION(T4)),
4865 			.intfver_nic = FW_INTFVER(T4, NIC),
4866 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4867 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4868 			.intfver_ri = FW_INTFVER(T4, RI),
4869 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4870 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4871 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4872 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4873 		},
4874 	}, {
4875 		.chip = CHELSIO_T5,
4876 		.kld_name = "t5fw_cfg",
4877 		.fw_mod_name = "t5fw",
4878 		.fw_h = {
4879 			.chip = FW_HDR_CHIP_T5,
4880 			.fw_ver = htobe32(FW_VERSION(T5)),
4881 			.intfver_nic = FW_INTFVER(T5, NIC),
4882 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4883 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4884 			.intfver_ri = FW_INTFVER(T5, RI),
4885 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4886 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4887 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4888 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4889 		},
4890 	}, {
4891 		.chip = CHELSIO_T6,
4892 		.kld_name = "t6fw_cfg",
4893 		.fw_mod_name = "t6fw",
4894 		.fw_h = {
4895 			.chip = FW_HDR_CHIP_T6,
4896 			.fw_ver = htobe32(FW_VERSION(T6)),
4897 			.intfver_nic = FW_INTFVER(T6, NIC),
4898 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4899 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4900 			.intfver_ri = FW_INTFVER(T6, RI),
4901 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4902 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4903 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4904 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4905 		},
4906 	}, {
4907 		.chip = CHELSIO_T7,
4908 		.kld_name = "t7fw_cfg",
4909 		.fw_mod_name = "t7fw",
4910 		.fw_h = {
4911 			.chip = FW_HDR_CHIP_T7,
4912 			.fw_ver = htobe32(FW_VERSION(T7)),
4913 			.intfver_nic = FW_INTFVER(T7, NIC),
4914 			.intfver_vnic = FW_INTFVER(T7, VNIC),
4915 			.intfver_ofld = FW_INTFVER(T7, OFLD),
4916 			.intfver_ri = FW_INTFVER(T7, RI),
4917 			.intfver_iscsipdu = FW_INTFVER(T7, ISCSIPDU),
4918 			.intfver_iscsi = FW_INTFVER(T7, ISCSI),
4919 			.intfver_fcoepdu = FW_INTFVER(T7, FCOEPDU),
4920 			.intfver_fcoe = FW_INTFVER(T7, FCOE),
4921 		},
4922 	}
4923 };
4924 
4925 static struct fw_info *
4926 find_fw_info(int chip)
4927 {
4928 	int i;
4929 
4930 	for (i = 0; i < nitems(fw_info); i++) {
4931 		if (fw_info[i].chip == chip)
4932 			return (&fw_info[i]);
4933 	}
4934 	return (NULL);
4935 }
4936 
4937 /*
4938  * Is the given firmware API compatible with the one the driver was compiled
4939  * with?
4940  */
4941 static int
4942 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4943 {
4944 
4945 	/* short circuit if it's the exact same firmware version */
4946 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4947 		return (1);
4948 
4949 	/*
4950 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4951 	 * features that are supported in the driver.
4952 	 */
4953 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4954 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4955 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4956 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4957 		return (1);
4958 #undef SAME_INTF
4959 
4960 	return (0);
4961 }
4962 
4963 static int
4964 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4965     const struct firmware **fw)
4966 {
4967 	struct fw_info *fw_info;
4968 
4969 	*dcfg = NULL;
4970 	if (fw != NULL)
4971 		*fw = NULL;
4972 
4973 	fw_info = find_fw_info(chip_id(sc));
4974 	if (fw_info == NULL) {
4975 		device_printf(sc->dev,
4976 		    "unable to look up firmware information for chip %d.\n",
4977 		    chip_id(sc));
4978 		return (EINVAL);
4979 	}
4980 
4981 	*dcfg = firmware_get(fw_info->kld_name);
4982 	if (*dcfg != NULL) {
4983 		if (fw != NULL)
4984 			*fw = firmware_get(fw_info->fw_mod_name);
4985 		return (0);
4986 	}
4987 
4988 	return (ENOENT);
4989 }
4990 
4991 static void
4992 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4993     const struct firmware *fw)
4994 {
4995 
4996 	if (fw != NULL)
4997 		firmware_put(fw, FIRMWARE_UNLOAD);
4998 	if (dcfg != NULL)
4999 		firmware_put(dcfg, FIRMWARE_UNLOAD);
5000 }
5001 
5002 /*
5003  * Return values:
5004  * 0 means no firmware install attempted.
5005  * ERESTART means a firmware install was attempted and was successful.
5006  * +ve errno means a firmware install was attempted but failed.
5007  */
5008 static int
5009 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
5010     const struct fw_h *drv_fw, const char *reason, int *already)
5011 {
5012 	const struct firmware *cfg, *fw;
5013 	const uint32_t c = be32toh(card_fw->fw_ver);
5014 	uint32_t d, k;
5015 	int rc, fw_install;
5016 	struct fw_h bundled_fw;
5017 	bool load_attempted;
5018 
5019 	cfg = fw = NULL;
5020 	load_attempted = false;
5021 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
5022 
5023 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
5024 	if (t4_fw_install < 0) {
5025 		rc = load_fw_module(sc, &cfg, &fw);
5026 		if (rc != 0 || fw == NULL) {
5027 			device_printf(sc->dev,
5028 			    "failed to load firmware module: %d. cfg %p, fw %p;"
5029 			    " will use compiled-in firmware version for"
5030 			    "hw.cxgbe.fw_install checks.\n",
5031 			    rc, cfg, fw);
5032 		} else {
5033 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
5034 		}
5035 		load_attempted = true;
5036 	}
5037 	d = be32toh(bundled_fw.fw_ver);
5038 
5039 	if (reason != NULL)
5040 		goto install;
5041 
5042 	if ((sc->flags & FW_OK) == 0) {
5043 
5044 		if (c == 0xffffffff) {
5045 			reason = "missing";
5046 			goto install;
5047 		}
5048 
5049 		rc = 0;
5050 		goto done;
5051 	}
5052 
5053 	if (!fw_compatible(card_fw, &bundled_fw)) {
5054 		reason = "incompatible or unusable";
5055 		goto install;
5056 	}
5057 
5058 	if (d > c) {
5059 		reason = "older than the version bundled with this driver";
5060 		goto install;
5061 	}
5062 
5063 	if (fw_install == 2 && d != c) {
5064 		reason = "different than the version bundled with this driver";
5065 		goto install;
5066 	}
5067 
5068 	/* No reason to do anything to the firmware already on the card. */
5069 	rc = 0;
5070 	goto done;
5071 
5072 install:
5073 	rc = 0;
5074 	if ((*already)++)
5075 		goto done;
5076 
5077 	if (fw_install == 0) {
5078 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
5079 		    "but the driver is prohibited from installing a firmware "
5080 		    "on the card.\n",
5081 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
5082 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
5083 
5084 		goto done;
5085 	}
5086 
5087 	/*
5088 	 * We'll attempt to install a firmware.  Load the module first (if it
5089 	 * hasn't been loaded already).
5090 	 */
5091 	if (!load_attempted) {
5092 		rc = load_fw_module(sc, &cfg, &fw);
5093 		if (rc != 0 || fw == NULL) {
5094 			device_printf(sc->dev,
5095 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
5096 			    rc, cfg, fw);
5097 			/* carry on */
5098 		}
5099 	}
5100 	if (fw == NULL) {
5101 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
5102 		    "but the driver cannot take corrective action because it "
5103 		    "is unable to load the firmware module.\n",
5104 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
5105 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
5106 		rc = sc->flags & FW_OK ? 0 : ENOENT;
5107 		goto done;
5108 	}
5109 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
5110 	if (k != d) {
5111 		MPASS(t4_fw_install > 0);
5112 		device_printf(sc->dev,
5113 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
5114 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
5115 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
5116 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
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 		rc = sc->flags & FW_OK ? 0 : EINVAL;
5120 		goto done;
5121 	}
5122 
5123 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
5124 	    "installing firmware %u.%u.%u.%u on card.\n",
5125 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
5126 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
5127 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
5128 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
5129 
5130 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
5131 	if (rc != 0) {
5132 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
5133 	} else {
5134 		/* Installed successfully, update the cached header too. */
5135 		rc = ERESTART;
5136 		memcpy(card_fw, fw->data, sizeof(*card_fw));
5137 	}
5138 done:
5139 	unload_fw_module(sc, cfg, fw);
5140 
5141 	return (rc);
5142 }
5143 
5144 /*
5145  * Establish contact with the firmware and attempt to become the master driver.
5146  *
5147  * A firmware will be installed to the card if needed (if the driver is allowed
5148  * to do so).
5149  */
5150 static int
5151 contact_firmware(struct adapter *sc)
5152 {
5153 	int rc, already = 0;
5154 	enum dev_state state;
5155 	struct fw_info *fw_info;
5156 	struct fw_hdr *card_fw;		/* fw on the card */
5157 	const struct fw_h *drv_fw;
5158 
5159 	fw_info = find_fw_info(chip_id(sc));
5160 	if (fw_info == NULL) {
5161 		device_printf(sc->dev,
5162 		    "unable to look up firmware information for chip %d.\n",
5163 		    chip_id(sc));
5164 		return (EINVAL);
5165 	}
5166 	drv_fw = &fw_info->fw_h;
5167 
5168 	/* Read the header of the firmware on the card */
5169 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
5170 restart:
5171 	rc = -t4_get_fw_hdr(sc, card_fw);
5172 	if (rc != 0) {
5173 		device_printf(sc->dev,
5174 		    "unable to read firmware header from card's flash: %d\n",
5175 		    rc);
5176 		goto done;
5177 	}
5178 
5179 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
5180 	    &already);
5181 	if (rc == ERESTART)
5182 		goto restart;
5183 	if (rc != 0)
5184 		goto done;
5185 
5186 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
5187 	if (rc < 0 || state == DEV_STATE_ERR) {
5188 		rc = -rc;
5189 		device_printf(sc->dev,
5190 		    "failed to connect to the firmware: %d, %d.  "
5191 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
5192 #if 0
5193 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
5194 		    "not responding properly to HELLO", &already) == ERESTART)
5195 			goto restart;
5196 #endif
5197 		goto done;
5198 	}
5199 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
5200 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
5201 
5202 	if (rc == sc->pf) {
5203 		sc->flags |= MASTER_PF;
5204 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
5205 		    NULL, &already);
5206 		if (rc == ERESTART)
5207 			rc = 0;
5208 		else if (rc != 0)
5209 			goto done;
5210 	} else if (state == DEV_STATE_UNINIT) {
5211 		/*
5212 		 * We didn't get to be the master so we definitely won't be
5213 		 * configuring the chip.  It's a bug if someone else hasn't
5214 		 * configured it already.
5215 		 */
5216 		device_printf(sc->dev, "couldn't be master(%d), "
5217 		    "device not already initialized either(%d).  "
5218 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
5219 		rc = EPROTO;
5220 		goto done;
5221 	} else {
5222 		/*
5223 		 * Some other PF is the master and has configured the chip.
5224 		 * This is allowed but untested.
5225 		 */
5226 		device_printf(sc->dev, "PF%d is master, device state %d.  "
5227 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
5228 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
5229 		sc->cfcsum = 0;
5230 		rc = 0;
5231 	}
5232 done:
5233 	if (rc != 0 && sc->flags & FW_OK) {
5234 		t4_fw_bye(sc, sc->mbox);
5235 		sc->flags &= ~FW_OK;
5236 	}
5237 	free(card_fw, M_CXGBE);
5238 	return (rc);
5239 }
5240 
5241 static int
5242 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
5243     uint32_t mtype, uint32_t moff, u_int maxlen)
5244 {
5245 	struct fw_info *fw_info;
5246 	const struct firmware *dcfg, *rcfg = NULL;
5247 	const uint32_t *cfdata;
5248 	uint32_t cflen, addr;
5249 	int rc;
5250 
5251 	load_fw_module(sc, &dcfg, NULL);
5252 
5253 	/* Card specific interpretation of "default". */
5254 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
5255 		if (pci_get_device(sc->dev) == 0x440a)
5256 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
5257 		if (is_fpga(sc))
5258 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
5259 	}
5260 
5261 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
5262 		if (dcfg == NULL) {
5263 			device_printf(sc->dev,
5264 			    "KLD with default config is not available.\n");
5265 			rc = ENOENT;
5266 			goto done;
5267 		}
5268 		cfdata = dcfg->data;
5269 		cflen = dcfg->datasize & ~3;
5270 	} else {
5271 		char s[32];
5272 
5273 		fw_info = find_fw_info(chip_id(sc));
5274 		if (fw_info == NULL) {
5275 			device_printf(sc->dev,
5276 			    "unable to look up firmware information for chip %d.\n",
5277 			    chip_id(sc));
5278 			rc = EINVAL;
5279 			goto done;
5280 		}
5281 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
5282 
5283 		rcfg = firmware_get(s);
5284 		if (rcfg == NULL) {
5285 			device_printf(sc->dev,
5286 			    "unable to load module \"%s\" for configuration "
5287 			    "profile \"%s\".\n", s, cfg_file);
5288 			rc = ENOENT;
5289 			goto done;
5290 		}
5291 		cfdata = rcfg->data;
5292 		cflen = rcfg->datasize & ~3;
5293 	}
5294 
5295 	if (cflen > maxlen) {
5296 		device_printf(sc->dev,
5297 		    "config file too long (%d, max allowed is %d).\n",
5298 		    cflen, maxlen);
5299 		rc = EINVAL;
5300 		goto done;
5301 	}
5302 
5303 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
5304 	if (rc != 0) {
5305 		device_printf(sc->dev,
5306 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
5307 		    __func__, mtype, moff, cflen, rc);
5308 		rc = EINVAL;
5309 		goto done;
5310 	}
5311 	write_via_memwin(sc, 2, addr, cfdata, cflen);
5312 done:
5313 	if (rcfg != NULL)
5314 		firmware_put(rcfg, FIRMWARE_UNLOAD);
5315 	unload_fw_module(sc, dcfg, NULL);
5316 	return (rc);
5317 }
5318 
5319 struct caps_allowed {
5320 	uint16_t nbmcaps;
5321 	uint16_t linkcaps;
5322 	uint16_t switchcaps;
5323 	uint16_t nvmecaps;
5324 	uint16_t niccaps;
5325 	uint16_t toecaps;
5326 	uint16_t rdmacaps;
5327 	uint16_t cryptocaps;
5328 	uint16_t iscsicaps;
5329 	uint16_t fcoecaps;
5330 };
5331 
5332 #define FW_PARAM_DEV(param) \
5333 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
5334 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
5335 #define FW_PARAM_PFVF(param) \
5336 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
5337 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
5338 
5339 /*
5340  * Provide a configuration profile to the firmware and have it initialize the
5341  * chip accordingly.  This may involve uploading a configuration file to the
5342  * card.
5343  */
5344 static int
5345 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
5346     const struct caps_allowed *caps_allowed)
5347 {
5348 	int rc;
5349 	struct fw_caps_config_cmd caps;
5350 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
5351 	unsigned int maxlen = 0;
5352 	const int cfg_addr = t4_flash_cfg_addr(sc, &maxlen);
5353 
5354 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
5355 	if (rc != 0) {
5356 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
5357 		return (rc);
5358 	}
5359 
5360 	bzero(&caps, sizeof(caps));
5361 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5362 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5363 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
5364 		mtype = 0;
5365 		moff = 0;
5366 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5367 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
5368 		mtype = FW_MEMTYPE_FLASH;
5369 		moff = cfg_addr;
5370 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5371 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5372 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5373 		    FW_LEN16(caps));
5374 	} else {
5375 		/*
5376 		 * Ask the firmware where it wants us to upload the config file.
5377 		 */
5378 		param = FW_PARAM_DEV(CF);
5379 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5380 		if (rc != 0) {
5381 			/* No support for config file?  Shouldn't happen. */
5382 			device_printf(sc->dev,
5383 			    "failed to query config file location: %d.\n", rc);
5384 			goto done;
5385 		}
5386 		mtype = G_FW_PARAMS_PARAM_Y(val);
5387 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
5388 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5389 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5390 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5391 		    FW_LEN16(caps));
5392 
5393 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff, maxlen);
5394 		if (rc != 0) {
5395 			device_printf(sc->dev,
5396 			    "failed to upload config file to card: %d.\n", rc);
5397 			goto done;
5398 		}
5399 	}
5400 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5401 	if (rc != 0) {
5402 		device_printf(sc->dev, "failed to pre-process config file: %d "
5403 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
5404 		goto done;
5405 	}
5406 
5407 	finicsum = be32toh(caps.finicsum);
5408 	cfcsum = be32toh(caps.cfcsum);	/* actual */
5409 	if (finicsum != cfcsum) {
5410 		device_printf(sc->dev,
5411 		    "WARNING: config file checksum mismatch: %08x %08x\n",
5412 		    finicsum, cfcsum);
5413 	}
5414 	sc->cfcsum = cfcsum;
5415 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
5416 
5417 	/*
5418 	 * Let the firmware know what features will (not) be used so it can tune
5419 	 * things accordingly.
5420 	 */
5421 #define LIMIT_CAPS(x) do { \
5422 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
5423 } while (0)
5424 	LIMIT_CAPS(nbm);
5425 	LIMIT_CAPS(link);
5426 	LIMIT_CAPS(switch);
5427 	LIMIT_CAPS(nvme);
5428 	LIMIT_CAPS(nic);
5429 	LIMIT_CAPS(toe);
5430 	LIMIT_CAPS(rdma);
5431 	LIMIT_CAPS(crypto);
5432 	LIMIT_CAPS(iscsi);
5433 	LIMIT_CAPS(fcoe);
5434 #undef LIMIT_CAPS
5435 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
5436 		/*
5437 		 * TOE and hashfilters are mutually exclusive.  It is a config
5438 		 * file or firmware bug if both are reported as available.  Try
5439 		 * to cope with the situation in non-debug builds by disabling
5440 		 * TOE.
5441 		 */
5442 		MPASS(caps.toecaps == 0);
5443 
5444 		caps.toecaps = 0;
5445 		caps.rdmacaps = 0;
5446 		caps.iscsicaps = 0;
5447 		caps.nvmecaps = 0;
5448 	}
5449 
5450 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5451 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
5452 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5453 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
5454 	if (rc != 0) {
5455 		device_printf(sc->dev,
5456 		    "failed to process config file: %d.\n", rc);
5457 		goto done;
5458 	}
5459 
5460 	t4_tweak_chip_settings(sc);
5461 	set_params__pre_init(sc);
5462 
5463 	/* get basic stuff going */
5464 	rc = -t4_fw_initialize(sc, sc->mbox);
5465 	if (rc != 0) {
5466 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
5467 		goto done;
5468 	}
5469 done:
5470 	return (rc);
5471 }
5472 
5473 /*
5474  * Partition chip resources for use between various PFs, VFs, etc.
5475  */
5476 static int
5477 partition_resources(struct adapter *sc)
5478 {
5479 	char cfg_file[sizeof(t4_cfg_file)];
5480 	struct caps_allowed caps_allowed;
5481 	int rc;
5482 	bool fallback;
5483 
5484 	/* Only the master driver gets to configure the chip resources. */
5485 	MPASS(sc->flags & MASTER_PF);
5486 
5487 #define COPY_CAPS(x) do { \
5488 	caps_allowed.x##caps = t4_##x##caps_allowed; \
5489 } while (0)
5490 	bzero(&caps_allowed, sizeof(caps_allowed));
5491 	COPY_CAPS(nbm);
5492 	COPY_CAPS(link);
5493 	COPY_CAPS(switch);
5494 	COPY_CAPS(nvme);
5495 	COPY_CAPS(nic);
5496 	COPY_CAPS(toe);
5497 	COPY_CAPS(rdma);
5498 	COPY_CAPS(crypto);
5499 	COPY_CAPS(iscsi);
5500 	COPY_CAPS(fcoe);
5501 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
5502 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
5503 retry:
5504 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
5505 	if (rc != 0 && fallback) {
5506 		dump_devlog(sc);
5507 		device_printf(sc->dev,
5508 		    "failed (%d) to configure card with \"%s\" profile, "
5509 		    "will fall back to a basic configuration and retry.\n",
5510 		    rc, cfg_file);
5511 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
5512 		bzero(&caps_allowed, sizeof(caps_allowed));
5513 		COPY_CAPS(switch);
5514 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
5515 		fallback = false;
5516 		goto retry;
5517 	}
5518 #undef COPY_CAPS
5519 	return (rc);
5520 }
5521 
5522 /*
5523  * Retrieve parameters that are needed (or nice to have) very early.
5524  */
5525 static int
5526 get_params__pre_init(struct adapter *sc)
5527 {
5528 	int rc;
5529 	uint32_t param[2], val[2];
5530 
5531 	t4_get_version_info(sc);
5532 
5533 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5534 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5535 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5536 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5537 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5538 
5539 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5540 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5541 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5542 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5543 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5544 
5545 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5546 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5547 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5548 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5549 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5550 
5551 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5552 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5553 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5554 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5555 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5556 
5557 	param[0] = FW_PARAM_DEV(PORTVEC);
5558 	param[1] = FW_PARAM_DEV(CCLK);
5559 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5560 	if (rc != 0) {
5561 		device_printf(sc->dev,
5562 		    "failed to query parameters (pre_init): %d.\n", rc);
5563 		return (rc);
5564 	}
5565 
5566 	sc->params.portvec = val[0];
5567 	sc->params.nports = bitcount32(val[0]);
5568 	sc->params.vpd.cclk = val[1];
5569 
5570 	/* Read device log parameters. */
5571 	rc = -t4_init_devlog_ncores_params(sc, 1);
5572 	if (rc == 0)
5573 		fixup_devlog_ncores_params(sc);
5574 	else {
5575 		device_printf(sc->dev,
5576 		    "failed to get devlog parameters: %d.\n", rc);
5577 		rc = 0;	/* devlog isn't critical for device operation */
5578 	}
5579 
5580 	return (rc);
5581 }
5582 
5583 /*
5584  * Any params that need to be set before FW_INITIALIZE.
5585  */
5586 static int
5587 set_params__pre_init(struct adapter *sc)
5588 {
5589 	int rc = 0;
5590 	uint32_t param, val;
5591 
5592 	if (chip_id(sc) >= CHELSIO_T6) {
5593 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5594 		val = 1;
5595 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5596 		/* firmwares < 1.20.1.0 do not have this param. */
5597 		if (rc == FW_EINVAL &&
5598 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5599 			rc = 0;
5600 		}
5601 		if (rc != 0) {
5602 			device_printf(sc->dev,
5603 			    "failed to enable high priority filters :%d.\n",
5604 			    rc);
5605 		}
5606 
5607 		param = FW_PARAM_DEV(PPOD_EDRAM);
5608 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5609 		if (rc == 0 && val == 1) {
5610 			rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param,
5611 			    &val);
5612 			if (rc != 0) {
5613 				device_printf(sc->dev,
5614 				    "failed to set PPOD_EDRAM: %d.\n", rc);
5615 			}
5616 		}
5617 	}
5618 
5619 	/* Enable opaque VIIDs with firmwares that support it. */
5620 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5621 	val = 1;
5622 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5623 	if (rc == 0 && val == 1)
5624 		sc->params.viid_smt_extn_support = true;
5625 	else
5626 		sc->params.viid_smt_extn_support = false;
5627 
5628 	return (rc);
5629 }
5630 
5631 /*
5632  * Retrieve various parameters that are of interest to the driver.  The device
5633  * has been initialized by the firmware at this point.
5634  */
5635 static int
5636 get_params__post_init(struct adapter *sc)
5637 {
5638 	int rc;
5639 	uint32_t param[7], val[7];
5640 	struct fw_caps_config_cmd caps;
5641 
5642 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5643 	param[1] = FW_PARAM_PFVF(EQ_START);
5644 	param[2] = FW_PARAM_PFVF(FILTER_START);
5645 	param[3] = FW_PARAM_PFVF(FILTER_END);
5646 	param[4] = FW_PARAM_PFVF(L2T_START);
5647 	param[5] = FW_PARAM_PFVF(L2T_END);
5648 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5649 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5650 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5651 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5652 	if (rc != 0) {
5653 		device_printf(sc->dev,
5654 		    "failed to query parameters (post_init): %d.\n", rc);
5655 		return (rc);
5656 	}
5657 
5658 	sc->sge.iq_start = val[0];
5659 	sc->sge.eq_start = val[1];
5660 	if ((int)val[3] > (int)val[2]) {
5661 		sc->tids.ftid_base = val[2];
5662 		sc->tids.ftid_end = val[3];
5663 		sc->tids.nftids = val[3] - val[2] + 1;
5664 	}
5665 	sc->vres.l2t.start = val[4];
5666 	sc->vres.l2t.size = val[5] - val[4] + 1;
5667 	/* val[5] is the last hwidx and it must not collide with F_SYNC_WR */
5668 	if (sc->vres.l2t.size > 0)
5669 		MPASS(fls(val[5]) <= S_SYNC_WR);
5670 	sc->params.core_vdd = val[6];
5671 
5672 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5673 	param[1] = FW_PARAM_PFVF(EQ_END);
5674 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5675 	if (rc != 0) {
5676 		device_printf(sc->dev,
5677 		    "failed to query parameters (post_init2): %d.\n", rc);
5678 		return (rc);
5679 	}
5680 	MPASS((int)val[0] >= sc->sge.iq_start);
5681 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5682 	MPASS((int)val[1] >= sc->sge.eq_start);
5683 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5684 
5685 	if (chip_id(sc) >= CHELSIO_T6) {
5686 
5687 		sc->tids.tid_base = t4_read_reg(sc,
5688 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5689 
5690 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5691 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5692 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5693 		if (rc != 0) {
5694 			device_printf(sc->dev,
5695 			   "failed to query hpfilter parameters: %d.\n", rc);
5696 			return (rc);
5697 		}
5698 		if ((int)val[1] > (int)val[0]) {
5699 			sc->tids.hpftid_base = val[0];
5700 			sc->tids.hpftid_end = val[1];
5701 			sc->tids.nhpftids = val[1] - val[0] + 1;
5702 
5703 			/*
5704 			 * These should go off if the layout changes and the
5705 			 * driver needs to catch up.
5706 			 */
5707 			MPASS(sc->tids.hpftid_base == 0);
5708 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5709 		}
5710 
5711 		param[0] = FW_PARAM_PFVF(RAWF_START);
5712 		param[1] = FW_PARAM_PFVF(RAWF_END);
5713 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5714 		if (rc != 0) {
5715 			device_printf(sc->dev,
5716 			   "failed to query rawf parameters: %d.\n", rc);
5717 			return (rc);
5718 		}
5719 		if ((int)val[1] > (int)val[0]) {
5720 			sc->rawf_base = val[0];
5721 			sc->nrawf = val[1] - val[0] + 1;
5722 		}
5723 	}
5724 
5725 	if (sc->params.ncores > 1) {
5726 		param[0] = FW_PARAM_DEV(TID_QID_SEL_MASK);
5727 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5728 		sc->params.tid_qid_sel_mask = rc == 0 ? val[0] : 0;
5729 	}
5730 
5731 	/*
5732 	 * The parameters that follow may not be available on all firmwares.  We
5733 	 * query them individually rather than in a compound query because old
5734 	 * firmwares fail the entire query if an unknown parameter is queried.
5735 	 */
5736 
5737 	/*
5738 	 * MPS buffer group configuration.
5739 	 */
5740 	param[0] = FW_PARAM_DEV(MPSBGMAP);
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.mps_bg_map = val[0];
5745 	else
5746 		sc->params.mps_bg_map = UINT32_MAX;	/* Not a legal value. */
5747 
5748 	param[0] = FW_PARAM_DEV(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.tp_ch_map = val[0];
5753 	else
5754 		sc->params.tp_ch_map = UINT32_MAX;	/* Not a legal value. */
5755 
5756 	param[0] = FW_PARAM_DEV(TX_TPCHMAP);
5757 	val[0] = 0;
5758 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5759 	if (rc == 0)
5760 		sc->params.tx_tp_ch_map = val[0];
5761 	else
5762 		sc->params.tx_tp_ch_map = UINT32_MAX;	/* Not a legal value. */
5763 
5764 	/*
5765 	 * Determine whether the firmware supports the filter2 work request.
5766 	 */
5767 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5768 	val[0] = 0;
5769 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5770 	if (rc == 0)
5771 		sc->params.filter2_wr_support = val[0] != 0;
5772 	else
5773 		sc->params.filter2_wr_support = 0;
5774 
5775 	/*
5776 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5777 	 */
5778 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5779 	val[0] = 0;
5780 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5781 	if (rc == 0)
5782 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5783 	else
5784 		sc->params.ulptx_memwrite_dsgl = false;
5785 
5786 	/* FW_RI_FR_NSMR_TPTE_WR support */
5787 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5788 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5789 	if (rc == 0)
5790 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5791 	else
5792 		sc->params.fr_nsmr_tpte_wr_support = false;
5793 
5794 	/* Support for 512 SGL entries per FR MR. */
5795 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5796 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5797 	if (rc == 0)
5798 		sc->params.dev_512sgl_mr = val[0] != 0;
5799 	else
5800 		sc->params.dev_512sgl_mr = false;
5801 
5802 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5803 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5804 	if (rc == 0)
5805 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5806 	else
5807 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5808 
5809 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5810 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5811 	if (rc == 0) {
5812 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5813 		sc->params.nsched_cls = val[0];
5814 	} else
5815 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5816 
5817 	/* get capabilites */
5818 	bzero(&caps, sizeof(caps));
5819 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5820 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5821 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5822 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5823 	if (rc != 0) {
5824 		device_printf(sc->dev,
5825 		    "failed to get card capabilities: %d.\n", rc);
5826 		return (rc);
5827 	}
5828 
5829 #define READ_CAPS(x) do { \
5830 	sc->x = htobe16(caps.x); \
5831 } while (0)
5832 	READ_CAPS(nbmcaps);
5833 	READ_CAPS(linkcaps);
5834 	READ_CAPS(switchcaps);
5835 	READ_CAPS(nvmecaps);
5836 	READ_CAPS(niccaps);
5837 	READ_CAPS(toecaps);
5838 	READ_CAPS(rdmacaps);
5839 	READ_CAPS(cryptocaps);
5840 	READ_CAPS(iscsicaps);
5841 	READ_CAPS(fcoecaps);
5842 
5843 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5844 		MPASS(chip_id(sc) > CHELSIO_T4);
5845 		MPASS(sc->toecaps == 0);
5846 		sc->toecaps = 0;
5847 
5848 		param[0] = FW_PARAM_DEV(NTID);
5849 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5850 		if (rc != 0) {
5851 			device_printf(sc->dev,
5852 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5853 			return (rc);
5854 		}
5855 		sc->tids.ntids = val[0];
5856 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5857 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5858 			sc->tids.ntids -= sc->tids.nhpftids;
5859 		}
5860 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5861 		sc->params.hash_filter = 1;
5862 	}
5863 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5864 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5865 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5866 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5867 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5868 		if (rc != 0) {
5869 			device_printf(sc->dev,
5870 			    "failed to query NIC parameters: %d.\n", rc);
5871 			return (rc);
5872 		}
5873 		if ((int)val[1] > (int)val[0]) {
5874 			sc->tids.etid_base = val[0];
5875 			sc->tids.etid_end = val[1];
5876 			sc->tids.netids = val[1] - val[0] + 1;
5877 			sc->params.eo_wr_cred = val[2];
5878 			sc->params.ethoffload = 1;
5879 		}
5880 	}
5881 	if (sc->toecaps) {
5882 		/* query offload-related parameters */
5883 		param[0] = FW_PARAM_DEV(NTID);
5884 		param[1] = FW_PARAM_PFVF(SERVER_START);
5885 		param[2] = FW_PARAM_PFVF(SERVER_END);
5886 		param[3] = FW_PARAM_PFVF(TDDP_START);
5887 		param[4] = FW_PARAM_PFVF(TDDP_END);
5888 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5889 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5890 		if (rc != 0) {
5891 			device_printf(sc->dev,
5892 			    "failed to query TOE parameters: %d.\n", rc);
5893 			return (rc);
5894 		}
5895 		sc->tids.ntids = val[0];
5896 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5897 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5898 			sc->tids.ntids -= sc->tids.nhpftids;
5899 		}
5900 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5901 		if ((int)val[2] > (int)val[1]) {
5902 			sc->tids.stid_base = val[1];
5903 			sc->tids.nstids = val[2] - val[1] + 1;
5904 		}
5905 		sc->vres.ddp.start = val[3];
5906 		sc->vres.ddp.size = val[4] - val[3] + 1;
5907 		sc->params.ofldq_wr_cred = val[5];
5908 		sc->params.offload = 1;
5909 	} else {
5910 		/*
5911 		 * The firmware attempts memfree TOE configuration for -SO cards
5912 		 * and will report toecaps=0 if it runs out of resources (this
5913 		 * depends on the config file).  It may not report 0 for other
5914 		 * capabilities dependent on the TOE in this case.  Set them to
5915 		 * 0 here so that the driver doesn't bother tracking resources
5916 		 * that will never be used.
5917 		 */
5918 		sc->iscsicaps = 0;
5919 		sc->nvmecaps = 0;
5920 		sc->rdmacaps = 0;
5921 	}
5922 	if (sc->nvmecaps || sc->rdmacaps) {
5923 		param[0] = FW_PARAM_PFVF(STAG_START);
5924 		param[1] = FW_PARAM_PFVF(STAG_END);
5925 		param[2] = FW_PARAM_PFVF(PBL_START);
5926 		param[3] = FW_PARAM_PFVF(PBL_END);
5927 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5928 		if (rc != 0) {
5929 			device_printf(sc->dev,
5930 			    "failed to query NVMe/RDMA parameters: %d.\n", rc);
5931 			return (rc);
5932 		}
5933 		sc->vres.stag.start = val[0];
5934 		sc->vres.stag.size = val[1] - val[0] + 1;
5935 		sc->vres.pbl.start = val[2];
5936 		sc->vres.pbl.size = val[3] - val[2] + 1;
5937 	}
5938 	if (sc->rdmacaps) {
5939 		param[0] = FW_PARAM_PFVF(RQ_START);
5940 		param[1] = FW_PARAM_PFVF(RQ_END);
5941 		param[2] = FW_PARAM_PFVF(SQRQ_START);
5942 		param[3] = FW_PARAM_PFVF(SQRQ_END);
5943 		param[4] = FW_PARAM_PFVF(CQ_START);
5944 		param[5] = FW_PARAM_PFVF(CQ_END);
5945 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5946 		if (rc != 0) {
5947 			device_printf(sc->dev,
5948 			    "failed to query RDMA parameters(1): %d.\n", rc);
5949 			return (rc);
5950 		}
5951 		sc->vres.rq.start = val[0];
5952 		sc->vres.rq.size = val[1] - val[0] + 1;
5953 		sc->vres.qp.start = val[2];
5954 		sc->vres.qp.size = val[3] - val[2] + 1;
5955 		sc->vres.cq.start = val[4];
5956 		sc->vres.cq.size = val[5] - val[4] + 1;
5957 
5958 		param[0] = FW_PARAM_PFVF(OCQ_START);
5959 		param[1] = FW_PARAM_PFVF(OCQ_END);
5960 		param[2] = FW_PARAM_PFVF(SRQ_START);
5961 		param[3] = FW_PARAM_PFVF(SRQ_END);
5962 		param[4] = FW_PARAM_DEV(MAXORDIRD_QP);
5963 		param[5] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5964 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5965 		if (rc != 0) {
5966 			device_printf(sc->dev,
5967 			    "failed to query RDMA parameters(2): %d.\n", rc);
5968 			return (rc);
5969 		}
5970 		sc->vres.ocq.start = val[0];
5971 		sc->vres.ocq.size = val[1] - val[0] + 1;
5972 		sc->vres.srq.start = val[2];
5973 		sc->vres.srq.size = val[3] - val[2] + 1;
5974 		sc->params.max_ordird_qp = val[4];
5975 		sc->params.max_ird_adapter = val[5];
5976 
5977 		param[0] = FW_PARAM_DEV(RDMA_WRITE_WITH_IMM);
5978 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5979 		if (rc == 0 && val[0] != 0)
5980 			sc->params.write_w_imm_support = true;
5981 
5982 		param[0] = FW_PARAM_DEV(RI_WRITE_CMPL_WR);
5983 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5984 		if (rc == 0 && val[0] != 0)
5985 			sc->params.write_cmpl_support = true;
5986 	}
5987 	if (sc->iscsicaps) {
5988 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5989 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5990 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5991 		if (rc != 0) {
5992 			device_printf(sc->dev,
5993 			    "failed to query iSCSI parameters: %d.\n", rc);
5994 			return (rc);
5995 		}
5996 		sc->vres.iscsi.start = val[0];
5997 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5998 	}
5999 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
6000 		param[0] = FW_PARAM_PFVF(TLS_START);
6001 		param[1] = FW_PARAM_PFVF(TLS_END);
6002 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
6003 		if (rc != 0) {
6004 			device_printf(sc->dev,
6005 			    "failed to query TLS parameters: %d.\n", rc);
6006 			return (rc);
6007 		}
6008 		sc->vres.key.start = val[0];
6009 		sc->vres.key.size = val[1] - val[0] + 1;
6010 	}
6011 	if (sc->cryptocaps & FW_CAPS_CONFIG_IPSEC_INLINE) {
6012 		param[0] = FW_PARAM_PFVF(NIPSEC_TUNNEL);
6013 		param[1] = FW_PARAM_PFVF(NIPSEC_TRANSPORT);
6014 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
6015 		if (rc == 0) {
6016 			sc->params.nipsec_tunnel = val[0];
6017 			sc->params.nipsec_transport = val[1];
6018 		} else {
6019 			CH_ERR(sc, "failed to query IPsec params: %d.\n", rc);
6020 			MPASS(sc->params.nipsec_tunnel == 0);
6021 			MPASS(sc->params.nipsec_transport == 0);
6022 		}
6023 	}
6024 	if (sc->cryptocaps & FW_CAPS_CONFIG_OFLD_OVER_IPSEC_INLINE) {
6025 		param[0] = FW_PARAM_PFVF(OFLD_NIPSEC_TUNNEL);
6026 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
6027 		if (rc == 0) {
6028 			sc->params.nofld_ipsec_tunnel = val[0];
6029 		} else {
6030 			CH_ERR(sc, "failed to query TOE IPsec params: %d.\n", rc);
6031 			MPASS(sc->params.nofld_ipsec_tunnel == 0);
6032 		}
6033 	}
6034 	/*
6035 	 * We've got the params we wanted to query directly from the firmware.
6036 	 * Grab some others via other means.
6037 	 */
6038 	t4_init_sge_params(sc);
6039 	t4_init_tp_params(sc);
6040 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
6041 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
6042 
6043 	rc = t4_verify_chip_settings(sc);
6044 	if (rc != 0)
6045 		return (rc);
6046 	t4_init_rx_buf_info(sc);
6047 
6048 	return (rc);
6049 }
6050 
6051 #ifdef KERN_TLS
6052 static void
6053 ktls_tick(void *arg)
6054 {
6055 	struct adapter *sc;
6056 	uint32_t tstamp;
6057 
6058 	sc = arg;
6059 	tstamp = tcp_ts_getticks();
6060 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
6061 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
6062 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
6063 }
6064 
6065 static int
6066 t6_config_kern_tls(struct adapter *sc, bool enable)
6067 {
6068 	int rc;
6069 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
6070 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
6071 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
6072 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
6073 
6074 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
6075 	if (rc != 0) {
6076 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
6077 		    enable ?  "enable" : "disable", rc);
6078 		return (rc);
6079 	}
6080 
6081 	if (enable) {
6082 		sc->flags |= KERN_TLS_ON;
6083 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
6084 		    C_HARDCLOCK);
6085 	} else {
6086 		sc->flags &= ~KERN_TLS_ON;
6087 		callout_stop(&sc->ktls_tick);
6088 	}
6089 
6090 	return (rc);
6091 }
6092 #endif
6093 
6094 static int
6095 set_params__post_init(struct adapter *sc)
6096 {
6097 	uint32_t mask, param, val;
6098 #ifdef TCP_OFFLOAD
6099 	int i, v, shift;
6100 #endif
6101 
6102 	/* ask for encapsulated CPLs */
6103 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
6104 	val = 1;
6105 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
6106 
6107 	/* Enable 32b port caps if the firmware supports it. */
6108 	param = FW_PARAM_PFVF(PORT_CAPS32);
6109 	val = 1;
6110 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
6111 		sc->params.port_caps32 = 1;
6112 
6113 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
6114 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
6115 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
6116 	    V_MASKFILTER(val - 1));
6117 
6118 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
6119 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
6120 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
6121 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
6122 	val = 0;
6123 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
6124 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
6125 		    F_ATTACKFILTERENABLE);
6126 		val |= F_DROPERRORATTACK;
6127 	}
6128 	if (t4_drop_ip_fragments != 0) {
6129 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
6130 		    F_FRAGMENTDROP);
6131 		val |= F_DROPERRORFRAG;
6132 	}
6133 	if (t4_drop_pkts_with_l2_errors != 0)
6134 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
6135 	if (t4_drop_pkts_with_l3_errors != 0) {
6136 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
6137 		    F_DROPERRORCSUMIP;
6138 	}
6139 	if (t4_drop_pkts_with_l4_errors != 0) {
6140 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
6141 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
6142 	}
6143 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
6144 
6145 #ifdef TCP_OFFLOAD
6146 	/*
6147 	 * Override the TOE timers with user provided tunables.  This is not the
6148 	 * recommended way to change the timers (the firmware config file is) so
6149 	 * these tunables are not documented.
6150 	 *
6151 	 * All the timer tunables are in microseconds.
6152 	 */
6153 	if (t4_toe_keepalive_idle != 0) {
6154 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
6155 		v &= M_KEEPALIVEIDLE;
6156 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
6157 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
6158 	}
6159 	if (t4_toe_keepalive_interval != 0) {
6160 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
6161 		v &= M_KEEPALIVEINTVL;
6162 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
6163 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
6164 	}
6165 	if (t4_toe_keepalive_count != 0) {
6166 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
6167 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
6168 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
6169 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
6170 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
6171 	}
6172 	if (t4_toe_rexmt_min != 0) {
6173 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
6174 		v &= M_RXTMIN;
6175 		t4_set_reg_field(sc, A_TP_RXT_MIN,
6176 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
6177 	}
6178 	if (t4_toe_rexmt_max != 0) {
6179 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
6180 		v &= M_RXTMAX;
6181 		t4_set_reg_field(sc, A_TP_RXT_MAX,
6182 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
6183 	}
6184 	if (t4_toe_rexmt_count != 0) {
6185 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
6186 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
6187 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
6188 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
6189 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
6190 	}
6191 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
6192 		if (t4_toe_rexmt_backoff[i] != -1) {
6193 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
6194 			shift = (i & 3) << 3;
6195 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
6196 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
6197 		}
6198 	}
6199 #endif
6200 
6201 	/*
6202 	 * Limit TOE connections to 2 reassembly "islands".  This is
6203 	 * required to permit migrating TOE connections to either
6204 	 * ULP_MODE_TCPDDP or UPL_MODE_TLS.
6205 	 */
6206 	t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG, V_PASSMODE(M_PASSMODE),
6207 	    V_PASSMODE(2));
6208 
6209 #ifdef KERN_TLS
6210 	if (is_ktls(sc)) {
6211 		sc->tlst.inline_keys = t4_tls_inline_keys;
6212 		if (t4_kern_tls != 0 && is_t6(sc)) {
6213 			sc->tlst.combo_wrs = t4_tls_combo_wrs;
6214 			t6_config_kern_tls(sc, true);
6215 		} else {
6216 			sc->tlst.short_records = t4_tls_short_records;
6217 			sc->tlst.partial_ghash = t4_tls_partial_ghash;
6218 		}
6219 	}
6220 #endif
6221 	return (0);
6222 }
6223 
6224 #undef FW_PARAM_PFVF
6225 #undef FW_PARAM_DEV
6226 
6227 static void
6228 t4_set_desc(struct adapter *sc)
6229 {
6230 	struct adapter_params *p = &sc->params;
6231 
6232 	device_set_descf(sc->dev, "Chelsio %s", p->vpd.id);
6233 }
6234 
6235 static inline void
6236 ifmedia_add4(struct ifmedia *ifm, int m)
6237 {
6238 
6239 	ifmedia_add(ifm, m, 0, NULL);
6240 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
6241 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
6242 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
6243 }
6244 
6245 /*
6246  * This is the selected media, which is not quite the same as the active media.
6247  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
6248  * and active are not the same, and "media: Ethernet selected" otherwise.
6249  */
6250 static void
6251 set_current_media(struct port_info *pi)
6252 {
6253 	struct link_config *lc;
6254 	struct ifmedia *ifm;
6255 	int mword;
6256 	u_int speed;
6257 
6258 	PORT_LOCK_ASSERT_OWNED(pi);
6259 
6260 	/* Leave current media alone if it's already set to IFM_NONE. */
6261 	ifm = &pi->media;
6262 	if (ifm->ifm_cur != NULL &&
6263 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
6264 		return;
6265 
6266 	lc = &pi->link_cfg;
6267 	if (lc->requested_aneg != AUTONEG_DISABLE &&
6268 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
6269 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
6270 		return;
6271 	}
6272 	mword = IFM_ETHER | IFM_FDX;
6273 	if (lc->requested_fc & PAUSE_TX)
6274 		mword |= IFM_ETH_TXPAUSE;
6275 	if (lc->requested_fc & PAUSE_RX)
6276 		mword |= IFM_ETH_RXPAUSE;
6277 	if (lc->requested_speed == 0)
6278 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
6279 	else
6280 		speed = lc->requested_speed;
6281 	mword |= port_mword(pi, speed_to_fwcap(speed));
6282 	ifmedia_set(ifm, mword);
6283 }
6284 
6285 /*
6286  * Returns true if the ifmedia list for the port cannot change.
6287  */
6288 static bool
6289 fixed_ifmedia(struct port_info *pi)
6290 {
6291 
6292 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
6293 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
6294 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
6295 	    pi->port_type == FW_PORT_TYPE_KX4 ||
6296 	    pi->port_type == FW_PORT_TYPE_KX ||
6297 	    pi->port_type == FW_PORT_TYPE_KR ||
6298 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
6299 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
6300 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
6301 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
6302 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
6303 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
6304 }
6305 
6306 static void
6307 build_medialist(struct port_info *pi)
6308 {
6309 	uint32_t ss, speed;
6310 	int unknown, mword, bit;
6311 	struct link_config *lc;
6312 	struct ifmedia *ifm;
6313 
6314 	PORT_LOCK_ASSERT_OWNED(pi);
6315 
6316 	if (pi->flags & FIXED_IFMEDIA)
6317 		return;
6318 
6319 	/*
6320 	 * Rebuild the ifmedia list.
6321 	 */
6322 	ifm = &pi->media;
6323 	ifmedia_removeall(ifm);
6324 	lc = &pi->link_cfg;
6325 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
6326 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
6327 		MPASS(ss != 0);
6328 no_media:
6329 		MPASS(LIST_EMPTY(&ifm->ifm_list));
6330 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
6331 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
6332 		return;
6333 	}
6334 
6335 	unknown = 0;
6336 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
6337 		speed = 1 << bit;
6338 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
6339 		if (ss & speed) {
6340 			mword = port_mword(pi, speed);
6341 			if (mword == IFM_NONE) {
6342 				goto no_media;
6343 			} else if (mword == IFM_UNKNOWN)
6344 				unknown++;
6345 			else
6346 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
6347 		}
6348 	}
6349 	if (unknown > 0) /* Add one unknown for all unknown media types. */
6350 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
6351 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
6352 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
6353 
6354 	set_current_media(pi);
6355 }
6356 
6357 /*
6358  * Initialize the requested fields in the link config based on driver tunables.
6359  */
6360 static void
6361 init_link_config(struct port_info *pi)
6362 {
6363 	struct link_config *lc = &pi->link_cfg;
6364 
6365 	PORT_LOCK_ASSERT_OWNED(pi);
6366 
6367 	lc->requested_caps = 0;
6368 	lc->requested_speed = 0;
6369 
6370 	if (t4_autoneg == 0)
6371 		lc->requested_aneg = AUTONEG_DISABLE;
6372 	else if (t4_autoneg == 1)
6373 		lc->requested_aneg = AUTONEG_ENABLE;
6374 	else
6375 		lc->requested_aneg = AUTONEG_AUTO;
6376 
6377 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
6378 	    PAUSE_AUTONEG);
6379 
6380 	if (t4_fec & FEC_AUTO)
6381 		lc->requested_fec = FEC_AUTO;
6382 	else if (t4_fec == 0)
6383 		lc->requested_fec = FEC_NONE;
6384 	else {
6385 		/* -1 is handled by the FEC_AUTO block above and not here. */
6386 		lc->requested_fec = t4_fec &
6387 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
6388 		if (lc->requested_fec == 0)
6389 			lc->requested_fec = FEC_AUTO;
6390 	}
6391 	if (t4_force_fec < 0)
6392 		lc->force_fec = -1;
6393 	else if (t4_force_fec > 0)
6394 		lc->force_fec = 1;
6395 	else
6396 		lc->force_fec = 0;
6397 }
6398 
6399 /*
6400  * Makes sure that all requested settings comply with what's supported by the
6401  * port.  Returns the number of settings that were invalid and had to be fixed.
6402  */
6403 static int
6404 fixup_link_config(struct port_info *pi)
6405 {
6406 	int n = 0;
6407 	struct link_config *lc = &pi->link_cfg;
6408 	uint32_t fwspeed;
6409 
6410 	PORT_LOCK_ASSERT_OWNED(pi);
6411 
6412 	/* Speed (when not autonegotiating) */
6413 	if (lc->requested_speed != 0) {
6414 		fwspeed = speed_to_fwcap(lc->requested_speed);
6415 		if ((fwspeed & lc->pcaps) == 0) {
6416 			n++;
6417 			lc->requested_speed = 0;
6418 		}
6419 	}
6420 
6421 	/* Link autonegotiation */
6422 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
6423 	    lc->requested_aneg == AUTONEG_DISABLE ||
6424 	    lc->requested_aneg == AUTONEG_AUTO);
6425 	if (lc->requested_aneg == AUTONEG_ENABLE &&
6426 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
6427 		n++;
6428 		lc->requested_aneg = AUTONEG_AUTO;
6429 	}
6430 
6431 	/* Flow control */
6432 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
6433 	if (lc->requested_fc & PAUSE_TX &&
6434 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
6435 		n++;
6436 		lc->requested_fc &= ~PAUSE_TX;
6437 	}
6438 	if (lc->requested_fc & PAUSE_RX &&
6439 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
6440 		n++;
6441 		lc->requested_fc &= ~PAUSE_RX;
6442 	}
6443 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
6444 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
6445 		n++;
6446 		lc->requested_fc |= PAUSE_AUTONEG;
6447 	}
6448 
6449 	/* FEC */
6450 	if ((lc->requested_fec & FEC_RS &&
6451 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
6452 	    (lc->requested_fec & FEC_BASER_RS &&
6453 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
6454 		n++;
6455 		lc->requested_fec = FEC_AUTO;
6456 	}
6457 
6458 	return (n);
6459 }
6460 
6461 /*
6462  * Apply the requested L1 settings, which are expected to be valid, to the
6463  * hardware.
6464  */
6465 static int
6466 apply_link_config(struct port_info *pi)
6467 {
6468 	struct adapter *sc = pi->adapter;
6469 	struct link_config *lc = &pi->link_cfg;
6470 	int rc;
6471 
6472 #ifdef INVARIANTS
6473 	ASSERT_SYNCHRONIZED_OP(sc);
6474 	PORT_LOCK_ASSERT_OWNED(pi);
6475 
6476 	if (lc->requested_aneg == AUTONEG_ENABLE)
6477 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
6478 	if (!(lc->requested_fc & PAUSE_AUTONEG))
6479 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
6480 	if (lc->requested_fc & PAUSE_TX)
6481 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
6482 	if (lc->requested_fc & PAUSE_RX)
6483 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
6484 	if (lc->requested_fec & FEC_RS)
6485 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
6486 	if (lc->requested_fec & FEC_BASER_RS)
6487 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
6488 #endif
6489 	if (!(sc->flags & IS_VF)) {
6490 		rc = -t4_link_l1cfg(sc, sc->mbox, pi->hw_port, lc);
6491 		if (rc != 0) {
6492 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
6493 			return (rc);
6494 		}
6495 	}
6496 
6497 	/*
6498 	 * An L1_CFG will almost always result in a link-change event if the
6499 	 * link is up, and the driver will refresh the actual fec/fc/etc. when
6500 	 * the notification is processed.  If the link is down then the actual
6501 	 * settings are meaningless.
6502 	 *
6503 	 * This takes care of the case where a change in the L1 settings may not
6504 	 * result in a notification.
6505 	 */
6506 	if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
6507 		lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
6508 
6509 	return (0);
6510 }
6511 
6512 #define FW_MAC_EXACT_CHUNK	7
6513 struct mcaddr_ctx {
6514 	if_t ifp;
6515 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
6516 	uint64_t hash;
6517 	int i;
6518 	int del;
6519 	int rc;
6520 };
6521 
6522 static u_int
6523 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
6524 {
6525 	struct mcaddr_ctx *ctx = arg;
6526 	struct vi_info *vi = if_getsoftc(ctx->ifp);
6527 	struct port_info *pi = vi->pi;
6528 	struct adapter *sc = pi->adapter;
6529 
6530 	if (ctx->rc < 0)
6531 		return (0);
6532 
6533 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
6534 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
6535 	ctx->i++;
6536 
6537 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
6538 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
6539 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
6540 		if (ctx->rc < 0) {
6541 			int j;
6542 
6543 			for (j = 0; j < ctx->i; j++) {
6544 				if_printf(ctx->ifp,
6545 				    "failed to add mc address"
6546 				    " %02x:%02x:%02x:"
6547 				    "%02x:%02x:%02x rc=%d\n",
6548 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
6549 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
6550 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
6551 				    -ctx->rc);
6552 			}
6553 			return (0);
6554 		}
6555 		ctx->del = 0;
6556 		ctx->i = 0;
6557 	}
6558 
6559 	return (1);
6560 }
6561 
6562 /*
6563  * Program the port's XGMAC based on parameters in ifnet.  The caller also
6564  * indicates which parameters should be programmed (the rest are left alone).
6565  */
6566 int
6567 update_mac_settings(if_t ifp, int flags)
6568 {
6569 	int rc = 0;
6570 	struct vi_info *vi = if_getsoftc(ifp);
6571 	struct port_info *pi = vi->pi;
6572 	struct adapter *sc = pi->adapter;
6573 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
6574 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
6575 
6576 	ASSERT_SYNCHRONIZED_OP(sc);
6577 	KASSERT(flags, ("%s: not told what to update.", __func__));
6578 
6579 	if (flags & XGMAC_MTU)
6580 		mtu = if_getmtu(ifp);
6581 
6582 	if (flags & XGMAC_PROMISC)
6583 		promisc = if_getflags(ifp) & IFF_PROMISC ? 1 : 0;
6584 
6585 	if (flags & XGMAC_ALLMULTI)
6586 		allmulti = if_getflags(ifp) & IFF_ALLMULTI ? 1 : 0;
6587 
6588 	if (flags & XGMAC_VLANEX)
6589 		vlanex = if_getcapenable(ifp) & IFCAP_VLAN_HWTAGGING ? 1 : 0;
6590 
6591 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
6592 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
6593 		    allmulti, 1, vlanex, false);
6594 		if (rc) {
6595 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
6596 			    rc);
6597 			return (rc);
6598 		}
6599 	}
6600 
6601 	if (flags & XGMAC_UCADDR) {
6602 		uint8_t ucaddr[ETHER_ADDR_LEN];
6603 
6604 		bcopy(if_getlladdr(ifp), ucaddr, sizeof(ucaddr));
6605 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
6606 		    ucaddr, true, &vi->smt_idx);
6607 		if (rc < 0) {
6608 			rc = -rc;
6609 			if_printf(ifp, "change_mac failed: %d\n", rc);
6610 			return (rc);
6611 		} else {
6612 			vi->xact_addr_filt = rc;
6613 			rc = 0;
6614 		}
6615 	}
6616 
6617 	if (flags & XGMAC_MCADDRS) {
6618 		struct epoch_tracker et;
6619 		struct mcaddr_ctx ctx;
6620 		int j;
6621 
6622 		ctx.ifp = ifp;
6623 		ctx.hash = 0;
6624 		ctx.i = 0;
6625 		ctx.del = 1;
6626 		ctx.rc = 0;
6627 		/*
6628 		 * Unlike other drivers, we accumulate list of pointers into
6629 		 * interface address lists and we need to keep it safe even
6630 		 * after if_foreach_llmaddr() returns, thus we must enter the
6631 		 * network epoch.
6632 		 */
6633 		NET_EPOCH_ENTER(et);
6634 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6635 		if (ctx.rc < 0) {
6636 			NET_EPOCH_EXIT(et);
6637 			rc = -ctx.rc;
6638 			return (rc);
6639 		}
6640 		if (ctx.i > 0) {
6641 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6642 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6643 			NET_EPOCH_EXIT(et);
6644 			if (rc < 0) {
6645 				rc = -rc;
6646 				for (j = 0; j < ctx.i; j++) {
6647 					if_printf(ifp,
6648 					    "failed to add mcast address"
6649 					    " %02x:%02x:%02x:"
6650 					    "%02x:%02x:%02x rc=%d\n",
6651 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6652 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6653 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6654 					    rc);
6655 				}
6656 				return (rc);
6657 			}
6658 			ctx.del = 0;
6659 		} else
6660 			NET_EPOCH_EXIT(et);
6661 
6662 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6663 		if (rc != 0)
6664 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6665 			    rc);
6666 		if (ctx.del == 0) {
6667 			/* We clobbered the VXLAN entry if there was one. */
6668 			pi->vxlan_tcam_entry = false;
6669 		}
6670 	}
6671 
6672 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6673 	    pi->vxlan_tcam_entry == false) {
6674 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6675 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6676 		    true);
6677 		if (rc < 0) {
6678 			rc = -rc;
6679 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6680 			    rc);
6681 		} else {
6682 			MPASS(rc == sc->rawf_base + pi->port_id);
6683 			rc = 0;
6684 			pi->vxlan_tcam_entry = true;
6685 		}
6686 	}
6687 
6688 	return (rc);
6689 }
6690 
6691 /*
6692  * {begin|end}_synchronized_op must be called from the same thread.
6693  */
6694 int
6695 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6696     char *wmesg)
6697 {
6698 	int rc;
6699 
6700 #ifdef WITNESS
6701 	/* the caller thinks it's ok to sleep, but is it really? */
6702 	if (flags & SLEEP_OK)
6703 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, __func__);
6704 #endif
6705 	ADAPTER_LOCK(sc);
6706 	for (;;) {
6707 
6708 		if (vi && IS_DETACHING(vi)) {
6709 			rc = ENXIO;
6710 			goto done;
6711 		}
6712 
6713 		if (!IS_BUSY(sc)) {
6714 			rc = 0;
6715 			break;
6716 		}
6717 
6718 		if (!(flags & SLEEP_OK)) {
6719 			rc = EBUSY;
6720 			goto done;
6721 		}
6722 
6723 		if (mtx_sleep(&sc->flags, &sc->sc_lock,
6724 		    flags & INTR_OK ? PCATCH : 0, wmesg, 0)) {
6725 			rc = EINTR;
6726 			goto done;
6727 		}
6728 	}
6729 
6730 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6731 	SET_BUSY(sc);
6732 #ifdef INVARIANTS
6733 	sc->last_op = wmesg;
6734 	sc->last_op_thr = curthread;
6735 	sc->last_op_flags = flags;
6736 #endif
6737 
6738 done:
6739 	if (!(flags & HOLD_LOCK) || rc)
6740 		ADAPTER_UNLOCK(sc);
6741 
6742 	return (rc);
6743 }
6744 
6745 /*
6746  * Tell if_ioctl and if_init that the VI is going away.  This is
6747  * special variant of begin_synchronized_op and must be paired with a
6748  * call to end_vi_detach.
6749  */
6750 void
6751 begin_vi_detach(struct adapter *sc, struct vi_info *vi)
6752 {
6753 	ADAPTER_LOCK(sc);
6754 	SET_DETACHING(vi);
6755 	wakeup(&sc->flags);
6756 	while (IS_BUSY(sc))
6757 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6758 	SET_BUSY(sc);
6759 #ifdef INVARIANTS
6760 	sc->last_op = "t4detach";
6761 	sc->last_op_thr = curthread;
6762 	sc->last_op_flags = 0;
6763 #endif
6764 	ADAPTER_UNLOCK(sc);
6765 }
6766 
6767 void
6768 end_vi_detach(struct adapter *sc, struct vi_info *vi)
6769 {
6770 	ADAPTER_LOCK(sc);
6771 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6772 	CLR_BUSY(sc);
6773 	CLR_DETACHING(vi);
6774 	wakeup(&sc->flags);
6775 	ADAPTER_UNLOCK(sc);
6776 }
6777 
6778 /*
6779  * {begin|end}_synchronized_op must be called from the same thread.
6780  */
6781 void
6782 end_synchronized_op(struct adapter *sc, int flags)
6783 {
6784 
6785 	if (flags & LOCK_HELD)
6786 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6787 	else
6788 		ADAPTER_LOCK(sc);
6789 
6790 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6791 	CLR_BUSY(sc);
6792 	wakeup(&sc->flags);
6793 	ADAPTER_UNLOCK(sc);
6794 }
6795 
6796 static int
6797 cxgbe_init_synchronized(struct vi_info *vi)
6798 {
6799 	struct port_info *pi = vi->pi;
6800 	struct adapter *sc = pi->adapter;
6801 	if_t ifp = vi->ifp;
6802 	int rc = 0, i;
6803 	struct sge_txq *txq;
6804 
6805 	ASSERT_SYNCHRONIZED_OP(sc);
6806 
6807 	if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
6808 		return (0);	/* already running */
6809 
6810 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6811 		return (rc);	/* error message displayed already */
6812 
6813 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6814 		return (rc); /* error message displayed already */
6815 
6816 	rc = update_mac_settings(ifp, XGMAC_ALL);
6817 	if (rc)
6818 		goto done;	/* error message displayed already */
6819 
6820 	PORT_LOCK(pi);
6821 	if (pi->up_vis == 0) {
6822 		t4_update_port_info(pi);
6823 		fixup_link_config(pi);
6824 		build_medialist(pi);
6825 		apply_link_config(pi);
6826 	}
6827 
6828 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6829 	if (rc != 0) {
6830 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6831 		PORT_UNLOCK(pi);
6832 		goto done;
6833 	}
6834 
6835 	/*
6836 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6837 	 * if this changes.
6838 	 */
6839 
6840 	for_each_txq(vi, i, txq) {
6841 		TXQ_LOCK(txq);
6842 		txq->eq.flags |= EQ_ENABLED;
6843 		TXQ_UNLOCK(txq);
6844 	}
6845 
6846 	/*
6847 	 * The first iq of the first port to come up is used for tracing.
6848 	 */
6849 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6850 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6851 		t4_set_trace_rss_control(sc, pi->tx_chan, sc->traceq);
6852 		pi->flags |= HAS_TRACEQ;
6853 	}
6854 
6855 	/* all ok */
6856 	pi->up_vis++;
6857 	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
6858 	if (pi->link_cfg.link_ok)
6859 		t4_os_link_changed(pi);
6860 	PORT_UNLOCK(pi);
6861 
6862 	mtx_lock(&vi->tick_mtx);
6863 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
6864 		callout_reset(&vi->tick, hz, vi_tick, vi);
6865 	else
6866 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6867 	mtx_unlock(&vi->tick_mtx);
6868 done:
6869 	if (rc != 0)
6870 		cxgbe_uninit_synchronized(vi);
6871 
6872 	return (rc);
6873 }
6874 
6875 /*
6876  * Idempotent.
6877  */
6878 static int
6879 cxgbe_uninit_synchronized(struct vi_info *vi)
6880 {
6881 	struct port_info *pi = vi->pi;
6882 	struct adapter *sc = pi->adapter;
6883 	if_t ifp = vi->ifp;
6884 	int rc, i;
6885 	struct sge_txq *txq;
6886 
6887 	ASSERT_SYNCHRONIZED_OP(sc);
6888 
6889 	if (!(vi->flags & VI_INIT_DONE)) {
6890 		if (__predict_false(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6891 			KASSERT(0, ("uninited VI is running"));
6892 			if_printf(ifp, "uninited VI with running ifnet.  "
6893 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6894 			    "if_drv_flags 0x%08x\n", vi->flags, if_getflags(ifp),
6895 			    if_getdrvflags(ifp));
6896 		}
6897 		return (0);
6898 	}
6899 
6900 	/*
6901 	 * Disable the VI so that all its data in either direction is discarded
6902 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6903 	 * tick) intact as the TP can deliver negative advice or data that it's
6904 	 * holding in its RAM (for an offloaded connection) even after the VI is
6905 	 * disabled.
6906 	 */
6907 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6908 	if (rc) {
6909 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6910 		return (rc);
6911 	}
6912 
6913 	for_each_txq(vi, i, txq) {
6914 		TXQ_LOCK(txq);
6915 		txq->eq.flags &= ~EQ_ENABLED;
6916 		TXQ_UNLOCK(txq);
6917 	}
6918 
6919 	mtx_lock(&vi->tick_mtx);
6920 	callout_stop(&vi->tick);
6921 	mtx_unlock(&vi->tick_mtx);
6922 
6923 	PORT_LOCK(pi);
6924 	if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6925 		PORT_UNLOCK(pi);
6926 		return (0);
6927 	}
6928 	if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
6929 	pi->up_vis--;
6930 	if (pi->up_vis > 0) {
6931 		PORT_UNLOCK(pi);
6932 		return (0);
6933 	}
6934 
6935 	pi->link_cfg.link_ok = false;
6936 	pi->link_cfg.speed = 0;
6937 	pi->link_cfg.link_down_rc = 255;
6938 	t4_os_link_changed(pi);
6939 	PORT_UNLOCK(pi);
6940 
6941 	return (0);
6942 }
6943 
6944 /*
6945  * It is ok for this function to fail midway and return right away.  t4_detach
6946  * will walk the entire sc->irq list and clean up whatever is valid.
6947  */
6948 int
6949 t4_setup_intr_handlers(struct adapter *sc)
6950 {
6951 	int rc, rid, p, q, v;
6952 	char s[8];
6953 	struct irq *irq;
6954 	struct port_info *pi;
6955 	struct vi_info *vi;
6956 	struct sge *sge = &sc->sge;
6957 	struct sge_rxq *rxq;
6958 #ifdef TCP_OFFLOAD
6959 	struct sge_ofld_rxq *ofld_rxq;
6960 #endif
6961 #ifdef DEV_NETMAP
6962 	struct sge_nm_rxq *nm_rxq;
6963 #endif
6964 #ifdef RSS
6965 	int nbuckets = rss_getnumbuckets();
6966 #endif
6967 
6968 	/*
6969 	 * Setup interrupts.
6970 	 */
6971 	irq = &sc->irq[0];
6972 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6973 	if (forwarding_intr_to_fwq(sc))
6974 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6975 
6976 	/* Multiple interrupts. */
6977 	if (sc->flags & IS_VF)
6978 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6979 		    ("%s: too few intr.", __func__));
6980 	else
6981 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6982 		    ("%s: too few intr.", __func__));
6983 
6984 	/* The first one is always error intr on PFs */
6985 	if (!(sc->flags & IS_VF)) {
6986 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6987 		if (rc != 0)
6988 			return (rc);
6989 		irq++;
6990 		rid++;
6991 	}
6992 
6993 	/* The second one is always the firmware event queue (first on VFs) */
6994 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6995 	if (rc != 0)
6996 		return (rc);
6997 	irq++;
6998 	rid++;
6999 
7000 	for_each_port(sc, p) {
7001 		pi = sc->port[p];
7002 		for_each_vi(pi, v, vi) {
7003 			vi->first_intr = rid - 1;
7004 
7005 			if (vi->nnmrxq > 0) {
7006 				int n = max(vi->nrxq, vi->nnmrxq);
7007 
7008 				rxq = &sge->rxq[vi->first_rxq];
7009 #ifdef DEV_NETMAP
7010 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
7011 #endif
7012 				for (q = 0; q < n; q++) {
7013 					snprintf(s, sizeof(s), "%x%c%x", p,
7014 					    'a' + v, q);
7015 					if (q < vi->nrxq)
7016 						irq->rxq = rxq++;
7017 #ifdef DEV_NETMAP
7018 					if (q < vi->nnmrxq)
7019 						irq->nm_rxq = nm_rxq++;
7020 
7021 					if (irq->nm_rxq != NULL &&
7022 					    irq->rxq == NULL) {
7023 						/* Netmap rx only */
7024 						rc = t4_alloc_irq(sc, irq, rid,
7025 						    t4_nm_intr, irq->nm_rxq, s);
7026 					}
7027 					if (irq->nm_rxq != NULL &&
7028 					    irq->rxq != NULL) {
7029 						/* NIC and Netmap rx */
7030 						rc = t4_alloc_irq(sc, irq, rid,
7031 						    t4_vi_intr, irq, s);
7032 					}
7033 #endif
7034 					if (irq->rxq != NULL &&
7035 					    irq->nm_rxq == NULL) {
7036 						/* NIC rx only */
7037 						rc = t4_alloc_irq(sc, irq, rid,
7038 						    t4_intr, irq->rxq, s);
7039 					}
7040 					if (rc != 0)
7041 						return (rc);
7042 #ifdef RSS
7043 					if (q < vi->nrxq) {
7044 						bus_bind_intr(sc->dev, irq->res,
7045 						    rss_getcpu(q % nbuckets));
7046 					}
7047 #endif
7048 					irq++;
7049 					rid++;
7050 					vi->nintr++;
7051 				}
7052 			} else {
7053 				for_each_rxq(vi, q, rxq) {
7054 					snprintf(s, sizeof(s), "%x%c%x", p,
7055 					    'a' + v, q);
7056 					rc = t4_alloc_irq(sc, irq, rid,
7057 					    t4_intr, rxq, s);
7058 					if (rc != 0)
7059 						return (rc);
7060 #ifdef RSS
7061 					bus_bind_intr(sc->dev, irq->res,
7062 					    rss_getcpu(q % nbuckets));
7063 #endif
7064 					irq++;
7065 					rid++;
7066 					vi->nintr++;
7067 				}
7068 			}
7069 #ifdef TCP_OFFLOAD
7070 			for_each_ofld_rxq(vi, q, ofld_rxq) {
7071 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
7072 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
7073 				    ofld_rxq, s);
7074 				if (rc != 0)
7075 					return (rc);
7076 				irq++;
7077 				rid++;
7078 				vi->nintr++;
7079 			}
7080 #endif
7081 		}
7082 	}
7083 	MPASS(irq == &sc->irq[sc->intr_count]);
7084 
7085 	return (0);
7086 }
7087 
7088 static void
7089 write_global_rss_key(struct adapter *sc)
7090 {
7091 	int i;
7092 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
7093 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
7094 
7095 	CTASSERT(RSS_KEYSIZE == 40);
7096 
7097 	rss_getkey((void *)&raw_rss_key[0]);
7098 	for (i = 0; i < nitems(rss_key); i++) {
7099 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
7100 	}
7101 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
7102 }
7103 
7104 /*
7105  * Idempotent.
7106  */
7107 static int
7108 adapter_full_init(struct adapter *sc)
7109 {
7110 	int rc, i;
7111 
7112 	ASSERT_SYNCHRONIZED_OP(sc);
7113 
7114 	/*
7115 	 * queues that belong to the adapter (not any particular port).
7116 	 */
7117 	rc = t4_setup_adapter_queues(sc);
7118 	if (rc != 0)
7119 		return (rc);
7120 
7121 	MPASS(sc->params.nports <= nitems(sc->tq));
7122 	for (i = 0; i < sc->params.nports; i++) {
7123 		if (sc->tq[i] != NULL)
7124 			continue;
7125 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
7126 		    taskqueue_thread_enqueue, &sc->tq[i]);
7127 		if (sc->tq[i] == NULL) {
7128 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
7129 			return (ENOMEM);
7130 		}
7131 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
7132 		    device_get_nameunit(sc->dev), i);
7133 	}
7134 
7135 	if (!(sc->flags & IS_VF)) {
7136 		write_global_rss_key(sc);
7137 		t4_intr_enable(sc);
7138 	}
7139 	return (0);
7140 }
7141 
7142 int
7143 adapter_init(struct adapter *sc)
7144 {
7145 	int rc;
7146 
7147 	ASSERT_SYNCHRONIZED_OP(sc);
7148 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
7149 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
7150 	    ("%s: FULL_INIT_DONE already", __func__));
7151 
7152 	rc = adapter_full_init(sc);
7153 	if (rc != 0)
7154 		adapter_full_uninit(sc);
7155 	else
7156 		sc->flags |= FULL_INIT_DONE;
7157 
7158 	return (rc);
7159 }
7160 
7161 /*
7162  * Idempotent.
7163  */
7164 static void
7165 adapter_full_uninit(struct adapter *sc)
7166 {
7167 	int i;
7168 
7169 	t4_teardown_adapter_queues(sc);
7170 
7171 	for (i = 0; i < nitems(sc->tq); i++) {
7172 		if (sc->tq[i] == NULL)
7173 			continue;
7174 		taskqueue_free(sc->tq[i]);
7175 		sc->tq[i] = NULL;
7176 	}
7177 
7178 	sc->flags &= ~FULL_INIT_DONE;
7179 }
7180 
7181 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
7182     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
7183     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
7184     RSS_HASHTYPE_RSS_UDP_IPV6)
7185 
7186 /* Translates kernel hash types to hardware. */
7187 static int
7188 hashconfig_to_hashen(int hashconfig)
7189 {
7190 	int hashen = 0;
7191 
7192 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
7193 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
7194 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
7195 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
7196 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
7197 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
7198 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
7199 	}
7200 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
7201 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
7202 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
7203 	}
7204 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
7205 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
7206 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
7207 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
7208 
7209 	return (hashen);
7210 }
7211 
7212 /* Translates hardware hash types to kernel. */
7213 static int
7214 hashen_to_hashconfig(int hashen)
7215 {
7216 	int hashconfig = 0;
7217 
7218 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
7219 		/*
7220 		 * If UDP hashing was enabled it must have been enabled for
7221 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
7222 		 * enabling any 4-tuple hash is nonsense configuration.
7223 		 */
7224 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
7225 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
7226 
7227 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
7228 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
7229 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
7230 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
7231 	}
7232 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
7233 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
7234 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
7235 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
7236 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
7237 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
7238 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
7239 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
7240 
7241 	return (hashconfig);
7242 }
7243 
7244 /*
7245  * Idempotent.
7246  */
7247 static int
7248 vi_full_init(struct vi_info *vi)
7249 {
7250 	struct adapter *sc = vi->adapter;
7251 	struct sge_rxq *rxq;
7252 	int rc, i, j, extra;
7253 	int hashconfig = rss_gethashconfig();
7254 #ifdef RSS
7255 	int nbuckets = rss_getnumbuckets();
7256 #endif
7257 
7258 	ASSERT_SYNCHRONIZED_OP(sc);
7259 
7260 	/*
7261 	 * Allocate tx/rx/fl queues for this VI.
7262 	 */
7263 	rc = t4_setup_vi_queues(vi);
7264 	if (rc != 0)
7265 		return (rc);
7266 
7267 	/*
7268 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
7269 	 */
7270 	if (vi->nrxq > vi->rss_size) {
7271 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
7272 		    "some queues will never receive traffic.\n", vi->nrxq,
7273 		    vi->rss_size);
7274 	} else if (vi->rss_size % vi->nrxq) {
7275 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
7276 		    "expect uneven traffic distribution.\n", vi->nrxq,
7277 		    vi->rss_size);
7278 	}
7279 #ifdef RSS
7280 	if (vi->nrxq != nbuckets) {
7281 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
7282 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
7283 	}
7284 #endif
7285 	if (vi->rss == NULL)
7286 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
7287 		    M_ZERO | M_WAITOK);
7288 	for (i = 0; i < vi->rss_size;) {
7289 #ifdef RSS
7290 		j = rss_get_indirection_to_bucket(i);
7291 		j %= vi->nrxq;
7292 		rxq = &sc->sge.rxq[vi->first_rxq + j];
7293 		vi->rss[i++] = rxq->iq.abs_id;
7294 #else
7295 		for_each_rxq(vi, j, rxq) {
7296 			vi->rss[i++] = rxq->iq.abs_id;
7297 			if (i == vi->rss_size)
7298 				break;
7299 		}
7300 #endif
7301 	}
7302 
7303 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
7304 	    vi->rss, vi->rss_size);
7305 	if (rc != 0) {
7306 		CH_ERR(vi, "rss_config failed: %d\n", rc);
7307 		return (rc);
7308 	}
7309 
7310 	vi->hashen = hashconfig_to_hashen(hashconfig);
7311 
7312 	/*
7313 	 * We may have had to enable some hashes even though the global config
7314 	 * wants them disabled.  This is a potential problem that must be
7315 	 * reported to the user.
7316 	 */
7317 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
7318 
7319 	/*
7320 	 * If we consider only the supported hash types, then the enabled hashes
7321 	 * are a superset of the requested hashes.  In other words, there cannot
7322 	 * be any supported hash that was requested but not enabled, but there
7323 	 * can be hashes that were not requested but had to be enabled.
7324 	 */
7325 	extra &= SUPPORTED_RSS_HASHTYPES;
7326 	MPASS((extra & hashconfig) == 0);
7327 
7328 	if (extra) {
7329 		CH_ALERT(vi,
7330 		    "global RSS config (0x%x) cannot be accommodated.\n",
7331 		    hashconfig);
7332 	}
7333 	if (extra & RSS_HASHTYPE_RSS_IPV4)
7334 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
7335 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
7336 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
7337 	if (extra & RSS_HASHTYPE_RSS_IPV6)
7338 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
7339 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
7340 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
7341 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
7342 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
7343 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
7344 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
7345 
7346 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
7347 	    0, 0);
7348 	if (rc != 0) {
7349 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
7350 		return (rc);
7351 	}
7352 
7353 	return (0);
7354 }
7355 
7356 int
7357 vi_init(struct vi_info *vi)
7358 {
7359 	int rc;
7360 
7361 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
7362 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
7363 	    ("%s: VI_INIT_DONE already", __func__));
7364 
7365 	rc = vi_full_init(vi);
7366 	if (rc != 0)
7367 		vi_full_uninit(vi);
7368 	else
7369 		vi->flags |= VI_INIT_DONE;
7370 
7371 	return (rc);
7372 }
7373 
7374 /*
7375  * Idempotent.
7376  */
7377 static void
7378 vi_full_uninit(struct vi_info *vi)
7379 {
7380 
7381 	if (vi->flags & VI_INIT_DONE) {
7382 		quiesce_vi(vi);
7383 		free(vi->rss, M_CXGBE);
7384 		free(vi->nm_rss, M_CXGBE);
7385 	}
7386 
7387 	t4_teardown_vi_queues(vi);
7388 	vi->flags &= ~VI_INIT_DONE;
7389 }
7390 
7391 static void
7392 quiesce_txq(struct sge_txq *txq)
7393 {
7394 	struct sge_eq *eq = &txq->eq;
7395 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
7396 
7397 	MPASS(eq->flags & EQ_SW_ALLOCATED);
7398 	MPASS(!(eq->flags & EQ_ENABLED));
7399 
7400 	/* Wait for the mp_ring to empty. */
7401 	while (!mp_ring_is_idle(txq->r)) {
7402 		mp_ring_check_drainage(txq->r, 4096);
7403 		pause("rquiesce", 1);
7404 	}
7405 	MPASS(txq->txp.npkt == 0);
7406 
7407 	if (eq->flags & EQ_HW_ALLOCATED) {
7408 		/*
7409 		 * Hardware is alive and working normally.  Wait for it to
7410 		 * finish and then wait for the driver to catch up and reclaim
7411 		 * all descriptors.
7412 		 */
7413 		while (spg->cidx != htobe16(eq->pidx))
7414 			pause("equiesce", 1);
7415 		while (eq->cidx != eq->pidx)
7416 			pause("dquiesce", 1);
7417 	} else {
7418 		/*
7419 		 * Hardware is unavailable.  Discard all pending tx and reclaim
7420 		 * descriptors directly.
7421 		 */
7422 		TXQ_LOCK(txq);
7423 		while (eq->cidx != eq->pidx) {
7424 			struct mbuf *m, *nextpkt;
7425 			struct tx_sdesc *txsd;
7426 
7427 			txsd = &txq->sdesc[eq->cidx];
7428 			for (m = txsd->m; m != NULL; m = nextpkt) {
7429 				nextpkt = m->m_nextpkt;
7430 				m->m_nextpkt = NULL;
7431 				m_freem(m);
7432 			}
7433 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
7434 		}
7435 		spg->pidx = spg->cidx = htobe16(eq->cidx);
7436 		TXQ_UNLOCK(txq);
7437 	}
7438 }
7439 
7440 static void
7441 quiesce_wrq(struct sge_wrq *wrq)
7442 {
7443 	struct wrqe *wr;
7444 
7445 	TXQ_LOCK(wrq);
7446 	while ((wr = STAILQ_FIRST(&wrq->wr_list)) != NULL) {
7447 		STAILQ_REMOVE_HEAD(&wrq->wr_list, link);
7448 #ifdef INVARIANTS
7449 		wrq->nwr_pending--;
7450 		wrq->ndesc_needed -= howmany(wr->wr_len, EQ_ESIZE);
7451 #endif
7452 		free(wr, M_CXGBE);
7453 	}
7454 	MPASS(wrq->nwr_pending == 0);
7455 	MPASS(wrq->ndesc_needed == 0);
7456 	wrq->nwr_pending = 0;
7457 	wrq->ndesc_needed = 0;
7458 	TXQ_UNLOCK(wrq);
7459 }
7460 
7461 static void
7462 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
7463 {
7464 	/* Synchronize with the interrupt handler */
7465 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
7466 		pause("iqfree", 1);
7467 
7468 	if (fl != NULL) {
7469 		MPASS(iq->flags & IQ_HAS_FL);
7470 
7471 		mtx_lock(&sc->sfl_lock);
7472 		FL_LOCK(fl);
7473 		fl->flags |= FL_DOOMED;
7474 		FL_UNLOCK(fl);
7475 		callout_stop(&sc->sfl_callout);
7476 		mtx_unlock(&sc->sfl_lock);
7477 
7478 		KASSERT((fl->flags & FL_STARVING) == 0,
7479 		    ("%s: still starving", __func__));
7480 
7481 		/* Release all buffers if hardware is no longer available. */
7482 		if (!(iq->flags & IQ_HW_ALLOCATED))
7483 			free_fl_buffers(sc, fl);
7484 	}
7485 }
7486 
7487 /*
7488  * Wait for all activity on all the queues of the VI to complete.  It is assumed
7489  * that no new work is being enqueued by the hardware or the driver.  That part
7490  * should be arranged before calling this function.
7491  */
7492 static void
7493 quiesce_vi(struct vi_info *vi)
7494 {
7495 	int i;
7496 	struct adapter *sc = vi->adapter;
7497 	struct sge_rxq *rxq;
7498 	struct sge_txq *txq;
7499 #ifdef TCP_OFFLOAD
7500 	struct sge_ofld_rxq *ofld_rxq;
7501 #endif
7502 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7503 	struct sge_ofld_txq *ofld_txq;
7504 #endif
7505 
7506 	if (!(vi->flags & VI_INIT_DONE))
7507 		return;
7508 
7509 	for_each_txq(vi, i, txq) {
7510 		quiesce_txq(txq);
7511 	}
7512 
7513 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7514 	for_each_ofld_txq(vi, i, ofld_txq) {
7515 		quiesce_wrq(&ofld_txq->wrq);
7516 	}
7517 #endif
7518 
7519 	for_each_rxq(vi, i, rxq) {
7520 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
7521 	}
7522 
7523 #ifdef TCP_OFFLOAD
7524 	for_each_ofld_rxq(vi, i, ofld_rxq) {
7525 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
7526 	}
7527 #endif
7528 }
7529 
7530 static int
7531 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
7532     driver_intr_t *handler, void *arg, char *name)
7533 {
7534 	int rc;
7535 
7536 	irq->rid = rid;
7537 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
7538 	    RF_SHAREABLE | RF_ACTIVE);
7539 	if (irq->res == NULL) {
7540 		device_printf(sc->dev,
7541 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
7542 		return (ENOMEM);
7543 	}
7544 
7545 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
7546 	    NULL, handler, arg, &irq->tag);
7547 	if (rc != 0) {
7548 		device_printf(sc->dev,
7549 		    "failed to setup interrupt for rid %d, name %s: %d\n",
7550 		    rid, name, rc);
7551 	} else if (name)
7552 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
7553 
7554 	return (rc);
7555 }
7556 
7557 static int
7558 t4_free_irq(struct adapter *sc, struct irq *irq)
7559 {
7560 	if (irq->tag)
7561 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
7562 	if (irq->res)
7563 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
7564 
7565 	bzero(irq, sizeof(*irq));
7566 
7567 	return (0);
7568 }
7569 
7570 static void
7571 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
7572 {
7573 
7574 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
7575 	t4_get_regs(sc, buf, regs->len);
7576 }
7577 
7578 #define	A_PL_INDIR_CMD	0x1f8
7579 
7580 #define	S_PL_AUTOINC	31
7581 #define	M_PL_AUTOINC	0x1U
7582 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
7583 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
7584 
7585 #define	S_PL_VFID	20
7586 #define	M_PL_VFID	0xffU
7587 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
7588 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
7589 
7590 #define	S_PL_ADDR	0
7591 #define	M_PL_ADDR	0xfffffU
7592 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
7593 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
7594 
7595 #define	A_PL_INDIR_DATA	0x1fc
7596 
7597 static uint64_t
7598 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7599 {
7600 	u32 stats[2];
7601 
7602 	if (sc->flags & IS_VF) {
7603 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7604 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7605 	} else {
7606 		mtx_assert(&sc->reg_lock, MA_OWNED);
7607 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7608 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7609 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7610 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7611 	}
7612 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7613 }
7614 
7615 static void
7616 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7617 {
7618 
7619 #define GET_STAT(name) \
7620 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7621 
7622 	if (!(sc->flags & IS_VF))
7623 		mtx_lock(&sc->reg_lock);
7624 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7625 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7626 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7627 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7628 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7629 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7630 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7631 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7632 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7633 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7634 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7635 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7636 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7637 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7638 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7639 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7640 	if (!(sc->flags & IS_VF))
7641 		mtx_unlock(&sc->reg_lock);
7642 
7643 #undef GET_STAT
7644 }
7645 
7646 static void
7647 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7648 {
7649 	int reg;
7650 
7651 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7652 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7653 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7654 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7655 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7656 }
7657 
7658 static void
7659 vi_refresh_stats(struct vi_info *vi)
7660 {
7661 	struct timeval tv;
7662 	const struct timeval interval = {0, 250000};	/* 250ms */
7663 
7664 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7665 
7666 	if (vi->flags & VI_SKIP_STATS)
7667 		return;
7668 
7669 	getmicrotime(&tv);
7670 	timevalsub(&tv, &interval);
7671 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7672 		return;
7673 
7674 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7675 	getmicrotime(&vi->last_refreshed);
7676 }
7677 
7678 static void
7679 cxgbe_refresh_stats(struct vi_info *vi)
7680 {
7681 	u_int i, v, tnl_cong_drops, chan_map;
7682 	struct timeval tv;
7683 	const struct timeval interval = {0, 250000};	/* 250ms */
7684 	struct port_info *pi;
7685 	struct adapter *sc;
7686 
7687 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7688 
7689 	if (vi->flags & VI_SKIP_STATS)
7690 		return;
7691 
7692 	getmicrotime(&tv);
7693 	timevalsub(&tv, &interval);
7694 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7695 		return;
7696 
7697 	pi = vi->pi;
7698 	sc = vi->adapter;
7699 	tnl_cong_drops = 0;
7700 	t4_get_port_stats(sc, pi->hw_port, &pi->stats);
7701 	chan_map = pi->rx_e_chan_map;
7702 	while (chan_map) {
7703 		i = ffs(chan_map) - 1;
7704 		mtx_lock(&sc->reg_lock);
7705 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7706 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7707 		mtx_unlock(&sc->reg_lock);
7708 		tnl_cong_drops += v;
7709 		chan_map &= ~(1 << i);
7710 	}
7711 	pi->tnl_cong_drops = tnl_cong_drops;
7712 	getmicrotime(&vi->last_refreshed);
7713 }
7714 
7715 static void
7716 cxgbe_tick(void *arg)
7717 {
7718 	struct vi_info *vi = arg;
7719 
7720 	MPASS(IS_MAIN_VI(vi));
7721 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7722 
7723 	cxgbe_refresh_stats(vi);
7724 	callout_schedule(&vi->tick, hz);
7725 }
7726 
7727 static void
7728 vi_tick(void *arg)
7729 {
7730 	struct vi_info *vi = arg;
7731 
7732 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7733 
7734 	vi_refresh_stats(vi);
7735 	callout_schedule(&vi->tick, hz);
7736 }
7737 
7738 /* CIM inbound queues */
7739 static const char *t4_ibq[CIM_NUM_IBQ] = {
7740 	"ibq_tp0", "ibq_tp1", "ibq_ulp", "ibq_sge0", "ibq_sge1", "ibq_ncsi"
7741 };
7742 static const char *t7_ibq[CIM_NUM_IBQ_T7] = {
7743 	"ibq_tp0", "ibq_tp1", "ibq_tp2", "ibq_tp3", "ibq_ulp", "ibq_sge0",
7744 	"ibq_sge1", "ibq_ncsi", NULL, "ibq_ipc1", "ibq_ipc2", "ibq_ipc3",
7745 	"ibq_ipc4", "ibq_ipc5", "ibq_ipc6", "ibq_ipc7"
7746 };
7747 static const char *t7_ibq_sec[] = {
7748 	"ibq_tp0", "ibq_tp1", "ibq_tp2", "ibq_tp3", "ibq_ulp", "ibq_sge0",
7749 	NULL, NULL, NULL, "ibq_ipc0"
7750 };
7751 
7752 /* CIM outbound queues */
7753 static const char *t4_obq[CIM_NUM_OBQ_T5] = {
7754 	"obq_ulp0", "obq_ulp1", "obq_ulp2", "obq_ulp3", "obq_sge", "obq_ncsi",
7755 	"obq_sge_rx_q0", "obq_sge_rx_q1" /* These two are T5/T6 only */
7756 };
7757 static const char *t7_obq[CIM_NUM_OBQ_T7] = {
7758 	"obq_ulp0", "obq_ulp1", "obq_ulp2", "obq_ulp3", "obq_sge", "obq_ncsi",
7759 	"obq_sge_rx_q0", NULL, NULL, "obq_ipc1", "obq_ipc2", "obq_ipc3",
7760 	"obq_ipc4", "obq_ipc5", "obq_ipc6", "obq_ipc7"
7761 };
7762 static const char *t7_obq_sec[] = {
7763 	"obq_ulp0", "obq_ulp1", "obq_ulp2", "obq_ulp3", "obq_sge", NULL,
7764 	"obq_sge_rx_q0", NULL, NULL, "obq_ipc0"
7765 };
7766 
7767 static void
7768 cim_sysctls(struct adapter *sc, struct sysctl_ctx_list *ctx,
7769     struct sysctl_oid_list *c0)
7770 {
7771 	struct sysctl_oid *oid;
7772 	struct sysctl_oid_list *children1;
7773 	int i, j, qcount;
7774 	char s[16];
7775 	const char **qname;
7776 
7777 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "cim",
7778 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "CIM block");
7779 	c0 = SYSCTL_CHILDREN(oid);
7780 
7781 	SYSCTL_ADD_U8(ctx, c0, OID_AUTO, "ncores", CTLFLAG_RD, NULL,
7782 	    sc->params.ncores, "# of active CIM cores");
7783 
7784 	for (i = 0; i < sc->params.ncores; i++) {
7785 		snprintf(s, sizeof(s), "%u", i);
7786 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, s,
7787 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "CIM core");
7788 		children1 = SYSCTL_CHILDREN(oid);
7789 
7790 		/*
7791 		 * CTLFLAG_SKIP because the misc.devlog sysctl already displays
7792 		 * the log for all cores.  Use this sysctl to get the log for a
7793 		 * particular core only.
7794 		 */
7795 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "devlog",
7796 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
7797 		    sc, i, sysctl_devlog, "A", "firmware's device log");
7798 
7799 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "loadavg",
7800 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7801 		    sysctl_loadavg, "A",
7802 		    "microprocessor load averages (select firmwares only)");
7803 
7804 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "qcfg",
7805 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7806 		    chip_id(sc) > CHELSIO_T6 ? sysctl_cim_qcfg_t7 : sysctl_cim_qcfg,
7807 		    "A", "Queue configuration");
7808 
7809 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "la",
7810 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7811 		    sysctl_cim_la, "A", "Logic analyzer");
7812 
7813 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "ma_la",
7814 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7815 		    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7816 
7817 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "pif_la",
7818 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7819 		    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7820 
7821 		/* IBQs */
7822 		switch (chip_id(sc)) {
7823 		case CHELSIO_T4:
7824 		case CHELSIO_T5:
7825 		case CHELSIO_T6:
7826 			qname = &t4_ibq[0];
7827 			qcount = nitems(t4_ibq);
7828 			break;
7829 		case CHELSIO_T7:
7830 		default:
7831 			if (i == 0) {
7832 				qname = &t7_ibq[0];
7833 				qcount = nitems(t7_ibq);
7834 			} else {
7835 				qname = &t7_ibq_sec[0];
7836 				qcount = nitems(t7_ibq_sec);
7837 			}
7838 			break;
7839 		}
7840 		MPASS(qcount <= sc->chip_params->cim_num_ibq);
7841 		for (j = 0; j < qcount; j++) {
7842 			if (qname[j] == NULL)
7843 				continue;
7844 			SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, qname[j],
7845 			    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7846 			    (i << 16) | j, sysctl_cim_ibq, "A", NULL);
7847 		}
7848 
7849 		/* OBQs */
7850 		switch (chip_id(sc)) {
7851 		case CHELSIO_T4:
7852 			qname = t4_obq;
7853 			qcount = CIM_NUM_OBQ;
7854 			break;
7855 		case CHELSIO_T5:
7856 		case CHELSIO_T6:
7857 			qname = t4_obq;
7858 			qcount = nitems(t4_obq);
7859 			break;
7860 		case CHELSIO_T7:
7861 		default:
7862 			if (i == 0) {
7863 				qname = t7_obq;
7864 				qcount = nitems(t7_obq);
7865 			} else {
7866 				qname = t7_obq_sec;
7867 				qcount = nitems(t7_obq_sec);
7868 			}
7869 			break;
7870 		}
7871 		MPASS(qcount <= sc->chip_params->cim_num_obq);
7872 		for (j = 0; j < qcount; j++) {
7873 			if (qname[j] == NULL)
7874 				continue;
7875 			SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, qname[j],
7876 			    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7877 			    (i << 16) | j, sysctl_cim_obq, "A", NULL);
7878 		}
7879 	}
7880 }
7881 
7882 /*
7883  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7884  */
7885 static char *caps_decoder[] = {
7886 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7887 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7888 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7889 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7890 	    "\006HASHFILTER\007ETHOFLD",
7891 	"\20\001TOE\002SENDPATH",			/* 4: TOE */
7892 	"\20\001RDDP\002RDMAC\003ROCEv2",		/* 5: RDMA */
7893 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7894 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7895 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7896 	    "\007T10DIF"
7897 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7898 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7899 	    "\004TLS_HW,\005TOE_IPSEC",
7900 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7901 		    "\004PO_INITIATOR\005PO_TARGET",
7902 	"\20\001NVMe_TCP",				/* 9: NVMe */
7903 };
7904 
7905 void
7906 t4_sysctls(struct adapter *sc)
7907 {
7908 	struct sysctl_ctx_list *ctx = &sc->ctx;
7909 	struct sysctl_oid *oid;
7910 	struct sysctl_oid_list *children, *c0;
7911 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7912 
7913 	/*
7914 	 * dev.t4nex.X.
7915 	 */
7916 	oid = device_get_sysctl_tree(sc->dev);
7917 	c0 = children = SYSCTL_CHILDREN(oid);
7918 
7919 	sc->sc_do_rxcopy = 1;
7920 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7921 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7922 
7923 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7924 	    sc->params.nports, "# of ports");
7925 
7926 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7927 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7928 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7929 	    "available doorbells");
7930 
7931 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7932 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7933 
7934 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7935 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7936 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7937 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7938 
7939 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7940 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7941 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7942 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7943 
7944 	t4_sge_sysctls(sc, ctx, children);
7945 
7946 	sc->lro_timeout = 100;
7947 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7948 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7949 
7950 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7951 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7952 
7953 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iflags", CTLFLAG_RW,
7954 	    &sc->intr_flags, 0, "flags for the slow interrupt handler");
7955 
7956 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7957 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7958 
7959 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7960 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7961 
7962 	if (sc->flags & IS_VF)
7963 		return;
7964 
7965 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7966 	    NULL, chip_rev(sc), "chip hardware revision");
7967 
7968 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7969 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7970 
7971 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7972 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7973 
7974 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7975 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7976 
7977 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7978 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7979 
7980 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7981 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7982 
7983 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7984 	    sc->er_version, 0, "expansion ROM version");
7985 
7986 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7987 	    sc->bs_version, 0, "bootstrap firmware version");
7988 
7989 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7990 	    NULL, sc->params.scfg_vers, "serial config version");
7991 
7992 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7993 	    NULL, sc->params.vpd_vers, "VPD version");
7994 
7995 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7996 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7997 
7998 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7999 	    sc->cfcsum, "config file checksum");
8000 
8001 #define SYSCTL_CAP(name, n, text) \
8002 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
8003 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
8004 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
8005 	    "available " text " capabilities")
8006 
8007 	SYSCTL_CAP(nbmcaps, 0, "NBM");
8008 	SYSCTL_CAP(linkcaps, 1, "link");
8009 	SYSCTL_CAP(switchcaps, 2, "switch");
8010 	SYSCTL_CAP(nvmecaps, 9, "NVMe");
8011 	SYSCTL_CAP(niccaps, 3, "NIC");
8012 	SYSCTL_CAP(toecaps, 4, "TCP offload");
8013 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
8014 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
8015 	SYSCTL_CAP(cryptocaps, 7, "crypto");
8016 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
8017 #undef SYSCTL_CAP
8018 
8019 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
8020 	    NULL, sc->tids.nftids, "number of filters");
8021 
8022 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "nipsec_tunnel", CTLFLAG_RD,
8023 	    NULL, sc->params.nipsec_tunnel, "max hw IPsec tunnels");
8024 
8025 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "nipsec_transport", CTLFLAG_RD,
8026 	    NULL, sc->params.nipsec_transport, "max hw IPsec transport pairs");
8027 
8028 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "nofld_ipsec_tunnel", CTLFLAG_RD,
8029 	    NULL, sc->params.nofld_ipsec_tunnel, "max hw IPsec tunnels (TOE)");
8030 
8031 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
8032 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8033 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
8034 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
8035 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
8036 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
8037 
8038 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
8039 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
8040 	    "I", "core Vdd (in mV)");
8041 
8042 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
8043 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
8044 	    sysctl_cpus, "A", "local CPUs");
8045 
8046 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
8047 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
8048 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
8049 
8050 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
8051 	    &sc->swintr, 0, "software triggered interrupts");
8052 
8053 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
8054 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
8055 	    "1 = reset adapter, 0 = zero reset counter");
8056 
8057 	/*
8058 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
8059 	 */
8060 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
8061 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
8062 	    "logs and miscellaneous information");
8063 	children = SYSCTL_CHILDREN(oid);
8064 
8065 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
8066 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8067 	    sysctl_cctrl, "A", "congestion control");
8068 
8069 	cim_sysctls(sc, ctx, children);
8070 
8071 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
8072 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8073 	    sysctl_cpl_stats, "A", "CPL statistics");
8074 
8075 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
8076 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8077 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
8078 
8079 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
8080 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8081 	    sysctl_tid_stats, "A", "tid stats");
8082 
8083 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
8084 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, -1,
8085 	    sysctl_devlog, "A", "firmware's device log (all cores)");
8086 
8087 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
8088 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8089 	    sysctl_fcoe_stats, "A", "FCoE statistics");
8090 
8091 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
8092 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8093 	    sysctl_hw_sched, "A", "hardware scheduler ");
8094 
8095 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
8096 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8097 	    sysctl_l2t, "A", "hardware L2 table");
8098 
8099 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
8100 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8101 	    sysctl_smt, "A", "hardware source MAC table");
8102 
8103 #ifdef INET6
8104 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
8105 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8106 	    sysctl_clip, "A", "active CLIP table entries");
8107 #endif
8108 
8109 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
8110 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8111 	    sysctl_lb_stats, "A", "loopback statistics");
8112 
8113 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
8114 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8115 	    sysctl_meminfo, "A", "memory regions");
8116 
8117 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
8118 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8119 	    chip_id(sc) >= CHELSIO_T7 ? sysctl_mps_tcam_t7 :
8120 	    (chip_id(sc) >= CHELSIO_T6 ? sysctl_mps_tcam_t6 : sysctl_mps_tcam),
8121 	    "A", "MPS TCAM entries");
8122 
8123 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
8124 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8125 	    sysctl_path_mtus, "A", "path MTUs");
8126 
8127 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
8128 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8129 	    sysctl_pm_stats, "A", "PM statistics");
8130 
8131 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
8132 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8133 	    sysctl_rdma_stats, "A", "RDMA statistics");
8134 
8135 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
8136 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8137 	    sysctl_tcp_stats, "A", "TCP statistics");
8138 
8139 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
8140 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8141 	    sysctl_tids, "A", "TID information");
8142 
8143 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
8144 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8145 	    sysctl_tp_err_stats, "A", "TP error statistics");
8146 
8147 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
8148 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8149 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
8150 
8151 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
8152 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
8153 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
8154 
8155 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
8156 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8157 	    sysctl_tp_la, "A", "TP logic analyzer");
8158 
8159 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
8160 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8161 	    sysctl_tx_rate, "A", "Tx rate");
8162 
8163 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
8164 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8165 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
8166 
8167 	if (chip_id(sc) >= CHELSIO_T5) {
8168 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
8169 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8170 		    sysctl_wcwr_stats, "A", "write combined work requests");
8171 	}
8172 
8173 	if (chip_id(sc) >= CHELSIO_T7) {
8174 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcb_cache",
8175 		    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_tcb_cache, "I",
8176 		    "1 = enabled (default), 0 = disabled (for debug only)");
8177 	}
8178 
8179 #ifdef KERN_TLS
8180 	if (is_ktls(sc)) {
8181 		/*
8182 		 * dev.t4nex.0.tls.
8183 		 */
8184 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
8185 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
8186 		children = SYSCTL_CHILDREN(oid);
8187 
8188 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
8189 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
8190 		    "keys in work requests (1) or attempt to store TLS keys "
8191 		    "in card memory.");
8192 
8193 		if (is_t6(sc))
8194 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
8195 			    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to "
8196 			    "combine TCB field updates with TLS record work "
8197 			    "requests.");
8198 		else {
8199 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "short_records",
8200 			    CTLFLAG_RW, &sc->tlst.short_records, 0,
8201 			    "Use cipher-only mode for short records.");
8202 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "partial_ghash",
8203 			    CTLFLAG_RW, &sc->tlst.partial_ghash, 0,
8204 			    "Use partial GHASH for AES-GCM records.");
8205 		}
8206 	}
8207 #endif
8208 
8209 #ifdef TCP_OFFLOAD
8210 	if (is_offload(sc)) {
8211 		int i;
8212 		char s[4];
8213 
8214 		/*
8215 		 * dev.t4nex.X.toe.
8216 		 */
8217 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
8218 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
8219 		children = SYSCTL_CHILDREN(oid);
8220 
8221 		sc->tt.cong_algorithm = -1;
8222 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
8223 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
8224 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
8225 		    "3 = highspeed)");
8226 
8227 		sc->tt.sndbuf = -1;
8228 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
8229 		    &sc->tt.sndbuf, 0, "hardware send buffer");
8230 
8231 		sc->tt.ddp = 0;
8232 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
8233 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
8234 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
8235 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
8236 
8237 		sc->tt.rx_coalesce = -1;
8238 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
8239 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
8240 
8241 		sc->tt.tls = 1;
8242 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
8243 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
8244 		    "Inline TLS allowed");
8245 
8246 		sc->tt.tx_align = -1;
8247 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
8248 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
8249 
8250 		sc->tt.tx_zcopy = 0;
8251 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
8252 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
8253 		    "Enable zero-copy aio_write(2)");
8254 
8255 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
8256 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
8257 		    "cop_managed_offloading", CTLFLAG_RW,
8258 		    &sc->tt.cop_managed_offloading, 0,
8259 		    "COP (Connection Offload Policy) controls all TOE offload");
8260 
8261 		sc->tt.autorcvbuf_inc = 16 * 1024;
8262 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
8263 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
8264 		    "autorcvbuf increment");
8265 
8266 		sc->tt.update_hc_on_pmtu_change = 1;
8267 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
8268 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
8269 		    &sc->tt.update_hc_on_pmtu_change, 0,
8270 		    "Update hostcache entry if the PMTU changes");
8271 
8272 		sc->tt.iso = 1;
8273 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
8274 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
8275 
8276 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
8277 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8278 		    sysctl_tp_tick, "A", "TP timer tick (us)");
8279 
8280 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
8281 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
8282 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
8283 
8284 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
8285 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
8286 		    sysctl_tp_tick, "A", "DACK tick (us)");
8287 
8288 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
8289 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8290 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
8291 
8292 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
8293 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8294 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
8295 		    "Minimum retransmit interval (us)");
8296 
8297 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
8298 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8299 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
8300 		    "Maximum retransmit interval (us)");
8301 
8302 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
8303 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8304 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
8305 		    "Persist timer min (us)");
8306 
8307 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
8308 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8309 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
8310 		    "Persist timer max (us)");
8311 
8312 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
8313 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8314 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
8315 		    "Keepalive idle timer (us)");
8316 
8317 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
8318 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8319 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
8320 		    "Keepalive interval timer (us)");
8321 
8322 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
8323 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8324 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
8325 
8326 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
8327 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8328 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
8329 		    "FINWAIT2 timer (us)");
8330 
8331 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
8332 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8333 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
8334 		    "Number of SYN retransmissions before abort");
8335 
8336 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
8337 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8338 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
8339 		    "Number of retransmissions before abort");
8340 
8341 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
8342 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8343 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
8344 		    "Number of keepalive probes before abort");
8345 
8346 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
8347 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
8348 		    "TOE retransmit backoffs");
8349 		children = SYSCTL_CHILDREN(oid);
8350 		for (i = 0; i < 16; i++) {
8351 			snprintf(s, sizeof(s), "%u", i);
8352 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
8353 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8354 			    i, sysctl_tp_backoff, "IU",
8355 			    "TOE retransmit backoff");
8356 		}
8357 	}
8358 #endif
8359 }
8360 
8361 void
8362 vi_sysctls(struct vi_info *vi)
8363 {
8364 	struct sysctl_ctx_list *ctx = &vi->ctx;
8365 	struct sysctl_oid *oid;
8366 	struct sysctl_oid_list *children;
8367 
8368 	/*
8369 	 * dev.v?(cxgbe|cxl).X.
8370 	 */
8371 	oid = device_get_sysctl_tree(vi->dev);
8372 	children = SYSCTL_CHILDREN(oid);
8373 
8374 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
8375 	    vi->viid, "VI identifer");
8376 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
8377 	    &vi->nrxq, 0, "# of rx queues");
8378 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
8379 	    &vi->ntxq, 0, "# of tx queues");
8380 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
8381 	    &vi->first_rxq, 0, "index of first rx queue");
8382 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
8383 	    &vi->first_txq, 0, "index of first tx queue");
8384 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
8385 	    vi->rss_base, "start of RSS indirection table");
8386 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
8387 	    vi->rss_size, "size of RSS indirection table");
8388 
8389 	if (IS_MAIN_VI(vi)) {
8390 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
8391 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8392 		    sysctl_noflowq, "IU",
8393 		    "Reserve queue 0 for non-flowid packets");
8394 	}
8395 
8396 	if (vi->adapter->flags & IS_VF) {
8397 		MPASS(vi->flags & TX_USES_VM_WR);
8398 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
8399 		    NULL, 1, "use VM work requests for transmit");
8400 	} else {
8401 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
8402 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8403 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
8404 	}
8405 
8406 #ifdef TCP_OFFLOAD
8407 	if (vi->nofldrxq != 0) {
8408 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
8409 		    &vi->nofldrxq, 0,
8410 		    "# of rx queues for offloaded TCP connections");
8411 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
8412 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
8413 		    "index of first TOE rx queue");
8414 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
8415 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8416 		    sysctl_holdoff_tmr_idx_ofld, "I",
8417 		    "holdoff timer index for TOE queues");
8418 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
8419 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8420 		    sysctl_holdoff_pktc_idx_ofld, "I",
8421 		    "holdoff packet counter index for TOE queues");
8422 	}
8423 #endif
8424 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
8425 	if (vi->nofldtxq != 0) {
8426 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
8427 		    &vi->nofldtxq, 0,
8428 		    "# of tx queues for TOE/ETHOFLD");
8429 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
8430 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
8431 		    "index of first TOE/ETHOFLD tx queue");
8432 	}
8433 #endif
8434 #ifdef DEV_NETMAP
8435 	if (vi->nnmrxq != 0) {
8436 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
8437 		    &vi->nnmrxq, 0, "# of netmap rx queues");
8438 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
8439 		    &vi->nnmtxq, 0, "# of netmap tx queues");
8440 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
8441 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
8442 		    "index of first netmap rx queue");
8443 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
8444 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
8445 		    "index of first netmap tx queue");
8446 	}
8447 #endif
8448 
8449 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
8450 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8451 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
8452 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
8453 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8454 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
8455 
8456 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
8457 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8458 	    sysctl_qsize_rxq, "I", "rx queue size");
8459 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
8460 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8461 	    sysctl_qsize_txq, "I", "tx queue size");
8462 }
8463 
8464 static void
8465 cxgbe_sysctls(struct port_info *pi)
8466 {
8467 	struct sysctl_ctx_list *ctx = &pi->ctx;
8468 	struct sysctl_oid *oid;
8469 	struct sysctl_oid_list *children, *children2;
8470 	struct adapter *sc = pi->adapter;
8471 	int i;
8472 	char name[16];
8473 	static char *tc_flags = {"\20\1USER"};
8474 
8475 	/*
8476 	 * dev.cxgbe.X.
8477 	 */
8478 	oid = device_get_sysctl_tree(pi->dev);
8479 	children = SYSCTL_CHILDREN(oid);
8480 
8481 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
8482 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
8483 	    sysctl_linkdnrc, "A", "reason why link is down");
8484 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
8485 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
8486 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
8487 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
8488 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
8489 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
8490 		    sysctl_btphy, "I", "PHY firmware version");
8491 	}
8492 
8493 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
8494 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8495 	    sysctl_pause_settings, "A",
8496 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
8497 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
8498 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
8499 	    "FEC in use on the link");
8500 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
8501 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8502 	    sysctl_requested_fec, "A",
8503 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
8504 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
8505 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
8506 	    "FEC recommended by the cable/transceiver");
8507 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
8508 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8509 	    sysctl_autoneg, "I",
8510 	    "autonegotiation (-1 = not supported)");
8511 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
8512 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8513 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
8514 
8515 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
8516 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
8517 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
8518 	    &pi->link_cfg.pcaps, 0, "port capabilities");
8519 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
8520 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
8521 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
8522 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
8523 
8524 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
8525 	    port_top_speed(pi), "max speed (in Gbps)");
8526 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
8527 	    pi->mps_bg_map, "MPS buffer group map");
8528 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
8529 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
8530 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_chan", CTLFLAG_RD, NULL,
8531 	    pi->tx_chan, "TP tx c-channel");
8532 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_chan", CTLFLAG_RD, NULL,
8533 	    pi->rx_chan, "TP rx c-channel");
8534 
8535 	if (sc->flags & IS_VF)
8536 		return;
8537 
8538 	/*
8539 	 * dev.(cxgbe|cxl).X.tc.
8540 	 */
8541 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
8542 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
8543 	    "Tx scheduler traffic classes (cl_rl)");
8544 	children2 = SYSCTL_CHILDREN(oid);
8545 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
8546 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
8547 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
8548 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
8549 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
8550 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
8551 	for (i = 0; i < sc->params.nsched_cls; i++) {
8552 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
8553 
8554 		snprintf(name, sizeof(name), "%d", i);
8555 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
8556 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
8557 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
8558 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
8559 		    CTLFLAG_RD, &tc->state, 0, "current state");
8560 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
8561 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
8562 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
8563 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
8564 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
8565 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
8566 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8567 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
8568 		    "traffic class parameters");
8569 	}
8570 
8571 	/*
8572 	 * dev.cxgbe.X.stats.
8573 	 */
8574 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
8575 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
8576 	children = SYSCTL_CHILDREN(oid);
8577 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
8578 	    &pi->tx_parse_error, 0,
8579 	    "# of tx packets with invalid length or # of segments");
8580 
8581 #define T4_LBSTAT(name, stat, desc) do { \
8582 	if (sc->params.tp.lb_mode) { \
8583 		SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8584 		    CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, \
8585 		    A_MPS_PORT_STAT_##stat##_L, \
8586 		    sysctl_handle_t4_portstat64, "QU", desc); \
8587 	} else { \
8588 		SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8589 		    CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8590 		    t4_port_reg(sc, pi->tx_chan, A_MPS_PORT_STAT_##stat##_L), \
8591 		    sysctl_handle_t4_reg64, "QU", desc); \
8592 	} \
8593 } while (0)
8594 
8595 	T4_LBSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
8596 	T4_LBSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
8597 	T4_LBSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
8598 	T4_LBSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
8599 	T4_LBSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
8600 	T4_LBSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
8601 	T4_LBSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
8602 	T4_LBSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
8603 	T4_LBSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
8604 	T4_LBSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
8605 	T4_LBSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
8606 	T4_LBSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
8607 	T4_LBSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
8608 	T4_LBSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
8609 	T4_LBSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
8610 	T4_LBSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
8611 	T4_LBSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
8612 	T4_LBSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
8613 	T4_LBSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
8614 	T4_LBSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
8615 	T4_LBSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
8616 	T4_LBSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
8617 	T4_LBSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
8618 
8619 	T4_LBSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
8620 	T4_LBSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
8621 	T4_LBSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
8622 	T4_LBSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
8623 	T4_LBSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
8624 	T4_LBSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
8625 	T4_LBSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
8626 	if (is_t6(sc)) {
8627 		/* Read from port_stats and may be stale by up to 1s */
8628 		SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, "rx_fcs_err",
8629 		    CTLFLAG_RD, &pi->stats.rx_fcs_err,
8630 		    "# of frames received with bad FCS since last link up");
8631 	} else {
8632 		T4_LBSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
8633 		    "# of frames received with bad FCS");
8634 	}
8635 	T4_LBSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
8636 	T4_LBSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
8637 	T4_LBSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
8638 	T4_LBSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
8639 	T4_LBSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
8640 	T4_LBSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
8641 	T4_LBSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
8642 	T4_LBSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
8643 	T4_LBSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
8644 	T4_LBSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
8645 	T4_LBSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
8646 	T4_LBSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
8647 	T4_LBSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
8648 	T4_LBSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
8649 	T4_LBSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
8650 	T4_LBSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
8651 	T4_LBSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
8652 	T4_LBSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
8653 	T4_LBSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
8654 #undef T4_LBSTAT
8655 
8656 #define T4_REGSTAT(name, stat, desc) do { \
8657 	SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8658 	    CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8659 	    A_MPS_STAT_##stat##_L, sysctl_handle_t4_reg64, "QU", desc); \
8660 } while (0)
8661 
8662 	if (pi->mps_bg_map & 1) {
8663 		T4_REGSTAT(rx_ovflow0, RX_BG_0_MAC_DROP_FRAME,
8664 		    "# drops due to buffer-group 0 overflows");
8665 		T4_REGSTAT(rx_trunc0, RX_BG_0_MAC_TRUNC_FRAME,
8666 		    "# of buffer-group 0 truncated packets");
8667 	}
8668 	if (pi->mps_bg_map & 2) {
8669 		T4_REGSTAT(rx_ovflow1, RX_BG_1_MAC_DROP_FRAME,
8670 		    "# drops due to buffer-group 1 overflows");
8671 		T4_REGSTAT(rx_trunc1, RX_BG_1_MAC_TRUNC_FRAME,
8672 		    "# of buffer-group 1 truncated packets");
8673 	}
8674 	if (pi->mps_bg_map & 4) {
8675 		T4_REGSTAT(rx_ovflow2, RX_BG_2_MAC_DROP_FRAME,
8676 		    "# drops due to buffer-group 2 overflows");
8677 		T4_REGSTAT(rx_trunc2, RX_BG_2_MAC_TRUNC_FRAME,
8678 		    "# of buffer-group 2 truncated packets");
8679 	}
8680 	if (pi->mps_bg_map & 8) {
8681 		T4_REGSTAT(rx_ovflow3, RX_BG_3_MAC_DROP_FRAME,
8682 		    "# drops due to buffer-group 3 overflows");
8683 		T4_REGSTAT(rx_trunc3, RX_BG_3_MAC_TRUNC_FRAME,
8684 		    "# of buffer-group 3 truncated packets");
8685 	}
8686 #undef T4_REGSTAT
8687 }
8688 
8689 static int
8690 sysctl_int_array(SYSCTL_HANDLER_ARGS)
8691 {
8692 	int rc, *i, space = 0;
8693 	struct sbuf sb;
8694 
8695 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
8696 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
8697 		if (space)
8698 			sbuf_printf(&sb, " ");
8699 		sbuf_printf(&sb, "%d", *i);
8700 		space = 1;
8701 	}
8702 	rc = sbuf_finish(&sb);
8703 	sbuf_delete(&sb);
8704 	return (rc);
8705 }
8706 
8707 static int
8708 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
8709 {
8710 	int rc;
8711 	struct sbuf *sb;
8712 
8713 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8714 	if (sb == NULL)
8715 		return (ENOMEM);
8716 
8717 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8718 	rc = sbuf_finish(sb);
8719 	sbuf_delete(sb);
8720 
8721 	return (rc);
8722 }
8723 
8724 static int
8725 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8726 {
8727 	int rc;
8728 	struct sbuf *sb;
8729 
8730 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8731 	if (sb == NULL)
8732 		return (ENOMEM);
8733 
8734 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8735 	rc = sbuf_finish(sb);
8736 	sbuf_delete(sb);
8737 
8738 	return (rc);
8739 }
8740 
8741 static int
8742 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8743 {
8744 	struct port_info *pi = arg1;
8745 	int op = arg2;
8746 	struct adapter *sc = pi->adapter;
8747 	u_int v;
8748 	int rc;
8749 
8750 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8751 	if (rc)
8752 		return (rc);
8753 	if (!hw_all_ok(sc))
8754 		rc = ENXIO;
8755 	else {
8756 		/* XXX: magic numbers */
8757 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8758 		    op ? 0x20 : 0xc820, &v);
8759 	}
8760 	end_synchronized_op(sc, 0);
8761 	if (rc)
8762 		return (rc);
8763 	if (op == 0)
8764 		v /= 256;
8765 
8766 	rc = sysctl_handle_int(oidp, &v, 0, req);
8767 	return (rc);
8768 }
8769 
8770 static int
8771 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8772 {
8773 	struct vi_info *vi = arg1;
8774 	int rc, val;
8775 
8776 	val = vi->rsrv_noflowq;
8777 	rc = sysctl_handle_int(oidp, &val, 0, req);
8778 	if (rc != 0 || req->newptr == NULL)
8779 		return (rc);
8780 
8781 	if ((val >= 1) && (vi->ntxq > 1))
8782 		vi->rsrv_noflowq = 1;
8783 	else
8784 		vi->rsrv_noflowq = 0;
8785 
8786 	return (rc);
8787 }
8788 
8789 static int
8790 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8791 {
8792 	struct vi_info *vi = arg1;
8793 	struct adapter *sc = vi->adapter;
8794 	int rc, val, i;
8795 
8796 	MPASS(!(sc->flags & IS_VF));
8797 
8798 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8799 	rc = sysctl_handle_int(oidp, &val, 0, req);
8800 	if (rc != 0 || req->newptr == NULL)
8801 		return (rc);
8802 
8803 	if (val != 0 && val != 1)
8804 		return (EINVAL);
8805 
8806 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8807 	    "t4txvm");
8808 	if (rc)
8809 		return (rc);
8810 	if (!hw_all_ok(sc))
8811 		rc = ENXIO;
8812 	else if (if_getdrvflags(vi->ifp) & IFF_DRV_RUNNING) {
8813 		/*
8814 		 * We don't want parse_pkt to run with one setting (VF or PF)
8815 		 * and then eth_tx to see a different setting but still use
8816 		 * stale information calculated by parse_pkt.
8817 		 */
8818 		rc = EBUSY;
8819 	} else {
8820 		struct port_info *pi = vi->pi;
8821 		struct sge_txq *txq;
8822 		uint32_t ctrl0;
8823 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8824 
8825 		if (val) {
8826 			vi->flags |= TX_USES_VM_WR;
8827 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_VM_TSO);
8828 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8829 			    V_TXPKT_INTF(pi->hw_port));
8830 			if (!(sc->flags & IS_VF))
8831 				npkt--;
8832 		} else {
8833 			vi->flags &= ~TX_USES_VM_WR;
8834 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_TSO);
8835 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8836 			    V_TXPKT_INTF(pi->hw_port) | V_TXPKT_PF(sc->pf) |
8837 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8838 		}
8839 		for_each_txq(vi, i, txq) {
8840 			txq->cpl_ctrl0 = ctrl0;
8841 			txq->txp.max_npkt = npkt;
8842 		}
8843 	}
8844 	end_synchronized_op(sc, LOCK_HELD);
8845 	return (rc);
8846 }
8847 
8848 static int
8849 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8850 {
8851 	struct vi_info *vi = arg1;
8852 	struct adapter *sc = vi->adapter;
8853 	int idx, rc, i;
8854 	struct sge_rxq *rxq;
8855 	uint8_t v;
8856 
8857 	idx = vi->tmr_idx;
8858 
8859 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8860 	if (rc != 0 || req->newptr == NULL)
8861 		return (rc);
8862 
8863 	if (idx < 0 || idx >= SGE_NTIMERS)
8864 		return (EINVAL);
8865 
8866 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8867 	    "t4tmr");
8868 	if (rc)
8869 		return (rc);
8870 
8871 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8872 	for_each_rxq(vi, i, rxq) {
8873 #ifdef atomic_store_rel_8
8874 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8875 #else
8876 		rxq->iq.intr_params = v;
8877 #endif
8878 	}
8879 	vi->tmr_idx = idx;
8880 
8881 	end_synchronized_op(sc, LOCK_HELD);
8882 	return (0);
8883 }
8884 
8885 static int
8886 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8887 {
8888 	struct vi_info *vi = arg1;
8889 	struct adapter *sc = vi->adapter;
8890 	int idx, rc;
8891 
8892 	idx = vi->pktc_idx;
8893 
8894 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8895 	if (rc != 0 || req->newptr == NULL)
8896 		return (rc);
8897 
8898 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8899 		return (EINVAL);
8900 
8901 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8902 	    "t4pktc");
8903 	if (rc)
8904 		return (rc);
8905 
8906 	if (vi->flags & VI_INIT_DONE)
8907 		rc = EBUSY; /* cannot be changed once the queues are created */
8908 	else
8909 		vi->pktc_idx = idx;
8910 
8911 	end_synchronized_op(sc, LOCK_HELD);
8912 	return (rc);
8913 }
8914 
8915 static int
8916 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8917 {
8918 	struct vi_info *vi = arg1;
8919 	struct adapter *sc = vi->adapter;
8920 	int qsize, rc;
8921 
8922 	qsize = vi->qsize_rxq;
8923 
8924 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8925 	if (rc != 0 || req->newptr == NULL)
8926 		return (rc);
8927 
8928 	if (qsize < 128 || (qsize & 7))
8929 		return (EINVAL);
8930 
8931 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8932 	    "t4rxqs");
8933 	if (rc)
8934 		return (rc);
8935 
8936 	if (vi->flags & VI_INIT_DONE)
8937 		rc = EBUSY; /* cannot be changed once the queues are created */
8938 	else
8939 		vi->qsize_rxq = qsize;
8940 
8941 	end_synchronized_op(sc, LOCK_HELD);
8942 	return (rc);
8943 }
8944 
8945 static int
8946 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8947 {
8948 	struct vi_info *vi = arg1;
8949 	struct adapter *sc = vi->adapter;
8950 	int qsize, rc;
8951 
8952 	qsize = vi->qsize_txq;
8953 
8954 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8955 	if (rc != 0 || req->newptr == NULL)
8956 		return (rc);
8957 
8958 	if (qsize < 128 || qsize > 65536)
8959 		return (EINVAL);
8960 
8961 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8962 	    "t4txqs");
8963 	if (rc)
8964 		return (rc);
8965 
8966 	if (vi->flags & VI_INIT_DONE)
8967 		rc = EBUSY; /* cannot be changed once the queues are created */
8968 	else
8969 		vi->qsize_txq = qsize;
8970 
8971 	end_synchronized_op(sc, LOCK_HELD);
8972 	return (rc);
8973 }
8974 
8975 static int
8976 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8977 {
8978 	struct port_info *pi = arg1;
8979 	struct adapter *sc = pi->adapter;
8980 	struct link_config *lc = &pi->link_cfg;
8981 	int rc;
8982 
8983 	if (req->newptr == NULL) {
8984 		struct sbuf *sb;
8985 		static char *bits = "\20\1RX\2TX\3AUTO";
8986 
8987 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8988 		if (sb == NULL)
8989 			return (ENOMEM);
8990 
8991 		if (lc->link_ok) {
8992 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8993 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8994 		} else {
8995 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8996 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8997 		}
8998 		rc = sbuf_finish(sb);
8999 		sbuf_delete(sb);
9000 	} else {
9001 		char s[2];
9002 		int n;
9003 
9004 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
9005 		    PAUSE_AUTONEG));
9006 		s[1] = 0;
9007 
9008 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
9009 		if (rc != 0)
9010 			return(rc);
9011 
9012 		if (s[1] != 0)
9013 			return (EINVAL);
9014 		if (s[0] < '0' || s[0] > '9')
9015 			return (EINVAL);	/* not a number */
9016 		n = s[0] - '0';
9017 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
9018 			return (EINVAL);	/* some other bit is set too */
9019 
9020 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
9021 		    "t4PAUSE");
9022 		if (rc)
9023 			return (rc);
9024 		if (hw_all_ok(sc)) {
9025 			PORT_LOCK(pi);
9026 			lc->requested_fc = n;
9027 			fixup_link_config(pi);
9028 			if (pi->up_vis > 0)
9029 				rc = apply_link_config(pi);
9030 			set_current_media(pi);
9031 			PORT_UNLOCK(pi);
9032 		}
9033 		end_synchronized_op(sc, 0);
9034 	}
9035 
9036 	return (rc);
9037 }
9038 
9039 static int
9040 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
9041 {
9042 	struct port_info *pi = arg1;
9043 	struct link_config *lc = &pi->link_cfg;
9044 	int rc;
9045 	struct sbuf *sb;
9046 
9047 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
9048 	if (sb == NULL)
9049 		return (ENOMEM);
9050 	if (lc->link_ok)
9051 		sbuf_printf(sb, "%b", lc->fec, t4_fec_bits);
9052 	else
9053 		sbuf_printf(sb, "no link");
9054 	rc = sbuf_finish(sb);
9055 	sbuf_delete(sb);
9056 
9057 	return (rc);
9058 }
9059 
9060 static int
9061 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
9062 {
9063 	struct port_info *pi = arg1;
9064 	struct adapter *sc = pi->adapter;
9065 	struct link_config *lc = &pi->link_cfg;
9066 	int rc;
9067 	int8_t old = lc->requested_fec;
9068 
9069 	if (req->newptr == NULL) {
9070 		struct sbuf *sb;
9071 
9072 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
9073 		if (sb == NULL)
9074 			return (ENOMEM);
9075 
9076 		sbuf_printf(sb, "%b", old, t4_fec_bits);
9077 		rc = sbuf_finish(sb);
9078 		sbuf_delete(sb);
9079 	} else {
9080 		char s[8];
9081 		int n;
9082 
9083 		snprintf(s, sizeof(s), "%d", old == FEC_AUTO ? -1 :
9084 		    old & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
9085 
9086 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
9087 		if (rc != 0)
9088 			return(rc);
9089 
9090 		n = strtol(&s[0], NULL, 0);
9091 		if (n < 0 || n & FEC_AUTO)
9092 			n = FEC_AUTO;
9093 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
9094 			return (EINVAL);/* some other bit is set too */
9095 
9096 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
9097 		    "t4reqf");
9098 		if (rc)
9099 			return (rc);
9100 		PORT_LOCK(pi);
9101 		if (lc->requested_fec != old) {
9102 			rc = EBUSY;
9103 			goto done;
9104 		}
9105 		if (n == FEC_AUTO)
9106 			lc->requested_fec = FEC_AUTO;
9107 		else if (n == 0 || n == FEC_NONE)
9108 			lc->requested_fec = FEC_NONE;
9109 		else {
9110 			if ((lc->pcaps |
9111 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
9112 			    lc->pcaps) {
9113 				rc = ENOTSUP;
9114 				goto done;
9115 			}
9116 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
9117 			    FEC_MODULE);
9118 		}
9119 		if (hw_all_ok(sc)) {
9120 			fixup_link_config(pi);
9121 			if (pi->up_vis > 0) {
9122 				rc = apply_link_config(pi);
9123 				if (rc != 0) {
9124 					lc->requested_fec = old;
9125 					if (rc == FW_EPROTO)
9126 						rc = ENOTSUP;
9127 				}
9128 			}
9129 		}
9130 done:
9131 		PORT_UNLOCK(pi);
9132 		end_synchronized_op(sc, 0);
9133 	}
9134 
9135 	return (rc);
9136 }
9137 
9138 static int
9139 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
9140 {
9141 	struct port_info *pi = arg1;
9142 	struct adapter *sc = pi->adapter;
9143 	struct link_config *lc = &pi->link_cfg;
9144 	int rc;
9145 	int8_t fec;
9146 	struct sbuf *sb;
9147 
9148 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
9149 	if (sb == NULL)
9150 		return (ENOMEM);
9151 
9152 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
9153 		rc = EBUSY;
9154 		goto done;
9155 	}
9156 	if (!hw_all_ok(sc)) {
9157 		rc = ENXIO;
9158 		goto done;
9159 	}
9160 	PORT_LOCK(pi);
9161 	if (pi->up_vis == 0) {
9162 		/*
9163 		 * If all the interfaces are administratively down the firmware
9164 		 * does not report transceiver changes.  Refresh port info here.
9165 		 * This is the only reason we have a synchronized op in this
9166 		 * function.  Just PORT_LOCK would have been enough otherwise.
9167 		 */
9168 		t4_update_port_info(pi);
9169 	}
9170 
9171 	fec = lc->fec_hint;
9172 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
9173 	    !fec_supported(lc->pcaps)) {
9174 		PORT_UNLOCK(pi);
9175 		sbuf_printf(sb, "n/a");
9176 	} else {
9177 		if (fec == 0)
9178 			fec = FEC_NONE;
9179 		PORT_UNLOCK(pi);
9180 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, t4_fec_bits);
9181 	}
9182 	rc = sbuf_finish(sb);
9183 done:
9184 	sbuf_delete(sb);
9185 	end_synchronized_op(sc, 0);
9186 
9187 	return (rc);
9188 }
9189 
9190 static int
9191 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
9192 {
9193 	struct port_info *pi = arg1;
9194 	struct adapter *sc = pi->adapter;
9195 	struct link_config *lc = &pi->link_cfg;
9196 	int rc, val;
9197 
9198 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
9199 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
9200 	else
9201 		val = -1;
9202 	rc = sysctl_handle_int(oidp, &val, 0, req);
9203 	if (rc != 0 || req->newptr == NULL)
9204 		return (rc);
9205 	if (val == 0)
9206 		val = AUTONEG_DISABLE;
9207 	else if (val == 1)
9208 		val = AUTONEG_ENABLE;
9209 	else
9210 		val = AUTONEG_AUTO;
9211 
9212 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
9213 	    "t4aneg");
9214 	if (rc)
9215 		return (rc);
9216 	PORT_LOCK(pi);
9217 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
9218 		rc = ENOTSUP;
9219 		goto done;
9220 	}
9221 	lc->requested_aneg = val;
9222 	if (hw_all_ok(sc)) {
9223 		fixup_link_config(pi);
9224 		if (pi->up_vis > 0)
9225 			rc = apply_link_config(pi);
9226 		set_current_media(pi);
9227 	}
9228 done:
9229 	PORT_UNLOCK(pi);
9230 	end_synchronized_op(sc, 0);
9231 	return (rc);
9232 }
9233 
9234 static int
9235 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
9236 {
9237 	struct port_info *pi = arg1;
9238 	struct adapter *sc = pi->adapter;
9239 	struct link_config *lc = &pi->link_cfg;
9240 	int rc, val;
9241 
9242 	val = lc->force_fec;
9243 	MPASS(val >= -1 && val <= 1);
9244 	rc = sysctl_handle_int(oidp, &val, 0, req);
9245 	if (rc != 0 || req->newptr == NULL)
9246 		return (rc);
9247 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
9248 		return (ENOTSUP);
9249 	if (val < -1 || val > 1)
9250 		return (EINVAL);
9251 
9252 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
9253 	if (rc)
9254 		return (rc);
9255 	PORT_LOCK(pi);
9256 	lc->force_fec = val;
9257 	if (hw_all_ok(sc)) {
9258 		fixup_link_config(pi);
9259 		if (pi->up_vis > 0)
9260 			rc = apply_link_config(pi);
9261 	}
9262 	PORT_UNLOCK(pi);
9263 	end_synchronized_op(sc, 0);
9264 	return (rc);
9265 }
9266 
9267 static int
9268 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
9269 {
9270 	struct adapter *sc = arg1;
9271 	int rc, reg = arg2;
9272 	uint64_t val;
9273 
9274 	mtx_lock(&sc->reg_lock);
9275 	if (hw_off_limits(sc))
9276 		rc = ENXIO;
9277 	else {
9278 		rc = 0;
9279 		val = t4_read_reg64(sc, reg);
9280 	}
9281 	mtx_unlock(&sc->reg_lock);
9282 	if (rc == 0)
9283 		rc = sysctl_handle_64(oidp, &val, 0, req);
9284 	return (rc);
9285 }
9286 
9287 static int
9288 sysctl_handle_t4_portstat64(SYSCTL_HANDLER_ARGS)
9289 {
9290 	struct port_info *pi = arg1;
9291 	struct adapter *sc = pi->adapter;
9292 	int rc, i, reg = arg2;
9293 	uint64_t val;
9294 
9295 	mtx_lock(&sc->reg_lock);
9296 	if (hw_off_limits(sc))
9297 		rc = ENXIO;
9298 	else {
9299 		val = 0;
9300 		for (i = 0; i < sc->params.tp.lb_nchan; i++) {
9301 			val += t4_read_reg64(sc,
9302 			    t4_port_reg(sc, pi->tx_chan + i, reg));
9303 		}
9304 		rc = 0;
9305 	}
9306 	mtx_unlock(&sc->reg_lock);
9307 	if (rc == 0)
9308 		rc = sysctl_handle_64(oidp, &val, 0, req);
9309 	return (rc);
9310 }
9311 
9312 static int
9313 sysctl_temperature(SYSCTL_HANDLER_ARGS)
9314 {
9315 	struct adapter *sc = arg1;
9316 	int rc, t;
9317 	uint32_t param, val;
9318 
9319 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
9320 	if (rc)
9321 		return (rc);
9322 	if (!hw_all_ok(sc))
9323 		rc = ENXIO;
9324 	else {
9325 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9326 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
9327 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
9328 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
9329 	}
9330 	end_synchronized_op(sc, 0);
9331 	if (rc)
9332 		return (rc);
9333 
9334 	/* unknown is returned as 0 but we display -1 in that case */
9335 	t = val == 0 ? -1 : val;
9336 
9337 	rc = sysctl_handle_int(oidp, &t, 0, req);
9338 	return (rc);
9339 }
9340 
9341 static int
9342 sysctl_vdd(SYSCTL_HANDLER_ARGS)
9343 {
9344 	struct adapter *sc = arg1;
9345 	int rc;
9346 	uint32_t param, val;
9347 
9348 	if (sc->params.core_vdd == 0) {
9349 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
9350 		    "t4vdd");
9351 		if (rc)
9352 			return (rc);
9353 		if (!hw_all_ok(sc))
9354 			rc = ENXIO;
9355 		else {
9356 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9357 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
9358 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
9359 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
9360 			    &param, &val);
9361 		}
9362 		end_synchronized_op(sc, 0);
9363 		if (rc)
9364 			return (rc);
9365 		sc->params.core_vdd = val;
9366 	}
9367 
9368 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
9369 }
9370 
9371 static int
9372 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
9373 {
9374 	struct adapter *sc = arg1;
9375 	int rc, v;
9376 	uint32_t param, val;
9377 
9378 	v = sc->sensor_resets;
9379 	rc = sysctl_handle_int(oidp, &v, 0, req);
9380 	if (rc != 0 || req->newptr == NULL || v <= 0)
9381 		return (rc);
9382 
9383 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
9384 	    chip_id(sc) < CHELSIO_T5)
9385 		return (ENOTSUP);
9386 
9387 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
9388 	if (rc)
9389 		return (rc);
9390 	if (!hw_all_ok(sc))
9391 		rc = ENXIO;
9392 	else {
9393 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9394 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
9395 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
9396 		val = 1;
9397 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
9398 	}
9399 	end_synchronized_op(sc, 0);
9400 	if (rc == 0)
9401 		sc->sensor_resets++;
9402 	return (rc);
9403 }
9404 
9405 static int
9406 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
9407 {
9408 	struct adapter *sc = arg1;
9409 	struct sbuf *sb;
9410 	int rc;
9411 	uint32_t param, val;
9412 	uint8_t coreid = (uint8_t)arg2;
9413 
9414 	KASSERT(coreid < sc->params.ncores,
9415 	    ("%s: bad coreid %u\n", __func__, coreid));
9416 
9417 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
9418 	if (rc)
9419 		return (rc);
9420 	if (!hw_all_ok(sc))
9421 		rc = ENXIO;
9422 	else {
9423 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9424 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD) |
9425 		    V_FW_PARAMS_PARAM_Y(coreid);
9426 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
9427 	}
9428 	end_synchronized_op(sc, 0);
9429 	if (rc)
9430 		return (rc);
9431 
9432 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9433 	if (sb == NULL)
9434 		return (ENOMEM);
9435 
9436 	if (val == 0xffffffff) {
9437 		/* Only debug and custom firmwares report load averages. */
9438 		sbuf_printf(sb, "not available");
9439 	} else {
9440 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
9441 		    (val >> 16) & 0xff);
9442 	}
9443 	rc = sbuf_finish(sb);
9444 	sbuf_delete(sb);
9445 
9446 	return (rc);
9447 }
9448 
9449 static int
9450 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
9451 {
9452 	struct adapter *sc = arg1;
9453 	struct sbuf *sb;
9454 	int rc, i;
9455 	uint16_t incr[NMTUS][NCCTRL_WIN];
9456 	static const char *dec_fac[] = {
9457 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
9458 		"0.9375"
9459 	};
9460 
9461 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9462 	if (sb == NULL)
9463 		return (ENOMEM);
9464 
9465 	rc = 0;
9466 	mtx_lock(&sc->reg_lock);
9467 	if (hw_off_limits(sc))
9468 		rc = ENXIO;
9469 	else
9470 		t4_read_cong_tbl(sc, incr);
9471 	mtx_unlock(&sc->reg_lock);
9472 	if (rc)
9473 		goto done;
9474 
9475 	for (i = 0; i < NCCTRL_WIN; ++i) {
9476 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
9477 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
9478 		    incr[5][i], incr[6][i], incr[7][i]);
9479 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
9480 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
9481 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
9482 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
9483 	}
9484 
9485 	rc = sbuf_finish(sb);
9486 done:
9487 	sbuf_delete(sb);
9488 	return (rc);
9489 }
9490 
9491 static int
9492 sysctl_cim_ibq(SYSCTL_HANDLER_ARGS)
9493 {
9494 	struct adapter *sc = arg1;
9495 	struct sbuf *sb;
9496 	int rc, i, n, qid, coreid;
9497 	uint32_t *buf, *p;
9498 
9499 	qid = arg2 & 0xffff;
9500 	coreid = arg2 >> 16;
9501 
9502 	KASSERT(qid >= 0 && qid < sc->chip_params->cim_num_ibq,
9503 	    ("%s: bad ibq qid %d\n", __func__, qid));
9504 	KASSERT(coreid >= 0 && coreid < sc->params.ncores,
9505 	    ("%s: bad coreid %d\n", __func__, coreid));
9506 
9507 	n = 4 * CIM_IBQ_SIZE;
9508 	buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
9509 	mtx_lock(&sc->reg_lock);
9510 	if (hw_off_limits(sc))
9511 		rc = -ENXIO;
9512 	else
9513 		rc = t4_read_cim_ibq_core(sc, coreid, qid, buf, n);
9514 	mtx_unlock(&sc->reg_lock);
9515 	if (rc < 0) {
9516 		rc = -rc;
9517 		goto done;
9518 	}
9519 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
9520 
9521 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9522 	if (sb == NULL) {
9523 		rc = ENOMEM;
9524 		goto done;
9525 	}
9526 	for (i = 0, p = buf; i < n; i += 16, p += 4)
9527 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
9528 		    p[2], p[3]);
9529 	rc = sbuf_finish(sb);
9530 	sbuf_delete(sb);
9531 done:
9532 	free(buf, M_CXGBE);
9533 	return (rc);
9534 }
9535 
9536 static int
9537 sysctl_cim_obq(SYSCTL_HANDLER_ARGS)
9538 {
9539 	struct adapter *sc = arg1;
9540 	struct sbuf *sb;
9541 	int rc, i, n, qid, coreid;
9542 	uint32_t *buf, *p;
9543 
9544 	qid = arg2 & 0xffff;
9545 	coreid = arg2 >> 16;
9546 
9547 	KASSERT(qid >= 0 && qid < sc->chip_params->cim_num_obq,
9548 	    ("%s: bad obq qid %d\n", __func__, qid));
9549 	KASSERT(coreid >= 0 && coreid < sc->params.ncores,
9550 	    ("%s: bad coreid %d\n", __func__, coreid));
9551 
9552 	n = 6 * CIM_OBQ_SIZE * 4;
9553 	buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
9554 	mtx_lock(&sc->reg_lock);
9555 	if (hw_off_limits(sc))
9556 		rc = -ENXIO;
9557 	else
9558 		rc = t4_read_cim_obq_core(sc, coreid, qid, buf, n);
9559 	mtx_unlock(&sc->reg_lock);
9560 	if (rc < 0) {
9561 		rc = -rc;
9562 		goto done;
9563 	}
9564 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
9565 
9566 	rc = sysctl_wire_old_buffer(req, 0);
9567 	if (rc != 0)
9568 		goto done;
9569 
9570 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9571 	if (sb == NULL) {
9572 		rc = ENOMEM;
9573 		goto done;
9574 	}
9575 	for (i = 0, p = buf; i < n; i += 16, p += 4)
9576 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
9577 		    p[2], p[3]);
9578 	rc = sbuf_finish(sb);
9579 	sbuf_delete(sb);
9580 done:
9581 	free(buf, M_CXGBE);
9582 	return (rc);
9583 }
9584 
9585 static void
9586 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9587 {
9588 	uint32_t *p;
9589 
9590 	sbuf_printf(sb, "Status   Data      PC%s",
9591 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9592 	    "     LS0Stat  LS0Addr             LS0Data");
9593 
9594 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
9595 		if (cfg & F_UPDBGLACAPTPCONLY) {
9596 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
9597 			    p[6], p[7]);
9598 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
9599 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
9600 			    p[4] & 0xff, p[5] >> 8);
9601 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
9602 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9603 			    p[1] & 0xf, p[2] >> 4);
9604 		} else {
9605 			sbuf_printf(sb,
9606 			    "\n  %02x   %x%07x %x%07x %08x %08x "
9607 			    "%08x%08x%08x%08x",
9608 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9609 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
9610 			    p[6], p[7]);
9611 		}
9612 	}
9613 }
9614 
9615 static void
9616 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9617 {
9618 	uint32_t *p;
9619 
9620 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
9621 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9622 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
9623 
9624 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
9625 		if (cfg & F_UPDBGLACAPTPCONLY) {
9626 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
9627 			    p[3] & 0xff, p[2], p[1], p[0]);
9628 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
9629 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
9630 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
9631 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
9632 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
9633 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
9634 			    p[6] >> 16);
9635 		} else {
9636 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
9637 			    "%08x %08x %08x %08x %08x %08x",
9638 			    (p[9] >> 16) & 0xff,
9639 			    p[9] & 0xffff, p[8] >> 16,
9640 			    p[8] & 0xffff, p[7] >> 16,
9641 			    p[7] & 0xffff, p[6] >> 16,
9642 			    p[2], p[1], p[0], p[5], p[4], p[3]);
9643 		}
9644 	}
9645 }
9646 
9647 static int
9648 sbuf_cim_la(struct adapter *sc, int coreid, struct sbuf *sb, int flags)
9649 {
9650 	uint32_t cfg, *buf;
9651 	int rc;
9652 
9653 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9654 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
9655 	    M_ZERO | flags);
9656 	if (buf == NULL)
9657 		return (ENOMEM);
9658 
9659 	mtx_lock(&sc->reg_lock);
9660 	if (hw_off_limits(sc))
9661 		rc = ENXIO;
9662 	else {
9663 		rc = -t4_cim_read_core(sc, 1, coreid, A_UP_UP_DBG_LA_CFG, 1,
9664 		    &cfg);
9665 		if (rc == 0)
9666 			rc = -t4_cim_read_la_core(sc, coreid, buf, NULL);
9667 	}
9668 	mtx_unlock(&sc->reg_lock);
9669 	if (rc == 0) {
9670 		if (chip_id(sc) < CHELSIO_T6)
9671 			sbuf_cim_la4(sc, sb, buf, cfg);
9672 		else
9673 			sbuf_cim_la6(sc, sb, buf, cfg);
9674 	}
9675 	free(buf, M_CXGBE);
9676 	return (rc);
9677 }
9678 
9679 static int
9680 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
9681 {
9682 	struct adapter *sc = arg1;
9683 	int coreid = arg2;
9684 	struct sbuf *sb;
9685 	int rc;
9686 
9687 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9688 	if (sb == NULL)
9689 		return (ENOMEM);
9690 
9691 	rc = sbuf_cim_la(sc, coreid, sb, M_WAITOK);
9692 	if (rc == 0)
9693 		rc = sbuf_finish(sb);
9694 	sbuf_delete(sb);
9695 	return (rc);
9696 }
9697 
9698 static void
9699 dump_cim_regs(struct adapter *sc)
9700 {
9701 	log(LOG_DEBUG, "%s: CIM debug regs1 %08x %08x %08x %08x %08x\n",
9702 	    device_get_nameunit(sc->dev),
9703 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9704 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9705 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA2),
9706 	    t4_read_reg(sc, A_EDC_H_BIST_DATA_PATTERN),
9707 	    t4_read_reg(sc, A_EDC_H_BIST_STATUS_RDATA));
9708 	log(LOG_DEBUG, "%s: CIM debug regs2 %08x %08x %08x %08x %08x\n",
9709 	    device_get_nameunit(sc->dev),
9710 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9711 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9712 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0 + 0x800),
9713 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1 + 0x800),
9714 	    t4_read_reg(sc, A_EDC_H_BIST_CMD_LEN));
9715 }
9716 
9717 static void
9718 dump_cimla(struct adapter *sc)
9719 {
9720 	struct sbuf sb;
9721 	int rc;
9722 
9723 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9724 		log(LOG_DEBUG, "%s: failed to generate CIM LA dump.\n",
9725 		    device_get_nameunit(sc->dev));
9726 		return;
9727 	}
9728 	rc = sbuf_cim_la(sc, 0, &sb, M_WAITOK);
9729 	if (rc == 0) {
9730 		rc = sbuf_finish(&sb);
9731 		if (rc == 0) {
9732 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s\n",
9733 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9734 		}
9735 	}
9736 	sbuf_delete(&sb);
9737 }
9738 
9739 void
9740 t4_os_cim_err(struct adapter *sc)
9741 {
9742 	atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
9743 }
9744 
9745 static int
9746 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
9747 {
9748 	struct adapter *sc = arg1;
9749 	u_int i;
9750 	struct sbuf *sb;
9751 	uint32_t *buf, *p;
9752 	int rc;
9753 
9754 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9755 	if (sb == NULL)
9756 		return (ENOMEM);
9757 
9758 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
9759 	    M_ZERO | M_WAITOK);
9760 
9761 	rc = 0;
9762 	mtx_lock(&sc->reg_lock);
9763 	if (hw_off_limits(sc))
9764 		rc = ENXIO;
9765 	else
9766 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
9767 	mtx_unlock(&sc->reg_lock);
9768 	if (rc)
9769 		goto done;
9770 
9771 	p = buf;
9772 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9773 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
9774 		    p[1], p[0]);
9775 	}
9776 
9777 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9778 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9779 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9780 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9781 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9782 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9783 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9784 		    p[0] & 1);
9785 	}
9786 	rc = sbuf_finish(sb);
9787 done:
9788 	sbuf_delete(sb);
9789 	free(buf, M_CXGBE);
9790 	return (rc);
9791 }
9792 
9793 static int
9794 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9795 {
9796 	struct adapter *sc = arg1;
9797 	u_int i;
9798 	struct sbuf *sb;
9799 	uint32_t *buf, *p;
9800 	int rc;
9801 
9802 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9803 	if (sb == NULL)
9804 		return (ENOMEM);
9805 
9806 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9807 	    M_ZERO | M_WAITOK);
9808 
9809 	rc = 0;
9810 	mtx_lock(&sc->reg_lock);
9811 	if (hw_off_limits(sc))
9812 		rc = ENXIO;
9813 	else
9814 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9815 	mtx_unlock(&sc->reg_lock);
9816 	if (rc)
9817 		goto done;
9818 
9819 	p = buf;
9820 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9821 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9822 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9823 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9824 		    p[4], p[3], p[2], p[1], p[0]);
9825 	}
9826 
9827 	sbuf_printf(sb, "\n\nCntl ID               Data");
9828 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9829 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9830 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9831 	}
9832 
9833 	rc = sbuf_finish(sb);
9834 done:
9835 	sbuf_delete(sb);
9836 	free(buf, M_CXGBE);
9837 	return (rc);
9838 }
9839 
9840 static int
9841 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9842 {
9843 	struct adapter *sc = arg1;
9844 	struct sbuf *sb;
9845 	int rc, i;
9846 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9847 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9848 	uint16_t thres[CIM_NUM_IBQ];
9849 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9850 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9851 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9852 	static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
9853 		"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
9854 		"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
9855 		"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
9856 	};
9857 
9858 	MPASS(chip_id(sc) < CHELSIO_T7);
9859 
9860 	cim_num_obq = sc->chip_params->cim_num_obq;
9861 	if (is_t4(sc)) {
9862 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9863 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9864 	} else {
9865 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9866 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9867 	}
9868 	nq = CIM_NUM_IBQ + cim_num_obq;
9869 
9870 	mtx_lock(&sc->reg_lock);
9871 	if (hw_off_limits(sc))
9872 		rc = ENXIO;
9873 	else {
9874 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9875 		if (rc == 0) {
9876 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9877 			    obq_wr);
9878 			if (rc == 0)
9879 				t4_read_cimq_cfg(sc, base, size, thres);
9880 		}
9881 	}
9882 	mtx_unlock(&sc->reg_lock);
9883 	if (rc)
9884 		return (rc);
9885 
9886 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9887 	if (sb == NULL)
9888 		return (ENOMEM);
9889 
9890 	sbuf_printf(sb,
9891 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9892 
9893 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9894 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9895 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9896 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9897 		    G_QUEREMFLITS(p[2]) * 16);
9898 	for ( ; i < nq; i++, p += 4, wr += 2)
9899 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9900 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9901 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9902 		    G_QUEREMFLITS(p[2]) * 16);
9903 
9904 	rc = sbuf_finish(sb);
9905 	sbuf_delete(sb);
9906 
9907 	return (rc);
9908 }
9909 
9910 static int
9911 sysctl_cim_qcfg_t7(SYSCTL_HANDLER_ARGS)
9912 {
9913 	struct adapter *sc = arg1;
9914 	u_int coreid = arg2;
9915 	struct sbuf *sb;
9916 	int rc, i;
9917 	u_int addr;
9918 	uint16_t base[CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7];
9919 	uint16_t size[CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7];
9920 	uint16_t thres[CIM_NUM_IBQ_T7];
9921 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T7], *wr = obq_wr;
9922 	uint32_t stat[4 * (CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7)], *p = stat;
9923 	static const char * const qname_ibq_t7[] = {
9924 		"TP0", "TP1", "TP2", "TP3", "ULP", "SGE0", "SGE1", "NC-SI",
9925 		"RSVD", "IPC1", "IPC2", "IPC3", "IPC4", "IPC5", "IPC6", "IPC7",
9926 	};
9927 	static const char * const qname_obq_t7[] = {
9928 		"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI", "SGE0-RX",
9929 		"RSVD", "RSVD", "IPC1", "IPC2", "IPC3", "IPC4", "IPC5",
9930 		"IPC6", "IPC7"
9931 	};
9932 	static const char * const qname_ibq_sec_t7[] = {
9933 		"TP0", "TP1", "TP2", "TP3", "ULP", "SGE0", "RSVD", "RSVD",
9934 		"RSVD", "IPC0", "RSVD", "RSVD", "RSVD", "RSVD",	"RSVD", "RSVD",
9935 	};
9936 	static const char * const qname_obq_sec_t7[] = {
9937 		"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "RSVD", "SGE0-RX",
9938 		"RSVD", "RSVD", "IPC0", "RSVD", "RSVD", "RSVD", "RSVD",
9939 		"RSVD", "RSVD",
9940 	};
9941 
9942 	MPASS(chip_id(sc) >= CHELSIO_T7);
9943 
9944 	mtx_lock(&sc->reg_lock);
9945 	if (hw_off_limits(sc))
9946 		rc = ENXIO;
9947 	else {
9948 		rc = -t4_cim_read_core(sc, 1, coreid,
9949 		    A_T7_UP_IBQ_0_SHADOW_RDADDR, 4 * CIM_NUM_IBQ_T7, stat);
9950 		if (rc != 0)
9951 			goto unlock;
9952 
9953 		rc = -t4_cim_read_core(sc, 1, coreid,
9954 		    A_T7_UP_OBQ_0_SHADOW_RDADDR, 4 * CIM_NUM_OBQ_T7,
9955 		    &stat[4 * CIM_NUM_IBQ_T7]);
9956 		if (rc != 0)
9957 			goto unlock;
9958 
9959 		addr = A_T7_UP_OBQ_0_SHADOW_REALADDR;
9960 		for (i = 0; i < CIM_NUM_OBQ_T7 * 2; i++, addr += 8) {
9961 			rc = -t4_cim_read_core(sc, 1, coreid, addr, 1,
9962 			    &obq_wr[i]);
9963 			if (rc != 0)
9964 				goto unlock;
9965 		}
9966 		t4_read_cimq_cfg_core(sc, coreid, base, size, thres);
9967 	}
9968 unlock:
9969 	mtx_unlock(&sc->reg_lock);
9970 	if (rc)
9971 		return (rc);
9972 
9973 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9974 	if (sb == NULL)
9975 		return (ENOMEM);
9976 
9977 	sbuf_printf(sb,
9978 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9979 
9980 	for (i = 0; i < CIM_NUM_IBQ_T7; i++, p += 4) {
9981 		if (!size[i])
9982 			continue;
9983 
9984 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9985 		    coreid == 0 ? qname_ibq_t7[i] : qname_ibq_sec_t7[i],
9986 		    base[i], size[i], thres[i], G_IBQRDADDR(p[0]) & 0xfff,
9987 		    G_IBQWRADDR(p[1]) & 0xfff, G_QUESOPCNT(p[3]),
9988 		    G_QUEEOPCNT(p[3]), G_T7_QUEREMFLITS(p[2]) * 16);
9989 	}
9990 
9991 	for ( ; i < CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7; i++, p += 4, wr += 2) {
9992 		if (!size[i])
9993 			continue;
9994 
9995 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u",
9996 		    coreid == 0 ? qname_obq_t7[i - CIM_NUM_IBQ_T7] :
9997 		    qname_obq_sec_t7[i - CIM_NUM_IBQ_T7],
9998 		    base[i], size[i], G_QUERDADDR(p[0]) & 0xfff,
9999 		    wr[0] << 1, G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
10000 		    G_T7_QUEREMFLITS(p[2]) * 16);
10001 	}
10002 
10003 	rc = sbuf_finish(sb);
10004 	sbuf_delete(sb);
10005 	return (rc);
10006 }
10007 
10008 static int
10009 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
10010 {
10011 	struct adapter *sc = arg1;
10012 	struct sbuf *sb;
10013 	int rc;
10014 	struct tp_cpl_stats stats;
10015 
10016 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10017 	if (sb == NULL)
10018 		return (ENOMEM);
10019 
10020 	rc = 0;
10021 	mtx_lock(&sc->reg_lock);
10022 	if (hw_off_limits(sc))
10023 		rc = ENXIO;
10024 	else
10025 		t4_tp_get_cpl_stats(sc, &stats, 0);
10026 	mtx_unlock(&sc->reg_lock);
10027 	if (rc)
10028 		goto done;
10029 
10030 	if (sc->chip_params->nchan > 2) {
10031 		sbuf_printf(sb, "                 channel 0  channel 1"
10032 		    "  channel 2  channel 3");
10033 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
10034 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
10035 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
10036 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
10037 	} else {
10038 		sbuf_printf(sb, "                 channel 0  channel 1");
10039 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
10040 		    stats.req[0], stats.req[1]);
10041 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
10042 		    stats.rsp[0], stats.rsp[1]);
10043 	}
10044 
10045 	rc = sbuf_finish(sb);
10046 done:
10047 	sbuf_delete(sb);
10048 	return (rc);
10049 }
10050 
10051 static int
10052 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
10053 {
10054 	struct adapter *sc = arg1;
10055 	struct sbuf *sb;
10056 	int rc;
10057 	struct tp_usm_stats stats;
10058 
10059 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10060 	if (sb == NULL)
10061 		return (ENOMEM);
10062 
10063 	rc = 0;
10064 	mtx_lock(&sc->reg_lock);
10065 	if (hw_off_limits(sc))
10066 		rc = ENXIO;
10067 	else
10068 		t4_get_usm_stats(sc, &stats, 1);
10069 	mtx_unlock(&sc->reg_lock);
10070 	if (rc == 0) {
10071 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
10072 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
10073 		sbuf_printf(sb, "Drops:  %u", stats.drops);
10074 		rc = sbuf_finish(sb);
10075 	}
10076 	sbuf_delete(sb);
10077 
10078 	return (rc);
10079 }
10080 
10081 static int
10082 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
10083 {
10084 	struct adapter *sc = arg1;
10085 	struct sbuf *sb;
10086 	int rc;
10087 	struct tp_tid_stats stats;
10088 
10089 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10090 	if (sb == NULL)
10091 		return (ENOMEM);
10092 
10093 	rc = 0;
10094 	mtx_lock(&sc->reg_lock);
10095 	if (hw_off_limits(sc))
10096 		rc = ENXIO;
10097 	else
10098 		t4_tp_get_tid_stats(sc, &stats, 1);
10099 	mtx_unlock(&sc->reg_lock);
10100 	if (rc == 0) {
10101 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
10102 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
10103 		sbuf_printf(sb, "Active:     %u\n", stats.act);
10104 		sbuf_printf(sb, "Passive:    %u", stats.pas);
10105 		rc = sbuf_finish(sb);
10106 	}
10107 	sbuf_delete(sb);
10108 
10109 	return (rc);
10110 }
10111 
10112 static const char * const devlog_level_strings[] = {
10113 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
10114 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
10115 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
10116 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
10117 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
10118 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
10119 };
10120 
10121 static const char * const devlog_facility_strings[] = {
10122 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
10123 	[FW_DEVLOG_FACILITY_CF]		= "CF",
10124 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
10125 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
10126 	[FW_DEVLOG_FACILITY_RES]	= "RES",
10127 	[FW_DEVLOG_FACILITY_HW]		= "HW",
10128 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
10129 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
10130 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
10131 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
10132 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
10133 	[FW_DEVLOG_FACILITY_VI]		= "VI",
10134 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
10135 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
10136 	[FW_DEVLOG_FACILITY_TM]		= "TM",
10137 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
10138 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
10139 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
10140 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
10141 	[FW_DEVLOG_FACILITY_RI]		= "RI",
10142 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
10143 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
10144 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
10145 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
10146 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
10147 };
10148 
10149 static int
10150 sbuf_devlog(struct adapter *sc, int coreid, struct sbuf *sb, int flags)
10151 {
10152 	int i, j, rc, nentries, first = 0;
10153 	struct devlog_params *dparams = &sc->params.devlog;
10154 	struct fw_devlog_e *buf, *e;
10155 	uint32_t addr, size;
10156 	uint64_t ftstamp = UINT64_MAX;
10157 
10158 	KASSERT(coreid >= 0 && coreid < sc->params.ncores,
10159 	    ("%s: bad coreid %d\n", __func__, coreid));
10160 
10161 	if (dparams->addr == 0)
10162 		return (ENXIO);
10163 
10164 	size = dparams->size / sc->params.ncores;
10165 	addr = dparams->addr + coreid * size;
10166 
10167 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
10168 	buf = malloc(size, M_CXGBE, M_ZERO | flags);
10169 	if (buf == NULL)
10170 		return (ENOMEM);
10171 
10172 	mtx_lock(&sc->reg_lock);
10173 	if (hw_off_limits(sc))
10174 		rc = ENXIO;
10175 	else
10176 		rc = read_via_memwin(sc, 1, addr, (void *)buf, size);
10177 	mtx_unlock(&sc->reg_lock);
10178 	if (rc != 0)
10179 		goto done;
10180 
10181 	nentries = size / sizeof(struct fw_devlog_e);
10182 	for (i = 0; i < nentries; i++) {
10183 		e = &buf[i];
10184 
10185 		if (e->timestamp == 0)
10186 			break;	/* end */
10187 
10188 		e->timestamp = be64toh(e->timestamp);
10189 		e->seqno = be32toh(e->seqno);
10190 		for (j = 0; j < 8; j++)
10191 			e->params[j] = be32toh(e->params[j]);
10192 
10193 		if (e->timestamp < ftstamp) {
10194 			ftstamp = e->timestamp;
10195 			first = i;
10196 		}
10197 	}
10198 
10199 	if (buf[first].timestamp == 0)
10200 		goto done;	/* nothing in the log */
10201 
10202 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
10203 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
10204 
10205 	i = first;
10206 	do {
10207 		e = &buf[i];
10208 		if (e->timestamp == 0)
10209 			break;	/* end */
10210 
10211 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
10212 		    e->seqno, e->timestamp,
10213 		    (e->level < nitems(devlog_level_strings) ?
10214 			devlog_level_strings[e->level] : "UNKNOWN"),
10215 		    (e->facility < nitems(devlog_facility_strings) ?
10216 			devlog_facility_strings[e->facility] : "UNKNOWN"));
10217 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
10218 		    e->params[2], e->params[3], e->params[4],
10219 		    e->params[5], e->params[6], e->params[7]);
10220 
10221 		if (++i == nentries)
10222 			i = 0;
10223 	} while (i != first);
10224 done:
10225 	free(buf, M_CXGBE);
10226 	return (rc);
10227 }
10228 
10229 static int
10230 sysctl_devlog(SYSCTL_HANDLER_ARGS)
10231 {
10232 	struct adapter *sc = arg1;
10233 	int rc, i, coreid = arg2;
10234 	struct sbuf *sb;
10235 
10236 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10237 	if (sb == NULL)
10238 		return (ENOMEM);
10239 	if (coreid == -1) {
10240 		/* -1 means all cores */
10241 		for (i = rc = 0; i < sc->params.ncores && rc == 0; i++) {
10242 			if (sc->params.ncores > 0)
10243 				sbuf_printf(sb, "=== CIM core %u ===\n", i);
10244 			rc = sbuf_devlog(sc, i, sb, M_WAITOK);
10245 		}
10246 	} else {
10247 		KASSERT(coreid >= 0 && coreid < sc->params.ncores,
10248 		    ("%s: bad coreid %d\n", __func__, coreid));
10249 		rc = sbuf_devlog(sc, coreid, sb, M_WAITOK);
10250 	}
10251 	if (rc == 0)
10252 		rc = sbuf_finish(sb);
10253 	sbuf_delete(sb);
10254 	return (rc);
10255 }
10256 
10257 static void
10258 dump_devlog(struct adapter *sc)
10259 {
10260 	int rc, i;
10261 	struct sbuf sb;
10262 
10263 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
10264 		log(LOG_DEBUG, "%s: failed to generate devlog dump.\n",
10265 		    device_get_nameunit(sc->dev));
10266 		return;
10267 	}
10268 	for (i = rc = 0; i < sc->params.ncores && rc == 0; i++) {
10269 		if (sc->params.ncores > 0)
10270 			sbuf_printf(&sb, "=== CIM core %u ===\n", i);
10271 		rc = sbuf_devlog(sc, i, &sb, M_WAITOK);
10272 	}
10273 	if (rc == 0) {
10274 		sbuf_finish(&sb);
10275 		log(LOG_DEBUG, "%s: device log follows.\n%s",
10276 		    device_get_nameunit(sc->dev), sbuf_data(&sb));
10277 	}
10278 	sbuf_delete(&sb);
10279 }
10280 
10281 static int
10282 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
10283 {
10284 	struct adapter *sc = arg1;
10285 	struct sbuf *sb;
10286 	int rc;
10287 	struct tp_fcoe_stats stats[MAX_NCHAN];
10288 	int i, nchan = sc->chip_params->nchan;
10289 
10290 	rc = 0;
10291 	mtx_lock(&sc->reg_lock);
10292 	if (hw_off_limits(sc))
10293 		rc = ENXIO;
10294 	else {
10295 		for (i = 0; i < nchan; i++)
10296 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
10297 	}
10298 	mtx_unlock(&sc->reg_lock);
10299 	if (rc != 0)
10300 		return (rc);
10301 
10302 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10303 	if (sb == NULL)
10304 		return (ENOMEM);
10305 
10306 	if (nchan > 2) {
10307 		sbuf_printf(sb, "                   channel 0        channel 1"
10308 		    "        channel 2        channel 3");
10309 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
10310 		    stats[0].octets_ddp, stats[1].octets_ddp,
10311 		    stats[2].octets_ddp, stats[3].octets_ddp);
10312 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
10313 		    stats[0].frames_ddp, stats[1].frames_ddp,
10314 		    stats[2].frames_ddp, stats[3].frames_ddp);
10315 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
10316 		    stats[0].frames_drop, stats[1].frames_drop,
10317 		    stats[2].frames_drop, stats[3].frames_drop);
10318 	} else {
10319 		sbuf_printf(sb, "                   channel 0        channel 1");
10320 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
10321 		    stats[0].octets_ddp, stats[1].octets_ddp);
10322 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
10323 		    stats[0].frames_ddp, stats[1].frames_ddp);
10324 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
10325 		    stats[0].frames_drop, stats[1].frames_drop);
10326 	}
10327 
10328 	rc = sbuf_finish(sb);
10329 	sbuf_delete(sb);
10330 
10331 	return (rc);
10332 }
10333 
10334 static int
10335 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
10336 {
10337 	struct adapter *sc = arg1;
10338 	struct sbuf *sb;
10339 	int rc, i;
10340 	unsigned int map, kbps, ipg, mode;
10341 	unsigned int pace_tab[NTX_SCHED];
10342 
10343 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
10344 	if (sb == NULL)
10345 		return (ENOMEM);
10346 
10347 	mtx_lock(&sc->reg_lock);
10348 	if (hw_off_limits(sc)) {
10349 		mtx_unlock(&sc->reg_lock);
10350 		rc = ENXIO;
10351 		goto done;
10352 	}
10353 
10354 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
10355 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
10356 	t4_read_pace_tbl(sc, pace_tab);
10357 	mtx_unlock(&sc->reg_lock);
10358 
10359 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
10360 	    "Class IPG (0.1 ns)   Flow IPG (us)");
10361 
10362 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
10363 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
10364 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
10365 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
10366 		if (kbps)
10367 			sbuf_printf(sb, "%9u     ", kbps);
10368 		else
10369 			sbuf_printf(sb, " disabled     ");
10370 
10371 		if (ipg)
10372 			sbuf_printf(sb, "%13u        ", ipg);
10373 		else
10374 			sbuf_printf(sb, "     disabled        ");
10375 
10376 		if (pace_tab[i])
10377 			sbuf_printf(sb, "%10u", pace_tab[i]);
10378 		else
10379 			sbuf_printf(sb, "  disabled");
10380 	}
10381 	rc = sbuf_finish(sb);
10382 done:
10383 	sbuf_delete(sb);
10384 	return (rc);
10385 }
10386 
10387 static int
10388 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
10389 {
10390 	struct adapter *sc = arg1;
10391 	struct sbuf *sb;
10392 	int rc, i, j;
10393 	uint64_t *p0, *p1;
10394 	struct lb_port_stats s[2];
10395 	static const char *stat_name[] = {
10396 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
10397 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
10398 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
10399 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
10400 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
10401 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
10402 		"BG2FramesTrunc:", "BG3FramesTrunc:"
10403 	};
10404 
10405 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10406 	if (sb == NULL)
10407 		return (ENOMEM);
10408 
10409 	memset(s, 0, sizeof(s));
10410 
10411 	rc = 0;
10412 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
10413 		mtx_lock(&sc->reg_lock);
10414 		if (hw_off_limits(sc))
10415 			rc = ENXIO;
10416 		else {
10417 			t4_get_lb_stats(sc, i, &s[0]);
10418 			t4_get_lb_stats(sc, i + 1, &s[1]);
10419 		}
10420 		mtx_unlock(&sc->reg_lock);
10421 		if (rc != 0)
10422 			break;
10423 
10424 		p0 = &s[0].octets;
10425 		p1 = &s[1].octets;
10426 		sbuf_printf(sb, "%s                       Loopback %u"
10427 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
10428 
10429 		for (j = 0; j < nitems(stat_name); j++)
10430 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
10431 				   *p0++, *p1++);
10432 	}
10433 
10434 	if (rc == 0)
10435 		rc = sbuf_finish(sb);
10436 	sbuf_delete(sb);
10437 
10438 	return (rc);
10439 }
10440 
10441 static int
10442 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
10443 {
10444 	int rc = 0;
10445 	struct port_info *pi = arg1;
10446 	struct link_config *lc = &pi->link_cfg;
10447 	struct sbuf *sb;
10448 
10449 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
10450 	if (sb == NULL)
10451 		return (ENOMEM);
10452 
10453 	if (lc->link_ok || lc->link_down_rc == 255)
10454 		sbuf_printf(sb, "n/a");
10455 	else
10456 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
10457 
10458 	rc = sbuf_finish(sb);
10459 	sbuf_delete(sb);
10460 
10461 	return (rc);
10462 }
10463 
10464 struct mem_desc {
10465 	uint64_t base;
10466 	uint64_t limit;
10467 	u_int idx;
10468 };
10469 
10470 static int
10471 mem_desc_cmp(const void *a, const void *b)
10472 {
10473 	const uint64_t v1 = ((const struct mem_desc *)a)->base;
10474 	const uint64_t v2 = ((const struct mem_desc *)b)->base;
10475 
10476 	if (v1 < v2)
10477 		return (-1);
10478 	else if (v1 > v2)
10479 		return (1);
10480 
10481 	return (0);
10482 }
10483 
10484 static void
10485 mem_region_show(struct sbuf *sb, const char *name, uint64_t from, uint64_t to)
10486 {
10487 	uintmax_t size;
10488 
10489 	if (from == to)
10490 		return;
10491 
10492 	size = to - from + 1;
10493 	if (size == 0)
10494 		return;
10495 
10496 	if (from > UINT32_MAX || to > UINT32_MAX)
10497 		sbuf_printf(sb, "%-18s 0x%012jx-0x%012jx [%ju]\n", name,
10498 		    (uintmax_t)from, (uintmax_t)to, size);
10499 	else
10500 		sbuf_printf(sb, "%-18s 0x%08jx-0x%08jx [%ju]\n", name,
10501 		    (uintmax_t)from, (uintmax_t)to, size);
10502 }
10503 
10504 static int
10505 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
10506 {
10507 	struct adapter *sc = arg1;
10508 	struct sbuf *sb;
10509 	int rc, i, n, nchan;
10510 	uint32_t lo, hi, used, free, alloc;
10511 	static const char *memory[] = {
10512 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
10513 	};
10514 	static const char *region[] = {
10515 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
10516 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
10517 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
10518 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
10519 		"RQUDP region:", "PBL region:", "TXPBL region:",
10520 		"TLSKey region:", "RRQ region:", "NVMe STAG region:",
10521 		"NVMe RQ region:", "NVMe RXPBL region:", "NVMe TPT region:",
10522 		"NVMe TXPBL region:", "DBVFIFO region:", "ULPRX state:",
10523 		"ULPTX state:", "RoCE RRQ region:", "On-chip queues:",
10524 	};
10525 	struct mem_desc avail[4];
10526 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
10527 	struct mem_desc *md;
10528 
10529 	rc = sysctl_wire_old_buffer(req, 0);
10530 	if (rc != 0)
10531 		return (rc);
10532 
10533 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10534 	if (sb == NULL)
10535 		return (ENOMEM);
10536 
10537 	for (i = 0; i < nitems(mem); i++) {
10538 		mem[i].limit = 0;
10539 		mem[i].idx = i;
10540 	}
10541 
10542 	mtx_lock(&sc->reg_lock);
10543 	if (hw_off_limits(sc)) {
10544 		rc = ENXIO;
10545 		goto done;
10546 	}
10547 
10548 	/* Find and sort the populated memory ranges */
10549 	i = 0;
10550 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
10551 	if (lo & F_EDRAM0_ENABLE) {
10552 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
10553 		if (chip_id(sc) >= CHELSIO_T7) {
10554 			avail[i].base = (uint64_t)G_T7_EDRAM0_BASE(hi) << 20;
10555 			avail[i].limit = avail[i].base +
10556 			    (G_T7_EDRAM0_SIZE(hi) << 20);
10557 		} else {
10558 			avail[i].base = (uint64_t)G_EDRAM0_BASE(hi) << 20;
10559 			avail[i].limit = avail[i].base +
10560 			    (G_EDRAM0_SIZE(hi) << 20);
10561 		}
10562 		avail[i].idx = 0;
10563 		i++;
10564 	}
10565 	if (lo & F_EDRAM1_ENABLE) {
10566 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
10567 		if (chip_id(sc) >= CHELSIO_T7) {
10568 			avail[i].base = (uint64_t)G_T7_EDRAM1_BASE(hi) << 20;
10569 			avail[i].limit = avail[i].base +
10570 			    (G_T7_EDRAM1_SIZE(hi) << 20);
10571 		} else {
10572 			avail[i].base = (uint64_t)G_EDRAM1_BASE(hi) << 20;
10573 			avail[i].limit = avail[i].base +
10574 			    (G_EDRAM1_SIZE(hi) << 20);
10575 		}
10576 		avail[i].idx = 1;
10577 		i++;
10578 	}
10579 	if (lo & F_EXT_MEM_ENABLE) {
10580 		switch (chip_id(sc)) {
10581 		case CHELSIO_T4:
10582 		case CHELSIO_T6:
10583 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
10584 			avail[i].base = (uint64_t)G_EXT_MEM_BASE(hi) << 20;
10585 			avail[i].limit = avail[i].base +
10586 			    (G_EXT_MEM_SIZE(hi) << 20);
10587 			avail[i].idx = 2;
10588 			break;
10589 		case CHELSIO_T5:
10590 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY0_BAR);
10591 			avail[i].base = (uint64_t)G_EXT_MEM0_BASE(hi) << 20;
10592 			avail[i].limit = avail[i].base +
10593 			    (G_EXT_MEM0_SIZE(hi) << 20);
10594 			avail[i].idx = 3;	/* Call it MC0 for T5 */
10595 			break;
10596 		default:
10597 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY0_BAR);
10598 			avail[i].base = (uint64_t)G_T7_EXT_MEM0_BASE(hi) << 20;
10599 			avail[i].limit = avail[i].base +
10600 			    (G_T7_EXT_MEM0_SIZE(hi) << 20);
10601 			avail[i].idx = 3;	/* Call it MC0 for T7+ */
10602 			break;
10603 		}
10604 		i++;
10605 	}
10606 	if (lo & F_EXT_MEM1_ENABLE && !(lo & F_MC_SPLIT)) {
10607 		/* Only T5 and T7+ have 2 MCs. */
10608 		MPASS(is_t5(sc) || chip_id(sc) >= CHELSIO_T7);
10609 
10610 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
10611 		if (chip_id(sc) >= CHELSIO_T7) {
10612 			avail[i].base = (uint64_t)G_T7_EXT_MEM1_BASE(hi) << 20;
10613 			avail[i].limit = avail[i].base +
10614 			    (G_T7_EXT_MEM1_SIZE(hi) << 20);
10615 		} else {
10616 			avail[i].base = (uint64_t)G_EXT_MEM1_BASE(hi) << 20;
10617 			avail[i].limit = avail[i].base +
10618 			    (G_EXT_MEM1_SIZE(hi) << 20);
10619 		}
10620 		avail[i].idx = 4;
10621 		i++;
10622 	}
10623 	if (lo & F_HMA_MUX) {
10624 		/* Only T6+ have HMA. */
10625 		MPASS(chip_id(sc) >= CHELSIO_T6);
10626 
10627 		if (chip_id(sc) >= CHELSIO_T7) {
10628 			hi = t4_read_reg(sc, A_MA_HOST_MEMORY_BAR);
10629 			avail[i].base = (uint64_t)G_HMATARGETBASE(hi) << 20;
10630 			avail[i].limit = avail[i].base +
10631 			    (G_T7_HMA_SIZE(hi) << 20);
10632 		} else {
10633 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
10634 			avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
10635 			avail[i].limit = avail[i].base +
10636 			    (G_EXT_MEM1_SIZE(hi) << 20);
10637 		}
10638 		avail[i].idx = 5;
10639 		i++;
10640 	}
10641 	MPASS(i <= nitems(avail));
10642 	if (!i)                                    /* no memory available */
10643 		goto done;
10644 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
10645 
10646 	md = &mem[0];
10647 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
10648 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
10649 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
10650 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
10651 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
10652 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
10653 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
10654 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
10655 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
10656 
10657 	/* the next few have explicit upper bounds */
10658 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
10659 	md->limit = md->base - 1 +
10660 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
10661 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
10662 	md++;
10663 
10664 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
10665 	md->limit = md->base - 1 +
10666 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
10667 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
10668 	md++;
10669 
10670 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10671 		if (chip_id(sc) <= CHELSIO_T5)
10672 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
10673 		else
10674 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
10675 		md->limit = 0;
10676 	} else {
10677 		md->base = 0;
10678 		md->idx = nitems(region);  /* hide it */
10679 	}
10680 	md++;
10681 
10682 #define ulp_region(reg) do {\
10683 		const u_int shift = chip_id(sc) >= CHELSIO_T7 ? 4 : 0; \
10684 		md->base = (uint64_t)t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT) << shift; \
10685 		md->limit = (uint64_t)t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT) << shift; \
10686 		md->limit += (1 << shift) - 1; \
10687 		md++; \
10688 	} while (0)
10689 
10690 #define	hide_ulp_region() do { \
10691 		md->base = 0; \
10692 		md->idx = nitems(region); \
10693 		md++; \
10694 	} while (0)
10695 
10696 	ulp_region(RX_ISCSI);
10697 	ulp_region(RX_TDDP);
10698 	ulp_region(TX_TPT);
10699 	ulp_region(RX_STAG);
10700 	ulp_region(RX_RQ);
10701 	if (chip_id(sc) < CHELSIO_T7)
10702 		ulp_region(RX_RQUDP);
10703 	else
10704 		hide_ulp_region();
10705 	ulp_region(RX_PBL);
10706 	ulp_region(TX_PBL);
10707 	if (chip_id(sc) >= CHELSIO_T6)
10708 		ulp_region(RX_TLS_KEY);
10709 	else
10710 		hide_ulp_region();
10711 	if (chip_id(sc) >= CHELSIO_T7) {
10712 		ulp_region(RX_RRQ);
10713 		ulp_region(RX_NVME_TCP_STAG);
10714 		ulp_region(RX_NVME_TCP_RQ);
10715 		ulp_region(RX_NVME_TCP_PBL);
10716 		ulp_region(TX_NVME_TCP_TPT);
10717 		ulp_region(TX_NVME_TCP_PBL);
10718 	} else {
10719 		hide_ulp_region();
10720 		hide_ulp_region();
10721 		hide_ulp_region();
10722 		hide_ulp_region();
10723 		hide_ulp_region();
10724 		hide_ulp_region();
10725 	}
10726 #undef ulp_region
10727 #undef hide_ulp_region
10728 
10729 	md->base = 0;
10730 	if (is_t4(sc))
10731 		md->idx = nitems(region);
10732 	else {
10733 		uint32_t size = 0;
10734 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
10735 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
10736 
10737 		if (is_t5(sc)) {
10738 			if (sge_ctrl & F_VFIFO_ENABLE)
10739 				size = fifo_size << 2;
10740 		} else
10741 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
10742 
10743 		if (size) {
10744 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
10745 			md->limit = md->base + size - 1;
10746 		} else
10747 			md->idx = nitems(region);
10748 	}
10749 	md++;
10750 
10751 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
10752 	md->limit = 0;
10753 	md++;
10754 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
10755 	md->limit = 0;
10756 	md++;
10757 
10758 	if (chip_id(sc) >= CHELSIO_T7) {
10759 		t4_tp_pio_read(sc, &lo, 1, A_TP_ROCE_RRQ_BASE, false);
10760 		md->base = lo;
10761 	} else {
10762 		md->base = 0;
10763 		md->idx = nitems(region);
10764 	}
10765 	md++;
10766 
10767 	md->base = sc->vres.ocq.start;
10768 	if (sc->vres.ocq.size)
10769 		md->limit = md->base + sc->vres.ocq.size - 1;
10770 	else
10771 		md->idx = nitems(region);  /* hide it */
10772 	md++;
10773 
10774 	/* add any address-space holes, there can be up to 3 */
10775 	for (n = 0; n < i - 1; n++)
10776 		if (avail[n].limit < avail[n + 1].base)
10777 			(md++)->base = avail[n].limit;
10778 	if (avail[n].limit)
10779 		(md++)->base = avail[n].limit;
10780 
10781 	n = md - mem;
10782 	MPASS(n <= nitems(mem));
10783 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
10784 
10785 	for (lo = 0; lo < i; lo++)
10786 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
10787 				avail[lo].limit - 1);
10788 
10789 	sbuf_printf(sb, "\n");
10790 	for (i = 0; i < n; i++) {
10791 		if (mem[i].idx >= nitems(region))
10792 			continue;                        /* skip holes */
10793 		if (!mem[i].limit)
10794 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
10795 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
10796 				mem[i].limit);
10797 	}
10798 
10799 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
10800 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
10801 	if (hi != lo  - 1) {
10802 		sbuf_printf(sb, "\n");
10803 		mem_region_show(sb, "uP RAM:", lo, hi);
10804 	}
10805 
10806 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
10807 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
10808 	if (hi != lo  - 1)
10809 		mem_region_show(sb, "uP Extmem2:", lo, hi);
10810 
10811 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
10812 	if (chip_id(sc) >= CHELSIO_T7)
10813 		nchan = 1 << G_T7_PMRXNUMCHN(lo);
10814 	else
10815 		nchan = lo & F_PMRXNUMCHN ? 2 : 1;
10816 	for (i = 0, free = 0; i < nchan; i++)
10817 		free += G_FREERXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_RX_CNT));
10818 	sbuf_printf(sb, "\n%u Rx pages (%u free) of size %uKiB for %u channels\n",
10819 		   G_PMRXMAXPAGE(lo), free,
10820 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10, nchan);
10821 
10822 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
10823 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
10824 	if (chip_id(sc) >= CHELSIO_T7)
10825 		nchan = 1 << G_T7_PMTXNUMCHN(lo);
10826 	else
10827 		nchan = 1 << G_PMTXNUMCHN(lo);
10828 	for (i = 0, free = 0; i < nchan; i++)
10829 		free += G_FREETXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_TX_CNT));
10830 	sbuf_printf(sb, "%u Tx pages (%u free) of size %u%ciB for %u channels\n",
10831 		   G_PMTXMAXPAGE(lo), free,
10832 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
10833 		   hi >= (1 << 20) ? 'M' : 'K', nchan);
10834 	sbuf_printf(sb, "%u p-structs (%u free)\n",
10835 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT),
10836 		   G_FREEPSTRUCTCOUNT(t4_read_reg(sc, A_TP_FLM_FREE_PS_CNT)));
10837 
10838 	for (i = 0; i < 4; i++) {
10839 		if (chip_id(sc) > CHELSIO_T5)
10840 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
10841 		else
10842 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
10843 		if (is_t5(sc)) {
10844 			used = G_T5_USED(lo);
10845 			alloc = G_T5_ALLOC(lo);
10846 		} else {
10847 			used = G_USED(lo);
10848 			alloc = G_ALLOC(lo);
10849 		}
10850 		/* For T6+ these are MAC buffer groups */
10851 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
10852 		    i, used, alloc);
10853 	}
10854 	for (i = 0; i < sc->chip_params->nchan; i++) {
10855 		if (chip_id(sc) > CHELSIO_T5)
10856 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
10857 		else
10858 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
10859 		if (is_t5(sc)) {
10860 			used = G_T5_USED(lo);
10861 			alloc = G_T5_ALLOC(lo);
10862 		} else {
10863 			used = G_USED(lo);
10864 			alloc = G_ALLOC(lo);
10865 		}
10866 		/* For T6+ these are MAC buffer groups */
10867 		sbuf_printf(sb,
10868 		    "\nLoopback %d using %u pages out of %u allocated",
10869 		    i, used, alloc);
10870 	}
10871 done:
10872 	mtx_unlock(&sc->reg_lock);
10873 	if (rc == 0)
10874 		rc = sbuf_finish(sb);
10875 	sbuf_delete(sb);
10876 	return (rc);
10877 }
10878 
10879 static inline void
10880 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
10881 {
10882 	*mask = x | y;
10883 	y = htobe64(y);
10884 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
10885 }
10886 
10887 static int
10888 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
10889 {
10890 	struct adapter *sc = arg1;
10891 	struct sbuf *sb;
10892 	int rc, i;
10893 
10894 	MPASS(chip_id(sc) <= CHELSIO_T5);
10895 
10896 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10897 	if (sb == NULL)
10898 		return (ENOMEM);
10899 
10900 	sbuf_printf(sb,
10901 	    "Idx  Ethernet address     Mask     Vld Ports PF"
10902 	    "  VF              Replication             P0 P1 P2 P3  ML");
10903 	rc = 0;
10904 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10905 		uint64_t tcamx, tcamy, mask;
10906 		uint32_t cls_lo, cls_hi;
10907 		uint8_t addr[ETHER_ADDR_LEN];
10908 
10909 		mtx_lock(&sc->reg_lock);
10910 		if (hw_off_limits(sc))
10911 			rc = ENXIO;
10912 		else {
10913 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
10914 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
10915 		}
10916 		mtx_unlock(&sc->reg_lock);
10917 		if (rc != 0)
10918 			break;
10919 		if (tcamx & tcamy)
10920 			continue;
10921 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10922 		mtx_lock(&sc->reg_lock);
10923 		if (hw_off_limits(sc))
10924 			rc = ENXIO;
10925 		else {
10926 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10927 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10928 		}
10929 		mtx_unlock(&sc->reg_lock);
10930 		if (rc != 0)
10931 			break;
10932 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
10933 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
10934 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
10935 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
10936 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
10937 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
10938 
10939 		if (cls_lo & F_REPLICATE) {
10940 			struct fw_ldst_cmd ldst_cmd;
10941 
10942 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10943 			ldst_cmd.op_to_addrspace =
10944 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10945 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10946 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10947 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10948 			ldst_cmd.u.mps.rplc.fid_idx =
10949 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10950 				V_FW_LDST_CMD_IDX(i));
10951 
10952 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10953 			    "t4mps");
10954 			if (rc)
10955 				break;
10956 			if (hw_off_limits(sc))
10957 				rc = ENXIO;
10958 			else
10959 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10960 				    sizeof(ldst_cmd), &ldst_cmd);
10961 			end_synchronized_op(sc, 0);
10962 			if (rc != 0)
10963 				break;
10964 			else {
10965 				sbuf_printf(sb, " %08x %08x %08x %08x",
10966 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10967 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10968 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10969 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10970 			}
10971 		} else
10972 			sbuf_printf(sb, "%36s", "");
10973 
10974 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
10975 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
10976 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
10977 	}
10978 
10979 	if (rc)
10980 		(void) sbuf_finish(sb);
10981 	else
10982 		rc = sbuf_finish(sb);
10983 	sbuf_delete(sb);
10984 
10985 	return (rc);
10986 }
10987 
10988 static int
10989 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
10990 {
10991 	struct adapter *sc = arg1;
10992 	struct sbuf *sb;
10993 	int rc, i;
10994 
10995 	MPASS(chip_id(sc) == CHELSIO_T6);
10996 
10997 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10998 	if (sb == NULL)
10999 		return (ENOMEM);
11000 
11001 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
11002 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
11003 	    "                           Replication"
11004 	    "                                    P0 P1 P2 P3  ML");
11005 
11006 	rc = 0;
11007 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
11008 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
11009 		uint16_t ivlan;
11010 		uint64_t tcamx, tcamy, val, mask;
11011 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
11012 		uint8_t addr[ETHER_ADDR_LEN];
11013 
11014 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
11015 		if (i < 256)
11016 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
11017 		else
11018 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
11019 		mtx_lock(&sc->reg_lock);
11020 		if (hw_off_limits(sc))
11021 			rc = ENXIO;
11022 		else {
11023 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
11024 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
11025 			tcamy = G_DMACH(val) << 32;
11026 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
11027 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
11028 		}
11029 		mtx_unlock(&sc->reg_lock);
11030 		if (rc != 0)
11031 			break;
11032 
11033 		lookup_type = G_DATALKPTYPE(data2);
11034 		port_num = G_DATAPORTNUM(data2);
11035 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11036 			/* Inner header VNI */
11037 			vniy = ((data2 & F_DATAVIDH2) << 23) |
11038 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
11039 			dip_hit = data2 & F_DATADIPHIT;
11040 			vlan_vld = 0;
11041 		} else {
11042 			vniy = 0;
11043 			dip_hit = 0;
11044 			vlan_vld = data2 & F_DATAVIDH2;
11045 			ivlan = G_VIDL(val);
11046 		}
11047 
11048 		ctl |= V_CTLXYBITSEL(1);
11049 		mtx_lock(&sc->reg_lock);
11050 		if (hw_off_limits(sc))
11051 			rc = ENXIO;
11052 		else {
11053 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
11054 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
11055 			tcamx = G_DMACH(val) << 32;
11056 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
11057 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
11058 		}
11059 		mtx_unlock(&sc->reg_lock);
11060 		if (rc != 0)
11061 			break;
11062 
11063 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11064 			/* Inner header VNI mask */
11065 			vnix = ((data2 & F_DATAVIDH2) << 23) |
11066 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
11067 		} else
11068 			vnix = 0;
11069 
11070 		if (tcamx & tcamy)
11071 			continue;
11072 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
11073 
11074 		mtx_lock(&sc->reg_lock);
11075 		if (hw_off_limits(sc))
11076 			rc = ENXIO;
11077 		else {
11078 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
11079 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
11080 		}
11081 		mtx_unlock(&sc->reg_lock);
11082 		if (rc != 0)
11083 			break;
11084 
11085 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11086 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11087 			    "%012jx %06x %06x    -    -   %3c"
11088 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
11089 			    addr[1], addr[2], addr[3], addr[4], addr[5],
11090 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
11091 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11092 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11093 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11094 		} else {
11095 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11096 			    "%012jx    -       -   ", i, addr[0], addr[1],
11097 			    addr[2], addr[3], addr[4], addr[5],
11098 			    (uintmax_t)mask);
11099 
11100 			if (vlan_vld)
11101 				sbuf_printf(sb, "%4u   Y     ", ivlan);
11102 			else
11103 				sbuf_printf(sb, "  -    N     ");
11104 
11105 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
11106 			    lookup_type ? 'I' : 'O', port_num,
11107 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11108 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11109 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11110 		}
11111 
11112 
11113 		if (cls_lo & F_T6_REPLICATE) {
11114 			struct fw_ldst_cmd ldst_cmd;
11115 
11116 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
11117 			ldst_cmd.op_to_addrspace =
11118 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
11119 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
11120 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
11121 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
11122 			ldst_cmd.u.mps.rplc.fid_idx =
11123 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
11124 				V_FW_LDST_CMD_IDX(i));
11125 
11126 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
11127 			    "t6mps");
11128 			if (rc)
11129 				break;
11130 			if (hw_off_limits(sc))
11131 				rc = ENXIO;
11132 			else
11133 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
11134 				    sizeof(ldst_cmd), &ldst_cmd);
11135 			end_synchronized_op(sc, 0);
11136 			if (rc != 0)
11137 				break;
11138 			else {
11139 				sbuf_printf(sb, " %08x %08x %08x %08x"
11140 				    " %08x %08x %08x %08x",
11141 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
11142 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
11143 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
11144 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
11145 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
11146 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
11147 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
11148 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
11149 			}
11150 		} else
11151 			sbuf_printf(sb, "%72s", "");
11152 
11153 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
11154 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
11155 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
11156 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
11157 	}
11158 
11159 	if (rc)
11160 		(void) sbuf_finish(sb);
11161 	else
11162 		rc = sbuf_finish(sb);
11163 	sbuf_delete(sb);
11164 
11165 	return (rc);
11166 }
11167 
11168 static int
11169 sysctl_mps_tcam_t7(SYSCTL_HANDLER_ARGS)
11170 {
11171 	struct adapter *sc = arg1;
11172 	struct sbuf *sb;
11173 	int rc, i;
11174 
11175 	MPASS(chip_id(sc) >= CHELSIO_T7);
11176 
11177 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11178 	if (sb == NULL)
11179 		return (ENOMEM);
11180 
11181 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
11182 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
11183 	    "                           Replication"
11184 	    "                                    P0 P1 P2 P3  ML");
11185 
11186 	rc = 0;
11187 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
11188 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
11189 		uint16_t ivlan;
11190 		uint64_t tcamx, tcamy, val, mask;
11191 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
11192 		uint8_t addr[ETHER_ADDR_LEN];
11193 
11194 		/* Read tcamy */
11195 		ctl = (V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0));
11196 		if (chip_rev(sc) == 0) {
11197 			if (i < 256)
11198 				ctl |= V_CTLTCAMINDEX(i) | V_T7_CTLTCAMSEL(0);
11199 			else
11200 				ctl |= V_CTLTCAMINDEX(i - 256) | V_T7_CTLTCAMSEL(1);
11201 		} else {
11202 #if 0
11203 			ctl = (V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0));
11204 #endif
11205 			if (i < 512)
11206 				ctl |= V_CTLTCAMINDEX(i) | V_T7_CTLTCAMSEL(0);
11207 			else if (i < 1024)
11208 				ctl |= V_CTLTCAMINDEX(i - 512) | V_T7_CTLTCAMSEL(1);
11209 			else
11210 				ctl |= V_CTLTCAMINDEX(i - 1024) | V_T7_CTLTCAMSEL(2);
11211 		}
11212 
11213 		mtx_lock(&sc->reg_lock);
11214 		if (hw_off_limits(sc))
11215 			rc = ENXIO;
11216 		else {
11217 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
11218 			val = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA1_REQ_ID1);
11219 			tcamy = G_DMACH(val) << 32;
11220 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA0_REQ_ID1);
11221 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA2_REQ_ID1);
11222 		}
11223 		mtx_unlock(&sc->reg_lock);
11224 		if (rc != 0)
11225 			break;
11226 
11227 		lookup_type = G_DATALKPTYPE(data2);
11228 		port_num = G_DATAPORTNUM(data2);
11229 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11230 			/* Inner header VNI */
11231 			vniy = (((data2 & F_DATAVIDH2) |
11232 			    G_DATAVIDH1(data2)) << 16) | G_VIDL(val);
11233 			dip_hit = data2 & F_DATADIPHIT;
11234 			vlan_vld = 0;
11235 		} else {
11236 			vniy = 0;
11237 			dip_hit = 0;
11238 			vlan_vld = data2 & F_DATAVIDH2;
11239 			ivlan = G_VIDL(val);
11240 		}
11241 
11242 		ctl |= V_CTLXYBITSEL(1);
11243 		mtx_lock(&sc->reg_lock);
11244 		if (hw_off_limits(sc))
11245 			rc = ENXIO;
11246 		else {
11247 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
11248 			val = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA1_REQ_ID1);
11249 			tcamx = G_DMACH(val) << 32;
11250 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA0_REQ_ID1);
11251 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA2_REQ_ID1);
11252 		}
11253 		mtx_unlock(&sc->reg_lock);
11254 		if (rc != 0)
11255 			break;
11256 
11257 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11258 			/* Inner header VNI mask */
11259 			vnix = (((data2 & F_DATAVIDH2) |
11260 			    G_DATAVIDH1(data2)) << 16) | G_VIDL(val);
11261 		} else
11262 			vnix = 0;
11263 
11264 		if (tcamx & tcamy)
11265 			continue;
11266 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
11267 
11268 		mtx_lock(&sc->reg_lock);
11269 		if (hw_off_limits(sc))
11270 			rc = ENXIO;
11271 		else {
11272 			if (chip_rev(sc) == 0) {
11273 				cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
11274 				cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
11275 			} else {
11276 				t4_write_reg(sc, A_MPS_CLS_SRAM_H,
11277 				    V_SRAMWRN(0) | V_SRAMINDEX(i));
11278 				cls_lo = t4_read_reg(sc, A_MPS_CLS_SRAM_L);
11279 				cls_hi = t4_read_reg(sc, A_MPS_CLS_SRAM_H);
11280 			}
11281 		}
11282 		mtx_unlock(&sc->reg_lock);
11283 		if (rc != 0)
11284 			break;
11285 
11286 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11287 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11288 			    "%012jx %06x %06x    -    -   %3c"
11289 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
11290 			    addr[1], addr[2], addr[3], addr[4], addr[5],
11291 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
11292 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11293 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11294 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11295 		} else {
11296 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11297 			    "%012jx    -       -   ", i, addr[0], addr[1],
11298 			    addr[2], addr[3], addr[4], addr[5],
11299 			    (uintmax_t)mask);
11300 
11301 			if (vlan_vld)
11302 				sbuf_printf(sb, "%4u   Y     ", ivlan);
11303 			else
11304 				sbuf_printf(sb, "  -    N     ");
11305 
11306 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
11307 			    lookup_type ? 'I' : 'O', port_num,
11308 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11309 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11310 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11311 		}
11312 
11313 		if (cls_lo & F_T6_REPLICATE) {
11314 			struct fw_ldst_cmd ldst_cmd;
11315 
11316 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
11317 			ldst_cmd.op_to_addrspace =
11318 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
11319 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
11320 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
11321 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
11322 			ldst_cmd.u.mps.rplc.fid_idx =
11323 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
11324 				V_FW_LDST_CMD_IDX(i));
11325 
11326 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
11327 			    "t6mps");
11328 			if (rc)
11329 				break;
11330 			if (hw_off_limits(sc))
11331 				rc = ENXIO;
11332 			else
11333 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
11334 				    sizeof(ldst_cmd), &ldst_cmd);
11335 			end_synchronized_op(sc, 0);
11336 			if (rc != 0)
11337 				break;
11338 			else {
11339 				sbuf_printf(sb, " %08x %08x %08x %08x"
11340 				    " %08x %08x %08x %08x",
11341 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
11342 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
11343 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
11344 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
11345 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
11346 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
11347 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
11348 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
11349 			}
11350 		} else
11351 			sbuf_printf(sb, "%72s", "");
11352 
11353 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
11354 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
11355 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
11356 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
11357 	}
11358 
11359 	if (rc)
11360 		(void) sbuf_finish(sb);
11361 	else
11362 		rc = sbuf_finish(sb);
11363 	sbuf_delete(sb);
11364 
11365 	return (rc);
11366 }
11367 
11368 static int
11369 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
11370 {
11371 	struct adapter *sc = arg1;
11372 	struct sbuf *sb;
11373 	int rc;
11374 	uint16_t mtus[NMTUS];
11375 
11376 	rc = 0;
11377 	mtx_lock(&sc->reg_lock);
11378 	if (hw_off_limits(sc))
11379 		rc = ENXIO;
11380 	else
11381 		t4_read_mtu_tbl(sc, mtus, NULL);
11382 	mtx_unlock(&sc->reg_lock);
11383 	if (rc != 0)
11384 		return (rc);
11385 
11386 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11387 	if (sb == NULL)
11388 		return (ENOMEM);
11389 
11390 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
11391 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
11392 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
11393 	    mtus[14], mtus[15]);
11394 
11395 	rc = sbuf_finish(sb);
11396 	sbuf_delete(sb);
11397 
11398 	return (rc);
11399 }
11400 
11401 static int
11402 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
11403 {
11404 	struct adapter *sc = arg1;
11405 	struct sbuf *sb;
11406 	int rc, i;
11407 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
11408 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
11409 	uint32_t stats[T7_PM_RX_CACHE_NSTATS];
11410 	static const char *tx_stats[MAX_PM_NSTATS] = {
11411 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
11412 		"Tx FIFO wait", NULL, "Tx latency"
11413 	};
11414 	static const char *rx_stats[MAX_PM_NSTATS] = {
11415 		"Read:", "Write bypass:", "Write mem:", "Flush:",
11416 		"Rx FIFO wait", NULL, "Rx latency"
11417 	};
11418 
11419 	rc = 0;
11420 	mtx_lock(&sc->reg_lock);
11421 	if (hw_off_limits(sc))
11422 		rc = ENXIO;
11423 	else {
11424 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
11425 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
11426 		if (chip_id(sc) >= CHELSIO_T7)
11427 			t4_pmrx_cache_get_stats(sc, stats);
11428 	}
11429 	mtx_unlock(&sc->reg_lock);
11430 	if (rc != 0)
11431 		return (rc);
11432 
11433 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11434 	if (sb == NULL)
11435 		return (ENOMEM);
11436 
11437 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
11438 	for (i = 0; i < 4; i++) {
11439 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
11440 		    tx_cyc[i]);
11441 	}
11442 
11443 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
11444 	for (i = 0; i < 4; i++) {
11445 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
11446 		    rx_cyc[i]);
11447 	}
11448 
11449 	if (chip_id(sc) > CHELSIO_T5) {
11450 		sbuf_printf(sb,
11451 		    "\n              Total wait      Total occupancy");
11452 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
11453 		    tx_cyc[i]);
11454 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
11455 		    rx_cyc[i]);
11456 
11457 		i += 2;
11458 		MPASS(i < nitems(tx_stats));
11459 
11460 		sbuf_printf(sb,
11461 		    "\n                   Reads           Total wait");
11462 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
11463 		    tx_cyc[i]);
11464 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
11465 		    rx_cyc[i]);
11466 	}
11467 
11468 	if (chip_id(sc) >= CHELSIO_T7) {
11469 		i = 0;
11470 		sbuf_printf(sb, "\n\nPM RX Cache Stats\n");
11471 		sbuf_printf(sb, "%-40s    %u\n", "ReqWrite", stats[i++]);
11472 		sbuf_printf(sb, "%-40s    %u\n", "ReqReadInv", stats[i++]);
11473 		sbuf_printf(sb, "%-40s    %u\n", "ReqReadNoInv", stats[i++]);
11474 		sbuf_printf(sb, "%-40s    %u\n", "Write Split Request",
11475 			   stats[i++]);
11476 		sbuf_printf(sb, "%-40s    %u\n",
11477 			   "Normal Read Split (Read Invalidate)", stats[i++]);
11478 		sbuf_printf(sb, "%-40s    %u\n",
11479 			   "Feedback Read Split (Read NoInvalidate)",
11480 			   stats[i++]);
11481 		sbuf_printf(sb, "%-40s    %u\n", "Write Hit", stats[i++]);
11482 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Hit",
11483 			   stats[i++]);
11484 		sbuf_printf(sb, "%-40s    %u\n", "Feedback Read Hit",
11485 			   stats[i++]);
11486 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Hit Full Avail",
11487 			   stats[i++]);
11488 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Hit Full UnAvail",
11489 			   stats[i++]);
11490 		sbuf_printf(sb, "%-40s    %u\n",
11491 			   "Normal Read Hit Partial Avail",
11492 			   stats[i++]);
11493 		sbuf_printf(sb, "%-40s    %u\n", "FB Read Hit Full Avail",
11494 			   stats[i++]);
11495 		sbuf_printf(sb, "%-40s    %u\n", "FB Read Hit Full UnAvail",
11496 			   stats[i++]);
11497 		sbuf_printf(sb, "%-40s    %u\n", "FB Read Hit Partial Avail",
11498 			   stats[i++]);
11499 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Full Free",
11500 			   stats[i++]);
11501 		sbuf_printf(sb, "%-40s    %u\n",
11502 			   "Normal Read Part-avail Mul-Regions",
11503 			   stats[i++]);
11504 		sbuf_printf(sb, "%-40s    %u\n",
11505 			   "FB Read Part-avail Mul-Regions",
11506 			   stats[i++]);
11507 		sbuf_printf(sb, "%-40s    %u\n", "Write Miss FL Used",
11508 			   stats[i++]);
11509 		sbuf_printf(sb, "%-40s    %u\n", "Write Miss LRU Used",
11510 			   stats[i++]);
11511 		sbuf_printf(sb, "%-40s    %u\n",
11512 			   "Write Miss LRU-Multiple Evict", stats[i++]);
11513 		sbuf_printf(sb, "%-40s    %u\n",
11514 			   "Write Hit Increasing Islands", stats[i++]);
11515 		sbuf_printf(sb, "%-40s    %u\n",
11516 			   "Normal Read Island Read split", stats[i++]);
11517 		sbuf_printf(sb, "%-40s    %u\n", "Write Overflow Eviction",
11518 			   stats[i++]);
11519 		sbuf_printf(sb, "%-40s    %u", "Read Overflow Eviction",
11520 			   stats[i++]);
11521 	}
11522 
11523 	rc = sbuf_finish(sb);
11524 	sbuf_delete(sb);
11525 
11526 	return (rc);
11527 }
11528 
11529 static int
11530 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
11531 {
11532 	struct adapter *sc = arg1;
11533 	struct sbuf *sb;
11534 	int rc;
11535 	struct tp_rdma_stats stats;
11536 
11537 	rc = 0;
11538 	mtx_lock(&sc->reg_lock);
11539 	if (hw_off_limits(sc))
11540 		rc = ENXIO;
11541 	else
11542 		t4_tp_get_rdma_stats(sc, &stats, 0);
11543 	mtx_unlock(&sc->reg_lock);
11544 	if (rc != 0)
11545 		return (rc);
11546 
11547 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11548 	if (sb == NULL)
11549 		return (ENOMEM);
11550 
11551 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
11552 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
11553 
11554 	rc = sbuf_finish(sb);
11555 	sbuf_delete(sb);
11556 
11557 	return (rc);
11558 }
11559 
11560 static int
11561 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
11562 {
11563 	struct adapter *sc = arg1;
11564 	struct sbuf *sb;
11565 	int rc;
11566 	struct tp_tcp_stats v4, v6;
11567 
11568 	rc = 0;
11569 	mtx_lock(&sc->reg_lock);
11570 	if (hw_off_limits(sc))
11571 		rc = ENXIO;
11572 	else
11573 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
11574 	mtx_unlock(&sc->reg_lock);
11575 	if (rc != 0)
11576 		return (rc);
11577 
11578 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11579 	if (sb == NULL)
11580 		return (ENOMEM);
11581 
11582 	sbuf_printf(sb,
11583 	    "                                IP                 IPv6\n");
11584 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
11585 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
11586 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
11587 	    v4.tcp_in_segs, v6.tcp_in_segs);
11588 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
11589 	    v4.tcp_out_segs, v6.tcp_out_segs);
11590 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
11591 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
11592 
11593 	rc = sbuf_finish(sb);
11594 	sbuf_delete(sb);
11595 
11596 	return (rc);
11597 }
11598 
11599 static int
11600 sysctl_tids(SYSCTL_HANDLER_ARGS)
11601 {
11602 	struct adapter *sc = arg1;
11603 	struct sbuf *sb;
11604 	int rc;
11605 	uint32_t x, y;
11606 	struct tid_info *t = &sc->tids;
11607 
11608 	rc = 0;
11609 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11610 	if (sb == NULL)
11611 		return (ENOMEM);
11612 
11613 	if (t->natids) {
11614 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
11615 		    t->atids_in_use);
11616 	}
11617 
11618 	if (t->nhpftids) {
11619 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
11620 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
11621 	}
11622 
11623 	if (t->ntids) {
11624 		bool hashen = false;
11625 
11626 		mtx_lock(&sc->reg_lock);
11627 		if (hw_off_limits(sc))
11628 			rc = ENXIO;
11629 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
11630 			hashen = true;
11631 			if (chip_id(sc) <= CHELSIO_T5) {
11632 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
11633 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
11634 			} else {
11635 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
11636 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
11637 			}
11638 		}
11639 		mtx_unlock(&sc->reg_lock);
11640 		if (rc != 0)
11641 			goto done;
11642 
11643 		sbuf_printf(sb, "TID range: ");
11644 		if (hashen) {
11645 			if (x)
11646 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
11647 			sbuf_printf(sb, "%u-%u", y, t->tid_base + t->ntids - 1);
11648 		} else {
11649 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
11650 			    t->ntids - 1);
11651 		}
11652 		sbuf_printf(sb, ", in use: %u\n",
11653 		    atomic_load_acq_int(&t->tids_in_use));
11654 	}
11655 
11656 	if (t->nstids) {
11657 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
11658 		    t->stid_base + t->nstids - 1, t->stids_in_use);
11659 	}
11660 
11661 	if (t->nftids) {
11662 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
11663 		    t->ftid_end, t->ftids_in_use);
11664 	}
11665 
11666 	if (t->netids) {
11667 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
11668 		    t->etid_base + t->netids - 1, t->etids_in_use);
11669 	}
11670 
11671 	mtx_lock(&sc->reg_lock);
11672 	if (hw_off_limits(sc))
11673 		rc = ENXIO;
11674 	else {
11675 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
11676 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
11677 	}
11678 	mtx_unlock(&sc->reg_lock);
11679 	if (rc != 0)
11680 		goto done;
11681 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
11682 done:
11683 	if (rc == 0)
11684 		rc = sbuf_finish(sb);
11685 	else
11686 		(void)sbuf_finish(sb);
11687 	sbuf_delete(sb);
11688 
11689 	return (rc);
11690 }
11691 
11692 static int
11693 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
11694 {
11695 	struct adapter *sc = arg1;
11696 	struct sbuf *sb;
11697 	int rc;
11698 	struct tp_err_stats stats;
11699 
11700 	rc = 0;
11701 	mtx_lock(&sc->reg_lock);
11702 	if (hw_off_limits(sc))
11703 		rc = ENXIO;
11704 	else
11705 		t4_tp_get_err_stats(sc, &stats, 0);
11706 	mtx_unlock(&sc->reg_lock);
11707 	if (rc != 0)
11708 		return (rc);
11709 
11710 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11711 	if (sb == NULL)
11712 		return (ENOMEM);
11713 
11714 	if (sc->chip_params->nchan > 2) {
11715 		sbuf_printf(sb, "                 channel 0  channel 1"
11716 		    "  channel 2  channel 3\n");
11717 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
11718 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
11719 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
11720 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
11721 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
11722 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
11723 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
11724 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
11725 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
11726 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
11727 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
11728 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
11729 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
11730 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
11731 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
11732 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
11733 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
11734 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
11735 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
11736 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
11737 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
11738 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
11739 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
11740 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
11741 	} else {
11742 		sbuf_printf(sb, "                 channel 0  channel 1\n");
11743 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
11744 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
11745 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
11746 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
11747 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
11748 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
11749 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
11750 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
11751 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
11752 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
11753 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
11754 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
11755 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
11756 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
11757 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
11758 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
11759 	}
11760 
11761 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
11762 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
11763 
11764 	rc = sbuf_finish(sb);
11765 	sbuf_delete(sb);
11766 
11767 	return (rc);
11768 }
11769 
11770 static int
11771 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
11772 {
11773 	struct adapter *sc = arg1;
11774 	struct sbuf *sb;
11775 	int rc;
11776 	struct tp_tnl_stats stats;
11777 
11778 	rc = 0;
11779 	mtx_lock(&sc->reg_lock);
11780 	if (hw_off_limits(sc))
11781 		rc = ENXIO;
11782 	else
11783 		t4_tp_get_tnl_stats(sc, &stats, 1);
11784 	mtx_unlock(&sc->reg_lock);
11785 	if (rc != 0)
11786 		return (rc);
11787 
11788 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11789 	if (sb == NULL)
11790 		return (ENOMEM);
11791 
11792 	if (sc->chip_params->nchan > 2) {
11793 		sbuf_printf(sb, "           channel 0  channel 1"
11794 		    "  channel 2  channel 3\n");
11795 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
11796 		    stats.out_pkt[0], stats.out_pkt[1],
11797 		    stats.out_pkt[2], stats.out_pkt[3]);
11798 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
11799 		    stats.in_pkt[0], stats.in_pkt[1],
11800 		    stats.in_pkt[2], stats.in_pkt[3]);
11801 	} else {
11802 		sbuf_printf(sb, "           channel 0  channel 1\n");
11803 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
11804 		    stats.out_pkt[0], stats.out_pkt[1]);
11805 		sbuf_printf(sb, "InPkts:   %10u %10u",
11806 		    stats.in_pkt[0], stats.in_pkt[1]);
11807 	}
11808 
11809 	rc = sbuf_finish(sb);
11810 	sbuf_delete(sb);
11811 
11812 	return (rc);
11813 }
11814 
11815 static int
11816 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
11817 {
11818 	struct adapter *sc = arg1;
11819 	struct tp_params *tpp = &sc->params.tp;
11820 	u_int mask;
11821 	int rc;
11822 
11823 	mask = tpp->la_mask >> 16;
11824 	rc = sysctl_handle_int(oidp, &mask, 0, req);
11825 	if (rc != 0 || req->newptr == NULL)
11826 		return (rc);
11827 	if (mask > 0xffff)
11828 		return (EINVAL);
11829 	mtx_lock(&sc->reg_lock);
11830 	if (hw_off_limits(sc))
11831 		rc = ENXIO;
11832 	else {
11833 		tpp->la_mask = mask << 16;
11834 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
11835 		    tpp->la_mask);
11836 	}
11837 	mtx_unlock(&sc->reg_lock);
11838 
11839 	return (rc);
11840 }
11841 
11842 struct field_desc {
11843 	const char *name;
11844 	u_int start;
11845 	u_int width;
11846 };
11847 
11848 static void
11849 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
11850 {
11851 	char buf[32];
11852 	int line_size = 0;
11853 
11854 	while (f->name) {
11855 		uint64_t mask = (1ULL << f->width) - 1;
11856 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
11857 		    ((uintmax_t)v >> f->start) & mask);
11858 
11859 		if (line_size + len >= 79) {
11860 			line_size = 8;
11861 			sbuf_printf(sb, "\n        ");
11862 		}
11863 		sbuf_printf(sb, "%s ", buf);
11864 		line_size += len + 1;
11865 		f++;
11866 	}
11867 	sbuf_printf(sb, "\n");
11868 }
11869 
11870 static const struct field_desc tp_la0[] = {
11871 	{ "RcfOpCodeOut", 60, 4 },
11872 	{ "State", 56, 4 },
11873 	{ "WcfState", 52, 4 },
11874 	{ "RcfOpcSrcOut", 50, 2 },
11875 	{ "CRxError", 49, 1 },
11876 	{ "ERxError", 48, 1 },
11877 	{ "SanityFailed", 47, 1 },
11878 	{ "SpuriousMsg", 46, 1 },
11879 	{ "FlushInputMsg", 45, 1 },
11880 	{ "FlushInputCpl", 44, 1 },
11881 	{ "RssUpBit", 43, 1 },
11882 	{ "RssFilterHit", 42, 1 },
11883 	{ "Tid", 32, 10 },
11884 	{ "InitTcb", 31, 1 },
11885 	{ "LineNumber", 24, 7 },
11886 	{ "Emsg", 23, 1 },
11887 	{ "EdataOut", 22, 1 },
11888 	{ "Cmsg", 21, 1 },
11889 	{ "CdataOut", 20, 1 },
11890 	{ "EreadPdu", 19, 1 },
11891 	{ "CreadPdu", 18, 1 },
11892 	{ "TunnelPkt", 17, 1 },
11893 	{ "RcfPeerFin", 16, 1 },
11894 	{ "RcfReasonOut", 12, 4 },
11895 	{ "TxCchannel", 10, 2 },
11896 	{ "RcfTxChannel", 8, 2 },
11897 	{ "RxEchannel", 6, 2 },
11898 	{ "RcfRxChannel", 5, 1 },
11899 	{ "RcfDataOutSrdy", 4, 1 },
11900 	{ "RxDvld", 3, 1 },
11901 	{ "RxOoDvld", 2, 1 },
11902 	{ "RxCongestion", 1, 1 },
11903 	{ "TxCongestion", 0, 1 },
11904 	{ NULL }
11905 };
11906 
11907 static const struct field_desc tp_la1[] = {
11908 	{ "CplCmdIn", 56, 8 },
11909 	{ "CplCmdOut", 48, 8 },
11910 	{ "ESynOut", 47, 1 },
11911 	{ "EAckOut", 46, 1 },
11912 	{ "EFinOut", 45, 1 },
11913 	{ "ERstOut", 44, 1 },
11914 	{ "SynIn", 43, 1 },
11915 	{ "AckIn", 42, 1 },
11916 	{ "FinIn", 41, 1 },
11917 	{ "RstIn", 40, 1 },
11918 	{ "DataIn", 39, 1 },
11919 	{ "DataInVld", 38, 1 },
11920 	{ "PadIn", 37, 1 },
11921 	{ "RxBufEmpty", 36, 1 },
11922 	{ "RxDdp", 35, 1 },
11923 	{ "RxFbCongestion", 34, 1 },
11924 	{ "TxFbCongestion", 33, 1 },
11925 	{ "TxPktSumSrdy", 32, 1 },
11926 	{ "RcfUlpType", 28, 4 },
11927 	{ "Eread", 27, 1 },
11928 	{ "Ebypass", 26, 1 },
11929 	{ "Esave", 25, 1 },
11930 	{ "Static0", 24, 1 },
11931 	{ "Cread", 23, 1 },
11932 	{ "Cbypass", 22, 1 },
11933 	{ "Csave", 21, 1 },
11934 	{ "CPktOut", 20, 1 },
11935 	{ "RxPagePoolFull", 18, 2 },
11936 	{ "RxLpbkPkt", 17, 1 },
11937 	{ "TxLpbkPkt", 16, 1 },
11938 	{ "RxVfValid", 15, 1 },
11939 	{ "SynLearned", 14, 1 },
11940 	{ "SetDelEntry", 13, 1 },
11941 	{ "SetInvEntry", 12, 1 },
11942 	{ "CpcmdDvld", 11, 1 },
11943 	{ "CpcmdSave", 10, 1 },
11944 	{ "RxPstructsFull", 8, 2 },
11945 	{ "EpcmdDvld", 7, 1 },
11946 	{ "EpcmdFlush", 6, 1 },
11947 	{ "EpcmdTrimPrefix", 5, 1 },
11948 	{ "EpcmdTrimPostfix", 4, 1 },
11949 	{ "ERssIp4Pkt", 3, 1 },
11950 	{ "ERssIp6Pkt", 2, 1 },
11951 	{ "ERssTcpUdpPkt", 1, 1 },
11952 	{ "ERssFceFipPkt", 0, 1 },
11953 	{ NULL }
11954 };
11955 
11956 static const struct field_desc tp_la2[] = {
11957 	{ "CplCmdIn", 56, 8 },
11958 	{ "MpsVfVld", 55, 1 },
11959 	{ "MpsPf", 52, 3 },
11960 	{ "MpsVf", 44, 8 },
11961 	{ "SynIn", 43, 1 },
11962 	{ "AckIn", 42, 1 },
11963 	{ "FinIn", 41, 1 },
11964 	{ "RstIn", 40, 1 },
11965 	{ "DataIn", 39, 1 },
11966 	{ "DataInVld", 38, 1 },
11967 	{ "PadIn", 37, 1 },
11968 	{ "RxBufEmpty", 36, 1 },
11969 	{ "RxDdp", 35, 1 },
11970 	{ "RxFbCongestion", 34, 1 },
11971 	{ "TxFbCongestion", 33, 1 },
11972 	{ "TxPktSumSrdy", 32, 1 },
11973 	{ "RcfUlpType", 28, 4 },
11974 	{ "Eread", 27, 1 },
11975 	{ "Ebypass", 26, 1 },
11976 	{ "Esave", 25, 1 },
11977 	{ "Static0", 24, 1 },
11978 	{ "Cread", 23, 1 },
11979 	{ "Cbypass", 22, 1 },
11980 	{ "Csave", 21, 1 },
11981 	{ "CPktOut", 20, 1 },
11982 	{ "RxPagePoolFull", 18, 2 },
11983 	{ "RxLpbkPkt", 17, 1 },
11984 	{ "TxLpbkPkt", 16, 1 },
11985 	{ "RxVfValid", 15, 1 },
11986 	{ "SynLearned", 14, 1 },
11987 	{ "SetDelEntry", 13, 1 },
11988 	{ "SetInvEntry", 12, 1 },
11989 	{ "CpcmdDvld", 11, 1 },
11990 	{ "CpcmdSave", 10, 1 },
11991 	{ "RxPstructsFull", 8, 2 },
11992 	{ "EpcmdDvld", 7, 1 },
11993 	{ "EpcmdFlush", 6, 1 },
11994 	{ "EpcmdTrimPrefix", 5, 1 },
11995 	{ "EpcmdTrimPostfix", 4, 1 },
11996 	{ "ERssIp4Pkt", 3, 1 },
11997 	{ "ERssIp6Pkt", 2, 1 },
11998 	{ "ERssTcpUdpPkt", 1, 1 },
11999 	{ "ERssFceFipPkt", 0, 1 },
12000 	{ NULL }
12001 };
12002 
12003 static void
12004 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
12005 {
12006 
12007 	field_desc_show(sb, *p, tp_la0);
12008 }
12009 
12010 static void
12011 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
12012 {
12013 
12014 	if (idx)
12015 		sbuf_printf(sb, "\n");
12016 	field_desc_show(sb, p[0], tp_la0);
12017 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
12018 		field_desc_show(sb, p[1], tp_la0);
12019 }
12020 
12021 static void
12022 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
12023 {
12024 
12025 	if (idx)
12026 		sbuf_printf(sb, "\n");
12027 	field_desc_show(sb, p[0], tp_la0);
12028 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
12029 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
12030 }
12031 
12032 static int
12033 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
12034 {
12035 	struct adapter *sc = arg1;
12036 	struct sbuf *sb;
12037 	uint64_t *buf, *p;
12038 	int rc;
12039 	u_int i, inc;
12040 	void (*show_func)(struct sbuf *, uint64_t *, int);
12041 
12042 	rc = 0;
12043 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
12044 	if (sb == NULL)
12045 		return (ENOMEM);
12046 
12047 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
12048 
12049 	mtx_lock(&sc->reg_lock);
12050 	if (hw_off_limits(sc))
12051 		rc = ENXIO;
12052 	else {
12053 		t4_tp_read_la(sc, buf, NULL);
12054 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
12055 		case 2:
12056 			inc = 2;
12057 			show_func = tp_la_show2;
12058 			break;
12059 		case 3:
12060 			inc = 2;
12061 			show_func = tp_la_show3;
12062 			break;
12063 		default:
12064 			inc = 1;
12065 			show_func = tp_la_show;
12066 		}
12067 	}
12068 	mtx_unlock(&sc->reg_lock);
12069 	if (rc != 0)
12070 		goto done;
12071 
12072 	p = buf;
12073 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
12074 		(*show_func)(sb, p, i);
12075 	rc = sbuf_finish(sb);
12076 done:
12077 	sbuf_delete(sb);
12078 	free(buf, M_CXGBE);
12079 	return (rc);
12080 }
12081 
12082 static int
12083 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
12084 {
12085 	struct adapter *sc = arg1;
12086 	struct sbuf *sb;
12087 	int rc;
12088 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
12089 
12090 	rc = 0;
12091 	mtx_lock(&sc->reg_lock);
12092 	if (hw_off_limits(sc))
12093 		rc = ENXIO;
12094 	else
12095 		t4_get_chan_txrate(sc, nrate, orate);
12096 	mtx_unlock(&sc->reg_lock);
12097 	if (rc != 0)
12098 		return (rc);
12099 
12100 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
12101 	if (sb == NULL)
12102 		return (ENOMEM);
12103 
12104 	if (sc->chip_params->nchan > 2) {
12105 		sbuf_printf(sb, "              channel 0   channel 1"
12106 		    "   channel 2   channel 3\n");
12107 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
12108 		    nrate[0], nrate[1], nrate[2], nrate[3]);
12109 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
12110 		    orate[0], orate[1], orate[2], orate[3]);
12111 	} else {
12112 		sbuf_printf(sb, "              channel 0   channel 1\n");
12113 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
12114 		    nrate[0], nrate[1]);
12115 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
12116 		    orate[0], orate[1]);
12117 	}
12118 
12119 	rc = sbuf_finish(sb);
12120 	sbuf_delete(sb);
12121 
12122 	return (rc);
12123 }
12124 
12125 static int
12126 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
12127 {
12128 	struct adapter *sc = arg1;
12129 	struct sbuf *sb;
12130 	uint32_t *buf, *p;
12131 	int rc, i;
12132 
12133 	rc = 0;
12134 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
12135 	if (sb == NULL)
12136 		return (ENOMEM);
12137 
12138 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
12139 	    M_ZERO | M_WAITOK);
12140 
12141 	mtx_lock(&sc->reg_lock);
12142 	if (hw_off_limits(sc))
12143 		rc = ENXIO;
12144 	else
12145 		t4_ulprx_read_la(sc, buf);
12146 	mtx_unlock(&sc->reg_lock);
12147 	if (rc != 0)
12148 		goto done;
12149 
12150 	p = buf;
12151 	sbuf_printf(sb, "      Pcmd        Type   Message"
12152 	    "                Data");
12153 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
12154 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
12155 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
12156 	}
12157 	rc = sbuf_finish(sb);
12158 done:
12159 	sbuf_delete(sb);
12160 	free(buf, M_CXGBE);
12161 	return (rc);
12162 }
12163 
12164 static int
12165 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
12166 {
12167 	struct adapter *sc = arg1;
12168 	struct sbuf *sb;
12169 	int rc;
12170 	uint32_t cfg, s1, s2;
12171 
12172 	MPASS(chip_id(sc) >= CHELSIO_T5);
12173 
12174 	rc = 0;
12175 	mtx_lock(&sc->reg_lock);
12176 	if (hw_off_limits(sc))
12177 		rc = ENXIO;
12178 	else {
12179 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
12180 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
12181 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
12182 	}
12183 	mtx_unlock(&sc->reg_lock);
12184 	if (rc != 0)
12185 		return (rc);
12186 
12187 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
12188 	if (sb == NULL)
12189 		return (ENOMEM);
12190 
12191 	if (G_STATSOURCE_T5(cfg) == 7) {
12192 		int mode;
12193 
12194 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
12195 		if (mode == 0)
12196 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
12197 		else if (mode == 1)
12198 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
12199 		else
12200 			sbuf_printf(sb, "unknown mode %d", mode);
12201 	}
12202 	rc = sbuf_finish(sb);
12203 	sbuf_delete(sb);
12204 
12205 	return (rc);
12206 }
12207 
12208 static int
12209 sysctl_cpus(SYSCTL_HANDLER_ARGS)
12210 {
12211 	struct adapter *sc = arg1;
12212 	enum cpu_sets op = arg2;
12213 	cpuset_t cpuset;
12214 	struct sbuf *sb;
12215 	int i, rc;
12216 
12217 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
12218 
12219 	CPU_ZERO(&cpuset);
12220 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
12221 	if (rc != 0)
12222 		return (rc);
12223 
12224 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
12225 	if (sb == NULL)
12226 		return (ENOMEM);
12227 
12228 	CPU_FOREACH(i)
12229 		sbuf_printf(sb, "%d ", i);
12230 	rc = sbuf_finish(sb);
12231 	sbuf_delete(sb);
12232 
12233 	return (rc);
12234 }
12235 
12236 static int
12237 sysctl_reset(SYSCTL_HANDLER_ARGS)
12238 {
12239 	struct adapter *sc = arg1;
12240 	u_int val;
12241 	int rc;
12242 
12243 	val = atomic_load_int(&sc->num_resets);
12244 	rc = sysctl_handle_int(oidp, &val, 0, req);
12245 	if (rc != 0 || req->newptr == NULL)
12246 		return (rc);
12247 
12248 	if (val == 0) {
12249 		/* Zero out the counter that tracks reset. */
12250 		atomic_store_int(&sc->num_resets, 0);
12251 		return (0);
12252 	}
12253 
12254 	if (val != 1)
12255 		return (EINVAL);	/* 0 or 1 are the only legal values */
12256 
12257 	if (hw_off_limits(sc))		/* harmless race */
12258 		return (EALREADY);
12259 
12260 	taskqueue_enqueue(reset_tq, &sc->reset_task);
12261 	return (0);
12262 }
12263 
12264 static int
12265 sysctl_tcb_cache(SYSCTL_HANDLER_ARGS)
12266 {
12267 	struct adapter *sc = arg1;
12268 	u_int val, v;
12269 	int rc;
12270 
12271 	mtx_lock(&sc->reg_lock);
12272 	if (hw_off_limits(sc)) {
12273 		rc = ENXIO;
12274 		goto done;
12275 	}
12276 	t4_tp_pio_read(sc, &v, 1, A_TP_CMM_CONFIG, 1);
12277 	mtx_unlock(&sc->reg_lock);
12278 
12279 	val = v & F_GLFL ? 0 : 1;
12280 	rc = sysctl_handle_int(oidp, &val, 0, req);
12281 	if (rc != 0 || req->newptr == NULL)
12282 		return (rc);
12283 	if (val == 0)
12284 		v |= F_GLFL;
12285 	else
12286 		v &= ~F_GLFL;
12287 
12288 	mtx_lock(&sc->reg_lock);
12289 	if (hw_off_limits(sc))
12290 		rc = ENXIO;
12291 	else
12292 		t4_tp_pio_write(sc, &v, 1, A_TP_CMM_CONFIG, 1);
12293 done:
12294 	mtx_unlock(&sc->reg_lock);
12295 	return (rc);
12296 }
12297 
12298 #ifdef TCP_OFFLOAD
12299 static int
12300 sysctl_tls(SYSCTL_HANDLER_ARGS)
12301 {
12302 	struct adapter *sc = arg1;
12303 	int i, j, v, rc;
12304 	struct vi_info *vi;
12305 
12306 	v = sc->tt.tls;
12307 	rc = sysctl_handle_int(oidp, &v, 0, req);
12308 	if (rc != 0 || req->newptr == NULL)
12309 		return (rc);
12310 
12311 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
12312 		return (ENOTSUP);
12313 
12314 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
12315 	if (rc)
12316 		return (rc);
12317 	if (hw_off_limits(sc))
12318 		rc = ENXIO;
12319 	else {
12320 		sc->tt.tls = !!v;
12321 		for_each_port(sc, i) {
12322 			for_each_vi(sc->port[i], j, vi) {
12323 				if (vi->flags & VI_INIT_DONE)
12324 					t4_update_fl_bufsize(vi->ifp);
12325 			}
12326 		}
12327 	}
12328 	end_synchronized_op(sc, 0);
12329 
12330 	return (rc);
12331 
12332 }
12333 
12334 static void
12335 unit_conv(char *buf, size_t len, u_int val, u_int factor)
12336 {
12337 	u_int rem = val % factor;
12338 
12339 	if (rem == 0)
12340 		snprintf(buf, len, "%u", val / factor);
12341 	else {
12342 		while (rem % 10 == 0)
12343 			rem /= 10;
12344 		snprintf(buf, len, "%u.%u", val / factor, rem);
12345 	}
12346 }
12347 
12348 static int
12349 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
12350 {
12351 	struct adapter *sc = arg1;
12352 	char buf[16];
12353 	u_int res, re;
12354 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
12355 
12356 	mtx_lock(&sc->reg_lock);
12357 	if (hw_off_limits(sc))
12358 		res = (u_int)-1;
12359 	else
12360 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
12361 	mtx_unlock(&sc->reg_lock);
12362 	if (res == (u_int)-1)
12363 		return (ENXIO);
12364 
12365 	switch (arg2) {
12366 	case 0:
12367 		/* timer_tick */
12368 		re = G_TIMERRESOLUTION(res);
12369 		break;
12370 	case 1:
12371 		/* TCP timestamp tick */
12372 		re = G_TIMESTAMPRESOLUTION(res);
12373 		break;
12374 	case 2:
12375 		/* DACK tick */
12376 		re = G_DELAYEDACKRESOLUTION(res);
12377 		break;
12378 	default:
12379 		return (EDOOFUS);
12380 	}
12381 
12382 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
12383 
12384 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
12385 }
12386 
12387 static int
12388 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
12389 {
12390 	struct adapter *sc = arg1;
12391 	int rc;
12392 	u_int dack_tmr, dack_re, v;
12393 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
12394 
12395 	mtx_lock(&sc->reg_lock);
12396 	if (hw_off_limits(sc))
12397 		rc = ENXIO;
12398 	else {
12399 		rc = 0;
12400 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
12401 		    A_TP_TIMER_RESOLUTION));
12402 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
12403 	}
12404 	mtx_unlock(&sc->reg_lock);
12405 	if (rc != 0)
12406 		return (rc);
12407 
12408 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
12409 
12410 	return (sysctl_handle_int(oidp, &v, 0, req));
12411 }
12412 
12413 static int
12414 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
12415 {
12416 	struct adapter *sc = arg1;
12417 	int rc, reg = arg2;
12418 	u_int tre;
12419 	u_long tp_tick_us, v;
12420 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
12421 
12422 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
12423 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
12424 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
12425 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
12426 
12427 	mtx_lock(&sc->reg_lock);
12428 	if (hw_off_limits(sc))
12429 		rc = ENXIO;
12430 	else {
12431 		rc = 0;
12432 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
12433 		tp_tick_us = (cclk_ps << tre) / 1000000;
12434 		if (reg == A_TP_INIT_SRTT)
12435 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
12436 		else
12437 			v = tp_tick_us * t4_read_reg(sc, reg);
12438 	}
12439 	mtx_unlock(&sc->reg_lock);
12440 	if (rc != 0)
12441 		return (rc);
12442 	else
12443 		return (sysctl_handle_long(oidp, &v, 0, req));
12444 }
12445 
12446 /*
12447  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
12448  * passed to this function.
12449  */
12450 static int
12451 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
12452 {
12453 	struct adapter *sc = arg1;
12454 	int rc, idx = arg2;
12455 	u_int v;
12456 
12457 	MPASS(idx >= 0 && idx <= 24);
12458 
12459 	mtx_lock(&sc->reg_lock);
12460 	if (hw_off_limits(sc))
12461 		rc = ENXIO;
12462 	else {
12463 		rc = 0;
12464 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
12465 	}
12466 	mtx_unlock(&sc->reg_lock);
12467 	if (rc != 0)
12468 		return (rc);
12469 	else
12470 		return (sysctl_handle_int(oidp, &v, 0, req));
12471 }
12472 
12473 static int
12474 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
12475 {
12476 	struct adapter *sc = arg1;
12477 	int rc, idx = arg2;
12478 	u_int shift, v, r;
12479 
12480 	MPASS(idx >= 0 && idx < 16);
12481 
12482 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
12483 	shift = (idx & 3) << 3;
12484 	mtx_lock(&sc->reg_lock);
12485 	if (hw_off_limits(sc))
12486 		rc = ENXIO;
12487 	else {
12488 		rc = 0;
12489 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
12490 	}
12491 	mtx_unlock(&sc->reg_lock);
12492 	if (rc != 0)
12493 		return (rc);
12494 	else
12495 		return (sysctl_handle_int(oidp, &v, 0, req));
12496 }
12497 
12498 static int
12499 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
12500 {
12501 	struct vi_info *vi = arg1;
12502 	struct adapter *sc = vi->adapter;
12503 	int idx, rc, i;
12504 	struct sge_ofld_rxq *ofld_rxq;
12505 	uint8_t v;
12506 
12507 	idx = vi->ofld_tmr_idx;
12508 
12509 	rc = sysctl_handle_int(oidp, &idx, 0, req);
12510 	if (rc != 0 || req->newptr == NULL)
12511 		return (rc);
12512 
12513 	if (idx < 0 || idx >= SGE_NTIMERS)
12514 		return (EINVAL);
12515 
12516 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
12517 	    "t4otmr");
12518 	if (rc)
12519 		return (rc);
12520 
12521 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
12522 	for_each_ofld_rxq(vi, i, ofld_rxq) {
12523 #ifdef atomic_store_rel_8
12524 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
12525 #else
12526 		ofld_rxq->iq.intr_params = v;
12527 #endif
12528 	}
12529 	vi->ofld_tmr_idx = idx;
12530 
12531 	end_synchronized_op(sc, LOCK_HELD);
12532 	return (0);
12533 }
12534 
12535 static int
12536 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
12537 {
12538 	struct vi_info *vi = arg1;
12539 	struct adapter *sc = vi->adapter;
12540 	int idx, rc;
12541 
12542 	idx = vi->ofld_pktc_idx;
12543 
12544 	rc = sysctl_handle_int(oidp, &idx, 0, req);
12545 	if (rc != 0 || req->newptr == NULL)
12546 		return (rc);
12547 
12548 	if (idx < -1 || idx >= SGE_NCOUNTERS)
12549 		return (EINVAL);
12550 
12551 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
12552 	    "t4opktc");
12553 	if (rc)
12554 		return (rc);
12555 
12556 	if (vi->flags & VI_INIT_DONE)
12557 		rc = EBUSY; /* cannot be changed once the queues are created */
12558 	else
12559 		vi->ofld_pktc_idx = idx;
12560 
12561 	end_synchronized_op(sc, LOCK_HELD);
12562 	return (rc);
12563 }
12564 #endif
12565 
12566 static int
12567 get_sge_context(struct adapter *sc, int mem_id, uint32_t cid, int len,
12568     uint32_t *data)
12569 {
12570 	int rc;
12571 
12572 	if (len < sc->chip_params->sge_ctxt_size)
12573 		return (ENOBUFS);
12574 	if (cid > M_CTXTQID)
12575 		return (EINVAL);
12576 	if (mem_id != CTXT_EGRESS && mem_id != CTXT_INGRESS &&
12577 	    mem_id != CTXT_FLM && mem_id != CTXT_CNM)
12578 		return (EINVAL);
12579 
12580 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
12581 	if (rc)
12582 		return (rc);
12583 
12584 	if (hw_off_limits(sc)) {
12585 		rc = ENXIO;
12586 		goto done;
12587 	}
12588 
12589 	if (sc->flags & FW_OK && !is_t7(sc)) {
12590 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cid, mem_id, data);
12591 		if (rc == 0)
12592 			goto done;
12593 	}
12594 
12595 	/*
12596 	 * Read via firmware failed or wasn't even attempted.  Read directly via
12597 	 * the backdoor.
12598 	 */
12599 	rc = -t4_sge_ctxt_rd_bd(sc, cid, mem_id, data);
12600 done:
12601 	end_synchronized_op(sc, 0);
12602 	return (rc);
12603 }
12604 
12605 static int
12606 load_fw(struct adapter *sc, struct t4_data *fw)
12607 {
12608 	int rc;
12609 	uint8_t *fw_data;
12610 
12611 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
12612 	if (rc)
12613 		return (rc);
12614 
12615 	if (hw_off_limits(sc)) {
12616 		rc = ENXIO;
12617 		goto done;
12618 	}
12619 
12620 	/*
12621 	 * The firmware, with the sole exception of the memory parity error
12622 	 * handler, runs from memory and not flash.  It is almost always safe to
12623 	 * install a new firmware on a running system.  Just set bit 1 in
12624 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
12625 	 */
12626 	if (sc->flags & FULL_INIT_DONE &&
12627 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
12628 		rc = EBUSY;
12629 		goto done;
12630 	}
12631 
12632 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
12633 
12634 	rc = copyin(fw->data, fw_data, fw->len);
12635 	if (rc == 0)
12636 		rc = -t4_load_fw(sc, fw_data, fw->len);
12637 
12638 	free(fw_data, M_CXGBE);
12639 done:
12640 	end_synchronized_op(sc, 0);
12641 	return (rc);
12642 }
12643 
12644 static int
12645 load_cfg(struct adapter *sc, struct t4_data *cfg)
12646 {
12647 	int rc;
12648 	uint8_t *cfg_data = NULL;
12649 
12650 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
12651 	if (rc)
12652 		return (rc);
12653 
12654 	if (hw_off_limits(sc)) {
12655 		rc = ENXIO;
12656 		goto done;
12657 	}
12658 
12659 	if (cfg->len == 0) {
12660 		/* clear */
12661 		rc = -t4_load_cfg(sc, NULL, 0);
12662 		goto done;
12663 	}
12664 
12665 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
12666 
12667 	rc = copyin(cfg->data, cfg_data, cfg->len);
12668 	if (rc == 0)
12669 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
12670 
12671 	free(cfg_data, M_CXGBE);
12672 done:
12673 	end_synchronized_op(sc, 0);
12674 	return (rc);
12675 }
12676 
12677 static int
12678 load_boot(struct adapter *sc, struct t4_bootrom *br)
12679 {
12680 	int rc;
12681 	uint8_t *br_data = NULL;
12682 	u_int offset;
12683 
12684 	if (br->len > 1024 * 1024)
12685 		return (EFBIG);
12686 
12687 	if (br->pf_offset == 0) {
12688 		/* pfidx */
12689 		if (br->pfidx_addr > 7)
12690 			return (EINVAL);
12691 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
12692 		    A_PCIE_PF_EXPROM_OFST)));
12693 	} else if (br->pf_offset == 1) {
12694 		/* offset */
12695 		offset = G_OFFSET(br->pfidx_addr);
12696 	} else {
12697 		return (EINVAL);
12698 	}
12699 
12700 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
12701 	if (rc)
12702 		return (rc);
12703 
12704 	if (hw_off_limits(sc)) {
12705 		rc = ENXIO;
12706 		goto done;
12707 	}
12708 
12709 	if (br->len == 0) {
12710 		/* clear */
12711 		rc = -t4_load_boot(sc, NULL, offset, 0);
12712 		goto done;
12713 	}
12714 
12715 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
12716 
12717 	rc = copyin(br->data, br_data, br->len);
12718 	if (rc == 0)
12719 		rc = -t4_load_boot(sc, br_data, offset, br->len);
12720 
12721 	free(br_data, M_CXGBE);
12722 done:
12723 	end_synchronized_op(sc, 0);
12724 	return (rc);
12725 }
12726 
12727 static int
12728 load_bootcfg(struct adapter *sc, struct t4_data *bc)
12729 {
12730 	int rc;
12731 	uint8_t *bc_data = NULL;
12732 
12733 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
12734 	if (rc)
12735 		return (rc);
12736 
12737 	if (hw_off_limits(sc)) {
12738 		rc = ENXIO;
12739 		goto done;
12740 	}
12741 
12742 	if (bc->len == 0) {
12743 		/* clear */
12744 		rc = -t4_load_bootcfg(sc, NULL, 0);
12745 		goto done;
12746 	}
12747 
12748 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
12749 
12750 	rc = copyin(bc->data, bc_data, bc->len);
12751 	if (rc == 0)
12752 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
12753 
12754 	free(bc_data, M_CXGBE);
12755 done:
12756 	end_synchronized_op(sc, 0);
12757 	return (rc);
12758 }
12759 
12760 static int
12761 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
12762 {
12763 	int rc;
12764 	struct cudbg_init *cudbg;
12765 	void *handle, *buf;
12766 
12767 	/* buf is large, don't block if no memory is available */
12768 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
12769 	if (buf == NULL)
12770 		return (ENOMEM);
12771 
12772 	handle = cudbg_alloc_handle();
12773 	if (handle == NULL) {
12774 		rc = ENOMEM;
12775 		goto done;
12776 	}
12777 
12778 	cudbg = cudbg_get_init(handle);
12779 	cudbg->adap = sc;
12780 	cudbg->print = (cudbg_print_cb)printf;
12781 
12782 #ifndef notyet
12783 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
12784 	    __func__, dump->wr_flash, dump->len, dump->data);
12785 #endif
12786 
12787 	if (dump->wr_flash)
12788 		cudbg->use_flash = 1;
12789 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
12790 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
12791 
12792 	rc = cudbg_collect(handle, buf, &dump->len);
12793 	if (rc != 0)
12794 		goto done;
12795 
12796 	rc = copyout(buf, dump->data, dump->len);
12797 done:
12798 	cudbg_free_handle(handle);
12799 	free(buf, M_CXGBE);
12800 	return (rc);
12801 }
12802 
12803 static void
12804 free_offload_policy(struct t4_offload_policy *op)
12805 {
12806 	struct offload_rule *r;
12807 	int i;
12808 
12809 	if (op == NULL)
12810 		return;
12811 
12812 	r = &op->rule[0];
12813 	for (i = 0; i < op->nrules; i++, r++) {
12814 		free(r->bpf_prog.bf_insns, M_CXGBE);
12815 	}
12816 	free(op->rule, M_CXGBE);
12817 	free(op, M_CXGBE);
12818 }
12819 
12820 static int
12821 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
12822 {
12823 	int i, rc, len;
12824 	struct t4_offload_policy *op, *old;
12825 	struct bpf_program *bf;
12826 	const struct offload_settings *s;
12827 	struct offload_rule *r;
12828 	void *u;
12829 
12830 	if (!is_offload(sc))
12831 		return (ENODEV);
12832 
12833 	if (uop->nrules == 0) {
12834 		/* Delete installed policies. */
12835 		op = NULL;
12836 		goto set_policy;
12837 	} else if (uop->nrules > 256) { /* arbitrary */
12838 		return (E2BIG);
12839 	}
12840 
12841 	/* Copy userspace offload policy to kernel */
12842 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
12843 	op->nrules = uop->nrules;
12844 	len = op->nrules * sizeof(struct offload_rule);
12845 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
12846 	rc = copyin(uop->rule, op->rule, len);
12847 	if (rc) {
12848 		free(op->rule, M_CXGBE);
12849 		free(op, M_CXGBE);
12850 		return (rc);
12851 	}
12852 
12853 	r = &op->rule[0];
12854 	for (i = 0; i < op->nrules; i++, r++) {
12855 
12856 		/* Validate open_type */
12857 		if (r->open_type != OPEN_TYPE_LISTEN &&
12858 		    r->open_type != OPEN_TYPE_ACTIVE &&
12859 		    r->open_type != OPEN_TYPE_PASSIVE &&
12860 		    r->open_type != OPEN_TYPE_DONTCARE) {
12861 error:
12862 			/*
12863 			 * Rules 0 to i have malloc'd filters that need to be
12864 			 * freed.  Rules i+1 to nrules have userspace pointers
12865 			 * and should be left alone.
12866 			 */
12867 			op->nrules = i;
12868 			free_offload_policy(op);
12869 			return (rc);
12870 		}
12871 
12872 		/* Validate settings */
12873 		s = &r->settings;
12874 		if ((s->offload != 0 && s->offload != 1) ||
12875 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
12876 		    s->sched_class < -1 ||
12877 		    s->sched_class >= sc->params.nsched_cls) {
12878 			rc = EINVAL;
12879 			goto error;
12880 		}
12881 
12882 		bf = &r->bpf_prog;
12883 		u = bf->bf_insns;	/* userspace ptr */
12884 		bf->bf_insns = NULL;
12885 		if (bf->bf_len == 0) {
12886 			/* legal, matches everything */
12887 			continue;
12888 		}
12889 		len = bf->bf_len * sizeof(*bf->bf_insns);
12890 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
12891 		rc = copyin(u, bf->bf_insns, len);
12892 		if (rc != 0)
12893 			goto error;
12894 
12895 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
12896 			rc = EINVAL;
12897 			goto error;
12898 		}
12899 	}
12900 set_policy:
12901 	rw_wlock(&sc->policy_lock);
12902 	old = sc->policy;
12903 	sc->policy = op;
12904 	rw_wunlock(&sc->policy_lock);
12905 	free_offload_policy(old);
12906 
12907 	return (0);
12908 }
12909 
12910 #define MAX_READ_BUF_SIZE (128 * 1024)
12911 static int
12912 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
12913 {
12914 	uint32_t addr, remaining, n;
12915 	uint32_t *buf;
12916 	int rc;
12917 	uint8_t *dst;
12918 
12919 	mtx_lock(&sc->reg_lock);
12920 	if (hw_off_limits(sc))
12921 		rc = ENXIO;
12922 	else
12923 		rc = validate_mem_range(sc, mr->addr, mr->len);
12924 	mtx_unlock(&sc->reg_lock);
12925 	if (rc != 0)
12926 		return (rc);
12927 
12928 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
12929 	addr = mr->addr;
12930 	remaining = mr->len;
12931 	dst = (void *)mr->data;
12932 
12933 	while (remaining) {
12934 		n = min(remaining, MAX_READ_BUF_SIZE);
12935 		mtx_lock(&sc->reg_lock);
12936 		if (hw_off_limits(sc))
12937 			rc = ENXIO;
12938 		else
12939 			read_via_memwin(sc, 2, addr, buf, n);
12940 		mtx_unlock(&sc->reg_lock);
12941 		if (rc != 0)
12942 			break;
12943 
12944 		rc = copyout(buf, dst, n);
12945 		if (rc != 0)
12946 			break;
12947 
12948 		dst += n;
12949 		remaining -= n;
12950 		addr += n;
12951 	}
12952 
12953 	free(buf, M_CXGBE);
12954 	return (rc);
12955 }
12956 #undef MAX_READ_BUF_SIZE
12957 
12958 static int
12959 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
12960 {
12961 	int rc;
12962 
12963 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
12964 		return (EINVAL);
12965 
12966 	if (i2cd->len > sizeof(i2cd->data))
12967 		return (EFBIG);
12968 
12969 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
12970 	if (rc)
12971 		return (rc);
12972 	if (hw_off_limits(sc))
12973 		rc = ENXIO;
12974 	else
12975 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
12976 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
12977 	end_synchronized_op(sc, 0);
12978 
12979 	return (rc);
12980 }
12981 
12982 static int
12983 clear_stats(struct adapter *sc, u_int port_id)
12984 {
12985 	int i, v, chan_map;
12986 	struct port_info *pi;
12987 	struct vi_info *vi;
12988 	struct sge_rxq *rxq;
12989 	struct sge_txq *txq;
12990 	struct sge_wrq *wrq;
12991 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12992 	struct sge_ofld_txq *ofld_txq;
12993 #endif
12994 #ifdef TCP_OFFLOAD
12995 	struct sge_ofld_rxq *ofld_rxq;
12996 #endif
12997 
12998 	if (port_id >= sc->params.nports)
12999 		return (EINVAL);
13000 	pi = sc->port[port_id];
13001 	if (pi == NULL)
13002 		return (EIO);
13003 
13004 	mtx_lock(&sc->reg_lock);
13005 	if (!hw_off_limits(sc)) {
13006 		/* MAC stats */
13007 		t4_clr_port_stats(sc, pi->hw_port);
13008 		if (is_t6(sc)) {
13009 			if (pi->fcs_reg != -1)
13010 				pi->fcs_base = t4_read_reg64(sc,
13011 				    t4_port_reg(sc, pi->tx_chan, pi->fcs_reg));
13012 			else
13013 				pi->stats.rx_fcs_err = 0;
13014 		}
13015 		for_each_vi(pi, v, vi) {
13016 			if (vi->flags & VI_INIT_DONE)
13017 				t4_clr_vi_stats(sc, vi->vin);
13018 		}
13019 		chan_map = pi->rx_e_chan_map;
13020 		v = 0;	/* reuse */
13021 		while (chan_map) {
13022 			i = ffs(chan_map) - 1;
13023 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
13024 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
13025 			chan_map &= ~(1 << i);
13026 		}
13027 	}
13028 	mtx_unlock(&sc->reg_lock);
13029 	pi->tx_parse_error = 0;
13030 	pi->tnl_cong_drops = 0;
13031 
13032 	/*
13033 	 * Since this command accepts a port, clear stats for
13034 	 * all VIs on this port.
13035 	 */
13036 	for_each_vi(pi, v, vi) {
13037 		if (vi->flags & VI_INIT_DONE) {
13038 
13039 			for_each_rxq(vi, i, rxq) {
13040 #if defined(INET) || defined(INET6)
13041 				rxq->lro.lro_queued = 0;
13042 				rxq->lro.lro_flushed = 0;
13043 #endif
13044 				rxq->rxcsum = 0;
13045 				rxq->vlan_extraction = 0;
13046 				rxq->vxlan_rxcsum = 0;
13047 
13048 				rxq->fl.cl_allocated = 0;
13049 				rxq->fl.cl_recycled = 0;
13050 				rxq->fl.cl_fast_recycled = 0;
13051 			}
13052 
13053 			for_each_txq(vi, i, txq) {
13054 				txq->txcsum = 0;
13055 				txq->tso_wrs = 0;
13056 				txq->vlan_insertion = 0;
13057 				txq->imm_wrs = 0;
13058 				txq->sgl_wrs = 0;
13059 				txq->txpkt_wrs = 0;
13060 				txq->txpkts0_wrs = 0;
13061 				txq->txpkts1_wrs = 0;
13062 				txq->txpkts0_pkts = 0;
13063 				txq->txpkts1_pkts = 0;
13064 				txq->txpkts_flush = 0;
13065 				txq->raw_wrs = 0;
13066 				txq->vxlan_tso_wrs = 0;
13067 				txq->vxlan_txcsum = 0;
13068 				txq->kern_tls_records = 0;
13069 				txq->kern_tls_short = 0;
13070 				txq->kern_tls_partial = 0;
13071 				txq->kern_tls_full = 0;
13072 				txq->kern_tls_octets = 0;
13073 				txq->kern_tls_waste = 0;
13074 				txq->kern_tls_header = 0;
13075 				txq->kern_tls_fin_short = 0;
13076 				txq->kern_tls_cbc = 0;
13077 				txq->kern_tls_gcm = 0;
13078 				if (is_t6(sc)) {
13079 					txq->kern_tls_options = 0;
13080 					txq->kern_tls_fin = 0;
13081 				} else {
13082 					txq->kern_tls_ghash_received = 0;
13083 					txq->kern_tls_ghash_requested = 0;
13084 					txq->kern_tls_lso = 0;
13085 					txq->kern_tls_partial_ghash = 0;
13086 					txq->kern_tls_splitmode = 0;
13087 					txq->kern_tls_trailer = 0;
13088 				}
13089 				mp_ring_reset_stats(txq->r);
13090 			}
13091 
13092 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
13093 			for_each_ofld_txq(vi, i, ofld_txq) {
13094 				ofld_txq->wrq.tx_wrs_direct = 0;
13095 				ofld_txq->wrq.tx_wrs_copied = 0;
13096 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
13097 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
13098 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
13099 				counter_u64_zero(ofld_txq->tx_nvme_pdus);
13100 				counter_u64_zero(ofld_txq->tx_nvme_octets);
13101 				counter_u64_zero(ofld_txq->tx_nvme_iso_wrs);
13102 				counter_u64_zero(ofld_txq->tx_aio_jobs);
13103 				counter_u64_zero(ofld_txq->tx_aio_octets);
13104 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
13105 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
13106 			}
13107 #endif
13108 #ifdef TCP_OFFLOAD
13109 			for_each_ofld_rxq(vi, i, ofld_rxq) {
13110 				ofld_rxq->fl.cl_allocated = 0;
13111 				ofld_rxq->fl.cl_recycled = 0;
13112 				ofld_rxq->fl.cl_fast_recycled = 0;
13113 				counter_u64_zero(
13114 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
13115 				counter_u64_zero(
13116 				    ofld_rxq->rx_iscsi_ddp_setup_error);
13117 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
13118 				ofld_rxq->rx_iscsi_ddp_octets = 0;
13119 				ofld_rxq->rx_iscsi_fl_pdus = 0;
13120 				ofld_rxq->rx_iscsi_fl_octets = 0;
13121 				counter_u64_zero(
13122 				    ofld_rxq->rx_nvme_ddp_setup_ok);
13123 				counter_u64_zero(
13124 				    ofld_rxq->rx_nvme_ddp_setup_no_stag);
13125 				counter_u64_zero(
13126 				    ofld_rxq->rx_nvme_ddp_setup_error);
13127 				counter_u64_zero(ofld_rxq->rx_nvme_ddp_pdus);
13128 				counter_u64_zero(ofld_rxq->rx_nvme_ddp_octets);
13129 				counter_u64_zero(ofld_rxq->rx_nvme_fl_pdus);
13130 				counter_u64_zero(ofld_rxq->rx_nvme_fl_octets);
13131 				counter_u64_zero(
13132 				    ofld_rxq->rx_nvme_invalid_headers);
13133 				counter_u64_zero(
13134 				    ofld_rxq->rx_nvme_header_digest_errors);
13135 				counter_u64_zero(
13136 				    ofld_rxq->rx_nvme_data_digest_errors);
13137 				ofld_rxq->rx_aio_ddp_jobs = 0;
13138 				ofld_rxq->rx_aio_ddp_octets = 0;
13139 				ofld_rxq->rx_toe_tls_records = 0;
13140 				ofld_rxq->rx_toe_tls_octets = 0;
13141 				ofld_rxq->rx_toe_ddp_octets = 0;
13142 				counter_u64_zero(ofld_rxq->ddp_buffer_alloc);
13143 				counter_u64_zero(ofld_rxq->ddp_buffer_reuse);
13144 				counter_u64_zero(ofld_rxq->ddp_buffer_free);
13145 			}
13146 #endif
13147 
13148 			if (IS_MAIN_VI(vi)) {
13149 				wrq = &sc->sge.ctrlq[pi->port_id];
13150 				wrq->tx_wrs_direct = 0;
13151 				wrq->tx_wrs_copied = 0;
13152 			}
13153 		}
13154 	}
13155 
13156 	return (0);
13157 }
13158 
13159 static int
13160 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
13161 {
13162 #ifdef INET6
13163 	struct in6_addr in6;
13164 
13165 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
13166 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
13167 		return (0);
13168 	else
13169 		return (EIO);
13170 #else
13171 	return (ENOTSUP);
13172 #endif
13173 }
13174 
13175 static int
13176 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
13177 {
13178 #ifdef INET6
13179 	struct in6_addr in6;
13180 
13181 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
13182 	return (t4_release_clip_addr(sc, &in6));
13183 #else
13184 	return (ENOTSUP);
13185 #endif
13186 }
13187 
13188 int
13189 t4_os_find_pci_capability(struct adapter *sc, int cap)
13190 {
13191 	int i;
13192 
13193 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
13194 }
13195 
13196 void
13197 t4_os_portmod_changed(struct port_info *pi)
13198 {
13199 	struct adapter *sc = pi->adapter;
13200 	struct vi_info *vi;
13201 	if_t ifp;
13202 	static const char *mod_str[] = {
13203 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM",
13204 		"LR_SIMPLEX", "DR"
13205 	};
13206 
13207 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
13208 	    ("%s: port_type %u", __func__, pi->port_type));
13209 
13210 	vi = &pi->vi[0];
13211 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
13212 		PORT_LOCK(pi);
13213 		build_medialist(pi);
13214 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
13215 			fixup_link_config(pi);
13216 			apply_link_config(pi);
13217 		}
13218 		PORT_UNLOCK(pi);
13219 		end_synchronized_op(sc, LOCK_HELD);
13220 	}
13221 
13222 	ifp = vi->ifp;
13223 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
13224 		if_printf(ifp, "transceiver unplugged.\n");
13225 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
13226 		if_printf(ifp, "unknown transceiver inserted.\n");
13227 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
13228 		if_printf(ifp, "unsupported transceiver inserted.\n");
13229 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
13230 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
13231 		    port_top_speed(pi), mod_str[pi->mod_type]);
13232 	} else {
13233 		if_printf(ifp, "transceiver (type %d) inserted.\n",
13234 		    pi->mod_type);
13235 	}
13236 }
13237 
13238 void
13239 t4_os_link_changed(struct port_info *pi)
13240 {
13241 	struct vi_info *vi;
13242 	if_t ifp;
13243 	struct link_config *lc = &pi->link_cfg;
13244 	struct adapter *sc = pi->adapter;
13245 	int v;
13246 
13247 	PORT_LOCK_ASSERT_OWNED(pi);
13248 
13249 	if (is_t6(sc)) {
13250 		if (lc->link_ok) {
13251 			if (lc->speed > 25000 ||
13252 			    (lc->speed == 25000 && lc->fec == FEC_RS))
13253 				pi->fcs_reg = A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS;
13254 			else
13255 				pi->fcs_reg = A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS;
13256 			pi->fcs_base = t4_read_reg64(sc,
13257 			    t4_port_reg(sc, pi->tx_chan, pi->fcs_reg));
13258 			pi->stats.rx_fcs_err = 0;
13259 		} else {
13260 			pi->fcs_reg = -1;
13261 		}
13262 	} else {
13263 		MPASS(pi->fcs_reg != -1);
13264 		MPASS(pi->fcs_base == 0);
13265 	}
13266 
13267 	for_each_vi(pi, v, vi) {
13268 		ifp = vi->ifp;
13269 		if (ifp == NULL || IS_DETACHING(vi))
13270 			continue;
13271 
13272 		if (lc->link_ok) {
13273 			if_setbaudrate(ifp, IF_Mbps(lc->speed));
13274 			if_link_state_change(ifp, LINK_STATE_UP);
13275 		} else {
13276 			if_link_state_change(ifp, LINK_STATE_DOWN);
13277 		}
13278 	}
13279 }
13280 
13281 void
13282 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
13283 {
13284 	struct adapter *sc;
13285 
13286 	sx_slock(&t4_list_lock);
13287 	SLIST_FOREACH(sc, &t4_list, link) {
13288 		/*
13289 		 * func should not make any assumptions about what state sc is
13290 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
13291 		 */
13292 		func(sc, arg);
13293 	}
13294 	sx_sunlock(&t4_list_lock);
13295 }
13296 
13297 static int
13298 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
13299     struct thread *td)
13300 {
13301 	int rc;
13302 	struct adapter *sc = dev->si_drv1;
13303 
13304 	rc = priv_check(td, PRIV_DRIVER);
13305 	if (rc != 0)
13306 		return (rc);
13307 
13308 	switch (cmd) {
13309 	case CHELSIO_T4_GETREG: {
13310 		struct t4_reg *edata = (struct t4_reg *)data;
13311 
13312 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
13313 			return (EFAULT);
13314 
13315 		mtx_lock(&sc->reg_lock);
13316 		if (hw_off_limits(sc))
13317 			rc = ENXIO;
13318 		else if (edata->size == 4)
13319 			edata->val = t4_read_reg(sc, edata->addr);
13320 		else if (edata->size == 8)
13321 			edata->val = t4_read_reg64(sc, edata->addr);
13322 		else
13323 			rc = EINVAL;
13324 		mtx_unlock(&sc->reg_lock);
13325 
13326 		break;
13327 	}
13328 	case CHELSIO_T4_SETREG: {
13329 		struct t4_reg *edata = (struct t4_reg *)data;
13330 
13331 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
13332 			return (EFAULT);
13333 
13334 		mtx_lock(&sc->reg_lock);
13335 		if (hw_off_limits(sc))
13336 			rc = ENXIO;
13337 		else if (edata->size == 4) {
13338 			if (edata->val & 0xffffffff00000000)
13339 				rc = EINVAL;
13340 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
13341 		} else if (edata->size == 8)
13342 			t4_write_reg64(sc, edata->addr, edata->val);
13343 		else
13344 			rc = EINVAL;
13345 		mtx_unlock(&sc->reg_lock);
13346 
13347 		break;
13348 	}
13349 	case CHELSIO_T4_REGDUMP: {
13350 		struct t4_regdump *regs = (struct t4_regdump *)data;
13351 		int reglen = t4_get_regs_len(sc);
13352 		uint8_t *buf;
13353 
13354 		if (regs->len < reglen) {
13355 			regs->len = reglen; /* hint to the caller */
13356 			return (ENOBUFS);
13357 		}
13358 
13359 		regs->len = reglen;
13360 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
13361 		mtx_lock(&sc->reg_lock);
13362 		if (hw_off_limits(sc))
13363 			rc = ENXIO;
13364 		else
13365 			get_regs(sc, regs, buf);
13366 		mtx_unlock(&sc->reg_lock);
13367 		if (rc == 0)
13368 			rc = copyout(buf, regs->data, reglen);
13369 		free(buf, M_CXGBE);
13370 		break;
13371 	}
13372 	case CHELSIO_T4_GET_FILTER_MODE:
13373 		rc = get_filter_mode(sc, (uint32_t *)data);
13374 		break;
13375 	case CHELSIO_T4_SET_FILTER_MODE:
13376 		rc = set_filter_mode(sc, *(uint32_t *)data);
13377 		break;
13378 	case CHELSIO_T4_SET_FILTER_MASK:
13379 		rc = set_filter_mask(sc, *(uint32_t *)data);
13380 		break;
13381 	case CHELSIO_T4_GET_FILTER:
13382 		rc = get_filter(sc, (struct t4_filter *)data);
13383 		break;
13384 	case CHELSIO_T4_SET_FILTER:
13385 		rc = set_filter(sc, (struct t4_filter *)data);
13386 		break;
13387 	case CHELSIO_T4_DEL_FILTER:
13388 		rc = del_filter(sc, (struct t4_filter *)data);
13389 		break;
13390 	case CHELSIO_T4_GET_SGE_CONTEXT: {
13391 		struct t4_sge_context *ctxt = (struct t4_sge_context *)data;
13392 
13393 		rc = get_sge_context(sc, ctxt->mem_id, ctxt->cid,
13394 		    sizeof(ctxt->data), &ctxt->data[0]);
13395 		break;
13396 	}
13397 	case CHELSIO_T4_LOAD_FW:
13398 		rc = load_fw(sc, (struct t4_data *)data);
13399 		break;
13400 	case CHELSIO_T4_GET_MEM:
13401 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
13402 		break;
13403 	case CHELSIO_T4_GET_I2C:
13404 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
13405 		break;
13406 	case CHELSIO_T4_CLEAR_STATS:
13407 		rc = clear_stats(sc, *(uint32_t *)data);
13408 		break;
13409 	case CHELSIO_T4_SCHED_CLASS:
13410 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
13411 		break;
13412 	case CHELSIO_T4_SCHED_QUEUE:
13413 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
13414 		break;
13415 	case CHELSIO_T4_GET_TRACER:
13416 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
13417 		break;
13418 	case CHELSIO_T4_SET_TRACER:
13419 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
13420 		break;
13421 	case CHELSIO_T4_LOAD_CFG:
13422 		rc = load_cfg(sc, (struct t4_data *)data);
13423 		break;
13424 	case CHELSIO_T4_LOAD_BOOT:
13425 		rc = load_boot(sc, (struct t4_bootrom *)data);
13426 		break;
13427 	case CHELSIO_T4_LOAD_BOOTCFG:
13428 		rc = load_bootcfg(sc, (struct t4_data *)data);
13429 		break;
13430 	case CHELSIO_T4_CUDBG_DUMP:
13431 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
13432 		break;
13433 	case CHELSIO_T4_SET_OFLD_POLICY:
13434 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
13435 		break;
13436 	case CHELSIO_T4_HOLD_CLIP_ADDR:
13437 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
13438 		break;
13439 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
13440 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
13441 		break;
13442 	case CHELSIO_T4_GET_SGE_CTXT: {
13443 		struct t4_sge_ctxt *ctxt = (struct t4_sge_ctxt *)data;
13444 
13445 		rc = get_sge_context(sc, ctxt->mem_id, ctxt->cid,
13446 		    sizeof(ctxt->data), &ctxt->data[0]);
13447 		break;
13448 	}
13449 	default:
13450 		rc = ENOTTY;
13451 	}
13452 
13453 	return (rc);
13454 }
13455 
13456 #ifdef TCP_OFFLOAD
13457 int
13458 toe_capability(struct vi_info *vi, bool enable)
13459 {
13460 	int rc;
13461 	struct port_info *pi = vi->pi;
13462 	struct adapter *sc = pi->adapter;
13463 
13464 	ASSERT_SYNCHRONIZED_OP(sc);
13465 
13466 	if (!is_offload(sc))
13467 		return (ENODEV);
13468 	if (!hw_all_ok(sc))
13469 		return (ENXIO);
13470 
13471 	if (enable) {
13472 #ifdef KERN_TLS
13473 		if (sc->flags & KERN_TLS_ON && is_t6(sc)) {
13474 			int i, j, n;
13475 			struct port_info *p;
13476 			struct vi_info *v;
13477 
13478 			/*
13479 			 * Reconfigure hardware for TOE if TXTLS is not enabled
13480 			 * on any ifnet.
13481 			 */
13482 			n = 0;
13483 			for_each_port(sc, i) {
13484 				p = sc->port[i];
13485 				for_each_vi(p, j, v) {
13486 					if (if_getcapenable(v->ifp) & IFCAP_TXTLS) {
13487 						CH_WARN(sc,
13488 						    "%s has NIC TLS enabled.\n",
13489 						    device_get_nameunit(v->dev));
13490 						n++;
13491 					}
13492 				}
13493 			}
13494 			if (n > 0) {
13495 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
13496 				    "associated with this adapter before "
13497 				    "trying to enable TOE.\n");
13498 				return (EAGAIN);
13499 			}
13500 			rc = t6_config_kern_tls(sc, false);
13501 			if (rc)
13502 				return (rc);
13503 		}
13504 #endif
13505 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) != 0) {
13506 			/* TOE is already enabled. */
13507 			return (0);
13508 		}
13509 
13510 		/*
13511 		 * We need the port's queues around so that we're able to send
13512 		 * and receive CPLs to/from the TOE even if the ifnet for this
13513 		 * port has never been UP'd administratively.
13514 		 */
13515 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
13516 			return (rc);
13517 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
13518 		    ((rc = vi_init(&pi->vi[0])) != 0))
13519 			return (rc);
13520 
13521 		if (isset(&sc->offload_map, pi->port_id)) {
13522 			/* TOE is enabled on another VI of this port. */
13523 			MPASS(pi->uld_vis > 0);
13524 			pi->uld_vis++;
13525 			return (0);
13526 		}
13527 
13528 		if (!uld_active(sc, ULD_TOM)) {
13529 			rc = t4_activate_uld(sc, ULD_TOM);
13530 			if (rc == EAGAIN) {
13531 				log(LOG_WARNING,
13532 				    "You must kldload t4_tom.ko before trying "
13533 				    "to enable TOE on a cxgbe interface.\n");
13534 			}
13535 			if (rc != 0)
13536 				return (rc);
13537 			KASSERT(sc->tom_softc != NULL,
13538 			    ("%s: TOM activated but softc NULL", __func__));
13539 			KASSERT(uld_active(sc, ULD_TOM),
13540 			    ("%s: TOM activated but flag not set", __func__));
13541 		}
13542 
13543 		/*
13544 		 * Activate iWARP, iSCSI, and NVMe too, if the modules
13545 		 * are loaded.
13546 		 */
13547 		if (!uld_active(sc, ULD_IWARP))
13548 			(void) t4_activate_uld(sc, ULD_IWARP);
13549 		if (!uld_active(sc, ULD_ISCSI))
13550 			(void) t4_activate_uld(sc, ULD_ISCSI);
13551 		if (!uld_active(sc, ULD_NVME))
13552 			(void) t4_activate_uld(sc, ULD_NVME);
13553 
13554 		if (pi->uld_vis++ == 0)
13555 			setbit(&sc->offload_map, pi->port_id);
13556 	} else {
13557 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) == 0) {
13558 			/* TOE is already disabled. */
13559 			return (0);
13560 		}
13561 		MPASS(isset(&sc->offload_map, pi->port_id));
13562 		MPASS(pi->uld_vis > 0);
13563 		if (--pi->uld_vis == 0)
13564 			clrbit(&sc->offload_map, pi->port_id);
13565 	}
13566 
13567 	return (0);
13568 }
13569 
13570 /*
13571  * Add an upper layer driver to the global list.
13572  */
13573 int
13574 t4_register_uld(struct uld_info *ui, int id)
13575 {
13576 	int rc;
13577 
13578 	if (id < 0 || id > ULD_MAX)
13579 		return (EINVAL);
13580 	sx_xlock(&t4_uld_list_lock);
13581 	if (t4_uld_list[id] != NULL)
13582 		rc = EEXIST;
13583 	else {
13584 		t4_uld_list[id] = ui;
13585 		rc = 0;
13586 	}
13587 	sx_xunlock(&t4_uld_list_lock);
13588 	return (rc);
13589 }
13590 
13591 int
13592 t4_unregister_uld(struct uld_info *ui, int id)
13593 {
13594 
13595 	if (id < 0 || id > ULD_MAX)
13596 		return (EINVAL);
13597 	sx_xlock(&t4_uld_list_lock);
13598 	MPASS(t4_uld_list[id] == ui);
13599 	t4_uld_list[id] = NULL;
13600 	sx_xunlock(&t4_uld_list_lock);
13601 	return (0);
13602 }
13603 
13604 int
13605 t4_activate_uld(struct adapter *sc, int id)
13606 {
13607 	int rc;
13608 
13609 	ASSERT_SYNCHRONIZED_OP(sc);
13610 
13611 	if (id < 0 || id > ULD_MAX)
13612 		return (EINVAL);
13613 
13614 	/* Adapter needs to be initialized before any ULD can be activated. */
13615 	if (!(sc->flags & FULL_INIT_DONE)) {
13616 		rc = adapter_init(sc);
13617 		if (rc != 0)
13618 			return (rc);
13619 	}
13620 
13621 	sx_slock(&t4_uld_list_lock);
13622 	if (t4_uld_list[id] == NULL)
13623 		rc = EAGAIN;	/* load the KLD with this ULD and try again. */
13624 	else {
13625 		rc = t4_uld_list[id]->uld_activate(sc);
13626 		if (rc == 0)
13627 			setbit(&sc->active_ulds, id);
13628 	}
13629 	sx_sunlock(&t4_uld_list_lock);
13630 
13631 	return (rc);
13632 }
13633 
13634 int
13635 t4_deactivate_uld(struct adapter *sc, int id)
13636 {
13637 	int rc;
13638 
13639 	ASSERT_SYNCHRONIZED_OP(sc);
13640 
13641 	if (id < 0 || id > ULD_MAX)
13642 		return (EINVAL);
13643 
13644 	sx_slock(&t4_uld_list_lock);
13645 	if (t4_uld_list[id] == NULL)
13646 		rc = ENXIO;
13647 	else {
13648 		rc = t4_uld_list[id]->uld_deactivate(sc);
13649 		if (rc == 0)
13650 			clrbit(&sc->active_ulds, id);
13651 	}
13652 	sx_sunlock(&t4_uld_list_lock);
13653 
13654 	return (rc);
13655 }
13656 
13657 static int
13658 deactivate_all_uld(struct adapter *sc)
13659 {
13660 	int i, rc;
13661 
13662 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4detuld");
13663 	if (rc != 0)
13664 		return (ENXIO);
13665 	sx_slock(&t4_uld_list_lock);
13666 	for (i = 0; i <= ULD_MAX; i++) {
13667 		if (t4_uld_list[i] == NULL || !uld_active(sc, i))
13668 			continue;
13669 		rc = t4_uld_list[i]->uld_deactivate(sc);
13670 		if (rc != 0)
13671 			break;
13672 		clrbit(&sc->active_ulds, i);
13673 	}
13674 	sx_sunlock(&t4_uld_list_lock);
13675 	end_synchronized_op(sc, 0);
13676 
13677 	return (rc);
13678 }
13679 
13680 static void
13681 stop_all_uld(struct adapter *sc)
13682 {
13683 	int i;
13684 
13685 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4uldst") != 0)
13686 		return;
13687 	sx_slock(&t4_uld_list_lock);
13688 	for (i = 0; i <= ULD_MAX; i++) {
13689 		if (t4_uld_list[i] == NULL || !uld_active(sc, i) ||
13690 		    t4_uld_list[i]->uld_stop == NULL)
13691 			continue;
13692 		(void) t4_uld_list[i]->uld_stop(sc);
13693 	}
13694 	sx_sunlock(&t4_uld_list_lock);
13695 	end_synchronized_op(sc, 0);
13696 }
13697 
13698 static void
13699 restart_all_uld(struct adapter *sc)
13700 {
13701 	int i;
13702 
13703 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4uldre") != 0)
13704 		return;
13705 	sx_slock(&t4_uld_list_lock);
13706 	for (i = 0; i <= ULD_MAX; i++) {
13707 		if (t4_uld_list[i] == NULL || !uld_active(sc, i) ||
13708 		    t4_uld_list[i]->uld_restart == NULL)
13709 			continue;
13710 		(void) t4_uld_list[i]->uld_restart(sc);
13711 	}
13712 	sx_sunlock(&t4_uld_list_lock);
13713 	end_synchronized_op(sc, 0);
13714 }
13715 
13716 int
13717 uld_active(struct adapter *sc, int id)
13718 {
13719 
13720 	MPASS(id >= 0 && id <= ULD_MAX);
13721 
13722 	return (isset(&sc->active_ulds, id));
13723 }
13724 #endif
13725 
13726 #ifdef KERN_TLS
13727 static int
13728 ktls_capability(struct adapter *sc, bool enable)
13729 {
13730 	ASSERT_SYNCHRONIZED_OP(sc);
13731 
13732 	if (!is_ktls(sc))
13733 		return (ENODEV);
13734 	if (!is_t6(sc))
13735 		return (0);
13736 	if (!hw_all_ok(sc))
13737 		return (ENXIO);
13738 
13739 	if (enable) {
13740 		if (sc->flags & KERN_TLS_ON)
13741 			return (0);	/* already on */
13742 		if (sc->offload_map != 0) {
13743 			CH_WARN(sc,
13744 			    "Disable TOE on all interfaces associated with "
13745 			    "this adapter before trying to enable NIC TLS.\n");
13746 			return (EAGAIN);
13747 		}
13748 		return (t6_config_kern_tls(sc, true));
13749 	} else {
13750 		/*
13751 		 * Nothing to do for disable.  If TOE is enabled sometime later
13752 		 * then toe_capability will reconfigure the hardware.
13753 		 */
13754 		return (0);
13755 	}
13756 }
13757 #endif
13758 
13759 /*
13760  * t  = ptr to tunable.
13761  * nc = number of CPUs.
13762  * c  = compiled in default for that tunable.
13763  */
13764 static void
13765 calculate_nqueues(int *t, int nc, const int c)
13766 {
13767 	int nq;
13768 
13769 	if (*t > 0)
13770 		return;
13771 	nq = *t < 0 ? -*t : c;
13772 	*t = min(nc, nq);
13773 }
13774 
13775 /*
13776  * Come up with reasonable defaults for some of the tunables, provided they're
13777  * not set by the user (in which case we'll use the values as is).
13778  */
13779 static void
13780 tweak_tunables(void)
13781 {
13782 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
13783 
13784 	if (t4_ntxq < 1) {
13785 #ifdef RSS
13786 		t4_ntxq = rss_getnumbuckets();
13787 #else
13788 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
13789 #endif
13790 	}
13791 
13792 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
13793 
13794 	if (t4_nrxq < 1) {
13795 #ifdef RSS
13796 		t4_nrxq = rss_getnumbuckets();
13797 #else
13798 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
13799 #endif
13800 	}
13801 
13802 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
13803 
13804 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
13805 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
13806 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
13807 #endif
13808 #ifdef TCP_OFFLOAD
13809 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
13810 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
13811 #endif
13812 
13813 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
13814 	if (t4_toecaps_allowed == -1)
13815 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
13816 #else
13817 	if (t4_toecaps_allowed == -1)
13818 		t4_toecaps_allowed = 0;
13819 #endif
13820 
13821 #ifdef TCP_OFFLOAD
13822 	if (t4_rdmacaps_allowed == -1) {
13823 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
13824 		    FW_CAPS_CONFIG_RDMA_RDMAC;
13825 	}
13826 
13827 	if (t4_iscsicaps_allowed == -1) {
13828 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
13829 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
13830 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
13831 	}
13832 
13833 	if (t4_nvmecaps_allowed == -1)
13834 		t4_nvmecaps_allowed = FW_CAPS_CONFIG_NVME_TCP;
13835 
13836 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
13837 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
13838 
13839 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
13840 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
13841 #else
13842 	if (t4_rdmacaps_allowed == -1)
13843 		t4_rdmacaps_allowed = 0;
13844 
13845 	if (t4_iscsicaps_allowed == -1)
13846 		t4_iscsicaps_allowed = 0;
13847 
13848 	if (t4_nvmecaps_allowed == -1)
13849 		t4_nvmecaps_allowed = 0;
13850 #endif
13851 
13852 #ifdef DEV_NETMAP
13853 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
13854 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
13855 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
13856 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
13857 #endif
13858 
13859 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
13860 		t4_tmr_idx = TMR_IDX;
13861 
13862 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
13863 		t4_pktc_idx = PKTC_IDX;
13864 
13865 	if (t4_qsize_txq < 128)
13866 		t4_qsize_txq = 128;
13867 
13868 	if (t4_qsize_rxq < 128)
13869 		t4_qsize_rxq = 128;
13870 	while (t4_qsize_rxq & 7)
13871 		t4_qsize_rxq++;
13872 
13873 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
13874 
13875 	/*
13876 	 * Number of VIs to create per-port.  The first VI is the "main" regular
13877 	 * VI for the port.  The rest are additional virtual interfaces on the
13878 	 * same physical port.  Note that the main VI does not have native
13879 	 * netmap support but the extra VIs do.
13880 	 *
13881 	 * Limit the number of VIs per port to the number of available
13882 	 * MAC addresses per port.
13883 	 */
13884 	if (t4_num_vis < 1)
13885 		t4_num_vis = 1;
13886 	if (t4_num_vis > nitems(vi_mac_funcs)) {
13887 		t4_num_vis = nitems(vi_mac_funcs);
13888 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
13889 	}
13890 
13891 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
13892 		pcie_relaxed_ordering = 1;
13893 #if defined(__i386__) || defined(__amd64__)
13894 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
13895 			pcie_relaxed_ordering = 0;
13896 #endif
13897 	}
13898 }
13899 
13900 #ifdef DDB
13901 static void
13902 t4_dump_mem(struct adapter *sc, u_int addr, u_int len)
13903 {
13904 	uint32_t base, j, off, pf, reg, save, win_pos;
13905 
13906 	reg = chip_id(sc) > CHELSIO_T6 ?
13907 	    PCIE_MEM_ACCESS_T7_REG(A_PCIE_MEM_ACCESS_OFFSET0, 2) :
13908 	    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
13909 	save = t4_read_reg(sc, reg);
13910 	base = sc->memwin[2].mw_base;
13911 
13912 	if (is_t4(sc)) {
13913 		pf = 0;
13914 		win_pos = addr & ~0xf;	/* start must be 16B aligned */
13915 	} else {
13916 		pf = V_PFNUM(sc->pf);
13917 		win_pos = addr & ~0x7f;	/* start must be 128B aligned */
13918 	}
13919 	off = addr - win_pos;
13920 	if (chip_id(sc) > CHELSIO_T6)
13921 		win_pos >>= X_T7_MEMOFST_SHIFT;
13922 	t4_write_reg(sc, reg, win_pos | pf);
13923 	t4_read_reg(sc, reg);
13924 
13925 	while (len > 0 && !db_pager_quit) {
13926 		uint32_t buf[8];
13927 		for (j = 0; j < 8; j++, off += 4)
13928 			buf[j] = htonl(t4_read_reg(sc, base + off));
13929 
13930 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
13931 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
13932 		    buf[7]);
13933 		if (len <= sizeof(buf))
13934 			len = 0;
13935 		else
13936 			len -= sizeof(buf);
13937 	}
13938 
13939 	t4_write_reg(sc, reg, save);
13940 	t4_read_reg(sc, reg);
13941 }
13942 
13943 static void
13944 t4_dump_tcb(struct adapter *sc, int tid)
13945 {
13946 	uint32_t tcb_addr;
13947 
13948 	/* Dump TCB for the tid */
13949 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
13950 	tcb_addr += tid * TCB_SIZE;
13951 	t4_dump_mem(sc, tcb_addr, TCB_SIZE);
13952 }
13953 
13954 static void
13955 t4_dump_devlog(struct adapter *sc)
13956 {
13957 	struct devlog_params *dparams = &sc->params.devlog;
13958 	struct fw_devlog_e e;
13959 	int i, first, j, m, nentries, rc;
13960 	uint64_t ftstamp = UINT64_MAX;
13961 
13962 	if (dparams->start == 0) {
13963 		db_printf("devlog params not valid\n");
13964 		return;
13965 	}
13966 
13967 	nentries = dparams->size / sizeof(struct fw_devlog_e);
13968 	m = fwmtype_to_hwmtype(dparams->memtype);
13969 
13970 	/* Find the first entry. */
13971 	first = -1;
13972 	for (i = 0; i < nentries && !db_pager_quit; i++) {
13973 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
13974 		    sizeof(e), (void *)&e);
13975 		if (rc != 0)
13976 			break;
13977 
13978 		if (e.timestamp == 0)
13979 			break;
13980 
13981 		e.timestamp = be64toh(e.timestamp);
13982 		if (e.timestamp < ftstamp) {
13983 			ftstamp = e.timestamp;
13984 			first = i;
13985 		}
13986 	}
13987 
13988 	if (first == -1)
13989 		return;
13990 
13991 	i = first;
13992 	do {
13993 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
13994 		    sizeof(e), (void *)&e);
13995 		if (rc != 0)
13996 			return;
13997 
13998 		if (e.timestamp == 0)
13999 			return;
14000 
14001 		e.timestamp = be64toh(e.timestamp);
14002 		e.seqno = be32toh(e.seqno);
14003 		for (j = 0; j < 8; j++)
14004 			e.params[j] = be32toh(e.params[j]);
14005 
14006 		db_printf("%10d  %15ju  %8s  %8s  ",
14007 		    e.seqno, e.timestamp,
14008 		    (e.level < nitems(devlog_level_strings) ?
14009 			devlog_level_strings[e.level] : "UNKNOWN"),
14010 		    (e.facility < nitems(devlog_facility_strings) ?
14011 			devlog_facility_strings[e.facility] : "UNKNOWN"));
14012 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
14013 		    e.params[3], e.params[4], e.params[5], e.params[6],
14014 		    e.params[7]);
14015 
14016 		if (++i == nentries)
14017 			i = 0;
14018 	} while (i != first && !db_pager_quit);
14019 }
14020 
14021 static DB_DEFINE_TABLE(show, t4, show_t4);
14022 
14023 DB_TABLE_COMMAND_FLAGS(show_t4, devlog, db_show_devlog, CS_OWN)
14024 {
14025 	device_t dev;
14026 	int t;
14027 	bool valid;
14028 
14029 	valid = false;
14030 	t = db_read_token();
14031 	if (t == tIDENT) {
14032 		dev = device_lookup_by_name(db_tok_string);
14033 		valid = true;
14034 	}
14035 	db_skip_to_eol();
14036 	if (!valid) {
14037 		db_printf("usage: show t4 devlog <nexus>\n");
14038 		return;
14039 	}
14040 
14041 	if (dev == NULL) {
14042 		db_printf("device not found\n");
14043 		return;
14044 	}
14045 
14046 	t4_dump_devlog(device_get_softc(dev));
14047 }
14048 
14049 DB_TABLE_COMMAND_FLAGS(show_t4, tcb, db_show_t4tcb, CS_OWN)
14050 {
14051 	device_t dev;
14052 	int radix, tid, t;
14053 	bool valid;
14054 
14055 	valid = false;
14056 	radix = db_radix;
14057 	db_radix = 10;
14058 	t = db_read_token();
14059 	if (t == tIDENT) {
14060 		dev = device_lookup_by_name(db_tok_string);
14061 		t = db_read_token();
14062 		if (t == tNUMBER) {
14063 			tid = db_tok_number;
14064 			valid = true;
14065 		}
14066 	}
14067 	db_radix = radix;
14068 	db_skip_to_eol();
14069 	if (!valid) {
14070 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
14071 		return;
14072 	}
14073 
14074 	if (dev == NULL) {
14075 		db_printf("device not found\n");
14076 		return;
14077 	}
14078 	if (tid < 0) {
14079 		db_printf("invalid tid\n");
14080 		return;
14081 	}
14082 
14083 	t4_dump_tcb(device_get_softc(dev), tid);
14084 }
14085 
14086 DB_TABLE_COMMAND_FLAGS(show_t4, memdump, db_show_memdump, CS_OWN)
14087 {
14088 	device_t dev;
14089 	int radix, t;
14090 	bool valid;
14091 
14092 	valid = false;
14093 	radix = db_radix;
14094 	db_radix = 10;
14095 	t = db_read_token();
14096 	if (t == tIDENT) {
14097 		dev = device_lookup_by_name(db_tok_string);
14098 		t = db_read_token();
14099 		if (t == tNUMBER) {
14100 			addr = db_tok_number;
14101 			t = db_read_token();
14102 			if (t == tNUMBER) {
14103 				count = db_tok_number;
14104 				valid = true;
14105 			}
14106 		}
14107 	}
14108 	db_radix = radix;
14109 	db_skip_to_eol();
14110 	if (!valid) {
14111 		db_printf("usage: show t4 memdump <nexus> <addr> <len>\n");
14112 		return;
14113 	}
14114 
14115 	if (dev == NULL) {
14116 		db_printf("device not found\n");
14117 		return;
14118 	}
14119 	if (addr < 0) {
14120 		db_printf("invalid address\n");
14121 		return;
14122 	}
14123 	if (count <= 0) {
14124 		db_printf("invalid length\n");
14125 		return;
14126 	}
14127 
14128 	t4_dump_mem(device_get_softc(dev), addr, count);
14129 }
14130 #endif
14131 
14132 static eventhandler_tag vxlan_start_evtag;
14133 static eventhandler_tag vxlan_stop_evtag;
14134 
14135 struct vxlan_evargs {
14136 	if_t ifp;
14137 	uint16_t port;
14138 };
14139 
14140 static void
14141 enable_vxlan_rx(struct adapter *sc)
14142 {
14143 	int i, rc;
14144 	struct port_info *pi;
14145 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
14146 
14147 	ASSERT_SYNCHRONIZED_OP(sc);
14148 
14149 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
14150 	    F_VXLAN_EN);
14151 	for_each_port(sc, i) {
14152 		pi = sc->port[i];
14153 		if (pi->vxlan_tcam_entry == true)
14154 			continue;
14155 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
14156 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
14157 		    true);
14158 		if (rc < 0) {
14159 			rc = -rc;
14160 			CH_ERR(&pi->vi[0],
14161 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
14162 		} else {
14163 			MPASS(rc == sc->rawf_base + pi->port_id);
14164 			pi->vxlan_tcam_entry = true;
14165 		}
14166 	}
14167 }
14168 
14169 static void
14170 t4_vxlan_start(struct adapter *sc, void *arg)
14171 {
14172 	struct vxlan_evargs *v = arg;
14173 
14174 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
14175 		return;
14176 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
14177 		return;
14178 
14179 	if (sc->vxlan_refcount == 0) {
14180 		sc->vxlan_port = v->port;
14181 		sc->vxlan_refcount = 1;
14182 		if (!hw_off_limits(sc))
14183 			enable_vxlan_rx(sc);
14184 	} else if (sc->vxlan_port == v->port) {
14185 		sc->vxlan_refcount++;
14186 	} else {
14187 		CH_ERR(sc, "VXLAN already configured on port  %d; "
14188 		    "ignoring attempt to configure it on port %d\n",
14189 		    sc->vxlan_port, v->port);
14190 	}
14191 	end_synchronized_op(sc, 0);
14192 }
14193 
14194 static void
14195 t4_vxlan_stop(struct adapter *sc, void *arg)
14196 {
14197 	struct vxlan_evargs *v = arg;
14198 
14199 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
14200 		return;
14201 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
14202 		return;
14203 
14204 	/*
14205 	 * VXLANs may have been configured before the driver was loaded so we
14206 	 * may see more stops than starts.  This is not handled cleanly but at
14207 	 * least we keep the refcount sane.
14208 	 */
14209 	if (sc->vxlan_port != v->port)
14210 		goto done;
14211 	if (sc->vxlan_refcount == 0) {
14212 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
14213 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
14214 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
14215 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
14216 done:
14217 	end_synchronized_op(sc, 0);
14218 }
14219 
14220 static void
14221 t4_vxlan_start_handler(void *arg __unused, if_t ifp,
14222     sa_family_t family, u_int port)
14223 {
14224 	struct vxlan_evargs v;
14225 
14226 	MPASS(family == AF_INET || family == AF_INET6);
14227 	v.ifp = ifp;
14228 	v.port = port;
14229 
14230 	t4_iterate(t4_vxlan_start, &v);
14231 }
14232 
14233 static void
14234 t4_vxlan_stop_handler(void *arg __unused, if_t ifp, sa_family_t family,
14235     u_int port)
14236 {
14237 	struct vxlan_evargs v;
14238 
14239 	MPASS(family == AF_INET || family == AF_INET6);
14240 	v.ifp = ifp;
14241 	v.port = port;
14242 
14243 	t4_iterate(t4_vxlan_stop, &v);
14244 }
14245 
14246 
14247 static struct sx mlu;	/* mod load unload */
14248 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
14249 
14250 static int
14251 mod_event(module_t mod, int cmd, void *arg)
14252 {
14253 	int rc = 0;
14254 	static int loaded = 0;
14255 
14256 	switch (cmd) {
14257 	case MOD_LOAD:
14258 		sx_xlock(&mlu);
14259 		if (loaded++ == 0) {
14260 			t4_sge_modload();
14261 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
14262 			    t4_filter_rpl, CPL_COOKIE_FILTER);
14263 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
14264 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
14265 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
14266 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
14267 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
14268 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
14269 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
14270 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
14271 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
14272 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
14273 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
14274 			    do_smt_write_rpl);
14275 			sx_init(&t4_list_lock, "T4/T5 adapters");
14276 			SLIST_INIT(&t4_list);
14277 			callout_init(&fatal_callout, 1);
14278 #ifdef TCP_OFFLOAD
14279 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
14280 #endif
14281 #ifdef INET6
14282 			t4_clip_modload();
14283 #endif
14284 #ifdef KERN_TLS
14285 			t6_ktls_modload();
14286 			t7_ktls_modload();
14287 #endif
14288 			t4_tracer_modload();
14289 			tweak_tunables();
14290 			vxlan_start_evtag =
14291 			    EVENTHANDLER_REGISTER(vxlan_start,
14292 				t4_vxlan_start_handler, NULL,
14293 				EVENTHANDLER_PRI_ANY);
14294 			vxlan_stop_evtag =
14295 			    EVENTHANDLER_REGISTER(vxlan_stop,
14296 				t4_vxlan_stop_handler, NULL,
14297 				EVENTHANDLER_PRI_ANY);
14298 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
14299 			    taskqueue_thread_enqueue, &reset_tq);
14300 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
14301 			    "t4_rst_thr");
14302 		}
14303 		sx_xunlock(&mlu);
14304 		break;
14305 
14306 	case MOD_UNLOAD:
14307 		sx_xlock(&mlu);
14308 		if (--loaded == 0) {
14309 #ifdef TCP_OFFLOAD
14310 			int i;
14311 #endif
14312 			int tries;
14313 
14314 			taskqueue_free(reset_tq);
14315 
14316 			tries = 0;
14317 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
14318 				uprintf("%ju clusters with custom free routine "
14319 				    "still is use.\n", t4_sge_extfree_refs());
14320 				pause("t4unload", 2 * hz);
14321 			}
14322 
14323 			sx_slock(&t4_list_lock);
14324 			if (!SLIST_EMPTY(&t4_list)) {
14325 				rc = EBUSY;
14326 				sx_sunlock(&t4_list_lock);
14327 				goto done_unload;
14328 			}
14329 #ifdef TCP_OFFLOAD
14330 			sx_slock(&t4_uld_list_lock);
14331 			for (i = 0; i <= ULD_MAX; i++) {
14332 				if (t4_uld_list[i] != NULL) {
14333 					rc = EBUSY;
14334 					sx_sunlock(&t4_uld_list_lock);
14335 					sx_sunlock(&t4_list_lock);
14336 					goto done_unload;
14337 				}
14338 			}
14339 			sx_sunlock(&t4_uld_list_lock);
14340 #endif
14341 			sx_sunlock(&t4_list_lock);
14342 
14343 			if (t4_sge_extfree_refs() == 0) {
14344 				EVENTHANDLER_DEREGISTER(vxlan_start,
14345 				    vxlan_start_evtag);
14346 				EVENTHANDLER_DEREGISTER(vxlan_stop,
14347 				    vxlan_stop_evtag);
14348 				t4_tracer_modunload();
14349 #ifdef KERN_TLS
14350 				t7_ktls_modunload();
14351 				t6_ktls_modunload();
14352 #endif
14353 #ifdef INET6
14354 				t4_clip_modunload();
14355 #endif
14356 #ifdef TCP_OFFLOAD
14357 				sx_destroy(&t4_uld_list_lock);
14358 #endif
14359 				sx_destroy(&t4_list_lock);
14360 				t4_sge_modunload();
14361 				loaded = 0;
14362 			} else {
14363 				rc = EBUSY;
14364 				loaded++;	/* undo earlier decrement */
14365 			}
14366 		}
14367 done_unload:
14368 		sx_xunlock(&mlu);
14369 		break;
14370 	}
14371 
14372 	return (rc);
14373 }
14374 
14375 DRIVER_MODULE(t4nex, pci, t4_driver, mod_event, 0);
14376 MODULE_VERSION(t4nex, 1);
14377 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
14378 #ifdef DEV_NETMAP
14379 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
14380 #endif /* DEV_NETMAP */
14381 
14382 DRIVER_MODULE(t5nex, pci, t5_driver, mod_event, 0);
14383 MODULE_VERSION(t5nex, 1);
14384 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
14385 #ifdef DEV_NETMAP
14386 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
14387 #endif /* DEV_NETMAP */
14388 
14389 DRIVER_MODULE(t6nex, pci, t6_driver, mod_event, 0);
14390 MODULE_VERSION(t6nex, 1);
14391 MODULE_DEPEND(t6nex, crypto, 1, 1, 1);
14392 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
14393 #ifdef DEV_NETMAP
14394 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
14395 #endif /* DEV_NETMAP */
14396 
14397 DRIVER_MODULE(chnex, pci, ch_driver, mod_event, 0);
14398 MODULE_VERSION(chnex, 1);
14399 MODULE_DEPEND(chnex, crypto, 1, 1, 1);
14400 MODULE_DEPEND(chnex, firmware, 1, 1, 1);
14401 #ifdef DEV_NETMAP
14402 MODULE_DEPEND(chnex, netmap, 1, 1, 1);
14403 #endif /* DEV_NETMAP */
14404 
14405 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, 0, 0);
14406 MODULE_VERSION(cxgbe, 1);
14407 
14408 DRIVER_MODULE(cxl, t5nex, cxl_driver, 0, 0);
14409 MODULE_VERSION(cxl, 1);
14410 
14411 DRIVER_MODULE(cc, t6nex, cc_driver, 0, 0);
14412 MODULE_VERSION(cc, 1);
14413 
14414 DRIVER_MODULE(che, chnex, che_driver, 0, 0);
14415 MODULE_VERSION(che, 1);
14416 
14417 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, 0, 0);
14418 MODULE_VERSION(vcxgbe, 1);
14419 
14420 DRIVER_MODULE(vcxl, cxl, vcxl_driver, 0, 0);
14421 MODULE_VERSION(vcxl, 1);
14422 
14423 DRIVER_MODULE(vcc, cc, vcc_driver, 0, 0);
14424 MODULE_VERSION(vcc, 1);
14425 
14426 DRIVER_MODULE(vche, che, vche_driver, 0, 0);
14427 MODULE_VERSION(vche, 1);
14428