xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision d7d962ead0b6e5e8a39202d0590022082bf5bfb6)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 Chelsio Communications, Inc.
5  * All rights reserved.
6  * Written by: Navdeep Parhar <np@FreeBSD.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include "opt_ddb.h"
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_kern_tls.h"
37 #include "opt_ratelimit.h"
38 #include "opt_rss.h"
39 
40 #include <sys/param.h>
41 #include <sys/conf.h>
42 #include <sys/priv.h>
43 #include <sys/kernel.h>
44 #include <sys/bus.h>
45 #include <sys/eventhandler.h>
46 #include <sys/module.h>
47 #include <sys/malloc.h>
48 #include <sys/queue.h>
49 #include <sys/taskqueue.h>
50 #include <sys/pciio.h>
51 #include <dev/pci/pcireg.h>
52 #include <dev/pci/pcivar.h>
53 #include <dev/pci/pci_private.h>
54 #include <sys/firmware.h>
55 #include <sys/sbuf.h>
56 #include <sys/smp.h>
57 #include <sys/socket.h>
58 #include <sys/sockio.h>
59 #include <sys/sysctl.h>
60 #include <net/ethernet.h>
61 #include <net/if.h>
62 #include <net/if_types.h>
63 #include <net/if_dl.h>
64 #include <net/if_vlan_var.h>
65 #ifdef RSS
66 #include <net/rss_config.h>
67 #endif
68 #include <netinet/in.h>
69 #include <netinet/ip.h>
70 #ifdef KERN_TLS
71 #include <netinet/tcp_seq.h>
72 #endif
73 #if defined(__i386__) || defined(__amd64__)
74 #include <machine/md_var.h>
75 #include <machine/cputypes.h>
76 #include <vm/vm.h>
77 #include <vm/pmap.h>
78 #endif
79 #ifdef DDB
80 #include <ddb/ddb.h>
81 #include <ddb/db_lex.h>
82 #endif
83 
84 #include "common/common.h"
85 #include "common/t4_msg.h"
86 #include "common/t4_regs.h"
87 #include "common/t4_regs_values.h"
88 #include "cudbg/cudbg.h"
89 #include "t4_clip.h"
90 #include "t4_ioctl.h"
91 #include "t4_l2t.h"
92 #include "t4_mp_ring.h"
93 #include "t4_if.h"
94 #include "t4_smt.h"
95 
96 /* T4 bus driver interface */
97 static int t4_probe(device_t);
98 static int t4_attach(device_t);
99 static int t4_detach(device_t);
100 static int t4_child_location(device_t, device_t, struct sbuf *);
101 static int t4_ready(device_t);
102 static int t4_read_port_device(device_t, int, device_t *);
103 static int t4_suspend(device_t);
104 static int t4_resume(device_t);
105 static int t4_reset_prepare(device_t, device_t);
106 static int t4_reset_post(device_t, device_t);
107 static device_method_t t4_methods[] = {
108 	DEVMETHOD(device_probe,		t4_probe),
109 	DEVMETHOD(device_attach,	t4_attach),
110 	DEVMETHOD(device_detach,	t4_detach),
111 	DEVMETHOD(device_suspend,	t4_suspend),
112 	DEVMETHOD(device_resume,	t4_resume),
113 
114 	DEVMETHOD(bus_child_location,	t4_child_location),
115 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
116 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
117 
118 	DEVMETHOD(t4_is_main_ready,	t4_ready),
119 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
120 
121 	DEVMETHOD_END
122 };
123 static driver_t t4_driver = {
124 	"t4nex",
125 	t4_methods,
126 	sizeof(struct adapter)
127 };
128 
129 
130 /* T4 port (cxgbe) interface */
131 static int cxgbe_probe(device_t);
132 static int cxgbe_attach(device_t);
133 static int cxgbe_detach(device_t);
134 device_method_t cxgbe_methods[] = {
135 	DEVMETHOD(device_probe,		cxgbe_probe),
136 	DEVMETHOD(device_attach,	cxgbe_attach),
137 	DEVMETHOD(device_detach,	cxgbe_detach),
138 	{ 0, 0 }
139 };
140 static driver_t cxgbe_driver = {
141 	"cxgbe",
142 	cxgbe_methods,
143 	sizeof(struct port_info)
144 };
145 
146 /* T4 VI (vcxgbe) interface */
147 static int vcxgbe_probe(device_t);
148 static int vcxgbe_attach(device_t);
149 static int vcxgbe_detach(device_t);
150 static device_method_t vcxgbe_methods[] = {
151 	DEVMETHOD(device_probe,		vcxgbe_probe),
152 	DEVMETHOD(device_attach,	vcxgbe_attach),
153 	DEVMETHOD(device_detach,	vcxgbe_detach),
154 	{ 0, 0 }
155 };
156 static driver_t vcxgbe_driver = {
157 	"vcxgbe",
158 	vcxgbe_methods,
159 	sizeof(struct vi_info)
160 };
161 
162 static d_ioctl_t t4_ioctl;
163 
164 static struct cdevsw t4_cdevsw = {
165        .d_version = D_VERSION,
166        .d_ioctl = t4_ioctl,
167        .d_name = "t4nex",
168 };
169 
170 /* T5 bus driver interface */
171 static int t5_probe(device_t);
172 static device_method_t t5_methods[] = {
173 	DEVMETHOD(device_probe,		t5_probe),
174 	DEVMETHOD(device_attach,	t4_attach),
175 	DEVMETHOD(device_detach,	t4_detach),
176 	DEVMETHOD(device_suspend,	t4_suspend),
177 	DEVMETHOD(device_resume,	t4_resume),
178 
179 	DEVMETHOD(bus_child_location,	t4_child_location),
180 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
181 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
182 
183 	DEVMETHOD(t4_is_main_ready,	t4_ready),
184 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
185 
186 	DEVMETHOD_END
187 };
188 static driver_t t5_driver = {
189 	"t5nex",
190 	t5_methods,
191 	sizeof(struct adapter)
192 };
193 
194 
195 /* T5 port (cxl) interface */
196 static driver_t cxl_driver = {
197 	"cxl",
198 	cxgbe_methods,
199 	sizeof(struct port_info)
200 };
201 
202 /* T5 VI (vcxl) interface */
203 static driver_t vcxl_driver = {
204 	"vcxl",
205 	vcxgbe_methods,
206 	sizeof(struct vi_info)
207 };
208 
209 /* T6 bus driver interface */
210 static int t6_probe(device_t);
211 static device_method_t t6_methods[] = {
212 	DEVMETHOD(device_probe,		t6_probe),
213 	DEVMETHOD(device_attach,	t4_attach),
214 	DEVMETHOD(device_detach,	t4_detach),
215 	DEVMETHOD(device_suspend,	t4_suspend),
216 	DEVMETHOD(device_resume,	t4_resume),
217 
218 	DEVMETHOD(bus_child_location,	t4_child_location),
219 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
220 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
221 
222 	DEVMETHOD(t4_is_main_ready,	t4_ready),
223 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
224 
225 	DEVMETHOD_END
226 };
227 static driver_t t6_driver = {
228 	"t6nex",
229 	t6_methods,
230 	sizeof(struct adapter)
231 };
232 
233 
234 /* T6 port (cc) interface */
235 static driver_t cc_driver = {
236 	"cc",
237 	cxgbe_methods,
238 	sizeof(struct port_info)
239 };
240 
241 /* T6 VI (vcc) interface */
242 static driver_t vcc_driver = {
243 	"vcc",
244 	vcxgbe_methods,
245 	sizeof(struct vi_info)
246 };
247 
248 /* ifnet interface */
249 static void cxgbe_init(void *);
250 static int cxgbe_ioctl(struct ifnet *, unsigned long, caddr_t);
251 static int cxgbe_transmit(struct ifnet *, struct mbuf *);
252 static void cxgbe_qflush(struct ifnet *);
253 #if defined(KERN_TLS) || defined(RATELIMIT)
254 static int cxgbe_snd_tag_alloc(struct ifnet *, union if_snd_tag_alloc_params *,
255     struct m_snd_tag **);
256 static int cxgbe_snd_tag_modify(struct m_snd_tag *,
257     union if_snd_tag_modify_params *);
258 static int cxgbe_snd_tag_query(struct m_snd_tag *,
259     union if_snd_tag_query_params *);
260 static void cxgbe_snd_tag_free(struct m_snd_tag *);
261 #endif
262 
263 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
264 
265 /*
266  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
267  * then ADAPTER_LOCK, then t4_uld_list_lock.
268  */
269 static struct sx t4_list_lock;
270 SLIST_HEAD(, adapter) t4_list;
271 #ifdef TCP_OFFLOAD
272 static struct sx t4_uld_list_lock;
273 SLIST_HEAD(, uld_info) t4_uld_list;
274 #endif
275 
276 /*
277  * Tunables.  See tweak_tunables() too.
278  *
279  * Each tunable is set to a default value here if it's known at compile-time.
280  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
281  * provide a reasonable default (upto n) when the driver is loaded.
282  *
283  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
284  * T5 are under hw.cxl.
285  */
286 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
287     "cxgbe(4) parameters");
288 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
289     "cxgbe(4) T5+ parameters");
290 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
291     "cxgbe(4) TOE parameters");
292 
293 /*
294  * Number of queues for tx and rx, NIC and offload.
295  */
296 #define NTXQ 16
297 int t4_ntxq = -NTXQ;
298 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
299     "Number of TX queues per port");
300 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);	/* Old name, undocumented */
301 
302 #define NRXQ 8
303 int t4_nrxq = -NRXQ;
304 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
305     "Number of RX queues per port");
306 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);	/* Old name, undocumented */
307 
308 #define NTXQ_VI 1
309 static int t4_ntxq_vi = -NTXQ_VI;
310 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
311     "Number of TX queues per VI");
312 
313 #define NRXQ_VI 1
314 static int t4_nrxq_vi = -NRXQ_VI;
315 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
316     "Number of RX queues per VI");
317 
318 static int t4_rsrv_noflowq = 0;
319 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
320     0, "Reserve TX queue 0 of each VI for non-flowid packets");
321 
322 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
323 #define NOFLDTXQ 8
324 static int t4_nofldtxq = -NOFLDTXQ;
325 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
326     "Number of offload TX queues per port");
327 
328 #define NOFLDRXQ 2
329 static int t4_nofldrxq = -NOFLDRXQ;
330 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
331     "Number of offload RX queues per port");
332 
333 #define NOFLDTXQ_VI 1
334 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
335 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
336     "Number of offload TX queues per VI");
337 
338 #define NOFLDRXQ_VI 1
339 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
340 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
341     "Number of offload RX queues per VI");
342 
343 #define TMR_IDX_OFLD 1
344 int t4_tmr_idx_ofld = TMR_IDX_OFLD;
345 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
346     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
347 
348 #define PKTC_IDX_OFLD (-1)
349 int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
350 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
351     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
352 
353 /* 0 means chip/fw default, non-zero number is value in microseconds */
354 static u_long t4_toe_keepalive_idle = 0;
355 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
356     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
357 
358 /* 0 means chip/fw default, non-zero number is value in microseconds */
359 static u_long t4_toe_keepalive_interval = 0;
360 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
361     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
362 
363 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
364 static int t4_toe_keepalive_count = 0;
365 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
366     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
367 
368 /* 0 means chip/fw default, non-zero number is value in microseconds */
369 static u_long t4_toe_rexmt_min = 0;
370 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
371     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
372 
373 /* 0 means chip/fw default, non-zero number is value in microseconds */
374 static u_long t4_toe_rexmt_max = 0;
375 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
376     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
377 
378 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
379 static int t4_toe_rexmt_count = 0;
380 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
381     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
382 
383 /* -1 means chip/fw default, other values are raw backoff values to use */
384 static int t4_toe_rexmt_backoff[16] = {
385 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
386 };
387 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
388     CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
389     "cxgbe(4) TOE retransmit backoff values");
390 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
391     &t4_toe_rexmt_backoff[0], 0, "");
392 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
393     &t4_toe_rexmt_backoff[1], 0, "");
394 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
395     &t4_toe_rexmt_backoff[2], 0, "");
396 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
397     &t4_toe_rexmt_backoff[3], 0, "");
398 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
399     &t4_toe_rexmt_backoff[4], 0, "");
400 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
401     &t4_toe_rexmt_backoff[5], 0, "");
402 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
403     &t4_toe_rexmt_backoff[6], 0, "");
404 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
405     &t4_toe_rexmt_backoff[7], 0, "");
406 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
407     &t4_toe_rexmt_backoff[8], 0, "");
408 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
409     &t4_toe_rexmt_backoff[9], 0, "");
410 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
411     &t4_toe_rexmt_backoff[10], 0, "");
412 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
413     &t4_toe_rexmt_backoff[11], 0, "");
414 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
415     &t4_toe_rexmt_backoff[12], 0, "");
416 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
417     &t4_toe_rexmt_backoff[13], 0, "");
418 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
419     &t4_toe_rexmt_backoff[14], 0, "");
420 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
421     &t4_toe_rexmt_backoff[15], 0, "");
422 
423 static int t4_toe_tls_rx_timeout = 5;
424 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, tls_rx_timeout, CTLFLAG_RDTUN,
425     &t4_toe_tls_rx_timeout, 0,
426     "Timeout in seconds to downgrade TLS sockets to plain TOE");
427 #endif
428 
429 #ifdef DEV_NETMAP
430 #define NN_MAIN_VI	(1 << 0)	/* Native netmap on the main VI */
431 #define NN_EXTRA_VI	(1 << 1)	/* Native netmap on the extra VI(s) */
432 static int t4_native_netmap = NN_EXTRA_VI;
433 SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
434     0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
435 
436 #define NNMTXQ 8
437 static int t4_nnmtxq = -NNMTXQ;
438 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
439     "Number of netmap TX queues");
440 
441 #define NNMRXQ 8
442 static int t4_nnmrxq = -NNMRXQ;
443 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
444     "Number of netmap RX queues");
445 
446 #define NNMTXQ_VI 2
447 static int t4_nnmtxq_vi = -NNMTXQ_VI;
448 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
449     "Number of netmap TX queues per VI");
450 
451 #define NNMRXQ_VI 2
452 static int t4_nnmrxq_vi = -NNMRXQ_VI;
453 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
454     "Number of netmap RX queues per VI");
455 #endif
456 
457 /*
458  * Holdoff parameters for ports.
459  */
460 #define TMR_IDX 1
461 int t4_tmr_idx = TMR_IDX;
462 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
463     0, "Holdoff timer index");
464 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);	/* Old name */
465 
466 #define PKTC_IDX (-1)
467 int t4_pktc_idx = PKTC_IDX;
468 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
469     0, "Holdoff packet counter index");
470 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);	/* Old name */
471 
472 /*
473  * Size (# of entries) of each tx and rx queue.
474  */
475 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
476 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
477     "Number of descriptors in each TX queue");
478 
479 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
480 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
481     "Number of descriptors in each RX queue");
482 
483 /*
484  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
485  */
486 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
487 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
488     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
489 
490 /*
491  * Configuration file.  All the _CF names here are special.
492  */
493 #define DEFAULT_CF	"default"
494 #define BUILTIN_CF	"built-in"
495 #define FLASH_CF	"flash"
496 #define UWIRE_CF	"uwire"
497 #define FPGA_CF		"fpga"
498 static char t4_cfg_file[32] = DEFAULT_CF;
499 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
500     sizeof(t4_cfg_file), "Firmware configuration file");
501 
502 /*
503  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
504  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
505  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
506  *            mark or when signalled to do so, 0 to never emit PAUSE.
507  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
508  *                 negotiated settings will override rx_pause/tx_pause.
509  *                 Otherwise rx_pause/tx_pause are applied forcibly.
510  */
511 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
512 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
513     &t4_pause_settings, 0,
514     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
515 
516 /*
517  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
518  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
519  *  0 to disable FEC.
520  */
521 static int t4_fec = -1;
522 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
523     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
524 
525 /*
526  * Link autonegotiation.
527  * -1 to run with the firmware default.
528  *  0 to disable.
529  *  1 to enable.
530  */
531 static int t4_autoneg = -1;
532 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
533     "Link autonegotiation");
534 
535 /*
536  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
537  * encouraged respectively).  '-n' is the same as 'n' except the firmware
538  * version used in the checks is read from the firmware bundled with the driver.
539  */
540 static int t4_fw_install = 1;
541 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
542     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
543 
544 /*
545  * ASIC features that will be used.  Disable the ones you don't want so that the
546  * chip resources aren't wasted on features that will not be used.
547  */
548 static int t4_nbmcaps_allowed = 0;
549 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
550     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
551 
552 static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
553 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
554     &t4_linkcaps_allowed, 0, "Default link capabilities");
555 
556 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
557     FW_CAPS_CONFIG_SWITCH_EGRESS;
558 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
559     &t4_switchcaps_allowed, 0, "Default switch capabilities");
560 
561 #ifdef RATELIMIT
562 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
563 	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
564 #else
565 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
566 	FW_CAPS_CONFIG_NIC_HASHFILTER;
567 #endif
568 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
569     &t4_niccaps_allowed, 0, "Default NIC capabilities");
570 
571 static int t4_toecaps_allowed = -1;
572 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
573     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
574 
575 static int t4_rdmacaps_allowed = -1;
576 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
577     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
578 
579 static int t4_cryptocaps_allowed = -1;
580 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
581     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
582 
583 static int t4_iscsicaps_allowed = -1;
584 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
585     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
586 
587 static int t4_fcoecaps_allowed = 0;
588 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
589     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
590 
591 static int t5_write_combine = 0;
592 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
593     0, "Use WC instead of UC for BAR2");
594 
595 static int t4_num_vis = 1;
596 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
597     "Number of VIs per port");
598 
599 /*
600  * PCIe Relaxed Ordering.
601  * -1: driver should figure out a good value.
602  * 0: disable RO.
603  * 1: enable RO.
604  * 2: leave RO alone.
605  */
606 static int pcie_relaxed_ordering = -1;
607 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
608     &pcie_relaxed_ordering, 0,
609     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
610 
611 static int t4_panic_on_fatal_err = 0;
612 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
613     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
614 
615 static int t4_reset_on_fatal_err = 0;
616 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
617     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
618 
619 static int t4_tx_vm_wr = 0;
620 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
621     "Use VM work requests to transmit packets.");
622 
623 /*
624  * Set to non-zero to enable the attack filter.  A packet that matches any of
625  * these conditions will get dropped on ingress:
626  * 1) IP && source address == destination address.
627  * 2) TCP/IP && source address is not a unicast address.
628  * 3) TCP/IP && destination address is not a unicast address.
629  * 4) IP && source address is loopback (127.x.y.z).
630  * 5) IP && destination address is loopback (127.x.y.z).
631  * 6) IPv6 && source address == destination address.
632  * 7) IPv6 && source address is not a unicast address.
633  * 8) IPv6 && source address is loopback (::1/128).
634  * 9) IPv6 && destination address is loopback (::1/128).
635  * 10) IPv6 && source address is unspecified (::/128).
636  * 11) IPv6 && destination address is unspecified (::/128).
637  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
638  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
639  */
640 static int t4_attack_filter = 0;
641 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
642     &t4_attack_filter, 0, "Drop suspicious traffic");
643 
644 static int t4_drop_ip_fragments = 0;
645 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
646     &t4_drop_ip_fragments, 0, "Drop IP fragments");
647 
648 static int t4_drop_pkts_with_l2_errors = 1;
649 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
650     &t4_drop_pkts_with_l2_errors, 0,
651     "Drop all frames with Layer 2 length or checksum errors");
652 
653 static int t4_drop_pkts_with_l3_errors = 0;
654 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
655     &t4_drop_pkts_with_l3_errors, 0,
656     "Drop all frames with IP version, length, or checksum errors");
657 
658 static int t4_drop_pkts_with_l4_errors = 0;
659 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
660     &t4_drop_pkts_with_l4_errors, 0,
661     "Drop all frames with Layer 4 length, checksum, or other errors");
662 
663 #ifdef TCP_OFFLOAD
664 /*
665  * TOE tunables.
666  */
667 static int t4_cop_managed_offloading = 0;
668 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
669     &t4_cop_managed_offloading, 0,
670     "COP (Connection Offload Policy) controls all TOE offload");
671 #endif
672 
673 #ifdef KERN_TLS
674 /*
675  * This enables KERN_TLS for all adapters if set.
676  */
677 static int t4_kern_tls = 0;
678 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
679     "Enable KERN_TLS mode for all supported adapters");
680 
681 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
682     "cxgbe(4) KERN_TLS parameters");
683 
684 static int t4_tls_inline_keys = 0;
685 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
686     &t4_tls_inline_keys, 0,
687     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
688     "in card memory.");
689 
690 static int t4_tls_combo_wrs = 0;
691 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
692     0, "Attempt to combine TCB field updates with TLS record work requests.");
693 #endif
694 
695 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
696 static int vi_mac_funcs[] = {
697 	FW_VI_FUNC_ETH,
698 	FW_VI_FUNC_OFLD,
699 	FW_VI_FUNC_IWARP,
700 	FW_VI_FUNC_OPENISCSI,
701 	FW_VI_FUNC_OPENFCOE,
702 	FW_VI_FUNC_FOISCSI,
703 	FW_VI_FUNC_FOFCOE,
704 };
705 
706 struct intrs_and_queues {
707 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
708 	uint16_t num_vis;	/* number of VIs for each port */
709 	uint16_t nirq;		/* Total # of vectors */
710 	uint16_t ntxq;		/* # of NIC txq's for each port */
711 	uint16_t nrxq;		/* # of NIC rxq's for each port */
712 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
713 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
714 	uint16_t nnmtxq;	/* # of netmap txq's */
715 	uint16_t nnmrxq;	/* # of netmap rxq's */
716 
717 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
718 	uint16_t ntxq_vi;	/* # of NIC txq's */
719 	uint16_t nrxq_vi;	/* # of NIC rxq's */
720 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
721 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
722 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
723 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
724 };
725 
726 static void setup_memwin(struct adapter *);
727 static void position_memwin(struct adapter *, int, uint32_t);
728 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
729 static int fwmtype_to_hwmtype(int);
730 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
731     uint32_t *);
732 static int fixup_devlog_params(struct adapter *);
733 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
734 static int contact_firmware(struct adapter *);
735 static int partition_resources(struct adapter *);
736 static int get_params__pre_init(struct adapter *);
737 static int set_params__pre_init(struct adapter *);
738 static int get_params__post_init(struct adapter *);
739 static int set_params__post_init(struct adapter *);
740 static void t4_set_desc(struct adapter *);
741 static bool fixed_ifmedia(struct port_info *);
742 static void build_medialist(struct port_info *);
743 static void init_link_config(struct port_info *);
744 static int fixup_link_config(struct port_info *);
745 static int apply_link_config(struct port_info *);
746 static int cxgbe_init_synchronized(struct vi_info *);
747 static int cxgbe_uninit_synchronized(struct vi_info *);
748 static int adapter_full_init(struct adapter *);
749 static void adapter_full_uninit(struct adapter *);
750 static int vi_full_init(struct vi_info *);
751 static void vi_full_uninit(struct vi_info *);
752 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
753 static void quiesce_txq(struct sge_txq *);
754 static void quiesce_wrq(struct sge_wrq *);
755 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
756 static void quiesce_vi(struct vi_info *);
757 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
758     driver_intr_t *, void *, char *);
759 static int t4_free_irq(struct adapter *, struct irq *);
760 static void t4_init_atid_table(struct adapter *);
761 static void t4_free_atid_table(struct adapter *);
762 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
763 static void vi_refresh_stats(struct vi_info *);
764 static void cxgbe_refresh_stats(struct vi_info *);
765 static void cxgbe_tick(void *);
766 static void vi_tick(void *);
767 static void cxgbe_sysctls(struct port_info *);
768 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
769 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
770 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
771 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
772 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
773 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
774 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
775 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
776 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
777 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
778 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
779 static int sysctl_fec(SYSCTL_HANDLER_ARGS);
780 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
781 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
782 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
783 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
784 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
785 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
786 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
787 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
788 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
789 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
790 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
791 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
792 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
793 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
794 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
795 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
796 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
797 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
798 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
799 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
800 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
801 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
802 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
803 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
804 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
805 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
806 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
807 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
808 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
809 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
810 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
811 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
812 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
813 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
814 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
815 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
816 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
817 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
818 #ifdef TCP_OFFLOAD
819 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
820 static int sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS);
821 static int sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS);
822 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
823 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
824 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
825 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
826 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
827 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
828 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
829 #endif
830 static int get_sge_context(struct adapter *, struct t4_sge_context *);
831 static int load_fw(struct adapter *, struct t4_data *);
832 static int load_cfg(struct adapter *, struct t4_data *);
833 static int load_boot(struct adapter *, struct t4_bootrom *);
834 static int load_bootcfg(struct adapter *, struct t4_data *);
835 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
836 static void free_offload_policy(struct t4_offload_policy *);
837 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
838 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
839 static int read_i2c(struct adapter *, struct t4_i2c_data *);
840 static int clear_stats(struct adapter *, u_int);
841 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
842 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
843 #ifdef TCP_OFFLOAD
844 static int toe_capability(struct vi_info *, bool);
845 static void t4_async_event(void *, int);
846 #endif
847 #ifdef KERN_TLS
848 static int ktls_capability(struct adapter *, bool);
849 #endif
850 static int mod_event(module_t, int, void *);
851 static int notify_siblings(device_t, int);
852 static uint64_t vi_get_counter(struct ifnet *, ift_counter);
853 static uint64_t cxgbe_get_counter(struct ifnet *, ift_counter);
854 static void enable_vxlan_rx(struct adapter *);
855 static void reset_adapter(void *, int);
856 
857 struct {
858 	uint16_t device;
859 	char *desc;
860 } t4_pciids[] = {
861 	{0xa000, "Chelsio Terminator 4 FPGA"},
862 	{0x4400, "Chelsio T440-dbg"},
863 	{0x4401, "Chelsio T420-CR"},
864 	{0x4402, "Chelsio T422-CR"},
865 	{0x4403, "Chelsio T440-CR"},
866 	{0x4404, "Chelsio T420-BCH"},
867 	{0x4405, "Chelsio T440-BCH"},
868 	{0x4406, "Chelsio T440-CH"},
869 	{0x4407, "Chelsio T420-SO"},
870 	{0x4408, "Chelsio T420-CX"},
871 	{0x4409, "Chelsio T420-BT"},
872 	{0x440a, "Chelsio T404-BT"},
873 	{0x440e, "Chelsio T440-LP-CR"},
874 }, t5_pciids[] = {
875 	{0xb000, "Chelsio Terminator 5 FPGA"},
876 	{0x5400, "Chelsio T580-dbg"},
877 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
878 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
879 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
880 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
881 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
882 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
883 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
884 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
885 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
886 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
887 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
888 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
889 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
890 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
891 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
892 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
893 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
894 
895 	/* Custom */
896 	{0x5483, "Custom T540-CR"},
897 	{0x5484, "Custom T540-BT"},
898 }, t6_pciids[] = {
899 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
900 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
901 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
902 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
903 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
904 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
905 	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
906 	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
907 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
908 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
909 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
910 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
911 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
912 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
913 	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
914 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
915 
916 	/* Custom */
917 	{0x6480, "Custom T6225-CR"},
918 	{0x6481, "Custom T62100-CR"},
919 	{0x6482, "Custom T6225-CR"},
920 	{0x6483, "Custom T62100-CR"},
921 	{0x6484, "Custom T64100-CR"},
922 	{0x6485, "Custom T6240-SO"},
923 	{0x6486, "Custom T6225-SO-CR"},
924 	{0x6487, "Custom T6225-CR"},
925 };
926 
927 #ifdef TCP_OFFLOAD
928 /*
929  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
930  * be exactly the same for both rxq and ofld_rxq.
931  */
932 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
933 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
934 #endif
935 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
936 
937 static int
938 t4_probe(device_t dev)
939 {
940 	int i;
941 	uint16_t v = pci_get_vendor(dev);
942 	uint16_t d = pci_get_device(dev);
943 	uint8_t f = pci_get_function(dev);
944 
945 	if (v != PCI_VENDOR_ID_CHELSIO)
946 		return (ENXIO);
947 
948 	/* Attach only to PF0 of the FPGA */
949 	if (d == 0xa000 && f != 0)
950 		return (ENXIO);
951 
952 	for (i = 0; i < nitems(t4_pciids); i++) {
953 		if (d == t4_pciids[i].device) {
954 			device_set_desc(dev, t4_pciids[i].desc);
955 			return (BUS_PROBE_DEFAULT);
956 		}
957 	}
958 
959 	return (ENXIO);
960 }
961 
962 static int
963 t5_probe(device_t dev)
964 {
965 	int i;
966 	uint16_t v = pci_get_vendor(dev);
967 	uint16_t d = pci_get_device(dev);
968 	uint8_t f = pci_get_function(dev);
969 
970 	if (v != PCI_VENDOR_ID_CHELSIO)
971 		return (ENXIO);
972 
973 	/* Attach only to PF0 of the FPGA */
974 	if (d == 0xb000 && f != 0)
975 		return (ENXIO);
976 
977 	for (i = 0; i < nitems(t5_pciids); i++) {
978 		if (d == t5_pciids[i].device) {
979 			device_set_desc(dev, t5_pciids[i].desc);
980 			return (BUS_PROBE_DEFAULT);
981 		}
982 	}
983 
984 	return (ENXIO);
985 }
986 
987 static int
988 t6_probe(device_t dev)
989 {
990 	int i;
991 	uint16_t v = pci_get_vendor(dev);
992 	uint16_t d = pci_get_device(dev);
993 
994 	if (v != PCI_VENDOR_ID_CHELSIO)
995 		return (ENXIO);
996 
997 	for (i = 0; i < nitems(t6_pciids); i++) {
998 		if (d == t6_pciids[i].device) {
999 			device_set_desc(dev, t6_pciids[i].desc);
1000 			return (BUS_PROBE_DEFAULT);
1001 		}
1002 	}
1003 
1004 	return (ENXIO);
1005 }
1006 
1007 static void
1008 t5_attribute_workaround(device_t dev)
1009 {
1010 	device_t root_port;
1011 	uint32_t v;
1012 
1013 	/*
1014 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1015 	 * Ordering attributes when replying to a TLP from a Root
1016 	 * Port.  As a workaround, find the parent Root Port and
1017 	 * disable No Snoop and Relaxed Ordering.  Note that this
1018 	 * affects all devices under this root port.
1019 	 */
1020 	root_port = pci_find_pcie_root_port(dev);
1021 	if (root_port == NULL) {
1022 		device_printf(dev, "Unable to find parent root port\n");
1023 		return;
1024 	}
1025 
1026 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1027 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1028 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1029 	    0)
1030 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1031 		    device_get_nameunit(root_port));
1032 }
1033 
1034 static const struct devnames devnames[] = {
1035 	{
1036 		.nexus_name = "t4nex",
1037 		.ifnet_name = "cxgbe",
1038 		.vi_ifnet_name = "vcxgbe",
1039 		.pf03_drv_name = "t4iov",
1040 		.vf_nexus_name = "t4vf",
1041 		.vf_ifnet_name = "cxgbev"
1042 	}, {
1043 		.nexus_name = "t5nex",
1044 		.ifnet_name = "cxl",
1045 		.vi_ifnet_name = "vcxl",
1046 		.pf03_drv_name = "t5iov",
1047 		.vf_nexus_name = "t5vf",
1048 		.vf_ifnet_name = "cxlv"
1049 	}, {
1050 		.nexus_name = "t6nex",
1051 		.ifnet_name = "cc",
1052 		.vi_ifnet_name = "vcc",
1053 		.pf03_drv_name = "t6iov",
1054 		.vf_nexus_name = "t6vf",
1055 		.vf_ifnet_name = "ccv"
1056 	}
1057 };
1058 
1059 void
1060 t4_init_devnames(struct adapter *sc)
1061 {
1062 	int id;
1063 
1064 	id = chip_id(sc);
1065 	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1066 		sc->names = &devnames[id - CHELSIO_T4];
1067 	else {
1068 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1069 		sc->names = NULL;
1070 	}
1071 }
1072 
1073 static int
1074 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1075 {
1076 	const char *parent, *name;
1077 	long value;
1078 	int line, unit;
1079 
1080 	line = 0;
1081 	parent = device_get_nameunit(sc->dev);
1082 	name = sc->names->ifnet_name;
1083 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1084 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1085 		    value == pi->port_id)
1086 			return (unit);
1087 	}
1088 	return (-1);
1089 }
1090 
1091 static int
1092 t4_attach(device_t dev)
1093 {
1094 	struct adapter *sc;
1095 	int rc = 0, i, j, rqidx, tqidx, nports;
1096 	struct make_dev_args mda;
1097 	struct intrs_and_queues iaq;
1098 	struct sge *s;
1099 	uint32_t *buf;
1100 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1101 	int ofld_tqidx;
1102 #endif
1103 #ifdef TCP_OFFLOAD
1104 	int ofld_rqidx;
1105 #endif
1106 #ifdef DEV_NETMAP
1107 	int nm_rqidx, nm_tqidx;
1108 #endif
1109 	int num_vis;
1110 
1111 	sc = device_get_softc(dev);
1112 	sc->dev = dev;
1113 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1114 
1115 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1116 		t5_attribute_workaround(dev);
1117 	pci_enable_busmaster(dev);
1118 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1119 		uint32_t v;
1120 
1121 		pci_set_max_read_req(dev, 4096);
1122 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1123 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1124 		if (pcie_relaxed_ordering == 0 &&
1125 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1126 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1127 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1128 		} else if (pcie_relaxed_ordering == 1 &&
1129 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1130 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1131 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1132 		}
1133 	}
1134 
1135 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1136 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1137 	sc->traceq = -1;
1138 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1139 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1140 	    device_get_nameunit(dev));
1141 
1142 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1143 	    device_get_nameunit(dev));
1144 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1145 	t4_add_adapter(sc);
1146 
1147 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1148 	TAILQ_INIT(&sc->sfl);
1149 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1150 
1151 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1152 
1153 	sc->policy = NULL;
1154 	rw_init(&sc->policy_lock, "connection offload policy");
1155 
1156 	callout_init(&sc->ktls_tick, 1);
1157 
1158 #ifdef TCP_OFFLOAD
1159 	TASK_INIT(&sc->async_event_task, 0, t4_async_event, sc);
1160 #endif
1161 
1162 	refcount_init(&sc->vxlan_refcount, 0);
1163 
1164 	TASK_INIT(&sc->reset_task, 0, reset_adapter, sc);
1165 
1166 	sc->ctrlq_oid = SYSCTL_ADD_NODE(device_get_sysctl_ctx(sc->dev),
1167 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1168 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1169 	sc->fwq_oid = SYSCTL_ADD_NODE(device_get_sysctl_ctx(sc->dev),
1170 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1171 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1172 
1173 	rc = t4_map_bars_0_and_4(sc);
1174 	if (rc != 0)
1175 		goto done; /* error message displayed already */
1176 
1177 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1178 
1179 	/* Prepare the adapter for operation. */
1180 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1181 	rc = -t4_prep_adapter(sc, buf);
1182 	free(buf, M_CXGBE);
1183 	if (rc != 0) {
1184 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1185 		goto done;
1186 	}
1187 
1188 	/*
1189 	 * This is the real PF# to which we're attaching.  Works from within PCI
1190 	 * passthrough environments too, where pci_get_function() could return a
1191 	 * different PF# depending on the passthrough configuration.  We need to
1192 	 * use the real PF# in all our communication with the firmware.
1193 	 */
1194 	j = t4_read_reg(sc, A_PL_WHOAMI);
1195 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1196 	sc->mbox = sc->pf;
1197 
1198 	t4_init_devnames(sc);
1199 	if (sc->names == NULL) {
1200 		rc = ENOTSUP;
1201 		goto done; /* error message displayed already */
1202 	}
1203 
1204 	/*
1205 	 * Do this really early, with the memory windows set up even before the
1206 	 * character device.  The userland tool's register i/o and mem read
1207 	 * will work even in "recovery mode".
1208 	 */
1209 	setup_memwin(sc);
1210 	if (t4_init_devlog_params(sc, 0) == 0)
1211 		fixup_devlog_params(sc);
1212 	make_dev_args_init(&mda);
1213 	mda.mda_devsw = &t4_cdevsw;
1214 	mda.mda_uid = UID_ROOT;
1215 	mda.mda_gid = GID_WHEEL;
1216 	mda.mda_mode = 0600;
1217 	mda.mda_si_drv1 = sc;
1218 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1219 	if (rc != 0)
1220 		device_printf(dev, "failed to create nexus char device: %d.\n",
1221 		    rc);
1222 
1223 	/* Go no further if recovery mode has been requested. */
1224 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1225 		device_printf(dev, "recovery mode.\n");
1226 		goto done;
1227 	}
1228 
1229 #if defined(__i386__)
1230 	if ((cpu_feature & CPUID_CX8) == 0) {
1231 		device_printf(dev, "64 bit atomics not available.\n");
1232 		rc = ENOTSUP;
1233 		goto done;
1234 	}
1235 #endif
1236 
1237 	/* Contact the firmware and try to become the master driver. */
1238 	rc = contact_firmware(sc);
1239 	if (rc != 0)
1240 		goto done; /* error message displayed already */
1241 	MPASS(sc->flags & FW_OK);
1242 
1243 	rc = get_params__pre_init(sc);
1244 	if (rc != 0)
1245 		goto done; /* error message displayed already */
1246 
1247 	if (sc->flags & MASTER_PF) {
1248 		rc = partition_resources(sc);
1249 		if (rc != 0)
1250 			goto done; /* error message displayed already */
1251 		t4_intr_clear(sc);
1252 	}
1253 
1254 	rc = get_params__post_init(sc);
1255 	if (rc != 0)
1256 		goto done; /* error message displayed already */
1257 
1258 	rc = set_params__post_init(sc);
1259 	if (rc != 0)
1260 		goto done; /* error message displayed already */
1261 
1262 	rc = t4_map_bar_2(sc);
1263 	if (rc != 0)
1264 		goto done; /* error message displayed already */
1265 
1266 	rc = t4_create_dma_tag(sc);
1267 	if (rc != 0)
1268 		goto done; /* error message displayed already */
1269 
1270 	/*
1271 	 * First pass over all the ports - allocate VIs and initialize some
1272 	 * basic parameters like mac address, port type, etc.
1273 	 */
1274 	for_each_port(sc, i) {
1275 		struct port_info *pi;
1276 
1277 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1278 		sc->port[i] = pi;
1279 
1280 		/* These must be set before t4_port_init */
1281 		pi->adapter = sc;
1282 		pi->port_id = i;
1283 		/*
1284 		 * XXX: vi[0] is special so we can't delay this allocation until
1285 		 * pi->nvi's final value is known.
1286 		 */
1287 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1288 		    M_ZERO | M_WAITOK);
1289 
1290 		/*
1291 		 * Allocate the "main" VI and initialize parameters
1292 		 * like mac addr.
1293 		 */
1294 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1295 		if (rc != 0) {
1296 			device_printf(dev, "unable to initialize port %d: %d\n",
1297 			    i, rc);
1298 			free(pi->vi, M_CXGBE);
1299 			free(pi, M_CXGBE);
1300 			sc->port[i] = NULL;
1301 			goto done;
1302 		}
1303 
1304 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1305 		    device_get_nameunit(dev), i);
1306 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1307 		sc->chan_map[pi->tx_chan] = i;
1308 
1309 		/*
1310 		 * The MPS counter for FCS errors doesn't work correctly on the
1311 		 * T6 so we use the MAC counter here.  Which MAC is in use
1312 		 * depends on the link settings which will be known when the
1313 		 * link comes up.
1314 		 */
1315 		if (is_t6(sc)) {
1316 			pi->fcs_reg = -1;
1317 		} else if (is_t4(sc)) {
1318 			pi->fcs_reg = PORT_REG(pi->tx_chan,
1319 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1320 		} else {
1321 			pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
1322 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1323 		}
1324 		pi->fcs_base = 0;
1325 
1326 		/* All VIs on this port share this media. */
1327 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1328 		    cxgbe_media_status);
1329 
1330 		PORT_LOCK(pi);
1331 		init_link_config(pi);
1332 		fixup_link_config(pi);
1333 		build_medialist(pi);
1334 		if (fixed_ifmedia(pi))
1335 			pi->flags |= FIXED_IFMEDIA;
1336 		PORT_UNLOCK(pi);
1337 
1338 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1339 		    t4_ifnet_unit(sc, pi));
1340 		if (pi->dev == NULL) {
1341 			device_printf(dev,
1342 			    "failed to add device for port %d.\n", i);
1343 			rc = ENXIO;
1344 			goto done;
1345 		}
1346 		pi->vi[0].dev = pi->dev;
1347 		device_set_softc(pi->dev, pi);
1348 	}
1349 
1350 	/*
1351 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1352 	 */
1353 	nports = sc->params.nports;
1354 	rc = cfg_itype_and_nqueues(sc, &iaq);
1355 	if (rc != 0)
1356 		goto done; /* error message displayed already */
1357 
1358 	num_vis = iaq.num_vis;
1359 	sc->intr_type = iaq.intr_type;
1360 	sc->intr_count = iaq.nirq;
1361 
1362 	s = &sc->sge;
1363 	s->nrxq = nports * iaq.nrxq;
1364 	s->ntxq = nports * iaq.ntxq;
1365 	if (num_vis > 1) {
1366 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1367 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1368 	}
1369 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1370 	s->neq += nports;		/* ctrl queues: 1 per port */
1371 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1372 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1373 	if (is_offload(sc) || is_ethoffload(sc)) {
1374 		s->nofldtxq = nports * iaq.nofldtxq;
1375 		if (num_vis > 1)
1376 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1377 		s->neq += s->nofldtxq;
1378 
1379 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1380 		    M_CXGBE, M_ZERO | M_WAITOK);
1381 	}
1382 #endif
1383 #ifdef TCP_OFFLOAD
1384 	if (is_offload(sc)) {
1385 		s->nofldrxq = nports * iaq.nofldrxq;
1386 		if (num_vis > 1)
1387 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1388 		s->neq += s->nofldrxq;	/* free list */
1389 		s->niq += s->nofldrxq;
1390 
1391 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1392 		    M_CXGBE, M_ZERO | M_WAITOK);
1393 	}
1394 #endif
1395 #ifdef DEV_NETMAP
1396 	s->nnmrxq = 0;
1397 	s->nnmtxq = 0;
1398 	if (t4_native_netmap & NN_MAIN_VI) {
1399 		s->nnmrxq += nports * iaq.nnmrxq;
1400 		s->nnmtxq += nports * iaq.nnmtxq;
1401 	}
1402 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1403 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1404 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1405 	}
1406 	s->neq += s->nnmtxq + s->nnmrxq;
1407 	s->niq += s->nnmrxq;
1408 
1409 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1410 	    M_CXGBE, M_ZERO | M_WAITOK);
1411 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1412 	    M_CXGBE, M_ZERO | M_WAITOK);
1413 #endif
1414 	MPASS(s->niq <= s->iqmap_sz);
1415 	MPASS(s->neq <= s->eqmap_sz);
1416 
1417 	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1418 	    M_ZERO | M_WAITOK);
1419 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1420 	    M_ZERO | M_WAITOK);
1421 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1422 	    M_ZERO | M_WAITOK);
1423 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1424 	    M_ZERO | M_WAITOK);
1425 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1426 	    M_ZERO | M_WAITOK);
1427 
1428 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1429 	    M_ZERO | M_WAITOK);
1430 
1431 	t4_init_l2t(sc, M_WAITOK);
1432 	t4_init_smt(sc, M_WAITOK);
1433 	t4_init_tx_sched(sc);
1434 	t4_init_atid_table(sc);
1435 #ifdef RATELIMIT
1436 	t4_init_etid_table(sc);
1437 #endif
1438 #ifdef INET6
1439 	t4_init_clip_table(sc);
1440 #endif
1441 	if (sc->vres.key.size != 0)
1442 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1443 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1444 
1445 	/*
1446 	 * Second pass over the ports.  This time we know the number of rx and
1447 	 * tx queues that each port should get.
1448 	 */
1449 	rqidx = tqidx = 0;
1450 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1451 	ofld_tqidx = 0;
1452 #endif
1453 #ifdef TCP_OFFLOAD
1454 	ofld_rqidx = 0;
1455 #endif
1456 #ifdef DEV_NETMAP
1457 	nm_rqidx = nm_tqidx = 0;
1458 #endif
1459 	for_each_port(sc, i) {
1460 		struct port_info *pi = sc->port[i];
1461 		struct vi_info *vi;
1462 
1463 		if (pi == NULL)
1464 			continue;
1465 
1466 		pi->nvi = num_vis;
1467 		for_each_vi(pi, j, vi) {
1468 			vi->pi = pi;
1469 			vi->adapter = sc;
1470 			vi->first_intr = -1;
1471 			vi->qsize_rxq = t4_qsize_rxq;
1472 			vi->qsize_txq = t4_qsize_txq;
1473 
1474 			vi->first_rxq = rqidx;
1475 			vi->first_txq = tqidx;
1476 			vi->tmr_idx = t4_tmr_idx;
1477 			vi->pktc_idx = t4_pktc_idx;
1478 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1479 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1480 
1481 			rqidx += vi->nrxq;
1482 			tqidx += vi->ntxq;
1483 
1484 			if (j == 0 && vi->ntxq > 1)
1485 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1486 			else
1487 				vi->rsrv_noflowq = 0;
1488 
1489 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1490 			vi->first_ofld_txq = ofld_tqidx;
1491 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1492 			ofld_tqidx += vi->nofldtxq;
1493 #endif
1494 #ifdef TCP_OFFLOAD
1495 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1496 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1497 			vi->first_ofld_rxq = ofld_rqidx;
1498 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1499 
1500 			ofld_rqidx += vi->nofldrxq;
1501 #endif
1502 #ifdef DEV_NETMAP
1503 			vi->first_nm_rxq = nm_rqidx;
1504 			vi->first_nm_txq = nm_tqidx;
1505 			if (j == 0) {
1506 				vi->nnmrxq = iaq.nnmrxq;
1507 				vi->nnmtxq = iaq.nnmtxq;
1508 			} else {
1509 				vi->nnmrxq = iaq.nnmrxq_vi;
1510 				vi->nnmtxq = iaq.nnmtxq_vi;
1511 			}
1512 			nm_rqidx += vi->nnmrxq;
1513 			nm_tqidx += vi->nnmtxq;
1514 #endif
1515 		}
1516 	}
1517 
1518 	rc = t4_setup_intr_handlers(sc);
1519 	if (rc != 0) {
1520 		device_printf(dev,
1521 		    "failed to setup interrupt handlers: %d\n", rc);
1522 		goto done;
1523 	}
1524 
1525 	rc = bus_generic_probe(dev);
1526 	if (rc != 0) {
1527 		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1528 		goto done;
1529 	}
1530 
1531 	/*
1532 	 * Ensure thread-safe mailbox access (in debug builds).
1533 	 *
1534 	 * So far this was the only thread accessing the mailbox but various
1535 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1536 	 * will access the mailbox from different threads.
1537 	 */
1538 	sc->flags |= CHK_MBOX_ACCESS;
1539 
1540 	rc = bus_generic_attach(dev);
1541 	if (rc != 0) {
1542 		device_printf(dev,
1543 		    "failed to attach all child ports: %d\n", rc);
1544 		goto done;
1545 	}
1546 
1547 	device_printf(dev,
1548 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1549 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1550 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1551 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1552 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1553 
1554 	t4_set_desc(sc);
1555 
1556 	notify_siblings(dev, 0);
1557 
1558 done:
1559 	if (rc != 0 && sc->cdev) {
1560 		/* cdev was created and so cxgbetool works; recover that way. */
1561 		device_printf(dev,
1562 		    "error during attach, adapter is now in recovery mode.\n");
1563 		rc = 0;
1564 	}
1565 
1566 	if (rc != 0)
1567 		t4_detach_common(dev);
1568 	else
1569 		t4_sysctls(sc);
1570 
1571 	return (rc);
1572 }
1573 
1574 static int
1575 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1576 {
1577 	struct adapter *sc;
1578 	struct port_info *pi;
1579 	int i;
1580 
1581 	sc = device_get_softc(bus);
1582 	for_each_port(sc, i) {
1583 		pi = sc->port[i];
1584 		if (pi != NULL && pi->dev == dev) {
1585 			sbuf_printf(sb, "port=%d", pi->port_id);
1586 			break;
1587 		}
1588 	}
1589 	return (0);
1590 }
1591 
1592 static int
1593 t4_ready(device_t dev)
1594 {
1595 	struct adapter *sc;
1596 
1597 	sc = device_get_softc(dev);
1598 	if (sc->flags & FW_OK)
1599 		return (0);
1600 	return (ENXIO);
1601 }
1602 
1603 static int
1604 t4_read_port_device(device_t dev, int port, device_t *child)
1605 {
1606 	struct adapter *sc;
1607 	struct port_info *pi;
1608 
1609 	sc = device_get_softc(dev);
1610 	if (port < 0 || port >= MAX_NPORTS)
1611 		return (EINVAL);
1612 	pi = sc->port[port];
1613 	if (pi == NULL || pi->dev == NULL)
1614 		return (ENXIO);
1615 	*child = pi->dev;
1616 	return (0);
1617 }
1618 
1619 static int
1620 notify_siblings(device_t dev, int detaching)
1621 {
1622 	device_t sibling;
1623 	int error, i;
1624 
1625 	error = 0;
1626 	for (i = 0; i < PCI_FUNCMAX; i++) {
1627 		if (i == pci_get_function(dev))
1628 			continue;
1629 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1630 		    pci_get_slot(dev), i);
1631 		if (sibling == NULL || !device_is_attached(sibling))
1632 			continue;
1633 		if (detaching)
1634 			error = T4_DETACH_CHILD(sibling);
1635 		else
1636 			(void)T4_ATTACH_CHILD(sibling);
1637 		if (error)
1638 			break;
1639 	}
1640 	return (error);
1641 }
1642 
1643 /*
1644  * Idempotent
1645  */
1646 static int
1647 t4_detach(device_t dev)
1648 {
1649 	struct adapter *sc;
1650 	int rc;
1651 
1652 	sc = device_get_softc(dev);
1653 
1654 	rc = notify_siblings(dev, 1);
1655 	if (rc) {
1656 		device_printf(dev,
1657 		    "failed to detach sibling devices: %d\n", rc);
1658 		return (rc);
1659 	}
1660 
1661 	return (t4_detach_common(dev));
1662 }
1663 
1664 int
1665 t4_detach_common(device_t dev)
1666 {
1667 	struct adapter *sc;
1668 	struct port_info *pi;
1669 	int i, rc;
1670 
1671 	sc = device_get_softc(dev);
1672 
1673 	if (sc->cdev) {
1674 		destroy_dev(sc->cdev);
1675 		sc->cdev = NULL;
1676 	}
1677 
1678 	sx_xlock(&t4_list_lock);
1679 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1680 	sx_xunlock(&t4_list_lock);
1681 
1682 	sc->flags &= ~CHK_MBOX_ACCESS;
1683 	if (sc->flags & FULL_INIT_DONE) {
1684 		if (!(sc->flags & IS_VF))
1685 			t4_intr_disable(sc);
1686 	}
1687 
1688 	if (device_is_attached(dev)) {
1689 		rc = bus_generic_detach(dev);
1690 		if (rc) {
1691 			device_printf(dev,
1692 			    "failed to detach child devices: %d\n", rc);
1693 			return (rc);
1694 		}
1695 	}
1696 
1697 #ifdef TCP_OFFLOAD
1698 	taskqueue_drain(taskqueue_thread, &sc->async_event_task);
1699 #endif
1700 
1701 	for (i = 0; i < sc->intr_count; i++)
1702 		t4_free_irq(sc, &sc->irq[i]);
1703 
1704 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1705 		t4_free_tx_sched(sc);
1706 
1707 	for (i = 0; i < MAX_NPORTS; i++) {
1708 		pi = sc->port[i];
1709 		if (pi) {
1710 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1711 			if (pi->dev)
1712 				device_delete_child(dev, pi->dev);
1713 
1714 			mtx_destroy(&pi->pi_lock);
1715 			free(pi->vi, M_CXGBE);
1716 			free(pi, M_CXGBE);
1717 		}
1718 	}
1719 
1720 	device_delete_children(dev);
1721 	adapter_full_uninit(sc);
1722 
1723 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1724 		t4_fw_bye(sc, sc->mbox);
1725 
1726 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1727 		pci_release_msi(dev);
1728 
1729 	if (sc->regs_res)
1730 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1731 		    sc->regs_res);
1732 
1733 	if (sc->udbs_res)
1734 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1735 		    sc->udbs_res);
1736 
1737 	if (sc->msix_res)
1738 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1739 		    sc->msix_res);
1740 
1741 	if (sc->l2t)
1742 		t4_free_l2t(sc->l2t);
1743 	if (sc->smt)
1744 		t4_free_smt(sc->smt);
1745 	t4_free_atid_table(sc);
1746 #ifdef RATELIMIT
1747 	t4_free_etid_table(sc);
1748 #endif
1749 	if (sc->key_map)
1750 		vmem_destroy(sc->key_map);
1751 #ifdef INET6
1752 	t4_destroy_clip_table(sc);
1753 #endif
1754 
1755 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1756 	free(sc->sge.ofld_txq, M_CXGBE);
1757 #endif
1758 #ifdef TCP_OFFLOAD
1759 	free(sc->sge.ofld_rxq, M_CXGBE);
1760 #endif
1761 #ifdef DEV_NETMAP
1762 	free(sc->sge.nm_rxq, M_CXGBE);
1763 	free(sc->sge.nm_txq, M_CXGBE);
1764 #endif
1765 	free(sc->irq, M_CXGBE);
1766 	free(sc->sge.rxq, M_CXGBE);
1767 	free(sc->sge.txq, M_CXGBE);
1768 	free(sc->sge.ctrlq, M_CXGBE);
1769 	free(sc->sge.iqmap, M_CXGBE);
1770 	free(sc->sge.eqmap, M_CXGBE);
1771 	free(sc->tids.ftid_tab, M_CXGBE);
1772 	free(sc->tids.hpftid_tab, M_CXGBE);
1773 	free_hftid_hash(&sc->tids);
1774 	free(sc->tids.tid_tab, M_CXGBE);
1775 	free(sc->tt.tls_rx_ports, M_CXGBE);
1776 	t4_destroy_dma_tag(sc);
1777 
1778 	callout_drain(&sc->ktls_tick);
1779 	callout_drain(&sc->sfl_callout);
1780 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1781 		mtx_destroy(&sc->tids.ftid_lock);
1782 		cv_destroy(&sc->tids.ftid_cv);
1783 	}
1784 	if (mtx_initialized(&sc->tids.atid_lock))
1785 		mtx_destroy(&sc->tids.atid_lock);
1786 	if (mtx_initialized(&sc->ifp_lock))
1787 		mtx_destroy(&sc->ifp_lock);
1788 
1789 	if (rw_initialized(&sc->policy_lock)) {
1790 		rw_destroy(&sc->policy_lock);
1791 #ifdef TCP_OFFLOAD
1792 		if (sc->policy != NULL)
1793 			free_offload_policy(sc->policy);
1794 #endif
1795 	}
1796 
1797 	for (i = 0; i < NUM_MEMWIN; i++) {
1798 		struct memwin *mw = &sc->memwin[i];
1799 
1800 		if (rw_initialized(&mw->mw_lock))
1801 			rw_destroy(&mw->mw_lock);
1802 	}
1803 
1804 	mtx_destroy(&sc->sfl_lock);
1805 	mtx_destroy(&sc->reg_lock);
1806 	mtx_destroy(&sc->sc_lock);
1807 
1808 	bzero(sc, sizeof(*sc));
1809 
1810 	return (0);
1811 }
1812 
1813 static inline bool
1814 ok_to_reset(struct adapter *sc)
1815 {
1816 	struct tid_info *t = &sc->tids;
1817 	struct port_info *pi;
1818 	struct vi_info *vi;
1819 	int i, j;
1820 	const int caps = IFCAP_TOE | IFCAP_TXTLS | IFCAP_NETMAP | IFCAP_TXRTLMT;
1821 
1822 	ASSERT_SYNCHRONIZED_OP(sc);
1823 	MPASS(!(sc->flags & IS_VF));
1824 
1825 	for_each_port(sc, i) {
1826 		pi = sc->port[i];
1827 		for_each_vi(pi, j, vi) {
1828 			if (vi->ifp->if_capenable & caps)
1829 				return (false);
1830 		}
1831 	}
1832 
1833 	if (atomic_load_int(&t->tids_in_use) > 0)
1834 		return (false);
1835 	if (atomic_load_int(&t->stids_in_use) > 0)
1836 		return (false);
1837 	if (atomic_load_int(&t->atids_in_use) > 0)
1838 		return (false);
1839 	if (atomic_load_int(&t->ftids_in_use) > 0)
1840 		return (false);
1841 	if (atomic_load_int(&t->hpftids_in_use) > 0)
1842 		return (false);
1843 	if (atomic_load_int(&t->etids_in_use) > 0)
1844 		return (false);
1845 
1846 	return (true);
1847 }
1848 
1849 static int
1850 t4_suspend(device_t dev)
1851 {
1852 	struct adapter *sc = device_get_softc(dev);
1853 	struct port_info *pi;
1854 	struct vi_info *vi;
1855 	struct ifnet *ifp;
1856 	struct sge_rxq *rxq;
1857 	struct sge_txq *txq;
1858 	struct sge_wrq *wrq;
1859 #ifdef TCP_OFFLOAD
1860 	struct sge_ofld_rxq *ofld_rxq;
1861 #endif
1862 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1863 	struct sge_ofld_txq *ofld_txq;
1864 #endif
1865 	int rc, i, j, k;
1866 
1867 	CH_ALERT(sc, "suspend requested\n");
1868 
1869 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4sus");
1870 	if (rc != 0)
1871 		return (ENXIO);
1872 
1873 	/* XXX: Can the kernel call suspend repeatedly without resume? */
1874 	MPASS(!hw_off_limits(sc));
1875 
1876 	if (!ok_to_reset(sc)) {
1877 		/* XXX: should list what resource is preventing suspend. */
1878 		CH_ERR(sc, "not safe to suspend.\n");
1879 		rc = EBUSY;
1880 		goto done;
1881 	}
1882 
1883 	/* No more DMA or interrupts. */
1884 	t4_shutdown_adapter(sc);
1885 
1886 	/* Quiesce all activity. */
1887 	for_each_port(sc, i) {
1888 		pi = sc->port[i];
1889 		pi->vxlan_tcam_entry = false;
1890 
1891 		PORT_LOCK(pi);
1892 		if (pi->up_vis > 0) {
1893 			/*
1894 			 * t4_shutdown_adapter has already shut down all the
1895 			 * PHYs but it also disables interrupts and DMA so there
1896 			 * won't be a link interrupt.  So we update the state
1897 			 * manually and inform the kernel.
1898 			 */
1899 			pi->link_cfg.link_ok = false;
1900 			t4_os_link_changed(pi);
1901 		}
1902 		PORT_UNLOCK(pi);
1903 
1904 		for_each_vi(pi, j, vi) {
1905 			vi->xact_addr_filt = -1;
1906 			if (!(vi->flags & VI_INIT_DONE))
1907 				continue;
1908 
1909 			ifp = vi->ifp;
1910 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1911 				mtx_lock(&vi->tick_mtx);
1912 				vi->flags |= VI_SKIP_STATS;
1913 				callout_stop(&vi->tick);
1914 				mtx_unlock(&vi->tick_mtx);
1915 				callout_drain(&vi->tick);
1916 			}
1917 
1918 			/*
1919 			 * Note that the HW is not available.
1920 			 */
1921 			for_each_txq(vi, k, txq) {
1922 				TXQ_LOCK(txq);
1923 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
1924 				TXQ_UNLOCK(txq);
1925 			}
1926 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1927 			for_each_ofld_txq(vi, k, ofld_txq) {
1928 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
1929 			}
1930 #endif
1931 			for_each_rxq(vi, k, rxq) {
1932 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1933 			}
1934 #if defined(TCP_OFFLOAD)
1935 			for_each_ofld_rxq(vi, k, ofld_rxq) {
1936 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1937 			}
1938 #endif
1939 
1940 			quiesce_vi(vi);
1941 		}
1942 
1943 		if (sc->flags & FULL_INIT_DONE) {
1944 			/* Control queue */
1945 			wrq = &sc->sge.ctrlq[i];
1946 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
1947 			quiesce_wrq(wrq);
1948 		}
1949 	}
1950 	if (sc->flags & FULL_INIT_DONE) {
1951 		/* Firmware event queue */
1952 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
1953 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
1954 	}
1955 
1956 	/* Mark the adapter totally off limits. */
1957 	mtx_lock(&sc->reg_lock);
1958 	sc->flags |= HW_OFF_LIMITS;
1959 	sc->flags &= ~(FW_OK | MASTER_PF);
1960 	sc->reset_thread = NULL;
1961 	mtx_unlock(&sc->reg_lock);
1962 
1963 	sc->num_resets++;
1964 	CH_ALERT(sc, "suspend completed.\n");
1965 done:
1966 	end_synchronized_op(sc, 0);
1967 	return (rc);
1968 }
1969 
1970 struct adapter_pre_reset_state {
1971 	u_int flags;
1972 	uint16_t nbmcaps;
1973 	uint16_t linkcaps;
1974 	uint16_t switchcaps;
1975 	uint16_t niccaps;
1976 	uint16_t toecaps;
1977 	uint16_t rdmacaps;
1978 	uint16_t cryptocaps;
1979 	uint16_t iscsicaps;
1980 	uint16_t fcoecaps;
1981 
1982 	u_int cfcsum;
1983 	char cfg_file[32];
1984 
1985 	struct adapter_params params;
1986 	struct t4_virt_res vres;
1987 	struct tid_info tids;
1988 	struct sge sge;
1989 
1990 	int rawf_base;
1991 	int nrawf;
1992 
1993 };
1994 
1995 static void
1996 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
1997 {
1998 
1999 	ASSERT_SYNCHRONIZED_OP(sc);
2000 
2001 	o->flags = sc->flags;
2002 
2003 	o->nbmcaps =  sc->nbmcaps;
2004 	o->linkcaps = sc->linkcaps;
2005 	o->switchcaps = sc->switchcaps;
2006 	o->niccaps = sc->niccaps;
2007 	o->toecaps = sc->toecaps;
2008 	o->rdmacaps = sc->rdmacaps;
2009 	o->cryptocaps = sc->cryptocaps;
2010 	o->iscsicaps = sc->iscsicaps;
2011 	o->fcoecaps = sc->fcoecaps;
2012 
2013 	o->cfcsum = sc->cfcsum;
2014 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2015 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2016 
2017 	o->params = sc->params;
2018 	o->vres = sc->vres;
2019 	o->tids = sc->tids;
2020 	o->sge = sc->sge;
2021 
2022 	o->rawf_base = sc->rawf_base;
2023 	o->nrawf = sc->nrawf;
2024 }
2025 
2026 static int
2027 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2028 {
2029 	int rc = 0;
2030 
2031 	ASSERT_SYNCHRONIZED_OP(sc);
2032 
2033 	/* Capabilities */
2034 #define COMPARE_CAPS(c) do { \
2035 	if (o->c##caps != sc->c##caps) { \
2036 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2037 		    sc->c##caps); \
2038 		rc = EINVAL; \
2039 	} \
2040 } while (0)
2041 	COMPARE_CAPS(nbm);
2042 	COMPARE_CAPS(link);
2043 	COMPARE_CAPS(switch);
2044 	COMPARE_CAPS(nic);
2045 	COMPARE_CAPS(toe);
2046 	COMPARE_CAPS(rdma);
2047 	COMPARE_CAPS(crypto);
2048 	COMPARE_CAPS(iscsi);
2049 	COMPARE_CAPS(fcoe);
2050 #undef COMPARE_CAPS
2051 
2052 	/* Firmware config file */
2053 	if (o->cfcsum != sc->cfcsum) {
2054 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2055 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2056 		rc = EINVAL;
2057 	}
2058 
2059 #define COMPARE_PARAM(p, name) do { \
2060 	if (o->p != sc->p) { \
2061 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2062 		rc = EINVAL; \
2063 	} \
2064 } while (0)
2065 	COMPARE_PARAM(sge.iq_start, iq_start);
2066 	COMPARE_PARAM(sge.eq_start, eq_start);
2067 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2068 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2069 	COMPARE_PARAM(tids.nftids, nftids);
2070 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2071 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2072 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2073 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2074 	COMPARE_PARAM(tids.tid_base, tid_base);
2075 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2076 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2077 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2078 	COMPARE_PARAM(rawf_base, rawf_base);
2079 	COMPARE_PARAM(nrawf, nrawf);
2080 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2081 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2082 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2083 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2084 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2085 	COMPARE_PARAM(tids.ntids, ntids);
2086 	COMPARE_PARAM(tids.etid_base, etid_base);
2087 	COMPARE_PARAM(tids.etid_end, etid_end);
2088 	COMPARE_PARAM(tids.netids, netids);
2089 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2090 	COMPARE_PARAM(params.ethoffload, ethoffload);
2091 	COMPARE_PARAM(tids.natids, natids);
2092 	COMPARE_PARAM(tids.stid_base, stid_base);
2093 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2094 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2095 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2096 	COMPARE_PARAM(vres.stag.start, stag_start);
2097 	COMPARE_PARAM(vres.stag.size, stag_size);
2098 	COMPARE_PARAM(vres.rq.start, rq_start);
2099 	COMPARE_PARAM(vres.rq.size, rq_size);
2100 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2101 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2102 	COMPARE_PARAM(vres.qp.start, qp_start);
2103 	COMPARE_PARAM(vres.qp.size, qp_size);
2104 	COMPARE_PARAM(vres.cq.start, cq_start);
2105 	COMPARE_PARAM(vres.cq.size, cq_size);
2106 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2107 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2108 	COMPARE_PARAM(vres.srq.start, srq_start);
2109 	COMPARE_PARAM(vres.srq.size, srq_size);
2110 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2111 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2112 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2113 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2114 	COMPARE_PARAM(vres.key.start, key_start);
2115 	COMPARE_PARAM(vres.key.size, key_size);
2116 #undef COMPARE_PARAM
2117 
2118 	return (rc);
2119 }
2120 
2121 static int
2122 t4_resume(device_t dev)
2123 {
2124 	struct adapter *sc = device_get_softc(dev);
2125 	struct adapter_pre_reset_state *old_state = NULL;
2126 	struct port_info *pi;
2127 	struct vi_info *vi;
2128 	struct ifnet *ifp;
2129 	struct sge_txq *txq;
2130 	int rc, i, j, k;
2131 
2132 	CH_ALERT(sc, "resume requested.\n");
2133 
2134 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4res");
2135 	if (rc != 0)
2136 		return (ENXIO);
2137 	MPASS(hw_off_limits(sc));
2138 	MPASS((sc->flags & FW_OK) == 0);
2139 	MPASS((sc->flags & MASTER_PF) == 0);
2140 	MPASS(sc->reset_thread == NULL);
2141 	sc->reset_thread = curthread;
2142 
2143 	/* Register access is expected to work by the time we're here. */
2144 	if (t4_read_reg(sc, A_PL_WHOAMI) == 0xffffffff) {
2145 		CH_ERR(sc, "%s: can't read device registers\n", __func__);
2146 		rc = ENXIO;
2147 		goto done;
2148 	}
2149 
2150 	/* Restore memory window. */
2151 	setup_memwin(sc);
2152 
2153 	/* Go no further if recovery mode has been requested. */
2154 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2155 		CH_ALERT(sc, "recovery mode on resume.\n");
2156 		rc = 0;
2157 		mtx_lock(&sc->reg_lock);
2158 		sc->flags &= ~HW_OFF_LIMITS;
2159 		mtx_unlock(&sc->reg_lock);
2160 		goto done;
2161 	}
2162 
2163 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2164 	save_caps_and_params(sc, old_state);
2165 
2166 	/* Reestablish contact with firmware and become the primary PF. */
2167 	rc = contact_firmware(sc);
2168 	if (rc != 0)
2169 		goto done; /* error message displayed already */
2170 	MPASS(sc->flags & FW_OK);
2171 
2172 	if (sc->flags & MASTER_PF) {
2173 		rc = partition_resources(sc);
2174 		if (rc != 0)
2175 			goto done; /* error message displayed already */
2176 		t4_intr_clear(sc);
2177 	}
2178 
2179 	rc = get_params__post_init(sc);
2180 	if (rc != 0)
2181 		goto done; /* error message displayed already */
2182 
2183 	rc = set_params__post_init(sc);
2184 	if (rc != 0)
2185 		goto done; /* error message displayed already */
2186 
2187 	rc = compare_caps_and_params(sc, old_state);
2188 	if (rc != 0)
2189 		goto done; /* error message displayed already */
2190 
2191 	for_each_port(sc, i) {
2192 		pi = sc->port[i];
2193 		MPASS(pi != NULL);
2194 		MPASS(pi->vi != NULL);
2195 		MPASS(pi->vi[0].dev == pi->dev);
2196 
2197 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2198 		if (rc != 0) {
2199 			CH_ERR(sc,
2200 			    "failed to re-initialize port %d: %d\n", i, rc);
2201 			goto done;
2202 		}
2203 		MPASS(sc->chan_map[pi->tx_chan] == i);
2204 
2205 		PORT_LOCK(pi);
2206 		fixup_link_config(pi);
2207 		build_medialist(pi);
2208 		PORT_UNLOCK(pi);
2209 		for_each_vi(pi, j, vi) {
2210 			if (IS_MAIN_VI(vi))
2211 				continue;
2212 			rc = alloc_extra_vi(sc, pi, vi);
2213 			if (rc != 0) {
2214 				CH_ERR(vi,
2215 				    "failed to re-allocate extra VI: %d\n", rc);
2216 				goto done;
2217 			}
2218 		}
2219 	}
2220 
2221 	/*
2222 	 * Interrupts and queues are about to be enabled and other threads will
2223 	 * want to access the hardware too.  It is safe to do so.  Note that
2224 	 * this thread is still in the middle of a synchronized_op.
2225 	 */
2226 	mtx_lock(&sc->reg_lock);
2227 	sc->flags &= ~HW_OFF_LIMITS;
2228 	mtx_unlock(&sc->reg_lock);
2229 
2230 	if (sc->flags & FULL_INIT_DONE) {
2231 		rc = adapter_full_init(sc);
2232 		if (rc != 0) {
2233 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2234 			goto done;
2235 		}
2236 
2237 		if (sc->vxlan_refcount > 0)
2238 			enable_vxlan_rx(sc);
2239 
2240 		for_each_port(sc, i) {
2241 			pi = sc->port[i];
2242 			for_each_vi(pi, j, vi) {
2243 				if (!(vi->flags & VI_INIT_DONE))
2244 					continue;
2245 				rc = vi_full_init(vi);
2246 				if (rc != 0) {
2247 					CH_ERR(vi, "failed to re-initialize "
2248 					    "interface: %d\n", rc);
2249 					goto done;
2250 				}
2251 
2252 				ifp = vi->ifp;
2253 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2254 					continue;
2255 				/*
2256 				 * Note that we do not setup multicast addresses
2257 				 * in the first pass.  This ensures that the
2258 				 * unicast DMACs for all VIs on all ports get an
2259 				 * MPS TCAM entry.
2260 				 */
2261 				rc = update_mac_settings(ifp, XGMAC_ALL &
2262 				    ~XGMAC_MCADDRS);
2263 				if (rc != 0) {
2264 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2265 					goto done;
2266 				}
2267 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2268 				    true);
2269 				if (rc != 0) {
2270 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2271 					goto done;
2272 				}
2273 				for_each_txq(vi, k, txq) {
2274 					TXQ_LOCK(txq);
2275 					txq->eq.flags |= EQ_ENABLED;
2276 					TXQ_UNLOCK(txq);
2277 				}
2278 				mtx_lock(&vi->tick_mtx);
2279 				vi->flags &= ~VI_SKIP_STATS;
2280 				callout_schedule(&vi->tick, hz);
2281 				mtx_unlock(&vi->tick_mtx);
2282 			}
2283 			PORT_LOCK(pi);
2284 			if (pi->up_vis > 0) {
2285 				t4_update_port_info(pi);
2286 				fixup_link_config(pi);
2287 				build_medialist(pi);
2288 				apply_link_config(pi);
2289 				if (pi->link_cfg.link_ok)
2290 					t4_os_link_changed(pi);
2291 			}
2292 			PORT_UNLOCK(pi);
2293 		}
2294 
2295 		/* Now reprogram the L2 multicast addresses. */
2296 		for_each_port(sc, i) {
2297 			pi = sc->port[i];
2298 			for_each_vi(pi, j, vi) {
2299 				if (!(vi->flags & VI_INIT_DONE))
2300 					continue;
2301 				ifp = vi->ifp;
2302 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2303 					continue;
2304 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2305 				if (rc != 0) {
2306 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2307 					rc = 0;	/* carry on */
2308 				}
2309 			}
2310 		}
2311 	}
2312 done:
2313 	if (rc == 0) {
2314 		sc->incarnation++;
2315 		CH_ALERT(sc, "resume completed.\n");
2316 	}
2317 	end_synchronized_op(sc, 0);
2318 	free(old_state, M_CXGBE);
2319 	return (rc);
2320 }
2321 
2322 static int
2323 t4_reset_prepare(device_t dev, device_t child)
2324 {
2325 	struct adapter *sc = device_get_softc(dev);
2326 
2327 	CH_ALERT(sc, "reset_prepare.\n");
2328 	return (0);
2329 }
2330 
2331 static int
2332 t4_reset_post(device_t dev, device_t child)
2333 {
2334 	struct adapter *sc = device_get_softc(dev);
2335 
2336 	CH_ALERT(sc, "reset_post.\n");
2337 	return (0);
2338 }
2339 
2340 static void
2341 reset_adapter(void *arg, int pending)
2342 {
2343 	struct adapter *sc = arg;
2344 	int rc;
2345 
2346 	CH_ALERT(sc, "reset requested.\n");
2347 
2348 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst1");
2349 	if (rc != 0)
2350 		return;
2351 
2352 	if (hw_off_limits(sc)) {
2353 		CH_ERR(sc, "adapter is suspended, use resume (not reset).\n");
2354 		rc = ENXIO;
2355 		goto done;
2356 	}
2357 
2358 	if (!ok_to_reset(sc)) {
2359 		/* XXX: should list what resource is preventing reset. */
2360 		CH_ERR(sc, "not safe to reset.\n");
2361 		rc = EBUSY;
2362 		goto done;
2363 	}
2364 
2365 done:
2366 	end_synchronized_op(sc, 0);
2367 	if (rc != 0)
2368 		return;	/* Error logged already. */
2369 
2370 	mtx_lock(&Giant);
2371 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2372 	mtx_unlock(&Giant);
2373 	if (rc != 0)
2374 		CH_ERR(sc, "bus_reset_child failed: %d.\n", rc);
2375 	else
2376 		CH_ALERT(sc, "bus_reset_child succeeded.\n");
2377 }
2378 
2379 static int
2380 cxgbe_probe(device_t dev)
2381 {
2382 	char buf[128];
2383 	struct port_info *pi = device_get_softc(dev);
2384 
2385 	snprintf(buf, sizeof(buf), "port %d", pi->port_id);
2386 	device_set_desc_copy(dev, buf);
2387 
2388 	return (BUS_PROBE_DEFAULT);
2389 }
2390 
2391 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2392     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2393     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2394     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2395 #define T4_CAP_ENABLE (T4_CAP)
2396 
2397 static int
2398 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2399 {
2400 	struct ifnet *ifp;
2401 	struct sbuf *sb;
2402 	struct sysctl_ctx_list *ctx;
2403 	struct sysctl_oid_list *children;
2404 	struct pfil_head_args pa;
2405 	struct adapter *sc = vi->adapter;
2406 
2407 	ctx = device_get_sysctl_ctx(vi->dev);
2408 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2409 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2410 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2411 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2412 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2413 #ifdef DEV_NETMAP
2414 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2415 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2416 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2417 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2418 #endif
2419 #ifdef TCP_OFFLOAD
2420 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2421 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2422 #endif
2423 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2424 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2425 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2426 #endif
2427 
2428 	vi->xact_addr_filt = -1;
2429 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2430 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2431 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2432 		vi->flags |= TX_USES_VM_WR;
2433 
2434 	/* Allocate an ifnet and set it up */
2435 	ifp = if_alloc_dev(IFT_ETHER, dev);
2436 	if (ifp == NULL) {
2437 		device_printf(dev, "Cannot allocate ifnet\n");
2438 		return (ENOMEM);
2439 	}
2440 	vi->ifp = ifp;
2441 	ifp->if_softc = vi;
2442 
2443 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2444 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
2445 
2446 	ifp->if_init = cxgbe_init;
2447 	ifp->if_ioctl = cxgbe_ioctl;
2448 	ifp->if_transmit = cxgbe_transmit;
2449 	ifp->if_qflush = cxgbe_qflush;
2450 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2451 		ifp->if_get_counter = vi_get_counter;
2452 	else
2453 		ifp->if_get_counter = cxgbe_get_counter;
2454 #if defined(KERN_TLS) || defined(RATELIMIT)
2455 	ifp->if_snd_tag_alloc = cxgbe_snd_tag_alloc;
2456 	ifp->if_snd_tag_modify = cxgbe_snd_tag_modify;
2457 	ifp->if_snd_tag_query = cxgbe_snd_tag_query;
2458 	ifp->if_snd_tag_free = cxgbe_snd_tag_free;
2459 #endif
2460 #ifdef RATELIMIT
2461 	ifp->if_ratelimit_query = cxgbe_ratelimit_query;
2462 #endif
2463 
2464 	ifp->if_capabilities = T4_CAP;
2465 	ifp->if_capenable = T4_CAP_ENABLE;
2466 	ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2467 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6;
2468 	if (chip_id(sc) >= CHELSIO_T6) {
2469 		ifp->if_capabilities |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2470 		ifp->if_capenable |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2471 		ifp->if_hwassist |= CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2472 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2473 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN;
2474 	}
2475 
2476 #ifdef TCP_OFFLOAD
2477 	if (vi->nofldrxq != 0)
2478 		ifp->if_capabilities |= IFCAP_TOE;
2479 #endif
2480 #ifdef RATELIMIT
2481 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2482 		ifp->if_capabilities |= IFCAP_TXRTLMT;
2483 		ifp->if_capenable |= IFCAP_TXRTLMT;
2484 	}
2485 #endif
2486 
2487 	ifp->if_hw_tsomax = IP_MAXPACKET;
2488 	if (vi->flags & TX_USES_VM_WR)
2489 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
2490 	else
2491 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
2492 #ifdef RATELIMIT
2493 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2494 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_EO_TSO;
2495 #endif
2496 	ifp->if_hw_tsomaxsegsize = 65536;
2497 #ifdef KERN_TLS
2498 	if (is_ktls(sc)) {
2499 		ifp->if_capabilities |= IFCAP_TXTLS;
2500 		if (sc->flags & KERN_TLS_ON)
2501 			ifp->if_capenable |= IFCAP_TXTLS;
2502 	}
2503 #endif
2504 
2505 	ether_ifattach(ifp, vi->hw_addr);
2506 #ifdef DEV_NETMAP
2507 	if (vi->nnmrxq != 0)
2508 		cxgbe_nm_attach(vi);
2509 #endif
2510 	sb = sbuf_new_auto();
2511 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2512 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2513 	switch (ifp->if_capabilities & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2514 	case IFCAP_TOE:
2515 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2516 		break;
2517 	case IFCAP_TOE | IFCAP_TXRTLMT:
2518 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2519 		break;
2520 	case IFCAP_TXRTLMT:
2521 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2522 		break;
2523 	}
2524 #endif
2525 #ifdef TCP_OFFLOAD
2526 	if (ifp->if_capabilities & IFCAP_TOE)
2527 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2528 #endif
2529 #ifdef DEV_NETMAP
2530 	if (ifp->if_capabilities & IFCAP_NETMAP)
2531 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2532 		    vi->nnmtxq, vi->nnmrxq);
2533 #endif
2534 	sbuf_finish(sb);
2535 	device_printf(dev, "%s\n", sbuf_data(sb));
2536 	sbuf_delete(sb);
2537 
2538 	vi_sysctls(vi);
2539 
2540 	pa.pa_version = PFIL_VERSION;
2541 	pa.pa_flags = PFIL_IN;
2542 	pa.pa_type = PFIL_TYPE_ETHERNET;
2543 	pa.pa_headname = ifp->if_xname;
2544 	vi->pfil = pfil_head_register(&pa);
2545 
2546 	return (0);
2547 }
2548 
2549 static int
2550 cxgbe_attach(device_t dev)
2551 {
2552 	struct port_info *pi = device_get_softc(dev);
2553 	struct adapter *sc = pi->adapter;
2554 	struct vi_info *vi;
2555 	int i, rc;
2556 
2557 	rc = cxgbe_vi_attach(dev, &pi->vi[0]);
2558 	if (rc)
2559 		return (rc);
2560 
2561 	for_each_vi(pi, i, vi) {
2562 		if (i == 0)
2563 			continue;
2564 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
2565 		if (vi->dev == NULL) {
2566 			device_printf(dev, "failed to add VI %d\n", i);
2567 			continue;
2568 		}
2569 		device_set_softc(vi->dev, vi);
2570 	}
2571 
2572 	cxgbe_sysctls(pi);
2573 
2574 	bus_generic_attach(dev);
2575 
2576 	return (0);
2577 }
2578 
2579 static void
2580 cxgbe_vi_detach(struct vi_info *vi)
2581 {
2582 	struct ifnet *ifp = vi->ifp;
2583 
2584 	if (vi->pfil != NULL) {
2585 		pfil_head_unregister(vi->pfil);
2586 		vi->pfil = NULL;
2587 	}
2588 
2589 	ether_ifdetach(ifp);
2590 
2591 	/* Let detach proceed even if these fail. */
2592 #ifdef DEV_NETMAP
2593 	if (ifp->if_capabilities & IFCAP_NETMAP)
2594 		cxgbe_nm_detach(vi);
2595 #endif
2596 	cxgbe_uninit_synchronized(vi);
2597 	callout_drain(&vi->tick);
2598 	vi_full_uninit(vi);
2599 
2600 	if_free(vi->ifp);
2601 	vi->ifp = NULL;
2602 }
2603 
2604 static int
2605 cxgbe_detach(device_t dev)
2606 {
2607 	struct port_info *pi = device_get_softc(dev);
2608 	struct adapter *sc = pi->adapter;
2609 	int rc;
2610 
2611 	/* Detach the extra VIs first. */
2612 	rc = bus_generic_detach(dev);
2613 	if (rc)
2614 		return (rc);
2615 	device_delete_children(dev);
2616 
2617 	doom_vi(sc, &pi->vi[0]);
2618 
2619 	if (pi->flags & HAS_TRACEQ) {
2620 		sc->traceq = -1;	/* cloner should not create ifnet */
2621 		t4_tracer_port_detach(sc);
2622 	}
2623 
2624 	cxgbe_vi_detach(&pi->vi[0]);
2625 	ifmedia_removeall(&pi->media);
2626 
2627 	end_synchronized_op(sc, 0);
2628 
2629 	return (0);
2630 }
2631 
2632 static void
2633 cxgbe_init(void *arg)
2634 {
2635 	struct vi_info *vi = arg;
2636 	struct adapter *sc = vi->adapter;
2637 
2638 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2639 		return;
2640 	cxgbe_init_synchronized(vi);
2641 	end_synchronized_op(sc, 0);
2642 }
2643 
2644 static int
2645 cxgbe_ioctl(struct ifnet *ifp, unsigned long cmd, caddr_t data)
2646 {
2647 	int rc = 0, mtu, flags;
2648 	struct vi_info *vi = ifp->if_softc;
2649 	struct port_info *pi = vi->pi;
2650 	struct adapter *sc = pi->adapter;
2651 	struct ifreq *ifr = (struct ifreq *)data;
2652 	uint32_t mask;
2653 
2654 	switch (cmd) {
2655 	case SIOCSIFMTU:
2656 		mtu = ifr->ifr_mtu;
2657 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2658 			return (EINVAL);
2659 
2660 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2661 		if (rc)
2662 			return (rc);
2663 		ifp->if_mtu = mtu;
2664 		if (vi->flags & VI_INIT_DONE) {
2665 			t4_update_fl_bufsize(ifp);
2666 			if (!hw_off_limits(sc) &&
2667 			    ifp->if_drv_flags & IFF_DRV_RUNNING)
2668 				rc = update_mac_settings(ifp, XGMAC_MTU);
2669 		}
2670 		end_synchronized_op(sc, 0);
2671 		break;
2672 
2673 	case SIOCSIFFLAGS:
2674 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2675 		if (rc)
2676 			return (rc);
2677 
2678 		if (hw_off_limits(sc)) {
2679 			rc = ENXIO;
2680 			goto fail;
2681 		}
2682 
2683 		if (ifp->if_flags & IFF_UP) {
2684 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2685 				flags = vi->if_flags;
2686 				if ((ifp->if_flags ^ flags) &
2687 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2688 					rc = update_mac_settings(ifp,
2689 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2690 				}
2691 			} else {
2692 				rc = cxgbe_init_synchronized(vi);
2693 			}
2694 			vi->if_flags = ifp->if_flags;
2695 		} else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2696 			rc = cxgbe_uninit_synchronized(vi);
2697 		}
2698 		end_synchronized_op(sc, 0);
2699 		break;
2700 
2701 	case SIOCADDMULTI:
2702 	case SIOCDELMULTI:
2703 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2704 		if (rc)
2705 			return (rc);
2706 		if (!hw_off_limits(sc) && ifp->if_drv_flags & IFF_DRV_RUNNING)
2707 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2708 		end_synchronized_op(sc, 0);
2709 		break;
2710 
2711 	case SIOCSIFCAP:
2712 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2713 		if (rc)
2714 			return (rc);
2715 
2716 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
2717 		if (mask & IFCAP_TXCSUM) {
2718 			ifp->if_capenable ^= IFCAP_TXCSUM;
2719 			ifp->if_hwassist ^= (CSUM_TCP | CSUM_UDP | CSUM_IP);
2720 
2721 			if (IFCAP_TSO4 & ifp->if_capenable &&
2722 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2723 				mask &= ~IFCAP_TSO4;
2724 				ifp->if_capenable &= ~IFCAP_TSO4;
2725 				if_printf(ifp,
2726 				    "tso4 disabled due to -txcsum.\n");
2727 			}
2728 		}
2729 		if (mask & IFCAP_TXCSUM_IPV6) {
2730 			ifp->if_capenable ^= IFCAP_TXCSUM_IPV6;
2731 			ifp->if_hwassist ^= (CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2732 
2733 			if (IFCAP_TSO6 & ifp->if_capenable &&
2734 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2735 				mask &= ~IFCAP_TSO6;
2736 				ifp->if_capenable &= ~IFCAP_TSO6;
2737 				if_printf(ifp,
2738 				    "tso6 disabled due to -txcsum6.\n");
2739 			}
2740 		}
2741 		if (mask & IFCAP_RXCSUM)
2742 			ifp->if_capenable ^= IFCAP_RXCSUM;
2743 		if (mask & IFCAP_RXCSUM_IPV6)
2744 			ifp->if_capenable ^= IFCAP_RXCSUM_IPV6;
2745 
2746 		/*
2747 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2748 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2749 		 * sending a TSO request our way, so it's sufficient to toggle
2750 		 * IFCAP_TSOx only.
2751 		 */
2752 		if (mask & IFCAP_TSO4) {
2753 			if (!(IFCAP_TSO4 & ifp->if_capenable) &&
2754 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2755 				if_printf(ifp, "enable txcsum first.\n");
2756 				rc = EAGAIN;
2757 				goto fail;
2758 			}
2759 			ifp->if_capenable ^= IFCAP_TSO4;
2760 		}
2761 		if (mask & IFCAP_TSO6) {
2762 			if (!(IFCAP_TSO6 & ifp->if_capenable) &&
2763 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2764 				if_printf(ifp, "enable txcsum6 first.\n");
2765 				rc = EAGAIN;
2766 				goto fail;
2767 			}
2768 			ifp->if_capenable ^= IFCAP_TSO6;
2769 		}
2770 		if (mask & IFCAP_LRO) {
2771 #if defined(INET) || defined(INET6)
2772 			int i;
2773 			struct sge_rxq *rxq;
2774 
2775 			ifp->if_capenable ^= IFCAP_LRO;
2776 			for_each_rxq(vi, i, rxq) {
2777 				if (ifp->if_capenable & IFCAP_LRO)
2778 					rxq->iq.flags |= IQ_LRO_ENABLED;
2779 				else
2780 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2781 			}
2782 #endif
2783 		}
2784 #ifdef TCP_OFFLOAD
2785 		if (mask & IFCAP_TOE) {
2786 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TOE;
2787 
2788 			rc = toe_capability(vi, enable);
2789 			if (rc != 0)
2790 				goto fail;
2791 
2792 			ifp->if_capenable ^= mask;
2793 		}
2794 #endif
2795 		if (mask & IFCAP_VLAN_HWTAGGING) {
2796 			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
2797 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2798 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2799 		}
2800 		if (mask & IFCAP_VLAN_MTU) {
2801 			ifp->if_capenable ^= IFCAP_VLAN_MTU;
2802 
2803 			/* Need to find out how to disable auto-mtu-inflation */
2804 		}
2805 		if (mask & IFCAP_VLAN_HWTSO)
2806 			ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
2807 		if (mask & IFCAP_VLAN_HWCSUM)
2808 			ifp->if_capenable ^= IFCAP_VLAN_HWCSUM;
2809 #ifdef RATELIMIT
2810 		if (mask & IFCAP_TXRTLMT)
2811 			ifp->if_capenable ^= IFCAP_TXRTLMT;
2812 #endif
2813 		if (mask & IFCAP_HWRXTSTMP) {
2814 			int i;
2815 			struct sge_rxq *rxq;
2816 
2817 			ifp->if_capenable ^= IFCAP_HWRXTSTMP;
2818 			for_each_rxq(vi, i, rxq) {
2819 				if (ifp->if_capenable & IFCAP_HWRXTSTMP)
2820 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2821 				else
2822 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2823 			}
2824 		}
2825 		if (mask & IFCAP_MEXTPG)
2826 			ifp->if_capenable ^= IFCAP_MEXTPG;
2827 
2828 #ifdef KERN_TLS
2829 		if (mask & IFCAP_TXTLS) {
2830 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TXTLS;
2831 
2832 			rc = ktls_capability(sc, enable);
2833 			if (rc != 0)
2834 				goto fail;
2835 
2836 			ifp->if_capenable ^= (mask & IFCAP_TXTLS);
2837 		}
2838 #endif
2839 		if (mask & IFCAP_VXLAN_HWCSUM) {
2840 			ifp->if_capenable ^= IFCAP_VXLAN_HWCSUM;
2841 			ifp->if_hwassist ^= CSUM_INNER_IP6_UDP |
2842 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
2843 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP;
2844 		}
2845 		if (mask & IFCAP_VXLAN_HWTSO) {
2846 			ifp->if_capenable ^= IFCAP_VXLAN_HWTSO;
2847 			ifp->if_hwassist ^= CSUM_INNER_IP6_TSO |
2848 			    CSUM_INNER_IP_TSO;
2849 		}
2850 
2851 #ifdef VLAN_CAPABILITIES
2852 		VLAN_CAPABILITIES(ifp);
2853 #endif
2854 fail:
2855 		end_synchronized_op(sc, 0);
2856 		break;
2857 
2858 	case SIOCSIFMEDIA:
2859 	case SIOCGIFMEDIA:
2860 	case SIOCGIFXMEDIA:
2861 		ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
2862 		break;
2863 
2864 	case SIOCGI2C: {
2865 		struct ifi2creq i2c;
2866 
2867 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
2868 		if (rc != 0)
2869 			break;
2870 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
2871 			rc = EPERM;
2872 			break;
2873 		}
2874 		if (i2c.len > sizeof(i2c.data)) {
2875 			rc = EINVAL;
2876 			break;
2877 		}
2878 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
2879 		if (rc)
2880 			return (rc);
2881 		if (hw_off_limits(sc))
2882 			rc = ENXIO;
2883 		else
2884 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
2885 			    i2c.offset, i2c.len, &i2c.data[0]);
2886 		end_synchronized_op(sc, 0);
2887 		if (rc == 0)
2888 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
2889 		break;
2890 	}
2891 
2892 	default:
2893 		rc = ether_ioctl(ifp, cmd, data);
2894 	}
2895 
2896 	return (rc);
2897 }
2898 
2899 static int
2900 cxgbe_transmit(struct ifnet *ifp, struct mbuf *m)
2901 {
2902 	struct vi_info *vi = ifp->if_softc;
2903 	struct port_info *pi = vi->pi;
2904 	struct adapter *sc;
2905 	struct sge_txq *txq;
2906 	void *items[1];
2907 	int rc;
2908 
2909 	M_ASSERTPKTHDR(m);
2910 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
2911 #if defined(KERN_TLS) || defined(RATELIMIT)
2912 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
2913 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
2914 #endif
2915 
2916 	if (__predict_false(pi->link_cfg.link_ok == false)) {
2917 		m_freem(m);
2918 		return (ENETDOWN);
2919 	}
2920 
2921 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
2922 	if (__predict_false(rc != 0)) {
2923 		MPASS(m == NULL);			/* was freed already */
2924 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
2925 		return (rc);
2926 	}
2927 #ifdef RATELIMIT
2928 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG) {
2929 		if (m->m_pkthdr.snd_tag->type == IF_SND_TAG_TYPE_RATE_LIMIT)
2930 			return (ethofld_transmit(ifp, m));
2931 	}
2932 #endif
2933 
2934 	/* Select a txq. */
2935 	sc = vi->adapter;
2936 	txq = &sc->sge.txq[vi->first_txq];
2937 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
2938 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
2939 		    vi->rsrv_noflowq);
2940 
2941 	items[0] = m;
2942 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
2943 	if (__predict_false(rc != 0))
2944 		m_freem(m);
2945 
2946 	return (rc);
2947 }
2948 
2949 static void
2950 cxgbe_qflush(struct ifnet *ifp)
2951 {
2952 	struct vi_info *vi = ifp->if_softc;
2953 	struct sge_txq *txq;
2954 	int i;
2955 
2956 	/* queues do not exist if !VI_INIT_DONE. */
2957 	if (vi->flags & VI_INIT_DONE) {
2958 		for_each_txq(vi, i, txq) {
2959 			TXQ_LOCK(txq);
2960 			txq->eq.flags |= EQ_QFLUSH;
2961 			TXQ_UNLOCK(txq);
2962 			while (!mp_ring_is_idle(txq->r)) {
2963 				mp_ring_check_drainage(txq->r, 4096);
2964 				pause("qflush", 1);
2965 			}
2966 			TXQ_LOCK(txq);
2967 			txq->eq.flags &= ~EQ_QFLUSH;
2968 			TXQ_UNLOCK(txq);
2969 		}
2970 	}
2971 	if_qflush(ifp);
2972 }
2973 
2974 static uint64_t
2975 vi_get_counter(struct ifnet *ifp, ift_counter c)
2976 {
2977 	struct vi_info *vi = ifp->if_softc;
2978 	struct fw_vi_stats_vf *s = &vi->stats;
2979 
2980 	mtx_lock(&vi->tick_mtx);
2981 	vi_refresh_stats(vi);
2982 	mtx_unlock(&vi->tick_mtx);
2983 
2984 	switch (c) {
2985 	case IFCOUNTER_IPACKETS:
2986 		return (s->rx_bcast_frames + s->rx_mcast_frames +
2987 		    s->rx_ucast_frames);
2988 	case IFCOUNTER_IERRORS:
2989 		return (s->rx_err_frames);
2990 	case IFCOUNTER_OPACKETS:
2991 		return (s->tx_bcast_frames + s->tx_mcast_frames +
2992 		    s->tx_ucast_frames + s->tx_offload_frames);
2993 	case IFCOUNTER_OERRORS:
2994 		return (s->tx_drop_frames);
2995 	case IFCOUNTER_IBYTES:
2996 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
2997 		    s->rx_ucast_bytes);
2998 	case IFCOUNTER_OBYTES:
2999 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3000 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3001 	case IFCOUNTER_IMCASTS:
3002 		return (s->rx_mcast_frames);
3003 	case IFCOUNTER_OMCASTS:
3004 		return (s->tx_mcast_frames);
3005 	case IFCOUNTER_OQDROPS: {
3006 		uint64_t drops;
3007 
3008 		drops = 0;
3009 		if (vi->flags & VI_INIT_DONE) {
3010 			int i;
3011 			struct sge_txq *txq;
3012 
3013 			for_each_txq(vi, i, txq)
3014 				drops += counter_u64_fetch(txq->r->dropped);
3015 		}
3016 
3017 		return (drops);
3018 
3019 	}
3020 
3021 	default:
3022 		return (if_get_counter_default(ifp, c));
3023 	}
3024 }
3025 
3026 static uint64_t
3027 cxgbe_get_counter(struct ifnet *ifp, ift_counter c)
3028 {
3029 	struct vi_info *vi = ifp->if_softc;
3030 	struct port_info *pi = vi->pi;
3031 	struct port_stats *s = &pi->stats;
3032 
3033 	mtx_lock(&vi->tick_mtx);
3034 	cxgbe_refresh_stats(vi);
3035 	mtx_unlock(&vi->tick_mtx);
3036 
3037 	switch (c) {
3038 	case IFCOUNTER_IPACKETS:
3039 		return (s->rx_frames);
3040 
3041 	case IFCOUNTER_IERRORS:
3042 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3043 		    s->rx_fcs_err + s->rx_len_err);
3044 
3045 	case IFCOUNTER_OPACKETS:
3046 		return (s->tx_frames);
3047 
3048 	case IFCOUNTER_OERRORS:
3049 		return (s->tx_error_frames);
3050 
3051 	case IFCOUNTER_IBYTES:
3052 		return (s->rx_octets);
3053 
3054 	case IFCOUNTER_OBYTES:
3055 		return (s->tx_octets);
3056 
3057 	case IFCOUNTER_IMCASTS:
3058 		return (s->rx_mcast_frames);
3059 
3060 	case IFCOUNTER_OMCASTS:
3061 		return (s->tx_mcast_frames);
3062 
3063 	case IFCOUNTER_IQDROPS:
3064 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3065 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3066 		    s->rx_trunc3 + pi->tnl_cong_drops);
3067 
3068 	case IFCOUNTER_OQDROPS: {
3069 		uint64_t drops;
3070 
3071 		drops = s->tx_drop;
3072 		if (vi->flags & VI_INIT_DONE) {
3073 			int i;
3074 			struct sge_txq *txq;
3075 
3076 			for_each_txq(vi, i, txq)
3077 				drops += counter_u64_fetch(txq->r->dropped);
3078 		}
3079 
3080 		return (drops);
3081 
3082 	}
3083 
3084 	default:
3085 		return (if_get_counter_default(ifp, c));
3086 	}
3087 }
3088 
3089 #if defined(KERN_TLS) || defined(RATELIMIT)
3090 static int
3091 cxgbe_snd_tag_alloc(struct ifnet *ifp, union if_snd_tag_alloc_params *params,
3092     struct m_snd_tag **pt)
3093 {
3094 	int error;
3095 
3096 	switch (params->hdr.type) {
3097 #ifdef RATELIMIT
3098 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3099 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3100 		break;
3101 #endif
3102 #ifdef KERN_TLS
3103 	case IF_SND_TAG_TYPE_TLS:
3104 		error = cxgbe_tls_tag_alloc(ifp, params, pt);
3105 		break;
3106 #endif
3107 	default:
3108 		error = EOPNOTSUPP;
3109 	}
3110 	return (error);
3111 }
3112 
3113 static int
3114 cxgbe_snd_tag_modify(struct m_snd_tag *mst,
3115     union if_snd_tag_modify_params *params)
3116 {
3117 
3118 	switch (mst->type) {
3119 #ifdef RATELIMIT
3120 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3121 		return (cxgbe_rate_tag_modify(mst, params));
3122 #endif
3123 	default:
3124 		return (EOPNOTSUPP);
3125 	}
3126 }
3127 
3128 static int
3129 cxgbe_snd_tag_query(struct m_snd_tag *mst,
3130     union if_snd_tag_query_params *params)
3131 {
3132 
3133 	switch (mst->type) {
3134 #ifdef RATELIMIT
3135 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3136 		return (cxgbe_rate_tag_query(mst, params));
3137 #endif
3138 	default:
3139 		return (EOPNOTSUPP);
3140 	}
3141 }
3142 
3143 static void
3144 cxgbe_snd_tag_free(struct m_snd_tag *mst)
3145 {
3146 
3147 	switch (mst->type) {
3148 #ifdef RATELIMIT
3149 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3150 		cxgbe_rate_tag_free(mst);
3151 		return;
3152 #endif
3153 #ifdef KERN_TLS
3154 	case IF_SND_TAG_TYPE_TLS:
3155 		cxgbe_tls_tag_free(mst);
3156 		return;
3157 #endif
3158 	default:
3159 		panic("shouldn't get here");
3160 	}
3161 }
3162 #endif
3163 
3164 /*
3165  * The kernel picks a media from the list we had provided but we still validate
3166  * the requeste.
3167  */
3168 int
3169 cxgbe_media_change(struct ifnet *ifp)
3170 {
3171 	struct vi_info *vi = ifp->if_softc;
3172 	struct port_info *pi = vi->pi;
3173 	struct ifmedia *ifm = &pi->media;
3174 	struct link_config *lc = &pi->link_cfg;
3175 	struct adapter *sc = pi->adapter;
3176 	int rc;
3177 
3178 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3179 	if (rc != 0)
3180 		return (rc);
3181 	PORT_LOCK(pi);
3182 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3183 		/* ifconfig .. media autoselect */
3184 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3185 			rc = ENOTSUP; /* AN not supported by transceiver */
3186 			goto done;
3187 		}
3188 		lc->requested_aneg = AUTONEG_ENABLE;
3189 		lc->requested_speed = 0;
3190 		lc->requested_fc |= PAUSE_AUTONEG;
3191 	} else {
3192 		lc->requested_aneg = AUTONEG_DISABLE;
3193 		lc->requested_speed =
3194 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3195 		lc->requested_fc = 0;
3196 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3197 			lc->requested_fc |= PAUSE_RX;
3198 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3199 			lc->requested_fc |= PAUSE_TX;
3200 	}
3201 	if (pi->up_vis > 0) {
3202 		fixup_link_config(pi);
3203 		rc = apply_link_config(pi);
3204 	}
3205 done:
3206 	PORT_UNLOCK(pi);
3207 	end_synchronized_op(sc, 0);
3208 	return (rc);
3209 }
3210 
3211 /*
3212  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3213  * given speed.
3214  */
3215 static int
3216 port_mword(struct port_info *pi, uint32_t speed)
3217 {
3218 
3219 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3220 	MPASS(powerof2(speed));
3221 
3222 	switch(pi->port_type) {
3223 	case FW_PORT_TYPE_BT_SGMII:
3224 	case FW_PORT_TYPE_BT_XFI:
3225 	case FW_PORT_TYPE_BT_XAUI:
3226 		/* BaseT */
3227 		switch (speed) {
3228 		case FW_PORT_CAP32_SPEED_100M:
3229 			return (IFM_100_T);
3230 		case FW_PORT_CAP32_SPEED_1G:
3231 			return (IFM_1000_T);
3232 		case FW_PORT_CAP32_SPEED_10G:
3233 			return (IFM_10G_T);
3234 		}
3235 		break;
3236 	case FW_PORT_TYPE_KX4:
3237 		if (speed == FW_PORT_CAP32_SPEED_10G)
3238 			return (IFM_10G_KX4);
3239 		break;
3240 	case FW_PORT_TYPE_CX4:
3241 		if (speed == FW_PORT_CAP32_SPEED_10G)
3242 			return (IFM_10G_CX4);
3243 		break;
3244 	case FW_PORT_TYPE_KX:
3245 		if (speed == FW_PORT_CAP32_SPEED_1G)
3246 			return (IFM_1000_KX);
3247 		break;
3248 	case FW_PORT_TYPE_KR:
3249 	case FW_PORT_TYPE_BP_AP:
3250 	case FW_PORT_TYPE_BP4_AP:
3251 	case FW_PORT_TYPE_BP40_BA:
3252 	case FW_PORT_TYPE_KR4_100G:
3253 	case FW_PORT_TYPE_KR_SFP28:
3254 	case FW_PORT_TYPE_KR_XLAUI:
3255 		switch (speed) {
3256 		case FW_PORT_CAP32_SPEED_1G:
3257 			return (IFM_1000_KX);
3258 		case FW_PORT_CAP32_SPEED_10G:
3259 			return (IFM_10G_KR);
3260 		case FW_PORT_CAP32_SPEED_25G:
3261 			return (IFM_25G_KR);
3262 		case FW_PORT_CAP32_SPEED_40G:
3263 			return (IFM_40G_KR4);
3264 		case FW_PORT_CAP32_SPEED_50G:
3265 			return (IFM_50G_KR2);
3266 		case FW_PORT_CAP32_SPEED_100G:
3267 			return (IFM_100G_KR4);
3268 		}
3269 		break;
3270 	case FW_PORT_TYPE_FIBER_XFI:
3271 	case FW_PORT_TYPE_FIBER_XAUI:
3272 	case FW_PORT_TYPE_SFP:
3273 	case FW_PORT_TYPE_QSFP_10G:
3274 	case FW_PORT_TYPE_QSA:
3275 	case FW_PORT_TYPE_QSFP:
3276 	case FW_PORT_TYPE_CR4_QSFP:
3277 	case FW_PORT_TYPE_CR_QSFP:
3278 	case FW_PORT_TYPE_CR2_QSFP:
3279 	case FW_PORT_TYPE_SFP28:
3280 		/* Pluggable transceiver */
3281 		switch (pi->mod_type) {
3282 		case FW_PORT_MOD_TYPE_LR:
3283 			switch (speed) {
3284 			case FW_PORT_CAP32_SPEED_1G:
3285 				return (IFM_1000_LX);
3286 			case FW_PORT_CAP32_SPEED_10G:
3287 				return (IFM_10G_LR);
3288 			case FW_PORT_CAP32_SPEED_25G:
3289 				return (IFM_25G_LR);
3290 			case FW_PORT_CAP32_SPEED_40G:
3291 				return (IFM_40G_LR4);
3292 			case FW_PORT_CAP32_SPEED_50G:
3293 				return (IFM_50G_LR2);
3294 			case FW_PORT_CAP32_SPEED_100G:
3295 				return (IFM_100G_LR4);
3296 			}
3297 			break;
3298 		case FW_PORT_MOD_TYPE_SR:
3299 			switch (speed) {
3300 			case FW_PORT_CAP32_SPEED_1G:
3301 				return (IFM_1000_SX);
3302 			case FW_PORT_CAP32_SPEED_10G:
3303 				return (IFM_10G_SR);
3304 			case FW_PORT_CAP32_SPEED_25G:
3305 				return (IFM_25G_SR);
3306 			case FW_PORT_CAP32_SPEED_40G:
3307 				return (IFM_40G_SR4);
3308 			case FW_PORT_CAP32_SPEED_50G:
3309 				return (IFM_50G_SR2);
3310 			case FW_PORT_CAP32_SPEED_100G:
3311 				return (IFM_100G_SR4);
3312 			}
3313 			break;
3314 		case FW_PORT_MOD_TYPE_ER:
3315 			if (speed == FW_PORT_CAP32_SPEED_10G)
3316 				return (IFM_10G_ER);
3317 			break;
3318 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3319 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3320 			switch (speed) {
3321 			case FW_PORT_CAP32_SPEED_1G:
3322 				return (IFM_1000_CX);
3323 			case FW_PORT_CAP32_SPEED_10G:
3324 				return (IFM_10G_TWINAX);
3325 			case FW_PORT_CAP32_SPEED_25G:
3326 				return (IFM_25G_CR);
3327 			case FW_PORT_CAP32_SPEED_40G:
3328 				return (IFM_40G_CR4);
3329 			case FW_PORT_CAP32_SPEED_50G:
3330 				return (IFM_50G_CR2);
3331 			case FW_PORT_CAP32_SPEED_100G:
3332 				return (IFM_100G_CR4);
3333 			}
3334 			break;
3335 		case FW_PORT_MOD_TYPE_LRM:
3336 			if (speed == FW_PORT_CAP32_SPEED_10G)
3337 				return (IFM_10G_LRM);
3338 			break;
3339 		case FW_PORT_MOD_TYPE_NA:
3340 			MPASS(0);	/* Not pluggable? */
3341 			/* fall throough */
3342 		case FW_PORT_MOD_TYPE_ERROR:
3343 		case FW_PORT_MOD_TYPE_UNKNOWN:
3344 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3345 			break;
3346 		case FW_PORT_MOD_TYPE_NONE:
3347 			return (IFM_NONE);
3348 		}
3349 		break;
3350 	case FW_PORT_TYPE_NONE:
3351 		return (IFM_NONE);
3352 	}
3353 
3354 	return (IFM_UNKNOWN);
3355 }
3356 
3357 void
3358 cxgbe_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
3359 {
3360 	struct vi_info *vi = ifp->if_softc;
3361 	struct port_info *pi = vi->pi;
3362 	struct adapter *sc = pi->adapter;
3363 	struct link_config *lc = &pi->link_cfg;
3364 
3365 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4med") != 0)
3366 		return;
3367 	PORT_LOCK(pi);
3368 
3369 	if (pi->up_vis == 0) {
3370 		/*
3371 		 * If all the interfaces are administratively down the firmware
3372 		 * does not report transceiver changes.  Refresh port info here
3373 		 * so that ifconfig displays accurate ifmedia at all times.
3374 		 * This is the only reason we have a synchronized op in this
3375 		 * function.  Just PORT_LOCK would have been enough otherwise.
3376 		 */
3377 		t4_update_port_info(pi);
3378 		build_medialist(pi);
3379 	}
3380 
3381 	/* ifm_status */
3382 	ifmr->ifm_status = IFM_AVALID;
3383 	if (lc->link_ok == false)
3384 		goto done;
3385 	ifmr->ifm_status |= IFM_ACTIVE;
3386 
3387 	/* ifm_active */
3388 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3389 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3390 	if (lc->fc & PAUSE_RX)
3391 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3392 	if (lc->fc & PAUSE_TX)
3393 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3394 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3395 done:
3396 	PORT_UNLOCK(pi);
3397 	end_synchronized_op(sc, 0);
3398 }
3399 
3400 static int
3401 vcxgbe_probe(device_t dev)
3402 {
3403 	char buf[128];
3404 	struct vi_info *vi = device_get_softc(dev);
3405 
3406 	snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
3407 	    vi - vi->pi->vi);
3408 	device_set_desc_copy(dev, buf);
3409 
3410 	return (BUS_PROBE_DEFAULT);
3411 }
3412 
3413 static int
3414 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3415 {
3416 	int func, index, rc;
3417 	uint32_t param, val;
3418 
3419 	ASSERT_SYNCHRONIZED_OP(sc);
3420 
3421 	index = vi - pi->vi;
3422 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3423 	KASSERT(index < nitems(vi_mac_funcs),
3424 	    ("%s: VI %s doesn't have a MAC func", __func__,
3425 	    device_get_nameunit(vi->dev)));
3426 	func = vi_mac_funcs[index];
3427 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3428 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3429 	if (rc < 0) {
3430 		CH_ERR(vi, "failed to allocate virtual interface %d"
3431 		    "for port %d: %d\n", index, pi->port_id, -rc);
3432 		return (-rc);
3433 	}
3434 	vi->viid = rc;
3435 
3436 	if (vi->rss_size == 1) {
3437 		/*
3438 		 * This VI didn't get a slice of the RSS table.  Reduce the
3439 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3440 		 * configuration file (nvi, rssnvi for this PF) if this is a
3441 		 * problem.
3442 		 */
3443 		device_printf(vi->dev, "RSS table not available.\n");
3444 		vi->rss_base = 0xffff;
3445 
3446 		return (0);
3447 	}
3448 
3449 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3450 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3451 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3452 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3453 	if (rc)
3454 		vi->rss_base = 0xffff;
3455 	else {
3456 		MPASS((val >> 16) == vi->rss_size);
3457 		vi->rss_base = val & 0xffff;
3458 	}
3459 
3460 	return (0);
3461 }
3462 
3463 static int
3464 vcxgbe_attach(device_t dev)
3465 {
3466 	struct vi_info *vi;
3467 	struct port_info *pi;
3468 	struct adapter *sc;
3469 	int rc;
3470 
3471 	vi = device_get_softc(dev);
3472 	pi = vi->pi;
3473 	sc = pi->adapter;
3474 
3475 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3476 	if (rc)
3477 		return (rc);
3478 	rc = alloc_extra_vi(sc, pi, vi);
3479 	end_synchronized_op(sc, 0);
3480 	if (rc)
3481 		return (rc);
3482 
3483 	rc = cxgbe_vi_attach(dev, vi);
3484 	if (rc) {
3485 		t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3486 		return (rc);
3487 	}
3488 	return (0);
3489 }
3490 
3491 static int
3492 vcxgbe_detach(device_t dev)
3493 {
3494 	struct vi_info *vi;
3495 	struct adapter *sc;
3496 
3497 	vi = device_get_softc(dev);
3498 	sc = vi->adapter;
3499 
3500 	doom_vi(sc, vi);
3501 
3502 	cxgbe_vi_detach(vi);
3503 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3504 
3505 	end_synchronized_op(sc, 0);
3506 
3507 	return (0);
3508 }
3509 
3510 static struct callout fatal_callout;
3511 static struct taskqueue *reset_tq;
3512 
3513 static void
3514 delayed_panic(void *arg)
3515 {
3516 	struct adapter *sc = arg;
3517 
3518 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3519 }
3520 
3521 void
3522 t4_fatal_err(struct adapter *sc, bool fw_error)
3523 {
3524 
3525 	t4_shutdown_adapter(sc);
3526 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped.\n",
3527 	    device_get_nameunit(sc->dev));
3528 	if (fw_error) {
3529 		if (sc->flags & CHK_MBOX_ACCESS)
3530 			ASSERT_SYNCHRONIZED_OP(sc);
3531 		sc->flags |= ADAP_ERR;
3532 	} else {
3533 		ADAPTER_LOCK(sc);
3534 		sc->flags |= ADAP_ERR;
3535 		ADAPTER_UNLOCK(sc);
3536 	}
3537 #ifdef TCP_OFFLOAD
3538 	taskqueue_enqueue(taskqueue_thread, &sc->async_event_task);
3539 #endif
3540 
3541 	if (t4_panic_on_fatal_err) {
3542 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3543 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3544 	} else if (t4_reset_on_fatal_err) {
3545 		CH_ALERT(sc, "resetting on fatal error.\n");
3546 		taskqueue_enqueue(reset_tq, &sc->reset_task);
3547 	}
3548 }
3549 
3550 void
3551 t4_add_adapter(struct adapter *sc)
3552 {
3553 	sx_xlock(&t4_list_lock);
3554 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3555 	sx_xunlock(&t4_list_lock);
3556 }
3557 
3558 int
3559 t4_map_bars_0_and_4(struct adapter *sc)
3560 {
3561 	sc->regs_rid = PCIR_BAR(0);
3562 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3563 	    &sc->regs_rid, RF_ACTIVE);
3564 	if (sc->regs_res == NULL) {
3565 		device_printf(sc->dev, "cannot map registers.\n");
3566 		return (ENXIO);
3567 	}
3568 	sc->bt = rman_get_bustag(sc->regs_res);
3569 	sc->bh = rman_get_bushandle(sc->regs_res);
3570 	sc->mmio_len = rman_get_size(sc->regs_res);
3571 	setbit(&sc->doorbells, DOORBELL_KDB);
3572 
3573 	sc->msix_rid = PCIR_BAR(4);
3574 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3575 	    &sc->msix_rid, RF_ACTIVE);
3576 	if (sc->msix_res == NULL) {
3577 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3578 		return (ENXIO);
3579 	}
3580 
3581 	return (0);
3582 }
3583 
3584 int
3585 t4_map_bar_2(struct adapter *sc)
3586 {
3587 
3588 	/*
3589 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3590 	 * to map it if RDMA is disabled.
3591 	 */
3592 	if (is_t4(sc) && sc->rdmacaps == 0)
3593 		return (0);
3594 
3595 	sc->udbs_rid = PCIR_BAR(2);
3596 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3597 	    &sc->udbs_rid, RF_ACTIVE);
3598 	if (sc->udbs_res == NULL) {
3599 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3600 		return (ENXIO);
3601 	}
3602 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3603 
3604 	if (chip_id(sc) >= CHELSIO_T5) {
3605 		setbit(&sc->doorbells, DOORBELL_UDB);
3606 #if defined(__i386__) || defined(__amd64__)
3607 		if (t5_write_combine) {
3608 			int rc, mode;
3609 
3610 			/*
3611 			 * Enable write combining on BAR2.  This is the
3612 			 * userspace doorbell BAR and is split into 128B
3613 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3614 			 * with an egress queue.  The first 64B has the doorbell
3615 			 * and the second 64B can be used to submit a tx work
3616 			 * request with an implicit doorbell.
3617 			 */
3618 
3619 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3620 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3621 			if (rc == 0) {
3622 				clrbit(&sc->doorbells, DOORBELL_UDB);
3623 				setbit(&sc->doorbells, DOORBELL_WCWR);
3624 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3625 			} else {
3626 				device_printf(sc->dev,
3627 				    "couldn't enable write combining: %d\n",
3628 				    rc);
3629 			}
3630 
3631 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3632 			t4_write_reg(sc, A_SGE_STAT_CFG,
3633 			    V_STATSOURCE_T5(7) | mode);
3634 		}
3635 #endif
3636 	}
3637 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3638 
3639 	return (0);
3640 }
3641 
3642 struct memwin_init {
3643 	uint32_t base;
3644 	uint32_t aperture;
3645 };
3646 
3647 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3648 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3649 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3650 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3651 };
3652 
3653 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3654 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3655 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3656 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3657 };
3658 
3659 static void
3660 setup_memwin(struct adapter *sc)
3661 {
3662 	const struct memwin_init *mw_init;
3663 	struct memwin *mw;
3664 	int i;
3665 	uint32_t bar0;
3666 
3667 	if (is_t4(sc)) {
3668 		/*
3669 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3670 		 * mechanism.  Works from within PCI passthrough environments
3671 		 * too, where rman_get_start() can return a different value.  We
3672 		 * need to program the T4 memory window decoders with the actual
3673 		 * addresses that will be coming across the PCIe link.
3674 		 */
3675 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3676 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3677 
3678 		mw_init = &t4_memwin[0];
3679 	} else {
3680 		/* T5+ use the relative offset inside the PCIe BAR */
3681 		bar0 = 0;
3682 
3683 		mw_init = &t5_memwin[0];
3684 	}
3685 
3686 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3687 		if (!rw_initialized(&mw->mw_lock)) {
3688 			rw_init(&mw->mw_lock, "memory window access");
3689 			mw->mw_base = mw_init->base;
3690 			mw->mw_aperture = mw_init->aperture;
3691 			mw->mw_curpos = 0;
3692 		}
3693 		t4_write_reg(sc,
3694 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3695 		    (mw->mw_base + bar0) | V_BIR(0) |
3696 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3697 		rw_wlock(&mw->mw_lock);
3698 		position_memwin(sc, i, mw->mw_curpos);
3699 		rw_wunlock(&mw->mw_lock);
3700 	}
3701 
3702 	/* flush */
3703 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3704 }
3705 
3706 /*
3707  * Positions the memory window at the given address in the card's address space.
3708  * There are some alignment requirements and the actual position may be at an
3709  * address prior to the requested address.  mw->mw_curpos always has the actual
3710  * position of the window.
3711  */
3712 static void
3713 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3714 {
3715 	struct memwin *mw;
3716 	uint32_t pf;
3717 	uint32_t reg;
3718 
3719 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3720 	mw = &sc->memwin[idx];
3721 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3722 
3723 	if (is_t4(sc)) {
3724 		pf = 0;
3725 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3726 	} else {
3727 		pf = V_PFNUM(sc->pf);
3728 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3729 	}
3730 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3731 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3732 	t4_read_reg(sc, reg);	/* flush */
3733 }
3734 
3735 int
3736 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3737     int len, int rw)
3738 {
3739 	struct memwin *mw;
3740 	uint32_t mw_end, v;
3741 
3742 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3743 
3744 	/* Memory can only be accessed in naturally aligned 4 byte units */
3745 	if (addr & 3 || len & 3 || len <= 0)
3746 		return (EINVAL);
3747 
3748 	mw = &sc->memwin[idx];
3749 	while (len > 0) {
3750 		rw_rlock(&mw->mw_lock);
3751 		mw_end = mw->mw_curpos + mw->mw_aperture;
3752 		if (addr >= mw_end || addr < mw->mw_curpos) {
3753 			/* Will need to reposition the window */
3754 			if (!rw_try_upgrade(&mw->mw_lock)) {
3755 				rw_runlock(&mw->mw_lock);
3756 				rw_wlock(&mw->mw_lock);
3757 			}
3758 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3759 			position_memwin(sc, idx, addr);
3760 			rw_downgrade(&mw->mw_lock);
3761 			mw_end = mw->mw_curpos + mw->mw_aperture;
3762 		}
3763 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3764 		while (addr < mw_end && len > 0) {
3765 			if (rw == 0) {
3766 				v = t4_read_reg(sc, mw->mw_base + addr -
3767 				    mw->mw_curpos);
3768 				*val++ = le32toh(v);
3769 			} else {
3770 				v = *val++;
3771 				t4_write_reg(sc, mw->mw_base + addr -
3772 				    mw->mw_curpos, htole32(v));
3773 			}
3774 			addr += 4;
3775 			len -= 4;
3776 		}
3777 		rw_runlock(&mw->mw_lock);
3778 	}
3779 
3780 	return (0);
3781 }
3782 
3783 static void
3784 t4_init_atid_table(struct adapter *sc)
3785 {
3786 	struct tid_info *t;
3787 	int i;
3788 
3789 	t = &sc->tids;
3790 	if (t->natids == 0)
3791 		return;
3792 
3793 	MPASS(t->atid_tab == NULL);
3794 
3795 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3796 	    M_ZERO | M_WAITOK);
3797 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3798 	t->afree = t->atid_tab;
3799 	t->atids_in_use = 0;
3800 	for (i = 1; i < t->natids; i++)
3801 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3802 	t->atid_tab[t->natids - 1].next = NULL;
3803 }
3804 
3805 static void
3806 t4_free_atid_table(struct adapter *sc)
3807 {
3808 	struct tid_info *t;
3809 
3810 	t = &sc->tids;
3811 
3812 	KASSERT(t->atids_in_use == 0,
3813 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3814 
3815 	if (mtx_initialized(&t->atid_lock))
3816 		mtx_destroy(&t->atid_lock);
3817 	free(t->atid_tab, M_CXGBE);
3818 	t->atid_tab = NULL;
3819 }
3820 
3821 int
3822 alloc_atid(struct adapter *sc, void *ctx)
3823 {
3824 	struct tid_info *t = &sc->tids;
3825 	int atid = -1;
3826 
3827 	mtx_lock(&t->atid_lock);
3828 	if (t->afree) {
3829 		union aopen_entry *p = t->afree;
3830 
3831 		atid = p - t->atid_tab;
3832 		MPASS(atid <= M_TID_TID);
3833 		t->afree = p->next;
3834 		p->data = ctx;
3835 		t->atids_in_use++;
3836 	}
3837 	mtx_unlock(&t->atid_lock);
3838 	return (atid);
3839 }
3840 
3841 void *
3842 lookup_atid(struct adapter *sc, int atid)
3843 {
3844 	struct tid_info *t = &sc->tids;
3845 
3846 	return (t->atid_tab[atid].data);
3847 }
3848 
3849 void
3850 free_atid(struct adapter *sc, int atid)
3851 {
3852 	struct tid_info *t = &sc->tids;
3853 	union aopen_entry *p = &t->atid_tab[atid];
3854 
3855 	mtx_lock(&t->atid_lock);
3856 	p->next = t->afree;
3857 	t->afree = p;
3858 	t->atids_in_use--;
3859 	mtx_unlock(&t->atid_lock);
3860 }
3861 
3862 static void
3863 queue_tid_release(struct adapter *sc, int tid)
3864 {
3865 
3866 	CXGBE_UNIMPLEMENTED("deferred tid release");
3867 }
3868 
3869 void
3870 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
3871 {
3872 	struct wrqe *wr;
3873 	struct cpl_tid_release *req;
3874 
3875 	wr = alloc_wrqe(sizeof(*req), ctrlq);
3876 	if (wr == NULL) {
3877 		queue_tid_release(sc, tid);	/* defer */
3878 		return;
3879 	}
3880 	req = wrtod(wr);
3881 
3882 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
3883 
3884 	t4_wrq_tx(sc, wr);
3885 }
3886 
3887 static int
3888 t4_range_cmp(const void *a, const void *b)
3889 {
3890 	return ((const struct t4_range *)a)->start -
3891 	       ((const struct t4_range *)b)->start;
3892 }
3893 
3894 /*
3895  * Verify that the memory range specified by the addr/len pair is valid within
3896  * the card's address space.
3897  */
3898 static int
3899 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
3900 {
3901 	struct t4_range mem_ranges[4], *r, *next;
3902 	uint32_t em, addr_len;
3903 	int i, n, remaining;
3904 
3905 	/* Memory can only be accessed in naturally aligned 4 byte units */
3906 	if (addr & 3 || len & 3 || len == 0)
3907 		return (EINVAL);
3908 
3909 	/* Enabled memories */
3910 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
3911 
3912 	r = &mem_ranges[0];
3913 	n = 0;
3914 	bzero(r, sizeof(mem_ranges));
3915 	if (em & F_EDRAM0_ENABLE) {
3916 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
3917 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
3918 		if (r->size > 0) {
3919 			r->start = G_EDRAM0_BASE(addr_len) << 20;
3920 			if (addr >= r->start &&
3921 			    addr + len <= r->start + r->size)
3922 				return (0);
3923 			r++;
3924 			n++;
3925 		}
3926 	}
3927 	if (em & F_EDRAM1_ENABLE) {
3928 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
3929 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
3930 		if (r->size > 0) {
3931 			r->start = G_EDRAM1_BASE(addr_len) << 20;
3932 			if (addr >= r->start &&
3933 			    addr + len <= r->start + r->size)
3934 				return (0);
3935 			r++;
3936 			n++;
3937 		}
3938 	}
3939 	if (em & F_EXT_MEM_ENABLE) {
3940 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
3941 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
3942 		if (r->size > 0) {
3943 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
3944 			if (addr >= r->start &&
3945 			    addr + len <= r->start + r->size)
3946 				return (0);
3947 			r++;
3948 			n++;
3949 		}
3950 	}
3951 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
3952 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
3953 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
3954 		if (r->size > 0) {
3955 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
3956 			if (addr >= r->start &&
3957 			    addr + len <= r->start + r->size)
3958 				return (0);
3959 			r++;
3960 			n++;
3961 		}
3962 	}
3963 	MPASS(n <= nitems(mem_ranges));
3964 
3965 	if (n > 1) {
3966 		/* Sort and merge the ranges. */
3967 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
3968 
3969 		/* Start from index 0 and examine the next n - 1 entries. */
3970 		r = &mem_ranges[0];
3971 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
3972 
3973 			MPASS(r->size > 0);	/* r is a valid entry. */
3974 			next = r + 1;
3975 			MPASS(next->size > 0);	/* and so is the next one. */
3976 
3977 			while (r->start + r->size >= next->start) {
3978 				/* Merge the next one into the current entry. */
3979 				r->size = max(r->start + r->size,
3980 				    next->start + next->size) - r->start;
3981 				n--;	/* One fewer entry in total. */
3982 				if (--remaining == 0)
3983 					goto done;	/* short circuit */
3984 				next++;
3985 			}
3986 			if (next != r + 1) {
3987 				/*
3988 				 * Some entries were merged into r and next
3989 				 * points to the first valid entry that couldn't
3990 				 * be merged.
3991 				 */
3992 				MPASS(next->size > 0);	/* must be valid */
3993 				memcpy(r + 1, next, remaining * sizeof(*r));
3994 #ifdef INVARIANTS
3995 				/*
3996 				 * This so that the foo->size assertion in the
3997 				 * next iteration of the loop do the right
3998 				 * thing for entries that were pulled up and are
3999 				 * no longer valid.
4000 				 */
4001 				MPASS(n < nitems(mem_ranges));
4002 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4003 				    sizeof(struct t4_range));
4004 #endif
4005 			}
4006 		}
4007 done:
4008 		/* Done merging the ranges. */
4009 		MPASS(n > 0);
4010 		r = &mem_ranges[0];
4011 		for (i = 0; i < n; i++, r++) {
4012 			if (addr >= r->start &&
4013 			    addr + len <= r->start + r->size)
4014 				return (0);
4015 		}
4016 	}
4017 
4018 	return (EFAULT);
4019 }
4020 
4021 static int
4022 fwmtype_to_hwmtype(int mtype)
4023 {
4024 
4025 	switch (mtype) {
4026 	case FW_MEMTYPE_EDC0:
4027 		return (MEM_EDC0);
4028 	case FW_MEMTYPE_EDC1:
4029 		return (MEM_EDC1);
4030 	case FW_MEMTYPE_EXTMEM:
4031 		return (MEM_MC0);
4032 	case FW_MEMTYPE_EXTMEM1:
4033 		return (MEM_MC1);
4034 	default:
4035 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4036 	}
4037 }
4038 
4039 /*
4040  * Verify that the memory range specified by the memtype/offset/len pair is
4041  * valid and lies entirely within the memtype specified.  The global address of
4042  * the start of the range is returned in addr.
4043  */
4044 static int
4045 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4046     uint32_t *addr)
4047 {
4048 	uint32_t em, addr_len, maddr;
4049 
4050 	/* Memory can only be accessed in naturally aligned 4 byte units */
4051 	if (off & 3 || len & 3 || len == 0)
4052 		return (EINVAL);
4053 
4054 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4055 	switch (fwmtype_to_hwmtype(mtype)) {
4056 	case MEM_EDC0:
4057 		if (!(em & F_EDRAM0_ENABLE))
4058 			return (EINVAL);
4059 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4060 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4061 		break;
4062 	case MEM_EDC1:
4063 		if (!(em & F_EDRAM1_ENABLE))
4064 			return (EINVAL);
4065 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4066 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4067 		break;
4068 	case MEM_MC:
4069 		if (!(em & F_EXT_MEM_ENABLE))
4070 			return (EINVAL);
4071 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4072 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4073 		break;
4074 	case MEM_MC1:
4075 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4076 			return (EINVAL);
4077 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4078 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4079 		break;
4080 	default:
4081 		return (EINVAL);
4082 	}
4083 
4084 	*addr = maddr + off;	/* global address */
4085 	return (validate_mem_range(sc, *addr, len));
4086 }
4087 
4088 static int
4089 fixup_devlog_params(struct adapter *sc)
4090 {
4091 	struct devlog_params *dparams = &sc->params.devlog;
4092 	int rc;
4093 
4094 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4095 	    dparams->size, &dparams->addr);
4096 
4097 	return (rc);
4098 }
4099 
4100 static void
4101 update_nirq(struct intrs_and_queues *iaq, int nports)
4102 {
4103 
4104 	iaq->nirq = T4_EXTRA_INTR;
4105 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4106 	iaq->nirq += nports * iaq->nofldrxq;
4107 	iaq->nirq += nports * (iaq->num_vis - 1) *
4108 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4109 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4110 }
4111 
4112 /*
4113  * Adjust requirements to fit the number of interrupts available.
4114  */
4115 static void
4116 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4117     int navail)
4118 {
4119 	int old_nirq;
4120 	const int nports = sc->params.nports;
4121 
4122 	MPASS(nports > 0);
4123 	MPASS(navail > 0);
4124 
4125 	bzero(iaq, sizeof(*iaq));
4126 	iaq->intr_type = itype;
4127 	iaq->num_vis = t4_num_vis;
4128 	iaq->ntxq = t4_ntxq;
4129 	iaq->ntxq_vi = t4_ntxq_vi;
4130 	iaq->nrxq = t4_nrxq;
4131 	iaq->nrxq_vi = t4_nrxq_vi;
4132 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4133 	if (is_offload(sc) || is_ethoffload(sc)) {
4134 		iaq->nofldtxq = t4_nofldtxq;
4135 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4136 	}
4137 #endif
4138 #ifdef TCP_OFFLOAD
4139 	if (is_offload(sc)) {
4140 		iaq->nofldrxq = t4_nofldrxq;
4141 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4142 	}
4143 #endif
4144 #ifdef DEV_NETMAP
4145 	if (t4_native_netmap & NN_MAIN_VI) {
4146 		iaq->nnmtxq = t4_nnmtxq;
4147 		iaq->nnmrxq = t4_nnmrxq;
4148 	}
4149 	if (t4_native_netmap & NN_EXTRA_VI) {
4150 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4151 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4152 	}
4153 #endif
4154 
4155 	update_nirq(iaq, nports);
4156 	if (iaq->nirq <= navail &&
4157 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4158 		/*
4159 		 * This is the normal case -- there are enough interrupts for
4160 		 * everything.
4161 		 */
4162 		goto done;
4163 	}
4164 
4165 	/*
4166 	 * If extra VIs have been configured try reducing their count and see if
4167 	 * that works.
4168 	 */
4169 	while (iaq->num_vis > 1) {
4170 		iaq->num_vis--;
4171 		update_nirq(iaq, nports);
4172 		if (iaq->nirq <= navail &&
4173 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4174 			device_printf(sc->dev, "virtual interfaces per port "
4175 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4176 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4177 			    "itype %d, navail %u, nirq %d.\n",
4178 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4179 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4180 			    itype, navail, iaq->nirq);
4181 			goto done;
4182 		}
4183 	}
4184 
4185 	/*
4186 	 * Extra VIs will not be created.  Log a message if they were requested.
4187 	 */
4188 	MPASS(iaq->num_vis == 1);
4189 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4190 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4191 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4192 	if (iaq->num_vis != t4_num_vis) {
4193 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4194 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4195 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4196 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4197 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4198 	}
4199 
4200 	/*
4201 	 * Keep reducing the number of NIC rx queues to the next lower power of
4202 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4203 	 * if that works.
4204 	 */
4205 	do {
4206 		if (iaq->nrxq > 1) {
4207 			do {
4208 				iaq->nrxq--;
4209 			} while (!powerof2(iaq->nrxq));
4210 			if (iaq->nnmrxq > iaq->nrxq)
4211 				iaq->nnmrxq = iaq->nrxq;
4212 		}
4213 		if (iaq->nofldrxq > 1)
4214 			iaq->nofldrxq >>= 1;
4215 
4216 		old_nirq = iaq->nirq;
4217 		update_nirq(iaq, nports);
4218 		if (iaq->nirq <= navail &&
4219 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4220 			device_printf(sc->dev, "running with reduced number of "
4221 			    "rx queues because of shortage of interrupts.  "
4222 			    "nrxq=%u, nofldrxq=%u.  "
4223 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4224 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4225 			goto done;
4226 		}
4227 	} while (old_nirq != iaq->nirq);
4228 
4229 	/* One interrupt for everything.  Ugh. */
4230 	device_printf(sc->dev, "running with minimal number of queues.  "
4231 	    "itype %d, navail %u.\n", itype, navail);
4232 	iaq->nirq = 1;
4233 	iaq->nrxq = 1;
4234 	iaq->ntxq = 1;
4235 	if (iaq->nofldrxq > 0) {
4236 		iaq->nofldrxq = 1;
4237 		iaq->nofldtxq = 1;
4238 	}
4239 	iaq->nnmtxq = 0;
4240 	iaq->nnmrxq = 0;
4241 done:
4242 	MPASS(iaq->num_vis > 0);
4243 	if (iaq->num_vis > 1) {
4244 		MPASS(iaq->nrxq_vi > 0);
4245 		MPASS(iaq->ntxq_vi > 0);
4246 	}
4247 	MPASS(iaq->nirq > 0);
4248 	MPASS(iaq->nrxq > 0);
4249 	MPASS(iaq->ntxq > 0);
4250 	if (itype == INTR_MSI) {
4251 		MPASS(powerof2(iaq->nirq));
4252 	}
4253 }
4254 
4255 static int
4256 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4257 {
4258 	int rc, itype, navail, nalloc;
4259 
4260 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4261 
4262 		if ((itype & t4_intr_types) == 0)
4263 			continue;	/* not allowed */
4264 
4265 		if (itype == INTR_MSIX)
4266 			navail = pci_msix_count(sc->dev);
4267 		else if (itype == INTR_MSI)
4268 			navail = pci_msi_count(sc->dev);
4269 		else
4270 			navail = 1;
4271 restart:
4272 		if (navail == 0)
4273 			continue;
4274 
4275 		calculate_iaq(sc, iaq, itype, navail);
4276 		nalloc = iaq->nirq;
4277 		rc = 0;
4278 		if (itype == INTR_MSIX)
4279 			rc = pci_alloc_msix(sc->dev, &nalloc);
4280 		else if (itype == INTR_MSI)
4281 			rc = pci_alloc_msi(sc->dev, &nalloc);
4282 
4283 		if (rc == 0 && nalloc > 0) {
4284 			if (nalloc == iaq->nirq)
4285 				return (0);
4286 
4287 			/*
4288 			 * Didn't get the number requested.  Use whatever number
4289 			 * the kernel is willing to allocate.
4290 			 */
4291 			device_printf(sc->dev, "fewer vectors than requested, "
4292 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4293 			    itype, iaq->nirq, nalloc);
4294 			pci_release_msi(sc->dev);
4295 			navail = nalloc;
4296 			goto restart;
4297 		}
4298 
4299 		device_printf(sc->dev,
4300 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4301 		    itype, rc, iaq->nirq, nalloc);
4302 	}
4303 
4304 	device_printf(sc->dev,
4305 	    "failed to find a usable interrupt type.  "
4306 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4307 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4308 
4309 	return (ENXIO);
4310 }
4311 
4312 #define FW_VERSION(chip) ( \
4313     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4314     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4315     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4316     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4317 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4318 
4319 /* Just enough of fw_hdr to cover all version info. */
4320 struct fw_h {
4321 	__u8	ver;
4322 	__u8	chip;
4323 	__be16	len512;
4324 	__be32	fw_ver;
4325 	__be32	tp_microcode_ver;
4326 	__u8	intfver_nic;
4327 	__u8	intfver_vnic;
4328 	__u8	intfver_ofld;
4329 	__u8	intfver_ri;
4330 	__u8	intfver_iscsipdu;
4331 	__u8	intfver_iscsi;
4332 	__u8	intfver_fcoepdu;
4333 	__u8	intfver_fcoe;
4334 };
4335 /* Spot check a couple of fields. */
4336 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4337 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4338 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4339 
4340 struct fw_info {
4341 	uint8_t chip;
4342 	char *kld_name;
4343 	char *fw_mod_name;
4344 	struct fw_h fw_h;
4345 } fw_info[] = {
4346 	{
4347 		.chip = CHELSIO_T4,
4348 		.kld_name = "t4fw_cfg",
4349 		.fw_mod_name = "t4fw",
4350 		.fw_h = {
4351 			.chip = FW_HDR_CHIP_T4,
4352 			.fw_ver = htobe32(FW_VERSION(T4)),
4353 			.intfver_nic = FW_INTFVER(T4, NIC),
4354 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4355 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4356 			.intfver_ri = FW_INTFVER(T4, RI),
4357 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4358 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4359 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4360 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4361 		},
4362 	}, {
4363 		.chip = CHELSIO_T5,
4364 		.kld_name = "t5fw_cfg",
4365 		.fw_mod_name = "t5fw",
4366 		.fw_h = {
4367 			.chip = FW_HDR_CHIP_T5,
4368 			.fw_ver = htobe32(FW_VERSION(T5)),
4369 			.intfver_nic = FW_INTFVER(T5, NIC),
4370 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4371 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4372 			.intfver_ri = FW_INTFVER(T5, RI),
4373 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4374 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4375 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4376 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4377 		},
4378 	}, {
4379 		.chip = CHELSIO_T6,
4380 		.kld_name = "t6fw_cfg",
4381 		.fw_mod_name = "t6fw",
4382 		.fw_h = {
4383 			.chip = FW_HDR_CHIP_T6,
4384 			.fw_ver = htobe32(FW_VERSION(T6)),
4385 			.intfver_nic = FW_INTFVER(T6, NIC),
4386 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4387 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4388 			.intfver_ri = FW_INTFVER(T6, RI),
4389 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4390 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4391 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4392 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4393 		},
4394 	}
4395 };
4396 
4397 static struct fw_info *
4398 find_fw_info(int chip)
4399 {
4400 	int i;
4401 
4402 	for (i = 0; i < nitems(fw_info); i++) {
4403 		if (fw_info[i].chip == chip)
4404 			return (&fw_info[i]);
4405 	}
4406 	return (NULL);
4407 }
4408 
4409 /*
4410  * Is the given firmware API compatible with the one the driver was compiled
4411  * with?
4412  */
4413 static int
4414 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4415 {
4416 
4417 	/* short circuit if it's the exact same firmware version */
4418 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4419 		return (1);
4420 
4421 	/*
4422 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4423 	 * features that are supported in the driver.
4424 	 */
4425 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4426 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4427 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4428 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4429 		return (1);
4430 #undef SAME_INTF
4431 
4432 	return (0);
4433 }
4434 
4435 static int
4436 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4437     const struct firmware **fw)
4438 {
4439 	struct fw_info *fw_info;
4440 
4441 	*dcfg = NULL;
4442 	if (fw != NULL)
4443 		*fw = NULL;
4444 
4445 	fw_info = find_fw_info(chip_id(sc));
4446 	if (fw_info == NULL) {
4447 		device_printf(sc->dev,
4448 		    "unable to look up firmware information for chip %d.\n",
4449 		    chip_id(sc));
4450 		return (EINVAL);
4451 	}
4452 
4453 	*dcfg = firmware_get(fw_info->kld_name);
4454 	if (*dcfg != NULL) {
4455 		if (fw != NULL)
4456 			*fw = firmware_get(fw_info->fw_mod_name);
4457 		return (0);
4458 	}
4459 
4460 	return (ENOENT);
4461 }
4462 
4463 static void
4464 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4465     const struct firmware *fw)
4466 {
4467 
4468 	if (fw != NULL)
4469 		firmware_put(fw, FIRMWARE_UNLOAD);
4470 	if (dcfg != NULL)
4471 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4472 }
4473 
4474 /*
4475  * Return values:
4476  * 0 means no firmware install attempted.
4477  * ERESTART means a firmware install was attempted and was successful.
4478  * +ve errno means a firmware install was attempted but failed.
4479  */
4480 static int
4481 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4482     const struct fw_h *drv_fw, const char *reason, int *already)
4483 {
4484 	const struct firmware *cfg, *fw;
4485 	const uint32_t c = be32toh(card_fw->fw_ver);
4486 	uint32_t d, k;
4487 	int rc, fw_install;
4488 	struct fw_h bundled_fw;
4489 	bool load_attempted;
4490 
4491 	cfg = fw = NULL;
4492 	load_attempted = false;
4493 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4494 
4495 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4496 	if (t4_fw_install < 0) {
4497 		rc = load_fw_module(sc, &cfg, &fw);
4498 		if (rc != 0 || fw == NULL) {
4499 			device_printf(sc->dev,
4500 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4501 			    " will use compiled-in firmware version for"
4502 			    "hw.cxgbe.fw_install checks.\n",
4503 			    rc, cfg, fw);
4504 		} else {
4505 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4506 		}
4507 		load_attempted = true;
4508 	}
4509 	d = be32toh(bundled_fw.fw_ver);
4510 
4511 	if (reason != NULL)
4512 		goto install;
4513 
4514 	if ((sc->flags & FW_OK) == 0) {
4515 
4516 		if (c == 0xffffffff) {
4517 			reason = "missing";
4518 			goto install;
4519 		}
4520 
4521 		rc = 0;
4522 		goto done;
4523 	}
4524 
4525 	if (!fw_compatible(card_fw, &bundled_fw)) {
4526 		reason = "incompatible or unusable";
4527 		goto install;
4528 	}
4529 
4530 	if (d > c) {
4531 		reason = "older than the version bundled with this driver";
4532 		goto install;
4533 	}
4534 
4535 	if (fw_install == 2 && d != c) {
4536 		reason = "different than the version bundled with this driver";
4537 		goto install;
4538 	}
4539 
4540 	/* No reason to do anything to the firmware already on the card. */
4541 	rc = 0;
4542 	goto done;
4543 
4544 install:
4545 	rc = 0;
4546 	if ((*already)++)
4547 		goto done;
4548 
4549 	if (fw_install == 0) {
4550 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4551 		    "but the driver is prohibited from installing a firmware "
4552 		    "on the card.\n",
4553 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4554 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4555 
4556 		goto done;
4557 	}
4558 
4559 	/*
4560 	 * We'll attempt to install a firmware.  Load the module first (if it
4561 	 * hasn't been loaded already).
4562 	 */
4563 	if (!load_attempted) {
4564 		rc = load_fw_module(sc, &cfg, &fw);
4565 		if (rc != 0 || fw == NULL) {
4566 			device_printf(sc->dev,
4567 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4568 			    rc, cfg, fw);
4569 			/* carry on */
4570 		}
4571 	}
4572 	if (fw == NULL) {
4573 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4574 		    "but the driver cannot take corrective action because it "
4575 		    "is unable to load the firmware module.\n",
4576 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4577 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4578 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4579 		goto done;
4580 	}
4581 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4582 	if (k != d) {
4583 		MPASS(t4_fw_install > 0);
4584 		device_printf(sc->dev,
4585 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4586 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4587 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4588 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4589 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4590 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4591 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4592 		goto done;
4593 	}
4594 
4595 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4596 	    "installing firmware %u.%u.%u.%u on card.\n",
4597 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4598 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4599 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4600 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4601 
4602 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4603 	if (rc != 0) {
4604 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4605 	} else {
4606 		/* Installed successfully, update the cached header too. */
4607 		rc = ERESTART;
4608 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4609 	}
4610 done:
4611 	unload_fw_module(sc, cfg, fw);
4612 
4613 	return (rc);
4614 }
4615 
4616 /*
4617  * Establish contact with the firmware and attempt to become the master driver.
4618  *
4619  * A firmware will be installed to the card if needed (if the driver is allowed
4620  * to do so).
4621  */
4622 static int
4623 contact_firmware(struct adapter *sc)
4624 {
4625 	int rc, already = 0;
4626 	enum dev_state state;
4627 	struct fw_info *fw_info;
4628 	struct fw_hdr *card_fw;		/* fw on the card */
4629 	const struct fw_h *drv_fw;
4630 
4631 	fw_info = find_fw_info(chip_id(sc));
4632 	if (fw_info == NULL) {
4633 		device_printf(sc->dev,
4634 		    "unable to look up firmware information for chip %d.\n",
4635 		    chip_id(sc));
4636 		return (EINVAL);
4637 	}
4638 	drv_fw = &fw_info->fw_h;
4639 
4640 	/* Read the header of the firmware on the card */
4641 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4642 restart:
4643 	rc = -t4_get_fw_hdr(sc, card_fw);
4644 	if (rc != 0) {
4645 		device_printf(sc->dev,
4646 		    "unable to read firmware header from card's flash: %d\n",
4647 		    rc);
4648 		goto done;
4649 	}
4650 
4651 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4652 	    &already);
4653 	if (rc == ERESTART)
4654 		goto restart;
4655 	if (rc != 0)
4656 		goto done;
4657 
4658 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4659 	if (rc < 0 || state == DEV_STATE_ERR) {
4660 		rc = -rc;
4661 		device_printf(sc->dev,
4662 		    "failed to connect to the firmware: %d, %d.  "
4663 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4664 #if 0
4665 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4666 		    "not responding properly to HELLO", &already) == ERESTART)
4667 			goto restart;
4668 #endif
4669 		goto done;
4670 	}
4671 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4672 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4673 
4674 	if (rc == sc->pf) {
4675 		sc->flags |= MASTER_PF;
4676 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4677 		    NULL, &already);
4678 		if (rc == ERESTART)
4679 			rc = 0;
4680 		else if (rc != 0)
4681 			goto done;
4682 	} else if (state == DEV_STATE_UNINIT) {
4683 		/*
4684 		 * We didn't get to be the master so we definitely won't be
4685 		 * configuring the chip.  It's a bug if someone else hasn't
4686 		 * configured it already.
4687 		 */
4688 		device_printf(sc->dev, "couldn't be master(%d), "
4689 		    "device not already initialized either(%d).  "
4690 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4691 		rc = EPROTO;
4692 		goto done;
4693 	} else {
4694 		/*
4695 		 * Some other PF is the master and has configured the chip.
4696 		 * This is allowed but untested.
4697 		 */
4698 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4699 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4700 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4701 		sc->cfcsum = 0;
4702 		rc = 0;
4703 	}
4704 done:
4705 	if (rc != 0 && sc->flags & FW_OK) {
4706 		t4_fw_bye(sc, sc->mbox);
4707 		sc->flags &= ~FW_OK;
4708 	}
4709 	free(card_fw, M_CXGBE);
4710 	return (rc);
4711 }
4712 
4713 static int
4714 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4715     uint32_t mtype, uint32_t moff)
4716 {
4717 	struct fw_info *fw_info;
4718 	const struct firmware *dcfg, *rcfg = NULL;
4719 	const uint32_t *cfdata;
4720 	uint32_t cflen, addr;
4721 	int rc;
4722 
4723 	load_fw_module(sc, &dcfg, NULL);
4724 
4725 	/* Card specific interpretation of "default". */
4726 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4727 		if (pci_get_device(sc->dev) == 0x440a)
4728 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4729 		if (is_fpga(sc))
4730 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4731 	}
4732 
4733 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4734 		if (dcfg == NULL) {
4735 			device_printf(sc->dev,
4736 			    "KLD with default config is not available.\n");
4737 			rc = ENOENT;
4738 			goto done;
4739 		}
4740 		cfdata = dcfg->data;
4741 		cflen = dcfg->datasize & ~3;
4742 	} else {
4743 		char s[32];
4744 
4745 		fw_info = find_fw_info(chip_id(sc));
4746 		if (fw_info == NULL) {
4747 			device_printf(sc->dev,
4748 			    "unable to look up firmware information for chip %d.\n",
4749 			    chip_id(sc));
4750 			rc = EINVAL;
4751 			goto done;
4752 		}
4753 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4754 
4755 		rcfg = firmware_get(s);
4756 		if (rcfg == NULL) {
4757 			device_printf(sc->dev,
4758 			    "unable to load module \"%s\" for configuration "
4759 			    "profile \"%s\".\n", s, cfg_file);
4760 			rc = ENOENT;
4761 			goto done;
4762 		}
4763 		cfdata = rcfg->data;
4764 		cflen = rcfg->datasize & ~3;
4765 	}
4766 
4767 	if (cflen > FLASH_CFG_MAX_SIZE) {
4768 		device_printf(sc->dev,
4769 		    "config file too long (%d, max allowed is %d).\n",
4770 		    cflen, FLASH_CFG_MAX_SIZE);
4771 		rc = EINVAL;
4772 		goto done;
4773 	}
4774 
4775 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4776 	if (rc != 0) {
4777 		device_printf(sc->dev,
4778 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4779 		    __func__, mtype, moff, cflen, rc);
4780 		rc = EINVAL;
4781 		goto done;
4782 	}
4783 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4784 done:
4785 	if (rcfg != NULL)
4786 		firmware_put(rcfg, FIRMWARE_UNLOAD);
4787 	unload_fw_module(sc, dcfg, NULL);
4788 	return (rc);
4789 }
4790 
4791 struct caps_allowed {
4792 	uint16_t nbmcaps;
4793 	uint16_t linkcaps;
4794 	uint16_t switchcaps;
4795 	uint16_t niccaps;
4796 	uint16_t toecaps;
4797 	uint16_t rdmacaps;
4798 	uint16_t cryptocaps;
4799 	uint16_t iscsicaps;
4800 	uint16_t fcoecaps;
4801 };
4802 
4803 #define FW_PARAM_DEV(param) \
4804 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4805 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4806 #define FW_PARAM_PFVF(param) \
4807 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4808 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4809 
4810 /*
4811  * Provide a configuration profile to the firmware and have it initialize the
4812  * chip accordingly.  This may involve uploading a configuration file to the
4813  * card.
4814  */
4815 static int
4816 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4817     const struct caps_allowed *caps_allowed)
4818 {
4819 	int rc;
4820 	struct fw_caps_config_cmd caps;
4821 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
4822 
4823 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4824 	if (rc != 0) {
4825 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
4826 		return (rc);
4827 	}
4828 
4829 	bzero(&caps, sizeof(caps));
4830 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4831 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
4832 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
4833 		mtype = 0;
4834 		moff = 0;
4835 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4836 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
4837 		mtype = FW_MEMTYPE_FLASH;
4838 		moff = t4_flash_cfg_addr(sc);
4839 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4840 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4841 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4842 		    FW_LEN16(caps));
4843 	} else {
4844 		/*
4845 		 * Ask the firmware where it wants us to upload the config file.
4846 		 */
4847 		param = FW_PARAM_DEV(CF);
4848 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4849 		if (rc != 0) {
4850 			/* No support for config file?  Shouldn't happen. */
4851 			device_printf(sc->dev,
4852 			    "failed to query config file location: %d.\n", rc);
4853 			goto done;
4854 		}
4855 		mtype = G_FW_PARAMS_PARAM_Y(val);
4856 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
4857 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4858 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4859 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4860 		    FW_LEN16(caps));
4861 
4862 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
4863 		if (rc != 0) {
4864 			device_printf(sc->dev,
4865 			    "failed to upload config file to card: %d.\n", rc);
4866 			goto done;
4867 		}
4868 	}
4869 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
4870 	if (rc != 0) {
4871 		device_printf(sc->dev, "failed to pre-process config file: %d "
4872 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
4873 		goto done;
4874 	}
4875 
4876 	finicsum = be32toh(caps.finicsum);
4877 	cfcsum = be32toh(caps.cfcsum);	/* actual */
4878 	if (finicsum != cfcsum) {
4879 		device_printf(sc->dev,
4880 		    "WARNING: config file checksum mismatch: %08x %08x\n",
4881 		    finicsum, cfcsum);
4882 	}
4883 	sc->cfcsum = cfcsum;
4884 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
4885 
4886 	/*
4887 	 * Let the firmware know what features will (not) be used so it can tune
4888 	 * things accordingly.
4889 	 */
4890 #define LIMIT_CAPS(x) do { \
4891 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
4892 } while (0)
4893 	LIMIT_CAPS(nbm);
4894 	LIMIT_CAPS(link);
4895 	LIMIT_CAPS(switch);
4896 	LIMIT_CAPS(nic);
4897 	LIMIT_CAPS(toe);
4898 	LIMIT_CAPS(rdma);
4899 	LIMIT_CAPS(crypto);
4900 	LIMIT_CAPS(iscsi);
4901 	LIMIT_CAPS(fcoe);
4902 #undef LIMIT_CAPS
4903 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
4904 		/*
4905 		 * TOE and hashfilters are mutually exclusive.  It is a config
4906 		 * file or firmware bug if both are reported as available.  Try
4907 		 * to cope with the situation in non-debug builds by disabling
4908 		 * TOE.
4909 		 */
4910 		MPASS(caps.toecaps == 0);
4911 
4912 		caps.toecaps = 0;
4913 		caps.rdmacaps = 0;
4914 		caps.iscsicaps = 0;
4915 	}
4916 
4917 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4918 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
4919 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4920 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
4921 	if (rc != 0) {
4922 		device_printf(sc->dev,
4923 		    "failed to process config file: %d.\n", rc);
4924 		goto done;
4925 	}
4926 
4927 	t4_tweak_chip_settings(sc);
4928 	set_params__pre_init(sc);
4929 
4930 	/* get basic stuff going */
4931 	rc = -t4_fw_initialize(sc, sc->mbox);
4932 	if (rc != 0) {
4933 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
4934 		goto done;
4935 	}
4936 done:
4937 	return (rc);
4938 }
4939 
4940 /*
4941  * Partition chip resources for use between various PFs, VFs, etc.
4942  */
4943 static int
4944 partition_resources(struct adapter *sc)
4945 {
4946 	char cfg_file[sizeof(t4_cfg_file)];
4947 	struct caps_allowed caps_allowed;
4948 	int rc;
4949 	bool fallback;
4950 
4951 	/* Only the master driver gets to configure the chip resources. */
4952 	MPASS(sc->flags & MASTER_PF);
4953 
4954 #define COPY_CAPS(x) do { \
4955 	caps_allowed.x##caps = t4_##x##caps_allowed; \
4956 } while (0)
4957 	bzero(&caps_allowed, sizeof(caps_allowed));
4958 	COPY_CAPS(nbm);
4959 	COPY_CAPS(link);
4960 	COPY_CAPS(switch);
4961 	COPY_CAPS(nic);
4962 	COPY_CAPS(toe);
4963 	COPY_CAPS(rdma);
4964 	COPY_CAPS(crypto);
4965 	COPY_CAPS(iscsi);
4966 	COPY_CAPS(fcoe);
4967 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
4968 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
4969 retry:
4970 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
4971 	if (rc != 0 && fallback) {
4972 		device_printf(sc->dev,
4973 		    "failed (%d) to configure card with \"%s\" profile, "
4974 		    "will fall back to a basic configuration and retry.\n",
4975 		    rc, cfg_file);
4976 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
4977 		bzero(&caps_allowed, sizeof(caps_allowed));
4978 		COPY_CAPS(switch);
4979 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
4980 		fallback = false;
4981 		goto retry;
4982 	}
4983 #undef COPY_CAPS
4984 	return (rc);
4985 }
4986 
4987 /*
4988  * Retrieve parameters that are needed (or nice to have) very early.
4989  */
4990 static int
4991 get_params__pre_init(struct adapter *sc)
4992 {
4993 	int rc;
4994 	uint32_t param[2], val[2];
4995 
4996 	t4_get_version_info(sc);
4997 
4998 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
4999 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5000 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5001 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5002 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5003 
5004 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5005 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5006 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5007 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5008 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5009 
5010 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5011 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5012 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5013 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5014 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5015 
5016 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5017 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5018 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5019 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5020 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5021 
5022 	param[0] = FW_PARAM_DEV(PORTVEC);
5023 	param[1] = FW_PARAM_DEV(CCLK);
5024 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5025 	if (rc != 0) {
5026 		device_printf(sc->dev,
5027 		    "failed to query parameters (pre_init): %d.\n", rc);
5028 		return (rc);
5029 	}
5030 
5031 	sc->params.portvec = val[0];
5032 	sc->params.nports = bitcount32(val[0]);
5033 	sc->params.vpd.cclk = val[1];
5034 
5035 	/* Read device log parameters. */
5036 	rc = -t4_init_devlog_params(sc, 1);
5037 	if (rc == 0)
5038 		fixup_devlog_params(sc);
5039 	else {
5040 		device_printf(sc->dev,
5041 		    "failed to get devlog parameters: %d.\n", rc);
5042 		rc = 0;	/* devlog isn't critical for device operation */
5043 	}
5044 
5045 	return (rc);
5046 }
5047 
5048 /*
5049  * Any params that need to be set before FW_INITIALIZE.
5050  */
5051 static int
5052 set_params__pre_init(struct adapter *sc)
5053 {
5054 	int rc = 0;
5055 	uint32_t param, val;
5056 
5057 	if (chip_id(sc) >= CHELSIO_T6) {
5058 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5059 		val = 1;
5060 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5061 		/* firmwares < 1.20.1.0 do not have this param. */
5062 		if (rc == FW_EINVAL &&
5063 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5064 			rc = 0;
5065 		}
5066 		if (rc != 0) {
5067 			device_printf(sc->dev,
5068 			    "failed to enable high priority filters :%d.\n",
5069 			    rc);
5070 		}
5071 	}
5072 
5073 	/* Enable opaque VIIDs with firmwares that support it. */
5074 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5075 	val = 1;
5076 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5077 	if (rc == 0 && val == 1)
5078 		sc->params.viid_smt_extn_support = true;
5079 	else
5080 		sc->params.viid_smt_extn_support = false;
5081 
5082 	return (rc);
5083 }
5084 
5085 /*
5086  * Retrieve various parameters that are of interest to the driver.  The device
5087  * has been initialized by the firmware at this point.
5088  */
5089 static int
5090 get_params__post_init(struct adapter *sc)
5091 {
5092 	int rc;
5093 	uint32_t param[7], val[7];
5094 	struct fw_caps_config_cmd caps;
5095 
5096 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5097 	param[1] = FW_PARAM_PFVF(EQ_START);
5098 	param[2] = FW_PARAM_PFVF(FILTER_START);
5099 	param[3] = FW_PARAM_PFVF(FILTER_END);
5100 	param[4] = FW_PARAM_PFVF(L2T_START);
5101 	param[5] = FW_PARAM_PFVF(L2T_END);
5102 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5103 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5104 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5105 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5106 	if (rc != 0) {
5107 		device_printf(sc->dev,
5108 		    "failed to query parameters (post_init): %d.\n", rc);
5109 		return (rc);
5110 	}
5111 
5112 	sc->sge.iq_start = val[0];
5113 	sc->sge.eq_start = val[1];
5114 	if ((int)val[3] > (int)val[2]) {
5115 		sc->tids.ftid_base = val[2];
5116 		sc->tids.ftid_end = val[3];
5117 		sc->tids.nftids = val[3] - val[2] + 1;
5118 	}
5119 	sc->vres.l2t.start = val[4];
5120 	sc->vres.l2t.size = val[5] - val[4] + 1;
5121 	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
5122 	    ("%s: L2 table size (%u) larger than expected (%u)",
5123 	    __func__, sc->vres.l2t.size, L2T_SIZE));
5124 	sc->params.core_vdd = val[6];
5125 
5126 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5127 	param[1] = FW_PARAM_PFVF(EQ_END);
5128 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5129 	if (rc != 0) {
5130 		device_printf(sc->dev,
5131 		    "failed to query parameters (post_init2): %d.\n", rc);
5132 		return (rc);
5133 	}
5134 	MPASS((int)val[0] >= sc->sge.iq_start);
5135 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5136 	MPASS((int)val[1] >= sc->sge.eq_start);
5137 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5138 
5139 	if (chip_id(sc) >= CHELSIO_T6) {
5140 
5141 		sc->tids.tid_base = t4_read_reg(sc,
5142 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5143 
5144 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5145 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5146 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5147 		if (rc != 0) {
5148 			device_printf(sc->dev,
5149 			   "failed to query hpfilter parameters: %d.\n", rc);
5150 			return (rc);
5151 		}
5152 		if ((int)val[1] > (int)val[0]) {
5153 			sc->tids.hpftid_base = val[0];
5154 			sc->tids.hpftid_end = val[1];
5155 			sc->tids.nhpftids = val[1] - val[0] + 1;
5156 
5157 			/*
5158 			 * These should go off if the layout changes and the
5159 			 * driver needs to catch up.
5160 			 */
5161 			MPASS(sc->tids.hpftid_base == 0);
5162 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5163 		}
5164 
5165 		param[0] = FW_PARAM_PFVF(RAWF_START);
5166 		param[1] = FW_PARAM_PFVF(RAWF_END);
5167 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5168 		if (rc != 0) {
5169 			device_printf(sc->dev,
5170 			   "failed to query rawf parameters: %d.\n", rc);
5171 			return (rc);
5172 		}
5173 		if ((int)val[1] > (int)val[0]) {
5174 			sc->rawf_base = val[0];
5175 			sc->nrawf = val[1] - val[0] + 1;
5176 		}
5177 	}
5178 
5179 	/*
5180 	 * MPSBGMAP is queried separately because only recent firmwares support
5181 	 * it as a parameter and we don't want the compound query above to fail
5182 	 * on older firmwares.
5183 	 */
5184 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5185 	val[0] = 0;
5186 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5187 	if (rc == 0)
5188 		sc->params.mps_bg_map = val[0];
5189 	else
5190 		sc->params.mps_bg_map = 0;
5191 
5192 	/*
5193 	 * Determine whether the firmware supports the filter2 work request.
5194 	 * This is queried separately for the same reason as MPSBGMAP above.
5195 	 */
5196 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5197 	val[0] = 0;
5198 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5199 	if (rc == 0)
5200 		sc->params.filter2_wr_support = val[0] != 0;
5201 	else
5202 		sc->params.filter2_wr_support = 0;
5203 
5204 	/*
5205 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5206 	 * This is queried separately for the same reason as other params above.
5207 	 */
5208 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5209 	val[0] = 0;
5210 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5211 	if (rc == 0)
5212 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5213 	else
5214 		sc->params.ulptx_memwrite_dsgl = false;
5215 
5216 	/* FW_RI_FR_NSMR_TPTE_WR support */
5217 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5218 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5219 	if (rc == 0)
5220 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5221 	else
5222 		sc->params.fr_nsmr_tpte_wr_support = false;
5223 
5224 	/* Support for 512 SGL entries per FR MR. */
5225 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5226 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5227 	if (rc == 0)
5228 		sc->params.dev_512sgl_mr = val[0] != 0;
5229 	else
5230 		sc->params.dev_512sgl_mr = false;
5231 
5232 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5233 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5234 	if (rc == 0)
5235 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5236 	else
5237 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5238 
5239 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5240 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5241 	if (rc == 0) {
5242 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5243 		sc->params.nsched_cls = val[0];
5244 	} else
5245 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5246 
5247 	/* get capabilites */
5248 	bzero(&caps, sizeof(caps));
5249 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5250 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5251 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5252 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5253 	if (rc != 0) {
5254 		device_printf(sc->dev,
5255 		    "failed to get card capabilities: %d.\n", rc);
5256 		return (rc);
5257 	}
5258 
5259 #define READ_CAPS(x) do { \
5260 	sc->x = htobe16(caps.x); \
5261 } while (0)
5262 	READ_CAPS(nbmcaps);
5263 	READ_CAPS(linkcaps);
5264 	READ_CAPS(switchcaps);
5265 	READ_CAPS(niccaps);
5266 	READ_CAPS(toecaps);
5267 	READ_CAPS(rdmacaps);
5268 	READ_CAPS(cryptocaps);
5269 	READ_CAPS(iscsicaps);
5270 	READ_CAPS(fcoecaps);
5271 
5272 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5273 		MPASS(chip_id(sc) > CHELSIO_T4);
5274 		MPASS(sc->toecaps == 0);
5275 		sc->toecaps = 0;
5276 
5277 		param[0] = FW_PARAM_DEV(NTID);
5278 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5279 		if (rc != 0) {
5280 			device_printf(sc->dev,
5281 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5282 			return (rc);
5283 		}
5284 		sc->tids.ntids = val[0];
5285 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5286 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5287 			sc->tids.ntids -= sc->tids.nhpftids;
5288 		}
5289 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5290 		sc->params.hash_filter = 1;
5291 	}
5292 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5293 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5294 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5295 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5296 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5297 		if (rc != 0) {
5298 			device_printf(sc->dev,
5299 			    "failed to query NIC parameters: %d.\n", rc);
5300 			return (rc);
5301 		}
5302 		if ((int)val[1] > (int)val[0]) {
5303 			sc->tids.etid_base = val[0];
5304 			sc->tids.etid_end = val[1];
5305 			sc->tids.netids = val[1] - val[0] + 1;
5306 			sc->params.eo_wr_cred = val[2];
5307 			sc->params.ethoffload = 1;
5308 		}
5309 	}
5310 	if (sc->toecaps) {
5311 		/* query offload-related parameters */
5312 		param[0] = FW_PARAM_DEV(NTID);
5313 		param[1] = FW_PARAM_PFVF(SERVER_START);
5314 		param[2] = FW_PARAM_PFVF(SERVER_END);
5315 		param[3] = FW_PARAM_PFVF(TDDP_START);
5316 		param[4] = FW_PARAM_PFVF(TDDP_END);
5317 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5318 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5319 		if (rc != 0) {
5320 			device_printf(sc->dev,
5321 			    "failed to query TOE parameters: %d.\n", rc);
5322 			return (rc);
5323 		}
5324 		sc->tids.ntids = val[0];
5325 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5326 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5327 			sc->tids.ntids -= sc->tids.nhpftids;
5328 		}
5329 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5330 		if ((int)val[2] > (int)val[1]) {
5331 			sc->tids.stid_base = val[1];
5332 			sc->tids.nstids = val[2] - val[1] + 1;
5333 		}
5334 		sc->vres.ddp.start = val[3];
5335 		sc->vres.ddp.size = val[4] - val[3] + 1;
5336 		sc->params.ofldq_wr_cred = val[5];
5337 		sc->params.offload = 1;
5338 	} else {
5339 		/*
5340 		 * The firmware attempts memfree TOE configuration for -SO cards
5341 		 * and will report toecaps=0 if it runs out of resources (this
5342 		 * depends on the config file).  It may not report 0 for other
5343 		 * capabilities dependent on the TOE in this case.  Set them to
5344 		 * 0 here so that the driver doesn't bother tracking resources
5345 		 * that will never be used.
5346 		 */
5347 		sc->iscsicaps = 0;
5348 		sc->rdmacaps = 0;
5349 	}
5350 	if (sc->rdmacaps) {
5351 		param[0] = FW_PARAM_PFVF(STAG_START);
5352 		param[1] = FW_PARAM_PFVF(STAG_END);
5353 		param[2] = FW_PARAM_PFVF(RQ_START);
5354 		param[3] = FW_PARAM_PFVF(RQ_END);
5355 		param[4] = FW_PARAM_PFVF(PBL_START);
5356 		param[5] = FW_PARAM_PFVF(PBL_END);
5357 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5358 		if (rc != 0) {
5359 			device_printf(sc->dev,
5360 			    "failed to query RDMA parameters(1): %d.\n", rc);
5361 			return (rc);
5362 		}
5363 		sc->vres.stag.start = val[0];
5364 		sc->vres.stag.size = val[1] - val[0] + 1;
5365 		sc->vres.rq.start = val[2];
5366 		sc->vres.rq.size = val[3] - val[2] + 1;
5367 		sc->vres.pbl.start = val[4];
5368 		sc->vres.pbl.size = val[5] - val[4] + 1;
5369 
5370 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5371 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5372 		param[2] = FW_PARAM_PFVF(CQ_START);
5373 		param[3] = FW_PARAM_PFVF(CQ_END);
5374 		param[4] = FW_PARAM_PFVF(OCQ_START);
5375 		param[5] = FW_PARAM_PFVF(OCQ_END);
5376 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5377 		if (rc != 0) {
5378 			device_printf(sc->dev,
5379 			    "failed to query RDMA parameters(2): %d.\n", rc);
5380 			return (rc);
5381 		}
5382 		sc->vres.qp.start = val[0];
5383 		sc->vres.qp.size = val[1] - val[0] + 1;
5384 		sc->vres.cq.start = val[2];
5385 		sc->vres.cq.size = val[3] - val[2] + 1;
5386 		sc->vres.ocq.start = val[4];
5387 		sc->vres.ocq.size = val[5] - val[4] + 1;
5388 
5389 		param[0] = FW_PARAM_PFVF(SRQ_START);
5390 		param[1] = FW_PARAM_PFVF(SRQ_END);
5391 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5392 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5393 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5394 		if (rc != 0) {
5395 			device_printf(sc->dev,
5396 			    "failed to query RDMA parameters(3): %d.\n", rc);
5397 			return (rc);
5398 		}
5399 		sc->vres.srq.start = val[0];
5400 		sc->vres.srq.size = val[1] - val[0] + 1;
5401 		sc->params.max_ordird_qp = val[2];
5402 		sc->params.max_ird_adapter = val[3];
5403 	}
5404 	if (sc->iscsicaps) {
5405 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5406 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5407 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5408 		if (rc != 0) {
5409 			device_printf(sc->dev,
5410 			    "failed to query iSCSI parameters: %d.\n", rc);
5411 			return (rc);
5412 		}
5413 		sc->vres.iscsi.start = val[0];
5414 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5415 	}
5416 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5417 		param[0] = FW_PARAM_PFVF(TLS_START);
5418 		param[1] = FW_PARAM_PFVF(TLS_END);
5419 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5420 		if (rc != 0) {
5421 			device_printf(sc->dev,
5422 			    "failed to query TLS parameters: %d.\n", rc);
5423 			return (rc);
5424 		}
5425 		sc->vres.key.start = val[0];
5426 		sc->vres.key.size = val[1] - val[0] + 1;
5427 	}
5428 
5429 	/*
5430 	 * We've got the params we wanted to query directly from the firmware.
5431 	 * Grab some others via other means.
5432 	 */
5433 	t4_init_sge_params(sc);
5434 	t4_init_tp_params(sc);
5435 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5436 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5437 
5438 	rc = t4_verify_chip_settings(sc);
5439 	if (rc != 0)
5440 		return (rc);
5441 	t4_init_rx_buf_info(sc);
5442 
5443 	return (rc);
5444 }
5445 
5446 #ifdef KERN_TLS
5447 static void
5448 ktls_tick(void *arg)
5449 {
5450 	struct adapter *sc;
5451 	uint32_t tstamp;
5452 
5453 	sc = arg;
5454 	if (sc->flags & KERN_TLS_ON) {
5455 		tstamp = tcp_ts_getticks();
5456 		t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5457 		t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5458 	}
5459 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5460 }
5461 
5462 static int
5463 t4_config_kern_tls(struct adapter *sc, bool enable)
5464 {
5465 	int rc;
5466 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5467 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5468 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5469 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5470 
5471 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5472 	if (rc != 0) {
5473 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5474 		    enable ?  "enable" : "disable", rc);
5475 		return (rc);
5476 	}
5477 
5478 	if (enable)
5479 		sc->flags |= KERN_TLS_ON;
5480 	else
5481 		sc->flags &= ~KERN_TLS_ON;
5482 
5483 	return (rc);
5484 }
5485 #endif
5486 
5487 static int
5488 set_params__post_init(struct adapter *sc)
5489 {
5490 	uint32_t mask, param, val;
5491 #ifdef TCP_OFFLOAD
5492 	int i, v, shift;
5493 #endif
5494 
5495 	/* ask for encapsulated CPLs */
5496 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5497 	val = 1;
5498 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5499 
5500 	/* Enable 32b port caps if the firmware supports it. */
5501 	param = FW_PARAM_PFVF(PORT_CAPS32);
5502 	val = 1;
5503 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5504 		sc->params.port_caps32 = 1;
5505 
5506 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5507 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5508 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5509 	    V_MASKFILTER(val - 1));
5510 
5511 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5512 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5513 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5514 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5515 	val = 0;
5516 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5517 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5518 		    F_ATTACKFILTERENABLE);
5519 		val |= F_DROPERRORATTACK;
5520 	}
5521 	if (t4_drop_ip_fragments != 0) {
5522 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5523 		    F_FRAGMENTDROP);
5524 		val |= F_DROPERRORFRAG;
5525 	}
5526 	if (t4_drop_pkts_with_l2_errors != 0)
5527 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5528 	if (t4_drop_pkts_with_l3_errors != 0) {
5529 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5530 		    F_DROPERRORCSUMIP;
5531 	}
5532 	if (t4_drop_pkts_with_l4_errors != 0) {
5533 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5534 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5535 	}
5536 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5537 
5538 #ifdef TCP_OFFLOAD
5539 	/*
5540 	 * Override the TOE timers with user provided tunables.  This is not the
5541 	 * recommended way to change the timers (the firmware config file is) so
5542 	 * these tunables are not documented.
5543 	 *
5544 	 * All the timer tunables are in microseconds.
5545 	 */
5546 	if (t4_toe_keepalive_idle != 0) {
5547 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5548 		v &= M_KEEPALIVEIDLE;
5549 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5550 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5551 	}
5552 	if (t4_toe_keepalive_interval != 0) {
5553 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5554 		v &= M_KEEPALIVEINTVL;
5555 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5556 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5557 	}
5558 	if (t4_toe_keepalive_count != 0) {
5559 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5560 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5561 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5562 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5563 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5564 	}
5565 	if (t4_toe_rexmt_min != 0) {
5566 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5567 		v &= M_RXTMIN;
5568 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5569 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5570 	}
5571 	if (t4_toe_rexmt_max != 0) {
5572 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5573 		v &= M_RXTMAX;
5574 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5575 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5576 	}
5577 	if (t4_toe_rexmt_count != 0) {
5578 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5579 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5580 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5581 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5582 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5583 	}
5584 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5585 		if (t4_toe_rexmt_backoff[i] != -1) {
5586 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5587 			shift = (i & 3) << 3;
5588 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5589 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5590 		}
5591 	}
5592 #endif
5593 
5594 #ifdef KERN_TLS
5595 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS &&
5596 	    sc->toecaps & FW_CAPS_CONFIG_TOE) {
5597 		/*
5598 		 * Limit TOE connections to 2 reassembly "islands".  This is
5599 		 * required for TOE TLS connections to downgrade to plain TOE
5600 		 * connections if an unsupported TLS version or ciphersuite is
5601 		 * used.
5602 		 */
5603 		t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG,
5604 		    V_PASSMODE(M_PASSMODE), V_PASSMODE(2));
5605 		if (is_ktls(sc)) {
5606 			sc->tlst.inline_keys = t4_tls_inline_keys;
5607 			sc->tlst.combo_wrs = t4_tls_combo_wrs;
5608 			if (t4_kern_tls != 0)
5609 				t4_config_kern_tls(sc, true);
5610 		}
5611 	}
5612 #endif
5613 	return (0);
5614 }
5615 
5616 #undef FW_PARAM_PFVF
5617 #undef FW_PARAM_DEV
5618 
5619 static void
5620 t4_set_desc(struct adapter *sc)
5621 {
5622 	char buf[128];
5623 	struct adapter_params *p = &sc->params;
5624 
5625 	snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
5626 
5627 	device_set_desc_copy(sc->dev, buf);
5628 }
5629 
5630 static inline void
5631 ifmedia_add4(struct ifmedia *ifm, int m)
5632 {
5633 
5634 	ifmedia_add(ifm, m, 0, NULL);
5635 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5636 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5637 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5638 }
5639 
5640 /*
5641  * This is the selected media, which is not quite the same as the active media.
5642  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5643  * and active are not the same, and "media: Ethernet selected" otherwise.
5644  */
5645 static void
5646 set_current_media(struct port_info *pi)
5647 {
5648 	struct link_config *lc;
5649 	struct ifmedia *ifm;
5650 	int mword;
5651 	u_int speed;
5652 
5653 	PORT_LOCK_ASSERT_OWNED(pi);
5654 
5655 	/* Leave current media alone if it's already set to IFM_NONE. */
5656 	ifm = &pi->media;
5657 	if (ifm->ifm_cur != NULL &&
5658 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5659 		return;
5660 
5661 	lc = &pi->link_cfg;
5662 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5663 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5664 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5665 		return;
5666 	}
5667 	mword = IFM_ETHER | IFM_FDX;
5668 	if (lc->requested_fc & PAUSE_TX)
5669 		mword |= IFM_ETH_TXPAUSE;
5670 	if (lc->requested_fc & PAUSE_RX)
5671 		mword |= IFM_ETH_RXPAUSE;
5672 	if (lc->requested_speed == 0)
5673 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5674 	else
5675 		speed = lc->requested_speed;
5676 	mword |= port_mword(pi, speed_to_fwcap(speed));
5677 	ifmedia_set(ifm, mword);
5678 }
5679 
5680 /*
5681  * Returns true if the ifmedia list for the port cannot change.
5682  */
5683 static bool
5684 fixed_ifmedia(struct port_info *pi)
5685 {
5686 
5687 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5688 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5689 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5690 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5691 	    pi->port_type == FW_PORT_TYPE_KX ||
5692 	    pi->port_type == FW_PORT_TYPE_KR ||
5693 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5694 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5695 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5696 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5697 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5698 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5699 }
5700 
5701 static void
5702 build_medialist(struct port_info *pi)
5703 {
5704 	uint32_t ss, speed;
5705 	int unknown, mword, bit;
5706 	struct link_config *lc;
5707 	struct ifmedia *ifm;
5708 
5709 	PORT_LOCK_ASSERT_OWNED(pi);
5710 
5711 	if (pi->flags & FIXED_IFMEDIA)
5712 		return;
5713 
5714 	/*
5715 	 * Rebuild the ifmedia list.
5716 	 */
5717 	ifm = &pi->media;
5718 	ifmedia_removeall(ifm);
5719 	lc = &pi->link_cfg;
5720 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5721 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5722 		MPASS(ss != 0);
5723 no_media:
5724 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5725 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5726 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5727 		return;
5728 	}
5729 
5730 	unknown = 0;
5731 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5732 		speed = 1 << bit;
5733 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5734 		if (ss & speed) {
5735 			mword = port_mword(pi, speed);
5736 			if (mword == IFM_NONE) {
5737 				goto no_media;
5738 			} else if (mword == IFM_UNKNOWN)
5739 				unknown++;
5740 			else
5741 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5742 		}
5743 	}
5744 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5745 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5746 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5747 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5748 
5749 	set_current_media(pi);
5750 }
5751 
5752 /*
5753  * Initialize the requested fields in the link config based on driver tunables.
5754  */
5755 static void
5756 init_link_config(struct port_info *pi)
5757 {
5758 	struct link_config *lc = &pi->link_cfg;
5759 
5760 	PORT_LOCK_ASSERT_OWNED(pi);
5761 
5762 	lc->requested_speed = 0;
5763 
5764 	if (t4_autoneg == 0)
5765 		lc->requested_aneg = AUTONEG_DISABLE;
5766 	else if (t4_autoneg == 1)
5767 		lc->requested_aneg = AUTONEG_ENABLE;
5768 	else
5769 		lc->requested_aneg = AUTONEG_AUTO;
5770 
5771 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5772 	    PAUSE_AUTONEG);
5773 
5774 	if (t4_fec & FEC_AUTO)
5775 		lc->requested_fec = FEC_AUTO;
5776 	else if (t4_fec == 0)
5777 		lc->requested_fec = FEC_NONE;
5778 	else {
5779 		/* -1 is handled by the FEC_AUTO block above and not here. */
5780 		lc->requested_fec = t4_fec &
5781 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5782 		if (lc->requested_fec == 0)
5783 			lc->requested_fec = FEC_AUTO;
5784 	}
5785 }
5786 
5787 /*
5788  * Makes sure that all requested settings comply with what's supported by the
5789  * port.  Returns the number of settings that were invalid and had to be fixed.
5790  */
5791 static int
5792 fixup_link_config(struct port_info *pi)
5793 {
5794 	int n = 0;
5795 	struct link_config *lc = &pi->link_cfg;
5796 	uint32_t fwspeed;
5797 
5798 	PORT_LOCK_ASSERT_OWNED(pi);
5799 
5800 	/* Speed (when not autonegotiating) */
5801 	if (lc->requested_speed != 0) {
5802 		fwspeed = speed_to_fwcap(lc->requested_speed);
5803 		if ((fwspeed & lc->pcaps) == 0) {
5804 			n++;
5805 			lc->requested_speed = 0;
5806 		}
5807 	}
5808 
5809 	/* Link autonegotiation */
5810 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5811 	    lc->requested_aneg == AUTONEG_DISABLE ||
5812 	    lc->requested_aneg == AUTONEG_AUTO);
5813 	if (lc->requested_aneg == AUTONEG_ENABLE &&
5814 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5815 		n++;
5816 		lc->requested_aneg = AUTONEG_AUTO;
5817 	}
5818 
5819 	/* Flow control */
5820 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5821 	if (lc->requested_fc & PAUSE_TX &&
5822 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5823 		n++;
5824 		lc->requested_fc &= ~PAUSE_TX;
5825 	}
5826 	if (lc->requested_fc & PAUSE_RX &&
5827 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
5828 		n++;
5829 		lc->requested_fc &= ~PAUSE_RX;
5830 	}
5831 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
5832 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
5833 		n++;
5834 		lc->requested_fc |= PAUSE_AUTONEG;
5835 	}
5836 
5837 	/* FEC */
5838 	if ((lc->requested_fec & FEC_RS &&
5839 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
5840 	    (lc->requested_fec & FEC_BASER_RS &&
5841 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
5842 		n++;
5843 		lc->requested_fec = FEC_AUTO;
5844 	}
5845 
5846 	return (n);
5847 }
5848 
5849 /*
5850  * Apply the requested L1 settings, which are expected to be valid, to the
5851  * hardware.
5852  */
5853 static int
5854 apply_link_config(struct port_info *pi)
5855 {
5856 	struct adapter *sc = pi->adapter;
5857 	struct link_config *lc = &pi->link_cfg;
5858 	int rc;
5859 
5860 #ifdef INVARIANTS
5861 	ASSERT_SYNCHRONIZED_OP(sc);
5862 	PORT_LOCK_ASSERT_OWNED(pi);
5863 
5864 	if (lc->requested_aneg == AUTONEG_ENABLE)
5865 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
5866 	if (!(lc->requested_fc & PAUSE_AUTONEG))
5867 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
5868 	if (lc->requested_fc & PAUSE_TX)
5869 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
5870 	if (lc->requested_fc & PAUSE_RX)
5871 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
5872 	if (lc->requested_fec & FEC_RS)
5873 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
5874 	if (lc->requested_fec & FEC_BASER_RS)
5875 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
5876 #endif
5877 	rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
5878 	if (rc != 0) {
5879 		/* Don't complain if the VF driver gets back an EPERM. */
5880 		if (!(sc->flags & IS_VF) || rc != FW_EPERM)
5881 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
5882 	} else {
5883 		/*
5884 		 * An L1_CFG will almost always result in a link-change event if
5885 		 * the link is up, and the driver will refresh the actual
5886 		 * fec/fc/etc. when the notification is processed.  If the link
5887 		 * is down then the actual settings are meaningless.
5888 		 *
5889 		 * This takes care of the case where a change in the L1 settings
5890 		 * may not result in a notification.
5891 		 */
5892 		if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
5893 			lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
5894 	}
5895 	return (rc);
5896 }
5897 
5898 #define FW_MAC_EXACT_CHUNK	7
5899 struct mcaddr_ctx {
5900 	struct ifnet *ifp;
5901 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
5902 	uint64_t hash;
5903 	int i;
5904 	int del;
5905 	int rc;
5906 };
5907 
5908 static u_int
5909 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
5910 {
5911 	struct mcaddr_ctx *ctx = arg;
5912 	struct vi_info *vi = ctx->ifp->if_softc;
5913 	struct port_info *pi = vi->pi;
5914 	struct adapter *sc = pi->adapter;
5915 
5916 	if (ctx->rc < 0)
5917 		return (0);
5918 
5919 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
5920 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
5921 	ctx->i++;
5922 
5923 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
5924 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
5925 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
5926 		if (ctx->rc < 0) {
5927 			int j;
5928 
5929 			for (j = 0; j < ctx->i; j++) {
5930 				if_printf(ctx->ifp,
5931 				    "failed to add mc address"
5932 				    " %02x:%02x:%02x:"
5933 				    "%02x:%02x:%02x rc=%d\n",
5934 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
5935 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
5936 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
5937 				    -ctx->rc);
5938 			}
5939 			return (0);
5940 		}
5941 		ctx->del = 0;
5942 		ctx->i = 0;
5943 	}
5944 
5945 	return (1);
5946 }
5947 
5948 /*
5949  * Program the port's XGMAC based on parameters in ifnet.  The caller also
5950  * indicates which parameters should be programmed (the rest are left alone).
5951  */
5952 int
5953 update_mac_settings(struct ifnet *ifp, int flags)
5954 {
5955 	int rc = 0;
5956 	struct vi_info *vi = ifp->if_softc;
5957 	struct port_info *pi = vi->pi;
5958 	struct adapter *sc = pi->adapter;
5959 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
5960 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
5961 
5962 	ASSERT_SYNCHRONIZED_OP(sc);
5963 	KASSERT(flags, ("%s: not told what to update.", __func__));
5964 
5965 	if (flags & XGMAC_MTU)
5966 		mtu = ifp->if_mtu;
5967 
5968 	if (flags & XGMAC_PROMISC)
5969 		promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
5970 
5971 	if (flags & XGMAC_ALLMULTI)
5972 		allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
5973 
5974 	if (flags & XGMAC_VLANEX)
5975 		vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
5976 
5977 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
5978 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
5979 		    allmulti, 1, vlanex, false);
5980 		if (rc) {
5981 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
5982 			    rc);
5983 			return (rc);
5984 		}
5985 	}
5986 
5987 	if (flags & XGMAC_UCADDR) {
5988 		uint8_t ucaddr[ETHER_ADDR_LEN];
5989 
5990 		bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
5991 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
5992 		    ucaddr, true, &vi->smt_idx);
5993 		if (rc < 0) {
5994 			rc = -rc;
5995 			if_printf(ifp, "change_mac failed: %d\n", rc);
5996 			return (rc);
5997 		} else {
5998 			vi->xact_addr_filt = rc;
5999 			rc = 0;
6000 		}
6001 	}
6002 
6003 	if (flags & XGMAC_MCADDRS) {
6004 		struct epoch_tracker et;
6005 		struct mcaddr_ctx ctx;
6006 		int j;
6007 
6008 		ctx.ifp = ifp;
6009 		ctx.hash = 0;
6010 		ctx.i = 0;
6011 		ctx.del = 1;
6012 		ctx.rc = 0;
6013 		/*
6014 		 * Unlike other drivers, we accumulate list of pointers into
6015 		 * interface address lists and we need to keep it safe even
6016 		 * after if_foreach_llmaddr() returns, thus we must enter the
6017 		 * network epoch.
6018 		 */
6019 		NET_EPOCH_ENTER(et);
6020 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6021 		if (ctx.rc < 0) {
6022 			NET_EPOCH_EXIT(et);
6023 			rc = -ctx.rc;
6024 			return (rc);
6025 		}
6026 		if (ctx.i > 0) {
6027 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6028 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6029 			NET_EPOCH_EXIT(et);
6030 			if (rc < 0) {
6031 				rc = -rc;
6032 				for (j = 0; j < ctx.i; j++) {
6033 					if_printf(ifp,
6034 					    "failed to add mcast address"
6035 					    " %02x:%02x:%02x:"
6036 					    "%02x:%02x:%02x rc=%d\n",
6037 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6038 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6039 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6040 					    rc);
6041 				}
6042 				return (rc);
6043 			}
6044 			ctx.del = 0;
6045 		} else
6046 			NET_EPOCH_EXIT(et);
6047 
6048 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6049 		if (rc != 0)
6050 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6051 			    rc);
6052 		if (ctx.del == 0) {
6053 			/* We clobbered the VXLAN entry if there was one. */
6054 			pi->vxlan_tcam_entry = false;
6055 		}
6056 	}
6057 
6058 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6059 	    pi->vxlan_tcam_entry == false) {
6060 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6061 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6062 		    true);
6063 		if (rc < 0) {
6064 			rc = -rc;
6065 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6066 			    rc);
6067 		} else {
6068 			MPASS(rc == sc->rawf_base + pi->port_id);
6069 			rc = 0;
6070 			pi->vxlan_tcam_entry = true;
6071 		}
6072 	}
6073 
6074 	return (rc);
6075 }
6076 
6077 /*
6078  * {begin|end}_synchronized_op must be called from the same thread.
6079  */
6080 int
6081 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6082     char *wmesg)
6083 {
6084 	int rc, pri;
6085 
6086 #ifdef WITNESS
6087 	/* the caller thinks it's ok to sleep, but is it really? */
6088 	if (flags & SLEEP_OK)
6089 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6090 		    "begin_synchronized_op");
6091 #endif
6092 
6093 	if (INTR_OK)
6094 		pri = PCATCH;
6095 	else
6096 		pri = 0;
6097 
6098 	ADAPTER_LOCK(sc);
6099 	for (;;) {
6100 
6101 		if (vi && IS_DOOMED(vi)) {
6102 			rc = ENXIO;
6103 			goto done;
6104 		}
6105 
6106 		if (!IS_BUSY(sc)) {
6107 			rc = 0;
6108 			break;
6109 		}
6110 
6111 		if (!(flags & SLEEP_OK)) {
6112 			rc = EBUSY;
6113 			goto done;
6114 		}
6115 
6116 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6117 			rc = EINTR;
6118 			goto done;
6119 		}
6120 	}
6121 
6122 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6123 	SET_BUSY(sc);
6124 #ifdef INVARIANTS
6125 	sc->last_op = wmesg;
6126 	sc->last_op_thr = curthread;
6127 	sc->last_op_flags = flags;
6128 #endif
6129 
6130 done:
6131 	if (!(flags & HOLD_LOCK) || rc)
6132 		ADAPTER_UNLOCK(sc);
6133 
6134 	return (rc);
6135 }
6136 
6137 /*
6138  * Tell if_ioctl and if_init that the VI is going away.  This is
6139  * special variant of begin_synchronized_op and must be paired with a
6140  * call to end_synchronized_op.
6141  */
6142 void
6143 doom_vi(struct adapter *sc, struct vi_info *vi)
6144 {
6145 
6146 	ADAPTER_LOCK(sc);
6147 	SET_DOOMED(vi);
6148 	wakeup(&sc->flags);
6149 	while (IS_BUSY(sc))
6150 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6151 	SET_BUSY(sc);
6152 #ifdef INVARIANTS
6153 	sc->last_op = "t4detach";
6154 	sc->last_op_thr = curthread;
6155 	sc->last_op_flags = 0;
6156 #endif
6157 	ADAPTER_UNLOCK(sc);
6158 }
6159 
6160 /*
6161  * {begin|end}_synchronized_op must be called from the same thread.
6162  */
6163 void
6164 end_synchronized_op(struct adapter *sc, int flags)
6165 {
6166 
6167 	if (flags & LOCK_HELD)
6168 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6169 	else
6170 		ADAPTER_LOCK(sc);
6171 
6172 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6173 	CLR_BUSY(sc);
6174 	wakeup(&sc->flags);
6175 	ADAPTER_UNLOCK(sc);
6176 }
6177 
6178 static int
6179 cxgbe_init_synchronized(struct vi_info *vi)
6180 {
6181 	struct port_info *pi = vi->pi;
6182 	struct adapter *sc = pi->adapter;
6183 	struct ifnet *ifp = vi->ifp;
6184 	int rc = 0, i;
6185 	struct sge_txq *txq;
6186 
6187 	ASSERT_SYNCHRONIZED_OP(sc);
6188 
6189 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
6190 		return (0);	/* already running */
6191 
6192 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6193 		return (rc);	/* error message displayed already */
6194 
6195 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6196 		return (rc); /* error message displayed already */
6197 
6198 	rc = update_mac_settings(ifp, XGMAC_ALL);
6199 	if (rc)
6200 		goto done;	/* error message displayed already */
6201 
6202 	PORT_LOCK(pi);
6203 	if (pi->up_vis == 0) {
6204 		t4_update_port_info(pi);
6205 		fixup_link_config(pi);
6206 		build_medialist(pi);
6207 		apply_link_config(pi);
6208 	}
6209 
6210 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6211 	if (rc != 0) {
6212 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6213 		PORT_UNLOCK(pi);
6214 		goto done;
6215 	}
6216 
6217 	/*
6218 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6219 	 * if this changes.
6220 	 */
6221 
6222 	for_each_txq(vi, i, txq) {
6223 		TXQ_LOCK(txq);
6224 		txq->eq.flags |= EQ_ENABLED;
6225 		TXQ_UNLOCK(txq);
6226 	}
6227 
6228 	/*
6229 	 * The first iq of the first port to come up is used for tracing.
6230 	 */
6231 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6232 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6233 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6234 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6235 		    V_QUEUENUMBER(sc->traceq));
6236 		pi->flags |= HAS_TRACEQ;
6237 	}
6238 
6239 	/* all ok */
6240 	pi->up_vis++;
6241 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
6242 	if (pi->link_cfg.link_ok)
6243 		t4_os_link_changed(pi);
6244 	PORT_UNLOCK(pi);
6245 
6246 	mtx_lock(&vi->tick_mtx);
6247 	if (ifp->if_get_counter == vi_get_counter)
6248 		callout_reset(&vi->tick, hz, vi_tick, vi);
6249 	else
6250 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6251 	mtx_unlock(&vi->tick_mtx);
6252 done:
6253 	if (rc != 0)
6254 		cxgbe_uninit_synchronized(vi);
6255 
6256 	return (rc);
6257 }
6258 
6259 /*
6260  * Idempotent.
6261  */
6262 static int
6263 cxgbe_uninit_synchronized(struct vi_info *vi)
6264 {
6265 	struct port_info *pi = vi->pi;
6266 	struct adapter *sc = pi->adapter;
6267 	struct ifnet *ifp = vi->ifp;
6268 	int rc, i;
6269 	struct sge_txq *txq;
6270 
6271 	ASSERT_SYNCHRONIZED_OP(sc);
6272 
6273 	if (!(vi->flags & VI_INIT_DONE)) {
6274 		if (__predict_false(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6275 			KASSERT(0, ("uninited VI is running"));
6276 			if_printf(ifp, "uninited VI with running ifnet.  "
6277 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6278 			    "if_drv_flags 0x%08x\n", vi->flags, ifp->if_flags,
6279 			    ifp->if_drv_flags);
6280 		}
6281 		return (0);
6282 	}
6283 
6284 	/*
6285 	 * Disable the VI so that all its data in either direction is discarded
6286 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6287 	 * tick) intact as the TP can deliver negative advice or data that it's
6288 	 * holding in its RAM (for an offloaded connection) even after the VI is
6289 	 * disabled.
6290 	 */
6291 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6292 	if (rc) {
6293 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6294 		return (rc);
6295 	}
6296 
6297 	for_each_txq(vi, i, txq) {
6298 		TXQ_LOCK(txq);
6299 		txq->eq.flags &= ~EQ_ENABLED;
6300 		TXQ_UNLOCK(txq);
6301 	}
6302 
6303 	mtx_lock(&vi->tick_mtx);
6304 	callout_stop(&vi->tick);
6305 	mtx_unlock(&vi->tick_mtx);
6306 
6307 	PORT_LOCK(pi);
6308 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6309 		PORT_UNLOCK(pi);
6310 		return (0);
6311 	}
6312 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
6313 	pi->up_vis--;
6314 	if (pi->up_vis > 0) {
6315 		PORT_UNLOCK(pi);
6316 		return (0);
6317 	}
6318 
6319 	pi->link_cfg.link_ok = false;
6320 	pi->link_cfg.speed = 0;
6321 	pi->link_cfg.link_down_rc = 255;
6322 	t4_os_link_changed(pi);
6323 	PORT_UNLOCK(pi);
6324 
6325 	return (0);
6326 }
6327 
6328 /*
6329  * It is ok for this function to fail midway and return right away.  t4_detach
6330  * will walk the entire sc->irq list and clean up whatever is valid.
6331  */
6332 int
6333 t4_setup_intr_handlers(struct adapter *sc)
6334 {
6335 	int rc, rid, p, q, v;
6336 	char s[8];
6337 	struct irq *irq;
6338 	struct port_info *pi;
6339 	struct vi_info *vi;
6340 	struct sge *sge = &sc->sge;
6341 	struct sge_rxq *rxq;
6342 #ifdef TCP_OFFLOAD
6343 	struct sge_ofld_rxq *ofld_rxq;
6344 #endif
6345 #ifdef DEV_NETMAP
6346 	struct sge_nm_rxq *nm_rxq;
6347 #endif
6348 #ifdef RSS
6349 	int nbuckets = rss_getnumbuckets();
6350 #endif
6351 
6352 	/*
6353 	 * Setup interrupts.
6354 	 */
6355 	irq = &sc->irq[0];
6356 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6357 	if (forwarding_intr_to_fwq(sc))
6358 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6359 
6360 	/* Multiple interrupts. */
6361 	if (sc->flags & IS_VF)
6362 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6363 		    ("%s: too few intr.", __func__));
6364 	else
6365 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6366 		    ("%s: too few intr.", __func__));
6367 
6368 	/* The first one is always error intr on PFs */
6369 	if (!(sc->flags & IS_VF)) {
6370 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6371 		if (rc != 0)
6372 			return (rc);
6373 		irq++;
6374 		rid++;
6375 	}
6376 
6377 	/* The second one is always the firmware event queue (first on VFs) */
6378 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6379 	if (rc != 0)
6380 		return (rc);
6381 	irq++;
6382 	rid++;
6383 
6384 	for_each_port(sc, p) {
6385 		pi = sc->port[p];
6386 		for_each_vi(pi, v, vi) {
6387 			vi->first_intr = rid - 1;
6388 
6389 			if (vi->nnmrxq > 0) {
6390 				int n = max(vi->nrxq, vi->nnmrxq);
6391 
6392 				rxq = &sge->rxq[vi->first_rxq];
6393 #ifdef DEV_NETMAP
6394 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6395 #endif
6396 				for (q = 0; q < n; q++) {
6397 					snprintf(s, sizeof(s), "%x%c%x", p,
6398 					    'a' + v, q);
6399 					if (q < vi->nrxq)
6400 						irq->rxq = rxq++;
6401 #ifdef DEV_NETMAP
6402 					if (q < vi->nnmrxq)
6403 						irq->nm_rxq = nm_rxq++;
6404 
6405 					if (irq->nm_rxq != NULL &&
6406 					    irq->rxq == NULL) {
6407 						/* Netmap rx only */
6408 						rc = t4_alloc_irq(sc, irq, rid,
6409 						    t4_nm_intr, irq->nm_rxq, s);
6410 					}
6411 					if (irq->nm_rxq != NULL &&
6412 					    irq->rxq != NULL) {
6413 						/* NIC and Netmap rx */
6414 						rc = t4_alloc_irq(sc, irq, rid,
6415 						    t4_vi_intr, irq, s);
6416 					}
6417 #endif
6418 					if (irq->rxq != NULL &&
6419 					    irq->nm_rxq == NULL) {
6420 						/* NIC rx only */
6421 						rc = t4_alloc_irq(sc, irq, rid,
6422 						    t4_intr, irq->rxq, s);
6423 					}
6424 					if (rc != 0)
6425 						return (rc);
6426 #ifdef RSS
6427 					if (q < vi->nrxq) {
6428 						bus_bind_intr(sc->dev, irq->res,
6429 						    rss_getcpu(q % nbuckets));
6430 					}
6431 #endif
6432 					irq++;
6433 					rid++;
6434 					vi->nintr++;
6435 				}
6436 			} else {
6437 				for_each_rxq(vi, q, rxq) {
6438 					snprintf(s, sizeof(s), "%x%c%x", p,
6439 					    'a' + v, q);
6440 					rc = t4_alloc_irq(sc, irq, rid,
6441 					    t4_intr, rxq, s);
6442 					if (rc != 0)
6443 						return (rc);
6444 #ifdef RSS
6445 					bus_bind_intr(sc->dev, irq->res,
6446 					    rss_getcpu(q % nbuckets));
6447 #endif
6448 					irq++;
6449 					rid++;
6450 					vi->nintr++;
6451 				}
6452 			}
6453 #ifdef TCP_OFFLOAD
6454 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6455 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6456 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6457 				    ofld_rxq, s);
6458 				if (rc != 0)
6459 					return (rc);
6460 				irq++;
6461 				rid++;
6462 				vi->nintr++;
6463 			}
6464 #endif
6465 		}
6466 	}
6467 	MPASS(irq == &sc->irq[sc->intr_count]);
6468 
6469 	return (0);
6470 }
6471 
6472 static void
6473 write_global_rss_key(struct adapter *sc)
6474 {
6475 #ifdef RSS
6476 	int i;
6477 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6478 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6479 
6480 	CTASSERT(RSS_KEYSIZE == 40);
6481 
6482 	rss_getkey((void *)&raw_rss_key[0]);
6483 	for (i = 0; i < nitems(rss_key); i++) {
6484 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6485 	}
6486 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6487 #endif
6488 }
6489 
6490 /*
6491  * Idempotent.
6492  */
6493 static int
6494 adapter_full_init(struct adapter *sc)
6495 {
6496 	int rc, i;
6497 
6498 	ASSERT_SYNCHRONIZED_OP(sc);
6499 
6500 	if (!(sc->flags & ADAP_SYSCTL_CTX)) {
6501 		sysctl_ctx_init(&sc->ctx);
6502 		sc->flags |= ADAP_SYSCTL_CTX;
6503 	}
6504 
6505 	/*
6506 	 * queues that belong to the adapter (not any particular port).
6507 	 */
6508 	rc = t4_setup_adapter_queues(sc);
6509 	if (rc != 0)
6510 		return (rc);
6511 
6512 	for (i = 0; i < nitems(sc->tq); i++) {
6513 		if (sc->tq[i] != NULL)
6514 			continue;
6515 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6516 		    taskqueue_thread_enqueue, &sc->tq[i]);
6517 		if (sc->tq[i] == NULL) {
6518 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6519 			return (ENOMEM);
6520 		}
6521 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6522 		    device_get_nameunit(sc->dev), i);
6523 	}
6524 
6525 	if (!(sc->flags & IS_VF)) {
6526 		write_global_rss_key(sc);
6527 		t4_intr_enable(sc);
6528 	}
6529 #ifdef KERN_TLS
6530 	if (is_ktls(sc))
6531 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
6532 		    C_HARDCLOCK);
6533 #endif
6534 	return (0);
6535 }
6536 
6537 int
6538 adapter_init(struct adapter *sc)
6539 {
6540 	int rc;
6541 
6542 	ASSERT_SYNCHRONIZED_OP(sc);
6543 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6544 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6545 	    ("%s: FULL_INIT_DONE already", __func__));
6546 
6547 	rc = adapter_full_init(sc);
6548 	if (rc != 0)
6549 		adapter_full_uninit(sc);
6550 	else
6551 		sc->flags |= FULL_INIT_DONE;
6552 
6553 	return (rc);
6554 }
6555 
6556 /*
6557  * Idempotent.
6558  */
6559 static void
6560 adapter_full_uninit(struct adapter *sc)
6561 {
6562 	int i;
6563 
6564 	/* Do this before freeing the adapter queues. */
6565 	if (sc->flags & ADAP_SYSCTL_CTX) {
6566 		sysctl_ctx_free(&sc->ctx);
6567 		sc->flags &= ~ADAP_SYSCTL_CTX;
6568 	}
6569 
6570 	t4_teardown_adapter_queues(sc);
6571 
6572 	for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
6573 		taskqueue_free(sc->tq[i]);
6574 		sc->tq[i] = NULL;
6575 	}
6576 
6577 	sc->flags &= ~FULL_INIT_DONE;
6578 }
6579 
6580 #ifdef RSS
6581 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6582     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6583     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6584     RSS_HASHTYPE_RSS_UDP_IPV6)
6585 
6586 /* Translates kernel hash types to hardware. */
6587 static int
6588 hashconfig_to_hashen(int hashconfig)
6589 {
6590 	int hashen = 0;
6591 
6592 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6593 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6594 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6595 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6596 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6597 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6598 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6599 	}
6600 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6601 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6602 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6603 	}
6604 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6605 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6606 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6607 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6608 
6609 	return (hashen);
6610 }
6611 
6612 /* Translates hardware hash types to kernel. */
6613 static int
6614 hashen_to_hashconfig(int hashen)
6615 {
6616 	int hashconfig = 0;
6617 
6618 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6619 		/*
6620 		 * If UDP hashing was enabled it must have been enabled for
6621 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6622 		 * enabling any 4-tuple hash is nonsense configuration.
6623 		 */
6624 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6625 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6626 
6627 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6628 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6629 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6630 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6631 	}
6632 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6633 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6634 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6635 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6636 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6637 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6638 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6639 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6640 
6641 	return (hashconfig);
6642 }
6643 #endif
6644 
6645 /*
6646  * Idempotent.
6647  */
6648 static int
6649 vi_full_init(struct vi_info *vi)
6650 {
6651 	struct adapter *sc = vi->adapter;
6652 	struct sge_rxq *rxq;
6653 	int rc, i, j;
6654 #ifdef RSS
6655 	int nbuckets = rss_getnumbuckets();
6656 	int hashconfig = rss_gethashconfig();
6657 	int extra;
6658 #endif
6659 
6660 	ASSERT_SYNCHRONIZED_OP(sc);
6661 
6662 	if (!(vi->flags & VI_SYSCTL_CTX)) {
6663 		sysctl_ctx_init(&vi->ctx);
6664 		vi->flags |= VI_SYSCTL_CTX;
6665 	}
6666 
6667 	/*
6668 	 * Allocate tx/rx/fl queues for this VI.
6669 	 */
6670 	rc = t4_setup_vi_queues(vi);
6671 	if (rc != 0)
6672 		return (rc);
6673 
6674 	/*
6675 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6676 	 */
6677 	if (vi->nrxq > vi->rss_size) {
6678 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6679 		    "some queues will never receive traffic.\n", vi->nrxq,
6680 		    vi->rss_size);
6681 	} else if (vi->rss_size % vi->nrxq) {
6682 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6683 		    "expect uneven traffic distribution.\n", vi->nrxq,
6684 		    vi->rss_size);
6685 	}
6686 #ifdef RSS
6687 	if (vi->nrxq != nbuckets) {
6688 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6689 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6690 	}
6691 #endif
6692 	if (vi->rss == NULL)
6693 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6694 		    M_ZERO | M_WAITOK);
6695 	for (i = 0; i < vi->rss_size;) {
6696 #ifdef RSS
6697 		j = rss_get_indirection_to_bucket(i);
6698 		j %= vi->nrxq;
6699 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6700 		vi->rss[i++] = rxq->iq.abs_id;
6701 #else
6702 		for_each_rxq(vi, j, rxq) {
6703 			vi->rss[i++] = rxq->iq.abs_id;
6704 			if (i == vi->rss_size)
6705 				break;
6706 		}
6707 #endif
6708 	}
6709 
6710 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6711 	    vi->rss, vi->rss_size);
6712 	if (rc != 0) {
6713 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6714 		return (rc);
6715 	}
6716 
6717 #ifdef RSS
6718 	vi->hashen = hashconfig_to_hashen(hashconfig);
6719 
6720 	/*
6721 	 * We may have had to enable some hashes even though the global config
6722 	 * wants them disabled.  This is a potential problem that must be
6723 	 * reported to the user.
6724 	 */
6725 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6726 
6727 	/*
6728 	 * If we consider only the supported hash types, then the enabled hashes
6729 	 * are a superset of the requested hashes.  In other words, there cannot
6730 	 * be any supported hash that was requested but not enabled, but there
6731 	 * can be hashes that were not requested but had to be enabled.
6732 	 */
6733 	extra &= SUPPORTED_RSS_HASHTYPES;
6734 	MPASS((extra & hashconfig) == 0);
6735 
6736 	if (extra) {
6737 		CH_ALERT(vi,
6738 		    "global RSS config (0x%x) cannot be accommodated.\n",
6739 		    hashconfig);
6740 	}
6741 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6742 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6743 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6744 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6745 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6746 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6747 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6748 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6749 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6750 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6751 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6752 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6753 #else
6754 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6755 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6756 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6757 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6758 #endif
6759 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6760 	    0, 0);
6761 	if (rc != 0) {
6762 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6763 		return (rc);
6764 	}
6765 
6766 	return (0);
6767 }
6768 
6769 int
6770 vi_init(struct vi_info *vi)
6771 {
6772 	int rc;
6773 
6774 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6775 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6776 	    ("%s: VI_INIT_DONE already", __func__));
6777 
6778 	rc = vi_full_init(vi);
6779 	if (rc != 0)
6780 		vi_full_uninit(vi);
6781 	else
6782 		vi->flags |= VI_INIT_DONE;
6783 
6784 	return (rc);
6785 }
6786 
6787 /*
6788  * Idempotent.
6789  */
6790 static void
6791 vi_full_uninit(struct vi_info *vi)
6792 {
6793 
6794 	if (vi->flags & VI_INIT_DONE) {
6795 		quiesce_vi(vi);
6796 		free(vi->rss, M_CXGBE);
6797 		free(vi->nm_rss, M_CXGBE);
6798 	}
6799 
6800 	/* Do this before freeing the VI queues. */
6801 	if (vi->flags & VI_SYSCTL_CTX) {
6802 		sysctl_ctx_free(&vi->ctx);
6803 		vi->flags &= ~VI_SYSCTL_CTX;
6804 	}
6805 
6806 	t4_teardown_vi_queues(vi);
6807 	vi->flags &= ~VI_INIT_DONE;
6808 }
6809 
6810 static void
6811 quiesce_txq(struct sge_txq *txq)
6812 {
6813 	struct sge_eq *eq = &txq->eq;
6814 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6815 
6816 	MPASS(eq->flags & EQ_SW_ALLOCATED);
6817 	MPASS(!(eq->flags & EQ_ENABLED));
6818 
6819 	/* Wait for the mp_ring to empty. */
6820 	while (!mp_ring_is_idle(txq->r)) {
6821 		mp_ring_check_drainage(txq->r, 4096);
6822 		pause("rquiesce", 1);
6823 	}
6824 	MPASS(txq->txp.npkt == 0);
6825 
6826 	if (eq->flags & EQ_HW_ALLOCATED) {
6827 		/*
6828 		 * Hardware is alive and working normally.  Wait for it to
6829 		 * finish and then wait for the driver to catch up and reclaim
6830 		 * all descriptors.
6831 		 */
6832 		while (spg->cidx != htobe16(eq->pidx))
6833 			pause("equiesce", 1);
6834 		while (eq->cidx != eq->pidx)
6835 			pause("dquiesce", 1);
6836 	} else {
6837 		/*
6838 		 * Hardware is unavailable.  Discard all pending tx and reclaim
6839 		 * descriptors directly.
6840 		 */
6841 		TXQ_LOCK(txq);
6842 		while (eq->cidx != eq->pidx) {
6843 			struct mbuf *m, *nextpkt;
6844 			struct tx_sdesc *txsd;
6845 
6846 			txsd = &txq->sdesc[eq->cidx];
6847 			for (m = txsd->m; m != NULL; m = nextpkt) {
6848 				nextpkt = m->m_nextpkt;
6849 				m->m_nextpkt = NULL;
6850 				m_freem(m);
6851 			}
6852 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
6853 		}
6854 		spg->pidx = spg->cidx = htobe16(eq->cidx);
6855 		TXQ_UNLOCK(txq);
6856 	}
6857 }
6858 
6859 static void
6860 quiesce_wrq(struct sge_wrq *wrq)
6861 {
6862 
6863 	/* XXXTX */
6864 }
6865 
6866 static void
6867 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
6868 {
6869 	/* Synchronize with the interrupt handler */
6870 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
6871 		pause("iqfree", 1);
6872 
6873 	if (fl != NULL) {
6874 		MPASS(iq->flags & IQ_HAS_FL);
6875 
6876 		mtx_lock(&sc->sfl_lock);
6877 		FL_LOCK(fl);
6878 		fl->flags |= FL_DOOMED;
6879 		FL_UNLOCK(fl);
6880 		callout_stop(&sc->sfl_callout);
6881 		mtx_unlock(&sc->sfl_lock);
6882 
6883 		KASSERT((fl->flags & FL_STARVING) == 0,
6884 		    ("%s: still starving", __func__));
6885 
6886 		/* Release all buffers if hardware is no longer available. */
6887 		if (!(iq->flags & IQ_HW_ALLOCATED))
6888 			free_fl_buffers(sc, fl);
6889 	}
6890 }
6891 
6892 /*
6893  * Wait for all activity on all the queues of the VI to complete.  It is assumed
6894  * that no new work is being enqueued by the hardware or the driver.  That part
6895  * should be arranged before calling this function.
6896  */
6897 static void
6898 quiesce_vi(struct vi_info *vi)
6899 {
6900 	int i;
6901 	struct adapter *sc = vi->adapter;
6902 	struct sge_rxq *rxq;
6903 	struct sge_txq *txq;
6904 #ifdef TCP_OFFLOAD
6905 	struct sge_ofld_rxq *ofld_rxq;
6906 #endif
6907 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6908 	struct sge_ofld_txq *ofld_txq;
6909 #endif
6910 
6911 	if (!(vi->flags & VI_INIT_DONE))
6912 		return;
6913 
6914 	for_each_txq(vi, i, txq) {
6915 		quiesce_txq(txq);
6916 	}
6917 
6918 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6919 	for_each_ofld_txq(vi, i, ofld_txq) {
6920 		quiesce_wrq(&ofld_txq->wrq);
6921 	}
6922 #endif
6923 
6924 	for_each_rxq(vi, i, rxq) {
6925 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
6926 	}
6927 
6928 #ifdef TCP_OFFLOAD
6929 	for_each_ofld_rxq(vi, i, ofld_rxq) {
6930 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
6931 	}
6932 #endif
6933 }
6934 
6935 static int
6936 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
6937     driver_intr_t *handler, void *arg, char *name)
6938 {
6939 	int rc;
6940 
6941 	irq->rid = rid;
6942 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
6943 	    RF_SHAREABLE | RF_ACTIVE);
6944 	if (irq->res == NULL) {
6945 		device_printf(sc->dev,
6946 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
6947 		return (ENOMEM);
6948 	}
6949 
6950 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
6951 	    NULL, handler, arg, &irq->tag);
6952 	if (rc != 0) {
6953 		device_printf(sc->dev,
6954 		    "failed to setup interrupt for rid %d, name %s: %d\n",
6955 		    rid, name, rc);
6956 	} else if (name)
6957 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
6958 
6959 	return (rc);
6960 }
6961 
6962 static int
6963 t4_free_irq(struct adapter *sc, struct irq *irq)
6964 {
6965 	if (irq->tag)
6966 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
6967 	if (irq->res)
6968 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
6969 
6970 	bzero(irq, sizeof(*irq));
6971 
6972 	return (0);
6973 }
6974 
6975 static void
6976 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
6977 {
6978 
6979 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
6980 	t4_get_regs(sc, buf, regs->len);
6981 }
6982 
6983 #define	A_PL_INDIR_CMD	0x1f8
6984 
6985 #define	S_PL_AUTOINC	31
6986 #define	M_PL_AUTOINC	0x1U
6987 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
6988 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
6989 
6990 #define	S_PL_VFID	20
6991 #define	M_PL_VFID	0xffU
6992 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
6993 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
6994 
6995 #define	S_PL_ADDR	0
6996 #define	M_PL_ADDR	0xfffffU
6997 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
6998 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
6999 
7000 #define	A_PL_INDIR_DATA	0x1fc
7001 
7002 static uint64_t
7003 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7004 {
7005 	u32 stats[2];
7006 
7007 	if (sc->flags & IS_VF) {
7008 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7009 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7010 	} else {
7011 		mtx_assert(&sc->reg_lock, MA_OWNED);
7012 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7013 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7014 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7015 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7016 	}
7017 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7018 }
7019 
7020 static void
7021 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7022 {
7023 
7024 #define GET_STAT(name) \
7025 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7026 
7027 	if (!(sc->flags & IS_VF))
7028 		mtx_lock(&sc->reg_lock);
7029 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7030 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7031 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7032 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7033 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7034 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7035 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7036 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7037 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7038 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7039 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7040 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7041 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7042 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7043 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7044 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7045 	if (!(sc->flags & IS_VF))
7046 		mtx_unlock(&sc->reg_lock);
7047 
7048 #undef GET_STAT
7049 }
7050 
7051 static void
7052 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7053 {
7054 	int reg;
7055 
7056 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7057 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7058 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7059 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7060 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7061 }
7062 
7063 static void
7064 vi_refresh_stats(struct vi_info *vi)
7065 {
7066 	struct timeval tv;
7067 	const struct timeval interval = {0, 250000};	/* 250ms */
7068 
7069 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7070 
7071 	if (!(vi->flags & VI_INIT_DONE) || vi->flags & VI_SKIP_STATS)
7072 		return;
7073 
7074 	getmicrotime(&tv);
7075 	timevalsub(&tv, &interval);
7076 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7077 		return;
7078 
7079 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7080 	getmicrotime(&vi->last_refreshed);
7081 }
7082 
7083 static void
7084 cxgbe_refresh_stats(struct vi_info *vi)
7085 {
7086 	u_int i, v, tnl_cong_drops, chan_map;
7087 	struct timeval tv;
7088 	const struct timeval interval = {0, 250000};	/* 250ms */
7089 	struct port_info *pi;
7090 	struct adapter *sc;
7091 
7092 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7093 
7094 	if (vi->flags & VI_SKIP_STATS)
7095 		return;
7096 
7097 	getmicrotime(&tv);
7098 	timevalsub(&tv, &interval);
7099 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7100 		return;
7101 
7102 	pi = vi->pi;
7103 	sc = vi->adapter;
7104 	tnl_cong_drops = 0;
7105 	t4_get_port_stats(sc, pi->tx_chan, &pi->stats);
7106 	chan_map = pi->rx_e_chan_map;
7107 	while (chan_map) {
7108 		i = ffs(chan_map) - 1;
7109 		mtx_lock(&sc->reg_lock);
7110 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7111 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7112 		mtx_unlock(&sc->reg_lock);
7113 		tnl_cong_drops += v;
7114 		chan_map &= ~(1 << i);
7115 	}
7116 	pi->tnl_cong_drops = tnl_cong_drops;
7117 	getmicrotime(&vi->last_refreshed);
7118 }
7119 
7120 static void
7121 cxgbe_tick(void *arg)
7122 {
7123 	struct vi_info *vi = arg;
7124 
7125 	MPASS(IS_MAIN_VI(vi));
7126 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7127 
7128 	cxgbe_refresh_stats(vi);
7129 	callout_schedule(&vi->tick, hz);
7130 }
7131 
7132 static void
7133 vi_tick(void *arg)
7134 {
7135 	struct vi_info *vi = arg;
7136 
7137 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7138 
7139 	vi_refresh_stats(vi);
7140 	callout_schedule(&vi->tick, hz);
7141 }
7142 
7143 /*
7144  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7145  */
7146 static char *caps_decoder[] = {
7147 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7148 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7149 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7150 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7151 	    "\006HASHFILTER\007ETHOFLD",
7152 	"\20\001TOE",					/* 4: TOE */
7153 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7154 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7155 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7156 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7157 	    "\007T10DIF"
7158 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7159 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7160 	    "\004TLS_HW",
7161 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7162 		    "\004PO_INITIATOR\005PO_TARGET",
7163 };
7164 
7165 void
7166 t4_sysctls(struct adapter *sc)
7167 {
7168 	struct sysctl_ctx_list *ctx;
7169 	struct sysctl_oid *oid;
7170 	struct sysctl_oid_list *children, *c0;
7171 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7172 
7173 	ctx = device_get_sysctl_ctx(sc->dev);
7174 
7175 	/*
7176 	 * dev.t4nex.X.
7177 	 */
7178 	oid = device_get_sysctl_tree(sc->dev);
7179 	c0 = children = SYSCTL_CHILDREN(oid);
7180 
7181 	sc->sc_do_rxcopy = 1;
7182 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7183 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7184 
7185 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7186 	    sc->params.nports, "# of ports");
7187 
7188 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7189 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7190 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7191 	    "available doorbells");
7192 
7193 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7194 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7195 
7196 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7197 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7198 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7199 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7200 
7201 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7202 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7203 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7204 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7205 
7206 	t4_sge_sysctls(sc, ctx, children);
7207 
7208 	sc->lro_timeout = 100;
7209 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7210 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7211 
7212 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7213 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7214 
7215 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7216 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7217 
7218 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7219 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7220 
7221 	if (sc->flags & IS_VF)
7222 		return;
7223 
7224 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7225 	    NULL, chip_rev(sc), "chip hardware revision");
7226 
7227 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7228 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7229 
7230 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7231 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7232 
7233 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7234 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7235 
7236 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7237 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7238 
7239 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7240 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7241 
7242 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7243 	    sc->er_version, 0, "expansion ROM version");
7244 
7245 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7246 	    sc->bs_version, 0, "bootstrap firmware version");
7247 
7248 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7249 	    NULL, sc->params.scfg_vers, "serial config version");
7250 
7251 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7252 	    NULL, sc->params.vpd_vers, "VPD version");
7253 
7254 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7255 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7256 
7257 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7258 	    sc->cfcsum, "config file checksum");
7259 
7260 #define SYSCTL_CAP(name, n, text) \
7261 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7262 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7263 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7264 	    "available " text " capabilities")
7265 
7266 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7267 	SYSCTL_CAP(linkcaps, 1, "link");
7268 	SYSCTL_CAP(switchcaps, 2, "switch");
7269 	SYSCTL_CAP(niccaps, 3, "NIC");
7270 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7271 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7272 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7273 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7274 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7275 #undef SYSCTL_CAP
7276 
7277 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7278 	    NULL, sc->tids.nftids, "number of filters");
7279 
7280 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7281 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7282 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7283 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7284 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7285 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7286 
7287 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7288 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7289 	    sysctl_loadavg, "A",
7290 	    "microprocessor load averages (debug firmwares only)");
7291 
7292 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7293 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7294 	    "I", "core Vdd (in mV)");
7295 
7296 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7297 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7298 	    sysctl_cpus, "A", "local CPUs");
7299 
7300 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7301 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7302 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7303 
7304 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7305 	    &sc->swintr, 0, "software triggered interrupts");
7306 
7307 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7308 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7309 	    "1 = reset adapter, 0 = zero reset counter");
7310 
7311 	/*
7312 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7313 	 */
7314 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7315 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7316 	    "logs and miscellaneous information");
7317 	children = SYSCTL_CHILDREN(oid);
7318 
7319 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7320 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7321 	    sysctl_cctrl, "A", "congestion control");
7322 
7323 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7324 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7325 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7326 
7327 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7328 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7329 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7330 
7331 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7332 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7333 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7334 
7335 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7336 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7337 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7338 
7339 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7340 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7341 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7342 
7343 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7344 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7345 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7346 
7347 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7348 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7349 	    sysctl_cim_la, "A", "CIM logic analyzer");
7350 
7351 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7352 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7353 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7354 
7355 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7356 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7357 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7358 
7359 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7360 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7361 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7362 
7363 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7364 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7365 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7366 
7367 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7368 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7369 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7370 
7371 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7372 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7373 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7374 
7375 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7376 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7377 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7378 
7379 	if (chip_id(sc) > CHELSIO_T4) {
7380 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7381 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7382 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7383 		    "CIM OBQ 6 (SGE0-RX)");
7384 
7385 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7386 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7387 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7388 		    "CIM OBQ 7 (SGE1-RX)");
7389 	}
7390 
7391 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7392 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7393 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7394 
7395 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7396 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7397 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7398 
7399 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7400 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7401 	    sysctl_cpl_stats, "A", "CPL statistics");
7402 
7403 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7404 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7405 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7406 
7407 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7408 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7409 	    sysctl_tid_stats, "A", "tid stats");
7410 
7411 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7412 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7413 	    sysctl_devlog, "A", "firmware's device log");
7414 
7415 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7416 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7417 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7418 
7419 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7420 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7421 	    sysctl_hw_sched, "A", "hardware scheduler ");
7422 
7423 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7424 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7425 	    sysctl_l2t, "A", "hardware L2 table");
7426 
7427 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7428 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7429 	    sysctl_smt, "A", "hardware source MAC table");
7430 
7431 #ifdef INET6
7432 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7433 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7434 	    sysctl_clip, "A", "active CLIP table entries");
7435 #endif
7436 
7437 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7438 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7439 	    sysctl_lb_stats, "A", "loopback statistics");
7440 
7441 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7442 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7443 	    sysctl_meminfo, "A", "memory regions");
7444 
7445 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7446 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7447 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7448 	    "A", "MPS TCAM entries");
7449 
7450 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7451 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7452 	    sysctl_path_mtus, "A", "path MTUs");
7453 
7454 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7455 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7456 	    sysctl_pm_stats, "A", "PM statistics");
7457 
7458 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7459 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7460 	    sysctl_rdma_stats, "A", "RDMA statistics");
7461 
7462 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7463 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7464 	    sysctl_tcp_stats, "A", "TCP statistics");
7465 
7466 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7467 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7468 	    sysctl_tids, "A", "TID information");
7469 
7470 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7471 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7472 	    sysctl_tp_err_stats, "A", "TP error statistics");
7473 
7474 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7475 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7476 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7477 
7478 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7479 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7480 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7481 
7482 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7483 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7484 	    sysctl_tp_la, "A", "TP logic analyzer");
7485 
7486 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7487 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7488 	    sysctl_tx_rate, "A", "Tx rate");
7489 
7490 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7491 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7492 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7493 
7494 	if (chip_id(sc) >= CHELSIO_T5) {
7495 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7496 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7497 		    sysctl_wcwr_stats, "A", "write combined work requests");
7498 	}
7499 
7500 #ifdef KERN_TLS
7501 	if (is_ktls(sc)) {
7502 		/*
7503 		 * dev.t4nex.0.tls.
7504 		 */
7505 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7506 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7507 		children = SYSCTL_CHILDREN(oid);
7508 
7509 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7510 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7511 		    "keys in work requests (1) or attempt to store TLS keys "
7512 		    "in card memory.");
7513 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7514 		    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to combine "
7515 		    "TCB field updates with TLS record work requests.");
7516 	}
7517 #endif
7518 
7519 #ifdef TCP_OFFLOAD
7520 	if (is_offload(sc)) {
7521 		int i;
7522 		char s[4];
7523 
7524 		/*
7525 		 * dev.t4nex.X.toe.
7526 		 */
7527 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7528 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7529 		children = SYSCTL_CHILDREN(oid);
7530 
7531 		sc->tt.cong_algorithm = -1;
7532 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7533 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7534 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7535 		    "3 = highspeed)");
7536 
7537 		sc->tt.sndbuf = -1;
7538 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7539 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7540 
7541 		sc->tt.ddp = 0;
7542 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7543 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7544 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7545 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7546 
7547 		sc->tt.rx_coalesce = -1;
7548 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7549 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7550 
7551 		sc->tt.tls = 0;
7552 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7553 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7554 		    "Inline TLS allowed");
7555 
7556 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_ports",
7557 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7558 		    sysctl_tls_rx_ports, "I",
7559 		    "TCP ports that use inline TLS+TOE RX");
7560 
7561 		sc->tt.tls_rx_timeout = t4_toe_tls_rx_timeout;
7562 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_timeout",
7563 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7564 		    sysctl_tls_rx_timeout, "I",
7565 		    "Timeout in seconds to downgrade TLS sockets to plain TOE");
7566 
7567 		sc->tt.tx_align = -1;
7568 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7569 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7570 
7571 		sc->tt.tx_zcopy = 0;
7572 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7573 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7574 		    "Enable zero-copy aio_write(2)");
7575 
7576 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7577 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7578 		    "cop_managed_offloading", CTLFLAG_RW,
7579 		    &sc->tt.cop_managed_offloading, 0,
7580 		    "COP (Connection Offload Policy) controls all TOE offload");
7581 
7582 		sc->tt.autorcvbuf_inc = 16 * 1024;
7583 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7584 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7585 		    "autorcvbuf increment");
7586 
7587 		sc->tt.update_hc_on_pmtu_change = 1;
7588 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7589 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7590 		    &sc->tt.update_hc_on_pmtu_change, 0,
7591 		    "Update hostcache entry if the PMTU changes");
7592 
7593 		sc->tt.iso = 1;
7594 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7595 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7596 
7597 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7598 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7599 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7600 
7601 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7602 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7603 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7604 
7605 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7606 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7607 		    sysctl_tp_tick, "A", "DACK tick (us)");
7608 
7609 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7610 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7611 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7612 
7613 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7614 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7615 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7616 		    "Minimum retransmit interval (us)");
7617 
7618 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7619 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7620 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7621 		    "Maximum retransmit interval (us)");
7622 
7623 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7624 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7625 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7626 		    "Persist timer min (us)");
7627 
7628 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7629 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7630 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7631 		    "Persist timer max (us)");
7632 
7633 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7634 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7635 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7636 		    "Keepalive idle timer (us)");
7637 
7638 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7639 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7640 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7641 		    "Keepalive interval timer (us)");
7642 
7643 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7644 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7645 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7646 
7647 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7648 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7649 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7650 		    "FINWAIT2 timer (us)");
7651 
7652 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7653 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7654 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7655 		    "Number of SYN retransmissions before abort");
7656 
7657 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7658 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7659 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7660 		    "Number of retransmissions before abort");
7661 
7662 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7663 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7664 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7665 		    "Number of keepalive probes before abort");
7666 
7667 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7668 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7669 		    "TOE retransmit backoffs");
7670 		children = SYSCTL_CHILDREN(oid);
7671 		for (i = 0; i < 16; i++) {
7672 			snprintf(s, sizeof(s), "%u", i);
7673 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7674 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7675 			    i, sysctl_tp_backoff, "IU",
7676 			    "TOE retransmit backoff");
7677 		}
7678 	}
7679 #endif
7680 }
7681 
7682 void
7683 vi_sysctls(struct vi_info *vi)
7684 {
7685 	struct sysctl_ctx_list *ctx;
7686 	struct sysctl_oid *oid;
7687 	struct sysctl_oid_list *children;
7688 
7689 	ctx = device_get_sysctl_ctx(vi->dev);
7690 
7691 	/*
7692 	 * dev.v?(cxgbe|cxl).X.
7693 	 */
7694 	oid = device_get_sysctl_tree(vi->dev);
7695 	children = SYSCTL_CHILDREN(oid);
7696 
7697 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7698 	    vi->viid, "VI identifer");
7699 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7700 	    &vi->nrxq, 0, "# of rx queues");
7701 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7702 	    &vi->ntxq, 0, "# of tx queues");
7703 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7704 	    &vi->first_rxq, 0, "index of first rx queue");
7705 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7706 	    &vi->first_txq, 0, "index of first tx queue");
7707 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7708 	    vi->rss_base, "start of RSS indirection table");
7709 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7710 	    vi->rss_size, "size of RSS indirection table");
7711 
7712 	if (IS_MAIN_VI(vi)) {
7713 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7714 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7715 		    sysctl_noflowq, "IU",
7716 		    "Reserve queue 0 for non-flowid packets");
7717 	}
7718 
7719 	if (vi->adapter->flags & IS_VF) {
7720 		MPASS(vi->flags & TX_USES_VM_WR);
7721 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7722 		    NULL, 1, "use VM work requests for transmit");
7723 	} else {
7724 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7725 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7726 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7727 	}
7728 
7729 #ifdef TCP_OFFLOAD
7730 	if (vi->nofldrxq != 0) {
7731 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7732 		    &vi->nofldrxq, 0,
7733 		    "# of rx queues for offloaded TCP connections");
7734 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7735 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7736 		    "index of first TOE rx queue");
7737 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7738 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7739 		    sysctl_holdoff_tmr_idx_ofld, "I",
7740 		    "holdoff timer index for TOE queues");
7741 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7742 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7743 		    sysctl_holdoff_pktc_idx_ofld, "I",
7744 		    "holdoff packet counter index for TOE queues");
7745 	}
7746 #endif
7747 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7748 	if (vi->nofldtxq != 0) {
7749 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7750 		    &vi->nofldtxq, 0,
7751 		    "# of tx queues for TOE/ETHOFLD");
7752 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7753 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7754 		    "index of first TOE/ETHOFLD tx queue");
7755 	}
7756 #endif
7757 #ifdef DEV_NETMAP
7758 	if (vi->nnmrxq != 0) {
7759 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7760 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7761 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7762 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7763 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7764 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7765 		    "index of first netmap rx queue");
7766 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7767 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7768 		    "index of first netmap tx queue");
7769 	}
7770 #endif
7771 
7772 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7773 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7774 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7775 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7776 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7777 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7778 
7779 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7780 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7781 	    sysctl_qsize_rxq, "I", "rx queue size");
7782 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7783 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7784 	    sysctl_qsize_txq, "I", "tx queue size");
7785 }
7786 
7787 static void
7788 cxgbe_sysctls(struct port_info *pi)
7789 {
7790 	struct sysctl_ctx_list *ctx;
7791 	struct sysctl_oid *oid;
7792 	struct sysctl_oid_list *children, *children2;
7793 	struct adapter *sc = pi->adapter;
7794 	int i;
7795 	char name[16];
7796 	static char *tc_flags = {"\20\1USER"};
7797 
7798 	ctx = device_get_sysctl_ctx(pi->dev);
7799 
7800 	/*
7801 	 * dev.cxgbe.X.
7802 	 */
7803 	oid = device_get_sysctl_tree(pi->dev);
7804 	children = SYSCTL_CHILDREN(oid);
7805 
7806 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7807 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7808 	    sysctl_linkdnrc, "A", "reason why link is down");
7809 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7810 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7811 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7812 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
7813 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7814 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7815 		    sysctl_btphy, "I", "PHY firmware version");
7816 	}
7817 
7818 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7819 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7820 	    sysctl_pause_settings, "A",
7821 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7822 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fec",
7823 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7824 	    sysctl_fec, "A",
7825 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7826 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7827 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7828 	    "FEC recommended by the cable/transceiver");
7829 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7830 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7831 	    sysctl_autoneg, "I",
7832 	    "autonegotiation (-1 = not supported)");
7833 
7834 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7835 	    &pi->link_cfg.pcaps, 0, "port capabilities");
7836 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7837 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
7838 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7839 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7840 
7841 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7842 	    port_top_speed(pi), "max speed (in Gbps)");
7843 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7844 	    pi->mps_bg_map, "MPS buffer group map");
7845 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
7846 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
7847 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_c_chan", CTLFLAG_RD, NULL,
7848 	    pi->rx_c_chan, "TP rx c-channel");
7849 
7850 	if (sc->flags & IS_VF)
7851 		return;
7852 
7853 	/*
7854 	 * dev.(cxgbe|cxl).X.tc.
7855 	 */
7856 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
7857 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7858 	    "Tx scheduler traffic classes (cl_rl)");
7859 	children2 = SYSCTL_CHILDREN(oid);
7860 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
7861 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
7862 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
7863 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
7864 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
7865 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
7866 	for (i = 0; i < sc->params.nsched_cls; i++) {
7867 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
7868 
7869 		snprintf(name, sizeof(name), "%d", i);
7870 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
7871 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
7872 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
7873 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
7874 		    CTLFLAG_RD, &tc->state, 0, "current state");
7875 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
7876 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
7877 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
7878 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
7879 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
7880 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
7881 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7882 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
7883 		    "traffic class parameters");
7884 	}
7885 
7886 	/*
7887 	 * dev.cxgbe.X.stats.
7888 	 */
7889 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
7890 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
7891 	children = SYSCTL_CHILDREN(oid);
7892 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
7893 	    &pi->tx_parse_error, 0,
7894 	    "# of tx packets with invalid length or # of segments");
7895 
7896 #define T4_REGSTAT(name, stat, desc) \
7897     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
7898         CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
7899 	(is_t4(sc) ? PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L) : \
7900 	T5_PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L)), \
7901         sysctl_handle_t4_reg64, "QU", desc)
7902 
7903 /* We get these from port_stats and they may be stale by up to 1s */
7904 #define T4_PORTSTAT(name, desc) \
7905 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
7906 	    &pi->stats.name, desc)
7907 
7908 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
7909 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
7910 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
7911 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
7912 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
7913 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
7914 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
7915 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
7916 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
7917 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
7918 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
7919 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
7920 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
7921 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
7922 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
7923 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
7924 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
7925 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
7926 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
7927 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
7928 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
7929 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
7930 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
7931 
7932 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
7933 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
7934 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
7935 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
7936 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
7937 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
7938 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
7939 	if (is_t6(sc)) {
7940 		T4_PORTSTAT(rx_fcs_err,
7941 		    "# of frames received with bad FCS since last link up");
7942 	} else {
7943 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
7944 		    "# of frames received with bad FCS");
7945 	}
7946 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
7947 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
7948 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
7949 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
7950 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
7951 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
7952 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
7953 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
7954 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
7955 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
7956 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
7957 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
7958 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
7959 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
7960 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
7961 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
7962 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
7963 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
7964 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
7965 
7966 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
7967 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
7968 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
7969 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
7970 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
7971 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
7972 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
7973 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
7974 
7975 #undef T4_REGSTAT
7976 #undef T4_PORTSTAT
7977 }
7978 
7979 static int
7980 sysctl_int_array(SYSCTL_HANDLER_ARGS)
7981 {
7982 	int rc, *i, space = 0;
7983 	struct sbuf sb;
7984 
7985 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
7986 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
7987 		if (space)
7988 			sbuf_printf(&sb, " ");
7989 		sbuf_printf(&sb, "%d", *i);
7990 		space = 1;
7991 	}
7992 	rc = sbuf_finish(&sb);
7993 	sbuf_delete(&sb);
7994 	return (rc);
7995 }
7996 
7997 static int
7998 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
7999 {
8000 	int rc;
8001 	struct sbuf *sb;
8002 
8003 	rc = sysctl_wire_old_buffer(req, 0);
8004 	if (rc != 0)
8005 		return(rc);
8006 
8007 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8008 	if (sb == NULL)
8009 		return (ENOMEM);
8010 
8011 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8012 	rc = sbuf_finish(sb);
8013 	sbuf_delete(sb);
8014 
8015 	return (rc);
8016 }
8017 
8018 static int
8019 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8020 {
8021 	int rc;
8022 	struct sbuf *sb;
8023 
8024 	rc = sysctl_wire_old_buffer(req, 0);
8025 	if (rc != 0)
8026 		return(rc);
8027 
8028 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8029 	if (sb == NULL)
8030 		return (ENOMEM);
8031 
8032 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8033 	rc = sbuf_finish(sb);
8034 	sbuf_delete(sb);
8035 
8036 	return (rc);
8037 }
8038 
8039 static int
8040 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8041 {
8042 	struct port_info *pi = arg1;
8043 	int op = arg2;
8044 	struct adapter *sc = pi->adapter;
8045 	u_int v;
8046 	int rc;
8047 
8048 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8049 	if (rc)
8050 		return (rc);
8051 	if (hw_off_limits(sc))
8052 		rc = ENXIO;
8053 	else {
8054 		/* XXX: magic numbers */
8055 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8056 		    op ? 0x20 : 0xc820, &v);
8057 	}
8058 	end_synchronized_op(sc, 0);
8059 	if (rc)
8060 		return (rc);
8061 	if (op == 0)
8062 		v /= 256;
8063 
8064 	rc = sysctl_handle_int(oidp, &v, 0, req);
8065 	return (rc);
8066 }
8067 
8068 static int
8069 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8070 {
8071 	struct vi_info *vi = arg1;
8072 	int rc, val;
8073 
8074 	val = vi->rsrv_noflowq;
8075 	rc = sysctl_handle_int(oidp, &val, 0, req);
8076 	if (rc != 0 || req->newptr == NULL)
8077 		return (rc);
8078 
8079 	if ((val >= 1) && (vi->ntxq > 1))
8080 		vi->rsrv_noflowq = 1;
8081 	else
8082 		vi->rsrv_noflowq = 0;
8083 
8084 	return (rc);
8085 }
8086 
8087 static int
8088 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8089 {
8090 	struct vi_info *vi = arg1;
8091 	struct adapter *sc = vi->adapter;
8092 	int rc, val, i;
8093 
8094 	MPASS(!(sc->flags & IS_VF));
8095 
8096 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8097 	rc = sysctl_handle_int(oidp, &val, 0, req);
8098 	if (rc != 0 || req->newptr == NULL)
8099 		return (rc);
8100 
8101 	if (val != 0 && val != 1)
8102 		return (EINVAL);
8103 
8104 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8105 	    "t4txvm");
8106 	if (rc)
8107 		return (rc);
8108 	if (hw_off_limits(sc))
8109 		rc = ENXIO;
8110 	else if (vi->ifp->if_drv_flags & IFF_DRV_RUNNING) {
8111 		/*
8112 		 * We don't want parse_pkt to run with one setting (VF or PF)
8113 		 * and then eth_tx to see a different setting but still use
8114 		 * stale information calculated by parse_pkt.
8115 		 */
8116 		rc = EBUSY;
8117 	} else {
8118 		struct port_info *pi = vi->pi;
8119 		struct sge_txq *txq;
8120 		uint32_t ctrl0;
8121 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8122 
8123 		if (val) {
8124 			vi->flags |= TX_USES_VM_WR;
8125 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
8126 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8127 			    V_TXPKT_INTF(pi->tx_chan));
8128 			if (!(sc->flags & IS_VF))
8129 				npkt--;
8130 		} else {
8131 			vi->flags &= ~TX_USES_VM_WR;
8132 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
8133 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8134 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8135 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8136 		}
8137 		for_each_txq(vi, i, txq) {
8138 			txq->cpl_ctrl0 = ctrl0;
8139 			txq->txp.max_npkt = npkt;
8140 		}
8141 	}
8142 	end_synchronized_op(sc, LOCK_HELD);
8143 	return (rc);
8144 }
8145 
8146 static int
8147 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8148 {
8149 	struct vi_info *vi = arg1;
8150 	struct adapter *sc = vi->adapter;
8151 	int idx, rc, i;
8152 	struct sge_rxq *rxq;
8153 	uint8_t v;
8154 
8155 	idx = vi->tmr_idx;
8156 
8157 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8158 	if (rc != 0 || req->newptr == NULL)
8159 		return (rc);
8160 
8161 	if (idx < 0 || idx >= SGE_NTIMERS)
8162 		return (EINVAL);
8163 
8164 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8165 	    "t4tmr");
8166 	if (rc)
8167 		return (rc);
8168 
8169 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8170 	for_each_rxq(vi, i, rxq) {
8171 #ifdef atomic_store_rel_8
8172 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8173 #else
8174 		rxq->iq.intr_params = v;
8175 #endif
8176 	}
8177 	vi->tmr_idx = idx;
8178 
8179 	end_synchronized_op(sc, LOCK_HELD);
8180 	return (0);
8181 }
8182 
8183 static int
8184 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8185 {
8186 	struct vi_info *vi = arg1;
8187 	struct adapter *sc = vi->adapter;
8188 	int idx, rc;
8189 
8190 	idx = vi->pktc_idx;
8191 
8192 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8193 	if (rc != 0 || req->newptr == NULL)
8194 		return (rc);
8195 
8196 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8197 		return (EINVAL);
8198 
8199 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8200 	    "t4pktc");
8201 	if (rc)
8202 		return (rc);
8203 
8204 	if (vi->flags & VI_INIT_DONE)
8205 		rc = EBUSY; /* cannot be changed once the queues are created */
8206 	else
8207 		vi->pktc_idx = idx;
8208 
8209 	end_synchronized_op(sc, LOCK_HELD);
8210 	return (rc);
8211 }
8212 
8213 static int
8214 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8215 {
8216 	struct vi_info *vi = arg1;
8217 	struct adapter *sc = vi->adapter;
8218 	int qsize, rc;
8219 
8220 	qsize = vi->qsize_rxq;
8221 
8222 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8223 	if (rc != 0 || req->newptr == NULL)
8224 		return (rc);
8225 
8226 	if (qsize < 128 || (qsize & 7))
8227 		return (EINVAL);
8228 
8229 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8230 	    "t4rxqs");
8231 	if (rc)
8232 		return (rc);
8233 
8234 	if (vi->flags & VI_INIT_DONE)
8235 		rc = EBUSY; /* cannot be changed once the queues are created */
8236 	else
8237 		vi->qsize_rxq = qsize;
8238 
8239 	end_synchronized_op(sc, LOCK_HELD);
8240 	return (rc);
8241 }
8242 
8243 static int
8244 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8245 {
8246 	struct vi_info *vi = arg1;
8247 	struct adapter *sc = vi->adapter;
8248 	int qsize, rc;
8249 
8250 	qsize = vi->qsize_txq;
8251 
8252 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8253 	if (rc != 0 || req->newptr == NULL)
8254 		return (rc);
8255 
8256 	if (qsize < 128 || qsize > 65536)
8257 		return (EINVAL);
8258 
8259 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8260 	    "t4txqs");
8261 	if (rc)
8262 		return (rc);
8263 
8264 	if (vi->flags & VI_INIT_DONE)
8265 		rc = EBUSY; /* cannot be changed once the queues are created */
8266 	else
8267 		vi->qsize_txq = qsize;
8268 
8269 	end_synchronized_op(sc, LOCK_HELD);
8270 	return (rc);
8271 }
8272 
8273 static int
8274 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8275 {
8276 	struct port_info *pi = arg1;
8277 	struct adapter *sc = pi->adapter;
8278 	struct link_config *lc = &pi->link_cfg;
8279 	int rc;
8280 
8281 	if (req->newptr == NULL) {
8282 		struct sbuf *sb;
8283 		static char *bits = "\20\1RX\2TX\3AUTO";
8284 
8285 		rc = sysctl_wire_old_buffer(req, 0);
8286 		if (rc != 0)
8287 			return(rc);
8288 
8289 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8290 		if (sb == NULL)
8291 			return (ENOMEM);
8292 
8293 		if (lc->link_ok) {
8294 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8295 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8296 		} else {
8297 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8298 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8299 		}
8300 		rc = sbuf_finish(sb);
8301 		sbuf_delete(sb);
8302 	} else {
8303 		char s[2];
8304 		int n;
8305 
8306 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8307 		    PAUSE_AUTONEG));
8308 		s[1] = 0;
8309 
8310 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8311 		if (rc != 0)
8312 			return(rc);
8313 
8314 		if (s[1] != 0)
8315 			return (EINVAL);
8316 		if (s[0] < '0' || s[0] > '9')
8317 			return (EINVAL);	/* not a number */
8318 		n = s[0] - '0';
8319 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8320 			return (EINVAL);	/* some other bit is set too */
8321 
8322 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8323 		    "t4PAUSE");
8324 		if (rc)
8325 			return (rc);
8326 		if (!hw_off_limits(sc)) {
8327 			PORT_LOCK(pi);
8328 			lc->requested_fc = n;
8329 			fixup_link_config(pi);
8330 			if (pi->up_vis > 0)
8331 				rc = apply_link_config(pi);
8332 			set_current_media(pi);
8333 			PORT_UNLOCK(pi);
8334 		}
8335 		end_synchronized_op(sc, 0);
8336 	}
8337 
8338 	return (rc);
8339 }
8340 
8341 static int
8342 sysctl_fec(SYSCTL_HANDLER_ARGS)
8343 {
8344 	struct port_info *pi = arg1;
8345 	struct adapter *sc = pi->adapter;
8346 	struct link_config *lc = &pi->link_cfg;
8347 	int rc;
8348 	int8_t old;
8349 
8350 	if (req->newptr == NULL) {
8351 		struct sbuf *sb;
8352 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8353 		    "\5RSVD3\6auto\7module";
8354 
8355 		rc = sysctl_wire_old_buffer(req, 0);
8356 		if (rc != 0)
8357 			return(rc);
8358 
8359 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8360 		if (sb == NULL)
8361 			return (ENOMEM);
8362 
8363 		/*
8364 		 * Display the requested_fec when the link is down -- the actual
8365 		 * FEC makes sense only when the link is up.
8366 		 */
8367 		if (lc->link_ok) {
8368 			sbuf_printf(sb, "%b", (lc->fec & M_FW_PORT_CAP32_FEC) |
8369 			    (lc->requested_fec & (FEC_AUTO | FEC_MODULE)),
8370 			    bits);
8371 		} else {
8372 			sbuf_printf(sb, "%b", lc->requested_fec, bits);
8373 		}
8374 		rc = sbuf_finish(sb);
8375 		sbuf_delete(sb);
8376 	} else {
8377 		char s[8];
8378 		int n;
8379 
8380 		snprintf(s, sizeof(s), "%d",
8381 		    lc->requested_fec == FEC_AUTO ? -1 :
8382 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8383 
8384 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8385 		if (rc != 0)
8386 			return(rc);
8387 
8388 		n = strtol(&s[0], NULL, 0);
8389 		if (n < 0 || n & FEC_AUTO)
8390 			n = FEC_AUTO;
8391 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8392 			return (EINVAL);/* some other bit is set too */
8393 
8394 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8395 		    "t4fec");
8396 		if (rc)
8397 			return (rc);
8398 		PORT_LOCK(pi);
8399 		old = lc->requested_fec;
8400 		if (n == FEC_AUTO)
8401 			lc->requested_fec = FEC_AUTO;
8402 		else if (n == 0 || n == FEC_NONE)
8403 			lc->requested_fec = FEC_NONE;
8404 		else {
8405 			if ((lc->pcaps |
8406 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8407 			    lc->pcaps) {
8408 				rc = ENOTSUP;
8409 				goto done;
8410 			}
8411 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8412 			    FEC_MODULE);
8413 		}
8414 		if (!hw_off_limits(sc)) {
8415 			fixup_link_config(pi);
8416 			if (pi->up_vis > 0) {
8417 				rc = apply_link_config(pi);
8418 				if (rc != 0) {
8419 					lc->requested_fec = old;
8420 					if (rc == FW_EPROTO)
8421 						rc = ENOTSUP;
8422 				}
8423 			}
8424 		}
8425 done:
8426 		PORT_UNLOCK(pi);
8427 		end_synchronized_op(sc, 0);
8428 	}
8429 
8430 	return (rc);
8431 }
8432 
8433 static int
8434 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8435 {
8436 	struct port_info *pi = arg1;
8437 	struct adapter *sc = pi->adapter;
8438 	struct link_config *lc = &pi->link_cfg;
8439 	int rc;
8440 	int8_t fec;
8441 	struct sbuf *sb;
8442 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8443 
8444 	rc = sysctl_wire_old_buffer(req, 0);
8445 	if (rc != 0)
8446 		return (rc);
8447 
8448 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8449 	if (sb == NULL)
8450 		return (ENOMEM);
8451 
8452 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8453 		rc = EBUSY;
8454 		goto done;
8455 	}
8456 	if (hw_off_limits(sc)) {
8457 		rc = ENXIO;
8458 		goto done;
8459 	}
8460 	PORT_LOCK(pi);
8461 	if (pi->up_vis == 0) {
8462 		/*
8463 		 * If all the interfaces are administratively down the firmware
8464 		 * does not report transceiver changes.  Refresh port info here.
8465 		 * This is the only reason we have a synchronized op in this
8466 		 * function.  Just PORT_LOCK would have been enough otherwise.
8467 		 */
8468 		t4_update_port_info(pi);
8469 	}
8470 
8471 	fec = lc->fec_hint;
8472 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8473 	    !fec_supported(lc->pcaps)) {
8474 		sbuf_printf(sb, "n/a");
8475 	} else {
8476 		if (fec == 0)
8477 			fec = FEC_NONE;
8478 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8479 	}
8480 	rc = sbuf_finish(sb);
8481 	PORT_UNLOCK(pi);
8482 done:
8483 	sbuf_delete(sb);
8484 	end_synchronized_op(sc, 0);
8485 
8486 	return (rc);
8487 }
8488 
8489 static int
8490 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8491 {
8492 	struct port_info *pi = arg1;
8493 	struct adapter *sc = pi->adapter;
8494 	struct link_config *lc = &pi->link_cfg;
8495 	int rc, val;
8496 
8497 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8498 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8499 	else
8500 		val = -1;
8501 	rc = sysctl_handle_int(oidp, &val, 0, req);
8502 	if (rc != 0 || req->newptr == NULL)
8503 		return (rc);
8504 	if (val == 0)
8505 		val = AUTONEG_DISABLE;
8506 	else if (val == 1)
8507 		val = AUTONEG_ENABLE;
8508 	else
8509 		val = AUTONEG_AUTO;
8510 
8511 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8512 	    "t4aneg");
8513 	if (rc)
8514 		return (rc);
8515 	PORT_LOCK(pi);
8516 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8517 		rc = ENOTSUP;
8518 		goto done;
8519 	}
8520 	lc->requested_aneg = val;
8521 	if (!hw_off_limits(sc)) {
8522 		fixup_link_config(pi);
8523 		if (pi->up_vis > 0)
8524 			rc = apply_link_config(pi);
8525 		set_current_media(pi);
8526 	}
8527 done:
8528 	PORT_UNLOCK(pi);
8529 	end_synchronized_op(sc, 0);
8530 	return (rc);
8531 }
8532 
8533 static int
8534 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8535 {
8536 	struct adapter *sc = arg1;
8537 	int rc, reg = arg2;
8538 	uint64_t val;
8539 
8540 	mtx_lock(&sc->reg_lock);
8541 	if (hw_off_limits(sc))
8542 		rc = ENXIO;
8543 	else {
8544 		rc = 0;
8545 		val = t4_read_reg64(sc, reg);
8546 	}
8547 	mtx_unlock(&sc->reg_lock);
8548 	if (rc == 0)
8549 		rc = sysctl_handle_64(oidp, &val, 0, req);
8550 	return (rc);
8551 }
8552 
8553 static int
8554 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8555 {
8556 	struct adapter *sc = arg1;
8557 	int rc, t;
8558 	uint32_t param, val;
8559 
8560 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8561 	if (rc)
8562 		return (rc);
8563 	if (hw_off_limits(sc))
8564 		rc = ENXIO;
8565 	else {
8566 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8567 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8568 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8569 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8570 	}
8571 	end_synchronized_op(sc, 0);
8572 	if (rc)
8573 		return (rc);
8574 
8575 	/* unknown is returned as 0 but we display -1 in that case */
8576 	t = val == 0 ? -1 : val;
8577 
8578 	rc = sysctl_handle_int(oidp, &t, 0, req);
8579 	return (rc);
8580 }
8581 
8582 static int
8583 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8584 {
8585 	struct adapter *sc = arg1;
8586 	int rc;
8587 	uint32_t param, val;
8588 
8589 	if (sc->params.core_vdd == 0) {
8590 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8591 		    "t4vdd");
8592 		if (rc)
8593 			return (rc);
8594 		if (hw_off_limits(sc))
8595 			rc = ENXIO;
8596 		else {
8597 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8598 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8599 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8600 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8601 			    &param, &val);
8602 		}
8603 		end_synchronized_op(sc, 0);
8604 		if (rc)
8605 			return (rc);
8606 		sc->params.core_vdd = val;
8607 	}
8608 
8609 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8610 }
8611 
8612 static int
8613 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8614 {
8615 	struct adapter *sc = arg1;
8616 	int rc, v;
8617 	uint32_t param, val;
8618 
8619 	v = sc->sensor_resets;
8620 	rc = sysctl_handle_int(oidp, &v, 0, req);
8621 	if (rc != 0 || req->newptr == NULL || v <= 0)
8622 		return (rc);
8623 
8624 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8625 	    chip_id(sc) < CHELSIO_T5)
8626 		return (ENOTSUP);
8627 
8628 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8629 	if (rc)
8630 		return (rc);
8631 	if (hw_off_limits(sc))
8632 		rc = ENXIO;
8633 	else {
8634 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8635 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8636 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8637 		val = 1;
8638 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8639 	}
8640 	end_synchronized_op(sc, 0);
8641 	if (rc == 0)
8642 		sc->sensor_resets++;
8643 	return (rc);
8644 }
8645 
8646 static int
8647 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8648 {
8649 	struct adapter *sc = arg1;
8650 	struct sbuf *sb;
8651 	int rc;
8652 	uint32_t param, val;
8653 
8654 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8655 	if (rc)
8656 		return (rc);
8657 	if (hw_off_limits(sc))
8658 		rc = ENXIO;
8659 	else {
8660 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8661 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8662 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8663 	}
8664 	end_synchronized_op(sc, 0);
8665 	if (rc)
8666 		return (rc);
8667 
8668 	rc = sysctl_wire_old_buffer(req, 0);
8669 	if (rc != 0)
8670 		return (rc);
8671 
8672 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8673 	if (sb == NULL)
8674 		return (ENOMEM);
8675 
8676 	if (val == 0xffffffff) {
8677 		/* Only debug and custom firmwares report load averages. */
8678 		sbuf_printf(sb, "not available");
8679 	} else {
8680 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8681 		    (val >> 16) & 0xff);
8682 	}
8683 	rc = sbuf_finish(sb);
8684 	sbuf_delete(sb);
8685 
8686 	return (rc);
8687 }
8688 
8689 static int
8690 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8691 {
8692 	struct adapter *sc = arg1;
8693 	struct sbuf *sb;
8694 	int rc, i;
8695 	uint16_t incr[NMTUS][NCCTRL_WIN];
8696 	static const char *dec_fac[] = {
8697 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8698 		"0.9375"
8699 	};
8700 
8701 	rc = sysctl_wire_old_buffer(req, 0);
8702 	if (rc != 0)
8703 		return (rc);
8704 
8705 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8706 	if (sb == NULL)
8707 		return (ENOMEM);
8708 
8709 	mtx_lock(&sc->reg_lock);
8710 	if (hw_off_limits(sc))
8711 		rc = ENXIO;
8712 	else
8713 		t4_read_cong_tbl(sc, incr);
8714 	mtx_unlock(&sc->reg_lock);
8715 	if (rc)
8716 		goto done;
8717 
8718 	for (i = 0; i < NCCTRL_WIN; ++i) {
8719 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8720 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8721 		    incr[5][i], incr[6][i], incr[7][i]);
8722 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8723 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8724 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8725 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8726 	}
8727 
8728 	rc = sbuf_finish(sb);
8729 done:
8730 	sbuf_delete(sb);
8731 	return (rc);
8732 }
8733 
8734 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8735 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8736 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8737 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8738 };
8739 
8740 static int
8741 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8742 {
8743 	struct adapter *sc = arg1;
8744 	struct sbuf *sb;
8745 	int rc, i, n, qid = arg2;
8746 	uint32_t *buf, *p;
8747 	char *qtype;
8748 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8749 
8750 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8751 	    ("%s: bad qid %d\n", __func__, qid));
8752 
8753 	if (qid < CIM_NUM_IBQ) {
8754 		/* inbound queue */
8755 		qtype = "IBQ";
8756 		n = 4 * CIM_IBQ_SIZE;
8757 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8758 		mtx_lock(&sc->reg_lock);
8759 		if (hw_off_limits(sc))
8760 			rc = -ENXIO;
8761 		else
8762 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8763 		mtx_unlock(&sc->reg_lock);
8764 	} else {
8765 		/* outbound queue */
8766 		qtype = "OBQ";
8767 		qid -= CIM_NUM_IBQ;
8768 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8769 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8770 		mtx_lock(&sc->reg_lock);
8771 		if (hw_off_limits(sc))
8772 			rc = -ENXIO;
8773 		else
8774 			rc = t4_read_cim_obq(sc, qid, buf, n);
8775 		mtx_unlock(&sc->reg_lock);
8776 	}
8777 
8778 	if (rc < 0) {
8779 		rc = -rc;
8780 		goto done;
8781 	}
8782 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
8783 
8784 	rc = sysctl_wire_old_buffer(req, 0);
8785 	if (rc != 0)
8786 		goto done;
8787 
8788 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8789 	if (sb == NULL) {
8790 		rc = ENOMEM;
8791 		goto done;
8792 	}
8793 
8794 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8795 	for (i = 0, p = buf; i < n; i += 16, p += 4)
8796 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
8797 		    p[2], p[3]);
8798 
8799 	rc = sbuf_finish(sb);
8800 	sbuf_delete(sb);
8801 done:
8802 	free(buf, M_CXGBE);
8803 	return (rc);
8804 }
8805 
8806 static void
8807 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8808 {
8809 	uint32_t *p;
8810 
8811 	sbuf_printf(sb, "Status   Data      PC%s",
8812 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8813 	    "     LS0Stat  LS0Addr             LS0Data");
8814 
8815 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
8816 		if (cfg & F_UPDBGLACAPTPCONLY) {
8817 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
8818 			    p[6], p[7]);
8819 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
8820 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
8821 			    p[4] & 0xff, p[5] >> 8);
8822 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
8823 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8824 			    p[1] & 0xf, p[2] >> 4);
8825 		} else {
8826 			sbuf_printf(sb,
8827 			    "\n  %02x   %x%07x %x%07x %08x %08x "
8828 			    "%08x%08x%08x%08x",
8829 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8830 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
8831 			    p[6], p[7]);
8832 		}
8833 	}
8834 }
8835 
8836 static void
8837 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8838 {
8839 	uint32_t *p;
8840 
8841 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
8842 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8843 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
8844 
8845 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
8846 		if (cfg & F_UPDBGLACAPTPCONLY) {
8847 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
8848 			    p[3] & 0xff, p[2], p[1], p[0]);
8849 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
8850 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
8851 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
8852 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
8853 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
8854 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
8855 			    p[6] >> 16);
8856 		} else {
8857 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
8858 			    "%08x %08x %08x %08x %08x %08x",
8859 			    (p[9] >> 16) & 0xff,
8860 			    p[9] & 0xffff, p[8] >> 16,
8861 			    p[8] & 0xffff, p[7] >> 16,
8862 			    p[7] & 0xffff, p[6] >> 16,
8863 			    p[2], p[1], p[0], p[5], p[4], p[3]);
8864 		}
8865 	}
8866 }
8867 
8868 static int
8869 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
8870 {
8871 	uint32_t cfg, *buf;
8872 	int rc;
8873 
8874 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
8875 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
8876 	    M_ZERO | flags);
8877 	if (buf == NULL)
8878 		return (ENOMEM);
8879 
8880 	mtx_lock(&sc->reg_lock);
8881 	if (hw_off_limits(sc))
8882 		rc = ENXIO;
8883 	else {
8884 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
8885 		if (rc == 0)
8886 			rc = -t4_cim_read_la(sc, buf, NULL);
8887 	}
8888 	mtx_unlock(&sc->reg_lock);
8889 	if (rc == 0) {
8890 		if (chip_id(sc) < CHELSIO_T6)
8891 			sbuf_cim_la4(sc, sb, buf, cfg);
8892 		else
8893 			sbuf_cim_la6(sc, sb, buf, cfg);
8894 	}
8895 	free(buf, M_CXGBE);
8896 	return (rc);
8897 }
8898 
8899 static int
8900 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
8901 {
8902 	struct adapter *sc = arg1;
8903 	struct sbuf *sb;
8904 	int rc;
8905 
8906 	rc = sysctl_wire_old_buffer(req, 0);
8907 	if (rc != 0)
8908 		return (rc);
8909 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8910 	if (sb == NULL)
8911 		return (ENOMEM);
8912 
8913 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
8914 	if (rc == 0)
8915 		rc = sbuf_finish(sb);
8916 	sbuf_delete(sb);
8917 	return (rc);
8918 }
8919 
8920 bool
8921 t4_os_dump_cimla(struct adapter *sc, int arg, bool verbose)
8922 {
8923 	struct sbuf sb;
8924 	int rc;
8925 
8926 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
8927 		return (false);
8928 	rc = sbuf_cim_la(sc, &sb, M_NOWAIT);
8929 	if (rc == 0) {
8930 		rc = sbuf_finish(&sb);
8931 		if (rc == 0) {
8932 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s",
8933 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
8934 		}
8935 	}
8936 	sbuf_delete(&sb);
8937 	return (false);
8938 }
8939 
8940 static int
8941 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
8942 {
8943 	struct adapter *sc = arg1;
8944 	u_int i;
8945 	struct sbuf *sb;
8946 	uint32_t *buf, *p;
8947 	int rc;
8948 
8949 	rc = sysctl_wire_old_buffer(req, 0);
8950 	if (rc != 0)
8951 		return (rc);
8952 
8953 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8954 	if (sb == NULL)
8955 		return (ENOMEM);
8956 
8957 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
8958 	    M_ZERO | M_WAITOK);
8959 
8960 	mtx_lock(&sc->reg_lock);
8961 	if (hw_off_limits(sc))
8962 		rc = ENXIO;
8963 	else
8964 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
8965 	mtx_unlock(&sc->reg_lock);
8966 	if (rc)
8967 		goto done;
8968 
8969 	p = buf;
8970 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
8971 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
8972 		    p[1], p[0]);
8973 	}
8974 
8975 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
8976 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
8977 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
8978 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
8979 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
8980 		    (p[1] >> 2) | ((p[2] & 3) << 30),
8981 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
8982 		    p[0] & 1);
8983 	}
8984 	rc = sbuf_finish(sb);
8985 done:
8986 	sbuf_delete(sb);
8987 	free(buf, M_CXGBE);
8988 	return (rc);
8989 }
8990 
8991 static int
8992 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
8993 {
8994 	struct adapter *sc = arg1;
8995 	u_int i;
8996 	struct sbuf *sb;
8997 	uint32_t *buf, *p;
8998 	int rc;
8999 
9000 	rc = sysctl_wire_old_buffer(req, 0);
9001 	if (rc != 0)
9002 		return (rc);
9003 
9004 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9005 	if (sb == NULL)
9006 		return (ENOMEM);
9007 
9008 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9009 	    M_ZERO | M_WAITOK);
9010 
9011 	mtx_lock(&sc->reg_lock);
9012 	if (hw_off_limits(sc))
9013 		rc = ENXIO;
9014 	else
9015 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9016 	mtx_unlock(&sc->reg_lock);
9017 	if (rc)
9018 		goto done;
9019 
9020 	p = buf;
9021 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9022 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9023 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9024 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9025 		    p[4], p[3], p[2], p[1], p[0]);
9026 	}
9027 
9028 	sbuf_printf(sb, "\n\nCntl ID               Data");
9029 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9030 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9031 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9032 	}
9033 
9034 	rc = sbuf_finish(sb);
9035 done:
9036 	sbuf_delete(sb);
9037 	free(buf, M_CXGBE);
9038 	return (rc);
9039 }
9040 
9041 static int
9042 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9043 {
9044 	struct adapter *sc = arg1;
9045 	struct sbuf *sb;
9046 	int rc, i;
9047 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9048 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9049 	uint16_t thres[CIM_NUM_IBQ];
9050 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9051 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9052 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9053 
9054 	cim_num_obq = sc->chip_params->cim_num_obq;
9055 	if (is_t4(sc)) {
9056 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9057 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9058 	} else {
9059 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9060 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9061 	}
9062 	nq = CIM_NUM_IBQ + cim_num_obq;
9063 
9064 	mtx_lock(&sc->reg_lock);
9065 	if (hw_off_limits(sc))
9066 		rc = ENXIO;
9067 	else {
9068 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9069 		if (rc == 0) {
9070 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9071 			    obq_wr);
9072 			if (rc == 0)
9073 				t4_read_cimq_cfg(sc, base, size, thres);
9074 		}
9075 	}
9076 	mtx_unlock(&sc->reg_lock);
9077 	if (rc)
9078 		return (rc);
9079 
9080 	rc = sysctl_wire_old_buffer(req, 0);
9081 	if (rc != 0)
9082 		return (rc);
9083 
9084 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9085 	if (sb == NULL)
9086 		return (ENOMEM);
9087 
9088 	sbuf_printf(sb,
9089 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9090 
9091 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9092 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9093 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9094 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9095 		    G_QUEREMFLITS(p[2]) * 16);
9096 	for ( ; i < nq; i++, p += 4, wr += 2)
9097 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9098 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9099 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9100 		    G_QUEREMFLITS(p[2]) * 16);
9101 
9102 	rc = sbuf_finish(sb);
9103 	sbuf_delete(sb);
9104 
9105 	return (rc);
9106 }
9107 
9108 static int
9109 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9110 {
9111 	struct adapter *sc = arg1;
9112 	struct sbuf *sb;
9113 	int rc;
9114 	struct tp_cpl_stats stats;
9115 
9116 	rc = sysctl_wire_old_buffer(req, 0);
9117 	if (rc != 0)
9118 		return (rc);
9119 
9120 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9121 	if (sb == NULL)
9122 		return (ENOMEM);
9123 
9124 	mtx_lock(&sc->reg_lock);
9125 	if (hw_off_limits(sc))
9126 		rc = ENXIO;
9127 	else
9128 		t4_tp_get_cpl_stats(sc, &stats, 0);
9129 	mtx_unlock(&sc->reg_lock);
9130 	if (rc)
9131 		goto done;
9132 
9133 	if (sc->chip_params->nchan > 2) {
9134 		sbuf_printf(sb, "                 channel 0  channel 1"
9135 		    "  channel 2  channel 3");
9136 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9137 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9138 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9139 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9140 	} else {
9141 		sbuf_printf(sb, "                 channel 0  channel 1");
9142 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9143 		    stats.req[0], stats.req[1]);
9144 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9145 		    stats.rsp[0], stats.rsp[1]);
9146 	}
9147 
9148 	rc = sbuf_finish(sb);
9149 done:
9150 	sbuf_delete(sb);
9151 	return (rc);
9152 }
9153 
9154 static int
9155 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9156 {
9157 	struct adapter *sc = arg1;
9158 	struct sbuf *sb;
9159 	int rc;
9160 	struct tp_usm_stats stats;
9161 
9162 	rc = sysctl_wire_old_buffer(req, 0);
9163 	if (rc != 0)
9164 		return(rc);
9165 
9166 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9167 	if (sb == NULL)
9168 		return (ENOMEM);
9169 
9170 	mtx_lock(&sc->reg_lock);
9171 	if (hw_off_limits(sc))
9172 		rc = ENXIO;
9173 	else
9174 		t4_get_usm_stats(sc, &stats, 1);
9175 	mtx_unlock(&sc->reg_lock);
9176 	if (rc == 0) {
9177 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9178 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9179 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9180 		rc = sbuf_finish(sb);
9181 	}
9182 	sbuf_delete(sb);
9183 
9184 	return (rc);
9185 }
9186 
9187 static int
9188 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9189 {
9190 	struct adapter *sc = arg1;
9191 	struct sbuf *sb;
9192 	int rc;
9193 	struct tp_tid_stats stats;
9194 
9195 	rc = sysctl_wire_old_buffer(req, 0);
9196 	if (rc != 0)
9197 		return(rc);
9198 
9199 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9200 	if (sb == NULL)
9201 		return (ENOMEM);
9202 
9203 	mtx_lock(&sc->reg_lock);
9204 	if (hw_off_limits(sc))
9205 		rc = ENXIO;
9206 	else
9207 		t4_tp_get_tid_stats(sc, &stats, 1);
9208 	mtx_unlock(&sc->reg_lock);
9209 	if (rc == 0) {
9210 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9211 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9212 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9213 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9214 		rc = sbuf_finish(sb);
9215 	}
9216 	sbuf_delete(sb);
9217 
9218 	return (rc);
9219 }
9220 
9221 static const char * const devlog_level_strings[] = {
9222 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9223 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9224 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9225 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9226 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9227 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9228 };
9229 
9230 static const char * const devlog_facility_strings[] = {
9231 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9232 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9233 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9234 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9235 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9236 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9237 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9238 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9239 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9240 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9241 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9242 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9243 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9244 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9245 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9246 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9247 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9248 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9249 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9250 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9251 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9252 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9253 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9254 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9255 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9256 };
9257 
9258 static int
9259 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9260 {
9261 	int i, j, rc, nentries, first = 0;
9262 	struct devlog_params *dparams = &sc->params.devlog;
9263 	struct fw_devlog_e *buf, *e;
9264 	uint64_t ftstamp = UINT64_MAX;
9265 
9266 	if (dparams->addr == 0)
9267 		return (ENXIO);
9268 
9269 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9270 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9271 	if (buf == NULL)
9272 		return (ENOMEM);
9273 
9274 	mtx_lock(&sc->reg_lock);
9275 	if (hw_off_limits(sc))
9276 		rc = ENXIO;
9277 	else
9278 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9279 		    dparams->size);
9280 	mtx_unlock(&sc->reg_lock);
9281 	if (rc != 0)
9282 		goto done;
9283 
9284 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9285 	for (i = 0; i < nentries; i++) {
9286 		e = &buf[i];
9287 
9288 		if (e->timestamp == 0)
9289 			break;	/* end */
9290 
9291 		e->timestamp = be64toh(e->timestamp);
9292 		e->seqno = be32toh(e->seqno);
9293 		for (j = 0; j < 8; j++)
9294 			e->params[j] = be32toh(e->params[j]);
9295 
9296 		if (e->timestamp < ftstamp) {
9297 			ftstamp = e->timestamp;
9298 			first = i;
9299 		}
9300 	}
9301 
9302 	if (buf[first].timestamp == 0)
9303 		goto done;	/* nothing in the log */
9304 
9305 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9306 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9307 
9308 	i = first;
9309 	do {
9310 		e = &buf[i];
9311 		if (e->timestamp == 0)
9312 			break;	/* end */
9313 
9314 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9315 		    e->seqno, e->timestamp,
9316 		    (e->level < nitems(devlog_level_strings) ?
9317 			devlog_level_strings[e->level] : "UNKNOWN"),
9318 		    (e->facility < nitems(devlog_facility_strings) ?
9319 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9320 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9321 		    e->params[2], e->params[3], e->params[4],
9322 		    e->params[5], e->params[6], e->params[7]);
9323 
9324 		if (++i == nentries)
9325 			i = 0;
9326 	} while (i != first);
9327 done:
9328 	free(buf, M_CXGBE);
9329 	return (rc);
9330 }
9331 
9332 static int
9333 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9334 {
9335 	struct adapter *sc = arg1;
9336 	int rc;
9337 	struct sbuf *sb;
9338 
9339 	rc = sysctl_wire_old_buffer(req, 0);
9340 	if (rc != 0)
9341 		return (rc);
9342 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9343 	if (sb == NULL)
9344 		return (ENOMEM);
9345 
9346 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9347 	if (rc == 0)
9348 		rc = sbuf_finish(sb);
9349 	sbuf_delete(sb);
9350 	return (rc);
9351 }
9352 
9353 void
9354 t4_os_dump_devlog(struct adapter *sc)
9355 {
9356 	int rc;
9357 	struct sbuf sb;
9358 
9359 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
9360 		return;
9361 	rc = sbuf_devlog(sc, &sb, M_NOWAIT);
9362 	if (rc == 0) {
9363 		rc = sbuf_finish(&sb);
9364 		if (rc == 0) {
9365 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9366 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
9367 		}
9368 	}
9369 	sbuf_delete(&sb);
9370 }
9371 
9372 static int
9373 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9374 {
9375 	struct adapter *sc = arg1;
9376 	struct sbuf *sb;
9377 	int rc;
9378 	struct tp_fcoe_stats stats[MAX_NCHAN];
9379 	int i, nchan = sc->chip_params->nchan;
9380 
9381 	rc = sysctl_wire_old_buffer(req, 0);
9382 	if (rc != 0)
9383 		return (rc);
9384 
9385 	mtx_lock(&sc->reg_lock);
9386 	if (hw_off_limits(sc))
9387 		rc = ENXIO;
9388 	else {
9389 		for (i = 0; i < nchan; i++)
9390 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9391 	}
9392 	mtx_unlock(&sc->reg_lock);
9393 	if (rc != 0)
9394 		return (rc);
9395 
9396 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9397 	if (sb == NULL)
9398 		return (ENOMEM);
9399 
9400 	if (nchan > 2) {
9401 		sbuf_printf(sb, "                   channel 0        channel 1"
9402 		    "        channel 2        channel 3");
9403 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9404 		    stats[0].octets_ddp, stats[1].octets_ddp,
9405 		    stats[2].octets_ddp, stats[3].octets_ddp);
9406 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9407 		    stats[0].frames_ddp, stats[1].frames_ddp,
9408 		    stats[2].frames_ddp, stats[3].frames_ddp);
9409 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9410 		    stats[0].frames_drop, stats[1].frames_drop,
9411 		    stats[2].frames_drop, stats[3].frames_drop);
9412 	} else {
9413 		sbuf_printf(sb, "                   channel 0        channel 1");
9414 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9415 		    stats[0].octets_ddp, stats[1].octets_ddp);
9416 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9417 		    stats[0].frames_ddp, stats[1].frames_ddp);
9418 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9419 		    stats[0].frames_drop, stats[1].frames_drop);
9420 	}
9421 
9422 	rc = sbuf_finish(sb);
9423 	sbuf_delete(sb);
9424 
9425 	return (rc);
9426 }
9427 
9428 static int
9429 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9430 {
9431 	struct adapter *sc = arg1;
9432 	struct sbuf *sb;
9433 	int rc, i;
9434 	unsigned int map, kbps, ipg, mode;
9435 	unsigned int pace_tab[NTX_SCHED];
9436 
9437 	rc = sysctl_wire_old_buffer(req, 0);
9438 	if (rc != 0)
9439 		return (rc);
9440 
9441 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9442 	if (sb == NULL)
9443 		return (ENOMEM);
9444 
9445 	mtx_lock(&sc->reg_lock);
9446 	if (hw_off_limits(sc)) {
9447 		rc = ENXIO;
9448 		goto done;
9449 	}
9450 
9451 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9452 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9453 	t4_read_pace_tbl(sc, pace_tab);
9454 
9455 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9456 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9457 
9458 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9459 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9460 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9461 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9462 		if (kbps)
9463 			sbuf_printf(sb, "%9u     ", kbps);
9464 		else
9465 			sbuf_printf(sb, " disabled     ");
9466 
9467 		if (ipg)
9468 			sbuf_printf(sb, "%13u        ", ipg);
9469 		else
9470 			sbuf_printf(sb, "     disabled        ");
9471 
9472 		if (pace_tab[i])
9473 			sbuf_printf(sb, "%10u", pace_tab[i]);
9474 		else
9475 			sbuf_printf(sb, "  disabled");
9476 	}
9477 	rc = sbuf_finish(sb);
9478 done:
9479 	mtx_unlock(&sc->reg_lock);
9480 	sbuf_delete(sb);
9481 	return (rc);
9482 }
9483 
9484 static int
9485 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9486 {
9487 	struct adapter *sc = arg1;
9488 	struct sbuf *sb;
9489 	int rc, i, j;
9490 	uint64_t *p0, *p1;
9491 	struct lb_port_stats s[2];
9492 	static const char *stat_name[] = {
9493 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9494 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9495 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9496 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9497 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9498 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9499 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9500 	};
9501 
9502 	rc = sysctl_wire_old_buffer(req, 0);
9503 	if (rc != 0)
9504 		return (rc);
9505 
9506 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9507 	if (sb == NULL)
9508 		return (ENOMEM);
9509 
9510 	memset(s, 0, sizeof(s));
9511 
9512 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9513 		mtx_lock(&sc->reg_lock);
9514 		if (hw_off_limits(sc))
9515 			rc = ENXIO;
9516 		else {
9517 			t4_get_lb_stats(sc, i, &s[0]);
9518 			t4_get_lb_stats(sc, i + 1, &s[1]);
9519 		}
9520 		mtx_unlock(&sc->reg_lock);
9521 		if (rc != 0)
9522 			break;
9523 
9524 		p0 = &s[0].octets;
9525 		p1 = &s[1].octets;
9526 		sbuf_printf(sb, "%s                       Loopback %u"
9527 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9528 
9529 		for (j = 0; j < nitems(stat_name); j++)
9530 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9531 				   *p0++, *p1++);
9532 	}
9533 
9534 	rc = sbuf_finish(sb);
9535 	sbuf_delete(sb);
9536 
9537 	return (rc);
9538 }
9539 
9540 static int
9541 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9542 {
9543 	int rc = 0;
9544 	struct port_info *pi = arg1;
9545 	struct link_config *lc = &pi->link_cfg;
9546 	struct sbuf *sb;
9547 
9548 	rc = sysctl_wire_old_buffer(req, 0);
9549 	if (rc != 0)
9550 		return(rc);
9551 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9552 	if (sb == NULL)
9553 		return (ENOMEM);
9554 
9555 	if (lc->link_ok || lc->link_down_rc == 255)
9556 		sbuf_printf(sb, "n/a");
9557 	else
9558 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9559 
9560 	rc = sbuf_finish(sb);
9561 	sbuf_delete(sb);
9562 
9563 	return (rc);
9564 }
9565 
9566 struct mem_desc {
9567 	unsigned int base;
9568 	unsigned int limit;
9569 	unsigned int idx;
9570 };
9571 
9572 static int
9573 mem_desc_cmp(const void *a, const void *b)
9574 {
9575 	return ((const struct mem_desc *)a)->base -
9576 	       ((const struct mem_desc *)b)->base;
9577 }
9578 
9579 static void
9580 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9581     unsigned int to)
9582 {
9583 	unsigned int size;
9584 
9585 	if (from == to)
9586 		return;
9587 
9588 	size = to - from + 1;
9589 	if (size == 0)
9590 		return;
9591 
9592 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9593 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9594 }
9595 
9596 static int
9597 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9598 {
9599 	struct adapter *sc = arg1;
9600 	struct sbuf *sb;
9601 	int rc, i, n;
9602 	uint32_t lo, hi, used, alloc;
9603 	static const char *memory[] = {
9604 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9605 	};
9606 	static const char *region[] = {
9607 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9608 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9609 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9610 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9611 		"RQUDP region:", "PBL region:", "TXPBL region:",
9612 		"DBVFIFO region:", "ULPRX state:", "ULPTX state:",
9613 		"On-chip queues:", "TLS keys:",
9614 	};
9615 	struct mem_desc avail[4];
9616 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9617 	struct mem_desc *md = mem;
9618 
9619 	rc = sysctl_wire_old_buffer(req, 0);
9620 	if (rc != 0)
9621 		return (rc);
9622 
9623 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9624 	if (sb == NULL)
9625 		return (ENOMEM);
9626 
9627 	for (i = 0; i < nitems(mem); i++) {
9628 		mem[i].limit = 0;
9629 		mem[i].idx = i;
9630 	}
9631 
9632 	mtx_lock(&sc->reg_lock);
9633 	if (hw_off_limits(sc)) {
9634 		rc = ENXIO;
9635 		goto done;
9636 	}
9637 
9638 	/* Find and sort the populated memory ranges */
9639 	i = 0;
9640 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9641 	if (lo & F_EDRAM0_ENABLE) {
9642 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9643 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9644 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9645 		avail[i].idx = 0;
9646 		i++;
9647 	}
9648 	if (lo & F_EDRAM1_ENABLE) {
9649 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9650 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9651 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9652 		avail[i].idx = 1;
9653 		i++;
9654 	}
9655 	if (lo & F_EXT_MEM_ENABLE) {
9656 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9657 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9658 		avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9659 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9660 		i++;
9661 	}
9662 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9663 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9664 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9665 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9666 		avail[i].idx = 4;
9667 		i++;
9668 	}
9669 	if (is_t6(sc) && lo & F_HMA_MUX) {
9670 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9671 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9672 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9673 		avail[i].idx = 5;
9674 		i++;
9675 	}
9676 	MPASS(i <= nitems(avail));
9677 	if (!i)                                    /* no memory available */
9678 		goto done;
9679 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9680 
9681 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9682 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9683 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9684 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9685 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9686 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9687 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9688 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9689 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9690 
9691 	/* the next few have explicit upper bounds */
9692 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9693 	md->limit = md->base - 1 +
9694 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9695 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9696 	md++;
9697 
9698 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9699 	md->limit = md->base - 1 +
9700 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9701 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9702 	md++;
9703 
9704 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9705 		if (chip_id(sc) <= CHELSIO_T5)
9706 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9707 		else
9708 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9709 		md->limit = 0;
9710 	} else {
9711 		md->base = 0;
9712 		md->idx = nitems(region);  /* hide it */
9713 	}
9714 	md++;
9715 
9716 #define ulp_region(reg) \
9717 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9718 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9719 
9720 	ulp_region(RX_ISCSI);
9721 	ulp_region(RX_TDDP);
9722 	ulp_region(TX_TPT);
9723 	ulp_region(RX_STAG);
9724 	ulp_region(RX_RQ);
9725 	ulp_region(RX_RQUDP);
9726 	ulp_region(RX_PBL);
9727 	ulp_region(TX_PBL);
9728 #undef ulp_region
9729 
9730 	md->base = 0;
9731 	if (is_t4(sc))
9732 		md->idx = nitems(region);
9733 	else {
9734 		uint32_t size = 0;
9735 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9736 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9737 
9738 		if (is_t5(sc)) {
9739 			if (sge_ctrl & F_VFIFO_ENABLE)
9740 				size = fifo_size << 2;
9741 		} else
9742 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9743 
9744 		if (size) {
9745 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
9746 			md->limit = md->base + size - 1;
9747 		} else
9748 			md->idx = nitems(region);
9749 	}
9750 	md++;
9751 
9752 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9753 	md->limit = 0;
9754 	md++;
9755 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9756 	md->limit = 0;
9757 	md++;
9758 
9759 	md->base = sc->vres.ocq.start;
9760 	if (sc->vres.ocq.size)
9761 		md->limit = md->base + sc->vres.ocq.size - 1;
9762 	else
9763 		md->idx = nitems(region);  /* hide it */
9764 	md++;
9765 
9766 	md->base = sc->vres.key.start;
9767 	if (sc->vres.key.size)
9768 		md->limit = md->base + sc->vres.key.size - 1;
9769 	else
9770 		md->idx = nitems(region);  /* hide it */
9771 	md++;
9772 
9773 	/* add any address-space holes, there can be up to 3 */
9774 	for (n = 0; n < i - 1; n++)
9775 		if (avail[n].limit < avail[n + 1].base)
9776 			(md++)->base = avail[n].limit;
9777 	if (avail[n].limit)
9778 		(md++)->base = avail[n].limit;
9779 
9780 	n = md - mem;
9781 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
9782 
9783 	for (lo = 0; lo < i; lo++)
9784 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
9785 				avail[lo].limit - 1);
9786 
9787 	sbuf_printf(sb, "\n");
9788 	for (i = 0; i < n; i++) {
9789 		if (mem[i].idx >= nitems(region))
9790 			continue;                        /* skip holes */
9791 		if (!mem[i].limit)
9792 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
9793 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
9794 				mem[i].limit);
9795 	}
9796 
9797 	sbuf_printf(sb, "\n");
9798 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
9799 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
9800 	mem_region_show(sb, "uP RAM:", lo, hi);
9801 
9802 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
9803 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
9804 	mem_region_show(sb, "uP Extmem2:", lo, hi);
9805 
9806 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
9807 	sbuf_printf(sb, "\n%u Rx pages of size %uKiB for %u channels\n",
9808 		   G_PMRXMAXPAGE(lo),
9809 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
9810 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
9811 
9812 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
9813 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
9814 	sbuf_printf(sb, "%u Tx pages of size %u%ciB for %u channels\n",
9815 		   G_PMTXMAXPAGE(lo),
9816 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
9817 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
9818 	sbuf_printf(sb, "%u p-structs\n",
9819 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT));
9820 
9821 	for (i = 0; i < 4; i++) {
9822 		if (chip_id(sc) > CHELSIO_T5)
9823 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
9824 		else
9825 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
9826 		if (is_t5(sc)) {
9827 			used = G_T5_USED(lo);
9828 			alloc = G_T5_ALLOC(lo);
9829 		} else {
9830 			used = G_USED(lo);
9831 			alloc = G_ALLOC(lo);
9832 		}
9833 		/* For T6 these are MAC buffer groups */
9834 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
9835 		    i, used, alloc);
9836 	}
9837 	for (i = 0; i < sc->chip_params->nchan; i++) {
9838 		if (chip_id(sc) > CHELSIO_T5)
9839 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
9840 		else
9841 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
9842 		if (is_t5(sc)) {
9843 			used = G_T5_USED(lo);
9844 			alloc = G_T5_ALLOC(lo);
9845 		} else {
9846 			used = G_USED(lo);
9847 			alloc = G_ALLOC(lo);
9848 		}
9849 		/* For T6 these are MAC buffer groups */
9850 		sbuf_printf(sb,
9851 		    "\nLoopback %d using %u pages out of %u allocated",
9852 		    i, used, alloc);
9853 	}
9854 done:
9855 	mtx_unlock(&sc->reg_lock);
9856 	if (rc == 0)
9857 		rc = sbuf_finish(sb);
9858 	sbuf_delete(sb);
9859 	return (rc);
9860 }
9861 
9862 static inline void
9863 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
9864 {
9865 	*mask = x | y;
9866 	y = htobe64(y);
9867 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
9868 }
9869 
9870 static int
9871 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
9872 {
9873 	struct adapter *sc = arg1;
9874 	struct sbuf *sb;
9875 	int rc, i;
9876 
9877 	MPASS(chip_id(sc) <= CHELSIO_T5);
9878 
9879 	rc = sysctl_wire_old_buffer(req, 0);
9880 	if (rc != 0)
9881 		return (rc);
9882 
9883 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9884 	if (sb == NULL)
9885 		return (ENOMEM);
9886 
9887 	sbuf_printf(sb,
9888 	    "Idx  Ethernet address     Mask     Vld Ports PF"
9889 	    "  VF              Replication             P0 P1 P2 P3  ML");
9890 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
9891 		uint64_t tcamx, tcamy, mask;
9892 		uint32_t cls_lo, cls_hi;
9893 		uint8_t addr[ETHER_ADDR_LEN];
9894 
9895 		mtx_lock(&sc->reg_lock);
9896 		if (hw_off_limits(sc))
9897 			rc = ENXIO;
9898 		else {
9899 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
9900 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
9901 		}
9902 		mtx_unlock(&sc->reg_lock);
9903 		if (rc != 0)
9904 			break;
9905 		if (tcamx & tcamy)
9906 			continue;
9907 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
9908 		mtx_lock(&sc->reg_lock);
9909 		if (hw_off_limits(sc))
9910 			rc = ENXIO;
9911 		else {
9912 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
9913 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
9914 		}
9915 		mtx_unlock(&sc->reg_lock);
9916 		if (rc != 0)
9917 			break;
9918 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
9919 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
9920 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
9921 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
9922 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
9923 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
9924 
9925 		if (cls_lo & F_REPLICATE) {
9926 			struct fw_ldst_cmd ldst_cmd;
9927 
9928 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
9929 			ldst_cmd.op_to_addrspace =
9930 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
9931 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
9932 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
9933 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
9934 			ldst_cmd.u.mps.rplc.fid_idx =
9935 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
9936 				V_FW_LDST_CMD_IDX(i));
9937 
9938 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
9939 			    "t4mps");
9940 			if (rc)
9941 				break;
9942 			if (hw_off_limits(sc))
9943 				rc = ENXIO;
9944 			else
9945 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
9946 				    sizeof(ldst_cmd), &ldst_cmd);
9947 			end_synchronized_op(sc, 0);
9948 			if (rc != 0)
9949 				break;
9950 			else {
9951 				sbuf_printf(sb, " %08x %08x %08x %08x",
9952 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
9953 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
9954 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
9955 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
9956 			}
9957 		} else
9958 			sbuf_printf(sb, "%36s", "");
9959 
9960 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
9961 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
9962 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
9963 	}
9964 
9965 	if (rc)
9966 		(void) sbuf_finish(sb);
9967 	else
9968 		rc = sbuf_finish(sb);
9969 	sbuf_delete(sb);
9970 
9971 	return (rc);
9972 }
9973 
9974 static int
9975 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
9976 {
9977 	struct adapter *sc = arg1;
9978 	struct sbuf *sb;
9979 	int rc, i;
9980 
9981 	MPASS(chip_id(sc) > CHELSIO_T5);
9982 
9983 	rc = sysctl_wire_old_buffer(req, 0);
9984 	if (rc != 0)
9985 		return (rc);
9986 
9987 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9988 	if (sb == NULL)
9989 		return (ENOMEM);
9990 
9991 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
9992 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
9993 	    "                           Replication"
9994 	    "                                    P0 P1 P2 P3  ML\n");
9995 
9996 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
9997 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
9998 		uint16_t ivlan;
9999 		uint64_t tcamx, tcamy, val, mask;
10000 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10001 		uint8_t addr[ETHER_ADDR_LEN];
10002 
10003 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10004 		if (i < 256)
10005 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10006 		else
10007 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10008 		mtx_lock(&sc->reg_lock);
10009 		if (hw_off_limits(sc))
10010 			rc = ENXIO;
10011 		else {
10012 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10013 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10014 			tcamy = G_DMACH(val) << 32;
10015 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10016 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10017 		}
10018 		mtx_unlock(&sc->reg_lock);
10019 		if (rc != 0)
10020 			break;
10021 
10022 		lookup_type = G_DATALKPTYPE(data2);
10023 		port_num = G_DATAPORTNUM(data2);
10024 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10025 			/* Inner header VNI */
10026 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10027 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10028 			dip_hit = data2 & F_DATADIPHIT;
10029 			vlan_vld = 0;
10030 		} else {
10031 			vniy = 0;
10032 			dip_hit = 0;
10033 			vlan_vld = data2 & F_DATAVIDH2;
10034 			ivlan = G_VIDL(val);
10035 		}
10036 
10037 		ctl |= V_CTLXYBITSEL(1);
10038 		mtx_lock(&sc->reg_lock);
10039 		if (hw_off_limits(sc))
10040 			rc = ENXIO;
10041 		else {
10042 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10043 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10044 			tcamx = G_DMACH(val) << 32;
10045 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10046 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10047 		}
10048 		mtx_unlock(&sc->reg_lock);
10049 		if (rc != 0)
10050 			break;
10051 
10052 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10053 			/* Inner header VNI mask */
10054 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10055 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10056 		} else
10057 			vnix = 0;
10058 
10059 		if (tcamx & tcamy)
10060 			continue;
10061 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10062 
10063 		mtx_lock(&sc->reg_lock);
10064 		if (hw_off_limits(sc))
10065 			rc = ENXIO;
10066 		else {
10067 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10068 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10069 		}
10070 		mtx_unlock(&sc->reg_lock);
10071 		if (rc != 0)
10072 			break;
10073 
10074 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10075 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10076 			    "%012jx %06x %06x    -    -   %3c"
10077 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10078 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10079 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10080 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10081 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10082 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10083 		} else {
10084 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10085 			    "%012jx    -       -   ", i, addr[0], addr[1],
10086 			    addr[2], addr[3], addr[4], addr[5],
10087 			    (uintmax_t)mask);
10088 
10089 			if (vlan_vld)
10090 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10091 			else
10092 				sbuf_printf(sb, "  -    N     ");
10093 
10094 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10095 			    lookup_type ? 'I' : 'O', port_num,
10096 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10097 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10098 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10099 		}
10100 
10101 
10102 		if (cls_lo & F_T6_REPLICATE) {
10103 			struct fw_ldst_cmd ldst_cmd;
10104 
10105 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10106 			ldst_cmd.op_to_addrspace =
10107 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10108 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10109 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10110 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10111 			ldst_cmd.u.mps.rplc.fid_idx =
10112 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10113 				V_FW_LDST_CMD_IDX(i));
10114 
10115 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10116 			    "t6mps");
10117 			if (rc)
10118 				break;
10119 			if (hw_off_limits(sc))
10120 				rc = ENXIO;
10121 			else
10122 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10123 				    sizeof(ldst_cmd), &ldst_cmd);
10124 			end_synchronized_op(sc, 0);
10125 			if (rc != 0)
10126 				break;
10127 			else {
10128 				sbuf_printf(sb, " %08x %08x %08x %08x"
10129 				    " %08x %08x %08x %08x",
10130 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10131 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10132 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10133 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10134 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10135 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10136 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10137 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10138 			}
10139 		} else
10140 			sbuf_printf(sb, "%72s", "");
10141 
10142 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10143 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10144 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10145 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10146 	}
10147 
10148 	if (rc)
10149 		(void) sbuf_finish(sb);
10150 	else
10151 		rc = sbuf_finish(sb);
10152 	sbuf_delete(sb);
10153 
10154 	return (rc);
10155 }
10156 
10157 static int
10158 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10159 {
10160 	struct adapter *sc = arg1;
10161 	struct sbuf *sb;
10162 	int rc;
10163 	uint16_t mtus[NMTUS];
10164 
10165 	rc = sysctl_wire_old_buffer(req, 0);
10166 	if (rc != 0)
10167 		return (rc);
10168 
10169 	mtx_lock(&sc->reg_lock);
10170 	if (hw_off_limits(sc))
10171 		rc = ENXIO;
10172 	else
10173 		t4_read_mtu_tbl(sc, mtus, NULL);
10174 	mtx_unlock(&sc->reg_lock);
10175 	if (rc != 0)
10176 		return (rc);
10177 
10178 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10179 	if (sb == NULL)
10180 		return (ENOMEM);
10181 
10182 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10183 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10184 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10185 	    mtus[14], mtus[15]);
10186 
10187 	rc = sbuf_finish(sb);
10188 	sbuf_delete(sb);
10189 
10190 	return (rc);
10191 }
10192 
10193 static int
10194 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10195 {
10196 	struct adapter *sc = arg1;
10197 	struct sbuf *sb;
10198 	int rc, i;
10199 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10200 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10201 	static const char *tx_stats[MAX_PM_NSTATS] = {
10202 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10203 		"Tx FIFO wait", NULL, "Tx latency"
10204 	};
10205 	static const char *rx_stats[MAX_PM_NSTATS] = {
10206 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10207 		"Rx FIFO wait", NULL, "Rx latency"
10208 	};
10209 
10210 	rc = sysctl_wire_old_buffer(req, 0);
10211 	if (rc != 0)
10212 		return (rc);
10213 
10214 	mtx_lock(&sc->reg_lock);
10215 	if (hw_off_limits(sc))
10216 		rc = ENXIO;
10217 	else {
10218 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10219 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10220 	}
10221 	mtx_unlock(&sc->reg_lock);
10222 	if (rc != 0)
10223 		return (rc);
10224 
10225 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10226 	if (sb == NULL)
10227 		return (ENOMEM);
10228 
10229 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10230 	for (i = 0; i < 4; i++) {
10231 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10232 		    tx_cyc[i]);
10233 	}
10234 
10235 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10236 	for (i = 0; i < 4; i++) {
10237 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10238 		    rx_cyc[i]);
10239 	}
10240 
10241 	if (chip_id(sc) > CHELSIO_T5) {
10242 		sbuf_printf(sb,
10243 		    "\n              Total wait      Total occupancy");
10244 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10245 		    tx_cyc[i]);
10246 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10247 		    rx_cyc[i]);
10248 
10249 		i += 2;
10250 		MPASS(i < nitems(tx_stats));
10251 
10252 		sbuf_printf(sb,
10253 		    "\n                   Reads           Total wait");
10254 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10255 		    tx_cyc[i]);
10256 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10257 		    rx_cyc[i]);
10258 	}
10259 
10260 	rc = sbuf_finish(sb);
10261 	sbuf_delete(sb);
10262 
10263 	return (rc);
10264 }
10265 
10266 static int
10267 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10268 {
10269 	struct adapter *sc = arg1;
10270 	struct sbuf *sb;
10271 	int rc;
10272 	struct tp_rdma_stats stats;
10273 
10274 	rc = sysctl_wire_old_buffer(req, 0);
10275 	if (rc != 0)
10276 		return (rc);
10277 
10278 	mtx_lock(&sc->reg_lock);
10279 	if (hw_off_limits(sc))
10280 		rc = ENXIO;
10281 	else
10282 		t4_tp_get_rdma_stats(sc, &stats, 0);
10283 	mtx_unlock(&sc->reg_lock);
10284 	if (rc != 0)
10285 		return (rc);
10286 
10287 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10288 	if (sb == NULL)
10289 		return (ENOMEM);
10290 
10291 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10292 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10293 
10294 	rc = sbuf_finish(sb);
10295 	sbuf_delete(sb);
10296 
10297 	return (rc);
10298 }
10299 
10300 static int
10301 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10302 {
10303 	struct adapter *sc = arg1;
10304 	struct sbuf *sb;
10305 	int rc;
10306 	struct tp_tcp_stats v4, v6;
10307 
10308 	rc = sysctl_wire_old_buffer(req, 0);
10309 	if (rc != 0)
10310 		return (rc);
10311 
10312 	mtx_lock(&sc->reg_lock);
10313 	if (hw_off_limits(sc))
10314 		rc = ENXIO;
10315 	else
10316 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10317 	mtx_unlock(&sc->reg_lock);
10318 	if (rc != 0)
10319 		return (rc);
10320 
10321 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10322 	if (sb == NULL)
10323 		return (ENOMEM);
10324 
10325 	sbuf_printf(sb,
10326 	    "                                IP                 IPv6\n");
10327 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10328 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10329 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10330 	    v4.tcp_in_segs, v6.tcp_in_segs);
10331 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10332 	    v4.tcp_out_segs, v6.tcp_out_segs);
10333 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10334 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10335 
10336 	rc = sbuf_finish(sb);
10337 	sbuf_delete(sb);
10338 
10339 	return (rc);
10340 }
10341 
10342 static int
10343 sysctl_tids(SYSCTL_HANDLER_ARGS)
10344 {
10345 	struct adapter *sc = arg1;
10346 	struct sbuf *sb;
10347 	int rc;
10348 	uint32_t x, y;
10349 	struct tid_info *t = &sc->tids;
10350 
10351 	rc = sysctl_wire_old_buffer(req, 0);
10352 	if (rc != 0)
10353 		return (rc);
10354 
10355 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10356 	if (sb == NULL)
10357 		return (ENOMEM);
10358 
10359 	if (t->natids) {
10360 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10361 		    t->atids_in_use);
10362 	}
10363 
10364 	if (t->nhpftids) {
10365 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10366 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10367 	}
10368 
10369 	if (t->ntids) {
10370 		bool hashen = false;
10371 
10372 		mtx_lock(&sc->reg_lock);
10373 		if (hw_off_limits(sc))
10374 			rc = ENXIO;
10375 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10376 			hashen = true;
10377 			if (chip_id(sc) <= CHELSIO_T5) {
10378 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10379 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10380 			} else {
10381 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10382 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10383 			}
10384 		}
10385 		mtx_unlock(&sc->reg_lock);
10386 		if (rc != 0)
10387 			goto done;
10388 
10389 		sbuf_printf(sb, "TID range: ");
10390 		if (hashen) {
10391 			if (x)
10392 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10393 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10394 		} else {
10395 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10396 			    t->ntids - 1);
10397 		}
10398 		sbuf_printf(sb, ", in use: %u\n",
10399 		    atomic_load_acq_int(&t->tids_in_use));
10400 	}
10401 
10402 	if (t->nstids) {
10403 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10404 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10405 	}
10406 
10407 	if (t->nftids) {
10408 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10409 		    t->ftid_end, t->ftids_in_use);
10410 	}
10411 
10412 	if (t->netids) {
10413 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10414 		    t->etid_base + t->netids - 1, t->etids_in_use);
10415 	}
10416 
10417 	mtx_lock(&sc->reg_lock);
10418 	if (hw_off_limits(sc))
10419 		rc = ENXIO;
10420 	else {
10421 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10422 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10423 	}
10424 	mtx_unlock(&sc->reg_lock);
10425 	if (rc != 0)
10426 		goto done;
10427 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10428 done:
10429 	if (rc == 0)
10430 		rc = sbuf_finish(sb);
10431 	else
10432 		(void)sbuf_finish(sb);
10433 	sbuf_delete(sb);
10434 
10435 	return (rc);
10436 }
10437 
10438 static int
10439 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10440 {
10441 	struct adapter *sc = arg1;
10442 	struct sbuf *sb;
10443 	int rc;
10444 	struct tp_err_stats stats;
10445 
10446 	rc = sysctl_wire_old_buffer(req, 0);
10447 	if (rc != 0)
10448 		return (rc);
10449 
10450 	mtx_lock(&sc->reg_lock);
10451 	if (hw_off_limits(sc))
10452 		rc = ENXIO;
10453 	else
10454 		t4_tp_get_err_stats(sc, &stats, 0);
10455 	mtx_unlock(&sc->reg_lock);
10456 	if (rc != 0)
10457 		return (rc);
10458 
10459 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10460 	if (sb == NULL)
10461 		return (ENOMEM);
10462 
10463 	if (sc->chip_params->nchan > 2) {
10464 		sbuf_printf(sb, "                 channel 0  channel 1"
10465 		    "  channel 2  channel 3\n");
10466 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10467 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10468 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10469 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10470 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10471 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10472 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10473 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10474 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10475 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10476 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10477 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10478 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10479 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10480 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10481 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10482 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10483 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10484 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10485 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10486 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10487 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10488 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10489 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10490 	} else {
10491 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10492 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10493 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10494 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10495 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10496 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10497 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10498 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10499 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10500 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10501 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10502 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10503 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10504 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10505 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10506 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10507 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10508 	}
10509 
10510 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10511 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10512 
10513 	rc = sbuf_finish(sb);
10514 	sbuf_delete(sb);
10515 
10516 	return (rc);
10517 }
10518 
10519 static int
10520 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10521 {
10522 	struct adapter *sc = arg1;
10523 	struct sbuf *sb;
10524 	int rc;
10525 	struct tp_tnl_stats stats;
10526 
10527 	rc = sysctl_wire_old_buffer(req, 0);
10528 	if (rc != 0)
10529 		return(rc);
10530 
10531 	mtx_lock(&sc->reg_lock);
10532 	if (hw_off_limits(sc))
10533 		rc = ENXIO;
10534 	else
10535 		t4_tp_get_tnl_stats(sc, &stats, 1);
10536 	mtx_unlock(&sc->reg_lock);
10537 	if (rc != 0)
10538 		return (rc);
10539 
10540 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10541 	if (sb == NULL)
10542 		return (ENOMEM);
10543 
10544 	if (sc->chip_params->nchan > 2) {
10545 		sbuf_printf(sb, "           channel 0  channel 1"
10546 		    "  channel 2  channel 3\n");
10547 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10548 		    stats.out_pkt[0], stats.out_pkt[1],
10549 		    stats.out_pkt[2], stats.out_pkt[3]);
10550 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10551 		    stats.in_pkt[0], stats.in_pkt[1],
10552 		    stats.in_pkt[2], stats.in_pkt[3]);
10553 	} else {
10554 		sbuf_printf(sb, "           channel 0  channel 1\n");
10555 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10556 		    stats.out_pkt[0], stats.out_pkt[1]);
10557 		sbuf_printf(sb, "InPkts:   %10u %10u",
10558 		    stats.in_pkt[0], stats.in_pkt[1]);
10559 	}
10560 
10561 	rc = sbuf_finish(sb);
10562 	sbuf_delete(sb);
10563 
10564 	return (rc);
10565 }
10566 
10567 static int
10568 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10569 {
10570 	struct adapter *sc = arg1;
10571 	struct tp_params *tpp = &sc->params.tp;
10572 	u_int mask;
10573 	int rc;
10574 
10575 	mask = tpp->la_mask >> 16;
10576 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10577 	if (rc != 0 || req->newptr == NULL)
10578 		return (rc);
10579 	if (mask > 0xffff)
10580 		return (EINVAL);
10581 	mtx_lock(&sc->reg_lock);
10582 	if (hw_off_limits(sc))
10583 		rc = ENXIO;
10584 	else {
10585 		tpp->la_mask = mask << 16;
10586 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10587 		    tpp->la_mask);
10588 	}
10589 	mtx_unlock(&sc->reg_lock);
10590 
10591 	return (rc);
10592 }
10593 
10594 struct field_desc {
10595 	const char *name;
10596 	u_int start;
10597 	u_int width;
10598 };
10599 
10600 static void
10601 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10602 {
10603 	char buf[32];
10604 	int line_size = 0;
10605 
10606 	while (f->name) {
10607 		uint64_t mask = (1ULL << f->width) - 1;
10608 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10609 		    ((uintmax_t)v >> f->start) & mask);
10610 
10611 		if (line_size + len >= 79) {
10612 			line_size = 8;
10613 			sbuf_printf(sb, "\n        ");
10614 		}
10615 		sbuf_printf(sb, "%s ", buf);
10616 		line_size += len + 1;
10617 		f++;
10618 	}
10619 	sbuf_printf(sb, "\n");
10620 }
10621 
10622 static const struct field_desc tp_la0[] = {
10623 	{ "RcfOpCodeOut", 60, 4 },
10624 	{ "State", 56, 4 },
10625 	{ "WcfState", 52, 4 },
10626 	{ "RcfOpcSrcOut", 50, 2 },
10627 	{ "CRxError", 49, 1 },
10628 	{ "ERxError", 48, 1 },
10629 	{ "SanityFailed", 47, 1 },
10630 	{ "SpuriousMsg", 46, 1 },
10631 	{ "FlushInputMsg", 45, 1 },
10632 	{ "FlushInputCpl", 44, 1 },
10633 	{ "RssUpBit", 43, 1 },
10634 	{ "RssFilterHit", 42, 1 },
10635 	{ "Tid", 32, 10 },
10636 	{ "InitTcb", 31, 1 },
10637 	{ "LineNumber", 24, 7 },
10638 	{ "Emsg", 23, 1 },
10639 	{ "EdataOut", 22, 1 },
10640 	{ "Cmsg", 21, 1 },
10641 	{ "CdataOut", 20, 1 },
10642 	{ "EreadPdu", 19, 1 },
10643 	{ "CreadPdu", 18, 1 },
10644 	{ "TunnelPkt", 17, 1 },
10645 	{ "RcfPeerFin", 16, 1 },
10646 	{ "RcfReasonOut", 12, 4 },
10647 	{ "TxCchannel", 10, 2 },
10648 	{ "RcfTxChannel", 8, 2 },
10649 	{ "RxEchannel", 6, 2 },
10650 	{ "RcfRxChannel", 5, 1 },
10651 	{ "RcfDataOutSrdy", 4, 1 },
10652 	{ "RxDvld", 3, 1 },
10653 	{ "RxOoDvld", 2, 1 },
10654 	{ "RxCongestion", 1, 1 },
10655 	{ "TxCongestion", 0, 1 },
10656 	{ NULL }
10657 };
10658 
10659 static const struct field_desc tp_la1[] = {
10660 	{ "CplCmdIn", 56, 8 },
10661 	{ "CplCmdOut", 48, 8 },
10662 	{ "ESynOut", 47, 1 },
10663 	{ "EAckOut", 46, 1 },
10664 	{ "EFinOut", 45, 1 },
10665 	{ "ERstOut", 44, 1 },
10666 	{ "SynIn", 43, 1 },
10667 	{ "AckIn", 42, 1 },
10668 	{ "FinIn", 41, 1 },
10669 	{ "RstIn", 40, 1 },
10670 	{ "DataIn", 39, 1 },
10671 	{ "DataInVld", 38, 1 },
10672 	{ "PadIn", 37, 1 },
10673 	{ "RxBufEmpty", 36, 1 },
10674 	{ "RxDdp", 35, 1 },
10675 	{ "RxFbCongestion", 34, 1 },
10676 	{ "TxFbCongestion", 33, 1 },
10677 	{ "TxPktSumSrdy", 32, 1 },
10678 	{ "RcfUlpType", 28, 4 },
10679 	{ "Eread", 27, 1 },
10680 	{ "Ebypass", 26, 1 },
10681 	{ "Esave", 25, 1 },
10682 	{ "Static0", 24, 1 },
10683 	{ "Cread", 23, 1 },
10684 	{ "Cbypass", 22, 1 },
10685 	{ "Csave", 21, 1 },
10686 	{ "CPktOut", 20, 1 },
10687 	{ "RxPagePoolFull", 18, 2 },
10688 	{ "RxLpbkPkt", 17, 1 },
10689 	{ "TxLpbkPkt", 16, 1 },
10690 	{ "RxVfValid", 15, 1 },
10691 	{ "SynLearned", 14, 1 },
10692 	{ "SetDelEntry", 13, 1 },
10693 	{ "SetInvEntry", 12, 1 },
10694 	{ "CpcmdDvld", 11, 1 },
10695 	{ "CpcmdSave", 10, 1 },
10696 	{ "RxPstructsFull", 8, 2 },
10697 	{ "EpcmdDvld", 7, 1 },
10698 	{ "EpcmdFlush", 6, 1 },
10699 	{ "EpcmdTrimPrefix", 5, 1 },
10700 	{ "EpcmdTrimPostfix", 4, 1 },
10701 	{ "ERssIp4Pkt", 3, 1 },
10702 	{ "ERssIp6Pkt", 2, 1 },
10703 	{ "ERssTcpUdpPkt", 1, 1 },
10704 	{ "ERssFceFipPkt", 0, 1 },
10705 	{ NULL }
10706 };
10707 
10708 static const struct field_desc tp_la2[] = {
10709 	{ "CplCmdIn", 56, 8 },
10710 	{ "MpsVfVld", 55, 1 },
10711 	{ "MpsPf", 52, 3 },
10712 	{ "MpsVf", 44, 8 },
10713 	{ "SynIn", 43, 1 },
10714 	{ "AckIn", 42, 1 },
10715 	{ "FinIn", 41, 1 },
10716 	{ "RstIn", 40, 1 },
10717 	{ "DataIn", 39, 1 },
10718 	{ "DataInVld", 38, 1 },
10719 	{ "PadIn", 37, 1 },
10720 	{ "RxBufEmpty", 36, 1 },
10721 	{ "RxDdp", 35, 1 },
10722 	{ "RxFbCongestion", 34, 1 },
10723 	{ "TxFbCongestion", 33, 1 },
10724 	{ "TxPktSumSrdy", 32, 1 },
10725 	{ "RcfUlpType", 28, 4 },
10726 	{ "Eread", 27, 1 },
10727 	{ "Ebypass", 26, 1 },
10728 	{ "Esave", 25, 1 },
10729 	{ "Static0", 24, 1 },
10730 	{ "Cread", 23, 1 },
10731 	{ "Cbypass", 22, 1 },
10732 	{ "Csave", 21, 1 },
10733 	{ "CPktOut", 20, 1 },
10734 	{ "RxPagePoolFull", 18, 2 },
10735 	{ "RxLpbkPkt", 17, 1 },
10736 	{ "TxLpbkPkt", 16, 1 },
10737 	{ "RxVfValid", 15, 1 },
10738 	{ "SynLearned", 14, 1 },
10739 	{ "SetDelEntry", 13, 1 },
10740 	{ "SetInvEntry", 12, 1 },
10741 	{ "CpcmdDvld", 11, 1 },
10742 	{ "CpcmdSave", 10, 1 },
10743 	{ "RxPstructsFull", 8, 2 },
10744 	{ "EpcmdDvld", 7, 1 },
10745 	{ "EpcmdFlush", 6, 1 },
10746 	{ "EpcmdTrimPrefix", 5, 1 },
10747 	{ "EpcmdTrimPostfix", 4, 1 },
10748 	{ "ERssIp4Pkt", 3, 1 },
10749 	{ "ERssIp6Pkt", 2, 1 },
10750 	{ "ERssTcpUdpPkt", 1, 1 },
10751 	{ "ERssFceFipPkt", 0, 1 },
10752 	{ NULL }
10753 };
10754 
10755 static void
10756 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10757 {
10758 
10759 	field_desc_show(sb, *p, tp_la0);
10760 }
10761 
10762 static void
10763 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10764 {
10765 
10766 	if (idx)
10767 		sbuf_printf(sb, "\n");
10768 	field_desc_show(sb, p[0], tp_la0);
10769 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10770 		field_desc_show(sb, p[1], tp_la0);
10771 }
10772 
10773 static void
10774 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
10775 {
10776 
10777 	if (idx)
10778 		sbuf_printf(sb, "\n");
10779 	field_desc_show(sb, p[0], tp_la0);
10780 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10781 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
10782 }
10783 
10784 static int
10785 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
10786 {
10787 	struct adapter *sc = arg1;
10788 	struct sbuf *sb;
10789 	uint64_t *buf, *p;
10790 	int rc;
10791 	u_int i, inc;
10792 	void (*show_func)(struct sbuf *, uint64_t *, int);
10793 
10794 	rc = sysctl_wire_old_buffer(req, 0);
10795 	if (rc != 0)
10796 		return (rc);
10797 
10798 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10799 	if (sb == NULL)
10800 		return (ENOMEM);
10801 
10802 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
10803 
10804 	mtx_lock(&sc->reg_lock);
10805 	if (hw_off_limits(sc))
10806 		rc = ENXIO;
10807 	else {
10808 		t4_tp_read_la(sc, buf, NULL);
10809 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
10810 		case 2:
10811 			inc = 2;
10812 			show_func = tp_la_show2;
10813 			break;
10814 		case 3:
10815 			inc = 2;
10816 			show_func = tp_la_show3;
10817 			break;
10818 		default:
10819 			inc = 1;
10820 			show_func = tp_la_show;
10821 		}
10822 	}
10823 	mtx_unlock(&sc->reg_lock);
10824 	if (rc != 0)
10825 		goto done;
10826 
10827 	p = buf;
10828 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
10829 		(*show_func)(sb, p, i);
10830 	rc = sbuf_finish(sb);
10831 done:
10832 	sbuf_delete(sb);
10833 	free(buf, M_CXGBE);
10834 	return (rc);
10835 }
10836 
10837 static int
10838 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
10839 {
10840 	struct adapter *sc = arg1;
10841 	struct sbuf *sb;
10842 	int rc;
10843 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
10844 
10845 	rc = sysctl_wire_old_buffer(req, 0);
10846 	if (rc != 0)
10847 		return (rc);
10848 
10849 	mtx_lock(&sc->reg_lock);
10850 	if (hw_off_limits(sc))
10851 		rc = ENXIO;
10852 	else
10853 		t4_get_chan_txrate(sc, nrate, orate);
10854 	mtx_unlock(&sc->reg_lock);
10855 	if (rc != 0)
10856 		return (rc);
10857 
10858 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10859 	if (sb == NULL)
10860 		return (ENOMEM);
10861 
10862 	if (sc->chip_params->nchan > 2) {
10863 		sbuf_printf(sb, "              channel 0   channel 1"
10864 		    "   channel 2   channel 3\n");
10865 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
10866 		    nrate[0], nrate[1], nrate[2], nrate[3]);
10867 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
10868 		    orate[0], orate[1], orate[2], orate[3]);
10869 	} else {
10870 		sbuf_printf(sb, "              channel 0   channel 1\n");
10871 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
10872 		    nrate[0], nrate[1]);
10873 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
10874 		    orate[0], orate[1]);
10875 	}
10876 
10877 	rc = sbuf_finish(sb);
10878 	sbuf_delete(sb);
10879 
10880 	return (rc);
10881 }
10882 
10883 static int
10884 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
10885 {
10886 	struct adapter *sc = arg1;
10887 	struct sbuf *sb;
10888 	uint32_t *buf, *p;
10889 	int rc, i;
10890 
10891 	rc = sysctl_wire_old_buffer(req, 0);
10892 	if (rc != 0)
10893 		return (rc);
10894 
10895 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10896 	if (sb == NULL)
10897 		return (ENOMEM);
10898 
10899 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
10900 	    M_ZERO | M_WAITOK);
10901 
10902 	mtx_lock(&sc->reg_lock);
10903 	if (hw_off_limits(sc))
10904 		rc = ENXIO;
10905 	else
10906 		t4_ulprx_read_la(sc, buf);
10907 	mtx_unlock(&sc->reg_lock);
10908 	if (rc != 0)
10909 		goto done;
10910 
10911 	p = buf;
10912 	sbuf_printf(sb, "      Pcmd        Type   Message"
10913 	    "                Data");
10914 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
10915 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
10916 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
10917 	}
10918 	rc = sbuf_finish(sb);
10919 done:
10920 	sbuf_delete(sb);
10921 	free(buf, M_CXGBE);
10922 	return (rc);
10923 }
10924 
10925 static int
10926 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
10927 {
10928 	struct adapter *sc = arg1;
10929 	struct sbuf *sb;
10930 	int rc;
10931 	uint32_t cfg, s1, s2;
10932 
10933 	MPASS(chip_id(sc) >= CHELSIO_T5);
10934 
10935 	rc = sysctl_wire_old_buffer(req, 0);
10936 	if (rc != 0)
10937 		return (rc);
10938 
10939 	mtx_lock(&sc->reg_lock);
10940 	if (hw_off_limits(sc))
10941 		rc = ENXIO;
10942 	else {
10943 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
10944 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
10945 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
10946 	}
10947 	mtx_unlock(&sc->reg_lock);
10948 	if (rc != 0)
10949 		return (rc);
10950 
10951 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10952 	if (sb == NULL)
10953 		return (ENOMEM);
10954 
10955 	if (G_STATSOURCE_T5(cfg) == 7) {
10956 		int mode;
10957 
10958 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
10959 		if (mode == 0)
10960 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
10961 		else if (mode == 1)
10962 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
10963 		else
10964 			sbuf_printf(sb, "unknown mode %d", mode);
10965 	}
10966 	rc = sbuf_finish(sb);
10967 	sbuf_delete(sb);
10968 
10969 	return (rc);
10970 }
10971 
10972 static int
10973 sysctl_cpus(SYSCTL_HANDLER_ARGS)
10974 {
10975 	struct adapter *sc = arg1;
10976 	enum cpu_sets op = arg2;
10977 	cpuset_t cpuset;
10978 	struct sbuf *sb;
10979 	int i, rc;
10980 
10981 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
10982 
10983 	CPU_ZERO(&cpuset);
10984 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
10985 	if (rc != 0)
10986 		return (rc);
10987 
10988 	rc = sysctl_wire_old_buffer(req, 0);
10989 	if (rc != 0)
10990 		return (rc);
10991 
10992 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10993 	if (sb == NULL)
10994 		return (ENOMEM);
10995 
10996 	CPU_FOREACH(i)
10997 		sbuf_printf(sb, "%d ", i);
10998 	rc = sbuf_finish(sb);
10999 	sbuf_delete(sb);
11000 
11001 	return (rc);
11002 }
11003 
11004 static int
11005 sysctl_reset(SYSCTL_HANDLER_ARGS)
11006 {
11007 	struct adapter *sc = arg1;
11008 	u_int val;
11009 	int rc;
11010 
11011 	val = sc->num_resets;
11012 	rc = sysctl_handle_int(oidp, &val, 0, req);
11013 	if (rc != 0 || req->newptr == NULL)
11014 		return (rc);
11015 
11016 	if (val == 0) {
11017 		/* Zero out the counter that tracks reset. */
11018 		sc->num_resets = 0;
11019 		return (0);
11020 	}
11021 
11022 	if (val != 1)
11023 		return (EINVAL);	/* 0 or 1 are the only legal values */
11024 
11025 	if (hw_off_limits(sc))		/* harmless race */
11026 		return (EALREADY);
11027 
11028 	taskqueue_enqueue(reset_tq, &sc->reset_task);
11029 	return (0);
11030 }
11031 
11032 #ifdef TCP_OFFLOAD
11033 static int
11034 sysctl_tls(SYSCTL_HANDLER_ARGS)
11035 {
11036 	struct adapter *sc = arg1;
11037 	int i, j, v, rc;
11038 	struct vi_info *vi;
11039 
11040 	v = sc->tt.tls;
11041 	rc = sysctl_handle_int(oidp, &v, 0, req);
11042 	if (rc != 0 || req->newptr == NULL)
11043 		return (rc);
11044 
11045 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11046 		return (ENOTSUP);
11047 
11048 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11049 	if (rc)
11050 		return (rc);
11051 	if (hw_off_limits(sc))
11052 		rc = ENXIO;
11053 	else {
11054 		sc->tt.tls = !!v;
11055 		for_each_port(sc, i) {
11056 			for_each_vi(sc->port[i], j, vi) {
11057 				if (vi->flags & VI_INIT_DONE)
11058 					t4_update_fl_bufsize(vi->ifp);
11059 			}
11060 		}
11061 	}
11062 	end_synchronized_op(sc, 0);
11063 
11064 	return (rc);
11065 
11066 }
11067 
11068 static int
11069 sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS)
11070 {
11071 	struct adapter *sc = arg1;
11072 	int *old_ports, *new_ports;
11073 	int i, new_count, rc;
11074 
11075 	if (req->newptr == NULL && req->oldptr == NULL)
11076 		return (SYSCTL_OUT(req, NULL, imax(sc->tt.num_tls_rx_ports, 1) *
11077 		    sizeof(sc->tt.tls_rx_ports[0])));
11078 
11079 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tlsrx");
11080 	if (rc)
11081 		return (rc);
11082 
11083 	if (hw_off_limits(sc)) {
11084 		rc = ENXIO;
11085 		goto done;
11086 	}
11087 
11088 	if (sc->tt.num_tls_rx_ports == 0) {
11089 		i = -1;
11090 		rc = SYSCTL_OUT(req, &i, sizeof(i));
11091 	} else
11092 		rc = SYSCTL_OUT(req, sc->tt.tls_rx_ports,
11093 		    sc->tt.num_tls_rx_ports * sizeof(sc->tt.tls_rx_ports[0]));
11094 	if (rc == 0 && req->newptr != NULL) {
11095 		new_count = req->newlen / sizeof(new_ports[0]);
11096 		new_ports = malloc(new_count * sizeof(new_ports[0]), M_CXGBE,
11097 		    M_WAITOK);
11098 		rc = SYSCTL_IN(req, new_ports, new_count *
11099 		    sizeof(new_ports[0]));
11100 		if (rc)
11101 			goto err;
11102 
11103 		/* Allow setting to a single '-1' to clear the list. */
11104 		if (new_count == 1 && new_ports[0] == -1) {
11105 			ADAPTER_LOCK(sc);
11106 			old_ports = sc->tt.tls_rx_ports;
11107 			sc->tt.tls_rx_ports = NULL;
11108 			sc->tt.num_tls_rx_ports = 0;
11109 			ADAPTER_UNLOCK(sc);
11110 			free(old_ports, M_CXGBE);
11111 		} else {
11112 			for (i = 0; i < new_count; i++) {
11113 				if (new_ports[i] < 1 ||
11114 				    new_ports[i] > IPPORT_MAX) {
11115 					rc = EINVAL;
11116 					goto err;
11117 				}
11118 			}
11119 
11120 			ADAPTER_LOCK(sc);
11121 			old_ports = sc->tt.tls_rx_ports;
11122 			sc->tt.tls_rx_ports = new_ports;
11123 			sc->tt.num_tls_rx_ports = new_count;
11124 			ADAPTER_UNLOCK(sc);
11125 			free(old_ports, M_CXGBE);
11126 			new_ports = NULL;
11127 		}
11128 	err:
11129 		free(new_ports, M_CXGBE);
11130 	}
11131 done:
11132 	end_synchronized_op(sc, 0);
11133 	return (rc);
11134 }
11135 
11136 static int
11137 sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS)
11138 {
11139 	struct adapter *sc = arg1;
11140 	int v, rc;
11141 
11142 	v = sc->tt.tls_rx_timeout;
11143 	rc = sysctl_handle_int(oidp, &v, 0, req);
11144 	if (rc != 0 || req->newptr == NULL)
11145 		return (rc);
11146 
11147 	if (v < 0)
11148 		return (EINVAL);
11149 
11150 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11151 		return (ENOTSUP);
11152 
11153 	sc->tt.tls_rx_timeout = v;
11154 
11155 	return (0);
11156 
11157 }
11158 
11159 static void
11160 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11161 {
11162 	u_int rem = val % factor;
11163 
11164 	if (rem == 0)
11165 		snprintf(buf, len, "%u", val / factor);
11166 	else {
11167 		while (rem % 10 == 0)
11168 			rem /= 10;
11169 		snprintf(buf, len, "%u.%u", val / factor, rem);
11170 	}
11171 }
11172 
11173 static int
11174 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11175 {
11176 	struct adapter *sc = arg1;
11177 	char buf[16];
11178 	u_int res, re;
11179 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11180 
11181 	mtx_lock(&sc->reg_lock);
11182 	if (hw_off_limits(sc))
11183 		res = (u_int)-1;
11184 	else
11185 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11186 	mtx_unlock(&sc->reg_lock);
11187 	if (res == (u_int)-1)
11188 		return (ENXIO);
11189 
11190 	switch (arg2) {
11191 	case 0:
11192 		/* timer_tick */
11193 		re = G_TIMERRESOLUTION(res);
11194 		break;
11195 	case 1:
11196 		/* TCP timestamp tick */
11197 		re = G_TIMESTAMPRESOLUTION(res);
11198 		break;
11199 	case 2:
11200 		/* DACK tick */
11201 		re = G_DELAYEDACKRESOLUTION(res);
11202 		break;
11203 	default:
11204 		return (EDOOFUS);
11205 	}
11206 
11207 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11208 
11209 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11210 }
11211 
11212 static int
11213 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11214 {
11215 	struct adapter *sc = arg1;
11216 	int rc;
11217 	u_int dack_tmr, dack_re, v;
11218 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11219 
11220 	mtx_lock(&sc->reg_lock);
11221 	if (hw_off_limits(sc))
11222 		rc = ENXIO;
11223 	else {
11224 		rc = 0;
11225 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11226 		    A_TP_TIMER_RESOLUTION));
11227 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11228 	}
11229 	mtx_unlock(&sc->reg_lock);
11230 	if (rc != 0)
11231 		return (rc);
11232 
11233 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11234 
11235 	return (sysctl_handle_int(oidp, &v, 0, req));
11236 }
11237 
11238 static int
11239 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11240 {
11241 	struct adapter *sc = arg1;
11242 	int rc, reg = arg2;
11243 	u_int tre;
11244 	u_long tp_tick_us, v;
11245 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11246 
11247 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11248 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11249 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11250 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11251 
11252 	mtx_lock(&sc->reg_lock);
11253 	if (hw_off_limits(sc))
11254 		rc = ENXIO;
11255 	else {
11256 		rc = 0;
11257 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11258 		tp_tick_us = (cclk_ps << tre) / 1000000;
11259 		if (reg == A_TP_INIT_SRTT)
11260 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11261 		else
11262 			v = tp_tick_us * t4_read_reg(sc, reg);
11263 	}
11264 	mtx_unlock(&sc->reg_lock);
11265 	if (rc != 0)
11266 		return (rc);
11267 	else
11268 		return (sysctl_handle_long(oidp, &v, 0, req));
11269 }
11270 
11271 /*
11272  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11273  * passed to this function.
11274  */
11275 static int
11276 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11277 {
11278 	struct adapter *sc = arg1;
11279 	int rc, idx = arg2;
11280 	u_int v;
11281 
11282 	MPASS(idx >= 0 && idx <= 24);
11283 
11284 	mtx_lock(&sc->reg_lock);
11285 	if (hw_off_limits(sc))
11286 		rc = ENXIO;
11287 	else {
11288 		rc = 0;
11289 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11290 	}
11291 	mtx_unlock(&sc->reg_lock);
11292 	if (rc != 0)
11293 		return (rc);
11294 	else
11295 		return (sysctl_handle_int(oidp, &v, 0, req));
11296 }
11297 
11298 static int
11299 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11300 {
11301 	struct adapter *sc = arg1;
11302 	int rc, idx = arg2;
11303 	u_int shift, v, r;
11304 
11305 	MPASS(idx >= 0 && idx < 16);
11306 
11307 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11308 	shift = (idx & 3) << 3;
11309 	mtx_lock(&sc->reg_lock);
11310 	if (hw_off_limits(sc))
11311 		rc = ENXIO;
11312 	else {
11313 		rc = 0;
11314 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11315 	}
11316 	mtx_unlock(&sc->reg_lock);
11317 	if (rc != 0)
11318 		return (rc);
11319 	else
11320 		return (sysctl_handle_int(oidp, &v, 0, req));
11321 }
11322 
11323 static int
11324 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11325 {
11326 	struct vi_info *vi = arg1;
11327 	struct adapter *sc = vi->adapter;
11328 	int idx, rc, i;
11329 	struct sge_ofld_rxq *ofld_rxq;
11330 	uint8_t v;
11331 
11332 	idx = vi->ofld_tmr_idx;
11333 
11334 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11335 	if (rc != 0 || req->newptr == NULL)
11336 		return (rc);
11337 
11338 	if (idx < 0 || idx >= SGE_NTIMERS)
11339 		return (EINVAL);
11340 
11341 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11342 	    "t4otmr");
11343 	if (rc)
11344 		return (rc);
11345 
11346 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11347 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11348 #ifdef atomic_store_rel_8
11349 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11350 #else
11351 		ofld_rxq->iq.intr_params = v;
11352 #endif
11353 	}
11354 	vi->ofld_tmr_idx = idx;
11355 
11356 	end_synchronized_op(sc, LOCK_HELD);
11357 	return (0);
11358 }
11359 
11360 static int
11361 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11362 {
11363 	struct vi_info *vi = arg1;
11364 	struct adapter *sc = vi->adapter;
11365 	int idx, rc;
11366 
11367 	idx = vi->ofld_pktc_idx;
11368 
11369 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11370 	if (rc != 0 || req->newptr == NULL)
11371 		return (rc);
11372 
11373 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11374 		return (EINVAL);
11375 
11376 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11377 	    "t4opktc");
11378 	if (rc)
11379 		return (rc);
11380 
11381 	if (vi->flags & VI_INIT_DONE)
11382 		rc = EBUSY; /* cannot be changed once the queues are created */
11383 	else
11384 		vi->ofld_pktc_idx = idx;
11385 
11386 	end_synchronized_op(sc, LOCK_HELD);
11387 	return (rc);
11388 }
11389 #endif
11390 
11391 static int
11392 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11393 {
11394 	int rc;
11395 
11396 	if (cntxt->cid > M_CTXTQID)
11397 		return (EINVAL);
11398 
11399 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11400 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11401 		return (EINVAL);
11402 
11403 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11404 	if (rc)
11405 		return (rc);
11406 
11407 	if (hw_off_limits(sc)) {
11408 		rc = ENXIO;
11409 		goto done;
11410 	}
11411 
11412 	if (sc->flags & FW_OK) {
11413 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11414 		    &cntxt->data[0]);
11415 		if (rc == 0)
11416 			goto done;
11417 	}
11418 
11419 	/*
11420 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11421 	 * the backdoor.
11422 	 */
11423 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11424 done:
11425 	end_synchronized_op(sc, 0);
11426 	return (rc);
11427 }
11428 
11429 static int
11430 load_fw(struct adapter *sc, struct t4_data *fw)
11431 {
11432 	int rc;
11433 	uint8_t *fw_data;
11434 
11435 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11436 	if (rc)
11437 		return (rc);
11438 
11439 	if (hw_off_limits(sc)) {
11440 		rc = ENXIO;
11441 		goto done;
11442 	}
11443 
11444 	/*
11445 	 * The firmware, with the sole exception of the memory parity error
11446 	 * handler, runs from memory and not flash.  It is almost always safe to
11447 	 * install a new firmware on a running system.  Just set bit 1 in
11448 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11449 	 */
11450 	if (sc->flags & FULL_INIT_DONE &&
11451 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11452 		rc = EBUSY;
11453 		goto done;
11454 	}
11455 
11456 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11457 
11458 	rc = copyin(fw->data, fw_data, fw->len);
11459 	if (rc == 0)
11460 		rc = -t4_load_fw(sc, fw_data, fw->len);
11461 
11462 	free(fw_data, M_CXGBE);
11463 done:
11464 	end_synchronized_op(sc, 0);
11465 	return (rc);
11466 }
11467 
11468 static int
11469 load_cfg(struct adapter *sc, struct t4_data *cfg)
11470 {
11471 	int rc;
11472 	uint8_t *cfg_data = NULL;
11473 
11474 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11475 	if (rc)
11476 		return (rc);
11477 
11478 	if (hw_off_limits(sc)) {
11479 		rc = ENXIO;
11480 		goto done;
11481 	}
11482 
11483 	if (cfg->len == 0) {
11484 		/* clear */
11485 		rc = -t4_load_cfg(sc, NULL, 0);
11486 		goto done;
11487 	}
11488 
11489 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11490 
11491 	rc = copyin(cfg->data, cfg_data, cfg->len);
11492 	if (rc == 0)
11493 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11494 
11495 	free(cfg_data, M_CXGBE);
11496 done:
11497 	end_synchronized_op(sc, 0);
11498 	return (rc);
11499 }
11500 
11501 static int
11502 load_boot(struct adapter *sc, struct t4_bootrom *br)
11503 {
11504 	int rc;
11505 	uint8_t *br_data = NULL;
11506 	u_int offset;
11507 
11508 	if (br->len > 1024 * 1024)
11509 		return (EFBIG);
11510 
11511 	if (br->pf_offset == 0) {
11512 		/* pfidx */
11513 		if (br->pfidx_addr > 7)
11514 			return (EINVAL);
11515 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11516 		    A_PCIE_PF_EXPROM_OFST)));
11517 	} else if (br->pf_offset == 1) {
11518 		/* offset */
11519 		offset = G_OFFSET(br->pfidx_addr);
11520 	} else {
11521 		return (EINVAL);
11522 	}
11523 
11524 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11525 	if (rc)
11526 		return (rc);
11527 
11528 	if (hw_off_limits(sc)) {
11529 		rc = ENXIO;
11530 		goto done;
11531 	}
11532 
11533 	if (br->len == 0) {
11534 		/* clear */
11535 		rc = -t4_load_boot(sc, NULL, offset, 0);
11536 		goto done;
11537 	}
11538 
11539 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11540 
11541 	rc = copyin(br->data, br_data, br->len);
11542 	if (rc == 0)
11543 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11544 
11545 	free(br_data, M_CXGBE);
11546 done:
11547 	end_synchronized_op(sc, 0);
11548 	return (rc);
11549 }
11550 
11551 static int
11552 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11553 {
11554 	int rc;
11555 	uint8_t *bc_data = NULL;
11556 
11557 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11558 	if (rc)
11559 		return (rc);
11560 
11561 	if (hw_off_limits(sc)) {
11562 		rc = ENXIO;
11563 		goto done;
11564 	}
11565 
11566 	if (bc->len == 0) {
11567 		/* clear */
11568 		rc = -t4_load_bootcfg(sc, NULL, 0);
11569 		goto done;
11570 	}
11571 
11572 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11573 
11574 	rc = copyin(bc->data, bc_data, bc->len);
11575 	if (rc == 0)
11576 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11577 
11578 	free(bc_data, M_CXGBE);
11579 done:
11580 	end_synchronized_op(sc, 0);
11581 	return (rc);
11582 }
11583 
11584 static int
11585 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11586 {
11587 	int rc;
11588 	struct cudbg_init *cudbg;
11589 	void *handle, *buf;
11590 
11591 	/* buf is large, don't block if no memory is available */
11592 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11593 	if (buf == NULL)
11594 		return (ENOMEM);
11595 
11596 	handle = cudbg_alloc_handle();
11597 	if (handle == NULL) {
11598 		rc = ENOMEM;
11599 		goto done;
11600 	}
11601 
11602 	cudbg = cudbg_get_init(handle);
11603 	cudbg->adap = sc;
11604 	cudbg->print = (cudbg_print_cb)printf;
11605 
11606 #ifndef notyet
11607 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11608 	    __func__, dump->wr_flash, dump->len, dump->data);
11609 #endif
11610 
11611 	if (dump->wr_flash)
11612 		cudbg->use_flash = 1;
11613 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11614 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11615 
11616 	rc = cudbg_collect(handle, buf, &dump->len);
11617 	if (rc != 0)
11618 		goto done;
11619 
11620 	rc = copyout(buf, dump->data, dump->len);
11621 done:
11622 	cudbg_free_handle(handle);
11623 	free(buf, M_CXGBE);
11624 	return (rc);
11625 }
11626 
11627 static void
11628 free_offload_policy(struct t4_offload_policy *op)
11629 {
11630 	struct offload_rule *r;
11631 	int i;
11632 
11633 	if (op == NULL)
11634 		return;
11635 
11636 	r = &op->rule[0];
11637 	for (i = 0; i < op->nrules; i++, r++) {
11638 		free(r->bpf_prog.bf_insns, M_CXGBE);
11639 	}
11640 	free(op->rule, M_CXGBE);
11641 	free(op, M_CXGBE);
11642 }
11643 
11644 static int
11645 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11646 {
11647 	int i, rc, len;
11648 	struct t4_offload_policy *op, *old;
11649 	struct bpf_program *bf;
11650 	const struct offload_settings *s;
11651 	struct offload_rule *r;
11652 	void *u;
11653 
11654 	if (!is_offload(sc))
11655 		return (ENODEV);
11656 
11657 	if (uop->nrules == 0) {
11658 		/* Delete installed policies. */
11659 		op = NULL;
11660 		goto set_policy;
11661 	} else if (uop->nrules > 256) { /* arbitrary */
11662 		return (E2BIG);
11663 	}
11664 
11665 	/* Copy userspace offload policy to kernel */
11666 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11667 	op->nrules = uop->nrules;
11668 	len = op->nrules * sizeof(struct offload_rule);
11669 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11670 	rc = copyin(uop->rule, op->rule, len);
11671 	if (rc) {
11672 		free(op->rule, M_CXGBE);
11673 		free(op, M_CXGBE);
11674 		return (rc);
11675 	}
11676 
11677 	r = &op->rule[0];
11678 	for (i = 0; i < op->nrules; i++, r++) {
11679 
11680 		/* Validate open_type */
11681 		if (r->open_type != OPEN_TYPE_LISTEN &&
11682 		    r->open_type != OPEN_TYPE_ACTIVE &&
11683 		    r->open_type != OPEN_TYPE_PASSIVE &&
11684 		    r->open_type != OPEN_TYPE_DONTCARE) {
11685 error:
11686 			/*
11687 			 * Rules 0 to i have malloc'd filters that need to be
11688 			 * freed.  Rules i+1 to nrules have userspace pointers
11689 			 * and should be left alone.
11690 			 */
11691 			op->nrules = i;
11692 			free_offload_policy(op);
11693 			return (rc);
11694 		}
11695 
11696 		/* Validate settings */
11697 		s = &r->settings;
11698 		if ((s->offload != 0 && s->offload != 1) ||
11699 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11700 		    s->sched_class < -1 ||
11701 		    s->sched_class >= sc->params.nsched_cls) {
11702 			rc = EINVAL;
11703 			goto error;
11704 		}
11705 
11706 		bf = &r->bpf_prog;
11707 		u = bf->bf_insns;	/* userspace ptr */
11708 		bf->bf_insns = NULL;
11709 		if (bf->bf_len == 0) {
11710 			/* legal, matches everything */
11711 			continue;
11712 		}
11713 		len = bf->bf_len * sizeof(*bf->bf_insns);
11714 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11715 		rc = copyin(u, bf->bf_insns, len);
11716 		if (rc != 0)
11717 			goto error;
11718 
11719 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11720 			rc = EINVAL;
11721 			goto error;
11722 		}
11723 	}
11724 set_policy:
11725 	rw_wlock(&sc->policy_lock);
11726 	old = sc->policy;
11727 	sc->policy = op;
11728 	rw_wunlock(&sc->policy_lock);
11729 	free_offload_policy(old);
11730 
11731 	return (0);
11732 }
11733 
11734 #define MAX_READ_BUF_SIZE (128 * 1024)
11735 static int
11736 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11737 {
11738 	uint32_t addr, remaining, n;
11739 	uint32_t *buf;
11740 	int rc;
11741 	uint8_t *dst;
11742 
11743 	mtx_lock(&sc->reg_lock);
11744 	if (hw_off_limits(sc))
11745 		rc = ENXIO;
11746 	else
11747 		rc = validate_mem_range(sc, mr->addr, mr->len);
11748 	mtx_unlock(&sc->reg_lock);
11749 	if (rc != 0)
11750 		return (rc);
11751 
11752 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11753 	addr = mr->addr;
11754 	remaining = mr->len;
11755 	dst = (void *)mr->data;
11756 
11757 	while (remaining) {
11758 		n = min(remaining, MAX_READ_BUF_SIZE);
11759 		mtx_lock(&sc->reg_lock);
11760 		if (hw_off_limits(sc))
11761 			rc = ENXIO;
11762 		else
11763 			read_via_memwin(sc, 2, addr, buf, n);
11764 		mtx_unlock(&sc->reg_lock);
11765 		if (rc != 0)
11766 			break;
11767 
11768 		rc = copyout(buf, dst, n);
11769 		if (rc != 0)
11770 			break;
11771 
11772 		dst += n;
11773 		remaining -= n;
11774 		addr += n;
11775 	}
11776 
11777 	free(buf, M_CXGBE);
11778 	return (rc);
11779 }
11780 #undef MAX_READ_BUF_SIZE
11781 
11782 static int
11783 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11784 {
11785 	int rc;
11786 
11787 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11788 		return (EINVAL);
11789 
11790 	if (i2cd->len > sizeof(i2cd->data))
11791 		return (EFBIG);
11792 
11793 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11794 	if (rc)
11795 		return (rc);
11796 	if (hw_off_limits(sc))
11797 		rc = ENXIO;
11798 	else
11799 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11800 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11801 	end_synchronized_op(sc, 0);
11802 
11803 	return (rc);
11804 }
11805 
11806 static int
11807 clear_stats(struct adapter *sc, u_int port_id)
11808 {
11809 	int i, v, chan_map;
11810 	struct port_info *pi;
11811 	struct vi_info *vi;
11812 	struct sge_rxq *rxq;
11813 	struct sge_txq *txq;
11814 	struct sge_wrq *wrq;
11815 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11816 	struct sge_ofld_txq *ofld_txq;
11817 #endif
11818 #ifdef TCP_OFFLOAD
11819 	struct sge_ofld_rxq *ofld_rxq;
11820 #endif
11821 
11822 	if (port_id >= sc->params.nports)
11823 		return (EINVAL);
11824 	pi = sc->port[port_id];
11825 	if (pi == NULL)
11826 		return (EIO);
11827 
11828 	mtx_lock(&sc->reg_lock);
11829 	if (!hw_off_limits(sc)) {
11830 		/* MAC stats */
11831 		t4_clr_port_stats(sc, pi->tx_chan);
11832 		if (is_t6(sc)) {
11833 			if (pi->fcs_reg != -1)
11834 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11835 			else
11836 				pi->stats.rx_fcs_err = 0;
11837 		}
11838 		for_each_vi(pi, v, vi) {
11839 			if (vi->flags & VI_INIT_DONE)
11840 				t4_clr_vi_stats(sc, vi->vin);
11841 		}
11842 		chan_map = pi->rx_e_chan_map;
11843 		v = 0;	/* reuse */
11844 		while (chan_map) {
11845 			i = ffs(chan_map) - 1;
11846 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11847 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11848 			chan_map &= ~(1 << i);
11849 		}
11850 	}
11851 	mtx_unlock(&sc->reg_lock);
11852 	pi->tx_parse_error = 0;
11853 	pi->tnl_cong_drops = 0;
11854 
11855 	/*
11856 	 * Since this command accepts a port, clear stats for
11857 	 * all VIs on this port.
11858 	 */
11859 	for_each_vi(pi, v, vi) {
11860 		if (vi->flags & VI_INIT_DONE) {
11861 
11862 			for_each_rxq(vi, i, rxq) {
11863 #if defined(INET) || defined(INET6)
11864 				rxq->lro.lro_queued = 0;
11865 				rxq->lro.lro_flushed = 0;
11866 #endif
11867 				rxq->rxcsum = 0;
11868 				rxq->vlan_extraction = 0;
11869 				rxq->vxlan_rxcsum = 0;
11870 
11871 				rxq->fl.cl_allocated = 0;
11872 				rxq->fl.cl_recycled = 0;
11873 				rxq->fl.cl_fast_recycled = 0;
11874 			}
11875 
11876 			for_each_txq(vi, i, txq) {
11877 				txq->txcsum = 0;
11878 				txq->tso_wrs = 0;
11879 				txq->vlan_insertion = 0;
11880 				txq->imm_wrs = 0;
11881 				txq->sgl_wrs = 0;
11882 				txq->txpkt_wrs = 0;
11883 				txq->txpkts0_wrs = 0;
11884 				txq->txpkts1_wrs = 0;
11885 				txq->txpkts0_pkts = 0;
11886 				txq->txpkts1_pkts = 0;
11887 				txq->txpkts_flush = 0;
11888 				txq->raw_wrs = 0;
11889 				txq->vxlan_tso_wrs = 0;
11890 				txq->vxlan_txcsum = 0;
11891 				txq->kern_tls_records = 0;
11892 				txq->kern_tls_short = 0;
11893 				txq->kern_tls_partial = 0;
11894 				txq->kern_tls_full = 0;
11895 				txq->kern_tls_octets = 0;
11896 				txq->kern_tls_waste = 0;
11897 				txq->kern_tls_options = 0;
11898 				txq->kern_tls_header = 0;
11899 				txq->kern_tls_fin = 0;
11900 				txq->kern_tls_fin_short = 0;
11901 				txq->kern_tls_cbc = 0;
11902 				txq->kern_tls_gcm = 0;
11903 				mp_ring_reset_stats(txq->r);
11904 			}
11905 
11906 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11907 			for_each_ofld_txq(vi, i, ofld_txq) {
11908 				ofld_txq->wrq.tx_wrs_direct = 0;
11909 				ofld_txq->wrq.tx_wrs_copied = 0;
11910 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
11911 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
11912 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
11913 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
11914 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
11915 			}
11916 #endif
11917 #ifdef TCP_OFFLOAD
11918 			for_each_ofld_rxq(vi, i, ofld_rxq) {
11919 				ofld_rxq->fl.cl_allocated = 0;
11920 				ofld_rxq->fl.cl_recycled = 0;
11921 				ofld_rxq->fl.cl_fast_recycled = 0;
11922 				counter_u64_zero(
11923 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
11924 				counter_u64_zero(
11925 				    ofld_rxq->rx_iscsi_ddp_setup_error);
11926 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
11927 				ofld_rxq->rx_iscsi_ddp_octets = 0;
11928 				ofld_rxq->rx_iscsi_fl_pdus = 0;
11929 				ofld_rxq->rx_iscsi_fl_octets = 0;
11930 				ofld_rxq->rx_toe_tls_records = 0;
11931 				ofld_rxq->rx_toe_tls_octets = 0;
11932 			}
11933 #endif
11934 
11935 			if (IS_MAIN_VI(vi)) {
11936 				wrq = &sc->sge.ctrlq[pi->port_id];
11937 				wrq->tx_wrs_direct = 0;
11938 				wrq->tx_wrs_copied = 0;
11939 			}
11940 		}
11941 	}
11942 
11943 	return (0);
11944 }
11945 
11946 static int
11947 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
11948 {
11949 #ifdef INET6
11950 	struct in6_addr in6;
11951 
11952 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
11953 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
11954 		return (0);
11955 	else
11956 		return (EIO);
11957 #else
11958 	return (ENOTSUP);
11959 #endif
11960 }
11961 
11962 static int
11963 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
11964 {
11965 #ifdef INET6
11966 	struct in6_addr in6;
11967 
11968 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
11969 	return (t4_release_clip_addr(sc, &in6));
11970 #else
11971 	return (ENOTSUP);
11972 #endif
11973 }
11974 
11975 int
11976 t4_os_find_pci_capability(struct adapter *sc, int cap)
11977 {
11978 	int i;
11979 
11980 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
11981 }
11982 
11983 int
11984 t4_os_pci_save_state(struct adapter *sc)
11985 {
11986 	device_t dev;
11987 	struct pci_devinfo *dinfo;
11988 
11989 	dev = sc->dev;
11990 	dinfo = device_get_ivars(dev);
11991 
11992 	pci_cfg_save(dev, dinfo, 0);
11993 	return (0);
11994 }
11995 
11996 int
11997 t4_os_pci_restore_state(struct adapter *sc)
11998 {
11999 	device_t dev;
12000 	struct pci_devinfo *dinfo;
12001 
12002 	dev = sc->dev;
12003 	dinfo = device_get_ivars(dev);
12004 
12005 	pci_cfg_restore(dev, dinfo);
12006 	return (0);
12007 }
12008 
12009 void
12010 t4_os_portmod_changed(struct port_info *pi)
12011 {
12012 	struct adapter *sc = pi->adapter;
12013 	struct vi_info *vi;
12014 	struct ifnet *ifp;
12015 	static const char *mod_str[] = {
12016 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
12017 	};
12018 
12019 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
12020 	    ("%s: port_type %u", __func__, pi->port_type));
12021 
12022 	vi = &pi->vi[0];
12023 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12024 		PORT_LOCK(pi);
12025 		build_medialist(pi);
12026 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12027 			fixup_link_config(pi);
12028 			apply_link_config(pi);
12029 		}
12030 		PORT_UNLOCK(pi);
12031 		end_synchronized_op(sc, LOCK_HELD);
12032 	}
12033 
12034 	ifp = vi->ifp;
12035 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12036 		if_printf(ifp, "transceiver unplugged.\n");
12037 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12038 		if_printf(ifp, "unknown transceiver inserted.\n");
12039 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12040 		if_printf(ifp, "unsupported transceiver inserted.\n");
12041 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12042 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12043 		    port_top_speed(pi), mod_str[pi->mod_type]);
12044 	} else {
12045 		if_printf(ifp, "transceiver (type %d) inserted.\n",
12046 		    pi->mod_type);
12047 	}
12048 }
12049 
12050 void
12051 t4_os_link_changed(struct port_info *pi)
12052 {
12053 	struct vi_info *vi;
12054 	struct ifnet *ifp;
12055 	struct link_config *lc = &pi->link_cfg;
12056 	struct adapter *sc = pi->adapter;
12057 	int v;
12058 
12059 	PORT_LOCK_ASSERT_OWNED(pi);
12060 
12061 	if (is_t6(sc)) {
12062 		if (lc->link_ok) {
12063 			if (lc->speed > 25000 ||
12064 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12065 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12066 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12067 			} else {
12068 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12069 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12070 			}
12071 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12072 			pi->stats.rx_fcs_err = 0;
12073 		} else {
12074 			pi->fcs_reg = -1;
12075 		}
12076 	} else {
12077 		MPASS(pi->fcs_reg != -1);
12078 		MPASS(pi->fcs_base == 0);
12079 	}
12080 
12081 	for_each_vi(pi, v, vi) {
12082 		ifp = vi->ifp;
12083 		if (ifp == NULL)
12084 			continue;
12085 
12086 		if (lc->link_ok) {
12087 			ifp->if_baudrate = IF_Mbps(lc->speed);
12088 			if_link_state_change(ifp, LINK_STATE_UP);
12089 		} else {
12090 			if_link_state_change(ifp, LINK_STATE_DOWN);
12091 		}
12092 	}
12093 }
12094 
12095 void
12096 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12097 {
12098 	struct adapter *sc;
12099 
12100 	sx_slock(&t4_list_lock);
12101 	SLIST_FOREACH(sc, &t4_list, link) {
12102 		/*
12103 		 * func should not make any assumptions about what state sc is
12104 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12105 		 */
12106 		func(sc, arg);
12107 	}
12108 	sx_sunlock(&t4_list_lock);
12109 }
12110 
12111 static int
12112 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12113     struct thread *td)
12114 {
12115 	int rc;
12116 	struct adapter *sc = dev->si_drv1;
12117 
12118 	rc = priv_check(td, PRIV_DRIVER);
12119 	if (rc != 0)
12120 		return (rc);
12121 
12122 	switch (cmd) {
12123 	case CHELSIO_T4_GETREG: {
12124 		struct t4_reg *edata = (struct t4_reg *)data;
12125 
12126 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12127 			return (EFAULT);
12128 
12129 		mtx_lock(&sc->reg_lock);
12130 		if (hw_off_limits(sc))
12131 			rc = ENXIO;
12132 		else if (edata->size == 4)
12133 			edata->val = t4_read_reg(sc, edata->addr);
12134 		else if (edata->size == 8)
12135 			edata->val = t4_read_reg64(sc, edata->addr);
12136 		else
12137 			rc = EINVAL;
12138 		mtx_unlock(&sc->reg_lock);
12139 
12140 		break;
12141 	}
12142 	case CHELSIO_T4_SETREG: {
12143 		struct t4_reg *edata = (struct t4_reg *)data;
12144 
12145 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12146 			return (EFAULT);
12147 
12148 		mtx_lock(&sc->reg_lock);
12149 		if (hw_off_limits(sc))
12150 			rc = ENXIO;
12151 		else if (edata->size == 4) {
12152 			if (edata->val & 0xffffffff00000000)
12153 				rc = EINVAL;
12154 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12155 		} else if (edata->size == 8)
12156 			t4_write_reg64(sc, edata->addr, edata->val);
12157 		else
12158 			rc = EINVAL;
12159 		mtx_unlock(&sc->reg_lock);
12160 
12161 		break;
12162 	}
12163 	case CHELSIO_T4_REGDUMP: {
12164 		struct t4_regdump *regs = (struct t4_regdump *)data;
12165 		int reglen = t4_get_regs_len(sc);
12166 		uint8_t *buf;
12167 
12168 		if (regs->len < reglen) {
12169 			regs->len = reglen; /* hint to the caller */
12170 			return (ENOBUFS);
12171 		}
12172 
12173 		regs->len = reglen;
12174 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12175 		mtx_lock(&sc->reg_lock);
12176 		if (hw_off_limits(sc))
12177 			rc = ENXIO;
12178 		else
12179 			get_regs(sc, regs, buf);
12180 		mtx_unlock(&sc->reg_lock);
12181 		if (rc == 0)
12182 			rc = copyout(buf, regs->data, reglen);
12183 		free(buf, M_CXGBE);
12184 		break;
12185 	}
12186 	case CHELSIO_T4_GET_FILTER_MODE:
12187 		rc = get_filter_mode(sc, (uint32_t *)data);
12188 		break;
12189 	case CHELSIO_T4_SET_FILTER_MODE:
12190 		rc = set_filter_mode(sc, *(uint32_t *)data);
12191 		break;
12192 	case CHELSIO_T4_SET_FILTER_MASK:
12193 		rc = set_filter_mask(sc, *(uint32_t *)data);
12194 		break;
12195 	case CHELSIO_T4_GET_FILTER:
12196 		rc = get_filter(sc, (struct t4_filter *)data);
12197 		break;
12198 	case CHELSIO_T4_SET_FILTER:
12199 		rc = set_filter(sc, (struct t4_filter *)data);
12200 		break;
12201 	case CHELSIO_T4_DEL_FILTER:
12202 		rc = del_filter(sc, (struct t4_filter *)data);
12203 		break;
12204 	case CHELSIO_T4_GET_SGE_CONTEXT:
12205 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12206 		break;
12207 	case CHELSIO_T4_LOAD_FW:
12208 		rc = load_fw(sc, (struct t4_data *)data);
12209 		break;
12210 	case CHELSIO_T4_GET_MEM:
12211 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12212 		break;
12213 	case CHELSIO_T4_GET_I2C:
12214 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12215 		break;
12216 	case CHELSIO_T4_CLEAR_STATS:
12217 		rc = clear_stats(sc, *(uint32_t *)data);
12218 		break;
12219 	case CHELSIO_T4_SCHED_CLASS:
12220 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12221 		break;
12222 	case CHELSIO_T4_SCHED_QUEUE:
12223 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12224 		break;
12225 	case CHELSIO_T4_GET_TRACER:
12226 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12227 		break;
12228 	case CHELSIO_T4_SET_TRACER:
12229 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12230 		break;
12231 	case CHELSIO_T4_LOAD_CFG:
12232 		rc = load_cfg(sc, (struct t4_data *)data);
12233 		break;
12234 	case CHELSIO_T4_LOAD_BOOT:
12235 		rc = load_boot(sc, (struct t4_bootrom *)data);
12236 		break;
12237 	case CHELSIO_T4_LOAD_BOOTCFG:
12238 		rc = load_bootcfg(sc, (struct t4_data *)data);
12239 		break;
12240 	case CHELSIO_T4_CUDBG_DUMP:
12241 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12242 		break;
12243 	case CHELSIO_T4_SET_OFLD_POLICY:
12244 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12245 		break;
12246 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12247 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12248 		break;
12249 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12250 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12251 		break;
12252 	default:
12253 		rc = ENOTTY;
12254 	}
12255 
12256 	return (rc);
12257 }
12258 
12259 #ifdef TCP_OFFLOAD
12260 static int
12261 toe_capability(struct vi_info *vi, bool enable)
12262 {
12263 	int rc;
12264 	struct port_info *pi = vi->pi;
12265 	struct adapter *sc = pi->adapter;
12266 
12267 	ASSERT_SYNCHRONIZED_OP(sc);
12268 
12269 	if (!is_offload(sc))
12270 		return (ENODEV);
12271 	if (hw_off_limits(sc))
12272 		return (ENXIO);
12273 
12274 	if (enable) {
12275 #ifdef KERN_TLS
12276 		if (sc->flags & KERN_TLS_ON) {
12277 			int i, j, n;
12278 			struct port_info *p;
12279 			struct vi_info *v;
12280 
12281 			/*
12282 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12283 			 * on any ifnet.
12284 			 */
12285 			n = 0;
12286 			for_each_port(sc, i) {
12287 				p = sc->port[i];
12288 				for_each_vi(p, j, v) {
12289 					if (v->ifp->if_capenable & IFCAP_TXTLS) {
12290 						CH_WARN(sc,
12291 						    "%s has NIC TLS enabled.\n",
12292 						    device_get_nameunit(v->dev));
12293 						n++;
12294 					}
12295 				}
12296 			}
12297 			if (n > 0) {
12298 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12299 				    "associated with this adapter before "
12300 				    "trying to enable TOE.\n");
12301 				return (EAGAIN);
12302 			}
12303 			rc = t4_config_kern_tls(sc, false);
12304 			if (rc)
12305 				return (rc);
12306 		}
12307 #endif
12308 		if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
12309 			/* TOE is already enabled. */
12310 			return (0);
12311 		}
12312 
12313 		/*
12314 		 * We need the port's queues around so that we're able to send
12315 		 * and receive CPLs to/from the TOE even if the ifnet for this
12316 		 * port has never been UP'd administratively.
12317 		 */
12318 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12319 			return (rc);
12320 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12321 		    ((rc = vi_init(&pi->vi[0])) != 0))
12322 			return (rc);
12323 
12324 		if (isset(&sc->offload_map, pi->port_id)) {
12325 			/* TOE is enabled on another VI of this port. */
12326 			pi->uld_vis++;
12327 			return (0);
12328 		}
12329 
12330 		if (!uld_active(sc, ULD_TOM)) {
12331 			rc = t4_activate_uld(sc, ULD_TOM);
12332 			if (rc == EAGAIN) {
12333 				log(LOG_WARNING,
12334 				    "You must kldload t4_tom.ko before trying "
12335 				    "to enable TOE on a cxgbe interface.\n");
12336 			}
12337 			if (rc != 0)
12338 				return (rc);
12339 			KASSERT(sc->tom_softc != NULL,
12340 			    ("%s: TOM activated but softc NULL", __func__));
12341 			KASSERT(uld_active(sc, ULD_TOM),
12342 			    ("%s: TOM activated but flag not set", __func__));
12343 		}
12344 
12345 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12346 		if (!uld_active(sc, ULD_IWARP))
12347 			(void) t4_activate_uld(sc, ULD_IWARP);
12348 		if (!uld_active(sc, ULD_ISCSI))
12349 			(void) t4_activate_uld(sc, ULD_ISCSI);
12350 
12351 		pi->uld_vis++;
12352 		setbit(&sc->offload_map, pi->port_id);
12353 	} else {
12354 		pi->uld_vis--;
12355 
12356 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12357 			return (0);
12358 
12359 		KASSERT(uld_active(sc, ULD_TOM),
12360 		    ("%s: TOM never initialized?", __func__));
12361 		clrbit(&sc->offload_map, pi->port_id);
12362 	}
12363 
12364 	return (0);
12365 }
12366 
12367 /*
12368  * Add an upper layer driver to the global list.
12369  */
12370 int
12371 t4_register_uld(struct uld_info *ui)
12372 {
12373 	int rc = 0;
12374 	struct uld_info *u;
12375 
12376 	sx_xlock(&t4_uld_list_lock);
12377 	SLIST_FOREACH(u, &t4_uld_list, link) {
12378 	    if (u->uld_id == ui->uld_id) {
12379 		    rc = EEXIST;
12380 		    goto done;
12381 	    }
12382 	}
12383 
12384 	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
12385 	ui->refcount = 0;
12386 done:
12387 	sx_xunlock(&t4_uld_list_lock);
12388 	return (rc);
12389 }
12390 
12391 int
12392 t4_unregister_uld(struct uld_info *ui)
12393 {
12394 	int rc = EINVAL;
12395 	struct uld_info *u;
12396 
12397 	sx_xlock(&t4_uld_list_lock);
12398 
12399 	SLIST_FOREACH(u, &t4_uld_list, link) {
12400 	    if (u == ui) {
12401 		    if (ui->refcount > 0) {
12402 			    rc = EBUSY;
12403 			    goto done;
12404 		    }
12405 
12406 		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
12407 		    rc = 0;
12408 		    goto done;
12409 	    }
12410 	}
12411 done:
12412 	sx_xunlock(&t4_uld_list_lock);
12413 	return (rc);
12414 }
12415 
12416 int
12417 t4_activate_uld(struct adapter *sc, int id)
12418 {
12419 	int rc;
12420 	struct uld_info *ui;
12421 
12422 	ASSERT_SYNCHRONIZED_OP(sc);
12423 
12424 	if (id < 0 || id > ULD_MAX)
12425 		return (EINVAL);
12426 	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
12427 
12428 	sx_slock(&t4_uld_list_lock);
12429 
12430 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12431 		if (ui->uld_id == id) {
12432 			if (!(sc->flags & FULL_INIT_DONE)) {
12433 				rc = adapter_init(sc);
12434 				if (rc != 0)
12435 					break;
12436 			}
12437 
12438 			rc = ui->activate(sc);
12439 			if (rc == 0) {
12440 				setbit(&sc->active_ulds, id);
12441 				ui->refcount++;
12442 			}
12443 			break;
12444 		}
12445 	}
12446 
12447 	sx_sunlock(&t4_uld_list_lock);
12448 
12449 	return (rc);
12450 }
12451 
12452 int
12453 t4_deactivate_uld(struct adapter *sc, int id)
12454 {
12455 	int rc;
12456 	struct uld_info *ui;
12457 
12458 	ASSERT_SYNCHRONIZED_OP(sc);
12459 
12460 	if (id < 0 || id > ULD_MAX)
12461 		return (EINVAL);
12462 	rc = ENXIO;
12463 
12464 	sx_slock(&t4_uld_list_lock);
12465 
12466 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12467 		if (ui->uld_id == id) {
12468 			rc = ui->deactivate(sc);
12469 			if (rc == 0) {
12470 				clrbit(&sc->active_ulds, id);
12471 				ui->refcount--;
12472 			}
12473 			break;
12474 		}
12475 	}
12476 
12477 	sx_sunlock(&t4_uld_list_lock);
12478 
12479 	return (rc);
12480 }
12481 
12482 static void
12483 t4_async_event(void *arg, int n)
12484 {
12485 	struct uld_info *ui;
12486 	struct adapter *sc = (struct adapter *)arg;
12487 
12488 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
12489 		return;
12490 	sx_slock(&t4_uld_list_lock);
12491 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12492 		if (ui->uld_id == ULD_IWARP) {
12493 			ui->async_event(sc);
12494 			break;
12495 		}
12496 	}
12497 	sx_sunlock(&t4_uld_list_lock);
12498 	end_synchronized_op(sc, 0);
12499 }
12500 
12501 int
12502 uld_active(struct adapter *sc, int uld_id)
12503 {
12504 
12505 	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
12506 
12507 	return (isset(&sc->active_ulds, uld_id));
12508 }
12509 #endif
12510 
12511 #ifdef KERN_TLS
12512 static int
12513 ktls_capability(struct adapter *sc, bool enable)
12514 {
12515 	ASSERT_SYNCHRONIZED_OP(sc);
12516 
12517 	if (!is_ktls(sc))
12518 		return (ENODEV);
12519 	if (hw_off_limits(sc))
12520 		return (ENXIO);
12521 
12522 	if (enable) {
12523 		if (sc->flags & KERN_TLS_ON)
12524 			return (0);	/* already on */
12525 		if (sc->offload_map != 0) {
12526 			CH_WARN(sc,
12527 			    "Disable TOE on all interfaces associated with "
12528 			    "this adapter before trying to enable NIC TLS.\n");
12529 			return (EAGAIN);
12530 		}
12531 		return (t4_config_kern_tls(sc, true));
12532 	} else {
12533 		/*
12534 		 * Nothing to do for disable.  If TOE is enabled sometime later
12535 		 * then toe_capability will reconfigure the hardware.
12536 		 */
12537 		return (0);
12538 	}
12539 }
12540 #endif
12541 
12542 /*
12543  * t  = ptr to tunable.
12544  * nc = number of CPUs.
12545  * c  = compiled in default for that tunable.
12546  */
12547 static void
12548 calculate_nqueues(int *t, int nc, const int c)
12549 {
12550 	int nq;
12551 
12552 	if (*t > 0)
12553 		return;
12554 	nq = *t < 0 ? -*t : c;
12555 	*t = min(nc, nq);
12556 }
12557 
12558 /*
12559  * Come up with reasonable defaults for some of the tunables, provided they're
12560  * not set by the user (in which case we'll use the values as is).
12561  */
12562 static void
12563 tweak_tunables(void)
12564 {
12565 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12566 
12567 	if (t4_ntxq < 1) {
12568 #ifdef RSS
12569 		t4_ntxq = rss_getnumbuckets();
12570 #else
12571 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12572 #endif
12573 	}
12574 
12575 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12576 
12577 	if (t4_nrxq < 1) {
12578 #ifdef RSS
12579 		t4_nrxq = rss_getnumbuckets();
12580 #else
12581 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12582 #endif
12583 	}
12584 
12585 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12586 
12587 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12588 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12589 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12590 #endif
12591 #ifdef TCP_OFFLOAD
12592 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12593 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12594 #endif
12595 
12596 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12597 	if (t4_toecaps_allowed == -1)
12598 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12599 #else
12600 	if (t4_toecaps_allowed == -1)
12601 		t4_toecaps_allowed = 0;
12602 #endif
12603 
12604 #ifdef TCP_OFFLOAD
12605 	if (t4_rdmacaps_allowed == -1) {
12606 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12607 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12608 	}
12609 
12610 	if (t4_iscsicaps_allowed == -1) {
12611 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12612 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12613 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12614 	}
12615 
12616 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12617 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12618 
12619 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12620 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12621 
12622 	if (t4_toe_tls_rx_timeout < 0)
12623 		t4_toe_tls_rx_timeout = 0;
12624 #else
12625 	if (t4_rdmacaps_allowed == -1)
12626 		t4_rdmacaps_allowed = 0;
12627 
12628 	if (t4_iscsicaps_allowed == -1)
12629 		t4_iscsicaps_allowed = 0;
12630 #endif
12631 
12632 #ifdef DEV_NETMAP
12633 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12634 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12635 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12636 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12637 #endif
12638 
12639 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12640 		t4_tmr_idx = TMR_IDX;
12641 
12642 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12643 		t4_pktc_idx = PKTC_IDX;
12644 
12645 	if (t4_qsize_txq < 128)
12646 		t4_qsize_txq = 128;
12647 
12648 	if (t4_qsize_rxq < 128)
12649 		t4_qsize_rxq = 128;
12650 	while (t4_qsize_rxq & 7)
12651 		t4_qsize_rxq++;
12652 
12653 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12654 
12655 	/*
12656 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12657 	 * VI for the port.  The rest are additional virtual interfaces on the
12658 	 * same physical port.  Note that the main VI does not have native
12659 	 * netmap support but the extra VIs do.
12660 	 *
12661 	 * Limit the number of VIs per port to the number of available
12662 	 * MAC addresses per port.
12663 	 */
12664 	if (t4_num_vis < 1)
12665 		t4_num_vis = 1;
12666 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12667 		t4_num_vis = nitems(vi_mac_funcs);
12668 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12669 	}
12670 
12671 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12672 		pcie_relaxed_ordering = 1;
12673 #if defined(__i386__) || defined(__amd64__)
12674 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12675 			pcie_relaxed_ordering = 0;
12676 #endif
12677 	}
12678 }
12679 
12680 #ifdef DDB
12681 static void
12682 t4_dump_tcb(struct adapter *sc, int tid)
12683 {
12684 	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
12685 
12686 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12687 	save = t4_read_reg(sc, reg);
12688 	base = sc->memwin[2].mw_base;
12689 
12690 	/* Dump TCB for the tid */
12691 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12692 	tcb_addr += tid * TCB_SIZE;
12693 
12694 	if (is_t4(sc)) {
12695 		pf = 0;
12696 		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
12697 	} else {
12698 		pf = V_PFNUM(sc->pf);
12699 		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
12700 	}
12701 	t4_write_reg(sc, reg, win_pos | pf);
12702 	t4_read_reg(sc, reg);
12703 
12704 	off = tcb_addr - win_pos;
12705 	for (i = 0; i < 4; i++) {
12706 		uint32_t buf[8];
12707 		for (j = 0; j < 8; j++, off += 4)
12708 			buf[j] = htonl(t4_read_reg(sc, base + off));
12709 
12710 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12711 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12712 		    buf[7]);
12713 	}
12714 
12715 	t4_write_reg(sc, reg, save);
12716 	t4_read_reg(sc, reg);
12717 }
12718 
12719 static void
12720 t4_dump_devlog(struct adapter *sc)
12721 {
12722 	struct devlog_params *dparams = &sc->params.devlog;
12723 	struct fw_devlog_e e;
12724 	int i, first, j, m, nentries, rc;
12725 	uint64_t ftstamp = UINT64_MAX;
12726 
12727 	if (dparams->start == 0) {
12728 		db_printf("devlog params not valid\n");
12729 		return;
12730 	}
12731 
12732 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12733 	m = fwmtype_to_hwmtype(dparams->memtype);
12734 
12735 	/* Find the first entry. */
12736 	first = -1;
12737 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12738 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12739 		    sizeof(e), (void *)&e);
12740 		if (rc != 0)
12741 			break;
12742 
12743 		if (e.timestamp == 0)
12744 			break;
12745 
12746 		e.timestamp = be64toh(e.timestamp);
12747 		if (e.timestamp < ftstamp) {
12748 			ftstamp = e.timestamp;
12749 			first = i;
12750 		}
12751 	}
12752 
12753 	if (first == -1)
12754 		return;
12755 
12756 	i = first;
12757 	do {
12758 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12759 		    sizeof(e), (void *)&e);
12760 		if (rc != 0)
12761 			return;
12762 
12763 		if (e.timestamp == 0)
12764 			return;
12765 
12766 		e.timestamp = be64toh(e.timestamp);
12767 		e.seqno = be32toh(e.seqno);
12768 		for (j = 0; j < 8; j++)
12769 			e.params[j] = be32toh(e.params[j]);
12770 
12771 		db_printf("%10d  %15ju  %8s  %8s  ",
12772 		    e.seqno, e.timestamp,
12773 		    (e.level < nitems(devlog_level_strings) ?
12774 			devlog_level_strings[e.level] : "UNKNOWN"),
12775 		    (e.facility < nitems(devlog_facility_strings) ?
12776 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12777 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12778 		    e.params[3], e.params[4], e.params[5], e.params[6],
12779 		    e.params[7]);
12780 
12781 		if (++i == nentries)
12782 			i = 0;
12783 	} while (i != first && !db_pager_quit);
12784 }
12785 
12786 static struct command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
12787 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
12788 
12789 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
12790 {
12791 	device_t dev;
12792 	int t;
12793 	bool valid;
12794 
12795 	valid = false;
12796 	t = db_read_token();
12797 	if (t == tIDENT) {
12798 		dev = device_lookup_by_name(db_tok_string);
12799 		valid = true;
12800 	}
12801 	db_skip_to_eol();
12802 	if (!valid) {
12803 		db_printf("usage: show t4 devlog <nexus>\n");
12804 		return;
12805 	}
12806 
12807 	if (dev == NULL) {
12808 		db_printf("device not found\n");
12809 		return;
12810 	}
12811 
12812 	t4_dump_devlog(device_get_softc(dev));
12813 }
12814 
12815 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
12816 {
12817 	device_t dev;
12818 	int radix, tid, t;
12819 	bool valid;
12820 
12821 	valid = false;
12822 	radix = db_radix;
12823 	db_radix = 10;
12824 	t = db_read_token();
12825 	if (t == tIDENT) {
12826 		dev = device_lookup_by_name(db_tok_string);
12827 		t = db_read_token();
12828 		if (t == tNUMBER) {
12829 			tid = db_tok_number;
12830 			valid = true;
12831 		}
12832 	}
12833 	db_radix = radix;
12834 	db_skip_to_eol();
12835 	if (!valid) {
12836 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
12837 		return;
12838 	}
12839 
12840 	if (dev == NULL) {
12841 		db_printf("device not found\n");
12842 		return;
12843 	}
12844 	if (tid < 0) {
12845 		db_printf("invalid tid\n");
12846 		return;
12847 	}
12848 
12849 	t4_dump_tcb(device_get_softc(dev), tid);
12850 }
12851 #endif
12852 
12853 static eventhandler_tag vxlan_start_evtag;
12854 static eventhandler_tag vxlan_stop_evtag;
12855 
12856 struct vxlan_evargs {
12857 	struct ifnet *ifp;
12858 	uint16_t port;
12859 };
12860 
12861 static void
12862 enable_vxlan_rx(struct adapter *sc)
12863 {
12864 	int i, rc;
12865 	struct port_info *pi;
12866 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
12867 
12868 	ASSERT_SYNCHRONIZED_OP(sc);
12869 
12870 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
12871 	    F_VXLAN_EN);
12872 	for_each_port(sc, i) {
12873 		pi = sc->port[i];
12874 		if (pi->vxlan_tcam_entry == true)
12875 			continue;
12876 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
12877 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
12878 		    true);
12879 		if (rc < 0) {
12880 			rc = -rc;
12881 			CH_ERR(&pi->vi[0],
12882 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
12883 		} else {
12884 			MPASS(rc == sc->rawf_base + pi->port_id);
12885 			pi->vxlan_tcam_entry = true;
12886 		}
12887 	}
12888 }
12889 
12890 static void
12891 t4_vxlan_start(struct adapter *sc, void *arg)
12892 {
12893 	struct vxlan_evargs *v = arg;
12894 
12895 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
12896 		return;
12897 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
12898 		return;
12899 
12900 	if (sc->vxlan_refcount == 0) {
12901 		sc->vxlan_port = v->port;
12902 		sc->vxlan_refcount = 1;
12903 		if (!hw_off_limits(sc))
12904 			enable_vxlan_rx(sc);
12905 	} else if (sc->vxlan_port == v->port) {
12906 		sc->vxlan_refcount++;
12907 	} else {
12908 		CH_ERR(sc, "VXLAN already configured on port  %d; "
12909 		    "ignoring attempt to configure it on port %d\n",
12910 		    sc->vxlan_port, v->port);
12911 	}
12912 	end_synchronized_op(sc, 0);
12913 }
12914 
12915 static void
12916 t4_vxlan_stop(struct adapter *sc, void *arg)
12917 {
12918 	struct vxlan_evargs *v = arg;
12919 
12920 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
12921 		return;
12922 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
12923 		return;
12924 
12925 	/*
12926 	 * VXLANs may have been configured before the driver was loaded so we
12927 	 * may see more stops than starts.  This is not handled cleanly but at
12928 	 * least we keep the refcount sane.
12929 	 */
12930 	if (sc->vxlan_port != v->port)
12931 		goto done;
12932 	if (sc->vxlan_refcount == 0) {
12933 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
12934 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
12935 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
12936 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
12937 done:
12938 	end_synchronized_op(sc, 0);
12939 }
12940 
12941 static void
12942 t4_vxlan_start_handler(void *arg __unused, struct ifnet *ifp,
12943     sa_family_t family, u_int port)
12944 {
12945 	struct vxlan_evargs v;
12946 
12947 	MPASS(family == AF_INET || family == AF_INET6);
12948 	v.ifp = ifp;
12949 	v.port = port;
12950 
12951 	t4_iterate(t4_vxlan_start, &v);
12952 }
12953 
12954 static void
12955 t4_vxlan_stop_handler(void *arg __unused, struct ifnet *ifp, sa_family_t family,
12956     u_int port)
12957 {
12958 	struct vxlan_evargs v;
12959 
12960 	MPASS(family == AF_INET || family == AF_INET6);
12961 	v.ifp = ifp;
12962 	v.port = port;
12963 
12964 	t4_iterate(t4_vxlan_stop, &v);
12965 }
12966 
12967 
12968 static struct sx mlu;	/* mod load unload */
12969 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
12970 
12971 static int
12972 mod_event(module_t mod, int cmd, void *arg)
12973 {
12974 	int rc = 0;
12975 	static int loaded = 0;
12976 
12977 	switch (cmd) {
12978 	case MOD_LOAD:
12979 		sx_xlock(&mlu);
12980 		if (loaded++ == 0) {
12981 			t4_sge_modload();
12982 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
12983 			    t4_filter_rpl, CPL_COOKIE_FILTER);
12984 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
12985 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
12986 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
12987 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
12988 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
12989 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
12990 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
12991 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
12992 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
12993 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
12994 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
12995 			    do_smt_write_rpl);
12996 			sx_init(&t4_list_lock, "T4/T5 adapters");
12997 			SLIST_INIT(&t4_list);
12998 			callout_init(&fatal_callout, 1);
12999 #ifdef TCP_OFFLOAD
13000 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
13001 			SLIST_INIT(&t4_uld_list);
13002 #endif
13003 #ifdef INET6
13004 			t4_clip_modload();
13005 #endif
13006 #ifdef KERN_TLS
13007 			t6_ktls_modload();
13008 #endif
13009 			t4_tracer_modload();
13010 			tweak_tunables();
13011 			vxlan_start_evtag =
13012 			    EVENTHANDLER_REGISTER(vxlan_start,
13013 				t4_vxlan_start_handler, NULL,
13014 				EVENTHANDLER_PRI_ANY);
13015 			vxlan_stop_evtag =
13016 			    EVENTHANDLER_REGISTER(vxlan_stop,
13017 				t4_vxlan_stop_handler, NULL,
13018 				EVENTHANDLER_PRI_ANY);
13019 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
13020 			    taskqueue_thread_enqueue, &reset_tq);
13021 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
13022 			    "t4_rst_thr");
13023 		}
13024 		sx_xunlock(&mlu);
13025 		break;
13026 
13027 	case MOD_UNLOAD:
13028 		sx_xlock(&mlu);
13029 		if (--loaded == 0) {
13030 			int tries;
13031 
13032 			taskqueue_free(reset_tq);
13033 			sx_slock(&t4_list_lock);
13034 			if (!SLIST_EMPTY(&t4_list)) {
13035 				rc = EBUSY;
13036 				sx_sunlock(&t4_list_lock);
13037 				goto done_unload;
13038 			}
13039 #ifdef TCP_OFFLOAD
13040 			sx_slock(&t4_uld_list_lock);
13041 			if (!SLIST_EMPTY(&t4_uld_list)) {
13042 				rc = EBUSY;
13043 				sx_sunlock(&t4_uld_list_lock);
13044 				sx_sunlock(&t4_list_lock);
13045 				goto done_unload;
13046 			}
13047 #endif
13048 			tries = 0;
13049 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13050 				uprintf("%ju clusters with custom free routine "
13051 				    "still is use.\n", t4_sge_extfree_refs());
13052 				pause("t4unload", 2 * hz);
13053 			}
13054 #ifdef TCP_OFFLOAD
13055 			sx_sunlock(&t4_uld_list_lock);
13056 #endif
13057 			sx_sunlock(&t4_list_lock);
13058 
13059 			if (t4_sge_extfree_refs() == 0) {
13060 				EVENTHANDLER_DEREGISTER(vxlan_start,
13061 				    vxlan_start_evtag);
13062 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13063 				    vxlan_stop_evtag);
13064 				t4_tracer_modunload();
13065 #ifdef KERN_TLS
13066 				t6_ktls_modunload();
13067 #endif
13068 #ifdef INET6
13069 				t4_clip_modunload();
13070 #endif
13071 #ifdef TCP_OFFLOAD
13072 				sx_destroy(&t4_uld_list_lock);
13073 #endif
13074 				sx_destroy(&t4_list_lock);
13075 				t4_sge_modunload();
13076 				loaded = 0;
13077 			} else {
13078 				rc = EBUSY;
13079 				loaded++;	/* undo earlier decrement */
13080 			}
13081 		}
13082 done_unload:
13083 		sx_xunlock(&mlu);
13084 		break;
13085 	}
13086 
13087 	return (rc);
13088 }
13089 
13090 static devclass_t t4_devclass, t5_devclass, t6_devclass;
13091 static devclass_t cxgbe_devclass, cxl_devclass, cc_devclass;
13092 static devclass_t vcxgbe_devclass, vcxl_devclass, vcc_devclass;
13093 
13094 DRIVER_MODULE(t4nex, pci, t4_driver, t4_devclass, mod_event, 0);
13095 MODULE_VERSION(t4nex, 1);
13096 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13097 #ifdef DEV_NETMAP
13098 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13099 #endif /* DEV_NETMAP */
13100 
13101 DRIVER_MODULE(t5nex, pci, t5_driver, t5_devclass, mod_event, 0);
13102 MODULE_VERSION(t5nex, 1);
13103 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13104 #ifdef DEV_NETMAP
13105 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13106 #endif /* DEV_NETMAP */
13107 
13108 DRIVER_MODULE(t6nex, pci, t6_driver, t6_devclass, mod_event, 0);
13109 MODULE_VERSION(t6nex, 1);
13110 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13111 #ifdef DEV_NETMAP
13112 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13113 #endif /* DEV_NETMAP */
13114 
13115 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, cxgbe_devclass, 0, 0);
13116 MODULE_VERSION(cxgbe, 1);
13117 
13118 DRIVER_MODULE(cxl, t5nex, cxl_driver, cxl_devclass, 0, 0);
13119 MODULE_VERSION(cxl, 1);
13120 
13121 DRIVER_MODULE(cc, t6nex, cc_driver, cc_devclass, 0, 0);
13122 MODULE_VERSION(cc, 1);
13123 
13124 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, vcxgbe_devclass, 0, 0);
13125 MODULE_VERSION(vcxgbe, 1);
13126 
13127 DRIVER_MODULE(vcxl, cxl, vcxl_driver, vcxl_devclass, 0, 0);
13128 MODULE_VERSION(vcxl, 1);
13129 
13130 DRIVER_MODULE(vcc, cc, vcc_driver, vcc_devclass, 0, 0);
13131 MODULE_VERSION(vcc, 1);
13132