xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision 6ba2210ee039f2f12878c217bcf058e9c8b26b29)
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_speed = 0;
5707 
5708 	if (t4_autoneg == 0)
5709 		lc->requested_aneg = AUTONEG_DISABLE;
5710 	else if (t4_autoneg == 1)
5711 		lc->requested_aneg = AUTONEG_ENABLE;
5712 	else
5713 		lc->requested_aneg = AUTONEG_AUTO;
5714 
5715 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5716 	    PAUSE_AUTONEG);
5717 
5718 	if (t4_fec & FEC_AUTO)
5719 		lc->requested_fec = FEC_AUTO;
5720 	else if (t4_fec == 0)
5721 		lc->requested_fec = FEC_NONE;
5722 	else {
5723 		/* -1 is handled by the FEC_AUTO block above and not here. */
5724 		lc->requested_fec = t4_fec &
5725 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5726 		if (lc->requested_fec == 0)
5727 			lc->requested_fec = FEC_AUTO;
5728 	}
5729 }
5730 
5731 /*
5732  * Makes sure that all requested settings comply with what's supported by the
5733  * port.  Returns the number of settings that were invalid and had to be fixed.
5734  */
5735 static int
5736 fixup_link_config(struct port_info *pi)
5737 {
5738 	int n = 0;
5739 	struct link_config *lc = &pi->link_cfg;
5740 	uint32_t fwspeed;
5741 
5742 	PORT_LOCK_ASSERT_OWNED(pi);
5743 
5744 	/* Speed (when not autonegotiating) */
5745 	if (lc->requested_speed != 0) {
5746 		fwspeed = speed_to_fwcap(lc->requested_speed);
5747 		if ((fwspeed & lc->pcaps) == 0) {
5748 			n++;
5749 			lc->requested_speed = 0;
5750 		}
5751 	}
5752 
5753 	/* Link autonegotiation */
5754 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5755 	    lc->requested_aneg == AUTONEG_DISABLE ||
5756 	    lc->requested_aneg == AUTONEG_AUTO);
5757 	if (lc->requested_aneg == AUTONEG_ENABLE &&
5758 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5759 		n++;
5760 		lc->requested_aneg = AUTONEG_AUTO;
5761 	}
5762 
5763 	/* Flow control */
5764 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5765 	if (lc->requested_fc & PAUSE_TX &&
5766 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5767 		n++;
5768 		lc->requested_fc &= ~PAUSE_TX;
5769 	}
5770 	if (lc->requested_fc & PAUSE_RX &&
5771 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
5772 		n++;
5773 		lc->requested_fc &= ~PAUSE_RX;
5774 	}
5775 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
5776 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
5777 		n++;
5778 		lc->requested_fc |= PAUSE_AUTONEG;
5779 	}
5780 
5781 	/* FEC */
5782 	if ((lc->requested_fec & FEC_RS &&
5783 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
5784 	    (lc->requested_fec & FEC_BASER_RS &&
5785 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
5786 		n++;
5787 		lc->requested_fec = FEC_AUTO;
5788 	}
5789 
5790 	return (n);
5791 }
5792 
5793 /*
5794  * Apply the requested L1 settings, which are expected to be valid, to the
5795  * hardware.
5796  */
5797 static int
5798 apply_link_config(struct port_info *pi)
5799 {
5800 	struct adapter *sc = pi->adapter;
5801 	struct link_config *lc = &pi->link_cfg;
5802 	int rc;
5803 
5804 #ifdef INVARIANTS
5805 	ASSERT_SYNCHRONIZED_OP(sc);
5806 	PORT_LOCK_ASSERT_OWNED(pi);
5807 
5808 	if (lc->requested_aneg == AUTONEG_ENABLE)
5809 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
5810 	if (!(lc->requested_fc & PAUSE_AUTONEG))
5811 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
5812 	if (lc->requested_fc & PAUSE_TX)
5813 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
5814 	if (lc->requested_fc & PAUSE_RX)
5815 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
5816 	if (lc->requested_fec & FEC_RS)
5817 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
5818 	if (lc->requested_fec & FEC_BASER_RS)
5819 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
5820 #endif
5821 	rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
5822 	if (rc != 0) {
5823 		/* Don't complain if the VF driver gets back an EPERM. */
5824 		if (!(sc->flags & IS_VF) || rc != FW_EPERM)
5825 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
5826 	} else {
5827 		/*
5828 		 * An L1_CFG will almost always result in a link-change event if
5829 		 * the link is up, and the driver will refresh the actual
5830 		 * fec/fc/etc. when the notification is processed.  If the link
5831 		 * is down then the actual settings are meaningless.
5832 		 *
5833 		 * This takes care of the case where a change in the L1 settings
5834 		 * may not result in a notification.
5835 		 */
5836 		if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
5837 			lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
5838 	}
5839 	return (rc);
5840 }
5841 
5842 #define FW_MAC_EXACT_CHUNK	7
5843 struct mcaddr_ctx {
5844 	struct ifnet *ifp;
5845 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
5846 	uint64_t hash;
5847 	int i;
5848 	int del;
5849 	int rc;
5850 };
5851 
5852 static u_int
5853 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
5854 {
5855 	struct mcaddr_ctx *ctx = arg;
5856 	struct vi_info *vi = ctx->ifp->if_softc;
5857 	struct port_info *pi = vi->pi;
5858 	struct adapter *sc = pi->adapter;
5859 
5860 	if (ctx->rc < 0)
5861 		return (0);
5862 
5863 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
5864 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
5865 	ctx->i++;
5866 
5867 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
5868 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
5869 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
5870 		if (ctx->rc < 0) {
5871 			int j;
5872 
5873 			for (j = 0; j < ctx->i; j++) {
5874 				if_printf(ctx->ifp,
5875 				    "failed to add mc address"
5876 				    " %02x:%02x:%02x:"
5877 				    "%02x:%02x:%02x rc=%d\n",
5878 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
5879 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
5880 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
5881 				    -ctx->rc);
5882 			}
5883 			return (0);
5884 		}
5885 		ctx->del = 0;
5886 		ctx->i = 0;
5887 	}
5888 
5889 	return (1);
5890 }
5891 
5892 /*
5893  * Program the port's XGMAC based on parameters in ifnet.  The caller also
5894  * indicates which parameters should be programmed (the rest are left alone).
5895  */
5896 int
5897 update_mac_settings(struct ifnet *ifp, int flags)
5898 {
5899 	int rc = 0;
5900 	struct vi_info *vi = ifp->if_softc;
5901 	struct port_info *pi = vi->pi;
5902 	struct adapter *sc = pi->adapter;
5903 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
5904 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
5905 
5906 	ASSERT_SYNCHRONIZED_OP(sc);
5907 	KASSERT(flags, ("%s: not told what to update.", __func__));
5908 
5909 	if (flags & XGMAC_MTU)
5910 		mtu = ifp->if_mtu;
5911 
5912 	if (flags & XGMAC_PROMISC)
5913 		promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
5914 
5915 	if (flags & XGMAC_ALLMULTI)
5916 		allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
5917 
5918 	if (flags & XGMAC_VLANEX)
5919 		vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
5920 
5921 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
5922 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
5923 		    allmulti, 1, vlanex, false);
5924 		if (rc) {
5925 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
5926 			    rc);
5927 			return (rc);
5928 		}
5929 	}
5930 
5931 	if (flags & XGMAC_UCADDR) {
5932 		uint8_t ucaddr[ETHER_ADDR_LEN];
5933 
5934 		bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
5935 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
5936 		    ucaddr, true, &vi->smt_idx);
5937 		if (rc < 0) {
5938 			rc = -rc;
5939 			if_printf(ifp, "change_mac failed: %d\n", rc);
5940 			return (rc);
5941 		} else {
5942 			vi->xact_addr_filt = rc;
5943 			rc = 0;
5944 		}
5945 	}
5946 
5947 	if (flags & XGMAC_MCADDRS) {
5948 		struct epoch_tracker et;
5949 		struct mcaddr_ctx ctx;
5950 		int j;
5951 
5952 		ctx.ifp = ifp;
5953 		ctx.hash = 0;
5954 		ctx.i = 0;
5955 		ctx.del = 1;
5956 		ctx.rc = 0;
5957 		/*
5958 		 * Unlike other drivers, we accumulate list of pointers into
5959 		 * interface address lists and we need to keep it safe even
5960 		 * after if_foreach_llmaddr() returns, thus we must enter the
5961 		 * network epoch.
5962 		 */
5963 		NET_EPOCH_ENTER(et);
5964 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
5965 		if (ctx.rc < 0) {
5966 			NET_EPOCH_EXIT(et);
5967 			rc = -ctx.rc;
5968 			return (rc);
5969 		}
5970 		if (ctx.i > 0) {
5971 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
5972 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
5973 			NET_EPOCH_EXIT(et);
5974 			if (rc < 0) {
5975 				rc = -rc;
5976 				for (j = 0; j < ctx.i; j++) {
5977 					if_printf(ifp,
5978 					    "failed to add mcast address"
5979 					    " %02x:%02x:%02x:"
5980 					    "%02x:%02x:%02x rc=%d\n",
5981 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
5982 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
5983 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
5984 					    rc);
5985 				}
5986 				return (rc);
5987 			}
5988 			ctx.del = 0;
5989 		} else
5990 			NET_EPOCH_EXIT(et);
5991 
5992 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
5993 		if (rc != 0)
5994 			if_printf(ifp, "failed to set mcast address hash: %d\n",
5995 			    rc);
5996 		if (ctx.del == 0) {
5997 			/* We clobbered the VXLAN entry if there was one. */
5998 			pi->vxlan_tcam_entry = false;
5999 		}
6000 	}
6001 
6002 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6003 	    pi->vxlan_tcam_entry == false) {
6004 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6005 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6006 		    true);
6007 		if (rc < 0) {
6008 			rc = -rc;
6009 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6010 			    rc);
6011 		} else {
6012 			MPASS(rc == sc->rawf_base + pi->port_id);
6013 			rc = 0;
6014 			pi->vxlan_tcam_entry = true;
6015 		}
6016 	}
6017 
6018 	return (rc);
6019 }
6020 
6021 /*
6022  * {begin|end}_synchronized_op must be called from the same thread.
6023  */
6024 int
6025 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6026     char *wmesg)
6027 {
6028 	int rc, pri;
6029 
6030 #ifdef WITNESS
6031 	/* the caller thinks it's ok to sleep, but is it really? */
6032 	if (flags & SLEEP_OK)
6033 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6034 		    "begin_synchronized_op");
6035 #endif
6036 
6037 	if (INTR_OK)
6038 		pri = PCATCH;
6039 	else
6040 		pri = 0;
6041 
6042 	ADAPTER_LOCK(sc);
6043 	for (;;) {
6044 
6045 		if (vi && IS_DOOMED(vi)) {
6046 			rc = ENXIO;
6047 			goto done;
6048 		}
6049 
6050 		if (!IS_BUSY(sc)) {
6051 			rc = 0;
6052 			break;
6053 		}
6054 
6055 		if (!(flags & SLEEP_OK)) {
6056 			rc = EBUSY;
6057 			goto done;
6058 		}
6059 
6060 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6061 			rc = EINTR;
6062 			goto done;
6063 		}
6064 	}
6065 
6066 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6067 	SET_BUSY(sc);
6068 #ifdef INVARIANTS
6069 	sc->last_op = wmesg;
6070 	sc->last_op_thr = curthread;
6071 	sc->last_op_flags = flags;
6072 #endif
6073 
6074 done:
6075 	if (!(flags & HOLD_LOCK) || rc)
6076 		ADAPTER_UNLOCK(sc);
6077 
6078 	return (rc);
6079 }
6080 
6081 /*
6082  * Tell if_ioctl and if_init that the VI is going away.  This is
6083  * special variant of begin_synchronized_op and must be paired with a
6084  * call to end_synchronized_op.
6085  */
6086 void
6087 doom_vi(struct adapter *sc, struct vi_info *vi)
6088 {
6089 
6090 	ADAPTER_LOCK(sc);
6091 	SET_DOOMED(vi);
6092 	wakeup(&sc->flags);
6093 	while (IS_BUSY(sc))
6094 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6095 	SET_BUSY(sc);
6096 #ifdef INVARIANTS
6097 	sc->last_op = "t4detach";
6098 	sc->last_op_thr = curthread;
6099 	sc->last_op_flags = 0;
6100 #endif
6101 	ADAPTER_UNLOCK(sc);
6102 }
6103 
6104 /*
6105  * {begin|end}_synchronized_op must be called from the same thread.
6106  */
6107 void
6108 end_synchronized_op(struct adapter *sc, int flags)
6109 {
6110 
6111 	if (flags & LOCK_HELD)
6112 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6113 	else
6114 		ADAPTER_LOCK(sc);
6115 
6116 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6117 	CLR_BUSY(sc);
6118 	wakeup(&sc->flags);
6119 	ADAPTER_UNLOCK(sc);
6120 }
6121 
6122 static int
6123 cxgbe_init_synchronized(struct vi_info *vi)
6124 {
6125 	struct port_info *pi = vi->pi;
6126 	struct adapter *sc = pi->adapter;
6127 	struct ifnet *ifp = vi->ifp;
6128 	int rc = 0, i;
6129 	struct sge_txq *txq;
6130 
6131 	ASSERT_SYNCHRONIZED_OP(sc);
6132 
6133 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
6134 		return (0);	/* already running */
6135 
6136 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6137 		return (rc);	/* error message displayed already */
6138 
6139 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6140 		return (rc); /* error message displayed already */
6141 
6142 	rc = update_mac_settings(ifp, XGMAC_ALL);
6143 	if (rc)
6144 		goto done;	/* error message displayed already */
6145 
6146 	PORT_LOCK(pi);
6147 	if (pi->up_vis == 0) {
6148 		t4_update_port_info(pi);
6149 		fixup_link_config(pi);
6150 		build_medialist(pi);
6151 		apply_link_config(pi);
6152 	}
6153 
6154 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6155 	if (rc != 0) {
6156 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6157 		PORT_UNLOCK(pi);
6158 		goto done;
6159 	}
6160 
6161 	/*
6162 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6163 	 * if this changes.
6164 	 */
6165 
6166 	for_each_txq(vi, i, txq) {
6167 		TXQ_LOCK(txq);
6168 		txq->eq.flags |= EQ_ENABLED;
6169 		TXQ_UNLOCK(txq);
6170 	}
6171 
6172 	/*
6173 	 * The first iq of the first port to come up is used for tracing.
6174 	 */
6175 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6176 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6177 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6178 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6179 		    V_QUEUENUMBER(sc->traceq));
6180 		pi->flags |= HAS_TRACEQ;
6181 	}
6182 
6183 	/* all ok */
6184 	pi->up_vis++;
6185 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
6186 	if (pi->link_cfg.link_ok)
6187 		t4_os_link_changed(pi);
6188 	PORT_UNLOCK(pi);
6189 
6190 	mtx_lock(&vi->tick_mtx);
6191 	if (ifp->if_get_counter == vi_get_counter)
6192 		callout_reset(&vi->tick, hz, vi_tick, vi);
6193 	else
6194 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6195 	mtx_unlock(&vi->tick_mtx);
6196 done:
6197 	if (rc != 0)
6198 		cxgbe_uninit_synchronized(vi);
6199 
6200 	return (rc);
6201 }
6202 
6203 /*
6204  * Idempotent.
6205  */
6206 static int
6207 cxgbe_uninit_synchronized(struct vi_info *vi)
6208 {
6209 	struct port_info *pi = vi->pi;
6210 	struct adapter *sc = pi->adapter;
6211 	struct ifnet *ifp = vi->ifp;
6212 	int rc, i;
6213 	struct sge_txq *txq;
6214 
6215 	ASSERT_SYNCHRONIZED_OP(sc);
6216 
6217 	if (!(vi->flags & VI_INIT_DONE)) {
6218 		if (__predict_false(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6219 			KASSERT(0, ("uninited VI is running"));
6220 			if_printf(ifp, "uninited VI with running ifnet.  "
6221 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6222 			    "if_drv_flags 0x%08x\n", vi->flags, ifp->if_flags,
6223 			    ifp->if_drv_flags);
6224 		}
6225 		return (0);
6226 	}
6227 
6228 	/*
6229 	 * Disable the VI so that all its data in either direction is discarded
6230 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6231 	 * tick) intact as the TP can deliver negative advice or data that it's
6232 	 * holding in its RAM (for an offloaded connection) even after the VI is
6233 	 * disabled.
6234 	 */
6235 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6236 	if (rc) {
6237 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6238 		return (rc);
6239 	}
6240 
6241 	for_each_txq(vi, i, txq) {
6242 		TXQ_LOCK(txq);
6243 		txq->eq.flags &= ~EQ_ENABLED;
6244 		TXQ_UNLOCK(txq);
6245 	}
6246 
6247 	mtx_lock(&vi->tick_mtx);
6248 	callout_stop(&vi->tick);
6249 	mtx_unlock(&vi->tick_mtx);
6250 
6251 	PORT_LOCK(pi);
6252 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6253 		PORT_UNLOCK(pi);
6254 		return (0);
6255 	}
6256 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
6257 	pi->up_vis--;
6258 	if (pi->up_vis > 0) {
6259 		PORT_UNLOCK(pi);
6260 		return (0);
6261 	}
6262 
6263 	pi->link_cfg.link_ok = false;
6264 	pi->link_cfg.speed = 0;
6265 	pi->link_cfg.link_down_rc = 255;
6266 	t4_os_link_changed(pi);
6267 	PORT_UNLOCK(pi);
6268 
6269 	return (0);
6270 }
6271 
6272 /*
6273  * It is ok for this function to fail midway and return right away.  t4_detach
6274  * will walk the entire sc->irq list and clean up whatever is valid.
6275  */
6276 int
6277 t4_setup_intr_handlers(struct adapter *sc)
6278 {
6279 	int rc, rid, p, q, v;
6280 	char s[8];
6281 	struct irq *irq;
6282 	struct port_info *pi;
6283 	struct vi_info *vi;
6284 	struct sge *sge = &sc->sge;
6285 	struct sge_rxq *rxq;
6286 #ifdef TCP_OFFLOAD
6287 	struct sge_ofld_rxq *ofld_rxq;
6288 #endif
6289 #ifdef DEV_NETMAP
6290 	struct sge_nm_rxq *nm_rxq;
6291 #endif
6292 #ifdef RSS
6293 	int nbuckets = rss_getnumbuckets();
6294 #endif
6295 
6296 	/*
6297 	 * Setup interrupts.
6298 	 */
6299 	irq = &sc->irq[0];
6300 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6301 	if (forwarding_intr_to_fwq(sc))
6302 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6303 
6304 	/* Multiple interrupts. */
6305 	if (sc->flags & IS_VF)
6306 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6307 		    ("%s: too few intr.", __func__));
6308 	else
6309 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6310 		    ("%s: too few intr.", __func__));
6311 
6312 	/* The first one is always error intr on PFs */
6313 	if (!(sc->flags & IS_VF)) {
6314 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6315 		if (rc != 0)
6316 			return (rc);
6317 		irq++;
6318 		rid++;
6319 	}
6320 
6321 	/* The second one is always the firmware event queue (first on VFs) */
6322 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6323 	if (rc != 0)
6324 		return (rc);
6325 	irq++;
6326 	rid++;
6327 
6328 	for_each_port(sc, p) {
6329 		pi = sc->port[p];
6330 		for_each_vi(pi, v, vi) {
6331 			vi->first_intr = rid - 1;
6332 
6333 			if (vi->nnmrxq > 0) {
6334 				int n = max(vi->nrxq, vi->nnmrxq);
6335 
6336 				rxq = &sge->rxq[vi->first_rxq];
6337 #ifdef DEV_NETMAP
6338 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6339 #endif
6340 				for (q = 0; q < n; q++) {
6341 					snprintf(s, sizeof(s), "%x%c%x", p,
6342 					    'a' + v, q);
6343 					if (q < vi->nrxq)
6344 						irq->rxq = rxq++;
6345 #ifdef DEV_NETMAP
6346 					if (q < vi->nnmrxq)
6347 						irq->nm_rxq = nm_rxq++;
6348 
6349 					if (irq->nm_rxq != NULL &&
6350 					    irq->rxq == NULL) {
6351 						/* Netmap rx only */
6352 						rc = t4_alloc_irq(sc, irq, rid,
6353 						    t4_nm_intr, irq->nm_rxq, s);
6354 					}
6355 					if (irq->nm_rxq != NULL &&
6356 					    irq->rxq != NULL) {
6357 						/* NIC and Netmap rx */
6358 						rc = t4_alloc_irq(sc, irq, rid,
6359 						    t4_vi_intr, irq, s);
6360 					}
6361 #endif
6362 					if (irq->rxq != NULL &&
6363 					    irq->nm_rxq == NULL) {
6364 						/* NIC rx only */
6365 						rc = t4_alloc_irq(sc, irq, rid,
6366 						    t4_intr, irq->rxq, s);
6367 					}
6368 					if (rc != 0)
6369 						return (rc);
6370 #ifdef RSS
6371 					if (q < vi->nrxq) {
6372 						bus_bind_intr(sc->dev, irq->res,
6373 						    rss_getcpu(q % nbuckets));
6374 					}
6375 #endif
6376 					irq++;
6377 					rid++;
6378 					vi->nintr++;
6379 				}
6380 			} else {
6381 				for_each_rxq(vi, q, rxq) {
6382 					snprintf(s, sizeof(s), "%x%c%x", p,
6383 					    'a' + v, q);
6384 					rc = t4_alloc_irq(sc, irq, rid,
6385 					    t4_intr, rxq, s);
6386 					if (rc != 0)
6387 						return (rc);
6388 #ifdef RSS
6389 					bus_bind_intr(sc->dev, irq->res,
6390 					    rss_getcpu(q % nbuckets));
6391 #endif
6392 					irq++;
6393 					rid++;
6394 					vi->nintr++;
6395 				}
6396 			}
6397 #ifdef TCP_OFFLOAD
6398 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6399 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6400 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6401 				    ofld_rxq, s);
6402 				if (rc != 0)
6403 					return (rc);
6404 				irq++;
6405 				rid++;
6406 				vi->nintr++;
6407 			}
6408 #endif
6409 		}
6410 	}
6411 	MPASS(irq == &sc->irq[sc->intr_count]);
6412 
6413 	return (0);
6414 }
6415 
6416 static void
6417 write_global_rss_key(struct adapter *sc)
6418 {
6419 #ifdef RSS
6420 	int i;
6421 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6422 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6423 
6424 	CTASSERT(RSS_KEYSIZE == 40);
6425 
6426 	rss_getkey((void *)&raw_rss_key[0]);
6427 	for (i = 0; i < nitems(rss_key); i++) {
6428 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6429 	}
6430 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6431 #endif
6432 }
6433 
6434 /*
6435  * Idempotent.
6436  */
6437 static int
6438 adapter_full_init(struct adapter *sc)
6439 {
6440 	int rc, i;
6441 
6442 	ASSERT_SYNCHRONIZED_OP(sc);
6443 
6444 	if (!(sc->flags & ADAP_SYSCTL_CTX)) {
6445 		sysctl_ctx_init(&sc->ctx);
6446 		sc->flags |= ADAP_SYSCTL_CTX;
6447 	}
6448 
6449 	/*
6450 	 * queues that belong to the adapter (not any particular port).
6451 	 */
6452 	rc = t4_setup_adapter_queues(sc);
6453 	if (rc != 0)
6454 		return (rc);
6455 
6456 	for (i = 0; i < nitems(sc->tq); i++) {
6457 		if (sc->tq[i] != NULL)
6458 			continue;
6459 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6460 		    taskqueue_thread_enqueue, &sc->tq[i]);
6461 		if (sc->tq[i] == NULL) {
6462 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6463 			return (ENOMEM);
6464 		}
6465 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6466 		    device_get_nameunit(sc->dev), i);
6467 	}
6468 
6469 	if (!(sc->flags & IS_VF)) {
6470 		write_global_rss_key(sc);
6471 		t4_intr_enable(sc);
6472 	}
6473 	return (0);
6474 }
6475 
6476 int
6477 adapter_init(struct adapter *sc)
6478 {
6479 	int rc;
6480 
6481 	ASSERT_SYNCHRONIZED_OP(sc);
6482 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6483 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6484 	    ("%s: FULL_INIT_DONE already", __func__));
6485 
6486 	rc = adapter_full_init(sc);
6487 	if (rc != 0)
6488 		adapter_full_uninit(sc);
6489 	else
6490 		sc->flags |= FULL_INIT_DONE;
6491 
6492 	return (rc);
6493 }
6494 
6495 /*
6496  * Idempotent.
6497  */
6498 static void
6499 adapter_full_uninit(struct adapter *sc)
6500 {
6501 	int i;
6502 
6503 	/* Do this before freeing the adapter queues. */
6504 	if (sc->flags & ADAP_SYSCTL_CTX) {
6505 		sysctl_ctx_free(&sc->ctx);
6506 		sc->flags &= ~ADAP_SYSCTL_CTX;
6507 	}
6508 
6509 	t4_teardown_adapter_queues(sc);
6510 
6511 	for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
6512 		taskqueue_free(sc->tq[i]);
6513 		sc->tq[i] = NULL;
6514 	}
6515 
6516 	sc->flags &= ~FULL_INIT_DONE;
6517 }
6518 
6519 #ifdef RSS
6520 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6521     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6522     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6523     RSS_HASHTYPE_RSS_UDP_IPV6)
6524 
6525 /* Translates kernel hash types to hardware. */
6526 static int
6527 hashconfig_to_hashen(int hashconfig)
6528 {
6529 	int hashen = 0;
6530 
6531 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6532 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6533 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6534 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6535 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6536 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6537 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6538 	}
6539 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6540 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6541 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6542 	}
6543 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6544 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6545 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6546 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6547 
6548 	return (hashen);
6549 }
6550 
6551 /* Translates hardware hash types to kernel. */
6552 static int
6553 hashen_to_hashconfig(int hashen)
6554 {
6555 	int hashconfig = 0;
6556 
6557 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6558 		/*
6559 		 * If UDP hashing was enabled it must have been enabled for
6560 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6561 		 * enabling any 4-tuple hash is nonsense configuration.
6562 		 */
6563 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6564 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6565 
6566 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6567 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6568 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6569 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6570 	}
6571 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6572 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6573 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6574 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6575 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6576 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6577 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6578 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6579 
6580 	return (hashconfig);
6581 }
6582 #endif
6583 
6584 /*
6585  * Idempotent.
6586  */
6587 static int
6588 vi_full_init(struct vi_info *vi)
6589 {
6590 	struct adapter *sc = vi->adapter;
6591 	struct sge_rxq *rxq;
6592 	int rc, i, j;
6593 #ifdef RSS
6594 	int nbuckets = rss_getnumbuckets();
6595 	int hashconfig = rss_gethashconfig();
6596 	int extra;
6597 #endif
6598 
6599 	ASSERT_SYNCHRONIZED_OP(sc);
6600 
6601 	if (!(vi->flags & VI_SYSCTL_CTX)) {
6602 		sysctl_ctx_init(&vi->ctx);
6603 		vi->flags |= VI_SYSCTL_CTX;
6604 	}
6605 
6606 	/*
6607 	 * Allocate tx/rx/fl queues for this VI.
6608 	 */
6609 	rc = t4_setup_vi_queues(vi);
6610 	if (rc != 0)
6611 		return (rc);
6612 
6613 	/*
6614 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6615 	 */
6616 	if (vi->nrxq > vi->rss_size) {
6617 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6618 		    "some queues will never receive traffic.\n", vi->nrxq,
6619 		    vi->rss_size);
6620 	} else if (vi->rss_size % vi->nrxq) {
6621 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6622 		    "expect uneven traffic distribution.\n", vi->nrxq,
6623 		    vi->rss_size);
6624 	}
6625 #ifdef RSS
6626 	if (vi->nrxq != nbuckets) {
6627 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6628 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6629 	}
6630 #endif
6631 	if (vi->rss == NULL)
6632 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6633 		    M_ZERO | M_WAITOK);
6634 	for (i = 0; i < vi->rss_size;) {
6635 #ifdef RSS
6636 		j = rss_get_indirection_to_bucket(i);
6637 		j %= vi->nrxq;
6638 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6639 		vi->rss[i++] = rxq->iq.abs_id;
6640 #else
6641 		for_each_rxq(vi, j, rxq) {
6642 			vi->rss[i++] = rxq->iq.abs_id;
6643 			if (i == vi->rss_size)
6644 				break;
6645 		}
6646 #endif
6647 	}
6648 
6649 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6650 	    vi->rss, vi->rss_size);
6651 	if (rc != 0) {
6652 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6653 		return (rc);
6654 	}
6655 
6656 #ifdef RSS
6657 	vi->hashen = hashconfig_to_hashen(hashconfig);
6658 
6659 	/*
6660 	 * We may have had to enable some hashes even though the global config
6661 	 * wants them disabled.  This is a potential problem that must be
6662 	 * reported to the user.
6663 	 */
6664 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6665 
6666 	/*
6667 	 * If we consider only the supported hash types, then the enabled hashes
6668 	 * are a superset of the requested hashes.  In other words, there cannot
6669 	 * be any supported hash that was requested but not enabled, but there
6670 	 * can be hashes that were not requested but had to be enabled.
6671 	 */
6672 	extra &= SUPPORTED_RSS_HASHTYPES;
6673 	MPASS((extra & hashconfig) == 0);
6674 
6675 	if (extra) {
6676 		CH_ALERT(vi,
6677 		    "global RSS config (0x%x) cannot be accommodated.\n",
6678 		    hashconfig);
6679 	}
6680 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6681 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6682 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6683 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6684 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6685 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6686 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6687 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6688 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6689 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6690 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6691 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6692 #else
6693 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6694 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6695 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6696 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6697 #endif
6698 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6699 	    0, 0);
6700 	if (rc != 0) {
6701 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6702 		return (rc);
6703 	}
6704 
6705 	return (0);
6706 }
6707 
6708 int
6709 vi_init(struct vi_info *vi)
6710 {
6711 	int rc;
6712 
6713 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6714 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6715 	    ("%s: VI_INIT_DONE already", __func__));
6716 
6717 	rc = vi_full_init(vi);
6718 	if (rc != 0)
6719 		vi_full_uninit(vi);
6720 	else
6721 		vi->flags |= VI_INIT_DONE;
6722 
6723 	return (rc);
6724 }
6725 
6726 /*
6727  * Idempotent.
6728  */
6729 static void
6730 vi_full_uninit(struct vi_info *vi)
6731 {
6732 
6733 	if (vi->flags & VI_INIT_DONE) {
6734 		quiesce_vi(vi);
6735 		free(vi->rss, M_CXGBE);
6736 		free(vi->nm_rss, M_CXGBE);
6737 	}
6738 
6739 	/* Do this before freeing the VI queues. */
6740 	if (vi->flags & VI_SYSCTL_CTX) {
6741 		sysctl_ctx_free(&vi->ctx);
6742 		vi->flags &= ~VI_SYSCTL_CTX;
6743 	}
6744 
6745 	t4_teardown_vi_queues(vi);
6746 	vi->flags &= ~VI_INIT_DONE;
6747 }
6748 
6749 static void
6750 quiesce_txq(struct sge_txq *txq)
6751 {
6752 	struct sge_eq *eq = &txq->eq;
6753 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6754 
6755 	MPASS(eq->flags & EQ_SW_ALLOCATED);
6756 	MPASS(!(eq->flags & EQ_ENABLED));
6757 
6758 	/* Wait for the mp_ring to empty. */
6759 	while (!mp_ring_is_idle(txq->r)) {
6760 		mp_ring_check_drainage(txq->r, 4096);
6761 		pause("rquiesce", 1);
6762 	}
6763 	MPASS(txq->txp.npkt == 0);
6764 
6765 	if (eq->flags & EQ_HW_ALLOCATED) {
6766 		/*
6767 		 * Hardware is alive and working normally.  Wait for it to
6768 		 * finish and then wait for the driver to catch up and reclaim
6769 		 * all descriptors.
6770 		 */
6771 		while (spg->cidx != htobe16(eq->pidx))
6772 			pause("equiesce", 1);
6773 		while (eq->cidx != eq->pidx)
6774 			pause("dquiesce", 1);
6775 	} else {
6776 		/*
6777 		 * Hardware is unavailable.  Discard all pending tx and reclaim
6778 		 * descriptors directly.
6779 		 */
6780 		TXQ_LOCK(txq);
6781 		while (eq->cidx != eq->pidx) {
6782 			struct mbuf *m, *nextpkt;
6783 			struct tx_sdesc *txsd;
6784 
6785 			txsd = &txq->sdesc[eq->cidx];
6786 			for (m = txsd->m; m != NULL; m = nextpkt) {
6787 				nextpkt = m->m_nextpkt;
6788 				m->m_nextpkt = NULL;
6789 				m_freem(m);
6790 			}
6791 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
6792 		}
6793 		spg->pidx = spg->cidx = htobe16(eq->cidx);
6794 		TXQ_UNLOCK(txq);
6795 	}
6796 }
6797 
6798 static void
6799 quiesce_wrq(struct sge_wrq *wrq)
6800 {
6801 
6802 	/* XXXTX */
6803 }
6804 
6805 static void
6806 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
6807 {
6808 	/* Synchronize with the interrupt handler */
6809 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
6810 		pause("iqfree", 1);
6811 
6812 	if (fl != NULL) {
6813 		MPASS(iq->flags & IQ_HAS_FL);
6814 
6815 		mtx_lock(&sc->sfl_lock);
6816 		FL_LOCK(fl);
6817 		fl->flags |= FL_DOOMED;
6818 		FL_UNLOCK(fl);
6819 		callout_stop(&sc->sfl_callout);
6820 		mtx_unlock(&sc->sfl_lock);
6821 
6822 		KASSERT((fl->flags & FL_STARVING) == 0,
6823 		    ("%s: still starving", __func__));
6824 
6825 		/* Release all buffers if hardware is no longer available. */
6826 		if (!(iq->flags & IQ_HW_ALLOCATED))
6827 			free_fl_buffers(sc, fl);
6828 	}
6829 }
6830 
6831 /*
6832  * Wait for all activity on all the queues of the VI to complete.  It is assumed
6833  * that no new work is being enqueued by the hardware or the driver.  That part
6834  * should be arranged before calling this function.
6835  */
6836 static void
6837 quiesce_vi(struct vi_info *vi)
6838 {
6839 	int i;
6840 	struct adapter *sc = vi->adapter;
6841 	struct sge_rxq *rxq;
6842 	struct sge_txq *txq;
6843 #ifdef TCP_OFFLOAD
6844 	struct sge_ofld_rxq *ofld_rxq;
6845 #endif
6846 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6847 	struct sge_ofld_txq *ofld_txq;
6848 #endif
6849 
6850 	if (!(vi->flags & VI_INIT_DONE))
6851 		return;
6852 
6853 	for_each_txq(vi, i, txq) {
6854 		quiesce_txq(txq);
6855 	}
6856 
6857 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6858 	for_each_ofld_txq(vi, i, ofld_txq) {
6859 		quiesce_wrq(&ofld_txq->wrq);
6860 	}
6861 #endif
6862 
6863 	for_each_rxq(vi, i, rxq) {
6864 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
6865 	}
6866 
6867 #ifdef TCP_OFFLOAD
6868 	for_each_ofld_rxq(vi, i, ofld_rxq) {
6869 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
6870 	}
6871 #endif
6872 }
6873 
6874 static int
6875 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
6876     driver_intr_t *handler, void *arg, char *name)
6877 {
6878 	int rc;
6879 
6880 	irq->rid = rid;
6881 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
6882 	    RF_SHAREABLE | RF_ACTIVE);
6883 	if (irq->res == NULL) {
6884 		device_printf(sc->dev,
6885 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
6886 		return (ENOMEM);
6887 	}
6888 
6889 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
6890 	    NULL, handler, arg, &irq->tag);
6891 	if (rc != 0) {
6892 		device_printf(sc->dev,
6893 		    "failed to setup interrupt for rid %d, name %s: %d\n",
6894 		    rid, name, rc);
6895 	} else if (name)
6896 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
6897 
6898 	return (rc);
6899 }
6900 
6901 static int
6902 t4_free_irq(struct adapter *sc, struct irq *irq)
6903 {
6904 	if (irq->tag)
6905 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
6906 	if (irq->res)
6907 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
6908 
6909 	bzero(irq, sizeof(*irq));
6910 
6911 	return (0);
6912 }
6913 
6914 static void
6915 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
6916 {
6917 
6918 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
6919 	t4_get_regs(sc, buf, regs->len);
6920 }
6921 
6922 #define	A_PL_INDIR_CMD	0x1f8
6923 
6924 #define	S_PL_AUTOINC	31
6925 #define	M_PL_AUTOINC	0x1U
6926 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
6927 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
6928 
6929 #define	S_PL_VFID	20
6930 #define	M_PL_VFID	0xffU
6931 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
6932 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
6933 
6934 #define	S_PL_ADDR	0
6935 #define	M_PL_ADDR	0xfffffU
6936 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
6937 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
6938 
6939 #define	A_PL_INDIR_DATA	0x1fc
6940 
6941 static uint64_t
6942 read_vf_stat(struct adapter *sc, u_int vin, int reg)
6943 {
6944 	u32 stats[2];
6945 
6946 	if (sc->flags & IS_VF) {
6947 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
6948 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
6949 	} else {
6950 		mtx_assert(&sc->reg_lock, MA_OWNED);
6951 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
6952 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
6953 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
6954 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
6955 	}
6956 	return (((uint64_t)stats[1]) << 32 | stats[0]);
6957 }
6958 
6959 static void
6960 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
6961 {
6962 
6963 #define GET_STAT(name) \
6964 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
6965 
6966 	if (!(sc->flags & IS_VF))
6967 		mtx_lock(&sc->reg_lock);
6968 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
6969 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
6970 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
6971 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
6972 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
6973 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
6974 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
6975 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
6976 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
6977 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
6978 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
6979 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
6980 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
6981 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
6982 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
6983 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
6984 	if (!(sc->flags & IS_VF))
6985 		mtx_unlock(&sc->reg_lock);
6986 
6987 #undef GET_STAT
6988 }
6989 
6990 static void
6991 t4_clr_vi_stats(struct adapter *sc, u_int vin)
6992 {
6993 	int reg;
6994 
6995 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
6996 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
6997 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
6998 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
6999 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7000 }
7001 
7002 static void
7003 vi_refresh_stats(struct vi_info *vi)
7004 {
7005 	struct timeval tv;
7006 	const struct timeval interval = {0, 250000};	/* 250ms */
7007 
7008 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7009 
7010 	if (!(vi->flags & VI_INIT_DONE) || vi->flags & VI_SKIP_STATS)
7011 		return;
7012 
7013 	getmicrotime(&tv);
7014 	timevalsub(&tv, &interval);
7015 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7016 		return;
7017 
7018 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7019 	getmicrotime(&vi->last_refreshed);
7020 }
7021 
7022 static void
7023 cxgbe_refresh_stats(struct vi_info *vi)
7024 {
7025 	u_int i, v, tnl_cong_drops, chan_map;
7026 	struct timeval tv;
7027 	const struct timeval interval = {0, 250000};	/* 250ms */
7028 	struct port_info *pi;
7029 	struct adapter *sc;
7030 
7031 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7032 
7033 	if (vi->flags & VI_SKIP_STATS)
7034 		return;
7035 
7036 	getmicrotime(&tv);
7037 	timevalsub(&tv, &interval);
7038 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7039 		return;
7040 
7041 	pi = vi->pi;
7042 	sc = vi->adapter;
7043 	tnl_cong_drops = 0;
7044 	t4_get_port_stats(sc, pi->tx_chan, &pi->stats);
7045 	chan_map = pi->rx_e_chan_map;
7046 	while (chan_map) {
7047 		i = ffs(chan_map) - 1;
7048 		mtx_lock(&sc->reg_lock);
7049 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7050 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7051 		mtx_unlock(&sc->reg_lock);
7052 		tnl_cong_drops += v;
7053 		chan_map &= ~(1 << i);
7054 	}
7055 	pi->tnl_cong_drops = tnl_cong_drops;
7056 	getmicrotime(&vi->last_refreshed);
7057 }
7058 
7059 static void
7060 cxgbe_tick(void *arg)
7061 {
7062 	struct vi_info *vi = arg;
7063 
7064 	MPASS(IS_MAIN_VI(vi));
7065 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7066 
7067 	cxgbe_refresh_stats(vi);
7068 	callout_schedule(&vi->tick, hz);
7069 }
7070 
7071 static void
7072 vi_tick(void *arg)
7073 {
7074 	struct vi_info *vi = arg;
7075 
7076 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7077 
7078 	vi_refresh_stats(vi);
7079 	callout_schedule(&vi->tick, hz);
7080 }
7081 
7082 /*
7083  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7084  */
7085 static char *caps_decoder[] = {
7086 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7087 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7088 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7089 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7090 	    "\006HASHFILTER\007ETHOFLD",
7091 	"\20\001TOE",					/* 4: TOE */
7092 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7093 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7094 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7095 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7096 	    "\007T10DIF"
7097 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7098 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7099 	    "\004TLS_HW",
7100 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7101 		    "\004PO_INITIATOR\005PO_TARGET",
7102 };
7103 
7104 void
7105 t4_sysctls(struct adapter *sc)
7106 {
7107 	struct sysctl_ctx_list *ctx;
7108 	struct sysctl_oid *oid;
7109 	struct sysctl_oid_list *children, *c0;
7110 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7111 
7112 	ctx = device_get_sysctl_ctx(sc->dev);
7113 
7114 	/*
7115 	 * dev.t4nex.X.
7116 	 */
7117 	oid = device_get_sysctl_tree(sc->dev);
7118 	c0 = children = SYSCTL_CHILDREN(oid);
7119 
7120 	sc->sc_do_rxcopy = 1;
7121 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7122 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7123 
7124 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7125 	    sc->params.nports, "# of ports");
7126 
7127 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7128 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7129 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7130 	    "available doorbells");
7131 
7132 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7133 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7134 
7135 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7136 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7137 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7138 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7139 
7140 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7141 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7142 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7143 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7144 
7145 	t4_sge_sysctls(sc, ctx, children);
7146 
7147 	sc->lro_timeout = 100;
7148 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7149 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7150 
7151 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7152 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7153 
7154 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7155 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7156 
7157 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7158 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7159 
7160 	if (sc->flags & IS_VF)
7161 		return;
7162 
7163 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7164 	    NULL, chip_rev(sc), "chip hardware revision");
7165 
7166 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7167 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7168 
7169 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7170 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7171 
7172 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7173 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7174 
7175 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7176 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7177 
7178 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7179 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7180 
7181 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7182 	    sc->er_version, 0, "expansion ROM version");
7183 
7184 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7185 	    sc->bs_version, 0, "bootstrap firmware version");
7186 
7187 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7188 	    NULL, sc->params.scfg_vers, "serial config version");
7189 
7190 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7191 	    NULL, sc->params.vpd_vers, "VPD version");
7192 
7193 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7194 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7195 
7196 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7197 	    sc->cfcsum, "config file checksum");
7198 
7199 #define SYSCTL_CAP(name, n, text) \
7200 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7201 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7202 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7203 	    "available " text " capabilities")
7204 
7205 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7206 	SYSCTL_CAP(linkcaps, 1, "link");
7207 	SYSCTL_CAP(switchcaps, 2, "switch");
7208 	SYSCTL_CAP(niccaps, 3, "NIC");
7209 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7210 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7211 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7212 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7213 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7214 #undef SYSCTL_CAP
7215 
7216 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7217 	    NULL, sc->tids.nftids, "number of filters");
7218 
7219 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7220 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7221 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7222 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7223 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7224 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7225 
7226 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7227 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7228 	    sysctl_loadavg, "A",
7229 	    "microprocessor load averages (debug firmwares only)");
7230 
7231 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7232 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7233 	    "I", "core Vdd (in mV)");
7234 
7235 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7236 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7237 	    sysctl_cpus, "A", "local CPUs");
7238 
7239 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7240 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7241 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7242 
7243 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7244 	    &sc->swintr, 0, "software triggered interrupts");
7245 
7246 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7247 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7248 	    "1 = reset adapter, 0 = zero reset counter");
7249 
7250 	/*
7251 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7252 	 */
7253 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7254 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7255 	    "logs and miscellaneous information");
7256 	children = SYSCTL_CHILDREN(oid);
7257 
7258 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7259 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7260 	    sysctl_cctrl, "A", "congestion control");
7261 
7262 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7263 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7264 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7265 
7266 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7267 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7268 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7269 
7270 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7271 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7272 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7273 
7274 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7275 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7276 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7277 
7278 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7279 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7280 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7281 
7282 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7283 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7284 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7285 
7286 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7287 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7288 	    sysctl_cim_la, "A", "CIM logic analyzer");
7289 
7290 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7291 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7292 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7293 
7294 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7295 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7296 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7297 
7298 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7299 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7300 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7301 
7302 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7303 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7304 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7305 
7306 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7307 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7308 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7309 
7310 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7311 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7312 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7313 
7314 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7315 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7316 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7317 
7318 	if (chip_id(sc) > CHELSIO_T4) {
7319 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7320 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7321 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7322 		    "CIM OBQ 6 (SGE0-RX)");
7323 
7324 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7325 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7326 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7327 		    "CIM OBQ 7 (SGE1-RX)");
7328 	}
7329 
7330 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7331 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7332 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7333 
7334 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7335 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7336 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7337 
7338 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7339 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7340 	    sysctl_cpl_stats, "A", "CPL statistics");
7341 
7342 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7343 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7344 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7345 
7346 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7347 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7348 	    sysctl_tid_stats, "A", "tid stats");
7349 
7350 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7351 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7352 	    sysctl_devlog, "A", "firmware's device log");
7353 
7354 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7355 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7356 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7357 
7358 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7359 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7360 	    sysctl_hw_sched, "A", "hardware scheduler ");
7361 
7362 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7363 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7364 	    sysctl_l2t, "A", "hardware L2 table");
7365 
7366 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7367 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7368 	    sysctl_smt, "A", "hardware source MAC table");
7369 
7370 #ifdef INET6
7371 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7372 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7373 	    sysctl_clip, "A", "active CLIP table entries");
7374 #endif
7375 
7376 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7377 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7378 	    sysctl_lb_stats, "A", "loopback statistics");
7379 
7380 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7381 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7382 	    sysctl_meminfo, "A", "memory regions");
7383 
7384 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7385 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7386 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7387 	    "A", "MPS TCAM entries");
7388 
7389 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7390 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7391 	    sysctl_path_mtus, "A", "path MTUs");
7392 
7393 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7394 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7395 	    sysctl_pm_stats, "A", "PM statistics");
7396 
7397 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7398 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7399 	    sysctl_rdma_stats, "A", "RDMA statistics");
7400 
7401 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7402 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7403 	    sysctl_tcp_stats, "A", "TCP statistics");
7404 
7405 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7406 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7407 	    sysctl_tids, "A", "TID information");
7408 
7409 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7410 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7411 	    sysctl_tp_err_stats, "A", "TP error statistics");
7412 
7413 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7414 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7415 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7416 
7417 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7418 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7419 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7420 
7421 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7422 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7423 	    sysctl_tp_la, "A", "TP logic analyzer");
7424 
7425 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7426 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7427 	    sysctl_tx_rate, "A", "Tx rate");
7428 
7429 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7430 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7431 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7432 
7433 	if (chip_id(sc) >= CHELSIO_T5) {
7434 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7435 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7436 		    sysctl_wcwr_stats, "A", "write combined work requests");
7437 	}
7438 
7439 #ifdef KERN_TLS
7440 	if (is_ktls(sc)) {
7441 		/*
7442 		 * dev.t4nex.0.tls.
7443 		 */
7444 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7445 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7446 		children = SYSCTL_CHILDREN(oid);
7447 
7448 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7449 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7450 		    "keys in work requests (1) or attempt to store TLS keys "
7451 		    "in card memory.");
7452 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7453 		    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to combine "
7454 		    "TCB field updates with TLS record work requests.");
7455 	}
7456 #endif
7457 
7458 #ifdef TCP_OFFLOAD
7459 	if (is_offload(sc)) {
7460 		int i;
7461 		char s[4];
7462 
7463 		/*
7464 		 * dev.t4nex.X.toe.
7465 		 */
7466 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7467 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7468 		children = SYSCTL_CHILDREN(oid);
7469 
7470 		sc->tt.cong_algorithm = -1;
7471 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7472 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7473 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7474 		    "3 = highspeed)");
7475 
7476 		sc->tt.sndbuf = -1;
7477 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7478 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7479 
7480 		sc->tt.ddp = 0;
7481 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7482 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7483 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7484 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7485 
7486 		sc->tt.rx_coalesce = -1;
7487 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7488 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7489 
7490 		sc->tt.tls = 0;
7491 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7492 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7493 		    "Inline TLS allowed");
7494 
7495 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_ports",
7496 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7497 		    sysctl_tls_rx_ports, "I",
7498 		    "TCP ports that use inline TLS+TOE RX");
7499 
7500 		sc->tt.tls_rx_timeout = t4_toe_tls_rx_timeout;
7501 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_timeout",
7502 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7503 		    sysctl_tls_rx_timeout, "I",
7504 		    "Timeout in seconds to downgrade TLS sockets to plain TOE");
7505 
7506 		sc->tt.tx_align = -1;
7507 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7508 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7509 
7510 		sc->tt.tx_zcopy = 0;
7511 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7512 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7513 		    "Enable zero-copy aio_write(2)");
7514 
7515 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7516 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7517 		    "cop_managed_offloading", CTLFLAG_RW,
7518 		    &sc->tt.cop_managed_offloading, 0,
7519 		    "COP (Connection Offload Policy) controls all TOE offload");
7520 
7521 		sc->tt.autorcvbuf_inc = 16 * 1024;
7522 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7523 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7524 		    "autorcvbuf increment");
7525 
7526 		sc->tt.update_hc_on_pmtu_change = 1;
7527 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7528 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7529 		    &sc->tt.update_hc_on_pmtu_change, 0,
7530 		    "Update hostcache entry if the PMTU changes");
7531 
7532 		sc->tt.iso = 1;
7533 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7534 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7535 
7536 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7537 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7538 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7539 
7540 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7541 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7542 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7543 
7544 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7545 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7546 		    sysctl_tp_tick, "A", "DACK tick (us)");
7547 
7548 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7549 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7550 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7551 
7552 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7553 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7554 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7555 		    "Minimum retransmit interval (us)");
7556 
7557 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7558 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7559 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7560 		    "Maximum retransmit interval (us)");
7561 
7562 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7563 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7564 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7565 		    "Persist timer min (us)");
7566 
7567 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7568 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7569 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7570 		    "Persist timer max (us)");
7571 
7572 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7573 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7574 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7575 		    "Keepalive idle timer (us)");
7576 
7577 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7578 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7579 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7580 		    "Keepalive interval timer (us)");
7581 
7582 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7583 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7584 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7585 
7586 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7587 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7588 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7589 		    "FINWAIT2 timer (us)");
7590 
7591 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7592 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7593 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7594 		    "Number of SYN retransmissions before abort");
7595 
7596 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7597 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7598 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7599 		    "Number of retransmissions before abort");
7600 
7601 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7602 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7603 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7604 		    "Number of keepalive probes before abort");
7605 
7606 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7607 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7608 		    "TOE retransmit backoffs");
7609 		children = SYSCTL_CHILDREN(oid);
7610 		for (i = 0; i < 16; i++) {
7611 			snprintf(s, sizeof(s), "%u", i);
7612 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7613 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7614 			    i, sysctl_tp_backoff, "IU",
7615 			    "TOE retransmit backoff");
7616 		}
7617 	}
7618 #endif
7619 }
7620 
7621 void
7622 vi_sysctls(struct vi_info *vi)
7623 {
7624 	struct sysctl_ctx_list *ctx;
7625 	struct sysctl_oid *oid;
7626 	struct sysctl_oid_list *children;
7627 
7628 	ctx = device_get_sysctl_ctx(vi->dev);
7629 
7630 	/*
7631 	 * dev.v?(cxgbe|cxl).X.
7632 	 */
7633 	oid = device_get_sysctl_tree(vi->dev);
7634 	children = SYSCTL_CHILDREN(oid);
7635 
7636 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7637 	    vi->viid, "VI identifer");
7638 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7639 	    &vi->nrxq, 0, "# of rx queues");
7640 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7641 	    &vi->ntxq, 0, "# of tx queues");
7642 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7643 	    &vi->first_rxq, 0, "index of first rx queue");
7644 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7645 	    &vi->first_txq, 0, "index of first tx queue");
7646 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7647 	    vi->rss_base, "start of RSS indirection table");
7648 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7649 	    vi->rss_size, "size of RSS indirection table");
7650 
7651 	if (IS_MAIN_VI(vi)) {
7652 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7653 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7654 		    sysctl_noflowq, "IU",
7655 		    "Reserve queue 0 for non-flowid packets");
7656 	}
7657 
7658 	if (vi->adapter->flags & IS_VF) {
7659 		MPASS(vi->flags & TX_USES_VM_WR);
7660 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7661 		    NULL, 1, "use VM work requests for transmit");
7662 	} else {
7663 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7664 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7665 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7666 	}
7667 
7668 #ifdef TCP_OFFLOAD
7669 	if (vi->nofldrxq != 0) {
7670 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7671 		    &vi->nofldrxq, 0,
7672 		    "# of rx queues for offloaded TCP connections");
7673 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7674 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7675 		    "index of first TOE rx queue");
7676 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7677 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7678 		    sysctl_holdoff_tmr_idx_ofld, "I",
7679 		    "holdoff timer index for TOE queues");
7680 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7681 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7682 		    sysctl_holdoff_pktc_idx_ofld, "I",
7683 		    "holdoff packet counter index for TOE queues");
7684 	}
7685 #endif
7686 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7687 	if (vi->nofldtxq != 0) {
7688 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7689 		    &vi->nofldtxq, 0,
7690 		    "# of tx queues for TOE/ETHOFLD");
7691 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7692 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7693 		    "index of first TOE/ETHOFLD tx queue");
7694 	}
7695 #endif
7696 #ifdef DEV_NETMAP
7697 	if (vi->nnmrxq != 0) {
7698 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7699 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7700 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7701 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7702 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7703 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7704 		    "index of first netmap rx queue");
7705 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7706 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7707 		    "index of first netmap tx queue");
7708 	}
7709 #endif
7710 
7711 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7712 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7713 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7714 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7715 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7716 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7717 
7718 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7719 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7720 	    sysctl_qsize_rxq, "I", "rx queue size");
7721 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7722 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7723 	    sysctl_qsize_txq, "I", "tx queue size");
7724 }
7725 
7726 static void
7727 cxgbe_sysctls(struct port_info *pi)
7728 {
7729 	struct sysctl_ctx_list *ctx;
7730 	struct sysctl_oid *oid;
7731 	struct sysctl_oid_list *children, *children2;
7732 	struct adapter *sc = pi->adapter;
7733 	int i;
7734 	char name[16];
7735 	static char *tc_flags = {"\20\1USER"};
7736 
7737 	ctx = device_get_sysctl_ctx(pi->dev);
7738 
7739 	/*
7740 	 * dev.cxgbe.X.
7741 	 */
7742 	oid = device_get_sysctl_tree(pi->dev);
7743 	children = SYSCTL_CHILDREN(oid);
7744 
7745 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7746 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7747 	    sysctl_linkdnrc, "A", "reason why link is down");
7748 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7749 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7750 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7751 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
7752 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7753 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7754 		    sysctl_btphy, "I", "PHY firmware version");
7755 	}
7756 
7757 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7758 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7759 	    sysctl_pause_settings, "A",
7760 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7761 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fec",
7762 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7763 	    sysctl_fec, "A",
7764 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7765 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7766 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7767 	    "FEC recommended by the cable/transceiver");
7768 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7769 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7770 	    sysctl_autoneg, "I",
7771 	    "autonegotiation (-1 = not supported)");
7772 
7773 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7774 	    &pi->link_cfg.pcaps, 0, "port capabilities");
7775 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7776 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
7777 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7778 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7779 
7780 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7781 	    port_top_speed(pi), "max speed (in Gbps)");
7782 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7783 	    pi->mps_bg_map, "MPS buffer group map");
7784 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
7785 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
7786 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_c_chan", CTLFLAG_RD, NULL,
7787 	    pi->rx_c_chan, "TP rx c-channel");
7788 
7789 	if (sc->flags & IS_VF)
7790 		return;
7791 
7792 	/*
7793 	 * dev.(cxgbe|cxl).X.tc.
7794 	 */
7795 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
7796 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7797 	    "Tx scheduler traffic classes (cl_rl)");
7798 	children2 = SYSCTL_CHILDREN(oid);
7799 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
7800 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
7801 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
7802 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
7803 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
7804 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
7805 	for (i = 0; i < sc->params.nsched_cls; i++) {
7806 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
7807 
7808 		snprintf(name, sizeof(name), "%d", i);
7809 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
7810 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
7811 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
7812 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
7813 		    CTLFLAG_RD, &tc->state, 0, "current state");
7814 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
7815 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
7816 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
7817 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
7818 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
7819 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
7820 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7821 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
7822 		    "traffic class parameters");
7823 	}
7824 
7825 	/*
7826 	 * dev.cxgbe.X.stats.
7827 	 */
7828 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
7829 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
7830 	children = SYSCTL_CHILDREN(oid);
7831 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
7832 	    &pi->tx_parse_error, 0,
7833 	    "# of tx packets with invalid length or # of segments");
7834 
7835 #define T4_REGSTAT(name, stat, desc) \
7836     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
7837         CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
7838 	(is_t4(sc) ? PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L) : \
7839 	T5_PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L)), \
7840         sysctl_handle_t4_reg64, "QU", desc)
7841 
7842 /* We get these from port_stats and they may be stale by up to 1s */
7843 #define T4_PORTSTAT(name, desc) \
7844 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
7845 	    &pi->stats.name, desc)
7846 
7847 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
7848 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
7849 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
7850 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
7851 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
7852 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
7853 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
7854 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
7855 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
7856 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
7857 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
7858 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
7859 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
7860 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
7861 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
7862 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
7863 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
7864 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
7865 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
7866 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
7867 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
7868 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
7869 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
7870 
7871 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
7872 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
7873 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
7874 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
7875 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
7876 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
7877 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
7878 	if (is_t6(sc)) {
7879 		T4_PORTSTAT(rx_fcs_err,
7880 		    "# of frames received with bad FCS since last link up");
7881 	} else {
7882 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
7883 		    "# of frames received with bad FCS");
7884 	}
7885 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
7886 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
7887 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
7888 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
7889 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
7890 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
7891 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
7892 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
7893 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
7894 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
7895 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
7896 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
7897 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
7898 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
7899 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
7900 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
7901 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
7902 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
7903 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
7904 
7905 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
7906 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
7907 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
7908 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
7909 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
7910 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
7911 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
7912 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
7913 
7914 #undef T4_REGSTAT
7915 #undef T4_PORTSTAT
7916 }
7917 
7918 static int
7919 sysctl_int_array(SYSCTL_HANDLER_ARGS)
7920 {
7921 	int rc, *i, space = 0;
7922 	struct sbuf sb;
7923 
7924 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
7925 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
7926 		if (space)
7927 			sbuf_printf(&sb, " ");
7928 		sbuf_printf(&sb, "%d", *i);
7929 		space = 1;
7930 	}
7931 	rc = sbuf_finish(&sb);
7932 	sbuf_delete(&sb);
7933 	return (rc);
7934 }
7935 
7936 static int
7937 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
7938 {
7939 	int rc;
7940 	struct sbuf *sb;
7941 
7942 	rc = sysctl_wire_old_buffer(req, 0);
7943 	if (rc != 0)
7944 		return(rc);
7945 
7946 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7947 	if (sb == NULL)
7948 		return (ENOMEM);
7949 
7950 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
7951 	rc = sbuf_finish(sb);
7952 	sbuf_delete(sb);
7953 
7954 	return (rc);
7955 }
7956 
7957 static int
7958 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
7959 {
7960 	int rc;
7961 	struct sbuf *sb;
7962 
7963 	rc = sysctl_wire_old_buffer(req, 0);
7964 	if (rc != 0)
7965 		return(rc);
7966 
7967 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7968 	if (sb == NULL)
7969 		return (ENOMEM);
7970 
7971 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
7972 	rc = sbuf_finish(sb);
7973 	sbuf_delete(sb);
7974 
7975 	return (rc);
7976 }
7977 
7978 static int
7979 sysctl_btphy(SYSCTL_HANDLER_ARGS)
7980 {
7981 	struct port_info *pi = arg1;
7982 	int op = arg2;
7983 	struct adapter *sc = pi->adapter;
7984 	u_int v;
7985 	int rc;
7986 
7987 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
7988 	if (rc)
7989 		return (rc);
7990 	if (hw_off_limits(sc))
7991 		rc = ENXIO;
7992 	else {
7993 		/* XXX: magic numbers */
7994 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
7995 		    op ? 0x20 : 0xc820, &v);
7996 	}
7997 	end_synchronized_op(sc, 0);
7998 	if (rc)
7999 		return (rc);
8000 	if (op == 0)
8001 		v /= 256;
8002 
8003 	rc = sysctl_handle_int(oidp, &v, 0, req);
8004 	return (rc);
8005 }
8006 
8007 static int
8008 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8009 {
8010 	struct vi_info *vi = arg1;
8011 	int rc, val;
8012 
8013 	val = vi->rsrv_noflowq;
8014 	rc = sysctl_handle_int(oidp, &val, 0, req);
8015 	if (rc != 0 || req->newptr == NULL)
8016 		return (rc);
8017 
8018 	if ((val >= 1) && (vi->ntxq > 1))
8019 		vi->rsrv_noflowq = 1;
8020 	else
8021 		vi->rsrv_noflowq = 0;
8022 
8023 	return (rc);
8024 }
8025 
8026 static int
8027 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8028 {
8029 	struct vi_info *vi = arg1;
8030 	struct adapter *sc = vi->adapter;
8031 	int rc, val, i;
8032 
8033 	MPASS(!(sc->flags & IS_VF));
8034 
8035 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8036 	rc = sysctl_handle_int(oidp, &val, 0, req);
8037 	if (rc != 0 || req->newptr == NULL)
8038 		return (rc);
8039 
8040 	if (val != 0 && val != 1)
8041 		return (EINVAL);
8042 
8043 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8044 	    "t4txvm");
8045 	if (rc)
8046 		return (rc);
8047 	if (hw_off_limits(sc))
8048 		rc = ENXIO;
8049 	else if (vi->ifp->if_drv_flags & IFF_DRV_RUNNING) {
8050 		/*
8051 		 * We don't want parse_pkt to run with one setting (VF or PF)
8052 		 * and then eth_tx to see a different setting but still use
8053 		 * stale information calculated by parse_pkt.
8054 		 */
8055 		rc = EBUSY;
8056 	} else {
8057 		struct port_info *pi = vi->pi;
8058 		struct sge_txq *txq;
8059 		uint32_t ctrl0;
8060 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8061 
8062 		if (val) {
8063 			vi->flags |= TX_USES_VM_WR;
8064 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
8065 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8066 			    V_TXPKT_INTF(pi->tx_chan));
8067 			if (!(sc->flags & IS_VF))
8068 				npkt--;
8069 		} else {
8070 			vi->flags &= ~TX_USES_VM_WR;
8071 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
8072 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8073 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8074 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8075 		}
8076 		for_each_txq(vi, i, txq) {
8077 			txq->cpl_ctrl0 = ctrl0;
8078 			txq->txp.max_npkt = npkt;
8079 		}
8080 	}
8081 	end_synchronized_op(sc, LOCK_HELD);
8082 	return (rc);
8083 }
8084 
8085 static int
8086 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8087 {
8088 	struct vi_info *vi = arg1;
8089 	struct adapter *sc = vi->adapter;
8090 	int idx, rc, i;
8091 	struct sge_rxq *rxq;
8092 	uint8_t v;
8093 
8094 	idx = vi->tmr_idx;
8095 
8096 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8097 	if (rc != 0 || req->newptr == NULL)
8098 		return (rc);
8099 
8100 	if (idx < 0 || idx >= SGE_NTIMERS)
8101 		return (EINVAL);
8102 
8103 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8104 	    "t4tmr");
8105 	if (rc)
8106 		return (rc);
8107 
8108 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8109 	for_each_rxq(vi, i, rxq) {
8110 #ifdef atomic_store_rel_8
8111 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8112 #else
8113 		rxq->iq.intr_params = v;
8114 #endif
8115 	}
8116 	vi->tmr_idx = idx;
8117 
8118 	end_synchronized_op(sc, LOCK_HELD);
8119 	return (0);
8120 }
8121 
8122 static int
8123 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8124 {
8125 	struct vi_info *vi = arg1;
8126 	struct adapter *sc = vi->adapter;
8127 	int idx, rc;
8128 
8129 	idx = vi->pktc_idx;
8130 
8131 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8132 	if (rc != 0 || req->newptr == NULL)
8133 		return (rc);
8134 
8135 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8136 		return (EINVAL);
8137 
8138 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8139 	    "t4pktc");
8140 	if (rc)
8141 		return (rc);
8142 
8143 	if (vi->flags & VI_INIT_DONE)
8144 		rc = EBUSY; /* cannot be changed once the queues are created */
8145 	else
8146 		vi->pktc_idx = idx;
8147 
8148 	end_synchronized_op(sc, LOCK_HELD);
8149 	return (rc);
8150 }
8151 
8152 static int
8153 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8154 {
8155 	struct vi_info *vi = arg1;
8156 	struct adapter *sc = vi->adapter;
8157 	int qsize, rc;
8158 
8159 	qsize = vi->qsize_rxq;
8160 
8161 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8162 	if (rc != 0 || req->newptr == NULL)
8163 		return (rc);
8164 
8165 	if (qsize < 128 || (qsize & 7))
8166 		return (EINVAL);
8167 
8168 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8169 	    "t4rxqs");
8170 	if (rc)
8171 		return (rc);
8172 
8173 	if (vi->flags & VI_INIT_DONE)
8174 		rc = EBUSY; /* cannot be changed once the queues are created */
8175 	else
8176 		vi->qsize_rxq = qsize;
8177 
8178 	end_synchronized_op(sc, LOCK_HELD);
8179 	return (rc);
8180 }
8181 
8182 static int
8183 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8184 {
8185 	struct vi_info *vi = arg1;
8186 	struct adapter *sc = vi->adapter;
8187 	int qsize, rc;
8188 
8189 	qsize = vi->qsize_txq;
8190 
8191 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8192 	if (rc != 0 || req->newptr == NULL)
8193 		return (rc);
8194 
8195 	if (qsize < 128 || qsize > 65536)
8196 		return (EINVAL);
8197 
8198 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8199 	    "t4txqs");
8200 	if (rc)
8201 		return (rc);
8202 
8203 	if (vi->flags & VI_INIT_DONE)
8204 		rc = EBUSY; /* cannot be changed once the queues are created */
8205 	else
8206 		vi->qsize_txq = qsize;
8207 
8208 	end_synchronized_op(sc, LOCK_HELD);
8209 	return (rc);
8210 }
8211 
8212 static int
8213 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8214 {
8215 	struct port_info *pi = arg1;
8216 	struct adapter *sc = pi->adapter;
8217 	struct link_config *lc = &pi->link_cfg;
8218 	int rc;
8219 
8220 	if (req->newptr == NULL) {
8221 		struct sbuf *sb;
8222 		static char *bits = "\20\1RX\2TX\3AUTO";
8223 
8224 		rc = sysctl_wire_old_buffer(req, 0);
8225 		if (rc != 0)
8226 			return(rc);
8227 
8228 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8229 		if (sb == NULL)
8230 			return (ENOMEM);
8231 
8232 		if (lc->link_ok) {
8233 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8234 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8235 		} else {
8236 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8237 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8238 		}
8239 		rc = sbuf_finish(sb);
8240 		sbuf_delete(sb);
8241 	} else {
8242 		char s[2];
8243 		int n;
8244 
8245 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8246 		    PAUSE_AUTONEG));
8247 		s[1] = 0;
8248 
8249 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8250 		if (rc != 0)
8251 			return(rc);
8252 
8253 		if (s[1] != 0)
8254 			return (EINVAL);
8255 		if (s[0] < '0' || s[0] > '9')
8256 			return (EINVAL);	/* not a number */
8257 		n = s[0] - '0';
8258 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8259 			return (EINVAL);	/* some other bit is set too */
8260 
8261 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8262 		    "t4PAUSE");
8263 		if (rc)
8264 			return (rc);
8265 		if (!hw_off_limits(sc)) {
8266 			PORT_LOCK(pi);
8267 			lc->requested_fc = n;
8268 			fixup_link_config(pi);
8269 			if (pi->up_vis > 0)
8270 				rc = apply_link_config(pi);
8271 			set_current_media(pi);
8272 			PORT_UNLOCK(pi);
8273 		}
8274 		end_synchronized_op(sc, 0);
8275 	}
8276 
8277 	return (rc);
8278 }
8279 
8280 static int
8281 sysctl_fec(SYSCTL_HANDLER_ARGS)
8282 {
8283 	struct port_info *pi = arg1;
8284 	struct adapter *sc = pi->adapter;
8285 	struct link_config *lc = &pi->link_cfg;
8286 	int rc;
8287 	int8_t old;
8288 
8289 	if (req->newptr == NULL) {
8290 		struct sbuf *sb;
8291 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8292 		    "\5RSVD3\6auto\7module";
8293 
8294 		rc = sysctl_wire_old_buffer(req, 0);
8295 		if (rc != 0)
8296 			return(rc);
8297 
8298 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8299 		if (sb == NULL)
8300 			return (ENOMEM);
8301 
8302 		/*
8303 		 * Display the requested_fec when the link is down -- the actual
8304 		 * FEC makes sense only when the link is up.
8305 		 */
8306 		if (lc->link_ok) {
8307 			sbuf_printf(sb, "%b", (lc->fec & M_FW_PORT_CAP32_FEC) |
8308 			    (lc->requested_fec & (FEC_AUTO | FEC_MODULE)),
8309 			    bits);
8310 		} else {
8311 			sbuf_printf(sb, "%b", lc->requested_fec, bits);
8312 		}
8313 		rc = sbuf_finish(sb);
8314 		sbuf_delete(sb);
8315 	} else {
8316 		char s[8];
8317 		int n;
8318 
8319 		snprintf(s, sizeof(s), "%d",
8320 		    lc->requested_fec == FEC_AUTO ? -1 :
8321 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8322 
8323 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8324 		if (rc != 0)
8325 			return(rc);
8326 
8327 		n = strtol(&s[0], NULL, 0);
8328 		if (n < 0 || n & FEC_AUTO)
8329 			n = FEC_AUTO;
8330 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8331 			return (EINVAL);/* some other bit is set too */
8332 
8333 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8334 		    "t4fec");
8335 		if (rc)
8336 			return (rc);
8337 		PORT_LOCK(pi);
8338 		old = lc->requested_fec;
8339 		if (n == FEC_AUTO)
8340 			lc->requested_fec = FEC_AUTO;
8341 		else if (n == 0 || n == FEC_NONE)
8342 			lc->requested_fec = FEC_NONE;
8343 		else {
8344 			if ((lc->pcaps |
8345 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8346 			    lc->pcaps) {
8347 				rc = ENOTSUP;
8348 				goto done;
8349 			}
8350 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8351 			    FEC_MODULE);
8352 		}
8353 		if (!hw_off_limits(sc)) {
8354 			fixup_link_config(pi);
8355 			if (pi->up_vis > 0) {
8356 				rc = apply_link_config(pi);
8357 				if (rc != 0) {
8358 					lc->requested_fec = old;
8359 					if (rc == FW_EPROTO)
8360 						rc = ENOTSUP;
8361 				}
8362 			}
8363 		}
8364 done:
8365 		PORT_UNLOCK(pi);
8366 		end_synchronized_op(sc, 0);
8367 	}
8368 
8369 	return (rc);
8370 }
8371 
8372 static int
8373 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8374 {
8375 	struct port_info *pi = arg1;
8376 	struct adapter *sc = pi->adapter;
8377 	struct link_config *lc = &pi->link_cfg;
8378 	int rc;
8379 	int8_t fec;
8380 	struct sbuf *sb;
8381 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8382 
8383 	rc = sysctl_wire_old_buffer(req, 0);
8384 	if (rc != 0)
8385 		return (rc);
8386 
8387 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8388 	if (sb == NULL)
8389 		return (ENOMEM);
8390 
8391 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8392 		rc = EBUSY;
8393 		goto done;
8394 	}
8395 	if (hw_off_limits(sc)) {
8396 		rc = ENXIO;
8397 		goto done;
8398 	}
8399 	PORT_LOCK(pi);
8400 	if (pi->up_vis == 0) {
8401 		/*
8402 		 * If all the interfaces are administratively down the firmware
8403 		 * does not report transceiver changes.  Refresh port info here.
8404 		 * This is the only reason we have a synchronized op in this
8405 		 * function.  Just PORT_LOCK would have been enough otherwise.
8406 		 */
8407 		t4_update_port_info(pi);
8408 	}
8409 
8410 	fec = lc->fec_hint;
8411 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8412 	    !fec_supported(lc->pcaps)) {
8413 		sbuf_printf(sb, "n/a");
8414 	} else {
8415 		if (fec == 0)
8416 			fec = FEC_NONE;
8417 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8418 	}
8419 	rc = sbuf_finish(sb);
8420 	PORT_UNLOCK(pi);
8421 done:
8422 	sbuf_delete(sb);
8423 	end_synchronized_op(sc, 0);
8424 
8425 	return (rc);
8426 }
8427 
8428 static int
8429 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8430 {
8431 	struct port_info *pi = arg1;
8432 	struct adapter *sc = pi->adapter;
8433 	struct link_config *lc = &pi->link_cfg;
8434 	int rc, val;
8435 
8436 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8437 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8438 	else
8439 		val = -1;
8440 	rc = sysctl_handle_int(oidp, &val, 0, req);
8441 	if (rc != 0 || req->newptr == NULL)
8442 		return (rc);
8443 	if (val == 0)
8444 		val = AUTONEG_DISABLE;
8445 	else if (val == 1)
8446 		val = AUTONEG_ENABLE;
8447 	else
8448 		val = AUTONEG_AUTO;
8449 
8450 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8451 	    "t4aneg");
8452 	if (rc)
8453 		return (rc);
8454 	PORT_LOCK(pi);
8455 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8456 		rc = ENOTSUP;
8457 		goto done;
8458 	}
8459 	lc->requested_aneg = val;
8460 	if (!hw_off_limits(sc)) {
8461 		fixup_link_config(pi);
8462 		if (pi->up_vis > 0)
8463 			rc = apply_link_config(pi);
8464 		set_current_media(pi);
8465 	}
8466 done:
8467 	PORT_UNLOCK(pi);
8468 	end_synchronized_op(sc, 0);
8469 	return (rc);
8470 }
8471 
8472 static int
8473 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8474 {
8475 	struct adapter *sc = arg1;
8476 	int rc, reg = arg2;
8477 	uint64_t val;
8478 
8479 	mtx_lock(&sc->reg_lock);
8480 	if (hw_off_limits(sc))
8481 		rc = ENXIO;
8482 	else {
8483 		rc = 0;
8484 		val = t4_read_reg64(sc, reg);
8485 	}
8486 	mtx_unlock(&sc->reg_lock);
8487 	if (rc == 0)
8488 		rc = sysctl_handle_64(oidp, &val, 0, req);
8489 	return (rc);
8490 }
8491 
8492 static int
8493 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8494 {
8495 	struct adapter *sc = arg1;
8496 	int rc, t;
8497 	uint32_t param, val;
8498 
8499 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8500 	if (rc)
8501 		return (rc);
8502 	if (hw_off_limits(sc))
8503 		rc = ENXIO;
8504 	else {
8505 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8506 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8507 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8508 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8509 	}
8510 	end_synchronized_op(sc, 0);
8511 	if (rc)
8512 		return (rc);
8513 
8514 	/* unknown is returned as 0 but we display -1 in that case */
8515 	t = val == 0 ? -1 : val;
8516 
8517 	rc = sysctl_handle_int(oidp, &t, 0, req);
8518 	return (rc);
8519 }
8520 
8521 static int
8522 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8523 {
8524 	struct adapter *sc = arg1;
8525 	int rc;
8526 	uint32_t param, val;
8527 
8528 	if (sc->params.core_vdd == 0) {
8529 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8530 		    "t4vdd");
8531 		if (rc)
8532 			return (rc);
8533 		if (hw_off_limits(sc))
8534 			rc = ENXIO;
8535 		else {
8536 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8537 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8538 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8539 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8540 			    &param, &val);
8541 		}
8542 		end_synchronized_op(sc, 0);
8543 		if (rc)
8544 			return (rc);
8545 		sc->params.core_vdd = val;
8546 	}
8547 
8548 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8549 }
8550 
8551 static int
8552 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8553 {
8554 	struct adapter *sc = arg1;
8555 	int rc, v;
8556 	uint32_t param, val;
8557 
8558 	v = sc->sensor_resets;
8559 	rc = sysctl_handle_int(oidp, &v, 0, req);
8560 	if (rc != 0 || req->newptr == NULL || v <= 0)
8561 		return (rc);
8562 
8563 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8564 	    chip_id(sc) < CHELSIO_T5)
8565 		return (ENOTSUP);
8566 
8567 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8568 	if (rc)
8569 		return (rc);
8570 	if (hw_off_limits(sc))
8571 		rc = ENXIO;
8572 	else {
8573 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8574 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8575 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8576 		val = 1;
8577 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8578 	}
8579 	end_synchronized_op(sc, 0);
8580 	if (rc == 0)
8581 		sc->sensor_resets++;
8582 	return (rc);
8583 }
8584 
8585 static int
8586 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8587 {
8588 	struct adapter *sc = arg1;
8589 	struct sbuf *sb;
8590 	int rc;
8591 	uint32_t param, val;
8592 
8593 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8594 	if (rc)
8595 		return (rc);
8596 	if (hw_off_limits(sc))
8597 		rc = ENXIO;
8598 	else {
8599 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8600 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8601 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8602 	}
8603 	end_synchronized_op(sc, 0);
8604 	if (rc)
8605 		return (rc);
8606 
8607 	rc = sysctl_wire_old_buffer(req, 0);
8608 	if (rc != 0)
8609 		return (rc);
8610 
8611 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8612 	if (sb == NULL)
8613 		return (ENOMEM);
8614 
8615 	if (val == 0xffffffff) {
8616 		/* Only debug and custom firmwares report load averages. */
8617 		sbuf_printf(sb, "not available");
8618 	} else {
8619 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8620 		    (val >> 16) & 0xff);
8621 	}
8622 	rc = sbuf_finish(sb);
8623 	sbuf_delete(sb);
8624 
8625 	return (rc);
8626 }
8627 
8628 static int
8629 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8630 {
8631 	struct adapter *sc = arg1;
8632 	struct sbuf *sb;
8633 	int rc, i;
8634 	uint16_t incr[NMTUS][NCCTRL_WIN];
8635 	static const char *dec_fac[] = {
8636 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8637 		"0.9375"
8638 	};
8639 
8640 	rc = sysctl_wire_old_buffer(req, 0);
8641 	if (rc != 0)
8642 		return (rc);
8643 
8644 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8645 	if (sb == NULL)
8646 		return (ENOMEM);
8647 
8648 	mtx_lock(&sc->reg_lock);
8649 	if (hw_off_limits(sc))
8650 		rc = ENXIO;
8651 	else
8652 		t4_read_cong_tbl(sc, incr);
8653 	mtx_unlock(&sc->reg_lock);
8654 	if (rc)
8655 		goto done;
8656 
8657 	for (i = 0; i < NCCTRL_WIN; ++i) {
8658 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8659 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8660 		    incr[5][i], incr[6][i], incr[7][i]);
8661 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8662 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8663 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8664 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8665 	}
8666 
8667 	rc = sbuf_finish(sb);
8668 done:
8669 	sbuf_delete(sb);
8670 	return (rc);
8671 }
8672 
8673 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8674 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8675 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8676 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8677 };
8678 
8679 static int
8680 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8681 {
8682 	struct adapter *sc = arg1;
8683 	struct sbuf *sb;
8684 	int rc, i, n, qid = arg2;
8685 	uint32_t *buf, *p;
8686 	char *qtype;
8687 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8688 
8689 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8690 	    ("%s: bad qid %d\n", __func__, qid));
8691 
8692 	if (qid < CIM_NUM_IBQ) {
8693 		/* inbound queue */
8694 		qtype = "IBQ";
8695 		n = 4 * CIM_IBQ_SIZE;
8696 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8697 		mtx_lock(&sc->reg_lock);
8698 		if (hw_off_limits(sc))
8699 			rc = -ENXIO;
8700 		else
8701 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8702 		mtx_unlock(&sc->reg_lock);
8703 	} else {
8704 		/* outbound queue */
8705 		qtype = "OBQ";
8706 		qid -= CIM_NUM_IBQ;
8707 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8708 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8709 		mtx_lock(&sc->reg_lock);
8710 		if (hw_off_limits(sc))
8711 			rc = -ENXIO;
8712 		else
8713 			rc = t4_read_cim_obq(sc, qid, buf, n);
8714 		mtx_unlock(&sc->reg_lock);
8715 	}
8716 
8717 	if (rc < 0) {
8718 		rc = -rc;
8719 		goto done;
8720 	}
8721 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
8722 
8723 	rc = sysctl_wire_old_buffer(req, 0);
8724 	if (rc != 0)
8725 		goto done;
8726 
8727 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8728 	if (sb == NULL) {
8729 		rc = ENOMEM;
8730 		goto done;
8731 	}
8732 
8733 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8734 	for (i = 0, p = buf; i < n; i += 16, p += 4)
8735 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
8736 		    p[2], p[3]);
8737 
8738 	rc = sbuf_finish(sb);
8739 	sbuf_delete(sb);
8740 done:
8741 	free(buf, M_CXGBE);
8742 	return (rc);
8743 }
8744 
8745 static void
8746 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8747 {
8748 	uint32_t *p;
8749 
8750 	sbuf_printf(sb, "Status   Data      PC%s",
8751 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8752 	    "     LS0Stat  LS0Addr             LS0Data");
8753 
8754 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
8755 		if (cfg & F_UPDBGLACAPTPCONLY) {
8756 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
8757 			    p[6], p[7]);
8758 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
8759 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
8760 			    p[4] & 0xff, p[5] >> 8);
8761 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
8762 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8763 			    p[1] & 0xf, p[2] >> 4);
8764 		} else {
8765 			sbuf_printf(sb,
8766 			    "\n  %02x   %x%07x %x%07x %08x %08x "
8767 			    "%08x%08x%08x%08x",
8768 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8769 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
8770 			    p[6], p[7]);
8771 		}
8772 	}
8773 }
8774 
8775 static void
8776 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8777 {
8778 	uint32_t *p;
8779 
8780 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
8781 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8782 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
8783 
8784 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
8785 		if (cfg & F_UPDBGLACAPTPCONLY) {
8786 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
8787 			    p[3] & 0xff, p[2], p[1], p[0]);
8788 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
8789 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
8790 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
8791 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
8792 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
8793 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
8794 			    p[6] >> 16);
8795 		} else {
8796 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
8797 			    "%08x %08x %08x %08x %08x %08x",
8798 			    (p[9] >> 16) & 0xff,
8799 			    p[9] & 0xffff, p[8] >> 16,
8800 			    p[8] & 0xffff, p[7] >> 16,
8801 			    p[7] & 0xffff, p[6] >> 16,
8802 			    p[2], p[1], p[0], p[5], p[4], p[3]);
8803 		}
8804 	}
8805 }
8806 
8807 static int
8808 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
8809 {
8810 	uint32_t cfg, *buf;
8811 	int rc;
8812 
8813 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
8814 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
8815 	    M_ZERO | flags);
8816 	if (buf == NULL)
8817 		return (ENOMEM);
8818 
8819 	mtx_lock(&sc->reg_lock);
8820 	if (hw_off_limits(sc))
8821 		rc = ENXIO;
8822 	else {
8823 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
8824 		if (rc == 0)
8825 			rc = -t4_cim_read_la(sc, buf, NULL);
8826 	}
8827 	mtx_unlock(&sc->reg_lock);
8828 	if (rc == 0) {
8829 		if (chip_id(sc) < CHELSIO_T6)
8830 			sbuf_cim_la4(sc, sb, buf, cfg);
8831 		else
8832 			sbuf_cim_la6(sc, sb, buf, cfg);
8833 	}
8834 	free(buf, M_CXGBE);
8835 	return (rc);
8836 }
8837 
8838 static int
8839 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
8840 {
8841 	struct adapter *sc = arg1;
8842 	struct sbuf *sb;
8843 	int rc;
8844 
8845 	rc = sysctl_wire_old_buffer(req, 0);
8846 	if (rc != 0)
8847 		return (rc);
8848 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8849 	if (sb == NULL)
8850 		return (ENOMEM);
8851 
8852 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
8853 	if (rc == 0)
8854 		rc = sbuf_finish(sb);
8855 	sbuf_delete(sb);
8856 	return (rc);
8857 }
8858 
8859 bool
8860 t4_os_dump_cimla(struct adapter *sc, int arg, bool verbose)
8861 {
8862 	struct sbuf sb;
8863 	int rc;
8864 
8865 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
8866 		return (false);
8867 	rc = sbuf_cim_la(sc, &sb, M_NOWAIT);
8868 	if (rc == 0) {
8869 		rc = sbuf_finish(&sb);
8870 		if (rc == 0) {
8871 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s",
8872 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
8873 		}
8874 	}
8875 	sbuf_delete(&sb);
8876 	return (false);
8877 }
8878 
8879 static int
8880 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
8881 {
8882 	struct adapter *sc = arg1;
8883 	u_int i;
8884 	struct sbuf *sb;
8885 	uint32_t *buf, *p;
8886 	int rc;
8887 
8888 	rc = sysctl_wire_old_buffer(req, 0);
8889 	if (rc != 0)
8890 		return (rc);
8891 
8892 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8893 	if (sb == NULL)
8894 		return (ENOMEM);
8895 
8896 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
8897 	    M_ZERO | M_WAITOK);
8898 
8899 	mtx_lock(&sc->reg_lock);
8900 	if (hw_off_limits(sc))
8901 		rc = ENXIO;
8902 	else
8903 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
8904 	mtx_unlock(&sc->reg_lock);
8905 	if (rc)
8906 		goto done;
8907 
8908 	p = buf;
8909 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
8910 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
8911 		    p[1], p[0]);
8912 	}
8913 
8914 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
8915 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
8916 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
8917 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
8918 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
8919 		    (p[1] >> 2) | ((p[2] & 3) << 30),
8920 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
8921 		    p[0] & 1);
8922 	}
8923 	rc = sbuf_finish(sb);
8924 done:
8925 	sbuf_delete(sb);
8926 	free(buf, M_CXGBE);
8927 	return (rc);
8928 }
8929 
8930 static int
8931 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
8932 {
8933 	struct adapter *sc = arg1;
8934 	u_int i;
8935 	struct sbuf *sb;
8936 	uint32_t *buf, *p;
8937 	int rc;
8938 
8939 	rc = sysctl_wire_old_buffer(req, 0);
8940 	if (rc != 0)
8941 		return (rc);
8942 
8943 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8944 	if (sb == NULL)
8945 		return (ENOMEM);
8946 
8947 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
8948 	    M_ZERO | M_WAITOK);
8949 
8950 	mtx_lock(&sc->reg_lock);
8951 	if (hw_off_limits(sc))
8952 		rc = ENXIO;
8953 	else
8954 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
8955 	mtx_unlock(&sc->reg_lock);
8956 	if (rc)
8957 		goto done;
8958 
8959 	p = buf;
8960 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
8961 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
8962 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
8963 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
8964 		    p[4], p[3], p[2], p[1], p[0]);
8965 	}
8966 
8967 	sbuf_printf(sb, "\n\nCntl ID               Data");
8968 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
8969 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
8970 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
8971 	}
8972 
8973 	rc = sbuf_finish(sb);
8974 done:
8975 	sbuf_delete(sb);
8976 	free(buf, M_CXGBE);
8977 	return (rc);
8978 }
8979 
8980 static int
8981 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
8982 {
8983 	struct adapter *sc = arg1;
8984 	struct sbuf *sb;
8985 	int rc, i;
8986 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
8987 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
8988 	uint16_t thres[CIM_NUM_IBQ];
8989 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
8990 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
8991 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
8992 
8993 	cim_num_obq = sc->chip_params->cim_num_obq;
8994 	if (is_t4(sc)) {
8995 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
8996 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
8997 	} else {
8998 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
8999 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9000 	}
9001 	nq = CIM_NUM_IBQ + cim_num_obq;
9002 
9003 	mtx_lock(&sc->reg_lock);
9004 	if (hw_off_limits(sc))
9005 		rc = ENXIO;
9006 	else {
9007 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9008 		if (rc == 0) {
9009 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9010 			    obq_wr);
9011 			if (rc == 0)
9012 				t4_read_cimq_cfg(sc, base, size, thres);
9013 		}
9014 	}
9015 	mtx_unlock(&sc->reg_lock);
9016 	if (rc)
9017 		return (rc);
9018 
9019 	rc = sysctl_wire_old_buffer(req, 0);
9020 	if (rc != 0)
9021 		return (rc);
9022 
9023 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9024 	if (sb == NULL)
9025 		return (ENOMEM);
9026 
9027 	sbuf_printf(sb,
9028 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9029 
9030 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9031 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9032 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9033 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9034 		    G_QUEREMFLITS(p[2]) * 16);
9035 	for ( ; i < nq; i++, p += 4, wr += 2)
9036 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9037 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9038 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9039 		    G_QUEREMFLITS(p[2]) * 16);
9040 
9041 	rc = sbuf_finish(sb);
9042 	sbuf_delete(sb);
9043 
9044 	return (rc);
9045 }
9046 
9047 static int
9048 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9049 {
9050 	struct adapter *sc = arg1;
9051 	struct sbuf *sb;
9052 	int rc;
9053 	struct tp_cpl_stats stats;
9054 
9055 	rc = sysctl_wire_old_buffer(req, 0);
9056 	if (rc != 0)
9057 		return (rc);
9058 
9059 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9060 	if (sb == NULL)
9061 		return (ENOMEM);
9062 
9063 	mtx_lock(&sc->reg_lock);
9064 	if (hw_off_limits(sc))
9065 		rc = ENXIO;
9066 	else
9067 		t4_tp_get_cpl_stats(sc, &stats, 0);
9068 	mtx_unlock(&sc->reg_lock);
9069 	if (rc)
9070 		goto done;
9071 
9072 	if (sc->chip_params->nchan > 2) {
9073 		sbuf_printf(sb, "                 channel 0  channel 1"
9074 		    "  channel 2  channel 3");
9075 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9076 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9077 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9078 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9079 	} else {
9080 		sbuf_printf(sb, "                 channel 0  channel 1");
9081 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9082 		    stats.req[0], stats.req[1]);
9083 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9084 		    stats.rsp[0], stats.rsp[1]);
9085 	}
9086 
9087 	rc = sbuf_finish(sb);
9088 done:
9089 	sbuf_delete(sb);
9090 	return (rc);
9091 }
9092 
9093 static int
9094 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9095 {
9096 	struct adapter *sc = arg1;
9097 	struct sbuf *sb;
9098 	int rc;
9099 	struct tp_usm_stats stats;
9100 
9101 	rc = sysctl_wire_old_buffer(req, 0);
9102 	if (rc != 0)
9103 		return(rc);
9104 
9105 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9106 	if (sb == NULL)
9107 		return (ENOMEM);
9108 
9109 	mtx_lock(&sc->reg_lock);
9110 	if (hw_off_limits(sc))
9111 		rc = ENXIO;
9112 	else
9113 		t4_get_usm_stats(sc, &stats, 1);
9114 	mtx_unlock(&sc->reg_lock);
9115 	if (rc == 0) {
9116 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9117 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9118 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9119 		rc = sbuf_finish(sb);
9120 	}
9121 	sbuf_delete(sb);
9122 
9123 	return (rc);
9124 }
9125 
9126 static int
9127 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9128 {
9129 	struct adapter *sc = arg1;
9130 	struct sbuf *sb;
9131 	int rc;
9132 	struct tp_tid_stats stats;
9133 
9134 	rc = sysctl_wire_old_buffer(req, 0);
9135 	if (rc != 0)
9136 		return(rc);
9137 
9138 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9139 	if (sb == NULL)
9140 		return (ENOMEM);
9141 
9142 	mtx_lock(&sc->reg_lock);
9143 	if (hw_off_limits(sc))
9144 		rc = ENXIO;
9145 	else
9146 		t4_tp_get_tid_stats(sc, &stats, 1);
9147 	mtx_unlock(&sc->reg_lock);
9148 	if (rc == 0) {
9149 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9150 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9151 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9152 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9153 		rc = sbuf_finish(sb);
9154 	}
9155 	sbuf_delete(sb);
9156 
9157 	return (rc);
9158 }
9159 
9160 static const char * const devlog_level_strings[] = {
9161 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9162 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9163 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9164 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9165 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9166 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9167 };
9168 
9169 static const char * const devlog_facility_strings[] = {
9170 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9171 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9172 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9173 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9174 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9175 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9176 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9177 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9178 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9179 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9180 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9181 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9182 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9183 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9184 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9185 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9186 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9187 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9188 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9189 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9190 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9191 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9192 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9193 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9194 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9195 };
9196 
9197 static int
9198 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9199 {
9200 	int i, j, rc, nentries, first = 0;
9201 	struct devlog_params *dparams = &sc->params.devlog;
9202 	struct fw_devlog_e *buf, *e;
9203 	uint64_t ftstamp = UINT64_MAX;
9204 
9205 	if (dparams->addr == 0)
9206 		return (ENXIO);
9207 
9208 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9209 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9210 	if (buf == NULL)
9211 		return (ENOMEM);
9212 
9213 	mtx_lock(&sc->reg_lock);
9214 	if (hw_off_limits(sc))
9215 		rc = ENXIO;
9216 	else
9217 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9218 		    dparams->size);
9219 	mtx_unlock(&sc->reg_lock);
9220 	if (rc != 0)
9221 		goto done;
9222 
9223 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9224 	for (i = 0; i < nentries; i++) {
9225 		e = &buf[i];
9226 
9227 		if (e->timestamp == 0)
9228 			break;	/* end */
9229 
9230 		e->timestamp = be64toh(e->timestamp);
9231 		e->seqno = be32toh(e->seqno);
9232 		for (j = 0; j < 8; j++)
9233 			e->params[j] = be32toh(e->params[j]);
9234 
9235 		if (e->timestamp < ftstamp) {
9236 			ftstamp = e->timestamp;
9237 			first = i;
9238 		}
9239 	}
9240 
9241 	if (buf[first].timestamp == 0)
9242 		goto done;	/* nothing in the log */
9243 
9244 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9245 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9246 
9247 	i = first;
9248 	do {
9249 		e = &buf[i];
9250 		if (e->timestamp == 0)
9251 			break;	/* end */
9252 
9253 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9254 		    e->seqno, e->timestamp,
9255 		    (e->level < nitems(devlog_level_strings) ?
9256 			devlog_level_strings[e->level] : "UNKNOWN"),
9257 		    (e->facility < nitems(devlog_facility_strings) ?
9258 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9259 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9260 		    e->params[2], e->params[3], e->params[4],
9261 		    e->params[5], e->params[6], e->params[7]);
9262 
9263 		if (++i == nentries)
9264 			i = 0;
9265 	} while (i != first);
9266 done:
9267 	free(buf, M_CXGBE);
9268 	return (rc);
9269 }
9270 
9271 static int
9272 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9273 {
9274 	struct adapter *sc = arg1;
9275 	int rc;
9276 	struct sbuf *sb;
9277 
9278 	rc = sysctl_wire_old_buffer(req, 0);
9279 	if (rc != 0)
9280 		return (rc);
9281 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9282 	if (sb == NULL)
9283 		return (ENOMEM);
9284 
9285 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9286 	if (rc == 0)
9287 		rc = sbuf_finish(sb);
9288 	sbuf_delete(sb);
9289 	return (rc);
9290 }
9291 
9292 void
9293 t4_os_dump_devlog(struct adapter *sc)
9294 {
9295 	int rc;
9296 	struct sbuf sb;
9297 
9298 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
9299 		return;
9300 	rc = sbuf_devlog(sc, &sb, M_NOWAIT);
9301 	if (rc == 0) {
9302 		rc = sbuf_finish(&sb);
9303 		if (rc == 0) {
9304 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9305 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
9306 		}
9307 	}
9308 	sbuf_delete(&sb);
9309 }
9310 
9311 static int
9312 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9313 {
9314 	struct adapter *sc = arg1;
9315 	struct sbuf *sb;
9316 	int rc;
9317 	struct tp_fcoe_stats stats[MAX_NCHAN];
9318 	int i, nchan = sc->chip_params->nchan;
9319 
9320 	rc = sysctl_wire_old_buffer(req, 0);
9321 	if (rc != 0)
9322 		return (rc);
9323 
9324 	mtx_lock(&sc->reg_lock);
9325 	if (hw_off_limits(sc))
9326 		rc = ENXIO;
9327 	else {
9328 		for (i = 0; i < nchan; i++)
9329 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9330 	}
9331 	mtx_unlock(&sc->reg_lock);
9332 	if (rc != 0)
9333 		return (rc);
9334 
9335 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9336 	if (sb == NULL)
9337 		return (ENOMEM);
9338 
9339 	if (nchan > 2) {
9340 		sbuf_printf(sb, "                   channel 0        channel 1"
9341 		    "        channel 2        channel 3");
9342 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9343 		    stats[0].octets_ddp, stats[1].octets_ddp,
9344 		    stats[2].octets_ddp, stats[3].octets_ddp);
9345 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9346 		    stats[0].frames_ddp, stats[1].frames_ddp,
9347 		    stats[2].frames_ddp, stats[3].frames_ddp);
9348 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9349 		    stats[0].frames_drop, stats[1].frames_drop,
9350 		    stats[2].frames_drop, stats[3].frames_drop);
9351 	} else {
9352 		sbuf_printf(sb, "                   channel 0        channel 1");
9353 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9354 		    stats[0].octets_ddp, stats[1].octets_ddp);
9355 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9356 		    stats[0].frames_ddp, stats[1].frames_ddp);
9357 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9358 		    stats[0].frames_drop, stats[1].frames_drop);
9359 	}
9360 
9361 	rc = sbuf_finish(sb);
9362 	sbuf_delete(sb);
9363 
9364 	return (rc);
9365 }
9366 
9367 static int
9368 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9369 {
9370 	struct adapter *sc = arg1;
9371 	struct sbuf *sb;
9372 	int rc, i;
9373 	unsigned int map, kbps, ipg, mode;
9374 	unsigned int pace_tab[NTX_SCHED];
9375 
9376 	rc = sysctl_wire_old_buffer(req, 0);
9377 	if (rc != 0)
9378 		return (rc);
9379 
9380 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9381 	if (sb == NULL)
9382 		return (ENOMEM);
9383 
9384 	mtx_lock(&sc->reg_lock);
9385 	if (hw_off_limits(sc)) {
9386 		rc = ENXIO;
9387 		goto done;
9388 	}
9389 
9390 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9391 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9392 	t4_read_pace_tbl(sc, pace_tab);
9393 
9394 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9395 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9396 
9397 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9398 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9399 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9400 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9401 		if (kbps)
9402 			sbuf_printf(sb, "%9u     ", kbps);
9403 		else
9404 			sbuf_printf(sb, " disabled     ");
9405 
9406 		if (ipg)
9407 			sbuf_printf(sb, "%13u        ", ipg);
9408 		else
9409 			sbuf_printf(sb, "     disabled        ");
9410 
9411 		if (pace_tab[i])
9412 			sbuf_printf(sb, "%10u", pace_tab[i]);
9413 		else
9414 			sbuf_printf(sb, "  disabled");
9415 	}
9416 	rc = sbuf_finish(sb);
9417 done:
9418 	mtx_unlock(&sc->reg_lock);
9419 	sbuf_delete(sb);
9420 	return (rc);
9421 }
9422 
9423 static int
9424 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9425 {
9426 	struct adapter *sc = arg1;
9427 	struct sbuf *sb;
9428 	int rc, i, j;
9429 	uint64_t *p0, *p1;
9430 	struct lb_port_stats s[2];
9431 	static const char *stat_name[] = {
9432 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9433 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9434 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9435 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9436 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9437 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9438 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9439 	};
9440 
9441 	rc = sysctl_wire_old_buffer(req, 0);
9442 	if (rc != 0)
9443 		return (rc);
9444 
9445 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9446 	if (sb == NULL)
9447 		return (ENOMEM);
9448 
9449 	memset(s, 0, sizeof(s));
9450 
9451 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9452 		mtx_lock(&sc->reg_lock);
9453 		if (hw_off_limits(sc))
9454 			rc = ENXIO;
9455 		else {
9456 			t4_get_lb_stats(sc, i, &s[0]);
9457 			t4_get_lb_stats(sc, i + 1, &s[1]);
9458 		}
9459 		mtx_unlock(&sc->reg_lock);
9460 		if (rc != 0)
9461 			break;
9462 
9463 		p0 = &s[0].octets;
9464 		p1 = &s[1].octets;
9465 		sbuf_printf(sb, "%s                       Loopback %u"
9466 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9467 
9468 		for (j = 0; j < nitems(stat_name); j++)
9469 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9470 				   *p0++, *p1++);
9471 	}
9472 
9473 	rc = sbuf_finish(sb);
9474 	sbuf_delete(sb);
9475 
9476 	return (rc);
9477 }
9478 
9479 static int
9480 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9481 {
9482 	int rc = 0;
9483 	struct port_info *pi = arg1;
9484 	struct link_config *lc = &pi->link_cfg;
9485 	struct sbuf *sb;
9486 
9487 	rc = sysctl_wire_old_buffer(req, 0);
9488 	if (rc != 0)
9489 		return(rc);
9490 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9491 	if (sb == NULL)
9492 		return (ENOMEM);
9493 
9494 	if (lc->link_ok || lc->link_down_rc == 255)
9495 		sbuf_printf(sb, "n/a");
9496 	else
9497 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9498 
9499 	rc = sbuf_finish(sb);
9500 	sbuf_delete(sb);
9501 
9502 	return (rc);
9503 }
9504 
9505 struct mem_desc {
9506 	unsigned int base;
9507 	unsigned int limit;
9508 	unsigned int idx;
9509 };
9510 
9511 static int
9512 mem_desc_cmp(const void *a, const void *b)
9513 {
9514 	return ((const struct mem_desc *)a)->base -
9515 	       ((const struct mem_desc *)b)->base;
9516 }
9517 
9518 static void
9519 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9520     unsigned int to)
9521 {
9522 	unsigned int size;
9523 
9524 	if (from == to)
9525 		return;
9526 
9527 	size = to - from + 1;
9528 	if (size == 0)
9529 		return;
9530 
9531 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9532 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9533 }
9534 
9535 static int
9536 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9537 {
9538 	struct adapter *sc = arg1;
9539 	struct sbuf *sb;
9540 	int rc, i, n;
9541 	uint32_t lo, hi, used, alloc;
9542 	static const char *memory[] = {
9543 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9544 	};
9545 	static const char *region[] = {
9546 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9547 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9548 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9549 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9550 		"RQUDP region:", "PBL region:", "TXPBL region:",
9551 		"DBVFIFO region:", "ULPRX state:", "ULPTX state:",
9552 		"On-chip queues:", "TLS keys:",
9553 	};
9554 	struct mem_desc avail[4];
9555 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9556 	struct mem_desc *md = mem;
9557 
9558 	rc = sysctl_wire_old_buffer(req, 0);
9559 	if (rc != 0)
9560 		return (rc);
9561 
9562 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9563 	if (sb == NULL)
9564 		return (ENOMEM);
9565 
9566 	for (i = 0; i < nitems(mem); i++) {
9567 		mem[i].limit = 0;
9568 		mem[i].idx = i;
9569 	}
9570 
9571 	mtx_lock(&sc->reg_lock);
9572 	if (hw_off_limits(sc)) {
9573 		rc = ENXIO;
9574 		goto done;
9575 	}
9576 
9577 	/* Find and sort the populated memory ranges */
9578 	i = 0;
9579 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9580 	if (lo & F_EDRAM0_ENABLE) {
9581 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9582 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9583 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9584 		avail[i].idx = 0;
9585 		i++;
9586 	}
9587 	if (lo & F_EDRAM1_ENABLE) {
9588 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9589 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9590 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9591 		avail[i].idx = 1;
9592 		i++;
9593 	}
9594 	if (lo & F_EXT_MEM_ENABLE) {
9595 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9596 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9597 		avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9598 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9599 		i++;
9600 	}
9601 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9602 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9603 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9604 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9605 		avail[i].idx = 4;
9606 		i++;
9607 	}
9608 	if (is_t6(sc) && lo & F_HMA_MUX) {
9609 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9610 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9611 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9612 		avail[i].idx = 5;
9613 		i++;
9614 	}
9615 	MPASS(i <= nitems(avail));
9616 	if (!i)                                    /* no memory available */
9617 		goto done;
9618 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9619 
9620 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9621 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9622 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9623 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9624 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9625 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9626 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9627 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9628 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9629 
9630 	/* the next few have explicit upper bounds */
9631 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9632 	md->limit = md->base - 1 +
9633 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9634 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9635 	md++;
9636 
9637 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9638 	md->limit = md->base - 1 +
9639 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9640 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9641 	md++;
9642 
9643 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9644 		if (chip_id(sc) <= CHELSIO_T5)
9645 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9646 		else
9647 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9648 		md->limit = 0;
9649 	} else {
9650 		md->base = 0;
9651 		md->idx = nitems(region);  /* hide it */
9652 	}
9653 	md++;
9654 
9655 #define ulp_region(reg) \
9656 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9657 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9658 
9659 	ulp_region(RX_ISCSI);
9660 	ulp_region(RX_TDDP);
9661 	ulp_region(TX_TPT);
9662 	ulp_region(RX_STAG);
9663 	ulp_region(RX_RQ);
9664 	ulp_region(RX_RQUDP);
9665 	ulp_region(RX_PBL);
9666 	ulp_region(TX_PBL);
9667 #undef ulp_region
9668 
9669 	md->base = 0;
9670 	if (is_t4(sc))
9671 		md->idx = nitems(region);
9672 	else {
9673 		uint32_t size = 0;
9674 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9675 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9676 
9677 		if (is_t5(sc)) {
9678 			if (sge_ctrl & F_VFIFO_ENABLE)
9679 				size = fifo_size << 2;
9680 		} else
9681 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9682 
9683 		if (size) {
9684 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
9685 			md->limit = md->base + size - 1;
9686 		} else
9687 			md->idx = nitems(region);
9688 	}
9689 	md++;
9690 
9691 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9692 	md->limit = 0;
9693 	md++;
9694 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9695 	md->limit = 0;
9696 	md++;
9697 
9698 	md->base = sc->vres.ocq.start;
9699 	if (sc->vres.ocq.size)
9700 		md->limit = md->base + sc->vres.ocq.size - 1;
9701 	else
9702 		md->idx = nitems(region);  /* hide it */
9703 	md++;
9704 
9705 	md->base = sc->vres.key.start;
9706 	if (sc->vres.key.size)
9707 		md->limit = md->base + sc->vres.key.size - 1;
9708 	else
9709 		md->idx = nitems(region);  /* hide it */
9710 	md++;
9711 
9712 	/* add any address-space holes, there can be up to 3 */
9713 	for (n = 0; n < i - 1; n++)
9714 		if (avail[n].limit < avail[n + 1].base)
9715 			(md++)->base = avail[n].limit;
9716 	if (avail[n].limit)
9717 		(md++)->base = avail[n].limit;
9718 
9719 	n = md - mem;
9720 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
9721 
9722 	for (lo = 0; lo < i; lo++)
9723 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
9724 				avail[lo].limit - 1);
9725 
9726 	sbuf_printf(sb, "\n");
9727 	for (i = 0; i < n; i++) {
9728 		if (mem[i].idx >= nitems(region))
9729 			continue;                        /* skip holes */
9730 		if (!mem[i].limit)
9731 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
9732 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
9733 				mem[i].limit);
9734 	}
9735 
9736 	sbuf_printf(sb, "\n");
9737 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
9738 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
9739 	mem_region_show(sb, "uP RAM:", lo, hi);
9740 
9741 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
9742 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
9743 	mem_region_show(sb, "uP Extmem2:", lo, hi);
9744 
9745 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
9746 	sbuf_printf(sb, "\n%u Rx pages of size %uKiB for %u channels\n",
9747 		   G_PMRXMAXPAGE(lo),
9748 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
9749 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
9750 
9751 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
9752 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
9753 	sbuf_printf(sb, "%u Tx pages of size %u%ciB for %u channels\n",
9754 		   G_PMTXMAXPAGE(lo),
9755 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
9756 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
9757 	sbuf_printf(sb, "%u p-structs\n",
9758 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT));
9759 
9760 	for (i = 0; i < 4; i++) {
9761 		if (chip_id(sc) > CHELSIO_T5)
9762 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
9763 		else
9764 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
9765 		if (is_t5(sc)) {
9766 			used = G_T5_USED(lo);
9767 			alloc = G_T5_ALLOC(lo);
9768 		} else {
9769 			used = G_USED(lo);
9770 			alloc = G_ALLOC(lo);
9771 		}
9772 		/* For T6 these are MAC buffer groups */
9773 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
9774 		    i, used, alloc);
9775 	}
9776 	for (i = 0; i < sc->chip_params->nchan; i++) {
9777 		if (chip_id(sc) > CHELSIO_T5)
9778 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
9779 		else
9780 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
9781 		if (is_t5(sc)) {
9782 			used = G_T5_USED(lo);
9783 			alloc = G_T5_ALLOC(lo);
9784 		} else {
9785 			used = G_USED(lo);
9786 			alloc = G_ALLOC(lo);
9787 		}
9788 		/* For T6 these are MAC buffer groups */
9789 		sbuf_printf(sb,
9790 		    "\nLoopback %d using %u pages out of %u allocated",
9791 		    i, used, alloc);
9792 	}
9793 done:
9794 	mtx_unlock(&sc->reg_lock);
9795 	if (rc == 0)
9796 		rc = sbuf_finish(sb);
9797 	sbuf_delete(sb);
9798 	return (rc);
9799 }
9800 
9801 static inline void
9802 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
9803 {
9804 	*mask = x | y;
9805 	y = htobe64(y);
9806 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
9807 }
9808 
9809 static int
9810 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
9811 {
9812 	struct adapter *sc = arg1;
9813 	struct sbuf *sb;
9814 	int rc, i;
9815 
9816 	MPASS(chip_id(sc) <= CHELSIO_T5);
9817 
9818 	rc = sysctl_wire_old_buffer(req, 0);
9819 	if (rc != 0)
9820 		return (rc);
9821 
9822 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9823 	if (sb == NULL)
9824 		return (ENOMEM);
9825 
9826 	sbuf_printf(sb,
9827 	    "Idx  Ethernet address     Mask     Vld Ports PF"
9828 	    "  VF              Replication             P0 P1 P2 P3  ML");
9829 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
9830 		uint64_t tcamx, tcamy, mask;
9831 		uint32_t cls_lo, cls_hi;
9832 		uint8_t addr[ETHER_ADDR_LEN];
9833 
9834 		mtx_lock(&sc->reg_lock);
9835 		if (hw_off_limits(sc))
9836 			rc = ENXIO;
9837 		else {
9838 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
9839 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
9840 		}
9841 		mtx_unlock(&sc->reg_lock);
9842 		if (rc != 0)
9843 			break;
9844 		if (tcamx & tcamy)
9845 			continue;
9846 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
9847 		mtx_lock(&sc->reg_lock);
9848 		if (hw_off_limits(sc))
9849 			rc = ENXIO;
9850 		else {
9851 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
9852 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
9853 		}
9854 		mtx_unlock(&sc->reg_lock);
9855 		if (rc != 0)
9856 			break;
9857 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
9858 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
9859 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
9860 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
9861 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
9862 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
9863 
9864 		if (cls_lo & F_REPLICATE) {
9865 			struct fw_ldst_cmd ldst_cmd;
9866 
9867 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
9868 			ldst_cmd.op_to_addrspace =
9869 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
9870 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
9871 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
9872 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
9873 			ldst_cmd.u.mps.rplc.fid_idx =
9874 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
9875 				V_FW_LDST_CMD_IDX(i));
9876 
9877 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
9878 			    "t4mps");
9879 			if (rc)
9880 				break;
9881 			if (hw_off_limits(sc))
9882 				rc = ENXIO;
9883 			else
9884 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
9885 				    sizeof(ldst_cmd), &ldst_cmd);
9886 			end_synchronized_op(sc, 0);
9887 			if (rc != 0)
9888 				break;
9889 			else {
9890 				sbuf_printf(sb, " %08x %08x %08x %08x",
9891 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
9892 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
9893 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
9894 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
9895 			}
9896 		} else
9897 			sbuf_printf(sb, "%36s", "");
9898 
9899 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
9900 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
9901 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
9902 	}
9903 
9904 	if (rc)
9905 		(void) sbuf_finish(sb);
9906 	else
9907 		rc = sbuf_finish(sb);
9908 	sbuf_delete(sb);
9909 
9910 	return (rc);
9911 }
9912 
9913 static int
9914 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
9915 {
9916 	struct adapter *sc = arg1;
9917 	struct sbuf *sb;
9918 	int rc, i;
9919 
9920 	MPASS(chip_id(sc) > CHELSIO_T5);
9921 
9922 	rc = sysctl_wire_old_buffer(req, 0);
9923 	if (rc != 0)
9924 		return (rc);
9925 
9926 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9927 	if (sb == NULL)
9928 		return (ENOMEM);
9929 
9930 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
9931 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
9932 	    "                           Replication"
9933 	    "                                    P0 P1 P2 P3  ML\n");
9934 
9935 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
9936 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
9937 		uint16_t ivlan;
9938 		uint64_t tcamx, tcamy, val, mask;
9939 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
9940 		uint8_t addr[ETHER_ADDR_LEN];
9941 
9942 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
9943 		if (i < 256)
9944 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
9945 		else
9946 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
9947 		mtx_lock(&sc->reg_lock);
9948 		if (hw_off_limits(sc))
9949 			rc = ENXIO;
9950 		else {
9951 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
9952 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
9953 			tcamy = G_DMACH(val) << 32;
9954 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
9955 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
9956 		}
9957 		mtx_unlock(&sc->reg_lock);
9958 		if (rc != 0)
9959 			break;
9960 
9961 		lookup_type = G_DATALKPTYPE(data2);
9962 		port_num = G_DATAPORTNUM(data2);
9963 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
9964 			/* Inner header VNI */
9965 			vniy = ((data2 & F_DATAVIDH2) << 23) |
9966 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
9967 			dip_hit = data2 & F_DATADIPHIT;
9968 			vlan_vld = 0;
9969 		} else {
9970 			vniy = 0;
9971 			dip_hit = 0;
9972 			vlan_vld = data2 & F_DATAVIDH2;
9973 			ivlan = G_VIDL(val);
9974 		}
9975 
9976 		ctl |= V_CTLXYBITSEL(1);
9977 		mtx_lock(&sc->reg_lock);
9978 		if (hw_off_limits(sc))
9979 			rc = ENXIO;
9980 		else {
9981 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
9982 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
9983 			tcamx = G_DMACH(val) << 32;
9984 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
9985 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
9986 		}
9987 		mtx_unlock(&sc->reg_lock);
9988 		if (rc != 0)
9989 			break;
9990 
9991 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
9992 			/* Inner header VNI mask */
9993 			vnix = ((data2 & F_DATAVIDH2) << 23) |
9994 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
9995 		} else
9996 			vnix = 0;
9997 
9998 		if (tcamx & tcamy)
9999 			continue;
10000 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10001 
10002 		mtx_lock(&sc->reg_lock);
10003 		if (hw_off_limits(sc))
10004 			rc = ENXIO;
10005 		else {
10006 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10007 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10008 		}
10009 		mtx_unlock(&sc->reg_lock);
10010 		if (rc != 0)
10011 			break;
10012 
10013 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10014 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10015 			    "%012jx %06x %06x    -    -   %3c"
10016 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10017 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10018 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10019 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10020 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10021 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10022 		} else {
10023 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10024 			    "%012jx    -       -   ", i, addr[0], addr[1],
10025 			    addr[2], addr[3], addr[4], addr[5],
10026 			    (uintmax_t)mask);
10027 
10028 			if (vlan_vld)
10029 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10030 			else
10031 				sbuf_printf(sb, "  -    N     ");
10032 
10033 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10034 			    lookup_type ? 'I' : 'O', port_num,
10035 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10036 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10037 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10038 		}
10039 
10040 
10041 		if (cls_lo & F_T6_REPLICATE) {
10042 			struct fw_ldst_cmd ldst_cmd;
10043 
10044 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10045 			ldst_cmd.op_to_addrspace =
10046 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10047 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10048 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10049 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10050 			ldst_cmd.u.mps.rplc.fid_idx =
10051 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10052 				V_FW_LDST_CMD_IDX(i));
10053 
10054 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10055 			    "t6mps");
10056 			if (rc)
10057 				break;
10058 			if (hw_off_limits(sc))
10059 				rc = ENXIO;
10060 			else
10061 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10062 				    sizeof(ldst_cmd), &ldst_cmd);
10063 			end_synchronized_op(sc, 0);
10064 			if (rc != 0)
10065 				break;
10066 			else {
10067 				sbuf_printf(sb, " %08x %08x %08x %08x"
10068 				    " %08x %08x %08x %08x",
10069 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10070 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10071 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10072 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10073 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10074 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10075 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10076 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10077 			}
10078 		} else
10079 			sbuf_printf(sb, "%72s", "");
10080 
10081 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10082 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10083 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10084 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10085 	}
10086 
10087 	if (rc)
10088 		(void) sbuf_finish(sb);
10089 	else
10090 		rc = sbuf_finish(sb);
10091 	sbuf_delete(sb);
10092 
10093 	return (rc);
10094 }
10095 
10096 static int
10097 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10098 {
10099 	struct adapter *sc = arg1;
10100 	struct sbuf *sb;
10101 	int rc;
10102 	uint16_t mtus[NMTUS];
10103 
10104 	rc = sysctl_wire_old_buffer(req, 0);
10105 	if (rc != 0)
10106 		return (rc);
10107 
10108 	mtx_lock(&sc->reg_lock);
10109 	if (hw_off_limits(sc))
10110 		rc = ENXIO;
10111 	else
10112 		t4_read_mtu_tbl(sc, mtus, NULL);
10113 	mtx_unlock(&sc->reg_lock);
10114 	if (rc != 0)
10115 		return (rc);
10116 
10117 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10118 	if (sb == NULL)
10119 		return (ENOMEM);
10120 
10121 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10122 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10123 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10124 	    mtus[14], mtus[15]);
10125 
10126 	rc = sbuf_finish(sb);
10127 	sbuf_delete(sb);
10128 
10129 	return (rc);
10130 }
10131 
10132 static int
10133 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10134 {
10135 	struct adapter *sc = arg1;
10136 	struct sbuf *sb;
10137 	int rc, i;
10138 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10139 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10140 	static const char *tx_stats[MAX_PM_NSTATS] = {
10141 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10142 		"Tx FIFO wait", NULL, "Tx latency"
10143 	};
10144 	static const char *rx_stats[MAX_PM_NSTATS] = {
10145 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10146 		"Rx FIFO wait", NULL, "Rx latency"
10147 	};
10148 
10149 	rc = sysctl_wire_old_buffer(req, 0);
10150 	if (rc != 0)
10151 		return (rc);
10152 
10153 	mtx_lock(&sc->reg_lock);
10154 	if (hw_off_limits(sc))
10155 		rc = ENXIO;
10156 	else {
10157 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10158 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10159 	}
10160 	mtx_unlock(&sc->reg_lock);
10161 	if (rc != 0)
10162 		return (rc);
10163 
10164 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10165 	if (sb == NULL)
10166 		return (ENOMEM);
10167 
10168 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10169 	for (i = 0; i < 4; i++) {
10170 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10171 		    tx_cyc[i]);
10172 	}
10173 
10174 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10175 	for (i = 0; i < 4; i++) {
10176 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10177 		    rx_cyc[i]);
10178 	}
10179 
10180 	if (chip_id(sc) > CHELSIO_T5) {
10181 		sbuf_printf(sb,
10182 		    "\n              Total wait      Total occupancy");
10183 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10184 		    tx_cyc[i]);
10185 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10186 		    rx_cyc[i]);
10187 
10188 		i += 2;
10189 		MPASS(i < nitems(tx_stats));
10190 
10191 		sbuf_printf(sb,
10192 		    "\n                   Reads           Total wait");
10193 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10194 		    tx_cyc[i]);
10195 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10196 		    rx_cyc[i]);
10197 	}
10198 
10199 	rc = sbuf_finish(sb);
10200 	sbuf_delete(sb);
10201 
10202 	return (rc);
10203 }
10204 
10205 static int
10206 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10207 {
10208 	struct adapter *sc = arg1;
10209 	struct sbuf *sb;
10210 	int rc;
10211 	struct tp_rdma_stats stats;
10212 
10213 	rc = sysctl_wire_old_buffer(req, 0);
10214 	if (rc != 0)
10215 		return (rc);
10216 
10217 	mtx_lock(&sc->reg_lock);
10218 	if (hw_off_limits(sc))
10219 		rc = ENXIO;
10220 	else
10221 		t4_tp_get_rdma_stats(sc, &stats, 0);
10222 	mtx_unlock(&sc->reg_lock);
10223 	if (rc != 0)
10224 		return (rc);
10225 
10226 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10227 	if (sb == NULL)
10228 		return (ENOMEM);
10229 
10230 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10231 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10232 
10233 	rc = sbuf_finish(sb);
10234 	sbuf_delete(sb);
10235 
10236 	return (rc);
10237 }
10238 
10239 static int
10240 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10241 {
10242 	struct adapter *sc = arg1;
10243 	struct sbuf *sb;
10244 	int rc;
10245 	struct tp_tcp_stats v4, v6;
10246 
10247 	rc = sysctl_wire_old_buffer(req, 0);
10248 	if (rc != 0)
10249 		return (rc);
10250 
10251 	mtx_lock(&sc->reg_lock);
10252 	if (hw_off_limits(sc))
10253 		rc = ENXIO;
10254 	else
10255 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10256 	mtx_unlock(&sc->reg_lock);
10257 	if (rc != 0)
10258 		return (rc);
10259 
10260 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10261 	if (sb == NULL)
10262 		return (ENOMEM);
10263 
10264 	sbuf_printf(sb,
10265 	    "                                IP                 IPv6\n");
10266 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10267 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10268 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10269 	    v4.tcp_in_segs, v6.tcp_in_segs);
10270 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10271 	    v4.tcp_out_segs, v6.tcp_out_segs);
10272 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10273 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10274 
10275 	rc = sbuf_finish(sb);
10276 	sbuf_delete(sb);
10277 
10278 	return (rc);
10279 }
10280 
10281 static int
10282 sysctl_tids(SYSCTL_HANDLER_ARGS)
10283 {
10284 	struct adapter *sc = arg1;
10285 	struct sbuf *sb;
10286 	int rc;
10287 	uint32_t x, y;
10288 	struct tid_info *t = &sc->tids;
10289 
10290 	rc = sysctl_wire_old_buffer(req, 0);
10291 	if (rc != 0)
10292 		return (rc);
10293 
10294 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10295 	if (sb == NULL)
10296 		return (ENOMEM);
10297 
10298 	if (t->natids) {
10299 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10300 		    t->atids_in_use);
10301 	}
10302 
10303 	if (t->nhpftids) {
10304 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10305 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10306 	}
10307 
10308 	if (t->ntids) {
10309 		bool hashen = false;
10310 
10311 		mtx_lock(&sc->reg_lock);
10312 		if (hw_off_limits(sc))
10313 			rc = ENXIO;
10314 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10315 			hashen = true;
10316 			if (chip_id(sc) <= CHELSIO_T5) {
10317 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10318 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10319 			} else {
10320 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10321 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10322 			}
10323 		}
10324 		mtx_unlock(&sc->reg_lock);
10325 		if (rc != 0)
10326 			goto done;
10327 
10328 		sbuf_printf(sb, "TID range: ");
10329 		if (hashen) {
10330 			if (x)
10331 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10332 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10333 		} else {
10334 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10335 			    t->ntids - 1);
10336 		}
10337 		sbuf_printf(sb, ", in use: %u\n",
10338 		    atomic_load_acq_int(&t->tids_in_use));
10339 	}
10340 
10341 	if (t->nstids) {
10342 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10343 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10344 	}
10345 
10346 	if (t->nftids) {
10347 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10348 		    t->ftid_end, t->ftids_in_use);
10349 	}
10350 
10351 	if (t->netids) {
10352 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10353 		    t->etid_base + t->netids - 1, t->etids_in_use);
10354 	}
10355 
10356 	mtx_lock(&sc->reg_lock);
10357 	if (hw_off_limits(sc))
10358 		rc = ENXIO;
10359 	else {
10360 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10361 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10362 	}
10363 	mtx_unlock(&sc->reg_lock);
10364 	if (rc != 0)
10365 		goto done;
10366 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10367 done:
10368 	if (rc == 0)
10369 		rc = sbuf_finish(sb);
10370 	else
10371 		(void)sbuf_finish(sb);
10372 	sbuf_delete(sb);
10373 
10374 	return (rc);
10375 }
10376 
10377 static int
10378 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10379 {
10380 	struct adapter *sc = arg1;
10381 	struct sbuf *sb;
10382 	int rc;
10383 	struct tp_err_stats stats;
10384 
10385 	rc = sysctl_wire_old_buffer(req, 0);
10386 	if (rc != 0)
10387 		return (rc);
10388 
10389 	mtx_lock(&sc->reg_lock);
10390 	if (hw_off_limits(sc))
10391 		rc = ENXIO;
10392 	else
10393 		t4_tp_get_err_stats(sc, &stats, 0);
10394 	mtx_unlock(&sc->reg_lock);
10395 	if (rc != 0)
10396 		return (rc);
10397 
10398 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10399 	if (sb == NULL)
10400 		return (ENOMEM);
10401 
10402 	if (sc->chip_params->nchan > 2) {
10403 		sbuf_printf(sb, "                 channel 0  channel 1"
10404 		    "  channel 2  channel 3\n");
10405 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10406 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10407 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10408 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10409 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10410 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10411 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10412 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10413 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10414 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10415 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10416 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10417 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10418 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10419 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10420 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10421 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10422 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10423 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10424 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10425 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10426 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10427 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10428 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10429 	} else {
10430 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10431 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10432 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10433 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10434 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10435 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10436 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10437 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10438 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10439 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10440 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10441 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10442 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10443 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10444 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10445 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10446 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10447 	}
10448 
10449 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10450 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10451 
10452 	rc = sbuf_finish(sb);
10453 	sbuf_delete(sb);
10454 
10455 	return (rc);
10456 }
10457 
10458 static int
10459 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10460 {
10461 	struct adapter *sc = arg1;
10462 	struct sbuf *sb;
10463 	int rc;
10464 	struct tp_tnl_stats stats;
10465 
10466 	rc = sysctl_wire_old_buffer(req, 0);
10467 	if (rc != 0)
10468 		return(rc);
10469 
10470 	mtx_lock(&sc->reg_lock);
10471 	if (hw_off_limits(sc))
10472 		rc = ENXIO;
10473 	else
10474 		t4_tp_get_tnl_stats(sc, &stats, 1);
10475 	mtx_unlock(&sc->reg_lock);
10476 	if (rc != 0)
10477 		return (rc);
10478 
10479 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10480 	if (sb == NULL)
10481 		return (ENOMEM);
10482 
10483 	if (sc->chip_params->nchan > 2) {
10484 		sbuf_printf(sb, "           channel 0  channel 1"
10485 		    "  channel 2  channel 3\n");
10486 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10487 		    stats.out_pkt[0], stats.out_pkt[1],
10488 		    stats.out_pkt[2], stats.out_pkt[3]);
10489 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10490 		    stats.in_pkt[0], stats.in_pkt[1],
10491 		    stats.in_pkt[2], stats.in_pkt[3]);
10492 	} else {
10493 		sbuf_printf(sb, "           channel 0  channel 1\n");
10494 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10495 		    stats.out_pkt[0], stats.out_pkt[1]);
10496 		sbuf_printf(sb, "InPkts:   %10u %10u",
10497 		    stats.in_pkt[0], stats.in_pkt[1]);
10498 	}
10499 
10500 	rc = sbuf_finish(sb);
10501 	sbuf_delete(sb);
10502 
10503 	return (rc);
10504 }
10505 
10506 static int
10507 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10508 {
10509 	struct adapter *sc = arg1;
10510 	struct tp_params *tpp = &sc->params.tp;
10511 	u_int mask;
10512 	int rc;
10513 
10514 	mask = tpp->la_mask >> 16;
10515 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10516 	if (rc != 0 || req->newptr == NULL)
10517 		return (rc);
10518 	if (mask > 0xffff)
10519 		return (EINVAL);
10520 	mtx_lock(&sc->reg_lock);
10521 	if (hw_off_limits(sc))
10522 		rc = ENXIO;
10523 	else {
10524 		tpp->la_mask = mask << 16;
10525 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10526 		    tpp->la_mask);
10527 	}
10528 	mtx_unlock(&sc->reg_lock);
10529 
10530 	return (rc);
10531 }
10532 
10533 struct field_desc {
10534 	const char *name;
10535 	u_int start;
10536 	u_int width;
10537 };
10538 
10539 static void
10540 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10541 {
10542 	char buf[32];
10543 	int line_size = 0;
10544 
10545 	while (f->name) {
10546 		uint64_t mask = (1ULL << f->width) - 1;
10547 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10548 		    ((uintmax_t)v >> f->start) & mask);
10549 
10550 		if (line_size + len >= 79) {
10551 			line_size = 8;
10552 			sbuf_printf(sb, "\n        ");
10553 		}
10554 		sbuf_printf(sb, "%s ", buf);
10555 		line_size += len + 1;
10556 		f++;
10557 	}
10558 	sbuf_printf(sb, "\n");
10559 }
10560 
10561 static const struct field_desc tp_la0[] = {
10562 	{ "RcfOpCodeOut", 60, 4 },
10563 	{ "State", 56, 4 },
10564 	{ "WcfState", 52, 4 },
10565 	{ "RcfOpcSrcOut", 50, 2 },
10566 	{ "CRxError", 49, 1 },
10567 	{ "ERxError", 48, 1 },
10568 	{ "SanityFailed", 47, 1 },
10569 	{ "SpuriousMsg", 46, 1 },
10570 	{ "FlushInputMsg", 45, 1 },
10571 	{ "FlushInputCpl", 44, 1 },
10572 	{ "RssUpBit", 43, 1 },
10573 	{ "RssFilterHit", 42, 1 },
10574 	{ "Tid", 32, 10 },
10575 	{ "InitTcb", 31, 1 },
10576 	{ "LineNumber", 24, 7 },
10577 	{ "Emsg", 23, 1 },
10578 	{ "EdataOut", 22, 1 },
10579 	{ "Cmsg", 21, 1 },
10580 	{ "CdataOut", 20, 1 },
10581 	{ "EreadPdu", 19, 1 },
10582 	{ "CreadPdu", 18, 1 },
10583 	{ "TunnelPkt", 17, 1 },
10584 	{ "RcfPeerFin", 16, 1 },
10585 	{ "RcfReasonOut", 12, 4 },
10586 	{ "TxCchannel", 10, 2 },
10587 	{ "RcfTxChannel", 8, 2 },
10588 	{ "RxEchannel", 6, 2 },
10589 	{ "RcfRxChannel", 5, 1 },
10590 	{ "RcfDataOutSrdy", 4, 1 },
10591 	{ "RxDvld", 3, 1 },
10592 	{ "RxOoDvld", 2, 1 },
10593 	{ "RxCongestion", 1, 1 },
10594 	{ "TxCongestion", 0, 1 },
10595 	{ NULL }
10596 };
10597 
10598 static const struct field_desc tp_la1[] = {
10599 	{ "CplCmdIn", 56, 8 },
10600 	{ "CplCmdOut", 48, 8 },
10601 	{ "ESynOut", 47, 1 },
10602 	{ "EAckOut", 46, 1 },
10603 	{ "EFinOut", 45, 1 },
10604 	{ "ERstOut", 44, 1 },
10605 	{ "SynIn", 43, 1 },
10606 	{ "AckIn", 42, 1 },
10607 	{ "FinIn", 41, 1 },
10608 	{ "RstIn", 40, 1 },
10609 	{ "DataIn", 39, 1 },
10610 	{ "DataInVld", 38, 1 },
10611 	{ "PadIn", 37, 1 },
10612 	{ "RxBufEmpty", 36, 1 },
10613 	{ "RxDdp", 35, 1 },
10614 	{ "RxFbCongestion", 34, 1 },
10615 	{ "TxFbCongestion", 33, 1 },
10616 	{ "TxPktSumSrdy", 32, 1 },
10617 	{ "RcfUlpType", 28, 4 },
10618 	{ "Eread", 27, 1 },
10619 	{ "Ebypass", 26, 1 },
10620 	{ "Esave", 25, 1 },
10621 	{ "Static0", 24, 1 },
10622 	{ "Cread", 23, 1 },
10623 	{ "Cbypass", 22, 1 },
10624 	{ "Csave", 21, 1 },
10625 	{ "CPktOut", 20, 1 },
10626 	{ "RxPagePoolFull", 18, 2 },
10627 	{ "RxLpbkPkt", 17, 1 },
10628 	{ "TxLpbkPkt", 16, 1 },
10629 	{ "RxVfValid", 15, 1 },
10630 	{ "SynLearned", 14, 1 },
10631 	{ "SetDelEntry", 13, 1 },
10632 	{ "SetInvEntry", 12, 1 },
10633 	{ "CpcmdDvld", 11, 1 },
10634 	{ "CpcmdSave", 10, 1 },
10635 	{ "RxPstructsFull", 8, 2 },
10636 	{ "EpcmdDvld", 7, 1 },
10637 	{ "EpcmdFlush", 6, 1 },
10638 	{ "EpcmdTrimPrefix", 5, 1 },
10639 	{ "EpcmdTrimPostfix", 4, 1 },
10640 	{ "ERssIp4Pkt", 3, 1 },
10641 	{ "ERssIp6Pkt", 2, 1 },
10642 	{ "ERssTcpUdpPkt", 1, 1 },
10643 	{ "ERssFceFipPkt", 0, 1 },
10644 	{ NULL }
10645 };
10646 
10647 static const struct field_desc tp_la2[] = {
10648 	{ "CplCmdIn", 56, 8 },
10649 	{ "MpsVfVld", 55, 1 },
10650 	{ "MpsPf", 52, 3 },
10651 	{ "MpsVf", 44, 8 },
10652 	{ "SynIn", 43, 1 },
10653 	{ "AckIn", 42, 1 },
10654 	{ "FinIn", 41, 1 },
10655 	{ "RstIn", 40, 1 },
10656 	{ "DataIn", 39, 1 },
10657 	{ "DataInVld", 38, 1 },
10658 	{ "PadIn", 37, 1 },
10659 	{ "RxBufEmpty", 36, 1 },
10660 	{ "RxDdp", 35, 1 },
10661 	{ "RxFbCongestion", 34, 1 },
10662 	{ "TxFbCongestion", 33, 1 },
10663 	{ "TxPktSumSrdy", 32, 1 },
10664 	{ "RcfUlpType", 28, 4 },
10665 	{ "Eread", 27, 1 },
10666 	{ "Ebypass", 26, 1 },
10667 	{ "Esave", 25, 1 },
10668 	{ "Static0", 24, 1 },
10669 	{ "Cread", 23, 1 },
10670 	{ "Cbypass", 22, 1 },
10671 	{ "Csave", 21, 1 },
10672 	{ "CPktOut", 20, 1 },
10673 	{ "RxPagePoolFull", 18, 2 },
10674 	{ "RxLpbkPkt", 17, 1 },
10675 	{ "TxLpbkPkt", 16, 1 },
10676 	{ "RxVfValid", 15, 1 },
10677 	{ "SynLearned", 14, 1 },
10678 	{ "SetDelEntry", 13, 1 },
10679 	{ "SetInvEntry", 12, 1 },
10680 	{ "CpcmdDvld", 11, 1 },
10681 	{ "CpcmdSave", 10, 1 },
10682 	{ "RxPstructsFull", 8, 2 },
10683 	{ "EpcmdDvld", 7, 1 },
10684 	{ "EpcmdFlush", 6, 1 },
10685 	{ "EpcmdTrimPrefix", 5, 1 },
10686 	{ "EpcmdTrimPostfix", 4, 1 },
10687 	{ "ERssIp4Pkt", 3, 1 },
10688 	{ "ERssIp6Pkt", 2, 1 },
10689 	{ "ERssTcpUdpPkt", 1, 1 },
10690 	{ "ERssFceFipPkt", 0, 1 },
10691 	{ NULL }
10692 };
10693 
10694 static void
10695 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10696 {
10697 
10698 	field_desc_show(sb, *p, tp_la0);
10699 }
10700 
10701 static void
10702 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10703 {
10704 
10705 	if (idx)
10706 		sbuf_printf(sb, "\n");
10707 	field_desc_show(sb, p[0], tp_la0);
10708 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10709 		field_desc_show(sb, p[1], tp_la0);
10710 }
10711 
10712 static void
10713 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
10714 {
10715 
10716 	if (idx)
10717 		sbuf_printf(sb, "\n");
10718 	field_desc_show(sb, p[0], tp_la0);
10719 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10720 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
10721 }
10722 
10723 static int
10724 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
10725 {
10726 	struct adapter *sc = arg1;
10727 	struct sbuf *sb;
10728 	uint64_t *buf, *p;
10729 	int rc;
10730 	u_int i, inc;
10731 	void (*show_func)(struct sbuf *, uint64_t *, int);
10732 
10733 	rc = sysctl_wire_old_buffer(req, 0);
10734 	if (rc != 0)
10735 		return (rc);
10736 
10737 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10738 	if (sb == NULL)
10739 		return (ENOMEM);
10740 
10741 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
10742 
10743 	mtx_lock(&sc->reg_lock);
10744 	if (hw_off_limits(sc))
10745 		rc = ENXIO;
10746 	else {
10747 		t4_tp_read_la(sc, buf, NULL);
10748 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
10749 		case 2:
10750 			inc = 2;
10751 			show_func = tp_la_show2;
10752 			break;
10753 		case 3:
10754 			inc = 2;
10755 			show_func = tp_la_show3;
10756 			break;
10757 		default:
10758 			inc = 1;
10759 			show_func = tp_la_show;
10760 		}
10761 	}
10762 	mtx_unlock(&sc->reg_lock);
10763 	if (rc != 0)
10764 		goto done;
10765 
10766 	p = buf;
10767 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
10768 		(*show_func)(sb, p, i);
10769 	rc = sbuf_finish(sb);
10770 done:
10771 	sbuf_delete(sb);
10772 	free(buf, M_CXGBE);
10773 	return (rc);
10774 }
10775 
10776 static int
10777 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
10778 {
10779 	struct adapter *sc = arg1;
10780 	struct sbuf *sb;
10781 	int rc;
10782 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
10783 
10784 	rc = sysctl_wire_old_buffer(req, 0);
10785 	if (rc != 0)
10786 		return (rc);
10787 
10788 	mtx_lock(&sc->reg_lock);
10789 	if (hw_off_limits(sc))
10790 		rc = ENXIO;
10791 	else
10792 		t4_get_chan_txrate(sc, nrate, orate);
10793 	mtx_unlock(&sc->reg_lock);
10794 	if (rc != 0)
10795 		return (rc);
10796 
10797 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10798 	if (sb == NULL)
10799 		return (ENOMEM);
10800 
10801 	if (sc->chip_params->nchan > 2) {
10802 		sbuf_printf(sb, "              channel 0   channel 1"
10803 		    "   channel 2   channel 3\n");
10804 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
10805 		    nrate[0], nrate[1], nrate[2], nrate[3]);
10806 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
10807 		    orate[0], orate[1], orate[2], orate[3]);
10808 	} else {
10809 		sbuf_printf(sb, "              channel 0   channel 1\n");
10810 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
10811 		    nrate[0], nrate[1]);
10812 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
10813 		    orate[0], orate[1]);
10814 	}
10815 
10816 	rc = sbuf_finish(sb);
10817 	sbuf_delete(sb);
10818 
10819 	return (rc);
10820 }
10821 
10822 static int
10823 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
10824 {
10825 	struct adapter *sc = arg1;
10826 	struct sbuf *sb;
10827 	uint32_t *buf, *p;
10828 	int rc, i;
10829 
10830 	rc = sysctl_wire_old_buffer(req, 0);
10831 	if (rc != 0)
10832 		return (rc);
10833 
10834 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10835 	if (sb == NULL)
10836 		return (ENOMEM);
10837 
10838 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
10839 	    M_ZERO | M_WAITOK);
10840 
10841 	mtx_lock(&sc->reg_lock);
10842 	if (hw_off_limits(sc))
10843 		rc = ENXIO;
10844 	else
10845 		t4_ulprx_read_la(sc, buf);
10846 	mtx_unlock(&sc->reg_lock);
10847 	if (rc != 0)
10848 		goto done;
10849 
10850 	p = buf;
10851 	sbuf_printf(sb, "      Pcmd        Type   Message"
10852 	    "                Data");
10853 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
10854 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
10855 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
10856 	}
10857 	rc = sbuf_finish(sb);
10858 done:
10859 	sbuf_delete(sb);
10860 	free(buf, M_CXGBE);
10861 	return (rc);
10862 }
10863 
10864 static int
10865 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
10866 {
10867 	struct adapter *sc = arg1;
10868 	struct sbuf *sb;
10869 	int rc;
10870 	uint32_t cfg, s1, s2;
10871 
10872 	MPASS(chip_id(sc) >= CHELSIO_T5);
10873 
10874 	rc = sysctl_wire_old_buffer(req, 0);
10875 	if (rc != 0)
10876 		return (rc);
10877 
10878 	mtx_lock(&sc->reg_lock);
10879 	if (hw_off_limits(sc))
10880 		rc = ENXIO;
10881 	else {
10882 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
10883 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
10884 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
10885 	}
10886 	mtx_unlock(&sc->reg_lock);
10887 	if (rc != 0)
10888 		return (rc);
10889 
10890 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10891 	if (sb == NULL)
10892 		return (ENOMEM);
10893 
10894 	if (G_STATSOURCE_T5(cfg) == 7) {
10895 		int mode;
10896 
10897 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
10898 		if (mode == 0)
10899 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
10900 		else if (mode == 1)
10901 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
10902 		else
10903 			sbuf_printf(sb, "unknown mode %d", mode);
10904 	}
10905 	rc = sbuf_finish(sb);
10906 	sbuf_delete(sb);
10907 
10908 	return (rc);
10909 }
10910 
10911 static int
10912 sysctl_cpus(SYSCTL_HANDLER_ARGS)
10913 {
10914 	struct adapter *sc = arg1;
10915 	enum cpu_sets op = arg2;
10916 	cpuset_t cpuset;
10917 	struct sbuf *sb;
10918 	int i, rc;
10919 
10920 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
10921 
10922 	CPU_ZERO(&cpuset);
10923 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
10924 	if (rc != 0)
10925 		return (rc);
10926 
10927 	rc = sysctl_wire_old_buffer(req, 0);
10928 	if (rc != 0)
10929 		return (rc);
10930 
10931 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10932 	if (sb == NULL)
10933 		return (ENOMEM);
10934 
10935 	CPU_FOREACH(i)
10936 		sbuf_printf(sb, "%d ", i);
10937 	rc = sbuf_finish(sb);
10938 	sbuf_delete(sb);
10939 
10940 	return (rc);
10941 }
10942 
10943 static int
10944 sysctl_reset(SYSCTL_HANDLER_ARGS)
10945 {
10946 	struct adapter *sc = arg1;
10947 	u_int val;
10948 	int rc;
10949 
10950 	val = sc->num_resets;
10951 	rc = sysctl_handle_int(oidp, &val, 0, req);
10952 	if (rc != 0 || req->newptr == NULL)
10953 		return (rc);
10954 
10955 	if (val == 0) {
10956 		/* Zero out the counter that tracks reset. */
10957 		sc->num_resets = 0;
10958 		return (0);
10959 	}
10960 
10961 	if (val != 1)
10962 		return (EINVAL);	/* 0 or 1 are the only legal values */
10963 
10964 	if (hw_off_limits(sc))		/* harmless race */
10965 		return (EALREADY);
10966 
10967 	taskqueue_enqueue(reset_tq, &sc->reset_task);
10968 	return (0);
10969 }
10970 
10971 #ifdef TCP_OFFLOAD
10972 static int
10973 sysctl_tls(SYSCTL_HANDLER_ARGS)
10974 {
10975 	struct adapter *sc = arg1;
10976 	int i, j, v, rc;
10977 	struct vi_info *vi;
10978 
10979 	v = sc->tt.tls;
10980 	rc = sysctl_handle_int(oidp, &v, 0, req);
10981 	if (rc != 0 || req->newptr == NULL)
10982 		return (rc);
10983 
10984 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
10985 		return (ENOTSUP);
10986 
10987 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
10988 	if (rc)
10989 		return (rc);
10990 	if (hw_off_limits(sc))
10991 		rc = ENXIO;
10992 	else {
10993 		sc->tt.tls = !!v;
10994 		for_each_port(sc, i) {
10995 			for_each_vi(sc->port[i], j, vi) {
10996 				if (vi->flags & VI_INIT_DONE)
10997 					t4_update_fl_bufsize(vi->ifp);
10998 			}
10999 		}
11000 	}
11001 	end_synchronized_op(sc, 0);
11002 
11003 	return (rc);
11004 
11005 }
11006 
11007 static int
11008 sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS)
11009 {
11010 	struct adapter *sc = arg1;
11011 	int *old_ports, *new_ports;
11012 	int i, new_count, rc;
11013 
11014 	if (req->newptr == NULL && req->oldptr == NULL)
11015 		return (SYSCTL_OUT(req, NULL, imax(sc->tt.num_tls_rx_ports, 1) *
11016 		    sizeof(sc->tt.tls_rx_ports[0])));
11017 
11018 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tlsrx");
11019 	if (rc)
11020 		return (rc);
11021 
11022 	if (hw_off_limits(sc)) {
11023 		rc = ENXIO;
11024 		goto done;
11025 	}
11026 
11027 	if (sc->tt.num_tls_rx_ports == 0) {
11028 		i = -1;
11029 		rc = SYSCTL_OUT(req, &i, sizeof(i));
11030 	} else
11031 		rc = SYSCTL_OUT(req, sc->tt.tls_rx_ports,
11032 		    sc->tt.num_tls_rx_ports * sizeof(sc->tt.tls_rx_ports[0]));
11033 	if (rc == 0 && req->newptr != NULL) {
11034 		new_count = req->newlen / sizeof(new_ports[0]);
11035 		new_ports = malloc(new_count * sizeof(new_ports[0]), M_CXGBE,
11036 		    M_WAITOK);
11037 		rc = SYSCTL_IN(req, new_ports, new_count *
11038 		    sizeof(new_ports[0]));
11039 		if (rc)
11040 			goto err;
11041 
11042 		/* Allow setting to a single '-1' to clear the list. */
11043 		if (new_count == 1 && new_ports[0] == -1) {
11044 			ADAPTER_LOCK(sc);
11045 			old_ports = sc->tt.tls_rx_ports;
11046 			sc->tt.tls_rx_ports = NULL;
11047 			sc->tt.num_tls_rx_ports = 0;
11048 			ADAPTER_UNLOCK(sc);
11049 			free(old_ports, M_CXGBE);
11050 		} else {
11051 			for (i = 0; i < new_count; i++) {
11052 				if (new_ports[i] < 1 ||
11053 				    new_ports[i] > IPPORT_MAX) {
11054 					rc = EINVAL;
11055 					goto err;
11056 				}
11057 			}
11058 
11059 			ADAPTER_LOCK(sc);
11060 			old_ports = sc->tt.tls_rx_ports;
11061 			sc->tt.tls_rx_ports = new_ports;
11062 			sc->tt.num_tls_rx_ports = new_count;
11063 			ADAPTER_UNLOCK(sc);
11064 			free(old_ports, M_CXGBE);
11065 			new_ports = NULL;
11066 		}
11067 	err:
11068 		free(new_ports, M_CXGBE);
11069 	}
11070 done:
11071 	end_synchronized_op(sc, 0);
11072 	return (rc);
11073 }
11074 
11075 static int
11076 sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS)
11077 {
11078 	struct adapter *sc = arg1;
11079 	int v, rc;
11080 
11081 	v = sc->tt.tls_rx_timeout;
11082 	rc = sysctl_handle_int(oidp, &v, 0, req);
11083 	if (rc != 0 || req->newptr == NULL)
11084 		return (rc);
11085 
11086 	if (v < 0)
11087 		return (EINVAL);
11088 
11089 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11090 		return (ENOTSUP);
11091 
11092 	sc->tt.tls_rx_timeout = v;
11093 
11094 	return (0);
11095 
11096 }
11097 
11098 static void
11099 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11100 {
11101 	u_int rem = val % factor;
11102 
11103 	if (rem == 0)
11104 		snprintf(buf, len, "%u", val / factor);
11105 	else {
11106 		while (rem % 10 == 0)
11107 			rem /= 10;
11108 		snprintf(buf, len, "%u.%u", val / factor, rem);
11109 	}
11110 }
11111 
11112 static int
11113 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11114 {
11115 	struct adapter *sc = arg1;
11116 	char buf[16];
11117 	u_int res, re;
11118 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11119 
11120 	mtx_lock(&sc->reg_lock);
11121 	if (hw_off_limits(sc))
11122 		res = (u_int)-1;
11123 	else
11124 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11125 	mtx_unlock(&sc->reg_lock);
11126 	if (res == (u_int)-1)
11127 		return (ENXIO);
11128 
11129 	switch (arg2) {
11130 	case 0:
11131 		/* timer_tick */
11132 		re = G_TIMERRESOLUTION(res);
11133 		break;
11134 	case 1:
11135 		/* TCP timestamp tick */
11136 		re = G_TIMESTAMPRESOLUTION(res);
11137 		break;
11138 	case 2:
11139 		/* DACK tick */
11140 		re = G_DELAYEDACKRESOLUTION(res);
11141 		break;
11142 	default:
11143 		return (EDOOFUS);
11144 	}
11145 
11146 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11147 
11148 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11149 }
11150 
11151 static int
11152 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11153 {
11154 	struct adapter *sc = arg1;
11155 	int rc;
11156 	u_int dack_tmr, dack_re, v;
11157 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11158 
11159 	mtx_lock(&sc->reg_lock);
11160 	if (hw_off_limits(sc))
11161 		rc = ENXIO;
11162 	else {
11163 		rc = 0;
11164 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11165 		    A_TP_TIMER_RESOLUTION));
11166 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11167 	}
11168 	mtx_unlock(&sc->reg_lock);
11169 	if (rc != 0)
11170 		return (rc);
11171 
11172 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11173 
11174 	return (sysctl_handle_int(oidp, &v, 0, req));
11175 }
11176 
11177 static int
11178 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11179 {
11180 	struct adapter *sc = arg1;
11181 	int rc, reg = arg2;
11182 	u_int tre;
11183 	u_long tp_tick_us, v;
11184 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11185 
11186 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11187 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11188 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11189 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11190 
11191 	mtx_lock(&sc->reg_lock);
11192 	if (hw_off_limits(sc))
11193 		rc = ENXIO;
11194 	else {
11195 		rc = 0;
11196 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11197 		tp_tick_us = (cclk_ps << tre) / 1000000;
11198 		if (reg == A_TP_INIT_SRTT)
11199 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11200 		else
11201 			v = tp_tick_us * t4_read_reg(sc, reg);
11202 	}
11203 	mtx_unlock(&sc->reg_lock);
11204 	if (rc != 0)
11205 		return (rc);
11206 	else
11207 		return (sysctl_handle_long(oidp, &v, 0, req));
11208 }
11209 
11210 /*
11211  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11212  * passed to this function.
11213  */
11214 static int
11215 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11216 {
11217 	struct adapter *sc = arg1;
11218 	int rc, idx = arg2;
11219 	u_int v;
11220 
11221 	MPASS(idx >= 0 && idx <= 24);
11222 
11223 	mtx_lock(&sc->reg_lock);
11224 	if (hw_off_limits(sc))
11225 		rc = ENXIO;
11226 	else {
11227 		rc = 0;
11228 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11229 	}
11230 	mtx_unlock(&sc->reg_lock);
11231 	if (rc != 0)
11232 		return (rc);
11233 	else
11234 		return (sysctl_handle_int(oidp, &v, 0, req));
11235 }
11236 
11237 static int
11238 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11239 {
11240 	struct adapter *sc = arg1;
11241 	int rc, idx = arg2;
11242 	u_int shift, v, r;
11243 
11244 	MPASS(idx >= 0 && idx < 16);
11245 
11246 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11247 	shift = (idx & 3) << 3;
11248 	mtx_lock(&sc->reg_lock);
11249 	if (hw_off_limits(sc))
11250 		rc = ENXIO;
11251 	else {
11252 		rc = 0;
11253 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11254 	}
11255 	mtx_unlock(&sc->reg_lock);
11256 	if (rc != 0)
11257 		return (rc);
11258 	else
11259 		return (sysctl_handle_int(oidp, &v, 0, req));
11260 }
11261 
11262 static int
11263 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11264 {
11265 	struct vi_info *vi = arg1;
11266 	struct adapter *sc = vi->adapter;
11267 	int idx, rc, i;
11268 	struct sge_ofld_rxq *ofld_rxq;
11269 	uint8_t v;
11270 
11271 	idx = vi->ofld_tmr_idx;
11272 
11273 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11274 	if (rc != 0 || req->newptr == NULL)
11275 		return (rc);
11276 
11277 	if (idx < 0 || idx >= SGE_NTIMERS)
11278 		return (EINVAL);
11279 
11280 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11281 	    "t4otmr");
11282 	if (rc)
11283 		return (rc);
11284 
11285 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11286 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11287 #ifdef atomic_store_rel_8
11288 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11289 #else
11290 		ofld_rxq->iq.intr_params = v;
11291 #endif
11292 	}
11293 	vi->ofld_tmr_idx = idx;
11294 
11295 	end_synchronized_op(sc, LOCK_HELD);
11296 	return (0);
11297 }
11298 
11299 static int
11300 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11301 {
11302 	struct vi_info *vi = arg1;
11303 	struct adapter *sc = vi->adapter;
11304 	int idx, rc;
11305 
11306 	idx = vi->ofld_pktc_idx;
11307 
11308 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11309 	if (rc != 0 || req->newptr == NULL)
11310 		return (rc);
11311 
11312 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11313 		return (EINVAL);
11314 
11315 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11316 	    "t4opktc");
11317 	if (rc)
11318 		return (rc);
11319 
11320 	if (vi->flags & VI_INIT_DONE)
11321 		rc = EBUSY; /* cannot be changed once the queues are created */
11322 	else
11323 		vi->ofld_pktc_idx = idx;
11324 
11325 	end_synchronized_op(sc, LOCK_HELD);
11326 	return (rc);
11327 }
11328 #endif
11329 
11330 static int
11331 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11332 {
11333 	int rc;
11334 
11335 	if (cntxt->cid > M_CTXTQID)
11336 		return (EINVAL);
11337 
11338 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11339 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11340 		return (EINVAL);
11341 
11342 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11343 	if (rc)
11344 		return (rc);
11345 
11346 	if (hw_off_limits(sc)) {
11347 		rc = ENXIO;
11348 		goto done;
11349 	}
11350 
11351 	if (sc->flags & FW_OK) {
11352 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11353 		    &cntxt->data[0]);
11354 		if (rc == 0)
11355 			goto done;
11356 	}
11357 
11358 	/*
11359 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11360 	 * the backdoor.
11361 	 */
11362 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11363 done:
11364 	end_synchronized_op(sc, 0);
11365 	return (rc);
11366 }
11367 
11368 static int
11369 load_fw(struct adapter *sc, struct t4_data *fw)
11370 {
11371 	int rc;
11372 	uint8_t *fw_data;
11373 
11374 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11375 	if (rc)
11376 		return (rc);
11377 
11378 	if (hw_off_limits(sc)) {
11379 		rc = ENXIO;
11380 		goto done;
11381 	}
11382 
11383 	/*
11384 	 * The firmware, with the sole exception of the memory parity error
11385 	 * handler, runs from memory and not flash.  It is almost always safe to
11386 	 * install a new firmware on a running system.  Just set bit 1 in
11387 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11388 	 */
11389 	if (sc->flags & FULL_INIT_DONE &&
11390 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11391 		rc = EBUSY;
11392 		goto done;
11393 	}
11394 
11395 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11396 
11397 	rc = copyin(fw->data, fw_data, fw->len);
11398 	if (rc == 0)
11399 		rc = -t4_load_fw(sc, fw_data, fw->len);
11400 
11401 	free(fw_data, M_CXGBE);
11402 done:
11403 	end_synchronized_op(sc, 0);
11404 	return (rc);
11405 }
11406 
11407 static int
11408 load_cfg(struct adapter *sc, struct t4_data *cfg)
11409 {
11410 	int rc;
11411 	uint8_t *cfg_data = NULL;
11412 
11413 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11414 	if (rc)
11415 		return (rc);
11416 
11417 	if (hw_off_limits(sc)) {
11418 		rc = ENXIO;
11419 		goto done;
11420 	}
11421 
11422 	if (cfg->len == 0) {
11423 		/* clear */
11424 		rc = -t4_load_cfg(sc, NULL, 0);
11425 		goto done;
11426 	}
11427 
11428 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11429 
11430 	rc = copyin(cfg->data, cfg_data, cfg->len);
11431 	if (rc == 0)
11432 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11433 
11434 	free(cfg_data, M_CXGBE);
11435 done:
11436 	end_synchronized_op(sc, 0);
11437 	return (rc);
11438 }
11439 
11440 static int
11441 load_boot(struct adapter *sc, struct t4_bootrom *br)
11442 {
11443 	int rc;
11444 	uint8_t *br_data = NULL;
11445 	u_int offset;
11446 
11447 	if (br->len > 1024 * 1024)
11448 		return (EFBIG);
11449 
11450 	if (br->pf_offset == 0) {
11451 		/* pfidx */
11452 		if (br->pfidx_addr > 7)
11453 			return (EINVAL);
11454 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11455 		    A_PCIE_PF_EXPROM_OFST)));
11456 	} else if (br->pf_offset == 1) {
11457 		/* offset */
11458 		offset = G_OFFSET(br->pfidx_addr);
11459 	} else {
11460 		return (EINVAL);
11461 	}
11462 
11463 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11464 	if (rc)
11465 		return (rc);
11466 
11467 	if (hw_off_limits(sc)) {
11468 		rc = ENXIO;
11469 		goto done;
11470 	}
11471 
11472 	if (br->len == 0) {
11473 		/* clear */
11474 		rc = -t4_load_boot(sc, NULL, offset, 0);
11475 		goto done;
11476 	}
11477 
11478 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11479 
11480 	rc = copyin(br->data, br_data, br->len);
11481 	if (rc == 0)
11482 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11483 
11484 	free(br_data, M_CXGBE);
11485 done:
11486 	end_synchronized_op(sc, 0);
11487 	return (rc);
11488 }
11489 
11490 static int
11491 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11492 {
11493 	int rc;
11494 	uint8_t *bc_data = NULL;
11495 
11496 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11497 	if (rc)
11498 		return (rc);
11499 
11500 	if (hw_off_limits(sc)) {
11501 		rc = ENXIO;
11502 		goto done;
11503 	}
11504 
11505 	if (bc->len == 0) {
11506 		/* clear */
11507 		rc = -t4_load_bootcfg(sc, NULL, 0);
11508 		goto done;
11509 	}
11510 
11511 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11512 
11513 	rc = copyin(bc->data, bc_data, bc->len);
11514 	if (rc == 0)
11515 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11516 
11517 	free(bc_data, M_CXGBE);
11518 done:
11519 	end_synchronized_op(sc, 0);
11520 	return (rc);
11521 }
11522 
11523 static int
11524 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11525 {
11526 	int rc;
11527 	struct cudbg_init *cudbg;
11528 	void *handle, *buf;
11529 
11530 	/* buf is large, don't block if no memory is available */
11531 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11532 	if (buf == NULL)
11533 		return (ENOMEM);
11534 
11535 	handle = cudbg_alloc_handle();
11536 	if (handle == NULL) {
11537 		rc = ENOMEM;
11538 		goto done;
11539 	}
11540 
11541 	cudbg = cudbg_get_init(handle);
11542 	cudbg->adap = sc;
11543 	cudbg->print = (cudbg_print_cb)printf;
11544 
11545 #ifndef notyet
11546 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11547 	    __func__, dump->wr_flash, dump->len, dump->data);
11548 #endif
11549 
11550 	if (dump->wr_flash)
11551 		cudbg->use_flash = 1;
11552 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11553 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11554 
11555 	rc = cudbg_collect(handle, buf, &dump->len);
11556 	if (rc != 0)
11557 		goto done;
11558 
11559 	rc = copyout(buf, dump->data, dump->len);
11560 done:
11561 	cudbg_free_handle(handle);
11562 	free(buf, M_CXGBE);
11563 	return (rc);
11564 }
11565 
11566 static void
11567 free_offload_policy(struct t4_offload_policy *op)
11568 {
11569 	struct offload_rule *r;
11570 	int i;
11571 
11572 	if (op == NULL)
11573 		return;
11574 
11575 	r = &op->rule[0];
11576 	for (i = 0; i < op->nrules; i++, r++) {
11577 		free(r->bpf_prog.bf_insns, M_CXGBE);
11578 	}
11579 	free(op->rule, M_CXGBE);
11580 	free(op, M_CXGBE);
11581 }
11582 
11583 static int
11584 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11585 {
11586 	int i, rc, len;
11587 	struct t4_offload_policy *op, *old;
11588 	struct bpf_program *bf;
11589 	const struct offload_settings *s;
11590 	struct offload_rule *r;
11591 	void *u;
11592 
11593 	if (!is_offload(sc))
11594 		return (ENODEV);
11595 
11596 	if (uop->nrules == 0) {
11597 		/* Delete installed policies. */
11598 		op = NULL;
11599 		goto set_policy;
11600 	} else if (uop->nrules > 256) { /* arbitrary */
11601 		return (E2BIG);
11602 	}
11603 
11604 	/* Copy userspace offload policy to kernel */
11605 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11606 	op->nrules = uop->nrules;
11607 	len = op->nrules * sizeof(struct offload_rule);
11608 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11609 	rc = copyin(uop->rule, op->rule, len);
11610 	if (rc) {
11611 		free(op->rule, M_CXGBE);
11612 		free(op, M_CXGBE);
11613 		return (rc);
11614 	}
11615 
11616 	r = &op->rule[0];
11617 	for (i = 0; i < op->nrules; i++, r++) {
11618 
11619 		/* Validate open_type */
11620 		if (r->open_type != OPEN_TYPE_LISTEN &&
11621 		    r->open_type != OPEN_TYPE_ACTIVE &&
11622 		    r->open_type != OPEN_TYPE_PASSIVE &&
11623 		    r->open_type != OPEN_TYPE_DONTCARE) {
11624 error:
11625 			/*
11626 			 * Rules 0 to i have malloc'd filters that need to be
11627 			 * freed.  Rules i+1 to nrules have userspace pointers
11628 			 * and should be left alone.
11629 			 */
11630 			op->nrules = i;
11631 			free_offload_policy(op);
11632 			return (rc);
11633 		}
11634 
11635 		/* Validate settings */
11636 		s = &r->settings;
11637 		if ((s->offload != 0 && s->offload != 1) ||
11638 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11639 		    s->sched_class < -1 ||
11640 		    s->sched_class >= sc->params.nsched_cls) {
11641 			rc = EINVAL;
11642 			goto error;
11643 		}
11644 
11645 		bf = &r->bpf_prog;
11646 		u = bf->bf_insns;	/* userspace ptr */
11647 		bf->bf_insns = NULL;
11648 		if (bf->bf_len == 0) {
11649 			/* legal, matches everything */
11650 			continue;
11651 		}
11652 		len = bf->bf_len * sizeof(*bf->bf_insns);
11653 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11654 		rc = copyin(u, bf->bf_insns, len);
11655 		if (rc != 0)
11656 			goto error;
11657 
11658 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11659 			rc = EINVAL;
11660 			goto error;
11661 		}
11662 	}
11663 set_policy:
11664 	rw_wlock(&sc->policy_lock);
11665 	old = sc->policy;
11666 	sc->policy = op;
11667 	rw_wunlock(&sc->policy_lock);
11668 	free_offload_policy(old);
11669 
11670 	return (0);
11671 }
11672 
11673 #define MAX_READ_BUF_SIZE (128 * 1024)
11674 static int
11675 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11676 {
11677 	uint32_t addr, remaining, n;
11678 	uint32_t *buf;
11679 	int rc;
11680 	uint8_t *dst;
11681 
11682 	mtx_lock(&sc->reg_lock);
11683 	if (hw_off_limits(sc))
11684 		rc = ENXIO;
11685 	else
11686 		rc = validate_mem_range(sc, mr->addr, mr->len);
11687 	mtx_unlock(&sc->reg_lock);
11688 	if (rc != 0)
11689 		return (rc);
11690 
11691 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11692 	addr = mr->addr;
11693 	remaining = mr->len;
11694 	dst = (void *)mr->data;
11695 
11696 	while (remaining) {
11697 		n = min(remaining, MAX_READ_BUF_SIZE);
11698 		mtx_lock(&sc->reg_lock);
11699 		if (hw_off_limits(sc))
11700 			rc = ENXIO;
11701 		else
11702 			read_via_memwin(sc, 2, addr, buf, n);
11703 		mtx_unlock(&sc->reg_lock);
11704 		if (rc != 0)
11705 			break;
11706 
11707 		rc = copyout(buf, dst, n);
11708 		if (rc != 0)
11709 			break;
11710 
11711 		dst += n;
11712 		remaining -= n;
11713 		addr += n;
11714 	}
11715 
11716 	free(buf, M_CXGBE);
11717 	return (rc);
11718 }
11719 #undef MAX_READ_BUF_SIZE
11720 
11721 static int
11722 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11723 {
11724 	int rc;
11725 
11726 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11727 		return (EINVAL);
11728 
11729 	if (i2cd->len > sizeof(i2cd->data))
11730 		return (EFBIG);
11731 
11732 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11733 	if (rc)
11734 		return (rc);
11735 	if (hw_off_limits(sc))
11736 		rc = ENXIO;
11737 	else
11738 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11739 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11740 	end_synchronized_op(sc, 0);
11741 
11742 	return (rc);
11743 }
11744 
11745 static int
11746 clear_stats(struct adapter *sc, u_int port_id)
11747 {
11748 	int i, v, chan_map;
11749 	struct port_info *pi;
11750 	struct vi_info *vi;
11751 	struct sge_rxq *rxq;
11752 	struct sge_txq *txq;
11753 	struct sge_wrq *wrq;
11754 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11755 	struct sge_ofld_txq *ofld_txq;
11756 #endif
11757 #ifdef TCP_OFFLOAD
11758 	struct sge_ofld_rxq *ofld_rxq;
11759 #endif
11760 
11761 	if (port_id >= sc->params.nports)
11762 		return (EINVAL);
11763 	pi = sc->port[port_id];
11764 	if (pi == NULL)
11765 		return (EIO);
11766 
11767 	mtx_lock(&sc->reg_lock);
11768 	if (!hw_off_limits(sc)) {
11769 		/* MAC stats */
11770 		t4_clr_port_stats(sc, pi->tx_chan);
11771 		if (is_t6(sc)) {
11772 			if (pi->fcs_reg != -1)
11773 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11774 			else
11775 				pi->stats.rx_fcs_err = 0;
11776 		}
11777 		for_each_vi(pi, v, vi) {
11778 			if (vi->flags & VI_INIT_DONE)
11779 				t4_clr_vi_stats(sc, vi->vin);
11780 		}
11781 		chan_map = pi->rx_e_chan_map;
11782 		v = 0;	/* reuse */
11783 		while (chan_map) {
11784 			i = ffs(chan_map) - 1;
11785 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11786 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11787 			chan_map &= ~(1 << i);
11788 		}
11789 	}
11790 	mtx_unlock(&sc->reg_lock);
11791 	pi->tx_parse_error = 0;
11792 	pi->tnl_cong_drops = 0;
11793 
11794 	/*
11795 	 * Since this command accepts a port, clear stats for
11796 	 * all VIs on this port.
11797 	 */
11798 	for_each_vi(pi, v, vi) {
11799 		if (vi->flags & VI_INIT_DONE) {
11800 
11801 			for_each_rxq(vi, i, rxq) {
11802 #if defined(INET) || defined(INET6)
11803 				rxq->lro.lro_queued = 0;
11804 				rxq->lro.lro_flushed = 0;
11805 #endif
11806 				rxq->rxcsum = 0;
11807 				rxq->vlan_extraction = 0;
11808 				rxq->vxlan_rxcsum = 0;
11809 
11810 				rxq->fl.cl_allocated = 0;
11811 				rxq->fl.cl_recycled = 0;
11812 				rxq->fl.cl_fast_recycled = 0;
11813 			}
11814 
11815 			for_each_txq(vi, i, txq) {
11816 				txq->txcsum = 0;
11817 				txq->tso_wrs = 0;
11818 				txq->vlan_insertion = 0;
11819 				txq->imm_wrs = 0;
11820 				txq->sgl_wrs = 0;
11821 				txq->txpkt_wrs = 0;
11822 				txq->txpkts0_wrs = 0;
11823 				txq->txpkts1_wrs = 0;
11824 				txq->txpkts0_pkts = 0;
11825 				txq->txpkts1_pkts = 0;
11826 				txq->txpkts_flush = 0;
11827 				txq->raw_wrs = 0;
11828 				txq->vxlan_tso_wrs = 0;
11829 				txq->vxlan_txcsum = 0;
11830 				txq->kern_tls_records = 0;
11831 				txq->kern_tls_short = 0;
11832 				txq->kern_tls_partial = 0;
11833 				txq->kern_tls_full = 0;
11834 				txq->kern_tls_octets = 0;
11835 				txq->kern_tls_waste = 0;
11836 				txq->kern_tls_options = 0;
11837 				txq->kern_tls_header = 0;
11838 				txq->kern_tls_fin = 0;
11839 				txq->kern_tls_fin_short = 0;
11840 				txq->kern_tls_cbc = 0;
11841 				txq->kern_tls_gcm = 0;
11842 				mp_ring_reset_stats(txq->r);
11843 			}
11844 
11845 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11846 			for_each_ofld_txq(vi, i, ofld_txq) {
11847 				ofld_txq->wrq.tx_wrs_direct = 0;
11848 				ofld_txq->wrq.tx_wrs_copied = 0;
11849 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
11850 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
11851 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
11852 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
11853 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
11854 			}
11855 #endif
11856 #ifdef TCP_OFFLOAD
11857 			for_each_ofld_rxq(vi, i, ofld_rxq) {
11858 				ofld_rxq->fl.cl_allocated = 0;
11859 				ofld_rxq->fl.cl_recycled = 0;
11860 				ofld_rxq->fl.cl_fast_recycled = 0;
11861 				counter_u64_zero(
11862 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
11863 				counter_u64_zero(
11864 				    ofld_rxq->rx_iscsi_ddp_setup_error);
11865 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
11866 				ofld_rxq->rx_iscsi_ddp_octets = 0;
11867 				ofld_rxq->rx_iscsi_fl_pdus = 0;
11868 				ofld_rxq->rx_iscsi_fl_octets = 0;
11869 				ofld_rxq->rx_toe_tls_records = 0;
11870 				ofld_rxq->rx_toe_tls_octets = 0;
11871 			}
11872 #endif
11873 
11874 			if (IS_MAIN_VI(vi)) {
11875 				wrq = &sc->sge.ctrlq[pi->port_id];
11876 				wrq->tx_wrs_direct = 0;
11877 				wrq->tx_wrs_copied = 0;
11878 			}
11879 		}
11880 	}
11881 
11882 	return (0);
11883 }
11884 
11885 static int
11886 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
11887 {
11888 #ifdef INET6
11889 	struct in6_addr in6;
11890 
11891 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
11892 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
11893 		return (0);
11894 	else
11895 		return (EIO);
11896 #else
11897 	return (ENOTSUP);
11898 #endif
11899 }
11900 
11901 static int
11902 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
11903 {
11904 #ifdef INET6
11905 	struct in6_addr in6;
11906 
11907 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
11908 	return (t4_release_clip_addr(sc, &in6));
11909 #else
11910 	return (ENOTSUP);
11911 #endif
11912 }
11913 
11914 int
11915 t4_os_find_pci_capability(struct adapter *sc, int cap)
11916 {
11917 	int i;
11918 
11919 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
11920 }
11921 
11922 int
11923 t4_os_pci_save_state(struct adapter *sc)
11924 {
11925 	device_t dev;
11926 	struct pci_devinfo *dinfo;
11927 
11928 	dev = sc->dev;
11929 	dinfo = device_get_ivars(dev);
11930 
11931 	pci_cfg_save(dev, dinfo, 0);
11932 	return (0);
11933 }
11934 
11935 int
11936 t4_os_pci_restore_state(struct adapter *sc)
11937 {
11938 	device_t dev;
11939 	struct pci_devinfo *dinfo;
11940 
11941 	dev = sc->dev;
11942 	dinfo = device_get_ivars(dev);
11943 
11944 	pci_cfg_restore(dev, dinfo);
11945 	return (0);
11946 }
11947 
11948 void
11949 t4_os_portmod_changed(struct port_info *pi)
11950 {
11951 	struct adapter *sc = pi->adapter;
11952 	struct vi_info *vi;
11953 	struct ifnet *ifp;
11954 	static const char *mod_str[] = {
11955 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
11956 	};
11957 
11958 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
11959 	    ("%s: port_type %u", __func__, pi->port_type));
11960 
11961 	vi = &pi->vi[0];
11962 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
11963 		PORT_LOCK(pi);
11964 		build_medialist(pi);
11965 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
11966 			fixup_link_config(pi);
11967 			apply_link_config(pi);
11968 		}
11969 		PORT_UNLOCK(pi);
11970 		end_synchronized_op(sc, LOCK_HELD);
11971 	}
11972 
11973 	ifp = vi->ifp;
11974 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
11975 		if_printf(ifp, "transceiver unplugged.\n");
11976 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
11977 		if_printf(ifp, "unknown transceiver inserted.\n");
11978 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
11979 		if_printf(ifp, "unsupported transceiver inserted.\n");
11980 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
11981 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
11982 		    port_top_speed(pi), mod_str[pi->mod_type]);
11983 	} else {
11984 		if_printf(ifp, "transceiver (type %d) inserted.\n",
11985 		    pi->mod_type);
11986 	}
11987 }
11988 
11989 void
11990 t4_os_link_changed(struct port_info *pi)
11991 {
11992 	struct vi_info *vi;
11993 	struct ifnet *ifp;
11994 	struct link_config *lc = &pi->link_cfg;
11995 	struct adapter *sc = pi->adapter;
11996 	int v;
11997 
11998 	PORT_LOCK_ASSERT_OWNED(pi);
11999 
12000 	if (is_t6(sc)) {
12001 		if (lc->link_ok) {
12002 			if (lc->speed > 25000 ||
12003 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12004 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12005 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12006 			} else {
12007 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12008 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12009 			}
12010 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12011 			pi->stats.rx_fcs_err = 0;
12012 		} else {
12013 			pi->fcs_reg = -1;
12014 		}
12015 	} else {
12016 		MPASS(pi->fcs_reg != -1);
12017 		MPASS(pi->fcs_base == 0);
12018 	}
12019 
12020 	for_each_vi(pi, v, vi) {
12021 		ifp = vi->ifp;
12022 		if (ifp == NULL)
12023 			continue;
12024 
12025 		if (lc->link_ok) {
12026 			ifp->if_baudrate = IF_Mbps(lc->speed);
12027 			if_link_state_change(ifp, LINK_STATE_UP);
12028 		} else {
12029 			if_link_state_change(ifp, LINK_STATE_DOWN);
12030 		}
12031 	}
12032 }
12033 
12034 void
12035 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12036 {
12037 	struct adapter *sc;
12038 
12039 	sx_slock(&t4_list_lock);
12040 	SLIST_FOREACH(sc, &t4_list, link) {
12041 		/*
12042 		 * func should not make any assumptions about what state sc is
12043 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12044 		 */
12045 		func(sc, arg);
12046 	}
12047 	sx_sunlock(&t4_list_lock);
12048 }
12049 
12050 static int
12051 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12052     struct thread *td)
12053 {
12054 	int rc;
12055 	struct adapter *sc = dev->si_drv1;
12056 
12057 	rc = priv_check(td, PRIV_DRIVER);
12058 	if (rc != 0)
12059 		return (rc);
12060 
12061 	switch (cmd) {
12062 	case CHELSIO_T4_GETREG: {
12063 		struct t4_reg *edata = (struct t4_reg *)data;
12064 
12065 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12066 			return (EFAULT);
12067 
12068 		mtx_lock(&sc->reg_lock);
12069 		if (hw_off_limits(sc))
12070 			rc = ENXIO;
12071 		else if (edata->size == 4)
12072 			edata->val = t4_read_reg(sc, edata->addr);
12073 		else if (edata->size == 8)
12074 			edata->val = t4_read_reg64(sc, edata->addr);
12075 		else
12076 			rc = EINVAL;
12077 		mtx_unlock(&sc->reg_lock);
12078 
12079 		break;
12080 	}
12081 	case CHELSIO_T4_SETREG: {
12082 		struct t4_reg *edata = (struct t4_reg *)data;
12083 
12084 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12085 			return (EFAULT);
12086 
12087 		mtx_lock(&sc->reg_lock);
12088 		if (hw_off_limits(sc))
12089 			rc = ENXIO;
12090 		else if (edata->size == 4) {
12091 			if (edata->val & 0xffffffff00000000)
12092 				rc = EINVAL;
12093 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12094 		} else if (edata->size == 8)
12095 			t4_write_reg64(sc, edata->addr, edata->val);
12096 		else
12097 			rc = EINVAL;
12098 		mtx_unlock(&sc->reg_lock);
12099 
12100 		break;
12101 	}
12102 	case CHELSIO_T4_REGDUMP: {
12103 		struct t4_regdump *regs = (struct t4_regdump *)data;
12104 		int reglen = t4_get_regs_len(sc);
12105 		uint8_t *buf;
12106 
12107 		if (regs->len < reglen) {
12108 			regs->len = reglen; /* hint to the caller */
12109 			return (ENOBUFS);
12110 		}
12111 
12112 		regs->len = reglen;
12113 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12114 		mtx_lock(&sc->reg_lock);
12115 		if (hw_off_limits(sc))
12116 			rc = ENXIO;
12117 		else
12118 			get_regs(sc, regs, buf);
12119 		mtx_unlock(&sc->reg_lock);
12120 		if (rc == 0)
12121 			rc = copyout(buf, regs->data, reglen);
12122 		free(buf, M_CXGBE);
12123 		break;
12124 	}
12125 	case CHELSIO_T4_GET_FILTER_MODE:
12126 		rc = get_filter_mode(sc, (uint32_t *)data);
12127 		break;
12128 	case CHELSIO_T4_SET_FILTER_MODE:
12129 		rc = set_filter_mode(sc, *(uint32_t *)data);
12130 		break;
12131 	case CHELSIO_T4_SET_FILTER_MASK:
12132 		rc = set_filter_mask(sc, *(uint32_t *)data);
12133 		break;
12134 	case CHELSIO_T4_GET_FILTER:
12135 		rc = get_filter(sc, (struct t4_filter *)data);
12136 		break;
12137 	case CHELSIO_T4_SET_FILTER:
12138 		rc = set_filter(sc, (struct t4_filter *)data);
12139 		break;
12140 	case CHELSIO_T4_DEL_FILTER:
12141 		rc = del_filter(sc, (struct t4_filter *)data);
12142 		break;
12143 	case CHELSIO_T4_GET_SGE_CONTEXT:
12144 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12145 		break;
12146 	case CHELSIO_T4_LOAD_FW:
12147 		rc = load_fw(sc, (struct t4_data *)data);
12148 		break;
12149 	case CHELSIO_T4_GET_MEM:
12150 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12151 		break;
12152 	case CHELSIO_T4_GET_I2C:
12153 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12154 		break;
12155 	case CHELSIO_T4_CLEAR_STATS:
12156 		rc = clear_stats(sc, *(uint32_t *)data);
12157 		break;
12158 	case CHELSIO_T4_SCHED_CLASS:
12159 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12160 		break;
12161 	case CHELSIO_T4_SCHED_QUEUE:
12162 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12163 		break;
12164 	case CHELSIO_T4_GET_TRACER:
12165 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12166 		break;
12167 	case CHELSIO_T4_SET_TRACER:
12168 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12169 		break;
12170 	case CHELSIO_T4_LOAD_CFG:
12171 		rc = load_cfg(sc, (struct t4_data *)data);
12172 		break;
12173 	case CHELSIO_T4_LOAD_BOOT:
12174 		rc = load_boot(sc, (struct t4_bootrom *)data);
12175 		break;
12176 	case CHELSIO_T4_LOAD_BOOTCFG:
12177 		rc = load_bootcfg(sc, (struct t4_data *)data);
12178 		break;
12179 	case CHELSIO_T4_CUDBG_DUMP:
12180 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12181 		break;
12182 	case CHELSIO_T4_SET_OFLD_POLICY:
12183 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12184 		break;
12185 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12186 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12187 		break;
12188 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12189 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12190 		break;
12191 	default:
12192 		rc = ENOTTY;
12193 	}
12194 
12195 	return (rc);
12196 }
12197 
12198 #ifdef TCP_OFFLOAD
12199 static int
12200 toe_capability(struct vi_info *vi, bool enable)
12201 {
12202 	int rc;
12203 	struct port_info *pi = vi->pi;
12204 	struct adapter *sc = pi->adapter;
12205 
12206 	ASSERT_SYNCHRONIZED_OP(sc);
12207 
12208 	if (!is_offload(sc))
12209 		return (ENODEV);
12210 	if (hw_off_limits(sc))
12211 		return (ENXIO);
12212 
12213 	if (enable) {
12214 #ifdef KERN_TLS
12215 		if (sc->flags & KERN_TLS_ON) {
12216 			int i, j, n;
12217 			struct port_info *p;
12218 			struct vi_info *v;
12219 
12220 			/*
12221 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12222 			 * on any ifnet.
12223 			 */
12224 			n = 0;
12225 			for_each_port(sc, i) {
12226 				p = sc->port[i];
12227 				for_each_vi(p, j, v) {
12228 					if (v->ifp->if_capenable & IFCAP_TXTLS) {
12229 						CH_WARN(sc,
12230 						    "%s has NIC TLS enabled.\n",
12231 						    device_get_nameunit(v->dev));
12232 						n++;
12233 					}
12234 				}
12235 			}
12236 			if (n > 0) {
12237 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12238 				    "associated with this adapter before "
12239 				    "trying to enable TOE.\n");
12240 				return (EAGAIN);
12241 			}
12242 			rc = t4_config_kern_tls(sc, false);
12243 			if (rc)
12244 				return (rc);
12245 		}
12246 #endif
12247 		if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
12248 			/* TOE is already enabled. */
12249 			return (0);
12250 		}
12251 
12252 		/*
12253 		 * We need the port's queues around so that we're able to send
12254 		 * and receive CPLs to/from the TOE even if the ifnet for this
12255 		 * port has never been UP'd administratively.
12256 		 */
12257 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12258 			return (rc);
12259 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12260 		    ((rc = vi_init(&pi->vi[0])) != 0))
12261 			return (rc);
12262 
12263 		if (isset(&sc->offload_map, pi->port_id)) {
12264 			/* TOE is enabled on another VI of this port. */
12265 			pi->uld_vis++;
12266 			return (0);
12267 		}
12268 
12269 		if (!uld_active(sc, ULD_TOM)) {
12270 			rc = t4_activate_uld(sc, ULD_TOM);
12271 			if (rc == EAGAIN) {
12272 				log(LOG_WARNING,
12273 				    "You must kldload t4_tom.ko before trying "
12274 				    "to enable TOE on a cxgbe interface.\n");
12275 			}
12276 			if (rc != 0)
12277 				return (rc);
12278 			KASSERT(sc->tom_softc != NULL,
12279 			    ("%s: TOM activated but softc NULL", __func__));
12280 			KASSERT(uld_active(sc, ULD_TOM),
12281 			    ("%s: TOM activated but flag not set", __func__));
12282 		}
12283 
12284 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12285 		if (!uld_active(sc, ULD_IWARP))
12286 			(void) t4_activate_uld(sc, ULD_IWARP);
12287 		if (!uld_active(sc, ULD_ISCSI))
12288 			(void) t4_activate_uld(sc, ULD_ISCSI);
12289 
12290 		pi->uld_vis++;
12291 		setbit(&sc->offload_map, pi->port_id);
12292 	} else {
12293 		pi->uld_vis--;
12294 
12295 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12296 			return (0);
12297 
12298 		KASSERT(uld_active(sc, ULD_TOM),
12299 		    ("%s: TOM never initialized?", __func__));
12300 		clrbit(&sc->offload_map, pi->port_id);
12301 	}
12302 
12303 	return (0);
12304 }
12305 
12306 /*
12307  * Add an upper layer driver to the global list.
12308  */
12309 int
12310 t4_register_uld(struct uld_info *ui)
12311 {
12312 	int rc = 0;
12313 	struct uld_info *u;
12314 
12315 	sx_xlock(&t4_uld_list_lock);
12316 	SLIST_FOREACH(u, &t4_uld_list, link) {
12317 	    if (u->uld_id == ui->uld_id) {
12318 		    rc = EEXIST;
12319 		    goto done;
12320 	    }
12321 	}
12322 
12323 	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
12324 	ui->refcount = 0;
12325 done:
12326 	sx_xunlock(&t4_uld_list_lock);
12327 	return (rc);
12328 }
12329 
12330 int
12331 t4_unregister_uld(struct uld_info *ui)
12332 {
12333 	int rc = EINVAL;
12334 	struct uld_info *u;
12335 
12336 	sx_xlock(&t4_uld_list_lock);
12337 
12338 	SLIST_FOREACH(u, &t4_uld_list, link) {
12339 	    if (u == ui) {
12340 		    if (ui->refcount > 0) {
12341 			    rc = EBUSY;
12342 			    goto done;
12343 		    }
12344 
12345 		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
12346 		    rc = 0;
12347 		    goto done;
12348 	    }
12349 	}
12350 done:
12351 	sx_xunlock(&t4_uld_list_lock);
12352 	return (rc);
12353 }
12354 
12355 int
12356 t4_activate_uld(struct adapter *sc, int id)
12357 {
12358 	int rc;
12359 	struct uld_info *ui;
12360 
12361 	ASSERT_SYNCHRONIZED_OP(sc);
12362 
12363 	if (id < 0 || id > ULD_MAX)
12364 		return (EINVAL);
12365 	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
12366 
12367 	sx_slock(&t4_uld_list_lock);
12368 
12369 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12370 		if (ui->uld_id == id) {
12371 			if (!(sc->flags & FULL_INIT_DONE)) {
12372 				rc = adapter_init(sc);
12373 				if (rc != 0)
12374 					break;
12375 			}
12376 
12377 			rc = ui->activate(sc);
12378 			if (rc == 0) {
12379 				setbit(&sc->active_ulds, id);
12380 				ui->refcount++;
12381 			}
12382 			break;
12383 		}
12384 	}
12385 
12386 	sx_sunlock(&t4_uld_list_lock);
12387 
12388 	return (rc);
12389 }
12390 
12391 int
12392 t4_deactivate_uld(struct adapter *sc, int id)
12393 {
12394 	int rc;
12395 	struct uld_info *ui;
12396 
12397 	ASSERT_SYNCHRONIZED_OP(sc);
12398 
12399 	if (id < 0 || id > ULD_MAX)
12400 		return (EINVAL);
12401 	rc = ENXIO;
12402 
12403 	sx_slock(&t4_uld_list_lock);
12404 
12405 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12406 		if (ui->uld_id == id) {
12407 			rc = ui->deactivate(sc);
12408 			if (rc == 0) {
12409 				clrbit(&sc->active_ulds, id);
12410 				ui->refcount--;
12411 			}
12412 			break;
12413 		}
12414 	}
12415 
12416 	sx_sunlock(&t4_uld_list_lock);
12417 
12418 	return (rc);
12419 }
12420 
12421 static void
12422 t4_async_event(void *arg, int n)
12423 {
12424 	struct uld_info *ui;
12425 	struct adapter *sc = (struct adapter *)arg;
12426 
12427 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
12428 		return;
12429 	sx_slock(&t4_uld_list_lock);
12430 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12431 		if (ui->uld_id == ULD_IWARP) {
12432 			ui->async_event(sc);
12433 			break;
12434 		}
12435 	}
12436 	sx_sunlock(&t4_uld_list_lock);
12437 	end_synchronized_op(sc, 0);
12438 }
12439 
12440 int
12441 uld_active(struct adapter *sc, int uld_id)
12442 {
12443 
12444 	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
12445 
12446 	return (isset(&sc->active_ulds, uld_id));
12447 }
12448 #endif
12449 
12450 #ifdef KERN_TLS
12451 static int
12452 ktls_capability(struct adapter *sc, bool enable)
12453 {
12454 	ASSERT_SYNCHRONIZED_OP(sc);
12455 
12456 	if (!is_ktls(sc))
12457 		return (ENODEV);
12458 	if (hw_off_limits(sc))
12459 		return (ENXIO);
12460 
12461 	if (enable) {
12462 		if (sc->flags & KERN_TLS_ON)
12463 			return (0);	/* already on */
12464 		if (sc->offload_map != 0) {
12465 			CH_WARN(sc,
12466 			    "Disable TOE on all interfaces associated with "
12467 			    "this adapter before trying to enable NIC TLS.\n");
12468 			return (EAGAIN);
12469 		}
12470 		return (t4_config_kern_tls(sc, true));
12471 	} else {
12472 		/*
12473 		 * Nothing to do for disable.  If TOE is enabled sometime later
12474 		 * then toe_capability will reconfigure the hardware.
12475 		 */
12476 		return (0);
12477 	}
12478 }
12479 #endif
12480 
12481 /*
12482  * t  = ptr to tunable.
12483  * nc = number of CPUs.
12484  * c  = compiled in default for that tunable.
12485  */
12486 static void
12487 calculate_nqueues(int *t, int nc, const int c)
12488 {
12489 	int nq;
12490 
12491 	if (*t > 0)
12492 		return;
12493 	nq = *t < 0 ? -*t : c;
12494 	*t = min(nc, nq);
12495 }
12496 
12497 /*
12498  * Come up with reasonable defaults for some of the tunables, provided they're
12499  * not set by the user (in which case we'll use the values as is).
12500  */
12501 static void
12502 tweak_tunables(void)
12503 {
12504 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12505 
12506 	if (t4_ntxq < 1) {
12507 #ifdef RSS
12508 		t4_ntxq = rss_getnumbuckets();
12509 #else
12510 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12511 #endif
12512 	}
12513 
12514 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12515 
12516 	if (t4_nrxq < 1) {
12517 #ifdef RSS
12518 		t4_nrxq = rss_getnumbuckets();
12519 #else
12520 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12521 #endif
12522 	}
12523 
12524 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12525 
12526 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12527 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12528 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12529 #endif
12530 #ifdef TCP_OFFLOAD
12531 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12532 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12533 #endif
12534 
12535 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12536 	if (t4_toecaps_allowed == -1)
12537 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12538 #else
12539 	if (t4_toecaps_allowed == -1)
12540 		t4_toecaps_allowed = 0;
12541 #endif
12542 
12543 #ifdef TCP_OFFLOAD
12544 	if (t4_rdmacaps_allowed == -1) {
12545 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12546 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12547 	}
12548 
12549 	if (t4_iscsicaps_allowed == -1) {
12550 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12551 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12552 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12553 	}
12554 
12555 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12556 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12557 
12558 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12559 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12560 
12561 	if (t4_toe_tls_rx_timeout < 0)
12562 		t4_toe_tls_rx_timeout = 0;
12563 #else
12564 	if (t4_rdmacaps_allowed == -1)
12565 		t4_rdmacaps_allowed = 0;
12566 
12567 	if (t4_iscsicaps_allowed == -1)
12568 		t4_iscsicaps_allowed = 0;
12569 #endif
12570 
12571 #ifdef DEV_NETMAP
12572 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12573 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12574 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12575 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12576 #endif
12577 
12578 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12579 		t4_tmr_idx = TMR_IDX;
12580 
12581 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12582 		t4_pktc_idx = PKTC_IDX;
12583 
12584 	if (t4_qsize_txq < 128)
12585 		t4_qsize_txq = 128;
12586 
12587 	if (t4_qsize_rxq < 128)
12588 		t4_qsize_rxq = 128;
12589 	while (t4_qsize_rxq & 7)
12590 		t4_qsize_rxq++;
12591 
12592 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12593 
12594 	/*
12595 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12596 	 * VI for the port.  The rest are additional virtual interfaces on the
12597 	 * same physical port.  Note that the main VI does not have native
12598 	 * netmap support but the extra VIs do.
12599 	 *
12600 	 * Limit the number of VIs per port to the number of available
12601 	 * MAC addresses per port.
12602 	 */
12603 	if (t4_num_vis < 1)
12604 		t4_num_vis = 1;
12605 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12606 		t4_num_vis = nitems(vi_mac_funcs);
12607 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12608 	}
12609 
12610 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12611 		pcie_relaxed_ordering = 1;
12612 #if defined(__i386__) || defined(__amd64__)
12613 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12614 			pcie_relaxed_ordering = 0;
12615 #endif
12616 	}
12617 }
12618 
12619 #ifdef DDB
12620 static void
12621 t4_dump_tcb(struct adapter *sc, int tid)
12622 {
12623 	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
12624 
12625 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12626 	save = t4_read_reg(sc, reg);
12627 	base = sc->memwin[2].mw_base;
12628 
12629 	/* Dump TCB for the tid */
12630 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12631 	tcb_addr += tid * TCB_SIZE;
12632 
12633 	if (is_t4(sc)) {
12634 		pf = 0;
12635 		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
12636 	} else {
12637 		pf = V_PFNUM(sc->pf);
12638 		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
12639 	}
12640 	t4_write_reg(sc, reg, win_pos | pf);
12641 	t4_read_reg(sc, reg);
12642 
12643 	off = tcb_addr - win_pos;
12644 	for (i = 0; i < 4; i++) {
12645 		uint32_t buf[8];
12646 		for (j = 0; j < 8; j++, off += 4)
12647 			buf[j] = htonl(t4_read_reg(sc, base + off));
12648 
12649 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12650 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12651 		    buf[7]);
12652 	}
12653 
12654 	t4_write_reg(sc, reg, save);
12655 	t4_read_reg(sc, reg);
12656 }
12657 
12658 static void
12659 t4_dump_devlog(struct adapter *sc)
12660 {
12661 	struct devlog_params *dparams = &sc->params.devlog;
12662 	struct fw_devlog_e e;
12663 	int i, first, j, m, nentries, rc;
12664 	uint64_t ftstamp = UINT64_MAX;
12665 
12666 	if (dparams->start == 0) {
12667 		db_printf("devlog params not valid\n");
12668 		return;
12669 	}
12670 
12671 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12672 	m = fwmtype_to_hwmtype(dparams->memtype);
12673 
12674 	/* Find the first entry. */
12675 	first = -1;
12676 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12677 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12678 		    sizeof(e), (void *)&e);
12679 		if (rc != 0)
12680 			break;
12681 
12682 		if (e.timestamp == 0)
12683 			break;
12684 
12685 		e.timestamp = be64toh(e.timestamp);
12686 		if (e.timestamp < ftstamp) {
12687 			ftstamp = e.timestamp;
12688 			first = i;
12689 		}
12690 	}
12691 
12692 	if (first == -1)
12693 		return;
12694 
12695 	i = first;
12696 	do {
12697 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12698 		    sizeof(e), (void *)&e);
12699 		if (rc != 0)
12700 			return;
12701 
12702 		if (e.timestamp == 0)
12703 			return;
12704 
12705 		e.timestamp = be64toh(e.timestamp);
12706 		e.seqno = be32toh(e.seqno);
12707 		for (j = 0; j < 8; j++)
12708 			e.params[j] = be32toh(e.params[j]);
12709 
12710 		db_printf("%10d  %15ju  %8s  %8s  ",
12711 		    e.seqno, e.timestamp,
12712 		    (e.level < nitems(devlog_level_strings) ?
12713 			devlog_level_strings[e.level] : "UNKNOWN"),
12714 		    (e.facility < nitems(devlog_facility_strings) ?
12715 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12716 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12717 		    e.params[3], e.params[4], e.params[5], e.params[6],
12718 		    e.params[7]);
12719 
12720 		if (++i == nentries)
12721 			i = 0;
12722 	} while (i != first && !db_pager_quit);
12723 }
12724 
12725 static struct command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
12726 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
12727 
12728 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
12729 {
12730 	device_t dev;
12731 	int t;
12732 	bool valid;
12733 
12734 	valid = false;
12735 	t = db_read_token();
12736 	if (t == tIDENT) {
12737 		dev = device_lookup_by_name(db_tok_string);
12738 		valid = true;
12739 	}
12740 	db_skip_to_eol();
12741 	if (!valid) {
12742 		db_printf("usage: show t4 devlog <nexus>\n");
12743 		return;
12744 	}
12745 
12746 	if (dev == NULL) {
12747 		db_printf("device not found\n");
12748 		return;
12749 	}
12750 
12751 	t4_dump_devlog(device_get_softc(dev));
12752 }
12753 
12754 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
12755 {
12756 	device_t dev;
12757 	int radix, tid, t;
12758 	bool valid;
12759 
12760 	valid = false;
12761 	radix = db_radix;
12762 	db_radix = 10;
12763 	t = db_read_token();
12764 	if (t == tIDENT) {
12765 		dev = device_lookup_by_name(db_tok_string);
12766 		t = db_read_token();
12767 		if (t == tNUMBER) {
12768 			tid = db_tok_number;
12769 			valid = true;
12770 		}
12771 	}
12772 	db_radix = radix;
12773 	db_skip_to_eol();
12774 	if (!valid) {
12775 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
12776 		return;
12777 	}
12778 
12779 	if (dev == NULL) {
12780 		db_printf("device not found\n");
12781 		return;
12782 	}
12783 	if (tid < 0) {
12784 		db_printf("invalid tid\n");
12785 		return;
12786 	}
12787 
12788 	t4_dump_tcb(device_get_softc(dev), tid);
12789 }
12790 #endif
12791 
12792 static eventhandler_tag vxlan_start_evtag;
12793 static eventhandler_tag vxlan_stop_evtag;
12794 
12795 struct vxlan_evargs {
12796 	struct ifnet *ifp;
12797 	uint16_t port;
12798 };
12799 
12800 static void
12801 enable_vxlan_rx(struct adapter *sc)
12802 {
12803 	int i, rc;
12804 	struct port_info *pi;
12805 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
12806 
12807 	ASSERT_SYNCHRONIZED_OP(sc);
12808 
12809 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
12810 	    F_VXLAN_EN);
12811 	for_each_port(sc, i) {
12812 		pi = sc->port[i];
12813 		if (pi->vxlan_tcam_entry == true)
12814 			continue;
12815 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
12816 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
12817 		    true);
12818 		if (rc < 0) {
12819 			rc = -rc;
12820 			CH_ERR(&pi->vi[0],
12821 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
12822 		} else {
12823 			MPASS(rc == sc->rawf_base + pi->port_id);
12824 			pi->vxlan_tcam_entry = true;
12825 		}
12826 	}
12827 }
12828 
12829 static void
12830 t4_vxlan_start(struct adapter *sc, void *arg)
12831 {
12832 	struct vxlan_evargs *v = arg;
12833 
12834 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
12835 		return;
12836 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
12837 		return;
12838 
12839 	if (sc->vxlan_refcount == 0) {
12840 		sc->vxlan_port = v->port;
12841 		sc->vxlan_refcount = 1;
12842 		if (!hw_off_limits(sc))
12843 			enable_vxlan_rx(sc);
12844 	} else if (sc->vxlan_port == v->port) {
12845 		sc->vxlan_refcount++;
12846 	} else {
12847 		CH_ERR(sc, "VXLAN already configured on port  %d; "
12848 		    "ignoring attempt to configure it on port %d\n",
12849 		    sc->vxlan_port, v->port);
12850 	}
12851 	end_synchronized_op(sc, 0);
12852 }
12853 
12854 static void
12855 t4_vxlan_stop(struct adapter *sc, void *arg)
12856 {
12857 	struct vxlan_evargs *v = arg;
12858 
12859 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
12860 		return;
12861 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
12862 		return;
12863 
12864 	/*
12865 	 * VXLANs may have been configured before the driver was loaded so we
12866 	 * may see more stops than starts.  This is not handled cleanly but at
12867 	 * least we keep the refcount sane.
12868 	 */
12869 	if (sc->vxlan_port != v->port)
12870 		goto done;
12871 	if (sc->vxlan_refcount == 0) {
12872 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
12873 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
12874 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
12875 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
12876 done:
12877 	end_synchronized_op(sc, 0);
12878 }
12879 
12880 static void
12881 t4_vxlan_start_handler(void *arg __unused, struct ifnet *ifp,
12882     sa_family_t family, u_int port)
12883 {
12884 	struct vxlan_evargs v;
12885 
12886 	MPASS(family == AF_INET || family == AF_INET6);
12887 	v.ifp = ifp;
12888 	v.port = port;
12889 
12890 	t4_iterate(t4_vxlan_start, &v);
12891 }
12892 
12893 static void
12894 t4_vxlan_stop_handler(void *arg __unused, struct ifnet *ifp, sa_family_t family,
12895     u_int port)
12896 {
12897 	struct vxlan_evargs v;
12898 
12899 	MPASS(family == AF_INET || family == AF_INET6);
12900 	v.ifp = ifp;
12901 	v.port = port;
12902 
12903 	t4_iterate(t4_vxlan_stop, &v);
12904 }
12905 
12906 
12907 static struct sx mlu;	/* mod load unload */
12908 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
12909 
12910 static int
12911 mod_event(module_t mod, int cmd, void *arg)
12912 {
12913 	int rc = 0;
12914 	static int loaded = 0;
12915 
12916 	switch (cmd) {
12917 	case MOD_LOAD:
12918 		sx_xlock(&mlu);
12919 		if (loaded++ == 0) {
12920 			t4_sge_modload();
12921 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
12922 			    t4_filter_rpl, CPL_COOKIE_FILTER);
12923 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
12924 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
12925 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
12926 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
12927 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
12928 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
12929 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
12930 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
12931 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
12932 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
12933 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
12934 			    do_smt_write_rpl);
12935 			sx_init(&t4_list_lock, "T4/T5 adapters");
12936 			SLIST_INIT(&t4_list);
12937 			callout_init(&fatal_callout, 1);
12938 #ifdef TCP_OFFLOAD
12939 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
12940 			SLIST_INIT(&t4_uld_list);
12941 #endif
12942 #ifdef INET6
12943 			t4_clip_modload();
12944 #endif
12945 #ifdef KERN_TLS
12946 			t6_ktls_modload();
12947 #endif
12948 			t4_tracer_modload();
12949 			tweak_tunables();
12950 			vxlan_start_evtag =
12951 			    EVENTHANDLER_REGISTER(vxlan_start,
12952 				t4_vxlan_start_handler, NULL,
12953 				EVENTHANDLER_PRI_ANY);
12954 			vxlan_stop_evtag =
12955 			    EVENTHANDLER_REGISTER(vxlan_stop,
12956 				t4_vxlan_stop_handler, NULL,
12957 				EVENTHANDLER_PRI_ANY);
12958 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
12959 			    taskqueue_thread_enqueue, &reset_tq);
12960 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
12961 			    "t4_rst_thr");
12962 		}
12963 		sx_xunlock(&mlu);
12964 		break;
12965 
12966 	case MOD_UNLOAD:
12967 		sx_xlock(&mlu);
12968 		if (--loaded == 0) {
12969 			int tries;
12970 
12971 			taskqueue_free(reset_tq);
12972 			sx_slock(&t4_list_lock);
12973 			if (!SLIST_EMPTY(&t4_list)) {
12974 				rc = EBUSY;
12975 				sx_sunlock(&t4_list_lock);
12976 				goto done_unload;
12977 			}
12978 #ifdef TCP_OFFLOAD
12979 			sx_slock(&t4_uld_list_lock);
12980 			if (!SLIST_EMPTY(&t4_uld_list)) {
12981 				rc = EBUSY;
12982 				sx_sunlock(&t4_uld_list_lock);
12983 				sx_sunlock(&t4_list_lock);
12984 				goto done_unload;
12985 			}
12986 #endif
12987 			tries = 0;
12988 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
12989 				uprintf("%ju clusters with custom free routine "
12990 				    "still is use.\n", t4_sge_extfree_refs());
12991 				pause("t4unload", 2 * hz);
12992 			}
12993 #ifdef TCP_OFFLOAD
12994 			sx_sunlock(&t4_uld_list_lock);
12995 #endif
12996 			sx_sunlock(&t4_list_lock);
12997 
12998 			if (t4_sge_extfree_refs() == 0) {
12999 				EVENTHANDLER_DEREGISTER(vxlan_start,
13000 				    vxlan_start_evtag);
13001 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13002 				    vxlan_stop_evtag);
13003 				t4_tracer_modunload();
13004 #ifdef KERN_TLS
13005 				t6_ktls_modunload();
13006 #endif
13007 #ifdef INET6
13008 				t4_clip_modunload();
13009 #endif
13010 #ifdef TCP_OFFLOAD
13011 				sx_destroy(&t4_uld_list_lock);
13012 #endif
13013 				sx_destroy(&t4_list_lock);
13014 				t4_sge_modunload();
13015 				loaded = 0;
13016 			} else {
13017 				rc = EBUSY;
13018 				loaded++;	/* undo earlier decrement */
13019 			}
13020 		}
13021 done_unload:
13022 		sx_xunlock(&mlu);
13023 		break;
13024 	}
13025 
13026 	return (rc);
13027 }
13028 
13029 static devclass_t t4_devclass, t5_devclass, t6_devclass;
13030 static devclass_t cxgbe_devclass, cxl_devclass, cc_devclass;
13031 static devclass_t vcxgbe_devclass, vcxl_devclass, vcc_devclass;
13032 
13033 DRIVER_MODULE(t4nex, pci, t4_driver, t4_devclass, mod_event, 0);
13034 MODULE_VERSION(t4nex, 1);
13035 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13036 #ifdef DEV_NETMAP
13037 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13038 #endif /* DEV_NETMAP */
13039 
13040 DRIVER_MODULE(t5nex, pci, t5_driver, t5_devclass, mod_event, 0);
13041 MODULE_VERSION(t5nex, 1);
13042 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13043 #ifdef DEV_NETMAP
13044 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13045 #endif /* DEV_NETMAP */
13046 
13047 DRIVER_MODULE(t6nex, pci, t6_driver, t6_devclass, mod_event, 0);
13048 MODULE_VERSION(t6nex, 1);
13049 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13050 #ifdef DEV_NETMAP
13051 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13052 #endif /* DEV_NETMAP */
13053 
13054 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, cxgbe_devclass, 0, 0);
13055 MODULE_VERSION(cxgbe, 1);
13056 
13057 DRIVER_MODULE(cxl, t5nex, cxl_driver, cxl_devclass, 0, 0);
13058 MODULE_VERSION(cxl, 1);
13059 
13060 DRIVER_MODULE(cc, t6nex, cc_driver, cc_devclass, 0, 0);
13061 MODULE_VERSION(cc, 1);
13062 
13063 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, vcxgbe_devclass, 0, 0);
13064 MODULE_VERSION(vcxgbe, 1);
13065 
13066 DRIVER_MODULE(vcxl, cxl, vcxl_driver, vcxl_devclass, 0, 0);
13067 MODULE_VERSION(vcxl, 1);
13068 
13069 DRIVER_MODULE(vcc, cc, vcc_driver, vcc_devclass, 0, 0);
13070 MODULE_VERSION(vcc, 1);
13071