xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision e6bfd18d21b225af6a0ed67ceeaf1293b7b9eba5)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2011 Chelsio Communications, Inc.
5  * All rights reserved.
6  * Written by: Navdeep Parhar <np@FreeBSD.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include "opt_ddb.h"
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_kern_tls.h"
37 #include "opt_ratelimit.h"
38 #include "opt_rss.h"
39 
40 #include <sys/param.h>
41 #include <sys/conf.h>
42 #include <sys/priv.h>
43 #include <sys/kernel.h>
44 #include <sys/bus.h>
45 #include <sys/eventhandler.h>
46 #include <sys/module.h>
47 #include <sys/malloc.h>
48 #include <sys/queue.h>
49 #include <sys/taskqueue.h>
50 #include <sys/pciio.h>
51 #include <dev/pci/pcireg.h>
52 #include <dev/pci/pcivar.h>
53 #include <dev/pci/pci_private.h>
54 #include <sys/firmware.h>
55 #include <sys/sbuf.h>
56 #include <sys/smp.h>
57 #include <sys/socket.h>
58 #include <sys/sockio.h>
59 #include <sys/sysctl.h>
60 #include <net/ethernet.h>
61 #include <net/if.h>
62 #include <net/if_types.h>
63 #include <net/if_dl.h>
64 #include <net/if_vlan_var.h>
65 #ifdef RSS
66 #include <net/rss_config.h>
67 #endif
68 #include <netinet/in.h>
69 #include <netinet/ip.h>
70 #ifdef KERN_TLS
71 #include <netinet/tcp_seq.h>
72 #endif
73 #if defined(__i386__) || defined(__amd64__)
74 #include <machine/md_var.h>
75 #include <machine/cputypes.h>
76 #include <vm/vm.h>
77 #include <vm/pmap.h>
78 #endif
79 #ifdef DDB
80 #include <ddb/ddb.h>
81 #include <ddb/db_lex.h>
82 #endif
83 
84 #include "common/common.h"
85 #include "common/t4_msg.h"
86 #include "common/t4_regs.h"
87 #include "common/t4_regs_values.h"
88 #include "cudbg/cudbg.h"
89 #include "t4_clip.h"
90 #include "t4_ioctl.h"
91 #include "t4_l2t.h"
92 #include "t4_mp_ring.h"
93 #include "t4_if.h"
94 #include "t4_smt.h"
95 
96 /* T4 bus driver interface */
97 static int t4_probe(device_t);
98 static int t4_attach(device_t);
99 static int t4_detach(device_t);
100 static int t4_child_location(device_t, device_t, struct sbuf *);
101 static int t4_ready(device_t);
102 static int t4_read_port_device(device_t, int, device_t *);
103 static int t4_suspend(device_t);
104 static int t4_resume(device_t);
105 static int t4_reset_prepare(device_t, device_t);
106 static int t4_reset_post(device_t, device_t);
107 static device_method_t t4_methods[] = {
108 	DEVMETHOD(device_probe,		t4_probe),
109 	DEVMETHOD(device_attach,	t4_attach),
110 	DEVMETHOD(device_detach,	t4_detach),
111 	DEVMETHOD(device_suspend,	t4_suspend),
112 	DEVMETHOD(device_resume,	t4_resume),
113 
114 	DEVMETHOD(bus_child_location,	t4_child_location),
115 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
116 	DEVMETHOD(bus_reset_post,	t4_reset_post),
117 
118 	DEVMETHOD(t4_is_main_ready,	t4_ready),
119 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
120 
121 	DEVMETHOD_END
122 };
123 static driver_t t4_driver = {
124 	"t4nex",
125 	t4_methods,
126 	sizeof(struct adapter)
127 };
128 
129 
130 /* T4 port (cxgbe) interface */
131 static int cxgbe_probe(device_t);
132 static int cxgbe_attach(device_t);
133 static int cxgbe_detach(device_t);
134 device_method_t cxgbe_methods[] = {
135 	DEVMETHOD(device_probe,		cxgbe_probe),
136 	DEVMETHOD(device_attach,	cxgbe_attach),
137 	DEVMETHOD(device_detach,	cxgbe_detach),
138 	{ 0, 0 }
139 };
140 static driver_t cxgbe_driver = {
141 	"cxgbe",
142 	cxgbe_methods,
143 	sizeof(struct port_info)
144 };
145 
146 /* T4 VI (vcxgbe) interface */
147 static int vcxgbe_probe(device_t);
148 static int vcxgbe_attach(device_t);
149 static int vcxgbe_detach(device_t);
150 static device_method_t vcxgbe_methods[] = {
151 	DEVMETHOD(device_probe,		vcxgbe_probe),
152 	DEVMETHOD(device_attach,	vcxgbe_attach),
153 	DEVMETHOD(device_detach,	vcxgbe_detach),
154 	{ 0, 0 }
155 };
156 static driver_t vcxgbe_driver = {
157 	"vcxgbe",
158 	vcxgbe_methods,
159 	sizeof(struct vi_info)
160 };
161 
162 static d_ioctl_t t4_ioctl;
163 
164 static struct cdevsw t4_cdevsw = {
165        .d_version = D_VERSION,
166        .d_ioctl = t4_ioctl,
167        .d_name = "t4nex",
168 };
169 
170 /* T5 bus driver interface */
171 static int t5_probe(device_t);
172 static device_method_t t5_methods[] = {
173 	DEVMETHOD(device_probe,		t5_probe),
174 	DEVMETHOD(device_attach,	t4_attach),
175 	DEVMETHOD(device_detach,	t4_detach),
176 	DEVMETHOD(device_suspend,	t4_suspend),
177 	DEVMETHOD(device_resume,	t4_resume),
178 
179 	DEVMETHOD(bus_child_location,	t4_child_location),
180 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
181 	DEVMETHOD(bus_reset_post,	t4_reset_post),
182 
183 	DEVMETHOD(t4_is_main_ready,	t4_ready),
184 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
185 
186 	DEVMETHOD_END
187 };
188 static driver_t t5_driver = {
189 	"t5nex",
190 	t5_methods,
191 	sizeof(struct adapter)
192 };
193 
194 
195 /* T5 port (cxl) interface */
196 static driver_t cxl_driver = {
197 	"cxl",
198 	cxgbe_methods,
199 	sizeof(struct port_info)
200 };
201 
202 /* T5 VI (vcxl) interface */
203 static driver_t vcxl_driver = {
204 	"vcxl",
205 	vcxgbe_methods,
206 	sizeof(struct vi_info)
207 };
208 
209 /* T6 bus driver interface */
210 static int t6_probe(device_t);
211 static device_method_t t6_methods[] = {
212 	DEVMETHOD(device_probe,		t6_probe),
213 	DEVMETHOD(device_attach,	t4_attach),
214 	DEVMETHOD(device_detach,	t4_detach),
215 	DEVMETHOD(device_suspend,	t4_suspend),
216 	DEVMETHOD(device_resume,	t4_resume),
217 
218 	DEVMETHOD(bus_child_location,	t4_child_location),
219 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
220 	DEVMETHOD(bus_reset_post,	t4_reset_post),
221 
222 	DEVMETHOD(t4_is_main_ready,	t4_ready),
223 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
224 
225 	DEVMETHOD_END
226 };
227 static driver_t t6_driver = {
228 	"t6nex",
229 	t6_methods,
230 	sizeof(struct adapter)
231 };
232 
233 
234 /* T6 port (cc) interface */
235 static driver_t cc_driver = {
236 	"cc",
237 	cxgbe_methods,
238 	sizeof(struct port_info)
239 };
240 
241 /* T6 VI (vcc) interface */
242 static driver_t vcc_driver = {
243 	"vcc",
244 	vcxgbe_methods,
245 	sizeof(struct vi_info)
246 };
247 
248 /* ifnet interface */
249 static void cxgbe_init(void *);
250 static int cxgbe_ioctl(if_t, unsigned long, caddr_t);
251 static int cxgbe_transmit(if_t, struct mbuf *);
252 static void cxgbe_qflush(if_t);
253 #if defined(KERN_TLS) || defined(RATELIMIT)
254 static int cxgbe_snd_tag_alloc(if_t, union if_snd_tag_alloc_params *,
255     struct m_snd_tag **);
256 #endif
257 
258 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
259 
260 /*
261  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
262  * then ADAPTER_LOCK, then t4_uld_list_lock.
263  */
264 static struct sx t4_list_lock;
265 SLIST_HEAD(, adapter) t4_list;
266 #ifdef TCP_OFFLOAD
267 static struct sx t4_uld_list_lock;
268 SLIST_HEAD(, uld_info) t4_uld_list;
269 #endif
270 
271 /*
272  * Tunables.  See tweak_tunables() too.
273  *
274  * Each tunable is set to a default value here if it's known at compile-time.
275  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
276  * provide a reasonable default (upto n) when the driver is loaded.
277  *
278  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
279  * T5 are under hw.cxl.
280  */
281 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
282     "cxgbe(4) parameters");
283 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
284     "cxgbe(4) T5+ parameters");
285 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
286     "cxgbe(4) TOE parameters");
287 
288 /*
289  * Number of queues for tx and rx, NIC and offload.
290  */
291 #define NTXQ 16
292 int t4_ntxq = -NTXQ;
293 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
294     "Number of TX queues per port");
295 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);	/* Old name, undocumented */
296 
297 #define NRXQ 8
298 int t4_nrxq = -NRXQ;
299 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
300     "Number of RX queues per port");
301 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);	/* Old name, undocumented */
302 
303 #define NTXQ_VI 1
304 static int t4_ntxq_vi = -NTXQ_VI;
305 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
306     "Number of TX queues per VI");
307 
308 #define NRXQ_VI 1
309 static int t4_nrxq_vi = -NRXQ_VI;
310 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
311     "Number of RX queues per VI");
312 
313 static int t4_rsrv_noflowq = 0;
314 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
315     0, "Reserve TX queue 0 of each VI for non-flowid packets");
316 
317 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
318 #define NOFLDTXQ 8
319 static int t4_nofldtxq = -NOFLDTXQ;
320 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
321     "Number of offload TX queues per port");
322 
323 #define NOFLDRXQ 2
324 static int t4_nofldrxq = -NOFLDRXQ;
325 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
326     "Number of offload RX queues per port");
327 
328 #define NOFLDTXQ_VI 1
329 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
330 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
331     "Number of offload TX queues per VI");
332 
333 #define NOFLDRXQ_VI 1
334 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
335 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
336     "Number of offload RX queues per VI");
337 
338 #define TMR_IDX_OFLD 1
339 int t4_tmr_idx_ofld = TMR_IDX_OFLD;
340 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
341     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
342 
343 #define PKTC_IDX_OFLD (-1)
344 int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
345 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
346     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
347 
348 /* 0 means chip/fw default, non-zero number is value in microseconds */
349 static u_long t4_toe_keepalive_idle = 0;
350 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
351     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
352 
353 /* 0 means chip/fw default, non-zero number is value in microseconds */
354 static u_long t4_toe_keepalive_interval = 0;
355 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
356     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
357 
358 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
359 static int t4_toe_keepalive_count = 0;
360 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
361     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
362 
363 /* 0 means chip/fw default, non-zero number is value in microseconds */
364 static u_long t4_toe_rexmt_min = 0;
365 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
366     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
367 
368 /* 0 means chip/fw default, non-zero number is value in microseconds */
369 static u_long t4_toe_rexmt_max = 0;
370 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
371     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
372 
373 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
374 static int t4_toe_rexmt_count = 0;
375 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
376     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
377 
378 /* -1 means chip/fw default, other values are raw backoff values to use */
379 static int t4_toe_rexmt_backoff[16] = {
380 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
381 };
382 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
383     CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
384     "cxgbe(4) TOE retransmit backoff values");
385 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
386     &t4_toe_rexmt_backoff[0], 0, "");
387 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
388     &t4_toe_rexmt_backoff[1], 0, "");
389 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
390     &t4_toe_rexmt_backoff[2], 0, "");
391 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
392     &t4_toe_rexmt_backoff[3], 0, "");
393 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
394     &t4_toe_rexmt_backoff[4], 0, "");
395 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
396     &t4_toe_rexmt_backoff[5], 0, "");
397 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
398     &t4_toe_rexmt_backoff[6], 0, "");
399 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
400     &t4_toe_rexmt_backoff[7], 0, "");
401 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
402     &t4_toe_rexmt_backoff[8], 0, "");
403 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
404     &t4_toe_rexmt_backoff[9], 0, "");
405 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
406     &t4_toe_rexmt_backoff[10], 0, "");
407 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
408     &t4_toe_rexmt_backoff[11], 0, "");
409 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
410     &t4_toe_rexmt_backoff[12], 0, "");
411 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
412     &t4_toe_rexmt_backoff[13], 0, "");
413 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
414     &t4_toe_rexmt_backoff[14], 0, "");
415 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
416     &t4_toe_rexmt_backoff[15], 0, "");
417 #endif
418 
419 #ifdef DEV_NETMAP
420 #define NN_MAIN_VI	(1 << 0)	/* Native netmap on the main VI */
421 #define NN_EXTRA_VI	(1 << 1)	/* Native netmap on the extra VI(s) */
422 static int t4_native_netmap = NN_EXTRA_VI;
423 SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
424     0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
425 
426 #define NNMTXQ 8
427 static int t4_nnmtxq = -NNMTXQ;
428 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
429     "Number of netmap TX queues");
430 
431 #define NNMRXQ 8
432 static int t4_nnmrxq = -NNMRXQ;
433 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
434     "Number of netmap RX queues");
435 
436 #define NNMTXQ_VI 2
437 static int t4_nnmtxq_vi = -NNMTXQ_VI;
438 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
439     "Number of netmap TX queues per VI");
440 
441 #define NNMRXQ_VI 2
442 static int t4_nnmrxq_vi = -NNMRXQ_VI;
443 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
444     "Number of netmap RX queues per VI");
445 #endif
446 
447 /*
448  * Holdoff parameters for ports.
449  */
450 #define TMR_IDX 1
451 int t4_tmr_idx = TMR_IDX;
452 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
453     0, "Holdoff timer index");
454 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);	/* Old name */
455 
456 #define PKTC_IDX (-1)
457 int t4_pktc_idx = PKTC_IDX;
458 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
459     0, "Holdoff packet counter index");
460 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);	/* Old name */
461 
462 /*
463  * Size (# of entries) of each tx and rx queue.
464  */
465 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
466 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
467     "Number of descriptors in each TX queue");
468 
469 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
470 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
471     "Number of descriptors in each RX queue");
472 
473 /*
474  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
475  */
476 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
477 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
478     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
479 
480 /*
481  * Configuration file.  All the _CF names here are special.
482  */
483 #define DEFAULT_CF	"default"
484 #define BUILTIN_CF	"built-in"
485 #define FLASH_CF	"flash"
486 #define UWIRE_CF	"uwire"
487 #define FPGA_CF		"fpga"
488 static char t4_cfg_file[32] = DEFAULT_CF;
489 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
490     sizeof(t4_cfg_file), "Firmware configuration file");
491 
492 /*
493  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
494  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
495  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
496  *            mark or when signalled to do so, 0 to never emit PAUSE.
497  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
498  *                 negotiated settings will override rx_pause/tx_pause.
499  *                 Otherwise rx_pause/tx_pause are applied forcibly.
500  */
501 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
502 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
503     &t4_pause_settings, 0,
504     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
505 
506 /*
507  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
508  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
509  *  0 to disable FEC.
510  */
511 static int t4_fec = -1;
512 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
513     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
514 
515 /*
516  * Controls when the driver sets the FORCE_FEC bit in the L1_CFG32 that it
517  * issues to the firmware.  If the firmware doesn't support FORCE_FEC then the
518  * driver runs as if this is set to 0.
519  * -1 to set FORCE_FEC iff requested_fec != AUTO. Multiple FEC bits are okay.
520  *  0 to never set FORCE_FEC. requested_fec = AUTO means use the hint from the
521  *    transceiver. Multiple FEC bits may not be okay but will be passed on to
522  *    the firmware anyway (may result in l1cfg errors with old firmwares).
523  *  1 to always set FORCE_FEC. Multiple FEC bits are okay. requested_fec = AUTO
524  *    means set all FEC bits that are valid for the speed.
525  */
526 static int t4_force_fec = -1;
527 SYSCTL_INT(_hw_cxgbe, OID_AUTO, force_fec, CTLFLAG_RDTUN, &t4_force_fec, 0,
528     "Controls the use of FORCE_FEC bit in L1 configuration.");
529 
530 /*
531  * Link autonegotiation.
532  * -1 to run with the firmware default.
533  *  0 to disable.
534  *  1 to enable.
535  */
536 static int t4_autoneg = -1;
537 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
538     "Link autonegotiation");
539 
540 /*
541  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
542  * encouraged respectively).  '-n' is the same as 'n' except the firmware
543  * version used in the checks is read from the firmware bundled with the driver.
544  */
545 static int t4_fw_install = 1;
546 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
547     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
548 
549 /*
550  * ASIC features that will be used.  Disable the ones you don't want so that the
551  * chip resources aren't wasted on features that will not be used.
552  */
553 static int t4_nbmcaps_allowed = 0;
554 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
555     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
556 
557 static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
558 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
559     &t4_linkcaps_allowed, 0, "Default link capabilities");
560 
561 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
562     FW_CAPS_CONFIG_SWITCH_EGRESS;
563 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
564     &t4_switchcaps_allowed, 0, "Default switch capabilities");
565 
566 #ifdef RATELIMIT
567 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
568 	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
569 #else
570 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
571 	FW_CAPS_CONFIG_NIC_HASHFILTER;
572 #endif
573 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
574     &t4_niccaps_allowed, 0, "Default NIC capabilities");
575 
576 static int t4_toecaps_allowed = -1;
577 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
578     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
579 
580 static int t4_rdmacaps_allowed = -1;
581 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
582     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
583 
584 static int t4_cryptocaps_allowed = -1;
585 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
586     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
587 
588 static int t4_iscsicaps_allowed = -1;
589 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
590     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
591 
592 static int t4_fcoecaps_allowed = 0;
593 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
594     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
595 
596 static int t5_write_combine = 0;
597 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
598     0, "Use WC instead of UC for BAR2");
599 
600 static int t4_num_vis = 1;
601 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
602     "Number of VIs per port");
603 
604 /*
605  * PCIe Relaxed Ordering.
606  * -1: driver should figure out a good value.
607  * 0: disable RO.
608  * 1: enable RO.
609  * 2: leave RO alone.
610  */
611 static int pcie_relaxed_ordering = -1;
612 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
613     &pcie_relaxed_ordering, 0,
614     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
615 
616 static int t4_panic_on_fatal_err = 0;
617 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
618     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
619 
620 static int t4_reset_on_fatal_err = 0;
621 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
622     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
623 
624 static int t4_clock_gate_on_suspend = 0;
625 SYSCTL_INT(_hw_cxgbe, OID_AUTO, clock_gate_on_suspend, CTLFLAG_RWTUN,
626     &t4_clock_gate_on_suspend, 0, "gate the clock on suspend");
627 
628 static int t4_tx_vm_wr = 0;
629 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
630     "Use VM work requests to transmit packets.");
631 
632 /*
633  * Set to non-zero to enable the attack filter.  A packet that matches any of
634  * these conditions will get dropped on ingress:
635  * 1) IP && source address == destination address.
636  * 2) TCP/IP && source address is not a unicast address.
637  * 3) TCP/IP && destination address is not a unicast address.
638  * 4) IP && source address is loopback (127.x.y.z).
639  * 5) IP && destination address is loopback (127.x.y.z).
640  * 6) IPv6 && source address == destination address.
641  * 7) IPv6 && source address is not a unicast address.
642  * 8) IPv6 && source address is loopback (::1/128).
643  * 9) IPv6 && destination address is loopback (::1/128).
644  * 10) IPv6 && source address is unspecified (::/128).
645  * 11) IPv6 && destination address is unspecified (::/128).
646  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
647  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
648  */
649 static int t4_attack_filter = 0;
650 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
651     &t4_attack_filter, 0, "Drop suspicious traffic");
652 
653 static int t4_drop_ip_fragments = 0;
654 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
655     &t4_drop_ip_fragments, 0, "Drop IP fragments");
656 
657 static int t4_drop_pkts_with_l2_errors = 1;
658 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
659     &t4_drop_pkts_with_l2_errors, 0,
660     "Drop all frames with Layer 2 length or checksum errors");
661 
662 static int t4_drop_pkts_with_l3_errors = 0;
663 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
664     &t4_drop_pkts_with_l3_errors, 0,
665     "Drop all frames with IP version, length, or checksum errors");
666 
667 static int t4_drop_pkts_with_l4_errors = 0;
668 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
669     &t4_drop_pkts_with_l4_errors, 0,
670     "Drop all frames with Layer 4 length, checksum, or other errors");
671 
672 #ifdef TCP_OFFLOAD
673 /*
674  * TOE tunables.
675  */
676 static int t4_cop_managed_offloading = 0;
677 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
678     &t4_cop_managed_offloading, 0,
679     "COP (Connection Offload Policy) controls all TOE offload");
680 #endif
681 
682 #ifdef KERN_TLS
683 /*
684  * This enables KERN_TLS for all adapters if set.
685  */
686 static int t4_kern_tls = 0;
687 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
688     "Enable KERN_TLS mode for T6 adapters");
689 
690 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
691     "cxgbe(4) KERN_TLS parameters");
692 
693 static int t4_tls_inline_keys = 0;
694 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
695     &t4_tls_inline_keys, 0,
696     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
697     "in card memory.");
698 
699 static int t4_tls_combo_wrs = 0;
700 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
701     0, "Attempt to combine TCB field updates with TLS record work requests.");
702 #endif
703 
704 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
705 static int vi_mac_funcs[] = {
706 	FW_VI_FUNC_ETH,
707 	FW_VI_FUNC_OFLD,
708 	FW_VI_FUNC_IWARP,
709 	FW_VI_FUNC_OPENISCSI,
710 	FW_VI_FUNC_OPENFCOE,
711 	FW_VI_FUNC_FOISCSI,
712 	FW_VI_FUNC_FOFCOE,
713 };
714 
715 struct intrs_and_queues {
716 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
717 	uint16_t num_vis;	/* number of VIs for each port */
718 	uint16_t nirq;		/* Total # of vectors */
719 	uint16_t ntxq;		/* # of NIC txq's for each port */
720 	uint16_t nrxq;		/* # of NIC rxq's for each port */
721 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
722 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
723 	uint16_t nnmtxq;	/* # of netmap txq's */
724 	uint16_t nnmrxq;	/* # of netmap rxq's */
725 
726 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
727 	uint16_t ntxq_vi;	/* # of NIC txq's */
728 	uint16_t nrxq_vi;	/* # of NIC rxq's */
729 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
730 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
731 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
732 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
733 };
734 
735 static void setup_memwin(struct adapter *);
736 static void position_memwin(struct adapter *, int, uint32_t);
737 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
738 static int fwmtype_to_hwmtype(int);
739 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
740     uint32_t *);
741 static int fixup_devlog_params(struct adapter *);
742 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
743 static int contact_firmware(struct adapter *);
744 static int partition_resources(struct adapter *);
745 static int get_params__pre_init(struct adapter *);
746 static int set_params__pre_init(struct adapter *);
747 static int get_params__post_init(struct adapter *);
748 static int set_params__post_init(struct adapter *);
749 static void t4_set_desc(struct adapter *);
750 static bool fixed_ifmedia(struct port_info *);
751 static void build_medialist(struct port_info *);
752 static void init_link_config(struct port_info *);
753 static int fixup_link_config(struct port_info *);
754 static int apply_link_config(struct port_info *);
755 static int cxgbe_init_synchronized(struct vi_info *);
756 static int cxgbe_uninit_synchronized(struct vi_info *);
757 static int adapter_full_init(struct adapter *);
758 static void adapter_full_uninit(struct adapter *);
759 static int vi_full_init(struct vi_info *);
760 static void vi_full_uninit(struct vi_info *);
761 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
762 static void quiesce_txq(struct sge_txq *);
763 static void quiesce_wrq(struct sge_wrq *);
764 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
765 static void quiesce_vi(struct vi_info *);
766 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
767     driver_intr_t *, void *, char *);
768 static int t4_free_irq(struct adapter *, struct irq *);
769 static void t4_init_atid_table(struct adapter *);
770 static void t4_free_atid_table(struct adapter *);
771 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
772 static void vi_refresh_stats(struct vi_info *);
773 static void cxgbe_refresh_stats(struct vi_info *);
774 static void cxgbe_tick(void *);
775 static void vi_tick(void *);
776 static void cxgbe_sysctls(struct port_info *);
777 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
778 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
779 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
780 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
781 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
782 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
783 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
784 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
785 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
786 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
787 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
788 static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
789 static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
790 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
791 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
792 static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
793 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
794 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
795 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
796 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
797 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
798 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
799 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
800 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
801 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
802 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
803 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
804 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
805 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
806 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
807 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
808 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
809 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
810 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
811 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
812 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
813 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
814 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
815 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
816 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
817 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
818 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
819 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
820 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
821 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
822 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
823 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
824 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
825 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
826 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
827 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
828 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
829 #ifdef TCP_OFFLOAD
830 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
831 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
832 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
833 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
834 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
835 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
836 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
837 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
838 #endif
839 static int get_sge_context(struct adapter *, struct t4_sge_context *);
840 static int load_fw(struct adapter *, struct t4_data *);
841 static int load_cfg(struct adapter *, struct t4_data *);
842 static int load_boot(struct adapter *, struct t4_bootrom *);
843 static int load_bootcfg(struct adapter *, struct t4_data *);
844 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
845 static void free_offload_policy(struct t4_offload_policy *);
846 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
847 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
848 static int read_i2c(struct adapter *, struct t4_i2c_data *);
849 static int clear_stats(struct adapter *, u_int);
850 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
851 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
852 #ifdef TCP_OFFLOAD
853 static int toe_capability(struct vi_info *, bool);
854 static int t4_deactivate_all_uld(struct adapter *);
855 static void t4_async_event(struct adapter *);
856 #endif
857 #ifdef KERN_TLS
858 static int ktls_capability(struct adapter *, bool);
859 #endif
860 static int mod_event(module_t, int, void *);
861 static int notify_siblings(device_t, int);
862 static uint64_t vi_get_counter(if_t, ift_counter);
863 static uint64_t cxgbe_get_counter(if_t, ift_counter);
864 static void enable_vxlan_rx(struct adapter *);
865 static void reset_adapter_task(void *, int);
866 static void fatal_error_task(void *, int);
867 static void dump_devlog(struct adapter *);
868 static void dump_cim_regs(struct adapter *);
869 static void dump_cimla(struct adapter *);
870 
871 struct {
872 	uint16_t device;
873 	char *desc;
874 } t4_pciids[] = {
875 	{0xa000, "Chelsio Terminator 4 FPGA"},
876 	{0x4400, "Chelsio T440-dbg"},
877 	{0x4401, "Chelsio T420-CR"},
878 	{0x4402, "Chelsio T422-CR"},
879 	{0x4403, "Chelsio T440-CR"},
880 	{0x4404, "Chelsio T420-BCH"},
881 	{0x4405, "Chelsio T440-BCH"},
882 	{0x4406, "Chelsio T440-CH"},
883 	{0x4407, "Chelsio T420-SO"},
884 	{0x4408, "Chelsio T420-CX"},
885 	{0x4409, "Chelsio T420-BT"},
886 	{0x440a, "Chelsio T404-BT"},
887 	{0x440e, "Chelsio T440-LP-CR"},
888 }, t5_pciids[] = {
889 	{0xb000, "Chelsio Terminator 5 FPGA"},
890 	{0x5400, "Chelsio T580-dbg"},
891 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
892 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
893 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
894 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
895 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
896 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
897 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
898 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
899 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
900 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
901 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
902 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
903 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
904 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
905 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
906 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
907 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
908 
909 	/* Custom */
910 	{0x5483, "Custom T540-CR"},
911 	{0x5484, "Custom T540-BT"},
912 }, t6_pciids[] = {
913 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
914 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
915 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
916 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
917 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
918 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
919 	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
920 	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
921 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
922 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
923 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
924 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
925 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
926 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
927 	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
928 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
929 
930 	/* Custom */
931 	{0x6480, "Custom T6225-CR"},
932 	{0x6481, "Custom T62100-CR"},
933 	{0x6482, "Custom T6225-CR"},
934 	{0x6483, "Custom T62100-CR"},
935 	{0x6484, "Custom T64100-CR"},
936 	{0x6485, "Custom T6240-SO"},
937 	{0x6486, "Custom T6225-SO-CR"},
938 	{0x6487, "Custom T6225-CR"},
939 };
940 
941 #ifdef TCP_OFFLOAD
942 /*
943  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
944  * be exactly the same for both rxq and ofld_rxq.
945  */
946 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
947 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
948 #endif
949 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
950 
951 static int
952 t4_probe(device_t dev)
953 {
954 	int i;
955 	uint16_t v = pci_get_vendor(dev);
956 	uint16_t d = pci_get_device(dev);
957 	uint8_t f = pci_get_function(dev);
958 
959 	if (v != PCI_VENDOR_ID_CHELSIO)
960 		return (ENXIO);
961 
962 	/* Attach only to PF0 of the FPGA */
963 	if (d == 0xa000 && f != 0)
964 		return (ENXIO);
965 
966 	for (i = 0; i < nitems(t4_pciids); i++) {
967 		if (d == t4_pciids[i].device) {
968 			device_set_desc(dev, t4_pciids[i].desc);
969 			return (BUS_PROBE_DEFAULT);
970 		}
971 	}
972 
973 	return (ENXIO);
974 }
975 
976 static int
977 t5_probe(device_t dev)
978 {
979 	int i;
980 	uint16_t v = pci_get_vendor(dev);
981 	uint16_t d = pci_get_device(dev);
982 	uint8_t f = pci_get_function(dev);
983 
984 	if (v != PCI_VENDOR_ID_CHELSIO)
985 		return (ENXIO);
986 
987 	/* Attach only to PF0 of the FPGA */
988 	if (d == 0xb000 && f != 0)
989 		return (ENXIO);
990 
991 	for (i = 0; i < nitems(t5_pciids); i++) {
992 		if (d == t5_pciids[i].device) {
993 			device_set_desc(dev, t5_pciids[i].desc);
994 			return (BUS_PROBE_DEFAULT);
995 		}
996 	}
997 
998 	return (ENXIO);
999 }
1000 
1001 static int
1002 t6_probe(device_t dev)
1003 {
1004 	int i;
1005 	uint16_t v = pci_get_vendor(dev);
1006 	uint16_t d = pci_get_device(dev);
1007 
1008 	if (v != PCI_VENDOR_ID_CHELSIO)
1009 		return (ENXIO);
1010 
1011 	for (i = 0; i < nitems(t6_pciids); i++) {
1012 		if (d == t6_pciids[i].device) {
1013 			device_set_desc(dev, t6_pciids[i].desc);
1014 			return (BUS_PROBE_DEFAULT);
1015 		}
1016 	}
1017 
1018 	return (ENXIO);
1019 }
1020 
1021 static void
1022 t5_attribute_workaround(device_t dev)
1023 {
1024 	device_t root_port;
1025 	uint32_t v;
1026 
1027 	/*
1028 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1029 	 * Ordering attributes when replying to a TLP from a Root
1030 	 * Port.  As a workaround, find the parent Root Port and
1031 	 * disable No Snoop and Relaxed Ordering.  Note that this
1032 	 * affects all devices under this root port.
1033 	 */
1034 	root_port = pci_find_pcie_root_port(dev);
1035 	if (root_port == NULL) {
1036 		device_printf(dev, "Unable to find parent root port\n");
1037 		return;
1038 	}
1039 
1040 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1041 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1042 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1043 	    0)
1044 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1045 		    device_get_nameunit(root_port));
1046 }
1047 
1048 static const struct devnames devnames[] = {
1049 	{
1050 		.nexus_name = "t4nex",
1051 		.ifnet_name = "cxgbe",
1052 		.vi_ifnet_name = "vcxgbe",
1053 		.pf03_drv_name = "t4iov",
1054 		.vf_nexus_name = "t4vf",
1055 		.vf_ifnet_name = "cxgbev"
1056 	}, {
1057 		.nexus_name = "t5nex",
1058 		.ifnet_name = "cxl",
1059 		.vi_ifnet_name = "vcxl",
1060 		.pf03_drv_name = "t5iov",
1061 		.vf_nexus_name = "t5vf",
1062 		.vf_ifnet_name = "cxlv"
1063 	}, {
1064 		.nexus_name = "t6nex",
1065 		.ifnet_name = "cc",
1066 		.vi_ifnet_name = "vcc",
1067 		.pf03_drv_name = "t6iov",
1068 		.vf_nexus_name = "t6vf",
1069 		.vf_ifnet_name = "ccv"
1070 	}
1071 };
1072 
1073 void
1074 t4_init_devnames(struct adapter *sc)
1075 {
1076 	int id;
1077 
1078 	id = chip_id(sc);
1079 	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1080 		sc->names = &devnames[id - CHELSIO_T4];
1081 	else {
1082 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1083 		sc->names = NULL;
1084 	}
1085 }
1086 
1087 static int
1088 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1089 {
1090 	const char *parent, *name;
1091 	long value;
1092 	int line, unit;
1093 
1094 	line = 0;
1095 	parent = device_get_nameunit(sc->dev);
1096 	name = sc->names->ifnet_name;
1097 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1098 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1099 		    value == pi->port_id)
1100 			return (unit);
1101 	}
1102 	return (-1);
1103 }
1104 
1105 static void
1106 t4_calibration(void *arg)
1107 {
1108 	struct adapter *sc;
1109 	struct clock_sync *cur, *nex;
1110 	uint64_t hw;
1111 	sbintime_t sbt;
1112 	int next_up;
1113 
1114 	sc = (struct adapter *)arg;
1115 
1116 	KASSERT((hw_off_limits(sc) == 0), ("hw_off_limits at t4_calibration"));
1117 	hw = t4_read_reg64(sc, A_SGE_TIMESTAMP_LO);
1118 	sbt = sbinuptime();
1119 
1120 	cur = &sc->cal_info[sc->cal_current];
1121 	next_up = (sc->cal_current + 1) % CNT_CAL_INFO;
1122 	nex = &sc->cal_info[next_up];
1123 	if (__predict_false(sc->cal_count == 0)) {
1124 		/* First time in, just get the values in */
1125 		cur->hw_cur = hw;
1126 		cur->sbt_cur = sbt;
1127 		sc->cal_count++;
1128 		goto done;
1129 	}
1130 
1131 	if (cur->hw_cur == hw) {
1132 		/* The clock is not advancing? */
1133 		sc->cal_count = 0;
1134 		atomic_store_rel_int(&cur->gen, 0);
1135 		goto done;
1136 	}
1137 
1138 	seqc_write_begin(&nex->gen);
1139 	nex->hw_prev = cur->hw_cur;
1140 	nex->sbt_prev = cur->sbt_cur;
1141 	nex->hw_cur = hw;
1142 	nex->sbt_cur = sbt;
1143 	seqc_write_end(&nex->gen);
1144 	sc->cal_current = next_up;
1145 done:
1146 	callout_reset_sbt_curcpu(&sc->cal_callout, SBT_1S, 0, t4_calibration,
1147 	    sc, C_DIRECT_EXEC);
1148 }
1149 
1150 static void
1151 t4_calibration_start(struct adapter *sc)
1152 {
1153 	/*
1154 	 * Here if we have not done a calibration
1155 	 * then do so otherwise start the appropriate
1156 	 * timer.
1157 	 */
1158 	int i;
1159 
1160 	for (i = 0; i < CNT_CAL_INFO; i++) {
1161 		sc->cal_info[i].gen = 0;
1162 	}
1163 	sc->cal_current = 0;
1164 	sc->cal_count = 0;
1165 	sc->cal_gen = 0;
1166 	t4_calibration(sc);
1167 }
1168 
1169 static int
1170 t4_attach(device_t dev)
1171 {
1172 	struct adapter *sc;
1173 	int rc = 0, i, j, rqidx, tqidx, nports;
1174 	struct make_dev_args mda;
1175 	struct intrs_and_queues iaq;
1176 	struct sge *s;
1177 	uint32_t *buf;
1178 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1179 	int ofld_tqidx;
1180 #endif
1181 #ifdef TCP_OFFLOAD
1182 	int ofld_rqidx;
1183 #endif
1184 #ifdef DEV_NETMAP
1185 	int nm_rqidx, nm_tqidx;
1186 #endif
1187 	int num_vis;
1188 
1189 	sc = device_get_softc(dev);
1190 	sc->dev = dev;
1191 	sysctl_ctx_init(&sc->ctx);
1192 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1193 
1194 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1195 		t5_attribute_workaround(dev);
1196 	pci_enable_busmaster(dev);
1197 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1198 		uint32_t v;
1199 
1200 		pci_set_max_read_req(dev, 4096);
1201 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1202 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1203 		if (pcie_relaxed_ordering == 0 &&
1204 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1205 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1206 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1207 		} else if (pcie_relaxed_ordering == 1 &&
1208 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1209 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1210 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1211 		}
1212 	}
1213 
1214 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1215 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1216 	sc->traceq = -1;
1217 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1218 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1219 	    device_get_nameunit(dev));
1220 
1221 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1222 	    device_get_nameunit(dev));
1223 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1224 	t4_add_adapter(sc);
1225 
1226 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1227 	TAILQ_INIT(&sc->sfl);
1228 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1229 
1230 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1231 
1232 	sc->policy = NULL;
1233 	rw_init(&sc->policy_lock, "connection offload policy");
1234 
1235 	callout_init(&sc->ktls_tick, 1);
1236 
1237 	callout_init(&sc->cal_callout, 1);
1238 
1239 	refcount_init(&sc->vxlan_refcount, 0);
1240 
1241 	TASK_INIT(&sc->reset_task, 0, reset_adapter_task, sc);
1242 	TASK_INIT(&sc->fatal_error_task, 0, fatal_error_task, sc);
1243 
1244 	sc->ctrlq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1245 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1246 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1247 	sc->fwq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1248 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1249 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1250 
1251 	rc = t4_map_bars_0_and_4(sc);
1252 	if (rc != 0)
1253 		goto done; /* error message displayed already */
1254 
1255 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1256 
1257 	/* Prepare the adapter for operation. */
1258 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1259 	rc = -t4_prep_adapter(sc, buf);
1260 	free(buf, M_CXGBE);
1261 	if (rc != 0) {
1262 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1263 		goto done;
1264 	}
1265 
1266 	/*
1267 	 * This is the real PF# to which we're attaching.  Works from within PCI
1268 	 * passthrough environments too, where pci_get_function() could return a
1269 	 * different PF# depending on the passthrough configuration.  We need to
1270 	 * use the real PF# in all our communication with the firmware.
1271 	 */
1272 	j = t4_read_reg(sc, A_PL_WHOAMI);
1273 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1274 	sc->mbox = sc->pf;
1275 
1276 	t4_init_devnames(sc);
1277 	if (sc->names == NULL) {
1278 		rc = ENOTSUP;
1279 		goto done; /* error message displayed already */
1280 	}
1281 
1282 	/*
1283 	 * Do this really early, with the memory windows set up even before the
1284 	 * character device.  The userland tool's register i/o and mem read
1285 	 * will work even in "recovery mode".
1286 	 */
1287 	setup_memwin(sc);
1288 	if (t4_init_devlog_params(sc, 0) == 0)
1289 		fixup_devlog_params(sc);
1290 	make_dev_args_init(&mda);
1291 	mda.mda_devsw = &t4_cdevsw;
1292 	mda.mda_uid = UID_ROOT;
1293 	mda.mda_gid = GID_WHEEL;
1294 	mda.mda_mode = 0600;
1295 	mda.mda_si_drv1 = sc;
1296 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1297 	if (rc != 0)
1298 		device_printf(dev, "failed to create nexus char device: %d.\n",
1299 		    rc);
1300 
1301 	/* Go no further if recovery mode has been requested. */
1302 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1303 		device_printf(dev, "recovery mode.\n");
1304 		goto done;
1305 	}
1306 
1307 #if defined(__i386__)
1308 	if ((cpu_feature & CPUID_CX8) == 0) {
1309 		device_printf(dev, "64 bit atomics not available.\n");
1310 		rc = ENOTSUP;
1311 		goto done;
1312 	}
1313 #endif
1314 
1315 	/* Contact the firmware and try to become the master driver. */
1316 	rc = contact_firmware(sc);
1317 	if (rc != 0)
1318 		goto done; /* error message displayed already */
1319 	MPASS(sc->flags & FW_OK);
1320 
1321 	rc = get_params__pre_init(sc);
1322 	if (rc != 0)
1323 		goto done; /* error message displayed already */
1324 
1325 	if (sc->flags & MASTER_PF) {
1326 		rc = partition_resources(sc);
1327 		if (rc != 0)
1328 			goto done; /* error message displayed already */
1329 		t4_intr_clear(sc);
1330 	}
1331 
1332 	rc = get_params__post_init(sc);
1333 	if (rc != 0)
1334 		goto done; /* error message displayed already */
1335 
1336 	rc = set_params__post_init(sc);
1337 	if (rc != 0)
1338 		goto done; /* error message displayed already */
1339 
1340 	rc = t4_map_bar_2(sc);
1341 	if (rc != 0)
1342 		goto done; /* error message displayed already */
1343 
1344 	rc = t4_create_dma_tag(sc);
1345 	if (rc != 0)
1346 		goto done; /* error message displayed already */
1347 
1348 	/*
1349 	 * First pass over all the ports - allocate VIs and initialize some
1350 	 * basic parameters like mac address, port type, etc.
1351 	 */
1352 	for_each_port(sc, i) {
1353 		struct port_info *pi;
1354 
1355 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1356 		sc->port[i] = pi;
1357 
1358 		/* These must be set before t4_port_init */
1359 		pi->adapter = sc;
1360 		pi->port_id = i;
1361 		/*
1362 		 * XXX: vi[0] is special so we can't delay this allocation until
1363 		 * pi->nvi's final value is known.
1364 		 */
1365 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1366 		    M_ZERO | M_WAITOK);
1367 
1368 		/*
1369 		 * Allocate the "main" VI and initialize parameters
1370 		 * like mac addr.
1371 		 */
1372 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1373 		if (rc != 0) {
1374 			device_printf(dev, "unable to initialize port %d: %d\n",
1375 			    i, rc);
1376 			free(pi->vi, M_CXGBE);
1377 			free(pi, M_CXGBE);
1378 			sc->port[i] = NULL;
1379 			goto done;
1380 		}
1381 
1382 		if (is_bt(pi->port_type))
1383 			setbit(&sc->bt_map, pi->tx_chan);
1384 		else
1385 			MPASS(!isset(&sc->bt_map, pi->tx_chan));
1386 
1387 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1388 		    device_get_nameunit(dev), i);
1389 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1390 		sc->chan_map[pi->tx_chan] = i;
1391 
1392 		/*
1393 		 * The MPS counter for FCS errors doesn't work correctly on the
1394 		 * T6 so we use the MAC counter here.  Which MAC is in use
1395 		 * depends on the link settings which will be known when the
1396 		 * link comes up.
1397 		 */
1398 		if (is_t6(sc)) {
1399 			pi->fcs_reg = -1;
1400 		} else if (is_t4(sc)) {
1401 			pi->fcs_reg = PORT_REG(pi->tx_chan,
1402 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1403 		} else {
1404 			pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
1405 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1406 		}
1407 		pi->fcs_base = 0;
1408 
1409 		/* All VIs on this port share this media. */
1410 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1411 		    cxgbe_media_status);
1412 
1413 		PORT_LOCK(pi);
1414 		init_link_config(pi);
1415 		fixup_link_config(pi);
1416 		build_medialist(pi);
1417 		if (fixed_ifmedia(pi))
1418 			pi->flags |= FIXED_IFMEDIA;
1419 		PORT_UNLOCK(pi);
1420 
1421 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1422 		    t4_ifnet_unit(sc, pi));
1423 		if (pi->dev == NULL) {
1424 			device_printf(dev,
1425 			    "failed to add device for port %d.\n", i);
1426 			rc = ENXIO;
1427 			goto done;
1428 		}
1429 		pi->vi[0].dev = pi->dev;
1430 		device_set_softc(pi->dev, pi);
1431 	}
1432 
1433 	/*
1434 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1435 	 */
1436 	nports = sc->params.nports;
1437 	rc = cfg_itype_and_nqueues(sc, &iaq);
1438 	if (rc != 0)
1439 		goto done; /* error message displayed already */
1440 
1441 	num_vis = iaq.num_vis;
1442 	sc->intr_type = iaq.intr_type;
1443 	sc->intr_count = iaq.nirq;
1444 
1445 	s = &sc->sge;
1446 	s->nrxq = nports * iaq.nrxq;
1447 	s->ntxq = nports * iaq.ntxq;
1448 	if (num_vis > 1) {
1449 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1450 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1451 	}
1452 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1453 	s->neq += nports;		/* ctrl queues: 1 per port */
1454 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1455 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1456 	if (is_offload(sc) || is_ethoffload(sc)) {
1457 		s->nofldtxq = nports * iaq.nofldtxq;
1458 		if (num_vis > 1)
1459 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1460 		s->neq += s->nofldtxq;
1461 
1462 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1463 		    M_CXGBE, M_ZERO | M_WAITOK);
1464 	}
1465 #endif
1466 #ifdef TCP_OFFLOAD
1467 	if (is_offload(sc)) {
1468 		s->nofldrxq = nports * iaq.nofldrxq;
1469 		if (num_vis > 1)
1470 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1471 		s->neq += s->nofldrxq;	/* free list */
1472 		s->niq += s->nofldrxq;
1473 
1474 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1475 		    M_CXGBE, M_ZERO | M_WAITOK);
1476 	}
1477 #endif
1478 #ifdef DEV_NETMAP
1479 	s->nnmrxq = 0;
1480 	s->nnmtxq = 0;
1481 	if (t4_native_netmap & NN_MAIN_VI) {
1482 		s->nnmrxq += nports * iaq.nnmrxq;
1483 		s->nnmtxq += nports * iaq.nnmtxq;
1484 	}
1485 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1486 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1487 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1488 	}
1489 	s->neq += s->nnmtxq + s->nnmrxq;
1490 	s->niq += s->nnmrxq;
1491 
1492 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1493 	    M_CXGBE, M_ZERO | M_WAITOK);
1494 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1495 	    M_CXGBE, M_ZERO | M_WAITOK);
1496 #endif
1497 	MPASS(s->niq <= s->iqmap_sz);
1498 	MPASS(s->neq <= s->eqmap_sz);
1499 
1500 	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1501 	    M_ZERO | M_WAITOK);
1502 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1503 	    M_ZERO | M_WAITOK);
1504 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1505 	    M_ZERO | M_WAITOK);
1506 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1507 	    M_ZERO | M_WAITOK);
1508 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1509 	    M_ZERO | M_WAITOK);
1510 
1511 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1512 	    M_ZERO | M_WAITOK);
1513 
1514 	t4_init_l2t(sc, M_WAITOK);
1515 	t4_init_smt(sc, M_WAITOK);
1516 	t4_init_tx_sched(sc);
1517 	t4_init_atid_table(sc);
1518 #ifdef RATELIMIT
1519 	t4_init_etid_table(sc);
1520 #endif
1521 #ifdef INET6
1522 	t4_init_clip_table(sc);
1523 #endif
1524 	if (sc->vres.key.size != 0)
1525 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1526 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1527 
1528 	/*
1529 	 * Second pass over the ports.  This time we know the number of rx and
1530 	 * tx queues that each port should get.
1531 	 */
1532 	rqidx = tqidx = 0;
1533 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1534 	ofld_tqidx = 0;
1535 #endif
1536 #ifdef TCP_OFFLOAD
1537 	ofld_rqidx = 0;
1538 #endif
1539 #ifdef DEV_NETMAP
1540 	nm_rqidx = nm_tqidx = 0;
1541 #endif
1542 	for_each_port(sc, i) {
1543 		struct port_info *pi = sc->port[i];
1544 		struct vi_info *vi;
1545 
1546 		if (pi == NULL)
1547 			continue;
1548 
1549 		pi->nvi = num_vis;
1550 		for_each_vi(pi, j, vi) {
1551 			vi->pi = pi;
1552 			vi->adapter = sc;
1553 			vi->first_intr = -1;
1554 			vi->qsize_rxq = t4_qsize_rxq;
1555 			vi->qsize_txq = t4_qsize_txq;
1556 
1557 			vi->first_rxq = rqidx;
1558 			vi->first_txq = tqidx;
1559 			vi->tmr_idx = t4_tmr_idx;
1560 			vi->pktc_idx = t4_pktc_idx;
1561 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1562 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1563 
1564 			rqidx += vi->nrxq;
1565 			tqidx += vi->ntxq;
1566 
1567 			if (j == 0 && vi->ntxq > 1)
1568 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1569 			else
1570 				vi->rsrv_noflowq = 0;
1571 
1572 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1573 			vi->first_ofld_txq = ofld_tqidx;
1574 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1575 			ofld_tqidx += vi->nofldtxq;
1576 #endif
1577 #ifdef TCP_OFFLOAD
1578 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1579 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1580 			vi->first_ofld_rxq = ofld_rqidx;
1581 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1582 
1583 			ofld_rqidx += vi->nofldrxq;
1584 #endif
1585 #ifdef DEV_NETMAP
1586 			vi->first_nm_rxq = nm_rqidx;
1587 			vi->first_nm_txq = nm_tqidx;
1588 			if (j == 0) {
1589 				vi->nnmrxq = iaq.nnmrxq;
1590 				vi->nnmtxq = iaq.nnmtxq;
1591 			} else {
1592 				vi->nnmrxq = iaq.nnmrxq_vi;
1593 				vi->nnmtxq = iaq.nnmtxq_vi;
1594 			}
1595 			nm_rqidx += vi->nnmrxq;
1596 			nm_tqidx += vi->nnmtxq;
1597 #endif
1598 		}
1599 	}
1600 
1601 	rc = t4_setup_intr_handlers(sc);
1602 	if (rc != 0) {
1603 		device_printf(dev,
1604 		    "failed to setup interrupt handlers: %d\n", rc);
1605 		goto done;
1606 	}
1607 
1608 	rc = bus_generic_probe(dev);
1609 	if (rc != 0) {
1610 		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1611 		goto done;
1612 	}
1613 
1614 	/*
1615 	 * Ensure thread-safe mailbox access (in debug builds).
1616 	 *
1617 	 * So far this was the only thread accessing the mailbox but various
1618 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1619 	 * will access the mailbox from different threads.
1620 	 */
1621 	sc->flags |= CHK_MBOX_ACCESS;
1622 
1623 	rc = bus_generic_attach(dev);
1624 	if (rc != 0) {
1625 		device_printf(dev,
1626 		    "failed to attach all child ports: %d\n", rc);
1627 		goto done;
1628 	}
1629 	t4_calibration_start(sc);
1630 
1631 	device_printf(dev,
1632 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1633 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1634 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1635 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1636 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1637 
1638 	t4_set_desc(sc);
1639 
1640 	notify_siblings(dev, 0);
1641 
1642 done:
1643 	if (rc != 0 && sc->cdev) {
1644 		/* cdev was created and so cxgbetool works; recover that way. */
1645 		device_printf(dev,
1646 		    "error during attach, adapter is now in recovery mode.\n");
1647 		rc = 0;
1648 	}
1649 
1650 	if (rc != 0)
1651 		t4_detach_common(dev);
1652 	else
1653 		t4_sysctls(sc);
1654 
1655 	return (rc);
1656 }
1657 
1658 static int
1659 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1660 {
1661 	struct adapter *sc;
1662 	struct port_info *pi;
1663 	int i;
1664 
1665 	sc = device_get_softc(bus);
1666 	for_each_port(sc, i) {
1667 		pi = sc->port[i];
1668 		if (pi != NULL && pi->dev == dev) {
1669 			sbuf_printf(sb, "port=%d", pi->port_id);
1670 			break;
1671 		}
1672 	}
1673 	return (0);
1674 }
1675 
1676 static int
1677 t4_ready(device_t dev)
1678 {
1679 	struct adapter *sc;
1680 
1681 	sc = device_get_softc(dev);
1682 	if (sc->flags & FW_OK)
1683 		return (0);
1684 	return (ENXIO);
1685 }
1686 
1687 static int
1688 t4_read_port_device(device_t dev, int port, device_t *child)
1689 {
1690 	struct adapter *sc;
1691 	struct port_info *pi;
1692 
1693 	sc = device_get_softc(dev);
1694 	if (port < 0 || port >= MAX_NPORTS)
1695 		return (EINVAL);
1696 	pi = sc->port[port];
1697 	if (pi == NULL || pi->dev == NULL)
1698 		return (ENXIO);
1699 	*child = pi->dev;
1700 	return (0);
1701 }
1702 
1703 static int
1704 notify_siblings(device_t dev, int detaching)
1705 {
1706 	device_t sibling;
1707 	int error, i;
1708 
1709 	error = 0;
1710 	for (i = 0; i < PCI_FUNCMAX; i++) {
1711 		if (i == pci_get_function(dev))
1712 			continue;
1713 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1714 		    pci_get_slot(dev), i);
1715 		if (sibling == NULL || !device_is_attached(sibling))
1716 			continue;
1717 		if (detaching)
1718 			error = T4_DETACH_CHILD(sibling);
1719 		else
1720 			(void)T4_ATTACH_CHILD(sibling);
1721 		if (error)
1722 			break;
1723 	}
1724 	return (error);
1725 }
1726 
1727 /*
1728  * Idempotent
1729  */
1730 static int
1731 t4_detach(device_t dev)
1732 {
1733 	int rc;
1734 
1735 	rc = notify_siblings(dev, 1);
1736 	if (rc) {
1737 		device_printf(dev,
1738 		    "failed to detach sibling devices: %d\n", rc);
1739 		return (rc);
1740 	}
1741 
1742 	return (t4_detach_common(dev));
1743 }
1744 
1745 int
1746 t4_detach_common(device_t dev)
1747 {
1748 	struct adapter *sc;
1749 	struct port_info *pi;
1750 	int i, rc;
1751 
1752 	sc = device_get_softc(dev);
1753 
1754 #ifdef TCP_OFFLOAD
1755 	rc = t4_deactivate_all_uld(sc);
1756 	if (rc) {
1757 		device_printf(dev,
1758 		    "failed to detach upper layer drivers: %d\n", rc);
1759 		return (rc);
1760 	}
1761 #endif
1762 
1763 	if (sc->cdev) {
1764 		destroy_dev(sc->cdev);
1765 		sc->cdev = NULL;
1766 	}
1767 
1768 	sx_xlock(&t4_list_lock);
1769 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1770 	sx_xunlock(&t4_list_lock);
1771 
1772 	sc->flags &= ~CHK_MBOX_ACCESS;
1773 	if (sc->flags & FULL_INIT_DONE) {
1774 		if (!(sc->flags & IS_VF))
1775 			t4_intr_disable(sc);
1776 	}
1777 
1778 	if (device_is_attached(dev)) {
1779 		rc = bus_generic_detach(dev);
1780 		if (rc) {
1781 			device_printf(dev,
1782 			    "failed to detach child devices: %d\n", rc);
1783 			return (rc);
1784 		}
1785 	}
1786 
1787 	for (i = 0; i < sc->intr_count; i++)
1788 		t4_free_irq(sc, &sc->irq[i]);
1789 
1790 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1791 		t4_free_tx_sched(sc);
1792 
1793 	for (i = 0; i < MAX_NPORTS; i++) {
1794 		pi = sc->port[i];
1795 		if (pi) {
1796 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1797 			if (pi->dev)
1798 				device_delete_child(dev, pi->dev);
1799 
1800 			mtx_destroy(&pi->pi_lock);
1801 			free(pi->vi, M_CXGBE);
1802 			free(pi, M_CXGBE);
1803 		}
1804 	}
1805 	callout_stop(&sc->cal_callout);
1806 	callout_drain(&sc->cal_callout);
1807 	device_delete_children(dev);
1808 	sysctl_ctx_free(&sc->ctx);
1809 	adapter_full_uninit(sc);
1810 
1811 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1812 		t4_fw_bye(sc, sc->mbox);
1813 
1814 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1815 		pci_release_msi(dev);
1816 
1817 	if (sc->regs_res)
1818 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1819 		    sc->regs_res);
1820 
1821 	if (sc->udbs_res)
1822 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1823 		    sc->udbs_res);
1824 
1825 	if (sc->msix_res)
1826 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1827 		    sc->msix_res);
1828 
1829 	if (sc->l2t)
1830 		t4_free_l2t(sc->l2t);
1831 	if (sc->smt)
1832 		t4_free_smt(sc->smt);
1833 	t4_free_atid_table(sc);
1834 #ifdef RATELIMIT
1835 	t4_free_etid_table(sc);
1836 #endif
1837 	if (sc->key_map)
1838 		vmem_destroy(sc->key_map);
1839 #ifdef INET6
1840 	t4_destroy_clip_table(sc);
1841 #endif
1842 
1843 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1844 	free(sc->sge.ofld_txq, M_CXGBE);
1845 #endif
1846 #ifdef TCP_OFFLOAD
1847 	free(sc->sge.ofld_rxq, M_CXGBE);
1848 #endif
1849 #ifdef DEV_NETMAP
1850 	free(sc->sge.nm_rxq, M_CXGBE);
1851 	free(sc->sge.nm_txq, M_CXGBE);
1852 #endif
1853 	free(sc->irq, M_CXGBE);
1854 	free(sc->sge.rxq, M_CXGBE);
1855 	free(sc->sge.txq, M_CXGBE);
1856 	free(sc->sge.ctrlq, M_CXGBE);
1857 	free(sc->sge.iqmap, M_CXGBE);
1858 	free(sc->sge.eqmap, M_CXGBE);
1859 	free(sc->tids.ftid_tab, M_CXGBE);
1860 	free(sc->tids.hpftid_tab, M_CXGBE);
1861 	free_hftid_hash(&sc->tids);
1862 	free(sc->tids.tid_tab, M_CXGBE);
1863 	t4_destroy_dma_tag(sc);
1864 
1865 	callout_drain(&sc->ktls_tick);
1866 	callout_drain(&sc->sfl_callout);
1867 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1868 		mtx_destroy(&sc->tids.ftid_lock);
1869 		cv_destroy(&sc->tids.ftid_cv);
1870 	}
1871 	if (mtx_initialized(&sc->tids.atid_lock))
1872 		mtx_destroy(&sc->tids.atid_lock);
1873 	if (mtx_initialized(&sc->ifp_lock))
1874 		mtx_destroy(&sc->ifp_lock);
1875 
1876 	if (rw_initialized(&sc->policy_lock)) {
1877 		rw_destroy(&sc->policy_lock);
1878 #ifdef TCP_OFFLOAD
1879 		if (sc->policy != NULL)
1880 			free_offload_policy(sc->policy);
1881 #endif
1882 	}
1883 
1884 	for (i = 0; i < NUM_MEMWIN; i++) {
1885 		struct memwin *mw = &sc->memwin[i];
1886 
1887 		if (rw_initialized(&mw->mw_lock))
1888 			rw_destroy(&mw->mw_lock);
1889 	}
1890 
1891 	mtx_destroy(&sc->sfl_lock);
1892 	mtx_destroy(&sc->reg_lock);
1893 	mtx_destroy(&sc->sc_lock);
1894 
1895 	bzero(sc, sizeof(*sc));
1896 
1897 	return (0);
1898 }
1899 
1900 static inline bool
1901 ok_to_reset(struct adapter *sc)
1902 {
1903 	struct tid_info *t = &sc->tids;
1904 	struct port_info *pi;
1905 	struct vi_info *vi;
1906 	int i, j;
1907 	int caps = IFCAP_TOE | IFCAP_NETMAP | IFCAP_TXRTLMT;
1908 
1909 	if (is_t6(sc))
1910 		caps |= IFCAP_TXTLS;
1911 
1912 	ASSERT_SYNCHRONIZED_OP(sc);
1913 	MPASS(!(sc->flags & IS_VF));
1914 
1915 	for_each_port(sc, i) {
1916 		pi = sc->port[i];
1917 		for_each_vi(pi, j, vi) {
1918 			if (if_getcapenable(vi->ifp) & caps)
1919 				return (false);
1920 		}
1921 	}
1922 
1923 	if (atomic_load_int(&t->tids_in_use) > 0)
1924 		return (false);
1925 	if (atomic_load_int(&t->stids_in_use) > 0)
1926 		return (false);
1927 	if (atomic_load_int(&t->atids_in_use) > 0)
1928 		return (false);
1929 	if (atomic_load_int(&t->ftids_in_use) > 0)
1930 		return (false);
1931 	if (atomic_load_int(&t->hpftids_in_use) > 0)
1932 		return (false);
1933 	if (atomic_load_int(&t->etids_in_use) > 0)
1934 		return (false);
1935 
1936 	return (true);
1937 }
1938 
1939 static inline int
1940 stop_adapter(struct adapter *sc)
1941 {
1942 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_STOPPED)))
1943 		return (1);		/* Already stopped. */
1944 	return (t4_shutdown_adapter(sc));
1945 }
1946 
1947 static int
1948 t4_suspend(device_t dev)
1949 {
1950 	struct adapter *sc = device_get_softc(dev);
1951 	struct port_info *pi;
1952 	struct vi_info *vi;
1953 	if_t ifp;
1954 	struct sge_rxq *rxq;
1955 	struct sge_txq *txq;
1956 	struct sge_wrq *wrq;
1957 #ifdef TCP_OFFLOAD
1958 	struct sge_ofld_rxq *ofld_rxq;
1959 #endif
1960 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1961 	struct sge_ofld_txq *ofld_txq;
1962 #endif
1963 	int rc, i, j, k;
1964 
1965 	CH_ALERT(sc, "suspend requested\n");
1966 
1967 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4sus");
1968 	if (rc != 0)
1969 		return (ENXIO);
1970 
1971 	/* XXX: Can the kernel call suspend repeatedly without resume? */
1972 	MPASS(!hw_off_limits(sc));
1973 
1974 	if (!ok_to_reset(sc)) {
1975 		/* XXX: should list what resource is preventing suspend. */
1976 		CH_ERR(sc, "not safe to suspend.\n");
1977 		rc = EBUSY;
1978 		goto done;
1979 	}
1980 
1981 	/* No more DMA or interrupts. */
1982 	stop_adapter(sc);
1983 
1984 	/* Quiesce all activity. */
1985 	for_each_port(sc, i) {
1986 		pi = sc->port[i];
1987 		pi->vxlan_tcam_entry = false;
1988 
1989 		PORT_LOCK(pi);
1990 		if (pi->up_vis > 0) {
1991 			/*
1992 			 * t4_shutdown_adapter has already shut down all the
1993 			 * PHYs but it also disables interrupts and DMA so there
1994 			 * won't be a link interrupt.  So we update the state
1995 			 * manually and inform the kernel.
1996 			 */
1997 			pi->link_cfg.link_ok = false;
1998 			t4_os_link_changed(pi);
1999 		}
2000 		PORT_UNLOCK(pi);
2001 
2002 		for_each_vi(pi, j, vi) {
2003 			vi->xact_addr_filt = -1;
2004 			mtx_lock(&vi->tick_mtx);
2005 			vi->flags |= VI_SKIP_STATS;
2006 			mtx_unlock(&vi->tick_mtx);
2007 			if (!(vi->flags & VI_INIT_DONE))
2008 				continue;
2009 
2010 			ifp = vi->ifp;
2011 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2012 				mtx_lock(&vi->tick_mtx);
2013 				callout_stop(&vi->tick);
2014 				mtx_unlock(&vi->tick_mtx);
2015 				callout_drain(&vi->tick);
2016 			}
2017 
2018 			/*
2019 			 * Note that the HW is not available.
2020 			 */
2021 			for_each_txq(vi, k, txq) {
2022 				TXQ_LOCK(txq);
2023 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
2024 				TXQ_UNLOCK(txq);
2025 			}
2026 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2027 			for_each_ofld_txq(vi, k, ofld_txq) {
2028 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
2029 			}
2030 #endif
2031 			for_each_rxq(vi, k, rxq) {
2032 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2033 			}
2034 #if defined(TCP_OFFLOAD)
2035 			for_each_ofld_rxq(vi, k, ofld_rxq) {
2036 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2037 			}
2038 #endif
2039 
2040 			quiesce_vi(vi);
2041 		}
2042 
2043 		if (sc->flags & FULL_INIT_DONE) {
2044 			/* Control queue */
2045 			wrq = &sc->sge.ctrlq[i];
2046 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
2047 			quiesce_wrq(wrq);
2048 		}
2049 	}
2050 	if (sc->flags & FULL_INIT_DONE) {
2051 		/* Firmware event queue */
2052 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
2053 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
2054 	}
2055 
2056 	/* Stop calibration */
2057 	callout_stop(&sc->cal_callout);
2058 	callout_drain(&sc->cal_callout);
2059 
2060 	/* Mark the adapter totally off limits. */
2061 	mtx_lock(&sc->reg_lock);
2062 	atomic_set_int(&sc->error_flags, HW_OFF_LIMITS);
2063 	sc->flags &= ~(FW_OK | MASTER_PF);
2064 	sc->reset_thread = NULL;
2065 	mtx_unlock(&sc->reg_lock);
2066 
2067 	if (t4_clock_gate_on_suspend) {
2068 		t4_set_reg_field(sc, A_PMU_PART_CG_PWRMODE, F_MA_PART_CGEN |
2069 		    F_LE_PART_CGEN | F_EDC1_PART_CGEN | F_EDC0_PART_CGEN |
2070 		    F_TP_PART_CGEN | F_PDP_PART_CGEN | F_SGE_PART_CGEN, 0);
2071 	}
2072 
2073 	CH_ALERT(sc, "suspend completed.\n");
2074 done:
2075 	end_synchronized_op(sc, 0);
2076 	return (rc);
2077 }
2078 
2079 struct adapter_pre_reset_state {
2080 	u_int flags;
2081 	uint16_t nbmcaps;
2082 	uint16_t linkcaps;
2083 	uint16_t switchcaps;
2084 	uint16_t niccaps;
2085 	uint16_t toecaps;
2086 	uint16_t rdmacaps;
2087 	uint16_t cryptocaps;
2088 	uint16_t iscsicaps;
2089 	uint16_t fcoecaps;
2090 
2091 	u_int cfcsum;
2092 	char cfg_file[32];
2093 
2094 	struct adapter_params params;
2095 	struct t4_virt_res vres;
2096 	struct tid_info tids;
2097 	struct sge sge;
2098 
2099 	int rawf_base;
2100 	int nrawf;
2101 
2102 };
2103 
2104 static void
2105 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2106 {
2107 
2108 	ASSERT_SYNCHRONIZED_OP(sc);
2109 
2110 	o->flags = sc->flags;
2111 
2112 	o->nbmcaps =  sc->nbmcaps;
2113 	o->linkcaps = sc->linkcaps;
2114 	o->switchcaps = sc->switchcaps;
2115 	o->niccaps = sc->niccaps;
2116 	o->toecaps = sc->toecaps;
2117 	o->rdmacaps = sc->rdmacaps;
2118 	o->cryptocaps = sc->cryptocaps;
2119 	o->iscsicaps = sc->iscsicaps;
2120 	o->fcoecaps = sc->fcoecaps;
2121 
2122 	o->cfcsum = sc->cfcsum;
2123 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2124 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2125 
2126 	o->params = sc->params;
2127 	o->vres = sc->vres;
2128 	o->tids = sc->tids;
2129 	o->sge = sc->sge;
2130 
2131 	o->rawf_base = sc->rawf_base;
2132 	o->nrawf = sc->nrawf;
2133 }
2134 
2135 static int
2136 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2137 {
2138 	int rc = 0;
2139 
2140 	ASSERT_SYNCHRONIZED_OP(sc);
2141 
2142 	/* Capabilities */
2143 #define COMPARE_CAPS(c) do { \
2144 	if (o->c##caps != sc->c##caps) { \
2145 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2146 		    sc->c##caps); \
2147 		rc = EINVAL; \
2148 	} \
2149 } while (0)
2150 	COMPARE_CAPS(nbm);
2151 	COMPARE_CAPS(link);
2152 	COMPARE_CAPS(switch);
2153 	COMPARE_CAPS(nic);
2154 	COMPARE_CAPS(toe);
2155 	COMPARE_CAPS(rdma);
2156 	COMPARE_CAPS(crypto);
2157 	COMPARE_CAPS(iscsi);
2158 	COMPARE_CAPS(fcoe);
2159 #undef COMPARE_CAPS
2160 
2161 	/* Firmware config file */
2162 	if (o->cfcsum != sc->cfcsum) {
2163 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2164 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2165 		rc = EINVAL;
2166 	}
2167 
2168 #define COMPARE_PARAM(p, name) do { \
2169 	if (o->p != sc->p) { \
2170 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2171 		rc = EINVAL; \
2172 	} \
2173 } while (0)
2174 	COMPARE_PARAM(sge.iq_start, iq_start);
2175 	COMPARE_PARAM(sge.eq_start, eq_start);
2176 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2177 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2178 	COMPARE_PARAM(tids.nftids, nftids);
2179 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2180 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2181 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2182 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2183 	COMPARE_PARAM(tids.tid_base, tid_base);
2184 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2185 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2186 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2187 	COMPARE_PARAM(rawf_base, rawf_base);
2188 	COMPARE_PARAM(nrawf, nrawf);
2189 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2190 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2191 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2192 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2193 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2194 	COMPARE_PARAM(tids.ntids, ntids);
2195 	COMPARE_PARAM(tids.etid_base, etid_base);
2196 	COMPARE_PARAM(tids.etid_end, etid_end);
2197 	COMPARE_PARAM(tids.netids, netids);
2198 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2199 	COMPARE_PARAM(params.ethoffload, ethoffload);
2200 	COMPARE_PARAM(tids.natids, natids);
2201 	COMPARE_PARAM(tids.stid_base, stid_base);
2202 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2203 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2204 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2205 	COMPARE_PARAM(vres.stag.start, stag_start);
2206 	COMPARE_PARAM(vres.stag.size, stag_size);
2207 	COMPARE_PARAM(vres.rq.start, rq_start);
2208 	COMPARE_PARAM(vres.rq.size, rq_size);
2209 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2210 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2211 	COMPARE_PARAM(vres.qp.start, qp_start);
2212 	COMPARE_PARAM(vres.qp.size, qp_size);
2213 	COMPARE_PARAM(vres.cq.start, cq_start);
2214 	COMPARE_PARAM(vres.cq.size, cq_size);
2215 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2216 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2217 	COMPARE_PARAM(vres.srq.start, srq_start);
2218 	COMPARE_PARAM(vres.srq.size, srq_size);
2219 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2220 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2221 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2222 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2223 	COMPARE_PARAM(vres.key.start, key_start);
2224 	COMPARE_PARAM(vres.key.size, key_size);
2225 #undef COMPARE_PARAM
2226 
2227 	return (rc);
2228 }
2229 
2230 static int
2231 t4_resume(device_t dev)
2232 {
2233 	struct adapter *sc = device_get_softc(dev);
2234 	struct adapter_pre_reset_state *old_state = NULL;
2235 	struct port_info *pi;
2236 	struct vi_info *vi;
2237 	if_t ifp;
2238 	struct sge_txq *txq;
2239 	int rc, i, j, k;
2240 
2241 	CH_ALERT(sc, "resume requested.\n");
2242 
2243 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4res");
2244 	if (rc != 0)
2245 		return (ENXIO);
2246 	MPASS(hw_off_limits(sc));
2247 	MPASS((sc->flags & FW_OK) == 0);
2248 	MPASS((sc->flags & MASTER_PF) == 0);
2249 	MPASS(sc->reset_thread == NULL);
2250 	sc->reset_thread = curthread;
2251 
2252 	/* Register access is expected to work by the time we're here. */
2253 	if (t4_read_reg(sc, A_PL_WHOAMI) == 0xffffffff) {
2254 		CH_ERR(sc, "%s: can't read device registers\n", __func__);
2255 		rc = ENXIO;
2256 		goto done;
2257 	}
2258 
2259 	/* Note that HW_OFF_LIMITS is cleared a bit later. */
2260 	atomic_clear_int(&sc->error_flags, ADAP_FATAL_ERR | ADAP_STOPPED);
2261 
2262 	/* Restore memory window. */
2263 	setup_memwin(sc);
2264 
2265 	/* Go no further if recovery mode has been requested. */
2266 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2267 		CH_ALERT(sc, "recovery mode on resume.\n");
2268 		rc = 0;
2269 		mtx_lock(&sc->reg_lock);
2270 		atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2271 		mtx_unlock(&sc->reg_lock);
2272 		goto done;
2273 	}
2274 
2275 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2276 	save_caps_and_params(sc, old_state);
2277 
2278 	/* Reestablish contact with firmware and become the primary PF. */
2279 	rc = contact_firmware(sc);
2280 	if (rc != 0)
2281 		goto done; /* error message displayed already */
2282 	MPASS(sc->flags & FW_OK);
2283 
2284 	if (sc->flags & MASTER_PF) {
2285 		rc = partition_resources(sc);
2286 		if (rc != 0)
2287 			goto done; /* error message displayed already */
2288 		t4_intr_clear(sc);
2289 	}
2290 
2291 	rc = get_params__post_init(sc);
2292 	if (rc != 0)
2293 		goto done; /* error message displayed already */
2294 
2295 	rc = set_params__post_init(sc);
2296 	if (rc != 0)
2297 		goto done; /* error message displayed already */
2298 
2299 	rc = compare_caps_and_params(sc, old_state);
2300 	if (rc != 0)
2301 		goto done; /* error message displayed already */
2302 
2303 	for_each_port(sc, i) {
2304 		pi = sc->port[i];
2305 		MPASS(pi != NULL);
2306 		MPASS(pi->vi != NULL);
2307 		MPASS(pi->vi[0].dev == pi->dev);
2308 
2309 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2310 		if (rc != 0) {
2311 			CH_ERR(sc,
2312 			    "failed to re-initialize port %d: %d\n", i, rc);
2313 			goto done;
2314 		}
2315 		MPASS(sc->chan_map[pi->tx_chan] == i);
2316 
2317 		PORT_LOCK(pi);
2318 		fixup_link_config(pi);
2319 		build_medialist(pi);
2320 		PORT_UNLOCK(pi);
2321 		for_each_vi(pi, j, vi) {
2322 			if (IS_MAIN_VI(vi))
2323 				continue;
2324 			rc = alloc_extra_vi(sc, pi, vi);
2325 			if (rc != 0) {
2326 				CH_ERR(vi,
2327 				    "failed to re-allocate extra VI: %d\n", rc);
2328 				goto done;
2329 			}
2330 		}
2331 	}
2332 
2333 	/*
2334 	 * Interrupts and queues are about to be enabled and other threads will
2335 	 * want to access the hardware too.  It is safe to do so.  Note that
2336 	 * this thread is still in the middle of a synchronized_op.
2337 	 */
2338 	mtx_lock(&sc->reg_lock);
2339 	atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2340 	mtx_unlock(&sc->reg_lock);
2341 
2342 	if (sc->flags & FULL_INIT_DONE) {
2343 		rc = adapter_full_init(sc);
2344 		if (rc != 0) {
2345 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2346 			goto done;
2347 		}
2348 
2349 		if (sc->vxlan_refcount > 0)
2350 			enable_vxlan_rx(sc);
2351 
2352 		for_each_port(sc, i) {
2353 			pi = sc->port[i];
2354 			for_each_vi(pi, j, vi) {
2355 				mtx_lock(&vi->tick_mtx);
2356 				vi->flags &= ~VI_SKIP_STATS;
2357 				mtx_unlock(&vi->tick_mtx);
2358 				if (!(vi->flags & VI_INIT_DONE))
2359 					continue;
2360 				rc = vi_full_init(vi);
2361 				if (rc != 0) {
2362 					CH_ERR(vi, "failed to re-initialize "
2363 					    "interface: %d\n", rc);
2364 					goto done;
2365 				}
2366 
2367 				ifp = vi->ifp;
2368 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2369 					continue;
2370 				/*
2371 				 * Note that we do not setup multicast addresses
2372 				 * in the first pass.  This ensures that the
2373 				 * unicast DMACs for all VIs on all ports get an
2374 				 * MPS TCAM entry.
2375 				 */
2376 				rc = update_mac_settings(ifp, XGMAC_ALL &
2377 				    ~XGMAC_MCADDRS);
2378 				if (rc != 0) {
2379 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2380 					goto done;
2381 				}
2382 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2383 				    true);
2384 				if (rc != 0) {
2385 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2386 					goto done;
2387 				}
2388 				for_each_txq(vi, k, txq) {
2389 					TXQ_LOCK(txq);
2390 					txq->eq.flags |= EQ_ENABLED;
2391 					TXQ_UNLOCK(txq);
2392 				}
2393 				mtx_lock(&vi->tick_mtx);
2394 				callout_schedule(&vi->tick, hz);
2395 				mtx_unlock(&vi->tick_mtx);
2396 			}
2397 			PORT_LOCK(pi);
2398 			if (pi->up_vis > 0) {
2399 				t4_update_port_info(pi);
2400 				fixup_link_config(pi);
2401 				build_medialist(pi);
2402 				apply_link_config(pi);
2403 				if (pi->link_cfg.link_ok)
2404 					t4_os_link_changed(pi);
2405 			}
2406 			PORT_UNLOCK(pi);
2407 		}
2408 
2409 		/* Now reprogram the L2 multicast addresses. */
2410 		for_each_port(sc, i) {
2411 			pi = sc->port[i];
2412 			for_each_vi(pi, j, vi) {
2413 				if (!(vi->flags & VI_INIT_DONE))
2414 					continue;
2415 				ifp = vi->ifp;
2416 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2417 					continue;
2418 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2419 				if (rc != 0) {
2420 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2421 					rc = 0;	/* carry on */
2422 				}
2423 			}
2424 		}
2425 	}
2426 
2427 	/* Reset all calibration */
2428 	t4_calibration_start(sc);
2429 
2430 done:
2431 	if (rc == 0) {
2432 		sc->incarnation++;
2433 		CH_ALERT(sc, "resume completed.\n");
2434 	}
2435 	end_synchronized_op(sc, 0);
2436 	free(old_state, M_CXGBE);
2437 	return (rc);
2438 }
2439 
2440 static int
2441 t4_reset_prepare(device_t dev, device_t child)
2442 {
2443 	struct adapter *sc = device_get_softc(dev);
2444 
2445 	CH_ALERT(sc, "reset_prepare.\n");
2446 	return (0);
2447 }
2448 
2449 static int
2450 t4_reset_post(device_t dev, device_t child)
2451 {
2452 	struct adapter *sc = device_get_softc(dev);
2453 
2454 	CH_ALERT(sc, "reset_post.\n");
2455 	return (0);
2456 }
2457 
2458 static int
2459 reset_adapter(struct adapter *sc)
2460 {
2461 	int rc, oldinc, error_flags;
2462 
2463 	CH_ALERT(sc, "reset requested.\n");
2464 
2465 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst1");
2466 	if (rc != 0)
2467 		return (EBUSY);
2468 
2469 	if (hw_off_limits(sc)) {
2470 		CH_ERR(sc, "adapter is suspended, use resume (not reset).\n");
2471 		rc = ENXIO;
2472 		goto done;
2473 	}
2474 
2475 	if (!ok_to_reset(sc)) {
2476 		/* XXX: should list what resource is preventing reset. */
2477 		CH_ERR(sc, "not safe to reset.\n");
2478 		rc = EBUSY;
2479 		goto done;
2480 	}
2481 
2482 done:
2483 	oldinc = sc->incarnation;
2484 	end_synchronized_op(sc, 0);
2485 	if (rc != 0)
2486 		return (rc);	/* Error logged already. */
2487 
2488 	atomic_add_int(&sc->num_resets, 1);
2489 	mtx_lock(&Giant);
2490 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2491 	mtx_unlock(&Giant);
2492 	if (rc != 0)
2493 		CH_ERR(sc, "bus_reset_child failed: %d.\n", rc);
2494 	else {
2495 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst2");
2496 		if (rc != 0)
2497 			return (EBUSY);
2498 		error_flags = atomic_load_int(&sc->error_flags);
2499 		if (sc->incarnation > oldinc && error_flags == 0) {
2500 			CH_ALERT(sc, "bus_reset_child succeeded.\n");
2501 		} else {
2502 			CH_ERR(sc, "adapter did not reset properly, flags "
2503 			    "0x%08x, error_flags 0x%08x.\n", sc->flags,
2504 			    error_flags);
2505 			rc = ENXIO;
2506 		}
2507 		end_synchronized_op(sc, 0);
2508 	}
2509 
2510 	return (rc);
2511 }
2512 
2513 static void
2514 reset_adapter_task(void *arg, int pending)
2515 {
2516 	/* XXX: t4_async_event here? */
2517 	reset_adapter(arg);
2518 }
2519 
2520 static int
2521 cxgbe_probe(device_t dev)
2522 {
2523 	char buf[128];
2524 	struct port_info *pi = device_get_softc(dev);
2525 
2526 	snprintf(buf, sizeof(buf), "port %d", pi->port_id);
2527 	device_set_desc_copy(dev, buf);
2528 
2529 	return (BUS_PROBE_DEFAULT);
2530 }
2531 
2532 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2533     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2534     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2535     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2536 #define T4_CAP_ENABLE (T4_CAP)
2537 
2538 static int
2539 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2540 {
2541 	if_t ifp;
2542 	struct sbuf *sb;
2543 	struct sysctl_ctx_list *ctx = &vi->ctx;
2544 	struct sysctl_oid_list *children;
2545 	struct pfil_head_args pa;
2546 	struct adapter *sc = vi->adapter;
2547 
2548 	sysctl_ctx_init(ctx);
2549 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2550 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2551 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2552 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2553 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2554 #ifdef DEV_NETMAP
2555 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2556 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2557 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2558 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2559 #endif
2560 #ifdef TCP_OFFLOAD
2561 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2562 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2563 #endif
2564 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2565 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2566 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2567 #endif
2568 
2569 	vi->xact_addr_filt = -1;
2570 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2571 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2572 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2573 		vi->flags |= TX_USES_VM_WR;
2574 
2575 	/* Allocate an ifnet and set it up */
2576 	ifp = if_alloc_dev(IFT_ETHER, dev);
2577 	if (ifp == NULL) {
2578 		device_printf(dev, "Cannot allocate ifnet\n");
2579 		return (ENOMEM);
2580 	}
2581 	vi->ifp = ifp;
2582 	if_setsoftc(ifp, vi);
2583 
2584 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2585 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2586 
2587 	if_setinitfn(ifp, cxgbe_init);
2588 	if_setioctlfn(ifp, cxgbe_ioctl);
2589 	if_settransmitfn(ifp, cxgbe_transmit);
2590 	if_setqflushfn(ifp, cxgbe_qflush);
2591 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2592 		if_setgetcounterfn(ifp, vi_get_counter);
2593 	else
2594 		if_setgetcounterfn(ifp, cxgbe_get_counter);
2595 #if defined(KERN_TLS) || defined(RATELIMIT)
2596 	if_setsndtagallocfn(ifp, cxgbe_snd_tag_alloc);
2597 #endif
2598 #ifdef RATELIMIT
2599 	if_setratelimitqueryfn(ifp, cxgbe_ratelimit_query);
2600 #endif
2601 
2602 	if_setcapabilities(ifp, T4_CAP);
2603 	if_setcapenable(ifp, T4_CAP_ENABLE);
2604 	if_sethwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2605 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2606 	if (chip_id(sc) >= CHELSIO_T6) {
2607 		if_setcapabilitiesbit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2608 		if_setcapenablebit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2609 		if_sethwassistbits(ifp, CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2610 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2611 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN, 0);
2612 	}
2613 
2614 #ifdef TCP_OFFLOAD
2615 	if (vi->nofldrxq != 0)
2616 		if_setcapabilitiesbit(ifp, IFCAP_TOE, 0);
2617 #endif
2618 #ifdef RATELIMIT
2619 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2620 		if_setcapabilitiesbit(ifp, IFCAP_TXRTLMT, 0);
2621 		if_setcapenablebit(ifp, IFCAP_TXRTLMT, 0);
2622 	}
2623 #endif
2624 
2625 	if_sethwtsomax(ifp, IP_MAXPACKET);
2626 	if (vi->flags & TX_USES_VM_WR)
2627 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_VM_TSO);
2628 	else
2629 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_TSO);
2630 #ifdef RATELIMIT
2631 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2632 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_EO_TSO);
2633 #endif
2634 	if_sethwtsomaxsegsize(ifp, 65536);
2635 #ifdef KERN_TLS
2636 	if (is_ktls(sc)) {
2637 		if_setcapabilitiesbit(ifp, IFCAP_TXTLS, 0);
2638 		if (sc->flags & KERN_TLS_ON || !is_t6(sc))
2639 			if_setcapenablebit(ifp, IFCAP_TXTLS, 0);
2640 	}
2641 #endif
2642 
2643 	ether_ifattach(ifp, vi->hw_addr);
2644 #ifdef DEV_NETMAP
2645 	if (vi->nnmrxq != 0)
2646 		cxgbe_nm_attach(vi);
2647 #endif
2648 	sb = sbuf_new_auto();
2649 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2650 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2651 	switch (if_getcapabilities(ifp) & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2652 	case IFCAP_TOE:
2653 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2654 		break;
2655 	case IFCAP_TOE | IFCAP_TXRTLMT:
2656 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2657 		break;
2658 	case IFCAP_TXRTLMT:
2659 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2660 		break;
2661 	}
2662 #endif
2663 #ifdef TCP_OFFLOAD
2664 	if (if_getcapabilities(ifp) & IFCAP_TOE)
2665 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2666 #endif
2667 #ifdef DEV_NETMAP
2668 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2669 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2670 		    vi->nnmtxq, vi->nnmrxq);
2671 #endif
2672 	sbuf_finish(sb);
2673 	device_printf(dev, "%s\n", sbuf_data(sb));
2674 	sbuf_delete(sb);
2675 
2676 	vi_sysctls(vi);
2677 
2678 	pa.pa_version = PFIL_VERSION;
2679 	pa.pa_flags = PFIL_IN;
2680 	pa.pa_type = PFIL_TYPE_ETHERNET;
2681 	pa.pa_headname = if_name(ifp);
2682 	vi->pfil = pfil_head_register(&pa);
2683 
2684 	return (0);
2685 }
2686 
2687 static int
2688 cxgbe_attach(device_t dev)
2689 {
2690 	struct port_info *pi = device_get_softc(dev);
2691 	struct adapter *sc = pi->adapter;
2692 	struct vi_info *vi;
2693 	int i, rc;
2694 
2695 	sysctl_ctx_init(&pi->ctx);
2696 
2697 	rc = cxgbe_vi_attach(dev, &pi->vi[0]);
2698 	if (rc)
2699 		return (rc);
2700 
2701 	for_each_vi(pi, i, vi) {
2702 		if (i == 0)
2703 			continue;
2704 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
2705 		if (vi->dev == NULL) {
2706 			device_printf(dev, "failed to add VI %d\n", i);
2707 			continue;
2708 		}
2709 		device_set_softc(vi->dev, vi);
2710 	}
2711 
2712 	cxgbe_sysctls(pi);
2713 
2714 	bus_generic_attach(dev);
2715 
2716 	return (0);
2717 }
2718 
2719 static void
2720 cxgbe_vi_detach(struct vi_info *vi)
2721 {
2722 	if_t ifp = vi->ifp;
2723 
2724 	if (vi->pfil != NULL) {
2725 		pfil_head_unregister(vi->pfil);
2726 		vi->pfil = NULL;
2727 	}
2728 
2729 	ether_ifdetach(ifp);
2730 
2731 	/* Let detach proceed even if these fail. */
2732 #ifdef DEV_NETMAP
2733 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2734 		cxgbe_nm_detach(vi);
2735 #endif
2736 	cxgbe_uninit_synchronized(vi);
2737 	callout_drain(&vi->tick);
2738 	sysctl_ctx_free(&vi->ctx);
2739 	vi_full_uninit(vi);
2740 
2741 	if_free(vi->ifp);
2742 	vi->ifp = NULL;
2743 }
2744 
2745 static int
2746 cxgbe_detach(device_t dev)
2747 {
2748 	struct port_info *pi = device_get_softc(dev);
2749 	struct adapter *sc = pi->adapter;
2750 	int rc;
2751 
2752 	/* Detach the extra VIs first. */
2753 	rc = bus_generic_detach(dev);
2754 	if (rc)
2755 		return (rc);
2756 	device_delete_children(dev);
2757 
2758 	sysctl_ctx_free(&pi->ctx);
2759 	doom_vi(sc, &pi->vi[0]);
2760 
2761 	if (pi->flags & HAS_TRACEQ) {
2762 		sc->traceq = -1;	/* cloner should not create ifnet */
2763 		t4_tracer_port_detach(sc);
2764 	}
2765 
2766 	cxgbe_vi_detach(&pi->vi[0]);
2767 	ifmedia_removeall(&pi->media);
2768 
2769 	end_synchronized_op(sc, 0);
2770 
2771 	return (0);
2772 }
2773 
2774 static void
2775 cxgbe_init(void *arg)
2776 {
2777 	struct vi_info *vi = arg;
2778 	struct adapter *sc = vi->adapter;
2779 
2780 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2781 		return;
2782 	cxgbe_init_synchronized(vi);
2783 	end_synchronized_op(sc, 0);
2784 }
2785 
2786 static int
2787 cxgbe_ioctl(if_t ifp, unsigned long cmd, caddr_t data)
2788 {
2789 	int rc = 0, mtu, flags;
2790 	struct vi_info *vi = if_getsoftc(ifp);
2791 	struct port_info *pi = vi->pi;
2792 	struct adapter *sc = pi->adapter;
2793 	struct ifreq *ifr = (struct ifreq *)data;
2794 	uint32_t mask;
2795 
2796 	switch (cmd) {
2797 	case SIOCSIFMTU:
2798 		mtu = ifr->ifr_mtu;
2799 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2800 			return (EINVAL);
2801 
2802 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2803 		if (rc)
2804 			return (rc);
2805 		if_setmtu(ifp, mtu);
2806 		if (vi->flags & VI_INIT_DONE) {
2807 			t4_update_fl_bufsize(ifp);
2808 			if (!hw_off_limits(sc) &&
2809 			    if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2810 				rc = update_mac_settings(ifp, XGMAC_MTU);
2811 		}
2812 		end_synchronized_op(sc, 0);
2813 		break;
2814 
2815 	case SIOCSIFFLAGS:
2816 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2817 		if (rc)
2818 			return (rc);
2819 
2820 		if (hw_off_limits(sc)) {
2821 			rc = ENXIO;
2822 			goto fail;
2823 		}
2824 
2825 		if (if_getflags(ifp) & IFF_UP) {
2826 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2827 				flags = vi->if_flags;
2828 				if ((if_getflags(ifp) ^ flags) &
2829 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2830 					rc = update_mac_settings(ifp,
2831 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2832 				}
2833 			} else {
2834 				rc = cxgbe_init_synchronized(vi);
2835 			}
2836 			vi->if_flags = if_getflags(ifp);
2837 		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2838 			rc = cxgbe_uninit_synchronized(vi);
2839 		}
2840 		end_synchronized_op(sc, 0);
2841 		break;
2842 
2843 	case SIOCADDMULTI:
2844 	case SIOCDELMULTI:
2845 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2846 		if (rc)
2847 			return (rc);
2848 		if (!hw_off_limits(sc) && if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2849 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2850 		end_synchronized_op(sc, 0);
2851 		break;
2852 
2853 	case SIOCSIFCAP:
2854 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2855 		if (rc)
2856 			return (rc);
2857 
2858 		mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
2859 		if (mask & IFCAP_TXCSUM) {
2860 			if_togglecapenable(ifp, IFCAP_TXCSUM);
2861 			if_togglehwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP);
2862 
2863 			if (IFCAP_TSO4 & if_getcapenable(ifp) &&
2864 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2865 				mask &= ~IFCAP_TSO4;
2866 				if_setcapenablebit(ifp, 0, IFCAP_TSO4);
2867 				if_printf(ifp,
2868 				    "tso4 disabled due to -txcsum.\n");
2869 			}
2870 		}
2871 		if (mask & IFCAP_TXCSUM_IPV6) {
2872 			if_togglecapenable(ifp, IFCAP_TXCSUM_IPV6);
2873 			if_togglehwassist(ifp, CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2874 
2875 			if (IFCAP_TSO6 & if_getcapenable(ifp) &&
2876 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2877 				mask &= ~IFCAP_TSO6;
2878 				if_setcapenablebit(ifp, 0, IFCAP_TSO6);
2879 				if_printf(ifp,
2880 				    "tso6 disabled due to -txcsum6.\n");
2881 			}
2882 		}
2883 		if (mask & IFCAP_RXCSUM)
2884 			if_togglecapenable(ifp, IFCAP_RXCSUM);
2885 		if (mask & IFCAP_RXCSUM_IPV6)
2886 			if_togglecapenable(ifp, IFCAP_RXCSUM_IPV6);
2887 
2888 		/*
2889 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2890 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2891 		 * sending a TSO request our way, so it's sufficient to toggle
2892 		 * IFCAP_TSOx only.
2893 		 */
2894 		if (mask & IFCAP_TSO4) {
2895 			if (!(IFCAP_TSO4 & if_getcapenable(ifp)) &&
2896 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2897 				if_printf(ifp, "enable txcsum first.\n");
2898 				rc = EAGAIN;
2899 				goto fail;
2900 			}
2901 			if_togglecapenable(ifp, IFCAP_TSO4);
2902 		}
2903 		if (mask & IFCAP_TSO6) {
2904 			if (!(IFCAP_TSO6 & if_getcapenable(ifp)) &&
2905 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2906 				if_printf(ifp, "enable txcsum6 first.\n");
2907 				rc = EAGAIN;
2908 				goto fail;
2909 			}
2910 			if_togglecapenable(ifp, IFCAP_TSO6);
2911 		}
2912 		if (mask & IFCAP_LRO) {
2913 #if defined(INET) || defined(INET6)
2914 			int i;
2915 			struct sge_rxq *rxq;
2916 
2917 			if_togglecapenable(ifp, IFCAP_LRO);
2918 			for_each_rxq(vi, i, rxq) {
2919 				if (if_getcapenable(ifp) & IFCAP_LRO)
2920 					rxq->iq.flags |= IQ_LRO_ENABLED;
2921 				else
2922 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2923 			}
2924 #endif
2925 		}
2926 #ifdef TCP_OFFLOAD
2927 		if (mask & IFCAP_TOE) {
2928 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TOE;
2929 
2930 			rc = toe_capability(vi, enable);
2931 			if (rc != 0)
2932 				goto fail;
2933 
2934 			if_togglecapenable(ifp, mask);
2935 		}
2936 #endif
2937 		if (mask & IFCAP_VLAN_HWTAGGING) {
2938 			if_togglecapenable(ifp, IFCAP_VLAN_HWTAGGING);
2939 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2940 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2941 		}
2942 		if (mask & IFCAP_VLAN_MTU) {
2943 			if_togglecapenable(ifp, IFCAP_VLAN_MTU);
2944 
2945 			/* Need to find out how to disable auto-mtu-inflation */
2946 		}
2947 		if (mask & IFCAP_VLAN_HWTSO)
2948 			if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
2949 		if (mask & IFCAP_VLAN_HWCSUM)
2950 			if_togglecapenable(ifp, IFCAP_VLAN_HWCSUM);
2951 #ifdef RATELIMIT
2952 		if (mask & IFCAP_TXRTLMT)
2953 			if_togglecapenable(ifp, IFCAP_TXRTLMT);
2954 #endif
2955 		if (mask & IFCAP_HWRXTSTMP) {
2956 			int i;
2957 			struct sge_rxq *rxq;
2958 
2959 			if_togglecapenable(ifp, IFCAP_HWRXTSTMP);
2960 			for_each_rxq(vi, i, rxq) {
2961 				if (if_getcapenable(ifp) & IFCAP_HWRXTSTMP)
2962 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2963 				else
2964 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2965 			}
2966 		}
2967 		if (mask & IFCAP_MEXTPG)
2968 			if_togglecapenable(ifp, IFCAP_MEXTPG);
2969 
2970 #ifdef KERN_TLS
2971 		if (mask & IFCAP_TXTLS) {
2972 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TXTLS;
2973 
2974 			rc = ktls_capability(sc, enable);
2975 			if (rc != 0)
2976 				goto fail;
2977 
2978 			if_togglecapenable(ifp, mask & IFCAP_TXTLS);
2979 		}
2980 #endif
2981 		if (mask & IFCAP_VXLAN_HWCSUM) {
2982 			if_togglecapenable(ifp, IFCAP_VXLAN_HWCSUM);
2983 			if_togglehwassist(ifp, CSUM_INNER_IP6_UDP |
2984 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
2985 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP);
2986 		}
2987 		if (mask & IFCAP_VXLAN_HWTSO) {
2988 			if_togglecapenable(ifp, IFCAP_VXLAN_HWTSO);
2989 			if_togglehwassist(ifp, CSUM_INNER_IP6_TSO |
2990 			    CSUM_INNER_IP_TSO);
2991 		}
2992 
2993 #ifdef VLAN_CAPABILITIES
2994 		VLAN_CAPABILITIES(ifp);
2995 #endif
2996 fail:
2997 		end_synchronized_op(sc, 0);
2998 		break;
2999 
3000 	case SIOCSIFMEDIA:
3001 	case SIOCGIFMEDIA:
3002 	case SIOCGIFXMEDIA:
3003 		rc = ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
3004 		break;
3005 
3006 	case SIOCGI2C: {
3007 		struct ifi2creq i2c;
3008 
3009 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
3010 		if (rc != 0)
3011 			break;
3012 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
3013 			rc = EPERM;
3014 			break;
3015 		}
3016 		if (i2c.len > sizeof(i2c.data)) {
3017 			rc = EINVAL;
3018 			break;
3019 		}
3020 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
3021 		if (rc)
3022 			return (rc);
3023 		if (hw_off_limits(sc))
3024 			rc = ENXIO;
3025 		else
3026 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
3027 			    i2c.offset, i2c.len, &i2c.data[0]);
3028 		end_synchronized_op(sc, 0);
3029 		if (rc == 0)
3030 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
3031 		break;
3032 	}
3033 
3034 	default:
3035 		rc = ether_ioctl(ifp, cmd, data);
3036 	}
3037 
3038 	return (rc);
3039 }
3040 
3041 static int
3042 cxgbe_transmit(if_t ifp, struct mbuf *m)
3043 {
3044 	struct vi_info *vi = if_getsoftc(ifp);
3045 	struct port_info *pi = vi->pi;
3046 	struct adapter *sc;
3047 	struct sge_txq *txq;
3048 	void *items[1];
3049 	int rc;
3050 
3051 	M_ASSERTPKTHDR(m);
3052 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
3053 #if defined(KERN_TLS) || defined(RATELIMIT)
3054 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
3055 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
3056 #endif
3057 
3058 	if (__predict_false(pi->link_cfg.link_ok == false)) {
3059 		m_freem(m);
3060 		return (ENETDOWN);
3061 	}
3062 
3063 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
3064 	if (__predict_false(rc != 0)) {
3065 		if (__predict_true(rc == EINPROGRESS)) {
3066 			/* queued by parse_pkt */
3067 			MPASS(m != NULL);
3068 			return (0);
3069 		}
3070 
3071 		MPASS(m == NULL);			/* was freed already */
3072 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
3073 		return (rc);
3074 	}
3075 
3076 	/* Select a txq. */
3077 	sc = vi->adapter;
3078 	txq = &sc->sge.txq[vi->first_txq];
3079 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
3080 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
3081 		    vi->rsrv_noflowq);
3082 
3083 	items[0] = m;
3084 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
3085 	if (__predict_false(rc != 0))
3086 		m_freem(m);
3087 
3088 	return (rc);
3089 }
3090 
3091 static void
3092 cxgbe_qflush(if_t ifp)
3093 {
3094 	struct vi_info *vi = if_getsoftc(ifp);
3095 	struct sge_txq *txq;
3096 	int i;
3097 
3098 	/* queues do not exist if !VI_INIT_DONE. */
3099 	if (vi->flags & VI_INIT_DONE) {
3100 		for_each_txq(vi, i, txq) {
3101 			TXQ_LOCK(txq);
3102 			txq->eq.flags |= EQ_QFLUSH;
3103 			TXQ_UNLOCK(txq);
3104 			while (!mp_ring_is_idle(txq->r)) {
3105 				mp_ring_check_drainage(txq->r, 4096);
3106 				pause("qflush", 1);
3107 			}
3108 			TXQ_LOCK(txq);
3109 			txq->eq.flags &= ~EQ_QFLUSH;
3110 			TXQ_UNLOCK(txq);
3111 		}
3112 	}
3113 	if_qflush(ifp);
3114 }
3115 
3116 static uint64_t
3117 vi_get_counter(if_t ifp, ift_counter c)
3118 {
3119 	struct vi_info *vi = if_getsoftc(ifp);
3120 	struct fw_vi_stats_vf *s = &vi->stats;
3121 
3122 	mtx_lock(&vi->tick_mtx);
3123 	vi_refresh_stats(vi);
3124 	mtx_unlock(&vi->tick_mtx);
3125 
3126 	switch (c) {
3127 	case IFCOUNTER_IPACKETS:
3128 		return (s->rx_bcast_frames + s->rx_mcast_frames +
3129 		    s->rx_ucast_frames);
3130 	case IFCOUNTER_IERRORS:
3131 		return (s->rx_err_frames);
3132 	case IFCOUNTER_OPACKETS:
3133 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3134 		    s->tx_ucast_frames + s->tx_offload_frames);
3135 	case IFCOUNTER_OERRORS:
3136 		return (s->tx_drop_frames);
3137 	case IFCOUNTER_IBYTES:
3138 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3139 		    s->rx_ucast_bytes);
3140 	case IFCOUNTER_OBYTES:
3141 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3142 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3143 	case IFCOUNTER_IMCASTS:
3144 		return (s->rx_mcast_frames);
3145 	case IFCOUNTER_OMCASTS:
3146 		return (s->tx_mcast_frames);
3147 	case IFCOUNTER_OQDROPS: {
3148 		uint64_t drops;
3149 
3150 		drops = 0;
3151 		if (vi->flags & VI_INIT_DONE) {
3152 			int i;
3153 			struct sge_txq *txq;
3154 
3155 			for_each_txq(vi, i, txq)
3156 				drops += counter_u64_fetch(txq->r->dropped);
3157 		}
3158 
3159 		return (drops);
3160 
3161 	}
3162 
3163 	default:
3164 		return (if_get_counter_default(ifp, c));
3165 	}
3166 }
3167 
3168 static uint64_t
3169 cxgbe_get_counter(if_t ifp, ift_counter c)
3170 {
3171 	struct vi_info *vi = if_getsoftc(ifp);
3172 	struct port_info *pi = vi->pi;
3173 	struct port_stats *s = &pi->stats;
3174 
3175 	mtx_lock(&vi->tick_mtx);
3176 	cxgbe_refresh_stats(vi);
3177 	mtx_unlock(&vi->tick_mtx);
3178 
3179 	switch (c) {
3180 	case IFCOUNTER_IPACKETS:
3181 		return (s->rx_frames);
3182 
3183 	case IFCOUNTER_IERRORS:
3184 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3185 		    s->rx_fcs_err + s->rx_len_err);
3186 
3187 	case IFCOUNTER_OPACKETS:
3188 		return (s->tx_frames);
3189 
3190 	case IFCOUNTER_OERRORS:
3191 		return (s->tx_error_frames);
3192 
3193 	case IFCOUNTER_IBYTES:
3194 		return (s->rx_octets);
3195 
3196 	case IFCOUNTER_OBYTES:
3197 		return (s->tx_octets);
3198 
3199 	case IFCOUNTER_IMCASTS:
3200 		return (s->rx_mcast_frames);
3201 
3202 	case IFCOUNTER_OMCASTS:
3203 		return (s->tx_mcast_frames);
3204 
3205 	case IFCOUNTER_IQDROPS:
3206 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3207 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3208 		    s->rx_trunc3 + pi->tnl_cong_drops);
3209 
3210 	case IFCOUNTER_OQDROPS: {
3211 		uint64_t drops;
3212 
3213 		drops = s->tx_drop;
3214 		if (vi->flags & VI_INIT_DONE) {
3215 			int i;
3216 			struct sge_txq *txq;
3217 
3218 			for_each_txq(vi, i, txq)
3219 				drops += counter_u64_fetch(txq->r->dropped);
3220 		}
3221 
3222 		return (drops);
3223 
3224 	}
3225 
3226 	default:
3227 		return (if_get_counter_default(ifp, c));
3228 	}
3229 }
3230 
3231 #if defined(KERN_TLS) || defined(RATELIMIT)
3232 static int
3233 cxgbe_snd_tag_alloc(if_t ifp, union if_snd_tag_alloc_params *params,
3234     struct m_snd_tag **pt)
3235 {
3236 	int error;
3237 
3238 	switch (params->hdr.type) {
3239 #ifdef RATELIMIT
3240 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3241 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3242 		break;
3243 #endif
3244 #ifdef KERN_TLS
3245 	case IF_SND_TAG_TYPE_TLS:
3246 	{
3247 		struct vi_info *vi = if_getsoftc(ifp);
3248 
3249 		if (is_t6(vi->pi->adapter))
3250 			error = t6_tls_tag_alloc(ifp, params, pt);
3251 		else
3252 			error = EOPNOTSUPP;
3253 		break;
3254 	}
3255 #endif
3256 	default:
3257 		error = EOPNOTSUPP;
3258 	}
3259 	return (error);
3260 }
3261 #endif
3262 
3263 /*
3264  * The kernel picks a media from the list we had provided but we still validate
3265  * the requeste.
3266  */
3267 int
3268 cxgbe_media_change(if_t ifp)
3269 {
3270 	struct vi_info *vi = if_getsoftc(ifp);
3271 	struct port_info *pi = vi->pi;
3272 	struct ifmedia *ifm = &pi->media;
3273 	struct link_config *lc = &pi->link_cfg;
3274 	struct adapter *sc = pi->adapter;
3275 	int rc;
3276 
3277 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3278 	if (rc != 0)
3279 		return (rc);
3280 	PORT_LOCK(pi);
3281 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3282 		/* ifconfig .. media autoselect */
3283 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3284 			rc = ENOTSUP; /* AN not supported by transceiver */
3285 			goto done;
3286 		}
3287 		lc->requested_aneg = AUTONEG_ENABLE;
3288 		lc->requested_speed = 0;
3289 		lc->requested_fc |= PAUSE_AUTONEG;
3290 	} else {
3291 		lc->requested_aneg = AUTONEG_DISABLE;
3292 		lc->requested_speed =
3293 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3294 		lc->requested_fc = 0;
3295 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3296 			lc->requested_fc |= PAUSE_RX;
3297 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3298 			lc->requested_fc |= PAUSE_TX;
3299 	}
3300 	if (pi->up_vis > 0 && !hw_off_limits(sc)) {
3301 		fixup_link_config(pi);
3302 		rc = apply_link_config(pi);
3303 	}
3304 done:
3305 	PORT_UNLOCK(pi);
3306 	end_synchronized_op(sc, 0);
3307 	return (rc);
3308 }
3309 
3310 /*
3311  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3312  * given speed.
3313  */
3314 static int
3315 port_mword(struct port_info *pi, uint32_t speed)
3316 {
3317 
3318 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3319 	MPASS(powerof2(speed));
3320 
3321 	switch(pi->port_type) {
3322 	case FW_PORT_TYPE_BT_SGMII:
3323 	case FW_PORT_TYPE_BT_XFI:
3324 	case FW_PORT_TYPE_BT_XAUI:
3325 		/* BaseT */
3326 		switch (speed) {
3327 		case FW_PORT_CAP32_SPEED_100M:
3328 			return (IFM_100_T);
3329 		case FW_PORT_CAP32_SPEED_1G:
3330 			return (IFM_1000_T);
3331 		case FW_PORT_CAP32_SPEED_10G:
3332 			return (IFM_10G_T);
3333 		}
3334 		break;
3335 	case FW_PORT_TYPE_KX4:
3336 		if (speed == FW_PORT_CAP32_SPEED_10G)
3337 			return (IFM_10G_KX4);
3338 		break;
3339 	case FW_PORT_TYPE_CX4:
3340 		if (speed == FW_PORT_CAP32_SPEED_10G)
3341 			return (IFM_10G_CX4);
3342 		break;
3343 	case FW_PORT_TYPE_KX:
3344 		if (speed == FW_PORT_CAP32_SPEED_1G)
3345 			return (IFM_1000_KX);
3346 		break;
3347 	case FW_PORT_TYPE_KR:
3348 	case FW_PORT_TYPE_BP_AP:
3349 	case FW_PORT_TYPE_BP4_AP:
3350 	case FW_PORT_TYPE_BP40_BA:
3351 	case FW_PORT_TYPE_KR4_100G:
3352 	case FW_PORT_TYPE_KR_SFP28:
3353 	case FW_PORT_TYPE_KR_XLAUI:
3354 		switch (speed) {
3355 		case FW_PORT_CAP32_SPEED_1G:
3356 			return (IFM_1000_KX);
3357 		case FW_PORT_CAP32_SPEED_10G:
3358 			return (IFM_10G_KR);
3359 		case FW_PORT_CAP32_SPEED_25G:
3360 			return (IFM_25G_KR);
3361 		case FW_PORT_CAP32_SPEED_40G:
3362 			return (IFM_40G_KR4);
3363 		case FW_PORT_CAP32_SPEED_50G:
3364 			return (IFM_50G_KR2);
3365 		case FW_PORT_CAP32_SPEED_100G:
3366 			return (IFM_100G_KR4);
3367 		}
3368 		break;
3369 	case FW_PORT_TYPE_FIBER_XFI:
3370 	case FW_PORT_TYPE_FIBER_XAUI:
3371 	case FW_PORT_TYPE_SFP:
3372 	case FW_PORT_TYPE_QSFP_10G:
3373 	case FW_PORT_TYPE_QSA:
3374 	case FW_PORT_TYPE_QSFP:
3375 	case FW_PORT_TYPE_CR4_QSFP:
3376 	case FW_PORT_TYPE_CR_QSFP:
3377 	case FW_PORT_TYPE_CR2_QSFP:
3378 	case FW_PORT_TYPE_SFP28:
3379 		/* Pluggable transceiver */
3380 		switch (pi->mod_type) {
3381 		case FW_PORT_MOD_TYPE_LR:
3382 			switch (speed) {
3383 			case FW_PORT_CAP32_SPEED_1G:
3384 				return (IFM_1000_LX);
3385 			case FW_PORT_CAP32_SPEED_10G:
3386 				return (IFM_10G_LR);
3387 			case FW_PORT_CAP32_SPEED_25G:
3388 				return (IFM_25G_LR);
3389 			case FW_PORT_CAP32_SPEED_40G:
3390 				return (IFM_40G_LR4);
3391 			case FW_PORT_CAP32_SPEED_50G:
3392 				return (IFM_50G_LR2);
3393 			case FW_PORT_CAP32_SPEED_100G:
3394 				return (IFM_100G_LR4);
3395 			}
3396 			break;
3397 		case FW_PORT_MOD_TYPE_SR:
3398 			switch (speed) {
3399 			case FW_PORT_CAP32_SPEED_1G:
3400 				return (IFM_1000_SX);
3401 			case FW_PORT_CAP32_SPEED_10G:
3402 				return (IFM_10G_SR);
3403 			case FW_PORT_CAP32_SPEED_25G:
3404 				return (IFM_25G_SR);
3405 			case FW_PORT_CAP32_SPEED_40G:
3406 				return (IFM_40G_SR4);
3407 			case FW_PORT_CAP32_SPEED_50G:
3408 				return (IFM_50G_SR2);
3409 			case FW_PORT_CAP32_SPEED_100G:
3410 				return (IFM_100G_SR4);
3411 			}
3412 			break;
3413 		case FW_PORT_MOD_TYPE_ER:
3414 			if (speed == FW_PORT_CAP32_SPEED_10G)
3415 				return (IFM_10G_ER);
3416 			break;
3417 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3418 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3419 			switch (speed) {
3420 			case FW_PORT_CAP32_SPEED_1G:
3421 				return (IFM_1000_CX);
3422 			case FW_PORT_CAP32_SPEED_10G:
3423 				return (IFM_10G_TWINAX);
3424 			case FW_PORT_CAP32_SPEED_25G:
3425 				return (IFM_25G_CR);
3426 			case FW_PORT_CAP32_SPEED_40G:
3427 				return (IFM_40G_CR4);
3428 			case FW_PORT_CAP32_SPEED_50G:
3429 				return (IFM_50G_CR2);
3430 			case FW_PORT_CAP32_SPEED_100G:
3431 				return (IFM_100G_CR4);
3432 			}
3433 			break;
3434 		case FW_PORT_MOD_TYPE_LRM:
3435 			if (speed == FW_PORT_CAP32_SPEED_10G)
3436 				return (IFM_10G_LRM);
3437 			break;
3438 		case FW_PORT_MOD_TYPE_NA:
3439 			MPASS(0);	/* Not pluggable? */
3440 			/* fall throough */
3441 		case FW_PORT_MOD_TYPE_ERROR:
3442 		case FW_PORT_MOD_TYPE_UNKNOWN:
3443 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3444 			break;
3445 		case FW_PORT_MOD_TYPE_NONE:
3446 			return (IFM_NONE);
3447 		}
3448 		break;
3449 	case FW_PORT_TYPE_NONE:
3450 		return (IFM_NONE);
3451 	}
3452 
3453 	return (IFM_UNKNOWN);
3454 }
3455 
3456 void
3457 cxgbe_media_status(if_t ifp, struct ifmediareq *ifmr)
3458 {
3459 	struct vi_info *vi = if_getsoftc(ifp);
3460 	struct port_info *pi = vi->pi;
3461 	struct adapter *sc = pi->adapter;
3462 	struct link_config *lc = &pi->link_cfg;
3463 
3464 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4med") != 0)
3465 		return;
3466 	PORT_LOCK(pi);
3467 
3468 	if (pi->up_vis == 0 && !hw_off_limits(sc)) {
3469 		/*
3470 		 * If all the interfaces are administratively down the firmware
3471 		 * does not report transceiver changes.  Refresh port info here
3472 		 * so that ifconfig displays accurate ifmedia at all times.
3473 		 * This is the only reason we have a synchronized op in this
3474 		 * function.  Just PORT_LOCK would have been enough otherwise.
3475 		 */
3476 		t4_update_port_info(pi);
3477 		build_medialist(pi);
3478 	}
3479 
3480 	/* ifm_status */
3481 	ifmr->ifm_status = IFM_AVALID;
3482 	if (lc->link_ok == false)
3483 		goto done;
3484 	ifmr->ifm_status |= IFM_ACTIVE;
3485 
3486 	/* ifm_active */
3487 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3488 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3489 	if (lc->fc & PAUSE_RX)
3490 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3491 	if (lc->fc & PAUSE_TX)
3492 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3493 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3494 done:
3495 	PORT_UNLOCK(pi);
3496 	end_synchronized_op(sc, 0);
3497 }
3498 
3499 static int
3500 vcxgbe_probe(device_t dev)
3501 {
3502 	char buf[128];
3503 	struct vi_info *vi = device_get_softc(dev);
3504 
3505 	snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
3506 	    vi - vi->pi->vi);
3507 	device_set_desc_copy(dev, buf);
3508 
3509 	return (BUS_PROBE_DEFAULT);
3510 }
3511 
3512 static int
3513 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3514 {
3515 	int func, index, rc;
3516 	uint32_t param, val;
3517 
3518 	ASSERT_SYNCHRONIZED_OP(sc);
3519 
3520 	index = vi - pi->vi;
3521 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3522 	KASSERT(index < nitems(vi_mac_funcs),
3523 	    ("%s: VI %s doesn't have a MAC func", __func__,
3524 	    device_get_nameunit(vi->dev)));
3525 	func = vi_mac_funcs[index];
3526 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3527 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3528 	if (rc < 0) {
3529 		CH_ERR(vi, "failed to allocate virtual interface %d"
3530 		    "for port %d: %d\n", index, pi->port_id, -rc);
3531 		return (-rc);
3532 	}
3533 	vi->viid = rc;
3534 
3535 	if (vi->rss_size == 1) {
3536 		/*
3537 		 * This VI didn't get a slice of the RSS table.  Reduce the
3538 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3539 		 * configuration file (nvi, rssnvi for this PF) if this is a
3540 		 * problem.
3541 		 */
3542 		device_printf(vi->dev, "RSS table not available.\n");
3543 		vi->rss_base = 0xffff;
3544 
3545 		return (0);
3546 	}
3547 
3548 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3549 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3550 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3551 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3552 	if (rc)
3553 		vi->rss_base = 0xffff;
3554 	else {
3555 		MPASS((val >> 16) == vi->rss_size);
3556 		vi->rss_base = val & 0xffff;
3557 	}
3558 
3559 	return (0);
3560 }
3561 
3562 static int
3563 vcxgbe_attach(device_t dev)
3564 {
3565 	struct vi_info *vi;
3566 	struct port_info *pi;
3567 	struct adapter *sc;
3568 	int rc;
3569 
3570 	vi = device_get_softc(dev);
3571 	pi = vi->pi;
3572 	sc = pi->adapter;
3573 
3574 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3575 	if (rc)
3576 		return (rc);
3577 	rc = alloc_extra_vi(sc, pi, vi);
3578 	end_synchronized_op(sc, 0);
3579 	if (rc)
3580 		return (rc);
3581 
3582 	rc = cxgbe_vi_attach(dev, vi);
3583 	if (rc) {
3584 		t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3585 		return (rc);
3586 	}
3587 	return (0);
3588 }
3589 
3590 static int
3591 vcxgbe_detach(device_t dev)
3592 {
3593 	struct vi_info *vi;
3594 	struct adapter *sc;
3595 
3596 	vi = device_get_softc(dev);
3597 	sc = vi->adapter;
3598 
3599 	doom_vi(sc, vi);
3600 
3601 	cxgbe_vi_detach(vi);
3602 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3603 
3604 	end_synchronized_op(sc, 0);
3605 
3606 	return (0);
3607 }
3608 
3609 static struct callout fatal_callout;
3610 static struct taskqueue *reset_tq;
3611 
3612 static void
3613 delayed_panic(void *arg)
3614 {
3615 	struct adapter *sc = arg;
3616 
3617 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3618 }
3619 
3620 static void
3621 fatal_error_task(void *arg, int pending)
3622 {
3623 	struct adapter *sc = arg;
3624 	int rc;
3625 
3626 #ifdef TCP_OFFLOAD
3627 	t4_async_event(sc);
3628 #endif
3629 	if (atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_CIM_ERR))) {
3630 		dump_cim_regs(sc);
3631 		dump_cimla(sc);
3632 		dump_devlog(sc);
3633 	}
3634 
3635 	if (t4_reset_on_fatal_err) {
3636 		CH_ALERT(sc, "resetting on fatal error.\n");
3637 		rc = reset_adapter(sc);
3638 		if (rc == 0 && t4_panic_on_fatal_err) {
3639 			CH_ALERT(sc, "reset was successful, "
3640 			    "system will NOT panic.\n");
3641 			return;
3642 		}
3643 	}
3644 
3645 	if (t4_panic_on_fatal_err) {
3646 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3647 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3648 	}
3649 }
3650 
3651 void
3652 t4_fatal_err(struct adapter *sc, bool fw_error)
3653 {
3654 	const bool verbose = (sc->debug_flags & DF_VERBOSE_SLOWINTR) != 0;
3655 
3656 	stop_adapter(sc);
3657 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_FATAL_ERR)))
3658 		return;
3659 	if (fw_error) {
3660 		/*
3661 		 * We are here because of a firmware error/timeout and not
3662 		 * because of a hardware interrupt.  It is possible (although
3663 		 * not very likely) that an error interrupt was also raised but
3664 		 * this thread ran first and inhibited t4_intr_err.  We walk the
3665 		 * main INT_CAUSE registers here to make sure we haven't missed
3666 		 * anything interesting.
3667 		 */
3668 		t4_slow_intr_handler(sc, verbose);
3669 		atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
3670 	}
3671 	t4_report_fw_error(sc);
3672 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped (%d).\n",
3673 	    device_get_nameunit(sc->dev), fw_error);
3674 	taskqueue_enqueue(reset_tq, &sc->fatal_error_task);
3675 }
3676 
3677 void
3678 t4_add_adapter(struct adapter *sc)
3679 {
3680 	sx_xlock(&t4_list_lock);
3681 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3682 	sx_xunlock(&t4_list_lock);
3683 }
3684 
3685 int
3686 t4_map_bars_0_and_4(struct adapter *sc)
3687 {
3688 	sc->regs_rid = PCIR_BAR(0);
3689 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3690 	    &sc->regs_rid, RF_ACTIVE);
3691 	if (sc->regs_res == NULL) {
3692 		device_printf(sc->dev, "cannot map registers.\n");
3693 		return (ENXIO);
3694 	}
3695 	sc->bt = rman_get_bustag(sc->regs_res);
3696 	sc->bh = rman_get_bushandle(sc->regs_res);
3697 	sc->mmio_len = rman_get_size(sc->regs_res);
3698 	setbit(&sc->doorbells, DOORBELL_KDB);
3699 
3700 	sc->msix_rid = PCIR_BAR(4);
3701 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3702 	    &sc->msix_rid, RF_ACTIVE);
3703 	if (sc->msix_res == NULL) {
3704 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3705 		return (ENXIO);
3706 	}
3707 
3708 	return (0);
3709 }
3710 
3711 int
3712 t4_map_bar_2(struct adapter *sc)
3713 {
3714 
3715 	/*
3716 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3717 	 * to map it if RDMA is disabled.
3718 	 */
3719 	if (is_t4(sc) && sc->rdmacaps == 0)
3720 		return (0);
3721 
3722 	sc->udbs_rid = PCIR_BAR(2);
3723 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3724 	    &sc->udbs_rid, RF_ACTIVE);
3725 	if (sc->udbs_res == NULL) {
3726 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3727 		return (ENXIO);
3728 	}
3729 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3730 
3731 	if (chip_id(sc) >= CHELSIO_T5) {
3732 		setbit(&sc->doorbells, DOORBELL_UDB);
3733 #if defined(__i386__) || defined(__amd64__)
3734 		if (t5_write_combine) {
3735 			int rc, mode;
3736 
3737 			/*
3738 			 * Enable write combining on BAR2.  This is the
3739 			 * userspace doorbell BAR and is split into 128B
3740 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3741 			 * with an egress queue.  The first 64B has the doorbell
3742 			 * and the second 64B can be used to submit a tx work
3743 			 * request with an implicit doorbell.
3744 			 */
3745 
3746 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3747 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3748 			if (rc == 0) {
3749 				clrbit(&sc->doorbells, DOORBELL_UDB);
3750 				setbit(&sc->doorbells, DOORBELL_WCWR);
3751 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3752 			} else {
3753 				device_printf(sc->dev,
3754 				    "couldn't enable write combining: %d\n",
3755 				    rc);
3756 			}
3757 
3758 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3759 			t4_write_reg(sc, A_SGE_STAT_CFG,
3760 			    V_STATSOURCE_T5(7) | mode);
3761 		}
3762 #endif
3763 	}
3764 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3765 
3766 	return (0);
3767 }
3768 
3769 struct memwin_init {
3770 	uint32_t base;
3771 	uint32_t aperture;
3772 };
3773 
3774 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3775 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3776 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3777 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3778 };
3779 
3780 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3781 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3782 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3783 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3784 };
3785 
3786 static void
3787 setup_memwin(struct adapter *sc)
3788 {
3789 	const struct memwin_init *mw_init;
3790 	struct memwin *mw;
3791 	int i;
3792 	uint32_t bar0;
3793 
3794 	if (is_t4(sc)) {
3795 		/*
3796 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3797 		 * mechanism.  Works from within PCI passthrough environments
3798 		 * too, where rman_get_start() can return a different value.  We
3799 		 * need to program the T4 memory window decoders with the actual
3800 		 * addresses that will be coming across the PCIe link.
3801 		 */
3802 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3803 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3804 
3805 		mw_init = &t4_memwin[0];
3806 	} else {
3807 		/* T5+ use the relative offset inside the PCIe BAR */
3808 		bar0 = 0;
3809 
3810 		mw_init = &t5_memwin[0];
3811 	}
3812 
3813 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3814 		if (!rw_initialized(&mw->mw_lock)) {
3815 			rw_init(&mw->mw_lock, "memory window access");
3816 			mw->mw_base = mw_init->base;
3817 			mw->mw_aperture = mw_init->aperture;
3818 			mw->mw_curpos = 0;
3819 		}
3820 		t4_write_reg(sc,
3821 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3822 		    (mw->mw_base + bar0) | V_BIR(0) |
3823 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3824 		rw_wlock(&mw->mw_lock);
3825 		position_memwin(sc, i, mw->mw_curpos);
3826 		rw_wunlock(&mw->mw_lock);
3827 	}
3828 
3829 	/* flush */
3830 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3831 }
3832 
3833 /*
3834  * Positions the memory window at the given address in the card's address space.
3835  * There are some alignment requirements and the actual position may be at an
3836  * address prior to the requested address.  mw->mw_curpos always has the actual
3837  * position of the window.
3838  */
3839 static void
3840 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3841 {
3842 	struct memwin *mw;
3843 	uint32_t pf;
3844 	uint32_t reg;
3845 
3846 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3847 	mw = &sc->memwin[idx];
3848 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3849 
3850 	if (is_t4(sc)) {
3851 		pf = 0;
3852 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3853 	} else {
3854 		pf = V_PFNUM(sc->pf);
3855 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3856 	}
3857 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3858 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3859 	t4_read_reg(sc, reg);	/* flush */
3860 }
3861 
3862 int
3863 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3864     int len, int rw)
3865 {
3866 	struct memwin *mw;
3867 	uint32_t mw_end, v;
3868 
3869 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3870 
3871 	/* Memory can only be accessed in naturally aligned 4 byte units */
3872 	if (addr & 3 || len & 3 || len <= 0)
3873 		return (EINVAL);
3874 
3875 	mw = &sc->memwin[idx];
3876 	while (len > 0) {
3877 		rw_rlock(&mw->mw_lock);
3878 		mw_end = mw->mw_curpos + mw->mw_aperture;
3879 		if (addr >= mw_end || addr < mw->mw_curpos) {
3880 			/* Will need to reposition the window */
3881 			if (!rw_try_upgrade(&mw->mw_lock)) {
3882 				rw_runlock(&mw->mw_lock);
3883 				rw_wlock(&mw->mw_lock);
3884 			}
3885 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3886 			position_memwin(sc, idx, addr);
3887 			rw_downgrade(&mw->mw_lock);
3888 			mw_end = mw->mw_curpos + mw->mw_aperture;
3889 		}
3890 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3891 		while (addr < mw_end && len > 0) {
3892 			if (rw == 0) {
3893 				v = t4_read_reg(sc, mw->mw_base + addr -
3894 				    mw->mw_curpos);
3895 				*val++ = le32toh(v);
3896 			} else {
3897 				v = *val++;
3898 				t4_write_reg(sc, mw->mw_base + addr -
3899 				    mw->mw_curpos, htole32(v));
3900 			}
3901 			addr += 4;
3902 			len -= 4;
3903 		}
3904 		rw_runlock(&mw->mw_lock);
3905 	}
3906 
3907 	return (0);
3908 }
3909 
3910 static void
3911 t4_init_atid_table(struct adapter *sc)
3912 {
3913 	struct tid_info *t;
3914 	int i;
3915 
3916 	t = &sc->tids;
3917 	if (t->natids == 0)
3918 		return;
3919 
3920 	MPASS(t->atid_tab == NULL);
3921 
3922 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3923 	    M_ZERO | M_WAITOK);
3924 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3925 	t->afree = t->atid_tab;
3926 	t->atids_in_use = 0;
3927 	for (i = 1; i < t->natids; i++)
3928 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3929 	t->atid_tab[t->natids - 1].next = NULL;
3930 }
3931 
3932 static void
3933 t4_free_atid_table(struct adapter *sc)
3934 {
3935 	struct tid_info *t;
3936 
3937 	t = &sc->tids;
3938 
3939 	KASSERT(t->atids_in_use == 0,
3940 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3941 
3942 	if (mtx_initialized(&t->atid_lock))
3943 		mtx_destroy(&t->atid_lock);
3944 	free(t->atid_tab, M_CXGBE);
3945 	t->atid_tab = NULL;
3946 }
3947 
3948 int
3949 alloc_atid(struct adapter *sc, void *ctx)
3950 {
3951 	struct tid_info *t = &sc->tids;
3952 	int atid = -1;
3953 
3954 	mtx_lock(&t->atid_lock);
3955 	if (t->afree) {
3956 		union aopen_entry *p = t->afree;
3957 
3958 		atid = p - t->atid_tab;
3959 		MPASS(atid <= M_TID_TID);
3960 		t->afree = p->next;
3961 		p->data = ctx;
3962 		t->atids_in_use++;
3963 	}
3964 	mtx_unlock(&t->atid_lock);
3965 	return (atid);
3966 }
3967 
3968 void *
3969 lookup_atid(struct adapter *sc, int atid)
3970 {
3971 	struct tid_info *t = &sc->tids;
3972 
3973 	return (t->atid_tab[atid].data);
3974 }
3975 
3976 void
3977 free_atid(struct adapter *sc, int atid)
3978 {
3979 	struct tid_info *t = &sc->tids;
3980 	union aopen_entry *p = &t->atid_tab[atid];
3981 
3982 	mtx_lock(&t->atid_lock);
3983 	p->next = t->afree;
3984 	t->afree = p;
3985 	t->atids_in_use--;
3986 	mtx_unlock(&t->atid_lock);
3987 }
3988 
3989 static void
3990 queue_tid_release(struct adapter *sc, int tid)
3991 {
3992 
3993 	CXGBE_UNIMPLEMENTED("deferred tid release");
3994 }
3995 
3996 void
3997 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
3998 {
3999 	struct wrqe *wr;
4000 	struct cpl_tid_release *req;
4001 
4002 	wr = alloc_wrqe(sizeof(*req), ctrlq);
4003 	if (wr == NULL) {
4004 		queue_tid_release(sc, tid);	/* defer */
4005 		return;
4006 	}
4007 	req = wrtod(wr);
4008 
4009 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
4010 
4011 	t4_wrq_tx(sc, wr);
4012 }
4013 
4014 static int
4015 t4_range_cmp(const void *a, const void *b)
4016 {
4017 	return ((const struct t4_range *)a)->start -
4018 	       ((const struct t4_range *)b)->start;
4019 }
4020 
4021 /*
4022  * Verify that the memory range specified by the addr/len pair is valid within
4023  * the card's address space.
4024  */
4025 static int
4026 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
4027 {
4028 	struct t4_range mem_ranges[4], *r, *next;
4029 	uint32_t em, addr_len;
4030 	int i, n, remaining;
4031 
4032 	/* Memory can only be accessed in naturally aligned 4 byte units */
4033 	if (addr & 3 || len & 3 || len == 0)
4034 		return (EINVAL);
4035 
4036 	/* Enabled memories */
4037 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4038 
4039 	r = &mem_ranges[0];
4040 	n = 0;
4041 	bzero(r, sizeof(mem_ranges));
4042 	if (em & F_EDRAM0_ENABLE) {
4043 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4044 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
4045 		if (r->size > 0) {
4046 			r->start = G_EDRAM0_BASE(addr_len) << 20;
4047 			if (addr >= r->start &&
4048 			    addr + len <= r->start + r->size)
4049 				return (0);
4050 			r++;
4051 			n++;
4052 		}
4053 	}
4054 	if (em & F_EDRAM1_ENABLE) {
4055 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4056 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
4057 		if (r->size > 0) {
4058 			r->start = G_EDRAM1_BASE(addr_len) << 20;
4059 			if (addr >= r->start &&
4060 			    addr + len <= r->start + r->size)
4061 				return (0);
4062 			r++;
4063 			n++;
4064 		}
4065 	}
4066 	if (em & F_EXT_MEM_ENABLE) {
4067 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4068 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
4069 		if (r->size > 0) {
4070 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
4071 			if (addr >= r->start &&
4072 			    addr + len <= r->start + r->size)
4073 				return (0);
4074 			r++;
4075 			n++;
4076 		}
4077 	}
4078 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
4079 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4080 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
4081 		if (r->size > 0) {
4082 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
4083 			if (addr >= r->start &&
4084 			    addr + len <= r->start + r->size)
4085 				return (0);
4086 			r++;
4087 			n++;
4088 		}
4089 	}
4090 	MPASS(n <= nitems(mem_ranges));
4091 
4092 	if (n > 1) {
4093 		/* Sort and merge the ranges. */
4094 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
4095 
4096 		/* Start from index 0 and examine the next n - 1 entries. */
4097 		r = &mem_ranges[0];
4098 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
4099 
4100 			MPASS(r->size > 0);	/* r is a valid entry. */
4101 			next = r + 1;
4102 			MPASS(next->size > 0);	/* and so is the next one. */
4103 
4104 			while (r->start + r->size >= next->start) {
4105 				/* Merge the next one into the current entry. */
4106 				r->size = max(r->start + r->size,
4107 				    next->start + next->size) - r->start;
4108 				n--;	/* One fewer entry in total. */
4109 				if (--remaining == 0)
4110 					goto done;	/* short circuit */
4111 				next++;
4112 			}
4113 			if (next != r + 1) {
4114 				/*
4115 				 * Some entries were merged into r and next
4116 				 * points to the first valid entry that couldn't
4117 				 * be merged.
4118 				 */
4119 				MPASS(next->size > 0);	/* must be valid */
4120 				memcpy(r + 1, next, remaining * sizeof(*r));
4121 #ifdef INVARIANTS
4122 				/*
4123 				 * This so that the foo->size assertion in the
4124 				 * next iteration of the loop do the right
4125 				 * thing for entries that were pulled up and are
4126 				 * no longer valid.
4127 				 */
4128 				MPASS(n < nitems(mem_ranges));
4129 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4130 				    sizeof(struct t4_range));
4131 #endif
4132 			}
4133 		}
4134 done:
4135 		/* Done merging the ranges. */
4136 		MPASS(n > 0);
4137 		r = &mem_ranges[0];
4138 		for (i = 0; i < n; i++, r++) {
4139 			if (addr >= r->start &&
4140 			    addr + len <= r->start + r->size)
4141 				return (0);
4142 		}
4143 	}
4144 
4145 	return (EFAULT);
4146 }
4147 
4148 static int
4149 fwmtype_to_hwmtype(int mtype)
4150 {
4151 
4152 	switch (mtype) {
4153 	case FW_MEMTYPE_EDC0:
4154 		return (MEM_EDC0);
4155 	case FW_MEMTYPE_EDC1:
4156 		return (MEM_EDC1);
4157 	case FW_MEMTYPE_EXTMEM:
4158 		return (MEM_MC0);
4159 	case FW_MEMTYPE_EXTMEM1:
4160 		return (MEM_MC1);
4161 	default:
4162 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4163 	}
4164 }
4165 
4166 /*
4167  * Verify that the memory range specified by the memtype/offset/len pair is
4168  * valid and lies entirely within the memtype specified.  The global address of
4169  * the start of the range is returned in addr.
4170  */
4171 static int
4172 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4173     uint32_t *addr)
4174 {
4175 	uint32_t em, addr_len, maddr;
4176 
4177 	/* Memory can only be accessed in naturally aligned 4 byte units */
4178 	if (off & 3 || len & 3 || len == 0)
4179 		return (EINVAL);
4180 
4181 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4182 	switch (fwmtype_to_hwmtype(mtype)) {
4183 	case MEM_EDC0:
4184 		if (!(em & F_EDRAM0_ENABLE))
4185 			return (EINVAL);
4186 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4187 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4188 		break;
4189 	case MEM_EDC1:
4190 		if (!(em & F_EDRAM1_ENABLE))
4191 			return (EINVAL);
4192 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4193 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4194 		break;
4195 	case MEM_MC:
4196 		if (!(em & F_EXT_MEM_ENABLE))
4197 			return (EINVAL);
4198 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4199 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4200 		break;
4201 	case MEM_MC1:
4202 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4203 			return (EINVAL);
4204 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4205 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4206 		break;
4207 	default:
4208 		return (EINVAL);
4209 	}
4210 
4211 	*addr = maddr + off;	/* global address */
4212 	return (validate_mem_range(sc, *addr, len));
4213 }
4214 
4215 static int
4216 fixup_devlog_params(struct adapter *sc)
4217 {
4218 	struct devlog_params *dparams = &sc->params.devlog;
4219 	int rc;
4220 
4221 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4222 	    dparams->size, &dparams->addr);
4223 
4224 	return (rc);
4225 }
4226 
4227 static void
4228 update_nirq(struct intrs_and_queues *iaq, int nports)
4229 {
4230 
4231 	iaq->nirq = T4_EXTRA_INTR;
4232 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4233 	iaq->nirq += nports * iaq->nofldrxq;
4234 	iaq->nirq += nports * (iaq->num_vis - 1) *
4235 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4236 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4237 }
4238 
4239 /*
4240  * Adjust requirements to fit the number of interrupts available.
4241  */
4242 static void
4243 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4244     int navail)
4245 {
4246 	int old_nirq;
4247 	const int nports = sc->params.nports;
4248 
4249 	MPASS(nports > 0);
4250 	MPASS(navail > 0);
4251 
4252 	bzero(iaq, sizeof(*iaq));
4253 	iaq->intr_type = itype;
4254 	iaq->num_vis = t4_num_vis;
4255 	iaq->ntxq = t4_ntxq;
4256 	iaq->ntxq_vi = t4_ntxq_vi;
4257 	iaq->nrxq = t4_nrxq;
4258 	iaq->nrxq_vi = t4_nrxq_vi;
4259 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4260 	if (is_offload(sc) || is_ethoffload(sc)) {
4261 		iaq->nofldtxq = t4_nofldtxq;
4262 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4263 	}
4264 #endif
4265 #ifdef TCP_OFFLOAD
4266 	if (is_offload(sc)) {
4267 		iaq->nofldrxq = t4_nofldrxq;
4268 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4269 	}
4270 #endif
4271 #ifdef DEV_NETMAP
4272 	if (t4_native_netmap & NN_MAIN_VI) {
4273 		iaq->nnmtxq = t4_nnmtxq;
4274 		iaq->nnmrxq = t4_nnmrxq;
4275 	}
4276 	if (t4_native_netmap & NN_EXTRA_VI) {
4277 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4278 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4279 	}
4280 #endif
4281 
4282 	update_nirq(iaq, nports);
4283 	if (iaq->nirq <= navail &&
4284 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4285 		/*
4286 		 * This is the normal case -- there are enough interrupts for
4287 		 * everything.
4288 		 */
4289 		goto done;
4290 	}
4291 
4292 	/*
4293 	 * If extra VIs have been configured try reducing their count and see if
4294 	 * that works.
4295 	 */
4296 	while (iaq->num_vis > 1) {
4297 		iaq->num_vis--;
4298 		update_nirq(iaq, nports);
4299 		if (iaq->nirq <= navail &&
4300 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4301 			device_printf(sc->dev, "virtual interfaces per port "
4302 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4303 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4304 			    "itype %d, navail %u, nirq %d.\n",
4305 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4306 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4307 			    itype, navail, iaq->nirq);
4308 			goto done;
4309 		}
4310 	}
4311 
4312 	/*
4313 	 * Extra VIs will not be created.  Log a message if they were requested.
4314 	 */
4315 	MPASS(iaq->num_vis == 1);
4316 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4317 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4318 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4319 	if (iaq->num_vis != t4_num_vis) {
4320 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4321 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4322 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4323 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4324 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4325 	}
4326 
4327 	/*
4328 	 * Keep reducing the number of NIC rx queues to the next lower power of
4329 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4330 	 * if that works.
4331 	 */
4332 	do {
4333 		if (iaq->nrxq > 1) {
4334 			do {
4335 				iaq->nrxq--;
4336 			} while (!powerof2(iaq->nrxq));
4337 			if (iaq->nnmrxq > iaq->nrxq)
4338 				iaq->nnmrxq = iaq->nrxq;
4339 		}
4340 		if (iaq->nofldrxq > 1)
4341 			iaq->nofldrxq >>= 1;
4342 
4343 		old_nirq = iaq->nirq;
4344 		update_nirq(iaq, nports);
4345 		if (iaq->nirq <= navail &&
4346 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4347 			device_printf(sc->dev, "running with reduced number of "
4348 			    "rx queues because of shortage of interrupts.  "
4349 			    "nrxq=%u, nofldrxq=%u.  "
4350 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4351 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4352 			goto done;
4353 		}
4354 	} while (old_nirq != iaq->nirq);
4355 
4356 	/* One interrupt for everything.  Ugh. */
4357 	device_printf(sc->dev, "running with minimal number of queues.  "
4358 	    "itype %d, navail %u.\n", itype, navail);
4359 	iaq->nirq = 1;
4360 	iaq->nrxq = 1;
4361 	iaq->ntxq = 1;
4362 	if (iaq->nofldrxq > 0) {
4363 		iaq->nofldrxq = 1;
4364 		iaq->nofldtxq = 1;
4365 	}
4366 	iaq->nnmtxq = 0;
4367 	iaq->nnmrxq = 0;
4368 done:
4369 	MPASS(iaq->num_vis > 0);
4370 	if (iaq->num_vis > 1) {
4371 		MPASS(iaq->nrxq_vi > 0);
4372 		MPASS(iaq->ntxq_vi > 0);
4373 	}
4374 	MPASS(iaq->nirq > 0);
4375 	MPASS(iaq->nrxq > 0);
4376 	MPASS(iaq->ntxq > 0);
4377 	if (itype == INTR_MSI) {
4378 		MPASS(powerof2(iaq->nirq));
4379 	}
4380 }
4381 
4382 static int
4383 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4384 {
4385 	int rc, itype, navail, nalloc;
4386 
4387 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4388 
4389 		if ((itype & t4_intr_types) == 0)
4390 			continue;	/* not allowed */
4391 
4392 		if (itype == INTR_MSIX)
4393 			navail = pci_msix_count(sc->dev);
4394 		else if (itype == INTR_MSI)
4395 			navail = pci_msi_count(sc->dev);
4396 		else
4397 			navail = 1;
4398 restart:
4399 		if (navail == 0)
4400 			continue;
4401 
4402 		calculate_iaq(sc, iaq, itype, navail);
4403 		nalloc = iaq->nirq;
4404 		rc = 0;
4405 		if (itype == INTR_MSIX)
4406 			rc = pci_alloc_msix(sc->dev, &nalloc);
4407 		else if (itype == INTR_MSI)
4408 			rc = pci_alloc_msi(sc->dev, &nalloc);
4409 
4410 		if (rc == 0 && nalloc > 0) {
4411 			if (nalloc == iaq->nirq)
4412 				return (0);
4413 
4414 			/*
4415 			 * Didn't get the number requested.  Use whatever number
4416 			 * the kernel is willing to allocate.
4417 			 */
4418 			device_printf(sc->dev, "fewer vectors than requested, "
4419 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4420 			    itype, iaq->nirq, nalloc);
4421 			pci_release_msi(sc->dev);
4422 			navail = nalloc;
4423 			goto restart;
4424 		}
4425 
4426 		device_printf(sc->dev,
4427 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4428 		    itype, rc, iaq->nirq, nalloc);
4429 	}
4430 
4431 	device_printf(sc->dev,
4432 	    "failed to find a usable interrupt type.  "
4433 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4434 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4435 
4436 	return (ENXIO);
4437 }
4438 
4439 #define FW_VERSION(chip) ( \
4440     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4441     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4442     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4443     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4444 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4445 
4446 /* Just enough of fw_hdr to cover all version info. */
4447 struct fw_h {
4448 	__u8	ver;
4449 	__u8	chip;
4450 	__be16	len512;
4451 	__be32	fw_ver;
4452 	__be32	tp_microcode_ver;
4453 	__u8	intfver_nic;
4454 	__u8	intfver_vnic;
4455 	__u8	intfver_ofld;
4456 	__u8	intfver_ri;
4457 	__u8	intfver_iscsipdu;
4458 	__u8	intfver_iscsi;
4459 	__u8	intfver_fcoepdu;
4460 	__u8	intfver_fcoe;
4461 };
4462 /* Spot check a couple of fields. */
4463 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4464 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4465 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4466 
4467 struct fw_info {
4468 	uint8_t chip;
4469 	char *kld_name;
4470 	char *fw_mod_name;
4471 	struct fw_h fw_h;
4472 } fw_info[] = {
4473 	{
4474 		.chip = CHELSIO_T4,
4475 		.kld_name = "t4fw_cfg",
4476 		.fw_mod_name = "t4fw",
4477 		.fw_h = {
4478 			.chip = FW_HDR_CHIP_T4,
4479 			.fw_ver = htobe32(FW_VERSION(T4)),
4480 			.intfver_nic = FW_INTFVER(T4, NIC),
4481 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4482 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4483 			.intfver_ri = FW_INTFVER(T4, RI),
4484 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4485 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4486 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4487 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4488 		},
4489 	}, {
4490 		.chip = CHELSIO_T5,
4491 		.kld_name = "t5fw_cfg",
4492 		.fw_mod_name = "t5fw",
4493 		.fw_h = {
4494 			.chip = FW_HDR_CHIP_T5,
4495 			.fw_ver = htobe32(FW_VERSION(T5)),
4496 			.intfver_nic = FW_INTFVER(T5, NIC),
4497 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4498 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4499 			.intfver_ri = FW_INTFVER(T5, RI),
4500 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4501 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4502 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4503 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4504 		},
4505 	}, {
4506 		.chip = CHELSIO_T6,
4507 		.kld_name = "t6fw_cfg",
4508 		.fw_mod_name = "t6fw",
4509 		.fw_h = {
4510 			.chip = FW_HDR_CHIP_T6,
4511 			.fw_ver = htobe32(FW_VERSION(T6)),
4512 			.intfver_nic = FW_INTFVER(T6, NIC),
4513 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4514 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4515 			.intfver_ri = FW_INTFVER(T6, RI),
4516 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4517 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4518 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4519 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4520 		},
4521 	}
4522 };
4523 
4524 static struct fw_info *
4525 find_fw_info(int chip)
4526 {
4527 	int i;
4528 
4529 	for (i = 0; i < nitems(fw_info); i++) {
4530 		if (fw_info[i].chip == chip)
4531 			return (&fw_info[i]);
4532 	}
4533 	return (NULL);
4534 }
4535 
4536 /*
4537  * Is the given firmware API compatible with the one the driver was compiled
4538  * with?
4539  */
4540 static int
4541 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4542 {
4543 
4544 	/* short circuit if it's the exact same firmware version */
4545 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4546 		return (1);
4547 
4548 	/*
4549 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4550 	 * features that are supported in the driver.
4551 	 */
4552 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4553 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4554 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4555 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4556 		return (1);
4557 #undef SAME_INTF
4558 
4559 	return (0);
4560 }
4561 
4562 static int
4563 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4564     const struct firmware **fw)
4565 {
4566 	struct fw_info *fw_info;
4567 
4568 	*dcfg = NULL;
4569 	if (fw != NULL)
4570 		*fw = NULL;
4571 
4572 	fw_info = find_fw_info(chip_id(sc));
4573 	if (fw_info == NULL) {
4574 		device_printf(sc->dev,
4575 		    "unable to look up firmware information for chip %d.\n",
4576 		    chip_id(sc));
4577 		return (EINVAL);
4578 	}
4579 
4580 	*dcfg = firmware_get(fw_info->kld_name);
4581 	if (*dcfg != NULL) {
4582 		if (fw != NULL)
4583 			*fw = firmware_get(fw_info->fw_mod_name);
4584 		return (0);
4585 	}
4586 
4587 	return (ENOENT);
4588 }
4589 
4590 static void
4591 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4592     const struct firmware *fw)
4593 {
4594 
4595 	if (fw != NULL)
4596 		firmware_put(fw, FIRMWARE_UNLOAD);
4597 	if (dcfg != NULL)
4598 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4599 }
4600 
4601 /*
4602  * Return values:
4603  * 0 means no firmware install attempted.
4604  * ERESTART means a firmware install was attempted and was successful.
4605  * +ve errno means a firmware install was attempted but failed.
4606  */
4607 static int
4608 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4609     const struct fw_h *drv_fw, const char *reason, int *already)
4610 {
4611 	const struct firmware *cfg, *fw;
4612 	const uint32_t c = be32toh(card_fw->fw_ver);
4613 	uint32_t d, k;
4614 	int rc, fw_install;
4615 	struct fw_h bundled_fw;
4616 	bool load_attempted;
4617 
4618 	cfg = fw = NULL;
4619 	load_attempted = false;
4620 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4621 
4622 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4623 	if (t4_fw_install < 0) {
4624 		rc = load_fw_module(sc, &cfg, &fw);
4625 		if (rc != 0 || fw == NULL) {
4626 			device_printf(sc->dev,
4627 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4628 			    " will use compiled-in firmware version for"
4629 			    "hw.cxgbe.fw_install checks.\n",
4630 			    rc, cfg, fw);
4631 		} else {
4632 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4633 		}
4634 		load_attempted = true;
4635 	}
4636 	d = be32toh(bundled_fw.fw_ver);
4637 
4638 	if (reason != NULL)
4639 		goto install;
4640 
4641 	if ((sc->flags & FW_OK) == 0) {
4642 
4643 		if (c == 0xffffffff) {
4644 			reason = "missing";
4645 			goto install;
4646 		}
4647 
4648 		rc = 0;
4649 		goto done;
4650 	}
4651 
4652 	if (!fw_compatible(card_fw, &bundled_fw)) {
4653 		reason = "incompatible or unusable";
4654 		goto install;
4655 	}
4656 
4657 	if (d > c) {
4658 		reason = "older than the version bundled with this driver";
4659 		goto install;
4660 	}
4661 
4662 	if (fw_install == 2 && d != c) {
4663 		reason = "different than the version bundled with this driver";
4664 		goto install;
4665 	}
4666 
4667 	/* No reason to do anything to the firmware already on the card. */
4668 	rc = 0;
4669 	goto done;
4670 
4671 install:
4672 	rc = 0;
4673 	if ((*already)++)
4674 		goto done;
4675 
4676 	if (fw_install == 0) {
4677 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4678 		    "but the driver is prohibited from installing a firmware "
4679 		    "on the card.\n",
4680 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4681 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4682 
4683 		goto done;
4684 	}
4685 
4686 	/*
4687 	 * We'll attempt to install a firmware.  Load the module first (if it
4688 	 * hasn't been loaded already).
4689 	 */
4690 	if (!load_attempted) {
4691 		rc = load_fw_module(sc, &cfg, &fw);
4692 		if (rc != 0 || fw == NULL) {
4693 			device_printf(sc->dev,
4694 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4695 			    rc, cfg, fw);
4696 			/* carry on */
4697 		}
4698 	}
4699 	if (fw == NULL) {
4700 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4701 		    "but the driver cannot take corrective action because it "
4702 		    "is unable to load the firmware module.\n",
4703 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4704 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4705 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4706 		goto done;
4707 	}
4708 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4709 	if (k != d) {
4710 		MPASS(t4_fw_install > 0);
4711 		device_printf(sc->dev,
4712 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4713 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4714 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4715 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4716 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4717 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4718 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4719 		goto done;
4720 	}
4721 
4722 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4723 	    "installing firmware %u.%u.%u.%u on card.\n",
4724 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4725 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4726 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4727 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4728 
4729 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4730 	if (rc != 0) {
4731 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4732 	} else {
4733 		/* Installed successfully, update the cached header too. */
4734 		rc = ERESTART;
4735 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4736 	}
4737 done:
4738 	unload_fw_module(sc, cfg, fw);
4739 
4740 	return (rc);
4741 }
4742 
4743 /*
4744  * Establish contact with the firmware and attempt to become the master driver.
4745  *
4746  * A firmware will be installed to the card if needed (if the driver is allowed
4747  * to do so).
4748  */
4749 static int
4750 contact_firmware(struct adapter *sc)
4751 {
4752 	int rc, already = 0;
4753 	enum dev_state state;
4754 	struct fw_info *fw_info;
4755 	struct fw_hdr *card_fw;		/* fw on the card */
4756 	const struct fw_h *drv_fw;
4757 
4758 	fw_info = find_fw_info(chip_id(sc));
4759 	if (fw_info == NULL) {
4760 		device_printf(sc->dev,
4761 		    "unable to look up firmware information for chip %d.\n",
4762 		    chip_id(sc));
4763 		return (EINVAL);
4764 	}
4765 	drv_fw = &fw_info->fw_h;
4766 
4767 	/* Read the header of the firmware on the card */
4768 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4769 restart:
4770 	rc = -t4_get_fw_hdr(sc, card_fw);
4771 	if (rc != 0) {
4772 		device_printf(sc->dev,
4773 		    "unable to read firmware header from card's flash: %d\n",
4774 		    rc);
4775 		goto done;
4776 	}
4777 
4778 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4779 	    &already);
4780 	if (rc == ERESTART)
4781 		goto restart;
4782 	if (rc != 0)
4783 		goto done;
4784 
4785 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4786 	if (rc < 0 || state == DEV_STATE_ERR) {
4787 		rc = -rc;
4788 		device_printf(sc->dev,
4789 		    "failed to connect to the firmware: %d, %d.  "
4790 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4791 #if 0
4792 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4793 		    "not responding properly to HELLO", &already) == ERESTART)
4794 			goto restart;
4795 #endif
4796 		goto done;
4797 	}
4798 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4799 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4800 
4801 	if (rc == sc->pf) {
4802 		sc->flags |= MASTER_PF;
4803 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4804 		    NULL, &already);
4805 		if (rc == ERESTART)
4806 			rc = 0;
4807 		else if (rc != 0)
4808 			goto done;
4809 	} else if (state == DEV_STATE_UNINIT) {
4810 		/*
4811 		 * We didn't get to be the master so we definitely won't be
4812 		 * configuring the chip.  It's a bug if someone else hasn't
4813 		 * configured it already.
4814 		 */
4815 		device_printf(sc->dev, "couldn't be master(%d), "
4816 		    "device not already initialized either(%d).  "
4817 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4818 		rc = EPROTO;
4819 		goto done;
4820 	} else {
4821 		/*
4822 		 * Some other PF is the master and has configured the chip.
4823 		 * This is allowed but untested.
4824 		 */
4825 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4826 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4827 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4828 		sc->cfcsum = 0;
4829 		rc = 0;
4830 	}
4831 done:
4832 	if (rc != 0 && sc->flags & FW_OK) {
4833 		t4_fw_bye(sc, sc->mbox);
4834 		sc->flags &= ~FW_OK;
4835 	}
4836 	free(card_fw, M_CXGBE);
4837 	return (rc);
4838 }
4839 
4840 static int
4841 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4842     uint32_t mtype, uint32_t moff)
4843 {
4844 	struct fw_info *fw_info;
4845 	const struct firmware *dcfg, *rcfg = NULL;
4846 	const uint32_t *cfdata;
4847 	uint32_t cflen, addr;
4848 	int rc;
4849 
4850 	load_fw_module(sc, &dcfg, NULL);
4851 
4852 	/* Card specific interpretation of "default". */
4853 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4854 		if (pci_get_device(sc->dev) == 0x440a)
4855 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4856 		if (is_fpga(sc))
4857 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4858 	}
4859 
4860 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4861 		if (dcfg == NULL) {
4862 			device_printf(sc->dev,
4863 			    "KLD with default config is not available.\n");
4864 			rc = ENOENT;
4865 			goto done;
4866 		}
4867 		cfdata = dcfg->data;
4868 		cflen = dcfg->datasize & ~3;
4869 	} else {
4870 		char s[32];
4871 
4872 		fw_info = find_fw_info(chip_id(sc));
4873 		if (fw_info == NULL) {
4874 			device_printf(sc->dev,
4875 			    "unable to look up firmware information for chip %d.\n",
4876 			    chip_id(sc));
4877 			rc = EINVAL;
4878 			goto done;
4879 		}
4880 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4881 
4882 		rcfg = firmware_get(s);
4883 		if (rcfg == NULL) {
4884 			device_printf(sc->dev,
4885 			    "unable to load module \"%s\" for configuration "
4886 			    "profile \"%s\".\n", s, cfg_file);
4887 			rc = ENOENT;
4888 			goto done;
4889 		}
4890 		cfdata = rcfg->data;
4891 		cflen = rcfg->datasize & ~3;
4892 	}
4893 
4894 	if (cflen > FLASH_CFG_MAX_SIZE) {
4895 		device_printf(sc->dev,
4896 		    "config file too long (%d, max allowed is %d).\n",
4897 		    cflen, FLASH_CFG_MAX_SIZE);
4898 		rc = EINVAL;
4899 		goto done;
4900 	}
4901 
4902 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4903 	if (rc != 0) {
4904 		device_printf(sc->dev,
4905 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4906 		    __func__, mtype, moff, cflen, rc);
4907 		rc = EINVAL;
4908 		goto done;
4909 	}
4910 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4911 done:
4912 	if (rcfg != NULL)
4913 		firmware_put(rcfg, FIRMWARE_UNLOAD);
4914 	unload_fw_module(sc, dcfg, NULL);
4915 	return (rc);
4916 }
4917 
4918 struct caps_allowed {
4919 	uint16_t nbmcaps;
4920 	uint16_t linkcaps;
4921 	uint16_t switchcaps;
4922 	uint16_t niccaps;
4923 	uint16_t toecaps;
4924 	uint16_t rdmacaps;
4925 	uint16_t cryptocaps;
4926 	uint16_t iscsicaps;
4927 	uint16_t fcoecaps;
4928 };
4929 
4930 #define FW_PARAM_DEV(param) \
4931 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4932 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4933 #define FW_PARAM_PFVF(param) \
4934 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4935 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4936 
4937 /*
4938  * Provide a configuration profile to the firmware and have it initialize the
4939  * chip accordingly.  This may involve uploading a configuration file to the
4940  * card.
4941  */
4942 static int
4943 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4944     const struct caps_allowed *caps_allowed)
4945 {
4946 	int rc;
4947 	struct fw_caps_config_cmd caps;
4948 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
4949 
4950 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4951 	if (rc != 0) {
4952 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
4953 		return (rc);
4954 	}
4955 
4956 	bzero(&caps, sizeof(caps));
4957 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4958 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
4959 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
4960 		mtype = 0;
4961 		moff = 0;
4962 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4963 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
4964 		mtype = FW_MEMTYPE_FLASH;
4965 		moff = t4_flash_cfg_addr(sc);
4966 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4967 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4968 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4969 		    FW_LEN16(caps));
4970 	} else {
4971 		/*
4972 		 * Ask the firmware where it wants us to upload the config file.
4973 		 */
4974 		param = FW_PARAM_DEV(CF);
4975 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4976 		if (rc != 0) {
4977 			/* No support for config file?  Shouldn't happen. */
4978 			device_printf(sc->dev,
4979 			    "failed to query config file location: %d.\n", rc);
4980 			goto done;
4981 		}
4982 		mtype = G_FW_PARAMS_PARAM_Y(val);
4983 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
4984 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4985 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4986 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4987 		    FW_LEN16(caps));
4988 
4989 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
4990 		if (rc != 0) {
4991 			device_printf(sc->dev,
4992 			    "failed to upload config file to card: %d.\n", rc);
4993 			goto done;
4994 		}
4995 	}
4996 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
4997 	if (rc != 0) {
4998 		device_printf(sc->dev, "failed to pre-process config file: %d "
4999 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
5000 		goto done;
5001 	}
5002 
5003 	finicsum = be32toh(caps.finicsum);
5004 	cfcsum = be32toh(caps.cfcsum);	/* actual */
5005 	if (finicsum != cfcsum) {
5006 		device_printf(sc->dev,
5007 		    "WARNING: config file checksum mismatch: %08x %08x\n",
5008 		    finicsum, cfcsum);
5009 	}
5010 	sc->cfcsum = cfcsum;
5011 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
5012 
5013 	/*
5014 	 * Let the firmware know what features will (not) be used so it can tune
5015 	 * things accordingly.
5016 	 */
5017 #define LIMIT_CAPS(x) do { \
5018 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
5019 } while (0)
5020 	LIMIT_CAPS(nbm);
5021 	LIMIT_CAPS(link);
5022 	LIMIT_CAPS(switch);
5023 	LIMIT_CAPS(nic);
5024 	LIMIT_CAPS(toe);
5025 	LIMIT_CAPS(rdma);
5026 	LIMIT_CAPS(crypto);
5027 	LIMIT_CAPS(iscsi);
5028 	LIMIT_CAPS(fcoe);
5029 #undef LIMIT_CAPS
5030 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
5031 		/*
5032 		 * TOE and hashfilters are mutually exclusive.  It is a config
5033 		 * file or firmware bug if both are reported as available.  Try
5034 		 * to cope with the situation in non-debug builds by disabling
5035 		 * TOE.
5036 		 */
5037 		MPASS(caps.toecaps == 0);
5038 
5039 		caps.toecaps = 0;
5040 		caps.rdmacaps = 0;
5041 		caps.iscsicaps = 0;
5042 	}
5043 
5044 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5045 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
5046 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5047 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
5048 	if (rc != 0) {
5049 		device_printf(sc->dev,
5050 		    "failed to process config file: %d.\n", rc);
5051 		goto done;
5052 	}
5053 
5054 	t4_tweak_chip_settings(sc);
5055 	set_params__pre_init(sc);
5056 
5057 	/* get basic stuff going */
5058 	rc = -t4_fw_initialize(sc, sc->mbox);
5059 	if (rc != 0) {
5060 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
5061 		goto done;
5062 	}
5063 done:
5064 	return (rc);
5065 }
5066 
5067 /*
5068  * Partition chip resources for use between various PFs, VFs, etc.
5069  */
5070 static int
5071 partition_resources(struct adapter *sc)
5072 {
5073 	char cfg_file[sizeof(t4_cfg_file)];
5074 	struct caps_allowed caps_allowed;
5075 	int rc;
5076 	bool fallback;
5077 
5078 	/* Only the master driver gets to configure the chip resources. */
5079 	MPASS(sc->flags & MASTER_PF);
5080 
5081 #define COPY_CAPS(x) do { \
5082 	caps_allowed.x##caps = t4_##x##caps_allowed; \
5083 } while (0)
5084 	bzero(&caps_allowed, sizeof(caps_allowed));
5085 	COPY_CAPS(nbm);
5086 	COPY_CAPS(link);
5087 	COPY_CAPS(switch);
5088 	COPY_CAPS(nic);
5089 	COPY_CAPS(toe);
5090 	COPY_CAPS(rdma);
5091 	COPY_CAPS(crypto);
5092 	COPY_CAPS(iscsi);
5093 	COPY_CAPS(fcoe);
5094 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
5095 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
5096 retry:
5097 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
5098 	if (rc != 0 && fallback) {
5099 		dump_devlog(sc);
5100 		device_printf(sc->dev,
5101 		    "failed (%d) to configure card with \"%s\" profile, "
5102 		    "will fall back to a basic configuration and retry.\n",
5103 		    rc, cfg_file);
5104 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
5105 		bzero(&caps_allowed, sizeof(caps_allowed));
5106 		COPY_CAPS(switch);
5107 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
5108 		fallback = false;
5109 		goto retry;
5110 	}
5111 #undef COPY_CAPS
5112 	return (rc);
5113 }
5114 
5115 /*
5116  * Retrieve parameters that are needed (or nice to have) very early.
5117  */
5118 static int
5119 get_params__pre_init(struct adapter *sc)
5120 {
5121 	int rc;
5122 	uint32_t param[2], val[2];
5123 
5124 	t4_get_version_info(sc);
5125 
5126 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5127 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5128 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5129 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5130 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5131 
5132 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5133 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5134 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5135 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5136 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5137 
5138 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5139 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5140 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5141 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5142 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5143 
5144 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5145 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5146 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5147 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5148 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5149 
5150 	param[0] = FW_PARAM_DEV(PORTVEC);
5151 	param[1] = FW_PARAM_DEV(CCLK);
5152 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5153 	if (rc != 0) {
5154 		device_printf(sc->dev,
5155 		    "failed to query parameters (pre_init): %d.\n", rc);
5156 		return (rc);
5157 	}
5158 
5159 	sc->params.portvec = val[0];
5160 	sc->params.nports = bitcount32(val[0]);
5161 	sc->params.vpd.cclk = val[1];
5162 
5163 	/* Read device log parameters. */
5164 	rc = -t4_init_devlog_params(sc, 1);
5165 	if (rc == 0)
5166 		fixup_devlog_params(sc);
5167 	else {
5168 		device_printf(sc->dev,
5169 		    "failed to get devlog parameters: %d.\n", rc);
5170 		rc = 0;	/* devlog isn't critical for device operation */
5171 	}
5172 
5173 	return (rc);
5174 }
5175 
5176 /*
5177  * Any params that need to be set before FW_INITIALIZE.
5178  */
5179 static int
5180 set_params__pre_init(struct adapter *sc)
5181 {
5182 	int rc = 0;
5183 	uint32_t param, val;
5184 
5185 	if (chip_id(sc) >= CHELSIO_T6) {
5186 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5187 		val = 1;
5188 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5189 		/* firmwares < 1.20.1.0 do not have this param. */
5190 		if (rc == FW_EINVAL &&
5191 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5192 			rc = 0;
5193 		}
5194 		if (rc != 0) {
5195 			device_printf(sc->dev,
5196 			    "failed to enable high priority filters :%d.\n",
5197 			    rc);
5198 		}
5199 
5200 		param = FW_PARAM_DEV(PPOD_EDRAM);
5201 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5202 		if (rc == 0 && val == 1) {
5203 			rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param,
5204 			    &val);
5205 			if (rc != 0) {
5206 				device_printf(sc->dev,
5207 				    "failed to set PPOD_EDRAM: %d.\n", rc);
5208 			}
5209 		}
5210 	}
5211 
5212 	/* Enable opaque VIIDs with firmwares that support it. */
5213 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5214 	val = 1;
5215 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5216 	if (rc == 0 && val == 1)
5217 		sc->params.viid_smt_extn_support = true;
5218 	else
5219 		sc->params.viid_smt_extn_support = false;
5220 
5221 	return (rc);
5222 }
5223 
5224 /*
5225  * Retrieve various parameters that are of interest to the driver.  The device
5226  * has been initialized by the firmware at this point.
5227  */
5228 static int
5229 get_params__post_init(struct adapter *sc)
5230 {
5231 	int rc;
5232 	uint32_t param[7], val[7];
5233 	struct fw_caps_config_cmd caps;
5234 
5235 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5236 	param[1] = FW_PARAM_PFVF(EQ_START);
5237 	param[2] = FW_PARAM_PFVF(FILTER_START);
5238 	param[3] = FW_PARAM_PFVF(FILTER_END);
5239 	param[4] = FW_PARAM_PFVF(L2T_START);
5240 	param[5] = FW_PARAM_PFVF(L2T_END);
5241 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5242 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5243 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5244 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5245 	if (rc != 0) {
5246 		device_printf(sc->dev,
5247 		    "failed to query parameters (post_init): %d.\n", rc);
5248 		return (rc);
5249 	}
5250 
5251 	sc->sge.iq_start = val[0];
5252 	sc->sge.eq_start = val[1];
5253 	if ((int)val[3] > (int)val[2]) {
5254 		sc->tids.ftid_base = val[2];
5255 		sc->tids.ftid_end = val[3];
5256 		sc->tids.nftids = val[3] - val[2] + 1;
5257 	}
5258 	sc->vres.l2t.start = val[4];
5259 	sc->vres.l2t.size = val[5] - val[4] + 1;
5260 	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
5261 	    ("%s: L2 table size (%u) larger than expected (%u)",
5262 	    __func__, sc->vres.l2t.size, L2T_SIZE));
5263 	sc->params.core_vdd = val[6];
5264 
5265 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5266 	param[1] = FW_PARAM_PFVF(EQ_END);
5267 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5268 	if (rc != 0) {
5269 		device_printf(sc->dev,
5270 		    "failed to query parameters (post_init2): %d.\n", rc);
5271 		return (rc);
5272 	}
5273 	MPASS((int)val[0] >= sc->sge.iq_start);
5274 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5275 	MPASS((int)val[1] >= sc->sge.eq_start);
5276 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5277 
5278 	if (chip_id(sc) >= CHELSIO_T6) {
5279 
5280 		sc->tids.tid_base = t4_read_reg(sc,
5281 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5282 
5283 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5284 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5285 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5286 		if (rc != 0) {
5287 			device_printf(sc->dev,
5288 			   "failed to query hpfilter parameters: %d.\n", rc);
5289 			return (rc);
5290 		}
5291 		if ((int)val[1] > (int)val[0]) {
5292 			sc->tids.hpftid_base = val[0];
5293 			sc->tids.hpftid_end = val[1];
5294 			sc->tids.nhpftids = val[1] - val[0] + 1;
5295 
5296 			/*
5297 			 * These should go off if the layout changes and the
5298 			 * driver needs to catch up.
5299 			 */
5300 			MPASS(sc->tids.hpftid_base == 0);
5301 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5302 		}
5303 
5304 		param[0] = FW_PARAM_PFVF(RAWF_START);
5305 		param[1] = FW_PARAM_PFVF(RAWF_END);
5306 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5307 		if (rc != 0) {
5308 			device_printf(sc->dev,
5309 			   "failed to query rawf parameters: %d.\n", rc);
5310 			return (rc);
5311 		}
5312 		if ((int)val[1] > (int)val[0]) {
5313 			sc->rawf_base = val[0];
5314 			sc->nrawf = val[1] - val[0] + 1;
5315 		}
5316 	}
5317 
5318 	/*
5319 	 * MPSBGMAP is queried separately because only recent firmwares support
5320 	 * it as a parameter and we don't want the compound query above to fail
5321 	 * on older firmwares.
5322 	 */
5323 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5324 	val[0] = 0;
5325 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5326 	if (rc == 0)
5327 		sc->params.mps_bg_map = val[0];
5328 	else
5329 		sc->params.mps_bg_map = 0;
5330 
5331 	/*
5332 	 * Determine whether the firmware supports the filter2 work request.
5333 	 * This is queried separately for the same reason as MPSBGMAP above.
5334 	 */
5335 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5336 	val[0] = 0;
5337 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5338 	if (rc == 0)
5339 		sc->params.filter2_wr_support = val[0] != 0;
5340 	else
5341 		sc->params.filter2_wr_support = 0;
5342 
5343 	/*
5344 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5345 	 * This is queried separately for the same reason as other params above.
5346 	 */
5347 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5348 	val[0] = 0;
5349 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5350 	if (rc == 0)
5351 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5352 	else
5353 		sc->params.ulptx_memwrite_dsgl = false;
5354 
5355 	/* FW_RI_FR_NSMR_TPTE_WR support */
5356 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5357 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5358 	if (rc == 0)
5359 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5360 	else
5361 		sc->params.fr_nsmr_tpte_wr_support = false;
5362 
5363 	/* Support for 512 SGL entries per FR MR. */
5364 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5365 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5366 	if (rc == 0)
5367 		sc->params.dev_512sgl_mr = val[0] != 0;
5368 	else
5369 		sc->params.dev_512sgl_mr = false;
5370 
5371 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5372 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5373 	if (rc == 0)
5374 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5375 	else
5376 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5377 
5378 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5379 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5380 	if (rc == 0) {
5381 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5382 		sc->params.nsched_cls = val[0];
5383 	} else
5384 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5385 
5386 	/* get capabilites */
5387 	bzero(&caps, sizeof(caps));
5388 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5389 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5390 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5391 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5392 	if (rc != 0) {
5393 		device_printf(sc->dev,
5394 		    "failed to get card capabilities: %d.\n", rc);
5395 		return (rc);
5396 	}
5397 
5398 #define READ_CAPS(x) do { \
5399 	sc->x = htobe16(caps.x); \
5400 } while (0)
5401 	READ_CAPS(nbmcaps);
5402 	READ_CAPS(linkcaps);
5403 	READ_CAPS(switchcaps);
5404 	READ_CAPS(niccaps);
5405 	READ_CAPS(toecaps);
5406 	READ_CAPS(rdmacaps);
5407 	READ_CAPS(cryptocaps);
5408 	READ_CAPS(iscsicaps);
5409 	READ_CAPS(fcoecaps);
5410 
5411 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5412 		MPASS(chip_id(sc) > CHELSIO_T4);
5413 		MPASS(sc->toecaps == 0);
5414 		sc->toecaps = 0;
5415 
5416 		param[0] = FW_PARAM_DEV(NTID);
5417 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5418 		if (rc != 0) {
5419 			device_printf(sc->dev,
5420 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5421 			return (rc);
5422 		}
5423 		sc->tids.ntids = val[0];
5424 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5425 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5426 			sc->tids.ntids -= sc->tids.nhpftids;
5427 		}
5428 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5429 		sc->params.hash_filter = 1;
5430 	}
5431 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5432 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5433 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5434 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5435 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5436 		if (rc != 0) {
5437 			device_printf(sc->dev,
5438 			    "failed to query NIC parameters: %d.\n", rc);
5439 			return (rc);
5440 		}
5441 		if ((int)val[1] > (int)val[0]) {
5442 			sc->tids.etid_base = val[0];
5443 			sc->tids.etid_end = val[1];
5444 			sc->tids.netids = val[1] - val[0] + 1;
5445 			sc->params.eo_wr_cred = val[2];
5446 			sc->params.ethoffload = 1;
5447 		}
5448 	}
5449 	if (sc->toecaps) {
5450 		/* query offload-related parameters */
5451 		param[0] = FW_PARAM_DEV(NTID);
5452 		param[1] = FW_PARAM_PFVF(SERVER_START);
5453 		param[2] = FW_PARAM_PFVF(SERVER_END);
5454 		param[3] = FW_PARAM_PFVF(TDDP_START);
5455 		param[4] = FW_PARAM_PFVF(TDDP_END);
5456 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5457 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5458 		if (rc != 0) {
5459 			device_printf(sc->dev,
5460 			    "failed to query TOE parameters: %d.\n", rc);
5461 			return (rc);
5462 		}
5463 		sc->tids.ntids = val[0];
5464 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5465 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5466 			sc->tids.ntids -= sc->tids.nhpftids;
5467 		}
5468 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5469 		if ((int)val[2] > (int)val[1]) {
5470 			sc->tids.stid_base = val[1];
5471 			sc->tids.nstids = val[2] - val[1] + 1;
5472 		}
5473 		sc->vres.ddp.start = val[3];
5474 		sc->vres.ddp.size = val[4] - val[3] + 1;
5475 		sc->params.ofldq_wr_cred = val[5];
5476 		sc->params.offload = 1;
5477 	} else {
5478 		/*
5479 		 * The firmware attempts memfree TOE configuration for -SO cards
5480 		 * and will report toecaps=0 if it runs out of resources (this
5481 		 * depends on the config file).  It may not report 0 for other
5482 		 * capabilities dependent on the TOE in this case.  Set them to
5483 		 * 0 here so that the driver doesn't bother tracking resources
5484 		 * that will never be used.
5485 		 */
5486 		sc->iscsicaps = 0;
5487 		sc->rdmacaps = 0;
5488 	}
5489 	if (sc->rdmacaps) {
5490 		param[0] = FW_PARAM_PFVF(STAG_START);
5491 		param[1] = FW_PARAM_PFVF(STAG_END);
5492 		param[2] = FW_PARAM_PFVF(RQ_START);
5493 		param[3] = FW_PARAM_PFVF(RQ_END);
5494 		param[4] = FW_PARAM_PFVF(PBL_START);
5495 		param[5] = FW_PARAM_PFVF(PBL_END);
5496 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5497 		if (rc != 0) {
5498 			device_printf(sc->dev,
5499 			    "failed to query RDMA parameters(1): %d.\n", rc);
5500 			return (rc);
5501 		}
5502 		sc->vres.stag.start = val[0];
5503 		sc->vres.stag.size = val[1] - val[0] + 1;
5504 		sc->vres.rq.start = val[2];
5505 		sc->vres.rq.size = val[3] - val[2] + 1;
5506 		sc->vres.pbl.start = val[4];
5507 		sc->vres.pbl.size = val[5] - val[4] + 1;
5508 
5509 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5510 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5511 		param[2] = FW_PARAM_PFVF(CQ_START);
5512 		param[3] = FW_PARAM_PFVF(CQ_END);
5513 		param[4] = FW_PARAM_PFVF(OCQ_START);
5514 		param[5] = FW_PARAM_PFVF(OCQ_END);
5515 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5516 		if (rc != 0) {
5517 			device_printf(sc->dev,
5518 			    "failed to query RDMA parameters(2): %d.\n", rc);
5519 			return (rc);
5520 		}
5521 		sc->vres.qp.start = val[0];
5522 		sc->vres.qp.size = val[1] - val[0] + 1;
5523 		sc->vres.cq.start = val[2];
5524 		sc->vres.cq.size = val[3] - val[2] + 1;
5525 		sc->vres.ocq.start = val[4];
5526 		sc->vres.ocq.size = val[5] - val[4] + 1;
5527 
5528 		param[0] = FW_PARAM_PFVF(SRQ_START);
5529 		param[1] = FW_PARAM_PFVF(SRQ_END);
5530 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5531 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5532 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5533 		if (rc != 0) {
5534 			device_printf(sc->dev,
5535 			    "failed to query RDMA parameters(3): %d.\n", rc);
5536 			return (rc);
5537 		}
5538 		sc->vres.srq.start = val[0];
5539 		sc->vres.srq.size = val[1] - val[0] + 1;
5540 		sc->params.max_ordird_qp = val[2];
5541 		sc->params.max_ird_adapter = val[3];
5542 	}
5543 	if (sc->iscsicaps) {
5544 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5545 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5546 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5547 		if (rc != 0) {
5548 			device_printf(sc->dev,
5549 			    "failed to query iSCSI parameters: %d.\n", rc);
5550 			return (rc);
5551 		}
5552 		sc->vres.iscsi.start = val[0];
5553 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5554 	}
5555 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5556 		param[0] = FW_PARAM_PFVF(TLS_START);
5557 		param[1] = FW_PARAM_PFVF(TLS_END);
5558 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5559 		if (rc != 0) {
5560 			device_printf(sc->dev,
5561 			    "failed to query TLS parameters: %d.\n", rc);
5562 			return (rc);
5563 		}
5564 		sc->vres.key.start = val[0];
5565 		sc->vres.key.size = val[1] - val[0] + 1;
5566 	}
5567 
5568 	/*
5569 	 * We've got the params we wanted to query directly from the firmware.
5570 	 * Grab some others via other means.
5571 	 */
5572 	t4_init_sge_params(sc);
5573 	t4_init_tp_params(sc);
5574 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5575 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5576 
5577 	rc = t4_verify_chip_settings(sc);
5578 	if (rc != 0)
5579 		return (rc);
5580 	t4_init_rx_buf_info(sc);
5581 
5582 	return (rc);
5583 }
5584 
5585 #ifdef KERN_TLS
5586 static void
5587 ktls_tick(void *arg)
5588 {
5589 	struct adapter *sc;
5590 	uint32_t tstamp;
5591 
5592 	sc = arg;
5593 	tstamp = tcp_ts_getticks();
5594 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5595 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5596 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5597 }
5598 
5599 static int
5600 t6_config_kern_tls(struct adapter *sc, bool enable)
5601 {
5602 	int rc;
5603 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5604 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5605 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5606 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5607 
5608 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5609 	if (rc != 0) {
5610 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5611 		    enable ?  "enable" : "disable", rc);
5612 		return (rc);
5613 	}
5614 
5615 	if (enable) {
5616 		sc->flags |= KERN_TLS_ON;
5617 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5618 		    C_HARDCLOCK);
5619 	} else {
5620 		sc->flags &= ~KERN_TLS_ON;
5621 		callout_stop(&sc->ktls_tick);
5622 	}
5623 
5624 	return (rc);
5625 }
5626 #endif
5627 
5628 static int
5629 set_params__post_init(struct adapter *sc)
5630 {
5631 	uint32_t mask, param, val;
5632 #ifdef TCP_OFFLOAD
5633 	int i, v, shift;
5634 #endif
5635 
5636 	/* ask for encapsulated CPLs */
5637 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5638 	val = 1;
5639 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5640 
5641 	/* Enable 32b port caps if the firmware supports it. */
5642 	param = FW_PARAM_PFVF(PORT_CAPS32);
5643 	val = 1;
5644 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5645 		sc->params.port_caps32 = 1;
5646 
5647 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5648 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5649 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5650 	    V_MASKFILTER(val - 1));
5651 
5652 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5653 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5654 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5655 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5656 	val = 0;
5657 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5658 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5659 		    F_ATTACKFILTERENABLE);
5660 		val |= F_DROPERRORATTACK;
5661 	}
5662 	if (t4_drop_ip_fragments != 0) {
5663 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5664 		    F_FRAGMENTDROP);
5665 		val |= F_DROPERRORFRAG;
5666 	}
5667 	if (t4_drop_pkts_with_l2_errors != 0)
5668 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5669 	if (t4_drop_pkts_with_l3_errors != 0) {
5670 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5671 		    F_DROPERRORCSUMIP;
5672 	}
5673 	if (t4_drop_pkts_with_l4_errors != 0) {
5674 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5675 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5676 	}
5677 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5678 
5679 #ifdef TCP_OFFLOAD
5680 	/*
5681 	 * Override the TOE timers with user provided tunables.  This is not the
5682 	 * recommended way to change the timers (the firmware config file is) so
5683 	 * these tunables are not documented.
5684 	 *
5685 	 * All the timer tunables are in microseconds.
5686 	 */
5687 	if (t4_toe_keepalive_idle != 0) {
5688 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5689 		v &= M_KEEPALIVEIDLE;
5690 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5691 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5692 	}
5693 	if (t4_toe_keepalive_interval != 0) {
5694 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5695 		v &= M_KEEPALIVEINTVL;
5696 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5697 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5698 	}
5699 	if (t4_toe_keepalive_count != 0) {
5700 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5701 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5702 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5703 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5704 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5705 	}
5706 	if (t4_toe_rexmt_min != 0) {
5707 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5708 		v &= M_RXTMIN;
5709 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5710 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5711 	}
5712 	if (t4_toe_rexmt_max != 0) {
5713 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5714 		v &= M_RXTMAX;
5715 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5716 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5717 	}
5718 	if (t4_toe_rexmt_count != 0) {
5719 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5720 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5721 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5722 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5723 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5724 	}
5725 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5726 		if (t4_toe_rexmt_backoff[i] != -1) {
5727 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5728 			shift = (i & 3) << 3;
5729 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5730 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5731 		}
5732 	}
5733 #endif
5734 
5735 #ifdef KERN_TLS
5736 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS &&
5737 	    sc->toecaps & FW_CAPS_CONFIG_TOE) {
5738 		/*
5739 		 * Limit TOE connections to 2 reassembly "islands".
5740 		 * This is required to permit migrating TOE
5741 		 * connections to UPL_MODE_TLS.
5742 		 */
5743 		t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG,
5744 		    V_PASSMODE(M_PASSMODE), V_PASSMODE(2));
5745 	}
5746 
5747 	if (is_ktls(sc)) {
5748 		sc->tlst.inline_keys = t4_tls_inline_keys;
5749 		sc->tlst.combo_wrs = t4_tls_combo_wrs;
5750 		if (t4_kern_tls != 0 && is_t6(sc))
5751 			t6_config_kern_tls(sc, true);
5752 	}
5753 #endif
5754 	return (0);
5755 }
5756 
5757 #undef FW_PARAM_PFVF
5758 #undef FW_PARAM_DEV
5759 
5760 static void
5761 t4_set_desc(struct adapter *sc)
5762 {
5763 	char buf[128];
5764 	struct adapter_params *p = &sc->params;
5765 
5766 	snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
5767 
5768 	device_set_desc_copy(sc->dev, buf);
5769 }
5770 
5771 static inline void
5772 ifmedia_add4(struct ifmedia *ifm, int m)
5773 {
5774 
5775 	ifmedia_add(ifm, m, 0, NULL);
5776 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5777 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5778 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5779 }
5780 
5781 /*
5782  * This is the selected media, which is not quite the same as the active media.
5783  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5784  * and active are not the same, and "media: Ethernet selected" otherwise.
5785  */
5786 static void
5787 set_current_media(struct port_info *pi)
5788 {
5789 	struct link_config *lc;
5790 	struct ifmedia *ifm;
5791 	int mword;
5792 	u_int speed;
5793 
5794 	PORT_LOCK_ASSERT_OWNED(pi);
5795 
5796 	/* Leave current media alone if it's already set to IFM_NONE. */
5797 	ifm = &pi->media;
5798 	if (ifm->ifm_cur != NULL &&
5799 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5800 		return;
5801 
5802 	lc = &pi->link_cfg;
5803 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5804 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5805 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5806 		return;
5807 	}
5808 	mword = IFM_ETHER | IFM_FDX;
5809 	if (lc->requested_fc & PAUSE_TX)
5810 		mword |= IFM_ETH_TXPAUSE;
5811 	if (lc->requested_fc & PAUSE_RX)
5812 		mword |= IFM_ETH_RXPAUSE;
5813 	if (lc->requested_speed == 0)
5814 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5815 	else
5816 		speed = lc->requested_speed;
5817 	mword |= port_mword(pi, speed_to_fwcap(speed));
5818 	ifmedia_set(ifm, mword);
5819 }
5820 
5821 /*
5822  * Returns true if the ifmedia list for the port cannot change.
5823  */
5824 static bool
5825 fixed_ifmedia(struct port_info *pi)
5826 {
5827 
5828 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5829 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5830 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5831 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5832 	    pi->port_type == FW_PORT_TYPE_KX ||
5833 	    pi->port_type == FW_PORT_TYPE_KR ||
5834 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5835 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5836 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5837 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5838 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5839 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5840 }
5841 
5842 static void
5843 build_medialist(struct port_info *pi)
5844 {
5845 	uint32_t ss, speed;
5846 	int unknown, mword, bit;
5847 	struct link_config *lc;
5848 	struct ifmedia *ifm;
5849 
5850 	PORT_LOCK_ASSERT_OWNED(pi);
5851 
5852 	if (pi->flags & FIXED_IFMEDIA)
5853 		return;
5854 
5855 	/*
5856 	 * Rebuild the ifmedia list.
5857 	 */
5858 	ifm = &pi->media;
5859 	ifmedia_removeall(ifm);
5860 	lc = &pi->link_cfg;
5861 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5862 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5863 		MPASS(ss != 0);
5864 no_media:
5865 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5866 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5867 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5868 		return;
5869 	}
5870 
5871 	unknown = 0;
5872 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5873 		speed = 1 << bit;
5874 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5875 		if (ss & speed) {
5876 			mword = port_mword(pi, speed);
5877 			if (mword == IFM_NONE) {
5878 				goto no_media;
5879 			} else if (mword == IFM_UNKNOWN)
5880 				unknown++;
5881 			else
5882 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5883 		}
5884 	}
5885 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5886 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5887 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5888 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5889 
5890 	set_current_media(pi);
5891 }
5892 
5893 /*
5894  * Initialize the requested fields in the link config based on driver tunables.
5895  */
5896 static void
5897 init_link_config(struct port_info *pi)
5898 {
5899 	struct link_config *lc = &pi->link_cfg;
5900 
5901 	PORT_LOCK_ASSERT_OWNED(pi);
5902 
5903 	lc->requested_caps = 0;
5904 	lc->requested_speed = 0;
5905 
5906 	if (t4_autoneg == 0)
5907 		lc->requested_aneg = AUTONEG_DISABLE;
5908 	else if (t4_autoneg == 1)
5909 		lc->requested_aneg = AUTONEG_ENABLE;
5910 	else
5911 		lc->requested_aneg = AUTONEG_AUTO;
5912 
5913 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5914 	    PAUSE_AUTONEG);
5915 
5916 	if (t4_fec & FEC_AUTO)
5917 		lc->requested_fec = FEC_AUTO;
5918 	else if (t4_fec == 0)
5919 		lc->requested_fec = FEC_NONE;
5920 	else {
5921 		/* -1 is handled by the FEC_AUTO block above and not here. */
5922 		lc->requested_fec = t4_fec &
5923 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5924 		if (lc->requested_fec == 0)
5925 			lc->requested_fec = FEC_AUTO;
5926 	}
5927 	if (t4_force_fec < 0)
5928 		lc->force_fec = -1;
5929 	else if (t4_force_fec > 0)
5930 		lc->force_fec = 1;
5931 	else
5932 		lc->force_fec = 0;
5933 }
5934 
5935 /*
5936  * Makes sure that all requested settings comply with what's supported by the
5937  * port.  Returns the number of settings that were invalid and had to be fixed.
5938  */
5939 static int
5940 fixup_link_config(struct port_info *pi)
5941 {
5942 	int n = 0;
5943 	struct link_config *lc = &pi->link_cfg;
5944 	uint32_t fwspeed;
5945 
5946 	PORT_LOCK_ASSERT_OWNED(pi);
5947 
5948 	/* Speed (when not autonegotiating) */
5949 	if (lc->requested_speed != 0) {
5950 		fwspeed = speed_to_fwcap(lc->requested_speed);
5951 		if ((fwspeed & lc->pcaps) == 0) {
5952 			n++;
5953 			lc->requested_speed = 0;
5954 		}
5955 	}
5956 
5957 	/* Link autonegotiation */
5958 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5959 	    lc->requested_aneg == AUTONEG_DISABLE ||
5960 	    lc->requested_aneg == AUTONEG_AUTO);
5961 	if (lc->requested_aneg == AUTONEG_ENABLE &&
5962 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5963 		n++;
5964 		lc->requested_aneg = AUTONEG_AUTO;
5965 	}
5966 
5967 	/* Flow control */
5968 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5969 	if (lc->requested_fc & PAUSE_TX &&
5970 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5971 		n++;
5972 		lc->requested_fc &= ~PAUSE_TX;
5973 	}
5974 	if (lc->requested_fc & PAUSE_RX &&
5975 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
5976 		n++;
5977 		lc->requested_fc &= ~PAUSE_RX;
5978 	}
5979 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
5980 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
5981 		n++;
5982 		lc->requested_fc |= PAUSE_AUTONEG;
5983 	}
5984 
5985 	/* FEC */
5986 	if ((lc->requested_fec & FEC_RS &&
5987 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
5988 	    (lc->requested_fec & FEC_BASER_RS &&
5989 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
5990 		n++;
5991 		lc->requested_fec = FEC_AUTO;
5992 	}
5993 
5994 	return (n);
5995 }
5996 
5997 /*
5998  * Apply the requested L1 settings, which are expected to be valid, to the
5999  * hardware.
6000  */
6001 static int
6002 apply_link_config(struct port_info *pi)
6003 {
6004 	struct adapter *sc = pi->adapter;
6005 	struct link_config *lc = &pi->link_cfg;
6006 	int rc;
6007 
6008 #ifdef INVARIANTS
6009 	ASSERT_SYNCHRONIZED_OP(sc);
6010 	PORT_LOCK_ASSERT_OWNED(pi);
6011 
6012 	if (lc->requested_aneg == AUTONEG_ENABLE)
6013 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
6014 	if (!(lc->requested_fc & PAUSE_AUTONEG))
6015 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
6016 	if (lc->requested_fc & PAUSE_TX)
6017 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
6018 	if (lc->requested_fc & PAUSE_RX)
6019 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
6020 	if (lc->requested_fec & FEC_RS)
6021 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
6022 	if (lc->requested_fec & FEC_BASER_RS)
6023 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
6024 #endif
6025 	rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
6026 	if (rc != 0) {
6027 		/* Don't complain if the VF driver gets back an EPERM. */
6028 		if (!(sc->flags & IS_VF) || rc != FW_EPERM)
6029 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
6030 	} else {
6031 		/*
6032 		 * An L1_CFG will almost always result in a link-change event if
6033 		 * the link is up, and the driver will refresh the actual
6034 		 * fec/fc/etc. when the notification is processed.  If the link
6035 		 * is down then the actual settings are meaningless.
6036 		 *
6037 		 * This takes care of the case where a change in the L1 settings
6038 		 * may not result in a notification.
6039 		 */
6040 		if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
6041 			lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
6042 	}
6043 	return (rc);
6044 }
6045 
6046 #define FW_MAC_EXACT_CHUNK	7
6047 struct mcaddr_ctx {
6048 	if_t ifp;
6049 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
6050 	uint64_t hash;
6051 	int i;
6052 	int del;
6053 	int rc;
6054 };
6055 
6056 static u_int
6057 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
6058 {
6059 	struct mcaddr_ctx *ctx = arg;
6060 	struct vi_info *vi = if_getsoftc(ctx->ifp);
6061 	struct port_info *pi = vi->pi;
6062 	struct adapter *sc = pi->adapter;
6063 
6064 	if (ctx->rc < 0)
6065 		return (0);
6066 
6067 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
6068 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
6069 	ctx->i++;
6070 
6071 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
6072 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
6073 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
6074 		if (ctx->rc < 0) {
6075 			int j;
6076 
6077 			for (j = 0; j < ctx->i; j++) {
6078 				if_printf(ctx->ifp,
6079 				    "failed to add mc address"
6080 				    " %02x:%02x:%02x:"
6081 				    "%02x:%02x:%02x rc=%d\n",
6082 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
6083 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
6084 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
6085 				    -ctx->rc);
6086 			}
6087 			return (0);
6088 		}
6089 		ctx->del = 0;
6090 		ctx->i = 0;
6091 	}
6092 
6093 	return (1);
6094 }
6095 
6096 /*
6097  * Program the port's XGMAC based on parameters in ifnet.  The caller also
6098  * indicates which parameters should be programmed (the rest are left alone).
6099  */
6100 int
6101 update_mac_settings(if_t ifp, int flags)
6102 {
6103 	int rc = 0;
6104 	struct vi_info *vi = if_getsoftc(ifp);
6105 	struct port_info *pi = vi->pi;
6106 	struct adapter *sc = pi->adapter;
6107 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
6108 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
6109 
6110 	ASSERT_SYNCHRONIZED_OP(sc);
6111 	KASSERT(flags, ("%s: not told what to update.", __func__));
6112 
6113 	if (flags & XGMAC_MTU)
6114 		mtu = if_getmtu(ifp);
6115 
6116 	if (flags & XGMAC_PROMISC)
6117 		promisc = if_getflags(ifp) & IFF_PROMISC ? 1 : 0;
6118 
6119 	if (flags & XGMAC_ALLMULTI)
6120 		allmulti = if_getflags(ifp) & IFF_ALLMULTI ? 1 : 0;
6121 
6122 	if (flags & XGMAC_VLANEX)
6123 		vlanex = if_getcapenable(ifp) & IFCAP_VLAN_HWTAGGING ? 1 : 0;
6124 
6125 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
6126 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
6127 		    allmulti, 1, vlanex, false);
6128 		if (rc) {
6129 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
6130 			    rc);
6131 			return (rc);
6132 		}
6133 	}
6134 
6135 	if (flags & XGMAC_UCADDR) {
6136 		uint8_t ucaddr[ETHER_ADDR_LEN];
6137 
6138 		bcopy(if_getlladdr(ifp), ucaddr, sizeof(ucaddr));
6139 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
6140 		    ucaddr, true, &vi->smt_idx);
6141 		if (rc < 0) {
6142 			rc = -rc;
6143 			if_printf(ifp, "change_mac failed: %d\n", rc);
6144 			return (rc);
6145 		} else {
6146 			vi->xact_addr_filt = rc;
6147 			rc = 0;
6148 		}
6149 	}
6150 
6151 	if (flags & XGMAC_MCADDRS) {
6152 		struct epoch_tracker et;
6153 		struct mcaddr_ctx ctx;
6154 		int j;
6155 
6156 		ctx.ifp = ifp;
6157 		ctx.hash = 0;
6158 		ctx.i = 0;
6159 		ctx.del = 1;
6160 		ctx.rc = 0;
6161 		/*
6162 		 * Unlike other drivers, we accumulate list of pointers into
6163 		 * interface address lists and we need to keep it safe even
6164 		 * after if_foreach_llmaddr() returns, thus we must enter the
6165 		 * network epoch.
6166 		 */
6167 		NET_EPOCH_ENTER(et);
6168 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6169 		if (ctx.rc < 0) {
6170 			NET_EPOCH_EXIT(et);
6171 			rc = -ctx.rc;
6172 			return (rc);
6173 		}
6174 		if (ctx.i > 0) {
6175 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6176 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6177 			NET_EPOCH_EXIT(et);
6178 			if (rc < 0) {
6179 				rc = -rc;
6180 				for (j = 0; j < ctx.i; j++) {
6181 					if_printf(ifp,
6182 					    "failed to add mcast address"
6183 					    " %02x:%02x:%02x:"
6184 					    "%02x:%02x:%02x rc=%d\n",
6185 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6186 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6187 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6188 					    rc);
6189 				}
6190 				return (rc);
6191 			}
6192 			ctx.del = 0;
6193 		} else
6194 			NET_EPOCH_EXIT(et);
6195 
6196 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6197 		if (rc != 0)
6198 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6199 			    rc);
6200 		if (ctx.del == 0) {
6201 			/* We clobbered the VXLAN entry if there was one. */
6202 			pi->vxlan_tcam_entry = false;
6203 		}
6204 	}
6205 
6206 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6207 	    pi->vxlan_tcam_entry == false) {
6208 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6209 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6210 		    true);
6211 		if (rc < 0) {
6212 			rc = -rc;
6213 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6214 			    rc);
6215 		} else {
6216 			MPASS(rc == sc->rawf_base + pi->port_id);
6217 			rc = 0;
6218 			pi->vxlan_tcam_entry = true;
6219 		}
6220 	}
6221 
6222 	return (rc);
6223 }
6224 
6225 /*
6226  * {begin|end}_synchronized_op must be called from the same thread.
6227  */
6228 int
6229 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6230     char *wmesg)
6231 {
6232 	int rc, pri;
6233 
6234 #ifdef WITNESS
6235 	/* the caller thinks it's ok to sleep, but is it really? */
6236 	if (flags & SLEEP_OK)
6237 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6238 		    "begin_synchronized_op");
6239 #endif
6240 
6241 	if (INTR_OK)
6242 		pri = PCATCH;
6243 	else
6244 		pri = 0;
6245 
6246 	ADAPTER_LOCK(sc);
6247 	for (;;) {
6248 
6249 		if (vi && IS_DOOMED(vi)) {
6250 			rc = ENXIO;
6251 			goto done;
6252 		}
6253 
6254 		if (!IS_BUSY(sc)) {
6255 			rc = 0;
6256 			break;
6257 		}
6258 
6259 		if (!(flags & SLEEP_OK)) {
6260 			rc = EBUSY;
6261 			goto done;
6262 		}
6263 
6264 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6265 			rc = EINTR;
6266 			goto done;
6267 		}
6268 	}
6269 
6270 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6271 	SET_BUSY(sc);
6272 #ifdef INVARIANTS
6273 	sc->last_op = wmesg;
6274 	sc->last_op_thr = curthread;
6275 	sc->last_op_flags = flags;
6276 #endif
6277 
6278 done:
6279 	if (!(flags & HOLD_LOCK) || rc)
6280 		ADAPTER_UNLOCK(sc);
6281 
6282 	return (rc);
6283 }
6284 
6285 /*
6286  * Tell if_ioctl and if_init that the VI is going away.  This is
6287  * special variant of begin_synchronized_op and must be paired with a
6288  * call to end_synchronized_op.
6289  */
6290 void
6291 doom_vi(struct adapter *sc, struct vi_info *vi)
6292 {
6293 
6294 	ADAPTER_LOCK(sc);
6295 	SET_DOOMED(vi);
6296 	wakeup(&sc->flags);
6297 	while (IS_BUSY(sc))
6298 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6299 	SET_BUSY(sc);
6300 #ifdef INVARIANTS
6301 	sc->last_op = "t4detach";
6302 	sc->last_op_thr = curthread;
6303 	sc->last_op_flags = 0;
6304 #endif
6305 	ADAPTER_UNLOCK(sc);
6306 }
6307 
6308 /*
6309  * {begin|end}_synchronized_op must be called from the same thread.
6310  */
6311 void
6312 end_synchronized_op(struct adapter *sc, int flags)
6313 {
6314 
6315 	if (flags & LOCK_HELD)
6316 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6317 	else
6318 		ADAPTER_LOCK(sc);
6319 
6320 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6321 	CLR_BUSY(sc);
6322 	wakeup(&sc->flags);
6323 	ADAPTER_UNLOCK(sc);
6324 }
6325 
6326 static int
6327 cxgbe_init_synchronized(struct vi_info *vi)
6328 {
6329 	struct port_info *pi = vi->pi;
6330 	struct adapter *sc = pi->adapter;
6331 	if_t ifp = vi->ifp;
6332 	int rc = 0, i;
6333 	struct sge_txq *txq;
6334 
6335 	ASSERT_SYNCHRONIZED_OP(sc);
6336 
6337 	if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
6338 		return (0);	/* already running */
6339 
6340 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6341 		return (rc);	/* error message displayed already */
6342 
6343 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6344 		return (rc); /* error message displayed already */
6345 
6346 	rc = update_mac_settings(ifp, XGMAC_ALL);
6347 	if (rc)
6348 		goto done;	/* error message displayed already */
6349 
6350 	PORT_LOCK(pi);
6351 	if (pi->up_vis == 0) {
6352 		t4_update_port_info(pi);
6353 		fixup_link_config(pi);
6354 		build_medialist(pi);
6355 		apply_link_config(pi);
6356 	}
6357 
6358 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6359 	if (rc != 0) {
6360 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6361 		PORT_UNLOCK(pi);
6362 		goto done;
6363 	}
6364 
6365 	/*
6366 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6367 	 * if this changes.
6368 	 */
6369 
6370 	for_each_txq(vi, i, txq) {
6371 		TXQ_LOCK(txq);
6372 		txq->eq.flags |= EQ_ENABLED;
6373 		TXQ_UNLOCK(txq);
6374 	}
6375 
6376 	/*
6377 	 * The first iq of the first port to come up is used for tracing.
6378 	 */
6379 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6380 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6381 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6382 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6383 		    V_QUEUENUMBER(sc->traceq));
6384 		pi->flags |= HAS_TRACEQ;
6385 	}
6386 
6387 	/* all ok */
6388 	pi->up_vis++;
6389 	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
6390 	if (pi->link_cfg.link_ok)
6391 		t4_os_link_changed(pi);
6392 	PORT_UNLOCK(pi);
6393 
6394 	mtx_lock(&vi->tick_mtx);
6395 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
6396 		callout_reset(&vi->tick, hz, vi_tick, vi);
6397 	else
6398 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6399 	mtx_unlock(&vi->tick_mtx);
6400 done:
6401 	if (rc != 0)
6402 		cxgbe_uninit_synchronized(vi);
6403 
6404 	return (rc);
6405 }
6406 
6407 /*
6408  * Idempotent.
6409  */
6410 static int
6411 cxgbe_uninit_synchronized(struct vi_info *vi)
6412 {
6413 	struct port_info *pi = vi->pi;
6414 	struct adapter *sc = pi->adapter;
6415 	if_t ifp = vi->ifp;
6416 	int rc, i;
6417 	struct sge_txq *txq;
6418 
6419 	ASSERT_SYNCHRONIZED_OP(sc);
6420 
6421 	if (!(vi->flags & VI_INIT_DONE)) {
6422 		if (__predict_false(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6423 			KASSERT(0, ("uninited VI is running"));
6424 			if_printf(ifp, "uninited VI with running ifnet.  "
6425 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6426 			    "if_drv_flags 0x%08x\n", vi->flags, if_getflags(ifp),
6427 			    if_getdrvflags(ifp));
6428 		}
6429 		return (0);
6430 	}
6431 
6432 	/*
6433 	 * Disable the VI so that all its data in either direction is discarded
6434 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6435 	 * tick) intact as the TP can deliver negative advice or data that it's
6436 	 * holding in its RAM (for an offloaded connection) even after the VI is
6437 	 * disabled.
6438 	 */
6439 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6440 	if (rc) {
6441 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6442 		return (rc);
6443 	}
6444 
6445 	for_each_txq(vi, i, txq) {
6446 		TXQ_LOCK(txq);
6447 		txq->eq.flags &= ~EQ_ENABLED;
6448 		TXQ_UNLOCK(txq);
6449 	}
6450 
6451 	mtx_lock(&vi->tick_mtx);
6452 	callout_stop(&vi->tick);
6453 	mtx_unlock(&vi->tick_mtx);
6454 
6455 	PORT_LOCK(pi);
6456 	if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6457 		PORT_UNLOCK(pi);
6458 		return (0);
6459 	}
6460 	if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
6461 	pi->up_vis--;
6462 	if (pi->up_vis > 0) {
6463 		PORT_UNLOCK(pi);
6464 		return (0);
6465 	}
6466 
6467 	pi->link_cfg.link_ok = false;
6468 	pi->link_cfg.speed = 0;
6469 	pi->link_cfg.link_down_rc = 255;
6470 	t4_os_link_changed(pi);
6471 	PORT_UNLOCK(pi);
6472 
6473 	return (0);
6474 }
6475 
6476 /*
6477  * It is ok for this function to fail midway and return right away.  t4_detach
6478  * will walk the entire sc->irq list and clean up whatever is valid.
6479  */
6480 int
6481 t4_setup_intr_handlers(struct adapter *sc)
6482 {
6483 	int rc, rid, p, q, v;
6484 	char s[8];
6485 	struct irq *irq;
6486 	struct port_info *pi;
6487 	struct vi_info *vi;
6488 	struct sge *sge = &sc->sge;
6489 	struct sge_rxq *rxq;
6490 #ifdef TCP_OFFLOAD
6491 	struct sge_ofld_rxq *ofld_rxq;
6492 #endif
6493 #ifdef DEV_NETMAP
6494 	struct sge_nm_rxq *nm_rxq;
6495 #endif
6496 #ifdef RSS
6497 	int nbuckets = rss_getnumbuckets();
6498 #endif
6499 
6500 	/*
6501 	 * Setup interrupts.
6502 	 */
6503 	irq = &sc->irq[0];
6504 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6505 	if (forwarding_intr_to_fwq(sc))
6506 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6507 
6508 	/* Multiple interrupts. */
6509 	if (sc->flags & IS_VF)
6510 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6511 		    ("%s: too few intr.", __func__));
6512 	else
6513 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6514 		    ("%s: too few intr.", __func__));
6515 
6516 	/* The first one is always error intr on PFs */
6517 	if (!(sc->flags & IS_VF)) {
6518 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6519 		if (rc != 0)
6520 			return (rc);
6521 		irq++;
6522 		rid++;
6523 	}
6524 
6525 	/* The second one is always the firmware event queue (first on VFs) */
6526 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6527 	if (rc != 0)
6528 		return (rc);
6529 	irq++;
6530 	rid++;
6531 
6532 	for_each_port(sc, p) {
6533 		pi = sc->port[p];
6534 		for_each_vi(pi, v, vi) {
6535 			vi->first_intr = rid - 1;
6536 
6537 			if (vi->nnmrxq > 0) {
6538 				int n = max(vi->nrxq, vi->nnmrxq);
6539 
6540 				rxq = &sge->rxq[vi->first_rxq];
6541 #ifdef DEV_NETMAP
6542 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6543 #endif
6544 				for (q = 0; q < n; q++) {
6545 					snprintf(s, sizeof(s), "%x%c%x", p,
6546 					    'a' + v, q);
6547 					if (q < vi->nrxq)
6548 						irq->rxq = rxq++;
6549 #ifdef DEV_NETMAP
6550 					if (q < vi->nnmrxq)
6551 						irq->nm_rxq = nm_rxq++;
6552 
6553 					if (irq->nm_rxq != NULL &&
6554 					    irq->rxq == NULL) {
6555 						/* Netmap rx only */
6556 						rc = t4_alloc_irq(sc, irq, rid,
6557 						    t4_nm_intr, irq->nm_rxq, s);
6558 					}
6559 					if (irq->nm_rxq != NULL &&
6560 					    irq->rxq != NULL) {
6561 						/* NIC and Netmap rx */
6562 						rc = t4_alloc_irq(sc, irq, rid,
6563 						    t4_vi_intr, irq, s);
6564 					}
6565 #endif
6566 					if (irq->rxq != NULL &&
6567 					    irq->nm_rxq == NULL) {
6568 						/* NIC rx only */
6569 						rc = t4_alloc_irq(sc, irq, rid,
6570 						    t4_intr, irq->rxq, s);
6571 					}
6572 					if (rc != 0)
6573 						return (rc);
6574 #ifdef RSS
6575 					if (q < vi->nrxq) {
6576 						bus_bind_intr(sc->dev, irq->res,
6577 						    rss_getcpu(q % nbuckets));
6578 					}
6579 #endif
6580 					irq++;
6581 					rid++;
6582 					vi->nintr++;
6583 				}
6584 			} else {
6585 				for_each_rxq(vi, q, rxq) {
6586 					snprintf(s, sizeof(s), "%x%c%x", p,
6587 					    'a' + v, q);
6588 					rc = t4_alloc_irq(sc, irq, rid,
6589 					    t4_intr, rxq, s);
6590 					if (rc != 0)
6591 						return (rc);
6592 #ifdef RSS
6593 					bus_bind_intr(sc->dev, irq->res,
6594 					    rss_getcpu(q % nbuckets));
6595 #endif
6596 					irq++;
6597 					rid++;
6598 					vi->nintr++;
6599 				}
6600 			}
6601 #ifdef TCP_OFFLOAD
6602 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6603 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6604 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6605 				    ofld_rxq, s);
6606 				if (rc != 0)
6607 					return (rc);
6608 				irq++;
6609 				rid++;
6610 				vi->nintr++;
6611 			}
6612 #endif
6613 		}
6614 	}
6615 	MPASS(irq == &sc->irq[sc->intr_count]);
6616 
6617 	return (0);
6618 }
6619 
6620 static void
6621 write_global_rss_key(struct adapter *sc)
6622 {
6623 #ifdef RSS
6624 	int i;
6625 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6626 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6627 
6628 	CTASSERT(RSS_KEYSIZE == 40);
6629 
6630 	rss_getkey((void *)&raw_rss_key[0]);
6631 	for (i = 0; i < nitems(rss_key); i++) {
6632 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6633 	}
6634 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6635 #endif
6636 }
6637 
6638 /*
6639  * Idempotent.
6640  */
6641 static int
6642 adapter_full_init(struct adapter *sc)
6643 {
6644 	int rc, i;
6645 
6646 	ASSERT_SYNCHRONIZED_OP(sc);
6647 
6648 	/*
6649 	 * queues that belong to the adapter (not any particular port).
6650 	 */
6651 	rc = t4_setup_adapter_queues(sc);
6652 	if (rc != 0)
6653 		return (rc);
6654 
6655 	for (i = 0; i < nitems(sc->tq); i++) {
6656 		if (sc->tq[i] != NULL)
6657 			continue;
6658 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6659 		    taskqueue_thread_enqueue, &sc->tq[i]);
6660 		if (sc->tq[i] == NULL) {
6661 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6662 			return (ENOMEM);
6663 		}
6664 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6665 		    device_get_nameunit(sc->dev), i);
6666 	}
6667 
6668 	if (!(sc->flags & IS_VF)) {
6669 		write_global_rss_key(sc);
6670 		t4_intr_enable(sc);
6671 	}
6672 	return (0);
6673 }
6674 
6675 int
6676 adapter_init(struct adapter *sc)
6677 {
6678 	int rc;
6679 
6680 	ASSERT_SYNCHRONIZED_OP(sc);
6681 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6682 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6683 	    ("%s: FULL_INIT_DONE already", __func__));
6684 
6685 	rc = adapter_full_init(sc);
6686 	if (rc != 0)
6687 		adapter_full_uninit(sc);
6688 	else
6689 		sc->flags |= FULL_INIT_DONE;
6690 
6691 	return (rc);
6692 }
6693 
6694 /*
6695  * Idempotent.
6696  */
6697 static void
6698 adapter_full_uninit(struct adapter *sc)
6699 {
6700 	int i;
6701 
6702 	t4_teardown_adapter_queues(sc);
6703 
6704 	for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
6705 		taskqueue_free(sc->tq[i]);
6706 		sc->tq[i] = NULL;
6707 	}
6708 
6709 	sc->flags &= ~FULL_INIT_DONE;
6710 }
6711 
6712 #ifdef RSS
6713 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6714     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6715     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6716     RSS_HASHTYPE_RSS_UDP_IPV6)
6717 
6718 /* Translates kernel hash types to hardware. */
6719 static int
6720 hashconfig_to_hashen(int hashconfig)
6721 {
6722 	int hashen = 0;
6723 
6724 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6725 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6726 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6727 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6728 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6729 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6730 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6731 	}
6732 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6733 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6734 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6735 	}
6736 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6737 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6738 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6739 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6740 
6741 	return (hashen);
6742 }
6743 
6744 /* Translates hardware hash types to kernel. */
6745 static int
6746 hashen_to_hashconfig(int hashen)
6747 {
6748 	int hashconfig = 0;
6749 
6750 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6751 		/*
6752 		 * If UDP hashing was enabled it must have been enabled for
6753 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6754 		 * enabling any 4-tuple hash is nonsense configuration.
6755 		 */
6756 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6757 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6758 
6759 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6760 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6761 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6762 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6763 	}
6764 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6765 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6766 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6767 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6768 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6769 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6770 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6771 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6772 
6773 	return (hashconfig);
6774 }
6775 #endif
6776 
6777 /*
6778  * Idempotent.
6779  */
6780 static int
6781 vi_full_init(struct vi_info *vi)
6782 {
6783 	struct adapter *sc = vi->adapter;
6784 	struct sge_rxq *rxq;
6785 	int rc, i, j;
6786 #ifdef RSS
6787 	int nbuckets = rss_getnumbuckets();
6788 	int hashconfig = rss_gethashconfig();
6789 	int extra;
6790 #endif
6791 
6792 	ASSERT_SYNCHRONIZED_OP(sc);
6793 
6794 	/*
6795 	 * Allocate tx/rx/fl queues for this VI.
6796 	 */
6797 	rc = t4_setup_vi_queues(vi);
6798 	if (rc != 0)
6799 		return (rc);
6800 
6801 	/*
6802 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6803 	 */
6804 	if (vi->nrxq > vi->rss_size) {
6805 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6806 		    "some queues will never receive traffic.\n", vi->nrxq,
6807 		    vi->rss_size);
6808 	} else if (vi->rss_size % vi->nrxq) {
6809 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6810 		    "expect uneven traffic distribution.\n", vi->nrxq,
6811 		    vi->rss_size);
6812 	}
6813 #ifdef RSS
6814 	if (vi->nrxq != nbuckets) {
6815 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6816 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6817 	}
6818 #endif
6819 	if (vi->rss == NULL)
6820 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6821 		    M_ZERO | M_WAITOK);
6822 	for (i = 0; i < vi->rss_size;) {
6823 #ifdef RSS
6824 		j = rss_get_indirection_to_bucket(i);
6825 		j %= vi->nrxq;
6826 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6827 		vi->rss[i++] = rxq->iq.abs_id;
6828 #else
6829 		for_each_rxq(vi, j, rxq) {
6830 			vi->rss[i++] = rxq->iq.abs_id;
6831 			if (i == vi->rss_size)
6832 				break;
6833 		}
6834 #endif
6835 	}
6836 
6837 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6838 	    vi->rss, vi->rss_size);
6839 	if (rc != 0) {
6840 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6841 		return (rc);
6842 	}
6843 
6844 #ifdef RSS
6845 	vi->hashen = hashconfig_to_hashen(hashconfig);
6846 
6847 	/*
6848 	 * We may have had to enable some hashes even though the global config
6849 	 * wants them disabled.  This is a potential problem that must be
6850 	 * reported to the user.
6851 	 */
6852 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6853 
6854 	/*
6855 	 * If we consider only the supported hash types, then the enabled hashes
6856 	 * are a superset of the requested hashes.  In other words, there cannot
6857 	 * be any supported hash that was requested but not enabled, but there
6858 	 * can be hashes that were not requested but had to be enabled.
6859 	 */
6860 	extra &= SUPPORTED_RSS_HASHTYPES;
6861 	MPASS((extra & hashconfig) == 0);
6862 
6863 	if (extra) {
6864 		CH_ALERT(vi,
6865 		    "global RSS config (0x%x) cannot be accommodated.\n",
6866 		    hashconfig);
6867 	}
6868 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6869 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6870 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6871 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6872 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6873 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6874 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6875 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6876 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6877 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6878 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6879 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6880 #else
6881 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6882 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6883 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6884 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6885 #endif
6886 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6887 	    0, 0);
6888 	if (rc != 0) {
6889 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6890 		return (rc);
6891 	}
6892 
6893 	return (0);
6894 }
6895 
6896 int
6897 vi_init(struct vi_info *vi)
6898 {
6899 	int rc;
6900 
6901 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6902 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6903 	    ("%s: VI_INIT_DONE already", __func__));
6904 
6905 	rc = vi_full_init(vi);
6906 	if (rc != 0)
6907 		vi_full_uninit(vi);
6908 	else
6909 		vi->flags |= VI_INIT_DONE;
6910 
6911 	return (rc);
6912 }
6913 
6914 /*
6915  * Idempotent.
6916  */
6917 static void
6918 vi_full_uninit(struct vi_info *vi)
6919 {
6920 
6921 	if (vi->flags & VI_INIT_DONE) {
6922 		quiesce_vi(vi);
6923 		free(vi->rss, M_CXGBE);
6924 		free(vi->nm_rss, M_CXGBE);
6925 	}
6926 
6927 	t4_teardown_vi_queues(vi);
6928 	vi->flags &= ~VI_INIT_DONE;
6929 }
6930 
6931 static void
6932 quiesce_txq(struct sge_txq *txq)
6933 {
6934 	struct sge_eq *eq = &txq->eq;
6935 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6936 
6937 	MPASS(eq->flags & EQ_SW_ALLOCATED);
6938 	MPASS(!(eq->flags & EQ_ENABLED));
6939 
6940 	/* Wait for the mp_ring to empty. */
6941 	while (!mp_ring_is_idle(txq->r)) {
6942 		mp_ring_check_drainage(txq->r, 4096);
6943 		pause("rquiesce", 1);
6944 	}
6945 	MPASS(txq->txp.npkt == 0);
6946 
6947 	if (eq->flags & EQ_HW_ALLOCATED) {
6948 		/*
6949 		 * Hardware is alive and working normally.  Wait for it to
6950 		 * finish and then wait for the driver to catch up and reclaim
6951 		 * all descriptors.
6952 		 */
6953 		while (spg->cidx != htobe16(eq->pidx))
6954 			pause("equiesce", 1);
6955 		while (eq->cidx != eq->pidx)
6956 			pause("dquiesce", 1);
6957 	} else {
6958 		/*
6959 		 * Hardware is unavailable.  Discard all pending tx and reclaim
6960 		 * descriptors directly.
6961 		 */
6962 		TXQ_LOCK(txq);
6963 		while (eq->cidx != eq->pidx) {
6964 			struct mbuf *m, *nextpkt;
6965 			struct tx_sdesc *txsd;
6966 
6967 			txsd = &txq->sdesc[eq->cidx];
6968 			for (m = txsd->m; m != NULL; m = nextpkt) {
6969 				nextpkt = m->m_nextpkt;
6970 				m->m_nextpkt = NULL;
6971 				m_freem(m);
6972 			}
6973 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
6974 		}
6975 		spg->pidx = spg->cidx = htobe16(eq->cidx);
6976 		TXQ_UNLOCK(txq);
6977 	}
6978 }
6979 
6980 static void
6981 quiesce_wrq(struct sge_wrq *wrq)
6982 {
6983 
6984 	/* XXXTX */
6985 }
6986 
6987 static void
6988 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
6989 {
6990 	/* Synchronize with the interrupt handler */
6991 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
6992 		pause("iqfree", 1);
6993 
6994 	if (fl != NULL) {
6995 		MPASS(iq->flags & IQ_HAS_FL);
6996 
6997 		mtx_lock(&sc->sfl_lock);
6998 		FL_LOCK(fl);
6999 		fl->flags |= FL_DOOMED;
7000 		FL_UNLOCK(fl);
7001 		callout_stop(&sc->sfl_callout);
7002 		mtx_unlock(&sc->sfl_lock);
7003 
7004 		KASSERT((fl->flags & FL_STARVING) == 0,
7005 		    ("%s: still starving", __func__));
7006 
7007 		/* Release all buffers if hardware is no longer available. */
7008 		if (!(iq->flags & IQ_HW_ALLOCATED))
7009 			free_fl_buffers(sc, fl);
7010 	}
7011 }
7012 
7013 /*
7014  * Wait for all activity on all the queues of the VI to complete.  It is assumed
7015  * that no new work is being enqueued by the hardware or the driver.  That part
7016  * should be arranged before calling this function.
7017  */
7018 static void
7019 quiesce_vi(struct vi_info *vi)
7020 {
7021 	int i;
7022 	struct adapter *sc = vi->adapter;
7023 	struct sge_rxq *rxq;
7024 	struct sge_txq *txq;
7025 #ifdef TCP_OFFLOAD
7026 	struct sge_ofld_rxq *ofld_rxq;
7027 #endif
7028 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7029 	struct sge_ofld_txq *ofld_txq;
7030 #endif
7031 
7032 	if (!(vi->flags & VI_INIT_DONE))
7033 		return;
7034 
7035 	for_each_txq(vi, i, txq) {
7036 		quiesce_txq(txq);
7037 	}
7038 
7039 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7040 	for_each_ofld_txq(vi, i, ofld_txq) {
7041 		quiesce_wrq(&ofld_txq->wrq);
7042 	}
7043 #endif
7044 
7045 	for_each_rxq(vi, i, rxq) {
7046 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
7047 	}
7048 
7049 #ifdef TCP_OFFLOAD
7050 	for_each_ofld_rxq(vi, i, ofld_rxq) {
7051 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
7052 	}
7053 #endif
7054 }
7055 
7056 static int
7057 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
7058     driver_intr_t *handler, void *arg, char *name)
7059 {
7060 	int rc;
7061 
7062 	irq->rid = rid;
7063 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
7064 	    RF_SHAREABLE | RF_ACTIVE);
7065 	if (irq->res == NULL) {
7066 		device_printf(sc->dev,
7067 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
7068 		return (ENOMEM);
7069 	}
7070 
7071 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
7072 	    NULL, handler, arg, &irq->tag);
7073 	if (rc != 0) {
7074 		device_printf(sc->dev,
7075 		    "failed to setup interrupt for rid %d, name %s: %d\n",
7076 		    rid, name, rc);
7077 	} else if (name)
7078 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
7079 
7080 	return (rc);
7081 }
7082 
7083 static int
7084 t4_free_irq(struct adapter *sc, struct irq *irq)
7085 {
7086 	if (irq->tag)
7087 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
7088 	if (irq->res)
7089 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
7090 
7091 	bzero(irq, sizeof(*irq));
7092 
7093 	return (0);
7094 }
7095 
7096 static void
7097 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
7098 {
7099 
7100 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
7101 	t4_get_regs(sc, buf, regs->len);
7102 }
7103 
7104 #define	A_PL_INDIR_CMD	0x1f8
7105 
7106 #define	S_PL_AUTOINC	31
7107 #define	M_PL_AUTOINC	0x1U
7108 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
7109 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
7110 
7111 #define	S_PL_VFID	20
7112 #define	M_PL_VFID	0xffU
7113 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
7114 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
7115 
7116 #define	S_PL_ADDR	0
7117 #define	M_PL_ADDR	0xfffffU
7118 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
7119 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
7120 
7121 #define	A_PL_INDIR_DATA	0x1fc
7122 
7123 static uint64_t
7124 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7125 {
7126 	u32 stats[2];
7127 
7128 	if (sc->flags & IS_VF) {
7129 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7130 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7131 	} else {
7132 		mtx_assert(&sc->reg_lock, MA_OWNED);
7133 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7134 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7135 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7136 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7137 	}
7138 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7139 }
7140 
7141 static void
7142 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7143 {
7144 
7145 #define GET_STAT(name) \
7146 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7147 
7148 	if (!(sc->flags & IS_VF))
7149 		mtx_lock(&sc->reg_lock);
7150 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7151 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7152 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7153 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7154 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7155 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7156 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7157 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7158 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7159 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7160 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7161 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7162 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7163 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7164 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7165 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7166 	if (!(sc->flags & IS_VF))
7167 		mtx_unlock(&sc->reg_lock);
7168 
7169 #undef GET_STAT
7170 }
7171 
7172 static void
7173 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7174 {
7175 	int reg;
7176 
7177 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7178 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7179 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7180 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7181 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7182 }
7183 
7184 static void
7185 vi_refresh_stats(struct vi_info *vi)
7186 {
7187 	struct timeval tv;
7188 	const struct timeval interval = {0, 250000};	/* 250ms */
7189 
7190 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7191 
7192 	if (vi->flags & VI_SKIP_STATS)
7193 		return;
7194 
7195 	getmicrotime(&tv);
7196 	timevalsub(&tv, &interval);
7197 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7198 		return;
7199 
7200 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7201 	getmicrotime(&vi->last_refreshed);
7202 }
7203 
7204 static void
7205 cxgbe_refresh_stats(struct vi_info *vi)
7206 {
7207 	u_int i, v, tnl_cong_drops, chan_map;
7208 	struct timeval tv;
7209 	const struct timeval interval = {0, 250000};	/* 250ms */
7210 	struct port_info *pi;
7211 	struct adapter *sc;
7212 
7213 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7214 
7215 	if (vi->flags & VI_SKIP_STATS)
7216 		return;
7217 
7218 	getmicrotime(&tv);
7219 	timevalsub(&tv, &interval);
7220 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7221 		return;
7222 
7223 	pi = vi->pi;
7224 	sc = vi->adapter;
7225 	tnl_cong_drops = 0;
7226 	t4_get_port_stats(sc, pi->port_id, &pi->stats);
7227 	chan_map = pi->rx_e_chan_map;
7228 	while (chan_map) {
7229 		i = ffs(chan_map) - 1;
7230 		mtx_lock(&sc->reg_lock);
7231 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7232 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7233 		mtx_unlock(&sc->reg_lock);
7234 		tnl_cong_drops += v;
7235 		chan_map &= ~(1 << i);
7236 	}
7237 	pi->tnl_cong_drops = tnl_cong_drops;
7238 	getmicrotime(&vi->last_refreshed);
7239 }
7240 
7241 static void
7242 cxgbe_tick(void *arg)
7243 {
7244 	struct vi_info *vi = arg;
7245 
7246 	MPASS(IS_MAIN_VI(vi));
7247 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7248 
7249 	cxgbe_refresh_stats(vi);
7250 	callout_schedule(&vi->tick, hz);
7251 }
7252 
7253 static void
7254 vi_tick(void *arg)
7255 {
7256 	struct vi_info *vi = arg;
7257 
7258 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7259 
7260 	vi_refresh_stats(vi);
7261 	callout_schedule(&vi->tick, hz);
7262 }
7263 
7264 /*
7265  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7266  */
7267 static char *caps_decoder[] = {
7268 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7269 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7270 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7271 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7272 	    "\006HASHFILTER\007ETHOFLD",
7273 	"\20\001TOE",					/* 4: TOE */
7274 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7275 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7276 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7277 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7278 	    "\007T10DIF"
7279 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7280 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7281 	    "\004TLS_HW",
7282 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7283 		    "\004PO_INITIATOR\005PO_TARGET",
7284 };
7285 
7286 void
7287 t4_sysctls(struct adapter *sc)
7288 {
7289 	struct sysctl_ctx_list *ctx = &sc->ctx;
7290 	struct sysctl_oid *oid;
7291 	struct sysctl_oid_list *children, *c0;
7292 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7293 
7294 	/*
7295 	 * dev.t4nex.X.
7296 	 */
7297 	oid = device_get_sysctl_tree(sc->dev);
7298 	c0 = children = SYSCTL_CHILDREN(oid);
7299 
7300 	sc->sc_do_rxcopy = 1;
7301 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7302 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7303 
7304 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7305 	    sc->params.nports, "# of ports");
7306 
7307 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7308 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7309 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7310 	    "available doorbells");
7311 
7312 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7313 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7314 
7315 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7316 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7317 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7318 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7319 
7320 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7321 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7322 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7323 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7324 
7325 	t4_sge_sysctls(sc, ctx, children);
7326 
7327 	sc->lro_timeout = 100;
7328 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7329 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7330 
7331 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7332 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7333 
7334 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7335 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7336 
7337 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7338 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7339 
7340 	if (sc->flags & IS_VF)
7341 		return;
7342 
7343 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7344 	    NULL, chip_rev(sc), "chip hardware revision");
7345 
7346 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7347 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7348 
7349 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7350 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7351 
7352 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7353 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7354 
7355 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7356 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7357 
7358 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7359 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7360 
7361 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7362 	    sc->er_version, 0, "expansion ROM version");
7363 
7364 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7365 	    sc->bs_version, 0, "bootstrap firmware version");
7366 
7367 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7368 	    NULL, sc->params.scfg_vers, "serial config version");
7369 
7370 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7371 	    NULL, sc->params.vpd_vers, "VPD version");
7372 
7373 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7374 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7375 
7376 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7377 	    sc->cfcsum, "config file checksum");
7378 
7379 #define SYSCTL_CAP(name, n, text) \
7380 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7381 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7382 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7383 	    "available " text " capabilities")
7384 
7385 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7386 	SYSCTL_CAP(linkcaps, 1, "link");
7387 	SYSCTL_CAP(switchcaps, 2, "switch");
7388 	SYSCTL_CAP(niccaps, 3, "NIC");
7389 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7390 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7391 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7392 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7393 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7394 #undef SYSCTL_CAP
7395 
7396 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7397 	    NULL, sc->tids.nftids, "number of filters");
7398 
7399 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7400 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7401 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7402 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7403 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7404 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7405 
7406 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7407 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7408 	    sysctl_loadavg, "A",
7409 	    "microprocessor load averages (debug firmwares only)");
7410 
7411 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7412 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7413 	    "I", "core Vdd (in mV)");
7414 
7415 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7416 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7417 	    sysctl_cpus, "A", "local CPUs");
7418 
7419 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7420 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7421 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7422 
7423 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7424 	    &sc->swintr, 0, "software triggered interrupts");
7425 
7426 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7427 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7428 	    "1 = reset adapter, 0 = zero reset counter");
7429 
7430 	/*
7431 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7432 	 */
7433 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7434 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7435 	    "logs and miscellaneous information");
7436 	children = SYSCTL_CHILDREN(oid);
7437 
7438 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7439 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7440 	    sysctl_cctrl, "A", "congestion control");
7441 
7442 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7443 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7444 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7445 
7446 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7447 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7448 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7449 
7450 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7451 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7452 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7453 
7454 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7455 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7456 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7457 
7458 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7459 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7460 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7461 
7462 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7463 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7464 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7465 
7466 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7467 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7468 	    sysctl_cim_la, "A", "CIM logic analyzer");
7469 
7470 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7471 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7472 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7473 
7474 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7475 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7476 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7477 
7478 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7479 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7480 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7481 
7482 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7483 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7484 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7485 
7486 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7487 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7488 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7489 
7490 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7491 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7492 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7493 
7494 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7495 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7496 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7497 
7498 	if (chip_id(sc) > CHELSIO_T4) {
7499 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7500 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7501 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7502 		    "CIM OBQ 6 (SGE0-RX)");
7503 
7504 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7505 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7506 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7507 		    "CIM OBQ 7 (SGE1-RX)");
7508 	}
7509 
7510 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7511 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7512 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7513 
7514 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7515 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7516 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7517 
7518 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7519 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7520 	    sysctl_cpl_stats, "A", "CPL statistics");
7521 
7522 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7523 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7524 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7525 
7526 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7527 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7528 	    sysctl_tid_stats, "A", "tid stats");
7529 
7530 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7531 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7532 	    sysctl_devlog, "A", "firmware's device log");
7533 
7534 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7535 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7536 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7537 
7538 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7539 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7540 	    sysctl_hw_sched, "A", "hardware scheduler ");
7541 
7542 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7543 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7544 	    sysctl_l2t, "A", "hardware L2 table");
7545 
7546 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7547 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7548 	    sysctl_smt, "A", "hardware source MAC table");
7549 
7550 #ifdef INET6
7551 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7552 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7553 	    sysctl_clip, "A", "active CLIP table entries");
7554 #endif
7555 
7556 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7557 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7558 	    sysctl_lb_stats, "A", "loopback statistics");
7559 
7560 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7561 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7562 	    sysctl_meminfo, "A", "memory regions");
7563 
7564 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7565 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7566 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7567 	    "A", "MPS TCAM entries");
7568 
7569 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7570 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7571 	    sysctl_path_mtus, "A", "path MTUs");
7572 
7573 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7574 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7575 	    sysctl_pm_stats, "A", "PM statistics");
7576 
7577 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7578 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7579 	    sysctl_rdma_stats, "A", "RDMA statistics");
7580 
7581 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7582 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7583 	    sysctl_tcp_stats, "A", "TCP statistics");
7584 
7585 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7586 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7587 	    sysctl_tids, "A", "TID information");
7588 
7589 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7590 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7591 	    sysctl_tp_err_stats, "A", "TP error statistics");
7592 
7593 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7594 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7595 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7596 
7597 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7598 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7599 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7600 
7601 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7602 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7603 	    sysctl_tp_la, "A", "TP logic analyzer");
7604 
7605 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7606 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7607 	    sysctl_tx_rate, "A", "Tx rate");
7608 
7609 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7610 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7611 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7612 
7613 	if (chip_id(sc) >= CHELSIO_T5) {
7614 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7615 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7616 		    sysctl_wcwr_stats, "A", "write combined work requests");
7617 	}
7618 
7619 #ifdef KERN_TLS
7620 	if (is_ktls(sc)) {
7621 		/*
7622 		 * dev.t4nex.0.tls.
7623 		 */
7624 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7625 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7626 		children = SYSCTL_CHILDREN(oid);
7627 
7628 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7629 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7630 		    "keys in work requests (1) or attempt to store TLS keys "
7631 		    "in card memory.");
7632 
7633 		if (is_t6(sc))
7634 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7635 			    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to "
7636 			    "combine TCB field updates with TLS record work "
7637 			    "requests.");
7638 	}
7639 #endif
7640 
7641 #ifdef TCP_OFFLOAD
7642 	if (is_offload(sc)) {
7643 		int i;
7644 		char s[4];
7645 
7646 		/*
7647 		 * dev.t4nex.X.toe.
7648 		 */
7649 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7650 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7651 		children = SYSCTL_CHILDREN(oid);
7652 
7653 		sc->tt.cong_algorithm = -1;
7654 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7655 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7656 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7657 		    "3 = highspeed)");
7658 
7659 		sc->tt.sndbuf = -1;
7660 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7661 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7662 
7663 		sc->tt.ddp = 0;
7664 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7665 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7666 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7667 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7668 
7669 		sc->tt.rx_coalesce = -1;
7670 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7671 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7672 
7673 		sc->tt.tls = 0;
7674 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7675 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7676 		    "Inline TLS allowed");
7677 
7678 		sc->tt.tx_align = -1;
7679 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7680 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7681 
7682 		sc->tt.tx_zcopy = 0;
7683 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7684 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7685 		    "Enable zero-copy aio_write(2)");
7686 
7687 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7688 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7689 		    "cop_managed_offloading", CTLFLAG_RW,
7690 		    &sc->tt.cop_managed_offloading, 0,
7691 		    "COP (Connection Offload Policy) controls all TOE offload");
7692 
7693 		sc->tt.autorcvbuf_inc = 16 * 1024;
7694 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7695 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7696 		    "autorcvbuf increment");
7697 
7698 		sc->tt.update_hc_on_pmtu_change = 1;
7699 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7700 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7701 		    &sc->tt.update_hc_on_pmtu_change, 0,
7702 		    "Update hostcache entry if the PMTU changes");
7703 
7704 		sc->tt.iso = 1;
7705 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7706 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7707 
7708 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7709 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7710 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7711 
7712 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7713 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7714 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7715 
7716 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7717 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7718 		    sysctl_tp_tick, "A", "DACK tick (us)");
7719 
7720 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7721 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7722 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7723 
7724 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7725 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7726 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7727 		    "Minimum retransmit interval (us)");
7728 
7729 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7730 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7731 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7732 		    "Maximum retransmit interval (us)");
7733 
7734 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7735 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7736 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7737 		    "Persist timer min (us)");
7738 
7739 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7740 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7741 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7742 		    "Persist timer max (us)");
7743 
7744 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7745 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7746 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7747 		    "Keepalive idle timer (us)");
7748 
7749 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7750 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7751 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7752 		    "Keepalive interval timer (us)");
7753 
7754 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7755 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7756 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7757 
7758 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7759 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7760 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7761 		    "FINWAIT2 timer (us)");
7762 
7763 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7764 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7765 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7766 		    "Number of SYN retransmissions before abort");
7767 
7768 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7769 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7770 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7771 		    "Number of retransmissions before abort");
7772 
7773 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7774 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7775 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7776 		    "Number of keepalive probes before abort");
7777 
7778 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7779 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7780 		    "TOE retransmit backoffs");
7781 		children = SYSCTL_CHILDREN(oid);
7782 		for (i = 0; i < 16; i++) {
7783 			snprintf(s, sizeof(s), "%u", i);
7784 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7785 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7786 			    i, sysctl_tp_backoff, "IU",
7787 			    "TOE retransmit backoff");
7788 		}
7789 	}
7790 #endif
7791 }
7792 
7793 void
7794 vi_sysctls(struct vi_info *vi)
7795 {
7796 	struct sysctl_ctx_list *ctx = &vi->ctx;
7797 	struct sysctl_oid *oid;
7798 	struct sysctl_oid_list *children;
7799 
7800 	/*
7801 	 * dev.v?(cxgbe|cxl).X.
7802 	 */
7803 	oid = device_get_sysctl_tree(vi->dev);
7804 	children = SYSCTL_CHILDREN(oid);
7805 
7806 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7807 	    vi->viid, "VI identifer");
7808 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7809 	    &vi->nrxq, 0, "# of rx queues");
7810 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7811 	    &vi->ntxq, 0, "# of tx queues");
7812 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7813 	    &vi->first_rxq, 0, "index of first rx queue");
7814 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7815 	    &vi->first_txq, 0, "index of first tx queue");
7816 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7817 	    vi->rss_base, "start of RSS indirection table");
7818 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7819 	    vi->rss_size, "size of RSS indirection table");
7820 
7821 	if (IS_MAIN_VI(vi)) {
7822 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7823 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7824 		    sysctl_noflowq, "IU",
7825 		    "Reserve queue 0 for non-flowid packets");
7826 	}
7827 
7828 	if (vi->adapter->flags & IS_VF) {
7829 		MPASS(vi->flags & TX_USES_VM_WR);
7830 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7831 		    NULL, 1, "use VM work requests for transmit");
7832 	} else {
7833 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7834 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7835 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7836 	}
7837 
7838 #ifdef TCP_OFFLOAD
7839 	if (vi->nofldrxq != 0) {
7840 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7841 		    &vi->nofldrxq, 0,
7842 		    "# of rx queues for offloaded TCP connections");
7843 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7844 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7845 		    "index of first TOE rx queue");
7846 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7847 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7848 		    sysctl_holdoff_tmr_idx_ofld, "I",
7849 		    "holdoff timer index for TOE queues");
7850 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7851 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7852 		    sysctl_holdoff_pktc_idx_ofld, "I",
7853 		    "holdoff packet counter index for TOE queues");
7854 	}
7855 #endif
7856 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7857 	if (vi->nofldtxq != 0) {
7858 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7859 		    &vi->nofldtxq, 0,
7860 		    "# of tx queues for TOE/ETHOFLD");
7861 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7862 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7863 		    "index of first TOE/ETHOFLD tx queue");
7864 	}
7865 #endif
7866 #ifdef DEV_NETMAP
7867 	if (vi->nnmrxq != 0) {
7868 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7869 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7870 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7871 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7872 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7873 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7874 		    "index of first netmap rx queue");
7875 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7876 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7877 		    "index of first netmap tx queue");
7878 	}
7879 #endif
7880 
7881 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7882 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7883 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7884 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7885 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7886 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7887 
7888 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7889 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7890 	    sysctl_qsize_rxq, "I", "rx queue size");
7891 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7892 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7893 	    sysctl_qsize_txq, "I", "tx queue size");
7894 }
7895 
7896 static void
7897 cxgbe_sysctls(struct port_info *pi)
7898 {
7899 	struct sysctl_ctx_list *ctx = &pi->ctx;
7900 	struct sysctl_oid *oid;
7901 	struct sysctl_oid_list *children, *children2;
7902 	struct adapter *sc = pi->adapter;
7903 	int i;
7904 	char name[16];
7905 	static char *tc_flags = {"\20\1USER"};
7906 
7907 	/*
7908 	 * dev.cxgbe.X.
7909 	 */
7910 	oid = device_get_sysctl_tree(pi->dev);
7911 	children = SYSCTL_CHILDREN(oid);
7912 
7913 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7914 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7915 	    sysctl_linkdnrc, "A", "reason why link is down");
7916 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7917 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7918 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7919 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
7920 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7921 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7922 		    sysctl_btphy, "I", "PHY firmware version");
7923 	}
7924 
7925 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7926 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7927 	    sysctl_pause_settings, "A",
7928 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7929 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
7930 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
7931 	    "FEC in use on the link");
7932 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
7933 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7934 	    sysctl_requested_fec, "A",
7935 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7936 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7937 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7938 	    "FEC recommended by the cable/transceiver");
7939 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7940 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7941 	    sysctl_autoneg, "I",
7942 	    "autonegotiation (-1 = not supported)");
7943 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
7944 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7945 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
7946 
7947 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
7948 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
7949 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7950 	    &pi->link_cfg.pcaps, 0, "port capabilities");
7951 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7952 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
7953 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7954 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7955 
7956 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7957 	    port_top_speed(pi), "max speed (in Gbps)");
7958 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7959 	    pi->mps_bg_map, "MPS buffer group map");
7960 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
7961 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
7962 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_c_chan", CTLFLAG_RD, NULL,
7963 	    pi->rx_c_chan, "TP rx c-channel");
7964 
7965 	if (sc->flags & IS_VF)
7966 		return;
7967 
7968 	/*
7969 	 * dev.(cxgbe|cxl).X.tc.
7970 	 */
7971 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
7972 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7973 	    "Tx scheduler traffic classes (cl_rl)");
7974 	children2 = SYSCTL_CHILDREN(oid);
7975 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
7976 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
7977 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
7978 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
7979 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
7980 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
7981 	for (i = 0; i < sc->params.nsched_cls; i++) {
7982 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
7983 
7984 		snprintf(name, sizeof(name), "%d", i);
7985 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
7986 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
7987 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
7988 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
7989 		    CTLFLAG_RD, &tc->state, 0, "current state");
7990 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
7991 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
7992 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
7993 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
7994 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
7995 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
7996 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7997 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
7998 		    "traffic class parameters");
7999 	}
8000 
8001 	/*
8002 	 * dev.cxgbe.X.stats.
8003 	 */
8004 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
8005 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
8006 	children = SYSCTL_CHILDREN(oid);
8007 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
8008 	    &pi->tx_parse_error, 0,
8009 	    "# of tx packets with invalid length or # of segments");
8010 
8011 #define T4_REGSTAT(name, stat, desc) \
8012     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8013         CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8014 	(is_t4(sc) ? PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L) : \
8015 	T5_PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L)), \
8016         sysctl_handle_t4_reg64, "QU", desc)
8017 
8018 /* We get these from port_stats and they may be stale by up to 1s */
8019 #define T4_PORTSTAT(name, desc) \
8020 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
8021 	    &pi->stats.name, desc)
8022 
8023 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
8024 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
8025 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
8026 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
8027 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
8028 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
8029 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
8030 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
8031 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
8032 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
8033 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
8034 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
8035 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
8036 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
8037 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
8038 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
8039 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
8040 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
8041 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
8042 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
8043 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
8044 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
8045 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
8046 
8047 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
8048 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
8049 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
8050 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
8051 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
8052 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
8053 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
8054 	if (is_t6(sc)) {
8055 		T4_PORTSTAT(rx_fcs_err,
8056 		    "# of frames received with bad FCS since last link up");
8057 	} else {
8058 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
8059 		    "# of frames received with bad FCS");
8060 	}
8061 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
8062 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
8063 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
8064 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
8065 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
8066 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
8067 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
8068 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
8069 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
8070 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
8071 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
8072 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
8073 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
8074 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
8075 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
8076 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
8077 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
8078 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
8079 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
8080 
8081 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
8082 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
8083 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
8084 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
8085 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
8086 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
8087 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
8088 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
8089 
8090 #undef T4_REGSTAT
8091 #undef T4_PORTSTAT
8092 }
8093 
8094 static int
8095 sysctl_int_array(SYSCTL_HANDLER_ARGS)
8096 {
8097 	int rc, *i, space = 0;
8098 	struct sbuf sb;
8099 
8100 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
8101 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
8102 		if (space)
8103 			sbuf_printf(&sb, " ");
8104 		sbuf_printf(&sb, "%d", *i);
8105 		space = 1;
8106 	}
8107 	rc = sbuf_finish(&sb);
8108 	sbuf_delete(&sb);
8109 	return (rc);
8110 }
8111 
8112 static int
8113 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
8114 {
8115 	int rc;
8116 	struct sbuf *sb;
8117 
8118 	rc = sysctl_wire_old_buffer(req, 0);
8119 	if (rc != 0)
8120 		return(rc);
8121 
8122 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8123 	if (sb == NULL)
8124 		return (ENOMEM);
8125 
8126 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8127 	rc = sbuf_finish(sb);
8128 	sbuf_delete(sb);
8129 
8130 	return (rc);
8131 }
8132 
8133 static int
8134 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8135 {
8136 	int rc;
8137 	struct sbuf *sb;
8138 
8139 	rc = sysctl_wire_old_buffer(req, 0);
8140 	if (rc != 0)
8141 		return(rc);
8142 
8143 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8144 	if (sb == NULL)
8145 		return (ENOMEM);
8146 
8147 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8148 	rc = sbuf_finish(sb);
8149 	sbuf_delete(sb);
8150 
8151 	return (rc);
8152 }
8153 
8154 static int
8155 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8156 {
8157 	struct port_info *pi = arg1;
8158 	int op = arg2;
8159 	struct adapter *sc = pi->adapter;
8160 	u_int v;
8161 	int rc;
8162 
8163 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8164 	if (rc)
8165 		return (rc);
8166 	if (hw_off_limits(sc))
8167 		rc = ENXIO;
8168 	else {
8169 		/* XXX: magic numbers */
8170 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8171 		    op ? 0x20 : 0xc820, &v);
8172 	}
8173 	end_synchronized_op(sc, 0);
8174 	if (rc)
8175 		return (rc);
8176 	if (op == 0)
8177 		v /= 256;
8178 
8179 	rc = sysctl_handle_int(oidp, &v, 0, req);
8180 	return (rc);
8181 }
8182 
8183 static int
8184 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8185 {
8186 	struct vi_info *vi = arg1;
8187 	int rc, val;
8188 
8189 	val = vi->rsrv_noflowq;
8190 	rc = sysctl_handle_int(oidp, &val, 0, req);
8191 	if (rc != 0 || req->newptr == NULL)
8192 		return (rc);
8193 
8194 	if ((val >= 1) && (vi->ntxq > 1))
8195 		vi->rsrv_noflowq = 1;
8196 	else
8197 		vi->rsrv_noflowq = 0;
8198 
8199 	return (rc);
8200 }
8201 
8202 static int
8203 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8204 {
8205 	struct vi_info *vi = arg1;
8206 	struct adapter *sc = vi->adapter;
8207 	int rc, val, i;
8208 
8209 	MPASS(!(sc->flags & IS_VF));
8210 
8211 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8212 	rc = sysctl_handle_int(oidp, &val, 0, req);
8213 	if (rc != 0 || req->newptr == NULL)
8214 		return (rc);
8215 
8216 	if (val != 0 && val != 1)
8217 		return (EINVAL);
8218 
8219 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8220 	    "t4txvm");
8221 	if (rc)
8222 		return (rc);
8223 	if (hw_off_limits(sc))
8224 		rc = ENXIO;
8225 	else if (if_getdrvflags(vi->ifp) & IFF_DRV_RUNNING) {
8226 		/*
8227 		 * We don't want parse_pkt to run with one setting (VF or PF)
8228 		 * and then eth_tx to see a different setting but still use
8229 		 * stale information calculated by parse_pkt.
8230 		 */
8231 		rc = EBUSY;
8232 	} else {
8233 		struct port_info *pi = vi->pi;
8234 		struct sge_txq *txq;
8235 		uint32_t ctrl0;
8236 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8237 
8238 		if (val) {
8239 			vi->flags |= TX_USES_VM_WR;
8240 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_VM_TSO);
8241 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8242 			    V_TXPKT_INTF(pi->tx_chan));
8243 			if (!(sc->flags & IS_VF))
8244 				npkt--;
8245 		} else {
8246 			vi->flags &= ~TX_USES_VM_WR;
8247 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_TSO);
8248 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8249 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8250 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8251 		}
8252 		for_each_txq(vi, i, txq) {
8253 			txq->cpl_ctrl0 = ctrl0;
8254 			txq->txp.max_npkt = npkt;
8255 		}
8256 	}
8257 	end_synchronized_op(sc, LOCK_HELD);
8258 	return (rc);
8259 }
8260 
8261 static int
8262 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8263 {
8264 	struct vi_info *vi = arg1;
8265 	struct adapter *sc = vi->adapter;
8266 	int idx, rc, i;
8267 	struct sge_rxq *rxq;
8268 	uint8_t v;
8269 
8270 	idx = vi->tmr_idx;
8271 
8272 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8273 	if (rc != 0 || req->newptr == NULL)
8274 		return (rc);
8275 
8276 	if (idx < 0 || idx >= SGE_NTIMERS)
8277 		return (EINVAL);
8278 
8279 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8280 	    "t4tmr");
8281 	if (rc)
8282 		return (rc);
8283 
8284 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8285 	for_each_rxq(vi, i, rxq) {
8286 #ifdef atomic_store_rel_8
8287 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8288 #else
8289 		rxq->iq.intr_params = v;
8290 #endif
8291 	}
8292 	vi->tmr_idx = idx;
8293 
8294 	end_synchronized_op(sc, LOCK_HELD);
8295 	return (0);
8296 }
8297 
8298 static int
8299 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8300 {
8301 	struct vi_info *vi = arg1;
8302 	struct adapter *sc = vi->adapter;
8303 	int idx, rc;
8304 
8305 	idx = vi->pktc_idx;
8306 
8307 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8308 	if (rc != 0 || req->newptr == NULL)
8309 		return (rc);
8310 
8311 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8312 		return (EINVAL);
8313 
8314 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8315 	    "t4pktc");
8316 	if (rc)
8317 		return (rc);
8318 
8319 	if (vi->flags & VI_INIT_DONE)
8320 		rc = EBUSY; /* cannot be changed once the queues are created */
8321 	else
8322 		vi->pktc_idx = idx;
8323 
8324 	end_synchronized_op(sc, LOCK_HELD);
8325 	return (rc);
8326 }
8327 
8328 static int
8329 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8330 {
8331 	struct vi_info *vi = arg1;
8332 	struct adapter *sc = vi->adapter;
8333 	int qsize, rc;
8334 
8335 	qsize = vi->qsize_rxq;
8336 
8337 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8338 	if (rc != 0 || req->newptr == NULL)
8339 		return (rc);
8340 
8341 	if (qsize < 128 || (qsize & 7))
8342 		return (EINVAL);
8343 
8344 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8345 	    "t4rxqs");
8346 	if (rc)
8347 		return (rc);
8348 
8349 	if (vi->flags & VI_INIT_DONE)
8350 		rc = EBUSY; /* cannot be changed once the queues are created */
8351 	else
8352 		vi->qsize_rxq = qsize;
8353 
8354 	end_synchronized_op(sc, LOCK_HELD);
8355 	return (rc);
8356 }
8357 
8358 static int
8359 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8360 {
8361 	struct vi_info *vi = arg1;
8362 	struct adapter *sc = vi->adapter;
8363 	int qsize, rc;
8364 
8365 	qsize = vi->qsize_txq;
8366 
8367 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8368 	if (rc != 0 || req->newptr == NULL)
8369 		return (rc);
8370 
8371 	if (qsize < 128 || qsize > 65536)
8372 		return (EINVAL);
8373 
8374 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8375 	    "t4txqs");
8376 	if (rc)
8377 		return (rc);
8378 
8379 	if (vi->flags & VI_INIT_DONE)
8380 		rc = EBUSY; /* cannot be changed once the queues are created */
8381 	else
8382 		vi->qsize_txq = qsize;
8383 
8384 	end_synchronized_op(sc, LOCK_HELD);
8385 	return (rc);
8386 }
8387 
8388 static int
8389 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8390 {
8391 	struct port_info *pi = arg1;
8392 	struct adapter *sc = pi->adapter;
8393 	struct link_config *lc = &pi->link_cfg;
8394 	int rc;
8395 
8396 	if (req->newptr == NULL) {
8397 		struct sbuf *sb;
8398 		static char *bits = "\20\1RX\2TX\3AUTO";
8399 
8400 		rc = sysctl_wire_old_buffer(req, 0);
8401 		if (rc != 0)
8402 			return(rc);
8403 
8404 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8405 		if (sb == NULL)
8406 			return (ENOMEM);
8407 
8408 		if (lc->link_ok) {
8409 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8410 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8411 		} else {
8412 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8413 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8414 		}
8415 		rc = sbuf_finish(sb);
8416 		sbuf_delete(sb);
8417 	} else {
8418 		char s[2];
8419 		int n;
8420 
8421 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8422 		    PAUSE_AUTONEG));
8423 		s[1] = 0;
8424 
8425 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8426 		if (rc != 0)
8427 			return(rc);
8428 
8429 		if (s[1] != 0)
8430 			return (EINVAL);
8431 		if (s[0] < '0' || s[0] > '9')
8432 			return (EINVAL);	/* not a number */
8433 		n = s[0] - '0';
8434 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8435 			return (EINVAL);	/* some other bit is set too */
8436 
8437 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8438 		    "t4PAUSE");
8439 		if (rc)
8440 			return (rc);
8441 		if (!hw_off_limits(sc)) {
8442 			PORT_LOCK(pi);
8443 			lc->requested_fc = n;
8444 			fixup_link_config(pi);
8445 			if (pi->up_vis > 0)
8446 				rc = apply_link_config(pi);
8447 			set_current_media(pi);
8448 			PORT_UNLOCK(pi);
8449 		}
8450 		end_synchronized_op(sc, 0);
8451 	}
8452 
8453 	return (rc);
8454 }
8455 
8456 static int
8457 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
8458 {
8459 	struct port_info *pi = arg1;
8460 	struct link_config *lc = &pi->link_cfg;
8461 	int rc;
8462 	struct sbuf *sb;
8463 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2";
8464 
8465 	rc = sysctl_wire_old_buffer(req, 0);
8466 	if (rc != 0)
8467 		return(rc);
8468 
8469 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8470 	if (sb == NULL)
8471 		return (ENOMEM);
8472 	if (lc->link_ok)
8473 		sbuf_printf(sb, "%b", lc->fec, bits);
8474 	else
8475 		sbuf_printf(sb, "no link");
8476 	rc = sbuf_finish(sb);
8477 	sbuf_delete(sb);
8478 
8479 	return (rc);
8480 }
8481 
8482 static int
8483 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
8484 {
8485 	struct port_info *pi = arg1;
8486 	struct adapter *sc = pi->adapter;
8487 	struct link_config *lc = &pi->link_cfg;
8488 	int rc;
8489 	int8_t old;
8490 
8491 	if (req->newptr == NULL) {
8492 		struct sbuf *sb;
8493 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8494 		    "\5RSVD3\6auto\7module";
8495 
8496 		rc = sysctl_wire_old_buffer(req, 0);
8497 		if (rc != 0)
8498 			return(rc);
8499 
8500 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8501 		if (sb == NULL)
8502 			return (ENOMEM);
8503 
8504 		sbuf_printf(sb, "%b", lc->requested_fec, bits);
8505 		rc = sbuf_finish(sb);
8506 		sbuf_delete(sb);
8507 	} else {
8508 		char s[8];
8509 		int n;
8510 
8511 		snprintf(s, sizeof(s), "%d",
8512 		    lc->requested_fec == FEC_AUTO ? -1 :
8513 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8514 
8515 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8516 		if (rc != 0)
8517 			return(rc);
8518 
8519 		n = strtol(&s[0], NULL, 0);
8520 		if (n < 0 || n & FEC_AUTO)
8521 			n = FEC_AUTO;
8522 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8523 			return (EINVAL);/* some other bit is set too */
8524 
8525 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8526 		    "t4reqf");
8527 		if (rc)
8528 			return (rc);
8529 		PORT_LOCK(pi);
8530 		old = lc->requested_fec;
8531 		if (n == FEC_AUTO)
8532 			lc->requested_fec = FEC_AUTO;
8533 		else if (n == 0 || n == FEC_NONE)
8534 			lc->requested_fec = FEC_NONE;
8535 		else {
8536 			if ((lc->pcaps |
8537 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8538 			    lc->pcaps) {
8539 				rc = ENOTSUP;
8540 				goto done;
8541 			}
8542 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8543 			    FEC_MODULE);
8544 		}
8545 		if (!hw_off_limits(sc)) {
8546 			fixup_link_config(pi);
8547 			if (pi->up_vis > 0) {
8548 				rc = apply_link_config(pi);
8549 				if (rc != 0) {
8550 					lc->requested_fec = old;
8551 					if (rc == FW_EPROTO)
8552 						rc = ENOTSUP;
8553 				}
8554 			}
8555 		}
8556 done:
8557 		PORT_UNLOCK(pi);
8558 		end_synchronized_op(sc, 0);
8559 	}
8560 
8561 	return (rc);
8562 }
8563 
8564 static int
8565 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8566 {
8567 	struct port_info *pi = arg1;
8568 	struct adapter *sc = pi->adapter;
8569 	struct link_config *lc = &pi->link_cfg;
8570 	int rc;
8571 	int8_t fec;
8572 	struct sbuf *sb;
8573 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8574 
8575 	rc = sysctl_wire_old_buffer(req, 0);
8576 	if (rc != 0)
8577 		return (rc);
8578 
8579 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8580 	if (sb == NULL)
8581 		return (ENOMEM);
8582 
8583 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8584 		rc = EBUSY;
8585 		goto done;
8586 	}
8587 	if (hw_off_limits(sc)) {
8588 		rc = ENXIO;
8589 		goto done;
8590 	}
8591 	PORT_LOCK(pi);
8592 	if (pi->up_vis == 0) {
8593 		/*
8594 		 * If all the interfaces are administratively down the firmware
8595 		 * does not report transceiver changes.  Refresh port info here.
8596 		 * This is the only reason we have a synchronized op in this
8597 		 * function.  Just PORT_LOCK would have been enough otherwise.
8598 		 */
8599 		t4_update_port_info(pi);
8600 	}
8601 
8602 	fec = lc->fec_hint;
8603 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8604 	    !fec_supported(lc->pcaps)) {
8605 		sbuf_printf(sb, "n/a");
8606 	} else {
8607 		if (fec == 0)
8608 			fec = FEC_NONE;
8609 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8610 	}
8611 	rc = sbuf_finish(sb);
8612 	PORT_UNLOCK(pi);
8613 done:
8614 	sbuf_delete(sb);
8615 	end_synchronized_op(sc, 0);
8616 
8617 	return (rc);
8618 }
8619 
8620 static int
8621 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8622 {
8623 	struct port_info *pi = arg1;
8624 	struct adapter *sc = pi->adapter;
8625 	struct link_config *lc = &pi->link_cfg;
8626 	int rc, val;
8627 
8628 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8629 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8630 	else
8631 		val = -1;
8632 	rc = sysctl_handle_int(oidp, &val, 0, req);
8633 	if (rc != 0 || req->newptr == NULL)
8634 		return (rc);
8635 	if (val == 0)
8636 		val = AUTONEG_DISABLE;
8637 	else if (val == 1)
8638 		val = AUTONEG_ENABLE;
8639 	else
8640 		val = AUTONEG_AUTO;
8641 
8642 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8643 	    "t4aneg");
8644 	if (rc)
8645 		return (rc);
8646 	PORT_LOCK(pi);
8647 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8648 		rc = ENOTSUP;
8649 		goto done;
8650 	}
8651 	lc->requested_aneg = val;
8652 	if (!hw_off_limits(sc)) {
8653 		fixup_link_config(pi);
8654 		if (pi->up_vis > 0)
8655 			rc = apply_link_config(pi);
8656 		set_current_media(pi);
8657 	}
8658 done:
8659 	PORT_UNLOCK(pi);
8660 	end_synchronized_op(sc, 0);
8661 	return (rc);
8662 }
8663 
8664 static int
8665 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
8666 {
8667 	struct port_info *pi = arg1;
8668 	struct adapter *sc = pi->adapter;
8669 	struct link_config *lc = &pi->link_cfg;
8670 	int rc, val;
8671 
8672 	val = lc->force_fec;
8673 	MPASS(val >= -1 && val <= 1);
8674 	rc = sysctl_handle_int(oidp, &val, 0, req);
8675 	if (rc != 0 || req->newptr == NULL)
8676 		return (rc);
8677 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
8678 		return (ENOTSUP);
8679 	if (val < -1 || val > 1)
8680 		return (EINVAL);
8681 
8682 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
8683 	if (rc)
8684 		return (rc);
8685 	PORT_LOCK(pi);
8686 	lc->force_fec = val;
8687 	if (!hw_off_limits(sc)) {
8688 		fixup_link_config(pi);
8689 		if (pi->up_vis > 0)
8690 			rc = apply_link_config(pi);
8691 	}
8692 	PORT_UNLOCK(pi);
8693 	end_synchronized_op(sc, 0);
8694 	return (rc);
8695 }
8696 
8697 static int
8698 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8699 {
8700 	struct adapter *sc = arg1;
8701 	int rc, reg = arg2;
8702 	uint64_t val;
8703 
8704 	mtx_lock(&sc->reg_lock);
8705 	if (hw_off_limits(sc))
8706 		rc = ENXIO;
8707 	else {
8708 		rc = 0;
8709 		val = t4_read_reg64(sc, reg);
8710 	}
8711 	mtx_unlock(&sc->reg_lock);
8712 	if (rc == 0)
8713 		rc = sysctl_handle_64(oidp, &val, 0, req);
8714 	return (rc);
8715 }
8716 
8717 static int
8718 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8719 {
8720 	struct adapter *sc = arg1;
8721 	int rc, t;
8722 	uint32_t param, val;
8723 
8724 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8725 	if (rc)
8726 		return (rc);
8727 	if (hw_off_limits(sc))
8728 		rc = ENXIO;
8729 	else {
8730 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8731 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8732 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8733 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8734 	}
8735 	end_synchronized_op(sc, 0);
8736 	if (rc)
8737 		return (rc);
8738 
8739 	/* unknown is returned as 0 but we display -1 in that case */
8740 	t = val == 0 ? -1 : val;
8741 
8742 	rc = sysctl_handle_int(oidp, &t, 0, req);
8743 	return (rc);
8744 }
8745 
8746 static int
8747 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8748 {
8749 	struct adapter *sc = arg1;
8750 	int rc;
8751 	uint32_t param, val;
8752 
8753 	if (sc->params.core_vdd == 0) {
8754 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8755 		    "t4vdd");
8756 		if (rc)
8757 			return (rc);
8758 		if (hw_off_limits(sc))
8759 			rc = ENXIO;
8760 		else {
8761 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8762 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8763 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8764 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8765 			    &param, &val);
8766 		}
8767 		end_synchronized_op(sc, 0);
8768 		if (rc)
8769 			return (rc);
8770 		sc->params.core_vdd = val;
8771 	}
8772 
8773 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8774 }
8775 
8776 static int
8777 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8778 {
8779 	struct adapter *sc = arg1;
8780 	int rc, v;
8781 	uint32_t param, val;
8782 
8783 	v = sc->sensor_resets;
8784 	rc = sysctl_handle_int(oidp, &v, 0, req);
8785 	if (rc != 0 || req->newptr == NULL || v <= 0)
8786 		return (rc);
8787 
8788 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8789 	    chip_id(sc) < CHELSIO_T5)
8790 		return (ENOTSUP);
8791 
8792 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8793 	if (rc)
8794 		return (rc);
8795 	if (hw_off_limits(sc))
8796 		rc = ENXIO;
8797 	else {
8798 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8799 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8800 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8801 		val = 1;
8802 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8803 	}
8804 	end_synchronized_op(sc, 0);
8805 	if (rc == 0)
8806 		sc->sensor_resets++;
8807 	return (rc);
8808 }
8809 
8810 static int
8811 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8812 {
8813 	struct adapter *sc = arg1;
8814 	struct sbuf *sb;
8815 	int rc;
8816 	uint32_t param, val;
8817 
8818 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8819 	if (rc)
8820 		return (rc);
8821 	if (hw_off_limits(sc))
8822 		rc = ENXIO;
8823 	else {
8824 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8825 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8826 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8827 	}
8828 	end_synchronized_op(sc, 0);
8829 	if (rc)
8830 		return (rc);
8831 
8832 	rc = sysctl_wire_old_buffer(req, 0);
8833 	if (rc != 0)
8834 		return (rc);
8835 
8836 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8837 	if (sb == NULL)
8838 		return (ENOMEM);
8839 
8840 	if (val == 0xffffffff) {
8841 		/* Only debug and custom firmwares report load averages. */
8842 		sbuf_printf(sb, "not available");
8843 	} else {
8844 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8845 		    (val >> 16) & 0xff);
8846 	}
8847 	rc = sbuf_finish(sb);
8848 	sbuf_delete(sb);
8849 
8850 	return (rc);
8851 }
8852 
8853 static int
8854 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8855 {
8856 	struct adapter *sc = arg1;
8857 	struct sbuf *sb;
8858 	int rc, i;
8859 	uint16_t incr[NMTUS][NCCTRL_WIN];
8860 	static const char *dec_fac[] = {
8861 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8862 		"0.9375"
8863 	};
8864 
8865 	rc = sysctl_wire_old_buffer(req, 0);
8866 	if (rc != 0)
8867 		return (rc);
8868 
8869 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8870 	if (sb == NULL)
8871 		return (ENOMEM);
8872 
8873 	mtx_lock(&sc->reg_lock);
8874 	if (hw_off_limits(sc))
8875 		rc = ENXIO;
8876 	else
8877 		t4_read_cong_tbl(sc, incr);
8878 	mtx_unlock(&sc->reg_lock);
8879 	if (rc)
8880 		goto done;
8881 
8882 	for (i = 0; i < NCCTRL_WIN; ++i) {
8883 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8884 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8885 		    incr[5][i], incr[6][i], incr[7][i]);
8886 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8887 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8888 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8889 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8890 	}
8891 
8892 	rc = sbuf_finish(sb);
8893 done:
8894 	sbuf_delete(sb);
8895 	return (rc);
8896 }
8897 
8898 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8899 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8900 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8901 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8902 };
8903 
8904 static int
8905 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8906 {
8907 	struct adapter *sc = arg1;
8908 	struct sbuf *sb;
8909 	int rc, i, n, qid = arg2;
8910 	uint32_t *buf, *p;
8911 	char *qtype;
8912 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8913 
8914 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8915 	    ("%s: bad qid %d\n", __func__, qid));
8916 
8917 	if (qid < CIM_NUM_IBQ) {
8918 		/* inbound queue */
8919 		qtype = "IBQ";
8920 		n = 4 * CIM_IBQ_SIZE;
8921 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8922 		mtx_lock(&sc->reg_lock);
8923 		if (hw_off_limits(sc))
8924 			rc = -ENXIO;
8925 		else
8926 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8927 		mtx_unlock(&sc->reg_lock);
8928 	} else {
8929 		/* outbound queue */
8930 		qtype = "OBQ";
8931 		qid -= CIM_NUM_IBQ;
8932 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8933 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8934 		mtx_lock(&sc->reg_lock);
8935 		if (hw_off_limits(sc))
8936 			rc = -ENXIO;
8937 		else
8938 			rc = t4_read_cim_obq(sc, qid, buf, n);
8939 		mtx_unlock(&sc->reg_lock);
8940 	}
8941 
8942 	if (rc < 0) {
8943 		rc = -rc;
8944 		goto done;
8945 	}
8946 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
8947 
8948 	rc = sysctl_wire_old_buffer(req, 0);
8949 	if (rc != 0)
8950 		goto done;
8951 
8952 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8953 	if (sb == NULL) {
8954 		rc = ENOMEM;
8955 		goto done;
8956 	}
8957 
8958 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8959 	for (i = 0, p = buf; i < n; i += 16, p += 4)
8960 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
8961 		    p[2], p[3]);
8962 
8963 	rc = sbuf_finish(sb);
8964 	sbuf_delete(sb);
8965 done:
8966 	free(buf, M_CXGBE);
8967 	return (rc);
8968 }
8969 
8970 static void
8971 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8972 {
8973 	uint32_t *p;
8974 
8975 	sbuf_printf(sb, "Status   Data      PC%s",
8976 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8977 	    "     LS0Stat  LS0Addr             LS0Data");
8978 
8979 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
8980 		if (cfg & F_UPDBGLACAPTPCONLY) {
8981 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
8982 			    p[6], p[7]);
8983 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
8984 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
8985 			    p[4] & 0xff, p[5] >> 8);
8986 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
8987 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8988 			    p[1] & 0xf, p[2] >> 4);
8989 		} else {
8990 			sbuf_printf(sb,
8991 			    "\n  %02x   %x%07x %x%07x %08x %08x "
8992 			    "%08x%08x%08x%08x",
8993 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8994 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
8995 			    p[6], p[7]);
8996 		}
8997 	}
8998 }
8999 
9000 static void
9001 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9002 {
9003 	uint32_t *p;
9004 
9005 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
9006 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9007 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
9008 
9009 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
9010 		if (cfg & F_UPDBGLACAPTPCONLY) {
9011 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
9012 			    p[3] & 0xff, p[2], p[1], p[0]);
9013 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
9014 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
9015 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
9016 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
9017 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
9018 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
9019 			    p[6] >> 16);
9020 		} else {
9021 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
9022 			    "%08x %08x %08x %08x %08x %08x",
9023 			    (p[9] >> 16) & 0xff,
9024 			    p[9] & 0xffff, p[8] >> 16,
9025 			    p[8] & 0xffff, p[7] >> 16,
9026 			    p[7] & 0xffff, p[6] >> 16,
9027 			    p[2], p[1], p[0], p[5], p[4], p[3]);
9028 		}
9029 	}
9030 }
9031 
9032 static int
9033 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
9034 {
9035 	uint32_t cfg, *buf;
9036 	int rc;
9037 
9038 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9039 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
9040 	    M_ZERO | flags);
9041 	if (buf == NULL)
9042 		return (ENOMEM);
9043 
9044 	mtx_lock(&sc->reg_lock);
9045 	if (hw_off_limits(sc))
9046 		rc = ENXIO;
9047 	else {
9048 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
9049 		if (rc == 0)
9050 			rc = -t4_cim_read_la(sc, buf, NULL);
9051 	}
9052 	mtx_unlock(&sc->reg_lock);
9053 	if (rc == 0) {
9054 		if (chip_id(sc) < CHELSIO_T6)
9055 			sbuf_cim_la4(sc, sb, buf, cfg);
9056 		else
9057 			sbuf_cim_la6(sc, sb, buf, cfg);
9058 	}
9059 	free(buf, M_CXGBE);
9060 	return (rc);
9061 }
9062 
9063 static int
9064 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
9065 {
9066 	struct adapter *sc = arg1;
9067 	struct sbuf *sb;
9068 	int rc;
9069 
9070 	rc = sysctl_wire_old_buffer(req, 0);
9071 	if (rc != 0)
9072 		return (rc);
9073 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9074 	if (sb == NULL)
9075 		return (ENOMEM);
9076 
9077 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
9078 	if (rc == 0)
9079 		rc = sbuf_finish(sb);
9080 	sbuf_delete(sb);
9081 	return (rc);
9082 }
9083 
9084 static void
9085 dump_cim_regs(struct adapter *sc)
9086 {
9087 	log(LOG_DEBUG, "%s: CIM debug regs1 %08x %08x %08x %08x %08x\n",
9088 	    device_get_nameunit(sc->dev),
9089 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9090 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9091 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA2),
9092 	    t4_read_reg(sc, A_EDC_H_BIST_DATA_PATTERN),
9093 	    t4_read_reg(sc, A_EDC_H_BIST_STATUS_RDATA));
9094 	log(LOG_DEBUG, "%s: CIM debug regs2 %08x %08x %08x %08x %08x\n",
9095 	    device_get_nameunit(sc->dev),
9096 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9097 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9098 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0 + 0x800),
9099 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1 + 0x800),
9100 	    t4_read_reg(sc, A_EDC_H_BIST_CMD_LEN));
9101 }
9102 
9103 static void
9104 dump_cimla(struct adapter *sc)
9105 {
9106 	struct sbuf sb;
9107 	int rc;
9108 
9109 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9110 		log(LOG_DEBUG, "%s: failed to generate CIM LA dump.\n",
9111 		    device_get_nameunit(sc->dev));
9112 		return;
9113 	}
9114 	rc = sbuf_cim_la(sc, &sb, M_WAITOK);
9115 	if (rc == 0) {
9116 		rc = sbuf_finish(&sb);
9117 		if (rc == 0) {
9118 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s\n",
9119 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9120 		}
9121 	}
9122 	sbuf_delete(&sb);
9123 }
9124 
9125 void
9126 t4_os_cim_err(struct adapter *sc)
9127 {
9128 	atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
9129 }
9130 
9131 static int
9132 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
9133 {
9134 	struct adapter *sc = arg1;
9135 	u_int i;
9136 	struct sbuf *sb;
9137 	uint32_t *buf, *p;
9138 	int rc;
9139 
9140 	rc = sysctl_wire_old_buffer(req, 0);
9141 	if (rc != 0)
9142 		return (rc);
9143 
9144 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9145 	if (sb == NULL)
9146 		return (ENOMEM);
9147 
9148 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
9149 	    M_ZERO | M_WAITOK);
9150 
9151 	mtx_lock(&sc->reg_lock);
9152 	if (hw_off_limits(sc))
9153 		rc = ENXIO;
9154 	else
9155 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
9156 	mtx_unlock(&sc->reg_lock);
9157 	if (rc)
9158 		goto done;
9159 
9160 	p = buf;
9161 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9162 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
9163 		    p[1], p[0]);
9164 	}
9165 
9166 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9167 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9168 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9169 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9170 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9171 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9172 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9173 		    p[0] & 1);
9174 	}
9175 	rc = sbuf_finish(sb);
9176 done:
9177 	sbuf_delete(sb);
9178 	free(buf, M_CXGBE);
9179 	return (rc);
9180 }
9181 
9182 static int
9183 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9184 {
9185 	struct adapter *sc = arg1;
9186 	u_int i;
9187 	struct sbuf *sb;
9188 	uint32_t *buf, *p;
9189 	int rc;
9190 
9191 	rc = sysctl_wire_old_buffer(req, 0);
9192 	if (rc != 0)
9193 		return (rc);
9194 
9195 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9196 	if (sb == NULL)
9197 		return (ENOMEM);
9198 
9199 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9200 	    M_ZERO | M_WAITOK);
9201 
9202 	mtx_lock(&sc->reg_lock);
9203 	if (hw_off_limits(sc))
9204 		rc = ENXIO;
9205 	else
9206 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9207 	mtx_unlock(&sc->reg_lock);
9208 	if (rc)
9209 		goto done;
9210 
9211 	p = buf;
9212 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9213 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9214 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9215 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9216 		    p[4], p[3], p[2], p[1], p[0]);
9217 	}
9218 
9219 	sbuf_printf(sb, "\n\nCntl ID               Data");
9220 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9221 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9222 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9223 	}
9224 
9225 	rc = sbuf_finish(sb);
9226 done:
9227 	sbuf_delete(sb);
9228 	free(buf, M_CXGBE);
9229 	return (rc);
9230 }
9231 
9232 static int
9233 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9234 {
9235 	struct adapter *sc = arg1;
9236 	struct sbuf *sb;
9237 	int rc, i;
9238 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9239 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9240 	uint16_t thres[CIM_NUM_IBQ];
9241 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9242 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9243 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9244 
9245 	cim_num_obq = sc->chip_params->cim_num_obq;
9246 	if (is_t4(sc)) {
9247 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9248 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9249 	} else {
9250 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9251 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9252 	}
9253 	nq = CIM_NUM_IBQ + cim_num_obq;
9254 
9255 	mtx_lock(&sc->reg_lock);
9256 	if (hw_off_limits(sc))
9257 		rc = ENXIO;
9258 	else {
9259 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9260 		if (rc == 0) {
9261 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9262 			    obq_wr);
9263 			if (rc == 0)
9264 				t4_read_cimq_cfg(sc, base, size, thres);
9265 		}
9266 	}
9267 	mtx_unlock(&sc->reg_lock);
9268 	if (rc)
9269 		return (rc);
9270 
9271 	rc = sysctl_wire_old_buffer(req, 0);
9272 	if (rc != 0)
9273 		return (rc);
9274 
9275 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9276 	if (sb == NULL)
9277 		return (ENOMEM);
9278 
9279 	sbuf_printf(sb,
9280 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9281 
9282 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9283 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9284 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9285 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9286 		    G_QUEREMFLITS(p[2]) * 16);
9287 	for ( ; i < nq; i++, p += 4, wr += 2)
9288 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9289 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9290 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9291 		    G_QUEREMFLITS(p[2]) * 16);
9292 
9293 	rc = sbuf_finish(sb);
9294 	sbuf_delete(sb);
9295 
9296 	return (rc);
9297 }
9298 
9299 static int
9300 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9301 {
9302 	struct adapter *sc = arg1;
9303 	struct sbuf *sb;
9304 	int rc;
9305 	struct tp_cpl_stats stats;
9306 
9307 	rc = sysctl_wire_old_buffer(req, 0);
9308 	if (rc != 0)
9309 		return (rc);
9310 
9311 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9312 	if (sb == NULL)
9313 		return (ENOMEM);
9314 
9315 	mtx_lock(&sc->reg_lock);
9316 	if (hw_off_limits(sc))
9317 		rc = ENXIO;
9318 	else
9319 		t4_tp_get_cpl_stats(sc, &stats, 0);
9320 	mtx_unlock(&sc->reg_lock);
9321 	if (rc)
9322 		goto done;
9323 
9324 	if (sc->chip_params->nchan > 2) {
9325 		sbuf_printf(sb, "                 channel 0  channel 1"
9326 		    "  channel 2  channel 3");
9327 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9328 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9329 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9330 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9331 	} else {
9332 		sbuf_printf(sb, "                 channel 0  channel 1");
9333 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9334 		    stats.req[0], stats.req[1]);
9335 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9336 		    stats.rsp[0], stats.rsp[1]);
9337 	}
9338 
9339 	rc = sbuf_finish(sb);
9340 done:
9341 	sbuf_delete(sb);
9342 	return (rc);
9343 }
9344 
9345 static int
9346 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9347 {
9348 	struct adapter *sc = arg1;
9349 	struct sbuf *sb;
9350 	int rc;
9351 	struct tp_usm_stats stats;
9352 
9353 	rc = sysctl_wire_old_buffer(req, 0);
9354 	if (rc != 0)
9355 		return(rc);
9356 
9357 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9358 	if (sb == NULL)
9359 		return (ENOMEM);
9360 
9361 	mtx_lock(&sc->reg_lock);
9362 	if (hw_off_limits(sc))
9363 		rc = ENXIO;
9364 	else
9365 		t4_get_usm_stats(sc, &stats, 1);
9366 	mtx_unlock(&sc->reg_lock);
9367 	if (rc == 0) {
9368 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9369 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9370 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9371 		rc = sbuf_finish(sb);
9372 	}
9373 	sbuf_delete(sb);
9374 
9375 	return (rc);
9376 }
9377 
9378 static int
9379 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9380 {
9381 	struct adapter *sc = arg1;
9382 	struct sbuf *sb;
9383 	int rc;
9384 	struct tp_tid_stats stats;
9385 
9386 	rc = sysctl_wire_old_buffer(req, 0);
9387 	if (rc != 0)
9388 		return(rc);
9389 
9390 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9391 	if (sb == NULL)
9392 		return (ENOMEM);
9393 
9394 	mtx_lock(&sc->reg_lock);
9395 	if (hw_off_limits(sc))
9396 		rc = ENXIO;
9397 	else
9398 		t4_tp_get_tid_stats(sc, &stats, 1);
9399 	mtx_unlock(&sc->reg_lock);
9400 	if (rc == 0) {
9401 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9402 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9403 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9404 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9405 		rc = sbuf_finish(sb);
9406 	}
9407 	sbuf_delete(sb);
9408 
9409 	return (rc);
9410 }
9411 
9412 static const char * const devlog_level_strings[] = {
9413 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9414 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9415 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9416 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9417 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9418 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9419 };
9420 
9421 static const char * const devlog_facility_strings[] = {
9422 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9423 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9424 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9425 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9426 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9427 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9428 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9429 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9430 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9431 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9432 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9433 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9434 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9435 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9436 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9437 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9438 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9439 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9440 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9441 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9442 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9443 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9444 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9445 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9446 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9447 };
9448 
9449 static int
9450 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9451 {
9452 	int i, j, rc, nentries, first = 0;
9453 	struct devlog_params *dparams = &sc->params.devlog;
9454 	struct fw_devlog_e *buf, *e;
9455 	uint64_t ftstamp = UINT64_MAX;
9456 
9457 	if (dparams->addr == 0)
9458 		return (ENXIO);
9459 
9460 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9461 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9462 	if (buf == NULL)
9463 		return (ENOMEM);
9464 
9465 	mtx_lock(&sc->reg_lock);
9466 	if (hw_off_limits(sc))
9467 		rc = ENXIO;
9468 	else
9469 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9470 		    dparams->size);
9471 	mtx_unlock(&sc->reg_lock);
9472 	if (rc != 0)
9473 		goto done;
9474 
9475 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9476 	for (i = 0; i < nentries; i++) {
9477 		e = &buf[i];
9478 
9479 		if (e->timestamp == 0)
9480 			break;	/* end */
9481 
9482 		e->timestamp = be64toh(e->timestamp);
9483 		e->seqno = be32toh(e->seqno);
9484 		for (j = 0; j < 8; j++)
9485 			e->params[j] = be32toh(e->params[j]);
9486 
9487 		if (e->timestamp < ftstamp) {
9488 			ftstamp = e->timestamp;
9489 			first = i;
9490 		}
9491 	}
9492 
9493 	if (buf[first].timestamp == 0)
9494 		goto done;	/* nothing in the log */
9495 
9496 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9497 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9498 
9499 	i = first;
9500 	do {
9501 		e = &buf[i];
9502 		if (e->timestamp == 0)
9503 			break;	/* end */
9504 
9505 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9506 		    e->seqno, e->timestamp,
9507 		    (e->level < nitems(devlog_level_strings) ?
9508 			devlog_level_strings[e->level] : "UNKNOWN"),
9509 		    (e->facility < nitems(devlog_facility_strings) ?
9510 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9511 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9512 		    e->params[2], e->params[3], e->params[4],
9513 		    e->params[5], e->params[6], e->params[7]);
9514 
9515 		if (++i == nentries)
9516 			i = 0;
9517 	} while (i != first);
9518 done:
9519 	free(buf, M_CXGBE);
9520 	return (rc);
9521 }
9522 
9523 static int
9524 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9525 {
9526 	struct adapter *sc = arg1;
9527 	int rc;
9528 	struct sbuf *sb;
9529 
9530 	rc = sysctl_wire_old_buffer(req, 0);
9531 	if (rc != 0)
9532 		return (rc);
9533 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9534 	if (sb == NULL)
9535 		return (ENOMEM);
9536 
9537 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9538 	if (rc == 0)
9539 		rc = sbuf_finish(sb);
9540 	sbuf_delete(sb);
9541 	return (rc);
9542 }
9543 
9544 static void
9545 dump_devlog(struct adapter *sc)
9546 {
9547 	int rc;
9548 	struct sbuf sb;
9549 
9550 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9551 		log(LOG_DEBUG, "%s: failed to generate devlog dump.\n",
9552 		    device_get_nameunit(sc->dev));
9553 		return;
9554 	}
9555 	rc = sbuf_devlog(sc, &sb, M_WAITOK);
9556 	if (rc == 0) {
9557 		rc = sbuf_finish(&sb);
9558 		if (rc == 0) {
9559 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9560 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9561 		}
9562 	}
9563 	sbuf_delete(&sb);
9564 }
9565 
9566 static int
9567 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9568 {
9569 	struct adapter *sc = arg1;
9570 	struct sbuf *sb;
9571 	int rc;
9572 	struct tp_fcoe_stats stats[MAX_NCHAN];
9573 	int i, nchan = sc->chip_params->nchan;
9574 
9575 	rc = sysctl_wire_old_buffer(req, 0);
9576 	if (rc != 0)
9577 		return (rc);
9578 
9579 	mtx_lock(&sc->reg_lock);
9580 	if (hw_off_limits(sc))
9581 		rc = ENXIO;
9582 	else {
9583 		for (i = 0; i < nchan; i++)
9584 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9585 	}
9586 	mtx_unlock(&sc->reg_lock);
9587 	if (rc != 0)
9588 		return (rc);
9589 
9590 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9591 	if (sb == NULL)
9592 		return (ENOMEM);
9593 
9594 	if (nchan > 2) {
9595 		sbuf_printf(sb, "                   channel 0        channel 1"
9596 		    "        channel 2        channel 3");
9597 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9598 		    stats[0].octets_ddp, stats[1].octets_ddp,
9599 		    stats[2].octets_ddp, stats[3].octets_ddp);
9600 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9601 		    stats[0].frames_ddp, stats[1].frames_ddp,
9602 		    stats[2].frames_ddp, stats[3].frames_ddp);
9603 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9604 		    stats[0].frames_drop, stats[1].frames_drop,
9605 		    stats[2].frames_drop, stats[3].frames_drop);
9606 	} else {
9607 		sbuf_printf(sb, "                   channel 0        channel 1");
9608 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9609 		    stats[0].octets_ddp, stats[1].octets_ddp);
9610 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9611 		    stats[0].frames_ddp, stats[1].frames_ddp);
9612 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9613 		    stats[0].frames_drop, stats[1].frames_drop);
9614 	}
9615 
9616 	rc = sbuf_finish(sb);
9617 	sbuf_delete(sb);
9618 
9619 	return (rc);
9620 }
9621 
9622 static int
9623 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9624 {
9625 	struct adapter *sc = arg1;
9626 	struct sbuf *sb;
9627 	int rc, i;
9628 	unsigned int map, kbps, ipg, mode;
9629 	unsigned int pace_tab[NTX_SCHED];
9630 
9631 	rc = sysctl_wire_old_buffer(req, 0);
9632 	if (rc != 0)
9633 		return (rc);
9634 
9635 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9636 	if (sb == NULL)
9637 		return (ENOMEM);
9638 
9639 	mtx_lock(&sc->reg_lock);
9640 	if (hw_off_limits(sc)) {
9641 		rc = ENXIO;
9642 		goto done;
9643 	}
9644 
9645 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9646 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9647 	t4_read_pace_tbl(sc, pace_tab);
9648 
9649 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9650 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9651 
9652 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9653 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9654 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9655 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9656 		if (kbps)
9657 			sbuf_printf(sb, "%9u     ", kbps);
9658 		else
9659 			sbuf_printf(sb, " disabled     ");
9660 
9661 		if (ipg)
9662 			sbuf_printf(sb, "%13u        ", ipg);
9663 		else
9664 			sbuf_printf(sb, "     disabled        ");
9665 
9666 		if (pace_tab[i])
9667 			sbuf_printf(sb, "%10u", pace_tab[i]);
9668 		else
9669 			sbuf_printf(sb, "  disabled");
9670 	}
9671 	rc = sbuf_finish(sb);
9672 done:
9673 	mtx_unlock(&sc->reg_lock);
9674 	sbuf_delete(sb);
9675 	return (rc);
9676 }
9677 
9678 static int
9679 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9680 {
9681 	struct adapter *sc = arg1;
9682 	struct sbuf *sb;
9683 	int rc, i, j;
9684 	uint64_t *p0, *p1;
9685 	struct lb_port_stats s[2];
9686 	static const char *stat_name[] = {
9687 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9688 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9689 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9690 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9691 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9692 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9693 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9694 	};
9695 
9696 	rc = sysctl_wire_old_buffer(req, 0);
9697 	if (rc != 0)
9698 		return (rc);
9699 
9700 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9701 	if (sb == NULL)
9702 		return (ENOMEM);
9703 
9704 	memset(s, 0, sizeof(s));
9705 
9706 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9707 		mtx_lock(&sc->reg_lock);
9708 		if (hw_off_limits(sc))
9709 			rc = ENXIO;
9710 		else {
9711 			t4_get_lb_stats(sc, i, &s[0]);
9712 			t4_get_lb_stats(sc, i + 1, &s[1]);
9713 		}
9714 		mtx_unlock(&sc->reg_lock);
9715 		if (rc != 0)
9716 			break;
9717 
9718 		p0 = &s[0].octets;
9719 		p1 = &s[1].octets;
9720 		sbuf_printf(sb, "%s                       Loopback %u"
9721 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9722 
9723 		for (j = 0; j < nitems(stat_name); j++)
9724 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9725 				   *p0++, *p1++);
9726 	}
9727 
9728 	rc = sbuf_finish(sb);
9729 	sbuf_delete(sb);
9730 
9731 	return (rc);
9732 }
9733 
9734 static int
9735 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9736 {
9737 	int rc = 0;
9738 	struct port_info *pi = arg1;
9739 	struct link_config *lc = &pi->link_cfg;
9740 	struct sbuf *sb;
9741 
9742 	rc = sysctl_wire_old_buffer(req, 0);
9743 	if (rc != 0)
9744 		return(rc);
9745 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9746 	if (sb == NULL)
9747 		return (ENOMEM);
9748 
9749 	if (lc->link_ok || lc->link_down_rc == 255)
9750 		sbuf_printf(sb, "n/a");
9751 	else
9752 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9753 
9754 	rc = sbuf_finish(sb);
9755 	sbuf_delete(sb);
9756 
9757 	return (rc);
9758 }
9759 
9760 struct mem_desc {
9761 	u_int base;
9762 	u_int limit;
9763 	u_int idx;
9764 };
9765 
9766 static int
9767 mem_desc_cmp(const void *a, const void *b)
9768 {
9769 	const u_int v1 = ((const struct mem_desc *)a)->base;
9770 	const u_int v2 = ((const struct mem_desc *)b)->base;
9771 
9772 	if (v1 < v2)
9773 		return (-1);
9774 	else if (v1 > v2)
9775 		return (1);
9776 
9777 	return (0);
9778 }
9779 
9780 static void
9781 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9782     unsigned int to)
9783 {
9784 	unsigned int size;
9785 
9786 	if (from == to)
9787 		return;
9788 
9789 	size = to - from + 1;
9790 	if (size == 0)
9791 		return;
9792 
9793 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9794 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9795 }
9796 
9797 static int
9798 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9799 {
9800 	struct adapter *sc = arg1;
9801 	struct sbuf *sb;
9802 	int rc, i, n;
9803 	uint32_t lo, hi, used, free, alloc;
9804 	static const char *memory[] = {
9805 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9806 	};
9807 	static const char *region[] = {
9808 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9809 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9810 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9811 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9812 		"RQUDP region:", "PBL region:", "TXPBL region:",
9813 		"TLSKey region:", "DBVFIFO region:", "ULPRX state:",
9814 		"ULPTX state:", "On-chip queues:",
9815 	};
9816 	struct mem_desc avail[4];
9817 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9818 	struct mem_desc *md = mem;
9819 
9820 	rc = sysctl_wire_old_buffer(req, 0);
9821 	if (rc != 0)
9822 		return (rc);
9823 
9824 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9825 	if (sb == NULL)
9826 		return (ENOMEM);
9827 
9828 	for (i = 0; i < nitems(mem); i++) {
9829 		mem[i].limit = 0;
9830 		mem[i].idx = i;
9831 	}
9832 
9833 	mtx_lock(&sc->reg_lock);
9834 	if (hw_off_limits(sc)) {
9835 		rc = ENXIO;
9836 		goto done;
9837 	}
9838 
9839 	/* Find and sort the populated memory ranges */
9840 	i = 0;
9841 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9842 	if (lo & F_EDRAM0_ENABLE) {
9843 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9844 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9845 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9846 		avail[i].idx = 0;
9847 		i++;
9848 	}
9849 	if (lo & F_EDRAM1_ENABLE) {
9850 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9851 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9852 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9853 		avail[i].idx = 1;
9854 		i++;
9855 	}
9856 	if (lo & F_EXT_MEM_ENABLE) {
9857 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9858 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9859 		avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9860 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9861 		i++;
9862 	}
9863 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9864 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9865 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9866 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9867 		avail[i].idx = 4;
9868 		i++;
9869 	}
9870 	if (is_t6(sc) && lo & F_HMA_MUX) {
9871 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9872 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9873 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9874 		avail[i].idx = 5;
9875 		i++;
9876 	}
9877 	MPASS(i <= nitems(avail));
9878 	if (!i)                                    /* no memory available */
9879 		goto done;
9880 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9881 
9882 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9883 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9884 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9885 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9886 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9887 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9888 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9889 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9890 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9891 
9892 	/* the next few have explicit upper bounds */
9893 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9894 	md->limit = md->base - 1 +
9895 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9896 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9897 	md++;
9898 
9899 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9900 	md->limit = md->base - 1 +
9901 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9902 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9903 	md++;
9904 
9905 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9906 		if (chip_id(sc) <= CHELSIO_T5)
9907 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9908 		else
9909 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9910 		md->limit = 0;
9911 	} else {
9912 		md->base = 0;
9913 		md->idx = nitems(region);  /* hide it */
9914 	}
9915 	md++;
9916 
9917 #define ulp_region(reg) \
9918 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9919 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9920 
9921 	ulp_region(RX_ISCSI);
9922 	ulp_region(RX_TDDP);
9923 	ulp_region(TX_TPT);
9924 	ulp_region(RX_STAG);
9925 	ulp_region(RX_RQ);
9926 	ulp_region(RX_RQUDP);
9927 	ulp_region(RX_PBL);
9928 	ulp_region(TX_PBL);
9929 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
9930 		ulp_region(RX_TLS_KEY);
9931 	}
9932 #undef ulp_region
9933 
9934 	md->base = 0;
9935 	if (is_t4(sc))
9936 		md->idx = nitems(region);
9937 	else {
9938 		uint32_t size = 0;
9939 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9940 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9941 
9942 		if (is_t5(sc)) {
9943 			if (sge_ctrl & F_VFIFO_ENABLE)
9944 				size = fifo_size << 2;
9945 		} else
9946 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9947 
9948 		if (size) {
9949 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
9950 			md->limit = md->base + size - 1;
9951 		} else
9952 			md->idx = nitems(region);
9953 	}
9954 	md++;
9955 
9956 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9957 	md->limit = 0;
9958 	md++;
9959 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9960 	md->limit = 0;
9961 	md++;
9962 
9963 	md->base = sc->vres.ocq.start;
9964 	if (sc->vres.ocq.size)
9965 		md->limit = md->base + sc->vres.ocq.size - 1;
9966 	else
9967 		md->idx = nitems(region);  /* hide it */
9968 	md++;
9969 
9970 	/* add any address-space holes, there can be up to 3 */
9971 	for (n = 0; n < i - 1; n++)
9972 		if (avail[n].limit < avail[n + 1].base)
9973 			(md++)->base = avail[n].limit;
9974 	if (avail[n].limit)
9975 		(md++)->base = avail[n].limit;
9976 
9977 	n = md - mem;
9978 	MPASS(n <= nitems(mem));
9979 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
9980 
9981 	for (lo = 0; lo < i; lo++)
9982 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
9983 				avail[lo].limit - 1);
9984 
9985 	sbuf_printf(sb, "\n");
9986 	for (i = 0; i < n; i++) {
9987 		if (mem[i].idx >= nitems(region))
9988 			continue;                        /* skip holes */
9989 		if (!mem[i].limit)
9990 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
9991 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
9992 				mem[i].limit);
9993 	}
9994 
9995 	sbuf_printf(sb, "\n");
9996 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
9997 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
9998 	mem_region_show(sb, "uP RAM:", lo, hi);
9999 
10000 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
10001 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
10002 	mem_region_show(sb, "uP Extmem2:", lo, hi);
10003 
10004 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
10005 	for (i = 0, free = 0; i < 2; i++)
10006 		free += G_FREERXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_RX_CNT));
10007 	sbuf_printf(sb, "\n%u Rx pages (%u free) of size %uKiB for %u channels\n",
10008 		   G_PMRXMAXPAGE(lo), free,
10009 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
10010 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
10011 
10012 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
10013 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
10014 	for (i = 0, free = 0; i < 4; i++)
10015 		free += G_FREETXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_TX_CNT));
10016 	sbuf_printf(sb, "%u Tx pages (%u free) of size %u%ciB for %u channels\n",
10017 		   G_PMTXMAXPAGE(lo), free,
10018 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
10019 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
10020 	sbuf_printf(sb, "%u p-structs (%u free)\n",
10021 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT),
10022 		   G_FREEPSTRUCTCOUNT(t4_read_reg(sc, A_TP_FLM_FREE_PS_CNT)));
10023 
10024 	for (i = 0; i < 4; i++) {
10025 		if (chip_id(sc) > CHELSIO_T5)
10026 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
10027 		else
10028 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
10029 		if (is_t5(sc)) {
10030 			used = G_T5_USED(lo);
10031 			alloc = G_T5_ALLOC(lo);
10032 		} else {
10033 			used = G_USED(lo);
10034 			alloc = G_ALLOC(lo);
10035 		}
10036 		/* For T6 these are MAC buffer groups */
10037 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
10038 		    i, used, alloc);
10039 	}
10040 	for (i = 0; i < sc->chip_params->nchan; i++) {
10041 		if (chip_id(sc) > CHELSIO_T5)
10042 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
10043 		else
10044 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
10045 		if (is_t5(sc)) {
10046 			used = G_T5_USED(lo);
10047 			alloc = G_T5_ALLOC(lo);
10048 		} else {
10049 			used = G_USED(lo);
10050 			alloc = G_ALLOC(lo);
10051 		}
10052 		/* For T6 these are MAC buffer groups */
10053 		sbuf_printf(sb,
10054 		    "\nLoopback %d using %u pages out of %u allocated",
10055 		    i, used, alloc);
10056 	}
10057 done:
10058 	mtx_unlock(&sc->reg_lock);
10059 	if (rc == 0)
10060 		rc = sbuf_finish(sb);
10061 	sbuf_delete(sb);
10062 	return (rc);
10063 }
10064 
10065 static inline void
10066 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
10067 {
10068 	*mask = x | y;
10069 	y = htobe64(y);
10070 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
10071 }
10072 
10073 static int
10074 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
10075 {
10076 	struct adapter *sc = arg1;
10077 	struct sbuf *sb;
10078 	int rc, i;
10079 
10080 	MPASS(chip_id(sc) <= CHELSIO_T5);
10081 
10082 	rc = sysctl_wire_old_buffer(req, 0);
10083 	if (rc != 0)
10084 		return (rc);
10085 
10086 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10087 	if (sb == NULL)
10088 		return (ENOMEM);
10089 
10090 	sbuf_printf(sb,
10091 	    "Idx  Ethernet address     Mask     Vld Ports PF"
10092 	    "  VF              Replication             P0 P1 P2 P3  ML");
10093 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10094 		uint64_t tcamx, tcamy, mask;
10095 		uint32_t cls_lo, cls_hi;
10096 		uint8_t addr[ETHER_ADDR_LEN];
10097 
10098 		mtx_lock(&sc->reg_lock);
10099 		if (hw_off_limits(sc))
10100 			rc = ENXIO;
10101 		else {
10102 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
10103 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
10104 		}
10105 		mtx_unlock(&sc->reg_lock);
10106 		if (rc != 0)
10107 			break;
10108 		if (tcamx & tcamy)
10109 			continue;
10110 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10111 		mtx_lock(&sc->reg_lock);
10112 		if (hw_off_limits(sc))
10113 			rc = ENXIO;
10114 		else {
10115 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10116 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10117 		}
10118 		mtx_unlock(&sc->reg_lock);
10119 		if (rc != 0)
10120 			break;
10121 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
10122 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
10123 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
10124 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
10125 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
10126 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
10127 
10128 		if (cls_lo & F_REPLICATE) {
10129 			struct fw_ldst_cmd ldst_cmd;
10130 
10131 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10132 			ldst_cmd.op_to_addrspace =
10133 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10134 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10135 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10136 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10137 			ldst_cmd.u.mps.rplc.fid_idx =
10138 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10139 				V_FW_LDST_CMD_IDX(i));
10140 
10141 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10142 			    "t4mps");
10143 			if (rc)
10144 				break;
10145 			if (hw_off_limits(sc))
10146 				rc = ENXIO;
10147 			else
10148 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10149 				    sizeof(ldst_cmd), &ldst_cmd);
10150 			end_synchronized_op(sc, 0);
10151 			if (rc != 0)
10152 				break;
10153 			else {
10154 				sbuf_printf(sb, " %08x %08x %08x %08x",
10155 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10156 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10157 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10158 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10159 			}
10160 		} else
10161 			sbuf_printf(sb, "%36s", "");
10162 
10163 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
10164 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
10165 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
10166 	}
10167 
10168 	if (rc)
10169 		(void) sbuf_finish(sb);
10170 	else
10171 		rc = sbuf_finish(sb);
10172 	sbuf_delete(sb);
10173 
10174 	return (rc);
10175 }
10176 
10177 static int
10178 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
10179 {
10180 	struct adapter *sc = arg1;
10181 	struct sbuf *sb;
10182 	int rc, i;
10183 
10184 	MPASS(chip_id(sc) > CHELSIO_T5);
10185 
10186 	rc = sysctl_wire_old_buffer(req, 0);
10187 	if (rc != 0)
10188 		return (rc);
10189 
10190 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10191 	if (sb == NULL)
10192 		return (ENOMEM);
10193 
10194 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
10195 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
10196 	    "                           Replication"
10197 	    "                                    P0 P1 P2 P3  ML\n");
10198 
10199 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10200 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
10201 		uint16_t ivlan;
10202 		uint64_t tcamx, tcamy, val, mask;
10203 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10204 		uint8_t addr[ETHER_ADDR_LEN];
10205 
10206 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10207 		if (i < 256)
10208 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10209 		else
10210 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10211 		mtx_lock(&sc->reg_lock);
10212 		if (hw_off_limits(sc))
10213 			rc = ENXIO;
10214 		else {
10215 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10216 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10217 			tcamy = G_DMACH(val) << 32;
10218 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10219 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10220 		}
10221 		mtx_unlock(&sc->reg_lock);
10222 		if (rc != 0)
10223 			break;
10224 
10225 		lookup_type = G_DATALKPTYPE(data2);
10226 		port_num = G_DATAPORTNUM(data2);
10227 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10228 			/* Inner header VNI */
10229 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10230 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10231 			dip_hit = data2 & F_DATADIPHIT;
10232 			vlan_vld = 0;
10233 		} else {
10234 			vniy = 0;
10235 			dip_hit = 0;
10236 			vlan_vld = data2 & F_DATAVIDH2;
10237 			ivlan = G_VIDL(val);
10238 		}
10239 
10240 		ctl |= V_CTLXYBITSEL(1);
10241 		mtx_lock(&sc->reg_lock);
10242 		if (hw_off_limits(sc))
10243 			rc = ENXIO;
10244 		else {
10245 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10246 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10247 			tcamx = G_DMACH(val) << 32;
10248 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10249 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10250 		}
10251 		mtx_unlock(&sc->reg_lock);
10252 		if (rc != 0)
10253 			break;
10254 
10255 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10256 			/* Inner header VNI mask */
10257 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10258 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10259 		} else
10260 			vnix = 0;
10261 
10262 		if (tcamx & tcamy)
10263 			continue;
10264 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10265 
10266 		mtx_lock(&sc->reg_lock);
10267 		if (hw_off_limits(sc))
10268 			rc = ENXIO;
10269 		else {
10270 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10271 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10272 		}
10273 		mtx_unlock(&sc->reg_lock);
10274 		if (rc != 0)
10275 			break;
10276 
10277 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10278 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10279 			    "%012jx %06x %06x    -    -   %3c"
10280 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10281 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10282 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10283 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10284 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10285 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10286 		} else {
10287 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10288 			    "%012jx    -       -   ", i, addr[0], addr[1],
10289 			    addr[2], addr[3], addr[4], addr[5],
10290 			    (uintmax_t)mask);
10291 
10292 			if (vlan_vld)
10293 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10294 			else
10295 				sbuf_printf(sb, "  -    N     ");
10296 
10297 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10298 			    lookup_type ? 'I' : 'O', port_num,
10299 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10300 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10301 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10302 		}
10303 
10304 
10305 		if (cls_lo & F_T6_REPLICATE) {
10306 			struct fw_ldst_cmd ldst_cmd;
10307 
10308 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10309 			ldst_cmd.op_to_addrspace =
10310 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10311 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10312 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10313 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10314 			ldst_cmd.u.mps.rplc.fid_idx =
10315 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10316 				V_FW_LDST_CMD_IDX(i));
10317 
10318 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10319 			    "t6mps");
10320 			if (rc)
10321 				break;
10322 			if (hw_off_limits(sc))
10323 				rc = ENXIO;
10324 			else
10325 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10326 				    sizeof(ldst_cmd), &ldst_cmd);
10327 			end_synchronized_op(sc, 0);
10328 			if (rc != 0)
10329 				break;
10330 			else {
10331 				sbuf_printf(sb, " %08x %08x %08x %08x"
10332 				    " %08x %08x %08x %08x",
10333 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10334 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10335 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10336 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10337 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10338 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10339 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10340 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10341 			}
10342 		} else
10343 			sbuf_printf(sb, "%72s", "");
10344 
10345 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10346 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10347 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10348 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10349 	}
10350 
10351 	if (rc)
10352 		(void) sbuf_finish(sb);
10353 	else
10354 		rc = sbuf_finish(sb);
10355 	sbuf_delete(sb);
10356 
10357 	return (rc);
10358 }
10359 
10360 static int
10361 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10362 {
10363 	struct adapter *sc = arg1;
10364 	struct sbuf *sb;
10365 	int rc;
10366 	uint16_t mtus[NMTUS];
10367 
10368 	rc = sysctl_wire_old_buffer(req, 0);
10369 	if (rc != 0)
10370 		return (rc);
10371 
10372 	mtx_lock(&sc->reg_lock);
10373 	if (hw_off_limits(sc))
10374 		rc = ENXIO;
10375 	else
10376 		t4_read_mtu_tbl(sc, mtus, NULL);
10377 	mtx_unlock(&sc->reg_lock);
10378 	if (rc != 0)
10379 		return (rc);
10380 
10381 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10382 	if (sb == NULL)
10383 		return (ENOMEM);
10384 
10385 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10386 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10387 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10388 	    mtus[14], mtus[15]);
10389 
10390 	rc = sbuf_finish(sb);
10391 	sbuf_delete(sb);
10392 
10393 	return (rc);
10394 }
10395 
10396 static int
10397 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10398 {
10399 	struct adapter *sc = arg1;
10400 	struct sbuf *sb;
10401 	int rc, i;
10402 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10403 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10404 	static const char *tx_stats[MAX_PM_NSTATS] = {
10405 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10406 		"Tx FIFO wait", NULL, "Tx latency"
10407 	};
10408 	static const char *rx_stats[MAX_PM_NSTATS] = {
10409 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10410 		"Rx FIFO wait", NULL, "Rx latency"
10411 	};
10412 
10413 	rc = sysctl_wire_old_buffer(req, 0);
10414 	if (rc != 0)
10415 		return (rc);
10416 
10417 	mtx_lock(&sc->reg_lock);
10418 	if (hw_off_limits(sc))
10419 		rc = ENXIO;
10420 	else {
10421 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10422 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10423 	}
10424 	mtx_unlock(&sc->reg_lock);
10425 	if (rc != 0)
10426 		return (rc);
10427 
10428 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10429 	if (sb == NULL)
10430 		return (ENOMEM);
10431 
10432 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10433 	for (i = 0; i < 4; i++) {
10434 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10435 		    tx_cyc[i]);
10436 	}
10437 
10438 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10439 	for (i = 0; i < 4; i++) {
10440 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10441 		    rx_cyc[i]);
10442 	}
10443 
10444 	if (chip_id(sc) > CHELSIO_T5) {
10445 		sbuf_printf(sb,
10446 		    "\n              Total wait      Total occupancy");
10447 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10448 		    tx_cyc[i]);
10449 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10450 		    rx_cyc[i]);
10451 
10452 		i += 2;
10453 		MPASS(i < nitems(tx_stats));
10454 
10455 		sbuf_printf(sb,
10456 		    "\n                   Reads           Total wait");
10457 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10458 		    tx_cyc[i]);
10459 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10460 		    rx_cyc[i]);
10461 	}
10462 
10463 	rc = sbuf_finish(sb);
10464 	sbuf_delete(sb);
10465 
10466 	return (rc);
10467 }
10468 
10469 static int
10470 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10471 {
10472 	struct adapter *sc = arg1;
10473 	struct sbuf *sb;
10474 	int rc;
10475 	struct tp_rdma_stats stats;
10476 
10477 	rc = sysctl_wire_old_buffer(req, 0);
10478 	if (rc != 0)
10479 		return (rc);
10480 
10481 	mtx_lock(&sc->reg_lock);
10482 	if (hw_off_limits(sc))
10483 		rc = ENXIO;
10484 	else
10485 		t4_tp_get_rdma_stats(sc, &stats, 0);
10486 	mtx_unlock(&sc->reg_lock);
10487 	if (rc != 0)
10488 		return (rc);
10489 
10490 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10491 	if (sb == NULL)
10492 		return (ENOMEM);
10493 
10494 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10495 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10496 
10497 	rc = sbuf_finish(sb);
10498 	sbuf_delete(sb);
10499 
10500 	return (rc);
10501 }
10502 
10503 static int
10504 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10505 {
10506 	struct adapter *sc = arg1;
10507 	struct sbuf *sb;
10508 	int rc;
10509 	struct tp_tcp_stats v4, v6;
10510 
10511 	rc = sysctl_wire_old_buffer(req, 0);
10512 	if (rc != 0)
10513 		return (rc);
10514 
10515 	mtx_lock(&sc->reg_lock);
10516 	if (hw_off_limits(sc))
10517 		rc = ENXIO;
10518 	else
10519 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10520 	mtx_unlock(&sc->reg_lock);
10521 	if (rc != 0)
10522 		return (rc);
10523 
10524 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10525 	if (sb == NULL)
10526 		return (ENOMEM);
10527 
10528 	sbuf_printf(sb,
10529 	    "                                IP                 IPv6\n");
10530 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10531 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10532 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10533 	    v4.tcp_in_segs, v6.tcp_in_segs);
10534 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10535 	    v4.tcp_out_segs, v6.tcp_out_segs);
10536 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10537 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10538 
10539 	rc = sbuf_finish(sb);
10540 	sbuf_delete(sb);
10541 
10542 	return (rc);
10543 }
10544 
10545 static int
10546 sysctl_tids(SYSCTL_HANDLER_ARGS)
10547 {
10548 	struct adapter *sc = arg1;
10549 	struct sbuf *sb;
10550 	int rc;
10551 	uint32_t x, y;
10552 	struct tid_info *t = &sc->tids;
10553 
10554 	rc = sysctl_wire_old_buffer(req, 0);
10555 	if (rc != 0)
10556 		return (rc);
10557 
10558 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10559 	if (sb == NULL)
10560 		return (ENOMEM);
10561 
10562 	if (t->natids) {
10563 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10564 		    t->atids_in_use);
10565 	}
10566 
10567 	if (t->nhpftids) {
10568 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10569 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10570 	}
10571 
10572 	if (t->ntids) {
10573 		bool hashen = false;
10574 
10575 		mtx_lock(&sc->reg_lock);
10576 		if (hw_off_limits(sc))
10577 			rc = ENXIO;
10578 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10579 			hashen = true;
10580 			if (chip_id(sc) <= CHELSIO_T5) {
10581 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10582 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10583 			} else {
10584 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10585 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10586 			}
10587 		}
10588 		mtx_unlock(&sc->reg_lock);
10589 		if (rc != 0)
10590 			goto done;
10591 
10592 		sbuf_printf(sb, "TID range: ");
10593 		if (hashen) {
10594 			if (x)
10595 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10596 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10597 		} else {
10598 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10599 			    t->ntids - 1);
10600 		}
10601 		sbuf_printf(sb, ", in use: %u\n",
10602 		    atomic_load_acq_int(&t->tids_in_use));
10603 	}
10604 
10605 	if (t->nstids) {
10606 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10607 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10608 	}
10609 
10610 	if (t->nftids) {
10611 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10612 		    t->ftid_end, t->ftids_in_use);
10613 	}
10614 
10615 	if (t->netids) {
10616 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10617 		    t->etid_base + t->netids - 1, t->etids_in_use);
10618 	}
10619 
10620 	mtx_lock(&sc->reg_lock);
10621 	if (hw_off_limits(sc))
10622 		rc = ENXIO;
10623 	else {
10624 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10625 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10626 	}
10627 	mtx_unlock(&sc->reg_lock);
10628 	if (rc != 0)
10629 		goto done;
10630 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10631 done:
10632 	if (rc == 0)
10633 		rc = sbuf_finish(sb);
10634 	else
10635 		(void)sbuf_finish(sb);
10636 	sbuf_delete(sb);
10637 
10638 	return (rc);
10639 }
10640 
10641 static int
10642 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10643 {
10644 	struct adapter *sc = arg1;
10645 	struct sbuf *sb;
10646 	int rc;
10647 	struct tp_err_stats stats;
10648 
10649 	rc = sysctl_wire_old_buffer(req, 0);
10650 	if (rc != 0)
10651 		return (rc);
10652 
10653 	mtx_lock(&sc->reg_lock);
10654 	if (hw_off_limits(sc))
10655 		rc = ENXIO;
10656 	else
10657 		t4_tp_get_err_stats(sc, &stats, 0);
10658 	mtx_unlock(&sc->reg_lock);
10659 	if (rc != 0)
10660 		return (rc);
10661 
10662 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10663 	if (sb == NULL)
10664 		return (ENOMEM);
10665 
10666 	if (sc->chip_params->nchan > 2) {
10667 		sbuf_printf(sb, "                 channel 0  channel 1"
10668 		    "  channel 2  channel 3\n");
10669 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10670 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10671 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10672 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10673 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10674 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10675 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10676 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10677 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10678 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10679 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10680 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10681 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10682 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10683 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10684 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10685 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10686 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10687 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10688 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10689 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10690 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10691 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10692 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10693 	} else {
10694 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10695 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10696 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10697 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10698 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10699 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10700 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10701 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10702 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10703 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10704 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10705 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10706 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10707 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10708 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10709 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10710 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10711 	}
10712 
10713 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10714 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10715 
10716 	rc = sbuf_finish(sb);
10717 	sbuf_delete(sb);
10718 
10719 	return (rc);
10720 }
10721 
10722 static int
10723 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10724 {
10725 	struct adapter *sc = arg1;
10726 	struct sbuf *sb;
10727 	int rc;
10728 	struct tp_tnl_stats stats;
10729 
10730 	rc = sysctl_wire_old_buffer(req, 0);
10731 	if (rc != 0)
10732 		return(rc);
10733 
10734 	mtx_lock(&sc->reg_lock);
10735 	if (hw_off_limits(sc))
10736 		rc = ENXIO;
10737 	else
10738 		t4_tp_get_tnl_stats(sc, &stats, 1);
10739 	mtx_unlock(&sc->reg_lock);
10740 	if (rc != 0)
10741 		return (rc);
10742 
10743 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10744 	if (sb == NULL)
10745 		return (ENOMEM);
10746 
10747 	if (sc->chip_params->nchan > 2) {
10748 		sbuf_printf(sb, "           channel 0  channel 1"
10749 		    "  channel 2  channel 3\n");
10750 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10751 		    stats.out_pkt[0], stats.out_pkt[1],
10752 		    stats.out_pkt[2], stats.out_pkt[3]);
10753 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10754 		    stats.in_pkt[0], stats.in_pkt[1],
10755 		    stats.in_pkt[2], stats.in_pkt[3]);
10756 	} else {
10757 		sbuf_printf(sb, "           channel 0  channel 1\n");
10758 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10759 		    stats.out_pkt[0], stats.out_pkt[1]);
10760 		sbuf_printf(sb, "InPkts:   %10u %10u",
10761 		    stats.in_pkt[0], stats.in_pkt[1]);
10762 	}
10763 
10764 	rc = sbuf_finish(sb);
10765 	sbuf_delete(sb);
10766 
10767 	return (rc);
10768 }
10769 
10770 static int
10771 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10772 {
10773 	struct adapter *sc = arg1;
10774 	struct tp_params *tpp = &sc->params.tp;
10775 	u_int mask;
10776 	int rc;
10777 
10778 	mask = tpp->la_mask >> 16;
10779 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10780 	if (rc != 0 || req->newptr == NULL)
10781 		return (rc);
10782 	if (mask > 0xffff)
10783 		return (EINVAL);
10784 	mtx_lock(&sc->reg_lock);
10785 	if (hw_off_limits(sc))
10786 		rc = ENXIO;
10787 	else {
10788 		tpp->la_mask = mask << 16;
10789 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10790 		    tpp->la_mask);
10791 	}
10792 	mtx_unlock(&sc->reg_lock);
10793 
10794 	return (rc);
10795 }
10796 
10797 struct field_desc {
10798 	const char *name;
10799 	u_int start;
10800 	u_int width;
10801 };
10802 
10803 static void
10804 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10805 {
10806 	char buf[32];
10807 	int line_size = 0;
10808 
10809 	while (f->name) {
10810 		uint64_t mask = (1ULL << f->width) - 1;
10811 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10812 		    ((uintmax_t)v >> f->start) & mask);
10813 
10814 		if (line_size + len >= 79) {
10815 			line_size = 8;
10816 			sbuf_printf(sb, "\n        ");
10817 		}
10818 		sbuf_printf(sb, "%s ", buf);
10819 		line_size += len + 1;
10820 		f++;
10821 	}
10822 	sbuf_printf(sb, "\n");
10823 }
10824 
10825 static const struct field_desc tp_la0[] = {
10826 	{ "RcfOpCodeOut", 60, 4 },
10827 	{ "State", 56, 4 },
10828 	{ "WcfState", 52, 4 },
10829 	{ "RcfOpcSrcOut", 50, 2 },
10830 	{ "CRxError", 49, 1 },
10831 	{ "ERxError", 48, 1 },
10832 	{ "SanityFailed", 47, 1 },
10833 	{ "SpuriousMsg", 46, 1 },
10834 	{ "FlushInputMsg", 45, 1 },
10835 	{ "FlushInputCpl", 44, 1 },
10836 	{ "RssUpBit", 43, 1 },
10837 	{ "RssFilterHit", 42, 1 },
10838 	{ "Tid", 32, 10 },
10839 	{ "InitTcb", 31, 1 },
10840 	{ "LineNumber", 24, 7 },
10841 	{ "Emsg", 23, 1 },
10842 	{ "EdataOut", 22, 1 },
10843 	{ "Cmsg", 21, 1 },
10844 	{ "CdataOut", 20, 1 },
10845 	{ "EreadPdu", 19, 1 },
10846 	{ "CreadPdu", 18, 1 },
10847 	{ "TunnelPkt", 17, 1 },
10848 	{ "RcfPeerFin", 16, 1 },
10849 	{ "RcfReasonOut", 12, 4 },
10850 	{ "TxCchannel", 10, 2 },
10851 	{ "RcfTxChannel", 8, 2 },
10852 	{ "RxEchannel", 6, 2 },
10853 	{ "RcfRxChannel", 5, 1 },
10854 	{ "RcfDataOutSrdy", 4, 1 },
10855 	{ "RxDvld", 3, 1 },
10856 	{ "RxOoDvld", 2, 1 },
10857 	{ "RxCongestion", 1, 1 },
10858 	{ "TxCongestion", 0, 1 },
10859 	{ NULL }
10860 };
10861 
10862 static const struct field_desc tp_la1[] = {
10863 	{ "CplCmdIn", 56, 8 },
10864 	{ "CplCmdOut", 48, 8 },
10865 	{ "ESynOut", 47, 1 },
10866 	{ "EAckOut", 46, 1 },
10867 	{ "EFinOut", 45, 1 },
10868 	{ "ERstOut", 44, 1 },
10869 	{ "SynIn", 43, 1 },
10870 	{ "AckIn", 42, 1 },
10871 	{ "FinIn", 41, 1 },
10872 	{ "RstIn", 40, 1 },
10873 	{ "DataIn", 39, 1 },
10874 	{ "DataInVld", 38, 1 },
10875 	{ "PadIn", 37, 1 },
10876 	{ "RxBufEmpty", 36, 1 },
10877 	{ "RxDdp", 35, 1 },
10878 	{ "RxFbCongestion", 34, 1 },
10879 	{ "TxFbCongestion", 33, 1 },
10880 	{ "TxPktSumSrdy", 32, 1 },
10881 	{ "RcfUlpType", 28, 4 },
10882 	{ "Eread", 27, 1 },
10883 	{ "Ebypass", 26, 1 },
10884 	{ "Esave", 25, 1 },
10885 	{ "Static0", 24, 1 },
10886 	{ "Cread", 23, 1 },
10887 	{ "Cbypass", 22, 1 },
10888 	{ "Csave", 21, 1 },
10889 	{ "CPktOut", 20, 1 },
10890 	{ "RxPagePoolFull", 18, 2 },
10891 	{ "RxLpbkPkt", 17, 1 },
10892 	{ "TxLpbkPkt", 16, 1 },
10893 	{ "RxVfValid", 15, 1 },
10894 	{ "SynLearned", 14, 1 },
10895 	{ "SetDelEntry", 13, 1 },
10896 	{ "SetInvEntry", 12, 1 },
10897 	{ "CpcmdDvld", 11, 1 },
10898 	{ "CpcmdSave", 10, 1 },
10899 	{ "RxPstructsFull", 8, 2 },
10900 	{ "EpcmdDvld", 7, 1 },
10901 	{ "EpcmdFlush", 6, 1 },
10902 	{ "EpcmdTrimPrefix", 5, 1 },
10903 	{ "EpcmdTrimPostfix", 4, 1 },
10904 	{ "ERssIp4Pkt", 3, 1 },
10905 	{ "ERssIp6Pkt", 2, 1 },
10906 	{ "ERssTcpUdpPkt", 1, 1 },
10907 	{ "ERssFceFipPkt", 0, 1 },
10908 	{ NULL }
10909 };
10910 
10911 static const struct field_desc tp_la2[] = {
10912 	{ "CplCmdIn", 56, 8 },
10913 	{ "MpsVfVld", 55, 1 },
10914 	{ "MpsPf", 52, 3 },
10915 	{ "MpsVf", 44, 8 },
10916 	{ "SynIn", 43, 1 },
10917 	{ "AckIn", 42, 1 },
10918 	{ "FinIn", 41, 1 },
10919 	{ "RstIn", 40, 1 },
10920 	{ "DataIn", 39, 1 },
10921 	{ "DataInVld", 38, 1 },
10922 	{ "PadIn", 37, 1 },
10923 	{ "RxBufEmpty", 36, 1 },
10924 	{ "RxDdp", 35, 1 },
10925 	{ "RxFbCongestion", 34, 1 },
10926 	{ "TxFbCongestion", 33, 1 },
10927 	{ "TxPktSumSrdy", 32, 1 },
10928 	{ "RcfUlpType", 28, 4 },
10929 	{ "Eread", 27, 1 },
10930 	{ "Ebypass", 26, 1 },
10931 	{ "Esave", 25, 1 },
10932 	{ "Static0", 24, 1 },
10933 	{ "Cread", 23, 1 },
10934 	{ "Cbypass", 22, 1 },
10935 	{ "Csave", 21, 1 },
10936 	{ "CPktOut", 20, 1 },
10937 	{ "RxPagePoolFull", 18, 2 },
10938 	{ "RxLpbkPkt", 17, 1 },
10939 	{ "TxLpbkPkt", 16, 1 },
10940 	{ "RxVfValid", 15, 1 },
10941 	{ "SynLearned", 14, 1 },
10942 	{ "SetDelEntry", 13, 1 },
10943 	{ "SetInvEntry", 12, 1 },
10944 	{ "CpcmdDvld", 11, 1 },
10945 	{ "CpcmdSave", 10, 1 },
10946 	{ "RxPstructsFull", 8, 2 },
10947 	{ "EpcmdDvld", 7, 1 },
10948 	{ "EpcmdFlush", 6, 1 },
10949 	{ "EpcmdTrimPrefix", 5, 1 },
10950 	{ "EpcmdTrimPostfix", 4, 1 },
10951 	{ "ERssIp4Pkt", 3, 1 },
10952 	{ "ERssIp6Pkt", 2, 1 },
10953 	{ "ERssTcpUdpPkt", 1, 1 },
10954 	{ "ERssFceFipPkt", 0, 1 },
10955 	{ NULL }
10956 };
10957 
10958 static void
10959 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10960 {
10961 
10962 	field_desc_show(sb, *p, tp_la0);
10963 }
10964 
10965 static void
10966 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10967 {
10968 
10969 	if (idx)
10970 		sbuf_printf(sb, "\n");
10971 	field_desc_show(sb, p[0], tp_la0);
10972 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10973 		field_desc_show(sb, p[1], tp_la0);
10974 }
10975 
10976 static void
10977 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
10978 {
10979 
10980 	if (idx)
10981 		sbuf_printf(sb, "\n");
10982 	field_desc_show(sb, p[0], tp_la0);
10983 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10984 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
10985 }
10986 
10987 static int
10988 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
10989 {
10990 	struct adapter *sc = arg1;
10991 	struct sbuf *sb;
10992 	uint64_t *buf, *p;
10993 	int rc;
10994 	u_int i, inc;
10995 	void (*show_func)(struct sbuf *, uint64_t *, int);
10996 
10997 	rc = sysctl_wire_old_buffer(req, 0);
10998 	if (rc != 0)
10999 		return (rc);
11000 
11001 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11002 	if (sb == NULL)
11003 		return (ENOMEM);
11004 
11005 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
11006 
11007 	mtx_lock(&sc->reg_lock);
11008 	if (hw_off_limits(sc))
11009 		rc = ENXIO;
11010 	else {
11011 		t4_tp_read_la(sc, buf, NULL);
11012 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
11013 		case 2:
11014 			inc = 2;
11015 			show_func = tp_la_show2;
11016 			break;
11017 		case 3:
11018 			inc = 2;
11019 			show_func = tp_la_show3;
11020 			break;
11021 		default:
11022 			inc = 1;
11023 			show_func = tp_la_show;
11024 		}
11025 	}
11026 	mtx_unlock(&sc->reg_lock);
11027 	if (rc != 0)
11028 		goto done;
11029 
11030 	p = buf;
11031 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
11032 		(*show_func)(sb, p, i);
11033 	rc = sbuf_finish(sb);
11034 done:
11035 	sbuf_delete(sb);
11036 	free(buf, M_CXGBE);
11037 	return (rc);
11038 }
11039 
11040 static int
11041 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
11042 {
11043 	struct adapter *sc = arg1;
11044 	struct sbuf *sb;
11045 	int rc;
11046 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
11047 
11048 	rc = sysctl_wire_old_buffer(req, 0);
11049 	if (rc != 0)
11050 		return (rc);
11051 
11052 	mtx_lock(&sc->reg_lock);
11053 	if (hw_off_limits(sc))
11054 		rc = ENXIO;
11055 	else
11056 		t4_get_chan_txrate(sc, nrate, orate);
11057 	mtx_unlock(&sc->reg_lock);
11058 	if (rc != 0)
11059 		return (rc);
11060 
11061 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11062 	if (sb == NULL)
11063 		return (ENOMEM);
11064 
11065 	if (sc->chip_params->nchan > 2) {
11066 		sbuf_printf(sb, "              channel 0   channel 1"
11067 		    "   channel 2   channel 3\n");
11068 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
11069 		    nrate[0], nrate[1], nrate[2], nrate[3]);
11070 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
11071 		    orate[0], orate[1], orate[2], orate[3]);
11072 	} else {
11073 		sbuf_printf(sb, "              channel 0   channel 1\n");
11074 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
11075 		    nrate[0], nrate[1]);
11076 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
11077 		    orate[0], orate[1]);
11078 	}
11079 
11080 	rc = sbuf_finish(sb);
11081 	sbuf_delete(sb);
11082 
11083 	return (rc);
11084 }
11085 
11086 static int
11087 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
11088 {
11089 	struct adapter *sc = arg1;
11090 	struct sbuf *sb;
11091 	uint32_t *buf, *p;
11092 	int rc, i;
11093 
11094 	rc = sysctl_wire_old_buffer(req, 0);
11095 	if (rc != 0)
11096 		return (rc);
11097 
11098 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11099 	if (sb == NULL)
11100 		return (ENOMEM);
11101 
11102 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
11103 	    M_ZERO | M_WAITOK);
11104 
11105 	mtx_lock(&sc->reg_lock);
11106 	if (hw_off_limits(sc))
11107 		rc = ENXIO;
11108 	else
11109 		t4_ulprx_read_la(sc, buf);
11110 	mtx_unlock(&sc->reg_lock);
11111 	if (rc != 0)
11112 		goto done;
11113 
11114 	p = buf;
11115 	sbuf_printf(sb, "      Pcmd        Type   Message"
11116 	    "                Data");
11117 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
11118 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
11119 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
11120 	}
11121 	rc = sbuf_finish(sb);
11122 done:
11123 	sbuf_delete(sb);
11124 	free(buf, M_CXGBE);
11125 	return (rc);
11126 }
11127 
11128 static int
11129 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
11130 {
11131 	struct adapter *sc = arg1;
11132 	struct sbuf *sb;
11133 	int rc;
11134 	uint32_t cfg, s1, s2;
11135 
11136 	MPASS(chip_id(sc) >= CHELSIO_T5);
11137 
11138 	rc = sysctl_wire_old_buffer(req, 0);
11139 	if (rc != 0)
11140 		return (rc);
11141 
11142 	mtx_lock(&sc->reg_lock);
11143 	if (hw_off_limits(sc))
11144 		rc = ENXIO;
11145 	else {
11146 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
11147 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
11148 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
11149 	}
11150 	mtx_unlock(&sc->reg_lock);
11151 	if (rc != 0)
11152 		return (rc);
11153 
11154 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11155 	if (sb == NULL)
11156 		return (ENOMEM);
11157 
11158 	if (G_STATSOURCE_T5(cfg) == 7) {
11159 		int mode;
11160 
11161 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
11162 		if (mode == 0)
11163 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
11164 		else if (mode == 1)
11165 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
11166 		else
11167 			sbuf_printf(sb, "unknown mode %d", mode);
11168 	}
11169 	rc = sbuf_finish(sb);
11170 	sbuf_delete(sb);
11171 
11172 	return (rc);
11173 }
11174 
11175 static int
11176 sysctl_cpus(SYSCTL_HANDLER_ARGS)
11177 {
11178 	struct adapter *sc = arg1;
11179 	enum cpu_sets op = arg2;
11180 	cpuset_t cpuset;
11181 	struct sbuf *sb;
11182 	int i, rc;
11183 
11184 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
11185 
11186 	CPU_ZERO(&cpuset);
11187 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
11188 	if (rc != 0)
11189 		return (rc);
11190 
11191 	rc = sysctl_wire_old_buffer(req, 0);
11192 	if (rc != 0)
11193 		return (rc);
11194 
11195 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11196 	if (sb == NULL)
11197 		return (ENOMEM);
11198 
11199 	CPU_FOREACH(i)
11200 		sbuf_printf(sb, "%d ", i);
11201 	rc = sbuf_finish(sb);
11202 	sbuf_delete(sb);
11203 
11204 	return (rc);
11205 }
11206 
11207 static int
11208 sysctl_reset(SYSCTL_HANDLER_ARGS)
11209 {
11210 	struct adapter *sc = arg1;
11211 	u_int val;
11212 	int rc;
11213 
11214 	val = atomic_load_int(&sc->num_resets);
11215 	rc = sysctl_handle_int(oidp, &val, 0, req);
11216 	if (rc != 0 || req->newptr == NULL)
11217 		return (rc);
11218 
11219 	if (val == 0) {
11220 		/* Zero out the counter that tracks reset. */
11221 		atomic_store_int(&sc->num_resets, 0);
11222 		return (0);
11223 	}
11224 
11225 	if (val != 1)
11226 		return (EINVAL);	/* 0 or 1 are the only legal values */
11227 
11228 	if (hw_off_limits(sc))		/* harmless race */
11229 		return (EALREADY);
11230 
11231 	taskqueue_enqueue(reset_tq, &sc->reset_task);
11232 	return (0);
11233 }
11234 
11235 #ifdef TCP_OFFLOAD
11236 static int
11237 sysctl_tls(SYSCTL_HANDLER_ARGS)
11238 {
11239 	struct adapter *sc = arg1;
11240 	int i, j, v, rc;
11241 	struct vi_info *vi;
11242 
11243 	v = sc->tt.tls;
11244 	rc = sysctl_handle_int(oidp, &v, 0, req);
11245 	if (rc != 0 || req->newptr == NULL)
11246 		return (rc);
11247 
11248 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11249 		return (ENOTSUP);
11250 
11251 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11252 	if (rc)
11253 		return (rc);
11254 	if (hw_off_limits(sc))
11255 		rc = ENXIO;
11256 	else {
11257 		sc->tt.tls = !!v;
11258 		for_each_port(sc, i) {
11259 			for_each_vi(sc->port[i], j, vi) {
11260 				if (vi->flags & VI_INIT_DONE)
11261 					t4_update_fl_bufsize(vi->ifp);
11262 			}
11263 		}
11264 	}
11265 	end_synchronized_op(sc, 0);
11266 
11267 	return (rc);
11268 
11269 }
11270 
11271 static void
11272 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11273 {
11274 	u_int rem = val % factor;
11275 
11276 	if (rem == 0)
11277 		snprintf(buf, len, "%u", val / factor);
11278 	else {
11279 		while (rem % 10 == 0)
11280 			rem /= 10;
11281 		snprintf(buf, len, "%u.%u", val / factor, rem);
11282 	}
11283 }
11284 
11285 static int
11286 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11287 {
11288 	struct adapter *sc = arg1;
11289 	char buf[16];
11290 	u_int res, re;
11291 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11292 
11293 	mtx_lock(&sc->reg_lock);
11294 	if (hw_off_limits(sc))
11295 		res = (u_int)-1;
11296 	else
11297 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11298 	mtx_unlock(&sc->reg_lock);
11299 	if (res == (u_int)-1)
11300 		return (ENXIO);
11301 
11302 	switch (arg2) {
11303 	case 0:
11304 		/* timer_tick */
11305 		re = G_TIMERRESOLUTION(res);
11306 		break;
11307 	case 1:
11308 		/* TCP timestamp tick */
11309 		re = G_TIMESTAMPRESOLUTION(res);
11310 		break;
11311 	case 2:
11312 		/* DACK tick */
11313 		re = G_DELAYEDACKRESOLUTION(res);
11314 		break;
11315 	default:
11316 		return (EDOOFUS);
11317 	}
11318 
11319 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11320 
11321 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11322 }
11323 
11324 static int
11325 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11326 {
11327 	struct adapter *sc = arg1;
11328 	int rc;
11329 	u_int dack_tmr, dack_re, v;
11330 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11331 
11332 	mtx_lock(&sc->reg_lock);
11333 	if (hw_off_limits(sc))
11334 		rc = ENXIO;
11335 	else {
11336 		rc = 0;
11337 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11338 		    A_TP_TIMER_RESOLUTION));
11339 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11340 	}
11341 	mtx_unlock(&sc->reg_lock);
11342 	if (rc != 0)
11343 		return (rc);
11344 
11345 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11346 
11347 	return (sysctl_handle_int(oidp, &v, 0, req));
11348 }
11349 
11350 static int
11351 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11352 {
11353 	struct adapter *sc = arg1;
11354 	int rc, reg = arg2;
11355 	u_int tre;
11356 	u_long tp_tick_us, v;
11357 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11358 
11359 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11360 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11361 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11362 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11363 
11364 	mtx_lock(&sc->reg_lock);
11365 	if (hw_off_limits(sc))
11366 		rc = ENXIO;
11367 	else {
11368 		rc = 0;
11369 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11370 		tp_tick_us = (cclk_ps << tre) / 1000000;
11371 		if (reg == A_TP_INIT_SRTT)
11372 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11373 		else
11374 			v = tp_tick_us * t4_read_reg(sc, reg);
11375 	}
11376 	mtx_unlock(&sc->reg_lock);
11377 	if (rc != 0)
11378 		return (rc);
11379 	else
11380 		return (sysctl_handle_long(oidp, &v, 0, req));
11381 }
11382 
11383 /*
11384  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11385  * passed to this function.
11386  */
11387 static int
11388 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11389 {
11390 	struct adapter *sc = arg1;
11391 	int rc, idx = arg2;
11392 	u_int v;
11393 
11394 	MPASS(idx >= 0 && idx <= 24);
11395 
11396 	mtx_lock(&sc->reg_lock);
11397 	if (hw_off_limits(sc))
11398 		rc = ENXIO;
11399 	else {
11400 		rc = 0;
11401 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11402 	}
11403 	mtx_unlock(&sc->reg_lock);
11404 	if (rc != 0)
11405 		return (rc);
11406 	else
11407 		return (sysctl_handle_int(oidp, &v, 0, req));
11408 }
11409 
11410 static int
11411 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11412 {
11413 	struct adapter *sc = arg1;
11414 	int rc, idx = arg2;
11415 	u_int shift, v, r;
11416 
11417 	MPASS(idx >= 0 && idx < 16);
11418 
11419 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11420 	shift = (idx & 3) << 3;
11421 	mtx_lock(&sc->reg_lock);
11422 	if (hw_off_limits(sc))
11423 		rc = ENXIO;
11424 	else {
11425 		rc = 0;
11426 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11427 	}
11428 	mtx_unlock(&sc->reg_lock);
11429 	if (rc != 0)
11430 		return (rc);
11431 	else
11432 		return (sysctl_handle_int(oidp, &v, 0, req));
11433 }
11434 
11435 static int
11436 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11437 {
11438 	struct vi_info *vi = arg1;
11439 	struct adapter *sc = vi->adapter;
11440 	int idx, rc, i;
11441 	struct sge_ofld_rxq *ofld_rxq;
11442 	uint8_t v;
11443 
11444 	idx = vi->ofld_tmr_idx;
11445 
11446 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11447 	if (rc != 0 || req->newptr == NULL)
11448 		return (rc);
11449 
11450 	if (idx < 0 || idx >= SGE_NTIMERS)
11451 		return (EINVAL);
11452 
11453 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11454 	    "t4otmr");
11455 	if (rc)
11456 		return (rc);
11457 
11458 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11459 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11460 #ifdef atomic_store_rel_8
11461 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11462 #else
11463 		ofld_rxq->iq.intr_params = v;
11464 #endif
11465 	}
11466 	vi->ofld_tmr_idx = idx;
11467 
11468 	end_synchronized_op(sc, LOCK_HELD);
11469 	return (0);
11470 }
11471 
11472 static int
11473 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11474 {
11475 	struct vi_info *vi = arg1;
11476 	struct adapter *sc = vi->adapter;
11477 	int idx, rc;
11478 
11479 	idx = vi->ofld_pktc_idx;
11480 
11481 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11482 	if (rc != 0 || req->newptr == NULL)
11483 		return (rc);
11484 
11485 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11486 		return (EINVAL);
11487 
11488 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11489 	    "t4opktc");
11490 	if (rc)
11491 		return (rc);
11492 
11493 	if (vi->flags & VI_INIT_DONE)
11494 		rc = EBUSY; /* cannot be changed once the queues are created */
11495 	else
11496 		vi->ofld_pktc_idx = idx;
11497 
11498 	end_synchronized_op(sc, LOCK_HELD);
11499 	return (rc);
11500 }
11501 #endif
11502 
11503 static int
11504 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11505 {
11506 	int rc;
11507 
11508 	if (cntxt->cid > M_CTXTQID)
11509 		return (EINVAL);
11510 
11511 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11512 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11513 		return (EINVAL);
11514 
11515 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11516 	if (rc)
11517 		return (rc);
11518 
11519 	if (hw_off_limits(sc)) {
11520 		rc = ENXIO;
11521 		goto done;
11522 	}
11523 
11524 	if (sc->flags & FW_OK) {
11525 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11526 		    &cntxt->data[0]);
11527 		if (rc == 0)
11528 			goto done;
11529 	}
11530 
11531 	/*
11532 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11533 	 * the backdoor.
11534 	 */
11535 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11536 done:
11537 	end_synchronized_op(sc, 0);
11538 	return (rc);
11539 }
11540 
11541 static int
11542 load_fw(struct adapter *sc, struct t4_data *fw)
11543 {
11544 	int rc;
11545 	uint8_t *fw_data;
11546 
11547 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11548 	if (rc)
11549 		return (rc);
11550 
11551 	if (hw_off_limits(sc)) {
11552 		rc = ENXIO;
11553 		goto done;
11554 	}
11555 
11556 	/*
11557 	 * The firmware, with the sole exception of the memory parity error
11558 	 * handler, runs from memory and not flash.  It is almost always safe to
11559 	 * install a new firmware on a running system.  Just set bit 1 in
11560 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11561 	 */
11562 	if (sc->flags & FULL_INIT_DONE &&
11563 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11564 		rc = EBUSY;
11565 		goto done;
11566 	}
11567 
11568 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11569 
11570 	rc = copyin(fw->data, fw_data, fw->len);
11571 	if (rc == 0)
11572 		rc = -t4_load_fw(sc, fw_data, fw->len);
11573 
11574 	free(fw_data, M_CXGBE);
11575 done:
11576 	end_synchronized_op(sc, 0);
11577 	return (rc);
11578 }
11579 
11580 static int
11581 load_cfg(struct adapter *sc, struct t4_data *cfg)
11582 {
11583 	int rc;
11584 	uint8_t *cfg_data = NULL;
11585 
11586 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11587 	if (rc)
11588 		return (rc);
11589 
11590 	if (hw_off_limits(sc)) {
11591 		rc = ENXIO;
11592 		goto done;
11593 	}
11594 
11595 	if (cfg->len == 0) {
11596 		/* clear */
11597 		rc = -t4_load_cfg(sc, NULL, 0);
11598 		goto done;
11599 	}
11600 
11601 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11602 
11603 	rc = copyin(cfg->data, cfg_data, cfg->len);
11604 	if (rc == 0)
11605 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11606 
11607 	free(cfg_data, M_CXGBE);
11608 done:
11609 	end_synchronized_op(sc, 0);
11610 	return (rc);
11611 }
11612 
11613 static int
11614 load_boot(struct adapter *sc, struct t4_bootrom *br)
11615 {
11616 	int rc;
11617 	uint8_t *br_data = NULL;
11618 	u_int offset;
11619 
11620 	if (br->len > 1024 * 1024)
11621 		return (EFBIG);
11622 
11623 	if (br->pf_offset == 0) {
11624 		/* pfidx */
11625 		if (br->pfidx_addr > 7)
11626 			return (EINVAL);
11627 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11628 		    A_PCIE_PF_EXPROM_OFST)));
11629 	} else if (br->pf_offset == 1) {
11630 		/* offset */
11631 		offset = G_OFFSET(br->pfidx_addr);
11632 	} else {
11633 		return (EINVAL);
11634 	}
11635 
11636 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11637 	if (rc)
11638 		return (rc);
11639 
11640 	if (hw_off_limits(sc)) {
11641 		rc = ENXIO;
11642 		goto done;
11643 	}
11644 
11645 	if (br->len == 0) {
11646 		/* clear */
11647 		rc = -t4_load_boot(sc, NULL, offset, 0);
11648 		goto done;
11649 	}
11650 
11651 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11652 
11653 	rc = copyin(br->data, br_data, br->len);
11654 	if (rc == 0)
11655 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11656 
11657 	free(br_data, M_CXGBE);
11658 done:
11659 	end_synchronized_op(sc, 0);
11660 	return (rc);
11661 }
11662 
11663 static int
11664 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11665 {
11666 	int rc;
11667 	uint8_t *bc_data = NULL;
11668 
11669 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11670 	if (rc)
11671 		return (rc);
11672 
11673 	if (hw_off_limits(sc)) {
11674 		rc = ENXIO;
11675 		goto done;
11676 	}
11677 
11678 	if (bc->len == 0) {
11679 		/* clear */
11680 		rc = -t4_load_bootcfg(sc, NULL, 0);
11681 		goto done;
11682 	}
11683 
11684 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11685 
11686 	rc = copyin(bc->data, bc_data, bc->len);
11687 	if (rc == 0)
11688 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11689 
11690 	free(bc_data, M_CXGBE);
11691 done:
11692 	end_synchronized_op(sc, 0);
11693 	return (rc);
11694 }
11695 
11696 static int
11697 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11698 {
11699 	int rc;
11700 	struct cudbg_init *cudbg;
11701 	void *handle, *buf;
11702 
11703 	/* buf is large, don't block if no memory is available */
11704 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11705 	if (buf == NULL)
11706 		return (ENOMEM);
11707 
11708 	handle = cudbg_alloc_handle();
11709 	if (handle == NULL) {
11710 		rc = ENOMEM;
11711 		goto done;
11712 	}
11713 
11714 	cudbg = cudbg_get_init(handle);
11715 	cudbg->adap = sc;
11716 	cudbg->print = (cudbg_print_cb)printf;
11717 
11718 #ifndef notyet
11719 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11720 	    __func__, dump->wr_flash, dump->len, dump->data);
11721 #endif
11722 
11723 	if (dump->wr_flash)
11724 		cudbg->use_flash = 1;
11725 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11726 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11727 
11728 	rc = cudbg_collect(handle, buf, &dump->len);
11729 	if (rc != 0)
11730 		goto done;
11731 
11732 	rc = copyout(buf, dump->data, dump->len);
11733 done:
11734 	cudbg_free_handle(handle);
11735 	free(buf, M_CXGBE);
11736 	return (rc);
11737 }
11738 
11739 static void
11740 free_offload_policy(struct t4_offload_policy *op)
11741 {
11742 	struct offload_rule *r;
11743 	int i;
11744 
11745 	if (op == NULL)
11746 		return;
11747 
11748 	r = &op->rule[0];
11749 	for (i = 0; i < op->nrules; i++, r++) {
11750 		free(r->bpf_prog.bf_insns, M_CXGBE);
11751 	}
11752 	free(op->rule, M_CXGBE);
11753 	free(op, M_CXGBE);
11754 }
11755 
11756 static int
11757 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11758 {
11759 	int i, rc, len;
11760 	struct t4_offload_policy *op, *old;
11761 	struct bpf_program *bf;
11762 	const struct offload_settings *s;
11763 	struct offload_rule *r;
11764 	void *u;
11765 
11766 	if (!is_offload(sc))
11767 		return (ENODEV);
11768 
11769 	if (uop->nrules == 0) {
11770 		/* Delete installed policies. */
11771 		op = NULL;
11772 		goto set_policy;
11773 	} else if (uop->nrules > 256) { /* arbitrary */
11774 		return (E2BIG);
11775 	}
11776 
11777 	/* Copy userspace offload policy to kernel */
11778 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11779 	op->nrules = uop->nrules;
11780 	len = op->nrules * sizeof(struct offload_rule);
11781 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11782 	rc = copyin(uop->rule, op->rule, len);
11783 	if (rc) {
11784 		free(op->rule, M_CXGBE);
11785 		free(op, M_CXGBE);
11786 		return (rc);
11787 	}
11788 
11789 	r = &op->rule[0];
11790 	for (i = 0; i < op->nrules; i++, r++) {
11791 
11792 		/* Validate open_type */
11793 		if (r->open_type != OPEN_TYPE_LISTEN &&
11794 		    r->open_type != OPEN_TYPE_ACTIVE &&
11795 		    r->open_type != OPEN_TYPE_PASSIVE &&
11796 		    r->open_type != OPEN_TYPE_DONTCARE) {
11797 error:
11798 			/*
11799 			 * Rules 0 to i have malloc'd filters that need to be
11800 			 * freed.  Rules i+1 to nrules have userspace pointers
11801 			 * and should be left alone.
11802 			 */
11803 			op->nrules = i;
11804 			free_offload_policy(op);
11805 			return (rc);
11806 		}
11807 
11808 		/* Validate settings */
11809 		s = &r->settings;
11810 		if ((s->offload != 0 && s->offload != 1) ||
11811 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11812 		    s->sched_class < -1 ||
11813 		    s->sched_class >= sc->params.nsched_cls) {
11814 			rc = EINVAL;
11815 			goto error;
11816 		}
11817 
11818 		bf = &r->bpf_prog;
11819 		u = bf->bf_insns;	/* userspace ptr */
11820 		bf->bf_insns = NULL;
11821 		if (bf->bf_len == 0) {
11822 			/* legal, matches everything */
11823 			continue;
11824 		}
11825 		len = bf->bf_len * sizeof(*bf->bf_insns);
11826 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11827 		rc = copyin(u, bf->bf_insns, len);
11828 		if (rc != 0)
11829 			goto error;
11830 
11831 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11832 			rc = EINVAL;
11833 			goto error;
11834 		}
11835 	}
11836 set_policy:
11837 	rw_wlock(&sc->policy_lock);
11838 	old = sc->policy;
11839 	sc->policy = op;
11840 	rw_wunlock(&sc->policy_lock);
11841 	free_offload_policy(old);
11842 
11843 	return (0);
11844 }
11845 
11846 #define MAX_READ_BUF_SIZE (128 * 1024)
11847 static int
11848 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11849 {
11850 	uint32_t addr, remaining, n;
11851 	uint32_t *buf;
11852 	int rc;
11853 	uint8_t *dst;
11854 
11855 	mtx_lock(&sc->reg_lock);
11856 	if (hw_off_limits(sc))
11857 		rc = ENXIO;
11858 	else
11859 		rc = validate_mem_range(sc, mr->addr, mr->len);
11860 	mtx_unlock(&sc->reg_lock);
11861 	if (rc != 0)
11862 		return (rc);
11863 
11864 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11865 	addr = mr->addr;
11866 	remaining = mr->len;
11867 	dst = (void *)mr->data;
11868 
11869 	while (remaining) {
11870 		n = min(remaining, MAX_READ_BUF_SIZE);
11871 		mtx_lock(&sc->reg_lock);
11872 		if (hw_off_limits(sc))
11873 			rc = ENXIO;
11874 		else
11875 			read_via_memwin(sc, 2, addr, buf, n);
11876 		mtx_unlock(&sc->reg_lock);
11877 		if (rc != 0)
11878 			break;
11879 
11880 		rc = copyout(buf, dst, n);
11881 		if (rc != 0)
11882 			break;
11883 
11884 		dst += n;
11885 		remaining -= n;
11886 		addr += n;
11887 	}
11888 
11889 	free(buf, M_CXGBE);
11890 	return (rc);
11891 }
11892 #undef MAX_READ_BUF_SIZE
11893 
11894 static int
11895 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11896 {
11897 	int rc;
11898 
11899 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11900 		return (EINVAL);
11901 
11902 	if (i2cd->len > sizeof(i2cd->data))
11903 		return (EFBIG);
11904 
11905 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11906 	if (rc)
11907 		return (rc);
11908 	if (hw_off_limits(sc))
11909 		rc = ENXIO;
11910 	else
11911 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11912 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11913 	end_synchronized_op(sc, 0);
11914 
11915 	return (rc);
11916 }
11917 
11918 static int
11919 clear_stats(struct adapter *sc, u_int port_id)
11920 {
11921 	int i, v, chan_map;
11922 	struct port_info *pi;
11923 	struct vi_info *vi;
11924 	struct sge_rxq *rxq;
11925 	struct sge_txq *txq;
11926 	struct sge_wrq *wrq;
11927 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11928 	struct sge_ofld_txq *ofld_txq;
11929 #endif
11930 #ifdef TCP_OFFLOAD
11931 	struct sge_ofld_rxq *ofld_rxq;
11932 #endif
11933 
11934 	if (port_id >= sc->params.nports)
11935 		return (EINVAL);
11936 	pi = sc->port[port_id];
11937 	if (pi == NULL)
11938 		return (EIO);
11939 
11940 	mtx_lock(&sc->reg_lock);
11941 	if (!hw_off_limits(sc)) {
11942 		/* MAC stats */
11943 		t4_clr_port_stats(sc, pi->tx_chan);
11944 		if (is_t6(sc)) {
11945 			if (pi->fcs_reg != -1)
11946 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11947 			else
11948 				pi->stats.rx_fcs_err = 0;
11949 		}
11950 		for_each_vi(pi, v, vi) {
11951 			if (vi->flags & VI_INIT_DONE)
11952 				t4_clr_vi_stats(sc, vi->vin);
11953 		}
11954 		chan_map = pi->rx_e_chan_map;
11955 		v = 0;	/* reuse */
11956 		while (chan_map) {
11957 			i = ffs(chan_map) - 1;
11958 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11959 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11960 			chan_map &= ~(1 << i);
11961 		}
11962 	}
11963 	mtx_unlock(&sc->reg_lock);
11964 	pi->tx_parse_error = 0;
11965 	pi->tnl_cong_drops = 0;
11966 
11967 	/*
11968 	 * Since this command accepts a port, clear stats for
11969 	 * all VIs on this port.
11970 	 */
11971 	for_each_vi(pi, v, vi) {
11972 		if (vi->flags & VI_INIT_DONE) {
11973 
11974 			for_each_rxq(vi, i, rxq) {
11975 #if defined(INET) || defined(INET6)
11976 				rxq->lro.lro_queued = 0;
11977 				rxq->lro.lro_flushed = 0;
11978 #endif
11979 				rxq->rxcsum = 0;
11980 				rxq->vlan_extraction = 0;
11981 				rxq->vxlan_rxcsum = 0;
11982 
11983 				rxq->fl.cl_allocated = 0;
11984 				rxq->fl.cl_recycled = 0;
11985 				rxq->fl.cl_fast_recycled = 0;
11986 			}
11987 
11988 			for_each_txq(vi, i, txq) {
11989 				txq->txcsum = 0;
11990 				txq->tso_wrs = 0;
11991 				txq->vlan_insertion = 0;
11992 				txq->imm_wrs = 0;
11993 				txq->sgl_wrs = 0;
11994 				txq->txpkt_wrs = 0;
11995 				txq->txpkts0_wrs = 0;
11996 				txq->txpkts1_wrs = 0;
11997 				txq->txpkts0_pkts = 0;
11998 				txq->txpkts1_pkts = 0;
11999 				txq->txpkts_flush = 0;
12000 				txq->raw_wrs = 0;
12001 				txq->vxlan_tso_wrs = 0;
12002 				txq->vxlan_txcsum = 0;
12003 				txq->kern_tls_records = 0;
12004 				txq->kern_tls_short = 0;
12005 				txq->kern_tls_partial = 0;
12006 				txq->kern_tls_full = 0;
12007 				txq->kern_tls_octets = 0;
12008 				txq->kern_tls_waste = 0;
12009 				txq->kern_tls_options = 0;
12010 				txq->kern_tls_header = 0;
12011 				txq->kern_tls_fin = 0;
12012 				txq->kern_tls_fin_short = 0;
12013 				txq->kern_tls_cbc = 0;
12014 				txq->kern_tls_gcm = 0;
12015 				mp_ring_reset_stats(txq->r);
12016 			}
12017 
12018 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12019 			for_each_ofld_txq(vi, i, ofld_txq) {
12020 				ofld_txq->wrq.tx_wrs_direct = 0;
12021 				ofld_txq->wrq.tx_wrs_copied = 0;
12022 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
12023 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
12024 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
12025 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
12026 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
12027 			}
12028 #endif
12029 #ifdef TCP_OFFLOAD
12030 			for_each_ofld_rxq(vi, i, ofld_rxq) {
12031 				ofld_rxq->fl.cl_allocated = 0;
12032 				ofld_rxq->fl.cl_recycled = 0;
12033 				ofld_rxq->fl.cl_fast_recycled = 0;
12034 				counter_u64_zero(
12035 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
12036 				counter_u64_zero(
12037 				    ofld_rxq->rx_iscsi_ddp_setup_error);
12038 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
12039 				ofld_rxq->rx_iscsi_ddp_octets = 0;
12040 				ofld_rxq->rx_iscsi_fl_pdus = 0;
12041 				ofld_rxq->rx_iscsi_fl_octets = 0;
12042 				ofld_rxq->rx_toe_tls_records = 0;
12043 				ofld_rxq->rx_toe_tls_octets = 0;
12044 			}
12045 #endif
12046 
12047 			if (IS_MAIN_VI(vi)) {
12048 				wrq = &sc->sge.ctrlq[pi->port_id];
12049 				wrq->tx_wrs_direct = 0;
12050 				wrq->tx_wrs_copied = 0;
12051 			}
12052 		}
12053 	}
12054 
12055 	return (0);
12056 }
12057 
12058 static int
12059 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12060 {
12061 #ifdef INET6
12062 	struct in6_addr in6;
12063 
12064 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12065 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
12066 		return (0);
12067 	else
12068 		return (EIO);
12069 #else
12070 	return (ENOTSUP);
12071 #endif
12072 }
12073 
12074 static int
12075 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12076 {
12077 #ifdef INET6
12078 	struct in6_addr in6;
12079 
12080 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12081 	return (t4_release_clip_addr(sc, &in6));
12082 #else
12083 	return (ENOTSUP);
12084 #endif
12085 }
12086 
12087 int
12088 t4_os_find_pci_capability(struct adapter *sc, int cap)
12089 {
12090 	int i;
12091 
12092 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
12093 }
12094 
12095 int
12096 t4_os_pci_save_state(struct adapter *sc)
12097 {
12098 	device_t dev;
12099 	struct pci_devinfo *dinfo;
12100 
12101 	dev = sc->dev;
12102 	dinfo = device_get_ivars(dev);
12103 
12104 	pci_cfg_save(dev, dinfo, 0);
12105 	return (0);
12106 }
12107 
12108 int
12109 t4_os_pci_restore_state(struct adapter *sc)
12110 {
12111 	device_t dev;
12112 	struct pci_devinfo *dinfo;
12113 
12114 	dev = sc->dev;
12115 	dinfo = device_get_ivars(dev);
12116 
12117 	pci_cfg_restore(dev, dinfo);
12118 	return (0);
12119 }
12120 
12121 void
12122 t4_os_portmod_changed(struct port_info *pi)
12123 {
12124 	struct adapter *sc = pi->adapter;
12125 	struct vi_info *vi;
12126 	if_t ifp;
12127 	static const char *mod_str[] = {
12128 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
12129 	};
12130 
12131 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
12132 	    ("%s: port_type %u", __func__, pi->port_type));
12133 
12134 	vi = &pi->vi[0];
12135 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12136 		PORT_LOCK(pi);
12137 		build_medialist(pi);
12138 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12139 			fixup_link_config(pi);
12140 			apply_link_config(pi);
12141 		}
12142 		PORT_UNLOCK(pi);
12143 		end_synchronized_op(sc, LOCK_HELD);
12144 	}
12145 
12146 	ifp = vi->ifp;
12147 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12148 		if_printf(ifp, "transceiver unplugged.\n");
12149 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12150 		if_printf(ifp, "unknown transceiver inserted.\n");
12151 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12152 		if_printf(ifp, "unsupported transceiver inserted.\n");
12153 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12154 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12155 		    port_top_speed(pi), mod_str[pi->mod_type]);
12156 	} else {
12157 		if_printf(ifp, "transceiver (type %d) inserted.\n",
12158 		    pi->mod_type);
12159 	}
12160 }
12161 
12162 void
12163 t4_os_link_changed(struct port_info *pi)
12164 {
12165 	struct vi_info *vi;
12166 	if_t ifp;
12167 	struct link_config *lc = &pi->link_cfg;
12168 	struct adapter *sc = pi->adapter;
12169 	int v;
12170 
12171 	PORT_LOCK_ASSERT_OWNED(pi);
12172 
12173 	if (is_t6(sc)) {
12174 		if (lc->link_ok) {
12175 			if (lc->speed > 25000 ||
12176 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12177 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12178 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12179 			} else {
12180 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12181 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12182 			}
12183 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12184 			pi->stats.rx_fcs_err = 0;
12185 		} else {
12186 			pi->fcs_reg = -1;
12187 		}
12188 	} else {
12189 		MPASS(pi->fcs_reg != -1);
12190 		MPASS(pi->fcs_base == 0);
12191 	}
12192 
12193 	for_each_vi(pi, v, vi) {
12194 		ifp = vi->ifp;
12195 		if (ifp == NULL)
12196 			continue;
12197 
12198 		if (lc->link_ok) {
12199 			if_setbaudrate(ifp, IF_Mbps(lc->speed));
12200 			if_link_state_change(ifp, LINK_STATE_UP);
12201 		} else {
12202 			if_link_state_change(ifp, LINK_STATE_DOWN);
12203 		}
12204 	}
12205 }
12206 
12207 void
12208 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12209 {
12210 	struct adapter *sc;
12211 
12212 	sx_slock(&t4_list_lock);
12213 	SLIST_FOREACH(sc, &t4_list, link) {
12214 		/*
12215 		 * func should not make any assumptions about what state sc is
12216 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12217 		 */
12218 		func(sc, arg);
12219 	}
12220 	sx_sunlock(&t4_list_lock);
12221 }
12222 
12223 static int
12224 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12225     struct thread *td)
12226 {
12227 	int rc;
12228 	struct adapter *sc = dev->si_drv1;
12229 
12230 	rc = priv_check(td, PRIV_DRIVER);
12231 	if (rc != 0)
12232 		return (rc);
12233 
12234 	switch (cmd) {
12235 	case CHELSIO_T4_GETREG: {
12236 		struct t4_reg *edata = (struct t4_reg *)data;
12237 
12238 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12239 			return (EFAULT);
12240 
12241 		mtx_lock(&sc->reg_lock);
12242 		if (hw_off_limits(sc))
12243 			rc = ENXIO;
12244 		else if (edata->size == 4)
12245 			edata->val = t4_read_reg(sc, edata->addr);
12246 		else if (edata->size == 8)
12247 			edata->val = t4_read_reg64(sc, edata->addr);
12248 		else
12249 			rc = EINVAL;
12250 		mtx_unlock(&sc->reg_lock);
12251 
12252 		break;
12253 	}
12254 	case CHELSIO_T4_SETREG: {
12255 		struct t4_reg *edata = (struct t4_reg *)data;
12256 
12257 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12258 			return (EFAULT);
12259 
12260 		mtx_lock(&sc->reg_lock);
12261 		if (hw_off_limits(sc))
12262 			rc = ENXIO;
12263 		else if (edata->size == 4) {
12264 			if (edata->val & 0xffffffff00000000)
12265 				rc = EINVAL;
12266 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12267 		} else if (edata->size == 8)
12268 			t4_write_reg64(sc, edata->addr, edata->val);
12269 		else
12270 			rc = EINVAL;
12271 		mtx_unlock(&sc->reg_lock);
12272 
12273 		break;
12274 	}
12275 	case CHELSIO_T4_REGDUMP: {
12276 		struct t4_regdump *regs = (struct t4_regdump *)data;
12277 		int reglen = t4_get_regs_len(sc);
12278 		uint8_t *buf;
12279 
12280 		if (regs->len < reglen) {
12281 			regs->len = reglen; /* hint to the caller */
12282 			return (ENOBUFS);
12283 		}
12284 
12285 		regs->len = reglen;
12286 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12287 		mtx_lock(&sc->reg_lock);
12288 		if (hw_off_limits(sc))
12289 			rc = ENXIO;
12290 		else
12291 			get_regs(sc, regs, buf);
12292 		mtx_unlock(&sc->reg_lock);
12293 		if (rc == 0)
12294 			rc = copyout(buf, regs->data, reglen);
12295 		free(buf, M_CXGBE);
12296 		break;
12297 	}
12298 	case CHELSIO_T4_GET_FILTER_MODE:
12299 		rc = get_filter_mode(sc, (uint32_t *)data);
12300 		break;
12301 	case CHELSIO_T4_SET_FILTER_MODE:
12302 		rc = set_filter_mode(sc, *(uint32_t *)data);
12303 		break;
12304 	case CHELSIO_T4_SET_FILTER_MASK:
12305 		rc = set_filter_mask(sc, *(uint32_t *)data);
12306 		break;
12307 	case CHELSIO_T4_GET_FILTER:
12308 		rc = get_filter(sc, (struct t4_filter *)data);
12309 		break;
12310 	case CHELSIO_T4_SET_FILTER:
12311 		rc = set_filter(sc, (struct t4_filter *)data);
12312 		break;
12313 	case CHELSIO_T4_DEL_FILTER:
12314 		rc = del_filter(sc, (struct t4_filter *)data);
12315 		break;
12316 	case CHELSIO_T4_GET_SGE_CONTEXT:
12317 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12318 		break;
12319 	case CHELSIO_T4_LOAD_FW:
12320 		rc = load_fw(sc, (struct t4_data *)data);
12321 		break;
12322 	case CHELSIO_T4_GET_MEM:
12323 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12324 		break;
12325 	case CHELSIO_T4_GET_I2C:
12326 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12327 		break;
12328 	case CHELSIO_T4_CLEAR_STATS:
12329 		rc = clear_stats(sc, *(uint32_t *)data);
12330 		break;
12331 	case CHELSIO_T4_SCHED_CLASS:
12332 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12333 		break;
12334 	case CHELSIO_T4_SCHED_QUEUE:
12335 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12336 		break;
12337 	case CHELSIO_T4_GET_TRACER:
12338 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12339 		break;
12340 	case CHELSIO_T4_SET_TRACER:
12341 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12342 		break;
12343 	case CHELSIO_T4_LOAD_CFG:
12344 		rc = load_cfg(sc, (struct t4_data *)data);
12345 		break;
12346 	case CHELSIO_T4_LOAD_BOOT:
12347 		rc = load_boot(sc, (struct t4_bootrom *)data);
12348 		break;
12349 	case CHELSIO_T4_LOAD_BOOTCFG:
12350 		rc = load_bootcfg(sc, (struct t4_data *)data);
12351 		break;
12352 	case CHELSIO_T4_CUDBG_DUMP:
12353 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12354 		break;
12355 	case CHELSIO_T4_SET_OFLD_POLICY:
12356 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12357 		break;
12358 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12359 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12360 		break;
12361 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12362 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12363 		break;
12364 	default:
12365 		rc = ENOTTY;
12366 	}
12367 
12368 	return (rc);
12369 }
12370 
12371 #ifdef TCP_OFFLOAD
12372 static int
12373 toe_capability(struct vi_info *vi, bool enable)
12374 {
12375 	int rc;
12376 	struct port_info *pi = vi->pi;
12377 	struct adapter *sc = pi->adapter;
12378 
12379 	ASSERT_SYNCHRONIZED_OP(sc);
12380 
12381 	if (!is_offload(sc))
12382 		return (ENODEV);
12383 	if (hw_off_limits(sc))
12384 		return (ENXIO);
12385 
12386 	if (enable) {
12387 #ifdef KERN_TLS
12388 		if (sc->flags & KERN_TLS_ON && is_t6(sc)) {
12389 			int i, j, n;
12390 			struct port_info *p;
12391 			struct vi_info *v;
12392 
12393 			/*
12394 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12395 			 * on any ifnet.
12396 			 */
12397 			n = 0;
12398 			for_each_port(sc, i) {
12399 				p = sc->port[i];
12400 				for_each_vi(p, j, v) {
12401 					if (if_getcapenable(v->ifp) & IFCAP_TXTLS) {
12402 						CH_WARN(sc,
12403 						    "%s has NIC TLS enabled.\n",
12404 						    device_get_nameunit(v->dev));
12405 						n++;
12406 					}
12407 				}
12408 			}
12409 			if (n > 0) {
12410 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12411 				    "associated with this adapter before "
12412 				    "trying to enable TOE.\n");
12413 				return (EAGAIN);
12414 			}
12415 			rc = t6_config_kern_tls(sc, false);
12416 			if (rc)
12417 				return (rc);
12418 		}
12419 #endif
12420 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) != 0) {
12421 			/* TOE is already enabled. */
12422 			return (0);
12423 		}
12424 
12425 		/*
12426 		 * We need the port's queues around so that we're able to send
12427 		 * and receive CPLs to/from the TOE even if the ifnet for this
12428 		 * port has never been UP'd administratively.
12429 		 */
12430 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12431 			return (rc);
12432 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12433 		    ((rc = vi_init(&pi->vi[0])) != 0))
12434 			return (rc);
12435 
12436 		if (isset(&sc->offload_map, pi->port_id)) {
12437 			/* TOE is enabled on another VI of this port. */
12438 			pi->uld_vis++;
12439 			return (0);
12440 		}
12441 
12442 		if (!uld_active(sc, ULD_TOM)) {
12443 			rc = t4_activate_uld(sc, ULD_TOM);
12444 			if (rc == EAGAIN) {
12445 				log(LOG_WARNING,
12446 				    "You must kldload t4_tom.ko before trying "
12447 				    "to enable TOE on a cxgbe interface.\n");
12448 			}
12449 			if (rc != 0)
12450 				return (rc);
12451 			KASSERT(sc->tom_softc != NULL,
12452 			    ("%s: TOM activated but softc NULL", __func__));
12453 			KASSERT(uld_active(sc, ULD_TOM),
12454 			    ("%s: TOM activated but flag not set", __func__));
12455 		}
12456 
12457 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12458 		if (!uld_active(sc, ULD_IWARP))
12459 			(void) t4_activate_uld(sc, ULD_IWARP);
12460 		if (!uld_active(sc, ULD_ISCSI))
12461 			(void) t4_activate_uld(sc, ULD_ISCSI);
12462 
12463 		pi->uld_vis++;
12464 		setbit(&sc->offload_map, pi->port_id);
12465 	} else {
12466 		pi->uld_vis--;
12467 
12468 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12469 			return (0);
12470 
12471 		KASSERT(uld_active(sc, ULD_TOM),
12472 		    ("%s: TOM never initialized?", __func__));
12473 		clrbit(&sc->offload_map, pi->port_id);
12474 	}
12475 
12476 	return (0);
12477 }
12478 
12479 /*
12480  * Add an upper layer driver to the global list.
12481  */
12482 int
12483 t4_register_uld(struct uld_info *ui)
12484 {
12485 	int rc = 0;
12486 	struct uld_info *u;
12487 
12488 	sx_xlock(&t4_uld_list_lock);
12489 	SLIST_FOREACH(u, &t4_uld_list, link) {
12490 	    if (u->uld_id == ui->uld_id) {
12491 		    rc = EEXIST;
12492 		    goto done;
12493 	    }
12494 	}
12495 
12496 	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
12497 	ui->refcount = 0;
12498 done:
12499 	sx_xunlock(&t4_uld_list_lock);
12500 	return (rc);
12501 }
12502 
12503 int
12504 t4_unregister_uld(struct uld_info *ui)
12505 {
12506 	int rc = EINVAL;
12507 	struct uld_info *u;
12508 
12509 	sx_xlock(&t4_uld_list_lock);
12510 
12511 	SLIST_FOREACH(u, &t4_uld_list, link) {
12512 	    if (u == ui) {
12513 		    if (ui->refcount > 0) {
12514 			    rc = EBUSY;
12515 			    goto done;
12516 		    }
12517 
12518 		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
12519 		    rc = 0;
12520 		    goto done;
12521 	    }
12522 	}
12523 done:
12524 	sx_xunlock(&t4_uld_list_lock);
12525 	return (rc);
12526 }
12527 
12528 int
12529 t4_activate_uld(struct adapter *sc, int id)
12530 {
12531 	int rc;
12532 	struct uld_info *ui;
12533 
12534 	ASSERT_SYNCHRONIZED_OP(sc);
12535 
12536 	if (id < 0 || id > ULD_MAX)
12537 		return (EINVAL);
12538 	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
12539 
12540 	sx_slock(&t4_uld_list_lock);
12541 
12542 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12543 		if (ui->uld_id == id) {
12544 			if (!(sc->flags & FULL_INIT_DONE)) {
12545 				rc = adapter_init(sc);
12546 				if (rc != 0)
12547 					break;
12548 			}
12549 
12550 			rc = ui->activate(sc);
12551 			if (rc == 0) {
12552 				setbit(&sc->active_ulds, id);
12553 				ui->refcount++;
12554 			}
12555 			break;
12556 		}
12557 	}
12558 
12559 	sx_sunlock(&t4_uld_list_lock);
12560 
12561 	return (rc);
12562 }
12563 
12564 int
12565 t4_deactivate_uld(struct adapter *sc, int id)
12566 {
12567 	int rc;
12568 	struct uld_info *ui;
12569 
12570 	ASSERT_SYNCHRONIZED_OP(sc);
12571 
12572 	if (id < 0 || id > ULD_MAX)
12573 		return (EINVAL);
12574 	rc = ENXIO;
12575 
12576 	sx_slock(&t4_uld_list_lock);
12577 
12578 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12579 		if (ui->uld_id == id) {
12580 			rc = ui->deactivate(sc);
12581 			if (rc == 0) {
12582 				clrbit(&sc->active_ulds, id);
12583 				ui->refcount--;
12584 			}
12585 			break;
12586 		}
12587 	}
12588 
12589 	sx_sunlock(&t4_uld_list_lock);
12590 
12591 	return (rc);
12592 }
12593 
12594 static int
12595 t4_deactivate_all_uld(struct adapter *sc)
12596 {
12597 	int rc;
12598 	struct uld_info *ui;
12599 
12600 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4detuld");
12601 	if (rc != 0)
12602 		return (ENXIO);
12603 
12604 	sx_slock(&t4_uld_list_lock);
12605 
12606 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12607 		if (isset(&sc->active_ulds, ui->uld_id)) {
12608 			rc = ui->deactivate(sc);
12609 			if (rc != 0)
12610 				break;
12611 			clrbit(&sc->active_ulds, ui->uld_id);
12612 			ui->refcount--;
12613 		}
12614 	}
12615 
12616 	sx_sunlock(&t4_uld_list_lock);
12617 	end_synchronized_op(sc, 0);
12618 
12619 	return (rc);
12620 }
12621 
12622 static void
12623 t4_async_event(struct adapter *sc)
12624 {
12625 	struct uld_info *ui;
12626 
12627 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
12628 		return;
12629 	sx_slock(&t4_uld_list_lock);
12630 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12631 		if (ui->uld_id == ULD_IWARP) {
12632 			ui->async_event(sc);
12633 			break;
12634 		}
12635 	}
12636 	sx_sunlock(&t4_uld_list_lock);
12637 	end_synchronized_op(sc, 0);
12638 }
12639 
12640 int
12641 uld_active(struct adapter *sc, int uld_id)
12642 {
12643 
12644 	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
12645 
12646 	return (isset(&sc->active_ulds, uld_id));
12647 }
12648 #endif
12649 
12650 #ifdef KERN_TLS
12651 static int
12652 ktls_capability(struct adapter *sc, bool enable)
12653 {
12654 	ASSERT_SYNCHRONIZED_OP(sc);
12655 
12656 	if (!is_ktls(sc))
12657 		return (ENODEV);
12658 	if (!is_t6(sc))
12659 		return (0);
12660 	if (hw_off_limits(sc))
12661 		return (ENXIO);
12662 
12663 	if (enable) {
12664 		if (sc->flags & KERN_TLS_ON)
12665 			return (0);	/* already on */
12666 		if (sc->offload_map != 0) {
12667 			CH_WARN(sc,
12668 			    "Disable TOE on all interfaces associated with "
12669 			    "this adapter before trying to enable NIC TLS.\n");
12670 			return (EAGAIN);
12671 		}
12672 		return (t6_config_kern_tls(sc, true));
12673 	} else {
12674 		/*
12675 		 * Nothing to do for disable.  If TOE is enabled sometime later
12676 		 * then toe_capability will reconfigure the hardware.
12677 		 */
12678 		return (0);
12679 	}
12680 }
12681 #endif
12682 
12683 /*
12684  * t  = ptr to tunable.
12685  * nc = number of CPUs.
12686  * c  = compiled in default for that tunable.
12687  */
12688 static void
12689 calculate_nqueues(int *t, int nc, const int c)
12690 {
12691 	int nq;
12692 
12693 	if (*t > 0)
12694 		return;
12695 	nq = *t < 0 ? -*t : c;
12696 	*t = min(nc, nq);
12697 }
12698 
12699 /*
12700  * Come up with reasonable defaults for some of the tunables, provided they're
12701  * not set by the user (in which case we'll use the values as is).
12702  */
12703 static void
12704 tweak_tunables(void)
12705 {
12706 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12707 
12708 	if (t4_ntxq < 1) {
12709 #ifdef RSS
12710 		t4_ntxq = rss_getnumbuckets();
12711 #else
12712 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12713 #endif
12714 	}
12715 
12716 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12717 
12718 	if (t4_nrxq < 1) {
12719 #ifdef RSS
12720 		t4_nrxq = rss_getnumbuckets();
12721 #else
12722 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12723 #endif
12724 	}
12725 
12726 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12727 
12728 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12729 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12730 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12731 #endif
12732 #ifdef TCP_OFFLOAD
12733 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12734 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12735 #endif
12736 
12737 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12738 	if (t4_toecaps_allowed == -1)
12739 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12740 #else
12741 	if (t4_toecaps_allowed == -1)
12742 		t4_toecaps_allowed = 0;
12743 #endif
12744 
12745 #ifdef TCP_OFFLOAD
12746 	if (t4_rdmacaps_allowed == -1) {
12747 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12748 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12749 	}
12750 
12751 	if (t4_iscsicaps_allowed == -1) {
12752 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12753 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12754 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12755 	}
12756 
12757 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12758 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12759 
12760 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12761 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12762 #else
12763 	if (t4_rdmacaps_allowed == -1)
12764 		t4_rdmacaps_allowed = 0;
12765 
12766 	if (t4_iscsicaps_allowed == -1)
12767 		t4_iscsicaps_allowed = 0;
12768 #endif
12769 
12770 #ifdef DEV_NETMAP
12771 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12772 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12773 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12774 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12775 #endif
12776 
12777 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12778 		t4_tmr_idx = TMR_IDX;
12779 
12780 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12781 		t4_pktc_idx = PKTC_IDX;
12782 
12783 	if (t4_qsize_txq < 128)
12784 		t4_qsize_txq = 128;
12785 
12786 	if (t4_qsize_rxq < 128)
12787 		t4_qsize_rxq = 128;
12788 	while (t4_qsize_rxq & 7)
12789 		t4_qsize_rxq++;
12790 
12791 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12792 
12793 	/*
12794 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12795 	 * VI for the port.  The rest are additional virtual interfaces on the
12796 	 * same physical port.  Note that the main VI does not have native
12797 	 * netmap support but the extra VIs do.
12798 	 *
12799 	 * Limit the number of VIs per port to the number of available
12800 	 * MAC addresses per port.
12801 	 */
12802 	if (t4_num_vis < 1)
12803 		t4_num_vis = 1;
12804 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12805 		t4_num_vis = nitems(vi_mac_funcs);
12806 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12807 	}
12808 
12809 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12810 		pcie_relaxed_ordering = 1;
12811 #if defined(__i386__) || defined(__amd64__)
12812 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12813 			pcie_relaxed_ordering = 0;
12814 #endif
12815 	}
12816 }
12817 
12818 #ifdef DDB
12819 static void
12820 t4_dump_tcb(struct adapter *sc, int tid)
12821 {
12822 	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
12823 
12824 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12825 	save = t4_read_reg(sc, reg);
12826 	base = sc->memwin[2].mw_base;
12827 
12828 	/* Dump TCB for the tid */
12829 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12830 	tcb_addr += tid * TCB_SIZE;
12831 
12832 	if (is_t4(sc)) {
12833 		pf = 0;
12834 		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
12835 	} else {
12836 		pf = V_PFNUM(sc->pf);
12837 		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
12838 	}
12839 	t4_write_reg(sc, reg, win_pos | pf);
12840 	t4_read_reg(sc, reg);
12841 
12842 	off = tcb_addr - win_pos;
12843 	for (i = 0; i < 4; i++) {
12844 		uint32_t buf[8];
12845 		for (j = 0; j < 8; j++, off += 4)
12846 			buf[j] = htonl(t4_read_reg(sc, base + off));
12847 
12848 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12849 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12850 		    buf[7]);
12851 	}
12852 
12853 	t4_write_reg(sc, reg, save);
12854 	t4_read_reg(sc, reg);
12855 }
12856 
12857 static void
12858 t4_dump_devlog(struct adapter *sc)
12859 {
12860 	struct devlog_params *dparams = &sc->params.devlog;
12861 	struct fw_devlog_e e;
12862 	int i, first, j, m, nentries, rc;
12863 	uint64_t ftstamp = UINT64_MAX;
12864 
12865 	if (dparams->start == 0) {
12866 		db_printf("devlog params not valid\n");
12867 		return;
12868 	}
12869 
12870 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12871 	m = fwmtype_to_hwmtype(dparams->memtype);
12872 
12873 	/* Find the first entry. */
12874 	first = -1;
12875 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12876 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12877 		    sizeof(e), (void *)&e);
12878 		if (rc != 0)
12879 			break;
12880 
12881 		if (e.timestamp == 0)
12882 			break;
12883 
12884 		e.timestamp = be64toh(e.timestamp);
12885 		if (e.timestamp < ftstamp) {
12886 			ftstamp = e.timestamp;
12887 			first = i;
12888 		}
12889 	}
12890 
12891 	if (first == -1)
12892 		return;
12893 
12894 	i = first;
12895 	do {
12896 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12897 		    sizeof(e), (void *)&e);
12898 		if (rc != 0)
12899 			return;
12900 
12901 		if (e.timestamp == 0)
12902 			return;
12903 
12904 		e.timestamp = be64toh(e.timestamp);
12905 		e.seqno = be32toh(e.seqno);
12906 		for (j = 0; j < 8; j++)
12907 			e.params[j] = be32toh(e.params[j]);
12908 
12909 		db_printf("%10d  %15ju  %8s  %8s  ",
12910 		    e.seqno, e.timestamp,
12911 		    (e.level < nitems(devlog_level_strings) ?
12912 			devlog_level_strings[e.level] : "UNKNOWN"),
12913 		    (e.facility < nitems(devlog_facility_strings) ?
12914 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12915 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12916 		    e.params[3], e.params[4], e.params[5], e.params[6],
12917 		    e.params[7]);
12918 
12919 		if (++i == nentries)
12920 			i = 0;
12921 	} while (i != first && !db_pager_quit);
12922 }
12923 
12924 static struct db_command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
12925 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
12926 
12927 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
12928 {
12929 	device_t dev;
12930 	int t;
12931 	bool valid;
12932 
12933 	valid = false;
12934 	t = db_read_token();
12935 	if (t == tIDENT) {
12936 		dev = device_lookup_by_name(db_tok_string);
12937 		valid = true;
12938 	}
12939 	db_skip_to_eol();
12940 	if (!valid) {
12941 		db_printf("usage: show t4 devlog <nexus>\n");
12942 		return;
12943 	}
12944 
12945 	if (dev == NULL) {
12946 		db_printf("device not found\n");
12947 		return;
12948 	}
12949 
12950 	t4_dump_devlog(device_get_softc(dev));
12951 }
12952 
12953 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
12954 {
12955 	device_t dev;
12956 	int radix, tid, t;
12957 	bool valid;
12958 
12959 	valid = false;
12960 	radix = db_radix;
12961 	db_radix = 10;
12962 	t = db_read_token();
12963 	if (t == tIDENT) {
12964 		dev = device_lookup_by_name(db_tok_string);
12965 		t = db_read_token();
12966 		if (t == tNUMBER) {
12967 			tid = db_tok_number;
12968 			valid = true;
12969 		}
12970 	}
12971 	db_radix = radix;
12972 	db_skip_to_eol();
12973 	if (!valid) {
12974 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
12975 		return;
12976 	}
12977 
12978 	if (dev == NULL) {
12979 		db_printf("device not found\n");
12980 		return;
12981 	}
12982 	if (tid < 0) {
12983 		db_printf("invalid tid\n");
12984 		return;
12985 	}
12986 
12987 	t4_dump_tcb(device_get_softc(dev), tid);
12988 }
12989 #endif
12990 
12991 static eventhandler_tag vxlan_start_evtag;
12992 static eventhandler_tag vxlan_stop_evtag;
12993 
12994 struct vxlan_evargs {
12995 	if_t ifp;
12996 	uint16_t port;
12997 };
12998 
12999 static void
13000 enable_vxlan_rx(struct adapter *sc)
13001 {
13002 	int i, rc;
13003 	struct port_info *pi;
13004 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
13005 
13006 	ASSERT_SYNCHRONIZED_OP(sc);
13007 
13008 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
13009 	    F_VXLAN_EN);
13010 	for_each_port(sc, i) {
13011 		pi = sc->port[i];
13012 		if (pi->vxlan_tcam_entry == true)
13013 			continue;
13014 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
13015 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
13016 		    true);
13017 		if (rc < 0) {
13018 			rc = -rc;
13019 			CH_ERR(&pi->vi[0],
13020 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
13021 		} else {
13022 			MPASS(rc == sc->rawf_base + pi->port_id);
13023 			pi->vxlan_tcam_entry = true;
13024 		}
13025 	}
13026 }
13027 
13028 static void
13029 t4_vxlan_start(struct adapter *sc, void *arg)
13030 {
13031 	struct vxlan_evargs *v = arg;
13032 
13033 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13034 		return;
13035 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
13036 		return;
13037 
13038 	if (sc->vxlan_refcount == 0) {
13039 		sc->vxlan_port = v->port;
13040 		sc->vxlan_refcount = 1;
13041 		if (!hw_off_limits(sc))
13042 			enable_vxlan_rx(sc);
13043 	} else if (sc->vxlan_port == v->port) {
13044 		sc->vxlan_refcount++;
13045 	} else {
13046 		CH_ERR(sc, "VXLAN already configured on port  %d; "
13047 		    "ignoring attempt to configure it on port %d\n",
13048 		    sc->vxlan_port, v->port);
13049 	}
13050 	end_synchronized_op(sc, 0);
13051 }
13052 
13053 static void
13054 t4_vxlan_stop(struct adapter *sc, void *arg)
13055 {
13056 	struct vxlan_evargs *v = arg;
13057 
13058 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13059 		return;
13060 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
13061 		return;
13062 
13063 	/*
13064 	 * VXLANs may have been configured before the driver was loaded so we
13065 	 * may see more stops than starts.  This is not handled cleanly but at
13066 	 * least we keep the refcount sane.
13067 	 */
13068 	if (sc->vxlan_port != v->port)
13069 		goto done;
13070 	if (sc->vxlan_refcount == 0) {
13071 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
13072 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
13073 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
13074 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
13075 done:
13076 	end_synchronized_op(sc, 0);
13077 }
13078 
13079 static void
13080 t4_vxlan_start_handler(void *arg __unused, if_t ifp,
13081     sa_family_t family, u_int port)
13082 {
13083 	struct vxlan_evargs v;
13084 
13085 	MPASS(family == AF_INET || family == AF_INET6);
13086 	v.ifp = ifp;
13087 	v.port = port;
13088 
13089 	t4_iterate(t4_vxlan_start, &v);
13090 }
13091 
13092 static void
13093 t4_vxlan_stop_handler(void *arg __unused, if_t ifp, sa_family_t family,
13094     u_int port)
13095 {
13096 	struct vxlan_evargs v;
13097 
13098 	MPASS(family == AF_INET || family == AF_INET6);
13099 	v.ifp = ifp;
13100 	v.port = port;
13101 
13102 	t4_iterate(t4_vxlan_stop, &v);
13103 }
13104 
13105 
13106 static struct sx mlu;	/* mod load unload */
13107 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
13108 
13109 static int
13110 mod_event(module_t mod, int cmd, void *arg)
13111 {
13112 	int rc = 0;
13113 	static int loaded = 0;
13114 
13115 	switch (cmd) {
13116 	case MOD_LOAD:
13117 		sx_xlock(&mlu);
13118 		if (loaded++ == 0) {
13119 			t4_sge_modload();
13120 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13121 			    t4_filter_rpl, CPL_COOKIE_FILTER);
13122 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
13123 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
13124 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
13125 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
13126 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13127 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
13128 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
13129 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
13130 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
13131 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
13132 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
13133 			    do_smt_write_rpl);
13134 			sx_init(&t4_list_lock, "T4/T5 adapters");
13135 			SLIST_INIT(&t4_list);
13136 			callout_init(&fatal_callout, 1);
13137 #ifdef TCP_OFFLOAD
13138 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
13139 			SLIST_INIT(&t4_uld_list);
13140 #endif
13141 #ifdef INET6
13142 			t4_clip_modload();
13143 #endif
13144 #ifdef KERN_TLS
13145 			t6_ktls_modload();
13146 #endif
13147 			t4_tracer_modload();
13148 			tweak_tunables();
13149 			vxlan_start_evtag =
13150 			    EVENTHANDLER_REGISTER(vxlan_start,
13151 				t4_vxlan_start_handler, NULL,
13152 				EVENTHANDLER_PRI_ANY);
13153 			vxlan_stop_evtag =
13154 			    EVENTHANDLER_REGISTER(vxlan_stop,
13155 				t4_vxlan_stop_handler, NULL,
13156 				EVENTHANDLER_PRI_ANY);
13157 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
13158 			    taskqueue_thread_enqueue, &reset_tq);
13159 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
13160 			    "t4_rst_thr");
13161 		}
13162 		sx_xunlock(&mlu);
13163 		break;
13164 
13165 	case MOD_UNLOAD:
13166 		sx_xlock(&mlu);
13167 		if (--loaded == 0) {
13168 			int tries;
13169 
13170 			taskqueue_free(reset_tq);
13171 			sx_slock(&t4_list_lock);
13172 			if (!SLIST_EMPTY(&t4_list)) {
13173 				rc = EBUSY;
13174 				sx_sunlock(&t4_list_lock);
13175 				goto done_unload;
13176 			}
13177 #ifdef TCP_OFFLOAD
13178 			sx_slock(&t4_uld_list_lock);
13179 			if (!SLIST_EMPTY(&t4_uld_list)) {
13180 				rc = EBUSY;
13181 				sx_sunlock(&t4_uld_list_lock);
13182 				sx_sunlock(&t4_list_lock);
13183 				goto done_unload;
13184 			}
13185 #endif
13186 			tries = 0;
13187 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13188 				uprintf("%ju clusters with custom free routine "
13189 				    "still is use.\n", t4_sge_extfree_refs());
13190 				pause("t4unload", 2 * hz);
13191 			}
13192 #ifdef TCP_OFFLOAD
13193 			sx_sunlock(&t4_uld_list_lock);
13194 #endif
13195 			sx_sunlock(&t4_list_lock);
13196 
13197 			if (t4_sge_extfree_refs() == 0) {
13198 				EVENTHANDLER_DEREGISTER(vxlan_start,
13199 				    vxlan_start_evtag);
13200 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13201 				    vxlan_stop_evtag);
13202 				t4_tracer_modunload();
13203 #ifdef KERN_TLS
13204 				t6_ktls_modunload();
13205 #endif
13206 #ifdef INET6
13207 				t4_clip_modunload();
13208 #endif
13209 #ifdef TCP_OFFLOAD
13210 				sx_destroy(&t4_uld_list_lock);
13211 #endif
13212 				sx_destroy(&t4_list_lock);
13213 				t4_sge_modunload();
13214 				loaded = 0;
13215 			} else {
13216 				rc = EBUSY;
13217 				loaded++;	/* undo earlier decrement */
13218 			}
13219 		}
13220 done_unload:
13221 		sx_xunlock(&mlu);
13222 		break;
13223 	}
13224 
13225 	return (rc);
13226 }
13227 
13228 DRIVER_MODULE(t4nex, pci, t4_driver, mod_event, 0);
13229 MODULE_VERSION(t4nex, 1);
13230 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13231 #ifdef DEV_NETMAP
13232 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13233 #endif /* DEV_NETMAP */
13234 
13235 DRIVER_MODULE(t5nex, pci, t5_driver, mod_event, 0);
13236 MODULE_VERSION(t5nex, 1);
13237 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13238 #ifdef DEV_NETMAP
13239 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13240 #endif /* DEV_NETMAP */
13241 
13242 DRIVER_MODULE(t6nex, pci, t6_driver, mod_event, 0);
13243 MODULE_VERSION(t6nex, 1);
13244 MODULE_DEPEND(t6nex, crypto, 1, 1, 1);
13245 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13246 #ifdef DEV_NETMAP
13247 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13248 #endif /* DEV_NETMAP */
13249 
13250 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, 0, 0);
13251 MODULE_VERSION(cxgbe, 1);
13252 
13253 DRIVER_MODULE(cxl, t5nex, cxl_driver, 0, 0);
13254 MODULE_VERSION(cxl, 1);
13255 
13256 DRIVER_MODULE(cc, t6nex, cc_driver, 0, 0);
13257 MODULE_VERSION(cc, 1);
13258 
13259 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, 0, 0);
13260 MODULE_VERSION(vcxgbe, 1);
13261 
13262 DRIVER_MODULE(vcxl, cxl, vcxl_driver, 0, 0);
13263 MODULE_VERSION(vcxl, 1);
13264 
13265 DRIVER_MODULE(vcc, cc, vcc_driver, 0, 0);
13266 MODULE_VERSION(vcc, 1);
13267