xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision 81b22a98)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 Chelsio Communications, Inc.
5  * All rights reserved.
6  * Written by: Navdeep Parhar <np@FreeBSD.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include "opt_ddb.h"
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_kern_tls.h"
37 #include "opt_ratelimit.h"
38 #include "opt_rss.h"
39 
40 #include <sys/param.h>
41 #include <sys/conf.h>
42 #include <sys/priv.h>
43 #include <sys/kernel.h>
44 #include <sys/bus.h>
45 #include <sys/eventhandler.h>
46 #include <sys/module.h>
47 #include <sys/malloc.h>
48 #include <sys/queue.h>
49 #include <sys/taskqueue.h>
50 #include <sys/pciio.h>
51 #include <dev/pci/pcireg.h>
52 #include <dev/pci/pcivar.h>
53 #include <dev/pci/pci_private.h>
54 #include <sys/firmware.h>
55 #include <sys/sbuf.h>
56 #include <sys/smp.h>
57 #include <sys/socket.h>
58 #include <sys/sockio.h>
59 #include <sys/sysctl.h>
60 #include <net/ethernet.h>
61 #include <net/if.h>
62 #include <net/if_types.h>
63 #include <net/if_dl.h>
64 #include <net/if_vlan_var.h>
65 #ifdef RSS
66 #include <net/rss_config.h>
67 #endif
68 #include <netinet/in.h>
69 #include <netinet/ip.h>
70 #ifdef KERN_TLS
71 #include <netinet/tcp_seq.h>
72 #endif
73 #if defined(__i386__) || defined(__amd64__)
74 #include <machine/md_var.h>
75 #include <machine/cputypes.h>
76 #include <vm/vm.h>
77 #include <vm/pmap.h>
78 #endif
79 #ifdef DDB
80 #include <ddb/ddb.h>
81 #include <ddb/db_lex.h>
82 #endif
83 
84 #include "common/common.h"
85 #include "common/t4_msg.h"
86 #include "common/t4_regs.h"
87 #include "common/t4_regs_values.h"
88 #include "cudbg/cudbg.h"
89 #include "t4_clip.h"
90 #include "t4_ioctl.h"
91 #include "t4_l2t.h"
92 #include "t4_mp_ring.h"
93 #include "t4_if.h"
94 #include "t4_smt.h"
95 
96 /* T4 bus driver interface */
97 static int t4_probe(device_t);
98 static int t4_attach(device_t);
99 static int t4_detach(device_t);
100 static int t4_child_location(device_t, device_t, struct sbuf *);
101 static int t4_ready(device_t);
102 static int t4_read_port_device(device_t, int, device_t *);
103 static int t4_suspend(device_t);
104 static int t4_resume(device_t);
105 static int t4_reset_prepare(device_t, device_t);
106 static int t4_reset_post(device_t, device_t);
107 static device_method_t t4_methods[] = {
108 	DEVMETHOD(device_probe,		t4_probe),
109 	DEVMETHOD(device_attach,	t4_attach),
110 	DEVMETHOD(device_detach,	t4_detach),
111 	DEVMETHOD(device_suspend,	t4_suspend),
112 	DEVMETHOD(device_resume,	t4_resume),
113 
114 	DEVMETHOD(bus_child_location,	t4_child_location),
115 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
116 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
117 
118 	DEVMETHOD(t4_is_main_ready,	t4_ready),
119 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
120 
121 	DEVMETHOD_END
122 };
123 static driver_t t4_driver = {
124 	"t4nex",
125 	t4_methods,
126 	sizeof(struct adapter)
127 };
128 
129 
130 /* T4 port (cxgbe) interface */
131 static int cxgbe_probe(device_t);
132 static int cxgbe_attach(device_t);
133 static int cxgbe_detach(device_t);
134 device_method_t cxgbe_methods[] = {
135 	DEVMETHOD(device_probe,		cxgbe_probe),
136 	DEVMETHOD(device_attach,	cxgbe_attach),
137 	DEVMETHOD(device_detach,	cxgbe_detach),
138 	{ 0, 0 }
139 };
140 static driver_t cxgbe_driver = {
141 	"cxgbe",
142 	cxgbe_methods,
143 	sizeof(struct port_info)
144 };
145 
146 /* T4 VI (vcxgbe) interface */
147 static int vcxgbe_probe(device_t);
148 static int vcxgbe_attach(device_t);
149 static int vcxgbe_detach(device_t);
150 static device_method_t vcxgbe_methods[] = {
151 	DEVMETHOD(device_probe,		vcxgbe_probe),
152 	DEVMETHOD(device_attach,	vcxgbe_attach),
153 	DEVMETHOD(device_detach,	vcxgbe_detach),
154 	{ 0, 0 }
155 };
156 static driver_t vcxgbe_driver = {
157 	"vcxgbe",
158 	vcxgbe_methods,
159 	sizeof(struct vi_info)
160 };
161 
162 static d_ioctl_t t4_ioctl;
163 
164 static struct cdevsw t4_cdevsw = {
165        .d_version = D_VERSION,
166        .d_ioctl = t4_ioctl,
167        .d_name = "t4nex",
168 };
169 
170 /* T5 bus driver interface */
171 static int t5_probe(device_t);
172 static device_method_t t5_methods[] = {
173 	DEVMETHOD(device_probe,		t5_probe),
174 	DEVMETHOD(device_attach,	t4_attach),
175 	DEVMETHOD(device_detach,	t4_detach),
176 	DEVMETHOD(device_suspend,	t4_suspend),
177 	DEVMETHOD(device_resume,	t4_resume),
178 
179 	DEVMETHOD(bus_child_location,	t4_child_location),
180 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
181 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
182 
183 	DEVMETHOD(t4_is_main_ready,	t4_ready),
184 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
185 
186 	DEVMETHOD_END
187 };
188 static driver_t t5_driver = {
189 	"t5nex",
190 	t5_methods,
191 	sizeof(struct adapter)
192 };
193 
194 
195 /* T5 port (cxl) interface */
196 static driver_t cxl_driver = {
197 	"cxl",
198 	cxgbe_methods,
199 	sizeof(struct port_info)
200 };
201 
202 /* T5 VI (vcxl) interface */
203 static driver_t vcxl_driver = {
204 	"vcxl",
205 	vcxgbe_methods,
206 	sizeof(struct vi_info)
207 };
208 
209 /* T6 bus driver interface */
210 static int t6_probe(device_t);
211 static device_method_t t6_methods[] = {
212 	DEVMETHOD(device_probe,		t6_probe),
213 	DEVMETHOD(device_attach,	t4_attach),
214 	DEVMETHOD(device_detach,	t4_detach),
215 	DEVMETHOD(device_suspend,	t4_suspend),
216 	DEVMETHOD(device_resume,	t4_resume),
217 
218 	DEVMETHOD(bus_child_location,	t4_child_location),
219 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
220 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
221 
222 	DEVMETHOD(t4_is_main_ready,	t4_ready),
223 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
224 
225 	DEVMETHOD_END
226 };
227 static driver_t t6_driver = {
228 	"t6nex",
229 	t6_methods,
230 	sizeof(struct adapter)
231 };
232 
233 
234 /* T6 port (cc) interface */
235 static driver_t cc_driver = {
236 	"cc",
237 	cxgbe_methods,
238 	sizeof(struct port_info)
239 };
240 
241 /* T6 VI (vcc) interface */
242 static driver_t vcc_driver = {
243 	"vcc",
244 	vcxgbe_methods,
245 	sizeof(struct vi_info)
246 };
247 
248 /* ifnet interface */
249 static void cxgbe_init(void *);
250 static int cxgbe_ioctl(struct ifnet *, unsigned long, caddr_t);
251 static int cxgbe_transmit(struct ifnet *, struct mbuf *);
252 static void cxgbe_qflush(struct ifnet *);
253 #if defined(KERN_TLS) || defined(RATELIMIT)
254 static int cxgbe_snd_tag_alloc(struct ifnet *, union if_snd_tag_alloc_params *,
255     struct m_snd_tag **);
256 #endif
257 
258 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
259 
260 /*
261  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
262  * then ADAPTER_LOCK, then t4_uld_list_lock.
263  */
264 static struct sx t4_list_lock;
265 SLIST_HEAD(, adapter) t4_list;
266 #ifdef TCP_OFFLOAD
267 static struct sx t4_uld_list_lock;
268 SLIST_HEAD(, uld_info) t4_uld_list;
269 #endif
270 
271 /*
272  * Tunables.  See tweak_tunables() too.
273  *
274  * Each tunable is set to a default value here if it's known at compile-time.
275  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
276  * provide a reasonable default (upto n) when the driver is loaded.
277  *
278  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
279  * T5 are under hw.cxl.
280  */
281 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
282     "cxgbe(4) parameters");
283 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
284     "cxgbe(4) T5+ parameters");
285 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
286     "cxgbe(4) TOE parameters");
287 
288 /*
289  * Number of queues for tx and rx, NIC and offload.
290  */
291 #define NTXQ 16
292 int t4_ntxq = -NTXQ;
293 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
294     "Number of TX queues per port");
295 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);	/* Old name, undocumented */
296 
297 #define NRXQ 8
298 int t4_nrxq = -NRXQ;
299 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
300     "Number of RX queues per port");
301 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);	/* Old name, undocumented */
302 
303 #define NTXQ_VI 1
304 static int t4_ntxq_vi = -NTXQ_VI;
305 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
306     "Number of TX queues per VI");
307 
308 #define NRXQ_VI 1
309 static int t4_nrxq_vi = -NRXQ_VI;
310 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
311     "Number of RX queues per VI");
312 
313 static int t4_rsrv_noflowq = 0;
314 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
315     0, "Reserve TX queue 0 of each VI for non-flowid packets");
316 
317 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
318 #define NOFLDTXQ 8
319 static int t4_nofldtxq = -NOFLDTXQ;
320 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
321     "Number of offload TX queues per port");
322 
323 #define NOFLDRXQ 2
324 static int t4_nofldrxq = -NOFLDRXQ;
325 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
326     "Number of offload RX queues per port");
327 
328 #define NOFLDTXQ_VI 1
329 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
330 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
331     "Number of offload TX queues per VI");
332 
333 #define NOFLDRXQ_VI 1
334 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
335 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
336     "Number of offload RX queues per VI");
337 
338 #define TMR_IDX_OFLD 1
339 int t4_tmr_idx_ofld = TMR_IDX_OFLD;
340 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
341     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
342 
343 #define PKTC_IDX_OFLD (-1)
344 int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
345 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
346     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
347 
348 /* 0 means chip/fw default, non-zero number is value in microseconds */
349 static u_long t4_toe_keepalive_idle = 0;
350 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
351     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
352 
353 /* 0 means chip/fw default, non-zero number is value in microseconds */
354 static u_long t4_toe_keepalive_interval = 0;
355 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
356     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
357 
358 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
359 static int t4_toe_keepalive_count = 0;
360 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
361     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
362 
363 /* 0 means chip/fw default, non-zero number is value in microseconds */
364 static u_long t4_toe_rexmt_min = 0;
365 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
366     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
367 
368 /* 0 means chip/fw default, non-zero number is value in microseconds */
369 static u_long t4_toe_rexmt_max = 0;
370 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
371     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
372 
373 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
374 static int t4_toe_rexmt_count = 0;
375 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
376     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
377 
378 /* -1 means chip/fw default, other values are raw backoff values to use */
379 static int t4_toe_rexmt_backoff[16] = {
380 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
381 };
382 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
383     CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
384     "cxgbe(4) TOE retransmit backoff values");
385 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
386     &t4_toe_rexmt_backoff[0], 0, "");
387 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
388     &t4_toe_rexmt_backoff[1], 0, "");
389 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
390     &t4_toe_rexmt_backoff[2], 0, "");
391 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
392     &t4_toe_rexmt_backoff[3], 0, "");
393 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
394     &t4_toe_rexmt_backoff[4], 0, "");
395 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
396     &t4_toe_rexmt_backoff[5], 0, "");
397 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
398     &t4_toe_rexmt_backoff[6], 0, "");
399 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
400     &t4_toe_rexmt_backoff[7], 0, "");
401 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
402     &t4_toe_rexmt_backoff[8], 0, "");
403 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
404     &t4_toe_rexmt_backoff[9], 0, "");
405 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
406     &t4_toe_rexmt_backoff[10], 0, "");
407 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
408     &t4_toe_rexmt_backoff[11], 0, "");
409 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
410     &t4_toe_rexmt_backoff[12], 0, "");
411 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
412     &t4_toe_rexmt_backoff[13], 0, "");
413 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
414     &t4_toe_rexmt_backoff[14], 0, "");
415 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
416     &t4_toe_rexmt_backoff[15], 0, "");
417 
418 static int t4_toe_tls_rx_timeout = 5;
419 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, tls_rx_timeout, CTLFLAG_RDTUN,
420     &t4_toe_tls_rx_timeout, 0,
421     "Timeout in seconds to downgrade TLS sockets to plain TOE");
422 #endif
423 
424 #ifdef DEV_NETMAP
425 #define NN_MAIN_VI	(1 << 0)	/* Native netmap on the main VI */
426 #define NN_EXTRA_VI	(1 << 1)	/* Native netmap on the extra VI(s) */
427 static int t4_native_netmap = NN_EXTRA_VI;
428 SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
429     0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
430 
431 #define NNMTXQ 8
432 static int t4_nnmtxq = -NNMTXQ;
433 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
434     "Number of netmap TX queues");
435 
436 #define NNMRXQ 8
437 static int t4_nnmrxq = -NNMRXQ;
438 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
439     "Number of netmap RX queues");
440 
441 #define NNMTXQ_VI 2
442 static int t4_nnmtxq_vi = -NNMTXQ_VI;
443 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
444     "Number of netmap TX queues per VI");
445 
446 #define NNMRXQ_VI 2
447 static int t4_nnmrxq_vi = -NNMRXQ_VI;
448 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
449     "Number of netmap RX queues per VI");
450 #endif
451 
452 /*
453  * Holdoff parameters for ports.
454  */
455 #define TMR_IDX 1
456 int t4_tmr_idx = TMR_IDX;
457 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
458     0, "Holdoff timer index");
459 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);	/* Old name */
460 
461 #define PKTC_IDX (-1)
462 int t4_pktc_idx = PKTC_IDX;
463 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
464     0, "Holdoff packet counter index");
465 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);	/* Old name */
466 
467 /*
468  * Size (# of entries) of each tx and rx queue.
469  */
470 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
471 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
472     "Number of descriptors in each TX queue");
473 
474 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
475 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
476     "Number of descriptors in each RX queue");
477 
478 /*
479  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
480  */
481 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
482 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
483     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
484 
485 /*
486  * Configuration file.  All the _CF names here are special.
487  */
488 #define DEFAULT_CF	"default"
489 #define BUILTIN_CF	"built-in"
490 #define FLASH_CF	"flash"
491 #define UWIRE_CF	"uwire"
492 #define FPGA_CF		"fpga"
493 static char t4_cfg_file[32] = DEFAULT_CF;
494 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
495     sizeof(t4_cfg_file), "Firmware configuration file");
496 
497 /*
498  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
499  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
500  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
501  *            mark or when signalled to do so, 0 to never emit PAUSE.
502  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
503  *                 negotiated settings will override rx_pause/tx_pause.
504  *                 Otherwise rx_pause/tx_pause are applied forcibly.
505  */
506 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
507 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
508     &t4_pause_settings, 0,
509     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
510 
511 /*
512  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
513  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
514  *  0 to disable FEC.
515  */
516 static int t4_fec = -1;
517 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
518     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
519 
520 /*
521  * Link autonegotiation.
522  * -1 to run with the firmware default.
523  *  0 to disable.
524  *  1 to enable.
525  */
526 static int t4_autoneg = -1;
527 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
528     "Link autonegotiation");
529 
530 /*
531  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
532  * encouraged respectively).  '-n' is the same as 'n' except the firmware
533  * version used in the checks is read from the firmware bundled with the driver.
534  */
535 static int t4_fw_install = 1;
536 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
537     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
538 
539 /*
540  * ASIC features that will be used.  Disable the ones you don't want so that the
541  * chip resources aren't wasted on features that will not be used.
542  */
543 static int t4_nbmcaps_allowed = 0;
544 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
545     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
546 
547 static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
548 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
549     &t4_linkcaps_allowed, 0, "Default link capabilities");
550 
551 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
552     FW_CAPS_CONFIG_SWITCH_EGRESS;
553 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
554     &t4_switchcaps_allowed, 0, "Default switch capabilities");
555 
556 #ifdef RATELIMIT
557 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
558 	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
559 #else
560 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
561 	FW_CAPS_CONFIG_NIC_HASHFILTER;
562 #endif
563 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
564     &t4_niccaps_allowed, 0, "Default NIC capabilities");
565 
566 static int t4_toecaps_allowed = -1;
567 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
568     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
569 
570 static int t4_rdmacaps_allowed = -1;
571 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
572     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
573 
574 static int t4_cryptocaps_allowed = -1;
575 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
576     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
577 
578 static int t4_iscsicaps_allowed = -1;
579 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
580     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
581 
582 static int t4_fcoecaps_allowed = 0;
583 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
584     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
585 
586 static int t5_write_combine = 0;
587 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
588     0, "Use WC instead of UC for BAR2");
589 
590 static int t4_num_vis = 1;
591 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
592     "Number of VIs per port");
593 
594 /*
595  * PCIe Relaxed Ordering.
596  * -1: driver should figure out a good value.
597  * 0: disable RO.
598  * 1: enable RO.
599  * 2: leave RO alone.
600  */
601 static int pcie_relaxed_ordering = -1;
602 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
603     &pcie_relaxed_ordering, 0,
604     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
605 
606 static int t4_panic_on_fatal_err = 0;
607 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
608     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
609 
610 static int t4_reset_on_fatal_err = 0;
611 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
612     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
613 
614 static int t4_tx_vm_wr = 0;
615 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
616     "Use VM work requests to transmit packets.");
617 
618 /*
619  * Set to non-zero to enable the attack filter.  A packet that matches any of
620  * these conditions will get dropped on ingress:
621  * 1) IP && source address == destination address.
622  * 2) TCP/IP && source address is not a unicast address.
623  * 3) TCP/IP && destination address is not a unicast address.
624  * 4) IP && source address is loopback (127.x.y.z).
625  * 5) IP && destination address is loopback (127.x.y.z).
626  * 6) IPv6 && source address == destination address.
627  * 7) IPv6 && source address is not a unicast address.
628  * 8) IPv6 && source address is loopback (::1/128).
629  * 9) IPv6 && destination address is loopback (::1/128).
630  * 10) IPv6 && source address is unspecified (::/128).
631  * 11) IPv6 && destination address is unspecified (::/128).
632  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
633  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
634  */
635 static int t4_attack_filter = 0;
636 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
637     &t4_attack_filter, 0, "Drop suspicious traffic");
638 
639 static int t4_drop_ip_fragments = 0;
640 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
641     &t4_drop_ip_fragments, 0, "Drop IP fragments");
642 
643 static int t4_drop_pkts_with_l2_errors = 1;
644 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
645     &t4_drop_pkts_with_l2_errors, 0,
646     "Drop all frames with Layer 2 length or checksum errors");
647 
648 static int t4_drop_pkts_with_l3_errors = 0;
649 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
650     &t4_drop_pkts_with_l3_errors, 0,
651     "Drop all frames with IP version, length, or checksum errors");
652 
653 static int t4_drop_pkts_with_l4_errors = 0;
654 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
655     &t4_drop_pkts_with_l4_errors, 0,
656     "Drop all frames with Layer 4 length, checksum, or other errors");
657 
658 #ifdef TCP_OFFLOAD
659 /*
660  * TOE tunables.
661  */
662 static int t4_cop_managed_offloading = 0;
663 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
664     &t4_cop_managed_offloading, 0,
665     "COP (Connection Offload Policy) controls all TOE offload");
666 #endif
667 
668 #ifdef KERN_TLS
669 /*
670  * This enables KERN_TLS for all adapters if set.
671  */
672 static int t4_kern_tls = 0;
673 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
674     "Enable KERN_TLS mode for all supported adapters");
675 
676 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
677     "cxgbe(4) KERN_TLS parameters");
678 
679 static int t4_tls_inline_keys = 0;
680 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
681     &t4_tls_inline_keys, 0,
682     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
683     "in card memory.");
684 
685 static int t4_tls_combo_wrs = 0;
686 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
687     0, "Attempt to combine TCB field updates with TLS record work requests.");
688 #endif
689 
690 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
691 static int vi_mac_funcs[] = {
692 	FW_VI_FUNC_ETH,
693 	FW_VI_FUNC_OFLD,
694 	FW_VI_FUNC_IWARP,
695 	FW_VI_FUNC_OPENISCSI,
696 	FW_VI_FUNC_OPENFCOE,
697 	FW_VI_FUNC_FOISCSI,
698 	FW_VI_FUNC_FOFCOE,
699 };
700 
701 struct intrs_and_queues {
702 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
703 	uint16_t num_vis;	/* number of VIs for each port */
704 	uint16_t nirq;		/* Total # of vectors */
705 	uint16_t ntxq;		/* # of NIC txq's for each port */
706 	uint16_t nrxq;		/* # of NIC rxq's for each port */
707 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
708 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
709 	uint16_t nnmtxq;	/* # of netmap txq's */
710 	uint16_t nnmrxq;	/* # of netmap rxq's */
711 
712 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
713 	uint16_t ntxq_vi;	/* # of NIC txq's */
714 	uint16_t nrxq_vi;	/* # of NIC rxq's */
715 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
716 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
717 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
718 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
719 };
720 
721 static void setup_memwin(struct adapter *);
722 static void position_memwin(struct adapter *, int, uint32_t);
723 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
724 static int fwmtype_to_hwmtype(int);
725 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
726     uint32_t *);
727 static int fixup_devlog_params(struct adapter *);
728 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
729 static int contact_firmware(struct adapter *);
730 static int partition_resources(struct adapter *);
731 static int get_params__pre_init(struct adapter *);
732 static int set_params__pre_init(struct adapter *);
733 static int get_params__post_init(struct adapter *);
734 static int set_params__post_init(struct adapter *);
735 static void t4_set_desc(struct adapter *);
736 static bool fixed_ifmedia(struct port_info *);
737 static void build_medialist(struct port_info *);
738 static void init_link_config(struct port_info *);
739 static int fixup_link_config(struct port_info *);
740 static int apply_link_config(struct port_info *);
741 static int cxgbe_init_synchronized(struct vi_info *);
742 static int cxgbe_uninit_synchronized(struct vi_info *);
743 static int adapter_full_init(struct adapter *);
744 static void adapter_full_uninit(struct adapter *);
745 static int vi_full_init(struct vi_info *);
746 static void vi_full_uninit(struct vi_info *);
747 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
748 static void quiesce_txq(struct sge_txq *);
749 static void quiesce_wrq(struct sge_wrq *);
750 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
751 static void quiesce_vi(struct vi_info *);
752 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
753     driver_intr_t *, void *, char *);
754 static int t4_free_irq(struct adapter *, struct irq *);
755 static void t4_init_atid_table(struct adapter *);
756 static void t4_free_atid_table(struct adapter *);
757 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
758 static void vi_refresh_stats(struct vi_info *);
759 static void cxgbe_refresh_stats(struct vi_info *);
760 static void cxgbe_tick(void *);
761 static void vi_tick(void *);
762 static void cxgbe_sysctls(struct port_info *);
763 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
764 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
765 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
766 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
767 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
768 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
769 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
770 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
771 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
772 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
773 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
774 static int sysctl_fec(SYSCTL_HANDLER_ARGS);
775 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
776 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
777 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
778 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
779 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
780 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
781 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
782 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
783 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
784 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
785 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
786 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
787 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
788 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
789 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
790 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
791 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
792 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
793 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
794 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
795 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
796 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
797 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
798 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
799 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
800 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
801 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
802 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
803 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
804 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
805 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
806 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
807 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
808 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
809 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
810 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
811 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
812 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
813 #ifdef TCP_OFFLOAD
814 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
815 static int sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS);
816 static int sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS);
817 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
818 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
819 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
820 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
821 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
822 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
823 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
824 #endif
825 static int get_sge_context(struct adapter *, struct t4_sge_context *);
826 static int load_fw(struct adapter *, struct t4_data *);
827 static int load_cfg(struct adapter *, struct t4_data *);
828 static int load_boot(struct adapter *, struct t4_bootrom *);
829 static int load_bootcfg(struct adapter *, struct t4_data *);
830 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
831 static void free_offload_policy(struct t4_offload_policy *);
832 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
833 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
834 static int read_i2c(struct adapter *, struct t4_i2c_data *);
835 static int clear_stats(struct adapter *, u_int);
836 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
837 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
838 #ifdef TCP_OFFLOAD
839 static int toe_capability(struct vi_info *, bool);
840 static void t4_async_event(void *, int);
841 #endif
842 #ifdef KERN_TLS
843 static int ktls_capability(struct adapter *, bool);
844 #endif
845 static int mod_event(module_t, int, void *);
846 static int notify_siblings(device_t, int);
847 static uint64_t vi_get_counter(struct ifnet *, ift_counter);
848 static uint64_t cxgbe_get_counter(struct ifnet *, ift_counter);
849 static void enable_vxlan_rx(struct adapter *);
850 static void reset_adapter(void *, int);
851 
852 struct {
853 	uint16_t device;
854 	char *desc;
855 } t4_pciids[] = {
856 	{0xa000, "Chelsio Terminator 4 FPGA"},
857 	{0x4400, "Chelsio T440-dbg"},
858 	{0x4401, "Chelsio T420-CR"},
859 	{0x4402, "Chelsio T422-CR"},
860 	{0x4403, "Chelsio T440-CR"},
861 	{0x4404, "Chelsio T420-BCH"},
862 	{0x4405, "Chelsio T440-BCH"},
863 	{0x4406, "Chelsio T440-CH"},
864 	{0x4407, "Chelsio T420-SO"},
865 	{0x4408, "Chelsio T420-CX"},
866 	{0x4409, "Chelsio T420-BT"},
867 	{0x440a, "Chelsio T404-BT"},
868 	{0x440e, "Chelsio T440-LP-CR"},
869 }, t5_pciids[] = {
870 	{0xb000, "Chelsio Terminator 5 FPGA"},
871 	{0x5400, "Chelsio T580-dbg"},
872 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
873 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
874 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
875 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
876 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
877 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
878 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
879 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
880 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
881 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
882 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
883 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
884 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
885 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
886 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
887 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
888 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
889 
890 	/* Custom */
891 	{0x5483, "Custom T540-CR"},
892 	{0x5484, "Custom T540-BT"},
893 }, t6_pciids[] = {
894 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
895 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
896 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
897 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
898 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
899 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
900 	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
901 	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
902 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
903 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
904 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
905 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
906 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
907 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
908 	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
909 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
910 
911 	/* Custom */
912 	{0x6480, "Custom T6225-CR"},
913 	{0x6481, "Custom T62100-CR"},
914 	{0x6482, "Custom T6225-CR"},
915 	{0x6483, "Custom T62100-CR"},
916 	{0x6484, "Custom T64100-CR"},
917 	{0x6485, "Custom T6240-SO"},
918 	{0x6486, "Custom T6225-SO-CR"},
919 	{0x6487, "Custom T6225-CR"},
920 };
921 
922 #ifdef TCP_OFFLOAD
923 /*
924  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
925  * be exactly the same for both rxq and ofld_rxq.
926  */
927 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
928 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
929 #endif
930 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
931 
932 static int
933 t4_probe(device_t dev)
934 {
935 	int i;
936 	uint16_t v = pci_get_vendor(dev);
937 	uint16_t d = pci_get_device(dev);
938 	uint8_t f = pci_get_function(dev);
939 
940 	if (v != PCI_VENDOR_ID_CHELSIO)
941 		return (ENXIO);
942 
943 	/* Attach only to PF0 of the FPGA */
944 	if (d == 0xa000 && f != 0)
945 		return (ENXIO);
946 
947 	for (i = 0; i < nitems(t4_pciids); i++) {
948 		if (d == t4_pciids[i].device) {
949 			device_set_desc(dev, t4_pciids[i].desc);
950 			return (BUS_PROBE_DEFAULT);
951 		}
952 	}
953 
954 	return (ENXIO);
955 }
956 
957 static int
958 t5_probe(device_t dev)
959 {
960 	int i;
961 	uint16_t v = pci_get_vendor(dev);
962 	uint16_t d = pci_get_device(dev);
963 	uint8_t f = pci_get_function(dev);
964 
965 	if (v != PCI_VENDOR_ID_CHELSIO)
966 		return (ENXIO);
967 
968 	/* Attach only to PF0 of the FPGA */
969 	if (d == 0xb000 && f != 0)
970 		return (ENXIO);
971 
972 	for (i = 0; i < nitems(t5_pciids); i++) {
973 		if (d == t5_pciids[i].device) {
974 			device_set_desc(dev, t5_pciids[i].desc);
975 			return (BUS_PROBE_DEFAULT);
976 		}
977 	}
978 
979 	return (ENXIO);
980 }
981 
982 static int
983 t6_probe(device_t dev)
984 {
985 	int i;
986 	uint16_t v = pci_get_vendor(dev);
987 	uint16_t d = pci_get_device(dev);
988 
989 	if (v != PCI_VENDOR_ID_CHELSIO)
990 		return (ENXIO);
991 
992 	for (i = 0; i < nitems(t6_pciids); i++) {
993 		if (d == t6_pciids[i].device) {
994 			device_set_desc(dev, t6_pciids[i].desc);
995 			return (BUS_PROBE_DEFAULT);
996 		}
997 	}
998 
999 	return (ENXIO);
1000 }
1001 
1002 static void
1003 t5_attribute_workaround(device_t dev)
1004 {
1005 	device_t root_port;
1006 	uint32_t v;
1007 
1008 	/*
1009 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1010 	 * Ordering attributes when replying to a TLP from a Root
1011 	 * Port.  As a workaround, find the parent Root Port and
1012 	 * disable No Snoop and Relaxed Ordering.  Note that this
1013 	 * affects all devices under this root port.
1014 	 */
1015 	root_port = pci_find_pcie_root_port(dev);
1016 	if (root_port == NULL) {
1017 		device_printf(dev, "Unable to find parent root port\n");
1018 		return;
1019 	}
1020 
1021 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1022 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1023 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1024 	    0)
1025 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1026 		    device_get_nameunit(root_port));
1027 }
1028 
1029 static const struct devnames devnames[] = {
1030 	{
1031 		.nexus_name = "t4nex",
1032 		.ifnet_name = "cxgbe",
1033 		.vi_ifnet_name = "vcxgbe",
1034 		.pf03_drv_name = "t4iov",
1035 		.vf_nexus_name = "t4vf",
1036 		.vf_ifnet_name = "cxgbev"
1037 	}, {
1038 		.nexus_name = "t5nex",
1039 		.ifnet_name = "cxl",
1040 		.vi_ifnet_name = "vcxl",
1041 		.pf03_drv_name = "t5iov",
1042 		.vf_nexus_name = "t5vf",
1043 		.vf_ifnet_name = "cxlv"
1044 	}, {
1045 		.nexus_name = "t6nex",
1046 		.ifnet_name = "cc",
1047 		.vi_ifnet_name = "vcc",
1048 		.pf03_drv_name = "t6iov",
1049 		.vf_nexus_name = "t6vf",
1050 		.vf_ifnet_name = "ccv"
1051 	}
1052 };
1053 
1054 void
1055 t4_init_devnames(struct adapter *sc)
1056 {
1057 	int id;
1058 
1059 	id = chip_id(sc);
1060 	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1061 		sc->names = &devnames[id - CHELSIO_T4];
1062 	else {
1063 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1064 		sc->names = NULL;
1065 	}
1066 }
1067 
1068 static int
1069 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1070 {
1071 	const char *parent, *name;
1072 	long value;
1073 	int line, unit;
1074 
1075 	line = 0;
1076 	parent = device_get_nameunit(sc->dev);
1077 	name = sc->names->ifnet_name;
1078 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1079 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1080 		    value == pi->port_id)
1081 			return (unit);
1082 	}
1083 	return (-1);
1084 }
1085 
1086 static int
1087 t4_attach(device_t dev)
1088 {
1089 	struct adapter *sc;
1090 	int rc = 0, i, j, rqidx, tqidx, nports;
1091 	struct make_dev_args mda;
1092 	struct intrs_and_queues iaq;
1093 	struct sge *s;
1094 	uint32_t *buf;
1095 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1096 	int ofld_tqidx;
1097 #endif
1098 #ifdef TCP_OFFLOAD
1099 	int ofld_rqidx;
1100 #endif
1101 #ifdef DEV_NETMAP
1102 	int nm_rqidx, nm_tqidx;
1103 #endif
1104 	int num_vis;
1105 
1106 	sc = device_get_softc(dev);
1107 	sc->dev = dev;
1108 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1109 
1110 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1111 		t5_attribute_workaround(dev);
1112 	pci_enable_busmaster(dev);
1113 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1114 		uint32_t v;
1115 
1116 		pci_set_max_read_req(dev, 4096);
1117 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1118 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1119 		if (pcie_relaxed_ordering == 0 &&
1120 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1121 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1122 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1123 		} else if (pcie_relaxed_ordering == 1 &&
1124 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1125 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1126 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1127 		}
1128 	}
1129 
1130 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1131 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1132 	sc->traceq = -1;
1133 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1134 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1135 	    device_get_nameunit(dev));
1136 
1137 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1138 	    device_get_nameunit(dev));
1139 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1140 	t4_add_adapter(sc);
1141 
1142 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1143 	TAILQ_INIT(&sc->sfl);
1144 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1145 
1146 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1147 
1148 	sc->policy = NULL;
1149 	rw_init(&sc->policy_lock, "connection offload policy");
1150 
1151 	callout_init(&sc->ktls_tick, 1);
1152 
1153 #ifdef TCP_OFFLOAD
1154 	TASK_INIT(&sc->async_event_task, 0, t4_async_event, sc);
1155 #endif
1156 
1157 	refcount_init(&sc->vxlan_refcount, 0);
1158 
1159 	TASK_INIT(&sc->reset_task, 0, reset_adapter, sc);
1160 
1161 	sc->ctrlq_oid = SYSCTL_ADD_NODE(device_get_sysctl_ctx(sc->dev),
1162 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1163 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1164 	sc->fwq_oid = SYSCTL_ADD_NODE(device_get_sysctl_ctx(sc->dev),
1165 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1166 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1167 
1168 	rc = t4_map_bars_0_and_4(sc);
1169 	if (rc != 0)
1170 		goto done; /* error message displayed already */
1171 
1172 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1173 
1174 	/* Prepare the adapter for operation. */
1175 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1176 	rc = -t4_prep_adapter(sc, buf);
1177 	free(buf, M_CXGBE);
1178 	if (rc != 0) {
1179 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1180 		goto done;
1181 	}
1182 
1183 	/*
1184 	 * This is the real PF# to which we're attaching.  Works from within PCI
1185 	 * passthrough environments too, where pci_get_function() could return a
1186 	 * different PF# depending on the passthrough configuration.  We need to
1187 	 * use the real PF# in all our communication with the firmware.
1188 	 */
1189 	j = t4_read_reg(sc, A_PL_WHOAMI);
1190 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1191 	sc->mbox = sc->pf;
1192 
1193 	t4_init_devnames(sc);
1194 	if (sc->names == NULL) {
1195 		rc = ENOTSUP;
1196 		goto done; /* error message displayed already */
1197 	}
1198 
1199 	/*
1200 	 * Do this really early, with the memory windows set up even before the
1201 	 * character device.  The userland tool's register i/o and mem read
1202 	 * will work even in "recovery mode".
1203 	 */
1204 	setup_memwin(sc);
1205 	if (t4_init_devlog_params(sc, 0) == 0)
1206 		fixup_devlog_params(sc);
1207 	make_dev_args_init(&mda);
1208 	mda.mda_devsw = &t4_cdevsw;
1209 	mda.mda_uid = UID_ROOT;
1210 	mda.mda_gid = GID_WHEEL;
1211 	mda.mda_mode = 0600;
1212 	mda.mda_si_drv1 = sc;
1213 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1214 	if (rc != 0)
1215 		device_printf(dev, "failed to create nexus char device: %d.\n",
1216 		    rc);
1217 
1218 	/* Go no further if recovery mode has been requested. */
1219 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1220 		device_printf(dev, "recovery mode.\n");
1221 		goto done;
1222 	}
1223 
1224 #if defined(__i386__)
1225 	if ((cpu_feature & CPUID_CX8) == 0) {
1226 		device_printf(dev, "64 bit atomics not available.\n");
1227 		rc = ENOTSUP;
1228 		goto done;
1229 	}
1230 #endif
1231 
1232 	/* Contact the firmware and try to become the master driver. */
1233 	rc = contact_firmware(sc);
1234 	if (rc != 0)
1235 		goto done; /* error message displayed already */
1236 	MPASS(sc->flags & FW_OK);
1237 
1238 	rc = get_params__pre_init(sc);
1239 	if (rc != 0)
1240 		goto done; /* error message displayed already */
1241 
1242 	if (sc->flags & MASTER_PF) {
1243 		rc = partition_resources(sc);
1244 		if (rc != 0)
1245 			goto done; /* error message displayed already */
1246 		t4_intr_clear(sc);
1247 	}
1248 
1249 	rc = get_params__post_init(sc);
1250 	if (rc != 0)
1251 		goto done; /* error message displayed already */
1252 
1253 	rc = set_params__post_init(sc);
1254 	if (rc != 0)
1255 		goto done; /* error message displayed already */
1256 
1257 	rc = t4_map_bar_2(sc);
1258 	if (rc != 0)
1259 		goto done; /* error message displayed already */
1260 
1261 	rc = t4_create_dma_tag(sc);
1262 	if (rc != 0)
1263 		goto done; /* error message displayed already */
1264 
1265 	/*
1266 	 * First pass over all the ports - allocate VIs and initialize some
1267 	 * basic parameters like mac address, port type, etc.
1268 	 */
1269 	for_each_port(sc, i) {
1270 		struct port_info *pi;
1271 
1272 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1273 		sc->port[i] = pi;
1274 
1275 		/* These must be set before t4_port_init */
1276 		pi->adapter = sc;
1277 		pi->port_id = i;
1278 		/*
1279 		 * XXX: vi[0] is special so we can't delay this allocation until
1280 		 * pi->nvi's final value is known.
1281 		 */
1282 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1283 		    M_ZERO | M_WAITOK);
1284 
1285 		/*
1286 		 * Allocate the "main" VI and initialize parameters
1287 		 * like mac addr.
1288 		 */
1289 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1290 		if (rc != 0) {
1291 			device_printf(dev, "unable to initialize port %d: %d\n",
1292 			    i, rc);
1293 			free(pi->vi, M_CXGBE);
1294 			free(pi, M_CXGBE);
1295 			sc->port[i] = NULL;
1296 			goto done;
1297 		}
1298 
1299 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1300 		    device_get_nameunit(dev), i);
1301 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1302 		sc->chan_map[pi->tx_chan] = i;
1303 
1304 		/*
1305 		 * The MPS counter for FCS errors doesn't work correctly on the
1306 		 * T6 so we use the MAC counter here.  Which MAC is in use
1307 		 * depends on the link settings which will be known when the
1308 		 * link comes up.
1309 		 */
1310 		if (is_t6(sc)) {
1311 			pi->fcs_reg = -1;
1312 		} else if (is_t4(sc)) {
1313 			pi->fcs_reg = PORT_REG(pi->tx_chan,
1314 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1315 		} else {
1316 			pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
1317 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1318 		}
1319 		pi->fcs_base = 0;
1320 
1321 		/* All VIs on this port share this media. */
1322 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1323 		    cxgbe_media_status);
1324 
1325 		PORT_LOCK(pi);
1326 		init_link_config(pi);
1327 		fixup_link_config(pi);
1328 		build_medialist(pi);
1329 		if (fixed_ifmedia(pi))
1330 			pi->flags |= FIXED_IFMEDIA;
1331 		PORT_UNLOCK(pi);
1332 
1333 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1334 		    t4_ifnet_unit(sc, pi));
1335 		if (pi->dev == NULL) {
1336 			device_printf(dev,
1337 			    "failed to add device for port %d.\n", i);
1338 			rc = ENXIO;
1339 			goto done;
1340 		}
1341 		pi->vi[0].dev = pi->dev;
1342 		device_set_softc(pi->dev, pi);
1343 	}
1344 
1345 	/*
1346 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1347 	 */
1348 	nports = sc->params.nports;
1349 	rc = cfg_itype_and_nqueues(sc, &iaq);
1350 	if (rc != 0)
1351 		goto done; /* error message displayed already */
1352 
1353 	num_vis = iaq.num_vis;
1354 	sc->intr_type = iaq.intr_type;
1355 	sc->intr_count = iaq.nirq;
1356 
1357 	s = &sc->sge;
1358 	s->nrxq = nports * iaq.nrxq;
1359 	s->ntxq = nports * iaq.ntxq;
1360 	if (num_vis > 1) {
1361 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1362 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1363 	}
1364 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1365 	s->neq += nports;		/* ctrl queues: 1 per port */
1366 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1367 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1368 	if (is_offload(sc) || is_ethoffload(sc)) {
1369 		s->nofldtxq = nports * iaq.nofldtxq;
1370 		if (num_vis > 1)
1371 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1372 		s->neq += s->nofldtxq;
1373 
1374 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1375 		    M_CXGBE, M_ZERO | M_WAITOK);
1376 	}
1377 #endif
1378 #ifdef TCP_OFFLOAD
1379 	if (is_offload(sc)) {
1380 		s->nofldrxq = nports * iaq.nofldrxq;
1381 		if (num_vis > 1)
1382 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1383 		s->neq += s->nofldrxq;	/* free list */
1384 		s->niq += s->nofldrxq;
1385 
1386 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1387 		    M_CXGBE, M_ZERO | M_WAITOK);
1388 	}
1389 #endif
1390 #ifdef DEV_NETMAP
1391 	s->nnmrxq = 0;
1392 	s->nnmtxq = 0;
1393 	if (t4_native_netmap & NN_MAIN_VI) {
1394 		s->nnmrxq += nports * iaq.nnmrxq;
1395 		s->nnmtxq += nports * iaq.nnmtxq;
1396 	}
1397 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1398 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1399 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1400 	}
1401 	s->neq += s->nnmtxq + s->nnmrxq;
1402 	s->niq += s->nnmrxq;
1403 
1404 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1405 	    M_CXGBE, M_ZERO | M_WAITOK);
1406 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1407 	    M_CXGBE, M_ZERO | M_WAITOK);
1408 #endif
1409 	MPASS(s->niq <= s->iqmap_sz);
1410 	MPASS(s->neq <= s->eqmap_sz);
1411 
1412 	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1413 	    M_ZERO | M_WAITOK);
1414 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1415 	    M_ZERO | M_WAITOK);
1416 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1417 	    M_ZERO | M_WAITOK);
1418 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1419 	    M_ZERO | M_WAITOK);
1420 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1421 	    M_ZERO | M_WAITOK);
1422 
1423 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1424 	    M_ZERO | M_WAITOK);
1425 
1426 	t4_init_l2t(sc, M_WAITOK);
1427 	t4_init_smt(sc, M_WAITOK);
1428 	t4_init_tx_sched(sc);
1429 	t4_init_atid_table(sc);
1430 #ifdef RATELIMIT
1431 	t4_init_etid_table(sc);
1432 #endif
1433 #ifdef INET6
1434 	t4_init_clip_table(sc);
1435 #endif
1436 	if (sc->vres.key.size != 0)
1437 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1438 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1439 
1440 	/*
1441 	 * Second pass over the ports.  This time we know the number of rx and
1442 	 * tx queues that each port should get.
1443 	 */
1444 	rqidx = tqidx = 0;
1445 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1446 	ofld_tqidx = 0;
1447 #endif
1448 #ifdef TCP_OFFLOAD
1449 	ofld_rqidx = 0;
1450 #endif
1451 #ifdef DEV_NETMAP
1452 	nm_rqidx = nm_tqidx = 0;
1453 #endif
1454 	for_each_port(sc, i) {
1455 		struct port_info *pi = sc->port[i];
1456 		struct vi_info *vi;
1457 
1458 		if (pi == NULL)
1459 			continue;
1460 
1461 		pi->nvi = num_vis;
1462 		for_each_vi(pi, j, vi) {
1463 			vi->pi = pi;
1464 			vi->adapter = sc;
1465 			vi->first_intr = -1;
1466 			vi->qsize_rxq = t4_qsize_rxq;
1467 			vi->qsize_txq = t4_qsize_txq;
1468 
1469 			vi->first_rxq = rqidx;
1470 			vi->first_txq = tqidx;
1471 			vi->tmr_idx = t4_tmr_idx;
1472 			vi->pktc_idx = t4_pktc_idx;
1473 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1474 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1475 
1476 			rqidx += vi->nrxq;
1477 			tqidx += vi->ntxq;
1478 
1479 			if (j == 0 && vi->ntxq > 1)
1480 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1481 			else
1482 				vi->rsrv_noflowq = 0;
1483 
1484 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1485 			vi->first_ofld_txq = ofld_tqidx;
1486 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1487 			ofld_tqidx += vi->nofldtxq;
1488 #endif
1489 #ifdef TCP_OFFLOAD
1490 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1491 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1492 			vi->first_ofld_rxq = ofld_rqidx;
1493 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1494 
1495 			ofld_rqidx += vi->nofldrxq;
1496 #endif
1497 #ifdef DEV_NETMAP
1498 			vi->first_nm_rxq = nm_rqidx;
1499 			vi->first_nm_txq = nm_tqidx;
1500 			if (j == 0) {
1501 				vi->nnmrxq = iaq.nnmrxq;
1502 				vi->nnmtxq = iaq.nnmtxq;
1503 			} else {
1504 				vi->nnmrxq = iaq.nnmrxq_vi;
1505 				vi->nnmtxq = iaq.nnmtxq_vi;
1506 			}
1507 			nm_rqidx += vi->nnmrxq;
1508 			nm_tqidx += vi->nnmtxq;
1509 #endif
1510 		}
1511 	}
1512 
1513 	rc = t4_setup_intr_handlers(sc);
1514 	if (rc != 0) {
1515 		device_printf(dev,
1516 		    "failed to setup interrupt handlers: %d\n", rc);
1517 		goto done;
1518 	}
1519 
1520 	rc = bus_generic_probe(dev);
1521 	if (rc != 0) {
1522 		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1523 		goto done;
1524 	}
1525 
1526 	/*
1527 	 * Ensure thread-safe mailbox access (in debug builds).
1528 	 *
1529 	 * So far this was the only thread accessing the mailbox but various
1530 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1531 	 * will access the mailbox from different threads.
1532 	 */
1533 	sc->flags |= CHK_MBOX_ACCESS;
1534 
1535 	rc = bus_generic_attach(dev);
1536 	if (rc != 0) {
1537 		device_printf(dev,
1538 		    "failed to attach all child ports: %d\n", rc);
1539 		goto done;
1540 	}
1541 
1542 	device_printf(dev,
1543 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1544 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1545 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1546 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1547 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1548 
1549 	t4_set_desc(sc);
1550 
1551 	notify_siblings(dev, 0);
1552 
1553 done:
1554 	if (rc != 0 && sc->cdev) {
1555 		/* cdev was created and so cxgbetool works; recover that way. */
1556 		device_printf(dev,
1557 		    "error during attach, adapter is now in recovery mode.\n");
1558 		rc = 0;
1559 	}
1560 
1561 	if (rc != 0)
1562 		t4_detach_common(dev);
1563 	else
1564 		t4_sysctls(sc);
1565 
1566 	return (rc);
1567 }
1568 
1569 static int
1570 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1571 {
1572 	struct adapter *sc;
1573 	struct port_info *pi;
1574 	int i;
1575 
1576 	sc = device_get_softc(bus);
1577 	for_each_port(sc, i) {
1578 		pi = sc->port[i];
1579 		if (pi != NULL && pi->dev == dev) {
1580 			sbuf_printf(sb, "port=%d", pi->port_id);
1581 			break;
1582 		}
1583 	}
1584 	return (0);
1585 }
1586 
1587 static int
1588 t4_ready(device_t dev)
1589 {
1590 	struct adapter *sc;
1591 
1592 	sc = device_get_softc(dev);
1593 	if (sc->flags & FW_OK)
1594 		return (0);
1595 	return (ENXIO);
1596 }
1597 
1598 static int
1599 t4_read_port_device(device_t dev, int port, device_t *child)
1600 {
1601 	struct adapter *sc;
1602 	struct port_info *pi;
1603 
1604 	sc = device_get_softc(dev);
1605 	if (port < 0 || port >= MAX_NPORTS)
1606 		return (EINVAL);
1607 	pi = sc->port[port];
1608 	if (pi == NULL || pi->dev == NULL)
1609 		return (ENXIO);
1610 	*child = pi->dev;
1611 	return (0);
1612 }
1613 
1614 static int
1615 notify_siblings(device_t dev, int detaching)
1616 {
1617 	device_t sibling;
1618 	int error, i;
1619 
1620 	error = 0;
1621 	for (i = 0; i < PCI_FUNCMAX; i++) {
1622 		if (i == pci_get_function(dev))
1623 			continue;
1624 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1625 		    pci_get_slot(dev), i);
1626 		if (sibling == NULL || !device_is_attached(sibling))
1627 			continue;
1628 		if (detaching)
1629 			error = T4_DETACH_CHILD(sibling);
1630 		else
1631 			(void)T4_ATTACH_CHILD(sibling);
1632 		if (error)
1633 			break;
1634 	}
1635 	return (error);
1636 }
1637 
1638 /*
1639  * Idempotent
1640  */
1641 static int
1642 t4_detach(device_t dev)
1643 {
1644 	struct adapter *sc;
1645 	int rc;
1646 
1647 	sc = device_get_softc(dev);
1648 
1649 	rc = notify_siblings(dev, 1);
1650 	if (rc) {
1651 		device_printf(dev,
1652 		    "failed to detach sibling devices: %d\n", rc);
1653 		return (rc);
1654 	}
1655 
1656 	return (t4_detach_common(dev));
1657 }
1658 
1659 int
1660 t4_detach_common(device_t dev)
1661 {
1662 	struct adapter *sc;
1663 	struct port_info *pi;
1664 	int i, rc;
1665 
1666 	sc = device_get_softc(dev);
1667 
1668 	if (sc->cdev) {
1669 		destroy_dev(sc->cdev);
1670 		sc->cdev = NULL;
1671 	}
1672 
1673 	sx_xlock(&t4_list_lock);
1674 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1675 	sx_xunlock(&t4_list_lock);
1676 
1677 	sc->flags &= ~CHK_MBOX_ACCESS;
1678 	if (sc->flags & FULL_INIT_DONE) {
1679 		if (!(sc->flags & IS_VF))
1680 			t4_intr_disable(sc);
1681 	}
1682 
1683 	if (device_is_attached(dev)) {
1684 		rc = bus_generic_detach(dev);
1685 		if (rc) {
1686 			device_printf(dev,
1687 			    "failed to detach child devices: %d\n", rc);
1688 			return (rc);
1689 		}
1690 	}
1691 
1692 #ifdef TCP_OFFLOAD
1693 	taskqueue_drain(taskqueue_thread, &sc->async_event_task);
1694 #endif
1695 
1696 	for (i = 0; i < sc->intr_count; i++)
1697 		t4_free_irq(sc, &sc->irq[i]);
1698 
1699 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1700 		t4_free_tx_sched(sc);
1701 
1702 	for (i = 0; i < MAX_NPORTS; i++) {
1703 		pi = sc->port[i];
1704 		if (pi) {
1705 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1706 			if (pi->dev)
1707 				device_delete_child(dev, pi->dev);
1708 
1709 			mtx_destroy(&pi->pi_lock);
1710 			free(pi->vi, M_CXGBE);
1711 			free(pi, M_CXGBE);
1712 		}
1713 	}
1714 
1715 	device_delete_children(dev);
1716 	adapter_full_uninit(sc);
1717 
1718 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1719 		t4_fw_bye(sc, sc->mbox);
1720 
1721 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1722 		pci_release_msi(dev);
1723 
1724 	if (sc->regs_res)
1725 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1726 		    sc->regs_res);
1727 
1728 	if (sc->udbs_res)
1729 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1730 		    sc->udbs_res);
1731 
1732 	if (sc->msix_res)
1733 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1734 		    sc->msix_res);
1735 
1736 	if (sc->l2t)
1737 		t4_free_l2t(sc->l2t);
1738 	if (sc->smt)
1739 		t4_free_smt(sc->smt);
1740 	t4_free_atid_table(sc);
1741 #ifdef RATELIMIT
1742 	t4_free_etid_table(sc);
1743 #endif
1744 	if (sc->key_map)
1745 		vmem_destroy(sc->key_map);
1746 #ifdef INET6
1747 	t4_destroy_clip_table(sc);
1748 #endif
1749 
1750 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1751 	free(sc->sge.ofld_txq, M_CXGBE);
1752 #endif
1753 #ifdef TCP_OFFLOAD
1754 	free(sc->sge.ofld_rxq, M_CXGBE);
1755 #endif
1756 #ifdef DEV_NETMAP
1757 	free(sc->sge.nm_rxq, M_CXGBE);
1758 	free(sc->sge.nm_txq, M_CXGBE);
1759 #endif
1760 	free(sc->irq, M_CXGBE);
1761 	free(sc->sge.rxq, M_CXGBE);
1762 	free(sc->sge.txq, M_CXGBE);
1763 	free(sc->sge.ctrlq, M_CXGBE);
1764 	free(sc->sge.iqmap, M_CXGBE);
1765 	free(sc->sge.eqmap, M_CXGBE);
1766 	free(sc->tids.ftid_tab, M_CXGBE);
1767 	free(sc->tids.hpftid_tab, M_CXGBE);
1768 	free_hftid_hash(&sc->tids);
1769 	free(sc->tids.tid_tab, M_CXGBE);
1770 	free(sc->tt.tls_rx_ports, M_CXGBE);
1771 	t4_destroy_dma_tag(sc);
1772 
1773 	callout_drain(&sc->ktls_tick);
1774 	callout_drain(&sc->sfl_callout);
1775 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1776 		mtx_destroy(&sc->tids.ftid_lock);
1777 		cv_destroy(&sc->tids.ftid_cv);
1778 	}
1779 	if (mtx_initialized(&sc->tids.atid_lock))
1780 		mtx_destroy(&sc->tids.atid_lock);
1781 	if (mtx_initialized(&sc->ifp_lock))
1782 		mtx_destroy(&sc->ifp_lock);
1783 
1784 	if (rw_initialized(&sc->policy_lock)) {
1785 		rw_destroy(&sc->policy_lock);
1786 #ifdef TCP_OFFLOAD
1787 		if (sc->policy != NULL)
1788 			free_offload_policy(sc->policy);
1789 #endif
1790 	}
1791 
1792 	for (i = 0; i < NUM_MEMWIN; i++) {
1793 		struct memwin *mw = &sc->memwin[i];
1794 
1795 		if (rw_initialized(&mw->mw_lock))
1796 			rw_destroy(&mw->mw_lock);
1797 	}
1798 
1799 	mtx_destroy(&sc->sfl_lock);
1800 	mtx_destroy(&sc->reg_lock);
1801 	mtx_destroy(&sc->sc_lock);
1802 
1803 	bzero(sc, sizeof(*sc));
1804 
1805 	return (0);
1806 }
1807 
1808 static inline bool
1809 ok_to_reset(struct adapter *sc)
1810 {
1811 	struct tid_info *t = &sc->tids;
1812 	struct port_info *pi;
1813 	struct vi_info *vi;
1814 	int i, j;
1815 	const int caps = IFCAP_TOE | IFCAP_TXTLS | IFCAP_NETMAP | IFCAP_TXRTLMT;
1816 
1817 	ASSERT_SYNCHRONIZED_OP(sc);
1818 	MPASS(!(sc->flags & IS_VF));
1819 
1820 	for_each_port(sc, i) {
1821 		pi = sc->port[i];
1822 		for_each_vi(pi, j, vi) {
1823 			if (vi->ifp->if_capenable & caps)
1824 				return (false);
1825 		}
1826 	}
1827 
1828 	if (atomic_load_int(&t->tids_in_use) > 0)
1829 		return (false);
1830 	if (atomic_load_int(&t->stids_in_use) > 0)
1831 		return (false);
1832 	if (atomic_load_int(&t->atids_in_use) > 0)
1833 		return (false);
1834 	if (atomic_load_int(&t->ftids_in_use) > 0)
1835 		return (false);
1836 	if (atomic_load_int(&t->hpftids_in_use) > 0)
1837 		return (false);
1838 	if (atomic_load_int(&t->etids_in_use) > 0)
1839 		return (false);
1840 
1841 	return (true);
1842 }
1843 
1844 static int
1845 t4_suspend(device_t dev)
1846 {
1847 	struct adapter *sc = device_get_softc(dev);
1848 	struct port_info *pi;
1849 	struct vi_info *vi;
1850 	struct ifnet *ifp;
1851 	struct sge_rxq *rxq;
1852 	struct sge_txq *txq;
1853 	struct sge_wrq *wrq;
1854 #ifdef TCP_OFFLOAD
1855 	struct sge_ofld_rxq *ofld_rxq;
1856 #endif
1857 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1858 	struct sge_ofld_txq *ofld_txq;
1859 #endif
1860 	int rc, i, j, k;
1861 
1862 	CH_ALERT(sc, "suspend requested\n");
1863 
1864 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4sus");
1865 	if (rc != 0)
1866 		return (ENXIO);
1867 
1868 	/* XXX: Can the kernel call suspend repeatedly without resume? */
1869 	MPASS(!hw_off_limits(sc));
1870 
1871 	if (!ok_to_reset(sc)) {
1872 		/* XXX: should list what resource is preventing suspend. */
1873 		CH_ERR(sc, "not safe to suspend.\n");
1874 		rc = EBUSY;
1875 		goto done;
1876 	}
1877 
1878 	/* No more DMA or interrupts. */
1879 	t4_shutdown_adapter(sc);
1880 
1881 	/* Quiesce all activity. */
1882 	for_each_port(sc, i) {
1883 		pi = sc->port[i];
1884 		pi->vxlan_tcam_entry = false;
1885 
1886 		PORT_LOCK(pi);
1887 		if (pi->up_vis > 0) {
1888 			/*
1889 			 * t4_shutdown_adapter has already shut down all the
1890 			 * PHYs but it also disables interrupts and DMA so there
1891 			 * won't be a link interrupt.  So we update the state
1892 			 * manually and inform the kernel.
1893 			 */
1894 			pi->link_cfg.link_ok = false;
1895 			t4_os_link_changed(pi);
1896 		}
1897 		PORT_UNLOCK(pi);
1898 
1899 		for_each_vi(pi, j, vi) {
1900 			vi->xact_addr_filt = -1;
1901 			if (!(vi->flags & VI_INIT_DONE))
1902 				continue;
1903 
1904 			ifp = vi->ifp;
1905 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1906 				mtx_lock(&vi->tick_mtx);
1907 				vi->flags |= VI_SKIP_STATS;
1908 				callout_stop(&vi->tick);
1909 				mtx_unlock(&vi->tick_mtx);
1910 				callout_drain(&vi->tick);
1911 			}
1912 
1913 			/*
1914 			 * Note that the HW is not available.
1915 			 */
1916 			for_each_txq(vi, k, txq) {
1917 				TXQ_LOCK(txq);
1918 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
1919 				TXQ_UNLOCK(txq);
1920 			}
1921 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1922 			for_each_ofld_txq(vi, k, ofld_txq) {
1923 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
1924 			}
1925 #endif
1926 			for_each_rxq(vi, k, rxq) {
1927 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1928 			}
1929 #if defined(TCP_OFFLOAD)
1930 			for_each_ofld_rxq(vi, k, ofld_rxq) {
1931 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1932 			}
1933 #endif
1934 
1935 			quiesce_vi(vi);
1936 		}
1937 
1938 		if (sc->flags & FULL_INIT_DONE) {
1939 			/* Control queue */
1940 			wrq = &sc->sge.ctrlq[i];
1941 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
1942 			quiesce_wrq(wrq);
1943 		}
1944 	}
1945 	if (sc->flags & FULL_INIT_DONE) {
1946 		/* Firmware event queue */
1947 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
1948 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
1949 	}
1950 
1951 	/* Mark the adapter totally off limits. */
1952 	mtx_lock(&sc->reg_lock);
1953 	sc->flags |= HW_OFF_LIMITS;
1954 	sc->flags &= ~(FW_OK | MASTER_PF);
1955 	sc->reset_thread = NULL;
1956 	mtx_unlock(&sc->reg_lock);
1957 
1958 	sc->num_resets++;
1959 	CH_ALERT(sc, "suspend completed.\n");
1960 done:
1961 	end_synchronized_op(sc, 0);
1962 	return (rc);
1963 }
1964 
1965 struct adapter_pre_reset_state {
1966 	u_int flags;
1967 	uint16_t nbmcaps;
1968 	uint16_t linkcaps;
1969 	uint16_t switchcaps;
1970 	uint16_t niccaps;
1971 	uint16_t toecaps;
1972 	uint16_t rdmacaps;
1973 	uint16_t cryptocaps;
1974 	uint16_t iscsicaps;
1975 	uint16_t fcoecaps;
1976 
1977 	u_int cfcsum;
1978 	char cfg_file[32];
1979 
1980 	struct adapter_params params;
1981 	struct t4_virt_res vres;
1982 	struct tid_info tids;
1983 	struct sge sge;
1984 
1985 	int rawf_base;
1986 	int nrawf;
1987 
1988 };
1989 
1990 static void
1991 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
1992 {
1993 
1994 	ASSERT_SYNCHRONIZED_OP(sc);
1995 
1996 	o->flags = sc->flags;
1997 
1998 	o->nbmcaps =  sc->nbmcaps;
1999 	o->linkcaps = sc->linkcaps;
2000 	o->switchcaps = sc->switchcaps;
2001 	o->niccaps = sc->niccaps;
2002 	o->toecaps = sc->toecaps;
2003 	o->rdmacaps = sc->rdmacaps;
2004 	o->cryptocaps = sc->cryptocaps;
2005 	o->iscsicaps = sc->iscsicaps;
2006 	o->fcoecaps = sc->fcoecaps;
2007 
2008 	o->cfcsum = sc->cfcsum;
2009 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2010 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2011 
2012 	o->params = sc->params;
2013 	o->vres = sc->vres;
2014 	o->tids = sc->tids;
2015 	o->sge = sc->sge;
2016 
2017 	o->rawf_base = sc->rawf_base;
2018 	o->nrawf = sc->nrawf;
2019 }
2020 
2021 static int
2022 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2023 {
2024 	int rc = 0;
2025 
2026 	ASSERT_SYNCHRONIZED_OP(sc);
2027 
2028 	/* Capabilities */
2029 #define COMPARE_CAPS(c) do { \
2030 	if (o->c##caps != sc->c##caps) { \
2031 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2032 		    sc->c##caps); \
2033 		rc = EINVAL; \
2034 	} \
2035 } while (0)
2036 	COMPARE_CAPS(nbm);
2037 	COMPARE_CAPS(link);
2038 	COMPARE_CAPS(switch);
2039 	COMPARE_CAPS(nic);
2040 	COMPARE_CAPS(toe);
2041 	COMPARE_CAPS(rdma);
2042 	COMPARE_CAPS(crypto);
2043 	COMPARE_CAPS(iscsi);
2044 	COMPARE_CAPS(fcoe);
2045 #undef COMPARE_CAPS
2046 
2047 	/* Firmware config file */
2048 	if (o->cfcsum != sc->cfcsum) {
2049 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2050 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2051 		rc = EINVAL;
2052 	}
2053 
2054 #define COMPARE_PARAM(p, name) do { \
2055 	if (o->p != sc->p) { \
2056 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2057 		rc = EINVAL; \
2058 	} \
2059 } while (0)
2060 	COMPARE_PARAM(sge.iq_start, iq_start);
2061 	COMPARE_PARAM(sge.eq_start, eq_start);
2062 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2063 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2064 	COMPARE_PARAM(tids.nftids, nftids);
2065 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2066 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2067 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2068 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2069 	COMPARE_PARAM(tids.tid_base, tid_base);
2070 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2071 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2072 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2073 	COMPARE_PARAM(rawf_base, rawf_base);
2074 	COMPARE_PARAM(nrawf, nrawf);
2075 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2076 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2077 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2078 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2079 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2080 	COMPARE_PARAM(tids.ntids, ntids);
2081 	COMPARE_PARAM(tids.etid_base, etid_base);
2082 	COMPARE_PARAM(tids.etid_end, etid_end);
2083 	COMPARE_PARAM(tids.netids, netids);
2084 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2085 	COMPARE_PARAM(params.ethoffload, ethoffload);
2086 	COMPARE_PARAM(tids.natids, natids);
2087 	COMPARE_PARAM(tids.stid_base, stid_base);
2088 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2089 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2090 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2091 	COMPARE_PARAM(vres.stag.start, stag_start);
2092 	COMPARE_PARAM(vres.stag.size, stag_size);
2093 	COMPARE_PARAM(vres.rq.start, rq_start);
2094 	COMPARE_PARAM(vres.rq.size, rq_size);
2095 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2096 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2097 	COMPARE_PARAM(vres.qp.start, qp_start);
2098 	COMPARE_PARAM(vres.qp.size, qp_size);
2099 	COMPARE_PARAM(vres.cq.start, cq_start);
2100 	COMPARE_PARAM(vres.cq.size, cq_size);
2101 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2102 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2103 	COMPARE_PARAM(vres.srq.start, srq_start);
2104 	COMPARE_PARAM(vres.srq.size, srq_size);
2105 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2106 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2107 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2108 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2109 	COMPARE_PARAM(vres.key.start, key_start);
2110 	COMPARE_PARAM(vres.key.size, key_size);
2111 #undef COMPARE_PARAM
2112 
2113 	return (rc);
2114 }
2115 
2116 static int
2117 t4_resume(device_t dev)
2118 {
2119 	struct adapter *sc = device_get_softc(dev);
2120 	struct adapter_pre_reset_state *old_state = NULL;
2121 	struct port_info *pi;
2122 	struct vi_info *vi;
2123 	struct ifnet *ifp;
2124 	struct sge_txq *txq;
2125 	int rc, i, j, k;
2126 
2127 	CH_ALERT(sc, "resume requested.\n");
2128 
2129 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4res");
2130 	if (rc != 0)
2131 		return (ENXIO);
2132 	MPASS(hw_off_limits(sc));
2133 	MPASS((sc->flags & FW_OK) == 0);
2134 	MPASS((sc->flags & MASTER_PF) == 0);
2135 	MPASS(sc->reset_thread == NULL);
2136 	sc->reset_thread = curthread;
2137 
2138 	/* Register access is expected to work by the time we're here. */
2139 	if (t4_read_reg(sc, A_PL_WHOAMI) == 0xffffffff) {
2140 		CH_ERR(sc, "%s: can't read device registers\n", __func__);
2141 		rc = ENXIO;
2142 		goto done;
2143 	}
2144 
2145 	/* Restore memory window. */
2146 	setup_memwin(sc);
2147 
2148 	/* Go no further if recovery mode has been requested. */
2149 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2150 		CH_ALERT(sc, "recovery mode on resume.\n");
2151 		rc = 0;
2152 		mtx_lock(&sc->reg_lock);
2153 		sc->flags &= ~HW_OFF_LIMITS;
2154 		mtx_unlock(&sc->reg_lock);
2155 		goto done;
2156 	}
2157 
2158 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2159 	save_caps_and_params(sc, old_state);
2160 
2161 	/* Reestablish contact with firmware and become the primary PF. */
2162 	rc = contact_firmware(sc);
2163 	if (rc != 0)
2164 		goto done; /* error message displayed already */
2165 	MPASS(sc->flags & FW_OK);
2166 
2167 	if (sc->flags & MASTER_PF) {
2168 		rc = partition_resources(sc);
2169 		if (rc != 0)
2170 			goto done; /* error message displayed already */
2171 		t4_intr_clear(sc);
2172 	}
2173 
2174 	rc = get_params__post_init(sc);
2175 	if (rc != 0)
2176 		goto done; /* error message displayed already */
2177 
2178 	rc = set_params__post_init(sc);
2179 	if (rc != 0)
2180 		goto done; /* error message displayed already */
2181 
2182 	rc = compare_caps_and_params(sc, old_state);
2183 	if (rc != 0)
2184 		goto done; /* error message displayed already */
2185 
2186 	for_each_port(sc, i) {
2187 		pi = sc->port[i];
2188 		MPASS(pi != NULL);
2189 		MPASS(pi->vi != NULL);
2190 		MPASS(pi->vi[0].dev == pi->dev);
2191 
2192 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2193 		if (rc != 0) {
2194 			CH_ERR(sc,
2195 			    "failed to re-initialize port %d: %d\n", i, rc);
2196 			goto done;
2197 		}
2198 		MPASS(sc->chan_map[pi->tx_chan] == i);
2199 
2200 		PORT_LOCK(pi);
2201 		fixup_link_config(pi);
2202 		build_medialist(pi);
2203 		PORT_UNLOCK(pi);
2204 		for_each_vi(pi, j, vi) {
2205 			if (IS_MAIN_VI(vi))
2206 				continue;
2207 			rc = alloc_extra_vi(sc, pi, vi);
2208 			if (rc != 0) {
2209 				CH_ERR(vi,
2210 				    "failed to re-allocate extra VI: %d\n", rc);
2211 				goto done;
2212 			}
2213 		}
2214 	}
2215 
2216 	/*
2217 	 * Interrupts and queues are about to be enabled and other threads will
2218 	 * want to access the hardware too.  It is safe to do so.  Note that
2219 	 * this thread is still in the middle of a synchronized_op.
2220 	 */
2221 	mtx_lock(&sc->reg_lock);
2222 	sc->flags &= ~HW_OFF_LIMITS;
2223 	mtx_unlock(&sc->reg_lock);
2224 
2225 	if (sc->flags & FULL_INIT_DONE) {
2226 		rc = adapter_full_init(sc);
2227 		if (rc != 0) {
2228 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2229 			goto done;
2230 		}
2231 
2232 		if (sc->vxlan_refcount > 0)
2233 			enable_vxlan_rx(sc);
2234 
2235 		for_each_port(sc, i) {
2236 			pi = sc->port[i];
2237 			for_each_vi(pi, j, vi) {
2238 				if (!(vi->flags & VI_INIT_DONE))
2239 					continue;
2240 				rc = vi_full_init(vi);
2241 				if (rc != 0) {
2242 					CH_ERR(vi, "failed to re-initialize "
2243 					    "interface: %d\n", rc);
2244 					goto done;
2245 				}
2246 
2247 				ifp = vi->ifp;
2248 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2249 					continue;
2250 				/*
2251 				 * Note that we do not setup multicast addresses
2252 				 * in the first pass.  This ensures that the
2253 				 * unicast DMACs for all VIs on all ports get an
2254 				 * MPS TCAM entry.
2255 				 */
2256 				rc = update_mac_settings(ifp, XGMAC_ALL &
2257 				    ~XGMAC_MCADDRS);
2258 				if (rc != 0) {
2259 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2260 					goto done;
2261 				}
2262 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2263 				    true);
2264 				if (rc != 0) {
2265 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2266 					goto done;
2267 				}
2268 				for_each_txq(vi, k, txq) {
2269 					TXQ_LOCK(txq);
2270 					txq->eq.flags |= EQ_ENABLED;
2271 					TXQ_UNLOCK(txq);
2272 				}
2273 				mtx_lock(&vi->tick_mtx);
2274 				vi->flags &= ~VI_SKIP_STATS;
2275 				callout_schedule(&vi->tick, hz);
2276 				mtx_unlock(&vi->tick_mtx);
2277 			}
2278 			PORT_LOCK(pi);
2279 			if (pi->up_vis > 0) {
2280 				t4_update_port_info(pi);
2281 				fixup_link_config(pi);
2282 				build_medialist(pi);
2283 				apply_link_config(pi);
2284 				if (pi->link_cfg.link_ok)
2285 					t4_os_link_changed(pi);
2286 			}
2287 			PORT_UNLOCK(pi);
2288 		}
2289 
2290 		/* Now reprogram the L2 multicast addresses. */
2291 		for_each_port(sc, i) {
2292 			pi = sc->port[i];
2293 			for_each_vi(pi, j, vi) {
2294 				if (!(vi->flags & VI_INIT_DONE))
2295 					continue;
2296 				ifp = vi->ifp;
2297 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2298 					continue;
2299 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2300 				if (rc != 0) {
2301 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2302 					rc = 0;	/* carry on */
2303 				}
2304 			}
2305 		}
2306 	}
2307 done:
2308 	if (rc == 0) {
2309 		sc->incarnation++;
2310 		CH_ALERT(sc, "resume completed.\n");
2311 	}
2312 	end_synchronized_op(sc, 0);
2313 	free(old_state, M_CXGBE);
2314 	return (rc);
2315 }
2316 
2317 static int
2318 t4_reset_prepare(device_t dev, device_t child)
2319 {
2320 	struct adapter *sc = device_get_softc(dev);
2321 
2322 	CH_ALERT(sc, "reset_prepare.\n");
2323 	return (0);
2324 }
2325 
2326 static int
2327 t4_reset_post(device_t dev, device_t child)
2328 {
2329 	struct adapter *sc = device_get_softc(dev);
2330 
2331 	CH_ALERT(sc, "reset_post.\n");
2332 	return (0);
2333 }
2334 
2335 static void
2336 reset_adapter(void *arg, int pending)
2337 {
2338 	struct adapter *sc = arg;
2339 	int rc;
2340 
2341 	CH_ALERT(sc, "reset requested.\n");
2342 
2343 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst1");
2344 	if (rc != 0)
2345 		return;
2346 
2347 	if (hw_off_limits(sc)) {
2348 		CH_ERR(sc, "adapter is suspended, use resume (not reset).\n");
2349 		rc = ENXIO;
2350 		goto done;
2351 	}
2352 
2353 	if (!ok_to_reset(sc)) {
2354 		/* XXX: should list what resource is preventing reset. */
2355 		CH_ERR(sc, "not safe to reset.\n");
2356 		rc = EBUSY;
2357 		goto done;
2358 	}
2359 
2360 done:
2361 	end_synchronized_op(sc, 0);
2362 	if (rc != 0)
2363 		return;	/* Error logged already. */
2364 
2365 	mtx_lock(&Giant);
2366 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2367 	mtx_unlock(&Giant);
2368 	if (rc != 0)
2369 		CH_ERR(sc, "bus_reset_child failed: %d.\n", rc);
2370 	else
2371 		CH_ALERT(sc, "bus_reset_child succeeded.\n");
2372 }
2373 
2374 static int
2375 cxgbe_probe(device_t dev)
2376 {
2377 	char buf[128];
2378 	struct port_info *pi = device_get_softc(dev);
2379 
2380 	snprintf(buf, sizeof(buf), "port %d", pi->port_id);
2381 	device_set_desc_copy(dev, buf);
2382 
2383 	return (BUS_PROBE_DEFAULT);
2384 }
2385 
2386 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2387     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2388     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2389     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2390 #define T4_CAP_ENABLE (T4_CAP)
2391 
2392 static int
2393 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2394 {
2395 	struct ifnet *ifp;
2396 	struct sbuf *sb;
2397 	struct sysctl_ctx_list *ctx;
2398 	struct sysctl_oid_list *children;
2399 	struct pfil_head_args pa;
2400 	struct adapter *sc = vi->adapter;
2401 
2402 	ctx = device_get_sysctl_ctx(vi->dev);
2403 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2404 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2405 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2406 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2407 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2408 #ifdef DEV_NETMAP
2409 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2410 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2411 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2412 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2413 #endif
2414 #ifdef TCP_OFFLOAD
2415 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2416 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2417 #endif
2418 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2419 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2420 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2421 #endif
2422 
2423 	vi->xact_addr_filt = -1;
2424 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2425 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2426 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2427 		vi->flags |= TX_USES_VM_WR;
2428 
2429 	/* Allocate an ifnet and set it up */
2430 	ifp = if_alloc_dev(IFT_ETHER, dev);
2431 	if (ifp == NULL) {
2432 		device_printf(dev, "Cannot allocate ifnet\n");
2433 		return (ENOMEM);
2434 	}
2435 	vi->ifp = ifp;
2436 	ifp->if_softc = vi;
2437 
2438 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2439 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
2440 
2441 	ifp->if_init = cxgbe_init;
2442 	ifp->if_ioctl = cxgbe_ioctl;
2443 	ifp->if_transmit = cxgbe_transmit;
2444 	ifp->if_qflush = cxgbe_qflush;
2445 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2446 		ifp->if_get_counter = vi_get_counter;
2447 	else
2448 		ifp->if_get_counter = cxgbe_get_counter;
2449 #if defined(KERN_TLS) || defined(RATELIMIT)
2450 	ifp->if_snd_tag_alloc = cxgbe_snd_tag_alloc;
2451 #endif
2452 #ifdef RATELIMIT
2453 	ifp->if_ratelimit_query = cxgbe_ratelimit_query;
2454 #endif
2455 
2456 	ifp->if_capabilities = T4_CAP;
2457 	ifp->if_capenable = T4_CAP_ENABLE;
2458 	ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2459 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6;
2460 	if (chip_id(sc) >= CHELSIO_T6) {
2461 		ifp->if_capabilities |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2462 		ifp->if_capenable |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2463 		ifp->if_hwassist |= CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2464 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2465 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN;
2466 	}
2467 
2468 #ifdef TCP_OFFLOAD
2469 	if (vi->nofldrxq != 0)
2470 		ifp->if_capabilities |= IFCAP_TOE;
2471 #endif
2472 #ifdef RATELIMIT
2473 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2474 		ifp->if_capabilities |= IFCAP_TXRTLMT;
2475 		ifp->if_capenable |= IFCAP_TXRTLMT;
2476 	}
2477 #endif
2478 
2479 	ifp->if_hw_tsomax = IP_MAXPACKET;
2480 	if (vi->flags & TX_USES_VM_WR)
2481 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
2482 	else
2483 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
2484 #ifdef RATELIMIT
2485 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2486 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_EO_TSO;
2487 #endif
2488 	ifp->if_hw_tsomaxsegsize = 65536;
2489 #ifdef KERN_TLS
2490 	if (is_ktls(sc)) {
2491 		ifp->if_capabilities |= IFCAP_TXTLS;
2492 		if (sc->flags & KERN_TLS_ON)
2493 			ifp->if_capenable |= IFCAP_TXTLS;
2494 	}
2495 #endif
2496 
2497 	ether_ifattach(ifp, vi->hw_addr);
2498 #ifdef DEV_NETMAP
2499 	if (vi->nnmrxq != 0)
2500 		cxgbe_nm_attach(vi);
2501 #endif
2502 	sb = sbuf_new_auto();
2503 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2504 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2505 	switch (ifp->if_capabilities & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2506 	case IFCAP_TOE:
2507 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2508 		break;
2509 	case IFCAP_TOE | IFCAP_TXRTLMT:
2510 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2511 		break;
2512 	case IFCAP_TXRTLMT:
2513 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2514 		break;
2515 	}
2516 #endif
2517 #ifdef TCP_OFFLOAD
2518 	if (ifp->if_capabilities & IFCAP_TOE)
2519 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2520 #endif
2521 #ifdef DEV_NETMAP
2522 	if (ifp->if_capabilities & IFCAP_NETMAP)
2523 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2524 		    vi->nnmtxq, vi->nnmrxq);
2525 #endif
2526 	sbuf_finish(sb);
2527 	device_printf(dev, "%s\n", sbuf_data(sb));
2528 	sbuf_delete(sb);
2529 
2530 	vi_sysctls(vi);
2531 
2532 	pa.pa_version = PFIL_VERSION;
2533 	pa.pa_flags = PFIL_IN;
2534 	pa.pa_type = PFIL_TYPE_ETHERNET;
2535 	pa.pa_headname = ifp->if_xname;
2536 	vi->pfil = pfil_head_register(&pa);
2537 
2538 	return (0);
2539 }
2540 
2541 static int
2542 cxgbe_attach(device_t dev)
2543 {
2544 	struct port_info *pi = device_get_softc(dev);
2545 	struct adapter *sc = pi->adapter;
2546 	struct vi_info *vi;
2547 	int i, rc;
2548 
2549 	rc = cxgbe_vi_attach(dev, &pi->vi[0]);
2550 	if (rc)
2551 		return (rc);
2552 
2553 	for_each_vi(pi, i, vi) {
2554 		if (i == 0)
2555 			continue;
2556 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
2557 		if (vi->dev == NULL) {
2558 			device_printf(dev, "failed to add VI %d\n", i);
2559 			continue;
2560 		}
2561 		device_set_softc(vi->dev, vi);
2562 	}
2563 
2564 	cxgbe_sysctls(pi);
2565 
2566 	bus_generic_attach(dev);
2567 
2568 	return (0);
2569 }
2570 
2571 static void
2572 cxgbe_vi_detach(struct vi_info *vi)
2573 {
2574 	struct ifnet *ifp = vi->ifp;
2575 
2576 	if (vi->pfil != NULL) {
2577 		pfil_head_unregister(vi->pfil);
2578 		vi->pfil = NULL;
2579 	}
2580 
2581 	ether_ifdetach(ifp);
2582 
2583 	/* Let detach proceed even if these fail. */
2584 #ifdef DEV_NETMAP
2585 	if (ifp->if_capabilities & IFCAP_NETMAP)
2586 		cxgbe_nm_detach(vi);
2587 #endif
2588 	cxgbe_uninit_synchronized(vi);
2589 	callout_drain(&vi->tick);
2590 	vi_full_uninit(vi);
2591 
2592 	if_free(vi->ifp);
2593 	vi->ifp = NULL;
2594 }
2595 
2596 static int
2597 cxgbe_detach(device_t dev)
2598 {
2599 	struct port_info *pi = device_get_softc(dev);
2600 	struct adapter *sc = pi->adapter;
2601 	int rc;
2602 
2603 	/* Detach the extra VIs first. */
2604 	rc = bus_generic_detach(dev);
2605 	if (rc)
2606 		return (rc);
2607 	device_delete_children(dev);
2608 
2609 	doom_vi(sc, &pi->vi[0]);
2610 
2611 	if (pi->flags & HAS_TRACEQ) {
2612 		sc->traceq = -1;	/* cloner should not create ifnet */
2613 		t4_tracer_port_detach(sc);
2614 	}
2615 
2616 	cxgbe_vi_detach(&pi->vi[0]);
2617 	ifmedia_removeall(&pi->media);
2618 
2619 	end_synchronized_op(sc, 0);
2620 
2621 	return (0);
2622 }
2623 
2624 static void
2625 cxgbe_init(void *arg)
2626 {
2627 	struct vi_info *vi = arg;
2628 	struct adapter *sc = vi->adapter;
2629 
2630 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2631 		return;
2632 	cxgbe_init_synchronized(vi);
2633 	end_synchronized_op(sc, 0);
2634 }
2635 
2636 static int
2637 cxgbe_ioctl(struct ifnet *ifp, unsigned long cmd, caddr_t data)
2638 {
2639 	int rc = 0, mtu, flags;
2640 	struct vi_info *vi = ifp->if_softc;
2641 	struct port_info *pi = vi->pi;
2642 	struct adapter *sc = pi->adapter;
2643 	struct ifreq *ifr = (struct ifreq *)data;
2644 	uint32_t mask;
2645 
2646 	switch (cmd) {
2647 	case SIOCSIFMTU:
2648 		mtu = ifr->ifr_mtu;
2649 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2650 			return (EINVAL);
2651 
2652 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2653 		if (rc)
2654 			return (rc);
2655 		ifp->if_mtu = mtu;
2656 		if (vi->flags & VI_INIT_DONE) {
2657 			t4_update_fl_bufsize(ifp);
2658 			if (!hw_off_limits(sc) &&
2659 			    ifp->if_drv_flags & IFF_DRV_RUNNING)
2660 				rc = update_mac_settings(ifp, XGMAC_MTU);
2661 		}
2662 		end_synchronized_op(sc, 0);
2663 		break;
2664 
2665 	case SIOCSIFFLAGS:
2666 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2667 		if (rc)
2668 			return (rc);
2669 
2670 		if (hw_off_limits(sc)) {
2671 			rc = ENXIO;
2672 			goto fail;
2673 		}
2674 
2675 		if (ifp->if_flags & IFF_UP) {
2676 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2677 				flags = vi->if_flags;
2678 				if ((ifp->if_flags ^ flags) &
2679 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2680 					rc = update_mac_settings(ifp,
2681 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2682 				}
2683 			} else {
2684 				rc = cxgbe_init_synchronized(vi);
2685 			}
2686 			vi->if_flags = ifp->if_flags;
2687 		} else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2688 			rc = cxgbe_uninit_synchronized(vi);
2689 		}
2690 		end_synchronized_op(sc, 0);
2691 		break;
2692 
2693 	case SIOCADDMULTI:
2694 	case SIOCDELMULTI:
2695 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2696 		if (rc)
2697 			return (rc);
2698 		if (!hw_off_limits(sc) && ifp->if_drv_flags & IFF_DRV_RUNNING)
2699 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2700 		end_synchronized_op(sc, 0);
2701 		break;
2702 
2703 	case SIOCSIFCAP:
2704 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2705 		if (rc)
2706 			return (rc);
2707 
2708 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
2709 		if (mask & IFCAP_TXCSUM) {
2710 			ifp->if_capenable ^= IFCAP_TXCSUM;
2711 			ifp->if_hwassist ^= (CSUM_TCP | CSUM_UDP | CSUM_IP);
2712 
2713 			if (IFCAP_TSO4 & ifp->if_capenable &&
2714 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2715 				mask &= ~IFCAP_TSO4;
2716 				ifp->if_capenable &= ~IFCAP_TSO4;
2717 				if_printf(ifp,
2718 				    "tso4 disabled due to -txcsum.\n");
2719 			}
2720 		}
2721 		if (mask & IFCAP_TXCSUM_IPV6) {
2722 			ifp->if_capenable ^= IFCAP_TXCSUM_IPV6;
2723 			ifp->if_hwassist ^= (CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2724 
2725 			if (IFCAP_TSO6 & ifp->if_capenable &&
2726 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2727 				mask &= ~IFCAP_TSO6;
2728 				ifp->if_capenable &= ~IFCAP_TSO6;
2729 				if_printf(ifp,
2730 				    "tso6 disabled due to -txcsum6.\n");
2731 			}
2732 		}
2733 		if (mask & IFCAP_RXCSUM)
2734 			ifp->if_capenable ^= IFCAP_RXCSUM;
2735 		if (mask & IFCAP_RXCSUM_IPV6)
2736 			ifp->if_capenable ^= IFCAP_RXCSUM_IPV6;
2737 
2738 		/*
2739 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2740 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2741 		 * sending a TSO request our way, so it's sufficient to toggle
2742 		 * IFCAP_TSOx only.
2743 		 */
2744 		if (mask & IFCAP_TSO4) {
2745 			if (!(IFCAP_TSO4 & ifp->if_capenable) &&
2746 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2747 				if_printf(ifp, "enable txcsum first.\n");
2748 				rc = EAGAIN;
2749 				goto fail;
2750 			}
2751 			ifp->if_capenable ^= IFCAP_TSO4;
2752 		}
2753 		if (mask & IFCAP_TSO6) {
2754 			if (!(IFCAP_TSO6 & ifp->if_capenable) &&
2755 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2756 				if_printf(ifp, "enable txcsum6 first.\n");
2757 				rc = EAGAIN;
2758 				goto fail;
2759 			}
2760 			ifp->if_capenable ^= IFCAP_TSO6;
2761 		}
2762 		if (mask & IFCAP_LRO) {
2763 #if defined(INET) || defined(INET6)
2764 			int i;
2765 			struct sge_rxq *rxq;
2766 
2767 			ifp->if_capenable ^= IFCAP_LRO;
2768 			for_each_rxq(vi, i, rxq) {
2769 				if (ifp->if_capenable & IFCAP_LRO)
2770 					rxq->iq.flags |= IQ_LRO_ENABLED;
2771 				else
2772 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2773 			}
2774 #endif
2775 		}
2776 #ifdef TCP_OFFLOAD
2777 		if (mask & IFCAP_TOE) {
2778 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TOE;
2779 
2780 			rc = toe_capability(vi, enable);
2781 			if (rc != 0)
2782 				goto fail;
2783 
2784 			ifp->if_capenable ^= mask;
2785 		}
2786 #endif
2787 		if (mask & IFCAP_VLAN_HWTAGGING) {
2788 			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
2789 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2790 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2791 		}
2792 		if (mask & IFCAP_VLAN_MTU) {
2793 			ifp->if_capenable ^= IFCAP_VLAN_MTU;
2794 
2795 			/* Need to find out how to disable auto-mtu-inflation */
2796 		}
2797 		if (mask & IFCAP_VLAN_HWTSO)
2798 			ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
2799 		if (mask & IFCAP_VLAN_HWCSUM)
2800 			ifp->if_capenable ^= IFCAP_VLAN_HWCSUM;
2801 #ifdef RATELIMIT
2802 		if (mask & IFCAP_TXRTLMT)
2803 			ifp->if_capenable ^= IFCAP_TXRTLMT;
2804 #endif
2805 		if (mask & IFCAP_HWRXTSTMP) {
2806 			int i;
2807 			struct sge_rxq *rxq;
2808 
2809 			ifp->if_capenable ^= IFCAP_HWRXTSTMP;
2810 			for_each_rxq(vi, i, rxq) {
2811 				if (ifp->if_capenable & IFCAP_HWRXTSTMP)
2812 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2813 				else
2814 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2815 			}
2816 		}
2817 		if (mask & IFCAP_MEXTPG)
2818 			ifp->if_capenable ^= IFCAP_MEXTPG;
2819 
2820 #ifdef KERN_TLS
2821 		if (mask & IFCAP_TXTLS) {
2822 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TXTLS;
2823 
2824 			rc = ktls_capability(sc, enable);
2825 			if (rc != 0)
2826 				goto fail;
2827 
2828 			ifp->if_capenable ^= (mask & IFCAP_TXTLS);
2829 		}
2830 #endif
2831 		if (mask & IFCAP_VXLAN_HWCSUM) {
2832 			ifp->if_capenable ^= IFCAP_VXLAN_HWCSUM;
2833 			ifp->if_hwassist ^= CSUM_INNER_IP6_UDP |
2834 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
2835 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP;
2836 		}
2837 		if (mask & IFCAP_VXLAN_HWTSO) {
2838 			ifp->if_capenable ^= IFCAP_VXLAN_HWTSO;
2839 			ifp->if_hwassist ^= CSUM_INNER_IP6_TSO |
2840 			    CSUM_INNER_IP_TSO;
2841 		}
2842 
2843 #ifdef VLAN_CAPABILITIES
2844 		VLAN_CAPABILITIES(ifp);
2845 #endif
2846 fail:
2847 		end_synchronized_op(sc, 0);
2848 		break;
2849 
2850 	case SIOCSIFMEDIA:
2851 	case SIOCGIFMEDIA:
2852 	case SIOCGIFXMEDIA:
2853 		ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
2854 		break;
2855 
2856 	case SIOCGI2C: {
2857 		struct ifi2creq i2c;
2858 
2859 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
2860 		if (rc != 0)
2861 			break;
2862 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
2863 			rc = EPERM;
2864 			break;
2865 		}
2866 		if (i2c.len > sizeof(i2c.data)) {
2867 			rc = EINVAL;
2868 			break;
2869 		}
2870 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
2871 		if (rc)
2872 			return (rc);
2873 		if (hw_off_limits(sc))
2874 			rc = ENXIO;
2875 		else
2876 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
2877 			    i2c.offset, i2c.len, &i2c.data[0]);
2878 		end_synchronized_op(sc, 0);
2879 		if (rc == 0)
2880 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
2881 		break;
2882 	}
2883 
2884 	default:
2885 		rc = ether_ioctl(ifp, cmd, data);
2886 	}
2887 
2888 	return (rc);
2889 }
2890 
2891 static int
2892 cxgbe_transmit(struct ifnet *ifp, struct mbuf *m)
2893 {
2894 	struct vi_info *vi = ifp->if_softc;
2895 	struct port_info *pi = vi->pi;
2896 	struct adapter *sc;
2897 	struct sge_txq *txq;
2898 	void *items[1];
2899 	int rc;
2900 
2901 	M_ASSERTPKTHDR(m);
2902 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
2903 #if defined(KERN_TLS) || defined(RATELIMIT)
2904 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
2905 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
2906 #endif
2907 
2908 	if (__predict_false(pi->link_cfg.link_ok == false)) {
2909 		m_freem(m);
2910 		return (ENETDOWN);
2911 	}
2912 
2913 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
2914 	if (__predict_false(rc != 0)) {
2915 		MPASS(m == NULL);			/* was freed already */
2916 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
2917 		return (rc);
2918 	}
2919 #ifdef RATELIMIT
2920 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG) {
2921 		if (m->m_pkthdr.snd_tag->sw->type == IF_SND_TAG_TYPE_RATE_LIMIT)
2922 			return (ethofld_transmit(ifp, m));
2923 	}
2924 #endif
2925 
2926 	/* Select a txq. */
2927 	sc = vi->adapter;
2928 	txq = &sc->sge.txq[vi->first_txq];
2929 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
2930 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
2931 		    vi->rsrv_noflowq);
2932 
2933 	items[0] = m;
2934 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
2935 	if (__predict_false(rc != 0))
2936 		m_freem(m);
2937 
2938 	return (rc);
2939 }
2940 
2941 static void
2942 cxgbe_qflush(struct ifnet *ifp)
2943 {
2944 	struct vi_info *vi = ifp->if_softc;
2945 	struct sge_txq *txq;
2946 	int i;
2947 
2948 	/* queues do not exist if !VI_INIT_DONE. */
2949 	if (vi->flags & VI_INIT_DONE) {
2950 		for_each_txq(vi, i, txq) {
2951 			TXQ_LOCK(txq);
2952 			txq->eq.flags |= EQ_QFLUSH;
2953 			TXQ_UNLOCK(txq);
2954 			while (!mp_ring_is_idle(txq->r)) {
2955 				mp_ring_check_drainage(txq->r, 4096);
2956 				pause("qflush", 1);
2957 			}
2958 			TXQ_LOCK(txq);
2959 			txq->eq.flags &= ~EQ_QFLUSH;
2960 			TXQ_UNLOCK(txq);
2961 		}
2962 	}
2963 	if_qflush(ifp);
2964 }
2965 
2966 static uint64_t
2967 vi_get_counter(struct ifnet *ifp, ift_counter c)
2968 {
2969 	struct vi_info *vi = ifp->if_softc;
2970 	struct fw_vi_stats_vf *s = &vi->stats;
2971 
2972 	mtx_lock(&vi->tick_mtx);
2973 	vi_refresh_stats(vi);
2974 	mtx_unlock(&vi->tick_mtx);
2975 
2976 	switch (c) {
2977 	case IFCOUNTER_IPACKETS:
2978 		return (s->rx_bcast_frames + s->rx_mcast_frames +
2979 		    s->rx_ucast_frames);
2980 	case IFCOUNTER_IERRORS:
2981 		return (s->rx_err_frames);
2982 	case IFCOUNTER_OPACKETS:
2983 		return (s->tx_bcast_frames + s->tx_mcast_frames +
2984 		    s->tx_ucast_frames + s->tx_offload_frames);
2985 	case IFCOUNTER_OERRORS:
2986 		return (s->tx_drop_frames);
2987 	case IFCOUNTER_IBYTES:
2988 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
2989 		    s->rx_ucast_bytes);
2990 	case IFCOUNTER_OBYTES:
2991 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
2992 		    s->tx_ucast_bytes + s->tx_offload_bytes);
2993 	case IFCOUNTER_IMCASTS:
2994 		return (s->rx_mcast_frames);
2995 	case IFCOUNTER_OMCASTS:
2996 		return (s->tx_mcast_frames);
2997 	case IFCOUNTER_OQDROPS: {
2998 		uint64_t drops;
2999 
3000 		drops = 0;
3001 		if (vi->flags & VI_INIT_DONE) {
3002 			int i;
3003 			struct sge_txq *txq;
3004 
3005 			for_each_txq(vi, i, txq)
3006 				drops += counter_u64_fetch(txq->r->dropped);
3007 		}
3008 
3009 		return (drops);
3010 
3011 	}
3012 
3013 	default:
3014 		return (if_get_counter_default(ifp, c));
3015 	}
3016 }
3017 
3018 static uint64_t
3019 cxgbe_get_counter(struct ifnet *ifp, ift_counter c)
3020 {
3021 	struct vi_info *vi = ifp->if_softc;
3022 	struct port_info *pi = vi->pi;
3023 	struct port_stats *s = &pi->stats;
3024 
3025 	mtx_lock(&vi->tick_mtx);
3026 	cxgbe_refresh_stats(vi);
3027 	mtx_unlock(&vi->tick_mtx);
3028 
3029 	switch (c) {
3030 	case IFCOUNTER_IPACKETS:
3031 		return (s->rx_frames);
3032 
3033 	case IFCOUNTER_IERRORS:
3034 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3035 		    s->rx_fcs_err + s->rx_len_err);
3036 
3037 	case IFCOUNTER_OPACKETS:
3038 		return (s->tx_frames);
3039 
3040 	case IFCOUNTER_OERRORS:
3041 		return (s->tx_error_frames);
3042 
3043 	case IFCOUNTER_IBYTES:
3044 		return (s->rx_octets);
3045 
3046 	case IFCOUNTER_OBYTES:
3047 		return (s->tx_octets);
3048 
3049 	case IFCOUNTER_IMCASTS:
3050 		return (s->rx_mcast_frames);
3051 
3052 	case IFCOUNTER_OMCASTS:
3053 		return (s->tx_mcast_frames);
3054 
3055 	case IFCOUNTER_IQDROPS:
3056 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3057 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3058 		    s->rx_trunc3 + pi->tnl_cong_drops);
3059 
3060 	case IFCOUNTER_OQDROPS: {
3061 		uint64_t drops;
3062 
3063 		drops = s->tx_drop;
3064 		if (vi->flags & VI_INIT_DONE) {
3065 			int i;
3066 			struct sge_txq *txq;
3067 
3068 			for_each_txq(vi, i, txq)
3069 				drops += counter_u64_fetch(txq->r->dropped);
3070 		}
3071 
3072 		return (drops);
3073 
3074 	}
3075 
3076 	default:
3077 		return (if_get_counter_default(ifp, c));
3078 	}
3079 }
3080 
3081 #if defined(KERN_TLS) || defined(RATELIMIT)
3082 static int
3083 cxgbe_snd_tag_alloc(struct ifnet *ifp, union if_snd_tag_alloc_params *params,
3084     struct m_snd_tag **pt)
3085 {
3086 	int error;
3087 
3088 	switch (params->hdr.type) {
3089 #ifdef RATELIMIT
3090 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3091 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3092 		break;
3093 #endif
3094 #ifdef KERN_TLS
3095 	case IF_SND_TAG_TYPE_TLS:
3096 		error = cxgbe_tls_tag_alloc(ifp, params, pt);
3097 		break;
3098 #endif
3099 	default:
3100 		error = EOPNOTSUPP;
3101 	}
3102 	return (error);
3103 }
3104 #endif
3105 
3106 /*
3107  * The kernel picks a media from the list we had provided but we still validate
3108  * the requeste.
3109  */
3110 int
3111 cxgbe_media_change(struct ifnet *ifp)
3112 {
3113 	struct vi_info *vi = ifp->if_softc;
3114 	struct port_info *pi = vi->pi;
3115 	struct ifmedia *ifm = &pi->media;
3116 	struct link_config *lc = &pi->link_cfg;
3117 	struct adapter *sc = pi->adapter;
3118 	int rc;
3119 
3120 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3121 	if (rc != 0)
3122 		return (rc);
3123 	PORT_LOCK(pi);
3124 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3125 		/* ifconfig .. media autoselect */
3126 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3127 			rc = ENOTSUP; /* AN not supported by transceiver */
3128 			goto done;
3129 		}
3130 		lc->requested_aneg = AUTONEG_ENABLE;
3131 		lc->requested_speed = 0;
3132 		lc->requested_fc |= PAUSE_AUTONEG;
3133 	} else {
3134 		lc->requested_aneg = AUTONEG_DISABLE;
3135 		lc->requested_speed =
3136 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3137 		lc->requested_fc = 0;
3138 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3139 			lc->requested_fc |= PAUSE_RX;
3140 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3141 			lc->requested_fc |= PAUSE_TX;
3142 	}
3143 	if (pi->up_vis > 0) {
3144 		fixup_link_config(pi);
3145 		rc = apply_link_config(pi);
3146 	}
3147 done:
3148 	PORT_UNLOCK(pi);
3149 	end_synchronized_op(sc, 0);
3150 	return (rc);
3151 }
3152 
3153 /*
3154  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3155  * given speed.
3156  */
3157 static int
3158 port_mword(struct port_info *pi, uint32_t speed)
3159 {
3160 
3161 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3162 	MPASS(powerof2(speed));
3163 
3164 	switch(pi->port_type) {
3165 	case FW_PORT_TYPE_BT_SGMII:
3166 	case FW_PORT_TYPE_BT_XFI:
3167 	case FW_PORT_TYPE_BT_XAUI:
3168 		/* BaseT */
3169 		switch (speed) {
3170 		case FW_PORT_CAP32_SPEED_100M:
3171 			return (IFM_100_T);
3172 		case FW_PORT_CAP32_SPEED_1G:
3173 			return (IFM_1000_T);
3174 		case FW_PORT_CAP32_SPEED_10G:
3175 			return (IFM_10G_T);
3176 		}
3177 		break;
3178 	case FW_PORT_TYPE_KX4:
3179 		if (speed == FW_PORT_CAP32_SPEED_10G)
3180 			return (IFM_10G_KX4);
3181 		break;
3182 	case FW_PORT_TYPE_CX4:
3183 		if (speed == FW_PORT_CAP32_SPEED_10G)
3184 			return (IFM_10G_CX4);
3185 		break;
3186 	case FW_PORT_TYPE_KX:
3187 		if (speed == FW_PORT_CAP32_SPEED_1G)
3188 			return (IFM_1000_KX);
3189 		break;
3190 	case FW_PORT_TYPE_KR:
3191 	case FW_PORT_TYPE_BP_AP:
3192 	case FW_PORT_TYPE_BP4_AP:
3193 	case FW_PORT_TYPE_BP40_BA:
3194 	case FW_PORT_TYPE_KR4_100G:
3195 	case FW_PORT_TYPE_KR_SFP28:
3196 	case FW_PORT_TYPE_KR_XLAUI:
3197 		switch (speed) {
3198 		case FW_PORT_CAP32_SPEED_1G:
3199 			return (IFM_1000_KX);
3200 		case FW_PORT_CAP32_SPEED_10G:
3201 			return (IFM_10G_KR);
3202 		case FW_PORT_CAP32_SPEED_25G:
3203 			return (IFM_25G_KR);
3204 		case FW_PORT_CAP32_SPEED_40G:
3205 			return (IFM_40G_KR4);
3206 		case FW_PORT_CAP32_SPEED_50G:
3207 			return (IFM_50G_KR2);
3208 		case FW_PORT_CAP32_SPEED_100G:
3209 			return (IFM_100G_KR4);
3210 		}
3211 		break;
3212 	case FW_PORT_TYPE_FIBER_XFI:
3213 	case FW_PORT_TYPE_FIBER_XAUI:
3214 	case FW_PORT_TYPE_SFP:
3215 	case FW_PORT_TYPE_QSFP_10G:
3216 	case FW_PORT_TYPE_QSA:
3217 	case FW_PORT_TYPE_QSFP:
3218 	case FW_PORT_TYPE_CR4_QSFP:
3219 	case FW_PORT_TYPE_CR_QSFP:
3220 	case FW_PORT_TYPE_CR2_QSFP:
3221 	case FW_PORT_TYPE_SFP28:
3222 		/* Pluggable transceiver */
3223 		switch (pi->mod_type) {
3224 		case FW_PORT_MOD_TYPE_LR:
3225 			switch (speed) {
3226 			case FW_PORT_CAP32_SPEED_1G:
3227 				return (IFM_1000_LX);
3228 			case FW_PORT_CAP32_SPEED_10G:
3229 				return (IFM_10G_LR);
3230 			case FW_PORT_CAP32_SPEED_25G:
3231 				return (IFM_25G_LR);
3232 			case FW_PORT_CAP32_SPEED_40G:
3233 				return (IFM_40G_LR4);
3234 			case FW_PORT_CAP32_SPEED_50G:
3235 				return (IFM_50G_LR2);
3236 			case FW_PORT_CAP32_SPEED_100G:
3237 				return (IFM_100G_LR4);
3238 			}
3239 			break;
3240 		case FW_PORT_MOD_TYPE_SR:
3241 			switch (speed) {
3242 			case FW_PORT_CAP32_SPEED_1G:
3243 				return (IFM_1000_SX);
3244 			case FW_PORT_CAP32_SPEED_10G:
3245 				return (IFM_10G_SR);
3246 			case FW_PORT_CAP32_SPEED_25G:
3247 				return (IFM_25G_SR);
3248 			case FW_PORT_CAP32_SPEED_40G:
3249 				return (IFM_40G_SR4);
3250 			case FW_PORT_CAP32_SPEED_50G:
3251 				return (IFM_50G_SR2);
3252 			case FW_PORT_CAP32_SPEED_100G:
3253 				return (IFM_100G_SR4);
3254 			}
3255 			break;
3256 		case FW_PORT_MOD_TYPE_ER:
3257 			if (speed == FW_PORT_CAP32_SPEED_10G)
3258 				return (IFM_10G_ER);
3259 			break;
3260 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3261 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3262 			switch (speed) {
3263 			case FW_PORT_CAP32_SPEED_1G:
3264 				return (IFM_1000_CX);
3265 			case FW_PORT_CAP32_SPEED_10G:
3266 				return (IFM_10G_TWINAX);
3267 			case FW_PORT_CAP32_SPEED_25G:
3268 				return (IFM_25G_CR);
3269 			case FW_PORT_CAP32_SPEED_40G:
3270 				return (IFM_40G_CR4);
3271 			case FW_PORT_CAP32_SPEED_50G:
3272 				return (IFM_50G_CR2);
3273 			case FW_PORT_CAP32_SPEED_100G:
3274 				return (IFM_100G_CR4);
3275 			}
3276 			break;
3277 		case FW_PORT_MOD_TYPE_LRM:
3278 			if (speed == FW_PORT_CAP32_SPEED_10G)
3279 				return (IFM_10G_LRM);
3280 			break;
3281 		case FW_PORT_MOD_TYPE_NA:
3282 			MPASS(0);	/* Not pluggable? */
3283 			/* fall throough */
3284 		case FW_PORT_MOD_TYPE_ERROR:
3285 		case FW_PORT_MOD_TYPE_UNKNOWN:
3286 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3287 			break;
3288 		case FW_PORT_MOD_TYPE_NONE:
3289 			return (IFM_NONE);
3290 		}
3291 		break;
3292 	case FW_PORT_TYPE_NONE:
3293 		return (IFM_NONE);
3294 	}
3295 
3296 	return (IFM_UNKNOWN);
3297 }
3298 
3299 void
3300 cxgbe_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
3301 {
3302 	struct vi_info *vi = ifp->if_softc;
3303 	struct port_info *pi = vi->pi;
3304 	struct adapter *sc = pi->adapter;
3305 	struct link_config *lc = &pi->link_cfg;
3306 
3307 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4med") != 0)
3308 		return;
3309 	PORT_LOCK(pi);
3310 
3311 	if (pi->up_vis == 0) {
3312 		/*
3313 		 * If all the interfaces are administratively down the firmware
3314 		 * does not report transceiver changes.  Refresh port info here
3315 		 * so that ifconfig displays accurate ifmedia at all times.
3316 		 * This is the only reason we have a synchronized op in this
3317 		 * function.  Just PORT_LOCK would have been enough otherwise.
3318 		 */
3319 		t4_update_port_info(pi);
3320 		build_medialist(pi);
3321 	}
3322 
3323 	/* ifm_status */
3324 	ifmr->ifm_status = IFM_AVALID;
3325 	if (lc->link_ok == false)
3326 		goto done;
3327 	ifmr->ifm_status |= IFM_ACTIVE;
3328 
3329 	/* ifm_active */
3330 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3331 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3332 	if (lc->fc & PAUSE_RX)
3333 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3334 	if (lc->fc & PAUSE_TX)
3335 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3336 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3337 done:
3338 	PORT_UNLOCK(pi);
3339 	end_synchronized_op(sc, 0);
3340 }
3341 
3342 static int
3343 vcxgbe_probe(device_t dev)
3344 {
3345 	char buf[128];
3346 	struct vi_info *vi = device_get_softc(dev);
3347 
3348 	snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
3349 	    vi - vi->pi->vi);
3350 	device_set_desc_copy(dev, buf);
3351 
3352 	return (BUS_PROBE_DEFAULT);
3353 }
3354 
3355 static int
3356 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3357 {
3358 	int func, index, rc;
3359 	uint32_t param, val;
3360 
3361 	ASSERT_SYNCHRONIZED_OP(sc);
3362 
3363 	index = vi - pi->vi;
3364 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3365 	KASSERT(index < nitems(vi_mac_funcs),
3366 	    ("%s: VI %s doesn't have a MAC func", __func__,
3367 	    device_get_nameunit(vi->dev)));
3368 	func = vi_mac_funcs[index];
3369 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3370 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3371 	if (rc < 0) {
3372 		CH_ERR(vi, "failed to allocate virtual interface %d"
3373 		    "for port %d: %d\n", index, pi->port_id, -rc);
3374 		return (-rc);
3375 	}
3376 	vi->viid = rc;
3377 
3378 	if (vi->rss_size == 1) {
3379 		/*
3380 		 * This VI didn't get a slice of the RSS table.  Reduce the
3381 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3382 		 * configuration file (nvi, rssnvi for this PF) if this is a
3383 		 * problem.
3384 		 */
3385 		device_printf(vi->dev, "RSS table not available.\n");
3386 		vi->rss_base = 0xffff;
3387 
3388 		return (0);
3389 	}
3390 
3391 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3392 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3393 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3394 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3395 	if (rc)
3396 		vi->rss_base = 0xffff;
3397 	else {
3398 		MPASS((val >> 16) == vi->rss_size);
3399 		vi->rss_base = val & 0xffff;
3400 	}
3401 
3402 	return (0);
3403 }
3404 
3405 static int
3406 vcxgbe_attach(device_t dev)
3407 {
3408 	struct vi_info *vi;
3409 	struct port_info *pi;
3410 	struct adapter *sc;
3411 	int rc;
3412 
3413 	vi = device_get_softc(dev);
3414 	pi = vi->pi;
3415 	sc = pi->adapter;
3416 
3417 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3418 	if (rc)
3419 		return (rc);
3420 	rc = alloc_extra_vi(sc, pi, vi);
3421 	end_synchronized_op(sc, 0);
3422 	if (rc)
3423 		return (rc);
3424 
3425 	rc = cxgbe_vi_attach(dev, vi);
3426 	if (rc) {
3427 		t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3428 		return (rc);
3429 	}
3430 	return (0);
3431 }
3432 
3433 static int
3434 vcxgbe_detach(device_t dev)
3435 {
3436 	struct vi_info *vi;
3437 	struct adapter *sc;
3438 
3439 	vi = device_get_softc(dev);
3440 	sc = vi->adapter;
3441 
3442 	doom_vi(sc, vi);
3443 
3444 	cxgbe_vi_detach(vi);
3445 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3446 
3447 	end_synchronized_op(sc, 0);
3448 
3449 	return (0);
3450 }
3451 
3452 static struct callout fatal_callout;
3453 static struct taskqueue *reset_tq;
3454 
3455 static void
3456 delayed_panic(void *arg)
3457 {
3458 	struct adapter *sc = arg;
3459 
3460 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3461 }
3462 
3463 void
3464 t4_fatal_err(struct adapter *sc, bool fw_error)
3465 {
3466 
3467 	t4_shutdown_adapter(sc);
3468 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped.\n",
3469 	    device_get_nameunit(sc->dev));
3470 	if (fw_error) {
3471 		if (sc->flags & CHK_MBOX_ACCESS)
3472 			ASSERT_SYNCHRONIZED_OP(sc);
3473 		sc->flags |= ADAP_ERR;
3474 	} else {
3475 		ADAPTER_LOCK(sc);
3476 		sc->flags |= ADAP_ERR;
3477 		ADAPTER_UNLOCK(sc);
3478 	}
3479 #ifdef TCP_OFFLOAD
3480 	taskqueue_enqueue(taskqueue_thread, &sc->async_event_task);
3481 #endif
3482 
3483 	if (t4_panic_on_fatal_err) {
3484 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3485 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3486 	} else if (t4_reset_on_fatal_err) {
3487 		CH_ALERT(sc, "resetting on fatal error.\n");
3488 		taskqueue_enqueue(reset_tq, &sc->reset_task);
3489 	}
3490 }
3491 
3492 void
3493 t4_add_adapter(struct adapter *sc)
3494 {
3495 	sx_xlock(&t4_list_lock);
3496 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3497 	sx_xunlock(&t4_list_lock);
3498 }
3499 
3500 int
3501 t4_map_bars_0_and_4(struct adapter *sc)
3502 {
3503 	sc->regs_rid = PCIR_BAR(0);
3504 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3505 	    &sc->regs_rid, RF_ACTIVE);
3506 	if (sc->regs_res == NULL) {
3507 		device_printf(sc->dev, "cannot map registers.\n");
3508 		return (ENXIO);
3509 	}
3510 	sc->bt = rman_get_bustag(sc->regs_res);
3511 	sc->bh = rman_get_bushandle(sc->regs_res);
3512 	sc->mmio_len = rman_get_size(sc->regs_res);
3513 	setbit(&sc->doorbells, DOORBELL_KDB);
3514 
3515 	sc->msix_rid = PCIR_BAR(4);
3516 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3517 	    &sc->msix_rid, RF_ACTIVE);
3518 	if (sc->msix_res == NULL) {
3519 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3520 		return (ENXIO);
3521 	}
3522 
3523 	return (0);
3524 }
3525 
3526 int
3527 t4_map_bar_2(struct adapter *sc)
3528 {
3529 
3530 	/*
3531 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3532 	 * to map it if RDMA is disabled.
3533 	 */
3534 	if (is_t4(sc) && sc->rdmacaps == 0)
3535 		return (0);
3536 
3537 	sc->udbs_rid = PCIR_BAR(2);
3538 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3539 	    &sc->udbs_rid, RF_ACTIVE);
3540 	if (sc->udbs_res == NULL) {
3541 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3542 		return (ENXIO);
3543 	}
3544 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3545 
3546 	if (chip_id(sc) >= CHELSIO_T5) {
3547 		setbit(&sc->doorbells, DOORBELL_UDB);
3548 #if defined(__i386__) || defined(__amd64__)
3549 		if (t5_write_combine) {
3550 			int rc, mode;
3551 
3552 			/*
3553 			 * Enable write combining on BAR2.  This is the
3554 			 * userspace doorbell BAR and is split into 128B
3555 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3556 			 * with an egress queue.  The first 64B has the doorbell
3557 			 * and the second 64B can be used to submit a tx work
3558 			 * request with an implicit doorbell.
3559 			 */
3560 
3561 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3562 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3563 			if (rc == 0) {
3564 				clrbit(&sc->doorbells, DOORBELL_UDB);
3565 				setbit(&sc->doorbells, DOORBELL_WCWR);
3566 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3567 			} else {
3568 				device_printf(sc->dev,
3569 				    "couldn't enable write combining: %d\n",
3570 				    rc);
3571 			}
3572 
3573 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3574 			t4_write_reg(sc, A_SGE_STAT_CFG,
3575 			    V_STATSOURCE_T5(7) | mode);
3576 		}
3577 #endif
3578 	}
3579 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3580 
3581 	return (0);
3582 }
3583 
3584 struct memwin_init {
3585 	uint32_t base;
3586 	uint32_t aperture;
3587 };
3588 
3589 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3590 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3591 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3592 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3593 };
3594 
3595 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3596 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3597 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3598 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3599 };
3600 
3601 static void
3602 setup_memwin(struct adapter *sc)
3603 {
3604 	const struct memwin_init *mw_init;
3605 	struct memwin *mw;
3606 	int i;
3607 	uint32_t bar0;
3608 
3609 	if (is_t4(sc)) {
3610 		/*
3611 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3612 		 * mechanism.  Works from within PCI passthrough environments
3613 		 * too, where rman_get_start() can return a different value.  We
3614 		 * need to program the T4 memory window decoders with the actual
3615 		 * addresses that will be coming across the PCIe link.
3616 		 */
3617 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3618 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3619 
3620 		mw_init = &t4_memwin[0];
3621 	} else {
3622 		/* T5+ use the relative offset inside the PCIe BAR */
3623 		bar0 = 0;
3624 
3625 		mw_init = &t5_memwin[0];
3626 	}
3627 
3628 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3629 		if (!rw_initialized(&mw->mw_lock)) {
3630 			rw_init(&mw->mw_lock, "memory window access");
3631 			mw->mw_base = mw_init->base;
3632 			mw->mw_aperture = mw_init->aperture;
3633 			mw->mw_curpos = 0;
3634 		}
3635 		t4_write_reg(sc,
3636 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3637 		    (mw->mw_base + bar0) | V_BIR(0) |
3638 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3639 		rw_wlock(&mw->mw_lock);
3640 		position_memwin(sc, i, mw->mw_curpos);
3641 		rw_wunlock(&mw->mw_lock);
3642 	}
3643 
3644 	/* flush */
3645 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3646 }
3647 
3648 /*
3649  * Positions the memory window at the given address in the card's address space.
3650  * There are some alignment requirements and the actual position may be at an
3651  * address prior to the requested address.  mw->mw_curpos always has the actual
3652  * position of the window.
3653  */
3654 static void
3655 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3656 {
3657 	struct memwin *mw;
3658 	uint32_t pf;
3659 	uint32_t reg;
3660 
3661 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3662 	mw = &sc->memwin[idx];
3663 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3664 
3665 	if (is_t4(sc)) {
3666 		pf = 0;
3667 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3668 	} else {
3669 		pf = V_PFNUM(sc->pf);
3670 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3671 	}
3672 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3673 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3674 	t4_read_reg(sc, reg);	/* flush */
3675 }
3676 
3677 int
3678 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3679     int len, int rw)
3680 {
3681 	struct memwin *mw;
3682 	uint32_t mw_end, v;
3683 
3684 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3685 
3686 	/* Memory can only be accessed in naturally aligned 4 byte units */
3687 	if (addr & 3 || len & 3 || len <= 0)
3688 		return (EINVAL);
3689 
3690 	mw = &sc->memwin[idx];
3691 	while (len > 0) {
3692 		rw_rlock(&mw->mw_lock);
3693 		mw_end = mw->mw_curpos + mw->mw_aperture;
3694 		if (addr >= mw_end || addr < mw->mw_curpos) {
3695 			/* Will need to reposition the window */
3696 			if (!rw_try_upgrade(&mw->mw_lock)) {
3697 				rw_runlock(&mw->mw_lock);
3698 				rw_wlock(&mw->mw_lock);
3699 			}
3700 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3701 			position_memwin(sc, idx, addr);
3702 			rw_downgrade(&mw->mw_lock);
3703 			mw_end = mw->mw_curpos + mw->mw_aperture;
3704 		}
3705 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3706 		while (addr < mw_end && len > 0) {
3707 			if (rw == 0) {
3708 				v = t4_read_reg(sc, mw->mw_base + addr -
3709 				    mw->mw_curpos);
3710 				*val++ = le32toh(v);
3711 			} else {
3712 				v = *val++;
3713 				t4_write_reg(sc, mw->mw_base + addr -
3714 				    mw->mw_curpos, htole32(v));
3715 			}
3716 			addr += 4;
3717 			len -= 4;
3718 		}
3719 		rw_runlock(&mw->mw_lock);
3720 	}
3721 
3722 	return (0);
3723 }
3724 
3725 static void
3726 t4_init_atid_table(struct adapter *sc)
3727 {
3728 	struct tid_info *t;
3729 	int i;
3730 
3731 	t = &sc->tids;
3732 	if (t->natids == 0)
3733 		return;
3734 
3735 	MPASS(t->atid_tab == NULL);
3736 
3737 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3738 	    M_ZERO | M_WAITOK);
3739 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3740 	t->afree = t->atid_tab;
3741 	t->atids_in_use = 0;
3742 	for (i = 1; i < t->natids; i++)
3743 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3744 	t->atid_tab[t->natids - 1].next = NULL;
3745 }
3746 
3747 static void
3748 t4_free_atid_table(struct adapter *sc)
3749 {
3750 	struct tid_info *t;
3751 
3752 	t = &sc->tids;
3753 
3754 	KASSERT(t->atids_in_use == 0,
3755 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3756 
3757 	if (mtx_initialized(&t->atid_lock))
3758 		mtx_destroy(&t->atid_lock);
3759 	free(t->atid_tab, M_CXGBE);
3760 	t->atid_tab = NULL;
3761 }
3762 
3763 int
3764 alloc_atid(struct adapter *sc, void *ctx)
3765 {
3766 	struct tid_info *t = &sc->tids;
3767 	int atid = -1;
3768 
3769 	mtx_lock(&t->atid_lock);
3770 	if (t->afree) {
3771 		union aopen_entry *p = t->afree;
3772 
3773 		atid = p - t->atid_tab;
3774 		MPASS(atid <= M_TID_TID);
3775 		t->afree = p->next;
3776 		p->data = ctx;
3777 		t->atids_in_use++;
3778 	}
3779 	mtx_unlock(&t->atid_lock);
3780 	return (atid);
3781 }
3782 
3783 void *
3784 lookup_atid(struct adapter *sc, int atid)
3785 {
3786 	struct tid_info *t = &sc->tids;
3787 
3788 	return (t->atid_tab[atid].data);
3789 }
3790 
3791 void
3792 free_atid(struct adapter *sc, int atid)
3793 {
3794 	struct tid_info *t = &sc->tids;
3795 	union aopen_entry *p = &t->atid_tab[atid];
3796 
3797 	mtx_lock(&t->atid_lock);
3798 	p->next = t->afree;
3799 	t->afree = p;
3800 	t->atids_in_use--;
3801 	mtx_unlock(&t->atid_lock);
3802 }
3803 
3804 static void
3805 queue_tid_release(struct adapter *sc, int tid)
3806 {
3807 
3808 	CXGBE_UNIMPLEMENTED("deferred tid release");
3809 }
3810 
3811 void
3812 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
3813 {
3814 	struct wrqe *wr;
3815 	struct cpl_tid_release *req;
3816 
3817 	wr = alloc_wrqe(sizeof(*req), ctrlq);
3818 	if (wr == NULL) {
3819 		queue_tid_release(sc, tid);	/* defer */
3820 		return;
3821 	}
3822 	req = wrtod(wr);
3823 
3824 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
3825 
3826 	t4_wrq_tx(sc, wr);
3827 }
3828 
3829 static int
3830 t4_range_cmp(const void *a, const void *b)
3831 {
3832 	return ((const struct t4_range *)a)->start -
3833 	       ((const struct t4_range *)b)->start;
3834 }
3835 
3836 /*
3837  * Verify that the memory range specified by the addr/len pair is valid within
3838  * the card's address space.
3839  */
3840 static int
3841 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
3842 {
3843 	struct t4_range mem_ranges[4], *r, *next;
3844 	uint32_t em, addr_len;
3845 	int i, n, remaining;
3846 
3847 	/* Memory can only be accessed in naturally aligned 4 byte units */
3848 	if (addr & 3 || len & 3 || len == 0)
3849 		return (EINVAL);
3850 
3851 	/* Enabled memories */
3852 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
3853 
3854 	r = &mem_ranges[0];
3855 	n = 0;
3856 	bzero(r, sizeof(mem_ranges));
3857 	if (em & F_EDRAM0_ENABLE) {
3858 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
3859 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
3860 		if (r->size > 0) {
3861 			r->start = G_EDRAM0_BASE(addr_len) << 20;
3862 			if (addr >= r->start &&
3863 			    addr + len <= r->start + r->size)
3864 				return (0);
3865 			r++;
3866 			n++;
3867 		}
3868 	}
3869 	if (em & F_EDRAM1_ENABLE) {
3870 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
3871 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
3872 		if (r->size > 0) {
3873 			r->start = G_EDRAM1_BASE(addr_len) << 20;
3874 			if (addr >= r->start &&
3875 			    addr + len <= r->start + r->size)
3876 				return (0);
3877 			r++;
3878 			n++;
3879 		}
3880 	}
3881 	if (em & F_EXT_MEM_ENABLE) {
3882 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
3883 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
3884 		if (r->size > 0) {
3885 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
3886 			if (addr >= r->start &&
3887 			    addr + len <= r->start + r->size)
3888 				return (0);
3889 			r++;
3890 			n++;
3891 		}
3892 	}
3893 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
3894 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
3895 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
3896 		if (r->size > 0) {
3897 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
3898 			if (addr >= r->start &&
3899 			    addr + len <= r->start + r->size)
3900 				return (0);
3901 			r++;
3902 			n++;
3903 		}
3904 	}
3905 	MPASS(n <= nitems(mem_ranges));
3906 
3907 	if (n > 1) {
3908 		/* Sort and merge the ranges. */
3909 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
3910 
3911 		/* Start from index 0 and examine the next n - 1 entries. */
3912 		r = &mem_ranges[0];
3913 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
3914 
3915 			MPASS(r->size > 0);	/* r is a valid entry. */
3916 			next = r + 1;
3917 			MPASS(next->size > 0);	/* and so is the next one. */
3918 
3919 			while (r->start + r->size >= next->start) {
3920 				/* Merge the next one into the current entry. */
3921 				r->size = max(r->start + r->size,
3922 				    next->start + next->size) - r->start;
3923 				n--;	/* One fewer entry in total. */
3924 				if (--remaining == 0)
3925 					goto done;	/* short circuit */
3926 				next++;
3927 			}
3928 			if (next != r + 1) {
3929 				/*
3930 				 * Some entries were merged into r and next
3931 				 * points to the first valid entry that couldn't
3932 				 * be merged.
3933 				 */
3934 				MPASS(next->size > 0);	/* must be valid */
3935 				memcpy(r + 1, next, remaining * sizeof(*r));
3936 #ifdef INVARIANTS
3937 				/*
3938 				 * This so that the foo->size assertion in the
3939 				 * next iteration of the loop do the right
3940 				 * thing for entries that were pulled up and are
3941 				 * no longer valid.
3942 				 */
3943 				MPASS(n < nitems(mem_ranges));
3944 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
3945 				    sizeof(struct t4_range));
3946 #endif
3947 			}
3948 		}
3949 done:
3950 		/* Done merging the ranges. */
3951 		MPASS(n > 0);
3952 		r = &mem_ranges[0];
3953 		for (i = 0; i < n; i++, r++) {
3954 			if (addr >= r->start &&
3955 			    addr + len <= r->start + r->size)
3956 				return (0);
3957 		}
3958 	}
3959 
3960 	return (EFAULT);
3961 }
3962 
3963 static int
3964 fwmtype_to_hwmtype(int mtype)
3965 {
3966 
3967 	switch (mtype) {
3968 	case FW_MEMTYPE_EDC0:
3969 		return (MEM_EDC0);
3970 	case FW_MEMTYPE_EDC1:
3971 		return (MEM_EDC1);
3972 	case FW_MEMTYPE_EXTMEM:
3973 		return (MEM_MC0);
3974 	case FW_MEMTYPE_EXTMEM1:
3975 		return (MEM_MC1);
3976 	default:
3977 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
3978 	}
3979 }
3980 
3981 /*
3982  * Verify that the memory range specified by the memtype/offset/len pair is
3983  * valid and lies entirely within the memtype specified.  The global address of
3984  * the start of the range is returned in addr.
3985  */
3986 static int
3987 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
3988     uint32_t *addr)
3989 {
3990 	uint32_t em, addr_len, maddr;
3991 
3992 	/* Memory can only be accessed in naturally aligned 4 byte units */
3993 	if (off & 3 || len & 3 || len == 0)
3994 		return (EINVAL);
3995 
3996 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
3997 	switch (fwmtype_to_hwmtype(mtype)) {
3998 	case MEM_EDC0:
3999 		if (!(em & F_EDRAM0_ENABLE))
4000 			return (EINVAL);
4001 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4002 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4003 		break;
4004 	case MEM_EDC1:
4005 		if (!(em & F_EDRAM1_ENABLE))
4006 			return (EINVAL);
4007 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4008 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4009 		break;
4010 	case MEM_MC:
4011 		if (!(em & F_EXT_MEM_ENABLE))
4012 			return (EINVAL);
4013 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4014 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4015 		break;
4016 	case MEM_MC1:
4017 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4018 			return (EINVAL);
4019 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4020 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4021 		break;
4022 	default:
4023 		return (EINVAL);
4024 	}
4025 
4026 	*addr = maddr + off;	/* global address */
4027 	return (validate_mem_range(sc, *addr, len));
4028 }
4029 
4030 static int
4031 fixup_devlog_params(struct adapter *sc)
4032 {
4033 	struct devlog_params *dparams = &sc->params.devlog;
4034 	int rc;
4035 
4036 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4037 	    dparams->size, &dparams->addr);
4038 
4039 	return (rc);
4040 }
4041 
4042 static void
4043 update_nirq(struct intrs_and_queues *iaq, int nports)
4044 {
4045 
4046 	iaq->nirq = T4_EXTRA_INTR;
4047 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4048 	iaq->nirq += nports * iaq->nofldrxq;
4049 	iaq->nirq += nports * (iaq->num_vis - 1) *
4050 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4051 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4052 }
4053 
4054 /*
4055  * Adjust requirements to fit the number of interrupts available.
4056  */
4057 static void
4058 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4059     int navail)
4060 {
4061 	int old_nirq;
4062 	const int nports = sc->params.nports;
4063 
4064 	MPASS(nports > 0);
4065 	MPASS(navail > 0);
4066 
4067 	bzero(iaq, sizeof(*iaq));
4068 	iaq->intr_type = itype;
4069 	iaq->num_vis = t4_num_vis;
4070 	iaq->ntxq = t4_ntxq;
4071 	iaq->ntxq_vi = t4_ntxq_vi;
4072 	iaq->nrxq = t4_nrxq;
4073 	iaq->nrxq_vi = t4_nrxq_vi;
4074 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4075 	if (is_offload(sc) || is_ethoffload(sc)) {
4076 		iaq->nofldtxq = t4_nofldtxq;
4077 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4078 	}
4079 #endif
4080 #ifdef TCP_OFFLOAD
4081 	if (is_offload(sc)) {
4082 		iaq->nofldrxq = t4_nofldrxq;
4083 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4084 	}
4085 #endif
4086 #ifdef DEV_NETMAP
4087 	if (t4_native_netmap & NN_MAIN_VI) {
4088 		iaq->nnmtxq = t4_nnmtxq;
4089 		iaq->nnmrxq = t4_nnmrxq;
4090 	}
4091 	if (t4_native_netmap & NN_EXTRA_VI) {
4092 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4093 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4094 	}
4095 #endif
4096 
4097 	update_nirq(iaq, nports);
4098 	if (iaq->nirq <= navail &&
4099 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4100 		/*
4101 		 * This is the normal case -- there are enough interrupts for
4102 		 * everything.
4103 		 */
4104 		goto done;
4105 	}
4106 
4107 	/*
4108 	 * If extra VIs have been configured try reducing their count and see if
4109 	 * that works.
4110 	 */
4111 	while (iaq->num_vis > 1) {
4112 		iaq->num_vis--;
4113 		update_nirq(iaq, nports);
4114 		if (iaq->nirq <= navail &&
4115 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4116 			device_printf(sc->dev, "virtual interfaces per port "
4117 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4118 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4119 			    "itype %d, navail %u, nirq %d.\n",
4120 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4121 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4122 			    itype, navail, iaq->nirq);
4123 			goto done;
4124 		}
4125 	}
4126 
4127 	/*
4128 	 * Extra VIs will not be created.  Log a message if they were requested.
4129 	 */
4130 	MPASS(iaq->num_vis == 1);
4131 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4132 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4133 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4134 	if (iaq->num_vis != t4_num_vis) {
4135 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4136 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4137 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4138 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4139 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4140 	}
4141 
4142 	/*
4143 	 * Keep reducing the number of NIC rx queues to the next lower power of
4144 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4145 	 * if that works.
4146 	 */
4147 	do {
4148 		if (iaq->nrxq > 1) {
4149 			do {
4150 				iaq->nrxq--;
4151 			} while (!powerof2(iaq->nrxq));
4152 			if (iaq->nnmrxq > iaq->nrxq)
4153 				iaq->nnmrxq = iaq->nrxq;
4154 		}
4155 		if (iaq->nofldrxq > 1)
4156 			iaq->nofldrxq >>= 1;
4157 
4158 		old_nirq = iaq->nirq;
4159 		update_nirq(iaq, nports);
4160 		if (iaq->nirq <= navail &&
4161 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4162 			device_printf(sc->dev, "running with reduced number of "
4163 			    "rx queues because of shortage of interrupts.  "
4164 			    "nrxq=%u, nofldrxq=%u.  "
4165 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4166 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4167 			goto done;
4168 		}
4169 	} while (old_nirq != iaq->nirq);
4170 
4171 	/* One interrupt for everything.  Ugh. */
4172 	device_printf(sc->dev, "running with minimal number of queues.  "
4173 	    "itype %d, navail %u.\n", itype, navail);
4174 	iaq->nirq = 1;
4175 	iaq->nrxq = 1;
4176 	iaq->ntxq = 1;
4177 	if (iaq->nofldrxq > 0) {
4178 		iaq->nofldrxq = 1;
4179 		iaq->nofldtxq = 1;
4180 	}
4181 	iaq->nnmtxq = 0;
4182 	iaq->nnmrxq = 0;
4183 done:
4184 	MPASS(iaq->num_vis > 0);
4185 	if (iaq->num_vis > 1) {
4186 		MPASS(iaq->nrxq_vi > 0);
4187 		MPASS(iaq->ntxq_vi > 0);
4188 	}
4189 	MPASS(iaq->nirq > 0);
4190 	MPASS(iaq->nrxq > 0);
4191 	MPASS(iaq->ntxq > 0);
4192 	if (itype == INTR_MSI) {
4193 		MPASS(powerof2(iaq->nirq));
4194 	}
4195 }
4196 
4197 static int
4198 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4199 {
4200 	int rc, itype, navail, nalloc;
4201 
4202 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4203 
4204 		if ((itype & t4_intr_types) == 0)
4205 			continue;	/* not allowed */
4206 
4207 		if (itype == INTR_MSIX)
4208 			navail = pci_msix_count(sc->dev);
4209 		else if (itype == INTR_MSI)
4210 			navail = pci_msi_count(sc->dev);
4211 		else
4212 			navail = 1;
4213 restart:
4214 		if (navail == 0)
4215 			continue;
4216 
4217 		calculate_iaq(sc, iaq, itype, navail);
4218 		nalloc = iaq->nirq;
4219 		rc = 0;
4220 		if (itype == INTR_MSIX)
4221 			rc = pci_alloc_msix(sc->dev, &nalloc);
4222 		else if (itype == INTR_MSI)
4223 			rc = pci_alloc_msi(sc->dev, &nalloc);
4224 
4225 		if (rc == 0 && nalloc > 0) {
4226 			if (nalloc == iaq->nirq)
4227 				return (0);
4228 
4229 			/*
4230 			 * Didn't get the number requested.  Use whatever number
4231 			 * the kernel is willing to allocate.
4232 			 */
4233 			device_printf(sc->dev, "fewer vectors than requested, "
4234 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4235 			    itype, iaq->nirq, nalloc);
4236 			pci_release_msi(sc->dev);
4237 			navail = nalloc;
4238 			goto restart;
4239 		}
4240 
4241 		device_printf(sc->dev,
4242 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4243 		    itype, rc, iaq->nirq, nalloc);
4244 	}
4245 
4246 	device_printf(sc->dev,
4247 	    "failed to find a usable interrupt type.  "
4248 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4249 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4250 
4251 	return (ENXIO);
4252 }
4253 
4254 #define FW_VERSION(chip) ( \
4255     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4256     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4257     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4258     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4259 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4260 
4261 /* Just enough of fw_hdr to cover all version info. */
4262 struct fw_h {
4263 	__u8	ver;
4264 	__u8	chip;
4265 	__be16	len512;
4266 	__be32	fw_ver;
4267 	__be32	tp_microcode_ver;
4268 	__u8	intfver_nic;
4269 	__u8	intfver_vnic;
4270 	__u8	intfver_ofld;
4271 	__u8	intfver_ri;
4272 	__u8	intfver_iscsipdu;
4273 	__u8	intfver_iscsi;
4274 	__u8	intfver_fcoepdu;
4275 	__u8	intfver_fcoe;
4276 };
4277 /* Spot check a couple of fields. */
4278 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4279 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4280 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4281 
4282 struct fw_info {
4283 	uint8_t chip;
4284 	char *kld_name;
4285 	char *fw_mod_name;
4286 	struct fw_h fw_h;
4287 } fw_info[] = {
4288 	{
4289 		.chip = CHELSIO_T4,
4290 		.kld_name = "t4fw_cfg",
4291 		.fw_mod_name = "t4fw",
4292 		.fw_h = {
4293 			.chip = FW_HDR_CHIP_T4,
4294 			.fw_ver = htobe32(FW_VERSION(T4)),
4295 			.intfver_nic = FW_INTFVER(T4, NIC),
4296 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4297 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4298 			.intfver_ri = FW_INTFVER(T4, RI),
4299 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4300 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4301 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4302 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4303 		},
4304 	}, {
4305 		.chip = CHELSIO_T5,
4306 		.kld_name = "t5fw_cfg",
4307 		.fw_mod_name = "t5fw",
4308 		.fw_h = {
4309 			.chip = FW_HDR_CHIP_T5,
4310 			.fw_ver = htobe32(FW_VERSION(T5)),
4311 			.intfver_nic = FW_INTFVER(T5, NIC),
4312 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4313 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4314 			.intfver_ri = FW_INTFVER(T5, RI),
4315 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4316 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4317 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4318 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4319 		},
4320 	}, {
4321 		.chip = CHELSIO_T6,
4322 		.kld_name = "t6fw_cfg",
4323 		.fw_mod_name = "t6fw",
4324 		.fw_h = {
4325 			.chip = FW_HDR_CHIP_T6,
4326 			.fw_ver = htobe32(FW_VERSION(T6)),
4327 			.intfver_nic = FW_INTFVER(T6, NIC),
4328 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4329 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4330 			.intfver_ri = FW_INTFVER(T6, RI),
4331 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4332 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4333 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4334 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4335 		},
4336 	}
4337 };
4338 
4339 static struct fw_info *
4340 find_fw_info(int chip)
4341 {
4342 	int i;
4343 
4344 	for (i = 0; i < nitems(fw_info); i++) {
4345 		if (fw_info[i].chip == chip)
4346 			return (&fw_info[i]);
4347 	}
4348 	return (NULL);
4349 }
4350 
4351 /*
4352  * Is the given firmware API compatible with the one the driver was compiled
4353  * with?
4354  */
4355 static int
4356 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4357 {
4358 
4359 	/* short circuit if it's the exact same firmware version */
4360 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4361 		return (1);
4362 
4363 	/*
4364 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4365 	 * features that are supported in the driver.
4366 	 */
4367 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4368 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4369 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4370 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4371 		return (1);
4372 #undef SAME_INTF
4373 
4374 	return (0);
4375 }
4376 
4377 static int
4378 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4379     const struct firmware **fw)
4380 {
4381 	struct fw_info *fw_info;
4382 
4383 	*dcfg = NULL;
4384 	if (fw != NULL)
4385 		*fw = NULL;
4386 
4387 	fw_info = find_fw_info(chip_id(sc));
4388 	if (fw_info == NULL) {
4389 		device_printf(sc->dev,
4390 		    "unable to look up firmware information for chip %d.\n",
4391 		    chip_id(sc));
4392 		return (EINVAL);
4393 	}
4394 
4395 	*dcfg = firmware_get(fw_info->kld_name);
4396 	if (*dcfg != NULL) {
4397 		if (fw != NULL)
4398 			*fw = firmware_get(fw_info->fw_mod_name);
4399 		return (0);
4400 	}
4401 
4402 	return (ENOENT);
4403 }
4404 
4405 static void
4406 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4407     const struct firmware *fw)
4408 {
4409 
4410 	if (fw != NULL)
4411 		firmware_put(fw, FIRMWARE_UNLOAD);
4412 	if (dcfg != NULL)
4413 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4414 }
4415 
4416 /*
4417  * Return values:
4418  * 0 means no firmware install attempted.
4419  * ERESTART means a firmware install was attempted and was successful.
4420  * +ve errno means a firmware install was attempted but failed.
4421  */
4422 static int
4423 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4424     const struct fw_h *drv_fw, const char *reason, int *already)
4425 {
4426 	const struct firmware *cfg, *fw;
4427 	const uint32_t c = be32toh(card_fw->fw_ver);
4428 	uint32_t d, k;
4429 	int rc, fw_install;
4430 	struct fw_h bundled_fw;
4431 	bool load_attempted;
4432 
4433 	cfg = fw = NULL;
4434 	load_attempted = false;
4435 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4436 
4437 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4438 	if (t4_fw_install < 0) {
4439 		rc = load_fw_module(sc, &cfg, &fw);
4440 		if (rc != 0 || fw == NULL) {
4441 			device_printf(sc->dev,
4442 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4443 			    " will use compiled-in firmware version for"
4444 			    "hw.cxgbe.fw_install checks.\n",
4445 			    rc, cfg, fw);
4446 		} else {
4447 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4448 		}
4449 		load_attempted = true;
4450 	}
4451 	d = be32toh(bundled_fw.fw_ver);
4452 
4453 	if (reason != NULL)
4454 		goto install;
4455 
4456 	if ((sc->flags & FW_OK) == 0) {
4457 
4458 		if (c == 0xffffffff) {
4459 			reason = "missing";
4460 			goto install;
4461 		}
4462 
4463 		rc = 0;
4464 		goto done;
4465 	}
4466 
4467 	if (!fw_compatible(card_fw, &bundled_fw)) {
4468 		reason = "incompatible or unusable";
4469 		goto install;
4470 	}
4471 
4472 	if (d > c) {
4473 		reason = "older than the version bundled with this driver";
4474 		goto install;
4475 	}
4476 
4477 	if (fw_install == 2 && d != c) {
4478 		reason = "different than the version bundled with this driver";
4479 		goto install;
4480 	}
4481 
4482 	/* No reason to do anything to the firmware already on the card. */
4483 	rc = 0;
4484 	goto done;
4485 
4486 install:
4487 	rc = 0;
4488 	if ((*already)++)
4489 		goto done;
4490 
4491 	if (fw_install == 0) {
4492 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4493 		    "but the driver is prohibited from installing a firmware "
4494 		    "on the card.\n",
4495 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4496 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4497 
4498 		goto done;
4499 	}
4500 
4501 	/*
4502 	 * We'll attempt to install a firmware.  Load the module first (if it
4503 	 * hasn't been loaded already).
4504 	 */
4505 	if (!load_attempted) {
4506 		rc = load_fw_module(sc, &cfg, &fw);
4507 		if (rc != 0 || fw == NULL) {
4508 			device_printf(sc->dev,
4509 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4510 			    rc, cfg, fw);
4511 			/* carry on */
4512 		}
4513 	}
4514 	if (fw == NULL) {
4515 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4516 		    "but the driver cannot take corrective action because it "
4517 		    "is unable to load the firmware module.\n",
4518 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4519 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4520 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4521 		goto done;
4522 	}
4523 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4524 	if (k != d) {
4525 		MPASS(t4_fw_install > 0);
4526 		device_printf(sc->dev,
4527 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4528 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4529 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4530 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4531 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4532 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4533 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4534 		goto done;
4535 	}
4536 
4537 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4538 	    "installing firmware %u.%u.%u.%u on card.\n",
4539 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4540 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4541 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4542 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4543 
4544 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4545 	if (rc != 0) {
4546 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4547 	} else {
4548 		/* Installed successfully, update the cached header too. */
4549 		rc = ERESTART;
4550 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4551 	}
4552 done:
4553 	unload_fw_module(sc, cfg, fw);
4554 
4555 	return (rc);
4556 }
4557 
4558 /*
4559  * Establish contact with the firmware and attempt to become the master driver.
4560  *
4561  * A firmware will be installed to the card if needed (if the driver is allowed
4562  * to do so).
4563  */
4564 static int
4565 contact_firmware(struct adapter *sc)
4566 {
4567 	int rc, already = 0;
4568 	enum dev_state state;
4569 	struct fw_info *fw_info;
4570 	struct fw_hdr *card_fw;		/* fw on the card */
4571 	const struct fw_h *drv_fw;
4572 
4573 	fw_info = find_fw_info(chip_id(sc));
4574 	if (fw_info == NULL) {
4575 		device_printf(sc->dev,
4576 		    "unable to look up firmware information for chip %d.\n",
4577 		    chip_id(sc));
4578 		return (EINVAL);
4579 	}
4580 	drv_fw = &fw_info->fw_h;
4581 
4582 	/* Read the header of the firmware on the card */
4583 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4584 restart:
4585 	rc = -t4_get_fw_hdr(sc, card_fw);
4586 	if (rc != 0) {
4587 		device_printf(sc->dev,
4588 		    "unable to read firmware header from card's flash: %d\n",
4589 		    rc);
4590 		goto done;
4591 	}
4592 
4593 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4594 	    &already);
4595 	if (rc == ERESTART)
4596 		goto restart;
4597 	if (rc != 0)
4598 		goto done;
4599 
4600 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4601 	if (rc < 0 || state == DEV_STATE_ERR) {
4602 		rc = -rc;
4603 		device_printf(sc->dev,
4604 		    "failed to connect to the firmware: %d, %d.  "
4605 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4606 #if 0
4607 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4608 		    "not responding properly to HELLO", &already) == ERESTART)
4609 			goto restart;
4610 #endif
4611 		goto done;
4612 	}
4613 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4614 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4615 
4616 	if (rc == sc->pf) {
4617 		sc->flags |= MASTER_PF;
4618 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4619 		    NULL, &already);
4620 		if (rc == ERESTART)
4621 			rc = 0;
4622 		else if (rc != 0)
4623 			goto done;
4624 	} else if (state == DEV_STATE_UNINIT) {
4625 		/*
4626 		 * We didn't get to be the master so we definitely won't be
4627 		 * configuring the chip.  It's a bug if someone else hasn't
4628 		 * configured it already.
4629 		 */
4630 		device_printf(sc->dev, "couldn't be master(%d), "
4631 		    "device not already initialized either(%d).  "
4632 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4633 		rc = EPROTO;
4634 		goto done;
4635 	} else {
4636 		/*
4637 		 * Some other PF is the master and has configured the chip.
4638 		 * This is allowed but untested.
4639 		 */
4640 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4641 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4642 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4643 		sc->cfcsum = 0;
4644 		rc = 0;
4645 	}
4646 done:
4647 	if (rc != 0 && sc->flags & FW_OK) {
4648 		t4_fw_bye(sc, sc->mbox);
4649 		sc->flags &= ~FW_OK;
4650 	}
4651 	free(card_fw, M_CXGBE);
4652 	return (rc);
4653 }
4654 
4655 static int
4656 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4657     uint32_t mtype, uint32_t moff)
4658 {
4659 	struct fw_info *fw_info;
4660 	const struct firmware *dcfg, *rcfg = NULL;
4661 	const uint32_t *cfdata;
4662 	uint32_t cflen, addr;
4663 	int rc;
4664 
4665 	load_fw_module(sc, &dcfg, NULL);
4666 
4667 	/* Card specific interpretation of "default". */
4668 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4669 		if (pci_get_device(sc->dev) == 0x440a)
4670 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4671 		if (is_fpga(sc))
4672 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4673 	}
4674 
4675 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4676 		if (dcfg == NULL) {
4677 			device_printf(sc->dev,
4678 			    "KLD with default config is not available.\n");
4679 			rc = ENOENT;
4680 			goto done;
4681 		}
4682 		cfdata = dcfg->data;
4683 		cflen = dcfg->datasize & ~3;
4684 	} else {
4685 		char s[32];
4686 
4687 		fw_info = find_fw_info(chip_id(sc));
4688 		if (fw_info == NULL) {
4689 			device_printf(sc->dev,
4690 			    "unable to look up firmware information for chip %d.\n",
4691 			    chip_id(sc));
4692 			rc = EINVAL;
4693 			goto done;
4694 		}
4695 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4696 
4697 		rcfg = firmware_get(s);
4698 		if (rcfg == NULL) {
4699 			device_printf(sc->dev,
4700 			    "unable to load module \"%s\" for configuration "
4701 			    "profile \"%s\".\n", s, cfg_file);
4702 			rc = ENOENT;
4703 			goto done;
4704 		}
4705 		cfdata = rcfg->data;
4706 		cflen = rcfg->datasize & ~3;
4707 	}
4708 
4709 	if (cflen > FLASH_CFG_MAX_SIZE) {
4710 		device_printf(sc->dev,
4711 		    "config file too long (%d, max allowed is %d).\n",
4712 		    cflen, FLASH_CFG_MAX_SIZE);
4713 		rc = EINVAL;
4714 		goto done;
4715 	}
4716 
4717 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4718 	if (rc != 0) {
4719 		device_printf(sc->dev,
4720 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4721 		    __func__, mtype, moff, cflen, rc);
4722 		rc = EINVAL;
4723 		goto done;
4724 	}
4725 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4726 done:
4727 	if (rcfg != NULL)
4728 		firmware_put(rcfg, FIRMWARE_UNLOAD);
4729 	unload_fw_module(sc, dcfg, NULL);
4730 	return (rc);
4731 }
4732 
4733 struct caps_allowed {
4734 	uint16_t nbmcaps;
4735 	uint16_t linkcaps;
4736 	uint16_t switchcaps;
4737 	uint16_t niccaps;
4738 	uint16_t toecaps;
4739 	uint16_t rdmacaps;
4740 	uint16_t cryptocaps;
4741 	uint16_t iscsicaps;
4742 	uint16_t fcoecaps;
4743 };
4744 
4745 #define FW_PARAM_DEV(param) \
4746 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4747 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4748 #define FW_PARAM_PFVF(param) \
4749 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4750 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4751 
4752 /*
4753  * Provide a configuration profile to the firmware and have it initialize the
4754  * chip accordingly.  This may involve uploading a configuration file to the
4755  * card.
4756  */
4757 static int
4758 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4759     const struct caps_allowed *caps_allowed)
4760 {
4761 	int rc;
4762 	struct fw_caps_config_cmd caps;
4763 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
4764 
4765 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4766 	if (rc != 0) {
4767 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
4768 		return (rc);
4769 	}
4770 
4771 	bzero(&caps, sizeof(caps));
4772 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4773 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
4774 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
4775 		mtype = 0;
4776 		moff = 0;
4777 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4778 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
4779 		mtype = FW_MEMTYPE_FLASH;
4780 		moff = t4_flash_cfg_addr(sc);
4781 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4782 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4783 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4784 		    FW_LEN16(caps));
4785 	} else {
4786 		/*
4787 		 * Ask the firmware where it wants us to upload the config file.
4788 		 */
4789 		param = FW_PARAM_DEV(CF);
4790 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4791 		if (rc != 0) {
4792 			/* No support for config file?  Shouldn't happen. */
4793 			device_printf(sc->dev,
4794 			    "failed to query config file location: %d.\n", rc);
4795 			goto done;
4796 		}
4797 		mtype = G_FW_PARAMS_PARAM_Y(val);
4798 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
4799 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4800 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4801 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4802 		    FW_LEN16(caps));
4803 
4804 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
4805 		if (rc != 0) {
4806 			device_printf(sc->dev,
4807 			    "failed to upload config file to card: %d.\n", rc);
4808 			goto done;
4809 		}
4810 	}
4811 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
4812 	if (rc != 0) {
4813 		device_printf(sc->dev, "failed to pre-process config file: %d "
4814 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
4815 		goto done;
4816 	}
4817 
4818 	finicsum = be32toh(caps.finicsum);
4819 	cfcsum = be32toh(caps.cfcsum);	/* actual */
4820 	if (finicsum != cfcsum) {
4821 		device_printf(sc->dev,
4822 		    "WARNING: config file checksum mismatch: %08x %08x\n",
4823 		    finicsum, cfcsum);
4824 	}
4825 	sc->cfcsum = cfcsum;
4826 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
4827 
4828 	/*
4829 	 * Let the firmware know what features will (not) be used so it can tune
4830 	 * things accordingly.
4831 	 */
4832 #define LIMIT_CAPS(x) do { \
4833 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
4834 } while (0)
4835 	LIMIT_CAPS(nbm);
4836 	LIMIT_CAPS(link);
4837 	LIMIT_CAPS(switch);
4838 	LIMIT_CAPS(nic);
4839 	LIMIT_CAPS(toe);
4840 	LIMIT_CAPS(rdma);
4841 	LIMIT_CAPS(crypto);
4842 	LIMIT_CAPS(iscsi);
4843 	LIMIT_CAPS(fcoe);
4844 #undef LIMIT_CAPS
4845 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
4846 		/*
4847 		 * TOE and hashfilters are mutually exclusive.  It is a config
4848 		 * file or firmware bug if both are reported as available.  Try
4849 		 * to cope with the situation in non-debug builds by disabling
4850 		 * TOE.
4851 		 */
4852 		MPASS(caps.toecaps == 0);
4853 
4854 		caps.toecaps = 0;
4855 		caps.rdmacaps = 0;
4856 		caps.iscsicaps = 0;
4857 	}
4858 
4859 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4860 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
4861 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4862 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
4863 	if (rc != 0) {
4864 		device_printf(sc->dev,
4865 		    "failed to process config file: %d.\n", rc);
4866 		goto done;
4867 	}
4868 
4869 	t4_tweak_chip_settings(sc);
4870 	set_params__pre_init(sc);
4871 
4872 	/* get basic stuff going */
4873 	rc = -t4_fw_initialize(sc, sc->mbox);
4874 	if (rc != 0) {
4875 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
4876 		goto done;
4877 	}
4878 done:
4879 	return (rc);
4880 }
4881 
4882 /*
4883  * Partition chip resources for use between various PFs, VFs, etc.
4884  */
4885 static int
4886 partition_resources(struct adapter *sc)
4887 {
4888 	char cfg_file[sizeof(t4_cfg_file)];
4889 	struct caps_allowed caps_allowed;
4890 	int rc;
4891 	bool fallback;
4892 
4893 	/* Only the master driver gets to configure the chip resources. */
4894 	MPASS(sc->flags & MASTER_PF);
4895 
4896 #define COPY_CAPS(x) do { \
4897 	caps_allowed.x##caps = t4_##x##caps_allowed; \
4898 } while (0)
4899 	bzero(&caps_allowed, sizeof(caps_allowed));
4900 	COPY_CAPS(nbm);
4901 	COPY_CAPS(link);
4902 	COPY_CAPS(switch);
4903 	COPY_CAPS(nic);
4904 	COPY_CAPS(toe);
4905 	COPY_CAPS(rdma);
4906 	COPY_CAPS(crypto);
4907 	COPY_CAPS(iscsi);
4908 	COPY_CAPS(fcoe);
4909 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
4910 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
4911 retry:
4912 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
4913 	if (rc != 0 && fallback) {
4914 		device_printf(sc->dev,
4915 		    "failed (%d) to configure card with \"%s\" profile, "
4916 		    "will fall back to a basic configuration and retry.\n",
4917 		    rc, cfg_file);
4918 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
4919 		bzero(&caps_allowed, sizeof(caps_allowed));
4920 		COPY_CAPS(switch);
4921 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
4922 		fallback = false;
4923 		goto retry;
4924 	}
4925 #undef COPY_CAPS
4926 	return (rc);
4927 }
4928 
4929 /*
4930  * Retrieve parameters that are needed (or nice to have) very early.
4931  */
4932 static int
4933 get_params__pre_init(struct adapter *sc)
4934 {
4935 	int rc;
4936 	uint32_t param[2], val[2];
4937 
4938 	t4_get_version_info(sc);
4939 
4940 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
4941 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
4942 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
4943 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
4944 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
4945 
4946 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
4947 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
4948 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
4949 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
4950 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
4951 
4952 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
4953 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
4954 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
4955 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
4956 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
4957 
4958 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
4959 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
4960 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
4961 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
4962 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
4963 
4964 	param[0] = FW_PARAM_DEV(PORTVEC);
4965 	param[1] = FW_PARAM_DEV(CCLK);
4966 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4967 	if (rc != 0) {
4968 		device_printf(sc->dev,
4969 		    "failed to query parameters (pre_init): %d.\n", rc);
4970 		return (rc);
4971 	}
4972 
4973 	sc->params.portvec = val[0];
4974 	sc->params.nports = bitcount32(val[0]);
4975 	sc->params.vpd.cclk = val[1];
4976 
4977 	/* Read device log parameters. */
4978 	rc = -t4_init_devlog_params(sc, 1);
4979 	if (rc == 0)
4980 		fixup_devlog_params(sc);
4981 	else {
4982 		device_printf(sc->dev,
4983 		    "failed to get devlog parameters: %d.\n", rc);
4984 		rc = 0;	/* devlog isn't critical for device operation */
4985 	}
4986 
4987 	return (rc);
4988 }
4989 
4990 /*
4991  * Any params that need to be set before FW_INITIALIZE.
4992  */
4993 static int
4994 set_params__pre_init(struct adapter *sc)
4995 {
4996 	int rc = 0;
4997 	uint32_t param, val;
4998 
4999 	if (chip_id(sc) >= CHELSIO_T6) {
5000 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5001 		val = 1;
5002 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5003 		/* firmwares < 1.20.1.0 do not have this param. */
5004 		if (rc == FW_EINVAL &&
5005 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5006 			rc = 0;
5007 		}
5008 		if (rc != 0) {
5009 			device_printf(sc->dev,
5010 			    "failed to enable high priority filters :%d.\n",
5011 			    rc);
5012 		}
5013 	}
5014 
5015 	/* Enable opaque VIIDs with firmwares that support it. */
5016 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5017 	val = 1;
5018 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5019 	if (rc == 0 && val == 1)
5020 		sc->params.viid_smt_extn_support = true;
5021 	else
5022 		sc->params.viid_smt_extn_support = false;
5023 
5024 	return (rc);
5025 }
5026 
5027 /*
5028  * Retrieve various parameters that are of interest to the driver.  The device
5029  * has been initialized by the firmware at this point.
5030  */
5031 static int
5032 get_params__post_init(struct adapter *sc)
5033 {
5034 	int rc;
5035 	uint32_t param[7], val[7];
5036 	struct fw_caps_config_cmd caps;
5037 
5038 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5039 	param[1] = FW_PARAM_PFVF(EQ_START);
5040 	param[2] = FW_PARAM_PFVF(FILTER_START);
5041 	param[3] = FW_PARAM_PFVF(FILTER_END);
5042 	param[4] = FW_PARAM_PFVF(L2T_START);
5043 	param[5] = FW_PARAM_PFVF(L2T_END);
5044 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5045 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5046 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5047 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5048 	if (rc != 0) {
5049 		device_printf(sc->dev,
5050 		    "failed to query parameters (post_init): %d.\n", rc);
5051 		return (rc);
5052 	}
5053 
5054 	sc->sge.iq_start = val[0];
5055 	sc->sge.eq_start = val[1];
5056 	if ((int)val[3] > (int)val[2]) {
5057 		sc->tids.ftid_base = val[2];
5058 		sc->tids.ftid_end = val[3];
5059 		sc->tids.nftids = val[3] - val[2] + 1;
5060 	}
5061 	sc->vres.l2t.start = val[4];
5062 	sc->vres.l2t.size = val[5] - val[4] + 1;
5063 	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
5064 	    ("%s: L2 table size (%u) larger than expected (%u)",
5065 	    __func__, sc->vres.l2t.size, L2T_SIZE));
5066 	sc->params.core_vdd = val[6];
5067 
5068 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5069 	param[1] = FW_PARAM_PFVF(EQ_END);
5070 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5071 	if (rc != 0) {
5072 		device_printf(sc->dev,
5073 		    "failed to query parameters (post_init2): %d.\n", rc);
5074 		return (rc);
5075 	}
5076 	MPASS((int)val[0] >= sc->sge.iq_start);
5077 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5078 	MPASS((int)val[1] >= sc->sge.eq_start);
5079 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5080 
5081 	if (chip_id(sc) >= CHELSIO_T6) {
5082 
5083 		sc->tids.tid_base = t4_read_reg(sc,
5084 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5085 
5086 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5087 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5088 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5089 		if (rc != 0) {
5090 			device_printf(sc->dev,
5091 			   "failed to query hpfilter parameters: %d.\n", rc);
5092 			return (rc);
5093 		}
5094 		if ((int)val[1] > (int)val[0]) {
5095 			sc->tids.hpftid_base = val[0];
5096 			sc->tids.hpftid_end = val[1];
5097 			sc->tids.nhpftids = val[1] - val[0] + 1;
5098 
5099 			/*
5100 			 * These should go off if the layout changes and the
5101 			 * driver needs to catch up.
5102 			 */
5103 			MPASS(sc->tids.hpftid_base == 0);
5104 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5105 		}
5106 
5107 		param[0] = FW_PARAM_PFVF(RAWF_START);
5108 		param[1] = FW_PARAM_PFVF(RAWF_END);
5109 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5110 		if (rc != 0) {
5111 			device_printf(sc->dev,
5112 			   "failed to query rawf parameters: %d.\n", rc);
5113 			return (rc);
5114 		}
5115 		if ((int)val[1] > (int)val[0]) {
5116 			sc->rawf_base = val[0];
5117 			sc->nrawf = val[1] - val[0] + 1;
5118 		}
5119 	}
5120 
5121 	/*
5122 	 * MPSBGMAP is queried separately because only recent firmwares support
5123 	 * it as a parameter and we don't want the compound query above to fail
5124 	 * on older firmwares.
5125 	 */
5126 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5127 	val[0] = 0;
5128 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5129 	if (rc == 0)
5130 		sc->params.mps_bg_map = val[0];
5131 	else
5132 		sc->params.mps_bg_map = 0;
5133 
5134 	/*
5135 	 * Determine whether the firmware supports the filter2 work request.
5136 	 * This is queried separately for the same reason as MPSBGMAP above.
5137 	 */
5138 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5139 	val[0] = 0;
5140 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5141 	if (rc == 0)
5142 		sc->params.filter2_wr_support = val[0] != 0;
5143 	else
5144 		sc->params.filter2_wr_support = 0;
5145 
5146 	/*
5147 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5148 	 * This is queried separately for the same reason as other params above.
5149 	 */
5150 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5151 	val[0] = 0;
5152 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5153 	if (rc == 0)
5154 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5155 	else
5156 		sc->params.ulptx_memwrite_dsgl = false;
5157 
5158 	/* FW_RI_FR_NSMR_TPTE_WR support */
5159 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5160 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5161 	if (rc == 0)
5162 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5163 	else
5164 		sc->params.fr_nsmr_tpte_wr_support = false;
5165 
5166 	/* Support for 512 SGL entries per FR MR. */
5167 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5168 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5169 	if (rc == 0)
5170 		sc->params.dev_512sgl_mr = val[0] != 0;
5171 	else
5172 		sc->params.dev_512sgl_mr = false;
5173 
5174 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5175 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5176 	if (rc == 0)
5177 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5178 	else
5179 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5180 
5181 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5182 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5183 	if (rc == 0) {
5184 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5185 		sc->params.nsched_cls = val[0];
5186 	} else
5187 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5188 
5189 	/* get capabilites */
5190 	bzero(&caps, sizeof(caps));
5191 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5192 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5193 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5194 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5195 	if (rc != 0) {
5196 		device_printf(sc->dev,
5197 		    "failed to get card capabilities: %d.\n", rc);
5198 		return (rc);
5199 	}
5200 
5201 #define READ_CAPS(x) do { \
5202 	sc->x = htobe16(caps.x); \
5203 } while (0)
5204 	READ_CAPS(nbmcaps);
5205 	READ_CAPS(linkcaps);
5206 	READ_CAPS(switchcaps);
5207 	READ_CAPS(niccaps);
5208 	READ_CAPS(toecaps);
5209 	READ_CAPS(rdmacaps);
5210 	READ_CAPS(cryptocaps);
5211 	READ_CAPS(iscsicaps);
5212 	READ_CAPS(fcoecaps);
5213 
5214 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5215 		MPASS(chip_id(sc) > CHELSIO_T4);
5216 		MPASS(sc->toecaps == 0);
5217 		sc->toecaps = 0;
5218 
5219 		param[0] = FW_PARAM_DEV(NTID);
5220 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5221 		if (rc != 0) {
5222 			device_printf(sc->dev,
5223 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5224 			return (rc);
5225 		}
5226 		sc->tids.ntids = val[0];
5227 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5228 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5229 			sc->tids.ntids -= sc->tids.nhpftids;
5230 		}
5231 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5232 		sc->params.hash_filter = 1;
5233 	}
5234 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5235 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5236 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5237 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5238 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5239 		if (rc != 0) {
5240 			device_printf(sc->dev,
5241 			    "failed to query NIC parameters: %d.\n", rc);
5242 			return (rc);
5243 		}
5244 		if ((int)val[1] > (int)val[0]) {
5245 			sc->tids.etid_base = val[0];
5246 			sc->tids.etid_end = val[1];
5247 			sc->tids.netids = val[1] - val[0] + 1;
5248 			sc->params.eo_wr_cred = val[2];
5249 			sc->params.ethoffload = 1;
5250 		}
5251 	}
5252 	if (sc->toecaps) {
5253 		/* query offload-related parameters */
5254 		param[0] = FW_PARAM_DEV(NTID);
5255 		param[1] = FW_PARAM_PFVF(SERVER_START);
5256 		param[2] = FW_PARAM_PFVF(SERVER_END);
5257 		param[3] = FW_PARAM_PFVF(TDDP_START);
5258 		param[4] = FW_PARAM_PFVF(TDDP_END);
5259 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5260 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5261 		if (rc != 0) {
5262 			device_printf(sc->dev,
5263 			    "failed to query TOE parameters: %d.\n", rc);
5264 			return (rc);
5265 		}
5266 		sc->tids.ntids = val[0];
5267 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5268 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5269 			sc->tids.ntids -= sc->tids.nhpftids;
5270 		}
5271 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5272 		if ((int)val[2] > (int)val[1]) {
5273 			sc->tids.stid_base = val[1];
5274 			sc->tids.nstids = val[2] - val[1] + 1;
5275 		}
5276 		sc->vres.ddp.start = val[3];
5277 		sc->vres.ddp.size = val[4] - val[3] + 1;
5278 		sc->params.ofldq_wr_cred = val[5];
5279 		sc->params.offload = 1;
5280 	} else {
5281 		/*
5282 		 * The firmware attempts memfree TOE configuration for -SO cards
5283 		 * and will report toecaps=0 if it runs out of resources (this
5284 		 * depends on the config file).  It may not report 0 for other
5285 		 * capabilities dependent on the TOE in this case.  Set them to
5286 		 * 0 here so that the driver doesn't bother tracking resources
5287 		 * that will never be used.
5288 		 */
5289 		sc->iscsicaps = 0;
5290 		sc->rdmacaps = 0;
5291 	}
5292 	if (sc->rdmacaps) {
5293 		param[0] = FW_PARAM_PFVF(STAG_START);
5294 		param[1] = FW_PARAM_PFVF(STAG_END);
5295 		param[2] = FW_PARAM_PFVF(RQ_START);
5296 		param[3] = FW_PARAM_PFVF(RQ_END);
5297 		param[4] = FW_PARAM_PFVF(PBL_START);
5298 		param[5] = FW_PARAM_PFVF(PBL_END);
5299 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5300 		if (rc != 0) {
5301 			device_printf(sc->dev,
5302 			    "failed to query RDMA parameters(1): %d.\n", rc);
5303 			return (rc);
5304 		}
5305 		sc->vres.stag.start = val[0];
5306 		sc->vres.stag.size = val[1] - val[0] + 1;
5307 		sc->vres.rq.start = val[2];
5308 		sc->vres.rq.size = val[3] - val[2] + 1;
5309 		sc->vres.pbl.start = val[4];
5310 		sc->vres.pbl.size = val[5] - val[4] + 1;
5311 
5312 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5313 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5314 		param[2] = FW_PARAM_PFVF(CQ_START);
5315 		param[3] = FW_PARAM_PFVF(CQ_END);
5316 		param[4] = FW_PARAM_PFVF(OCQ_START);
5317 		param[5] = FW_PARAM_PFVF(OCQ_END);
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 RDMA parameters(2): %d.\n", rc);
5322 			return (rc);
5323 		}
5324 		sc->vres.qp.start = val[0];
5325 		sc->vres.qp.size = val[1] - val[0] + 1;
5326 		sc->vres.cq.start = val[2];
5327 		sc->vres.cq.size = val[3] - val[2] + 1;
5328 		sc->vres.ocq.start = val[4];
5329 		sc->vres.ocq.size = val[5] - val[4] + 1;
5330 
5331 		param[0] = FW_PARAM_PFVF(SRQ_START);
5332 		param[1] = FW_PARAM_PFVF(SRQ_END);
5333 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5334 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5335 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5336 		if (rc != 0) {
5337 			device_printf(sc->dev,
5338 			    "failed to query RDMA parameters(3): %d.\n", rc);
5339 			return (rc);
5340 		}
5341 		sc->vres.srq.start = val[0];
5342 		sc->vres.srq.size = val[1] - val[0] + 1;
5343 		sc->params.max_ordird_qp = val[2];
5344 		sc->params.max_ird_adapter = val[3];
5345 	}
5346 	if (sc->iscsicaps) {
5347 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5348 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5349 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5350 		if (rc != 0) {
5351 			device_printf(sc->dev,
5352 			    "failed to query iSCSI parameters: %d.\n", rc);
5353 			return (rc);
5354 		}
5355 		sc->vres.iscsi.start = val[0];
5356 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5357 	}
5358 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5359 		param[0] = FW_PARAM_PFVF(TLS_START);
5360 		param[1] = FW_PARAM_PFVF(TLS_END);
5361 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5362 		if (rc != 0) {
5363 			device_printf(sc->dev,
5364 			    "failed to query TLS parameters: %d.\n", rc);
5365 			return (rc);
5366 		}
5367 		sc->vres.key.start = val[0];
5368 		sc->vres.key.size = val[1] - val[0] + 1;
5369 	}
5370 
5371 	/*
5372 	 * We've got the params we wanted to query directly from the firmware.
5373 	 * Grab some others via other means.
5374 	 */
5375 	t4_init_sge_params(sc);
5376 	t4_init_tp_params(sc);
5377 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5378 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5379 
5380 	rc = t4_verify_chip_settings(sc);
5381 	if (rc != 0)
5382 		return (rc);
5383 	t4_init_rx_buf_info(sc);
5384 
5385 	return (rc);
5386 }
5387 
5388 #ifdef KERN_TLS
5389 static void
5390 ktls_tick(void *arg)
5391 {
5392 	struct adapter *sc;
5393 	uint32_t tstamp;
5394 
5395 	sc = arg;
5396 	tstamp = tcp_ts_getticks();
5397 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5398 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5399 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5400 }
5401 
5402 static int
5403 t4_config_kern_tls(struct adapter *sc, bool enable)
5404 {
5405 	int rc;
5406 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5407 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5408 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5409 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5410 
5411 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5412 	if (rc != 0) {
5413 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5414 		    enable ?  "enable" : "disable", rc);
5415 		return (rc);
5416 	}
5417 
5418 	if (enable) {
5419 		sc->flags |= KERN_TLS_ON;
5420 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5421 		    C_HARDCLOCK);
5422 	} else {
5423 		sc->flags &= ~KERN_TLS_ON;
5424 		callout_stop(&sc->ktls_tick);
5425 	}
5426 
5427 	return (rc);
5428 }
5429 #endif
5430 
5431 static int
5432 set_params__post_init(struct adapter *sc)
5433 {
5434 	uint32_t mask, param, val;
5435 #ifdef TCP_OFFLOAD
5436 	int i, v, shift;
5437 #endif
5438 
5439 	/* ask for encapsulated CPLs */
5440 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5441 	val = 1;
5442 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5443 
5444 	/* Enable 32b port caps if the firmware supports it. */
5445 	param = FW_PARAM_PFVF(PORT_CAPS32);
5446 	val = 1;
5447 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5448 		sc->params.port_caps32 = 1;
5449 
5450 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5451 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5452 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5453 	    V_MASKFILTER(val - 1));
5454 
5455 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5456 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5457 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5458 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5459 	val = 0;
5460 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5461 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5462 		    F_ATTACKFILTERENABLE);
5463 		val |= F_DROPERRORATTACK;
5464 	}
5465 	if (t4_drop_ip_fragments != 0) {
5466 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5467 		    F_FRAGMENTDROP);
5468 		val |= F_DROPERRORFRAG;
5469 	}
5470 	if (t4_drop_pkts_with_l2_errors != 0)
5471 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5472 	if (t4_drop_pkts_with_l3_errors != 0) {
5473 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5474 		    F_DROPERRORCSUMIP;
5475 	}
5476 	if (t4_drop_pkts_with_l4_errors != 0) {
5477 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5478 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5479 	}
5480 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5481 
5482 #ifdef TCP_OFFLOAD
5483 	/*
5484 	 * Override the TOE timers with user provided tunables.  This is not the
5485 	 * recommended way to change the timers (the firmware config file is) so
5486 	 * these tunables are not documented.
5487 	 *
5488 	 * All the timer tunables are in microseconds.
5489 	 */
5490 	if (t4_toe_keepalive_idle != 0) {
5491 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5492 		v &= M_KEEPALIVEIDLE;
5493 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5494 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5495 	}
5496 	if (t4_toe_keepalive_interval != 0) {
5497 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5498 		v &= M_KEEPALIVEINTVL;
5499 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5500 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5501 	}
5502 	if (t4_toe_keepalive_count != 0) {
5503 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5504 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5505 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5506 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5507 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5508 	}
5509 	if (t4_toe_rexmt_min != 0) {
5510 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5511 		v &= M_RXTMIN;
5512 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5513 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5514 	}
5515 	if (t4_toe_rexmt_max != 0) {
5516 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5517 		v &= M_RXTMAX;
5518 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5519 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5520 	}
5521 	if (t4_toe_rexmt_count != 0) {
5522 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5523 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5524 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5525 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5526 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5527 	}
5528 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5529 		if (t4_toe_rexmt_backoff[i] != -1) {
5530 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5531 			shift = (i & 3) << 3;
5532 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5533 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5534 		}
5535 	}
5536 #endif
5537 
5538 #ifdef KERN_TLS
5539 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS &&
5540 	    sc->toecaps & FW_CAPS_CONFIG_TOE) {
5541 		/*
5542 		 * Limit TOE connections to 2 reassembly "islands".  This is
5543 		 * required for TOE TLS connections to downgrade to plain TOE
5544 		 * connections if an unsupported TLS version or ciphersuite is
5545 		 * used.
5546 		 */
5547 		t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG,
5548 		    V_PASSMODE(M_PASSMODE), V_PASSMODE(2));
5549 		if (is_ktls(sc)) {
5550 			sc->tlst.inline_keys = t4_tls_inline_keys;
5551 			sc->tlst.combo_wrs = t4_tls_combo_wrs;
5552 			if (t4_kern_tls != 0)
5553 				t4_config_kern_tls(sc, true);
5554 		}
5555 	}
5556 #endif
5557 	return (0);
5558 }
5559 
5560 #undef FW_PARAM_PFVF
5561 #undef FW_PARAM_DEV
5562 
5563 static void
5564 t4_set_desc(struct adapter *sc)
5565 {
5566 	char buf[128];
5567 	struct adapter_params *p = &sc->params;
5568 
5569 	snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
5570 
5571 	device_set_desc_copy(sc->dev, buf);
5572 }
5573 
5574 static inline void
5575 ifmedia_add4(struct ifmedia *ifm, int m)
5576 {
5577 
5578 	ifmedia_add(ifm, m, 0, NULL);
5579 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5580 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5581 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5582 }
5583 
5584 /*
5585  * This is the selected media, which is not quite the same as the active media.
5586  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5587  * and active are not the same, and "media: Ethernet selected" otherwise.
5588  */
5589 static void
5590 set_current_media(struct port_info *pi)
5591 {
5592 	struct link_config *lc;
5593 	struct ifmedia *ifm;
5594 	int mword;
5595 	u_int speed;
5596 
5597 	PORT_LOCK_ASSERT_OWNED(pi);
5598 
5599 	/* Leave current media alone if it's already set to IFM_NONE. */
5600 	ifm = &pi->media;
5601 	if (ifm->ifm_cur != NULL &&
5602 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5603 		return;
5604 
5605 	lc = &pi->link_cfg;
5606 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5607 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5608 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5609 		return;
5610 	}
5611 	mword = IFM_ETHER | IFM_FDX;
5612 	if (lc->requested_fc & PAUSE_TX)
5613 		mword |= IFM_ETH_TXPAUSE;
5614 	if (lc->requested_fc & PAUSE_RX)
5615 		mword |= IFM_ETH_RXPAUSE;
5616 	if (lc->requested_speed == 0)
5617 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5618 	else
5619 		speed = lc->requested_speed;
5620 	mword |= port_mword(pi, speed_to_fwcap(speed));
5621 	ifmedia_set(ifm, mword);
5622 }
5623 
5624 /*
5625  * Returns true if the ifmedia list for the port cannot change.
5626  */
5627 static bool
5628 fixed_ifmedia(struct port_info *pi)
5629 {
5630 
5631 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5632 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5633 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5634 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5635 	    pi->port_type == FW_PORT_TYPE_KX ||
5636 	    pi->port_type == FW_PORT_TYPE_KR ||
5637 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5638 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5639 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5640 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5641 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5642 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5643 }
5644 
5645 static void
5646 build_medialist(struct port_info *pi)
5647 {
5648 	uint32_t ss, speed;
5649 	int unknown, mword, bit;
5650 	struct link_config *lc;
5651 	struct ifmedia *ifm;
5652 
5653 	PORT_LOCK_ASSERT_OWNED(pi);
5654 
5655 	if (pi->flags & FIXED_IFMEDIA)
5656 		return;
5657 
5658 	/*
5659 	 * Rebuild the ifmedia list.
5660 	 */
5661 	ifm = &pi->media;
5662 	ifmedia_removeall(ifm);
5663 	lc = &pi->link_cfg;
5664 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5665 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5666 		MPASS(ss != 0);
5667 no_media:
5668 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5669 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5670 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5671 		return;
5672 	}
5673 
5674 	unknown = 0;
5675 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5676 		speed = 1 << bit;
5677 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5678 		if (ss & speed) {
5679 			mword = port_mword(pi, speed);
5680 			if (mword == IFM_NONE) {
5681 				goto no_media;
5682 			} else if (mword == IFM_UNKNOWN)
5683 				unknown++;
5684 			else
5685 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5686 		}
5687 	}
5688 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5689 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5690 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5691 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5692 
5693 	set_current_media(pi);
5694 }
5695 
5696 /*
5697  * Initialize the requested fields in the link config based on driver tunables.
5698  */
5699 static void
5700 init_link_config(struct port_info *pi)
5701 {
5702 	struct link_config *lc = &pi->link_cfg;
5703 
5704 	PORT_LOCK_ASSERT_OWNED(pi);
5705 
5706 	lc->requested_caps = 0;
5707 	lc->requested_speed = 0;
5708 
5709 	if (t4_autoneg == 0)
5710 		lc->requested_aneg = AUTONEG_DISABLE;
5711 	else if (t4_autoneg == 1)
5712 		lc->requested_aneg = AUTONEG_ENABLE;
5713 	else
5714 		lc->requested_aneg = AUTONEG_AUTO;
5715 
5716 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5717 	    PAUSE_AUTONEG);
5718 
5719 	if (t4_fec & FEC_AUTO)
5720 		lc->requested_fec = FEC_AUTO;
5721 	else if (t4_fec == 0)
5722 		lc->requested_fec = FEC_NONE;
5723 	else {
5724 		/* -1 is handled by the FEC_AUTO block above and not here. */
5725 		lc->requested_fec = t4_fec &
5726 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5727 		if (lc->requested_fec == 0)
5728 			lc->requested_fec = FEC_AUTO;
5729 	}
5730 }
5731 
5732 /*
5733  * Makes sure that all requested settings comply with what's supported by the
5734  * port.  Returns the number of settings that were invalid and had to be fixed.
5735  */
5736 static int
5737 fixup_link_config(struct port_info *pi)
5738 {
5739 	int n = 0;
5740 	struct link_config *lc = &pi->link_cfg;
5741 	uint32_t fwspeed;
5742 
5743 	PORT_LOCK_ASSERT_OWNED(pi);
5744 
5745 	/* Speed (when not autonegotiating) */
5746 	if (lc->requested_speed != 0) {
5747 		fwspeed = speed_to_fwcap(lc->requested_speed);
5748 		if ((fwspeed & lc->pcaps) == 0) {
5749 			n++;
5750 			lc->requested_speed = 0;
5751 		}
5752 	}
5753 
5754 	/* Link autonegotiation */
5755 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5756 	    lc->requested_aneg == AUTONEG_DISABLE ||
5757 	    lc->requested_aneg == AUTONEG_AUTO);
5758 	if (lc->requested_aneg == AUTONEG_ENABLE &&
5759 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5760 		n++;
5761 		lc->requested_aneg = AUTONEG_AUTO;
5762 	}
5763 
5764 	/* Flow control */
5765 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5766 	if (lc->requested_fc & PAUSE_TX &&
5767 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5768 		n++;
5769 		lc->requested_fc &= ~PAUSE_TX;
5770 	}
5771 	if (lc->requested_fc & PAUSE_RX &&
5772 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
5773 		n++;
5774 		lc->requested_fc &= ~PAUSE_RX;
5775 	}
5776 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
5777 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
5778 		n++;
5779 		lc->requested_fc |= PAUSE_AUTONEG;
5780 	}
5781 
5782 	/* FEC */
5783 	if ((lc->requested_fec & FEC_RS &&
5784 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
5785 	    (lc->requested_fec & FEC_BASER_RS &&
5786 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
5787 		n++;
5788 		lc->requested_fec = FEC_AUTO;
5789 	}
5790 
5791 	return (n);
5792 }
5793 
5794 /*
5795  * Apply the requested L1 settings, which are expected to be valid, to the
5796  * hardware.
5797  */
5798 static int
5799 apply_link_config(struct port_info *pi)
5800 {
5801 	struct adapter *sc = pi->adapter;
5802 	struct link_config *lc = &pi->link_cfg;
5803 	int rc;
5804 
5805 #ifdef INVARIANTS
5806 	ASSERT_SYNCHRONIZED_OP(sc);
5807 	PORT_LOCK_ASSERT_OWNED(pi);
5808 
5809 	if (lc->requested_aneg == AUTONEG_ENABLE)
5810 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
5811 	if (!(lc->requested_fc & PAUSE_AUTONEG))
5812 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
5813 	if (lc->requested_fc & PAUSE_TX)
5814 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
5815 	if (lc->requested_fc & PAUSE_RX)
5816 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
5817 	if (lc->requested_fec & FEC_RS)
5818 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
5819 	if (lc->requested_fec & FEC_BASER_RS)
5820 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
5821 #endif
5822 	rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
5823 	if (rc != 0) {
5824 		/* Don't complain if the VF driver gets back an EPERM. */
5825 		if (!(sc->flags & IS_VF) || rc != FW_EPERM)
5826 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
5827 	} else {
5828 		/*
5829 		 * An L1_CFG will almost always result in a link-change event if
5830 		 * the link is up, and the driver will refresh the actual
5831 		 * fec/fc/etc. when the notification is processed.  If the link
5832 		 * is down then the actual settings are meaningless.
5833 		 *
5834 		 * This takes care of the case where a change in the L1 settings
5835 		 * may not result in a notification.
5836 		 */
5837 		if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
5838 			lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
5839 	}
5840 	return (rc);
5841 }
5842 
5843 #define FW_MAC_EXACT_CHUNK	7
5844 struct mcaddr_ctx {
5845 	struct ifnet *ifp;
5846 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
5847 	uint64_t hash;
5848 	int i;
5849 	int del;
5850 	int rc;
5851 };
5852 
5853 static u_int
5854 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
5855 {
5856 	struct mcaddr_ctx *ctx = arg;
5857 	struct vi_info *vi = ctx->ifp->if_softc;
5858 	struct port_info *pi = vi->pi;
5859 	struct adapter *sc = pi->adapter;
5860 
5861 	if (ctx->rc < 0)
5862 		return (0);
5863 
5864 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
5865 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
5866 	ctx->i++;
5867 
5868 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
5869 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
5870 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
5871 		if (ctx->rc < 0) {
5872 			int j;
5873 
5874 			for (j = 0; j < ctx->i; j++) {
5875 				if_printf(ctx->ifp,
5876 				    "failed to add mc address"
5877 				    " %02x:%02x:%02x:"
5878 				    "%02x:%02x:%02x rc=%d\n",
5879 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
5880 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
5881 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
5882 				    -ctx->rc);
5883 			}
5884 			return (0);
5885 		}
5886 		ctx->del = 0;
5887 		ctx->i = 0;
5888 	}
5889 
5890 	return (1);
5891 }
5892 
5893 /*
5894  * Program the port's XGMAC based on parameters in ifnet.  The caller also
5895  * indicates which parameters should be programmed (the rest are left alone).
5896  */
5897 int
5898 update_mac_settings(struct ifnet *ifp, int flags)
5899 {
5900 	int rc = 0;
5901 	struct vi_info *vi = ifp->if_softc;
5902 	struct port_info *pi = vi->pi;
5903 	struct adapter *sc = pi->adapter;
5904 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
5905 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
5906 
5907 	ASSERT_SYNCHRONIZED_OP(sc);
5908 	KASSERT(flags, ("%s: not told what to update.", __func__));
5909 
5910 	if (flags & XGMAC_MTU)
5911 		mtu = ifp->if_mtu;
5912 
5913 	if (flags & XGMAC_PROMISC)
5914 		promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
5915 
5916 	if (flags & XGMAC_ALLMULTI)
5917 		allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
5918 
5919 	if (flags & XGMAC_VLANEX)
5920 		vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
5921 
5922 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
5923 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
5924 		    allmulti, 1, vlanex, false);
5925 		if (rc) {
5926 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
5927 			    rc);
5928 			return (rc);
5929 		}
5930 	}
5931 
5932 	if (flags & XGMAC_UCADDR) {
5933 		uint8_t ucaddr[ETHER_ADDR_LEN];
5934 
5935 		bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
5936 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
5937 		    ucaddr, true, &vi->smt_idx);
5938 		if (rc < 0) {
5939 			rc = -rc;
5940 			if_printf(ifp, "change_mac failed: %d\n", rc);
5941 			return (rc);
5942 		} else {
5943 			vi->xact_addr_filt = rc;
5944 			rc = 0;
5945 		}
5946 	}
5947 
5948 	if (flags & XGMAC_MCADDRS) {
5949 		struct epoch_tracker et;
5950 		struct mcaddr_ctx ctx;
5951 		int j;
5952 
5953 		ctx.ifp = ifp;
5954 		ctx.hash = 0;
5955 		ctx.i = 0;
5956 		ctx.del = 1;
5957 		ctx.rc = 0;
5958 		/*
5959 		 * Unlike other drivers, we accumulate list of pointers into
5960 		 * interface address lists and we need to keep it safe even
5961 		 * after if_foreach_llmaddr() returns, thus we must enter the
5962 		 * network epoch.
5963 		 */
5964 		NET_EPOCH_ENTER(et);
5965 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
5966 		if (ctx.rc < 0) {
5967 			NET_EPOCH_EXIT(et);
5968 			rc = -ctx.rc;
5969 			return (rc);
5970 		}
5971 		if (ctx.i > 0) {
5972 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
5973 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
5974 			NET_EPOCH_EXIT(et);
5975 			if (rc < 0) {
5976 				rc = -rc;
5977 				for (j = 0; j < ctx.i; j++) {
5978 					if_printf(ifp,
5979 					    "failed to add mcast address"
5980 					    " %02x:%02x:%02x:"
5981 					    "%02x:%02x:%02x rc=%d\n",
5982 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
5983 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
5984 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
5985 					    rc);
5986 				}
5987 				return (rc);
5988 			}
5989 			ctx.del = 0;
5990 		} else
5991 			NET_EPOCH_EXIT(et);
5992 
5993 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
5994 		if (rc != 0)
5995 			if_printf(ifp, "failed to set mcast address hash: %d\n",
5996 			    rc);
5997 		if (ctx.del == 0) {
5998 			/* We clobbered the VXLAN entry if there was one. */
5999 			pi->vxlan_tcam_entry = false;
6000 		}
6001 	}
6002 
6003 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6004 	    pi->vxlan_tcam_entry == false) {
6005 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6006 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6007 		    true);
6008 		if (rc < 0) {
6009 			rc = -rc;
6010 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6011 			    rc);
6012 		} else {
6013 			MPASS(rc == sc->rawf_base + pi->port_id);
6014 			rc = 0;
6015 			pi->vxlan_tcam_entry = true;
6016 		}
6017 	}
6018 
6019 	return (rc);
6020 }
6021 
6022 /*
6023  * {begin|end}_synchronized_op must be called from the same thread.
6024  */
6025 int
6026 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6027     char *wmesg)
6028 {
6029 	int rc, pri;
6030 
6031 #ifdef WITNESS
6032 	/* the caller thinks it's ok to sleep, but is it really? */
6033 	if (flags & SLEEP_OK)
6034 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6035 		    "begin_synchronized_op");
6036 #endif
6037 
6038 	if (INTR_OK)
6039 		pri = PCATCH;
6040 	else
6041 		pri = 0;
6042 
6043 	ADAPTER_LOCK(sc);
6044 	for (;;) {
6045 
6046 		if (vi && IS_DOOMED(vi)) {
6047 			rc = ENXIO;
6048 			goto done;
6049 		}
6050 
6051 		if (!IS_BUSY(sc)) {
6052 			rc = 0;
6053 			break;
6054 		}
6055 
6056 		if (!(flags & SLEEP_OK)) {
6057 			rc = EBUSY;
6058 			goto done;
6059 		}
6060 
6061 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6062 			rc = EINTR;
6063 			goto done;
6064 		}
6065 	}
6066 
6067 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6068 	SET_BUSY(sc);
6069 #ifdef INVARIANTS
6070 	sc->last_op = wmesg;
6071 	sc->last_op_thr = curthread;
6072 	sc->last_op_flags = flags;
6073 #endif
6074 
6075 done:
6076 	if (!(flags & HOLD_LOCK) || rc)
6077 		ADAPTER_UNLOCK(sc);
6078 
6079 	return (rc);
6080 }
6081 
6082 /*
6083  * Tell if_ioctl and if_init that the VI is going away.  This is
6084  * special variant of begin_synchronized_op and must be paired with a
6085  * call to end_synchronized_op.
6086  */
6087 void
6088 doom_vi(struct adapter *sc, struct vi_info *vi)
6089 {
6090 
6091 	ADAPTER_LOCK(sc);
6092 	SET_DOOMED(vi);
6093 	wakeup(&sc->flags);
6094 	while (IS_BUSY(sc))
6095 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6096 	SET_BUSY(sc);
6097 #ifdef INVARIANTS
6098 	sc->last_op = "t4detach";
6099 	sc->last_op_thr = curthread;
6100 	sc->last_op_flags = 0;
6101 #endif
6102 	ADAPTER_UNLOCK(sc);
6103 }
6104 
6105 /*
6106  * {begin|end}_synchronized_op must be called from the same thread.
6107  */
6108 void
6109 end_synchronized_op(struct adapter *sc, int flags)
6110 {
6111 
6112 	if (flags & LOCK_HELD)
6113 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6114 	else
6115 		ADAPTER_LOCK(sc);
6116 
6117 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6118 	CLR_BUSY(sc);
6119 	wakeup(&sc->flags);
6120 	ADAPTER_UNLOCK(sc);
6121 }
6122 
6123 static int
6124 cxgbe_init_synchronized(struct vi_info *vi)
6125 {
6126 	struct port_info *pi = vi->pi;
6127 	struct adapter *sc = pi->adapter;
6128 	struct ifnet *ifp = vi->ifp;
6129 	int rc = 0, i;
6130 	struct sge_txq *txq;
6131 
6132 	ASSERT_SYNCHRONIZED_OP(sc);
6133 
6134 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
6135 		return (0);	/* already running */
6136 
6137 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6138 		return (rc);	/* error message displayed already */
6139 
6140 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6141 		return (rc); /* error message displayed already */
6142 
6143 	rc = update_mac_settings(ifp, XGMAC_ALL);
6144 	if (rc)
6145 		goto done;	/* error message displayed already */
6146 
6147 	PORT_LOCK(pi);
6148 	if (pi->up_vis == 0) {
6149 		t4_update_port_info(pi);
6150 		fixup_link_config(pi);
6151 		build_medialist(pi);
6152 		apply_link_config(pi);
6153 	}
6154 
6155 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6156 	if (rc != 0) {
6157 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6158 		PORT_UNLOCK(pi);
6159 		goto done;
6160 	}
6161 
6162 	/*
6163 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6164 	 * if this changes.
6165 	 */
6166 
6167 	for_each_txq(vi, i, txq) {
6168 		TXQ_LOCK(txq);
6169 		txq->eq.flags |= EQ_ENABLED;
6170 		TXQ_UNLOCK(txq);
6171 	}
6172 
6173 	/*
6174 	 * The first iq of the first port to come up is used for tracing.
6175 	 */
6176 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6177 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6178 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6179 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6180 		    V_QUEUENUMBER(sc->traceq));
6181 		pi->flags |= HAS_TRACEQ;
6182 	}
6183 
6184 	/* all ok */
6185 	pi->up_vis++;
6186 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
6187 	if (pi->link_cfg.link_ok)
6188 		t4_os_link_changed(pi);
6189 	PORT_UNLOCK(pi);
6190 
6191 	mtx_lock(&vi->tick_mtx);
6192 	if (ifp->if_get_counter == vi_get_counter)
6193 		callout_reset(&vi->tick, hz, vi_tick, vi);
6194 	else
6195 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6196 	mtx_unlock(&vi->tick_mtx);
6197 done:
6198 	if (rc != 0)
6199 		cxgbe_uninit_synchronized(vi);
6200 
6201 	return (rc);
6202 }
6203 
6204 /*
6205  * Idempotent.
6206  */
6207 static int
6208 cxgbe_uninit_synchronized(struct vi_info *vi)
6209 {
6210 	struct port_info *pi = vi->pi;
6211 	struct adapter *sc = pi->adapter;
6212 	struct ifnet *ifp = vi->ifp;
6213 	int rc, i;
6214 	struct sge_txq *txq;
6215 
6216 	ASSERT_SYNCHRONIZED_OP(sc);
6217 
6218 	if (!(vi->flags & VI_INIT_DONE)) {
6219 		if (__predict_false(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6220 			KASSERT(0, ("uninited VI is running"));
6221 			if_printf(ifp, "uninited VI with running ifnet.  "
6222 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6223 			    "if_drv_flags 0x%08x\n", vi->flags, ifp->if_flags,
6224 			    ifp->if_drv_flags);
6225 		}
6226 		return (0);
6227 	}
6228 
6229 	/*
6230 	 * Disable the VI so that all its data in either direction is discarded
6231 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6232 	 * tick) intact as the TP can deliver negative advice or data that it's
6233 	 * holding in its RAM (for an offloaded connection) even after the VI is
6234 	 * disabled.
6235 	 */
6236 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6237 	if (rc) {
6238 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6239 		return (rc);
6240 	}
6241 
6242 	for_each_txq(vi, i, txq) {
6243 		TXQ_LOCK(txq);
6244 		txq->eq.flags &= ~EQ_ENABLED;
6245 		TXQ_UNLOCK(txq);
6246 	}
6247 
6248 	mtx_lock(&vi->tick_mtx);
6249 	callout_stop(&vi->tick);
6250 	mtx_unlock(&vi->tick_mtx);
6251 
6252 	PORT_LOCK(pi);
6253 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6254 		PORT_UNLOCK(pi);
6255 		return (0);
6256 	}
6257 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
6258 	pi->up_vis--;
6259 	if (pi->up_vis > 0) {
6260 		PORT_UNLOCK(pi);
6261 		return (0);
6262 	}
6263 
6264 	pi->link_cfg.link_ok = false;
6265 	pi->link_cfg.speed = 0;
6266 	pi->link_cfg.link_down_rc = 255;
6267 	t4_os_link_changed(pi);
6268 	PORT_UNLOCK(pi);
6269 
6270 	return (0);
6271 }
6272 
6273 /*
6274  * It is ok for this function to fail midway and return right away.  t4_detach
6275  * will walk the entire sc->irq list and clean up whatever is valid.
6276  */
6277 int
6278 t4_setup_intr_handlers(struct adapter *sc)
6279 {
6280 	int rc, rid, p, q, v;
6281 	char s[8];
6282 	struct irq *irq;
6283 	struct port_info *pi;
6284 	struct vi_info *vi;
6285 	struct sge *sge = &sc->sge;
6286 	struct sge_rxq *rxq;
6287 #ifdef TCP_OFFLOAD
6288 	struct sge_ofld_rxq *ofld_rxq;
6289 #endif
6290 #ifdef DEV_NETMAP
6291 	struct sge_nm_rxq *nm_rxq;
6292 #endif
6293 #ifdef RSS
6294 	int nbuckets = rss_getnumbuckets();
6295 #endif
6296 
6297 	/*
6298 	 * Setup interrupts.
6299 	 */
6300 	irq = &sc->irq[0];
6301 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6302 	if (forwarding_intr_to_fwq(sc))
6303 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6304 
6305 	/* Multiple interrupts. */
6306 	if (sc->flags & IS_VF)
6307 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6308 		    ("%s: too few intr.", __func__));
6309 	else
6310 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6311 		    ("%s: too few intr.", __func__));
6312 
6313 	/* The first one is always error intr on PFs */
6314 	if (!(sc->flags & IS_VF)) {
6315 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6316 		if (rc != 0)
6317 			return (rc);
6318 		irq++;
6319 		rid++;
6320 	}
6321 
6322 	/* The second one is always the firmware event queue (first on VFs) */
6323 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6324 	if (rc != 0)
6325 		return (rc);
6326 	irq++;
6327 	rid++;
6328 
6329 	for_each_port(sc, p) {
6330 		pi = sc->port[p];
6331 		for_each_vi(pi, v, vi) {
6332 			vi->first_intr = rid - 1;
6333 
6334 			if (vi->nnmrxq > 0) {
6335 				int n = max(vi->nrxq, vi->nnmrxq);
6336 
6337 				rxq = &sge->rxq[vi->first_rxq];
6338 #ifdef DEV_NETMAP
6339 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6340 #endif
6341 				for (q = 0; q < n; q++) {
6342 					snprintf(s, sizeof(s), "%x%c%x", p,
6343 					    'a' + v, q);
6344 					if (q < vi->nrxq)
6345 						irq->rxq = rxq++;
6346 #ifdef DEV_NETMAP
6347 					if (q < vi->nnmrxq)
6348 						irq->nm_rxq = nm_rxq++;
6349 
6350 					if (irq->nm_rxq != NULL &&
6351 					    irq->rxq == NULL) {
6352 						/* Netmap rx only */
6353 						rc = t4_alloc_irq(sc, irq, rid,
6354 						    t4_nm_intr, irq->nm_rxq, s);
6355 					}
6356 					if (irq->nm_rxq != NULL &&
6357 					    irq->rxq != NULL) {
6358 						/* NIC and Netmap rx */
6359 						rc = t4_alloc_irq(sc, irq, rid,
6360 						    t4_vi_intr, irq, s);
6361 					}
6362 #endif
6363 					if (irq->rxq != NULL &&
6364 					    irq->nm_rxq == NULL) {
6365 						/* NIC rx only */
6366 						rc = t4_alloc_irq(sc, irq, rid,
6367 						    t4_intr, irq->rxq, s);
6368 					}
6369 					if (rc != 0)
6370 						return (rc);
6371 #ifdef RSS
6372 					if (q < vi->nrxq) {
6373 						bus_bind_intr(sc->dev, irq->res,
6374 						    rss_getcpu(q % nbuckets));
6375 					}
6376 #endif
6377 					irq++;
6378 					rid++;
6379 					vi->nintr++;
6380 				}
6381 			} else {
6382 				for_each_rxq(vi, q, rxq) {
6383 					snprintf(s, sizeof(s), "%x%c%x", p,
6384 					    'a' + v, q);
6385 					rc = t4_alloc_irq(sc, irq, rid,
6386 					    t4_intr, rxq, s);
6387 					if (rc != 0)
6388 						return (rc);
6389 #ifdef RSS
6390 					bus_bind_intr(sc->dev, irq->res,
6391 					    rss_getcpu(q % nbuckets));
6392 #endif
6393 					irq++;
6394 					rid++;
6395 					vi->nintr++;
6396 				}
6397 			}
6398 #ifdef TCP_OFFLOAD
6399 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6400 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6401 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6402 				    ofld_rxq, s);
6403 				if (rc != 0)
6404 					return (rc);
6405 				irq++;
6406 				rid++;
6407 				vi->nintr++;
6408 			}
6409 #endif
6410 		}
6411 	}
6412 	MPASS(irq == &sc->irq[sc->intr_count]);
6413 
6414 	return (0);
6415 }
6416 
6417 static void
6418 write_global_rss_key(struct adapter *sc)
6419 {
6420 #ifdef RSS
6421 	int i;
6422 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6423 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6424 
6425 	CTASSERT(RSS_KEYSIZE == 40);
6426 
6427 	rss_getkey((void *)&raw_rss_key[0]);
6428 	for (i = 0; i < nitems(rss_key); i++) {
6429 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6430 	}
6431 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6432 #endif
6433 }
6434 
6435 /*
6436  * Idempotent.
6437  */
6438 static int
6439 adapter_full_init(struct adapter *sc)
6440 {
6441 	int rc, i;
6442 
6443 	ASSERT_SYNCHRONIZED_OP(sc);
6444 
6445 	if (!(sc->flags & ADAP_SYSCTL_CTX)) {
6446 		sysctl_ctx_init(&sc->ctx);
6447 		sc->flags |= ADAP_SYSCTL_CTX;
6448 	}
6449 
6450 	/*
6451 	 * queues that belong to the adapter (not any particular port).
6452 	 */
6453 	rc = t4_setup_adapter_queues(sc);
6454 	if (rc != 0)
6455 		return (rc);
6456 
6457 	for (i = 0; i < nitems(sc->tq); i++) {
6458 		if (sc->tq[i] != NULL)
6459 			continue;
6460 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6461 		    taskqueue_thread_enqueue, &sc->tq[i]);
6462 		if (sc->tq[i] == NULL) {
6463 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6464 			return (ENOMEM);
6465 		}
6466 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6467 		    device_get_nameunit(sc->dev), i);
6468 	}
6469 
6470 	if (!(sc->flags & IS_VF)) {
6471 		write_global_rss_key(sc);
6472 		t4_intr_enable(sc);
6473 	}
6474 	return (0);
6475 }
6476 
6477 int
6478 adapter_init(struct adapter *sc)
6479 {
6480 	int rc;
6481 
6482 	ASSERT_SYNCHRONIZED_OP(sc);
6483 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6484 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6485 	    ("%s: FULL_INIT_DONE already", __func__));
6486 
6487 	rc = adapter_full_init(sc);
6488 	if (rc != 0)
6489 		adapter_full_uninit(sc);
6490 	else
6491 		sc->flags |= FULL_INIT_DONE;
6492 
6493 	return (rc);
6494 }
6495 
6496 /*
6497  * Idempotent.
6498  */
6499 static void
6500 adapter_full_uninit(struct adapter *sc)
6501 {
6502 	int i;
6503 
6504 	/* Do this before freeing the adapter queues. */
6505 	if (sc->flags & ADAP_SYSCTL_CTX) {
6506 		sysctl_ctx_free(&sc->ctx);
6507 		sc->flags &= ~ADAP_SYSCTL_CTX;
6508 	}
6509 
6510 	t4_teardown_adapter_queues(sc);
6511 
6512 	for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
6513 		taskqueue_free(sc->tq[i]);
6514 		sc->tq[i] = NULL;
6515 	}
6516 
6517 	sc->flags &= ~FULL_INIT_DONE;
6518 }
6519 
6520 #ifdef RSS
6521 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6522     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6523     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6524     RSS_HASHTYPE_RSS_UDP_IPV6)
6525 
6526 /* Translates kernel hash types to hardware. */
6527 static int
6528 hashconfig_to_hashen(int hashconfig)
6529 {
6530 	int hashen = 0;
6531 
6532 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6533 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6534 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6535 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6536 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6537 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6538 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6539 	}
6540 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6541 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6542 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6543 	}
6544 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6545 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6546 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6547 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6548 
6549 	return (hashen);
6550 }
6551 
6552 /* Translates hardware hash types to kernel. */
6553 static int
6554 hashen_to_hashconfig(int hashen)
6555 {
6556 	int hashconfig = 0;
6557 
6558 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6559 		/*
6560 		 * If UDP hashing was enabled it must have been enabled for
6561 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6562 		 * enabling any 4-tuple hash is nonsense configuration.
6563 		 */
6564 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6565 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6566 
6567 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6568 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6569 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6570 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6571 	}
6572 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6573 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6574 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6575 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6576 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6577 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6578 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6579 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6580 
6581 	return (hashconfig);
6582 }
6583 #endif
6584 
6585 /*
6586  * Idempotent.
6587  */
6588 static int
6589 vi_full_init(struct vi_info *vi)
6590 {
6591 	struct adapter *sc = vi->adapter;
6592 	struct sge_rxq *rxq;
6593 	int rc, i, j;
6594 #ifdef RSS
6595 	int nbuckets = rss_getnumbuckets();
6596 	int hashconfig = rss_gethashconfig();
6597 	int extra;
6598 #endif
6599 
6600 	ASSERT_SYNCHRONIZED_OP(sc);
6601 
6602 	if (!(vi->flags & VI_SYSCTL_CTX)) {
6603 		sysctl_ctx_init(&vi->ctx);
6604 		vi->flags |= VI_SYSCTL_CTX;
6605 	}
6606 
6607 	/*
6608 	 * Allocate tx/rx/fl queues for this VI.
6609 	 */
6610 	rc = t4_setup_vi_queues(vi);
6611 	if (rc != 0)
6612 		return (rc);
6613 
6614 	/*
6615 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6616 	 */
6617 	if (vi->nrxq > vi->rss_size) {
6618 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6619 		    "some queues will never receive traffic.\n", vi->nrxq,
6620 		    vi->rss_size);
6621 	} else if (vi->rss_size % vi->nrxq) {
6622 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6623 		    "expect uneven traffic distribution.\n", vi->nrxq,
6624 		    vi->rss_size);
6625 	}
6626 #ifdef RSS
6627 	if (vi->nrxq != nbuckets) {
6628 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6629 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6630 	}
6631 #endif
6632 	if (vi->rss == NULL)
6633 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6634 		    M_ZERO | M_WAITOK);
6635 	for (i = 0; i < vi->rss_size;) {
6636 #ifdef RSS
6637 		j = rss_get_indirection_to_bucket(i);
6638 		j %= vi->nrxq;
6639 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6640 		vi->rss[i++] = rxq->iq.abs_id;
6641 #else
6642 		for_each_rxq(vi, j, rxq) {
6643 			vi->rss[i++] = rxq->iq.abs_id;
6644 			if (i == vi->rss_size)
6645 				break;
6646 		}
6647 #endif
6648 	}
6649 
6650 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6651 	    vi->rss, vi->rss_size);
6652 	if (rc != 0) {
6653 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6654 		return (rc);
6655 	}
6656 
6657 #ifdef RSS
6658 	vi->hashen = hashconfig_to_hashen(hashconfig);
6659 
6660 	/*
6661 	 * We may have had to enable some hashes even though the global config
6662 	 * wants them disabled.  This is a potential problem that must be
6663 	 * reported to the user.
6664 	 */
6665 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6666 
6667 	/*
6668 	 * If we consider only the supported hash types, then the enabled hashes
6669 	 * are a superset of the requested hashes.  In other words, there cannot
6670 	 * be any supported hash that was requested but not enabled, but there
6671 	 * can be hashes that were not requested but had to be enabled.
6672 	 */
6673 	extra &= SUPPORTED_RSS_HASHTYPES;
6674 	MPASS((extra & hashconfig) == 0);
6675 
6676 	if (extra) {
6677 		CH_ALERT(vi,
6678 		    "global RSS config (0x%x) cannot be accommodated.\n",
6679 		    hashconfig);
6680 	}
6681 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6682 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6683 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6684 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6685 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6686 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6687 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6688 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6689 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6690 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6691 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6692 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6693 #else
6694 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6695 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6696 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6697 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6698 #endif
6699 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6700 	    0, 0);
6701 	if (rc != 0) {
6702 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6703 		return (rc);
6704 	}
6705 
6706 	return (0);
6707 }
6708 
6709 int
6710 vi_init(struct vi_info *vi)
6711 {
6712 	int rc;
6713 
6714 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6715 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6716 	    ("%s: VI_INIT_DONE already", __func__));
6717 
6718 	rc = vi_full_init(vi);
6719 	if (rc != 0)
6720 		vi_full_uninit(vi);
6721 	else
6722 		vi->flags |= VI_INIT_DONE;
6723 
6724 	return (rc);
6725 }
6726 
6727 /*
6728  * Idempotent.
6729  */
6730 static void
6731 vi_full_uninit(struct vi_info *vi)
6732 {
6733 
6734 	if (vi->flags & VI_INIT_DONE) {
6735 		quiesce_vi(vi);
6736 		free(vi->rss, M_CXGBE);
6737 		free(vi->nm_rss, M_CXGBE);
6738 	}
6739 
6740 	/* Do this before freeing the VI queues. */
6741 	if (vi->flags & VI_SYSCTL_CTX) {
6742 		sysctl_ctx_free(&vi->ctx);
6743 		vi->flags &= ~VI_SYSCTL_CTX;
6744 	}
6745 
6746 	t4_teardown_vi_queues(vi);
6747 	vi->flags &= ~VI_INIT_DONE;
6748 }
6749 
6750 static void
6751 quiesce_txq(struct sge_txq *txq)
6752 {
6753 	struct sge_eq *eq = &txq->eq;
6754 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6755 
6756 	MPASS(eq->flags & EQ_SW_ALLOCATED);
6757 	MPASS(!(eq->flags & EQ_ENABLED));
6758 
6759 	/* Wait for the mp_ring to empty. */
6760 	while (!mp_ring_is_idle(txq->r)) {
6761 		mp_ring_check_drainage(txq->r, 4096);
6762 		pause("rquiesce", 1);
6763 	}
6764 	MPASS(txq->txp.npkt == 0);
6765 
6766 	if (eq->flags & EQ_HW_ALLOCATED) {
6767 		/*
6768 		 * Hardware is alive and working normally.  Wait for it to
6769 		 * finish and then wait for the driver to catch up and reclaim
6770 		 * all descriptors.
6771 		 */
6772 		while (spg->cidx != htobe16(eq->pidx))
6773 			pause("equiesce", 1);
6774 		while (eq->cidx != eq->pidx)
6775 			pause("dquiesce", 1);
6776 	} else {
6777 		/*
6778 		 * Hardware is unavailable.  Discard all pending tx and reclaim
6779 		 * descriptors directly.
6780 		 */
6781 		TXQ_LOCK(txq);
6782 		while (eq->cidx != eq->pidx) {
6783 			struct mbuf *m, *nextpkt;
6784 			struct tx_sdesc *txsd;
6785 
6786 			txsd = &txq->sdesc[eq->cidx];
6787 			for (m = txsd->m; m != NULL; m = nextpkt) {
6788 				nextpkt = m->m_nextpkt;
6789 				m->m_nextpkt = NULL;
6790 				m_freem(m);
6791 			}
6792 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
6793 		}
6794 		spg->pidx = spg->cidx = htobe16(eq->cidx);
6795 		TXQ_UNLOCK(txq);
6796 	}
6797 }
6798 
6799 static void
6800 quiesce_wrq(struct sge_wrq *wrq)
6801 {
6802 
6803 	/* XXXTX */
6804 }
6805 
6806 static void
6807 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
6808 {
6809 	/* Synchronize with the interrupt handler */
6810 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
6811 		pause("iqfree", 1);
6812 
6813 	if (fl != NULL) {
6814 		MPASS(iq->flags & IQ_HAS_FL);
6815 
6816 		mtx_lock(&sc->sfl_lock);
6817 		FL_LOCK(fl);
6818 		fl->flags |= FL_DOOMED;
6819 		FL_UNLOCK(fl);
6820 		callout_stop(&sc->sfl_callout);
6821 		mtx_unlock(&sc->sfl_lock);
6822 
6823 		KASSERT((fl->flags & FL_STARVING) == 0,
6824 		    ("%s: still starving", __func__));
6825 
6826 		/* Release all buffers if hardware is no longer available. */
6827 		if (!(iq->flags & IQ_HW_ALLOCATED))
6828 			free_fl_buffers(sc, fl);
6829 	}
6830 }
6831 
6832 /*
6833  * Wait for all activity on all the queues of the VI to complete.  It is assumed
6834  * that no new work is being enqueued by the hardware or the driver.  That part
6835  * should be arranged before calling this function.
6836  */
6837 static void
6838 quiesce_vi(struct vi_info *vi)
6839 {
6840 	int i;
6841 	struct adapter *sc = vi->adapter;
6842 	struct sge_rxq *rxq;
6843 	struct sge_txq *txq;
6844 #ifdef TCP_OFFLOAD
6845 	struct sge_ofld_rxq *ofld_rxq;
6846 #endif
6847 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6848 	struct sge_ofld_txq *ofld_txq;
6849 #endif
6850 
6851 	if (!(vi->flags & VI_INIT_DONE))
6852 		return;
6853 
6854 	for_each_txq(vi, i, txq) {
6855 		quiesce_txq(txq);
6856 	}
6857 
6858 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6859 	for_each_ofld_txq(vi, i, ofld_txq) {
6860 		quiesce_wrq(&ofld_txq->wrq);
6861 	}
6862 #endif
6863 
6864 	for_each_rxq(vi, i, rxq) {
6865 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
6866 	}
6867 
6868 #ifdef TCP_OFFLOAD
6869 	for_each_ofld_rxq(vi, i, ofld_rxq) {
6870 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
6871 	}
6872 #endif
6873 }
6874 
6875 static int
6876 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
6877     driver_intr_t *handler, void *arg, char *name)
6878 {
6879 	int rc;
6880 
6881 	irq->rid = rid;
6882 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
6883 	    RF_SHAREABLE | RF_ACTIVE);
6884 	if (irq->res == NULL) {
6885 		device_printf(sc->dev,
6886 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
6887 		return (ENOMEM);
6888 	}
6889 
6890 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
6891 	    NULL, handler, arg, &irq->tag);
6892 	if (rc != 0) {
6893 		device_printf(sc->dev,
6894 		    "failed to setup interrupt for rid %d, name %s: %d\n",
6895 		    rid, name, rc);
6896 	} else if (name)
6897 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
6898 
6899 	return (rc);
6900 }
6901 
6902 static int
6903 t4_free_irq(struct adapter *sc, struct irq *irq)
6904 {
6905 	if (irq->tag)
6906 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
6907 	if (irq->res)
6908 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
6909 
6910 	bzero(irq, sizeof(*irq));
6911 
6912 	return (0);
6913 }
6914 
6915 static void
6916 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
6917 {
6918 
6919 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
6920 	t4_get_regs(sc, buf, regs->len);
6921 }
6922 
6923 #define	A_PL_INDIR_CMD	0x1f8
6924 
6925 #define	S_PL_AUTOINC	31
6926 #define	M_PL_AUTOINC	0x1U
6927 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
6928 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
6929 
6930 #define	S_PL_VFID	20
6931 #define	M_PL_VFID	0xffU
6932 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
6933 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
6934 
6935 #define	S_PL_ADDR	0
6936 #define	M_PL_ADDR	0xfffffU
6937 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
6938 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
6939 
6940 #define	A_PL_INDIR_DATA	0x1fc
6941 
6942 static uint64_t
6943 read_vf_stat(struct adapter *sc, u_int vin, int reg)
6944 {
6945 	u32 stats[2];
6946 
6947 	if (sc->flags & IS_VF) {
6948 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
6949 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
6950 	} else {
6951 		mtx_assert(&sc->reg_lock, MA_OWNED);
6952 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
6953 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
6954 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
6955 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
6956 	}
6957 	return (((uint64_t)stats[1]) << 32 | stats[0]);
6958 }
6959 
6960 static void
6961 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
6962 {
6963 
6964 #define GET_STAT(name) \
6965 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
6966 
6967 	if (!(sc->flags & IS_VF))
6968 		mtx_lock(&sc->reg_lock);
6969 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
6970 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
6971 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
6972 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
6973 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
6974 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
6975 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
6976 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
6977 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
6978 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
6979 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
6980 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
6981 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
6982 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
6983 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
6984 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
6985 	if (!(sc->flags & IS_VF))
6986 		mtx_unlock(&sc->reg_lock);
6987 
6988 #undef GET_STAT
6989 }
6990 
6991 static void
6992 t4_clr_vi_stats(struct adapter *sc, u_int vin)
6993 {
6994 	int reg;
6995 
6996 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
6997 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
6998 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
6999 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7000 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7001 }
7002 
7003 static void
7004 vi_refresh_stats(struct vi_info *vi)
7005 {
7006 	struct timeval tv;
7007 	const struct timeval interval = {0, 250000};	/* 250ms */
7008 
7009 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7010 
7011 	if (!(vi->flags & VI_INIT_DONE) || vi->flags & VI_SKIP_STATS)
7012 		return;
7013 
7014 	getmicrotime(&tv);
7015 	timevalsub(&tv, &interval);
7016 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7017 		return;
7018 
7019 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7020 	getmicrotime(&vi->last_refreshed);
7021 }
7022 
7023 static void
7024 cxgbe_refresh_stats(struct vi_info *vi)
7025 {
7026 	u_int i, v, tnl_cong_drops, chan_map;
7027 	struct timeval tv;
7028 	const struct timeval interval = {0, 250000};	/* 250ms */
7029 	struct port_info *pi;
7030 	struct adapter *sc;
7031 
7032 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7033 
7034 	if (vi->flags & VI_SKIP_STATS)
7035 		return;
7036 
7037 	getmicrotime(&tv);
7038 	timevalsub(&tv, &interval);
7039 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7040 		return;
7041 
7042 	pi = vi->pi;
7043 	sc = vi->adapter;
7044 	tnl_cong_drops = 0;
7045 	t4_get_port_stats(sc, pi->tx_chan, &pi->stats);
7046 	chan_map = pi->rx_e_chan_map;
7047 	while (chan_map) {
7048 		i = ffs(chan_map) - 1;
7049 		mtx_lock(&sc->reg_lock);
7050 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7051 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7052 		mtx_unlock(&sc->reg_lock);
7053 		tnl_cong_drops += v;
7054 		chan_map &= ~(1 << i);
7055 	}
7056 	pi->tnl_cong_drops = tnl_cong_drops;
7057 	getmicrotime(&vi->last_refreshed);
7058 }
7059 
7060 static void
7061 cxgbe_tick(void *arg)
7062 {
7063 	struct vi_info *vi = arg;
7064 
7065 	MPASS(IS_MAIN_VI(vi));
7066 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7067 
7068 	cxgbe_refresh_stats(vi);
7069 	callout_schedule(&vi->tick, hz);
7070 }
7071 
7072 static void
7073 vi_tick(void *arg)
7074 {
7075 	struct vi_info *vi = arg;
7076 
7077 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7078 
7079 	vi_refresh_stats(vi);
7080 	callout_schedule(&vi->tick, hz);
7081 }
7082 
7083 /*
7084  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7085  */
7086 static char *caps_decoder[] = {
7087 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7088 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7089 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7090 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7091 	    "\006HASHFILTER\007ETHOFLD",
7092 	"\20\001TOE",					/* 4: TOE */
7093 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7094 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7095 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7096 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7097 	    "\007T10DIF"
7098 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7099 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7100 	    "\004TLS_HW",
7101 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7102 		    "\004PO_INITIATOR\005PO_TARGET",
7103 };
7104 
7105 void
7106 t4_sysctls(struct adapter *sc)
7107 {
7108 	struct sysctl_ctx_list *ctx;
7109 	struct sysctl_oid *oid;
7110 	struct sysctl_oid_list *children, *c0;
7111 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7112 
7113 	ctx = device_get_sysctl_ctx(sc->dev);
7114 
7115 	/*
7116 	 * dev.t4nex.X.
7117 	 */
7118 	oid = device_get_sysctl_tree(sc->dev);
7119 	c0 = children = SYSCTL_CHILDREN(oid);
7120 
7121 	sc->sc_do_rxcopy = 1;
7122 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7123 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7124 
7125 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7126 	    sc->params.nports, "# of ports");
7127 
7128 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7129 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7130 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7131 	    "available doorbells");
7132 
7133 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7134 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7135 
7136 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7137 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7138 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7139 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7140 
7141 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7142 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7143 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7144 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7145 
7146 	t4_sge_sysctls(sc, ctx, children);
7147 
7148 	sc->lro_timeout = 100;
7149 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7150 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7151 
7152 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7153 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7154 
7155 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7156 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7157 
7158 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7159 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7160 
7161 	if (sc->flags & IS_VF)
7162 		return;
7163 
7164 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7165 	    NULL, chip_rev(sc), "chip hardware revision");
7166 
7167 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7168 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7169 
7170 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7171 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7172 
7173 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7174 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7175 
7176 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7177 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7178 
7179 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7180 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7181 
7182 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7183 	    sc->er_version, 0, "expansion ROM version");
7184 
7185 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7186 	    sc->bs_version, 0, "bootstrap firmware version");
7187 
7188 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7189 	    NULL, sc->params.scfg_vers, "serial config version");
7190 
7191 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7192 	    NULL, sc->params.vpd_vers, "VPD version");
7193 
7194 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7195 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7196 
7197 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7198 	    sc->cfcsum, "config file checksum");
7199 
7200 #define SYSCTL_CAP(name, n, text) \
7201 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7202 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7203 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7204 	    "available " text " capabilities")
7205 
7206 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7207 	SYSCTL_CAP(linkcaps, 1, "link");
7208 	SYSCTL_CAP(switchcaps, 2, "switch");
7209 	SYSCTL_CAP(niccaps, 3, "NIC");
7210 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7211 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7212 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7213 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7214 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7215 #undef SYSCTL_CAP
7216 
7217 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7218 	    NULL, sc->tids.nftids, "number of filters");
7219 
7220 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7221 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7222 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7223 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7224 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7225 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7226 
7227 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7228 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7229 	    sysctl_loadavg, "A",
7230 	    "microprocessor load averages (debug firmwares only)");
7231 
7232 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7233 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7234 	    "I", "core Vdd (in mV)");
7235 
7236 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7237 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7238 	    sysctl_cpus, "A", "local CPUs");
7239 
7240 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7241 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7242 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7243 
7244 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7245 	    &sc->swintr, 0, "software triggered interrupts");
7246 
7247 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7248 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7249 	    "1 = reset adapter, 0 = zero reset counter");
7250 
7251 	/*
7252 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7253 	 */
7254 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7255 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7256 	    "logs and miscellaneous information");
7257 	children = SYSCTL_CHILDREN(oid);
7258 
7259 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7260 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7261 	    sysctl_cctrl, "A", "congestion control");
7262 
7263 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7264 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7265 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7266 
7267 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7268 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7269 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7270 
7271 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7272 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7273 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7274 
7275 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7276 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7277 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7278 
7279 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7280 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7281 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7282 
7283 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7284 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7285 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7286 
7287 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7288 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7289 	    sysctl_cim_la, "A", "CIM logic analyzer");
7290 
7291 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7292 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7293 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7294 
7295 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7296 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7297 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7298 
7299 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7300 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7301 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7302 
7303 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7304 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7305 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7306 
7307 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7308 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7309 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7310 
7311 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7312 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7313 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7314 
7315 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7316 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7317 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7318 
7319 	if (chip_id(sc) > CHELSIO_T4) {
7320 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7321 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7322 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7323 		    "CIM OBQ 6 (SGE0-RX)");
7324 
7325 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7326 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7327 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7328 		    "CIM OBQ 7 (SGE1-RX)");
7329 	}
7330 
7331 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7332 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7333 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7334 
7335 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7336 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7337 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7338 
7339 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7340 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7341 	    sysctl_cpl_stats, "A", "CPL statistics");
7342 
7343 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7344 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7345 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7346 
7347 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7348 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7349 	    sysctl_tid_stats, "A", "tid stats");
7350 
7351 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7352 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7353 	    sysctl_devlog, "A", "firmware's device log");
7354 
7355 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7356 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7357 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7358 
7359 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7360 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7361 	    sysctl_hw_sched, "A", "hardware scheduler ");
7362 
7363 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7364 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7365 	    sysctl_l2t, "A", "hardware L2 table");
7366 
7367 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7368 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7369 	    sysctl_smt, "A", "hardware source MAC table");
7370 
7371 #ifdef INET6
7372 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7373 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7374 	    sysctl_clip, "A", "active CLIP table entries");
7375 #endif
7376 
7377 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7378 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7379 	    sysctl_lb_stats, "A", "loopback statistics");
7380 
7381 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7382 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7383 	    sysctl_meminfo, "A", "memory regions");
7384 
7385 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7386 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7387 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7388 	    "A", "MPS TCAM entries");
7389 
7390 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7391 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7392 	    sysctl_path_mtus, "A", "path MTUs");
7393 
7394 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7395 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7396 	    sysctl_pm_stats, "A", "PM statistics");
7397 
7398 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7399 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7400 	    sysctl_rdma_stats, "A", "RDMA statistics");
7401 
7402 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7403 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7404 	    sysctl_tcp_stats, "A", "TCP statistics");
7405 
7406 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7407 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7408 	    sysctl_tids, "A", "TID information");
7409 
7410 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7411 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7412 	    sysctl_tp_err_stats, "A", "TP error statistics");
7413 
7414 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7415 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7416 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7417 
7418 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7419 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7420 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7421 
7422 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7423 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7424 	    sysctl_tp_la, "A", "TP logic analyzer");
7425 
7426 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7427 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7428 	    sysctl_tx_rate, "A", "Tx rate");
7429 
7430 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7431 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7432 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7433 
7434 	if (chip_id(sc) >= CHELSIO_T5) {
7435 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7436 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7437 		    sysctl_wcwr_stats, "A", "write combined work requests");
7438 	}
7439 
7440 #ifdef KERN_TLS
7441 	if (is_ktls(sc)) {
7442 		/*
7443 		 * dev.t4nex.0.tls.
7444 		 */
7445 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7446 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7447 		children = SYSCTL_CHILDREN(oid);
7448 
7449 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7450 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7451 		    "keys in work requests (1) or attempt to store TLS keys "
7452 		    "in card memory.");
7453 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7454 		    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to combine "
7455 		    "TCB field updates with TLS record work requests.");
7456 	}
7457 #endif
7458 
7459 #ifdef TCP_OFFLOAD
7460 	if (is_offload(sc)) {
7461 		int i;
7462 		char s[4];
7463 
7464 		/*
7465 		 * dev.t4nex.X.toe.
7466 		 */
7467 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7468 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7469 		children = SYSCTL_CHILDREN(oid);
7470 
7471 		sc->tt.cong_algorithm = -1;
7472 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7473 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7474 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7475 		    "3 = highspeed)");
7476 
7477 		sc->tt.sndbuf = -1;
7478 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7479 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7480 
7481 		sc->tt.ddp = 0;
7482 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7483 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7484 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7485 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7486 
7487 		sc->tt.rx_coalesce = -1;
7488 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7489 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7490 
7491 		sc->tt.tls = 0;
7492 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7493 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7494 		    "Inline TLS allowed");
7495 
7496 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_ports",
7497 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7498 		    sysctl_tls_rx_ports, "I",
7499 		    "TCP ports that use inline TLS+TOE RX");
7500 
7501 		sc->tt.tls_rx_timeout = t4_toe_tls_rx_timeout;
7502 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_timeout",
7503 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7504 		    sysctl_tls_rx_timeout, "I",
7505 		    "Timeout in seconds to downgrade TLS sockets to plain TOE");
7506 
7507 		sc->tt.tx_align = -1;
7508 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7509 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7510 
7511 		sc->tt.tx_zcopy = 0;
7512 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7513 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7514 		    "Enable zero-copy aio_write(2)");
7515 
7516 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7517 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7518 		    "cop_managed_offloading", CTLFLAG_RW,
7519 		    &sc->tt.cop_managed_offloading, 0,
7520 		    "COP (Connection Offload Policy) controls all TOE offload");
7521 
7522 		sc->tt.autorcvbuf_inc = 16 * 1024;
7523 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7524 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7525 		    "autorcvbuf increment");
7526 
7527 		sc->tt.update_hc_on_pmtu_change = 1;
7528 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7529 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7530 		    &sc->tt.update_hc_on_pmtu_change, 0,
7531 		    "Update hostcache entry if the PMTU changes");
7532 
7533 		sc->tt.iso = 1;
7534 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7535 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7536 
7537 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7538 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7539 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7540 
7541 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7542 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7543 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7544 
7545 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7546 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7547 		    sysctl_tp_tick, "A", "DACK tick (us)");
7548 
7549 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7550 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7551 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7552 
7553 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7554 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7555 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7556 		    "Minimum retransmit interval (us)");
7557 
7558 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7559 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7560 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7561 		    "Maximum retransmit interval (us)");
7562 
7563 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7564 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7565 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7566 		    "Persist timer min (us)");
7567 
7568 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7569 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7570 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7571 		    "Persist timer max (us)");
7572 
7573 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7574 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7575 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7576 		    "Keepalive idle timer (us)");
7577 
7578 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7579 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7580 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7581 		    "Keepalive interval timer (us)");
7582 
7583 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7584 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7585 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7586 
7587 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7588 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7589 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7590 		    "FINWAIT2 timer (us)");
7591 
7592 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7593 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7594 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7595 		    "Number of SYN retransmissions before abort");
7596 
7597 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7598 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7599 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7600 		    "Number of retransmissions before abort");
7601 
7602 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7603 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7604 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7605 		    "Number of keepalive probes before abort");
7606 
7607 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7608 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7609 		    "TOE retransmit backoffs");
7610 		children = SYSCTL_CHILDREN(oid);
7611 		for (i = 0; i < 16; i++) {
7612 			snprintf(s, sizeof(s), "%u", i);
7613 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7614 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7615 			    i, sysctl_tp_backoff, "IU",
7616 			    "TOE retransmit backoff");
7617 		}
7618 	}
7619 #endif
7620 }
7621 
7622 void
7623 vi_sysctls(struct vi_info *vi)
7624 {
7625 	struct sysctl_ctx_list *ctx;
7626 	struct sysctl_oid *oid;
7627 	struct sysctl_oid_list *children;
7628 
7629 	ctx = device_get_sysctl_ctx(vi->dev);
7630 
7631 	/*
7632 	 * dev.v?(cxgbe|cxl).X.
7633 	 */
7634 	oid = device_get_sysctl_tree(vi->dev);
7635 	children = SYSCTL_CHILDREN(oid);
7636 
7637 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7638 	    vi->viid, "VI identifer");
7639 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7640 	    &vi->nrxq, 0, "# of rx queues");
7641 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7642 	    &vi->ntxq, 0, "# of tx queues");
7643 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7644 	    &vi->first_rxq, 0, "index of first rx queue");
7645 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7646 	    &vi->first_txq, 0, "index of first tx queue");
7647 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7648 	    vi->rss_base, "start of RSS indirection table");
7649 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7650 	    vi->rss_size, "size of RSS indirection table");
7651 
7652 	if (IS_MAIN_VI(vi)) {
7653 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7654 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7655 		    sysctl_noflowq, "IU",
7656 		    "Reserve queue 0 for non-flowid packets");
7657 	}
7658 
7659 	if (vi->adapter->flags & IS_VF) {
7660 		MPASS(vi->flags & TX_USES_VM_WR);
7661 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7662 		    NULL, 1, "use VM work requests for transmit");
7663 	} else {
7664 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7665 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7666 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7667 	}
7668 
7669 #ifdef TCP_OFFLOAD
7670 	if (vi->nofldrxq != 0) {
7671 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7672 		    &vi->nofldrxq, 0,
7673 		    "# of rx queues for offloaded TCP connections");
7674 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7675 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7676 		    "index of first TOE rx queue");
7677 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7678 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7679 		    sysctl_holdoff_tmr_idx_ofld, "I",
7680 		    "holdoff timer index for TOE queues");
7681 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7682 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7683 		    sysctl_holdoff_pktc_idx_ofld, "I",
7684 		    "holdoff packet counter index for TOE queues");
7685 	}
7686 #endif
7687 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7688 	if (vi->nofldtxq != 0) {
7689 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7690 		    &vi->nofldtxq, 0,
7691 		    "# of tx queues for TOE/ETHOFLD");
7692 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7693 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7694 		    "index of first TOE/ETHOFLD tx queue");
7695 	}
7696 #endif
7697 #ifdef DEV_NETMAP
7698 	if (vi->nnmrxq != 0) {
7699 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7700 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7701 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7702 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7703 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7704 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7705 		    "index of first netmap rx queue");
7706 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7707 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7708 		    "index of first netmap tx queue");
7709 	}
7710 #endif
7711 
7712 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7713 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7714 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7715 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7716 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7717 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7718 
7719 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7720 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7721 	    sysctl_qsize_rxq, "I", "rx queue size");
7722 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7723 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7724 	    sysctl_qsize_txq, "I", "tx queue size");
7725 }
7726 
7727 static void
7728 cxgbe_sysctls(struct port_info *pi)
7729 {
7730 	struct sysctl_ctx_list *ctx;
7731 	struct sysctl_oid *oid;
7732 	struct sysctl_oid_list *children, *children2;
7733 	struct adapter *sc = pi->adapter;
7734 	int i;
7735 	char name[16];
7736 	static char *tc_flags = {"\20\1USER"};
7737 
7738 	ctx = device_get_sysctl_ctx(pi->dev);
7739 
7740 	/*
7741 	 * dev.cxgbe.X.
7742 	 */
7743 	oid = device_get_sysctl_tree(pi->dev);
7744 	children = SYSCTL_CHILDREN(oid);
7745 
7746 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7747 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7748 	    sysctl_linkdnrc, "A", "reason why link is down");
7749 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7750 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7751 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7752 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
7753 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7754 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7755 		    sysctl_btphy, "I", "PHY firmware version");
7756 	}
7757 
7758 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7759 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7760 	    sysctl_pause_settings, "A",
7761 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7762 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fec",
7763 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7764 	    sysctl_fec, "A",
7765 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7766 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7767 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7768 	    "FEC recommended by the cable/transceiver");
7769 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7770 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7771 	    sysctl_autoneg, "I",
7772 	    "autonegotiation (-1 = not supported)");
7773 
7774 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
7775 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
7776 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7777 	    &pi->link_cfg.pcaps, 0, "port capabilities");
7778 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7779 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
7780 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7781 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7782 
7783 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7784 	    port_top_speed(pi), "max speed (in Gbps)");
7785 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7786 	    pi->mps_bg_map, "MPS buffer group map");
7787 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
7788 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
7789 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_c_chan", CTLFLAG_RD, NULL,
7790 	    pi->rx_c_chan, "TP rx c-channel");
7791 
7792 	if (sc->flags & IS_VF)
7793 		return;
7794 
7795 	/*
7796 	 * dev.(cxgbe|cxl).X.tc.
7797 	 */
7798 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
7799 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7800 	    "Tx scheduler traffic classes (cl_rl)");
7801 	children2 = SYSCTL_CHILDREN(oid);
7802 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
7803 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
7804 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
7805 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
7806 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
7807 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
7808 	for (i = 0; i < sc->params.nsched_cls; i++) {
7809 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
7810 
7811 		snprintf(name, sizeof(name), "%d", i);
7812 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
7813 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
7814 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
7815 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
7816 		    CTLFLAG_RD, &tc->state, 0, "current state");
7817 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
7818 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
7819 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
7820 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
7821 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
7822 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
7823 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7824 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
7825 		    "traffic class parameters");
7826 	}
7827 
7828 	/*
7829 	 * dev.cxgbe.X.stats.
7830 	 */
7831 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
7832 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
7833 	children = SYSCTL_CHILDREN(oid);
7834 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
7835 	    &pi->tx_parse_error, 0,
7836 	    "# of tx packets with invalid length or # of segments");
7837 
7838 #define T4_REGSTAT(name, stat, desc) \
7839     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
7840         CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
7841 	(is_t4(sc) ? PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L) : \
7842 	T5_PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L)), \
7843         sysctl_handle_t4_reg64, "QU", desc)
7844 
7845 /* We get these from port_stats and they may be stale by up to 1s */
7846 #define T4_PORTSTAT(name, desc) \
7847 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
7848 	    &pi->stats.name, desc)
7849 
7850 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
7851 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
7852 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
7853 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
7854 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
7855 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
7856 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
7857 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
7858 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
7859 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
7860 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
7861 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
7862 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
7863 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
7864 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
7865 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
7866 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
7867 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
7868 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
7869 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
7870 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
7871 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
7872 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
7873 
7874 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
7875 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
7876 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
7877 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
7878 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
7879 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
7880 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
7881 	if (is_t6(sc)) {
7882 		T4_PORTSTAT(rx_fcs_err,
7883 		    "# of frames received with bad FCS since last link up");
7884 	} else {
7885 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
7886 		    "# of frames received with bad FCS");
7887 	}
7888 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
7889 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
7890 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
7891 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
7892 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
7893 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
7894 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
7895 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
7896 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
7897 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
7898 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
7899 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
7900 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
7901 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
7902 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
7903 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
7904 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
7905 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
7906 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
7907 
7908 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
7909 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
7910 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
7911 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
7912 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
7913 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
7914 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
7915 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
7916 
7917 #undef T4_REGSTAT
7918 #undef T4_PORTSTAT
7919 }
7920 
7921 static int
7922 sysctl_int_array(SYSCTL_HANDLER_ARGS)
7923 {
7924 	int rc, *i, space = 0;
7925 	struct sbuf sb;
7926 
7927 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
7928 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
7929 		if (space)
7930 			sbuf_printf(&sb, " ");
7931 		sbuf_printf(&sb, "%d", *i);
7932 		space = 1;
7933 	}
7934 	rc = sbuf_finish(&sb);
7935 	sbuf_delete(&sb);
7936 	return (rc);
7937 }
7938 
7939 static int
7940 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
7941 {
7942 	int rc;
7943 	struct sbuf *sb;
7944 
7945 	rc = sysctl_wire_old_buffer(req, 0);
7946 	if (rc != 0)
7947 		return(rc);
7948 
7949 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7950 	if (sb == NULL)
7951 		return (ENOMEM);
7952 
7953 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
7954 	rc = sbuf_finish(sb);
7955 	sbuf_delete(sb);
7956 
7957 	return (rc);
7958 }
7959 
7960 static int
7961 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
7962 {
7963 	int rc;
7964 	struct sbuf *sb;
7965 
7966 	rc = sysctl_wire_old_buffer(req, 0);
7967 	if (rc != 0)
7968 		return(rc);
7969 
7970 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7971 	if (sb == NULL)
7972 		return (ENOMEM);
7973 
7974 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
7975 	rc = sbuf_finish(sb);
7976 	sbuf_delete(sb);
7977 
7978 	return (rc);
7979 }
7980 
7981 static int
7982 sysctl_btphy(SYSCTL_HANDLER_ARGS)
7983 {
7984 	struct port_info *pi = arg1;
7985 	int op = arg2;
7986 	struct adapter *sc = pi->adapter;
7987 	u_int v;
7988 	int rc;
7989 
7990 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
7991 	if (rc)
7992 		return (rc);
7993 	if (hw_off_limits(sc))
7994 		rc = ENXIO;
7995 	else {
7996 		/* XXX: magic numbers */
7997 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
7998 		    op ? 0x20 : 0xc820, &v);
7999 	}
8000 	end_synchronized_op(sc, 0);
8001 	if (rc)
8002 		return (rc);
8003 	if (op == 0)
8004 		v /= 256;
8005 
8006 	rc = sysctl_handle_int(oidp, &v, 0, req);
8007 	return (rc);
8008 }
8009 
8010 static int
8011 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8012 {
8013 	struct vi_info *vi = arg1;
8014 	int rc, val;
8015 
8016 	val = vi->rsrv_noflowq;
8017 	rc = sysctl_handle_int(oidp, &val, 0, req);
8018 	if (rc != 0 || req->newptr == NULL)
8019 		return (rc);
8020 
8021 	if ((val >= 1) && (vi->ntxq > 1))
8022 		vi->rsrv_noflowq = 1;
8023 	else
8024 		vi->rsrv_noflowq = 0;
8025 
8026 	return (rc);
8027 }
8028 
8029 static int
8030 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8031 {
8032 	struct vi_info *vi = arg1;
8033 	struct adapter *sc = vi->adapter;
8034 	int rc, val, i;
8035 
8036 	MPASS(!(sc->flags & IS_VF));
8037 
8038 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8039 	rc = sysctl_handle_int(oidp, &val, 0, req);
8040 	if (rc != 0 || req->newptr == NULL)
8041 		return (rc);
8042 
8043 	if (val != 0 && val != 1)
8044 		return (EINVAL);
8045 
8046 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8047 	    "t4txvm");
8048 	if (rc)
8049 		return (rc);
8050 	if (hw_off_limits(sc))
8051 		rc = ENXIO;
8052 	else if (vi->ifp->if_drv_flags & IFF_DRV_RUNNING) {
8053 		/*
8054 		 * We don't want parse_pkt to run with one setting (VF or PF)
8055 		 * and then eth_tx to see a different setting but still use
8056 		 * stale information calculated by parse_pkt.
8057 		 */
8058 		rc = EBUSY;
8059 	} else {
8060 		struct port_info *pi = vi->pi;
8061 		struct sge_txq *txq;
8062 		uint32_t ctrl0;
8063 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8064 
8065 		if (val) {
8066 			vi->flags |= TX_USES_VM_WR;
8067 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
8068 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8069 			    V_TXPKT_INTF(pi->tx_chan));
8070 			if (!(sc->flags & IS_VF))
8071 				npkt--;
8072 		} else {
8073 			vi->flags &= ~TX_USES_VM_WR;
8074 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
8075 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8076 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8077 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8078 		}
8079 		for_each_txq(vi, i, txq) {
8080 			txq->cpl_ctrl0 = ctrl0;
8081 			txq->txp.max_npkt = npkt;
8082 		}
8083 	}
8084 	end_synchronized_op(sc, LOCK_HELD);
8085 	return (rc);
8086 }
8087 
8088 static int
8089 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8090 {
8091 	struct vi_info *vi = arg1;
8092 	struct adapter *sc = vi->adapter;
8093 	int idx, rc, i;
8094 	struct sge_rxq *rxq;
8095 	uint8_t v;
8096 
8097 	idx = vi->tmr_idx;
8098 
8099 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8100 	if (rc != 0 || req->newptr == NULL)
8101 		return (rc);
8102 
8103 	if (idx < 0 || idx >= SGE_NTIMERS)
8104 		return (EINVAL);
8105 
8106 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8107 	    "t4tmr");
8108 	if (rc)
8109 		return (rc);
8110 
8111 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8112 	for_each_rxq(vi, i, rxq) {
8113 #ifdef atomic_store_rel_8
8114 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8115 #else
8116 		rxq->iq.intr_params = v;
8117 #endif
8118 	}
8119 	vi->tmr_idx = idx;
8120 
8121 	end_synchronized_op(sc, LOCK_HELD);
8122 	return (0);
8123 }
8124 
8125 static int
8126 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8127 {
8128 	struct vi_info *vi = arg1;
8129 	struct adapter *sc = vi->adapter;
8130 	int idx, rc;
8131 
8132 	idx = vi->pktc_idx;
8133 
8134 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8135 	if (rc != 0 || req->newptr == NULL)
8136 		return (rc);
8137 
8138 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8139 		return (EINVAL);
8140 
8141 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8142 	    "t4pktc");
8143 	if (rc)
8144 		return (rc);
8145 
8146 	if (vi->flags & VI_INIT_DONE)
8147 		rc = EBUSY; /* cannot be changed once the queues are created */
8148 	else
8149 		vi->pktc_idx = idx;
8150 
8151 	end_synchronized_op(sc, LOCK_HELD);
8152 	return (rc);
8153 }
8154 
8155 static int
8156 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8157 {
8158 	struct vi_info *vi = arg1;
8159 	struct adapter *sc = vi->adapter;
8160 	int qsize, rc;
8161 
8162 	qsize = vi->qsize_rxq;
8163 
8164 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8165 	if (rc != 0 || req->newptr == NULL)
8166 		return (rc);
8167 
8168 	if (qsize < 128 || (qsize & 7))
8169 		return (EINVAL);
8170 
8171 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8172 	    "t4rxqs");
8173 	if (rc)
8174 		return (rc);
8175 
8176 	if (vi->flags & VI_INIT_DONE)
8177 		rc = EBUSY; /* cannot be changed once the queues are created */
8178 	else
8179 		vi->qsize_rxq = qsize;
8180 
8181 	end_synchronized_op(sc, LOCK_HELD);
8182 	return (rc);
8183 }
8184 
8185 static int
8186 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8187 {
8188 	struct vi_info *vi = arg1;
8189 	struct adapter *sc = vi->adapter;
8190 	int qsize, rc;
8191 
8192 	qsize = vi->qsize_txq;
8193 
8194 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8195 	if (rc != 0 || req->newptr == NULL)
8196 		return (rc);
8197 
8198 	if (qsize < 128 || qsize > 65536)
8199 		return (EINVAL);
8200 
8201 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8202 	    "t4txqs");
8203 	if (rc)
8204 		return (rc);
8205 
8206 	if (vi->flags & VI_INIT_DONE)
8207 		rc = EBUSY; /* cannot be changed once the queues are created */
8208 	else
8209 		vi->qsize_txq = qsize;
8210 
8211 	end_synchronized_op(sc, LOCK_HELD);
8212 	return (rc);
8213 }
8214 
8215 static int
8216 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8217 {
8218 	struct port_info *pi = arg1;
8219 	struct adapter *sc = pi->adapter;
8220 	struct link_config *lc = &pi->link_cfg;
8221 	int rc;
8222 
8223 	if (req->newptr == NULL) {
8224 		struct sbuf *sb;
8225 		static char *bits = "\20\1RX\2TX\3AUTO";
8226 
8227 		rc = sysctl_wire_old_buffer(req, 0);
8228 		if (rc != 0)
8229 			return(rc);
8230 
8231 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8232 		if (sb == NULL)
8233 			return (ENOMEM);
8234 
8235 		if (lc->link_ok) {
8236 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8237 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8238 		} else {
8239 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8240 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8241 		}
8242 		rc = sbuf_finish(sb);
8243 		sbuf_delete(sb);
8244 	} else {
8245 		char s[2];
8246 		int n;
8247 
8248 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8249 		    PAUSE_AUTONEG));
8250 		s[1] = 0;
8251 
8252 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8253 		if (rc != 0)
8254 			return(rc);
8255 
8256 		if (s[1] != 0)
8257 			return (EINVAL);
8258 		if (s[0] < '0' || s[0] > '9')
8259 			return (EINVAL);	/* not a number */
8260 		n = s[0] - '0';
8261 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8262 			return (EINVAL);	/* some other bit is set too */
8263 
8264 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8265 		    "t4PAUSE");
8266 		if (rc)
8267 			return (rc);
8268 		if (!hw_off_limits(sc)) {
8269 			PORT_LOCK(pi);
8270 			lc->requested_fc = n;
8271 			fixup_link_config(pi);
8272 			if (pi->up_vis > 0)
8273 				rc = apply_link_config(pi);
8274 			set_current_media(pi);
8275 			PORT_UNLOCK(pi);
8276 		}
8277 		end_synchronized_op(sc, 0);
8278 	}
8279 
8280 	return (rc);
8281 }
8282 
8283 static int
8284 sysctl_fec(SYSCTL_HANDLER_ARGS)
8285 {
8286 	struct port_info *pi = arg1;
8287 	struct adapter *sc = pi->adapter;
8288 	struct link_config *lc = &pi->link_cfg;
8289 	int rc;
8290 	int8_t old;
8291 
8292 	if (req->newptr == NULL) {
8293 		struct sbuf *sb;
8294 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8295 		    "\5RSVD3\6auto\7module";
8296 
8297 		rc = sysctl_wire_old_buffer(req, 0);
8298 		if (rc != 0)
8299 			return(rc);
8300 
8301 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8302 		if (sb == NULL)
8303 			return (ENOMEM);
8304 
8305 		/*
8306 		 * Display the requested_fec when the link is down -- the actual
8307 		 * FEC makes sense only when the link is up.
8308 		 */
8309 		if (lc->link_ok) {
8310 			sbuf_printf(sb, "%b", (lc->fec & M_FW_PORT_CAP32_FEC) |
8311 			    (lc->requested_fec & (FEC_AUTO | FEC_MODULE)),
8312 			    bits);
8313 		} else {
8314 			sbuf_printf(sb, "%b", lc->requested_fec, bits);
8315 		}
8316 		rc = sbuf_finish(sb);
8317 		sbuf_delete(sb);
8318 	} else {
8319 		char s[8];
8320 		int n;
8321 
8322 		snprintf(s, sizeof(s), "%d",
8323 		    lc->requested_fec == FEC_AUTO ? -1 :
8324 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8325 
8326 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8327 		if (rc != 0)
8328 			return(rc);
8329 
8330 		n = strtol(&s[0], NULL, 0);
8331 		if (n < 0 || n & FEC_AUTO)
8332 			n = FEC_AUTO;
8333 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8334 			return (EINVAL);/* some other bit is set too */
8335 
8336 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8337 		    "t4fec");
8338 		if (rc)
8339 			return (rc);
8340 		PORT_LOCK(pi);
8341 		old = lc->requested_fec;
8342 		if (n == FEC_AUTO)
8343 			lc->requested_fec = FEC_AUTO;
8344 		else if (n == 0 || n == FEC_NONE)
8345 			lc->requested_fec = FEC_NONE;
8346 		else {
8347 			if ((lc->pcaps |
8348 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8349 			    lc->pcaps) {
8350 				rc = ENOTSUP;
8351 				goto done;
8352 			}
8353 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8354 			    FEC_MODULE);
8355 		}
8356 		if (!hw_off_limits(sc)) {
8357 			fixup_link_config(pi);
8358 			if (pi->up_vis > 0) {
8359 				rc = apply_link_config(pi);
8360 				if (rc != 0) {
8361 					lc->requested_fec = old;
8362 					if (rc == FW_EPROTO)
8363 						rc = ENOTSUP;
8364 				}
8365 			}
8366 		}
8367 done:
8368 		PORT_UNLOCK(pi);
8369 		end_synchronized_op(sc, 0);
8370 	}
8371 
8372 	return (rc);
8373 }
8374 
8375 static int
8376 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8377 {
8378 	struct port_info *pi = arg1;
8379 	struct adapter *sc = pi->adapter;
8380 	struct link_config *lc = &pi->link_cfg;
8381 	int rc;
8382 	int8_t fec;
8383 	struct sbuf *sb;
8384 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8385 
8386 	rc = sysctl_wire_old_buffer(req, 0);
8387 	if (rc != 0)
8388 		return (rc);
8389 
8390 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8391 	if (sb == NULL)
8392 		return (ENOMEM);
8393 
8394 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8395 		rc = EBUSY;
8396 		goto done;
8397 	}
8398 	if (hw_off_limits(sc)) {
8399 		rc = ENXIO;
8400 		goto done;
8401 	}
8402 	PORT_LOCK(pi);
8403 	if (pi->up_vis == 0) {
8404 		/*
8405 		 * If all the interfaces are administratively down the firmware
8406 		 * does not report transceiver changes.  Refresh port info here.
8407 		 * This is the only reason we have a synchronized op in this
8408 		 * function.  Just PORT_LOCK would have been enough otherwise.
8409 		 */
8410 		t4_update_port_info(pi);
8411 	}
8412 
8413 	fec = lc->fec_hint;
8414 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8415 	    !fec_supported(lc->pcaps)) {
8416 		sbuf_printf(sb, "n/a");
8417 	} else {
8418 		if (fec == 0)
8419 			fec = FEC_NONE;
8420 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8421 	}
8422 	rc = sbuf_finish(sb);
8423 	PORT_UNLOCK(pi);
8424 done:
8425 	sbuf_delete(sb);
8426 	end_synchronized_op(sc, 0);
8427 
8428 	return (rc);
8429 }
8430 
8431 static int
8432 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8433 {
8434 	struct port_info *pi = arg1;
8435 	struct adapter *sc = pi->adapter;
8436 	struct link_config *lc = &pi->link_cfg;
8437 	int rc, val;
8438 
8439 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8440 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8441 	else
8442 		val = -1;
8443 	rc = sysctl_handle_int(oidp, &val, 0, req);
8444 	if (rc != 0 || req->newptr == NULL)
8445 		return (rc);
8446 	if (val == 0)
8447 		val = AUTONEG_DISABLE;
8448 	else if (val == 1)
8449 		val = AUTONEG_ENABLE;
8450 	else
8451 		val = AUTONEG_AUTO;
8452 
8453 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8454 	    "t4aneg");
8455 	if (rc)
8456 		return (rc);
8457 	PORT_LOCK(pi);
8458 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8459 		rc = ENOTSUP;
8460 		goto done;
8461 	}
8462 	lc->requested_aneg = val;
8463 	if (!hw_off_limits(sc)) {
8464 		fixup_link_config(pi);
8465 		if (pi->up_vis > 0)
8466 			rc = apply_link_config(pi);
8467 		set_current_media(pi);
8468 	}
8469 done:
8470 	PORT_UNLOCK(pi);
8471 	end_synchronized_op(sc, 0);
8472 	return (rc);
8473 }
8474 
8475 static int
8476 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8477 {
8478 	struct adapter *sc = arg1;
8479 	int rc, reg = arg2;
8480 	uint64_t val;
8481 
8482 	mtx_lock(&sc->reg_lock);
8483 	if (hw_off_limits(sc))
8484 		rc = ENXIO;
8485 	else {
8486 		rc = 0;
8487 		val = t4_read_reg64(sc, reg);
8488 	}
8489 	mtx_unlock(&sc->reg_lock);
8490 	if (rc == 0)
8491 		rc = sysctl_handle_64(oidp, &val, 0, req);
8492 	return (rc);
8493 }
8494 
8495 static int
8496 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8497 {
8498 	struct adapter *sc = arg1;
8499 	int rc, t;
8500 	uint32_t param, val;
8501 
8502 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8503 	if (rc)
8504 		return (rc);
8505 	if (hw_off_limits(sc))
8506 		rc = ENXIO;
8507 	else {
8508 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8509 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8510 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8511 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8512 	}
8513 	end_synchronized_op(sc, 0);
8514 	if (rc)
8515 		return (rc);
8516 
8517 	/* unknown is returned as 0 but we display -1 in that case */
8518 	t = val == 0 ? -1 : val;
8519 
8520 	rc = sysctl_handle_int(oidp, &t, 0, req);
8521 	return (rc);
8522 }
8523 
8524 static int
8525 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8526 {
8527 	struct adapter *sc = arg1;
8528 	int rc;
8529 	uint32_t param, val;
8530 
8531 	if (sc->params.core_vdd == 0) {
8532 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8533 		    "t4vdd");
8534 		if (rc)
8535 			return (rc);
8536 		if (hw_off_limits(sc))
8537 			rc = ENXIO;
8538 		else {
8539 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8540 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8541 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8542 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8543 			    &param, &val);
8544 		}
8545 		end_synchronized_op(sc, 0);
8546 		if (rc)
8547 			return (rc);
8548 		sc->params.core_vdd = val;
8549 	}
8550 
8551 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8552 }
8553 
8554 static int
8555 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8556 {
8557 	struct adapter *sc = arg1;
8558 	int rc, v;
8559 	uint32_t param, val;
8560 
8561 	v = sc->sensor_resets;
8562 	rc = sysctl_handle_int(oidp, &v, 0, req);
8563 	if (rc != 0 || req->newptr == NULL || v <= 0)
8564 		return (rc);
8565 
8566 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8567 	    chip_id(sc) < CHELSIO_T5)
8568 		return (ENOTSUP);
8569 
8570 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8571 	if (rc)
8572 		return (rc);
8573 	if (hw_off_limits(sc))
8574 		rc = ENXIO;
8575 	else {
8576 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8577 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8578 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8579 		val = 1;
8580 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8581 	}
8582 	end_synchronized_op(sc, 0);
8583 	if (rc == 0)
8584 		sc->sensor_resets++;
8585 	return (rc);
8586 }
8587 
8588 static int
8589 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8590 {
8591 	struct adapter *sc = arg1;
8592 	struct sbuf *sb;
8593 	int rc;
8594 	uint32_t param, val;
8595 
8596 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8597 	if (rc)
8598 		return (rc);
8599 	if (hw_off_limits(sc))
8600 		rc = ENXIO;
8601 	else {
8602 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8603 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8604 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8605 	}
8606 	end_synchronized_op(sc, 0);
8607 	if (rc)
8608 		return (rc);
8609 
8610 	rc = sysctl_wire_old_buffer(req, 0);
8611 	if (rc != 0)
8612 		return (rc);
8613 
8614 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8615 	if (sb == NULL)
8616 		return (ENOMEM);
8617 
8618 	if (val == 0xffffffff) {
8619 		/* Only debug and custom firmwares report load averages. */
8620 		sbuf_printf(sb, "not available");
8621 	} else {
8622 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8623 		    (val >> 16) & 0xff);
8624 	}
8625 	rc = sbuf_finish(sb);
8626 	sbuf_delete(sb);
8627 
8628 	return (rc);
8629 }
8630 
8631 static int
8632 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8633 {
8634 	struct adapter *sc = arg1;
8635 	struct sbuf *sb;
8636 	int rc, i;
8637 	uint16_t incr[NMTUS][NCCTRL_WIN];
8638 	static const char *dec_fac[] = {
8639 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8640 		"0.9375"
8641 	};
8642 
8643 	rc = sysctl_wire_old_buffer(req, 0);
8644 	if (rc != 0)
8645 		return (rc);
8646 
8647 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8648 	if (sb == NULL)
8649 		return (ENOMEM);
8650 
8651 	mtx_lock(&sc->reg_lock);
8652 	if (hw_off_limits(sc))
8653 		rc = ENXIO;
8654 	else
8655 		t4_read_cong_tbl(sc, incr);
8656 	mtx_unlock(&sc->reg_lock);
8657 	if (rc)
8658 		goto done;
8659 
8660 	for (i = 0; i < NCCTRL_WIN; ++i) {
8661 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8662 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8663 		    incr[5][i], incr[6][i], incr[7][i]);
8664 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8665 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8666 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8667 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8668 	}
8669 
8670 	rc = sbuf_finish(sb);
8671 done:
8672 	sbuf_delete(sb);
8673 	return (rc);
8674 }
8675 
8676 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8677 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8678 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8679 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8680 };
8681 
8682 static int
8683 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8684 {
8685 	struct adapter *sc = arg1;
8686 	struct sbuf *sb;
8687 	int rc, i, n, qid = arg2;
8688 	uint32_t *buf, *p;
8689 	char *qtype;
8690 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8691 
8692 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8693 	    ("%s: bad qid %d\n", __func__, qid));
8694 
8695 	if (qid < CIM_NUM_IBQ) {
8696 		/* inbound queue */
8697 		qtype = "IBQ";
8698 		n = 4 * CIM_IBQ_SIZE;
8699 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8700 		mtx_lock(&sc->reg_lock);
8701 		if (hw_off_limits(sc))
8702 			rc = -ENXIO;
8703 		else
8704 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8705 		mtx_unlock(&sc->reg_lock);
8706 	} else {
8707 		/* outbound queue */
8708 		qtype = "OBQ";
8709 		qid -= CIM_NUM_IBQ;
8710 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8711 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8712 		mtx_lock(&sc->reg_lock);
8713 		if (hw_off_limits(sc))
8714 			rc = -ENXIO;
8715 		else
8716 			rc = t4_read_cim_obq(sc, qid, buf, n);
8717 		mtx_unlock(&sc->reg_lock);
8718 	}
8719 
8720 	if (rc < 0) {
8721 		rc = -rc;
8722 		goto done;
8723 	}
8724 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
8725 
8726 	rc = sysctl_wire_old_buffer(req, 0);
8727 	if (rc != 0)
8728 		goto done;
8729 
8730 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8731 	if (sb == NULL) {
8732 		rc = ENOMEM;
8733 		goto done;
8734 	}
8735 
8736 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8737 	for (i = 0, p = buf; i < n; i += 16, p += 4)
8738 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
8739 		    p[2], p[3]);
8740 
8741 	rc = sbuf_finish(sb);
8742 	sbuf_delete(sb);
8743 done:
8744 	free(buf, M_CXGBE);
8745 	return (rc);
8746 }
8747 
8748 static void
8749 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8750 {
8751 	uint32_t *p;
8752 
8753 	sbuf_printf(sb, "Status   Data      PC%s",
8754 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8755 	    "     LS0Stat  LS0Addr             LS0Data");
8756 
8757 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
8758 		if (cfg & F_UPDBGLACAPTPCONLY) {
8759 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
8760 			    p[6], p[7]);
8761 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
8762 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
8763 			    p[4] & 0xff, p[5] >> 8);
8764 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
8765 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8766 			    p[1] & 0xf, p[2] >> 4);
8767 		} else {
8768 			sbuf_printf(sb,
8769 			    "\n  %02x   %x%07x %x%07x %08x %08x "
8770 			    "%08x%08x%08x%08x",
8771 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8772 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
8773 			    p[6], p[7]);
8774 		}
8775 	}
8776 }
8777 
8778 static void
8779 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8780 {
8781 	uint32_t *p;
8782 
8783 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
8784 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8785 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
8786 
8787 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
8788 		if (cfg & F_UPDBGLACAPTPCONLY) {
8789 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
8790 			    p[3] & 0xff, p[2], p[1], p[0]);
8791 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
8792 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
8793 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
8794 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
8795 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
8796 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
8797 			    p[6] >> 16);
8798 		} else {
8799 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
8800 			    "%08x %08x %08x %08x %08x %08x",
8801 			    (p[9] >> 16) & 0xff,
8802 			    p[9] & 0xffff, p[8] >> 16,
8803 			    p[8] & 0xffff, p[7] >> 16,
8804 			    p[7] & 0xffff, p[6] >> 16,
8805 			    p[2], p[1], p[0], p[5], p[4], p[3]);
8806 		}
8807 	}
8808 }
8809 
8810 static int
8811 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
8812 {
8813 	uint32_t cfg, *buf;
8814 	int rc;
8815 
8816 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
8817 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
8818 	    M_ZERO | flags);
8819 	if (buf == NULL)
8820 		return (ENOMEM);
8821 
8822 	mtx_lock(&sc->reg_lock);
8823 	if (hw_off_limits(sc))
8824 		rc = ENXIO;
8825 	else {
8826 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
8827 		if (rc == 0)
8828 			rc = -t4_cim_read_la(sc, buf, NULL);
8829 	}
8830 	mtx_unlock(&sc->reg_lock);
8831 	if (rc == 0) {
8832 		if (chip_id(sc) < CHELSIO_T6)
8833 			sbuf_cim_la4(sc, sb, buf, cfg);
8834 		else
8835 			sbuf_cim_la6(sc, sb, buf, cfg);
8836 	}
8837 	free(buf, M_CXGBE);
8838 	return (rc);
8839 }
8840 
8841 static int
8842 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
8843 {
8844 	struct adapter *sc = arg1;
8845 	struct sbuf *sb;
8846 	int rc;
8847 
8848 	rc = sysctl_wire_old_buffer(req, 0);
8849 	if (rc != 0)
8850 		return (rc);
8851 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8852 	if (sb == NULL)
8853 		return (ENOMEM);
8854 
8855 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
8856 	if (rc == 0)
8857 		rc = sbuf_finish(sb);
8858 	sbuf_delete(sb);
8859 	return (rc);
8860 }
8861 
8862 bool
8863 t4_os_dump_cimla(struct adapter *sc, int arg, bool verbose)
8864 {
8865 	struct sbuf sb;
8866 	int rc;
8867 
8868 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
8869 		return (false);
8870 	rc = sbuf_cim_la(sc, &sb, M_NOWAIT);
8871 	if (rc == 0) {
8872 		rc = sbuf_finish(&sb);
8873 		if (rc == 0) {
8874 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s",
8875 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
8876 		}
8877 	}
8878 	sbuf_delete(&sb);
8879 	return (false);
8880 }
8881 
8882 static int
8883 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
8884 {
8885 	struct adapter *sc = arg1;
8886 	u_int i;
8887 	struct sbuf *sb;
8888 	uint32_t *buf, *p;
8889 	int rc;
8890 
8891 	rc = sysctl_wire_old_buffer(req, 0);
8892 	if (rc != 0)
8893 		return (rc);
8894 
8895 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8896 	if (sb == NULL)
8897 		return (ENOMEM);
8898 
8899 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
8900 	    M_ZERO | M_WAITOK);
8901 
8902 	mtx_lock(&sc->reg_lock);
8903 	if (hw_off_limits(sc))
8904 		rc = ENXIO;
8905 	else
8906 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
8907 	mtx_unlock(&sc->reg_lock);
8908 	if (rc)
8909 		goto done;
8910 
8911 	p = buf;
8912 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
8913 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
8914 		    p[1], p[0]);
8915 	}
8916 
8917 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
8918 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
8919 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
8920 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
8921 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
8922 		    (p[1] >> 2) | ((p[2] & 3) << 30),
8923 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
8924 		    p[0] & 1);
8925 	}
8926 	rc = sbuf_finish(sb);
8927 done:
8928 	sbuf_delete(sb);
8929 	free(buf, M_CXGBE);
8930 	return (rc);
8931 }
8932 
8933 static int
8934 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
8935 {
8936 	struct adapter *sc = arg1;
8937 	u_int i;
8938 	struct sbuf *sb;
8939 	uint32_t *buf, *p;
8940 	int rc;
8941 
8942 	rc = sysctl_wire_old_buffer(req, 0);
8943 	if (rc != 0)
8944 		return (rc);
8945 
8946 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8947 	if (sb == NULL)
8948 		return (ENOMEM);
8949 
8950 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
8951 	    M_ZERO | M_WAITOK);
8952 
8953 	mtx_lock(&sc->reg_lock);
8954 	if (hw_off_limits(sc))
8955 		rc = ENXIO;
8956 	else
8957 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
8958 	mtx_unlock(&sc->reg_lock);
8959 	if (rc)
8960 		goto done;
8961 
8962 	p = buf;
8963 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
8964 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
8965 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
8966 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
8967 		    p[4], p[3], p[2], p[1], p[0]);
8968 	}
8969 
8970 	sbuf_printf(sb, "\n\nCntl ID               Data");
8971 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
8972 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
8973 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
8974 	}
8975 
8976 	rc = sbuf_finish(sb);
8977 done:
8978 	sbuf_delete(sb);
8979 	free(buf, M_CXGBE);
8980 	return (rc);
8981 }
8982 
8983 static int
8984 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
8985 {
8986 	struct adapter *sc = arg1;
8987 	struct sbuf *sb;
8988 	int rc, i;
8989 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
8990 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
8991 	uint16_t thres[CIM_NUM_IBQ];
8992 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
8993 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
8994 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
8995 
8996 	cim_num_obq = sc->chip_params->cim_num_obq;
8997 	if (is_t4(sc)) {
8998 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
8999 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9000 	} else {
9001 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9002 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9003 	}
9004 	nq = CIM_NUM_IBQ + cim_num_obq;
9005 
9006 	mtx_lock(&sc->reg_lock);
9007 	if (hw_off_limits(sc))
9008 		rc = ENXIO;
9009 	else {
9010 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9011 		if (rc == 0) {
9012 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9013 			    obq_wr);
9014 			if (rc == 0)
9015 				t4_read_cimq_cfg(sc, base, size, thres);
9016 		}
9017 	}
9018 	mtx_unlock(&sc->reg_lock);
9019 	if (rc)
9020 		return (rc);
9021 
9022 	rc = sysctl_wire_old_buffer(req, 0);
9023 	if (rc != 0)
9024 		return (rc);
9025 
9026 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9027 	if (sb == NULL)
9028 		return (ENOMEM);
9029 
9030 	sbuf_printf(sb,
9031 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9032 
9033 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9034 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9035 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9036 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9037 		    G_QUEREMFLITS(p[2]) * 16);
9038 	for ( ; i < nq; i++, p += 4, wr += 2)
9039 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9040 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9041 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9042 		    G_QUEREMFLITS(p[2]) * 16);
9043 
9044 	rc = sbuf_finish(sb);
9045 	sbuf_delete(sb);
9046 
9047 	return (rc);
9048 }
9049 
9050 static int
9051 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9052 {
9053 	struct adapter *sc = arg1;
9054 	struct sbuf *sb;
9055 	int rc;
9056 	struct tp_cpl_stats stats;
9057 
9058 	rc = sysctl_wire_old_buffer(req, 0);
9059 	if (rc != 0)
9060 		return (rc);
9061 
9062 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9063 	if (sb == NULL)
9064 		return (ENOMEM);
9065 
9066 	mtx_lock(&sc->reg_lock);
9067 	if (hw_off_limits(sc))
9068 		rc = ENXIO;
9069 	else
9070 		t4_tp_get_cpl_stats(sc, &stats, 0);
9071 	mtx_unlock(&sc->reg_lock);
9072 	if (rc)
9073 		goto done;
9074 
9075 	if (sc->chip_params->nchan > 2) {
9076 		sbuf_printf(sb, "                 channel 0  channel 1"
9077 		    "  channel 2  channel 3");
9078 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9079 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9080 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9081 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9082 	} else {
9083 		sbuf_printf(sb, "                 channel 0  channel 1");
9084 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9085 		    stats.req[0], stats.req[1]);
9086 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9087 		    stats.rsp[0], stats.rsp[1]);
9088 	}
9089 
9090 	rc = sbuf_finish(sb);
9091 done:
9092 	sbuf_delete(sb);
9093 	return (rc);
9094 }
9095 
9096 static int
9097 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9098 {
9099 	struct adapter *sc = arg1;
9100 	struct sbuf *sb;
9101 	int rc;
9102 	struct tp_usm_stats stats;
9103 
9104 	rc = sysctl_wire_old_buffer(req, 0);
9105 	if (rc != 0)
9106 		return(rc);
9107 
9108 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9109 	if (sb == NULL)
9110 		return (ENOMEM);
9111 
9112 	mtx_lock(&sc->reg_lock);
9113 	if (hw_off_limits(sc))
9114 		rc = ENXIO;
9115 	else
9116 		t4_get_usm_stats(sc, &stats, 1);
9117 	mtx_unlock(&sc->reg_lock);
9118 	if (rc == 0) {
9119 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9120 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9121 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9122 		rc = sbuf_finish(sb);
9123 	}
9124 	sbuf_delete(sb);
9125 
9126 	return (rc);
9127 }
9128 
9129 static int
9130 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9131 {
9132 	struct adapter *sc = arg1;
9133 	struct sbuf *sb;
9134 	int rc;
9135 	struct tp_tid_stats stats;
9136 
9137 	rc = sysctl_wire_old_buffer(req, 0);
9138 	if (rc != 0)
9139 		return(rc);
9140 
9141 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9142 	if (sb == NULL)
9143 		return (ENOMEM);
9144 
9145 	mtx_lock(&sc->reg_lock);
9146 	if (hw_off_limits(sc))
9147 		rc = ENXIO;
9148 	else
9149 		t4_tp_get_tid_stats(sc, &stats, 1);
9150 	mtx_unlock(&sc->reg_lock);
9151 	if (rc == 0) {
9152 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9153 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9154 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9155 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9156 		rc = sbuf_finish(sb);
9157 	}
9158 	sbuf_delete(sb);
9159 
9160 	return (rc);
9161 }
9162 
9163 static const char * const devlog_level_strings[] = {
9164 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9165 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9166 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9167 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9168 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9169 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9170 };
9171 
9172 static const char * const devlog_facility_strings[] = {
9173 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9174 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9175 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9176 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9177 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9178 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9179 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9180 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9181 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9182 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9183 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9184 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9185 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9186 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9187 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9188 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9189 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9190 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9191 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9192 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9193 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9194 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9195 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9196 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9197 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9198 };
9199 
9200 static int
9201 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9202 {
9203 	int i, j, rc, nentries, first = 0;
9204 	struct devlog_params *dparams = &sc->params.devlog;
9205 	struct fw_devlog_e *buf, *e;
9206 	uint64_t ftstamp = UINT64_MAX;
9207 
9208 	if (dparams->addr == 0)
9209 		return (ENXIO);
9210 
9211 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9212 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9213 	if (buf == NULL)
9214 		return (ENOMEM);
9215 
9216 	mtx_lock(&sc->reg_lock);
9217 	if (hw_off_limits(sc))
9218 		rc = ENXIO;
9219 	else
9220 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9221 		    dparams->size);
9222 	mtx_unlock(&sc->reg_lock);
9223 	if (rc != 0)
9224 		goto done;
9225 
9226 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9227 	for (i = 0; i < nentries; i++) {
9228 		e = &buf[i];
9229 
9230 		if (e->timestamp == 0)
9231 			break;	/* end */
9232 
9233 		e->timestamp = be64toh(e->timestamp);
9234 		e->seqno = be32toh(e->seqno);
9235 		for (j = 0; j < 8; j++)
9236 			e->params[j] = be32toh(e->params[j]);
9237 
9238 		if (e->timestamp < ftstamp) {
9239 			ftstamp = e->timestamp;
9240 			first = i;
9241 		}
9242 	}
9243 
9244 	if (buf[first].timestamp == 0)
9245 		goto done;	/* nothing in the log */
9246 
9247 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9248 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9249 
9250 	i = first;
9251 	do {
9252 		e = &buf[i];
9253 		if (e->timestamp == 0)
9254 			break;	/* end */
9255 
9256 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9257 		    e->seqno, e->timestamp,
9258 		    (e->level < nitems(devlog_level_strings) ?
9259 			devlog_level_strings[e->level] : "UNKNOWN"),
9260 		    (e->facility < nitems(devlog_facility_strings) ?
9261 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9262 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9263 		    e->params[2], e->params[3], e->params[4],
9264 		    e->params[5], e->params[6], e->params[7]);
9265 
9266 		if (++i == nentries)
9267 			i = 0;
9268 	} while (i != first);
9269 done:
9270 	free(buf, M_CXGBE);
9271 	return (rc);
9272 }
9273 
9274 static int
9275 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9276 {
9277 	struct adapter *sc = arg1;
9278 	int rc;
9279 	struct sbuf *sb;
9280 
9281 	rc = sysctl_wire_old_buffer(req, 0);
9282 	if (rc != 0)
9283 		return (rc);
9284 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9285 	if (sb == NULL)
9286 		return (ENOMEM);
9287 
9288 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9289 	if (rc == 0)
9290 		rc = sbuf_finish(sb);
9291 	sbuf_delete(sb);
9292 	return (rc);
9293 }
9294 
9295 void
9296 t4_os_dump_devlog(struct adapter *sc)
9297 {
9298 	int rc;
9299 	struct sbuf sb;
9300 
9301 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
9302 		return;
9303 	rc = sbuf_devlog(sc, &sb, M_NOWAIT);
9304 	if (rc == 0) {
9305 		rc = sbuf_finish(&sb);
9306 		if (rc == 0) {
9307 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9308 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
9309 		}
9310 	}
9311 	sbuf_delete(&sb);
9312 }
9313 
9314 static int
9315 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9316 {
9317 	struct adapter *sc = arg1;
9318 	struct sbuf *sb;
9319 	int rc;
9320 	struct tp_fcoe_stats stats[MAX_NCHAN];
9321 	int i, nchan = sc->chip_params->nchan;
9322 
9323 	rc = sysctl_wire_old_buffer(req, 0);
9324 	if (rc != 0)
9325 		return (rc);
9326 
9327 	mtx_lock(&sc->reg_lock);
9328 	if (hw_off_limits(sc))
9329 		rc = ENXIO;
9330 	else {
9331 		for (i = 0; i < nchan; i++)
9332 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9333 	}
9334 	mtx_unlock(&sc->reg_lock);
9335 	if (rc != 0)
9336 		return (rc);
9337 
9338 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9339 	if (sb == NULL)
9340 		return (ENOMEM);
9341 
9342 	if (nchan > 2) {
9343 		sbuf_printf(sb, "                   channel 0        channel 1"
9344 		    "        channel 2        channel 3");
9345 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9346 		    stats[0].octets_ddp, stats[1].octets_ddp,
9347 		    stats[2].octets_ddp, stats[3].octets_ddp);
9348 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9349 		    stats[0].frames_ddp, stats[1].frames_ddp,
9350 		    stats[2].frames_ddp, stats[3].frames_ddp);
9351 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9352 		    stats[0].frames_drop, stats[1].frames_drop,
9353 		    stats[2].frames_drop, stats[3].frames_drop);
9354 	} else {
9355 		sbuf_printf(sb, "                   channel 0        channel 1");
9356 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9357 		    stats[0].octets_ddp, stats[1].octets_ddp);
9358 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9359 		    stats[0].frames_ddp, stats[1].frames_ddp);
9360 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9361 		    stats[0].frames_drop, stats[1].frames_drop);
9362 	}
9363 
9364 	rc = sbuf_finish(sb);
9365 	sbuf_delete(sb);
9366 
9367 	return (rc);
9368 }
9369 
9370 static int
9371 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9372 {
9373 	struct adapter *sc = arg1;
9374 	struct sbuf *sb;
9375 	int rc, i;
9376 	unsigned int map, kbps, ipg, mode;
9377 	unsigned int pace_tab[NTX_SCHED];
9378 
9379 	rc = sysctl_wire_old_buffer(req, 0);
9380 	if (rc != 0)
9381 		return (rc);
9382 
9383 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9384 	if (sb == NULL)
9385 		return (ENOMEM);
9386 
9387 	mtx_lock(&sc->reg_lock);
9388 	if (hw_off_limits(sc)) {
9389 		rc = ENXIO;
9390 		goto done;
9391 	}
9392 
9393 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9394 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9395 	t4_read_pace_tbl(sc, pace_tab);
9396 
9397 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9398 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9399 
9400 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9401 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9402 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9403 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9404 		if (kbps)
9405 			sbuf_printf(sb, "%9u     ", kbps);
9406 		else
9407 			sbuf_printf(sb, " disabled     ");
9408 
9409 		if (ipg)
9410 			sbuf_printf(sb, "%13u        ", ipg);
9411 		else
9412 			sbuf_printf(sb, "     disabled        ");
9413 
9414 		if (pace_tab[i])
9415 			sbuf_printf(sb, "%10u", pace_tab[i]);
9416 		else
9417 			sbuf_printf(sb, "  disabled");
9418 	}
9419 	rc = sbuf_finish(sb);
9420 done:
9421 	mtx_unlock(&sc->reg_lock);
9422 	sbuf_delete(sb);
9423 	return (rc);
9424 }
9425 
9426 static int
9427 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9428 {
9429 	struct adapter *sc = arg1;
9430 	struct sbuf *sb;
9431 	int rc, i, j;
9432 	uint64_t *p0, *p1;
9433 	struct lb_port_stats s[2];
9434 	static const char *stat_name[] = {
9435 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9436 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9437 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9438 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9439 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9440 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9441 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9442 	};
9443 
9444 	rc = sysctl_wire_old_buffer(req, 0);
9445 	if (rc != 0)
9446 		return (rc);
9447 
9448 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9449 	if (sb == NULL)
9450 		return (ENOMEM);
9451 
9452 	memset(s, 0, sizeof(s));
9453 
9454 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9455 		mtx_lock(&sc->reg_lock);
9456 		if (hw_off_limits(sc))
9457 			rc = ENXIO;
9458 		else {
9459 			t4_get_lb_stats(sc, i, &s[0]);
9460 			t4_get_lb_stats(sc, i + 1, &s[1]);
9461 		}
9462 		mtx_unlock(&sc->reg_lock);
9463 		if (rc != 0)
9464 			break;
9465 
9466 		p0 = &s[0].octets;
9467 		p1 = &s[1].octets;
9468 		sbuf_printf(sb, "%s                       Loopback %u"
9469 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9470 
9471 		for (j = 0; j < nitems(stat_name); j++)
9472 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9473 				   *p0++, *p1++);
9474 	}
9475 
9476 	rc = sbuf_finish(sb);
9477 	sbuf_delete(sb);
9478 
9479 	return (rc);
9480 }
9481 
9482 static int
9483 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9484 {
9485 	int rc = 0;
9486 	struct port_info *pi = arg1;
9487 	struct link_config *lc = &pi->link_cfg;
9488 	struct sbuf *sb;
9489 
9490 	rc = sysctl_wire_old_buffer(req, 0);
9491 	if (rc != 0)
9492 		return(rc);
9493 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9494 	if (sb == NULL)
9495 		return (ENOMEM);
9496 
9497 	if (lc->link_ok || lc->link_down_rc == 255)
9498 		sbuf_printf(sb, "n/a");
9499 	else
9500 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9501 
9502 	rc = sbuf_finish(sb);
9503 	sbuf_delete(sb);
9504 
9505 	return (rc);
9506 }
9507 
9508 struct mem_desc {
9509 	unsigned int base;
9510 	unsigned int limit;
9511 	unsigned int idx;
9512 };
9513 
9514 static int
9515 mem_desc_cmp(const void *a, const void *b)
9516 {
9517 	return ((const struct mem_desc *)a)->base -
9518 	       ((const struct mem_desc *)b)->base;
9519 }
9520 
9521 static void
9522 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9523     unsigned int to)
9524 {
9525 	unsigned int size;
9526 
9527 	if (from == to)
9528 		return;
9529 
9530 	size = to - from + 1;
9531 	if (size == 0)
9532 		return;
9533 
9534 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9535 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9536 }
9537 
9538 static int
9539 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9540 {
9541 	struct adapter *sc = arg1;
9542 	struct sbuf *sb;
9543 	int rc, i, n;
9544 	uint32_t lo, hi, used, alloc;
9545 	static const char *memory[] = {
9546 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9547 	};
9548 	static const char *region[] = {
9549 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9550 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9551 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9552 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9553 		"RQUDP region:", "PBL region:", "TXPBL region:",
9554 		"DBVFIFO region:", "ULPRX state:", "ULPTX state:",
9555 		"On-chip queues:", "TLS keys:",
9556 	};
9557 	struct mem_desc avail[4];
9558 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9559 	struct mem_desc *md = mem;
9560 
9561 	rc = sysctl_wire_old_buffer(req, 0);
9562 	if (rc != 0)
9563 		return (rc);
9564 
9565 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9566 	if (sb == NULL)
9567 		return (ENOMEM);
9568 
9569 	for (i = 0; i < nitems(mem); i++) {
9570 		mem[i].limit = 0;
9571 		mem[i].idx = i;
9572 	}
9573 
9574 	mtx_lock(&sc->reg_lock);
9575 	if (hw_off_limits(sc)) {
9576 		rc = ENXIO;
9577 		goto done;
9578 	}
9579 
9580 	/* Find and sort the populated memory ranges */
9581 	i = 0;
9582 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9583 	if (lo & F_EDRAM0_ENABLE) {
9584 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9585 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9586 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9587 		avail[i].idx = 0;
9588 		i++;
9589 	}
9590 	if (lo & F_EDRAM1_ENABLE) {
9591 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9592 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9593 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9594 		avail[i].idx = 1;
9595 		i++;
9596 	}
9597 	if (lo & F_EXT_MEM_ENABLE) {
9598 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9599 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9600 		avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9601 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9602 		i++;
9603 	}
9604 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9605 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9606 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9607 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9608 		avail[i].idx = 4;
9609 		i++;
9610 	}
9611 	if (is_t6(sc) && lo & F_HMA_MUX) {
9612 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9613 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9614 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9615 		avail[i].idx = 5;
9616 		i++;
9617 	}
9618 	MPASS(i <= nitems(avail));
9619 	if (!i)                                    /* no memory available */
9620 		goto done;
9621 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9622 
9623 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9624 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9625 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9626 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9627 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9628 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9629 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9630 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9631 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9632 
9633 	/* the next few have explicit upper bounds */
9634 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9635 	md->limit = md->base - 1 +
9636 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9637 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9638 	md++;
9639 
9640 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9641 	md->limit = md->base - 1 +
9642 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9643 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9644 	md++;
9645 
9646 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9647 		if (chip_id(sc) <= CHELSIO_T5)
9648 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9649 		else
9650 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9651 		md->limit = 0;
9652 	} else {
9653 		md->base = 0;
9654 		md->idx = nitems(region);  /* hide it */
9655 	}
9656 	md++;
9657 
9658 #define ulp_region(reg) \
9659 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9660 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9661 
9662 	ulp_region(RX_ISCSI);
9663 	ulp_region(RX_TDDP);
9664 	ulp_region(TX_TPT);
9665 	ulp_region(RX_STAG);
9666 	ulp_region(RX_RQ);
9667 	ulp_region(RX_RQUDP);
9668 	ulp_region(RX_PBL);
9669 	ulp_region(TX_PBL);
9670 #undef ulp_region
9671 
9672 	md->base = 0;
9673 	if (is_t4(sc))
9674 		md->idx = nitems(region);
9675 	else {
9676 		uint32_t size = 0;
9677 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9678 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9679 
9680 		if (is_t5(sc)) {
9681 			if (sge_ctrl & F_VFIFO_ENABLE)
9682 				size = fifo_size << 2;
9683 		} else
9684 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9685 
9686 		if (size) {
9687 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
9688 			md->limit = md->base + size - 1;
9689 		} else
9690 			md->idx = nitems(region);
9691 	}
9692 	md++;
9693 
9694 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9695 	md->limit = 0;
9696 	md++;
9697 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9698 	md->limit = 0;
9699 	md++;
9700 
9701 	md->base = sc->vres.ocq.start;
9702 	if (sc->vres.ocq.size)
9703 		md->limit = md->base + sc->vres.ocq.size - 1;
9704 	else
9705 		md->idx = nitems(region);  /* hide it */
9706 	md++;
9707 
9708 	md->base = sc->vres.key.start;
9709 	if (sc->vres.key.size)
9710 		md->limit = md->base + sc->vres.key.size - 1;
9711 	else
9712 		md->idx = nitems(region);  /* hide it */
9713 	md++;
9714 
9715 	/* add any address-space holes, there can be up to 3 */
9716 	for (n = 0; n < i - 1; n++)
9717 		if (avail[n].limit < avail[n + 1].base)
9718 			(md++)->base = avail[n].limit;
9719 	if (avail[n].limit)
9720 		(md++)->base = avail[n].limit;
9721 
9722 	n = md - mem;
9723 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
9724 
9725 	for (lo = 0; lo < i; lo++)
9726 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
9727 				avail[lo].limit - 1);
9728 
9729 	sbuf_printf(sb, "\n");
9730 	for (i = 0; i < n; i++) {
9731 		if (mem[i].idx >= nitems(region))
9732 			continue;                        /* skip holes */
9733 		if (!mem[i].limit)
9734 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
9735 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
9736 				mem[i].limit);
9737 	}
9738 
9739 	sbuf_printf(sb, "\n");
9740 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
9741 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
9742 	mem_region_show(sb, "uP RAM:", lo, hi);
9743 
9744 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
9745 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
9746 	mem_region_show(sb, "uP Extmem2:", lo, hi);
9747 
9748 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
9749 	sbuf_printf(sb, "\n%u Rx pages of size %uKiB for %u channels\n",
9750 		   G_PMRXMAXPAGE(lo),
9751 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
9752 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
9753 
9754 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
9755 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
9756 	sbuf_printf(sb, "%u Tx pages of size %u%ciB for %u channels\n",
9757 		   G_PMTXMAXPAGE(lo),
9758 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
9759 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
9760 	sbuf_printf(sb, "%u p-structs\n",
9761 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT));
9762 
9763 	for (i = 0; i < 4; i++) {
9764 		if (chip_id(sc) > CHELSIO_T5)
9765 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
9766 		else
9767 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
9768 		if (is_t5(sc)) {
9769 			used = G_T5_USED(lo);
9770 			alloc = G_T5_ALLOC(lo);
9771 		} else {
9772 			used = G_USED(lo);
9773 			alloc = G_ALLOC(lo);
9774 		}
9775 		/* For T6 these are MAC buffer groups */
9776 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
9777 		    i, used, alloc);
9778 	}
9779 	for (i = 0; i < sc->chip_params->nchan; i++) {
9780 		if (chip_id(sc) > CHELSIO_T5)
9781 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
9782 		else
9783 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
9784 		if (is_t5(sc)) {
9785 			used = G_T5_USED(lo);
9786 			alloc = G_T5_ALLOC(lo);
9787 		} else {
9788 			used = G_USED(lo);
9789 			alloc = G_ALLOC(lo);
9790 		}
9791 		/* For T6 these are MAC buffer groups */
9792 		sbuf_printf(sb,
9793 		    "\nLoopback %d using %u pages out of %u allocated",
9794 		    i, used, alloc);
9795 	}
9796 done:
9797 	mtx_unlock(&sc->reg_lock);
9798 	if (rc == 0)
9799 		rc = sbuf_finish(sb);
9800 	sbuf_delete(sb);
9801 	return (rc);
9802 }
9803 
9804 static inline void
9805 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
9806 {
9807 	*mask = x | y;
9808 	y = htobe64(y);
9809 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
9810 }
9811 
9812 static int
9813 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
9814 {
9815 	struct adapter *sc = arg1;
9816 	struct sbuf *sb;
9817 	int rc, i;
9818 
9819 	MPASS(chip_id(sc) <= CHELSIO_T5);
9820 
9821 	rc = sysctl_wire_old_buffer(req, 0);
9822 	if (rc != 0)
9823 		return (rc);
9824 
9825 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9826 	if (sb == NULL)
9827 		return (ENOMEM);
9828 
9829 	sbuf_printf(sb,
9830 	    "Idx  Ethernet address     Mask     Vld Ports PF"
9831 	    "  VF              Replication             P0 P1 P2 P3  ML");
9832 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
9833 		uint64_t tcamx, tcamy, mask;
9834 		uint32_t cls_lo, cls_hi;
9835 		uint8_t addr[ETHER_ADDR_LEN];
9836 
9837 		mtx_lock(&sc->reg_lock);
9838 		if (hw_off_limits(sc))
9839 			rc = ENXIO;
9840 		else {
9841 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
9842 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
9843 		}
9844 		mtx_unlock(&sc->reg_lock);
9845 		if (rc != 0)
9846 			break;
9847 		if (tcamx & tcamy)
9848 			continue;
9849 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
9850 		mtx_lock(&sc->reg_lock);
9851 		if (hw_off_limits(sc))
9852 			rc = ENXIO;
9853 		else {
9854 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
9855 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
9856 		}
9857 		mtx_unlock(&sc->reg_lock);
9858 		if (rc != 0)
9859 			break;
9860 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
9861 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
9862 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
9863 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
9864 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
9865 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
9866 
9867 		if (cls_lo & F_REPLICATE) {
9868 			struct fw_ldst_cmd ldst_cmd;
9869 
9870 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
9871 			ldst_cmd.op_to_addrspace =
9872 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
9873 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
9874 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
9875 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
9876 			ldst_cmd.u.mps.rplc.fid_idx =
9877 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
9878 				V_FW_LDST_CMD_IDX(i));
9879 
9880 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
9881 			    "t4mps");
9882 			if (rc)
9883 				break;
9884 			if (hw_off_limits(sc))
9885 				rc = ENXIO;
9886 			else
9887 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
9888 				    sizeof(ldst_cmd), &ldst_cmd);
9889 			end_synchronized_op(sc, 0);
9890 			if (rc != 0)
9891 				break;
9892 			else {
9893 				sbuf_printf(sb, " %08x %08x %08x %08x",
9894 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
9895 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
9896 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
9897 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
9898 			}
9899 		} else
9900 			sbuf_printf(sb, "%36s", "");
9901 
9902 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
9903 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
9904 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
9905 	}
9906 
9907 	if (rc)
9908 		(void) sbuf_finish(sb);
9909 	else
9910 		rc = sbuf_finish(sb);
9911 	sbuf_delete(sb);
9912 
9913 	return (rc);
9914 }
9915 
9916 static int
9917 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
9918 {
9919 	struct adapter *sc = arg1;
9920 	struct sbuf *sb;
9921 	int rc, i;
9922 
9923 	MPASS(chip_id(sc) > CHELSIO_T5);
9924 
9925 	rc = sysctl_wire_old_buffer(req, 0);
9926 	if (rc != 0)
9927 		return (rc);
9928 
9929 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9930 	if (sb == NULL)
9931 		return (ENOMEM);
9932 
9933 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
9934 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
9935 	    "                           Replication"
9936 	    "                                    P0 P1 P2 P3  ML\n");
9937 
9938 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
9939 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
9940 		uint16_t ivlan;
9941 		uint64_t tcamx, tcamy, val, mask;
9942 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
9943 		uint8_t addr[ETHER_ADDR_LEN];
9944 
9945 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
9946 		if (i < 256)
9947 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
9948 		else
9949 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
9950 		mtx_lock(&sc->reg_lock);
9951 		if (hw_off_limits(sc))
9952 			rc = ENXIO;
9953 		else {
9954 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
9955 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
9956 			tcamy = G_DMACH(val) << 32;
9957 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
9958 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
9959 		}
9960 		mtx_unlock(&sc->reg_lock);
9961 		if (rc != 0)
9962 			break;
9963 
9964 		lookup_type = G_DATALKPTYPE(data2);
9965 		port_num = G_DATAPORTNUM(data2);
9966 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
9967 			/* Inner header VNI */
9968 			vniy = ((data2 & F_DATAVIDH2) << 23) |
9969 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
9970 			dip_hit = data2 & F_DATADIPHIT;
9971 			vlan_vld = 0;
9972 		} else {
9973 			vniy = 0;
9974 			dip_hit = 0;
9975 			vlan_vld = data2 & F_DATAVIDH2;
9976 			ivlan = G_VIDL(val);
9977 		}
9978 
9979 		ctl |= V_CTLXYBITSEL(1);
9980 		mtx_lock(&sc->reg_lock);
9981 		if (hw_off_limits(sc))
9982 			rc = ENXIO;
9983 		else {
9984 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
9985 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
9986 			tcamx = G_DMACH(val) << 32;
9987 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
9988 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
9989 		}
9990 		mtx_unlock(&sc->reg_lock);
9991 		if (rc != 0)
9992 			break;
9993 
9994 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
9995 			/* Inner header VNI mask */
9996 			vnix = ((data2 & F_DATAVIDH2) << 23) |
9997 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
9998 		} else
9999 			vnix = 0;
10000 
10001 		if (tcamx & tcamy)
10002 			continue;
10003 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10004 
10005 		mtx_lock(&sc->reg_lock);
10006 		if (hw_off_limits(sc))
10007 			rc = ENXIO;
10008 		else {
10009 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10010 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10011 		}
10012 		mtx_unlock(&sc->reg_lock);
10013 		if (rc != 0)
10014 			break;
10015 
10016 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10017 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10018 			    "%012jx %06x %06x    -    -   %3c"
10019 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10020 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10021 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10022 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10023 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10024 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10025 		} else {
10026 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10027 			    "%012jx    -       -   ", i, addr[0], addr[1],
10028 			    addr[2], addr[3], addr[4], addr[5],
10029 			    (uintmax_t)mask);
10030 
10031 			if (vlan_vld)
10032 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10033 			else
10034 				sbuf_printf(sb, "  -    N     ");
10035 
10036 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10037 			    lookup_type ? 'I' : 'O', port_num,
10038 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10039 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10040 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10041 		}
10042 
10043 
10044 		if (cls_lo & F_T6_REPLICATE) {
10045 			struct fw_ldst_cmd ldst_cmd;
10046 
10047 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10048 			ldst_cmd.op_to_addrspace =
10049 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10050 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10051 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10052 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10053 			ldst_cmd.u.mps.rplc.fid_idx =
10054 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10055 				V_FW_LDST_CMD_IDX(i));
10056 
10057 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10058 			    "t6mps");
10059 			if (rc)
10060 				break;
10061 			if (hw_off_limits(sc))
10062 				rc = ENXIO;
10063 			else
10064 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10065 				    sizeof(ldst_cmd), &ldst_cmd);
10066 			end_synchronized_op(sc, 0);
10067 			if (rc != 0)
10068 				break;
10069 			else {
10070 				sbuf_printf(sb, " %08x %08x %08x %08x"
10071 				    " %08x %08x %08x %08x",
10072 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10073 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10074 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10075 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10076 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10077 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10078 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10079 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10080 			}
10081 		} else
10082 			sbuf_printf(sb, "%72s", "");
10083 
10084 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10085 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10086 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10087 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10088 	}
10089 
10090 	if (rc)
10091 		(void) sbuf_finish(sb);
10092 	else
10093 		rc = sbuf_finish(sb);
10094 	sbuf_delete(sb);
10095 
10096 	return (rc);
10097 }
10098 
10099 static int
10100 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10101 {
10102 	struct adapter *sc = arg1;
10103 	struct sbuf *sb;
10104 	int rc;
10105 	uint16_t mtus[NMTUS];
10106 
10107 	rc = sysctl_wire_old_buffer(req, 0);
10108 	if (rc != 0)
10109 		return (rc);
10110 
10111 	mtx_lock(&sc->reg_lock);
10112 	if (hw_off_limits(sc))
10113 		rc = ENXIO;
10114 	else
10115 		t4_read_mtu_tbl(sc, mtus, NULL);
10116 	mtx_unlock(&sc->reg_lock);
10117 	if (rc != 0)
10118 		return (rc);
10119 
10120 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10121 	if (sb == NULL)
10122 		return (ENOMEM);
10123 
10124 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10125 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10126 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10127 	    mtus[14], mtus[15]);
10128 
10129 	rc = sbuf_finish(sb);
10130 	sbuf_delete(sb);
10131 
10132 	return (rc);
10133 }
10134 
10135 static int
10136 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10137 {
10138 	struct adapter *sc = arg1;
10139 	struct sbuf *sb;
10140 	int rc, i;
10141 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10142 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10143 	static const char *tx_stats[MAX_PM_NSTATS] = {
10144 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10145 		"Tx FIFO wait", NULL, "Tx latency"
10146 	};
10147 	static const char *rx_stats[MAX_PM_NSTATS] = {
10148 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10149 		"Rx FIFO wait", NULL, "Rx latency"
10150 	};
10151 
10152 	rc = sysctl_wire_old_buffer(req, 0);
10153 	if (rc != 0)
10154 		return (rc);
10155 
10156 	mtx_lock(&sc->reg_lock);
10157 	if (hw_off_limits(sc))
10158 		rc = ENXIO;
10159 	else {
10160 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10161 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10162 	}
10163 	mtx_unlock(&sc->reg_lock);
10164 	if (rc != 0)
10165 		return (rc);
10166 
10167 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10168 	if (sb == NULL)
10169 		return (ENOMEM);
10170 
10171 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10172 	for (i = 0; i < 4; i++) {
10173 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10174 		    tx_cyc[i]);
10175 	}
10176 
10177 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10178 	for (i = 0; i < 4; i++) {
10179 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10180 		    rx_cyc[i]);
10181 	}
10182 
10183 	if (chip_id(sc) > CHELSIO_T5) {
10184 		sbuf_printf(sb,
10185 		    "\n              Total wait      Total occupancy");
10186 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10187 		    tx_cyc[i]);
10188 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10189 		    rx_cyc[i]);
10190 
10191 		i += 2;
10192 		MPASS(i < nitems(tx_stats));
10193 
10194 		sbuf_printf(sb,
10195 		    "\n                   Reads           Total wait");
10196 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10197 		    tx_cyc[i]);
10198 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10199 		    rx_cyc[i]);
10200 	}
10201 
10202 	rc = sbuf_finish(sb);
10203 	sbuf_delete(sb);
10204 
10205 	return (rc);
10206 }
10207 
10208 static int
10209 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10210 {
10211 	struct adapter *sc = arg1;
10212 	struct sbuf *sb;
10213 	int rc;
10214 	struct tp_rdma_stats stats;
10215 
10216 	rc = sysctl_wire_old_buffer(req, 0);
10217 	if (rc != 0)
10218 		return (rc);
10219 
10220 	mtx_lock(&sc->reg_lock);
10221 	if (hw_off_limits(sc))
10222 		rc = ENXIO;
10223 	else
10224 		t4_tp_get_rdma_stats(sc, &stats, 0);
10225 	mtx_unlock(&sc->reg_lock);
10226 	if (rc != 0)
10227 		return (rc);
10228 
10229 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10230 	if (sb == NULL)
10231 		return (ENOMEM);
10232 
10233 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10234 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10235 
10236 	rc = sbuf_finish(sb);
10237 	sbuf_delete(sb);
10238 
10239 	return (rc);
10240 }
10241 
10242 static int
10243 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10244 {
10245 	struct adapter *sc = arg1;
10246 	struct sbuf *sb;
10247 	int rc;
10248 	struct tp_tcp_stats v4, v6;
10249 
10250 	rc = sysctl_wire_old_buffer(req, 0);
10251 	if (rc != 0)
10252 		return (rc);
10253 
10254 	mtx_lock(&sc->reg_lock);
10255 	if (hw_off_limits(sc))
10256 		rc = ENXIO;
10257 	else
10258 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10259 	mtx_unlock(&sc->reg_lock);
10260 	if (rc != 0)
10261 		return (rc);
10262 
10263 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10264 	if (sb == NULL)
10265 		return (ENOMEM);
10266 
10267 	sbuf_printf(sb,
10268 	    "                                IP                 IPv6\n");
10269 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10270 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10271 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10272 	    v4.tcp_in_segs, v6.tcp_in_segs);
10273 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10274 	    v4.tcp_out_segs, v6.tcp_out_segs);
10275 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10276 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10277 
10278 	rc = sbuf_finish(sb);
10279 	sbuf_delete(sb);
10280 
10281 	return (rc);
10282 }
10283 
10284 static int
10285 sysctl_tids(SYSCTL_HANDLER_ARGS)
10286 {
10287 	struct adapter *sc = arg1;
10288 	struct sbuf *sb;
10289 	int rc;
10290 	uint32_t x, y;
10291 	struct tid_info *t = &sc->tids;
10292 
10293 	rc = sysctl_wire_old_buffer(req, 0);
10294 	if (rc != 0)
10295 		return (rc);
10296 
10297 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10298 	if (sb == NULL)
10299 		return (ENOMEM);
10300 
10301 	if (t->natids) {
10302 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10303 		    t->atids_in_use);
10304 	}
10305 
10306 	if (t->nhpftids) {
10307 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10308 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10309 	}
10310 
10311 	if (t->ntids) {
10312 		bool hashen = false;
10313 
10314 		mtx_lock(&sc->reg_lock);
10315 		if (hw_off_limits(sc))
10316 			rc = ENXIO;
10317 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10318 			hashen = true;
10319 			if (chip_id(sc) <= CHELSIO_T5) {
10320 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10321 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10322 			} else {
10323 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10324 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10325 			}
10326 		}
10327 		mtx_unlock(&sc->reg_lock);
10328 		if (rc != 0)
10329 			goto done;
10330 
10331 		sbuf_printf(sb, "TID range: ");
10332 		if (hashen) {
10333 			if (x)
10334 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10335 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10336 		} else {
10337 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10338 			    t->ntids - 1);
10339 		}
10340 		sbuf_printf(sb, ", in use: %u\n",
10341 		    atomic_load_acq_int(&t->tids_in_use));
10342 	}
10343 
10344 	if (t->nstids) {
10345 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10346 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10347 	}
10348 
10349 	if (t->nftids) {
10350 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10351 		    t->ftid_end, t->ftids_in_use);
10352 	}
10353 
10354 	if (t->netids) {
10355 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10356 		    t->etid_base + t->netids - 1, t->etids_in_use);
10357 	}
10358 
10359 	mtx_lock(&sc->reg_lock);
10360 	if (hw_off_limits(sc))
10361 		rc = ENXIO;
10362 	else {
10363 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10364 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10365 	}
10366 	mtx_unlock(&sc->reg_lock);
10367 	if (rc != 0)
10368 		goto done;
10369 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10370 done:
10371 	if (rc == 0)
10372 		rc = sbuf_finish(sb);
10373 	else
10374 		(void)sbuf_finish(sb);
10375 	sbuf_delete(sb);
10376 
10377 	return (rc);
10378 }
10379 
10380 static int
10381 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10382 {
10383 	struct adapter *sc = arg1;
10384 	struct sbuf *sb;
10385 	int rc;
10386 	struct tp_err_stats stats;
10387 
10388 	rc = sysctl_wire_old_buffer(req, 0);
10389 	if (rc != 0)
10390 		return (rc);
10391 
10392 	mtx_lock(&sc->reg_lock);
10393 	if (hw_off_limits(sc))
10394 		rc = ENXIO;
10395 	else
10396 		t4_tp_get_err_stats(sc, &stats, 0);
10397 	mtx_unlock(&sc->reg_lock);
10398 	if (rc != 0)
10399 		return (rc);
10400 
10401 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10402 	if (sb == NULL)
10403 		return (ENOMEM);
10404 
10405 	if (sc->chip_params->nchan > 2) {
10406 		sbuf_printf(sb, "                 channel 0  channel 1"
10407 		    "  channel 2  channel 3\n");
10408 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10409 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10410 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10411 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10412 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10413 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10414 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10415 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10416 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10417 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10418 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10419 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10420 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10421 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10422 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10423 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10424 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10425 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10426 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10427 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10428 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10429 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10430 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10431 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10432 	} else {
10433 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10434 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10435 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10436 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10437 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10438 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10439 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10440 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10441 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10442 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10443 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10444 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10445 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10446 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10447 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10448 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10449 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10450 	}
10451 
10452 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10453 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10454 
10455 	rc = sbuf_finish(sb);
10456 	sbuf_delete(sb);
10457 
10458 	return (rc);
10459 }
10460 
10461 static int
10462 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10463 {
10464 	struct adapter *sc = arg1;
10465 	struct sbuf *sb;
10466 	int rc;
10467 	struct tp_tnl_stats stats;
10468 
10469 	rc = sysctl_wire_old_buffer(req, 0);
10470 	if (rc != 0)
10471 		return(rc);
10472 
10473 	mtx_lock(&sc->reg_lock);
10474 	if (hw_off_limits(sc))
10475 		rc = ENXIO;
10476 	else
10477 		t4_tp_get_tnl_stats(sc, &stats, 1);
10478 	mtx_unlock(&sc->reg_lock);
10479 	if (rc != 0)
10480 		return (rc);
10481 
10482 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10483 	if (sb == NULL)
10484 		return (ENOMEM);
10485 
10486 	if (sc->chip_params->nchan > 2) {
10487 		sbuf_printf(sb, "           channel 0  channel 1"
10488 		    "  channel 2  channel 3\n");
10489 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10490 		    stats.out_pkt[0], stats.out_pkt[1],
10491 		    stats.out_pkt[2], stats.out_pkt[3]);
10492 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10493 		    stats.in_pkt[0], stats.in_pkt[1],
10494 		    stats.in_pkt[2], stats.in_pkt[3]);
10495 	} else {
10496 		sbuf_printf(sb, "           channel 0  channel 1\n");
10497 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10498 		    stats.out_pkt[0], stats.out_pkt[1]);
10499 		sbuf_printf(sb, "InPkts:   %10u %10u",
10500 		    stats.in_pkt[0], stats.in_pkt[1]);
10501 	}
10502 
10503 	rc = sbuf_finish(sb);
10504 	sbuf_delete(sb);
10505 
10506 	return (rc);
10507 }
10508 
10509 static int
10510 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10511 {
10512 	struct adapter *sc = arg1;
10513 	struct tp_params *tpp = &sc->params.tp;
10514 	u_int mask;
10515 	int rc;
10516 
10517 	mask = tpp->la_mask >> 16;
10518 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10519 	if (rc != 0 || req->newptr == NULL)
10520 		return (rc);
10521 	if (mask > 0xffff)
10522 		return (EINVAL);
10523 	mtx_lock(&sc->reg_lock);
10524 	if (hw_off_limits(sc))
10525 		rc = ENXIO;
10526 	else {
10527 		tpp->la_mask = mask << 16;
10528 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10529 		    tpp->la_mask);
10530 	}
10531 	mtx_unlock(&sc->reg_lock);
10532 
10533 	return (rc);
10534 }
10535 
10536 struct field_desc {
10537 	const char *name;
10538 	u_int start;
10539 	u_int width;
10540 };
10541 
10542 static void
10543 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10544 {
10545 	char buf[32];
10546 	int line_size = 0;
10547 
10548 	while (f->name) {
10549 		uint64_t mask = (1ULL << f->width) - 1;
10550 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10551 		    ((uintmax_t)v >> f->start) & mask);
10552 
10553 		if (line_size + len >= 79) {
10554 			line_size = 8;
10555 			sbuf_printf(sb, "\n        ");
10556 		}
10557 		sbuf_printf(sb, "%s ", buf);
10558 		line_size += len + 1;
10559 		f++;
10560 	}
10561 	sbuf_printf(sb, "\n");
10562 }
10563 
10564 static const struct field_desc tp_la0[] = {
10565 	{ "RcfOpCodeOut", 60, 4 },
10566 	{ "State", 56, 4 },
10567 	{ "WcfState", 52, 4 },
10568 	{ "RcfOpcSrcOut", 50, 2 },
10569 	{ "CRxError", 49, 1 },
10570 	{ "ERxError", 48, 1 },
10571 	{ "SanityFailed", 47, 1 },
10572 	{ "SpuriousMsg", 46, 1 },
10573 	{ "FlushInputMsg", 45, 1 },
10574 	{ "FlushInputCpl", 44, 1 },
10575 	{ "RssUpBit", 43, 1 },
10576 	{ "RssFilterHit", 42, 1 },
10577 	{ "Tid", 32, 10 },
10578 	{ "InitTcb", 31, 1 },
10579 	{ "LineNumber", 24, 7 },
10580 	{ "Emsg", 23, 1 },
10581 	{ "EdataOut", 22, 1 },
10582 	{ "Cmsg", 21, 1 },
10583 	{ "CdataOut", 20, 1 },
10584 	{ "EreadPdu", 19, 1 },
10585 	{ "CreadPdu", 18, 1 },
10586 	{ "TunnelPkt", 17, 1 },
10587 	{ "RcfPeerFin", 16, 1 },
10588 	{ "RcfReasonOut", 12, 4 },
10589 	{ "TxCchannel", 10, 2 },
10590 	{ "RcfTxChannel", 8, 2 },
10591 	{ "RxEchannel", 6, 2 },
10592 	{ "RcfRxChannel", 5, 1 },
10593 	{ "RcfDataOutSrdy", 4, 1 },
10594 	{ "RxDvld", 3, 1 },
10595 	{ "RxOoDvld", 2, 1 },
10596 	{ "RxCongestion", 1, 1 },
10597 	{ "TxCongestion", 0, 1 },
10598 	{ NULL }
10599 };
10600 
10601 static const struct field_desc tp_la1[] = {
10602 	{ "CplCmdIn", 56, 8 },
10603 	{ "CplCmdOut", 48, 8 },
10604 	{ "ESynOut", 47, 1 },
10605 	{ "EAckOut", 46, 1 },
10606 	{ "EFinOut", 45, 1 },
10607 	{ "ERstOut", 44, 1 },
10608 	{ "SynIn", 43, 1 },
10609 	{ "AckIn", 42, 1 },
10610 	{ "FinIn", 41, 1 },
10611 	{ "RstIn", 40, 1 },
10612 	{ "DataIn", 39, 1 },
10613 	{ "DataInVld", 38, 1 },
10614 	{ "PadIn", 37, 1 },
10615 	{ "RxBufEmpty", 36, 1 },
10616 	{ "RxDdp", 35, 1 },
10617 	{ "RxFbCongestion", 34, 1 },
10618 	{ "TxFbCongestion", 33, 1 },
10619 	{ "TxPktSumSrdy", 32, 1 },
10620 	{ "RcfUlpType", 28, 4 },
10621 	{ "Eread", 27, 1 },
10622 	{ "Ebypass", 26, 1 },
10623 	{ "Esave", 25, 1 },
10624 	{ "Static0", 24, 1 },
10625 	{ "Cread", 23, 1 },
10626 	{ "Cbypass", 22, 1 },
10627 	{ "Csave", 21, 1 },
10628 	{ "CPktOut", 20, 1 },
10629 	{ "RxPagePoolFull", 18, 2 },
10630 	{ "RxLpbkPkt", 17, 1 },
10631 	{ "TxLpbkPkt", 16, 1 },
10632 	{ "RxVfValid", 15, 1 },
10633 	{ "SynLearned", 14, 1 },
10634 	{ "SetDelEntry", 13, 1 },
10635 	{ "SetInvEntry", 12, 1 },
10636 	{ "CpcmdDvld", 11, 1 },
10637 	{ "CpcmdSave", 10, 1 },
10638 	{ "RxPstructsFull", 8, 2 },
10639 	{ "EpcmdDvld", 7, 1 },
10640 	{ "EpcmdFlush", 6, 1 },
10641 	{ "EpcmdTrimPrefix", 5, 1 },
10642 	{ "EpcmdTrimPostfix", 4, 1 },
10643 	{ "ERssIp4Pkt", 3, 1 },
10644 	{ "ERssIp6Pkt", 2, 1 },
10645 	{ "ERssTcpUdpPkt", 1, 1 },
10646 	{ "ERssFceFipPkt", 0, 1 },
10647 	{ NULL }
10648 };
10649 
10650 static const struct field_desc tp_la2[] = {
10651 	{ "CplCmdIn", 56, 8 },
10652 	{ "MpsVfVld", 55, 1 },
10653 	{ "MpsPf", 52, 3 },
10654 	{ "MpsVf", 44, 8 },
10655 	{ "SynIn", 43, 1 },
10656 	{ "AckIn", 42, 1 },
10657 	{ "FinIn", 41, 1 },
10658 	{ "RstIn", 40, 1 },
10659 	{ "DataIn", 39, 1 },
10660 	{ "DataInVld", 38, 1 },
10661 	{ "PadIn", 37, 1 },
10662 	{ "RxBufEmpty", 36, 1 },
10663 	{ "RxDdp", 35, 1 },
10664 	{ "RxFbCongestion", 34, 1 },
10665 	{ "TxFbCongestion", 33, 1 },
10666 	{ "TxPktSumSrdy", 32, 1 },
10667 	{ "RcfUlpType", 28, 4 },
10668 	{ "Eread", 27, 1 },
10669 	{ "Ebypass", 26, 1 },
10670 	{ "Esave", 25, 1 },
10671 	{ "Static0", 24, 1 },
10672 	{ "Cread", 23, 1 },
10673 	{ "Cbypass", 22, 1 },
10674 	{ "Csave", 21, 1 },
10675 	{ "CPktOut", 20, 1 },
10676 	{ "RxPagePoolFull", 18, 2 },
10677 	{ "RxLpbkPkt", 17, 1 },
10678 	{ "TxLpbkPkt", 16, 1 },
10679 	{ "RxVfValid", 15, 1 },
10680 	{ "SynLearned", 14, 1 },
10681 	{ "SetDelEntry", 13, 1 },
10682 	{ "SetInvEntry", 12, 1 },
10683 	{ "CpcmdDvld", 11, 1 },
10684 	{ "CpcmdSave", 10, 1 },
10685 	{ "RxPstructsFull", 8, 2 },
10686 	{ "EpcmdDvld", 7, 1 },
10687 	{ "EpcmdFlush", 6, 1 },
10688 	{ "EpcmdTrimPrefix", 5, 1 },
10689 	{ "EpcmdTrimPostfix", 4, 1 },
10690 	{ "ERssIp4Pkt", 3, 1 },
10691 	{ "ERssIp6Pkt", 2, 1 },
10692 	{ "ERssTcpUdpPkt", 1, 1 },
10693 	{ "ERssFceFipPkt", 0, 1 },
10694 	{ NULL }
10695 };
10696 
10697 static void
10698 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10699 {
10700 
10701 	field_desc_show(sb, *p, tp_la0);
10702 }
10703 
10704 static void
10705 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10706 {
10707 
10708 	if (idx)
10709 		sbuf_printf(sb, "\n");
10710 	field_desc_show(sb, p[0], tp_la0);
10711 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10712 		field_desc_show(sb, p[1], tp_la0);
10713 }
10714 
10715 static void
10716 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
10717 {
10718 
10719 	if (idx)
10720 		sbuf_printf(sb, "\n");
10721 	field_desc_show(sb, p[0], tp_la0);
10722 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10723 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
10724 }
10725 
10726 static int
10727 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
10728 {
10729 	struct adapter *sc = arg1;
10730 	struct sbuf *sb;
10731 	uint64_t *buf, *p;
10732 	int rc;
10733 	u_int i, inc;
10734 	void (*show_func)(struct sbuf *, uint64_t *, int);
10735 
10736 	rc = sysctl_wire_old_buffer(req, 0);
10737 	if (rc != 0)
10738 		return (rc);
10739 
10740 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10741 	if (sb == NULL)
10742 		return (ENOMEM);
10743 
10744 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
10745 
10746 	mtx_lock(&sc->reg_lock);
10747 	if (hw_off_limits(sc))
10748 		rc = ENXIO;
10749 	else {
10750 		t4_tp_read_la(sc, buf, NULL);
10751 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
10752 		case 2:
10753 			inc = 2;
10754 			show_func = tp_la_show2;
10755 			break;
10756 		case 3:
10757 			inc = 2;
10758 			show_func = tp_la_show3;
10759 			break;
10760 		default:
10761 			inc = 1;
10762 			show_func = tp_la_show;
10763 		}
10764 	}
10765 	mtx_unlock(&sc->reg_lock);
10766 	if (rc != 0)
10767 		goto done;
10768 
10769 	p = buf;
10770 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
10771 		(*show_func)(sb, p, i);
10772 	rc = sbuf_finish(sb);
10773 done:
10774 	sbuf_delete(sb);
10775 	free(buf, M_CXGBE);
10776 	return (rc);
10777 }
10778 
10779 static int
10780 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
10781 {
10782 	struct adapter *sc = arg1;
10783 	struct sbuf *sb;
10784 	int rc;
10785 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
10786 
10787 	rc = sysctl_wire_old_buffer(req, 0);
10788 	if (rc != 0)
10789 		return (rc);
10790 
10791 	mtx_lock(&sc->reg_lock);
10792 	if (hw_off_limits(sc))
10793 		rc = ENXIO;
10794 	else
10795 		t4_get_chan_txrate(sc, nrate, orate);
10796 	mtx_unlock(&sc->reg_lock);
10797 	if (rc != 0)
10798 		return (rc);
10799 
10800 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10801 	if (sb == NULL)
10802 		return (ENOMEM);
10803 
10804 	if (sc->chip_params->nchan > 2) {
10805 		sbuf_printf(sb, "              channel 0   channel 1"
10806 		    "   channel 2   channel 3\n");
10807 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
10808 		    nrate[0], nrate[1], nrate[2], nrate[3]);
10809 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
10810 		    orate[0], orate[1], orate[2], orate[3]);
10811 	} else {
10812 		sbuf_printf(sb, "              channel 0   channel 1\n");
10813 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
10814 		    nrate[0], nrate[1]);
10815 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
10816 		    orate[0], orate[1]);
10817 	}
10818 
10819 	rc = sbuf_finish(sb);
10820 	sbuf_delete(sb);
10821 
10822 	return (rc);
10823 }
10824 
10825 static int
10826 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
10827 {
10828 	struct adapter *sc = arg1;
10829 	struct sbuf *sb;
10830 	uint32_t *buf, *p;
10831 	int rc, i;
10832 
10833 	rc = sysctl_wire_old_buffer(req, 0);
10834 	if (rc != 0)
10835 		return (rc);
10836 
10837 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10838 	if (sb == NULL)
10839 		return (ENOMEM);
10840 
10841 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
10842 	    M_ZERO | M_WAITOK);
10843 
10844 	mtx_lock(&sc->reg_lock);
10845 	if (hw_off_limits(sc))
10846 		rc = ENXIO;
10847 	else
10848 		t4_ulprx_read_la(sc, buf);
10849 	mtx_unlock(&sc->reg_lock);
10850 	if (rc != 0)
10851 		goto done;
10852 
10853 	p = buf;
10854 	sbuf_printf(sb, "      Pcmd        Type   Message"
10855 	    "                Data");
10856 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
10857 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
10858 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
10859 	}
10860 	rc = sbuf_finish(sb);
10861 done:
10862 	sbuf_delete(sb);
10863 	free(buf, M_CXGBE);
10864 	return (rc);
10865 }
10866 
10867 static int
10868 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
10869 {
10870 	struct adapter *sc = arg1;
10871 	struct sbuf *sb;
10872 	int rc;
10873 	uint32_t cfg, s1, s2;
10874 
10875 	MPASS(chip_id(sc) >= CHELSIO_T5);
10876 
10877 	rc = sysctl_wire_old_buffer(req, 0);
10878 	if (rc != 0)
10879 		return (rc);
10880 
10881 	mtx_lock(&sc->reg_lock);
10882 	if (hw_off_limits(sc))
10883 		rc = ENXIO;
10884 	else {
10885 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
10886 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
10887 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
10888 	}
10889 	mtx_unlock(&sc->reg_lock);
10890 	if (rc != 0)
10891 		return (rc);
10892 
10893 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10894 	if (sb == NULL)
10895 		return (ENOMEM);
10896 
10897 	if (G_STATSOURCE_T5(cfg) == 7) {
10898 		int mode;
10899 
10900 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
10901 		if (mode == 0)
10902 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
10903 		else if (mode == 1)
10904 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
10905 		else
10906 			sbuf_printf(sb, "unknown mode %d", mode);
10907 	}
10908 	rc = sbuf_finish(sb);
10909 	sbuf_delete(sb);
10910 
10911 	return (rc);
10912 }
10913 
10914 static int
10915 sysctl_cpus(SYSCTL_HANDLER_ARGS)
10916 {
10917 	struct adapter *sc = arg1;
10918 	enum cpu_sets op = arg2;
10919 	cpuset_t cpuset;
10920 	struct sbuf *sb;
10921 	int i, rc;
10922 
10923 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
10924 
10925 	CPU_ZERO(&cpuset);
10926 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
10927 	if (rc != 0)
10928 		return (rc);
10929 
10930 	rc = sysctl_wire_old_buffer(req, 0);
10931 	if (rc != 0)
10932 		return (rc);
10933 
10934 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10935 	if (sb == NULL)
10936 		return (ENOMEM);
10937 
10938 	CPU_FOREACH(i)
10939 		sbuf_printf(sb, "%d ", i);
10940 	rc = sbuf_finish(sb);
10941 	sbuf_delete(sb);
10942 
10943 	return (rc);
10944 }
10945 
10946 static int
10947 sysctl_reset(SYSCTL_HANDLER_ARGS)
10948 {
10949 	struct adapter *sc = arg1;
10950 	u_int val;
10951 	int rc;
10952 
10953 	val = sc->num_resets;
10954 	rc = sysctl_handle_int(oidp, &val, 0, req);
10955 	if (rc != 0 || req->newptr == NULL)
10956 		return (rc);
10957 
10958 	if (val == 0) {
10959 		/* Zero out the counter that tracks reset. */
10960 		sc->num_resets = 0;
10961 		return (0);
10962 	}
10963 
10964 	if (val != 1)
10965 		return (EINVAL);	/* 0 or 1 are the only legal values */
10966 
10967 	if (hw_off_limits(sc))		/* harmless race */
10968 		return (EALREADY);
10969 
10970 	taskqueue_enqueue(reset_tq, &sc->reset_task);
10971 	return (0);
10972 }
10973 
10974 #ifdef TCP_OFFLOAD
10975 static int
10976 sysctl_tls(SYSCTL_HANDLER_ARGS)
10977 {
10978 	struct adapter *sc = arg1;
10979 	int i, j, v, rc;
10980 	struct vi_info *vi;
10981 
10982 	v = sc->tt.tls;
10983 	rc = sysctl_handle_int(oidp, &v, 0, req);
10984 	if (rc != 0 || req->newptr == NULL)
10985 		return (rc);
10986 
10987 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
10988 		return (ENOTSUP);
10989 
10990 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
10991 	if (rc)
10992 		return (rc);
10993 	if (hw_off_limits(sc))
10994 		rc = ENXIO;
10995 	else {
10996 		sc->tt.tls = !!v;
10997 		for_each_port(sc, i) {
10998 			for_each_vi(sc->port[i], j, vi) {
10999 				if (vi->flags & VI_INIT_DONE)
11000 					t4_update_fl_bufsize(vi->ifp);
11001 			}
11002 		}
11003 	}
11004 	end_synchronized_op(sc, 0);
11005 
11006 	return (rc);
11007 
11008 }
11009 
11010 static int
11011 sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS)
11012 {
11013 	struct adapter *sc = arg1;
11014 	int *old_ports, *new_ports;
11015 	int i, new_count, rc;
11016 
11017 	if (req->newptr == NULL && req->oldptr == NULL)
11018 		return (SYSCTL_OUT(req, NULL, imax(sc->tt.num_tls_rx_ports, 1) *
11019 		    sizeof(sc->tt.tls_rx_ports[0])));
11020 
11021 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tlsrx");
11022 	if (rc)
11023 		return (rc);
11024 
11025 	if (hw_off_limits(sc)) {
11026 		rc = ENXIO;
11027 		goto done;
11028 	}
11029 
11030 	if (sc->tt.num_tls_rx_ports == 0) {
11031 		i = -1;
11032 		rc = SYSCTL_OUT(req, &i, sizeof(i));
11033 	} else
11034 		rc = SYSCTL_OUT(req, sc->tt.tls_rx_ports,
11035 		    sc->tt.num_tls_rx_ports * sizeof(sc->tt.tls_rx_ports[0]));
11036 	if (rc == 0 && req->newptr != NULL) {
11037 		new_count = req->newlen / sizeof(new_ports[0]);
11038 		new_ports = malloc(new_count * sizeof(new_ports[0]), M_CXGBE,
11039 		    M_WAITOK);
11040 		rc = SYSCTL_IN(req, new_ports, new_count *
11041 		    sizeof(new_ports[0]));
11042 		if (rc)
11043 			goto err;
11044 
11045 		/* Allow setting to a single '-1' to clear the list. */
11046 		if (new_count == 1 && new_ports[0] == -1) {
11047 			ADAPTER_LOCK(sc);
11048 			old_ports = sc->tt.tls_rx_ports;
11049 			sc->tt.tls_rx_ports = NULL;
11050 			sc->tt.num_tls_rx_ports = 0;
11051 			ADAPTER_UNLOCK(sc);
11052 			free(old_ports, M_CXGBE);
11053 		} else {
11054 			for (i = 0; i < new_count; i++) {
11055 				if (new_ports[i] < 1 ||
11056 				    new_ports[i] > IPPORT_MAX) {
11057 					rc = EINVAL;
11058 					goto err;
11059 				}
11060 			}
11061 
11062 			ADAPTER_LOCK(sc);
11063 			old_ports = sc->tt.tls_rx_ports;
11064 			sc->tt.tls_rx_ports = new_ports;
11065 			sc->tt.num_tls_rx_ports = new_count;
11066 			ADAPTER_UNLOCK(sc);
11067 			free(old_ports, M_CXGBE);
11068 			new_ports = NULL;
11069 		}
11070 	err:
11071 		free(new_ports, M_CXGBE);
11072 	}
11073 done:
11074 	end_synchronized_op(sc, 0);
11075 	return (rc);
11076 }
11077 
11078 static int
11079 sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS)
11080 {
11081 	struct adapter *sc = arg1;
11082 	int v, rc;
11083 
11084 	v = sc->tt.tls_rx_timeout;
11085 	rc = sysctl_handle_int(oidp, &v, 0, req);
11086 	if (rc != 0 || req->newptr == NULL)
11087 		return (rc);
11088 
11089 	if (v < 0)
11090 		return (EINVAL);
11091 
11092 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11093 		return (ENOTSUP);
11094 
11095 	sc->tt.tls_rx_timeout = v;
11096 
11097 	return (0);
11098 
11099 }
11100 
11101 static void
11102 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11103 {
11104 	u_int rem = val % factor;
11105 
11106 	if (rem == 0)
11107 		snprintf(buf, len, "%u", val / factor);
11108 	else {
11109 		while (rem % 10 == 0)
11110 			rem /= 10;
11111 		snprintf(buf, len, "%u.%u", val / factor, rem);
11112 	}
11113 }
11114 
11115 static int
11116 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11117 {
11118 	struct adapter *sc = arg1;
11119 	char buf[16];
11120 	u_int res, re;
11121 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11122 
11123 	mtx_lock(&sc->reg_lock);
11124 	if (hw_off_limits(sc))
11125 		res = (u_int)-1;
11126 	else
11127 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11128 	mtx_unlock(&sc->reg_lock);
11129 	if (res == (u_int)-1)
11130 		return (ENXIO);
11131 
11132 	switch (arg2) {
11133 	case 0:
11134 		/* timer_tick */
11135 		re = G_TIMERRESOLUTION(res);
11136 		break;
11137 	case 1:
11138 		/* TCP timestamp tick */
11139 		re = G_TIMESTAMPRESOLUTION(res);
11140 		break;
11141 	case 2:
11142 		/* DACK tick */
11143 		re = G_DELAYEDACKRESOLUTION(res);
11144 		break;
11145 	default:
11146 		return (EDOOFUS);
11147 	}
11148 
11149 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11150 
11151 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11152 }
11153 
11154 static int
11155 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11156 {
11157 	struct adapter *sc = arg1;
11158 	int rc;
11159 	u_int dack_tmr, dack_re, v;
11160 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11161 
11162 	mtx_lock(&sc->reg_lock);
11163 	if (hw_off_limits(sc))
11164 		rc = ENXIO;
11165 	else {
11166 		rc = 0;
11167 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11168 		    A_TP_TIMER_RESOLUTION));
11169 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11170 	}
11171 	mtx_unlock(&sc->reg_lock);
11172 	if (rc != 0)
11173 		return (rc);
11174 
11175 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11176 
11177 	return (sysctl_handle_int(oidp, &v, 0, req));
11178 }
11179 
11180 static int
11181 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11182 {
11183 	struct adapter *sc = arg1;
11184 	int rc, reg = arg2;
11185 	u_int tre;
11186 	u_long tp_tick_us, v;
11187 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11188 
11189 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11190 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11191 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11192 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11193 
11194 	mtx_lock(&sc->reg_lock);
11195 	if (hw_off_limits(sc))
11196 		rc = ENXIO;
11197 	else {
11198 		rc = 0;
11199 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11200 		tp_tick_us = (cclk_ps << tre) / 1000000;
11201 		if (reg == A_TP_INIT_SRTT)
11202 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11203 		else
11204 			v = tp_tick_us * t4_read_reg(sc, reg);
11205 	}
11206 	mtx_unlock(&sc->reg_lock);
11207 	if (rc != 0)
11208 		return (rc);
11209 	else
11210 		return (sysctl_handle_long(oidp, &v, 0, req));
11211 }
11212 
11213 /*
11214  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11215  * passed to this function.
11216  */
11217 static int
11218 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11219 {
11220 	struct adapter *sc = arg1;
11221 	int rc, idx = arg2;
11222 	u_int v;
11223 
11224 	MPASS(idx >= 0 && idx <= 24);
11225 
11226 	mtx_lock(&sc->reg_lock);
11227 	if (hw_off_limits(sc))
11228 		rc = ENXIO;
11229 	else {
11230 		rc = 0;
11231 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11232 	}
11233 	mtx_unlock(&sc->reg_lock);
11234 	if (rc != 0)
11235 		return (rc);
11236 	else
11237 		return (sysctl_handle_int(oidp, &v, 0, req));
11238 }
11239 
11240 static int
11241 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11242 {
11243 	struct adapter *sc = arg1;
11244 	int rc, idx = arg2;
11245 	u_int shift, v, r;
11246 
11247 	MPASS(idx >= 0 && idx < 16);
11248 
11249 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11250 	shift = (idx & 3) << 3;
11251 	mtx_lock(&sc->reg_lock);
11252 	if (hw_off_limits(sc))
11253 		rc = ENXIO;
11254 	else {
11255 		rc = 0;
11256 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11257 	}
11258 	mtx_unlock(&sc->reg_lock);
11259 	if (rc != 0)
11260 		return (rc);
11261 	else
11262 		return (sysctl_handle_int(oidp, &v, 0, req));
11263 }
11264 
11265 static int
11266 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11267 {
11268 	struct vi_info *vi = arg1;
11269 	struct adapter *sc = vi->adapter;
11270 	int idx, rc, i;
11271 	struct sge_ofld_rxq *ofld_rxq;
11272 	uint8_t v;
11273 
11274 	idx = vi->ofld_tmr_idx;
11275 
11276 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11277 	if (rc != 0 || req->newptr == NULL)
11278 		return (rc);
11279 
11280 	if (idx < 0 || idx >= SGE_NTIMERS)
11281 		return (EINVAL);
11282 
11283 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11284 	    "t4otmr");
11285 	if (rc)
11286 		return (rc);
11287 
11288 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11289 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11290 #ifdef atomic_store_rel_8
11291 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11292 #else
11293 		ofld_rxq->iq.intr_params = v;
11294 #endif
11295 	}
11296 	vi->ofld_tmr_idx = idx;
11297 
11298 	end_synchronized_op(sc, LOCK_HELD);
11299 	return (0);
11300 }
11301 
11302 static int
11303 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11304 {
11305 	struct vi_info *vi = arg1;
11306 	struct adapter *sc = vi->adapter;
11307 	int idx, rc;
11308 
11309 	idx = vi->ofld_pktc_idx;
11310 
11311 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11312 	if (rc != 0 || req->newptr == NULL)
11313 		return (rc);
11314 
11315 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11316 		return (EINVAL);
11317 
11318 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11319 	    "t4opktc");
11320 	if (rc)
11321 		return (rc);
11322 
11323 	if (vi->flags & VI_INIT_DONE)
11324 		rc = EBUSY; /* cannot be changed once the queues are created */
11325 	else
11326 		vi->ofld_pktc_idx = idx;
11327 
11328 	end_synchronized_op(sc, LOCK_HELD);
11329 	return (rc);
11330 }
11331 #endif
11332 
11333 static int
11334 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11335 {
11336 	int rc;
11337 
11338 	if (cntxt->cid > M_CTXTQID)
11339 		return (EINVAL);
11340 
11341 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11342 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11343 		return (EINVAL);
11344 
11345 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11346 	if (rc)
11347 		return (rc);
11348 
11349 	if (hw_off_limits(sc)) {
11350 		rc = ENXIO;
11351 		goto done;
11352 	}
11353 
11354 	if (sc->flags & FW_OK) {
11355 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11356 		    &cntxt->data[0]);
11357 		if (rc == 0)
11358 			goto done;
11359 	}
11360 
11361 	/*
11362 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11363 	 * the backdoor.
11364 	 */
11365 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11366 done:
11367 	end_synchronized_op(sc, 0);
11368 	return (rc);
11369 }
11370 
11371 static int
11372 load_fw(struct adapter *sc, struct t4_data *fw)
11373 {
11374 	int rc;
11375 	uint8_t *fw_data;
11376 
11377 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11378 	if (rc)
11379 		return (rc);
11380 
11381 	if (hw_off_limits(sc)) {
11382 		rc = ENXIO;
11383 		goto done;
11384 	}
11385 
11386 	/*
11387 	 * The firmware, with the sole exception of the memory parity error
11388 	 * handler, runs from memory and not flash.  It is almost always safe to
11389 	 * install a new firmware on a running system.  Just set bit 1 in
11390 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11391 	 */
11392 	if (sc->flags & FULL_INIT_DONE &&
11393 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11394 		rc = EBUSY;
11395 		goto done;
11396 	}
11397 
11398 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11399 
11400 	rc = copyin(fw->data, fw_data, fw->len);
11401 	if (rc == 0)
11402 		rc = -t4_load_fw(sc, fw_data, fw->len);
11403 
11404 	free(fw_data, M_CXGBE);
11405 done:
11406 	end_synchronized_op(sc, 0);
11407 	return (rc);
11408 }
11409 
11410 static int
11411 load_cfg(struct adapter *sc, struct t4_data *cfg)
11412 {
11413 	int rc;
11414 	uint8_t *cfg_data = NULL;
11415 
11416 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11417 	if (rc)
11418 		return (rc);
11419 
11420 	if (hw_off_limits(sc)) {
11421 		rc = ENXIO;
11422 		goto done;
11423 	}
11424 
11425 	if (cfg->len == 0) {
11426 		/* clear */
11427 		rc = -t4_load_cfg(sc, NULL, 0);
11428 		goto done;
11429 	}
11430 
11431 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11432 
11433 	rc = copyin(cfg->data, cfg_data, cfg->len);
11434 	if (rc == 0)
11435 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11436 
11437 	free(cfg_data, M_CXGBE);
11438 done:
11439 	end_synchronized_op(sc, 0);
11440 	return (rc);
11441 }
11442 
11443 static int
11444 load_boot(struct adapter *sc, struct t4_bootrom *br)
11445 {
11446 	int rc;
11447 	uint8_t *br_data = NULL;
11448 	u_int offset;
11449 
11450 	if (br->len > 1024 * 1024)
11451 		return (EFBIG);
11452 
11453 	if (br->pf_offset == 0) {
11454 		/* pfidx */
11455 		if (br->pfidx_addr > 7)
11456 			return (EINVAL);
11457 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11458 		    A_PCIE_PF_EXPROM_OFST)));
11459 	} else if (br->pf_offset == 1) {
11460 		/* offset */
11461 		offset = G_OFFSET(br->pfidx_addr);
11462 	} else {
11463 		return (EINVAL);
11464 	}
11465 
11466 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11467 	if (rc)
11468 		return (rc);
11469 
11470 	if (hw_off_limits(sc)) {
11471 		rc = ENXIO;
11472 		goto done;
11473 	}
11474 
11475 	if (br->len == 0) {
11476 		/* clear */
11477 		rc = -t4_load_boot(sc, NULL, offset, 0);
11478 		goto done;
11479 	}
11480 
11481 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11482 
11483 	rc = copyin(br->data, br_data, br->len);
11484 	if (rc == 0)
11485 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11486 
11487 	free(br_data, M_CXGBE);
11488 done:
11489 	end_synchronized_op(sc, 0);
11490 	return (rc);
11491 }
11492 
11493 static int
11494 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11495 {
11496 	int rc;
11497 	uint8_t *bc_data = NULL;
11498 
11499 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11500 	if (rc)
11501 		return (rc);
11502 
11503 	if (hw_off_limits(sc)) {
11504 		rc = ENXIO;
11505 		goto done;
11506 	}
11507 
11508 	if (bc->len == 0) {
11509 		/* clear */
11510 		rc = -t4_load_bootcfg(sc, NULL, 0);
11511 		goto done;
11512 	}
11513 
11514 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11515 
11516 	rc = copyin(bc->data, bc_data, bc->len);
11517 	if (rc == 0)
11518 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11519 
11520 	free(bc_data, M_CXGBE);
11521 done:
11522 	end_synchronized_op(sc, 0);
11523 	return (rc);
11524 }
11525 
11526 static int
11527 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11528 {
11529 	int rc;
11530 	struct cudbg_init *cudbg;
11531 	void *handle, *buf;
11532 
11533 	/* buf is large, don't block if no memory is available */
11534 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11535 	if (buf == NULL)
11536 		return (ENOMEM);
11537 
11538 	handle = cudbg_alloc_handle();
11539 	if (handle == NULL) {
11540 		rc = ENOMEM;
11541 		goto done;
11542 	}
11543 
11544 	cudbg = cudbg_get_init(handle);
11545 	cudbg->adap = sc;
11546 	cudbg->print = (cudbg_print_cb)printf;
11547 
11548 #ifndef notyet
11549 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11550 	    __func__, dump->wr_flash, dump->len, dump->data);
11551 #endif
11552 
11553 	if (dump->wr_flash)
11554 		cudbg->use_flash = 1;
11555 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11556 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11557 
11558 	rc = cudbg_collect(handle, buf, &dump->len);
11559 	if (rc != 0)
11560 		goto done;
11561 
11562 	rc = copyout(buf, dump->data, dump->len);
11563 done:
11564 	cudbg_free_handle(handle);
11565 	free(buf, M_CXGBE);
11566 	return (rc);
11567 }
11568 
11569 static void
11570 free_offload_policy(struct t4_offload_policy *op)
11571 {
11572 	struct offload_rule *r;
11573 	int i;
11574 
11575 	if (op == NULL)
11576 		return;
11577 
11578 	r = &op->rule[0];
11579 	for (i = 0; i < op->nrules; i++, r++) {
11580 		free(r->bpf_prog.bf_insns, M_CXGBE);
11581 	}
11582 	free(op->rule, M_CXGBE);
11583 	free(op, M_CXGBE);
11584 }
11585 
11586 static int
11587 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11588 {
11589 	int i, rc, len;
11590 	struct t4_offload_policy *op, *old;
11591 	struct bpf_program *bf;
11592 	const struct offload_settings *s;
11593 	struct offload_rule *r;
11594 	void *u;
11595 
11596 	if (!is_offload(sc))
11597 		return (ENODEV);
11598 
11599 	if (uop->nrules == 0) {
11600 		/* Delete installed policies. */
11601 		op = NULL;
11602 		goto set_policy;
11603 	} else if (uop->nrules > 256) { /* arbitrary */
11604 		return (E2BIG);
11605 	}
11606 
11607 	/* Copy userspace offload policy to kernel */
11608 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11609 	op->nrules = uop->nrules;
11610 	len = op->nrules * sizeof(struct offload_rule);
11611 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11612 	rc = copyin(uop->rule, op->rule, len);
11613 	if (rc) {
11614 		free(op->rule, M_CXGBE);
11615 		free(op, M_CXGBE);
11616 		return (rc);
11617 	}
11618 
11619 	r = &op->rule[0];
11620 	for (i = 0; i < op->nrules; i++, r++) {
11621 
11622 		/* Validate open_type */
11623 		if (r->open_type != OPEN_TYPE_LISTEN &&
11624 		    r->open_type != OPEN_TYPE_ACTIVE &&
11625 		    r->open_type != OPEN_TYPE_PASSIVE &&
11626 		    r->open_type != OPEN_TYPE_DONTCARE) {
11627 error:
11628 			/*
11629 			 * Rules 0 to i have malloc'd filters that need to be
11630 			 * freed.  Rules i+1 to nrules have userspace pointers
11631 			 * and should be left alone.
11632 			 */
11633 			op->nrules = i;
11634 			free_offload_policy(op);
11635 			return (rc);
11636 		}
11637 
11638 		/* Validate settings */
11639 		s = &r->settings;
11640 		if ((s->offload != 0 && s->offload != 1) ||
11641 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11642 		    s->sched_class < -1 ||
11643 		    s->sched_class >= sc->params.nsched_cls) {
11644 			rc = EINVAL;
11645 			goto error;
11646 		}
11647 
11648 		bf = &r->bpf_prog;
11649 		u = bf->bf_insns;	/* userspace ptr */
11650 		bf->bf_insns = NULL;
11651 		if (bf->bf_len == 0) {
11652 			/* legal, matches everything */
11653 			continue;
11654 		}
11655 		len = bf->bf_len * sizeof(*bf->bf_insns);
11656 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11657 		rc = copyin(u, bf->bf_insns, len);
11658 		if (rc != 0)
11659 			goto error;
11660 
11661 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11662 			rc = EINVAL;
11663 			goto error;
11664 		}
11665 	}
11666 set_policy:
11667 	rw_wlock(&sc->policy_lock);
11668 	old = sc->policy;
11669 	sc->policy = op;
11670 	rw_wunlock(&sc->policy_lock);
11671 	free_offload_policy(old);
11672 
11673 	return (0);
11674 }
11675 
11676 #define MAX_READ_BUF_SIZE (128 * 1024)
11677 static int
11678 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11679 {
11680 	uint32_t addr, remaining, n;
11681 	uint32_t *buf;
11682 	int rc;
11683 	uint8_t *dst;
11684 
11685 	mtx_lock(&sc->reg_lock);
11686 	if (hw_off_limits(sc))
11687 		rc = ENXIO;
11688 	else
11689 		rc = validate_mem_range(sc, mr->addr, mr->len);
11690 	mtx_unlock(&sc->reg_lock);
11691 	if (rc != 0)
11692 		return (rc);
11693 
11694 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11695 	addr = mr->addr;
11696 	remaining = mr->len;
11697 	dst = (void *)mr->data;
11698 
11699 	while (remaining) {
11700 		n = min(remaining, MAX_READ_BUF_SIZE);
11701 		mtx_lock(&sc->reg_lock);
11702 		if (hw_off_limits(sc))
11703 			rc = ENXIO;
11704 		else
11705 			read_via_memwin(sc, 2, addr, buf, n);
11706 		mtx_unlock(&sc->reg_lock);
11707 		if (rc != 0)
11708 			break;
11709 
11710 		rc = copyout(buf, dst, n);
11711 		if (rc != 0)
11712 			break;
11713 
11714 		dst += n;
11715 		remaining -= n;
11716 		addr += n;
11717 	}
11718 
11719 	free(buf, M_CXGBE);
11720 	return (rc);
11721 }
11722 #undef MAX_READ_BUF_SIZE
11723 
11724 static int
11725 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11726 {
11727 	int rc;
11728 
11729 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11730 		return (EINVAL);
11731 
11732 	if (i2cd->len > sizeof(i2cd->data))
11733 		return (EFBIG);
11734 
11735 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11736 	if (rc)
11737 		return (rc);
11738 	if (hw_off_limits(sc))
11739 		rc = ENXIO;
11740 	else
11741 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11742 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11743 	end_synchronized_op(sc, 0);
11744 
11745 	return (rc);
11746 }
11747 
11748 static int
11749 clear_stats(struct adapter *sc, u_int port_id)
11750 {
11751 	int i, v, chan_map;
11752 	struct port_info *pi;
11753 	struct vi_info *vi;
11754 	struct sge_rxq *rxq;
11755 	struct sge_txq *txq;
11756 	struct sge_wrq *wrq;
11757 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11758 	struct sge_ofld_txq *ofld_txq;
11759 #endif
11760 #ifdef TCP_OFFLOAD
11761 	struct sge_ofld_rxq *ofld_rxq;
11762 #endif
11763 
11764 	if (port_id >= sc->params.nports)
11765 		return (EINVAL);
11766 	pi = sc->port[port_id];
11767 	if (pi == NULL)
11768 		return (EIO);
11769 
11770 	mtx_lock(&sc->reg_lock);
11771 	if (!hw_off_limits(sc)) {
11772 		/* MAC stats */
11773 		t4_clr_port_stats(sc, pi->tx_chan);
11774 		if (is_t6(sc)) {
11775 			if (pi->fcs_reg != -1)
11776 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11777 			else
11778 				pi->stats.rx_fcs_err = 0;
11779 		}
11780 		for_each_vi(pi, v, vi) {
11781 			if (vi->flags & VI_INIT_DONE)
11782 				t4_clr_vi_stats(sc, vi->vin);
11783 		}
11784 		chan_map = pi->rx_e_chan_map;
11785 		v = 0;	/* reuse */
11786 		while (chan_map) {
11787 			i = ffs(chan_map) - 1;
11788 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11789 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11790 			chan_map &= ~(1 << i);
11791 		}
11792 	}
11793 	mtx_unlock(&sc->reg_lock);
11794 	pi->tx_parse_error = 0;
11795 	pi->tnl_cong_drops = 0;
11796 
11797 	/*
11798 	 * Since this command accepts a port, clear stats for
11799 	 * all VIs on this port.
11800 	 */
11801 	for_each_vi(pi, v, vi) {
11802 		if (vi->flags & VI_INIT_DONE) {
11803 
11804 			for_each_rxq(vi, i, rxq) {
11805 #if defined(INET) || defined(INET6)
11806 				rxq->lro.lro_queued = 0;
11807 				rxq->lro.lro_flushed = 0;
11808 #endif
11809 				rxq->rxcsum = 0;
11810 				rxq->vlan_extraction = 0;
11811 				rxq->vxlan_rxcsum = 0;
11812 
11813 				rxq->fl.cl_allocated = 0;
11814 				rxq->fl.cl_recycled = 0;
11815 				rxq->fl.cl_fast_recycled = 0;
11816 			}
11817 
11818 			for_each_txq(vi, i, txq) {
11819 				txq->txcsum = 0;
11820 				txq->tso_wrs = 0;
11821 				txq->vlan_insertion = 0;
11822 				txq->imm_wrs = 0;
11823 				txq->sgl_wrs = 0;
11824 				txq->txpkt_wrs = 0;
11825 				txq->txpkts0_wrs = 0;
11826 				txq->txpkts1_wrs = 0;
11827 				txq->txpkts0_pkts = 0;
11828 				txq->txpkts1_pkts = 0;
11829 				txq->txpkts_flush = 0;
11830 				txq->raw_wrs = 0;
11831 				txq->vxlan_tso_wrs = 0;
11832 				txq->vxlan_txcsum = 0;
11833 				txq->kern_tls_records = 0;
11834 				txq->kern_tls_short = 0;
11835 				txq->kern_tls_partial = 0;
11836 				txq->kern_tls_full = 0;
11837 				txq->kern_tls_octets = 0;
11838 				txq->kern_tls_waste = 0;
11839 				txq->kern_tls_options = 0;
11840 				txq->kern_tls_header = 0;
11841 				txq->kern_tls_fin = 0;
11842 				txq->kern_tls_fin_short = 0;
11843 				txq->kern_tls_cbc = 0;
11844 				txq->kern_tls_gcm = 0;
11845 				mp_ring_reset_stats(txq->r);
11846 			}
11847 
11848 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11849 			for_each_ofld_txq(vi, i, ofld_txq) {
11850 				ofld_txq->wrq.tx_wrs_direct = 0;
11851 				ofld_txq->wrq.tx_wrs_copied = 0;
11852 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
11853 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
11854 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
11855 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
11856 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
11857 			}
11858 #endif
11859 #ifdef TCP_OFFLOAD
11860 			for_each_ofld_rxq(vi, i, ofld_rxq) {
11861 				ofld_rxq->fl.cl_allocated = 0;
11862 				ofld_rxq->fl.cl_recycled = 0;
11863 				ofld_rxq->fl.cl_fast_recycled = 0;
11864 				counter_u64_zero(
11865 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
11866 				counter_u64_zero(
11867 				    ofld_rxq->rx_iscsi_ddp_setup_error);
11868 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
11869 				ofld_rxq->rx_iscsi_ddp_octets = 0;
11870 				ofld_rxq->rx_iscsi_fl_pdus = 0;
11871 				ofld_rxq->rx_iscsi_fl_octets = 0;
11872 				ofld_rxq->rx_toe_tls_records = 0;
11873 				ofld_rxq->rx_toe_tls_octets = 0;
11874 			}
11875 #endif
11876 
11877 			if (IS_MAIN_VI(vi)) {
11878 				wrq = &sc->sge.ctrlq[pi->port_id];
11879 				wrq->tx_wrs_direct = 0;
11880 				wrq->tx_wrs_copied = 0;
11881 			}
11882 		}
11883 	}
11884 
11885 	return (0);
11886 }
11887 
11888 static int
11889 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
11890 {
11891 #ifdef INET6
11892 	struct in6_addr in6;
11893 
11894 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
11895 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
11896 		return (0);
11897 	else
11898 		return (EIO);
11899 #else
11900 	return (ENOTSUP);
11901 #endif
11902 }
11903 
11904 static int
11905 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
11906 {
11907 #ifdef INET6
11908 	struct in6_addr in6;
11909 
11910 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
11911 	return (t4_release_clip_addr(sc, &in6));
11912 #else
11913 	return (ENOTSUP);
11914 #endif
11915 }
11916 
11917 int
11918 t4_os_find_pci_capability(struct adapter *sc, int cap)
11919 {
11920 	int i;
11921 
11922 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
11923 }
11924 
11925 int
11926 t4_os_pci_save_state(struct adapter *sc)
11927 {
11928 	device_t dev;
11929 	struct pci_devinfo *dinfo;
11930 
11931 	dev = sc->dev;
11932 	dinfo = device_get_ivars(dev);
11933 
11934 	pci_cfg_save(dev, dinfo, 0);
11935 	return (0);
11936 }
11937 
11938 int
11939 t4_os_pci_restore_state(struct adapter *sc)
11940 {
11941 	device_t dev;
11942 	struct pci_devinfo *dinfo;
11943 
11944 	dev = sc->dev;
11945 	dinfo = device_get_ivars(dev);
11946 
11947 	pci_cfg_restore(dev, dinfo);
11948 	return (0);
11949 }
11950 
11951 void
11952 t4_os_portmod_changed(struct port_info *pi)
11953 {
11954 	struct adapter *sc = pi->adapter;
11955 	struct vi_info *vi;
11956 	struct ifnet *ifp;
11957 	static const char *mod_str[] = {
11958 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
11959 	};
11960 
11961 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
11962 	    ("%s: port_type %u", __func__, pi->port_type));
11963 
11964 	vi = &pi->vi[0];
11965 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
11966 		PORT_LOCK(pi);
11967 		build_medialist(pi);
11968 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
11969 			fixup_link_config(pi);
11970 			apply_link_config(pi);
11971 		}
11972 		PORT_UNLOCK(pi);
11973 		end_synchronized_op(sc, LOCK_HELD);
11974 	}
11975 
11976 	ifp = vi->ifp;
11977 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
11978 		if_printf(ifp, "transceiver unplugged.\n");
11979 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
11980 		if_printf(ifp, "unknown transceiver inserted.\n");
11981 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
11982 		if_printf(ifp, "unsupported transceiver inserted.\n");
11983 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
11984 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
11985 		    port_top_speed(pi), mod_str[pi->mod_type]);
11986 	} else {
11987 		if_printf(ifp, "transceiver (type %d) inserted.\n",
11988 		    pi->mod_type);
11989 	}
11990 }
11991 
11992 void
11993 t4_os_link_changed(struct port_info *pi)
11994 {
11995 	struct vi_info *vi;
11996 	struct ifnet *ifp;
11997 	struct link_config *lc = &pi->link_cfg;
11998 	struct adapter *sc = pi->adapter;
11999 	int v;
12000 
12001 	PORT_LOCK_ASSERT_OWNED(pi);
12002 
12003 	if (is_t6(sc)) {
12004 		if (lc->link_ok) {
12005 			if (lc->speed > 25000 ||
12006 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12007 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12008 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12009 			} else {
12010 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12011 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12012 			}
12013 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12014 			pi->stats.rx_fcs_err = 0;
12015 		} else {
12016 			pi->fcs_reg = -1;
12017 		}
12018 	} else {
12019 		MPASS(pi->fcs_reg != -1);
12020 		MPASS(pi->fcs_base == 0);
12021 	}
12022 
12023 	for_each_vi(pi, v, vi) {
12024 		ifp = vi->ifp;
12025 		if (ifp == NULL)
12026 			continue;
12027 
12028 		if (lc->link_ok) {
12029 			ifp->if_baudrate = IF_Mbps(lc->speed);
12030 			if_link_state_change(ifp, LINK_STATE_UP);
12031 		} else {
12032 			if_link_state_change(ifp, LINK_STATE_DOWN);
12033 		}
12034 	}
12035 }
12036 
12037 void
12038 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12039 {
12040 	struct adapter *sc;
12041 
12042 	sx_slock(&t4_list_lock);
12043 	SLIST_FOREACH(sc, &t4_list, link) {
12044 		/*
12045 		 * func should not make any assumptions about what state sc is
12046 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12047 		 */
12048 		func(sc, arg);
12049 	}
12050 	sx_sunlock(&t4_list_lock);
12051 }
12052 
12053 static int
12054 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12055     struct thread *td)
12056 {
12057 	int rc;
12058 	struct adapter *sc = dev->si_drv1;
12059 
12060 	rc = priv_check(td, PRIV_DRIVER);
12061 	if (rc != 0)
12062 		return (rc);
12063 
12064 	switch (cmd) {
12065 	case CHELSIO_T4_GETREG: {
12066 		struct t4_reg *edata = (struct t4_reg *)data;
12067 
12068 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12069 			return (EFAULT);
12070 
12071 		mtx_lock(&sc->reg_lock);
12072 		if (hw_off_limits(sc))
12073 			rc = ENXIO;
12074 		else if (edata->size == 4)
12075 			edata->val = t4_read_reg(sc, edata->addr);
12076 		else if (edata->size == 8)
12077 			edata->val = t4_read_reg64(sc, edata->addr);
12078 		else
12079 			rc = EINVAL;
12080 		mtx_unlock(&sc->reg_lock);
12081 
12082 		break;
12083 	}
12084 	case CHELSIO_T4_SETREG: {
12085 		struct t4_reg *edata = (struct t4_reg *)data;
12086 
12087 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12088 			return (EFAULT);
12089 
12090 		mtx_lock(&sc->reg_lock);
12091 		if (hw_off_limits(sc))
12092 			rc = ENXIO;
12093 		else if (edata->size == 4) {
12094 			if (edata->val & 0xffffffff00000000)
12095 				rc = EINVAL;
12096 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12097 		} else if (edata->size == 8)
12098 			t4_write_reg64(sc, edata->addr, edata->val);
12099 		else
12100 			rc = EINVAL;
12101 		mtx_unlock(&sc->reg_lock);
12102 
12103 		break;
12104 	}
12105 	case CHELSIO_T4_REGDUMP: {
12106 		struct t4_regdump *regs = (struct t4_regdump *)data;
12107 		int reglen = t4_get_regs_len(sc);
12108 		uint8_t *buf;
12109 
12110 		if (regs->len < reglen) {
12111 			regs->len = reglen; /* hint to the caller */
12112 			return (ENOBUFS);
12113 		}
12114 
12115 		regs->len = reglen;
12116 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12117 		mtx_lock(&sc->reg_lock);
12118 		if (hw_off_limits(sc))
12119 			rc = ENXIO;
12120 		else
12121 			get_regs(sc, regs, buf);
12122 		mtx_unlock(&sc->reg_lock);
12123 		if (rc == 0)
12124 			rc = copyout(buf, regs->data, reglen);
12125 		free(buf, M_CXGBE);
12126 		break;
12127 	}
12128 	case CHELSIO_T4_GET_FILTER_MODE:
12129 		rc = get_filter_mode(sc, (uint32_t *)data);
12130 		break;
12131 	case CHELSIO_T4_SET_FILTER_MODE:
12132 		rc = set_filter_mode(sc, *(uint32_t *)data);
12133 		break;
12134 	case CHELSIO_T4_SET_FILTER_MASK:
12135 		rc = set_filter_mask(sc, *(uint32_t *)data);
12136 		break;
12137 	case CHELSIO_T4_GET_FILTER:
12138 		rc = get_filter(sc, (struct t4_filter *)data);
12139 		break;
12140 	case CHELSIO_T4_SET_FILTER:
12141 		rc = set_filter(sc, (struct t4_filter *)data);
12142 		break;
12143 	case CHELSIO_T4_DEL_FILTER:
12144 		rc = del_filter(sc, (struct t4_filter *)data);
12145 		break;
12146 	case CHELSIO_T4_GET_SGE_CONTEXT:
12147 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12148 		break;
12149 	case CHELSIO_T4_LOAD_FW:
12150 		rc = load_fw(sc, (struct t4_data *)data);
12151 		break;
12152 	case CHELSIO_T4_GET_MEM:
12153 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12154 		break;
12155 	case CHELSIO_T4_GET_I2C:
12156 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12157 		break;
12158 	case CHELSIO_T4_CLEAR_STATS:
12159 		rc = clear_stats(sc, *(uint32_t *)data);
12160 		break;
12161 	case CHELSIO_T4_SCHED_CLASS:
12162 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12163 		break;
12164 	case CHELSIO_T4_SCHED_QUEUE:
12165 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12166 		break;
12167 	case CHELSIO_T4_GET_TRACER:
12168 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12169 		break;
12170 	case CHELSIO_T4_SET_TRACER:
12171 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12172 		break;
12173 	case CHELSIO_T4_LOAD_CFG:
12174 		rc = load_cfg(sc, (struct t4_data *)data);
12175 		break;
12176 	case CHELSIO_T4_LOAD_BOOT:
12177 		rc = load_boot(sc, (struct t4_bootrom *)data);
12178 		break;
12179 	case CHELSIO_T4_LOAD_BOOTCFG:
12180 		rc = load_bootcfg(sc, (struct t4_data *)data);
12181 		break;
12182 	case CHELSIO_T4_CUDBG_DUMP:
12183 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12184 		break;
12185 	case CHELSIO_T4_SET_OFLD_POLICY:
12186 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12187 		break;
12188 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12189 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12190 		break;
12191 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12192 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12193 		break;
12194 	default:
12195 		rc = ENOTTY;
12196 	}
12197 
12198 	return (rc);
12199 }
12200 
12201 #ifdef TCP_OFFLOAD
12202 static int
12203 toe_capability(struct vi_info *vi, bool enable)
12204 {
12205 	int rc;
12206 	struct port_info *pi = vi->pi;
12207 	struct adapter *sc = pi->adapter;
12208 
12209 	ASSERT_SYNCHRONIZED_OP(sc);
12210 
12211 	if (!is_offload(sc))
12212 		return (ENODEV);
12213 	if (hw_off_limits(sc))
12214 		return (ENXIO);
12215 
12216 	if (enable) {
12217 #ifdef KERN_TLS
12218 		if (sc->flags & KERN_TLS_ON) {
12219 			int i, j, n;
12220 			struct port_info *p;
12221 			struct vi_info *v;
12222 
12223 			/*
12224 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12225 			 * on any ifnet.
12226 			 */
12227 			n = 0;
12228 			for_each_port(sc, i) {
12229 				p = sc->port[i];
12230 				for_each_vi(p, j, v) {
12231 					if (v->ifp->if_capenable & IFCAP_TXTLS) {
12232 						CH_WARN(sc,
12233 						    "%s has NIC TLS enabled.\n",
12234 						    device_get_nameunit(v->dev));
12235 						n++;
12236 					}
12237 				}
12238 			}
12239 			if (n > 0) {
12240 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12241 				    "associated with this adapter before "
12242 				    "trying to enable TOE.\n");
12243 				return (EAGAIN);
12244 			}
12245 			rc = t4_config_kern_tls(sc, false);
12246 			if (rc)
12247 				return (rc);
12248 		}
12249 #endif
12250 		if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
12251 			/* TOE is already enabled. */
12252 			return (0);
12253 		}
12254 
12255 		/*
12256 		 * We need the port's queues around so that we're able to send
12257 		 * and receive CPLs to/from the TOE even if the ifnet for this
12258 		 * port has never been UP'd administratively.
12259 		 */
12260 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12261 			return (rc);
12262 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12263 		    ((rc = vi_init(&pi->vi[0])) != 0))
12264 			return (rc);
12265 
12266 		if (isset(&sc->offload_map, pi->port_id)) {
12267 			/* TOE is enabled on another VI of this port. */
12268 			pi->uld_vis++;
12269 			return (0);
12270 		}
12271 
12272 		if (!uld_active(sc, ULD_TOM)) {
12273 			rc = t4_activate_uld(sc, ULD_TOM);
12274 			if (rc == EAGAIN) {
12275 				log(LOG_WARNING,
12276 				    "You must kldload t4_tom.ko before trying "
12277 				    "to enable TOE on a cxgbe interface.\n");
12278 			}
12279 			if (rc != 0)
12280 				return (rc);
12281 			KASSERT(sc->tom_softc != NULL,
12282 			    ("%s: TOM activated but softc NULL", __func__));
12283 			KASSERT(uld_active(sc, ULD_TOM),
12284 			    ("%s: TOM activated but flag not set", __func__));
12285 		}
12286 
12287 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12288 		if (!uld_active(sc, ULD_IWARP))
12289 			(void) t4_activate_uld(sc, ULD_IWARP);
12290 		if (!uld_active(sc, ULD_ISCSI))
12291 			(void) t4_activate_uld(sc, ULD_ISCSI);
12292 
12293 		pi->uld_vis++;
12294 		setbit(&sc->offload_map, pi->port_id);
12295 	} else {
12296 		pi->uld_vis--;
12297 
12298 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12299 			return (0);
12300 
12301 		KASSERT(uld_active(sc, ULD_TOM),
12302 		    ("%s: TOM never initialized?", __func__));
12303 		clrbit(&sc->offload_map, pi->port_id);
12304 	}
12305 
12306 	return (0);
12307 }
12308 
12309 /*
12310  * Add an upper layer driver to the global list.
12311  */
12312 int
12313 t4_register_uld(struct uld_info *ui)
12314 {
12315 	int rc = 0;
12316 	struct uld_info *u;
12317 
12318 	sx_xlock(&t4_uld_list_lock);
12319 	SLIST_FOREACH(u, &t4_uld_list, link) {
12320 	    if (u->uld_id == ui->uld_id) {
12321 		    rc = EEXIST;
12322 		    goto done;
12323 	    }
12324 	}
12325 
12326 	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
12327 	ui->refcount = 0;
12328 done:
12329 	sx_xunlock(&t4_uld_list_lock);
12330 	return (rc);
12331 }
12332 
12333 int
12334 t4_unregister_uld(struct uld_info *ui)
12335 {
12336 	int rc = EINVAL;
12337 	struct uld_info *u;
12338 
12339 	sx_xlock(&t4_uld_list_lock);
12340 
12341 	SLIST_FOREACH(u, &t4_uld_list, link) {
12342 	    if (u == ui) {
12343 		    if (ui->refcount > 0) {
12344 			    rc = EBUSY;
12345 			    goto done;
12346 		    }
12347 
12348 		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
12349 		    rc = 0;
12350 		    goto done;
12351 	    }
12352 	}
12353 done:
12354 	sx_xunlock(&t4_uld_list_lock);
12355 	return (rc);
12356 }
12357 
12358 int
12359 t4_activate_uld(struct adapter *sc, int id)
12360 {
12361 	int rc;
12362 	struct uld_info *ui;
12363 
12364 	ASSERT_SYNCHRONIZED_OP(sc);
12365 
12366 	if (id < 0 || id > ULD_MAX)
12367 		return (EINVAL);
12368 	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
12369 
12370 	sx_slock(&t4_uld_list_lock);
12371 
12372 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12373 		if (ui->uld_id == id) {
12374 			if (!(sc->flags & FULL_INIT_DONE)) {
12375 				rc = adapter_init(sc);
12376 				if (rc != 0)
12377 					break;
12378 			}
12379 
12380 			rc = ui->activate(sc);
12381 			if (rc == 0) {
12382 				setbit(&sc->active_ulds, id);
12383 				ui->refcount++;
12384 			}
12385 			break;
12386 		}
12387 	}
12388 
12389 	sx_sunlock(&t4_uld_list_lock);
12390 
12391 	return (rc);
12392 }
12393 
12394 int
12395 t4_deactivate_uld(struct adapter *sc, int id)
12396 {
12397 	int rc;
12398 	struct uld_info *ui;
12399 
12400 	ASSERT_SYNCHRONIZED_OP(sc);
12401 
12402 	if (id < 0 || id > ULD_MAX)
12403 		return (EINVAL);
12404 	rc = ENXIO;
12405 
12406 	sx_slock(&t4_uld_list_lock);
12407 
12408 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12409 		if (ui->uld_id == id) {
12410 			rc = ui->deactivate(sc);
12411 			if (rc == 0) {
12412 				clrbit(&sc->active_ulds, id);
12413 				ui->refcount--;
12414 			}
12415 			break;
12416 		}
12417 	}
12418 
12419 	sx_sunlock(&t4_uld_list_lock);
12420 
12421 	return (rc);
12422 }
12423 
12424 static void
12425 t4_async_event(void *arg, int n)
12426 {
12427 	struct uld_info *ui;
12428 	struct adapter *sc = (struct adapter *)arg;
12429 
12430 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
12431 		return;
12432 	sx_slock(&t4_uld_list_lock);
12433 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12434 		if (ui->uld_id == ULD_IWARP) {
12435 			ui->async_event(sc);
12436 			break;
12437 		}
12438 	}
12439 	sx_sunlock(&t4_uld_list_lock);
12440 	end_synchronized_op(sc, 0);
12441 }
12442 
12443 int
12444 uld_active(struct adapter *sc, int uld_id)
12445 {
12446 
12447 	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
12448 
12449 	return (isset(&sc->active_ulds, uld_id));
12450 }
12451 #endif
12452 
12453 #ifdef KERN_TLS
12454 static int
12455 ktls_capability(struct adapter *sc, bool enable)
12456 {
12457 	ASSERT_SYNCHRONIZED_OP(sc);
12458 
12459 	if (!is_ktls(sc))
12460 		return (ENODEV);
12461 	if (hw_off_limits(sc))
12462 		return (ENXIO);
12463 
12464 	if (enable) {
12465 		if (sc->flags & KERN_TLS_ON)
12466 			return (0);	/* already on */
12467 		if (sc->offload_map != 0) {
12468 			CH_WARN(sc,
12469 			    "Disable TOE on all interfaces associated with "
12470 			    "this adapter before trying to enable NIC TLS.\n");
12471 			return (EAGAIN);
12472 		}
12473 		return (t4_config_kern_tls(sc, true));
12474 	} else {
12475 		/*
12476 		 * Nothing to do for disable.  If TOE is enabled sometime later
12477 		 * then toe_capability will reconfigure the hardware.
12478 		 */
12479 		return (0);
12480 	}
12481 }
12482 #endif
12483 
12484 /*
12485  * t  = ptr to tunable.
12486  * nc = number of CPUs.
12487  * c  = compiled in default for that tunable.
12488  */
12489 static void
12490 calculate_nqueues(int *t, int nc, const int c)
12491 {
12492 	int nq;
12493 
12494 	if (*t > 0)
12495 		return;
12496 	nq = *t < 0 ? -*t : c;
12497 	*t = min(nc, nq);
12498 }
12499 
12500 /*
12501  * Come up with reasonable defaults for some of the tunables, provided they're
12502  * not set by the user (in which case we'll use the values as is).
12503  */
12504 static void
12505 tweak_tunables(void)
12506 {
12507 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12508 
12509 	if (t4_ntxq < 1) {
12510 #ifdef RSS
12511 		t4_ntxq = rss_getnumbuckets();
12512 #else
12513 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12514 #endif
12515 	}
12516 
12517 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12518 
12519 	if (t4_nrxq < 1) {
12520 #ifdef RSS
12521 		t4_nrxq = rss_getnumbuckets();
12522 #else
12523 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12524 #endif
12525 	}
12526 
12527 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12528 
12529 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12530 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12531 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12532 #endif
12533 #ifdef TCP_OFFLOAD
12534 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12535 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12536 #endif
12537 
12538 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12539 	if (t4_toecaps_allowed == -1)
12540 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12541 #else
12542 	if (t4_toecaps_allowed == -1)
12543 		t4_toecaps_allowed = 0;
12544 #endif
12545 
12546 #ifdef TCP_OFFLOAD
12547 	if (t4_rdmacaps_allowed == -1) {
12548 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12549 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12550 	}
12551 
12552 	if (t4_iscsicaps_allowed == -1) {
12553 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12554 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12555 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12556 	}
12557 
12558 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12559 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12560 
12561 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12562 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12563 
12564 	if (t4_toe_tls_rx_timeout < 0)
12565 		t4_toe_tls_rx_timeout = 0;
12566 #else
12567 	if (t4_rdmacaps_allowed == -1)
12568 		t4_rdmacaps_allowed = 0;
12569 
12570 	if (t4_iscsicaps_allowed == -1)
12571 		t4_iscsicaps_allowed = 0;
12572 #endif
12573 
12574 #ifdef DEV_NETMAP
12575 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12576 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12577 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12578 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12579 #endif
12580 
12581 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12582 		t4_tmr_idx = TMR_IDX;
12583 
12584 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12585 		t4_pktc_idx = PKTC_IDX;
12586 
12587 	if (t4_qsize_txq < 128)
12588 		t4_qsize_txq = 128;
12589 
12590 	if (t4_qsize_rxq < 128)
12591 		t4_qsize_rxq = 128;
12592 	while (t4_qsize_rxq & 7)
12593 		t4_qsize_rxq++;
12594 
12595 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12596 
12597 	/*
12598 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12599 	 * VI for the port.  The rest are additional virtual interfaces on the
12600 	 * same physical port.  Note that the main VI does not have native
12601 	 * netmap support but the extra VIs do.
12602 	 *
12603 	 * Limit the number of VIs per port to the number of available
12604 	 * MAC addresses per port.
12605 	 */
12606 	if (t4_num_vis < 1)
12607 		t4_num_vis = 1;
12608 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12609 		t4_num_vis = nitems(vi_mac_funcs);
12610 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12611 	}
12612 
12613 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12614 		pcie_relaxed_ordering = 1;
12615 #if defined(__i386__) || defined(__amd64__)
12616 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12617 			pcie_relaxed_ordering = 0;
12618 #endif
12619 	}
12620 }
12621 
12622 #ifdef DDB
12623 static void
12624 t4_dump_tcb(struct adapter *sc, int tid)
12625 {
12626 	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
12627 
12628 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12629 	save = t4_read_reg(sc, reg);
12630 	base = sc->memwin[2].mw_base;
12631 
12632 	/* Dump TCB for the tid */
12633 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12634 	tcb_addr += tid * TCB_SIZE;
12635 
12636 	if (is_t4(sc)) {
12637 		pf = 0;
12638 		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
12639 	} else {
12640 		pf = V_PFNUM(sc->pf);
12641 		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
12642 	}
12643 	t4_write_reg(sc, reg, win_pos | pf);
12644 	t4_read_reg(sc, reg);
12645 
12646 	off = tcb_addr - win_pos;
12647 	for (i = 0; i < 4; i++) {
12648 		uint32_t buf[8];
12649 		for (j = 0; j < 8; j++, off += 4)
12650 			buf[j] = htonl(t4_read_reg(sc, base + off));
12651 
12652 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12653 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12654 		    buf[7]);
12655 	}
12656 
12657 	t4_write_reg(sc, reg, save);
12658 	t4_read_reg(sc, reg);
12659 }
12660 
12661 static void
12662 t4_dump_devlog(struct adapter *sc)
12663 {
12664 	struct devlog_params *dparams = &sc->params.devlog;
12665 	struct fw_devlog_e e;
12666 	int i, first, j, m, nentries, rc;
12667 	uint64_t ftstamp = UINT64_MAX;
12668 
12669 	if (dparams->start == 0) {
12670 		db_printf("devlog params not valid\n");
12671 		return;
12672 	}
12673 
12674 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12675 	m = fwmtype_to_hwmtype(dparams->memtype);
12676 
12677 	/* Find the first entry. */
12678 	first = -1;
12679 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12680 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12681 		    sizeof(e), (void *)&e);
12682 		if (rc != 0)
12683 			break;
12684 
12685 		if (e.timestamp == 0)
12686 			break;
12687 
12688 		e.timestamp = be64toh(e.timestamp);
12689 		if (e.timestamp < ftstamp) {
12690 			ftstamp = e.timestamp;
12691 			first = i;
12692 		}
12693 	}
12694 
12695 	if (first == -1)
12696 		return;
12697 
12698 	i = first;
12699 	do {
12700 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12701 		    sizeof(e), (void *)&e);
12702 		if (rc != 0)
12703 			return;
12704 
12705 		if (e.timestamp == 0)
12706 			return;
12707 
12708 		e.timestamp = be64toh(e.timestamp);
12709 		e.seqno = be32toh(e.seqno);
12710 		for (j = 0; j < 8; j++)
12711 			e.params[j] = be32toh(e.params[j]);
12712 
12713 		db_printf("%10d  %15ju  %8s  %8s  ",
12714 		    e.seqno, e.timestamp,
12715 		    (e.level < nitems(devlog_level_strings) ?
12716 			devlog_level_strings[e.level] : "UNKNOWN"),
12717 		    (e.facility < nitems(devlog_facility_strings) ?
12718 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12719 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12720 		    e.params[3], e.params[4], e.params[5], e.params[6],
12721 		    e.params[7]);
12722 
12723 		if (++i == nentries)
12724 			i = 0;
12725 	} while (i != first && !db_pager_quit);
12726 }
12727 
12728 static struct command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
12729 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
12730 
12731 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
12732 {
12733 	device_t dev;
12734 	int t;
12735 	bool valid;
12736 
12737 	valid = false;
12738 	t = db_read_token();
12739 	if (t == tIDENT) {
12740 		dev = device_lookup_by_name(db_tok_string);
12741 		valid = true;
12742 	}
12743 	db_skip_to_eol();
12744 	if (!valid) {
12745 		db_printf("usage: show t4 devlog <nexus>\n");
12746 		return;
12747 	}
12748 
12749 	if (dev == NULL) {
12750 		db_printf("device not found\n");
12751 		return;
12752 	}
12753 
12754 	t4_dump_devlog(device_get_softc(dev));
12755 }
12756 
12757 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
12758 {
12759 	device_t dev;
12760 	int radix, tid, t;
12761 	bool valid;
12762 
12763 	valid = false;
12764 	radix = db_radix;
12765 	db_radix = 10;
12766 	t = db_read_token();
12767 	if (t == tIDENT) {
12768 		dev = device_lookup_by_name(db_tok_string);
12769 		t = db_read_token();
12770 		if (t == tNUMBER) {
12771 			tid = db_tok_number;
12772 			valid = true;
12773 		}
12774 	}
12775 	db_radix = radix;
12776 	db_skip_to_eol();
12777 	if (!valid) {
12778 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
12779 		return;
12780 	}
12781 
12782 	if (dev == NULL) {
12783 		db_printf("device not found\n");
12784 		return;
12785 	}
12786 	if (tid < 0) {
12787 		db_printf("invalid tid\n");
12788 		return;
12789 	}
12790 
12791 	t4_dump_tcb(device_get_softc(dev), tid);
12792 }
12793 #endif
12794 
12795 static eventhandler_tag vxlan_start_evtag;
12796 static eventhandler_tag vxlan_stop_evtag;
12797 
12798 struct vxlan_evargs {
12799 	struct ifnet *ifp;
12800 	uint16_t port;
12801 };
12802 
12803 static void
12804 enable_vxlan_rx(struct adapter *sc)
12805 {
12806 	int i, rc;
12807 	struct port_info *pi;
12808 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
12809 
12810 	ASSERT_SYNCHRONIZED_OP(sc);
12811 
12812 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
12813 	    F_VXLAN_EN);
12814 	for_each_port(sc, i) {
12815 		pi = sc->port[i];
12816 		if (pi->vxlan_tcam_entry == true)
12817 			continue;
12818 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
12819 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
12820 		    true);
12821 		if (rc < 0) {
12822 			rc = -rc;
12823 			CH_ERR(&pi->vi[0],
12824 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
12825 		} else {
12826 			MPASS(rc == sc->rawf_base + pi->port_id);
12827 			pi->vxlan_tcam_entry = true;
12828 		}
12829 	}
12830 }
12831 
12832 static void
12833 t4_vxlan_start(struct adapter *sc, void *arg)
12834 {
12835 	struct vxlan_evargs *v = arg;
12836 
12837 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
12838 		return;
12839 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
12840 		return;
12841 
12842 	if (sc->vxlan_refcount == 0) {
12843 		sc->vxlan_port = v->port;
12844 		sc->vxlan_refcount = 1;
12845 		if (!hw_off_limits(sc))
12846 			enable_vxlan_rx(sc);
12847 	} else if (sc->vxlan_port == v->port) {
12848 		sc->vxlan_refcount++;
12849 	} else {
12850 		CH_ERR(sc, "VXLAN already configured on port  %d; "
12851 		    "ignoring attempt to configure it on port %d\n",
12852 		    sc->vxlan_port, v->port);
12853 	}
12854 	end_synchronized_op(sc, 0);
12855 }
12856 
12857 static void
12858 t4_vxlan_stop(struct adapter *sc, void *arg)
12859 {
12860 	struct vxlan_evargs *v = arg;
12861 
12862 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
12863 		return;
12864 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
12865 		return;
12866 
12867 	/*
12868 	 * VXLANs may have been configured before the driver was loaded so we
12869 	 * may see more stops than starts.  This is not handled cleanly but at
12870 	 * least we keep the refcount sane.
12871 	 */
12872 	if (sc->vxlan_port != v->port)
12873 		goto done;
12874 	if (sc->vxlan_refcount == 0) {
12875 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
12876 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
12877 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
12878 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
12879 done:
12880 	end_synchronized_op(sc, 0);
12881 }
12882 
12883 static void
12884 t4_vxlan_start_handler(void *arg __unused, struct ifnet *ifp,
12885     sa_family_t family, u_int port)
12886 {
12887 	struct vxlan_evargs v;
12888 
12889 	MPASS(family == AF_INET || family == AF_INET6);
12890 	v.ifp = ifp;
12891 	v.port = port;
12892 
12893 	t4_iterate(t4_vxlan_start, &v);
12894 }
12895 
12896 static void
12897 t4_vxlan_stop_handler(void *arg __unused, struct ifnet *ifp, sa_family_t family,
12898     u_int port)
12899 {
12900 	struct vxlan_evargs v;
12901 
12902 	MPASS(family == AF_INET || family == AF_INET6);
12903 	v.ifp = ifp;
12904 	v.port = port;
12905 
12906 	t4_iterate(t4_vxlan_stop, &v);
12907 }
12908 
12909 
12910 static struct sx mlu;	/* mod load unload */
12911 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
12912 
12913 static int
12914 mod_event(module_t mod, int cmd, void *arg)
12915 {
12916 	int rc = 0;
12917 	static int loaded = 0;
12918 
12919 	switch (cmd) {
12920 	case MOD_LOAD:
12921 		sx_xlock(&mlu);
12922 		if (loaded++ == 0) {
12923 			t4_sge_modload();
12924 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
12925 			    t4_filter_rpl, CPL_COOKIE_FILTER);
12926 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
12927 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
12928 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
12929 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
12930 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
12931 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
12932 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
12933 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
12934 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
12935 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
12936 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
12937 			    do_smt_write_rpl);
12938 			sx_init(&t4_list_lock, "T4/T5 adapters");
12939 			SLIST_INIT(&t4_list);
12940 			callout_init(&fatal_callout, 1);
12941 #ifdef TCP_OFFLOAD
12942 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
12943 			SLIST_INIT(&t4_uld_list);
12944 #endif
12945 #ifdef INET6
12946 			t4_clip_modload();
12947 #endif
12948 #ifdef KERN_TLS
12949 			t6_ktls_modload();
12950 #endif
12951 			t4_tracer_modload();
12952 			tweak_tunables();
12953 			vxlan_start_evtag =
12954 			    EVENTHANDLER_REGISTER(vxlan_start,
12955 				t4_vxlan_start_handler, NULL,
12956 				EVENTHANDLER_PRI_ANY);
12957 			vxlan_stop_evtag =
12958 			    EVENTHANDLER_REGISTER(vxlan_stop,
12959 				t4_vxlan_stop_handler, NULL,
12960 				EVENTHANDLER_PRI_ANY);
12961 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
12962 			    taskqueue_thread_enqueue, &reset_tq);
12963 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
12964 			    "t4_rst_thr");
12965 		}
12966 		sx_xunlock(&mlu);
12967 		break;
12968 
12969 	case MOD_UNLOAD:
12970 		sx_xlock(&mlu);
12971 		if (--loaded == 0) {
12972 			int tries;
12973 
12974 			taskqueue_free(reset_tq);
12975 			sx_slock(&t4_list_lock);
12976 			if (!SLIST_EMPTY(&t4_list)) {
12977 				rc = EBUSY;
12978 				sx_sunlock(&t4_list_lock);
12979 				goto done_unload;
12980 			}
12981 #ifdef TCP_OFFLOAD
12982 			sx_slock(&t4_uld_list_lock);
12983 			if (!SLIST_EMPTY(&t4_uld_list)) {
12984 				rc = EBUSY;
12985 				sx_sunlock(&t4_uld_list_lock);
12986 				sx_sunlock(&t4_list_lock);
12987 				goto done_unload;
12988 			}
12989 #endif
12990 			tries = 0;
12991 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
12992 				uprintf("%ju clusters with custom free routine "
12993 				    "still is use.\n", t4_sge_extfree_refs());
12994 				pause("t4unload", 2 * hz);
12995 			}
12996 #ifdef TCP_OFFLOAD
12997 			sx_sunlock(&t4_uld_list_lock);
12998 #endif
12999 			sx_sunlock(&t4_list_lock);
13000 
13001 			if (t4_sge_extfree_refs() == 0) {
13002 				EVENTHANDLER_DEREGISTER(vxlan_start,
13003 				    vxlan_start_evtag);
13004 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13005 				    vxlan_stop_evtag);
13006 				t4_tracer_modunload();
13007 #ifdef KERN_TLS
13008 				t6_ktls_modunload();
13009 #endif
13010 #ifdef INET6
13011 				t4_clip_modunload();
13012 #endif
13013 #ifdef TCP_OFFLOAD
13014 				sx_destroy(&t4_uld_list_lock);
13015 #endif
13016 				sx_destroy(&t4_list_lock);
13017 				t4_sge_modunload();
13018 				loaded = 0;
13019 			} else {
13020 				rc = EBUSY;
13021 				loaded++;	/* undo earlier decrement */
13022 			}
13023 		}
13024 done_unload:
13025 		sx_xunlock(&mlu);
13026 		break;
13027 	}
13028 
13029 	return (rc);
13030 }
13031 
13032 static devclass_t t4_devclass, t5_devclass, t6_devclass;
13033 static devclass_t cxgbe_devclass, cxl_devclass, cc_devclass;
13034 static devclass_t vcxgbe_devclass, vcxl_devclass, vcc_devclass;
13035 
13036 DRIVER_MODULE(t4nex, pci, t4_driver, t4_devclass, mod_event, 0);
13037 MODULE_VERSION(t4nex, 1);
13038 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13039 #ifdef DEV_NETMAP
13040 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13041 #endif /* DEV_NETMAP */
13042 
13043 DRIVER_MODULE(t5nex, pci, t5_driver, t5_devclass, mod_event, 0);
13044 MODULE_VERSION(t5nex, 1);
13045 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13046 #ifdef DEV_NETMAP
13047 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13048 #endif /* DEV_NETMAP */
13049 
13050 DRIVER_MODULE(t6nex, pci, t6_driver, t6_devclass, mod_event, 0);
13051 MODULE_VERSION(t6nex, 1);
13052 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13053 #ifdef DEV_NETMAP
13054 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13055 #endif /* DEV_NETMAP */
13056 
13057 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, cxgbe_devclass, 0, 0);
13058 MODULE_VERSION(cxgbe, 1);
13059 
13060 DRIVER_MODULE(cxl, t5nex, cxl_driver, cxl_devclass, 0, 0);
13061 MODULE_VERSION(cxl, 1);
13062 
13063 DRIVER_MODULE(cc, t6nex, cc_driver, cc_devclass, 0, 0);
13064 MODULE_VERSION(cc, 1);
13065 
13066 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, vcxgbe_devclass, 0, 0);
13067 MODULE_VERSION(vcxgbe, 1);
13068 
13069 DRIVER_MODULE(vcxl, cxl, vcxl_driver, vcxl_devclass, 0, 0);
13070 MODULE_VERSION(vcxl, 1);
13071 
13072 DRIVER_MODULE(vcc, cc, vcc_driver, vcc_devclass, 0, 0);
13073 MODULE_VERSION(vcc, 1);
13074