xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision 3332f1b444d4a73238e9f59cca27bfc95fe936bd)
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  * Controls when the driver sets the FORCE_FEC bit in the L1_CFG32 that it
522  * issues to the firmware.  If the firmware doesn't support FORCE_FEC then the
523  * driver runs as if this is set to 0.
524  * -1 to set FORCE_FEC iff requested_fec != AUTO. Multiple FEC bits are okay.
525  *  0 to never set FORCE_FEC. requested_fec = AUTO means use the hint from the
526  *    transceiver. Multiple FEC bits may not be okay but will be passed on to
527  *    the firmware anyway (may result in l1cfg errors with old firmwares).
528  *  1 to always set FORCE_FEC. Multiple FEC bits are okay. requested_fec = AUTO
529  *    means set all FEC bits that are valid for the speed.
530  */
531 static int t4_force_fec = -1;
532 SYSCTL_INT(_hw_cxgbe, OID_AUTO, force_fec, CTLFLAG_RDTUN, &t4_force_fec, 0,
533     "Controls the use of FORCE_FEC bit in L1 configuration.");
534 
535 /*
536  * Link autonegotiation.
537  * -1 to run with the firmware default.
538  *  0 to disable.
539  *  1 to enable.
540  */
541 static int t4_autoneg = -1;
542 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
543     "Link autonegotiation");
544 
545 /*
546  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
547  * encouraged respectively).  '-n' is the same as 'n' except the firmware
548  * version used in the checks is read from the firmware bundled with the driver.
549  */
550 static int t4_fw_install = 1;
551 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
552     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
553 
554 /*
555  * ASIC features that will be used.  Disable the ones you don't want so that the
556  * chip resources aren't wasted on features that will not be used.
557  */
558 static int t4_nbmcaps_allowed = 0;
559 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
560     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
561 
562 static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
563 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
564     &t4_linkcaps_allowed, 0, "Default link capabilities");
565 
566 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
567     FW_CAPS_CONFIG_SWITCH_EGRESS;
568 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
569     &t4_switchcaps_allowed, 0, "Default switch capabilities");
570 
571 #ifdef RATELIMIT
572 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
573 	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
574 #else
575 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
576 	FW_CAPS_CONFIG_NIC_HASHFILTER;
577 #endif
578 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
579     &t4_niccaps_allowed, 0, "Default NIC capabilities");
580 
581 static int t4_toecaps_allowed = -1;
582 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
583     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
584 
585 static int t4_rdmacaps_allowed = -1;
586 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
587     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
588 
589 static int t4_cryptocaps_allowed = -1;
590 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
591     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
592 
593 static int t4_iscsicaps_allowed = -1;
594 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
595     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
596 
597 static int t4_fcoecaps_allowed = 0;
598 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
599     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
600 
601 static int t5_write_combine = 0;
602 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
603     0, "Use WC instead of UC for BAR2");
604 
605 static int t4_num_vis = 1;
606 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
607     "Number of VIs per port");
608 
609 /*
610  * PCIe Relaxed Ordering.
611  * -1: driver should figure out a good value.
612  * 0: disable RO.
613  * 1: enable RO.
614  * 2: leave RO alone.
615  */
616 static int pcie_relaxed_ordering = -1;
617 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
618     &pcie_relaxed_ordering, 0,
619     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
620 
621 static int t4_panic_on_fatal_err = 0;
622 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
623     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
624 
625 static int t4_reset_on_fatal_err = 0;
626 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
627     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
628 
629 static int t4_tx_vm_wr = 0;
630 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
631     "Use VM work requests to transmit packets.");
632 
633 /*
634  * Set to non-zero to enable the attack filter.  A packet that matches any of
635  * these conditions will get dropped on ingress:
636  * 1) IP && source address == destination address.
637  * 2) TCP/IP && source address is not a unicast address.
638  * 3) TCP/IP && destination address is not a unicast address.
639  * 4) IP && source address is loopback (127.x.y.z).
640  * 5) IP && destination address is loopback (127.x.y.z).
641  * 6) IPv6 && source address == destination address.
642  * 7) IPv6 && source address is not a unicast address.
643  * 8) IPv6 && source address is loopback (::1/128).
644  * 9) IPv6 && destination address is loopback (::1/128).
645  * 10) IPv6 && source address is unspecified (::/128).
646  * 11) IPv6 && destination address is unspecified (::/128).
647  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
648  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
649  */
650 static int t4_attack_filter = 0;
651 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
652     &t4_attack_filter, 0, "Drop suspicious traffic");
653 
654 static int t4_drop_ip_fragments = 0;
655 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
656     &t4_drop_ip_fragments, 0, "Drop IP fragments");
657 
658 static int t4_drop_pkts_with_l2_errors = 1;
659 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
660     &t4_drop_pkts_with_l2_errors, 0,
661     "Drop all frames with Layer 2 length or checksum errors");
662 
663 static int t4_drop_pkts_with_l3_errors = 0;
664 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
665     &t4_drop_pkts_with_l3_errors, 0,
666     "Drop all frames with IP version, length, or checksum errors");
667 
668 static int t4_drop_pkts_with_l4_errors = 0;
669 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
670     &t4_drop_pkts_with_l4_errors, 0,
671     "Drop all frames with Layer 4 length, checksum, or other errors");
672 
673 #ifdef TCP_OFFLOAD
674 /*
675  * TOE tunables.
676  */
677 static int t4_cop_managed_offloading = 0;
678 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
679     &t4_cop_managed_offloading, 0,
680     "COP (Connection Offload Policy) controls all TOE offload");
681 #endif
682 
683 #ifdef KERN_TLS
684 /*
685  * This enables KERN_TLS for all adapters if set.
686  */
687 static int t4_kern_tls = 0;
688 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
689     "Enable KERN_TLS mode for all supported adapters");
690 
691 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
692     "cxgbe(4) KERN_TLS parameters");
693 
694 static int t4_tls_inline_keys = 0;
695 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
696     &t4_tls_inline_keys, 0,
697     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
698     "in card memory.");
699 
700 static int t4_tls_combo_wrs = 0;
701 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
702     0, "Attempt to combine TCB field updates with TLS record work requests.");
703 #endif
704 
705 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
706 static int vi_mac_funcs[] = {
707 	FW_VI_FUNC_ETH,
708 	FW_VI_FUNC_OFLD,
709 	FW_VI_FUNC_IWARP,
710 	FW_VI_FUNC_OPENISCSI,
711 	FW_VI_FUNC_OPENFCOE,
712 	FW_VI_FUNC_FOISCSI,
713 	FW_VI_FUNC_FOFCOE,
714 };
715 
716 struct intrs_and_queues {
717 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
718 	uint16_t num_vis;	/* number of VIs for each port */
719 	uint16_t nirq;		/* Total # of vectors */
720 	uint16_t ntxq;		/* # of NIC txq's for each port */
721 	uint16_t nrxq;		/* # of NIC rxq's for each port */
722 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
723 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
724 	uint16_t nnmtxq;	/* # of netmap txq's */
725 	uint16_t nnmrxq;	/* # of netmap rxq's */
726 
727 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
728 	uint16_t ntxq_vi;	/* # of NIC txq's */
729 	uint16_t nrxq_vi;	/* # of NIC rxq's */
730 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
731 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
732 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
733 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
734 };
735 
736 static void setup_memwin(struct adapter *);
737 static void position_memwin(struct adapter *, int, uint32_t);
738 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
739 static int fwmtype_to_hwmtype(int);
740 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
741     uint32_t *);
742 static int fixup_devlog_params(struct adapter *);
743 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
744 static int contact_firmware(struct adapter *);
745 static int partition_resources(struct adapter *);
746 static int get_params__pre_init(struct adapter *);
747 static int set_params__pre_init(struct adapter *);
748 static int get_params__post_init(struct adapter *);
749 static int set_params__post_init(struct adapter *);
750 static void t4_set_desc(struct adapter *);
751 static bool fixed_ifmedia(struct port_info *);
752 static void build_medialist(struct port_info *);
753 static void init_link_config(struct port_info *);
754 static int fixup_link_config(struct port_info *);
755 static int apply_link_config(struct port_info *);
756 static int cxgbe_init_synchronized(struct vi_info *);
757 static int cxgbe_uninit_synchronized(struct vi_info *);
758 static int adapter_full_init(struct adapter *);
759 static void adapter_full_uninit(struct adapter *);
760 static int vi_full_init(struct vi_info *);
761 static void vi_full_uninit(struct vi_info *);
762 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
763 static void quiesce_txq(struct sge_txq *);
764 static void quiesce_wrq(struct sge_wrq *);
765 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
766 static void quiesce_vi(struct vi_info *);
767 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
768     driver_intr_t *, void *, char *);
769 static int t4_free_irq(struct adapter *, struct irq *);
770 static void t4_init_atid_table(struct adapter *);
771 static void t4_free_atid_table(struct adapter *);
772 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
773 static void vi_refresh_stats(struct vi_info *);
774 static void cxgbe_refresh_stats(struct vi_info *);
775 static void cxgbe_tick(void *);
776 static void vi_tick(void *);
777 static void cxgbe_sysctls(struct port_info *);
778 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
779 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
780 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
781 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
782 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
783 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
784 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
785 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
786 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
787 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
788 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
789 static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
790 static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
791 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
792 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
793 static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
794 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
795 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
796 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
797 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
798 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
799 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
800 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
801 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
802 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
803 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
804 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
805 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
806 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
807 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
808 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
809 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
810 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
811 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
812 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
813 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
814 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
815 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
816 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
817 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
818 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
819 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
820 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
821 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
822 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
823 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
824 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
825 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
826 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
827 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
828 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
829 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
830 #ifdef TCP_OFFLOAD
831 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
832 static int sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS);
833 static int sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS);
834 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
835 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
836 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
837 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
838 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
839 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
840 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
841 #endif
842 static int get_sge_context(struct adapter *, struct t4_sge_context *);
843 static int load_fw(struct adapter *, struct t4_data *);
844 static int load_cfg(struct adapter *, struct t4_data *);
845 static int load_boot(struct adapter *, struct t4_bootrom *);
846 static int load_bootcfg(struct adapter *, struct t4_data *);
847 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
848 static void free_offload_policy(struct t4_offload_policy *);
849 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
850 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
851 static int read_i2c(struct adapter *, struct t4_i2c_data *);
852 static int clear_stats(struct adapter *, u_int);
853 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
854 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
855 #ifdef TCP_OFFLOAD
856 static int toe_capability(struct vi_info *, bool);
857 static void t4_async_event(void *, int);
858 #endif
859 #ifdef KERN_TLS
860 static int ktls_capability(struct adapter *, bool);
861 #endif
862 static int mod_event(module_t, int, void *);
863 static int notify_siblings(device_t, int);
864 static uint64_t vi_get_counter(struct ifnet *, ift_counter);
865 static uint64_t cxgbe_get_counter(struct ifnet *, ift_counter);
866 static void enable_vxlan_rx(struct adapter *);
867 static void reset_adapter(void *, int);
868 
869 struct {
870 	uint16_t device;
871 	char *desc;
872 } t4_pciids[] = {
873 	{0xa000, "Chelsio Terminator 4 FPGA"},
874 	{0x4400, "Chelsio T440-dbg"},
875 	{0x4401, "Chelsio T420-CR"},
876 	{0x4402, "Chelsio T422-CR"},
877 	{0x4403, "Chelsio T440-CR"},
878 	{0x4404, "Chelsio T420-BCH"},
879 	{0x4405, "Chelsio T440-BCH"},
880 	{0x4406, "Chelsio T440-CH"},
881 	{0x4407, "Chelsio T420-SO"},
882 	{0x4408, "Chelsio T420-CX"},
883 	{0x4409, "Chelsio T420-BT"},
884 	{0x440a, "Chelsio T404-BT"},
885 	{0x440e, "Chelsio T440-LP-CR"},
886 }, t5_pciids[] = {
887 	{0xb000, "Chelsio Terminator 5 FPGA"},
888 	{0x5400, "Chelsio T580-dbg"},
889 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
890 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
891 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
892 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
893 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
894 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
895 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
896 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
897 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
898 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
899 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
900 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
901 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
902 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
903 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
904 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
905 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
906 
907 	/* Custom */
908 	{0x5483, "Custom T540-CR"},
909 	{0x5484, "Custom T540-BT"},
910 }, t6_pciids[] = {
911 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
912 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
913 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
914 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
915 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
916 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
917 	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
918 	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
919 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
920 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
921 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
922 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
923 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
924 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
925 	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
926 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
927 
928 	/* Custom */
929 	{0x6480, "Custom T6225-CR"},
930 	{0x6481, "Custom T62100-CR"},
931 	{0x6482, "Custom T6225-CR"},
932 	{0x6483, "Custom T62100-CR"},
933 	{0x6484, "Custom T64100-CR"},
934 	{0x6485, "Custom T6240-SO"},
935 	{0x6486, "Custom T6225-SO-CR"},
936 	{0x6487, "Custom T6225-CR"},
937 };
938 
939 #ifdef TCP_OFFLOAD
940 /*
941  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
942  * be exactly the same for both rxq and ofld_rxq.
943  */
944 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
945 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
946 #endif
947 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
948 
949 static int
950 t4_probe(device_t dev)
951 {
952 	int i;
953 	uint16_t v = pci_get_vendor(dev);
954 	uint16_t d = pci_get_device(dev);
955 	uint8_t f = pci_get_function(dev);
956 
957 	if (v != PCI_VENDOR_ID_CHELSIO)
958 		return (ENXIO);
959 
960 	/* Attach only to PF0 of the FPGA */
961 	if (d == 0xa000 && f != 0)
962 		return (ENXIO);
963 
964 	for (i = 0; i < nitems(t4_pciids); i++) {
965 		if (d == t4_pciids[i].device) {
966 			device_set_desc(dev, t4_pciids[i].desc);
967 			return (BUS_PROBE_DEFAULT);
968 		}
969 	}
970 
971 	return (ENXIO);
972 }
973 
974 static int
975 t5_probe(device_t dev)
976 {
977 	int i;
978 	uint16_t v = pci_get_vendor(dev);
979 	uint16_t d = pci_get_device(dev);
980 	uint8_t f = pci_get_function(dev);
981 
982 	if (v != PCI_VENDOR_ID_CHELSIO)
983 		return (ENXIO);
984 
985 	/* Attach only to PF0 of the FPGA */
986 	if (d == 0xb000 && f != 0)
987 		return (ENXIO);
988 
989 	for (i = 0; i < nitems(t5_pciids); i++) {
990 		if (d == t5_pciids[i].device) {
991 			device_set_desc(dev, t5_pciids[i].desc);
992 			return (BUS_PROBE_DEFAULT);
993 		}
994 	}
995 
996 	return (ENXIO);
997 }
998 
999 static int
1000 t6_probe(device_t dev)
1001 {
1002 	int i;
1003 	uint16_t v = pci_get_vendor(dev);
1004 	uint16_t d = pci_get_device(dev);
1005 
1006 	if (v != PCI_VENDOR_ID_CHELSIO)
1007 		return (ENXIO);
1008 
1009 	for (i = 0; i < nitems(t6_pciids); i++) {
1010 		if (d == t6_pciids[i].device) {
1011 			device_set_desc(dev, t6_pciids[i].desc);
1012 			return (BUS_PROBE_DEFAULT);
1013 		}
1014 	}
1015 
1016 	return (ENXIO);
1017 }
1018 
1019 static void
1020 t5_attribute_workaround(device_t dev)
1021 {
1022 	device_t root_port;
1023 	uint32_t v;
1024 
1025 	/*
1026 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1027 	 * Ordering attributes when replying to a TLP from a Root
1028 	 * Port.  As a workaround, find the parent Root Port and
1029 	 * disable No Snoop and Relaxed Ordering.  Note that this
1030 	 * affects all devices under this root port.
1031 	 */
1032 	root_port = pci_find_pcie_root_port(dev);
1033 	if (root_port == NULL) {
1034 		device_printf(dev, "Unable to find parent root port\n");
1035 		return;
1036 	}
1037 
1038 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1039 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1040 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1041 	    0)
1042 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1043 		    device_get_nameunit(root_port));
1044 }
1045 
1046 static const struct devnames devnames[] = {
1047 	{
1048 		.nexus_name = "t4nex",
1049 		.ifnet_name = "cxgbe",
1050 		.vi_ifnet_name = "vcxgbe",
1051 		.pf03_drv_name = "t4iov",
1052 		.vf_nexus_name = "t4vf",
1053 		.vf_ifnet_name = "cxgbev"
1054 	}, {
1055 		.nexus_name = "t5nex",
1056 		.ifnet_name = "cxl",
1057 		.vi_ifnet_name = "vcxl",
1058 		.pf03_drv_name = "t5iov",
1059 		.vf_nexus_name = "t5vf",
1060 		.vf_ifnet_name = "cxlv"
1061 	}, {
1062 		.nexus_name = "t6nex",
1063 		.ifnet_name = "cc",
1064 		.vi_ifnet_name = "vcc",
1065 		.pf03_drv_name = "t6iov",
1066 		.vf_nexus_name = "t6vf",
1067 		.vf_ifnet_name = "ccv"
1068 	}
1069 };
1070 
1071 void
1072 t4_init_devnames(struct adapter *sc)
1073 {
1074 	int id;
1075 
1076 	id = chip_id(sc);
1077 	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1078 		sc->names = &devnames[id - CHELSIO_T4];
1079 	else {
1080 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1081 		sc->names = NULL;
1082 	}
1083 }
1084 
1085 static int
1086 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1087 {
1088 	const char *parent, *name;
1089 	long value;
1090 	int line, unit;
1091 
1092 	line = 0;
1093 	parent = device_get_nameunit(sc->dev);
1094 	name = sc->names->ifnet_name;
1095 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1096 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1097 		    value == pi->port_id)
1098 			return (unit);
1099 	}
1100 	return (-1);
1101 }
1102 
1103 static int
1104 t4_attach(device_t dev)
1105 {
1106 	struct adapter *sc;
1107 	int rc = 0, i, j, rqidx, tqidx, nports;
1108 	struct make_dev_args mda;
1109 	struct intrs_and_queues iaq;
1110 	struct sge *s;
1111 	uint32_t *buf;
1112 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1113 	int ofld_tqidx;
1114 #endif
1115 #ifdef TCP_OFFLOAD
1116 	int ofld_rqidx;
1117 #endif
1118 #ifdef DEV_NETMAP
1119 	int nm_rqidx, nm_tqidx;
1120 #endif
1121 	int num_vis;
1122 
1123 	sc = device_get_softc(dev);
1124 	sc->dev = dev;
1125 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1126 
1127 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1128 		t5_attribute_workaround(dev);
1129 	pci_enable_busmaster(dev);
1130 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1131 		uint32_t v;
1132 
1133 		pci_set_max_read_req(dev, 4096);
1134 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1135 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1136 		if (pcie_relaxed_ordering == 0 &&
1137 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1138 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1139 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1140 		} else if (pcie_relaxed_ordering == 1 &&
1141 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1142 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1143 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1144 		}
1145 	}
1146 
1147 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1148 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1149 	sc->traceq = -1;
1150 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1151 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1152 	    device_get_nameunit(dev));
1153 
1154 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1155 	    device_get_nameunit(dev));
1156 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1157 	t4_add_adapter(sc);
1158 
1159 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1160 	TAILQ_INIT(&sc->sfl);
1161 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1162 
1163 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1164 
1165 	sc->policy = NULL;
1166 	rw_init(&sc->policy_lock, "connection offload policy");
1167 
1168 	callout_init(&sc->ktls_tick, 1);
1169 
1170 #ifdef TCP_OFFLOAD
1171 	TASK_INIT(&sc->async_event_task, 0, t4_async_event, sc);
1172 #endif
1173 
1174 	refcount_init(&sc->vxlan_refcount, 0);
1175 
1176 	TASK_INIT(&sc->reset_task, 0, reset_adapter, sc);
1177 
1178 	sc->ctrlq_oid = SYSCTL_ADD_NODE(device_get_sysctl_ctx(sc->dev),
1179 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1180 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1181 	sc->fwq_oid = SYSCTL_ADD_NODE(device_get_sysctl_ctx(sc->dev),
1182 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1183 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1184 
1185 	rc = t4_map_bars_0_and_4(sc);
1186 	if (rc != 0)
1187 		goto done; /* error message displayed already */
1188 
1189 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1190 
1191 	/* Prepare the adapter for operation. */
1192 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1193 	rc = -t4_prep_adapter(sc, buf);
1194 	free(buf, M_CXGBE);
1195 	if (rc != 0) {
1196 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1197 		goto done;
1198 	}
1199 
1200 	/*
1201 	 * This is the real PF# to which we're attaching.  Works from within PCI
1202 	 * passthrough environments too, where pci_get_function() could return a
1203 	 * different PF# depending on the passthrough configuration.  We need to
1204 	 * use the real PF# in all our communication with the firmware.
1205 	 */
1206 	j = t4_read_reg(sc, A_PL_WHOAMI);
1207 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1208 	sc->mbox = sc->pf;
1209 
1210 	t4_init_devnames(sc);
1211 	if (sc->names == NULL) {
1212 		rc = ENOTSUP;
1213 		goto done; /* error message displayed already */
1214 	}
1215 
1216 	/*
1217 	 * Do this really early, with the memory windows set up even before the
1218 	 * character device.  The userland tool's register i/o and mem read
1219 	 * will work even in "recovery mode".
1220 	 */
1221 	setup_memwin(sc);
1222 	if (t4_init_devlog_params(sc, 0) == 0)
1223 		fixup_devlog_params(sc);
1224 	make_dev_args_init(&mda);
1225 	mda.mda_devsw = &t4_cdevsw;
1226 	mda.mda_uid = UID_ROOT;
1227 	mda.mda_gid = GID_WHEEL;
1228 	mda.mda_mode = 0600;
1229 	mda.mda_si_drv1 = sc;
1230 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1231 	if (rc != 0)
1232 		device_printf(dev, "failed to create nexus char device: %d.\n",
1233 		    rc);
1234 
1235 	/* Go no further if recovery mode has been requested. */
1236 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1237 		device_printf(dev, "recovery mode.\n");
1238 		goto done;
1239 	}
1240 
1241 #if defined(__i386__)
1242 	if ((cpu_feature & CPUID_CX8) == 0) {
1243 		device_printf(dev, "64 bit atomics not available.\n");
1244 		rc = ENOTSUP;
1245 		goto done;
1246 	}
1247 #endif
1248 
1249 	/* Contact the firmware and try to become the master driver. */
1250 	rc = contact_firmware(sc);
1251 	if (rc != 0)
1252 		goto done; /* error message displayed already */
1253 	MPASS(sc->flags & FW_OK);
1254 
1255 	rc = get_params__pre_init(sc);
1256 	if (rc != 0)
1257 		goto done; /* error message displayed already */
1258 
1259 	if (sc->flags & MASTER_PF) {
1260 		rc = partition_resources(sc);
1261 		if (rc != 0)
1262 			goto done; /* error message displayed already */
1263 		t4_intr_clear(sc);
1264 	}
1265 
1266 	rc = get_params__post_init(sc);
1267 	if (rc != 0)
1268 		goto done; /* error message displayed already */
1269 
1270 	rc = set_params__post_init(sc);
1271 	if (rc != 0)
1272 		goto done; /* error message displayed already */
1273 
1274 	rc = t4_map_bar_2(sc);
1275 	if (rc != 0)
1276 		goto done; /* error message displayed already */
1277 
1278 	rc = t4_create_dma_tag(sc);
1279 	if (rc != 0)
1280 		goto done; /* error message displayed already */
1281 
1282 	/*
1283 	 * First pass over all the ports - allocate VIs and initialize some
1284 	 * basic parameters like mac address, port type, etc.
1285 	 */
1286 	for_each_port(sc, i) {
1287 		struct port_info *pi;
1288 
1289 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1290 		sc->port[i] = pi;
1291 
1292 		/* These must be set before t4_port_init */
1293 		pi->adapter = sc;
1294 		pi->port_id = i;
1295 		/*
1296 		 * XXX: vi[0] is special so we can't delay this allocation until
1297 		 * pi->nvi's final value is known.
1298 		 */
1299 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1300 		    M_ZERO | M_WAITOK);
1301 
1302 		/*
1303 		 * Allocate the "main" VI and initialize parameters
1304 		 * like mac addr.
1305 		 */
1306 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1307 		if (rc != 0) {
1308 			device_printf(dev, "unable to initialize port %d: %d\n",
1309 			    i, rc);
1310 			free(pi->vi, M_CXGBE);
1311 			free(pi, M_CXGBE);
1312 			sc->port[i] = NULL;
1313 			goto done;
1314 		}
1315 
1316 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1317 		    device_get_nameunit(dev), i);
1318 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1319 		sc->chan_map[pi->tx_chan] = i;
1320 
1321 		/*
1322 		 * The MPS counter for FCS errors doesn't work correctly on the
1323 		 * T6 so we use the MAC counter here.  Which MAC is in use
1324 		 * depends on the link settings which will be known when the
1325 		 * link comes up.
1326 		 */
1327 		if (is_t6(sc)) {
1328 			pi->fcs_reg = -1;
1329 		} else if (is_t4(sc)) {
1330 			pi->fcs_reg = PORT_REG(pi->tx_chan,
1331 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1332 		} else {
1333 			pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
1334 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1335 		}
1336 		pi->fcs_base = 0;
1337 
1338 		/* All VIs on this port share this media. */
1339 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1340 		    cxgbe_media_status);
1341 
1342 		PORT_LOCK(pi);
1343 		init_link_config(pi);
1344 		fixup_link_config(pi);
1345 		build_medialist(pi);
1346 		if (fixed_ifmedia(pi))
1347 			pi->flags |= FIXED_IFMEDIA;
1348 		PORT_UNLOCK(pi);
1349 
1350 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1351 		    t4_ifnet_unit(sc, pi));
1352 		if (pi->dev == NULL) {
1353 			device_printf(dev,
1354 			    "failed to add device for port %d.\n", i);
1355 			rc = ENXIO;
1356 			goto done;
1357 		}
1358 		pi->vi[0].dev = pi->dev;
1359 		device_set_softc(pi->dev, pi);
1360 	}
1361 
1362 	/*
1363 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1364 	 */
1365 	nports = sc->params.nports;
1366 	rc = cfg_itype_and_nqueues(sc, &iaq);
1367 	if (rc != 0)
1368 		goto done; /* error message displayed already */
1369 
1370 	num_vis = iaq.num_vis;
1371 	sc->intr_type = iaq.intr_type;
1372 	sc->intr_count = iaq.nirq;
1373 
1374 	s = &sc->sge;
1375 	s->nrxq = nports * iaq.nrxq;
1376 	s->ntxq = nports * iaq.ntxq;
1377 	if (num_vis > 1) {
1378 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1379 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1380 	}
1381 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1382 	s->neq += nports;		/* ctrl queues: 1 per port */
1383 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1384 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1385 	if (is_offload(sc) || is_ethoffload(sc)) {
1386 		s->nofldtxq = nports * iaq.nofldtxq;
1387 		if (num_vis > 1)
1388 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1389 		s->neq += s->nofldtxq;
1390 
1391 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1392 		    M_CXGBE, M_ZERO | M_WAITOK);
1393 	}
1394 #endif
1395 #ifdef TCP_OFFLOAD
1396 	if (is_offload(sc)) {
1397 		s->nofldrxq = nports * iaq.nofldrxq;
1398 		if (num_vis > 1)
1399 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1400 		s->neq += s->nofldrxq;	/* free list */
1401 		s->niq += s->nofldrxq;
1402 
1403 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1404 		    M_CXGBE, M_ZERO | M_WAITOK);
1405 	}
1406 #endif
1407 #ifdef DEV_NETMAP
1408 	s->nnmrxq = 0;
1409 	s->nnmtxq = 0;
1410 	if (t4_native_netmap & NN_MAIN_VI) {
1411 		s->nnmrxq += nports * iaq.nnmrxq;
1412 		s->nnmtxq += nports * iaq.nnmtxq;
1413 	}
1414 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1415 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1416 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1417 	}
1418 	s->neq += s->nnmtxq + s->nnmrxq;
1419 	s->niq += s->nnmrxq;
1420 
1421 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1422 	    M_CXGBE, M_ZERO | M_WAITOK);
1423 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1424 	    M_CXGBE, M_ZERO | M_WAITOK);
1425 #endif
1426 	MPASS(s->niq <= s->iqmap_sz);
1427 	MPASS(s->neq <= s->eqmap_sz);
1428 
1429 	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1430 	    M_ZERO | M_WAITOK);
1431 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1432 	    M_ZERO | M_WAITOK);
1433 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1434 	    M_ZERO | M_WAITOK);
1435 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1436 	    M_ZERO | M_WAITOK);
1437 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1438 	    M_ZERO | M_WAITOK);
1439 
1440 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1441 	    M_ZERO | M_WAITOK);
1442 
1443 	t4_init_l2t(sc, M_WAITOK);
1444 	t4_init_smt(sc, M_WAITOK);
1445 	t4_init_tx_sched(sc);
1446 	t4_init_atid_table(sc);
1447 #ifdef RATELIMIT
1448 	t4_init_etid_table(sc);
1449 #endif
1450 #ifdef INET6
1451 	t4_init_clip_table(sc);
1452 #endif
1453 	if (sc->vres.key.size != 0)
1454 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1455 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1456 
1457 	/*
1458 	 * Second pass over the ports.  This time we know the number of rx and
1459 	 * tx queues that each port should get.
1460 	 */
1461 	rqidx = tqidx = 0;
1462 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1463 	ofld_tqidx = 0;
1464 #endif
1465 #ifdef TCP_OFFLOAD
1466 	ofld_rqidx = 0;
1467 #endif
1468 #ifdef DEV_NETMAP
1469 	nm_rqidx = nm_tqidx = 0;
1470 #endif
1471 	for_each_port(sc, i) {
1472 		struct port_info *pi = sc->port[i];
1473 		struct vi_info *vi;
1474 
1475 		if (pi == NULL)
1476 			continue;
1477 
1478 		pi->nvi = num_vis;
1479 		for_each_vi(pi, j, vi) {
1480 			vi->pi = pi;
1481 			vi->adapter = sc;
1482 			vi->first_intr = -1;
1483 			vi->qsize_rxq = t4_qsize_rxq;
1484 			vi->qsize_txq = t4_qsize_txq;
1485 
1486 			vi->first_rxq = rqidx;
1487 			vi->first_txq = tqidx;
1488 			vi->tmr_idx = t4_tmr_idx;
1489 			vi->pktc_idx = t4_pktc_idx;
1490 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1491 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1492 
1493 			rqidx += vi->nrxq;
1494 			tqidx += vi->ntxq;
1495 
1496 			if (j == 0 && vi->ntxq > 1)
1497 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1498 			else
1499 				vi->rsrv_noflowq = 0;
1500 
1501 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1502 			vi->first_ofld_txq = ofld_tqidx;
1503 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1504 			ofld_tqidx += vi->nofldtxq;
1505 #endif
1506 #ifdef TCP_OFFLOAD
1507 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1508 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1509 			vi->first_ofld_rxq = ofld_rqidx;
1510 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1511 
1512 			ofld_rqidx += vi->nofldrxq;
1513 #endif
1514 #ifdef DEV_NETMAP
1515 			vi->first_nm_rxq = nm_rqidx;
1516 			vi->first_nm_txq = nm_tqidx;
1517 			if (j == 0) {
1518 				vi->nnmrxq = iaq.nnmrxq;
1519 				vi->nnmtxq = iaq.nnmtxq;
1520 			} else {
1521 				vi->nnmrxq = iaq.nnmrxq_vi;
1522 				vi->nnmtxq = iaq.nnmtxq_vi;
1523 			}
1524 			nm_rqidx += vi->nnmrxq;
1525 			nm_tqidx += vi->nnmtxq;
1526 #endif
1527 		}
1528 	}
1529 
1530 	rc = t4_setup_intr_handlers(sc);
1531 	if (rc != 0) {
1532 		device_printf(dev,
1533 		    "failed to setup interrupt handlers: %d\n", rc);
1534 		goto done;
1535 	}
1536 
1537 	rc = bus_generic_probe(dev);
1538 	if (rc != 0) {
1539 		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1540 		goto done;
1541 	}
1542 
1543 	/*
1544 	 * Ensure thread-safe mailbox access (in debug builds).
1545 	 *
1546 	 * So far this was the only thread accessing the mailbox but various
1547 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1548 	 * will access the mailbox from different threads.
1549 	 */
1550 	sc->flags |= CHK_MBOX_ACCESS;
1551 
1552 	rc = bus_generic_attach(dev);
1553 	if (rc != 0) {
1554 		device_printf(dev,
1555 		    "failed to attach all child ports: %d\n", rc);
1556 		goto done;
1557 	}
1558 
1559 	device_printf(dev,
1560 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1561 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1562 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1563 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1564 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1565 
1566 	t4_set_desc(sc);
1567 
1568 	notify_siblings(dev, 0);
1569 
1570 done:
1571 	if (rc != 0 && sc->cdev) {
1572 		/* cdev was created and so cxgbetool works; recover that way. */
1573 		device_printf(dev,
1574 		    "error during attach, adapter is now in recovery mode.\n");
1575 		rc = 0;
1576 	}
1577 
1578 	if (rc != 0)
1579 		t4_detach_common(dev);
1580 	else
1581 		t4_sysctls(sc);
1582 
1583 	return (rc);
1584 }
1585 
1586 static int
1587 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1588 {
1589 	struct adapter *sc;
1590 	struct port_info *pi;
1591 	int i;
1592 
1593 	sc = device_get_softc(bus);
1594 	for_each_port(sc, i) {
1595 		pi = sc->port[i];
1596 		if (pi != NULL && pi->dev == dev) {
1597 			sbuf_printf(sb, "port=%d", pi->port_id);
1598 			break;
1599 		}
1600 	}
1601 	return (0);
1602 }
1603 
1604 static int
1605 t4_ready(device_t dev)
1606 {
1607 	struct adapter *sc;
1608 
1609 	sc = device_get_softc(dev);
1610 	if (sc->flags & FW_OK)
1611 		return (0);
1612 	return (ENXIO);
1613 }
1614 
1615 static int
1616 t4_read_port_device(device_t dev, int port, device_t *child)
1617 {
1618 	struct adapter *sc;
1619 	struct port_info *pi;
1620 
1621 	sc = device_get_softc(dev);
1622 	if (port < 0 || port >= MAX_NPORTS)
1623 		return (EINVAL);
1624 	pi = sc->port[port];
1625 	if (pi == NULL || pi->dev == NULL)
1626 		return (ENXIO);
1627 	*child = pi->dev;
1628 	return (0);
1629 }
1630 
1631 static int
1632 notify_siblings(device_t dev, int detaching)
1633 {
1634 	device_t sibling;
1635 	int error, i;
1636 
1637 	error = 0;
1638 	for (i = 0; i < PCI_FUNCMAX; i++) {
1639 		if (i == pci_get_function(dev))
1640 			continue;
1641 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1642 		    pci_get_slot(dev), i);
1643 		if (sibling == NULL || !device_is_attached(sibling))
1644 			continue;
1645 		if (detaching)
1646 			error = T4_DETACH_CHILD(sibling);
1647 		else
1648 			(void)T4_ATTACH_CHILD(sibling);
1649 		if (error)
1650 			break;
1651 	}
1652 	return (error);
1653 }
1654 
1655 /*
1656  * Idempotent
1657  */
1658 static int
1659 t4_detach(device_t dev)
1660 {
1661 	struct adapter *sc;
1662 	int rc;
1663 
1664 	sc = device_get_softc(dev);
1665 
1666 	rc = notify_siblings(dev, 1);
1667 	if (rc) {
1668 		device_printf(dev,
1669 		    "failed to detach sibling devices: %d\n", rc);
1670 		return (rc);
1671 	}
1672 
1673 	return (t4_detach_common(dev));
1674 }
1675 
1676 int
1677 t4_detach_common(device_t dev)
1678 {
1679 	struct adapter *sc;
1680 	struct port_info *pi;
1681 	int i, rc;
1682 
1683 	sc = device_get_softc(dev);
1684 
1685 	if (sc->cdev) {
1686 		destroy_dev(sc->cdev);
1687 		sc->cdev = NULL;
1688 	}
1689 
1690 	sx_xlock(&t4_list_lock);
1691 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1692 	sx_xunlock(&t4_list_lock);
1693 
1694 	sc->flags &= ~CHK_MBOX_ACCESS;
1695 	if (sc->flags & FULL_INIT_DONE) {
1696 		if (!(sc->flags & IS_VF))
1697 			t4_intr_disable(sc);
1698 	}
1699 
1700 	if (device_is_attached(dev)) {
1701 		rc = bus_generic_detach(dev);
1702 		if (rc) {
1703 			device_printf(dev,
1704 			    "failed to detach child devices: %d\n", rc);
1705 			return (rc);
1706 		}
1707 	}
1708 
1709 #ifdef TCP_OFFLOAD
1710 	taskqueue_drain(taskqueue_thread, &sc->async_event_task);
1711 #endif
1712 
1713 	for (i = 0; i < sc->intr_count; i++)
1714 		t4_free_irq(sc, &sc->irq[i]);
1715 
1716 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1717 		t4_free_tx_sched(sc);
1718 
1719 	for (i = 0; i < MAX_NPORTS; i++) {
1720 		pi = sc->port[i];
1721 		if (pi) {
1722 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1723 			if (pi->dev)
1724 				device_delete_child(dev, pi->dev);
1725 
1726 			mtx_destroy(&pi->pi_lock);
1727 			free(pi->vi, M_CXGBE);
1728 			free(pi, M_CXGBE);
1729 		}
1730 	}
1731 
1732 	device_delete_children(dev);
1733 	adapter_full_uninit(sc);
1734 
1735 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1736 		t4_fw_bye(sc, sc->mbox);
1737 
1738 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1739 		pci_release_msi(dev);
1740 
1741 	if (sc->regs_res)
1742 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1743 		    sc->regs_res);
1744 
1745 	if (sc->udbs_res)
1746 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1747 		    sc->udbs_res);
1748 
1749 	if (sc->msix_res)
1750 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1751 		    sc->msix_res);
1752 
1753 	if (sc->l2t)
1754 		t4_free_l2t(sc->l2t);
1755 	if (sc->smt)
1756 		t4_free_smt(sc->smt);
1757 	t4_free_atid_table(sc);
1758 #ifdef RATELIMIT
1759 	t4_free_etid_table(sc);
1760 #endif
1761 	if (sc->key_map)
1762 		vmem_destroy(sc->key_map);
1763 #ifdef INET6
1764 	t4_destroy_clip_table(sc);
1765 #endif
1766 
1767 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1768 	free(sc->sge.ofld_txq, M_CXGBE);
1769 #endif
1770 #ifdef TCP_OFFLOAD
1771 	free(sc->sge.ofld_rxq, M_CXGBE);
1772 #endif
1773 #ifdef DEV_NETMAP
1774 	free(sc->sge.nm_rxq, M_CXGBE);
1775 	free(sc->sge.nm_txq, M_CXGBE);
1776 #endif
1777 	free(sc->irq, M_CXGBE);
1778 	free(sc->sge.rxq, M_CXGBE);
1779 	free(sc->sge.txq, M_CXGBE);
1780 	free(sc->sge.ctrlq, M_CXGBE);
1781 	free(sc->sge.iqmap, M_CXGBE);
1782 	free(sc->sge.eqmap, M_CXGBE);
1783 	free(sc->tids.ftid_tab, M_CXGBE);
1784 	free(sc->tids.hpftid_tab, M_CXGBE);
1785 	free_hftid_hash(&sc->tids);
1786 	free(sc->tids.tid_tab, M_CXGBE);
1787 	free(sc->tt.tls_rx_ports, M_CXGBE);
1788 	t4_destroy_dma_tag(sc);
1789 
1790 	callout_drain(&sc->ktls_tick);
1791 	callout_drain(&sc->sfl_callout);
1792 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1793 		mtx_destroy(&sc->tids.ftid_lock);
1794 		cv_destroy(&sc->tids.ftid_cv);
1795 	}
1796 	if (mtx_initialized(&sc->tids.atid_lock))
1797 		mtx_destroy(&sc->tids.atid_lock);
1798 	if (mtx_initialized(&sc->ifp_lock))
1799 		mtx_destroy(&sc->ifp_lock);
1800 
1801 	if (rw_initialized(&sc->policy_lock)) {
1802 		rw_destroy(&sc->policy_lock);
1803 #ifdef TCP_OFFLOAD
1804 		if (sc->policy != NULL)
1805 			free_offload_policy(sc->policy);
1806 #endif
1807 	}
1808 
1809 	for (i = 0; i < NUM_MEMWIN; i++) {
1810 		struct memwin *mw = &sc->memwin[i];
1811 
1812 		if (rw_initialized(&mw->mw_lock))
1813 			rw_destroy(&mw->mw_lock);
1814 	}
1815 
1816 	mtx_destroy(&sc->sfl_lock);
1817 	mtx_destroy(&sc->reg_lock);
1818 	mtx_destroy(&sc->sc_lock);
1819 
1820 	bzero(sc, sizeof(*sc));
1821 
1822 	return (0);
1823 }
1824 
1825 static inline bool
1826 ok_to_reset(struct adapter *sc)
1827 {
1828 	struct tid_info *t = &sc->tids;
1829 	struct port_info *pi;
1830 	struct vi_info *vi;
1831 	int i, j;
1832 	const int caps = IFCAP_TOE | IFCAP_TXTLS | IFCAP_NETMAP | IFCAP_TXRTLMT;
1833 
1834 	ASSERT_SYNCHRONIZED_OP(sc);
1835 	MPASS(!(sc->flags & IS_VF));
1836 
1837 	for_each_port(sc, i) {
1838 		pi = sc->port[i];
1839 		for_each_vi(pi, j, vi) {
1840 			if (vi->ifp->if_capenable & caps)
1841 				return (false);
1842 		}
1843 	}
1844 
1845 	if (atomic_load_int(&t->tids_in_use) > 0)
1846 		return (false);
1847 	if (atomic_load_int(&t->stids_in_use) > 0)
1848 		return (false);
1849 	if (atomic_load_int(&t->atids_in_use) > 0)
1850 		return (false);
1851 	if (atomic_load_int(&t->ftids_in_use) > 0)
1852 		return (false);
1853 	if (atomic_load_int(&t->hpftids_in_use) > 0)
1854 		return (false);
1855 	if (atomic_load_int(&t->etids_in_use) > 0)
1856 		return (false);
1857 
1858 	return (true);
1859 }
1860 
1861 static int
1862 t4_suspend(device_t dev)
1863 {
1864 	struct adapter *sc = device_get_softc(dev);
1865 	struct port_info *pi;
1866 	struct vi_info *vi;
1867 	struct ifnet *ifp;
1868 	struct sge_rxq *rxq;
1869 	struct sge_txq *txq;
1870 	struct sge_wrq *wrq;
1871 #ifdef TCP_OFFLOAD
1872 	struct sge_ofld_rxq *ofld_rxq;
1873 #endif
1874 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1875 	struct sge_ofld_txq *ofld_txq;
1876 #endif
1877 	int rc, i, j, k;
1878 
1879 	CH_ALERT(sc, "suspend requested\n");
1880 
1881 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4sus");
1882 	if (rc != 0)
1883 		return (ENXIO);
1884 
1885 	/* XXX: Can the kernel call suspend repeatedly without resume? */
1886 	MPASS(!hw_off_limits(sc));
1887 
1888 	if (!ok_to_reset(sc)) {
1889 		/* XXX: should list what resource is preventing suspend. */
1890 		CH_ERR(sc, "not safe to suspend.\n");
1891 		rc = EBUSY;
1892 		goto done;
1893 	}
1894 
1895 	/* No more DMA or interrupts. */
1896 	t4_shutdown_adapter(sc);
1897 
1898 	/* Quiesce all activity. */
1899 	for_each_port(sc, i) {
1900 		pi = sc->port[i];
1901 		pi->vxlan_tcam_entry = false;
1902 
1903 		PORT_LOCK(pi);
1904 		if (pi->up_vis > 0) {
1905 			/*
1906 			 * t4_shutdown_adapter has already shut down all the
1907 			 * PHYs but it also disables interrupts and DMA so there
1908 			 * won't be a link interrupt.  So we update the state
1909 			 * manually and inform the kernel.
1910 			 */
1911 			pi->link_cfg.link_ok = false;
1912 			t4_os_link_changed(pi);
1913 		}
1914 		PORT_UNLOCK(pi);
1915 
1916 		for_each_vi(pi, j, vi) {
1917 			vi->xact_addr_filt = -1;
1918 			if (!(vi->flags & VI_INIT_DONE))
1919 				continue;
1920 
1921 			ifp = vi->ifp;
1922 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1923 				mtx_lock(&vi->tick_mtx);
1924 				vi->flags |= VI_SKIP_STATS;
1925 				callout_stop(&vi->tick);
1926 				mtx_unlock(&vi->tick_mtx);
1927 				callout_drain(&vi->tick);
1928 			}
1929 
1930 			/*
1931 			 * Note that the HW is not available.
1932 			 */
1933 			for_each_txq(vi, k, txq) {
1934 				TXQ_LOCK(txq);
1935 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
1936 				TXQ_UNLOCK(txq);
1937 			}
1938 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1939 			for_each_ofld_txq(vi, k, ofld_txq) {
1940 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
1941 			}
1942 #endif
1943 			for_each_rxq(vi, k, rxq) {
1944 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1945 			}
1946 #if defined(TCP_OFFLOAD)
1947 			for_each_ofld_rxq(vi, k, ofld_rxq) {
1948 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1949 			}
1950 #endif
1951 
1952 			quiesce_vi(vi);
1953 		}
1954 
1955 		if (sc->flags & FULL_INIT_DONE) {
1956 			/* Control queue */
1957 			wrq = &sc->sge.ctrlq[i];
1958 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
1959 			quiesce_wrq(wrq);
1960 		}
1961 	}
1962 	if (sc->flags & FULL_INIT_DONE) {
1963 		/* Firmware event queue */
1964 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
1965 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
1966 	}
1967 
1968 	/* Mark the adapter totally off limits. */
1969 	mtx_lock(&sc->reg_lock);
1970 	sc->flags |= HW_OFF_LIMITS;
1971 	sc->flags &= ~(FW_OK | MASTER_PF);
1972 	sc->reset_thread = NULL;
1973 	mtx_unlock(&sc->reg_lock);
1974 
1975 	sc->num_resets++;
1976 	CH_ALERT(sc, "suspend completed.\n");
1977 done:
1978 	end_synchronized_op(sc, 0);
1979 	return (rc);
1980 }
1981 
1982 struct adapter_pre_reset_state {
1983 	u_int flags;
1984 	uint16_t nbmcaps;
1985 	uint16_t linkcaps;
1986 	uint16_t switchcaps;
1987 	uint16_t niccaps;
1988 	uint16_t toecaps;
1989 	uint16_t rdmacaps;
1990 	uint16_t cryptocaps;
1991 	uint16_t iscsicaps;
1992 	uint16_t fcoecaps;
1993 
1994 	u_int cfcsum;
1995 	char cfg_file[32];
1996 
1997 	struct adapter_params params;
1998 	struct t4_virt_res vres;
1999 	struct tid_info tids;
2000 	struct sge sge;
2001 
2002 	int rawf_base;
2003 	int nrawf;
2004 
2005 };
2006 
2007 static void
2008 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2009 {
2010 
2011 	ASSERT_SYNCHRONIZED_OP(sc);
2012 
2013 	o->flags = sc->flags;
2014 
2015 	o->nbmcaps =  sc->nbmcaps;
2016 	o->linkcaps = sc->linkcaps;
2017 	o->switchcaps = sc->switchcaps;
2018 	o->niccaps = sc->niccaps;
2019 	o->toecaps = sc->toecaps;
2020 	o->rdmacaps = sc->rdmacaps;
2021 	o->cryptocaps = sc->cryptocaps;
2022 	o->iscsicaps = sc->iscsicaps;
2023 	o->fcoecaps = sc->fcoecaps;
2024 
2025 	o->cfcsum = sc->cfcsum;
2026 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2027 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2028 
2029 	o->params = sc->params;
2030 	o->vres = sc->vres;
2031 	o->tids = sc->tids;
2032 	o->sge = sc->sge;
2033 
2034 	o->rawf_base = sc->rawf_base;
2035 	o->nrawf = sc->nrawf;
2036 }
2037 
2038 static int
2039 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2040 {
2041 	int rc = 0;
2042 
2043 	ASSERT_SYNCHRONIZED_OP(sc);
2044 
2045 	/* Capabilities */
2046 #define COMPARE_CAPS(c) do { \
2047 	if (o->c##caps != sc->c##caps) { \
2048 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2049 		    sc->c##caps); \
2050 		rc = EINVAL; \
2051 	} \
2052 } while (0)
2053 	COMPARE_CAPS(nbm);
2054 	COMPARE_CAPS(link);
2055 	COMPARE_CAPS(switch);
2056 	COMPARE_CAPS(nic);
2057 	COMPARE_CAPS(toe);
2058 	COMPARE_CAPS(rdma);
2059 	COMPARE_CAPS(crypto);
2060 	COMPARE_CAPS(iscsi);
2061 	COMPARE_CAPS(fcoe);
2062 #undef COMPARE_CAPS
2063 
2064 	/* Firmware config file */
2065 	if (o->cfcsum != sc->cfcsum) {
2066 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2067 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2068 		rc = EINVAL;
2069 	}
2070 
2071 #define COMPARE_PARAM(p, name) do { \
2072 	if (o->p != sc->p) { \
2073 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2074 		rc = EINVAL; \
2075 	} \
2076 } while (0)
2077 	COMPARE_PARAM(sge.iq_start, iq_start);
2078 	COMPARE_PARAM(sge.eq_start, eq_start);
2079 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2080 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2081 	COMPARE_PARAM(tids.nftids, nftids);
2082 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2083 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2084 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2085 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2086 	COMPARE_PARAM(tids.tid_base, tid_base);
2087 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2088 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2089 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2090 	COMPARE_PARAM(rawf_base, rawf_base);
2091 	COMPARE_PARAM(nrawf, nrawf);
2092 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2093 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2094 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2095 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2096 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2097 	COMPARE_PARAM(tids.ntids, ntids);
2098 	COMPARE_PARAM(tids.etid_base, etid_base);
2099 	COMPARE_PARAM(tids.etid_end, etid_end);
2100 	COMPARE_PARAM(tids.netids, netids);
2101 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2102 	COMPARE_PARAM(params.ethoffload, ethoffload);
2103 	COMPARE_PARAM(tids.natids, natids);
2104 	COMPARE_PARAM(tids.stid_base, stid_base);
2105 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2106 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2107 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2108 	COMPARE_PARAM(vres.stag.start, stag_start);
2109 	COMPARE_PARAM(vres.stag.size, stag_size);
2110 	COMPARE_PARAM(vres.rq.start, rq_start);
2111 	COMPARE_PARAM(vres.rq.size, rq_size);
2112 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2113 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2114 	COMPARE_PARAM(vres.qp.start, qp_start);
2115 	COMPARE_PARAM(vres.qp.size, qp_size);
2116 	COMPARE_PARAM(vres.cq.start, cq_start);
2117 	COMPARE_PARAM(vres.cq.size, cq_size);
2118 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2119 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2120 	COMPARE_PARAM(vres.srq.start, srq_start);
2121 	COMPARE_PARAM(vres.srq.size, srq_size);
2122 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2123 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2124 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2125 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2126 	COMPARE_PARAM(vres.key.start, key_start);
2127 	COMPARE_PARAM(vres.key.size, key_size);
2128 #undef COMPARE_PARAM
2129 
2130 	return (rc);
2131 }
2132 
2133 static int
2134 t4_resume(device_t dev)
2135 {
2136 	struct adapter *sc = device_get_softc(dev);
2137 	struct adapter_pre_reset_state *old_state = NULL;
2138 	struct port_info *pi;
2139 	struct vi_info *vi;
2140 	struct ifnet *ifp;
2141 	struct sge_txq *txq;
2142 	int rc, i, j, k;
2143 
2144 	CH_ALERT(sc, "resume requested.\n");
2145 
2146 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4res");
2147 	if (rc != 0)
2148 		return (ENXIO);
2149 	MPASS(hw_off_limits(sc));
2150 	MPASS((sc->flags & FW_OK) == 0);
2151 	MPASS((sc->flags & MASTER_PF) == 0);
2152 	MPASS(sc->reset_thread == NULL);
2153 	sc->reset_thread = curthread;
2154 
2155 	/* Register access is expected to work by the time we're here. */
2156 	if (t4_read_reg(sc, A_PL_WHOAMI) == 0xffffffff) {
2157 		CH_ERR(sc, "%s: can't read device registers\n", __func__);
2158 		rc = ENXIO;
2159 		goto done;
2160 	}
2161 
2162 	/* Restore memory window. */
2163 	setup_memwin(sc);
2164 
2165 	/* Go no further if recovery mode has been requested. */
2166 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2167 		CH_ALERT(sc, "recovery mode on resume.\n");
2168 		rc = 0;
2169 		mtx_lock(&sc->reg_lock);
2170 		sc->flags &= ~HW_OFF_LIMITS;
2171 		mtx_unlock(&sc->reg_lock);
2172 		goto done;
2173 	}
2174 
2175 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2176 	save_caps_and_params(sc, old_state);
2177 
2178 	/* Reestablish contact with firmware and become the primary PF. */
2179 	rc = contact_firmware(sc);
2180 	if (rc != 0)
2181 		goto done; /* error message displayed already */
2182 	MPASS(sc->flags & FW_OK);
2183 
2184 	if (sc->flags & MASTER_PF) {
2185 		rc = partition_resources(sc);
2186 		if (rc != 0)
2187 			goto done; /* error message displayed already */
2188 		t4_intr_clear(sc);
2189 	}
2190 
2191 	rc = get_params__post_init(sc);
2192 	if (rc != 0)
2193 		goto done; /* error message displayed already */
2194 
2195 	rc = set_params__post_init(sc);
2196 	if (rc != 0)
2197 		goto done; /* error message displayed already */
2198 
2199 	rc = compare_caps_and_params(sc, old_state);
2200 	if (rc != 0)
2201 		goto done; /* error message displayed already */
2202 
2203 	for_each_port(sc, i) {
2204 		pi = sc->port[i];
2205 		MPASS(pi != NULL);
2206 		MPASS(pi->vi != NULL);
2207 		MPASS(pi->vi[0].dev == pi->dev);
2208 
2209 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2210 		if (rc != 0) {
2211 			CH_ERR(sc,
2212 			    "failed to re-initialize port %d: %d\n", i, rc);
2213 			goto done;
2214 		}
2215 		MPASS(sc->chan_map[pi->tx_chan] == i);
2216 
2217 		PORT_LOCK(pi);
2218 		fixup_link_config(pi);
2219 		build_medialist(pi);
2220 		PORT_UNLOCK(pi);
2221 		for_each_vi(pi, j, vi) {
2222 			if (IS_MAIN_VI(vi))
2223 				continue;
2224 			rc = alloc_extra_vi(sc, pi, vi);
2225 			if (rc != 0) {
2226 				CH_ERR(vi,
2227 				    "failed to re-allocate extra VI: %d\n", rc);
2228 				goto done;
2229 			}
2230 		}
2231 	}
2232 
2233 	/*
2234 	 * Interrupts and queues are about to be enabled and other threads will
2235 	 * want to access the hardware too.  It is safe to do so.  Note that
2236 	 * this thread is still in the middle of a synchronized_op.
2237 	 */
2238 	mtx_lock(&sc->reg_lock);
2239 	sc->flags &= ~HW_OFF_LIMITS;
2240 	mtx_unlock(&sc->reg_lock);
2241 
2242 	if (sc->flags & FULL_INIT_DONE) {
2243 		rc = adapter_full_init(sc);
2244 		if (rc != 0) {
2245 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2246 			goto done;
2247 		}
2248 
2249 		if (sc->vxlan_refcount > 0)
2250 			enable_vxlan_rx(sc);
2251 
2252 		for_each_port(sc, i) {
2253 			pi = sc->port[i];
2254 			for_each_vi(pi, j, vi) {
2255 				if (!(vi->flags & VI_INIT_DONE))
2256 					continue;
2257 				rc = vi_full_init(vi);
2258 				if (rc != 0) {
2259 					CH_ERR(vi, "failed to re-initialize "
2260 					    "interface: %d\n", rc);
2261 					goto done;
2262 				}
2263 
2264 				ifp = vi->ifp;
2265 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2266 					continue;
2267 				/*
2268 				 * Note that we do not setup multicast addresses
2269 				 * in the first pass.  This ensures that the
2270 				 * unicast DMACs for all VIs on all ports get an
2271 				 * MPS TCAM entry.
2272 				 */
2273 				rc = update_mac_settings(ifp, XGMAC_ALL &
2274 				    ~XGMAC_MCADDRS);
2275 				if (rc != 0) {
2276 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2277 					goto done;
2278 				}
2279 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2280 				    true);
2281 				if (rc != 0) {
2282 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2283 					goto done;
2284 				}
2285 				for_each_txq(vi, k, txq) {
2286 					TXQ_LOCK(txq);
2287 					txq->eq.flags |= EQ_ENABLED;
2288 					TXQ_UNLOCK(txq);
2289 				}
2290 				mtx_lock(&vi->tick_mtx);
2291 				vi->flags &= ~VI_SKIP_STATS;
2292 				callout_schedule(&vi->tick, hz);
2293 				mtx_unlock(&vi->tick_mtx);
2294 			}
2295 			PORT_LOCK(pi);
2296 			if (pi->up_vis > 0) {
2297 				t4_update_port_info(pi);
2298 				fixup_link_config(pi);
2299 				build_medialist(pi);
2300 				apply_link_config(pi);
2301 				if (pi->link_cfg.link_ok)
2302 					t4_os_link_changed(pi);
2303 			}
2304 			PORT_UNLOCK(pi);
2305 		}
2306 
2307 		/* Now reprogram the L2 multicast addresses. */
2308 		for_each_port(sc, i) {
2309 			pi = sc->port[i];
2310 			for_each_vi(pi, j, vi) {
2311 				if (!(vi->flags & VI_INIT_DONE))
2312 					continue;
2313 				ifp = vi->ifp;
2314 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2315 					continue;
2316 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2317 				if (rc != 0) {
2318 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2319 					rc = 0;	/* carry on */
2320 				}
2321 			}
2322 		}
2323 	}
2324 done:
2325 	if (rc == 0) {
2326 		sc->incarnation++;
2327 		CH_ALERT(sc, "resume completed.\n");
2328 	}
2329 	end_synchronized_op(sc, 0);
2330 	free(old_state, M_CXGBE);
2331 	return (rc);
2332 }
2333 
2334 static int
2335 t4_reset_prepare(device_t dev, device_t child)
2336 {
2337 	struct adapter *sc = device_get_softc(dev);
2338 
2339 	CH_ALERT(sc, "reset_prepare.\n");
2340 	return (0);
2341 }
2342 
2343 static int
2344 t4_reset_post(device_t dev, device_t child)
2345 {
2346 	struct adapter *sc = device_get_softc(dev);
2347 
2348 	CH_ALERT(sc, "reset_post.\n");
2349 	return (0);
2350 }
2351 
2352 static void
2353 reset_adapter(void *arg, int pending)
2354 {
2355 	struct adapter *sc = arg;
2356 	int rc;
2357 
2358 	CH_ALERT(sc, "reset requested.\n");
2359 
2360 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst1");
2361 	if (rc != 0)
2362 		return;
2363 
2364 	if (hw_off_limits(sc)) {
2365 		CH_ERR(sc, "adapter is suspended, use resume (not reset).\n");
2366 		rc = ENXIO;
2367 		goto done;
2368 	}
2369 
2370 	if (!ok_to_reset(sc)) {
2371 		/* XXX: should list what resource is preventing reset. */
2372 		CH_ERR(sc, "not safe to reset.\n");
2373 		rc = EBUSY;
2374 		goto done;
2375 	}
2376 
2377 done:
2378 	end_synchronized_op(sc, 0);
2379 	if (rc != 0)
2380 		return;	/* Error logged already. */
2381 
2382 	mtx_lock(&Giant);
2383 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2384 	mtx_unlock(&Giant);
2385 	if (rc != 0)
2386 		CH_ERR(sc, "bus_reset_child failed: %d.\n", rc);
2387 	else
2388 		CH_ALERT(sc, "bus_reset_child succeeded.\n");
2389 }
2390 
2391 static int
2392 cxgbe_probe(device_t dev)
2393 {
2394 	char buf[128];
2395 	struct port_info *pi = device_get_softc(dev);
2396 
2397 	snprintf(buf, sizeof(buf), "port %d", pi->port_id);
2398 	device_set_desc_copy(dev, buf);
2399 
2400 	return (BUS_PROBE_DEFAULT);
2401 }
2402 
2403 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2404     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2405     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2406     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2407 #define T4_CAP_ENABLE (T4_CAP)
2408 
2409 static int
2410 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2411 {
2412 	struct ifnet *ifp;
2413 	struct sbuf *sb;
2414 	struct sysctl_ctx_list *ctx;
2415 	struct sysctl_oid_list *children;
2416 	struct pfil_head_args pa;
2417 	struct adapter *sc = vi->adapter;
2418 
2419 	ctx = device_get_sysctl_ctx(vi->dev);
2420 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2421 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2422 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2423 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2424 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2425 #ifdef DEV_NETMAP
2426 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2427 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2428 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2429 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2430 #endif
2431 #ifdef TCP_OFFLOAD
2432 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2433 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2434 #endif
2435 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2436 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2437 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2438 #endif
2439 
2440 	vi->xact_addr_filt = -1;
2441 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2442 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2443 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2444 		vi->flags |= TX_USES_VM_WR;
2445 
2446 	/* Allocate an ifnet and set it up */
2447 	ifp = if_alloc_dev(IFT_ETHER, dev);
2448 	if (ifp == NULL) {
2449 		device_printf(dev, "Cannot allocate ifnet\n");
2450 		return (ENOMEM);
2451 	}
2452 	vi->ifp = ifp;
2453 	ifp->if_softc = vi;
2454 
2455 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2456 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
2457 
2458 	ifp->if_init = cxgbe_init;
2459 	ifp->if_ioctl = cxgbe_ioctl;
2460 	ifp->if_transmit = cxgbe_transmit;
2461 	ifp->if_qflush = cxgbe_qflush;
2462 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2463 		ifp->if_get_counter = vi_get_counter;
2464 	else
2465 		ifp->if_get_counter = cxgbe_get_counter;
2466 #if defined(KERN_TLS) || defined(RATELIMIT)
2467 	ifp->if_snd_tag_alloc = cxgbe_snd_tag_alloc;
2468 #endif
2469 #ifdef RATELIMIT
2470 	ifp->if_ratelimit_query = cxgbe_ratelimit_query;
2471 #endif
2472 
2473 	ifp->if_capabilities = T4_CAP;
2474 	ifp->if_capenable = T4_CAP_ENABLE;
2475 	ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2476 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6;
2477 	if (chip_id(sc) >= CHELSIO_T6) {
2478 		ifp->if_capabilities |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2479 		ifp->if_capenable |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2480 		ifp->if_hwassist |= CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2481 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2482 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN;
2483 	}
2484 
2485 #ifdef TCP_OFFLOAD
2486 	if (vi->nofldrxq != 0)
2487 		ifp->if_capabilities |= IFCAP_TOE;
2488 #endif
2489 #ifdef RATELIMIT
2490 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2491 		ifp->if_capabilities |= IFCAP_TXRTLMT;
2492 		ifp->if_capenable |= IFCAP_TXRTLMT;
2493 	}
2494 #endif
2495 
2496 	ifp->if_hw_tsomax = IP_MAXPACKET;
2497 	if (vi->flags & TX_USES_VM_WR)
2498 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
2499 	else
2500 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
2501 #ifdef RATELIMIT
2502 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2503 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_EO_TSO;
2504 #endif
2505 	ifp->if_hw_tsomaxsegsize = 65536;
2506 #ifdef KERN_TLS
2507 	if (is_ktls(sc)) {
2508 		ifp->if_capabilities |= IFCAP_TXTLS;
2509 		if (sc->flags & KERN_TLS_ON)
2510 			ifp->if_capenable |= IFCAP_TXTLS;
2511 	}
2512 #endif
2513 
2514 	ether_ifattach(ifp, vi->hw_addr);
2515 #ifdef DEV_NETMAP
2516 	if (vi->nnmrxq != 0)
2517 		cxgbe_nm_attach(vi);
2518 #endif
2519 	sb = sbuf_new_auto();
2520 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2521 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2522 	switch (ifp->if_capabilities & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2523 	case IFCAP_TOE:
2524 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2525 		break;
2526 	case IFCAP_TOE | IFCAP_TXRTLMT:
2527 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2528 		break;
2529 	case IFCAP_TXRTLMT:
2530 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2531 		break;
2532 	}
2533 #endif
2534 #ifdef TCP_OFFLOAD
2535 	if (ifp->if_capabilities & IFCAP_TOE)
2536 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2537 #endif
2538 #ifdef DEV_NETMAP
2539 	if (ifp->if_capabilities & IFCAP_NETMAP)
2540 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2541 		    vi->nnmtxq, vi->nnmrxq);
2542 #endif
2543 	sbuf_finish(sb);
2544 	device_printf(dev, "%s\n", sbuf_data(sb));
2545 	sbuf_delete(sb);
2546 
2547 	vi_sysctls(vi);
2548 
2549 	pa.pa_version = PFIL_VERSION;
2550 	pa.pa_flags = PFIL_IN;
2551 	pa.pa_type = PFIL_TYPE_ETHERNET;
2552 	pa.pa_headname = ifp->if_xname;
2553 	vi->pfil = pfil_head_register(&pa);
2554 
2555 	return (0);
2556 }
2557 
2558 static int
2559 cxgbe_attach(device_t dev)
2560 {
2561 	struct port_info *pi = device_get_softc(dev);
2562 	struct adapter *sc = pi->adapter;
2563 	struct vi_info *vi;
2564 	int i, rc;
2565 
2566 	rc = cxgbe_vi_attach(dev, &pi->vi[0]);
2567 	if (rc)
2568 		return (rc);
2569 
2570 	for_each_vi(pi, i, vi) {
2571 		if (i == 0)
2572 			continue;
2573 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
2574 		if (vi->dev == NULL) {
2575 			device_printf(dev, "failed to add VI %d\n", i);
2576 			continue;
2577 		}
2578 		device_set_softc(vi->dev, vi);
2579 	}
2580 
2581 	cxgbe_sysctls(pi);
2582 
2583 	bus_generic_attach(dev);
2584 
2585 	return (0);
2586 }
2587 
2588 static void
2589 cxgbe_vi_detach(struct vi_info *vi)
2590 {
2591 	struct ifnet *ifp = vi->ifp;
2592 
2593 	if (vi->pfil != NULL) {
2594 		pfil_head_unregister(vi->pfil);
2595 		vi->pfil = NULL;
2596 	}
2597 
2598 	ether_ifdetach(ifp);
2599 
2600 	/* Let detach proceed even if these fail. */
2601 #ifdef DEV_NETMAP
2602 	if (ifp->if_capabilities & IFCAP_NETMAP)
2603 		cxgbe_nm_detach(vi);
2604 #endif
2605 	cxgbe_uninit_synchronized(vi);
2606 	callout_drain(&vi->tick);
2607 	vi_full_uninit(vi);
2608 
2609 	if_free(vi->ifp);
2610 	vi->ifp = NULL;
2611 }
2612 
2613 static int
2614 cxgbe_detach(device_t dev)
2615 {
2616 	struct port_info *pi = device_get_softc(dev);
2617 	struct adapter *sc = pi->adapter;
2618 	int rc;
2619 
2620 	/* Detach the extra VIs first. */
2621 	rc = bus_generic_detach(dev);
2622 	if (rc)
2623 		return (rc);
2624 	device_delete_children(dev);
2625 
2626 	doom_vi(sc, &pi->vi[0]);
2627 
2628 	if (pi->flags & HAS_TRACEQ) {
2629 		sc->traceq = -1;	/* cloner should not create ifnet */
2630 		t4_tracer_port_detach(sc);
2631 	}
2632 
2633 	cxgbe_vi_detach(&pi->vi[0]);
2634 	ifmedia_removeall(&pi->media);
2635 
2636 	end_synchronized_op(sc, 0);
2637 
2638 	return (0);
2639 }
2640 
2641 static void
2642 cxgbe_init(void *arg)
2643 {
2644 	struct vi_info *vi = arg;
2645 	struct adapter *sc = vi->adapter;
2646 
2647 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2648 		return;
2649 	cxgbe_init_synchronized(vi);
2650 	end_synchronized_op(sc, 0);
2651 }
2652 
2653 static int
2654 cxgbe_ioctl(struct ifnet *ifp, unsigned long cmd, caddr_t data)
2655 {
2656 	int rc = 0, mtu, flags;
2657 	struct vi_info *vi = ifp->if_softc;
2658 	struct port_info *pi = vi->pi;
2659 	struct adapter *sc = pi->adapter;
2660 	struct ifreq *ifr = (struct ifreq *)data;
2661 	uint32_t mask;
2662 
2663 	switch (cmd) {
2664 	case SIOCSIFMTU:
2665 		mtu = ifr->ifr_mtu;
2666 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2667 			return (EINVAL);
2668 
2669 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2670 		if (rc)
2671 			return (rc);
2672 		ifp->if_mtu = mtu;
2673 		if (vi->flags & VI_INIT_DONE) {
2674 			t4_update_fl_bufsize(ifp);
2675 			if (!hw_off_limits(sc) &&
2676 			    ifp->if_drv_flags & IFF_DRV_RUNNING)
2677 				rc = update_mac_settings(ifp, XGMAC_MTU);
2678 		}
2679 		end_synchronized_op(sc, 0);
2680 		break;
2681 
2682 	case SIOCSIFFLAGS:
2683 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2684 		if (rc)
2685 			return (rc);
2686 
2687 		if (hw_off_limits(sc)) {
2688 			rc = ENXIO;
2689 			goto fail;
2690 		}
2691 
2692 		if (ifp->if_flags & IFF_UP) {
2693 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2694 				flags = vi->if_flags;
2695 				if ((ifp->if_flags ^ flags) &
2696 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2697 					rc = update_mac_settings(ifp,
2698 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2699 				}
2700 			} else {
2701 				rc = cxgbe_init_synchronized(vi);
2702 			}
2703 			vi->if_flags = ifp->if_flags;
2704 		} else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2705 			rc = cxgbe_uninit_synchronized(vi);
2706 		}
2707 		end_synchronized_op(sc, 0);
2708 		break;
2709 
2710 	case SIOCADDMULTI:
2711 	case SIOCDELMULTI:
2712 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2713 		if (rc)
2714 			return (rc);
2715 		if (!hw_off_limits(sc) && ifp->if_drv_flags & IFF_DRV_RUNNING)
2716 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2717 		end_synchronized_op(sc, 0);
2718 		break;
2719 
2720 	case SIOCSIFCAP:
2721 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2722 		if (rc)
2723 			return (rc);
2724 
2725 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
2726 		if (mask & IFCAP_TXCSUM) {
2727 			ifp->if_capenable ^= IFCAP_TXCSUM;
2728 			ifp->if_hwassist ^= (CSUM_TCP | CSUM_UDP | CSUM_IP);
2729 
2730 			if (IFCAP_TSO4 & ifp->if_capenable &&
2731 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2732 				mask &= ~IFCAP_TSO4;
2733 				ifp->if_capenable &= ~IFCAP_TSO4;
2734 				if_printf(ifp,
2735 				    "tso4 disabled due to -txcsum.\n");
2736 			}
2737 		}
2738 		if (mask & IFCAP_TXCSUM_IPV6) {
2739 			ifp->if_capenable ^= IFCAP_TXCSUM_IPV6;
2740 			ifp->if_hwassist ^= (CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2741 
2742 			if (IFCAP_TSO6 & ifp->if_capenable &&
2743 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2744 				mask &= ~IFCAP_TSO6;
2745 				ifp->if_capenable &= ~IFCAP_TSO6;
2746 				if_printf(ifp,
2747 				    "tso6 disabled due to -txcsum6.\n");
2748 			}
2749 		}
2750 		if (mask & IFCAP_RXCSUM)
2751 			ifp->if_capenable ^= IFCAP_RXCSUM;
2752 		if (mask & IFCAP_RXCSUM_IPV6)
2753 			ifp->if_capenable ^= IFCAP_RXCSUM_IPV6;
2754 
2755 		/*
2756 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2757 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2758 		 * sending a TSO request our way, so it's sufficient to toggle
2759 		 * IFCAP_TSOx only.
2760 		 */
2761 		if (mask & IFCAP_TSO4) {
2762 			if (!(IFCAP_TSO4 & ifp->if_capenable) &&
2763 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2764 				if_printf(ifp, "enable txcsum first.\n");
2765 				rc = EAGAIN;
2766 				goto fail;
2767 			}
2768 			ifp->if_capenable ^= IFCAP_TSO4;
2769 		}
2770 		if (mask & IFCAP_TSO6) {
2771 			if (!(IFCAP_TSO6 & ifp->if_capenable) &&
2772 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2773 				if_printf(ifp, "enable txcsum6 first.\n");
2774 				rc = EAGAIN;
2775 				goto fail;
2776 			}
2777 			ifp->if_capenable ^= IFCAP_TSO6;
2778 		}
2779 		if (mask & IFCAP_LRO) {
2780 #if defined(INET) || defined(INET6)
2781 			int i;
2782 			struct sge_rxq *rxq;
2783 
2784 			ifp->if_capenable ^= IFCAP_LRO;
2785 			for_each_rxq(vi, i, rxq) {
2786 				if (ifp->if_capenable & IFCAP_LRO)
2787 					rxq->iq.flags |= IQ_LRO_ENABLED;
2788 				else
2789 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2790 			}
2791 #endif
2792 		}
2793 #ifdef TCP_OFFLOAD
2794 		if (mask & IFCAP_TOE) {
2795 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TOE;
2796 
2797 			rc = toe_capability(vi, enable);
2798 			if (rc != 0)
2799 				goto fail;
2800 
2801 			ifp->if_capenable ^= mask;
2802 		}
2803 #endif
2804 		if (mask & IFCAP_VLAN_HWTAGGING) {
2805 			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
2806 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2807 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2808 		}
2809 		if (mask & IFCAP_VLAN_MTU) {
2810 			ifp->if_capenable ^= IFCAP_VLAN_MTU;
2811 
2812 			/* Need to find out how to disable auto-mtu-inflation */
2813 		}
2814 		if (mask & IFCAP_VLAN_HWTSO)
2815 			ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
2816 		if (mask & IFCAP_VLAN_HWCSUM)
2817 			ifp->if_capenable ^= IFCAP_VLAN_HWCSUM;
2818 #ifdef RATELIMIT
2819 		if (mask & IFCAP_TXRTLMT)
2820 			ifp->if_capenable ^= IFCAP_TXRTLMT;
2821 #endif
2822 		if (mask & IFCAP_HWRXTSTMP) {
2823 			int i;
2824 			struct sge_rxq *rxq;
2825 
2826 			ifp->if_capenable ^= IFCAP_HWRXTSTMP;
2827 			for_each_rxq(vi, i, rxq) {
2828 				if (ifp->if_capenable & IFCAP_HWRXTSTMP)
2829 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2830 				else
2831 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2832 			}
2833 		}
2834 		if (mask & IFCAP_MEXTPG)
2835 			ifp->if_capenable ^= IFCAP_MEXTPG;
2836 
2837 #ifdef KERN_TLS
2838 		if (mask & IFCAP_TXTLS) {
2839 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TXTLS;
2840 
2841 			rc = ktls_capability(sc, enable);
2842 			if (rc != 0)
2843 				goto fail;
2844 
2845 			ifp->if_capenable ^= (mask & IFCAP_TXTLS);
2846 		}
2847 #endif
2848 		if (mask & IFCAP_VXLAN_HWCSUM) {
2849 			ifp->if_capenable ^= IFCAP_VXLAN_HWCSUM;
2850 			ifp->if_hwassist ^= CSUM_INNER_IP6_UDP |
2851 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
2852 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP;
2853 		}
2854 		if (mask & IFCAP_VXLAN_HWTSO) {
2855 			ifp->if_capenable ^= IFCAP_VXLAN_HWTSO;
2856 			ifp->if_hwassist ^= CSUM_INNER_IP6_TSO |
2857 			    CSUM_INNER_IP_TSO;
2858 		}
2859 
2860 #ifdef VLAN_CAPABILITIES
2861 		VLAN_CAPABILITIES(ifp);
2862 #endif
2863 fail:
2864 		end_synchronized_op(sc, 0);
2865 		break;
2866 
2867 	case SIOCSIFMEDIA:
2868 	case SIOCGIFMEDIA:
2869 	case SIOCGIFXMEDIA:
2870 		ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
2871 		break;
2872 
2873 	case SIOCGI2C: {
2874 		struct ifi2creq i2c;
2875 
2876 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
2877 		if (rc != 0)
2878 			break;
2879 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
2880 			rc = EPERM;
2881 			break;
2882 		}
2883 		if (i2c.len > sizeof(i2c.data)) {
2884 			rc = EINVAL;
2885 			break;
2886 		}
2887 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
2888 		if (rc)
2889 			return (rc);
2890 		if (hw_off_limits(sc))
2891 			rc = ENXIO;
2892 		else
2893 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
2894 			    i2c.offset, i2c.len, &i2c.data[0]);
2895 		end_synchronized_op(sc, 0);
2896 		if (rc == 0)
2897 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
2898 		break;
2899 	}
2900 
2901 	default:
2902 		rc = ether_ioctl(ifp, cmd, data);
2903 	}
2904 
2905 	return (rc);
2906 }
2907 
2908 static int
2909 cxgbe_transmit(struct ifnet *ifp, struct mbuf *m)
2910 {
2911 	struct vi_info *vi = ifp->if_softc;
2912 	struct port_info *pi = vi->pi;
2913 	struct adapter *sc;
2914 	struct sge_txq *txq;
2915 	void *items[1];
2916 	int rc;
2917 
2918 	M_ASSERTPKTHDR(m);
2919 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
2920 #if defined(KERN_TLS) || defined(RATELIMIT)
2921 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
2922 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
2923 #endif
2924 
2925 	if (__predict_false(pi->link_cfg.link_ok == false)) {
2926 		m_freem(m);
2927 		return (ENETDOWN);
2928 	}
2929 
2930 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
2931 	if (__predict_false(rc != 0)) {
2932 		MPASS(m == NULL);			/* was freed already */
2933 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
2934 		return (rc);
2935 	}
2936 #ifdef RATELIMIT
2937 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG) {
2938 		if (m->m_pkthdr.snd_tag->sw->type == IF_SND_TAG_TYPE_RATE_LIMIT)
2939 			return (ethofld_transmit(ifp, m));
2940 	}
2941 #endif
2942 
2943 	/* Select a txq. */
2944 	sc = vi->adapter;
2945 	txq = &sc->sge.txq[vi->first_txq];
2946 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
2947 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
2948 		    vi->rsrv_noflowq);
2949 
2950 	items[0] = m;
2951 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
2952 	if (__predict_false(rc != 0))
2953 		m_freem(m);
2954 
2955 	return (rc);
2956 }
2957 
2958 static void
2959 cxgbe_qflush(struct ifnet *ifp)
2960 {
2961 	struct vi_info *vi = ifp->if_softc;
2962 	struct sge_txq *txq;
2963 	int i;
2964 
2965 	/* queues do not exist if !VI_INIT_DONE. */
2966 	if (vi->flags & VI_INIT_DONE) {
2967 		for_each_txq(vi, i, txq) {
2968 			TXQ_LOCK(txq);
2969 			txq->eq.flags |= EQ_QFLUSH;
2970 			TXQ_UNLOCK(txq);
2971 			while (!mp_ring_is_idle(txq->r)) {
2972 				mp_ring_check_drainage(txq->r, 4096);
2973 				pause("qflush", 1);
2974 			}
2975 			TXQ_LOCK(txq);
2976 			txq->eq.flags &= ~EQ_QFLUSH;
2977 			TXQ_UNLOCK(txq);
2978 		}
2979 	}
2980 	if_qflush(ifp);
2981 }
2982 
2983 static uint64_t
2984 vi_get_counter(struct ifnet *ifp, ift_counter c)
2985 {
2986 	struct vi_info *vi = ifp->if_softc;
2987 	struct fw_vi_stats_vf *s = &vi->stats;
2988 
2989 	mtx_lock(&vi->tick_mtx);
2990 	vi_refresh_stats(vi);
2991 	mtx_unlock(&vi->tick_mtx);
2992 
2993 	switch (c) {
2994 	case IFCOUNTER_IPACKETS:
2995 		return (s->rx_bcast_frames + s->rx_mcast_frames +
2996 		    s->rx_ucast_frames);
2997 	case IFCOUNTER_IERRORS:
2998 		return (s->rx_err_frames);
2999 	case IFCOUNTER_OPACKETS:
3000 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3001 		    s->tx_ucast_frames + s->tx_offload_frames);
3002 	case IFCOUNTER_OERRORS:
3003 		return (s->tx_drop_frames);
3004 	case IFCOUNTER_IBYTES:
3005 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3006 		    s->rx_ucast_bytes);
3007 	case IFCOUNTER_OBYTES:
3008 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3009 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3010 	case IFCOUNTER_IMCASTS:
3011 		return (s->rx_mcast_frames);
3012 	case IFCOUNTER_OMCASTS:
3013 		return (s->tx_mcast_frames);
3014 	case IFCOUNTER_OQDROPS: {
3015 		uint64_t drops;
3016 
3017 		drops = 0;
3018 		if (vi->flags & VI_INIT_DONE) {
3019 			int i;
3020 			struct sge_txq *txq;
3021 
3022 			for_each_txq(vi, i, txq)
3023 				drops += counter_u64_fetch(txq->r->dropped);
3024 		}
3025 
3026 		return (drops);
3027 
3028 	}
3029 
3030 	default:
3031 		return (if_get_counter_default(ifp, c));
3032 	}
3033 }
3034 
3035 static uint64_t
3036 cxgbe_get_counter(struct ifnet *ifp, ift_counter c)
3037 {
3038 	struct vi_info *vi = ifp->if_softc;
3039 	struct port_info *pi = vi->pi;
3040 	struct port_stats *s = &pi->stats;
3041 
3042 	mtx_lock(&vi->tick_mtx);
3043 	cxgbe_refresh_stats(vi);
3044 	mtx_unlock(&vi->tick_mtx);
3045 
3046 	switch (c) {
3047 	case IFCOUNTER_IPACKETS:
3048 		return (s->rx_frames);
3049 
3050 	case IFCOUNTER_IERRORS:
3051 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3052 		    s->rx_fcs_err + s->rx_len_err);
3053 
3054 	case IFCOUNTER_OPACKETS:
3055 		return (s->tx_frames);
3056 
3057 	case IFCOUNTER_OERRORS:
3058 		return (s->tx_error_frames);
3059 
3060 	case IFCOUNTER_IBYTES:
3061 		return (s->rx_octets);
3062 
3063 	case IFCOUNTER_OBYTES:
3064 		return (s->tx_octets);
3065 
3066 	case IFCOUNTER_IMCASTS:
3067 		return (s->rx_mcast_frames);
3068 
3069 	case IFCOUNTER_OMCASTS:
3070 		return (s->tx_mcast_frames);
3071 
3072 	case IFCOUNTER_IQDROPS:
3073 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3074 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3075 		    s->rx_trunc3 + pi->tnl_cong_drops);
3076 
3077 	case IFCOUNTER_OQDROPS: {
3078 		uint64_t drops;
3079 
3080 		drops = s->tx_drop;
3081 		if (vi->flags & VI_INIT_DONE) {
3082 			int i;
3083 			struct sge_txq *txq;
3084 
3085 			for_each_txq(vi, i, txq)
3086 				drops += counter_u64_fetch(txq->r->dropped);
3087 		}
3088 
3089 		return (drops);
3090 
3091 	}
3092 
3093 	default:
3094 		return (if_get_counter_default(ifp, c));
3095 	}
3096 }
3097 
3098 #if defined(KERN_TLS) || defined(RATELIMIT)
3099 static int
3100 cxgbe_snd_tag_alloc(struct ifnet *ifp, union if_snd_tag_alloc_params *params,
3101     struct m_snd_tag **pt)
3102 {
3103 	int error;
3104 
3105 	switch (params->hdr.type) {
3106 #ifdef RATELIMIT
3107 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3108 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3109 		break;
3110 #endif
3111 #ifdef KERN_TLS
3112 	case IF_SND_TAG_TYPE_TLS:
3113 		error = cxgbe_tls_tag_alloc(ifp, params, pt);
3114 		break;
3115 #endif
3116 	default:
3117 		error = EOPNOTSUPP;
3118 	}
3119 	return (error);
3120 }
3121 #endif
3122 
3123 /*
3124  * The kernel picks a media from the list we had provided but we still validate
3125  * the requeste.
3126  */
3127 int
3128 cxgbe_media_change(struct ifnet *ifp)
3129 {
3130 	struct vi_info *vi = ifp->if_softc;
3131 	struct port_info *pi = vi->pi;
3132 	struct ifmedia *ifm = &pi->media;
3133 	struct link_config *lc = &pi->link_cfg;
3134 	struct adapter *sc = pi->adapter;
3135 	int rc;
3136 
3137 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3138 	if (rc != 0)
3139 		return (rc);
3140 	PORT_LOCK(pi);
3141 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3142 		/* ifconfig .. media autoselect */
3143 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3144 			rc = ENOTSUP; /* AN not supported by transceiver */
3145 			goto done;
3146 		}
3147 		lc->requested_aneg = AUTONEG_ENABLE;
3148 		lc->requested_speed = 0;
3149 		lc->requested_fc |= PAUSE_AUTONEG;
3150 	} else {
3151 		lc->requested_aneg = AUTONEG_DISABLE;
3152 		lc->requested_speed =
3153 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3154 		lc->requested_fc = 0;
3155 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3156 			lc->requested_fc |= PAUSE_RX;
3157 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3158 			lc->requested_fc |= PAUSE_TX;
3159 	}
3160 	if (pi->up_vis > 0) {
3161 		fixup_link_config(pi);
3162 		rc = apply_link_config(pi);
3163 	}
3164 done:
3165 	PORT_UNLOCK(pi);
3166 	end_synchronized_op(sc, 0);
3167 	return (rc);
3168 }
3169 
3170 /*
3171  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3172  * given speed.
3173  */
3174 static int
3175 port_mword(struct port_info *pi, uint32_t speed)
3176 {
3177 
3178 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3179 	MPASS(powerof2(speed));
3180 
3181 	switch(pi->port_type) {
3182 	case FW_PORT_TYPE_BT_SGMII:
3183 	case FW_PORT_TYPE_BT_XFI:
3184 	case FW_PORT_TYPE_BT_XAUI:
3185 		/* BaseT */
3186 		switch (speed) {
3187 		case FW_PORT_CAP32_SPEED_100M:
3188 			return (IFM_100_T);
3189 		case FW_PORT_CAP32_SPEED_1G:
3190 			return (IFM_1000_T);
3191 		case FW_PORT_CAP32_SPEED_10G:
3192 			return (IFM_10G_T);
3193 		}
3194 		break;
3195 	case FW_PORT_TYPE_KX4:
3196 		if (speed == FW_PORT_CAP32_SPEED_10G)
3197 			return (IFM_10G_KX4);
3198 		break;
3199 	case FW_PORT_TYPE_CX4:
3200 		if (speed == FW_PORT_CAP32_SPEED_10G)
3201 			return (IFM_10G_CX4);
3202 		break;
3203 	case FW_PORT_TYPE_KX:
3204 		if (speed == FW_PORT_CAP32_SPEED_1G)
3205 			return (IFM_1000_KX);
3206 		break;
3207 	case FW_PORT_TYPE_KR:
3208 	case FW_PORT_TYPE_BP_AP:
3209 	case FW_PORT_TYPE_BP4_AP:
3210 	case FW_PORT_TYPE_BP40_BA:
3211 	case FW_PORT_TYPE_KR4_100G:
3212 	case FW_PORT_TYPE_KR_SFP28:
3213 	case FW_PORT_TYPE_KR_XLAUI:
3214 		switch (speed) {
3215 		case FW_PORT_CAP32_SPEED_1G:
3216 			return (IFM_1000_KX);
3217 		case FW_PORT_CAP32_SPEED_10G:
3218 			return (IFM_10G_KR);
3219 		case FW_PORT_CAP32_SPEED_25G:
3220 			return (IFM_25G_KR);
3221 		case FW_PORT_CAP32_SPEED_40G:
3222 			return (IFM_40G_KR4);
3223 		case FW_PORT_CAP32_SPEED_50G:
3224 			return (IFM_50G_KR2);
3225 		case FW_PORT_CAP32_SPEED_100G:
3226 			return (IFM_100G_KR4);
3227 		}
3228 		break;
3229 	case FW_PORT_TYPE_FIBER_XFI:
3230 	case FW_PORT_TYPE_FIBER_XAUI:
3231 	case FW_PORT_TYPE_SFP:
3232 	case FW_PORT_TYPE_QSFP_10G:
3233 	case FW_PORT_TYPE_QSA:
3234 	case FW_PORT_TYPE_QSFP:
3235 	case FW_PORT_TYPE_CR4_QSFP:
3236 	case FW_PORT_TYPE_CR_QSFP:
3237 	case FW_PORT_TYPE_CR2_QSFP:
3238 	case FW_PORT_TYPE_SFP28:
3239 		/* Pluggable transceiver */
3240 		switch (pi->mod_type) {
3241 		case FW_PORT_MOD_TYPE_LR:
3242 			switch (speed) {
3243 			case FW_PORT_CAP32_SPEED_1G:
3244 				return (IFM_1000_LX);
3245 			case FW_PORT_CAP32_SPEED_10G:
3246 				return (IFM_10G_LR);
3247 			case FW_PORT_CAP32_SPEED_25G:
3248 				return (IFM_25G_LR);
3249 			case FW_PORT_CAP32_SPEED_40G:
3250 				return (IFM_40G_LR4);
3251 			case FW_PORT_CAP32_SPEED_50G:
3252 				return (IFM_50G_LR2);
3253 			case FW_PORT_CAP32_SPEED_100G:
3254 				return (IFM_100G_LR4);
3255 			}
3256 			break;
3257 		case FW_PORT_MOD_TYPE_SR:
3258 			switch (speed) {
3259 			case FW_PORT_CAP32_SPEED_1G:
3260 				return (IFM_1000_SX);
3261 			case FW_PORT_CAP32_SPEED_10G:
3262 				return (IFM_10G_SR);
3263 			case FW_PORT_CAP32_SPEED_25G:
3264 				return (IFM_25G_SR);
3265 			case FW_PORT_CAP32_SPEED_40G:
3266 				return (IFM_40G_SR4);
3267 			case FW_PORT_CAP32_SPEED_50G:
3268 				return (IFM_50G_SR2);
3269 			case FW_PORT_CAP32_SPEED_100G:
3270 				return (IFM_100G_SR4);
3271 			}
3272 			break;
3273 		case FW_PORT_MOD_TYPE_ER:
3274 			if (speed == FW_PORT_CAP32_SPEED_10G)
3275 				return (IFM_10G_ER);
3276 			break;
3277 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3278 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3279 			switch (speed) {
3280 			case FW_PORT_CAP32_SPEED_1G:
3281 				return (IFM_1000_CX);
3282 			case FW_PORT_CAP32_SPEED_10G:
3283 				return (IFM_10G_TWINAX);
3284 			case FW_PORT_CAP32_SPEED_25G:
3285 				return (IFM_25G_CR);
3286 			case FW_PORT_CAP32_SPEED_40G:
3287 				return (IFM_40G_CR4);
3288 			case FW_PORT_CAP32_SPEED_50G:
3289 				return (IFM_50G_CR2);
3290 			case FW_PORT_CAP32_SPEED_100G:
3291 				return (IFM_100G_CR4);
3292 			}
3293 			break;
3294 		case FW_PORT_MOD_TYPE_LRM:
3295 			if (speed == FW_PORT_CAP32_SPEED_10G)
3296 				return (IFM_10G_LRM);
3297 			break;
3298 		case FW_PORT_MOD_TYPE_NA:
3299 			MPASS(0);	/* Not pluggable? */
3300 			/* fall throough */
3301 		case FW_PORT_MOD_TYPE_ERROR:
3302 		case FW_PORT_MOD_TYPE_UNKNOWN:
3303 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3304 			break;
3305 		case FW_PORT_MOD_TYPE_NONE:
3306 			return (IFM_NONE);
3307 		}
3308 		break;
3309 	case FW_PORT_TYPE_NONE:
3310 		return (IFM_NONE);
3311 	}
3312 
3313 	return (IFM_UNKNOWN);
3314 }
3315 
3316 void
3317 cxgbe_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
3318 {
3319 	struct vi_info *vi = ifp->if_softc;
3320 	struct port_info *pi = vi->pi;
3321 	struct adapter *sc = pi->adapter;
3322 	struct link_config *lc = &pi->link_cfg;
3323 
3324 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4med") != 0)
3325 		return;
3326 	PORT_LOCK(pi);
3327 
3328 	if (pi->up_vis == 0) {
3329 		/*
3330 		 * If all the interfaces are administratively down the firmware
3331 		 * does not report transceiver changes.  Refresh port info here
3332 		 * so that ifconfig displays accurate ifmedia at all times.
3333 		 * This is the only reason we have a synchronized op in this
3334 		 * function.  Just PORT_LOCK would have been enough otherwise.
3335 		 */
3336 		t4_update_port_info(pi);
3337 		build_medialist(pi);
3338 	}
3339 
3340 	/* ifm_status */
3341 	ifmr->ifm_status = IFM_AVALID;
3342 	if (lc->link_ok == false)
3343 		goto done;
3344 	ifmr->ifm_status |= IFM_ACTIVE;
3345 
3346 	/* ifm_active */
3347 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3348 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3349 	if (lc->fc & PAUSE_RX)
3350 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3351 	if (lc->fc & PAUSE_TX)
3352 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3353 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3354 done:
3355 	PORT_UNLOCK(pi);
3356 	end_synchronized_op(sc, 0);
3357 }
3358 
3359 static int
3360 vcxgbe_probe(device_t dev)
3361 {
3362 	char buf[128];
3363 	struct vi_info *vi = device_get_softc(dev);
3364 
3365 	snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
3366 	    vi - vi->pi->vi);
3367 	device_set_desc_copy(dev, buf);
3368 
3369 	return (BUS_PROBE_DEFAULT);
3370 }
3371 
3372 static int
3373 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3374 {
3375 	int func, index, rc;
3376 	uint32_t param, val;
3377 
3378 	ASSERT_SYNCHRONIZED_OP(sc);
3379 
3380 	index = vi - pi->vi;
3381 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3382 	KASSERT(index < nitems(vi_mac_funcs),
3383 	    ("%s: VI %s doesn't have a MAC func", __func__,
3384 	    device_get_nameunit(vi->dev)));
3385 	func = vi_mac_funcs[index];
3386 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3387 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3388 	if (rc < 0) {
3389 		CH_ERR(vi, "failed to allocate virtual interface %d"
3390 		    "for port %d: %d\n", index, pi->port_id, -rc);
3391 		return (-rc);
3392 	}
3393 	vi->viid = rc;
3394 
3395 	if (vi->rss_size == 1) {
3396 		/*
3397 		 * This VI didn't get a slice of the RSS table.  Reduce the
3398 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3399 		 * configuration file (nvi, rssnvi for this PF) if this is a
3400 		 * problem.
3401 		 */
3402 		device_printf(vi->dev, "RSS table not available.\n");
3403 		vi->rss_base = 0xffff;
3404 
3405 		return (0);
3406 	}
3407 
3408 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3409 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3410 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3411 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3412 	if (rc)
3413 		vi->rss_base = 0xffff;
3414 	else {
3415 		MPASS((val >> 16) == vi->rss_size);
3416 		vi->rss_base = val & 0xffff;
3417 	}
3418 
3419 	return (0);
3420 }
3421 
3422 static int
3423 vcxgbe_attach(device_t dev)
3424 {
3425 	struct vi_info *vi;
3426 	struct port_info *pi;
3427 	struct adapter *sc;
3428 	int rc;
3429 
3430 	vi = device_get_softc(dev);
3431 	pi = vi->pi;
3432 	sc = pi->adapter;
3433 
3434 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3435 	if (rc)
3436 		return (rc);
3437 	rc = alloc_extra_vi(sc, pi, vi);
3438 	end_synchronized_op(sc, 0);
3439 	if (rc)
3440 		return (rc);
3441 
3442 	rc = cxgbe_vi_attach(dev, vi);
3443 	if (rc) {
3444 		t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3445 		return (rc);
3446 	}
3447 	return (0);
3448 }
3449 
3450 static int
3451 vcxgbe_detach(device_t dev)
3452 {
3453 	struct vi_info *vi;
3454 	struct adapter *sc;
3455 
3456 	vi = device_get_softc(dev);
3457 	sc = vi->adapter;
3458 
3459 	doom_vi(sc, vi);
3460 
3461 	cxgbe_vi_detach(vi);
3462 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3463 
3464 	end_synchronized_op(sc, 0);
3465 
3466 	return (0);
3467 }
3468 
3469 static struct callout fatal_callout;
3470 static struct taskqueue *reset_tq;
3471 
3472 static void
3473 delayed_panic(void *arg)
3474 {
3475 	struct adapter *sc = arg;
3476 
3477 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3478 }
3479 
3480 void
3481 t4_fatal_err(struct adapter *sc, bool fw_error)
3482 {
3483 
3484 	t4_shutdown_adapter(sc);
3485 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped.\n",
3486 	    device_get_nameunit(sc->dev));
3487 	if (fw_error) {
3488 		if (sc->flags & CHK_MBOX_ACCESS)
3489 			ASSERT_SYNCHRONIZED_OP(sc);
3490 		sc->flags |= ADAP_ERR;
3491 	} else {
3492 		ADAPTER_LOCK(sc);
3493 		sc->flags |= ADAP_ERR;
3494 		ADAPTER_UNLOCK(sc);
3495 	}
3496 #ifdef TCP_OFFLOAD
3497 	taskqueue_enqueue(taskqueue_thread, &sc->async_event_task);
3498 #endif
3499 
3500 	if (t4_panic_on_fatal_err) {
3501 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3502 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3503 	} else if (t4_reset_on_fatal_err) {
3504 		CH_ALERT(sc, "resetting on fatal error.\n");
3505 		taskqueue_enqueue(reset_tq, &sc->reset_task);
3506 	}
3507 }
3508 
3509 void
3510 t4_add_adapter(struct adapter *sc)
3511 {
3512 	sx_xlock(&t4_list_lock);
3513 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3514 	sx_xunlock(&t4_list_lock);
3515 }
3516 
3517 int
3518 t4_map_bars_0_and_4(struct adapter *sc)
3519 {
3520 	sc->regs_rid = PCIR_BAR(0);
3521 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3522 	    &sc->regs_rid, RF_ACTIVE);
3523 	if (sc->regs_res == NULL) {
3524 		device_printf(sc->dev, "cannot map registers.\n");
3525 		return (ENXIO);
3526 	}
3527 	sc->bt = rman_get_bustag(sc->regs_res);
3528 	sc->bh = rman_get_bushandle(sc->regs_res);
3529 	sc->mmio_len = rman_get_size(sc->regs_res);
3530 	setbit(&sc->doorbells, DOORBELL_KDB);
3531 
3532 	sc->msix_rid = PCIR_BAR(4);
3533 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3534 	    &sc->msix_rid, RF_ACTIVE);
3535 	if (sc->msix_res == NULL) {
3536 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3537 		return (ENXIO);
3538 	}
3539 
3540 	return (0);
3541 }
3542 
3543 int
3544 t4_map_bar_2(struct adapter *sc)
3545 {
3546 
3547 	/*
3548 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3549 	 * to map it if RDMA is disabled.
3550 	 */
3551 	if (is_t4(sc) && sc->rdmacaps == 0)
3552 		return (0);
3553 
3554 	sc->udbs_rid = PCIR_BAR(2);
3555 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3556 	    &sc->udbs_rid, RF_ACTIVE);
3557 	if (sc->udbs_res == NULL) {
3558 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3559 		return (ENXIO);
3560 	}
3561 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3562 
3563 	if (chip_id(sc) >= CHELSIO_T5) {
3564 		setbit(&sc->doorbells, DOORBELL_UDB);
3565 #if defined(__i386__) || defined(__amd64__)
3566 		if (t5_write_combine) {
3567 			int rc, mode;
3568 
3569 			/*
3570 			 * Enable write combining on BAR2.  This is the
3571 			 * userspace doorbell BAR and is split into 128B
3572 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3573 			 * with an egress queue.  The first 64B has the doorbell
3574 			 * and the second 64B can be used to submit a tx work
3575 			 * request with an implicit doorbell.
3576 			 */
3577 
3578 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3579 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3580 			if (rc == 0) {
3581 				clrbit(&sc->doorbells, DOORBELL_UDB);
3582 				setbit(&sc->doorbells, DOORBELL_WCWR);
3583 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3584 			} else {
3585 				device_printf(sc->dev,
3586 				    "couldn't enable write combining: %d\n",
3587 				    rc);
3588 			}
3589 
3590 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3591 			t4_write_reg(sc, A_SGE_STAT_CFG,
3592 			    V_STATSOURCE_T5(7) | mode);
3593 		}
3594 #endif
3595 	}
3596 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3597 
3598 	return (0);
3599 }
3600 
3601 struct memwin_init {
3602 	uint32_t base;
3603 	uint32_t aperture;
3604 };
3605 
3606 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3607 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3608 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3609 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3610 };
3611 
3612 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3613 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3614 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3615 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3616 };
3617 
3618 static void
3619 setup_memwin(struct adapter *sc)
3620 {
3621 	const struct memwin_init *mw_init;
3622 	struct memwin *mw;
3623 	int i;
3624 	uint32_t bar0;
3625 
3626 	if (is_t4(sc)) {
3627 		/*
3628 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3629 		 * mechanism.  Works from within PCI passthrough environments
3630 		 * too, where rman_get_start() can return a different value.  We
3631 		 * need to program the T4 memory window decoders with the actual
3632 		 * addresses that will be coming across the PCIe link.
3633 		 */
3634 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3635 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3636 
3637 		mw_init = &t4_memwin[0];
3638 	} else {
3639 		/* T5+ use the relative offset inside the PCIe BAR */
3640 		bar0 = 0;
3641 
3642 		mw_init = &t5_memwin[0];
3643 	}
3644 
3645 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3646 		if (!rw_initialized(&mw->mw_lock)) {
3647 			rw_init(&mw->mw_lock, "memory window access");
3648 			mw->mw_base = mw_init->base;
3649 			mw->mw_aperture = mw_init->aperture;
3650 			mw->mw_curpos = 0;
3651 		}
3652 		t4_write_reg(sc,
3653 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3654 		    (mw->mw_base + bar0) | V_BIR(0) |
3655 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3656 		rw_wlock(&mw->mw_lock);
3657 		position_memwin(sc, i, mw->mw_curpos);
3658 		rw_wunlock(&mw->mw_lock);
3659 	}
3660 
3661 	/* flush */
3662 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3663 }
3664 
3665 /*
3666  * Positions the memory window at the given address in the card's address space.
3667  * There are some alignment requirements and the actual position may be at an
3668  * address prior to the requested address.  mw->mw_curpos always has the actual
3669  * position of the window.
3670  */
3671 static void
3672 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3673 {
3674 	struct memwin *mw;
3675 	uint32_t pf;
3676 	uint32_t reg;
3677 
3678 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3679 	mw = &sc->memwin[idx];
3680 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3681 
3682 	if (is_t4(sc)) {
3683 		pf = 0;
3684 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3685 	} else {
3686 		pf = V_PFNUM(sc->pf);
3687 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3688 	}
3689 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3690 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3691 	t4_read_reg(sc, reg);	/* flush */
3692 }
3693 
3694 int
3695 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3696     int len, int rw)
3697 {
3698 	struct memwin *mw;
3699 	uint32_t mw_end, v;
3700 
3701 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3702 
3703 	/* Memory can only be accessed in naturally aligned 4 byte units */
3704 	if (addr & 3 || len & 3 || len <= 0)
3705 		return (EINVAL);
3706 
3707 	mw = &sc->memwin[idx];
3708 	while (len > 0) {
3709 		rw_rlock(&mw->mw_lock);
3710 		mw_end = mw->mw_curpos + mw->mw_aperture;
3711 		if (addr >= mw_end || addr < mw->mw_curpos) {
3712 			/* Will need to reposition the window */
3713 			if (!rw_try_upgrade(&mw->mw_lock)) {
3714 				rw_runlock(&mw->mw_lock);
3715 				rw_wlock(&mw->mw_lock);
3716 			}
3717 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3718 			position_memwin(sc, idx, addr);
3719 			rw_downgrade(&mw->mw_lock);
3720 			mw_end = mw->mw_curpos + mw->mw_aperture;
3721 		}
3722 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3723 		while (addr < mw_end && len > 0) {
3724 			if (rw == 0) {
3725 				v = t4_read_reg(sc, mw->mw_base + addr -
3726 				    mw->mw_curpos);
3727 				*val++ = le32toh(v);
3728 			} else {
3729 				v = *val++;
3730 				t4_write_reg(sc, mw->mw_base + addr -
3731 				    mw->mw_curpos, htole32(v));
3732 			}
3733 			addr += 4;
3734 			len -= 4;
3735 		}
3736 		rw_runlock(&mw->mw_lock);
3737 	}
3738 
3739 	return (0);
3740 }
3741 
3742 static void
3743 t4_init_atid_table(struct adapter *sc)
3744 {
3745 	struct tid_info *t;
3746 	int i;
3747 
3748 	t = &sc->tids;
3749 	if (t->natids == 0)
3750 		return;
3751 
3752 	MPASS(t->atid_tab == NULL);
3753 
3754 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3755 	    M_ZERO | M_WAITOK);
3756 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3757 	t->afree = t->atid_tab;
3758 	t->atids_in_use = 0;
3759 	for (i = 1; i < t->natids; i++)
3760 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3761 	t->atid_tab[t->natids - 1].next = NULL;
3762 }
3763 
3764 static void
3765 t4_free_atid_table(struct adapter *sc)
3766 {
3767 	struct tid_info *t;
3768 
3769 	t = &sc->tids;
3770 
3771 	KASSERT(t->atids_in_use == 0,
3772 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3773 
3774 	if (mtx_initialized(&t->atid_lock))
3775 		mtx_destroy(&t->atid_lock);
3776 	free(t->atid_tab, M_CXGBE);
3777 	t->atid_tab = NULL;
3778 }
3779 
3780 int
3781 alloc_atid(struct adapter *sc, void *ctx)
3782 {
3783 	struct tid_info *t = &sc->tids;
3784 	int atid = -1;
3785 
3786 	mtx_lock(&t->atid_lock);
3787 	if (t->afree) {
3788 		union aopen_entry *p = t->afree;
3789 
3790 		atid = p - t->atid_tab;
3791 		MPASS(atid <= M_TID_TID);
3792 		t->afree = p->next;
3793 		p->data = ctx;
3794 		t->atids_in_use++;
3795 	}
3796 	mtx_unlock(&t->atid_lock);
3797 	return (atid);
3798 }
3799 
3800 void *
3801 lookup_atid(struct adapter *sc, int atid)
3802 {
3803 	struct tid_info *t = &sc->tids;
3804 
3805 	return (t->atid_tab[atid].data);
3806 }
3807 
3808 void
3809 free_atid(struct adapter *sc, int atid)
3810 {
3811 	struct tid_info *t = &sc->tids;
3812 	union aopen_entry *p = &t->atid_tab[atid];
3813 
3814 	mtx_lock(&t->atid_lock);
3815 	p->next = t->afree;
3816 	t->afree = p;
3817 	t->atids_in_use--;
3818 	mtx_unlock(&t->atid_lock);
3819 }
3820 
3821 static void
3822 queue_tid_release(struct adapter *sc, int tid)
3823 {
3824 
3825 	CXGBE_UNIMPLEMENTED("deferred tid release");
3826 }
3827 
3828 void
3829 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
3830 {
3831 	struct wrqe *wr;
3832 	struct cpl_tid_release *req;
3833 
3834 	wr = alloc_wrqe(sizeof(*req), ctrlq);
3835 	if (wr == NULL) {
3836 		queue_tid_release(sc, tid);	/* defer */
3837 		return;
3838 	}
3839 	req = wrtod(wr);
3840 
3841 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
3842 
3843 	t4_wrq_tx(sc, wr);
3844 }
3845 
3846 static int
3847 t4_range_cmp(const void *a, const void *b)
3848 {
3849 	return ((const struct t4_range *)a)->start -
3850 	       ((const struct t4_range *)b)->start;
3851 }
3852 
3853 /*
3854  * Verify that the memory range specified by the addr/len pair is valid within
3855  * the card's address space.
3856  */
3857 static int
3858 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
3859 {
3860 	struct t4_range mem_ranges[4], *r, *next;
3861 	uint32_t em, addr_len;
3862 	int i, n, remaining;
3863 
3864 	/* Memory can only be accessed in naturally aligned 4 byte units */
3865 	if (addr & 3 || len & 3 || len == 0)
3866 		return (EINVAL);
3867 
3868 	/* Enabled memories */
3869 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
3870 
3871 	r = &mem_ranges[0];
3872 	n = 0;
3873 	bzero(r, sizeof(mem_ranges));
3874 	if (em & F_EDRAM0_ENABLE) {
3875 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
3876 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
3877 		if (r->size > 0) {
3878 			r->start = G_EDRAM0_BASE(addr_len) << 20;
3879 			if (addr >= r->start &&
3880 			    addr + len <= r->start + r->size)
3881 				return (0);
3882 			r++;
3883 			n++;
3884 		}
3885 	}
3886 	if (em & F_EDRAM1_ENABLE) {
3887 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
3888 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
3889 		if (r->size > 0) {
3890 			r->start = G_EDRAM1_BASE(addr_len) << 20;
3891 			if (addr >= r->start &&
3892 			    addr + len <= r->start + r->size)
3893 				return (0);
3894 			r++;
3895 			n++;
3896 		}
3897 	}
3898 	if (em & F_EXT_MEM_ENABLE) {
3899 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
3900 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
3901 		if (r->size > 0) {
3902 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
3903 			if (addr >= r->start &&
3904 			    addr + len <= r->start + r->size)
3905 				return (0);
3906 			r++;
3907 			n++;
3908 		}
3909 	}
3910 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
3911 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
3912 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
3913 		if (r->size > 0) {
3914 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
3915 			if (addr >= r->start &&
3916 			    addr + len <= r->start + r->size)
3917 				return (0);
3918 			r++;
3919 			n++;
3920 		}
3921 	}
3922 	MPASS(n <= nitems(mem_ranges));
3923 
3924 	if (n > 1) {
3925 		/* Sort and merge the ranges. */
3926 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
3927 
3928 		/* Start from index 0 and examine the next n - 1 entries. */
3929 		r = &mem_ranges[0];
3930 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
3931 
3932 			MPASS(r->size > 0);	/* r is a valid entry. */
3933 			next = r + 1;
3934 			MPASS(next->size > 0);	/* and so is the next one. */
3935 
3936 			while (r->start + r->size >= next->start) {
3937 				/* Merge the next one into the current entry. */
3938 				r->size = max(r->start + r->size,
3939 				    next->start + next->size) - r->start;
3940 				n--;	/* One fewer entry in total. */
3941 				if (--remaining == 0)
3942 					goto done;	/* short circuit */
3943 				next++;
3944 			}
3945 			if (next != r + 1) {
3946 				/*
3947 				 * Some entries were merged into r and next
3948 				 * points to the first valid entry that couldn't
3949 				 * be merged.
3950 				 */
3951 				MPASS(next->size > 0);	/* must be valid */
3952 				memcpy(r + 1, next, remaining * sizeof(*r));
3953 #ifdef INVARIANTS
3954 				/*
3955 				 * This so that the foo->size assertion in the
3956 				 * next iteration of the loop do the right
3957 				 * thing for entries that were pulled up and are
3958 				 * no longer valid.
3959 				 */
3960 				MPASS(n < nitems(mem_ranges));
3961 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
3962 				    sizeof(struct t4_range));
3963 #endif
3964 			}
3965 		}
3966 done:
3967 		/* Done merging the ranges. */
3968 		MPASS(n > 0);
3969 		r = &mem_ranges[0];
3970 		for (i = 0; i < n; i++, r++) {
3971 			if (addr >= r->start &&
3972 			    addr + len <= r->start + r->size)
3973 				return (0);
3974 		}
3975 	}
3976 
3977 	return (EFAULT);
3978 }
3979 
3980 static int
3981 fwmtype_to_hwmtype(int mtype)
3982 {
3983 
3984 	switch (mtype) {
3985 	case FW_MEMTYPE_EDC0:
3986 		return (MEM_EDC0);
3987 	case FW_MEMTYPE_EDC1:
3988 		return (MEM_EDC1);
3989 	case FW_MEMTYPE_EXTMEM:
3990 		return (MEM_MC0);
3991 	case FW_MEMTYPE_EXTMEM1:
3992 		return (MEM_MC1);
3993 	default:
3994 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
3995 	}
3996 }
3997 
3998 /*
3999  * Verify that the memory range specified by the memtype/offset/len pair is
4000  * valid and lies entirely within the memtype specified.  The global address of
4001  * the start of the range is returned in addr.
4002  */
4003 static int
4004 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4005     uint32_t *addr)
4006 {
4007 	uint32_t em, addr_len, maddr;
4008 
4009 	/* Memory can only be accessed in naturally aligned 4 byte units */
4010 	if (off & 3 || len & 3 || len == 0)
4011 		return (EINVAL);
4012 
4013 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4014 	switch (fwmtype_to_hwmtype(mtype)) {
4015 	case MEM_EDC0:
4016 		if (!(em & F_EDRAM0_ENABLE))
4017 			return (EINVAL);
4018 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4019 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4020 		break;
4021 	case MEM_EDC1:
4022 		if (!(em & F_EDRAM1_ENABLE))
4023 			return (EINVAL);
4024 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4025 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4026 		break;
4027 	case MEM_MC:
4028 		if (!(em & F_EXT_MEM_ENABLE))
4029 			return (EINVAL);
4030 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4031 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4032 		break;
4033 	case MEM_MC1:
4034 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4035 			return (EINVAL);
4036 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4037 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4038 		break;
4039 	default:
4040 		return (EINVAL);
4041 	}
4042 
4043 	*addr = maddr + off;	/* global address */
4044 	return (validate_mem_range(sc, *addr, len));
4045 }
4046 
4047 static int
4048 fixup_devlog_params(struct adapter *sc)
4049 {
4050 	struct devlog_params *dparams = &sc->params.devlog;
4051 	int rc;
4052 
4053 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4054 	    dparams->size, &dparams->addr);
4055 
4056 	return (rc);
4057 }
4058 
4059 static void
4060 update_nirq(struct intrs_and_queues *iaq, int nports)
4061 {
4062 
4063 	iaq->nirq = T4_EXTRA_INTR;
4064 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4065 	iaq->nirq += nports * iaq->nofldrxq;
4066 	iaq->nirq += nports * (iaq->num_vis - 1) *
4067 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4068 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4069 }
4070 
4071 /*
4072  * Adjust requirements to fit the number of interrupts available.
4073  */
4074 static void
4075 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4076     int navail)
4077 {
4078 	int old_nirq;
4079 	const int nports = sc->params.nports;
4080 
4081 	MPASS(nports > 0);
4082 	MPASS(navail > 0);
4083 
4084 	bzero(iaq, sizeof(*iaq));
4085 	iaq->intr_type = itype;
4086 	iaq->num_vis = t4_num_vis;
4087 	iaq->ntxq = t4_ntxq;
4088 	iaq->ntxq_vi = t4_ntxq_vi;
4089 	iaq->nrxq = t4_nrxq;
4090 	iaq->nrxq_vi = t4_nrxq_vi;
4091 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4092 	if (is_offload(sc) || is_ethoffload(sc)) {
4093 		iaq->nofldtxq = t4_nofldtxq;
4094 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4095 	}
4096 #endif
4097 #ifdef TCP_OFFLOAD
4098 	if (is_offload(sc)) {
4099 		iaq->nofldrxq = t4_nofldrxq;
4100 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4101 	}
4102 #endif
4103 #ifdef DEV_NETMAP
4104 	if (t4_native_netmap & NN_MAIN_VI) {
4105 		iaq->nnmtxq = t4_nnmtxq;
4106 		iaq->nnmrxq = t4_nnmrxq;
4107 	}
4108 	if (t4_native_netmap & NN_EXTRA_VI) {
4109 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4110 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4111 	}
4112 #endif
4113 
4114 	update_nirq(iaq, nports);
4115 	if (iaq->nirq <= navail &&
4116 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4117 		/*
4118 		 * This is the normal case -- there are enough interrupts for
4119 		 * everything.
4120 		 */
4121 		goto done;
4122 	}
4123 
4124 	/*
4125 	 * If extra VIs have been configured try reducing their count and see if
4126 	 * that works.
4127 	 */
4128 	while (iaq->num_vis > 1) {
4129 		iaq->num_vis--;
4130 		update_nirq(iaq, nports);
4131 		if (iaq->nirq <= navail &&
4132 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4133 			device_printf(sc->dev, "virtual interfaces per port "
4134 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4135 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4136 			    "itype %d, navail %u, nirq %d.\n",
4137 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4138 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4139 			    itype, navail, iaq->nirq);
4140 			goto done;
4141 		}
4142 	}
4143 
4144 	/*
4145 	 * Extra VIs will not be created.  Log a message if they were requested.
4146 	 */
4147 	MPASS(iaq->num_vis == 1);
4148 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4149 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4150 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4151 	if (iaq->num_vis != t4_num_vis) {
4152 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4153 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4154 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4155 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4156 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4157 	}
4158 
4159 	/*
4160 	 * Keep reducing the number of NIC rx queues to the next lower power of
4161 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4162 	 * if that works.
4163 	 */
4164 	do {
4165 		if (iaq->nrxq > 1) {
4166 			do {
4167 				iaq->nrxq--;
4168 			} while (!powerof2(iaq->nrxq));
4169 			if (iaq->nnmrxq > iaq->nrxq)
4170 				iaq->nnmrxq = iaq->nrxq;
4171 		}
4172 		if (iaq->nofldrxq > 1)
4173 			iaq->nofldrxq >>= 1;
4174 
4175 		old_nirq = iaq->nirq;
4176 		update_nirq(iaq, nports);
4177 		if (iaq->nirq <= navail &&
4178 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4179 			device_printf(sc->dev, "running with reduced number of "
4180 			    "rx queues because of shortage of interrupts.  "
4181 			    "nrxq=%u, nofldrxq=%u.  "
4182 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4183 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4184 			goto done;
4185 		}
4186 	} while (old_nirq != iaq->nirq);
4187 
4188 	/* One interrupt for everything.  Ugh. */
4189 	device_printf(sc->dev, "running with minimal number of queues.  "
4190 	    "itype %d, navail %u.\n", itype, navail);
4191 	iaq->nirq = 1;
4192 	iaq->nrxq = 1;
4193 	iaq->ntxq = 1;
4194 	if (iaq->nofldrxq > 0) {
4195 		iaq->nofldrxq = 1;
4196 		iaq->nofldtxq = 1;
4197 	}
4198 	iaq->nnmtxq = 0;
4199 	iaq->nnmrxq = 0;
4200 done:
4201 	MPASS(iaq->num_vis > 0);
4202 	if (iaq->num_vis > 1) {
4203 		MPASS(iaq->nrxq_vi > 0);
4204 		MPASS(iaq->ntxq_vi > 0);
4205 	}
4206 	MPASS(iaq->nirq > 0);
4207 	MPASS(iaq->nrxq > 0);
4208 	MPASS(iaq->ntxq > 0);
4209 	if (itype == INTR_MSI) {
4210 		MPASS(powerof2(iaq->nirq));
4211 	}
4212 }
4213 
4214 static int
4215 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4216 {
4217 	int rc, itype, navail, nalloc;
4218 
4219 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4220 
4221 		if ((itype & t4_intr_types) == 0)
4222 			continue;	/* not allowed */
4223 
4224 		if (itype == INTR_MSIX)
4225 			navail = pci_msix_count(sc->dev);
4226 		else if (itype == INTR_MSI)
4227 			navail = pci_msi_count(sc->dev);
4228 		else
4229 			navail = 1;
4230 restart:
4231 		if (navail == 0)
4232 			continue;
4233 
4234 		calculate_iaq(sc, iaq, itype, navail);
4235 		nalloc = iaq->nirq;
4236 		rc = 0;
4237 		if (itype == INTR_MSIX)
4238 			rc = pci_alloc_msix(sc->dev, &nalloc);
4239 		else if (itype == INTR_MSI)
4240 			rc = pci_alloc_msi(sc->dev, &nalloc);
4241 
4242 		if (rc == 0 && nalloc > 0) {
4243 			if (nalloc == iaq->nirq)
4244 				return (0);
4245 
4246 			/*
4247 			 * Didn't get the number requested.  Use whatever number
4248 			 * the kernel is willing to allocate.
4249 			 */
4250 			device_printf(sc->dev, "fewer vectors than requested, "
4251 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4252 			    itype, iaq->nirq, nalloc);
4253 			pci_release_msi(sc->dev);
4254 			navail = nalloc;
4255 			goto restart;
4256 		}
4257 
4258 		device_printf(sc->dev,
4259 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4260 		    itype, rc, iaq->nirq, nalloc);
4261 	}
4262 
4263 	device_printf(sc->dev,
4264 	    "failed to find a usable interrupt type.  "
4265 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4266 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4267 
4268 	return (ENXIO);
4269 }
4270 
4271 #define FW_VERSION(chip) ( \
4272     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4273     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4274     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4275     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4276 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4277 
4278 /* Just enough of fw_hdr to cover all version info. */
4279 struct fw_h {
4280 	__u8	ver;
4281 	__u8	chip;
4282 	__be16	len512;
4283 	__be32	fw_ver;
4284 	__be32	tp_microcode_ver;
4285 	__u8	intfver_nic;
4286 	__u8	intfver_vnic;
4287 	__u8	intfver_ofld;
4288 	__u8	intfver_ri;
4289 	__u8	intfver_iscsipdu;
4290 	__u8	intfver_iscsi;
4291 	__u8	intfver_fcoepdu;
4292 	__u8	intfver_fcoe;
4293 };
4294 /* Spot check a couple of fields. */
4295 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4296 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4297 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4298 
4299 struct fw_info {
4300 	uint8_t chip;
4301 	char *kld_name;
4302 	char *fw_mod_name;
4303 	struct fw_h fw_h;
4304 } fw_info[] = {
4305 	{
4306 		.chip = CHELSIO_T4,
4307 		.kld_name = "t4fw_cfg",
4308 		.fw_mod_name = "t4fw",
4309 		.fw_h = {
4310 			.chip = FW_HDR_CHIP_T4,
4311 			.fw_ver = htobe32(FW_VERSION(T4)),
4312 			.intfver_nic = FW_INTFVER(T4, NIC),
4313 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4314 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4315 			.intfver_ri = FW_INTFVER(T4, RI),
4316 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4317 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4318 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4319 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4320 		},
4321 	}, {
4322 		.chip = CHELSIO_T5,
4323 		.kld_name = "t5fw_cfg",
4324 		.fw_mod_name = "t5fw",
4325 		.fw_h = {
4326 			.chip = FW_HDR_CHIP_T5,
4327 			.fw_ver = htobe32(FW_VERSION(T5)),
4328 			.intfver_nic = FW_INTFVER(T5, NIC),
4329 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4330 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4331 			.intfver_ri = FW_INTFVER(T5, RI),
4332 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4333 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4334 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4335 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4336 		},
4337 	}, {
4338 		.chip = CHELSIO_T6,
4339 		.kld_name = "t6fw_cfg",
4340 		.fw_mod_name = "t6fw",
4341 		.fw_h = {
4342 			.chip = FW_HDR_CHIP_T6,
4343 			.fw_ver = htobe32(FW_VERSION(T6)),
4344 			.intfver_nic = FW_INTFVER(T6, NIC),
4345 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4346 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4347 			.intfver_ri = FW_INTFVER(T6, RI),
4348 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4349 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4350 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4351 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4352 		},
4353 	}
4354 };
4355 
4356 static struct fw_info *
4357 find_fw_info(int chip)
4358 {
4359 	int i;
4360 
4361 	for (i = 0; i < nitems(fw_info); i++) {
4362 		if (fw_info[i].chip == chip)
4363 			return (&fw_info[i]);
4364 	}
4365 	return (NULL);
4366 }
4367 
4368 /*
4369  * Is the given firmware API compatible with the one the driver was compiled
4370  * with?
4371  */
4372 static int
4373 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4374 {
4375 
4376 	/* short circuit if it's the exact same firmware version */
4377 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4378 		return (1);
4379 
4380 	/*
4381 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4382 	 * features that are supported in the driver.
4383 	 */
4384 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4385 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4386 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4387 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4388 		return (1);
4389 #undef SAME_INTF
4390 
4391 	return (0);
4392 }
4393 
4394 static int
4395 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4396     const struct firmware **fw)
4397 {
4398 	struct fw_info *fw_info;
4399 
4400 	*dcfg = NULL;
4401 	if (fw != NULL)
4402 		*fw = NULL;
4403 
4404 	fw_info = find_fw_info(chip_id(sc));
4405 	if (fw_info == NULL) {
4406 		device_printf(sc->dev,
4407 		    "unable to look up firmware information for chip %d.\n",
4408 		    chip_id(sc));
4409 		return (EINVAL);
4410 	}
4411 
4412 	*dcfg = firmware_get(fw_info->kld_name);
4413 	if (*dcfg != NULL) {
4414 		if (fw != NULL)
4415 			*fw = firmware_get(fw_info->fw_mod_name);
4416 		return (0);
4417 	}
4418 
4419 	return (ENOENT);
4420 }
4421 
4422 static void
4423 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4424     const struct firmware *fw)
4425 {
4426 
4427 	if (fw != NULL)
4428 		firmware_put(fw, FIRMWARE_UNLOAD);
4429 	if (dcfg != NULL)
4430 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4431 }
4432 
4433 /*
4434  * Return values:
4435  * 0 means no firmware install attempted.
4436  * ERESTART means a firmware install was attempted and was successful.
4437  * +ve errno means a firmware install was attempted but failed.
4438  */
4439 static int
4440 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4441     const struct fw_h *drv_fw, const char *reason, int *already)
4442 {
4443 	const struct firmware *cfg, *fw;
4444 	const uint32_t c = be32toh(card_fw->fw_ver);
4445 	uint32_t d, k;
4446 	int rc, fw_install;
4447 	struct fw_h bundled_fw;
4448 	bool load_attempted;
4449 
4450 	cfg = fw = NULL;
4451 	load_attempted = false;
4452 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4453 
4454 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4455 	if (t4_fw_install < 0) {
4456 		rc = load_fw_module(sc, &cfg, &fw);
4457 		if (rc != 0 || fw == NULL) {
4458 			device_printf(sc->dev,
4459 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4460 			    " will use compiled-in firmware version for"
4461 			    "hw.cxgbe.fw_install checks.\n",
4462 			    rc, cfg, fw);
4463 		} else {
4464 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4465 		}
4466 		load_attempted = true;
4467 	}
4468 	d = be32toh(bundled_fw.fw_ver);
4469 
4470 	if (reason != NULL)
4471 		goto install;
4472 
4473 	if ((sc->flags & FW_OK) == 0) {
4474 
4475 		if (c == 0xffffffff) {
4476 			reason = "missing";
4477 			goto install;
4478 		}
4479 
4480 		rc = 0;
4481 		goto done;
4482 	}
4483 
4484 	if (!fw_compatible(card_fw, &bundled_fw)) {
4485 		reason = "incompatible or unusable";
4486 		goto install;
4487 	}
4488 
4489 	if (d > c) {
4490 		reason = "older than the version bundled with this driver";
4491 		goto install;
4492 	}
4493 
4494 	if (fw_install == 2 && d != c) {
4495 		reason = "different than the version bundled with this driver";
4496 		goto install;
4497 	}
4498 
4499 	/* No reason to do anything to the firmware already on the card. */
4500 	rc = 0;
4501 	goto done;
4502 
4503 install:
4504 	rc = 0;
4505 	if ((*already)++)
4506 		goto done;
4507 
4508 	if (fw_install == 0) {
4509 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4510 		    "but the driver is prohibited from installing a firmware "
4511 		    "on the card.\n",
4512 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4513 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4514 
4515 		goto done;
4516 	}
4517 
4518 	/*
4519 	 * We'll attempt to install a firmware.  Load the module first (if it
4520 	 * hasn't been loaded already).
4521 	 */
4522 	if (!load_attempted) {
4523 		rc = load_fw_module(sc, &cfg, &fw);
4524 		if (rc != 0 || fw == NULL) {
4525 			device_printf(sc->dev,
4526 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4527 			    rc, cfg, fw);
4528 			/* carry on */
4529 		}
4530 	}
4531 	if (fw == NULL) {
4532 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4533 		    "but the driver cannot take corrective action because it "
4534 		    "is unable to load the firmware module.\n",
4535 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4536 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4537 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4538 		goto done;
4539 	}
4540 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4541 	if (k != d) {
4542 		MPASS(t4_fw_install > 0);
4543 		device_printf(sc->dev,
4544 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4545 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4546 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4547 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4548 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4549 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4550 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4551 		goto done;
4552 	}
4553 
4554 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4555 	    "installing firmware %u.%u.%u.%u on card.\n",
4556 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4557 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4558 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4559 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4560 
4561 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4562 	if (rc != 0) {
4563 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4564 	} else {
4565 		/* Installed successfully, update the cached header too. */
4566 		rc = ERESTART;
4567 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4568 	}
4569 done:
4570 	unload_fw_module(sc, cfg, fw);
4571 
4572 	return (rc);
4573 }
4574 
4575 /*
4576  * Establish contact with the firmware and attempt to become the master driver.
4577  *
4578  * A firmware will be installed to the card if needed (if the driver is allowed
4579  * to do so).
4580  */
4581 static int
4582 contact_firmware(struct adapter *sc)
4583 {
4584 	int rc, already = 0;
4585 	enum dev_state state;
4586 	struct fw_info *fw_info;
4587 	struct fw_hdr *card_fw;		/* fw on the card */
4588 	const struct fw_h *drv_fw;
4589 
4590 	fw_info = find_fw_info(chip_id(sc));
4591 	if (fw_info == NULL) {
4592 		device_printf(sc->dev,
4593 		    "unable to look up firmware information for chip %d.\n",
4594 		    chip_id(sc));
4595 		return (EINVAL);
4596 	}
4597 	drv_fw = &fw_info->fw_h;
4598 
4599 	/* Read the header of the firmware on the card */
4600 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4601 restart:
4602 	rc = -t4_get_fw_hdr(sc, card_fw);
4603 	if (rc != 0) {
4604 		device_printf(sc->dev,
4605 		    "unable to read firmware header from card's flash: %d\n",
4606 		    rc);
4607 		goto done;
4608 	}
4609 
4610 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4611 	    &already);
4612 	if (rc == ERESTART)
4613 		goto restart;
4614 	if (rc != 0)
4615 		goto done;
4616 
4617 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4618 	if (rc < 0 || state == DEV_STATE_ERR) {
4619 		rc = -rc;
4620 		device_printf(sc->dev,
4621 		    "failed to connect to the firmware: %d, %d.  "
4622 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4623 #if 0
4624 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4625 		    "not responding properly to HELLO", &already) == ERESTART)
4626 			goto restart;
4627 #endif
4628 		goto done;
4629 	}
4630 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4631 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4632 
4633 	if (rc == sc->pf) {
4634 		sc->flags |= MASTER_PF;
4635 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4636 		    NULL, &already);
4637 		if (rc == ERESTART)
4638 			rc = 0;
4639 		else if (rc != 0)
4640 			goto done;
4641 	} else if (state == DEV_STATE_UNINIT) {
4642 		/*
4643 		 * We didn't get to be the master so we definitely won't be
4644 		 * configuring the chip.  It's a bug if someone else hasn't
4645 		 * configured it already.
4646 		 */
4647 		device_printf(sc->dev, "couldn't be master(%d), "
4648 		    "device not already initialized either(%d).  "
4649 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4650 		rc = EPROTO;
4651 		goto done;
4652 	} else {
4653 		/*
4654 		 * Some other PF is the master and has configured the chip.
4655 		 * This is allowed but untested.
4656 		 */
4657 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4658 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4659 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4660 		sc->cfcsum = 0;
4661 		rc = 0;
4662 	}
4663 done:
4664 	if (rc != 0 && sc->flags & FW_OK) {
4665 		t4_fw_bye(sc, sc->mbox);
4666 		sc->flags &= ~FW_OK;
4667 	}
4668 	free(card_fw, M_CXGBE);
4669 	return (rc);
4670 }
4671 
4672 static int
4673 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4674     uint32_t mtype, uint32_t moff)
4675 {
4676 	struct fw_info *fw_info;
4677 	const struct firmware *dcfg, *rcfg = NULL;
4678 	const uint32_t *cfdata;
4679 	uint32_t cflen, addr;
4680 	int rc;
4681 
4682 	load_fw_module(sc, &dcfg, NULL);
4683 
4684 	/* Card specific interpretation of "default". */
4685 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4686 		if (pci_get_device(sc->dev) == 0x440a)
4687 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4688 		if (is_fpga(sc))
4689 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4690 	}
4691 
4692 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4693 		if (dcfg == NULL) {
4694 			device_printf(sc->dev,
4695 			    "KLD with default config is not available.\n");
4696 			rc = ENOENT;
4697 			goto done;
4698 		}
4699 		cfdata = dcfg->data;
4700 		cflen = dcfg->datasize & ~3;
4701 	} else {
4702 		char s[32];
4703 
4704 		fw_info = find_fw_info(chip_id(sc));
4705 		if (fw_info == NULL) {
4706 			device_printf(sc->dev,
4707 			    "unable to look up firmware information for chip %d.\n",
4708 			    chip_id(sc));
4709 			rc = EINVAL;
4710 			goto done;
4711 		}
4712 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4713 
4714 		rcfg = firmware_get(s);
4715 		if (rcfg == NULL) {
4716 			device_printf(sc->dev,
4717 			    "unable to load module \"%s\" for configuration "
4718 			    "profile \"%s\".\n", s, cfg_file);
4719 			rc = ENOENT;
4720 			goto done;
4721 		}
4722 		cfdata = rcfg->data;
4723 		cflen = rcfg->datasize & ~3;
4724 	}
4725 
4726 	if (cflen > FLASH_CFG_MAX_SIZE) {
4727 		device_printf(sc->dev,
4728 		    "config file too long (%d, max allowed is %d).\n",
4729 		    cflen, FLASH_CFG_MAX_SIZE);
4730 		rc = EINVAL;
4731 		goto done;
4732 	}
4733 
4734 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4735 	if (rc != 0) {
4736 		device_printf(sc->dev,
4737 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4738 		    __func__, mtype, moff, cflen, rc);
4739 		rc = EINVAL;
4740 		goto done;
4741 	}
4742 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4743 done:
4744 	if (rcfg != NULL)
4745 		firmware_put(rcfg, FIRMWARE_UNLOAD);
4746 	unload_fw_module(sc, dcfg, NULL);
4747 	return (rc);
4748 }
4749 
4750 struct caps_allowed {
4751 	uint16_t nbmcaps;
4752 	uint16_t linkcaps;
4753 	uint16_t switchcaps;
4754 	uint16_t niccaps;
4755 	uint16_t toecaps;
4756 	uint16_t rdmacaps;
4757 	uint16_t cryptocaps;
4758 	uint16_t iscsicaps;
4759 	uint16_t fcoecaps;
4760 };
4761 
4762 #define FW_PARAM_DEV(param) \
4763 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4764 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4765 #define FW_PARAM_PFVF(param) \
4766 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4767 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4768 
4769 /*
4770  * Provide a configuration profile to the firmware and have it initialize the
4771  * chip accordingly.  This may involve uploading a configuration file to the
4772  * card.
4773  */
4774 static int
4775 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4776     const struct caps_allowed *caps_allowed)
4777 {
4778 	int rc;
4779 	struct fw_caps_config_cmd caps;
4780 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
4781 
4782 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4783 	if (rc != 0) {
4784 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
4785 		return (rc);
4786 	}
4787 
4788 	bzero(&caps, sizeof(caps));
4789 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4790 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
4791 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
4792 		mtype = 0;
4793 		moff = 0;
4794 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4795 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
4796 		mtype = FW_MEMTYPE_FLASH;
4797 		moff = t4_flash_cfg_addr(sc);
4798 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4799 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4800 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4801 		    FW_LEN16(caps));
4802 	} else {
4803 		/*
4804 		 * Ask the firmware where it wants us to upload the config file.
4805 		 */
4806 		param = FW_PARAM_DEV(CF);
4807 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4808 		if (rc != 0) {
4809 			/* No support for config file?  Shouldn't happen. */
4810 			device_printf(sc->dev,
4811 			    "failed to query config file location: %d.\n", rc);
4812 			goto done;
4813 		}
4814 		mtype = G_FW_PARAMS_PARAM_Y(val);
4815 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
4816 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4817 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4818 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4819 		    FW_LEN16(caps));
4820 
4821 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
4822 		if (rc != 0) {
4823 			device_printf(sc->dev,
4824 			    "failed to upload config file to card: %d.\n", rc);
4825 			goto done;
4826 		}
4827 	}
4828 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
4829 	if (rc != 0) {
4830 		device_printf(sc->dev, "failed to pre-process config file: %d "
4831 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
4832 		goto done;
4833 	}
4834 
4835 	finicsum = be32toh(caps.finicsum);
4836 	cfcsum = be32toh(caps.cfcsum);	/* actual */
4837 	if (finicsum != cfcsum) {
4838 		device_printf(sc->dev,
4839 		    "WARNING: config file checksum mismatch: %08x %08x\n",
4840 		    finicsum, cfcsum);
4841 	}
4842 	sc->cfcsum = cfcsum;
4843 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
4844 
4845 	/*
4846 	 * Let the firmware know what features will (not) be used so it can tune
4847 	 * things accordingly.
4848 	 */
4849 #define LIMIT_CAPS(x) do { \
4850 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
4851 } while (0)
4852 	LIMIT_CAPS(nbm);
4853 	LIMIT_CAPS(link);
4854 	LIMIT_CAPS(switch);
4855 	LIMIT_CAPS(nic);
4856 	LIMIT_CAPS(toe);
4857 	LIMIT_CAPS(rdma);
4858 	LIMIT_CAPS(crypto);
4859 	LIMIT_CAPS(iscsi);
4860 	LIMIT_CAPS(fcoe);
4861 #undef LIMIT_CAPS
4862 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
4863 		/*
4864 		 * TOE and hashfilters are mutually exclusive.  It is a config
4865 		 * file or firmware bug if both are reported as available.  Try
4866 		 * to cope with the situation in non-debug builds by disabling
4867 		 * TOE.
4868 		 */
4869 		MPASS(caps.toecaps == 0);
4870 
4871 		caps.toecaps = 0;
4872 		caps.rdmacaps = 0;
4873 		caps.iscsicaps = 0;
4874 	}
4875 
4876 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4877 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
4878 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4879 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
4880 	if (rc != 0) {
4881 		device_printf(sc->dev,
4882 		    "failed to process config file: %d.\n", rc);
4883 		goto done;
4884 	}
4885 
4886 	t4_tweak_chip_settings(sc);
4887 	set_params__pre_init(sc);
4888 
4889 	/* get basic stuff going */
4890 	rc = -t4_fw_initialize(sc, sc->mbox);
4891 	if (rc != 0) {
4892 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
4893 		goto done;
4894 	}
4895 done:
4896 	return (rc);
4897 }
4898 
4899 /*
4900  * Partition chip resources for use between various PFs, VFs, etc.
4901  */
4902 static int
4903 partition_resources(struct adapter *sc)
4904 {
4905 	char cfg_file[sizeof(t4_cfg_file)];
4906 	struct caps_allowed caps_allowed;
4907 	int rc;
4908 	bool fallback;
4909 
4910 	/* Only the master driver gets to configure the chip resources. */
4911 	MPASS(sc->flags & MASTER_PF);
4912 
4913 #define COPY_CAPS(x) do { \
4914 	caps_allowed.x##caps = t4_##x##caps_allowed; \
4915 } while (0)
4916 	bzero(&caps_allowed, sizeof(caps_allowed));
4917 	COPY_CAPS(nbm);
4918 	COPY_CAPS(link);
4919 	COPY_CAPS(switch);
4920 	COPY_CAPS(nic);
4921 	COPY_CAPS(toe);
4922 	COPY_CAPS(rdma);
4923 	COPY_CAPS(crypto);
4924 	COPY_CAPS(iscsi);
4925 	COPY_CAPS(fcoe);
4926 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
4927 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
4928 retry:
4929 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
4930 	if (rc != 0 && fallback) {
4931 		device_printf(sc->dev,
4932 		    "failed (%d) to configure card with \"%s\" profile, "
4933 		    "will fall back to a basic configuration and retry.\n",
4934 		    rc, cfg_file);
4935 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
4936 		bzero(&caps_allowed, sizeof(caps_allowed));
4937 		COPY_CAPS(switch);
4938 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
4939 		fallback = false;
4940 		goto retry;
4941 	}
4942 #undef COPY_CAPS
4943 	return (rc);
4944 }
4945 
4946 /*
4947  * Retrieve parameters that are needed (or nice to have) very early.
4948  */
4949 static int
4950 get_params__pre_init(struct adapter *sc)
4951 {
4952 	int rc;
4953 	uint32_t param[2], val[2];
4954 
4955 	t4_get_version_info(sc);
4956 
4957 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
4958 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
4959 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
4960 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
4961 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
4962 
4963 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
4964 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
4965 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
4966 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
4967 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
4968 
4969 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
4970 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
4971 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
4972 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
4973 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
4974 
4975 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
4976 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
4977 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
4978 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
4979 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
4980 
4981 	param[0] = FW_PARAM_DEV(PORTVEC);
4982 	param[1] = FW_PARAM_DEV(CCLK);
4983 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4984 	if (rc != 0) {
4985 		device_printf(sc->dev,
4986 		    "failed to query parameters (pre_init): %d.\n", rc);
4987 		return (rc);
4988 	}
4989 
4990 	sc->params.portvec = val[0];
4991 	sc->params.nports = bitcount32(val[0]);
4992 	sc->params.vpd.cclk = val[1];
4993 
4994 	/* Read device log parameters. */
4995 	rc = -t4_init_devlog_params(sc, 1);
4996 	if (rc == 0)
4997 		fixup_devlog_params(sc);
4998 	else {
4999 		device_printf(sc->dev,
5000 		    "failed to get devlog parameters: %d.\n", rc);
5001 		rc = 0;	/* devlog isn't critical for device operation */
5002 	}
5003 
5004 	return (rc);
5005 }
5006 
5007 /*
5008  * Any params that need to be set before FW_INITIALIZE.
5009  */
5010 static int
5011 set_params__pre_init(struct adapter *sc)
5012 {
5013 	int rc = 0;
5014 	uint32_t param, val;
5015 
5016 	if (chip_id(sc) >= CHELSIO_T6) {
5017 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5018 		val = 1;
5019 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5020 		/* firmwares < 1.20.1.0 do not have this param. */
5021 		if (rc == FW_EINVAL &&
5022 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5023 			rc = 0;
5024 		}
5025 		if (rc != 0) {
5026 			device_printf(sc->dev,
5027 			    "failed to enable high priority filters :%d.\n",
5028 			    rc);
5029 		}
5030 	}
5031 
5032 	/* Enable opaque VIIDs with firmwares that support it. */
5033 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5034 	val = 1;
5035 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5036 	if (rc == 0 && val == 1)
5037 		sc->params.viid_smt_extn_support = true;
5038 	else
5039 		sc->params.viid_smt_extn_support = false;
5040 
5041 	return (rc);
5042 }
5043 
5044 /*
5045  * Retrieve various parameters that are of interest to the driver.  The device
5046  * has been initialized by the firmware at this point.
5047  */
5048 static int
5049 get_params__post_init(struct adapter *sc)
5050 {
5051 	int rc;
5052 	uint32_t param[7], val[7];
5053 	struct fw_caps_config_cmd caps;
5054 
5055 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5056 	param[1] = FW_PARAM_PFVF(EQ_START);
5057 	param[2] = FW_PARAM_PFVF(FILTER_START);
5058 	param[3] = FW_PARAM_PFVF(FILTER_END);
5059 	param[4] = FW_PARAM_PFVF(L2T_START);
5060 	param[5] = FW_PARAM_PFVF(L2T_END);
5061 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5062 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5063 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5064 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5065 	if (rc != 0) {
5066 		device_printf(sc->dev,
5067 		    "failed to query parameters (post_init): %d.\n", rc);
5068 		return (rc);
5069 	}
5070 
5071 	sc->sge.iq_start = val[0];
5072 	sc->sge.eq_start = val[1];
5073 	if ((int)val[3] > (int)val[2]) {
5074 		sc->tids.ftid_base = val[2];
5075 		sc->tids.ftid_end = val[3];
5076 		sc->tids.nftids = val[3] - val[2] + 1;
5077 	}
5078 	sc->vres.l2t.start = val[4];
5079 	sc->vres.l2t.size = val[5] - val[4] + 1;
5080 	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
5081 	    ("%s: L2 table size (%u) larger than expected (%u)",
5082 	    __func__, sc->vres.l2t.size, L2T_SIZE));
5083 	sc->params.core_vdd = val[6];
5084 
5085 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5086 	param[1] = FW_PARAM_PFVF(EQ_END);
5087 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5088 	if (rc != 0) {
5089 		device_printf(sc->dev,
5090 		    "failed to query parameters (post_init2): %d.\n", rc);
5091 		return (rc);
5092 	}
5093 	MPASS((int)val[0] >= sc->sge.iq_start);
5094 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5095 	MPASS((int)val[1] >= sc->sge.eq_start);
5096 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5097 
5098 	if (chip_id(sc) >= CHELSIO_T6) {
5099 
5100 		sc->tids.tid_base = t4_read_reg(sc,
5101 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5102 
5103 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5104 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5105 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5106 		if (rc != 0) {
5107 			device_printf(sc->dev,
5108 			   "failed to query hpfilter parameters: %d.\n", rc);
5109 			return (rc);
5110 		}
5111 		if ((int)val[1] > (int)val[0]) {
5112 			sc->tids.hpftid_base = val[0];
5113 			sc->tids.hpftid_end = val[1];
5114 			sc->tids.nhpftids = val[1] - val[0] + 1;
5115 
5116 			/*
5117 			 * These should go off if the layout changes and the
5118 			 * driver needs to catch up.
5119 			 */
5120 			MPASS(sc->tids.hpftid_base == 0);
5121 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5122 		}
5123 
5124 		param[0] = FW_PARAM_PFVF(RAWF_START);
5125 		param[1] = FW_PARAM_PFVF(RAWF_END);
5126 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5127 		if (rc != 0) {
5128 			device_printf(sc->dev,
5129 			   "failed to query rawf parameters: %d.\n", rc);
5130 			return (rc);
5131 		}
5132 		if ((int)val[1] > (int)val[0]) {
5133 			sc->rawf_base = val[0];
5134 			sc->nrawf = val[1] - val[0] + 1;
5135 		}
5136 	}
5137 
5138 	/*
5139 	 * MPSBGMAP is queried separately because only recent firmwares support
5140 	 * it as a parameter and we don't want the compound query above to fail
5141 	 * on older firmwares.
5142 	 */
5143 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5144 	val[0] = 0;
5145 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5146 	if (rc == 0)
5147 		sc->params.mps_bg_map = val[0];
5148 	else
5149 		sc->params.mps_bg_map = 0;
5150 
5151 	/*
5152 	 * Determine whether the firmware supports the filter2 work request.
5153 	 * This is queried separately for the same reason as MPSBGMAP above.
5154 	 */
5155 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5156 	val[0] = 0;
5157 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5158 	if (rc == 0)
5159 		sc->params.filter2_wr_support = val[0] != 0;
5160 	else
5161 		sc->params.filter2_wr_support = 0;
5162 
5163 	/*
5164 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5165 	 * This is queried separately for the same reason as other params above.
5166 	 */
5167 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5168 	val[0] = 0;
5169 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5170 	if (rc == 0)
5171 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5172 	else
5173 		sc->params.ulptx_memwrite_dsgl = false;
5174 
5175 	/* FW_RI_FR_NSMR_TPTE_WR support */
5176 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5177 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5178 	if (rc == 0)
5179 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5180 	else
5181 		sc->params.fr_nsmr_tpte_wr_support = false;
5182 
5183 	/* Support for 512 SGL entries per FR MR. */
5184 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5185 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5186 	if (rc == 0)
5187 		sc->params.dev_512sgl_mr = val[0] != 0;
5188 	else
5189 		sc->params.dev_512sgl_mr = false;
5190 
5191 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5192 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5193 	if (rc == 0)
5194 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5195 	else
5196 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5197 
5198 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5199 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5200 	if (rc == 0) {
5201 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5202 		sc->params.nsched_cls = val[0];
5203 	} else
5204 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5205 
5206 	/* get capabilites */
5207 	bzero(&caps, sizeof(caps));
5208 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5209 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5210 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5211 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5212 	if (rc != 0) {
5213 		device_printf(sc->dev,
5214 		    "failed to get card capabilities: %d.\n", rc);
5215 		return (rc);
5216 	}
5217 
5218 #define READ_CAPS(x) do { \
5219 	sc->x = htobe16(caps.x); \
5220 } while (0)
5221 	READ_CAPS(nbmcaps);
5222 	READ_CAPS(linkcaps);
5223 	READ_CAPS(switchcaps);
5224 	READ_CAPS(niccaps);
5225 	READ_CAPS(toecaps);
5226 	READ_CAPS(rdmacaps);
5227 	READ_CAPS(cryptocaps);
5228 	READ_CAPS(iscsicaps);
5229 	READ_CAPS(fcoecaps);
5230 
5231 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5232 		MPASS(chip_id(sc) > CHELSIO_T4);
5233 		MPASS(sc->toecaps == 0);
5234 		sc->toecaps = 0;
5235 
5236 		param[0] = FW_PARAM_DEV(NTID);
5237 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5238 		if (rc != 0) {
5239 			device_printf(sc->dev,
5240 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5241 			return (rc);
5242 		}
5243 		sc->tids.ntids = val[0];
5244 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5245 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5246 			sc->tids.ntids -= sc->tids.nhpftids;
5247 		}
5248 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5249 		sc->params.hash_filter = 1;
5250 	}
5251 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5252 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5253 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5254 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5255 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5256 		if (rc != 0) {
5257 			device_printf(sc->dev,
5258 			    "failed to query NIC parameters: %d.\n", rc);
5259 			return (rc);
5260 		}
5261 		if ((int)val[1] > (int)val[0]) {
5262 			sc->tids.etid_base = val[0];
5263 			sc->tids.etid_end = val[1];
5264 			sc->tids.netids = val[1] - val[0] + 1;
5265 			sc->params.eo_wr_cred = val[2];
5266 			sc->params.ethoffload = 1;
5267 		}
5268 	}
5269 	if (sc->toecaps) {
5270 		/* query offload-related parameters */
5271 		param[0] = FW_PARAM_DEV(NTID);
5272 		param[1] = FW_PARAM_PFVF(SERVER_START);
5273 		param[2] = FW_PARAM_PFVF(SERVER_END);
5274 		param[3] = FW_PARAM_PFVF(TDDP_START);
5275 		param[4] = FW_PARAM_PFVF(TDDP_END);
5276 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5277 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5278 		if (rc != 0) {
5279 			device_printf(sc->dev,
5280 			    "failed to query TOE parameters: %d.\n", rc);
5281 			return (rc);
5282 		}
5283 		sc->tids.ntids = val[0];
5284 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5285 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5286 			sc->tids.ntids -= sc->tids.nhpftids;
5287 		}
5288 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5289 		if ((int)val[2] > (int)val[1]) {
5290 			sc->tids.stid_base = val[1];
5291 			sc->tids.nstids = val[2] - val[1] + 1;
5292 		}
5293 		sc->vres.ddp.start = val[3];
5294 		sc->vres.ddp.size = val[4] - val[3] + 1;
5295 		sc->params.ofldq_wr_cred = val[5];
5296 		sc->params.offload = 1;
5297 	} else {
5298 		/*
5299 		 * The firmware attempts memfree TOE configuration for -SO cards
5300 		 * and will report toecaps=0 if it runs out of resources (this
5301 		 * depends on the config file).  It may not report 0 for other
5302 		 * capabilities dependent on the TOE in this case.  Set them to
5303 		 * 0 here so that the driver doesn't bother tracking resources
5304 		 * that will never be used.
5305 		 */
5306 		sc->iscsicaps = 0;
5307 		sc->rdmacaps = 0;
5308 	}
5309 	if (sc->rdmacaps) {
5310 		param[0] = FW_PARAM_PFVF(STAG_START);
5311 		param[1] = FW_PARAM_PFVF(STAG_END);
5312 		param[2] = FW_PARAM_PFVF(RQ_START);
5313 		param[3] = FW_PARAM_PFVF(RQ_END);
5314 		param[4] = FW_PARAM_PFVF(PBL_START);
5315 		param[5] = FW_PARAM_PFVF(PBL_END);
5316 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5317 		if (rc != 0) {
5318 			device_printf(sc->dev,
5319 			    "failed to query RDMA parameters(1): %d.\n", rc);
5320 			return (rc);
5321 		}
5322 		sc->vres.stag.start = val[0];
5323 		sc->vres.stag.size = val[1] - val[0] + 1;
5324 		sc->vres.rq.start = val[2];
5325 		sc->vres.rq.size = val[3] - val[2] + 1;
5326 		sc->vres.pbl.start = val[4];
5327 		sc->vres.pbl.size = val[5] - val[4] + 1;
5328 
5329 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5330 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5331 		param[2] = FW_PARAM_PFVF(CQ_START);
5332 		param[3] = FW_PARAM_PFVF(CQ_END);
5333 		param[4] = FW_PARAM_PFVF(OCQ_START);
5334 		param[5] = FW_PARAM_PFVF(OCQ_END);
5335 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5336 		if (rc != 0) {
5337 			device_printf(sc->dev,
5338 			    "failed to query RDMA parameters(2): %d.\n", rc);
5339 			return (rc);
5340 		}
5341 		sc->vres.qp.start = val[0];
5342 		sc->vres.qp.size = val[1] - val[0] + 1;
5343 		sc->vres.cq.start = val[2];
5344 		sc->vres.cq.size = val[3] - val[2] + 1;
5345 		sc->vres.ocq.start = val[4];
5346 		sc->vres.ocq.size = val[5] - val[4] + 1;
5347 
5348 		param[0] = FW_PARAM_PFVF(SRQ_START);
5349 		param[1] = FW_PARAM_PFVF(SRQ_END);
5350 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5351 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5352 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5353 		if (rc != 0) {
5354 			device_printf(sc->dev,
5355 			    "failed to query RDMA parameters(3): %d.\n", rc);
5356 			return (rc);
5357 		}
5358 		sc->vres.srq.start = val[0];
5359 		sc->vres.srq.size = val[1] - val[0] + 1;
5360 		sc->params.max_ordird_qp = val[2];
5361 		sc->params.max_ird_adapter = val[3];
5362 	}
5363 	if (sc->iscsicaps) {
5364 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5365 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5366 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5367 		if (rc != 0) {
5368 			device_printf(sc->dev,
5369 			    "failed to query iSCSI parameters: %d.\n", rc);
5370 			return (rc);
5371 		}
5372 		sc->vres.iscsi.start = val[0];
5373 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5374 	}
5375 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5376 		param[0] = FW_PARAM_PFVF(TLS_START);
5377 		param[1] = FW_PARAM_PFVF(TLS_END);
5378 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5379 		if (rc != 0) {
5380 			device_printf(sc->dev,
5381 			    "failed to query TLS parameters: %d.\n", rc);
5382 			return (rc);
5383 		}
5384 		sc->vres.key.start = val[0];
5385 		sc->vres.key.size = val[1] - val[0] + 1;
5386 	}
5387 
5388 	/*
5389 	 * We've got the params we wanted to query directly from the firmware.
5390 	 * Grab some others via other means.
5391 	 */
5392 	t4_init_sge_params(sc);
5393 	t4_init_tp_params(sc);
5394 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5395 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5396 
5397 	rc = t4_verify_chip_settings(sc);
5398 	if (rc != 0)
5399 		return (rc);
5400 	t4_init_rx_buf_info(sc);
5401 
5402 	return (rc);
5403 }
5404 
5405 #ifdef KERN_TLS
5406 static void
5407 ktls_tick(void *arg)
5408 {
5409 	struct adapter *sc;
5410 	uint32_t tstamp;
5411 
5412 	sc = arg;
5413 	tstamp = tcp_ts_getticks();
5414 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5415 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5416 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5417 }
5418 
5419 static int
5420 t4_config_kern_tls(struct adapter *sc, bool enable)
5421 {
5422 	int rc;
5423 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5424 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5425 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5426 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5427 
5428 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5429 	if (rc != 0) {
5430 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5431 		    enable ?  "enable" : "disable", rc);
5432 		return (rc);
5433 	}
5434 
5435 	if (enable) {
5436 		sc->flags |= KERN_TLS_ON;
5437 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5438 		    C_HARDCLOCK);
5439 	} else {
5440 		sc->flags &= ~KERN_TLS_ON;
5441 		callout_stop(&sc->ktls_tick);
5442 	}
5443 
5444 	return (rc);
5445 }
5446 #endif
5447 
5448 static int
5449 set_params__post_init(struct adapter *sc)
5450 {
5451 	uint32_t mask, param, val;
5452 #ifdef TCP_OFFLOAD
5453 	int i, v, shift;
5454 #endif
5455 
5456 	/* ask for encapsulated CPLs */
5457 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5458 	val = 1;
5459 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5460 
5461 	/* Enable 32b port caps if the firmware supports it. */
5462 	param = FW_PARAM_PFVF(PORT_CAPS32);
5463 	val = 1;
5464 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5465 		sc->params.port_caps32 = 1;
5466 
5467 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5468 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5469 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5470 	    V_MASKFILTER(val - 1));
5471 
5472 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5473 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5474 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5475 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5476 	val = 0;
5477 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5478 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5479 		    F_ATTACKFILTERENABLE);
5480 		val |= F_DROPERRORATTACK;
5481 	}
5482 	if (t4_drop_ip_fragments != 0) {
5483 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5484 		    F_FRAGMENTDROP);
5485 		val |= F_DROPERRORFRAG;
5486 	}
5487 	if (t4_drop_pkts_with_l2_errors != 0)
5488 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5489 	if (t4_drop_pkts_with_l3_errors != 0) {
5490 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5491 		    F_DROPERRORCSUMIP;
5492 	}
5493 	if (t4_drop_pkts_with_l4_errors != 0) {
5494 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5495 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5496 	}
5497 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5498 
5499 #ifdef TCP_OFFLOAD
5500 	/*
5501 	 * Override the TOE timers with user provided tunables.  This is not the
5502 	 * recommended way to change the timers (the firmware config file is) so
5503 	 * these tunables are not documented.
5504 	 *
5505 	 * All the timer tunables are in microseconds.
5506 	 */
5507 	if (t4_toe_keepalive_idle != 0) {
5508 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5509 		v &= M_KEEPALIVEIDLE;
5510 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5511 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5512 	}
5513 	if (t4_toe_keepalive_interval != 0) {
5514 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5515 		v &= M_KEEPALIVEINTVL;
5516 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5517 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5518 	}
5519 	if (t4_toe_keepalive_count != 0) {
5520 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5521 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5522 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5523 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5524 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5525 	}
5526 	if (t4_toe_rexmt_min != 0) {
5527 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5528 		v &= M_RXTMIN;
5529 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5530 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5531 	}
5532 	if (t4_toe_rexmt_max != 0) {
5533 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5534 		v &= M_RXTMAX;
5535 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5536 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5537 	}
5538 	if (t4_toe_rexmt_count != 0) {
5539 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5540 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5541 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5542 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5543 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5544 	}
5545 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5546 		if (t4_toe_rexmt_backoff[i] != -1) {
5547 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5548 			shift = (i & 3) << 3;
5549 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5550 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5551 		}
5552 	}
5553 #endif
5554 
5555 #ifdef KERN_TLS
5556 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS &&
5557 	    sc->toecaps & FW_CAPS_CONFIG_TOE) {
5558 		/*
5559 		 * Limit TOE connections to 2 reassembly "islands".  This is
5560 		 * required for TOE TLS connections to downgrade to plain TOE
5561 		 * connections if an unsupported TLS version or ciphersuite is
5562 		 * used.
5563 		 */
5564 		t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG,
5565 		    V_PASSMODE(M_PASSMODE), V_PASSMODE(2));
5566 		if (is_ktls(sc)) {
5567 			sc->tlst.inline_keys = t4_tls_inline_keys;
5568 			sc->tlst.combo_wrs = t4_tls_combo_wrs;
5569 			if (t4_kern_tls != 0)
5570 				t4_config_kern_tls(sc, true);
5571 		}
5572 	}
5573 #endif
5574 	return (0);
5575 }
5576 
5577 #undef FW_PARAM_PFVF
5578 #undef FW_PARAM_DEV
5579 
5580 static void
5581 t4_set_desc(struct adapter *sc)
5582 {
5583 	char buf[128];
5584 	struct adapter_params *p = &sc->params;
5585 
5586 	snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
5587 
5588 	device_set_desc_copy(sc->dev, buf);
5589 }
5590 
5591 static inline void
5592 ifmedia_add4(struct ifmedia *ifm, int m)
5593 {
5594 
5595 	ifmedia_add(ifm, m, 0, NULL);
5596 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5597 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5598 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5599 }
5600 
5601 /*
5602  * This is the selected media, which is not quite the same as the active media.
5603  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5604  * and active are not the same, and "media: Ethernet selected" otherwise.
5605  */
5606 static void
5607 set_current_media(struct port_info *pi)
5608 {
5609 	struct link_config *lc;
5610 	struct ifmedia *ifm;
5611 	int mword;
5612 	u_int speed;
5613 
5614 	PORT_LOCK_ASSERT_OWNED(pi);
5615 
5616 	/* Leave current media alone if it's already set to IFM_NONE. */
5617 	ifm = &pi->media;
5618 	if (ifm->ifm_cur != NULL &&
5619 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5620 		return;
5621 
5622 	lc = &pi->link_cfg;
5623 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5624 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5625 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5626 		return;
5627 	}
5628 	mword = IFM_ETHER | IFM_FDX;
5629 	if (lc->requested_fc & PAUSE_TX)
5630 		mword |= IFM_ETH_TXPAUSE;
5631 	if (lc->requested_fc & PAUSE_RX)
5632 		mword |= IFM_ETH_RXPAUSE;
5633 	if (lc->requested_speed == 0)
5634 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5635 	else
5636 		speed = lc->requested_speed;
5637 	mword |= port_mword(pi, speed_to_fwcap(speed));
5638 	ifmedia_set(ifm, mword);
5639 }
5640 
5641 /*
5642  * Returns true if the ifmedia list for the port cannot change.
5643  */
5644 static bool
5645 fixed_ifmedia(struct port_info *pi)
5646 {
5647 
5648 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5649 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5650 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5651 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5652 	    pi->port_type == FW_PORT_TYPE_KX ||
5653 	    pi->port_type == FW_PORT_TYPE_KR ||
5654 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5655 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5656 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5657 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5658 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5659 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5660 }
5661 
5662 static void
5663 build_medialist(struct port_info *pi)
5664 {
5665 	uint32_t ss, speed;
5666 	int unknown, mword, bit;
5667 	struct link_config *lc;
5668 	struct ifmedia *ifm;
5669 
5670 	PORT_LOCK_ASSERT_OWNED(pi);
5671 
5672 	if (pi->flags & FIXED_IFMEDIA)
5673 		return;
5674 
5675 	/*
5676 	 * Rebuild the ifmedia list.
5677 	 */
5678 	ifm = &pi->media;
5679 	ifmedia_removeall(ifm);
5680 	lc = &pi->link_cfg;
5681 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5682 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5683 		MPASS(ss != 0);
5684 no_media:
5685 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5686 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5687 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5688 		return;
5689 	}
5690 
5691 	unknown = 0;
5692 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5693 		speed = 1 << bit;
5694 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5695 		if (ss & speed) {
5696 			mword = port_mword(pi, speed);
5697 			if (mword == IFM_NONE) {
5698 				goto no_media;
5699 			} else if (mword == IFM_UNKNOWN)
5700 				unknown++;
5701 			else
5702 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5703 		}
5704 	}
5705 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5706 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5707 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5708 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5709 
5710 	set_current_media(pi);
5711 }
5712 
5713 /*
5714  * Initialize the requested fields in the link config based on driver tunables.
5715  */
5716 static void
5717 init_link_config(struct port_info *pi)
5718 {
5719 	struct link_config *lc = &pi->link_cfg;
5720 
5721 	PORT_LOCK_ASSERT_OWNED(pi);
5722 	MPASS(lc->pcaps != 0);
5723 
5724 	lc->requested_caps = 0;
5725 	lc->requested_speed = 0;
5726 
5727 	if (t4_autoneg == 0)
5728 		lc->requested_aneg = AUTONEG_DISABLE;
5729 	else if (t4_autoneg == 1)
5730 		lc->requested_aneg = AUTONEG_ENABLE;
5731 	else
5732 		lc->requested_aneg = AUTONEG_AUTO;
5733 
5734 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5735 	    PAUSE_AUTONEG);
5736 
5737 	if (t4_fec & FEC_AUTO)
5738 		lc->requested_fec = FEC_AUTO;
5739 	else if (t4_fec == 0)
5740 		lc->requested_fec = FEC_NONE;
5741 	else {
5742 		/* -1 is handled by the FEC_AUTO block above and not here. */
5743 		lc->requested_fec = t4_fec &
5744 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5745 		if (lc->requested_fec == 0)
5746 			lc->requested_fec = FEC_AUTO;
5747 	}
5748 	lc->force_fec = 0;
5749 	if (lc->pcaps & FW_PORT_CAP32_FORCE_FEC) {
5750 		if (t4_force_fec < 0)
5751 			lc->force_fec = -1;
5752 		else if (t4_force_fec > 0)
5753 			lc->force_fec = 1;
5754 	}
5755 }
5756 
5757 /*
5758  * Makes sure that all requested settings comply with what's supported by the
5759  * port.  Returns the number of settings that were invalid and had to be fixed.
5760  */
5761 static int
5762 fixup_link_config(struct port_info *pi)
5763 {
5764 	int n = 0;
5765 	struct link_config *lc = &pi->link_cfg;
5766 	uint32_t fwspeed;
5767 
5768 	PORT_LOCK_ASSERT_OWNED(pi);
5769 
5770 	/* Speed (when not autonegotiating) */
5771 	if (lc->requested_speed != 0) {
5772 		fwspeed = speed_to_fwcap(lc->requested_speed);
5773 		if ((fwspeed & lc->pcaps) == 0) {
5774 			n++;
5775 			lc->requested_speed = 0;
5776 		}
5777 	}
5778 
5779 	/* Link autonegotiation */
5780 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5781 	    lc->requested_aneg == AUTONEG_DISABLE ||
5782 	    lc->requested_aneg == AUTONEG_AUTO);
5783 	if (lc->requested_aneg == AUTONEG_ENABLE &&
5784 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5785 		n++;
5786 		lc->requested_aneg = AUTONEG_AUTO;
5787 	}
5788 
5789 	/* Flow control */
5790 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5791 	if (lc->requested_fc & PAUSE_TX &&
5792 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5793 		n++;
5794 		lc->requested_fc &= ~PAUSE_TX;
5795 	}
5796 	if (lc->requested_fc & PAUSE_RX &&
5797 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
5798 		n++;
5799 		lc->requested_fc &= ~PAUSE_RX;
5800 	}
5801 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
5802 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
5803 		n++;
5804 		lc->requested_fc |= PAUSE_AUTONEG;
5805 	}
5806 
5807 	/* FEC */
5808 	if ((lc->requested_fec & FEC_RS &&
5809 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
5810 	    (lc->requested_fec & FEC_BASER_RS &&
5811 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
5812 		n++;
5813 		lc->requested_fec = FEC_AUTO;
5814 	}
5815 
5816 	return (n);
5817 }
5818 
5819 /*
5820  * Apply the requested L1 settings, which are expected to be valid, to the
5821  * hardware.
5822  */
5823 static int
5824 apply_link_config(struct port_info *pi)
5825 {
5826 	struct adapter *sc = pi->adapter;
5827 	struct link_config *lc = &pi->link_cfg;
5828 	int rc;
5829 
5830 #ifdef INVARIANTS
5831 	ASSERT_SYNCHRONIZED_OP(sc);
5832 	PORT_LOCK_ASSERT_OWNED(pi);
5833 
5834 	if (lc->requested_aneg == AUTONEG_ENABLE)
5835 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
5836 	if (!(lc->requested_fc & PAUSE_AUTONEG))
5837 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
5838 	if (lc->requested_fc & PAUSE_TX)
5839 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
5840 	if (lc->requested_fc & PAUSE_RX)
5841 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
5842 	if (lc->requested_fec & FEC_RS)
5843 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
5844 	if (lc->requested_fec & FEC_BASER_RS)
5845 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
5846 #endif
5847 	rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
5848 	if (rc != 0) {
5849 		/* Don't complain if the VF driver gets back an EPERM. */
5850 		if (!(sc->flags & IS_VF) || rc != FW_EPERM)
5851 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
5852 	} else {
5853 		/*
5854 		 * An L1_CFG will almost always result in a link-change event if
5855 		 * the link is up, and the driver will refresh the actual
5856 		 * fec/fc/etc. when the notification is processed.  If the link
5857 		 * is down then the actual settings are meaningless.
5858 		 *
5859 		 * This takes care of the case where a change in the L1 settings
5860 		 * may not result in a notification.
5861 		 */
5862 		if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
5863 			lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
5864 	}
5865 	return (rc);
5866 }
5867 
5868 #define FW_MAC_EXACT_CHUNK	7
5869 struct mcaddr_ctx {
5870 	struct ifnet *ifp;
5871 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
5872 	uint64_t hash;
5873 	int i;
5874 	int del;
5875 	int rc;
5876 };
5877 
5878 static u_int
5879 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
5880 {
5881 	struct mcaddr_ctx *ctx = arg;
5882 	struct vi_info *vi = ctx->ifp->if_softc;
5883 	struct port_info *pi = vi->pi;
5884 	struct adapter *sc = pi->adapter;
5885 
5886 	if (ctx->rc < 0)
5887 		return (0);
5888 
5889 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
5890 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
5891 	ctx->i++;
5892 
5893 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
5894 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
5895 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
5896 		if (ctx->rc < 0) {
5897 			int j;
5898 
5899 			for (j = 0; j < ctx->i; j++) {
5900 				if_printf(ctx->ifp,
5901 				    "failed to add mc address"
5902 				    " %02x:%02x:%02x:"
5903 				    "%02x:%02x:%02x rc=%d\n",
5904 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
5905 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
5906 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
5907 				    -ctx->rc);
5908 			}
5909 			return (0);
5910 		}
5911 		ctx->del = 0;
5912 		ctx->i = 0;
5913 	}
5914 
5915 	return (1);
5916 }
5917 
5918 /*
5919  * Program the port's XGMAC based on parameters in ifnet.  The caller also
5920  * indicates which parameters should be programmed (the rest are left alone).
5921  */
5922 int
5923 update_mac_settings(struct ifnet *ifp, int flags)
5924 {
5925 	int rc = 0;
5926 	struct vi_info *vi = ifp->if_softc;
5927 	struct port_info *pi = vi->pi;
5928 	struct adapter *sc = pi->adapter;
5929 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
5930 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
5931 
5932 	ASSERT_SYNCHRONIZED_OP(sc);
5933 	KASSERT(flags, ("%s: not told what to update.", __func__));
5934 
5935 	if (flags & XGMAC_MTU)
5936 		mtu = ifp->if_mtu;
5937 
5938 	if (flags & XGMAC_PROMISC)
5939 		promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
5940 
5941 	if (flags & XGMAC_ALLMULTI)
5942 		allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
5943 
5944 	if (flags & XGMAC_VLANEX)
5945 		vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
5946 
5947 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
5948 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
5949 		    allmulti, 1, vlanex, false);
5950 		if (rc) {
5951 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
5952 			    rc);
5953 			return (rc);
5954 		}
5955 	}
5956 
5957 	if (flags & XGMAC_UCADDR) {
5958 		uint8_t ucaddr[ETHER_ADDR_LEN];
5959 
5960 		bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
5961 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
5962 		    ucaddr, true, &vi->smt_idx);
5963 		if (rc < 0) {
5964 			rc = -rc;
5965 			if_printf(ifp, "change_mac failed: %d\n", rc);
5966 			return (rc);
5967 		} else {
5968 			vi->xact_addr_filt = rc;
5969 			rc = 0;
5970 		}
5971 	}
5972 
5973 	if (flags & XGMAC_MCADDRS) {
5974 		struct epoch_tracker et;
5975 		struct mcaddr_ctx ctx;
5976 		int j;
5977 
5978 		ctx.ifp = ifp;
5979 		ctx.hash = 0;
5980 		ctx.i = 0;
5981 		ctx.del = 1;
5982 		ctx.rc = 0;
5983 		/*
5984 		 * Unlike other drivers, we accumulate list of pointers into
5985 		 * interface address lists and we need to keep it safe even
5986 		 * after if_foreach_llmaddr() returns, thus we must enter the
5987 		 * network epoch.
5988 		 */
5989 		NET_EPOCH_ENTER(et);
5990 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
5991 		if (ctx.rc < 0) {
5992 			NET_EPOCH_EXIT(et);
5993 			rc = -ctx.rc;
5994 			return (rc);
5995 		}
5996 		if (ctx.i > 0) {
5997 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
5998 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
5999 			NET_EPOCH_EXIT(et);
6000 			if (rc < 0) {
6001 				rc = -rc;
6002 				for (j = 0; j < ctx.i; j++) {
6003 					if_printf(ifp,
6004 					    "failed to add mcast address"
6005 					    " %02x:%02x:%02x:"
6006 					    "%02x:%02x:%02x rc=%d\n",
6007 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6008 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6009 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6010 					    rc);
6011 				}
6012 				return (rc);
6013 			}
6014 			ctx.del = 0;
6015 		} else
6016 			NET_EPOCH_EXIT(et);
6017 
6018 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6019 		if (rc != 0)
6020 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6021 			    rc);
6022 		if (ctx.del == 0) {
6023 			/* We clobbered the VXLAN entry if there was one. */
6024 			pi->vxlan_tcam_entry = false;
6025 		}
6026 	}
6027 
6028 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6029 	    pi->vxlan_tcam_entry == false) {
6030 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6031 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6032 		    true);
6033 		if (rc < 0) {
6034 			rc = -rc;
6035 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6036 			    rc);
6037 		} else {
6038 			MPASS(rc == sc->rawf_base + pi->port_id);
6039 			rc = 0;
6040 			pi->vxlan_tcam_entry = true;
6041 		}
6042 	}
6043 
6044 	return (rc);
6045 }
6046 
6047 /*
6048  * {begin|end}_synchronized_op must be called from the same thread.
6049  */
6050 int
6051 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6052     char *wmesg)
6053 {
6054 	int rc, pri;
6055 
6056 #ifdef WITNESS
6057 	/* the caller thinks it's ok to sleep, but is it really? */
6058 	if (flags & SLEEP_OK)
6059 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6060 		    "begin_synchronized_op");
6061 #endif
6062 
6063 	if (INTR_OK)
6064 		pri = PCATCH;
6065 	else
6066 		pri = 0;
6067 
6068 	ADAPTER_LOCK(sc);
6069 	for (;;) {
6070 
6071 		if (vi && IS_DOOMED(vi)) {
6072 			rc = ENXIO;
6073 			goto done;
6074 		}
6075 
6076 		if (!IS_BUSY(sc)) {
6077 			rc = 0;
6078 			break;
6079 		}
6080 
6081 		if (!(flags & SLEEP_OK)) {
6082 			rc = EBUSY;
6083 			goto done;
6084 		}
6085 
6086 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6087 			rc = EINTR;
6088 			goto done;
6089 		}
6090 	}
6091 
6092 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6093 	SET_BUSY(sc);
6094 #ifdef INVARIANTS
6095 	sc->last_op = wmesg;
6096 	sc->last_op_thr = curthread;
6097 	sc->last_op_flags = flags;
6098 #endif
6099 
6100 done:
6101 	if (!(flags & HOLD_LOCK) || rc)
6102 		ADAPTER_UNLOCK(sc);
6103 
6104 	return (rc);
6105 }
6106 
6107 /*
6108  * Tell if_ioctl and if_init that the VI is going away.  This is
6109  * special variant of begin_synchronized_op and must be paired with a
6110  * call to end_synchronized_op.
6111  */
6112 void
6113 doom_vi(struct adapter *sc, struct vi_info *vi)
6114 {
6115 
6116 	ADAPTER_LOCK(sc);
6117 	SET_DOOMED(vi);
6118 	wakeup(&sc->flags);
6119 	while (IS_BUSY(sc))
6120 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6121 	SET_BUSY(sc);
6122 #ifdef INVARIANTS
6123 	sc->last_op = "t4detach";
6124 	sc->last_op_thr = curthread;
6125 	sc->last_op_flags = 0;
6126 #endif
6127 	ADAPTER_UNLOCK(sc);
6128 }
6129 
6130 /*
6131  * {begin|end}_synchronized_op must be called from the same thread.
6132  */
6133 void
6134 end_synchronized_op(struct adapter *sc, int flags)
6135 {
6136 
6137 	if (flags & LOCK_HELD)
6138 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6139 	else
6140 		ADAPTER_LOCK(sc);
6141 
6142 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6143 	CLR_BUSY(sc);
6144 	wakeup(&sc->flags);
6145 	ADAPTER_UNLOCK(sc);
6146 }
6147 
6148 static int
6149 cxgbe_init_synchronized(struct vi_info *vi)
6150 {
6151 	struct port_info *pi = vi->pi;
6152 	struct adapter *sc = pi->adapter;
6153 	struct ifnet *ifp = vi->ifp;
6154 	int rc = 0, i;
6155 	struct sge_txq *txq;
6156 
6157 	ASSERT_SYNCHRONIZED_OP(sc);
6158 
6159 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
6160 		return (0);	/* already running */
6161 
6162 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6163 		return (rc);	/* error message displayed already */
6164 
6165 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6166 		return (rc); /* error message displayed already */
6167 
6168 	rc = update_mac_settings(ifp, XGMAC_ALL);
6169 	if (rc)
6170 		goto done;	/* error message displayed already */
6171 
6172 	PORT_LOCK(pi);
6173 	if (pi->up_vis == 0) {
6174 		t4_update_port_info(pi);
6175 		fixup_link_config(pi);
6176 		build_medialist(pi);
6177 		apply_link_config(pi);
6178 	}
6179 
6180 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6181 	if (rc != 0) {
6182 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6183 		PORT_UNLOCK(pi);
6184 		goto done;
6185 	}
6186 
6187 	/*
6188 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6189 	 * if this changes.
6190 	 */
6191 
6192 	for_each_txq(vi, i, txq) {
6193 		TXQ_LOCK(txq);
6194 		txq->eq.flags |= EQ_ENABLED;
6195 		TXQ_UNLOCK(txq);
6196 	}
6197 
6198 	/*
6199 	 * The first iq of the first port to come up is used for tracing.
6200 	 */
6201 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6202 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6203 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6204 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6205 		    V_QUEUENUMBER(sc->traceq));
6206 		pi->flags |= HAS_TRACEQ;
6207 	}
6208 
6209 	/* all ok */
6210 	pi->up_vis++;
6211 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
6212 	if (pi->link_cfg.link_ok)
6213 		t4_os_link_changed(pi);
6214 	PORT_UNLOCK(pi);
6215 
6216 	mtx_lock(&vi->tick_mtx);
6217 	if (ifp->if_get_counter == vi_get_counter)
6218 		callout_reset(&vi->tick, hz, vi_tick, vi);
6219 	else
6220 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6221 	mtx_unlock(&vi->tick_mtx);
6222 done:
6223 	if (rc != 0)
6224 		cxgbe_uninit_synchronized(vi);
6225 
6226 	return (rc);
6227 }
6228 
6229 /*
6230  * Idempotent.
6231  */
6232 static int
6233 cxgbe_uninit_synchronized(struct vi_info *vi)
6234 {
6235 	struct port_info *pi = vi->pi;
6236 	struct adapter *sc = pi->adapter;
6237 	struct ifnet *ifp = vi->ifp;
6238 	int rc, i;
6239 	struct sge_txq *txq;
6240 
6241 	ASSERT_SYNCHRONIZED_OP(sc);
6242 
6243 	if (!(vi->flags & VI_INIT_DONE)) {
6244 		if (__predict_false(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6245 			KASSERT(0, ("uninited VI is running"));
6246 			if_printf(ifp, "uninited VI with running ifnet.  "
6247 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6248 			    "if_drv_flags 0x%08x\n", vi->flags, ifp->if_flags,
6249 			    ifp->if_drv_flags);
6250 		}
6251 		return (0);
6252 	}
6253 
6254 	/*
6255 	 * Disable the VI so that all its data in either direction is discarded
6256 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6257 	 * tick) intact as the TP can deliver negative advice or data that it's
6258 	 * holding in its RAM (for an offloaded connection) even after the VI is
6259 	 * disabled.
6260 	 */
6261 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6262 	if (rc) {
6263 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6264 		return (rc);
6265 	}
6266 
6267 	for_each_txq(vi, i, txq) {
6268 		TXQ_LOCK(txq);
6269 		txq->eq.flags &= ~EQ_ENABLED;
6270 		TXQ_UNLOCK(txq);
6271 	}
6272 
6273 	mtx_lock(&vi->tick_mtx);
6274 	callout_stop(&vi->tick);
6275 	mtx_unlock(&vi->tick_mtx);
6276 
6277 	PORT_LOCK(pi);
6278 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6279 		PORT_UNLOCK(pi);
6280 		return (0);
6281 	}
6282 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
6283 	pi->up_vis--;
6284 	if (pi->up_vis > 0) {
6285 		PORT_UNLOCK(pi);
6286 		return (0);
6287 	}
6288 
6289 	pi->link_cfg.link_ok = false;
6290 	pi->link_cfg.speed = 0;
6291 	pi->link_cfg.link_down_rc = 255;
6292 	t4_os_link_changed(pi);
6293 	PORT_UNLOCK(pi);
6294 
6295 	return (0);
6296 }
6297 
6298 /*
6299  * It is ok for this function to fail midway and return right away.  t4_detach
6300  * will walk the entire sc->irq list and clean up whatever is valid.
6301  */
6302 int
6303 t4_setup_intr_handlers(struct adapter *sc)
6304 {
6305 	int rc, rid, p, q, v;
6306 	char s[8];
6307 	struct irq *irq;
6308 	struct port_info *pi;
6309 	struct vi_info *vi;
6310 	struct sge *sge = &sc->sge;
6311 	struct sge_rxq *rxq;
6312 #ifdef TCP_OFFLOAD
6313 	struct sge_ofld_rxq *ofld_rxq;
6314 #endif
6315 #ifdef DEV_NETMAP
6316 	struct sge_nm_rxq *nm_rxq;
6317 #endif
6318 #ifdef RSS
6319 	int nbuckets = rss_getnumbuckets();
6320 #endif
6321 
6322 	/*
6323 	 * Setup interrupts.
6324 	 */
6325 	irq = &sc->irq[0];
6326 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6327 	if (forwarding_intr_to_fwq(sc))
6328 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6329 
6330 	/* Multiple interrupts. */
6331 	if (sc->flags & IS_VF)
6332 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6333 		    ("%s: too few intr.", __func__));
6334 	else
6335 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6336 		    ("%s: too few intr.", __func__));
6337 
6338 	/* The first one is always error intr on PFs */
6339 	if (!(sc->flags & IS_VF)) {
6340 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6341 		if (rc != 0)
6342 			return (rc);
6343 		irq++;
6344 		rid++;
6345 	}
6346 
6347 	/* The second one is always the firmware event queue (first on VFs) */
6348 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6349 	if (rc != 0)
6350 		return (rc);
6351 	irq++;
6352 	rid++;
6353 
6354 	for_each_port(sc, p) {
6355 		pi = sc->port[p];
6356 		for_each_vi(pi, v, vi) {
6357 			vi->first_intr = rid - 1;
6358 
6359 			if (vi->nnmrxq > 0) {
6360 				int n = max(vi->nrxq, vi->nnmrxq);
6361 
6362 				rxq = &sge->rxq[vi->first_rxq];
6363 #ifdef DEV_NETMAP
6364 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6365 #endif
6366 				for (q = 0; q < n; q++) {
6367 					snprintf(s, sizeof(s), "%x%c%x", p,
6368 					    'a' + v, q);
6369 					if (q < vi->nrxq)
6370 						irq->rxq = rxq++;
6371 #ifdef DEV_NETMAP
6372 					if (q < vi->nnmrxq)
6373 						irq->nm_rxq = nm_rxq++;
6374 
6375 					if (irq->nm_rxq != NULL &&
6376 					    irq->rxq == NULL) {
6377 						/* Netmap rx only */
6378 						rc = t4_alloc_irq(sc, irq, rid,
6379 						    t4_nm_intr, irq->nm_rxq, s);
6380 					}
6381 					if (irq->nm_rxq != NULL &&
6382 					    irq->rxq != NULL) {
6383 						/* NIC and Netmap rx */
6384 						rc = t4_alloc_irq(sc, irq, rid,
6385 						    t4_vi_intr, irq, s);
6386 					}
6387 #endif
6388 					if (irq->rxq != NULL &&
6389 					    irq->nm_rxq == NULL) {
6390 						/* NIC rx only */
6391 						rc = t4_alloc_irq(sc, irq, rid,
6392 						    t4_intr, irq->rxq, s);
6393 					}
6394 					if (rc != 0)
6395 						return (rc);
6396 #ifdef RSS
6397 					if (q < vi->nrxq) {
6398 						bus_bind_intr(sc->dev, irq->res,
6399 						    rss_getcpu(q % nbuckets));
6400 					}
6401 #endif
6402 					irq++;
6403 					rid++;
6404 					vi->nintr++;
6405 				}
6406 			} else {
6407 				for_each_rxq(vi, q, rxq) {
6408 					snprintf(s, sizeof(s), "%x%c%x", p,
6409 					    'a' + v, q);
6410 					rc = t4_alloc_irq(sc, irq, rid,
6411 					    t4_intr, rxq, s);
6412 					if (rc != 0)
6413 						return (rc);
6414 #ifdef RSS
6415 					bus_bind_intr(sc->dev, irq->res,
6416 					    rss_getcpu(q % nbuckets));
6417 #endif
6418 					irq++;
6419 					rid++;
6420 					vi->nintr++;
6421 				}
6422 			}
6423 #ifdef TCP_OFFLOAD
6424 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6425 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6426 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6427 				    ofld_rxq, s);
6428 				if (rc != 0)
6429 					return (rc);
6430 				irq++;
6431 				rid++;
6432 				vi->nintr++;
6433 			}
6434 #endif
6435 		}
6436 	}
6437 	MPASS(irq == &sc->irq[sc->intr_count]);
6438 
6439 	return (0);
6440 }
6441 
6442 static void
6443 write_global_rss_key(struct adapter *sc)
6444 {
6445 #ifdef RSS
6446 	int i;
6447 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6448 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6449 
6450 	CTASSERT(RSS_KEYSIZE == 40);
6451 
6452 	rss_getkey((void *)&raw_rss_key[0]);
6453 	for (i = 0; i < nitems(rss_key); i++) {
6454 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6455 	}
6456 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6457 #endif
6458 }
6459 
6460 /*
6461  * Idempotent.
6462  */
6463 static int
6464 adapter_full_init(struct adapter *sc)
6465 {
6466 	int rc, i;
6467 
6468 	ASSERT_SYNCHRONIZED_OP(sc);
6469 
6470 	if (!(sc->flags & ADAP_SYSCTL_CTX)) {
6471 		sysctl_ctx_init(&sc->ctx);
6472 		sc->flags |= ADAP_SYSCTL_CTX;
6473 	}
6474 
6475 	/*
6476 	 * queues that belong to the adapter (not any particular port).
6477 	 */
6478 	rc = t4_setup_adapter_queues(sc);
6479 	if (rc != 0)
6480 		return (rc);
6481 
6482 	for (i = 0; i < nitems(sc->tq); i++) {
6483 		if (sc->tq[i] != NULL)
6484 			continue;
6485 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6486 		    taskqueue_thread_enqueue, &sc->tq[i]);
6487 		if (sc->tq[i] == NULL) {
6488 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6489 			return (ENOMEM);
6490 		}
6491 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6492 		    device_get_nameunit(sc->dev), i);
6493 	}
6494 
6495 	if (!(sc->flags & IS_VF)) {
6496 		write_global_rss_key(sc);
6497 		t4_intr_enable(sc);
6498 	}
6499 	return (0);
6500 }
6501 
6502 int
6503 adapter_init(struct adapter *sc)
6504 {
6505 	int rc;
6506 
6507 	ASSERT_SYNCHRONIZED_OP(sc);
6508 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6509 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6510 	    ("%s: FULL_INIT_DONE already", __func__));
6511 
6512 	rc = adapter_full_init(sc);
6513 	if (rc != 0)
6514 		adapter_full_uninit(sc);
6515 	else
6516 		sc->flags |= FULL_INIT_DONE;
6517 
6518 	return (rc);
6519 }
6520 
6521 /*
6522  * Idempotent.
6523  */
6524 static void
6525 adapter_full_uninit(struct adapter *sc)
6526 {
6527 	int i;
6528 
6529 	/* Do this before freeing the adapter queues. */
6530 	if (sc->flags & ADAP_SYSCTL_CTX) {
6531 		sysctl_ctx_free(&sc->ctx);
6532 		sc->flags &= ~ADAP_SYSCTL_CTX;
6533 	}
6534 
6535 	t4_teardown_adapter_queues(sc);
6536 
6537 	for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
6538 		taskqueue_free(sc->tq[i]);
6539 		sc->tq[i] = NULL;
6540 	}
6541 
6542 	sc->flags &= ~FULL_INIT_DONE;
6543 }
6544 
6545 #ifdef RSS
6546 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6547     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6548     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6549     RSS_HASHTYPE_RSS_UDP_IPV6)
6550 
6551 /* Translates kernel hash types to hardware. */
6552 static int
6553 hashconfig_to_hashen(int hashconfig)
6554 {
6555 	int hashen = 0;
6556 
6557 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6558 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6559 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6560 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6561 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6562 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6563 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6564 	}
6565 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6566 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6567 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6568 	}
6569 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6570 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6571 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6572 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6573 
6574 	return (hashen);
6575 }
6576 
6577 /* Translates hardware hash types to kernel. */
6578 static int
6579 hashen_to_hashconfig(int hashen)
6580 {
6581 	int hashconfig = 0;
6582 
6583 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6584 		/*
6585 		 * If UDP hashing was enabled it must have been enabled for
6586 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6587 		 * enabling any 4-tuple hash is nonsense configuration.
6588 		 */
6589 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6590 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6591 
6592 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6593 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6594 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6595 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6596 	}
6597 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6598 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6599 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6600 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6601 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6602 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6603 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6604 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6605 
6606 	return (hashconfig);
6607 }
6608 #endif
6609 
6610 /*
6611  * Idempotent.
6612  */
6613 static int
6614 vi_full_init(struct vi_info *vi)
6615 {
6616 	struct adapter *sc = vi->adapter;
6617 	struct sge_rxq *rxq;
6618 	int rc, i, j;
6619 #ifdef RSS
6620 	int nbuckets = rss_getnumbuckets();
6621 	int hashconfig = rss_gethashconfig();
6622 	int extra;
6623 #endif
6624 
6625 	ASSERT_SYNCHRONIZED_OP(sc);
6626 
6627 	if (!(vi->flags & VI_SYSCTL_CTX)) {
6628 		sysctl_ctx_init(&vi->ctx);
6629 		vi->flags |= VI_SYSCTL_CTX;
6630 	}
6631 
6632 	/*
6633 	 * Allocate tx/rx/fl queues for this VI.
6634 	 */
6635 	rc = t4_setup_vi_queues(vi);
6636 	if (rc != 0)
6637 		return (rc);
6638 
6639 	/*
6640 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6641 	 */
6642 	if (vi->nrxq > vi->rss_size) {
6643 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6644 		    "some queues will never receive traffic.\n", vi->nrxq,
6645 		    vi->rss_size);
6646 	} else if (vi->rss_size % vi->nrxq) {
6647 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6648 		    "expect uneven traffic distribution.\n", vi->nrxq,
6649 		    vi->rss_size);
6650 	}
6651 #ifdef RSS
6652 	if (vi->nrxq != nbuckets) {
6653 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6654 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6655 	}
6656 #endif
6657 	if (vi->rss == NULL)
6658 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6659 		    M_ZERO | M_WAITOK);
6660 	for (i = 0; i < vi->rss_size;) {
6661 #ifdef RSS
6662 		j = rss_get_indirection_to_bucket(i);
6663 		j %= vi->nrxq;
6664 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6665 		vi->rss[i++] = rxq->iq.abs_id;
6666 #else
6667 		for_each_rxq(vi, j, rxq) {
6668 			vi->rss[i++] = rxq->iq.abs_id;
6669 			if (i == vi->rss_size)
6670 				break;
6671 		}
6672 #endif
6673 	}
6674 
6675 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6676 	    vi->rss, vi->rss_size);
6677 	if (rc != 0) {
6678 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6679 		return (rc);
6680 	}
6681 
6682 #ifdef RSS
6683 	vi->hashen = hashconfig_to_hashen(hashconfig);
6684 
6685 	/*
6686 	 * We may have had to enable some hashes even though the global config
6687 	 * wants them disabled.  This is a potential problem that must be
6688 	 * reported to the user.
6689 	 */
6690 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6691 
6692 	/*
6693 	 * If we consider only the supported hash types, then the enabled hashes
6694 	 * are a superset of the requested hashes.  In other words, there cannot
6695 	 * be any supported hash that was requested but not enabled, but there
6696 	 * can be hashes that were not requested but had to be enabled.
6697 	 */
6698 	extra &= SUPPORTED_RSS_HASHTYPES;
6699 	MPASS((extra & hashconfig) == 0);
6700 
6701 	if (extra) {
6702 		CH_ALERT(vi,
6703 		    "global RSS config (0x%x) cannot be accommodated.\n",
6704 		    hashconfig);
6705 	}
6706 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6707 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6708 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6709 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6710 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6711 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6712 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6713 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6714 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6715 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6716 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6717 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6718 #else
6719 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6720 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6721 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6722 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6723 #endif
6724 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6725 	    0, 0);
6726 	if (rc != 0) {
6727 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6728 		return (rc);
6729 	}
6730 
6731 	return (0);
6732 }
6733 
6734 int
6735 vi_init(struct vi_info *vi)
6736 {
6737 	int rc;
6738 
6739 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6740 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6741 	    ("%s: VI_INIT_DONE already", __func__));
6742 
6743 	rc = vi_full_init(vi);
6744 	if (rc != 0)
6745 		vi_full_uninit(vi);
6746 	else
6747 		vi->flags |= VI_INIT_DONE;
6748 
6749 	return (rc);
6750 }
6751 
6752 /*
6753  * Idempotent.
6754  */
6755 static void
6756 vi_full_uninit(struct vi_info *vi)
6757 {
6758 
6759 	if (vi->flags & VI_INIT_DONE) {
6760 		quiesce_vi(vi);
6761 		free(vi->rss, M_CXGBE);
6762 		free(vi->nm_rss, M_CXGBE);
6763 	}
6764 
6765 	/* Do this before freeing the VI queues. */
6766 	if (vi->flags & VI_SYSCTL_CTX) {
6767 		sysctl_ctx_free(&vi->ctx);
6768 		vi->flags &= ~VI_SYSCTL_CTX;
6769 	}
6770 
6771 	t4_teardown_vi_queues(vi);
6772 	vi->flags &= ~VI_INIT_DONE;
6773 }
6774 
6775 static void
6776 quiesce_txq(struct sge_txq *txq)
6777 {
6778 	struct sge_eq *eq = &txq->eq;
6779 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6780 
6781 	MPASS(eq->flags & EQ_SW_ALLOCATED);
6782 	MPASS(!(eq->flags & EQ_ENABLED));
6783 
6784 	/* Wait for the mp_ring to empty. */
6785 	while (!mp_ring_is_idle(txq->r)) {
6786 		mp_ring_check_drainage(txq->r, 4096);
6787 		pause("rquiesce", 1);
6788 	}
6789 	MPASS(txq->txp.npkt == 0);
6790 
6791 	if (eq->flags & EQ_HW_ALLOCATED) {
6792 		/*
6793 		 * Hardware is alive and working normally.  Wait for it to
6794 		 * finish and then wait for the driver to catch up and reclaim
6795 		 * all descriptors.
6796 		 */
6797 		while (spg->cidx != htobe16(eq->pidx))
6798 			pause("equiesce", 1);
6799 		while (eq->cidx != eq->pidx)
6800 			pause("dquiesce", 1);
6801 	} else {
6802 		/*
6803 		 * Hardware is unavailable.  Discard all pending tx and reclaim
6804 		 * descriptors directly.
6805 		 */
6806 		TXQ_LOCK(txq);
6807 		while (eq->cidx != eq->pidx) {
6808 			struct mbuf *m, *nextpkt;
6809 			struct tx_sdesc *txsd;
6810 
6811 			txsd = &txq->sdesc[eq->cidx];
6812 			for (m = txsd->m; m != NULL; m = nextpkt) {
6813 				nextpkt = m->m_nextpkt;
6814 				m->m_nextpkt = NULL;
6815 				m_freem(m);
6816 			}
6817 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
6818 		}
6819 		spg->pidx = spg->cidx = htobe16(eq->cidx);
6820 		TXQ_UNLOCK(txq);
6821 	}
6822 }
6823 
6824 static void
6825 quiesce_wrq(struct sge_wrq *wrq)
6826 {
6827 
6828 	/* XXXTX */
6829 }
6830 
6831 static void
6832 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
6833 {
6834 	/* Synchronize with the interrupt handler */
6835 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
6836 		pause("iqfree", 1);
6837 
6838 	if (fl != NULL) {
6839 		MPASS(iq->flags & IQ_HAS_FL);
6840 
6841 		mtx_lock(&sc->sfl_lock);
6842 		FL_LOCK(fl);
6843 		fl->flags |= FL_DOOMED;
6844 		FL_UNLOCK(fl);
6845 		callout_stop(&sc->sfl_callout);
6846 		mtx_unlock(&sc->sfl_lock);
6847 
6848 		KASSERT((fl->flags & FL_STARVING) == 0,
6849 		    ("%s: still starving", __func__));
6850 
6851 		/* Release all buffers if hardware is no longer available. */
6852 		if (!(iq->flags & IQ_HW_ALLOCATED))
6853 			free_fl_buffers(sc, fl);
6854 	}
6855 }
6856 
6857 /*
6858  * Wait for all activity on all the queues of the VI to complete.  It is assumed
6859  * that no new work is being enqueued by the hardware or the driver.  That part
6860  * should be arranged before calling this function.
6861  */
6862 static void
6863 quiesce_vi(struct vi_info *vi)
6864 {
6865 	int i;
6866 	struct adapter *sc = vi->adapter;
6867 	struct sge_rxq *rxq;
6868 	struct sge_txq *txq;
6869 #ifdef TCP_OFFLOAD
6870 	struct sge_ofld_rxq *ofld_rxq;
6871 #endif
6872 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6873 	struct sge_ofld_txq *ofld_txq;
6874 #endif
6875 
6876 	if (!(vi->flags & VI_INIT_DONE))
6877 		return;
6878 
6879 	for_each_txq(vi, i, txq) {
6880 		quiesce_txq(txq);
6881 	}
6882 
6883 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6884 	for_each_ofld_txq(vi, i, ofld_txq) {
6885 		quiesce_wrq(&ofld_txq->wrq);
6886 	}
6887 #endif
6888 
6889 	for_each_rxq(vi, i, rxq) {
6890 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
6891 	}
6892 
6893 #ifdef TCP_OFFLOAD
6894 	for_each_ofld_rxq(vi, i, ofld_rxq) {
6895 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
6896 	}
6897 #endif
6898 }
6899 
6900 static int
6901 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
6902     driver_intr_t *handler, void *arg, char *name)
6903 {
6904 	int rc;
6905 
6906 	irq->rid = rid;
6907 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
6908 	    RF_SHAREABLE | RF_ACTIVE);
6909 	if (irq->res == NULL) {
6910 		device_printf(sc->dev,
6911 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
6912 		return (ENOMEM);
6913 	}
6914 
6915 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
6916 	    NULL, handler, arg, &irq->tag);
6917 	if (rc != 0) {
6918 		device_printf(sc->dev,
6919 		    "failed to setup interrupt for rid %d, name %s: %d\n",
6920 		    rid, name, rc);
6921 	} else if (name)
6922 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
6923 
6924 	return (rc);
6925 }
6926 
6927 static int
6928 t4_free_irq(struct adapter *sc, struct irq *irq)
6929 {
6930 	if (irq->tag)
6931 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
6932 	if (irq->res)
6933 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
6934 
6935 	bzero(irq, sizeof(*irq));
6936 
6937 	return (0);
6938 }
6939 
6940 static void
6941 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
6942 {
6943 
6944 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
6945 	t4_get_regs(sc, buf, regs->len);
6946 }
6947 
6948 #define	A_PL_INDIR_CMD	0x1f8
6949 
6950 #define	S_PL_AUTOINC	31
6951 #define	M_PL_AUTOINC	0x1U
6952 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
6953 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
6954 
6955 #define	S_PL_VFID	20
6956 #define	M_PL_VFID	0xffU
6957 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
6958 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
6959 
6960 #define	S_PL_ADDR	0
6961 #define	M_PL_ADDR	0xfffffU
6962 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
6963 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
6964 
6965 #define	A_PL_INDIR_DATA	0x1fc
6966 
6967 static uint64_t
6968 read_vf_stat(struct adapter *sc, u_int vin, int reg)
6969 {
6970 	u32 stats[2];
6971 
6972 	if (sc->flags & IS_VF) {
6973 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
6974 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
6975 	} else {
6976 		mtx_assert(&sc->reg_lock, MA_OWNED);
6977 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
6978 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
6979 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
6980 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
6981 	}
6982 	return (((uint64_t)stats[1]) << 32 | stats[0]);
6983 }
6984 
6985 static void
6986 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
6987 {
6988 
6989 #define GET_STAT(name) \
6990 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
6991 
6992 	if (!(sc->flags & IS_VF))
6993 		mtx_lock(&sc->reg_lock);
6994 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
6995 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
6996 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
6997 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
6998 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
6999 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7000 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7001 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7002 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7003 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7004 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7005 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7006 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7007 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7008 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7009 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7010 	if (!(sc->flags & IS_VF))
7011 		mtx_unlock(&sc->reg_lock);
7012 
7013 #undef GET_STAT
7014 }
7015 
7016 static void
7017 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7018 {
7019 	int reg;
7020 
7021 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7022 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7023 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7024 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7025 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7026 }
7027 
7028 static void
7029 vi_refresh_stats(struct vi_info *vi)
7030 {
7031 	struct timeval tv;
7032 	const struct timeval interval = {0, 250000};	/* 250ms */
7033 
7034 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7035 
7036 	if (!(vi->flags & VI_INIT_DONE) || vi->flags & VI_SKIP_STATS)
7037 		return;
7038 
7039 	getmicrotime(&tv);
7040 	timevalsub(&tv, &interval);
7041 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7042 		return;
7043 
7044 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7045 	getmicrotime(&vi->last_refreshed);
7046 }
7047 
7048 static void
7049 cxgbe_refresh_stats(struct vi_info *vi)
7050 {
7051 	u_int i, v, tnl_cong_drops, chan_map;
7052 	struct timeval tv;
7053 	const struct timeval interval = {0, 250000};	/* 250ms */
7054 	struct port_info *pi;
7055 	struct adapter *sc;
7056 
7057 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7058 
7059 	if (vi->flags & VI_SKIP_STATS)
7060 		return;
7061 
7062 	getmicrotime(&tv);
7063 	timevalsub(&tv, &interval);
7064 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7065 		return;
7066 
7067 	pi = vi->pi;
7068 	sc = vi->adapter;
7069 	tnl_cong_drops = 0;
7070 	t4_get_port_stats(sc, pi->tx_chan, &pi->stats);
7071 	chan_map = pi->rx_e_chan_map;
7072 	while (chan_map) {
7073 		i = ffs(chan_map) - 1;
7074 		mtx_lock(&sc->reg_lock);
7075 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7076 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7077 		mtx_unlock(&sc->reg_lock);
7078 		tnl_cong_drops += v;
7079 		chan_map &= ~(1 << i);
7080 	}
7081 	pi->tnl_cong_drops = tnl_cong_drops;
7082 	getmicrotime(&vi->last_refreshed);
7083 }
7084 
7085 static void
7086 cxgbe_tick(void *arg)
7087 {
7088 	struct vi_info *vi = arg;
7089 
7090 	MPASS(IS_MAIN_VI(vi));
7091 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7092 
7093 	cxgbe_refresh_stats(vi);
7094 	callout_schedule(&vi->tick, hz);
7095 }
7096 
7097 static void
7098 vi_tick(void *arg)
7099 {
7100 	struct vi_info *vi = arg;
7101 
7102 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7103 
7104 	vi_refresh_stats(vi);
7105 	callout_schedule(&vi->tick, hz);
7106 }
7107 
7108 /*
7109  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7110  */
7111 static char *caps_decoder[] = {
7112 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7113 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7114 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7115 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7116 	    "\006HASHFILTER\007ETHOFLD",
7117 	"\20\001TOE",					/* 4: TOE */
7118 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7119 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7120 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7121 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7122 	    "\007T10DIF"
7123 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7124 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7125 	    "\004TLS_HW",
7126 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7127 		    "\004PO_INITIATOR\005PO_TARGET",
7128 };
7129 
7130 void
7131 t4_sysctls(struct adapter *sc)
7132 {
7133 	struct sysctl_ctx_list *ctx;
7134 	struct sysctl_oid *oid;
7135 	struct sysctl_oid_list *children, *c0;
7136 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7137 
7138 	ctx = device_get_sysctl_ctx(sc->dev);
7139 
7140 	/*
7141 	 * dev.t4nex.X.
7142 	 */
7143 	oid = device_get_sysctl_tree(sc->dev);
7144 	c0 = children = SYSCTL_CHILDREN(oid);
7145 
7146 	sc->sc_do_rxcopy = 1;
7147 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7148 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7149 
7150 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7151 	    sc->params.nports, "# of ports");
7152 
7153 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7154 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7155 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7156 	    "available doorbells");
7157 
7158 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7159 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7160 
7161 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7162 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7163 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7164 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7165 
7166 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7167 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7168 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7169 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7170 
7171 	t4_sge_sysctls(sc, ctx, children);
7172 
7173 	sc->lro_timeout = 100;
7174 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7175 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7176 
7177 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7178 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7179 
7180 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7181 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7182 
7183 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7184 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7185 
7186 	if (sc->flags & IS_VF)
7187 		return;
7188 
7189 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7190 	    NULL, chip_rev(sc), "chip hardware revision");
7191 
7192 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7193 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7194 
7195 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7196 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7197 
7198 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7199 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7200 
7201 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7202 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7203 
7204 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7205 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7206 
7207 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7208 	    sc->er_version, 0, "expansion ROM version");
7209 
7210 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7211 	    sc->bs_version, 0, "bootstrap firmware version");
7212 
7213 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7214 	    NULL, sc->params.scfg_vers, "serial config version");
7215 
7216 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7217 	    NULL, sc->params.vpd_vers, "VPD version");
7218 
7219 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7220 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7221 
7222 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7223 	    sc->cfcsum, "config file checksum");
7224 
7225 #define SYSCTL_CAP(name, n, text) \
7226 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7227 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7228 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7229 	    "available " text " capabilities")
7230 
7231 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7232 	SYSCTL_CAP(linkcaps, 1, "link");
7233 	SYSCTL_CAP(switchcaps, 2, "switch");
7234 	SYSCTL_CAP(niccaps, 3, "NIC");
7235 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7236 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7237 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7238 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7239 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7240 #undef SYSCTL_CAP
7241 
7242 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7243 	    NULL, sc->tids.nftids, "number of filters");
7244 
7245 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7246 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7247 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7248 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7249 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7250 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7251 
7252 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7253 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7254 	    sysctl_loadavg, "A",
7255 	    "microprocessor load averages (debug firmwares only)");
7256 
7257 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7258 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7259 	    "I", "core Vdd (in mV)");
7260 
7261 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7262 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7263 	    sysctl_cpus, "A", "local CPUs");
7264 
7265 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7266 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7267 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7268 
7269 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7270 	    &sc->swintr, 0, "software triggered interrupts");
7271 
7272 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7273 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7274 	    "1 = reset adapter, 0 = zero reset counter");
7275 
7276 	/*
7277 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7278 	 */
7279 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7280 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7281 	    "logs and miscellaneous information");
7282 	children = SYSCTL_CHILDREN(oid);
7283 
7284 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7285 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7286 	    sysctl_cctrl, "A", "congestion control");
7287 
7288 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7289 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7290 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7291 
7292 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7293 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7294 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7295 
7296 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7297 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7298 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7299 
7300 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7301 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7302 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7303 
7304 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7305 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7306 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7307 
7308 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7309 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7310 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7311 
7312 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7313 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7314 	    sysctl_cim_la, "A", "CIM logic analyzer");
7315 
7316 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7317 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7318 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7319 
7320 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7321 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7322 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7323 
7324 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7325 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7326 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7327 
7328 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7329 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7330 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7331 
7332 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7333 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7334 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7335 
7336 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7337 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7338 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7339 
7340 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7341 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7342 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7343 
7344 	if (chip_id(sc) > CHELSIO_T4) {
7345 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7346 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7347 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7348 		    "CIM OBQ 6 (SGE0-RX)");
7349 
7350 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7351 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7352 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7353 		    "CIM OBQ 7 (SGE1-RX)");
7354 	}
7355 
7356 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7357 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7358 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7359 
7360 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7361 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7362 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7363 
7364 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7365 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7366 	    sysctl_cpl_stats, "A", "CPL statistics");
7367 
7368 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7369 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7370 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7371 
7372 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7373 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7374 	    sysctl_tid_stats, "A", "tid stats");
7375 
7376 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7377 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7378 	    sysctl_devlog, "A", "firmware's device log");
7379 
7380 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7381 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7382 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7383 
7384 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7385 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7386 	    sysctl_hw_sched, "A", "hardware scheduler ");
7387 
7388 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7389 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7390 	    sysctl_l2t, "A", "hardware L2 table");
7391 
7392 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7393 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7394 	    sysctl_smt, "A", "hardware source MAC table");
7395 
7396 #ifdef INET6
7397 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7398 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7399 	    sysctl_clip, "A", "active CLIP table entries");
7400 #endif
7401 
7402 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7403 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7404 	    sysctl_lb_stats, "A", "loopback statistics");
7405 
7406 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7407 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7408 	    sysctl_meminfo, "A", "memory regions");
7409 
7410 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7411 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7412 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7413 	    "A", "MPS TCAM entries");
7414 
7415 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7416 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7417 	    sysctl_path_mtus, "A", "path MTUs");
7418 
7419 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7420 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7421 	    sysctl_pm_stats, "A", "PM statistics");
7422 
7423 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7424 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7425 	    sysctl_rdma_stats, "A", "RDMA statistics");
7426 
7427 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7428 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7429 	    sysctl_tcp_stats, "A", "TCP statistics");
7430 
7431 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7432 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7433 	    sysctl_tids, "A", "TID information");
7434 
7435 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7436 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7437 	    sysctl_tp_err_stats, "A", "TP error statistics");
7438 
7439 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7440 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7441 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7442 
7443 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7444 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7445 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7446 
7447 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7448 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7449 	    sysctl_tp_la, "A", "TP logic analyzer");
7450 
7451 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7452 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7453 	    sysctl_tx_rate, "A", "Tx rate");
7454 
7455 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7456 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7457 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7458 
7459 	if (chip_id(sc) >= CHELSIO_T5) {
7460 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7461 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7462 		    sysctl_wcwr_stats, "A", "write combined work requests");
7463 	}
7464 
7465 #ifdef KERN_TLS
7466 	if (is_ktls(sc)) {
7467 		/*
7468 		 * dev.t4nex.0.tls.
7469 		 */
7470 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7471 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7472 		children = SYSCTL_CHILDREN(oid);
7473 
7474 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7475 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7476 		    "keys in work requests (1) or attempt to store TLS keys "
7477 		    "in card memory.");
7478 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7479 		    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to combine "
7480 		    "TCB field updates with TLS record work requests.");
7481 	}
7482 #endif
7483 
7484 #ifdef TCP_OFFLOAD
7485 	if (is_offload(sc)) {
7486 		int i;
7487 		char s[4];
7488 
7489 		/*
7490 		 * dev.t4nex.X.toe.
7491 		 */
7492 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7493 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7494 		children = SYSCTL_CHILDREN(oid);
7495 
7496 		sc->tt.cong_algorithm = -1;
7497 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7498 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7499 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7500 		    "3 = highspeed)");
7501 
7502 		sc->tt.sndbuf = -1;
7503 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7504 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7505 
7506 		sc->tt.ddp = 0;
7507 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7508 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7509 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7510 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7511 
7512 		sc->tt.rx_coalesce = -1;
7513 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7514 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7515 
7516 		sc->tt.tls = 0;
7517 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7518 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7519 		    "Inline TLS allowed");
7520 
7521 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_ports",
7522 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7523 		    sysctl_tls_rx_ports, "I",
7524 		    "TCP ports that use inline TLS+TOE RX");
7525 
7526 		sc->tt.tls_rx_timeout = t4_toe_tls_rx_timeout;
7527 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_timeout",
7528 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7529 		    sysctl_tls_rx_timeout, "I",
7530 		    "Timeout in seconds to downgrade TLS sockets to plain TOE");
7531 
7532 		sc->tt.tx_align = -1;
7533 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7534 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7535 
7536 		sc->tt.tx_zcopy = 0;
7537 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7538 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7539 		    "Enable zero-copy aio_write(2)");
7540 
7541 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7542 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7543 		    "cop_managed_offloading", CTLFLAG_RW,
7544 		    &sc->tt.cop_managed_offloading, 0,
7545 		    "COP (Connection Offload Policy) controls all TOE offload");
7546 
7547 		sc->tt.autorcvbuf_inc = 16 * 1024;
7548 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7549 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7550 		    "autorcvbuf increment");
7551 
7552 		sc->tt.update_hc_on_pmtu_change = 1;
7553 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7554 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7555 		    &sc->tt.update_hc_on_pmtu_change, 0,
7556 		    "Update hostcache entry if the PMTU changes");
7557 
7558 		sc->tt.iso = 1;
7559 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7560 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7561 
7562 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7563 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7564 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7565 
7566 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7567 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7568 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7569 
7570 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7571 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7572 		    sysctl_tp_tick, "A", "DACK tick (us)");
7573 
7574 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7575 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7576 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7577 
7578 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7579 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7580 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7581 		    "Minimum retransmit interval (us)");
7582 
7583 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7584 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7585 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7586 		    "Maximum retransmit interval (us)");
7587 
7588 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7589 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7590 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7591 		    "Persist timer min (us)");
7592 
7593 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7594 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7595 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7596 		    "Persist timer max (us)");
7597 
7598 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7599 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7600 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7601 		    "Keepalive idle timer (us)");
7602 
7603 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7604 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7605 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7606 		    "Keepalive interval timer (us)");
7607 
7608 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7609 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7610 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7611 
7612 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7613 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7614 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7615 		    "FINWAIT2 timer (us)");
7616 
7617 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7618 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7619 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7620 		    "Number of SYN retransmissions before abort");
7621 
7622 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7623 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7624 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7625 		    "Number of retransmissions before abort");
7626 
7627 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7628 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7629 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7630 		    "Number of keepalive probes before abort");
7631 
7632 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7633 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7634 		    "TOE retransmit backoffs");
7635 		children = SYSCTL_CHILDREN(oid);
7636 		for (i = 0; i < 16; i++) {
7637 			snprintf(s, sizeof(s), "%u", i);
7638 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7639 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7640 			    i, sysctl_tp_backoff, "IU",
7641 			    "TOE retransmit backoff");
7642 		}
7643 	}
7644 #endif
7645 }
7646 
7647 void
7648 vi_sysctls(struct vi_info *vi)
7649 {
7650 	struct sysctl_ctx_list *ctx;
7651 	struct sysctl_oid *oid;
7652 	struct sysctl_oid_list *children;
7653 
7654 	ctx = device_get_sysctl_ctx(vi->dev);
7655 
7656 	/*
7657 	 * dev.v?(cxgbe|cxl).X.
7658 	 */
7659 	oid = device_get_sysctl_tree(vi->dev);
7660 	children = SYSCTL_CHILDREN(oid);
7661 
7662 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7663 	    vi->viid, "VI identifer");
7664 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7665 	    &vi->nrxq, 0, "# of rx queues");
7666 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7667 	    &vi->ntxq, 0, "# of tx queues");
7668 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7669 	    &vi->first_rxq, 0, "index of first rx queue");
7670 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7671 	    &vi->first_txq, 0, "index of first tx queue");
7672 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7673 	    vi->rss_base, "start of RSS indirection table");
7674 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7675 	    vi->rss_size, "size of RSS indirection table");
7676 
7677 	if (IS_MAIN_VI(vi)) {
7678 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7679 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7680 		    sysctl_noflowq, "IU",
7681 		    "Reserve queue 0 for non-flowid packets");
7682 	}
7683 
7684 	if (vi->adapter->flags & IS_VF) {
7685 		MPASS(vi->flags & TX_USES_VM_WR);
7686 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7687 		    NULL, 1, "use VM work requests for transmit");
7688 	} else {
7689 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7690 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7691 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7692 	}
7693 
7694 #ifdef TCP_OFFLOAD
7695 	if (vi->nofldrxq != 0) {
7696 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7697 		    &vi->nofldrxq, 0,
7698 		    "# of rx queues for offloaded TCP connections");
7699 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7700 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7701 		    "index of first TOE rx queue");
7702 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7703 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7704 		    sysctl_holdoff_tmr_idx_ofld, "I",
7705 		    "holdoff timer index for TOE queues");
7706 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7707 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7708 		    sysctl_holdoff_pktc_idx_ofld, "I",
7709 		    "holdoff packet counter index for TOE queues");
7710 	}
7711 #endif
7712 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7713 	if (vi->nofldtxq != 0) {
7714 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7715 		    &vi->nofldtxq, 0,
7716 		    "# of tx queues for TOE/ETHOFLD");
7717 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7718 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7719 		    "index of first TOE/ETHOFLD tx queue");
7720 	}
7721 #endif
7722 #ifdef DEV_NETMAP
7723 	if (vi->nnmrxq != 0) {
7724 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7725 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7726 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7727 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7728 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7729 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7730 		    "index of first netmap rx queue");
7731 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7732 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7733 		    "index of first netmap tx queue");
7734 	}
7735 #endif
7736 
7737 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7738 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7739 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7740 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7741 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7742 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7743 
7744 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7745 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7746 	    sysctl_qsize_rxq, "I", "rx queue size");
7747 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7748 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7749 	    sysctl_qsize_txq, "I", "tx queue size");
7750 }
7751 
7752 static void
7753 cxgbe_sysctls(struct port_info *pi)
7754 {
7755 	struct sysctl_ctx_list *ctx;
7756 	struct sysctl_oid *oid;
7757 	struct sysctl_oid_list *children, *children2;
7758 	struct adapter *sc = pi->adapter;
7759 	int i;
7760 	char name[16];
7761 	static char *tc_flags = {"\20\1USER"};
7762 
7763 	ctx = device_get_sysctl_ctx(pi->dev);
7764 
7765 	/*
7766 	 * dev.cxgbe.X.
7767 	 */
7768 	oid = device_get_sysctl_tree(pi->dev);
7769 	children = SYSCTL_CHILDREN(oid);
7770 
7771 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7772 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7773 	    sysctl_linkdnrc, "A", "reason why link is down");
7774 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7775 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7776 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7777 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
7778 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7779 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7780 		    sysctl_btphy, "I", "PHY firmware version");
7781 	}
7782 
7783 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7784 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7785 	    sysctl_pause_settings, "A",
7786 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7787 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
7788 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
7789 	    "FEC in use on the link");
7790 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
7791 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7792 	    sysctl_requested_fec, "A",
7793 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7794 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7795 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7796 	    "FEC recommended by the cable/transceiver");
7797 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7798 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7799 	    sysctl_autoneg, "I",
7800 	    "autonegotiation (-1 = not supported)");
7801 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
7802 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7803 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
7804 
7805 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
7806 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
7807 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7808 	    &pi->link_cfg.pcaps, 0, "port capabilities");
7809 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7810 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
7811 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7812 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7813 
7814 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7815 	    port_top_speed(pi), "max speed (in Gbps)");
7816 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7817 	    pi->mps_bg_map, "MPS buffer group map");
7818 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
7819 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
7820 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_c_chan", CTLFLAG_RD, NULL,
7821 	    pi->rx_c_chan, "TP rx c-channel");
7822 
7823 	if (sc->flags & IS_VF)
7824 		return;
7825 
7826 	/*
7827 	 * dev.(cxgbe|cxl).X.tc.
7828 	 */
7829 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
7830 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7831 	    "Tx scheduler traffic classes (cl_rl)");
7832 	children2 = SYSCTL_CHILDREN(oid);
7833 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
7834 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
7835 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
7836 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
7837 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
7838 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
7839 	for (i = 0; i < sc->params.nsched_cls; i++) {
7840 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
7841 
7842 		snprintf(name, sizeof(name), "%d", i);
7843 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
7844 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
7845 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
7846 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
7847 		    CTLFLAG_RD, &tc->state, 0, "current state");
7848 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
7849 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
7850 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
7851 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
7852 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
7853 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
7854 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7855 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
7856 		    "traffic class parameters");
7857 	}
7858 
7859 	/*
7860 	 * dev.cxgbe.X.stats.
7861 	 */
7862 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
7863 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
7864 	children = SYSCTL_CHILDREN(oid);
7865 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
7866 	    &pi->tx_parse_error, 0,
7867 	    "# of tx packets with invalid length or # of segments");
7868 
7869 #define T4_REGSTAT(name, stat, desc) \
7870     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
7871         CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
7872 	(is_t4(sc) ? PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L) : \
7873 	T5_PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L)), \
7874         sysctl_handle_t4_reg64, "QU", desc)
7875 
7876 /* We get these from port_stats and they may be stale by up to 1s */
7877 #define T4_PORTSTAT(name, desc) \
7878 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
7879 	    &pi->stats.name, desc)
7880 
7881 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
7882 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
7883 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
7884 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
7885 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
7886 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
7887 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
7888 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
7889 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
7890 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
7891 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
7892 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
7893 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
7894 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
7895 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
7896 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
7897 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
7898 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
7899 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
7900 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
7901 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
7902 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
7903 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
7904 
7905 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
7906 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
7907 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
7908 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
7909 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
7910 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
7911 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
7912 	if (is_t6(sc)) {
7913 		T4_PORTSTAT(rx_fcs_err,
7914 		    "# of frames received with bad FCS since last link up");
7915 	} else {
7916 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
7917 		    "# of frames received with bad FCS");
7918 	}
7919 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
7920 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
7921 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
7922 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
7923 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
7924 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
7925 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
7926 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
7927 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
7928 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
7929 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
7930 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
7931 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
7932 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
7933 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
7934 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
7935 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
7936 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
7937 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
7938 
7939 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
7940 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
7941 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
7942 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
7943 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
7944 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
7945 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
7946 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
7947 
7948 #undef T4_REGSTAT
7949 #undef T4_PORTSTAT
7950 }
7951 
7952 static int
7953 sysctl_int_array(SYSCTL_HANDLER_ARGS)
7954 {
7955 	int rc, *i, space = 0;
7956 	struct sbuf sb;
7957 
7958 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
7959 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
7960 		if (space)
7961 			sbuf_printf(&sb, " ");
7962 		sbuf_printf(&sb, "%d", *i);
7963 		space = 1;
7964 	}
7965 	rc = sbuf_finish(&sb);
7966 	sbuf_delete(&sb);
7967 	return (rc);
7968 }
7969 
7970 static int
7971 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
7972 {
7973 	int rc;
7974 	struct sbuf *sb;
7975 
7976 	rc = sysctl_wire_old_buffer(req, 0);
7977 	if (rc != 0)
7978 		return(rc);
7979 
7980 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7981 	if (sb == NULL)
7982 		return (ENOMEM);
7983 
7984 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
7985 	rc = sbuf_finish(sb);
7986 	sbuf_delete(sb);
7987 
7988 	return (rc);
7989 }
7990 
7991 static int
7992 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
7993 {
7994 	int rc;
7995 	struct sbuf *sb;
7996 
7997 	rc = sysctl_wire_old_buffer(req, 0);
7998 	if (rc != 0)
7999 		return(rc);
8000 
8001 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8002 	if (sb == NULL)
8003 		return (ENOMEM);
8004 
8005 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8006 	rc = sbuf_finish(sb);
8007 	sbuf_delete(sb);
8008 
8009 	return (rc);
8010 }
8011 
8012 static int
8013 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8014 {
8015 	struct port_info *pi = arg1;
8016 	int op = arg2;
8017 	struct adapter *sc = pi->adapter;
8018 	u_int v;
8019 	int rc;
8020 
8021 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8022 	if (rc)
8023 		return (rc);
8024 	if (hw_off_limits(sc))
8025 		rc = ENXIO;
8026 	else {
8027 		/* XXX: magic numbers */
8028 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8029 		    op ? 0x20 : 0xc820, &v);
8030 	}
8031 	end_synchronized_op(sc, 0);
8032 	if (rc)
8033 		return (rc);
8034 	if (op == 0)
8035 		v /= 256;
8036 
8037 	rc = sysctl_handle_int(oidp, &v, 0, req);
8038 	return (rc);
8039 }
8040 
8041 static int
8042 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8043 {
8044 	struct vi_info *vi = arg1;
8045 	int rc, val;
8046 
8047 	val = vi->rsrv_noflowq;
8048 	rc = sysctl_handle_int(oidp, &val, 0, req);
8049 	if (rc != 0 || req->newptr == NULL)
8050 		return (rc);
8051 
8052 	if ((val >= 1) && (vi->ntxq > 1))
8053 		vi->rsrv_noflowq = 1;
8054 	else
8055 		vi->rsrv_noflowq = 0;
8056 
8057 	return (rc);
8058 }
8059 
8060 static int
8061 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8062 {
8063 	struct vi_info *vi = arg1;
8064 	struct adapter *sc = vi->adapter;
8065 	int rc, val, i;
8066 
8067 	MPASS(!(sc->flags & IS_VF));
8068 
8069 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8070 	rc = sysctl_handle_int(oidp, &val, 0, req);
8071 	if (rc != 0 || req->newptr == NULL)
8072 		return (rc);
8073 
8074 	if (val != 0 && val != 1)
8075 		return (EINVAL);
8076 
8077 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8078 	    "t4txvm");
8079 	if (rc)
8080 		return (rc);
8081 	if (hw_off_limits(sc))
8082 		rc = ENXIO;
8083 	else if (vi->ifp->if_drv_flags & IFF_DRV_RUNNING) {
8084 		/*
8085 		 * We don't want parse_pkt to run with one setting (VF or PF)
8086 		 * and then eth_tx to see a different setting but still use
8087 		 * stale information calculated by parse_pkt.
8088 		 */
8089 		rc = EBUSY;
8090 	} else {
8091 		struct port_info *pi = vi->pi;
8092 		struct sge_txq *txq;
8093 		uint32_t ctrl0;
8094 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8095 
8096 		if (val) {
8097 			vi->flags |= TX_USES_VM_WR;
8098 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
8099 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8100 			    V_TXPKT_INTF(pi->tx_chan));
8101 			if (!(sc->flags & IS_VF))
8102 				npkt--;
8103 		} else {
8104 			vi->flags &= ~TX_USES_VM_WR;
8105 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
8106 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8107 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8108 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8109 		}
8110 		for_each_txq(vi, i, txq) {
8111 			txq->cpl_ctrl0 = ctrl0;
8112 			txq->txp.max_npkt = npkt;
8113 		}
8114 	}
8115 	end_synchronized_op(sc, LOCK_HELD);
8116 	return (rc);
8117 }
8118 
8119 static int
8120 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8121 {
8122 	struct vi_info *vi = arg1;
8123 	struct adapter *sc = vi->adapter;
8124 	int idx, rc, i;
8125 	struct sge_rxq *rxq;
8126 	uint8_t v;
8127 
8128 	idx = vi->tmr_idx;
8129 
8130 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8131 	if (rc != 0 || req->newptr == NULL)
8132 		return (rc);
8133 
8134 	if (idx < 0 || idx >= SGE_NTIMERS)
8135 		return (EINVAL);
8136 
8137 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8138 	    "t4tmr");
8139 	if (rc)
8140 		return (rc);
8141 
8142 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8143 	for_each_rxq(vi, i, rxq) {
8144 #ifdef atomic_store_rel_8
8145 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8146 #else
8147 		rxq->iq.intr_params = v;
8148 #endif
8149 	}
8150 	vi->tmr_idx = idx;
8151 
8152 	end_synchronized_op(sc, LOCK_HELD);
8153 	return (0);
8154 }
8155 
8156 static int
8157 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8158 {
8159 	struct vi_info *vi = arg1;
8160 	struct adapter *sc = vi->adapter;
8161 	int idx, rc;
8162 
8163 	idx = vi->pktc_idx;
8164 
8165 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8166 	if (rc != 0 || req->newptr == NULL)
8167 		return (rc);
8168 
8169 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8170 		return (EINVAL);
8171 
8172 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8173 	    "t4pktc");
8174 	if (rc)
8175 		return (rc);
8176 
8177 	if (vi->flags & VI_INIT_DONE)
8178 		rc = EBUSY; /* cannot be changed once the queues are created */
8179 	else
8180 		vi->pktc_idx = idx;
8181 
8182 	end_synchronized_op(sc, LOCK_HELD);
8183 	return (rc);
8184 }
8185 
8186 static int
8187 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8188 {
8189 	struct vi_info *vi = arg1;
8190 	struct adapter *sc = vi->adapter;
8191 	int qsize, rc;
8192 
8193 	qsize = vi->qsize_rxq;
8194 
8195 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8196 	if (rc != 0 || req->newptr == NULL)
8197 		return (rc);
8198 
8199 	if (qsize < 128 || (qsize & 7))
8200 		return (EINVAL);
8201 
8202 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8203 	    "t4rxqs");
8204 	if (rc)
8205 		return (rc);
8206 
8207 	if (vi->flags & VI_INIT_DONE)
8208 		rc = EBUSY; /* cannot be changed once the queues are created */
8209 	else
8210 		vi->qsize_rxq = qsize;
8211 
8212 	end_synchronized_op(sc, LOCK_HELD);
8213 	return (rc);
8214 }
8215 
8216 static int
8217 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8218 {
8219 	struct vi_info *vi = arg1;
8220 	struct adapter *sc = vi->adapter;
8221 	int qsize, rc;
8222 
8223 	qsize = vi->qsize_txq;
8224 
8225 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8226 	if (rc != 0 || req->newptr == NULL)
8227 		return (rc);
8228 
8229 	if (qsize < 128 || qsize > 65536)
8230 		return (EINVAL);
8231 
8232 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8233 	    "t4txqs");
8234 	if (rc)
8235 		return (rc);
8236 
8237 	if (vi->flags & VI_INIT_DONE)
8238 		rc = EBUSY; /* cannot be changed once the queues are created */
8239 	else
8240 		vi->qsize_txq = qsize;
8241 
8242 	end_synchronized_op(sc, LOCK_HELD);
8243 	return (rc);
8244 }
8245 
8246 static int
8247 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8248 {
8249 	struct port_info *pi = arg1;
8250 	struct adapter *sc = pi->adapter;
8251 	struct link_config *lc = &pi->link_cfg;
8252 	int rc;
8253 
8254 	if (req->newptr == NULL) {
8255 		struct sbuf *sb;
8256 		static char *bits = "\20\1RX\2TX\3AUTO";
8257 
8258 		rc = sysctl_wire_old_buffer(req, 0);
8259 		if (rc != 0)
8260 			return(rc);
8261 
8262 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8263 		if (sb == NULL)
8264 			return (ENOMEM);
8265 
8266 		if (lc->link_ok) {
8267 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8268 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8269 		} else {
8270 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8271 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8272 		}
8273 		rc = sbuf_finish(sb);
8274 		sbuf_delete(sb);
8275 	} else {
8276 		char s[2];
8277 		int n;
8278 
8279 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8280 		    PAUSE_AUTONEG));
8281 		s[1] = 0;
8282 
8283 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8284 		if (rc != 0)
8285 			return(rc);
8286 
8287 		if (s[1] != 0)
8288 			return (EINVAL);
8289 		if (s[0] < '0' || s[0] > '9')
8290 			return (EINVAL);	/* not a number */
8291 		n = s[0] - '0';
8292 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8293 			return (EINVAL);	/* some other bit is set too */
8294 
8295 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8296 		    "t4PAUSE");
8297 		if (rc)
8298 			return (rc);
8299 		if (!hw_off_limits(sc)) {
8300 			PORT_LOCK(pi);
8301 			lc->requested_fc = n;
8302 			fixup_link_config(pi);
8303 			if (pi->up_vis > 0)
8304 				rc = apply_link_config(pi);
8305 			set_current_media(pi);
8306 			PORT_UNLOCK(pi);
8307 		}
8308 		end_synchronized_op(sc, 0);
8309 	}
8310 
8311 	return (rc);
8312 }
8313 
8314 static int
8315 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
8316 {
8317 	struct port_info *pi = arg1;
8318 	struct link_config *lc = &pi->link_cfg;
8319 	int rc;
8320 	struct sbuf *sb;
8321 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2";
8322 
8323 	rc = sysctl_wire_old_buffer(req, 0);
8324 	if (rc != 0)
8325 		return(rc);
8326 
8327 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8328 	if (sb == NULL)
8329 		return (ENOMEM);
8330 	if (lc->link_ok)
8331 		sbuf_printf(sb, "%b", lc->fec, bits);
8332 	else
8333 		sbuf_printf(sb, "no link");
8334 	rc = sbuf_finish(sb);
8335 	sbuf_delete(sb);
8336 
8337 	return (rc);
8338 }
8339 
8340 static int
8341 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
8342 {
8343 	struct port_info *pi = arg1;
8344 	struct adapter *sc = pi->adapter;
8345 	struct link_config *lc = &pi->link_cfg;
8346 	int rc;
8347 	int8_t old;
8348 
8349 	if (req->newptr == NULL) {
8350 		struct sbuf *sb;
8351 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8352 		    "\5RSVD3\6auto\7module";
8353 
8354 		rc = sysctl_wire_old_buffer(req, 0);
8355 		if (rc != 0)
8356 			return(rc);
8357 
8358 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8359 		if (sb == NULL)
8360 			return (ENOMEM);
8361 
8362 		sbuf_printf(sb, "%b", lc->requested_fec, bits);
8363 		rc = sbuf_finish(sb);
8364 		sbuf_delete(sb);
8365 	} else {
8366 		char s[8];
8367 		int n;
8368 
8369 		snprintf(s, sizeof(s), "%d",
8370 		    lc->requested_fec == FEC_AUTO ? -1 :
8371 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8372 
8373 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8374 		if (rc != 0)
8375 			return(rc);
8376 
8377 		n = strtol(&s[0], NULL, 0);
8378 		if (n < 0 || n & FEC_AUTO)
8379 			n = FEC_AUTO;
8380 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8381 			return (EINVAL);/* some other bit is set too */
8382 
8383 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8384 		    "t4reqf");
8385 		if (rc)
8386 			return (rc);
8387 		PORT_LOCK(pi);
8388 		old = lc->requested_fec;
8389 		if (n == FEC_AUTO)
8390 			lc->requested_fec = FEC_AUTO;
8391 		else if (n == 0 || n == FEC_NONE)
8392 			lc->requested_fec = FEC_NONE;
8393 		else {
8394 			if ((lc->pcaps |
8395 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8396 			    lc->pcaps) {
8397 				rc = ENOTSUP;
8398 				goto done;
8399 			}
8400 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8401 			    FEC_MODULE);
8402 		}
8403 		if (!hw_off_limits(sc)) {
8404 			fixup_link_config(pi);
8405 			if (pi->up_vis > 0) {
8406 				rc = apply_link_config(pi);
8407 				if (rc != 0) {
8408 					lc->requested_fec = old;
8409 					if (rc == FW_EPROTO)
8410 						rc = ENOTSUP;
8411 				}
8412 			}
8413 		}
8414 done:
8415 		PORT_UNLOCK(pi);
8416 		end_synchronized_op(sc, 0);
8417 	}
8418 
8419 	return (rc);
8420 }
8421 
8422 static int
8423 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8424 {
8425 	struct port_info *pi = arg1;
8426 	struct adapter *sc = pi->adapter;
8427 	struct link_config *lc = &pi->link_cfg;
8428 	int rc;
8429 	int8_t fec;
8430 	struct sbuf *sb;
8431 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8432 
8433 	rc = sysctl_wire_old_buffer(req, 0);
8434 	if (rc != 0)
8435 		return (rc);
8436 
8437 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8438 	if (sb == NULL)
8439 		return (ENOMEM);
8440 
8441 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8442 		rc = EBUSY;
8443 		goto done;
8444 	}
8445 	if (hw_off_limits(sc)) {
8446 		rc = ENXIO;
8447 		goto done;
8448 	}
8449 	PORT_LOCK(pi);
8450 	if (pi->up_vis == 0) {
8451 		/*
8452 		 * If all the interfaces are administratively down the firmware
8453 		 * does not report transceiver changes.  Refresh port info here.
8454 		 * This is the only reason we have a synchronized op in this
8455 		 * function.  Just PORT_LOCK would have been enough otherwise.
8456 		 */
8457 		t4_update_port_info(pi);
8458 	}
8459 
8460 	fec = lc->fec_hint;
8461 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8462 	    !fec_supported(lc->pcaps)) {
8463 		sbuf_printf(sb, "n/a");
8464 	} else {
8465 		if (fec == 0)
8466 			fec = FEC_NONE;
8467 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8468 	}
8469 	rc = sbuf_finish(sb);
8470 	PORT_UNLOCK(pi);
8471 done:
8472 	sbuf_delete(sb);
8473 	end_synchronized_op(sc, 0);
8474 
8475 	return (rc);
8476 }
8477 
8478 static int
8479 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8480 {
8481 	struct port_info *pi = arg1;
8482 	struct adapter *sc = pi->adapter;
8483 	struct link_config *lc = &pi->link_cfg;
8484 	int rc, val;
8485 
8486 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8487 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8488 	else
8489 		val = -1;
8490 	rc = sysctl_handle_int(oidp, &val, 0, req);
8491 	if (rc != 0 || req->newptr == NULL)
8492 		return (rc);
8493 	if (val == 0)
8494 		val = AUTONEG_DISABLE;
8495 	else if (val == 1)
8496 		val = AUTONEG_ENABLE;
8497 	else
8498 		val = AUTONEG_AUTO;
8499 
8500 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8501 	    "t4aneg");
8502 	if (rc)
8503 		return (rc);
8504 	PORT_LOCK(pi);
8505 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8506 		rc = ENOTSUP;
8507 		goto done;
8508 	}
8509 	lc->requested_aneg = val;
8510 	if (!hw_off_limits(sc)) {
8511 		fixup_link_config(pi);
8512 		if (pi->up_vis > 0)
8513 			rc = apply_link_config(pi);
8514 		set_current_media(pi);
8515 	}
8516 done:
8517 	PORT_UNLOCK(pi);
8518 	end_synchronized_op(sc, 0);
8519 	return (rc);
8520 }
8521 
8522 static int
8523 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
8524 {
8525 	struct port_info *pi = arg1;
8526 	struct adapter *sc = pi->adapter;
8527 	struct link_config *lc = &pi->link_cfg;
8528 	int rc, val;
8529 
8530 	val = lc->force_fec;
8531 	MPASS(val >= -1 && val <= 1);
8532 	rc = sysctl_handle_int(oidp, &val, 0, req);
8533 	if (rc != 0 || req->newptr == NULL)
8534 		return (rc);
8535 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
8536 		return (ENOTSUP);
8537 	if (val < -1 || val > 1)
8538 		return (EINVAL);
8539 
8540 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
8541 	if (rc)
8542 		return (rc);
8543 	PORT_LOCK(pi);
8544 	lc->force_fec = val;
8545 	if (!hw_off_limits(sc)) {
8546 		fixup_link_config(pi);
8547 		if (pi->up_vis > 0)
8548 			rc = apply_link_config(pi);
8549 	}
8550 	PORT_UNLOCK(pi);
8551 	end_synchronized_op(sc, 0);
8552 	return (rc);
8553 }
8554 
8555 static int
8556 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8557 {
8558 	struct adapter *sc = arg1;
8559 	int rc, reg = arg2;
8560 	uint64_t val;
8561 
8562 	mtx_lock(&sc->reg_lock);
8563 	if (hw_off_limits(sc))
8564 		rc = ENXIO;
8565 	else {
8566 		rc = 0;
8567 		val = t4_read_reg64(sc, reg);
8568 	}
8569 	mtx_unlock(&sc->reg_lock);
8570 	if (rc == 0)
8571 		rc = sysctl_handle_64(oidp, &val, 0, req);
8572 	return (rc);
8573 }
8574 
8575 static int
8576 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8577 {
8578 	struct adapter *sc = arg1;
8579 	int rc, t;
8580 	uint32_t param, val;
8581 
8582 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8583 	if (rc)
8584 		return (rc);
8585 	if (hw_off_limits(sc))
8586 		rc = ENXIO;
8587 	else {
8588 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8589 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8590 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8591 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8592 	}
8593 	end_synchronized_op(sc, 0);
8594 	if (rc)
8595 		return (rc);
8596 
8597 	/* unknown is returned as 0 but we display -1 in that case */
8598 	t = val == 0 ? -1 : val;
8599 
8600 	rc = sysctl_handle_int(oidp, &t, 0, req);
8601 	return (rc);
8602 }
8603 
8604 static int
8605 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8606 {
8607 	struct adapter *sc = arg1;
8608 	int rc;
8609 	uint32_t param, val;
8610 
8611 	if (sc->params.core_vdd == 0) {
8612 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8613 		    "t4vdd");
8614 		if (rc)
8615 			return (rc);
8616 		if (hw_off_limits(sc))
8617 			rc = ENXIO;
8618 		else {
8619 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8620 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8621 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8622 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8623 			    &param, &val);
8624 		}
8625 		end_synchronized_op(sc, 0);
8626 		if (rc)
8627 			return (rc);
8628 		sc->params.core_vdd = val;
8629 	}
8630 
8631 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8632 }
8633 
8634 static int
8635 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8636 {
8637 	struct adapter *sc = arg1;
8638 	int rc, v;
8639 	uint32_t param, val;
8640 
8641 	v = sc->sensor_resets;
8642 	rc = sysctl_handle_int(oidp, &v, 0, req);
8643 	if (rc != 0 || req->newptr == NULL || v <= 0)
8644 		return (rc);
8645 
8646 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8647 	    chip_id(sc) < CHELSIO_T5)
8648 		return (ENOTSUP);
8649 
8650 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8651 	if (rc)
8652 		return (rc);
8653 	if (hw_off_limits(sc))
8654 		rc = ENXIO;
8655 	else {
8656 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8657 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8658 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8659 		val = 1;
8660 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8661 	}
8662 	end_synchronized_op(sc, 0);
8663 	if (rc == 0)
8664 		sc->sensor_resets++;
8665 	return (rc);
8666 }
8667 
8668 static int
8669 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8670 {
8671 	struct adapter *sc = arg1;
8672 	struct sbuf *sb;
8673 	int rc;
8674 	uint32_t param, val;
8675 
8676 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8677 	if (rc)
8678 		return (rc);
8679 	if (hw_off_limits(sc))
8680 		rc = ENXIO;
8681 	else {
8682 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8683 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8684 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8685 	}
8686 	end_synchronized_op(sc, 0);
8687 	if (rc)
8688 		return (rc);
8689 
8690 	rc = sysctl_wire_old_buffer(req, 0);
8691 	if (rc != 0)
8692 		return (rc);
8693 
8694 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8695 	if (sb == NULL)
8696 		return (ENOMEM);
8697 
8698 	if (val == 0xffffffff) {
8699 		/* Only debug and custom firmwares report load averages. */
8700 		sbuf_printf(sb, "not available");
8701 	} else {
8702 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8703 		    (val >> 16) & 0xff);
8704 	}
8705 	rc = sbuf_finish(sb);
8706 	sbuf_delete(sb);
8707 
8708 	return (rc);
8709 }
8710 
8711 static int
8712 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8713 {
8714 	struct adapter *sc = arg1;
8715 	struct sbuf *sb;
8716 	int rc, i;
8717 	uint16_t incr[NMTUS][NCCTRL_WIN];
8718 	static const char *dec_fac[] = {
8719 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8720 		"0.9375"
8721 	};
8722 
8723 	rc = sysctl_wire_old_buffer(req, 0);
8724 	if (rc != 0)
8725 		return (rc);
8726 
8727 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8728 	if (sb == NULL)
8729 		return (ENOMEM);
8730 
8731 	mtx_lock(&sc->reg_lock);
8732 	if (hw_off_limits(sc))
8733 		rc = ENXIO;
8734 	else
8735 		t4_read_cong_tbl(sc, incr);
8736 	mtx_unlock(&sc->reg_lock);
8737 	if (rc)
8738 		goto done;
8739 
8740 	for (i = 0; i < NCCTRL_WIN; ++i) {
8741 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8742 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8743 		    incr[5][i], incr[6][i], incr[7][i]);
8744 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8745 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8746 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8747 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8748 	}
8749 
8750 	rc = sbuf_finish(sb);
8751 done:
8752 	sbuf_delete(sb);
8753 	return (rc);
8754 }
8755 
8756 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8757 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8758 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8759 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8760 };
8761 
8762 static int
8763 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8764 {
8765 	struct adapter *sc = arg1;
8766 	struct sbuf *sb;
8767 	int rc, i, n, qid = arg2;
8768 	uint32_t *buf, *p;
8769 	char *qtype;
8770 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8771 
8772 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8773 	    ("%s: bad qid %d\n", __func__, qid));
8774 
8775 	if (qid < CIM_NUM_IBQ) {
8776 		/* inbound queue */
8777 		qtype = "IBQ";
8778 		n = 4 * CIM_IBQ_SIZE;
8779 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8780 		mtx_lock(&sc->reg_lock);
8781 		if (hw_off_limits(sc))
8782 			rc = -ENXIO;
8783 		else
8784 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8785 		mtx_unlock(&sc->reg_lock);
8786 	} else {
8787 		/* outbound queue */
8788 		qtype = "OBQ";
8789 		qid -= CIM_NUM_IBQ;
8790 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8791 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8792 		mtx_lock(&sc->reg_lock);
8793 		if (hw_off_limits(sc))
8794 			rc = -ENXIO;
8795 		else
8796 			rc = t4_read_cim_obq(sc, qid, buf, n);
8797 		mtx_unlock(&sc->reg_lock);
8798 	}
8799 
8800 	if (rc < 0) {
8801 		rc = -rc;
8802 		goto done;
8803 	}
8804 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
8805 
8806 	rc = sysctl_wire_old_buffer(req, 0);
8807 	if (rc != 0)
8808 		goto done;
8809 
8810 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8811 	if (sb == NULL) {
8812 		rc = ENOMEM;
8813 		goto done;
8814 	}
8815 
8816 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8817 	for (i = 0, p = buf; i < n; i += 16, p += 4)
8818 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
8819 		    p[2], p[3]);
8820 
8821 	rc = sbuf_finish(sb);
8822 	sbuf_delete(sb);
8823 done:
8824 	free(buf, M_CXGBE);
8825 	return (rc);
8826 }
8827 
8828 static void
8829 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8830 {
8831 	uint32_t *p;
8832 
8833 	sbuf_printf(sb, "Status   Data      PC%s",
8834 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8835 	    "     LS0Stat  LS0Addr             LS0Data");
8836 
8837 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
8838 		if (cfg & F_UPDBGLACAPTPCONLY) {
8839 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
8840 			    p[6], p[7]);
8841 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
8842 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
8843 			    p[4] & 0xff, p[5] >> 8);
8844 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
8845 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8846 			    p[1] & 0xf, p[2] >> 4);
8847 		} else {
8848 			sbuf_printf(sb,
8849 			    "\n  %02x   %x%07x %x%07x %08x %08x "
8850 			    "%08x%08x%08x%08x",
8851 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8852 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
8853 			    p[6], p[7]);
8854 		}
8855 	}
8856 }
8857 
8858 static void
8859 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8860 {
8861 	uint32_t *p;
8862 
8863 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
8864 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8865 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
8866 
8867 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
8868 		if (cfg & F_UPDBGLACAPTPCONLY) {
8869 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
8870 			    p[3] & 0xff, p[2], p[1], p[0]);
8871 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
8872 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
8873 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
8874 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
8875 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
8876 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
8877 			    p[6] >> 16);
8878 		} else {
8879 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
8880 			    "%08x %08x %08x %08x %08x %08x",
8881 			    (p[9] >> 16) & 0xff,
8882 			    p[9] & 0xffff, p[8] >> 16,
8883 			    p[8] & 0xffff, p[7] >> 16,
8884 			    p[7] & 0xffff, p[6] >> 16,
8885 			    p[2], p[1], p[0], p[5], p[4], p[3]);
8886 		}
8887 	}
8888 }
8889 
8890 static int
8891 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
8892 {
8893 	uint32_t cfg, *buf;
8894 	int rc;
8895 
8896 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
8897 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
8898 	    M_ZERO | flags);
8899 	if (buf == NULL)
8900 		return (ENOMEM);
8901 
8902 	mtx_lock(&sc->reg_lock);
8903 	if (hw_off_limits(sc))
8904 		rc = ENXIO;
8905 	else {
8906 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
8907 		if (rc == 0)
8908 			rc = -t4_cim_read_la(sc, buf, NULL);
8909 	}
8910 	mtx_unlock(&sc->reg_lock);
8911 	if (rc == 0) {
8912 		if (chip_id(sc) < CHELSIO_T6)
8913 			sbuf_cim_la4(sc, sb, buf, cfg);
8914 		else
8915 			sbuf_cim_la6(sc, sb, buf, cfg);
8916 	}
8917 	free(buf, M_CXGBE);
8918 	return (rc);
8919 }
8920 
8921 static int
8922 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
8923 {
8924 	struct adapter *sc = arg1;
8925 	struct sbuf *sb;
8926 	int rc;
8927 
8928 	rc = sysctl_wire_old_buffer(req, 0);
8929 	if (rc != 0)
8930 		return (rc);
8931 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8932 	if (sb == NULL)
8933 		return (ENOMEM);
8934 
8935 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
8936 	if (rc == 0)
8937 		rc = sbuf_finish(sb);
8938 	sbuf_delete(sb);
8939 	return (rc);
8940 }
8941 
8942 bool
8943 t4_os_dump_cimla(struct adapter *sc, int arg, bool verbose)
8944 {
8945 	struct sbuf sb;
8946 	int rc;
8947 
8948 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
8949 		return (false);
8950 	rc = sbuf_cim_la(sc, &sb, M_NOWAIT);
8951 	if (rc == 0) {
8952 		rc = sbuf_finish(&sb);
8953 		if (rc == 0) {
8954 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s",
8955 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
8956 		}
8957 	}
8958 	sbuf_delete(&sb);
8959 	return (false);
8960 }
8961 
8962 static int
8963 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
8964 {
8965 	struct adapter *sc = arg1;
8966 	u_int i;
8967 	struct sbuf *sb;
8968 	uint32_t *buf, *p;
8969 	int rc;
8970 
8971 	rc = sysctl_wire_old_buffer(req, 0);
8972 	if (rc != 0)
8973 		return (rc);
8974 
8975 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8976 	if (sb == NULL)
8977 		return (ENOMEM);
8978 
8979 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
8980 	    M_ZERO | M_WAITOK);
8981 
8982 	mtx_lock(&sc->reg_lock);
8983 	if (hw_off_limits(sc))
8984 		rc = ENXIO;
8985 	else
8986 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
8987 	mtx_unlock(&sc->reg_lock);
8988 	if (rc)
8989 		goto done;
8990 
8991 	p = buf;
8992 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
8993 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
8994 		    p[1], p[0]);
8995 	}
8996 
8997 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
8998 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
8999 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9000 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9001 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9002 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9003 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9004 		    p[0] & 1);
9005 	}
9006 	rc = sbuf_finish(sb);
9007 done:
9008 	sbuf_delete(sb);
9009 	free(buf, M_CXGBE);
9010 	return (rc);
9011 }
9012 
9013 static int
9014 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9015 {
9016 	struct adapter *sc = arg1;
9017 	u_int i;
9018 	struct sbuf *sb;
9019 	uint32_t *buf, *p;
9020 	int rc;
9021 
9022 	rc = sysctl_wire_old_buffer(req, 0);
9023 	if (rc != 0)
9024 		return (rc);
9025 
9026 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9027 	if (sb == NULL)
9028 		return (ENOMEM);
9029 
9030 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9031 	    M_ZERO | M_WAITOK);
9032 
9033 	mtx_lock(&sc->reg_lock);
9034 	if (hw_off_limits(sc))
9035 		rc = ENXIO;
9036 	else
9037 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9038 	mtx_unlock(&sc->reg_lock);
9039 	if (rc)
9040 		goto done;
9041 
9042 	p = buf;
9043 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9044 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9045 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9046 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9047 		    p[4], p[3], p[2], p[1], p[0]);
9048 	}
9049 
9050 	sbuf_printf(sb, "\n\nCntl ID               Data");
9051 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9052 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9053 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9054 	}
9055 
9056 	rc = sbuf_finish(sb);
9057 done:
9058 	sbuf_delete(sb);
9059 	free(buf, M_CXGBE);
9060 	return (rc);
9061 }
9062 
9063 static int
9064 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9065 {
9066 	struct adapter *sc = arg1;
9067 	struct sbuf *sb;
9068 	int rc, i;
9069 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9070 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9071 	uint16_t thres[CIM_NUM_IBQ];
9072 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9073 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9074 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9075 
9076 	cim_num_obq = sc->chip_params->cim_num_obq;
9077 	if (is_t4(sc)) {
9078 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9079 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9080 	} else {
9081 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9082 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9083 	}
9084 	nq = CIM_NUM_IBQ + cim_num_obq;
9085 
9086 	mtx_lock(&sc->reg_lock);
9087 	if (hw_off_limits(sc))
9088 		rc = ENXIO;
9089 	else {
9090 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9091 		if (rc == 0) {
9092 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9093 			    obq_wr);
9094 			if (rc == 0)
9095 				t4_read_cimq_cfg(sc, base, size, thres);
9096 		}
9097 	}
9098 	mtx_unlock(&sc->reg_lock);
9099 	if (rc)
9100 		return (rc);
9101 
9102 	rc = sysctl_wire_old_buffer(req, 0);
9103 	if (rc != 0)
9104 		return (rc);
9105 
9106 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9107 	if (sb == NULL)
9108 		return (ENOMEM);
9109 
9110 	sbuf_printf(sb,
9111 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9112 
9113 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9114 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9115 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9116 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9117 		    G_QUEREMFLITS(p[2]) * 16);
9118 	for ( ; i < nq; i++, p += 4, wr += 2)
9119 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9120 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9121 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9122 		    G_QUEREMFLITS(p[2]) * 16);
9123 
9124 	rc = sbuf_finish(sb);
9125 	sbuf_delete(sb);
9126 
9127 	return (rc);
9128 }
9129 
9130 static int
9131 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9132 {
9133 	struct adapter *sc = arg1;
9134 	struct sbuf *sb;
9135 	int rc;
9136 	struct tp_cpl_stats stats;
9137 
9138 	rc = sysctl_wire_old_buffer(req, 0);
9139 	if (rc != 0)
9140 		return (rc);
9141 
9142 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9143 	if (sb == NULL)
9144 		return (ENOMEM);
9145 
9146 	mtx_lock(&sc->reg_lock);
9147 	if (hw_off_limits(sc))
9148 		rc = ENXIO;
9149 	else
9150 		t4_tp_get_cpl_stats(sc, &stats, 0);
9151 	mtx_unlock(&sc->reg_lock);
9152 	if (rc)
9153 		goto done;
9154 
9155 	if (sc->chip_params->nchan > 2) {
9156 		sbuf_printf(sb, "                 channel 0  channel 1"
9157 		    "  channel 2  channel 3");
9158 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9159 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9160 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9161 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9162 	} else {
9163 		sbuf_printf(sb, "                 channel 0  channel 1");
9164 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9165 		    stats.req[0], stats.req[1]);
9166 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9167 		    stats.rsp[0], stats.rsp[1]);
9168 	}
9169 
9170 	rc = sbuf_finish(sb);
9171 done:
9172 	sbuf_delete(sb);
9173 	return (rc);
9174 }
9175 
9176 static int
9177 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9178 {
9179 	struct adapter *sc = arg1;
9180 	struct sbuf *sb;
9181 	int rc;
9182 	struct tp_usm_stats stats;
9183 
9184 	rc = sysctl_wire_old_buffer(req, 0);
9185 	if (rc != 0)
9186 		return(rc);
9187 
9188 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9189 	if (sb == NULL)
9190 		return (ENOMEM);
9191 
9192 	mtx_lock(&sc->reg_lock);
9193 	if (hw_off_limits(sc))
9194 		rc = ENXIO;
9195 	else
9196 		t4_get_usm_stats(sc, &stats, 1);
9197 	mtx_unlock(&sc->reg_lock);
9198 	if (rc == 0) {
9199 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9200 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9201 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9202 		rc = sbuf_finish(sb);
9203 	}
9204 	sbuf_delete(sb);
9205 
9206 	return (rc);
9207 }
9208 
9209 static int
9210 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9211 {
9212 	struct adapter *sc = arg1;
9213 	struct sbuf *sb;
9214 	int rc;
9215 	struct tp_tid_stats stats;
9216 
9217 	rc = sysctl_wire_old_buffer(req, 0);
9218 	if (rc != 0)
9219 		return(rc);
9220 
9221 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9222 	if (sb == NULL)
9223 		return (ENOMEM);
9224 
9225 	mtx_lock(&sc->reg_lock);
9226 	if (hw_off_limits(sc))
9227 		rc = ENXIO;
9228 	else
9229 		t4_tp_get_tid_stats(sc, &stats, 1);
9230 	mtx_unlock(&sc->reg_lock);
9231 	if (rc == 0) {
9232 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9233 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9234 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9235 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9236 		rc = sbuf_finish(sb);
9237 	}
9238 	sbuf_delete(sb);
9239 
9240 	return (rc);
9241 }
9242 
9243 static const char * const devlog_level_strings[] = {
9244 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9245 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9246 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9247 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9248 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9249 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9250 };
9251 
9252 static const char * const devlog_facility_strings[] = {
9253 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9254 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9255 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9256 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9257 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9258 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9259 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9260 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9261 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9262 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9263 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9264 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9265 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9266 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9267 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9268 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9269 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9270 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9271 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9272 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9273 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9274 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9275 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9276 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9277 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9278 };
9279 
9280 static int
9281 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9282 {
9283 	int i, j, rc, nentries, first = 0;
9284 	struct devlog_params *dparams = &sc->params.devlog;
9285 	struct fw_devlog_e *buf, *e;
9286 	uint64_t ftstamp = UINT64_MAX;
9287 
9288 	if (dparams->addr == 0)
9289 		return (ENXIO);
9290 
9291 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9292 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9293 	if (buf == NULL)
9294 		return (ENOMEM);
9295 
9296 	mtx_lock(&sc->reg_lock);
9297 	if (hw_off_limits(sc))
9298 		rc = ENXIO;
9299 	else
9300 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9301 		    dparams->size);
9302 	mtx_unlock(&sc->reg_lock);
9303 	if (rc != 0)
9304 		goto done;
9305 
9306 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9307 	for (i = 0; i < nentries; i++) {
9308 		e = &buf[i];
9309 
9310 		if (e->timestamp == 0)
9311 			break;	/* end */
9312 
9313 		e->timestamp = be64toh(e->timestamp);
9314 		e->seqno = be32toh(e->seqno);
9315 		for (j = 0; j < 8; j++)
9316 			e->params[j] = be32toh(e->params[j]);
9317 
9318 		if (e->timestamp < ftstamp) {
9319 			ftstamp = e->timestamp;
9320 			first = i;
9321 		}
9322 	}
9323 
9324 	if (buf[first].timestamp == 0)
9325 		goto done;	/* nothing in the log */
9326 
9327 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9328 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9329 
9330 	i = first;
9331 	do {
9332 		e = &buf[i];
9333 		if (e->timestamp == 0)
9334 			break;	/* end */
9335 
9336 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9337 		    e->seqno, e->timestamp,
9338 		    (e->level < nitems(devlog_level_strings) ?
9339 			devlog_level_strings[e->level] : "UNKNOWN"),
9340 		    (e->facility < nitems(devlog_facility_strings) ?
9341 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9342 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9343 		    e->params[2], e->params[3], e->params[4],
9344 		    e->params[5], e->params[6], e->params[7]);
9345 
9346 		if (++i == nentries)
9347 			i = 0;
9348 	} while (i != first);
9349 done:
9350 	free(buf, M_CXGBE);
9351 	return (rc);
9352 }
9353 
9354 static int
9355 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9356 {
9357 	struct adapter *sc = arg1;
9358 	int rc;
9359 	struct sbuf *sb;
9360 
9361 	rc = sysctl_wire_old_buffer(req, 0);
9362 	if (rc != 0)
9363 		return (rc);
9364 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9365 	if (sb == NULL)
9366 		return (ENOMEM);
9367 
9368 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9369 	if (rc == 0)
9370 		rc = sbuf_finish(sb);
9371 	sbuf_delete(sb);
9372 	return (rc);
9373 }
9374 
9375 void
9376 t4_os_dump_devlog(struct adapter *sc)
9377 {
9378 	int rc;
9379 	struct sbuf sb;
9380 
9381 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
9382 		return;
9383 	rc = sbuf_devlog(sc, &sb, M_NOWAIT);
9384 	if (rc == 0) {
9385 		rc = sbuf_finish(&sb);
9386 		if (rc == 0) {
9387 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9388 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
9389 		}
9390 	}
9391 	sbuf_delete(&sb);
9392 }
9393 
9394 static int
9395 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9396 {
9397 	struct adapter *sc = arg1;
9398 	struct sbuf *sb;
9399 	int rc;
9400 	struct tp_fcoe_stats stats[MAX_NCHAN];
9401 	int i, nchan = sc->chip_params->nchan;
9402 
9403 	rc = sysctl_wire_old_buffer(req, 0);
9404 	if (rc != 0)
9405 		return (rc);
9406 
9407 	mtx_lock(&sc->reg_lock);
9408 	if (hw_off_limits(sc))
9409 		rc = ENXIO;
9410 	else {
9411 		for (i = 0; i < nchan; i++)
9412 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9413 	}
9414 	mtx_unlock(&sc->reg_lock);
9415 	if (rc != 0)
9416 		return (rc);
9417 
9418 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9419 	if (sb == NULL)
9420 		return (ENOMEM);
9421 
9422 	if (nchan > 2) {
9423 		sbuf_printf(sb, "                   channel 0        channel 1"
9424 		    "        channel 2        channel 3");
9425 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9426 		    stats[0].octets_ddp, stats[1].octets_ddp,
9427 		    stats[2].octets_ddp, stats[3].octets_ddp);
9428 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9429 		    stats[0].frames_ddp, stats[1].frames_ddp,
9430 		    stats[2].frames_ddp, stats[3].frames_ddp);
9431 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9432 		    stats[0].frames_drop, stats[1].frames_drop,
9433 		    stats[2].frames_drop, stats[3].frames_drop);
9434 	} else {
9435 		sbuf_printf(sb, "                   channel 0        channel 1");
9436 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9437 		    stats[0].octets_ddp, stats[1].octets_ddp);
9438 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9439 		    stats[0].frames_ddp, stats[1].frames_ddp);
9440 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9441 		    stats[0].frames_drop, stats[1].frames_drop);
9442 	}
9443 
9444 	rc = sbuf_finish(sb);
9445 	sbuf_delete(sb);
9446 
9447 	return (rc);
9448 }
9449 
9450 static int
9451 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9452 {
9453 	struct adapter *sc = arg1;
9454 	struct sbuf *sb;
9455 	int rc, i;
9456 	unsigned int map, kbps, ipg, mode;
9457 	unsigned int pace_tab[NTX_SCHED];
9458 
9459 	rc = sysctl_wire_old_buffer(req, 0);
9460 	if (rc != 0)
9461 		return (rc);
9462 
9463 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9464 	if (sb == NULL)
9465 		return (ENOMEM);
9466 
9467 	mtx_lock(&sc->reg_lock);
9468 	if (hw_off_limits(sc)) {
9469 		rc = ENXIO;
9470 		goto done;
9471 	}
9472 
9473 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9474 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9475 	t4_read_pace_tbl(sc, pace_tab);
9476 
9477 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9478 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9479 
9480 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9481 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9482 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9483 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9484 		if (kbps)
9485 			sbuf_printf(sb, "%9u     ", kbps);
9486 		else
9487 			sbuf_printf(sb, " disabled     ");
9488 
9489 		if (ipg)
9490 			sbuf_printf(sb, "%13u        ", ipg);
9491 		else
9492 			sbuf_printf(sb, "     disabled        ");
9493 
9494 		if (pace_tab[i])
9495 			sbuf_printf(sb, "%10u", pace_tab[i]);
9496 		else
9497 			sbuf_printf(sb, "  disabled");
9498 	}
9499 	rc = sbuf_finish(sb);
9500 done:
9501 	mtx_unlock(&sc->reg_lock);
9502 	sbuf_delete(sb);
9503 	return (rc);
9504 }
9505 
9506 static int
9507 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9508 {
9509 	struct adapter *sc = arg1;
9510 	struct sbuf *sb;
9511 	int rc, i, j;
9512 	uint64_t *p0, *p1;
9513 	struct lb_port_stats s[2];
9514 	static const char *stat_name[] = {
9515 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9516 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9517 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9518 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9519 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9520 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9521 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9522 	};
9523 
9524 	rc = sysctl_wire_old_buffer(req, 0);
9525 	if (rc != 0)
9526 		return (rc);
9527 
9528 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9529 	if (sb == NULL)
9530 		return (ENOMEM);
9531 
9532 	memset(s, 0, sizeof(s));
9533 
9534 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9535 		mtx_lock(&sc->reg_lock);
9536 		if (hw_off_limits(sc))
9537 			rc = ENXIO;
9538 		else {
9539 			t4_get_lb_stats(sc, i, &s[0]);
9540 			t4_get_lb_stats(sc, i + 1, &s[1]);
9541 		}
9542 		mtx_unlock(&sc->reg_lock);
9543 		if (rc != 0)
9544 			break;
9545 
9546 		p0 = &s[0].octets;
9547 		p1 = &s[1].octets;
9548 		sbuf_printf(sb, "%s                       Loopback %u"
9549 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9550 
9551 		for (j = 0; j < nitems(stat_name); j++)
9552 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9553 				   *p0++, *p1++);
9554 	}
9555 
9556 	rc = sbuf_finish(sb);
9557 	sbuf_delete(sb);
9558 
9559 	return (rc);
9560 }
9561 
9562 static int
9563 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9564 {
9565 	int rc = 0;
9566 	struct port_info *pi = arg1;
9567 	struct link_config *lc = &pi->link_cfg;
9568 	struct sbuf *sb;
9569 
9570 	rc = sysctl_wire_old_buffer(req, 0);
9571 	if (rc != 0)
9572 		return(rc);
9573 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9574 	if (sb == NULL)
9575 		return (ENOMEM);
9576 
9577 	if (lc->link_ok || lc->link_down_rc == 255)
9578 		sbuf_printf(sb, "n/a");
9579 	else
9580 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9581 
9582 	rc = sbuf_finish(sb);
9583 	sbuf_delete(sb);
9584 
9585 	return (rc);
9586 }
9587 
9588 struct mem_desc {
9589 	unsigned int base;
9590 	unsigned int limit;
9591 	unsigned int idx;
9592 };
9593 
9594 static int
9595 mem_desc_cmp(const void *a, const void *b)
9596 {
9597 	return ((const struct mem_desc *)a)->base -
9598 	       ((const struct mem_desc *)b)->base;
9599 }
9600 
9601 static void
9602 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9603     unsigned int to)
9604 {
9605 	unsigned int size;
9606 
9607 	if (from == to)
9608 		return;
9609 
9610 	size = to - from + 1;
9611 	if (size == 0)
9612 		return;
9613 
9614 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9615 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9616 }
9617 
9618 static int
9619 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9620 {
9621 	struct adapter *sc = arg1;
9622 	struct sbuf *sb;
9623 	int rc, i, n;
9624 	uint32_t lo, hi, used, alloc;
9625 	static const char *memory[] = {
9626 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9627 	};
9628 	static const char *region[] = {
9629 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9630 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9631 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9632 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9633 		"RQUDP region:", "PBL region:", "TXPBL region:",
9634 		"DBVFIFO region:", "ULPRX state:", "ULPTX state:",
9635 		"On-chip queues:", "TLS keys:",
9636 	};
9637 	struct mem_desc avail[4];
9638 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9639 	struct mem_desc *md = mem;
9640 
9641 	rc = sysctl_wire_old_buffer(req, 0);
9642 	if (rc != 0)
9643 		return (rc);
9644 
9645 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9646 	if (sb == NULL)
9647 		return (ENOMEM);
9648 
9649 	for (i = 0; i < nitems(mem); i++) {
9650 		mem[i].limit = 0;
9651 		mem[i].idx = i;
9652 	}
9653 
9654 	mtx_lock(&sc->reg_lock);
9655 	if (hw_off_limits(sc)) {
9656 		rc = ENXIO;
9657 		goto done;
9658 	}
9659 
9660 	/* Find and sort the populated memory ranges */
9661 	i = 0;
9662 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9663 	if (lo & F_EDRAM0_ENABLE) {
9664 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9665 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9666 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9667 		avail[i].idx = 0;
9668 		i++;
9669 	}
9670 	if (lo & F_EDRAM1_ENABLE) {
9671 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9672 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9673 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9674 		avail[i].idx = 1;
9675 		i++;
9676 	}
9677 	if (lo & F_EXT_MEM_ENABLE) {
9678 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9679 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9680 		avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9681 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9682 		i++;
9683 	}
9684 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9685 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9686 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9687 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9688 		avail[i].idx = 4;
9689 		i++;
9690 	}
9691 	if (is_t6(sc) && lo & F_HMA_MUX) {
9692 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9693 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9694 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9695 		avail[i].idx = 5;
9696 		i++;
9697 	}
9698 	MPASS(i <= nitems(avail));
9699 	if (!i)                                    /* no memory available */
9700 		goto done;
9701 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9702 
9703 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9704 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9705 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9706 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9707 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9708 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9709 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9710 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9711 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9712 
9713 	/* the next few have explicit upper bounds */
9714 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9715 	md->limit = md->base - 1 +
9716 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9717 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9718 	md++;
9719 
9720 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9721 	md->limit = md->base - 1 +
9722 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9723 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9724 	md++;
9725 
9726 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9727 		if (chip_id(sc) <= CHELSIO_T5)
9728 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9729 		else
9730 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9731 		md->limit = 0;
9732 	} else {
9733 		md->base = 0;
9734 		md->idx = nitems(region);  /* hide it */
9735 	}
9736 	md++;
9737 
9738 #define ulp_region(reg) \
9739 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9740 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9741 
9742 	ulp_region(RX_ISCSI);
9743 	ulp_region(RX_TDDP);
9744 	ulp_region(TX_TPT);
9745 	ulp_region(RX_STAG);
9746 	ulp_region(RX_RQ);
9747 	ulp_region(RX_RQUDP);
9748 	ulp_region(RX_PBL);
9749 	ulp_region(TX_PBL);
9750 #undef ulp_region
9751 
9752 	md->base = 0;
9753 	if (is_t4(sc))
9754 		md->idx = nitems(region);
9755 	else {
9756 		uint32_t size = 0;
9757 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9758 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9759 
9760 		if (is_t5(sc)) {
9761 			if (sge_ctrl & F_VFIFO_ENABLE)
9762 				size = fifo_size << 2;
9763 		} else
9764 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9765 
9766 		if (size) {
9767 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
9768 			md->limit = md->base + size - 1;
9769 		} else
9770 			md->idx = nitems(region);
9771 	}
9772 	md++;
9773 
9774 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9775 	md->limit = 0;
9776 	md++;
9777 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9778 	md->limit = 0;
9779 	md++;
9780 
9781 	md->base = sc->vres.ocq.start;
9782 	if (sc->vres.ocq.size)
9783 		md->limit = md->base + sc->vres.ocq.size - 1;
9784 	else
9785 		md->idx = nitems(region);  /* hide it */
9786 	md++;
9787 
9788 	md->base = sc->vres.key.start;
9789 	if (sc->vres.key.size)
9790 		md->limit = md->base + sc->vres.key.size - 1;
9791 	else
9792 		md->idx = nitems(region);  /* hide it */
9793 	md++;
9794 
9795 	/* add any address-space holes, there can be up to 3 */
9796 	for (n = 0; n < i - 1; n++)
9797 		if (avail[n].limit < avail[n + 1].base)
9798 			(md++)->base = avail[n].limit;
9799 	if (avail[n].limit)
9800 		(md++)->base = avail[n].limit;
9801 
9802 	n = md - mem;
9803 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
9804 
9805 	for (lo = 0; lo < i; lo++)
9806 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
9807 				avail[lo].limit - 1);
9808 
9809 	sbuf_printf(sb, "\n");
9810 	for (i = 0; i < n; i++) {
9811 		if (mem[i].idx >= nitems(region))
9812 			continue;                        /* skip holes */
9813 		if (!mem[i].limit)
9814 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
9815 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
9816 				mem[i].limit);
9817 	}
9818 
9819 	sbuf_printf(sb, "\n");
9820 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
9821 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
9822 	mem_region_show(sb, "uP RAM:", lo, hi);
9823 
9824 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
9825 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
9826 	mem_region_show(sb, "uP Extmem2:", lo, hi);
9827 
9828 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
9829 	sbuf_printf(sb, "\n%u Rx pages of size %uKiB for %u channels\n",
9830 		   G_PMRXMAXPAGE(lo),
9831 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
9832 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
9833 
9834 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
9835 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
9836 	sbuf_printf(sb, "%u Tx pages of size %u%ciB for %u channels\n",
9837 		   G_PMTXMAXPAGE(lo),
9838 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
9839 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
9840 	sbuf_printf(sb, "%u p-structs\n",
9841 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT));
9842 
9843 	for (i = 0; i < 4; i++) {
9844 		if (chip_id(sc) > CHELSIO_T5)
9845 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
9846 		else
9847 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
9848 		if (is_t5(sc)) {
9849 			used = G_T5_USED(lo);
9850 			alloc = G_T5_ALLOC(lo);
9851 		} else {
9852 			used = G_USED(lo);
9853 			alloc = G_ALLOC(lo);
9854 		}
9855 		/* For T6 these are MAC buffer groups */
9856 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
9857 		    i, used, alloc);
9858 	}
9859 	for (i = 0; i < sc->chip_params->nchan; i++) {
9860 		if (chip_id(sc) > CHELSIO_T5)
9861 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
9862 		else
9863 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
9864 		if (is_t5(sc)) {
9865 			used = G_T5_USED(lo);
9866 			alloc = G_T5_ALLOC(lo);
9867 		} else {
9868 			used = G_USED(lo);
9869 			alloc = G_ALLOC(lo);
9870 		}
9871 		/* For T6 these are MAC buffer groups */
9872 		sbuf_printf(sb,
9873 		    "\nLoopback %d using %u pages out of %u allocated",
9874 		    i, used, alloc);
9875 	}
9876 done:
9877 	mtx_unlock(&sc->reg_lock);
9878 	if (rc == 0)
9879 		rc = sbuf_finish(sb);
9880 	sbuf_delete(sb);
9881 	return (rc);
9882 }
9883 
9884 static inline void
9885 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
9886 {
9887 	*mask = x | y;
9888 	y = htobe64(y);
9889 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
9890 }
9891 
9892 static int
9893 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
9894 {
9895 	struct adapter *sc = arg1;
9896 	struct sbuf *sb;
9897 	int rc, i;
9898 
9899 	MPASS(chip_id(sc) <= CHELSIO_T5);
9900 
9901 	rc = sysctl_wire_old_buffer(req, 0);
9902 	if (rc != 0)
9903 		return (rc);
9904 
9905 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9906 	if (sb == NULL)
9907 		return (ENOMEM);
9908 
9909 	sbuf_printf(sb,
9910 	    "Idx  Ethernet address     Mask     Vld Ports PF"
9911 	    "  VF              Replication             P0 P1 P2 P3  ML");
9912 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
9913 		uint64_t tcamx, tcamy, mask;
9914 		uint32_t cls_lo, cls_hi;
9915 		uint8_t addr[ETHER_ADDR_LEN];
9916 
9917 		mtx_lock(&sc->reg_lock);
9918 		if (hw_off_limits(sc))
9919 			rc = ENXIO;
9920 		else {
9921 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
9922 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
9923 		}
9924 		mtx_unlock(&sc->reg_lock);
9925 		if (rc != 0)
9926 			break;
9927 		if (tcamx & tcamy)
9928 			continue;
9929 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
9930 		mtx_lock(&sc->reg_lock);
9931 		if (hw_off_limits(sc))
9932 			rc = ENXIO;
9933 		else {
9934 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
9935 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
9936 		}
9937 		mtx_unlock(&sc->reg_lock);
9938 		if (rc != 0)
9939 			break;
9940 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
9941 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
9942 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
9943 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
9944 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
9945 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
9946 
9947 		if (cls_lo & F_REPLICATE) {
9948 			struct fw_ldst_cmd ldst_cmd;
9949 
9950 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
9951 			ldst_cmd.op_to_addrspace =
9952 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
9953 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
9954 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
9955 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
9956 			ldst_cmd.u.mps.rplc.fid_idx =
9957 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
9958 				V_FW_LDST_CMD_IDX(i));
9959 
9960 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
9961 			    "t4mps");
9962 			if (rc)
9963 				break;
9964 			if (hw_off_limits(sc))
9965 				rc = ENXIO;
9966 			else
9967 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
9968 				    sizeof(ldst_cmd), &ldst_cmd);
9969 			end_synchronized_op(sc, 0);
9970 			if (rc != 0)
9971 				break;
9972 			else {
9973 				sbuf_printf(sb, " %08x %08x %08x %08x",
9974 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
9975 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
9976 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
9977 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
9978 			}
9979 		} else
9980 			sbuf_printf(sb, "%36s", "");
9981 
9982 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
9983 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
9984 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
9985 	}
9986 
9987 	if (rc)
9988 		(void) sbuf_finish(sb);
9989 	else
9990 		rc = sbuf_finish(sb);
9991 	sbuf_delete(sb);
9992 
9993 	return (rc);
9994 }
9995 
9996 static int
9997 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
9998 {
9999 	struct adapter *sc = arg1;
10000 	struct sbuf *sb;
10001 	int rc, i;
10002 
10003 	MPASS(chip_id(sc) > CHELSIO_T5);
10004 
10005 	rc = sysctl_wire_old_buffer(req, 0);
10006 	if (rc != 0)
10007 		return (rc);
10008 
10009 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10010 	if (sb == NULL)
10011 		return (ENOMEM);
10012 
10013 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
10014 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
10015 	    "                           Replication"
10016 	    "                                    P0 P1 P2 P3  ML\n");
10017 
10018 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10019 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
10020 		uint16_t ivlan;
10021 		uint64_t tcamx, tcamy, val, mask;
10022 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10023 		uint8_t addr[ETHER_ADDR_LEN];
10024 
10025 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10026 		if (i < 256)
10027 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10028 		else
10029 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10030 		mtx_lock(&sc->reg_lock);
10031 		if (hw_off_limits(sc))
10032 			rc = ENXIO;
10033 		else {
10034 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10035 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10036 			tcamy = G_DMACH(val) << 32;
10037 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10038 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10039 		}
10040 		mtx_unlock(&sc->reg_lock);
10041 		if (rc != 0)
10042 			break;
10043 
10044 		lookup_type = G_DATALKPTYPE(data2);
10045 		port_num = G_DATAPORTNUM(data2);
10046 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10047 			/* Inner header VNI */
10048 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10049 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10050 			dip_hit = data2 & F_DATADIPHIT;
10051 			vlan_vld = 0;
10052 		} else {
10053 			vniy = 0;
10054 			dip_hit = 0;
10055 			vlan_vld = data2 & F_DATAVIDH2;
10056 			ivlan = G_VIDL(val);
10057 		}
10058 
10059 		ctl |= V_CTLXYBITSEL(1);
10060 		mtx_lock(&sc->reg_lock);
10061 		if (hw_off_limits(sc))
10062 			rc = ENXIO;
10063 		else {
10064 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10065 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10066 			tcamx = G_DMACH(val) << 32;
10067 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10068 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10069 		}
10070 		mtx_unlock(&sc->reg_lock);
10071 		if (rc != 0)
10072 			break;
10073 
10074 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10075 			/* Inner header VNI mask */
10076 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10077 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10078 		} else
10079 			vnix = 0;
10080 
10081 		if (tcamx & tcamy)
10082 			continue;
10083 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10084 
10085 		mtx_lock(&sc->reg_lock);
10086 		if (hw_off_limits(sc))
10087 			rc = ENXIO;
10088 		else {
10089 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10090 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10091 		}
10092 		mtx_unlock(&sc->reg_lock);
10093 		if (rc != 0)
10094 			break;
10095 
10096 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10097 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10098 			    "%012jx %06x %06x    -    -   %3c"
10099 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10100 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10101 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10102 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10103 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10104 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10105 		} else {
10106 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10107 			    "%012jx    -       -   ", i, addr[0], addr[1],
10108 			    addr[2], addr[3], addr[4], addr[5],
10109 			    (uintmax_t)mask);
10110 
10111 			if (vlan_vld)
10112 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10113 			else
10114 				sbuf_printf(sb, "  -    N     ");
10115 
10116 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10117 			    lookup_type ? 'I' : 'O', port_num,
10118 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10119 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10120 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10121 		}
10122 
10123 
10124 		if (cls_lo & F_T6_REPLICATE) {
10125 			struct fw_ldst_cmd ldst_cmd;
10126 
10127 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10128 			ldst_cmd.op_to_addrspace =
10129 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10130 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10131 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10132 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10133 			ldst_cmd.u.mps.rplc.fid_idx =
10134 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10135 				V_FW_LDST_CMD_IDX(i));
10136 
10137 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10138 			    "t6mps");
10139 			if (rc)
10140 				break;
10141 			if (hw_off_limits(sc))
10142 				rc = ENXIO;
10143 			else
10144 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10145 				    sizeof(ldst_cmd), &ldst_cmd);
10146 			end_synchronized_op(sc, 0);
10147 			if (rc != 0)
10148 				break;
10149 			else {
10150 				sbuf_printf(sb, " %08x %08x %08x %08x"
10151 				    " %08x %08x %08x %08x",
10152 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10153 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10154 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10155 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10156 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10157 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10158 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10159 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10160 			}
10161 		} else
10162 			sbuf_printf(sb, "%72s", "");
10163 
10164 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10165 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10166 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10167 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10168 	}
10169 
10170 	if (rc)
10171 		(void) sbuf_finish(sb);
10172 	else
10173 		rc = sbuf_finish(sb);
10174 	sbuf_delete(sb);
10175 
10176 	return (rc);
10177 }
10178 
10179 static int
10180 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10181 {
10182 	struct adapter *sc = arg1;
10183 	struct sbuf *sb;
10184 	int rc;
10185 	uint16_t mtus[NMTUS];
10186 
10187 	rc = sysctl_wire_old_buffer(req, 0);
10188 	if (rc != 0)
10189 		return (rc);
10190 
10191 	mtx_lock(&sc->reg_lock);
10192 	if (hw_off_limits(sc))
10193 		rc = ENXIO;
10194 	else
10195 		t4_read_mtu_tbl(sc, mtus, NULL);
10196 	mtx_unlock(&sc->reg_lock);
10197 	if (rc != 0)
10198 		return (rc);
10199 
10200 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10201 	if (sb == NULL)
10202 		return (ENOMEM);
10203 
10204 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10205 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10206 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10207 	    mtus[14], mtus[15]);
10208 
10209 	rc = sbuf_finish(sb);
10210 	sbuf_delete(sb);
10211 
10212 	return (rc);
10213 }
10214 
10215 static int
10216 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10217 {
10218 	struct adapter *sc = arg1;
10219 	struct sbuf *sb;
10220 	int rc, i;
10221 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10222 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10223 	static const char *tx_stats[MAX_PM_NSTATS] = {
10224 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10225 		"Tx FIFO wait", NULL, "Tx latency"
10226 	};
10227 	static const char *rx_stats[MAX_PM_NSTATS] = {
10228 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10229 		"Rx FIFO wait", NULL, "Rx latency"
10230 	};
10231 
10232 	rc = sysctl_wire_old_buffer(req, 0);
10233 	if (rc != 0)
10234 		return (rc);
10235 
10236 	mtx_lock(&sc->reg_lock);
10237 	if (hw_off_limits(sc))
10238 		rc = ENXIO;
10239 	else {
10240 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10241 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10242 	}
10243 	mtx_unlock(&sc->reg_lock);
10244 	if (rc != 0)
10245 		return (rc);
10246 
10247 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10248 	if (sb == NULL)
10249 		return (ENOMEM);
10250 
10251 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10252 	for (i = 0; i < 4; i++) {
10253 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10254 		    tx_cyc[i]);
10255 	}
10256 
10257 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10258 	for (i = 0; i < 4; i++) {
10259 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10260 		    rx_cyc[i]);
10261 	}
10262 
10263 	if (chip_id(sc) > CHELSIO_T5) {
10264 		sbuf_printf(sb,
10265 		    "\n              Total wait      Total occupancy");
10266 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10267 		    tx_cyc[i]);
10268 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10269 		    rx_cyc[i]);
10270 
10271 		i += 2;
10272 		MPASS(i < nitems(tx_stats));
10273 
10274 		sbuf_printf(sb,
10275 		    "\n                   Reads           Total wait");
10276 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10277 		    tx_cyc[i]);
10278 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10279 		    rx_cyc[i]);
10280 	}
10281 
10282 	rc = sbuf_finish(sb);
10283 	sbuf_delete(sb);
10284 
10285 	return (rc);
10286 }
10287 
10288 static int
10289 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10290 {
10291 	struct adapter *sc = arg1;
10292 	struct sbuf *sb;
10293 	int rc;
10294 	struct tp_rdma_stats stats;
10295 
10296 	rc = sysctl_wire_old_buffer(req, 0);
10297 	if (rc != 0)
10298 		return (rc);
10299 
10300 	mtx_lock(&sc->reg_lock);
10301 	if (hw_off_limits(sc))
10302 		rc = ENXIO;
10303 	else
10304 		t4_tp_get_rdma_stats(sc, &stats, 0);
10305 	mtx_unlock(&sc->reg_lock);
10306 	if (rc != 0)
10307 		return (rc);
10308 
10309 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10310 	if (sb == NULL)
10311 		return (ENOMEM);
10312 
10313 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10314 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10315 
10316 	rc = sbuf_finish(sb);
10317 	sbuf_delete(sb);
10318 
10319 	return (rc);
10320 }
10321 
10322 static int
10323 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10324 {
10325 	struct adapter *sc = arg1;
10326 	struct sbuf *sb;
10327 	int rc;
10328 	struct tp_tcp_stats v4, v6;
10329 
10330 	rc = sysctl_wire_old_buffer(req, 0);
10331 	if (rc != 0)
10332 		return (rc);
10333 
10334 	mtx_lock(&sc->reg_lock);
10335 	if (hw_off_limits(sc))
10336 		rc = ENXIO;
10337 	else
10338 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10339 	mtx_unlock(&sc->reg_lock);
10340 	if (rc != 0)
10341 		return (rc);
10342 
10343 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10344 	if (sb == NULL)
10345 		return (ENOMEM);
10346 
10347 	sbuf_printf(sb,
10348 	    "                                IP                 IPv6\n");
10349 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10350 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10351 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10352 	    v4.tcp_in_segs, v6.tcp_in_segs);
10353 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10354 	    v4.tcp_out_segs, v6.tcp_out_segs);
10355 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10356 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10357 
10358 	rc = sbuf_finish(sb);
10359 	sbuf_delete(sb);
10360 
10361 	return (rc);
10362 }
10363 
10364 static int
10365 sysctl_tids(SYSCTL_HANDLER_ARGS)
10366 {
10367 	struct adapter *sc = arg1;
10368 	struct sbuf *sb;
10369 	int rc;
10370 	uint32_t x, y;
10371 	struct tid_info *t = &sc->tids;
10372 
10373 	rc = sysctl_wire_old_buffer(req, 0);
10374 	if (rc != 0)
10375 		return (rc);
10376 
10377 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10378 	if (sb == NULL)
10379 		return (ENOMEM);
10380 
10381 	if (t->natids) {
10382 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10383 		    t->atids_in_use);
10384 	}
10385 
10386 	if (t->nhpftids) {
10387 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10388 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10389 	}
10390 
10391 	if (t->ntids) {
10392 		bool hashen = false;
10393 
10394 		mtx_lock(&sc->reg_lock);
10395 		if (hw_off_limits(sc))
10396 			rc = ENXIO;
10397 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10398 			hashen = true;
10399 			if (chip_id(sc) <= CHELSIO_T5) {
10400 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10401 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10402 			} else {
10403 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10404 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10405 			}
10406 		}
10407 		mtx_unlock(&sc->reg_lock);
10408 		if (rc != 0)
10409 			goto done;
10410 
10411 		sbuf_printf(sb, "TID range: ");
10412 		if (hashen) {
10413 			if (x)
10414 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10415 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10416 		} else {
10417 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10418 			    t->ntids - 1);
10419 		}
10420 		sbuf_printf(sb, ", in use: %u\n",
10421 		    atomic_load_acq_int(&t->tids_in_use));
10422 	}
10423 
10424 	if (t->nstids) {
10425 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10426 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10427 	}
10428 
10429 	if (t->nftids) {
10430 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10431 		    t->ftid_end, t->ftids_in_use);
10432 	}
10433 
10434 	if (t->netids) {
10435 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10436 		    t->etid_base + t->netids - 1, t->etids_in_use);
10437 	}
10438 
10439 	mtx_lock(&sc->reg_lock);
10440 	if (hw_off_limits(sc))
10441 		rc = ENXIO;
10442 	else {
10443 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10444 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10445 	}
10446 	mtx_unlock(&sc->reg_lock);
10447 	if (rc != 0)
10448 		goto done;
10449 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10450 done:
10451 	if (rc == 0)
10452 		rc = sbuf_finish(sb);
10453 	else
10454 		(void)sbuf_finish(sb);
10455 	sbuf_delete(sb);
10456 
10457 	return (rc);
10458 }
10459 
10460 static int
10461 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10462 {
10463 	struct adapter *sc = arg1;
10464 	struct sbuf *sb;
10465 	int rc;
10466 	struct tp_err_stats stats;
10467 
10468 	rc = sysctl_wire_old_buffer(req, 0);
10469 	if (rc != 0)
10470 		return (rc);
10471 
10472 	mtx_lock(&sc->reg_lock);
10473 	if (hw_off_limits(sc))
10474 		rc = ENXIO;
10475 	else
10476 		t4_tp_get_err_stats(sc, &stats, 0);
10477 	mtx_unlock(&sc->reg_lock);
10478 	if (rc != 0)
10479 		return (rc);
10480 
10481 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10482 	if (sb == NULL)
10483 		return (ENOMEM);
10484 
10485 	if (sc->chip_params->nchan > 2) {
10486 		sbuf_printf(sb, "                 channel 0  channel 1"
10487 		    "  channel 2  channel 3\n");
10488 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10489 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10490 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10491 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10492 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10493 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10494 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10495 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10496 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10497 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10498 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10499 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10500 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10501 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10502 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10503 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10504 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10505 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10506 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10507 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10508 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10509 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10510 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10511 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10512 	} else {
10513 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10514 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10515 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10516 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10517 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10518 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10519 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10520 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10521 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10522 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10523 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10524 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10525 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10526 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10527 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10528 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10529 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10530 	}
10531 
10532 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10533 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10534 
10535 	rc = sbuf_finish(sb);
10536 	sbuf_delete(sb);
10537 
10538 	return (rc);
10539 }
10540 
10541 static int
10542 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10543 {
10544 	struct adapter *sc = arg1;
10545 	struct sbuf *sb;
10546 	int rc;
10547 	struct tp_tnl_stats stats;
10548 
10549 	rc = sysctl_wire_old_buffer(req, 0);
10550 	if (rc != 0)
10551 		return(rc);
10552 
10553 	mtx_lock(&sc->reg_lock);
10554 	if (hw_off_limits(sc))
10555 		rc = ENXIO;
10556 	else
10557 		t4_tp_get_tnl_stats(sc, &stats, 1);
10558 	mtx_unlock(&sc->reg_lock);
10559 	if (rc != 0)
10560 		return (rc);
10561 
10562 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10563 	if (sb == NULL)
10564 		return (ENOMEM);
10565 
10566 	if (sc->chip_params->nchan > 2) {
10567 		sbuf_printf(sb, "           channel 0  channel 1"
10568 		    "  channel 2  channel 3\n");
10569 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10570 		    stats.out_pkt[0], stats.out_pkt[1],
10571 		    stats.out_pkt[2], stats.out_pkt[3]);
10572 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10573 		    stats.in_pkt[0], stats.in_pkt[1],
10574 		    stats.in_pkt[2], stats.in_pkt[3]);
10575 	} else {
10576 		sbuf_printf(sb, "           channel 0  channel 1\n");
10577 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10578 		    stats.out_pkt[0], stats.out_pkt[1]);
10579 		sbuf_printf(sb, "InPkts:   %10u %10u",
10580 		    stats.in_pkt[0], stats.in_pkt[1]);
10581 	}
10582 
10583 	rc = sbuf_finish(sb);
10584 	sbuf_delete(sb);
10585 
10586 	return (rc);
10587 }
10588 
10589 static int
10590 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10591 {
10592 	struct adapter *sc = arg1;
10593 	struct tp_params *tpp = &sc->params.tp;
10594 	u_int mask;
10595 	int rc;
10596 
10597 	mask = tpp->la_mask >> 16;
10598 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10599 	if (rc != 0 || req->newptr == NULL)
10600 		return (rc);
10601 	if (mask > 0xffff)
10602 		return (EINVAL);
10603 	mtx_lock(&sc->reg_lock);
10604 	if (hw_off_limits(sc))
10605 		rc = ENXIO;
10606 	else {
10607 		tpp->la_mask = mask << 16;
10608 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10609 		    tpp->la_mask);
10610 	}
10611 	mtx_unlock(&sc->reg_lock);
10612 
10613 	return (rc);
10614 }
10615 
10616 struct field_desc {
10617 	const char *name;
10618 	u_int start;
10619 	u_int width;
10620 };
10621 
10622 static void
10623 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10624 {
10625 	char buf[32];
10626 	int line_size = 0;
10627 
10628 	while (f->name) {
10629 		uint64_t mask = (1ULL << f->width) - 1;
10630 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10631 		    ((uintmax_t)v >> f->start) & mask);
10632 
10633 		if (line_size + len >= 79) {
10634 			line_size = 8;
10635 			sbuf_printf(sb, "\n        ");
10636 		}
10637 		sbuf_printf(sb, "%s ", buf);
10638 		line_size += len + 1;
10639 		f++;
10640 	}
10641 	sbuf_printf(sb, "\n");
10642 }
10643 
10644 static const struct field_desc tp_la0[] = {
10645 	{ "RcfOpCodeOut", 60, 4 },
10646 	{ "State", 56, 4 },
10647 	{ "WcfState", 52, 4 },
10648 	{ "RcfOpcSrcOut", 50, 2 },
10649 	{ "CRxError", 49, 1 },
10650 	{ "ERxError", 48, 1 },
10651 	{ "SanityFailed", 47, 1 },
10652 	{ "SpuriousMsg", 46, 1 },
10653 	{ "FlushInputMsg", 45, 1 },
10654 	{ "FlushInputCpl", 44, 1 },
10655 	{ "RssUpBit", 43, 1 },
10656 	{ "RssFilterHit", 42, 1 },
10657 	{ "Tid", 32, 10 },
10658 	{ "InitTcb", 31, 1 },
10659 	{ "LineNumber", 24, 7 },
10660 	{ "Emsg", 23, 1 },
10661 	{ "EdataOut", 22, 1 },
10662 	{ "Cmsg", 21, 1 },
10663 	{ "CdataOut", 20, 1 },
10664 	{ "EreadPdu", 19, 1 },
10665 	{ "CreadPdu", 18, 1 },
10666 	{ "TunnelPkt", 17, 1 },
10667 	{ "RcfPeerFin", 16, 1 },
10668 	{ "RcfReasonOut", 12, 4 },
10669 	{ "TxCchannel", 10, 2 },
10670 	{ "RcfTxChannel", 8, 2 },
10671 	{ "RxEchannel", 6, 2 },
10672 	{ "RcfRxChannel", 5, 1 },
10673 	{ "RcfDataOutSrdy", 4, 1 },
10674 	{ "RxDvld", 3, 1 },
10675 	{ "RxOoDvld", 2, 1 },
10676 	{ "RxCongestion", 1, 1 },
10677 	{ "TxCongestion", 0, 1 },
10678 	{ NULL }
10679 };
10680 
10681 static const struct field_desc tp_la1[] = {
10682 	{ "CplCmdIn", 56, 8 },
10683 	{ "CplCmdOut", 48, 8 },
10684 	{ "ESynOut", 47, 1 },
10685 	{ "EAckOut", 46, 1 },
10686 	{ "EFinOut", 45, 1 },
10687 	{ "ERstOut", 44, 1 },
10688 	{ "SynIn", 43, 1 },
10689 	{ "AckIn", 42, 1 },
10690 	{ "FinIn", 41, 1 },
10691 	{ "RstIn", 40, 1 },
10692 	{ "DataIn", 39, 1 },
10693 	{ "DataInVld", 38, 1 },
10694 	{ "PadIn", 37, 1 },
10695 	{ "RxBufEmpty", 36, 1 },
10696 	{ "RxDdp", 35, 1 },
10697 	{ "RxFbCongestion", 34, 1 },
10698 	{ "TxFbCongestion", 33, 1 },
10699 	{ "TxPktSumSrdy", 32, 1 },
10700 	{ "RcfUlpType", 28, 4 },
10701 	{ "Eread", 27, 1 },
10702 	{ "Ebypass", 26, 1 },
10703 	{ "Esave", 25, 1 },
10704 	{ "Static0", 24, 1 },
10705 	{ "Cread", 23, 1 },
10706 	{ "Cbypass", 22, 1 },
10707 	{ "Csave", 21, 1 },
10708 	{ "CPktOut", 20, 1 },
10709 	{ "RxPagePoolFull", 18, 2 },
10710 	{ "RxLpbkPkt", 17, 1 },
10711 	{ "TxLpbkPkt", 16, 1 },
10712 	{ "RxVfValid", 15, 1 },
10713 	{ "SynLearned", 14, 1 },
10714 	{ "SetDelEntry", 13, 1 },
10715 	{ "SetInvEntry", 12, 1 },
10716 	{ "CpcmdDvld", 11, 1 },
10717 	{ "CpcmdSave", 10, 1 },
10718 	{ "RxPstructsFull", 8, 2 },
10719 	{ "EpcmdDvld", 7, 1 },
10720 	{ "EpcmdFlush", 6, 1 },
10721 	{ "EpcmdTrimPrefix", 5, 1 },
10722 	{ "EpcmdTrimPostfix", 4, 1 },
10723 	{ "ERssIp4Pkt", 3, 1 },
10724 	{ "ERssIp6Pkt", 2, 1 },
10725 	{ "ERssTcpUdpPkt", 1, 1 },
10726 	{ "ERssFceFipPkt", 0, 1 },
10727 	{ NULL }
10728 };
10729 
10730 static const struct field_desc tp_la2[] = {
10731 	{ "CplCmdIn", 56, 8 },
10732 	{ "MpsVfVld", 55, 1 },
10733 	{ "MpsPf", 52, 3 },
10734 	{ "MpsVf", 44, 8 },
10735 	{ "SynIn", 43, 1 },
10736 	{ "AckIn", 42, 1 },
10737 	{ "FinIn", 41, 1 },
10738 	{ "RstIn", 40, 1 },
10739 	{ "DataIn", 39, 1 },
10740 	{ "DataInVld", 38, 1 },
10741 	{ "PadIn", 37, 1 },
10742 	{ "RxBufEmpty", 36, 1 },
10743 	{ "RxDdp", 35, 1 },
10744 	{ "RxFbCongestion", 34, 1 },
10745 	{ "TxFbCongestion", 33, 1 },
10746 	{ "TxPktSumSrdy", 32, 1 },
10747 	{ "RcfUlpType", 28, 4 },
10748 	{ "Eread", 27, 1 },
10749 	{ "Ebypass", 26, 1 },
10750 	{ "Esave", 25, 1 },
10751 	{ "Static0", 24, 1 },
10752 	{ "Cread", 23, 1 },
10753 	{ "Cbypass", 22, 1 },
10754 	{ "Csave", 21, 1 },
10755 	{ "CPktOut", 20, 1 },
10756 	{ "RxPagePoolFull", 18, 2 },
10757 	{ "RxLpbkPkt", 17, 1 },
10758 	{ "TxLpbkPkt", 16, 1 },
10759 	{ "RxVfValid", 15, 1 },
10760 	{ "SynLearned", 14, 1 },
10761 	{ "SetDelEntry", 13, 1 },
10762 	{ "SetInvEntry", 12, 1 },
10763 	{ "CpcmdDvld", 11, 1 },
10764 	{ "CpcmdSave", 10, 1 },
10765 	{ "RxPstructsFull", 8, 2 },
10766 	{ "EpcmdDvld", 7, 1 },
10767 	{ "EpcmdFlush", 6, 1 },
10768 	{ "EpcmdTrimPrefix", 5, 1 },
10769 	{ "EpcmdTrimPostfix", 4, 1 },
10770 	{ "ERssIp4Pkt", 3, 1 },
10771 	{ "ERssIp6Pkt", 2, 1 },
10772 	{ "ERssTcpUdpPkt", 1, 1 },
10773 	{ "ERssFceFipPkt", 0, 1 },
10774 	{ NULL }
10775 };
10776 
10777 static void
10778 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10779 {
10780 
10781 	field_desc_show(sb, *p, tp_la0);
10782 }
10783 
10784 static void
10785 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10786 {
10787 
10788 	if (idx)
10789 		sbuf_printf(sb, "\n");
10790 	field_desc_show(sb, p[0], tp_la0);
10791 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10792 		field_desc_show(sb, p[1], tp_la0);
10793 }
10794 
10795 static void
10796 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
10797 {
10798 
10799 	if (idx)
10800 		sbuf_printf(sb, "\n");
10801 	field_desc_show(sb, p[0], tp_la0);
10802 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10803 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
10804 }
10805 
10806 static int
10807 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
10808 {
10809 	struct adapter *sc = arg1;
10810 	struct sbuf *sb;
10811 	uint64_t *buf, *p;
10812 	int rc;
10813 	u_int i, inc;
10814 	void (*show_func)(struct sbuf *, uint64_t *, int);
10815 
10816 	rc = sysctl_wire_old_buffer(req, 0);
10817 	if (rc != 0)
10818 		return (rc);
10819 
10820 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10821 	if (sb == NULL)
10822 		return (ENOMEM);
10823 
10824 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
10825 
10826 	mtx_lock(&sc->reg_lock);
10827 	if (hw_off_limits(sc))
10828 		rc = ENXIO;
10829 	else {
10830 		t4_tp_read_la(sc, buf, NULL);
10831 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
10832 		case 2:
10833 			inc = 2;
10834 			show_func = tp_la_show2;
10835 			break;
10836 		case 3:
10837 			inc = 2;
10838 			show_func = tp_la_show3;
10839 			break;
10840 		default:
10841 			inc = 1;
10842 			show_func = tp_la_show;
10843 		}
10844 	}
10845 	mtx_unlock(&sc->reg_lock);
10846 	if (rc != 0)
10847 		goto done;
10848 
10849 	p = buf;
10850 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
10851 		(*show_func)(sb, p, i);
10852 	rc = sbuf_finish(sb);
10853 done:
10854 	sbuf_delete(sb);
10855 	free(buf, M_CXGBE);
10856 	return (rc);
10857 }
10858 
10859 static int
10860 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
10861 {
10862 	struct adapter *sc = arg1;
10863 	struct sbuf *sb;
10864 	int rc;
10865 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
10866 
10867 	rc = sysctl_wire_old_buffer(req, 0);
10868 	if (rc != 0)
10869 		return (rc);
10870 
10871 	mtx_lock(&sc->reg_lock);
10872 	if (hw_off_limits(sc))
10873 		rc = ENXIO;
10874 	else
10875 		t4_get_chan_txrate(sc, nrate, orate);
10876 	mtx_unlock(&sc->reg_lock);
10877 	if (rc != 0)
10878 		return (rc);
10879 
10880 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10881 	if (sb == NULL)
10882 		return (ENOMEM);
10883 
10884 	if (sc->chip_params->nchan > 2) {
10885 		sbuf_printf(sb, "              channel 0   channel 1"
10886 		    "   channel 2   channel 3\n");
10887 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
10888 		    nrate[0], nrate[1], nrate[2], nrate[3]);
10889 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
10890 		    orate[0], orate[1], orate[2], orate[3]);
10891 	} else {
10892 		sbuf_printf(sb, "              channel 0   channel 1\n");
10893 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
10894 		    nrate[0], nrate[1]);
10895 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
10896 		    orate[0], orate[1]);
10897 	}
10898 
10899 	rc = sbuf_finish(sb);
10900 	sbuf_delete(sb);
10901 
10902 	return (rc);
10903 }
10904 
10905 static int
10906 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
10907 {
10908 	struct adapter *sc = arg1;
10909 	struct sbuf *sb;
10910 	uint32_t *buf, *p;
10911 	int rc, i;
10912 
10913 	rc = sysctl_wire_old_buffer(req, 0);
10914 	if (rc != 0)
10915 		return (rc);
10916 
10917 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10918 	if (sb == NULL)
10919 		return (ENOMEM);
10920 
10921 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
10922 	    M_ZERO | M_WAITOK);
10923 
10924 	mtx_lock(&sc->reg_lock);
10925 	if (hw_off_limits(sc))
10926 		rc = ENXIO;
10927 	else
10928 		t4_ulprx_read_la(sc, buf);
10929 	mtx_unlock(&sc->reg_lock);
10930 	if (rc != 0)
10931 		goto done;
10932 
10933 	p = buf;
10934 	sbuf_printf(sb, "      Pcmd        Type   Message"
10935 	    "                Data");
10936 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
10937 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
10938 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
10939 	}
10940 	rc = sbuf_finish(sb);
10941 done:
10942 	sbuf_delete(sb);
10943 	free(buf, M_CXGBE);
10944 	return (rc);
10945 }
10946 
10947 static int
10948 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
10949 {
10950 	struct adapter *sc = arg1;
10951 	struct sbuf *sb;
10952 	int rc;
10953 	uint32_t cfg, s1, s2;
10954 
10955 	MPASS(chip_id(sc) >= CHELSIO_T5);
10956 
10957 	rc = sysctl_wire_old_buffer(req, 0);
10958 	if (rc != 0)
10959 		return (rc);
10960 
10961 	mtx_lock(&sc->reg_lock);
10962 	if (hw_off_limits(sc))
10963 		rc = ENXIO;
10964 	else {
10965 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
10966 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
10967 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
10968 	}
10969 	mtx_unlock(&sc->reg_lock);
10970 	if (rc != 0)
10971 		return (rc);
10972 
10973 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10974 	if (sb == NULL)
10975 		return (ENOMEM);
10976 
10977 	if (G_STATSOURCE_T5(cfg) == 7) {
10978 		int mode;
10979 
10980 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
10981 		if (mode == 0)
10982 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
10983 		else if (mode == 1)
10984 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
10985 		else
10986 			sbuf_printf(sb, "unknown mode %d", mode);
10987 	}
10988 	rc = sbuf_finish(sb);
10989 	sbuf_delete(sb);
10990 
10991 	return (rc);
10992 }
10993 
10994 static int
10995 sysctl_cpus(SYSCTL_HANDLER_ARGS)
10996 {
10997 	struct adapter *sc = arg1;
10998 	enum cpu_sets op = arg2;
10999 	cpuset_t cpuset;
11000 	struct sbuf *sb;
11001 	int i, rc;
11002 
11003 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
11004 
11005 	CPU_ZERO(&cpuset);
11006 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
11007 	if (rc != 0)
11008 		return (rc);
11009 
11010 	rc = sysctl_wire_old_buffer(req, 0);
11011 	if (rc != 0)
11012 		return (rc);
11013 
11014 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11015 	if (sb == NULL)
11016 		return (ENOMEM);
11017 
11018 	CPU_FOREACH(i)
11019 		sbuf_printf(sb, "%d ", i);
11020 	rc = sbuf_finish(sb);
11021 	sbuf_delete(sb);
11022 
11023 	return (rc);
11024 }
11025 
11026 static int
11027 sysctl_reset(SYSCTL_HANDLER_ARGS)
11028 {
11029 	struct adapter *sc = arg1;
11030 	u_int val;
11031 	int rc;
11032 
11033 	val = sc->num_resets;
11034 	rc = sysctl_handle_int(oidp, &val, 0, req);
11035 	if (rc != 0 || req->newptr == NULL)
11036 		return (rc);
11037 
11038 	if (val == 0) {
11039 		/* Zero out the counter that tracks reset. */
11040 		sc->num_resets = 0;
11041 		return (0);
11042 	}
11043 
11044 	if (val != 1)
11045 		return (EINVAL);	/* 0 or 1 are the only legal values */
11046 
11047 	if (hw_off_limits(sc))		/* harmless race */
11048 		return (EALREADY);
11049 
11050 	taskqueue_enqueue(reset_tq, &sc->reset_task);
11051 	return (0);
11052 }
11053 
11054 #ifdef TCP_OFFLOAD
11055 static int
11056 sysctl_tls(SYSCTL_HANDLER_ARGS)
11057 {
11058 	struct adapter *sc = arg1;
11059 	int i, j, v, rc;
11060 	struct vi_info *vi;
11061 
11062 	v = sc->tt.tls;
11063 	rc = sysctl_handle_int(oidp, &v, 0, req);
11064 	if (rc != 0 || req->newptr == NULL)
11065 		return (rc);
11066 
11067 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11068 		return (ENOTSUP);
11069 
11070 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11071 	if (rc)
11072 		return (rc);
11073 	if (hw_off_limits(sc))
11074 		rc = ENXIO;
11075 	else {
11076 		sc->tt.tls = !!v;
11077 		for_each_port(sc, i) {
11078 			for_each_vi(sc->port[i], j, vi) {
11079 				if (vi->flags & VI_INIT_DONE)
11080 					t4_update_fl_bufsize(vi->ifp);
11081 			}
11082 		}
11083 	}
11084 	end_synchronized_op(sc, 0);
11085 
11086 	return (rc);
11087 
11088 }
11089 
11090 static int
11091 sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS)
11092 {
11093 	struct adapter *sc = arg1;
11094 	int *old_ports, *new_ports;
11095 	int i, new_count, rc;
11096 
11097 	if (req->newptr == NULL && req->oldptr == NULL)
11098 		return (SYSCTL_OUT(req, NULL, imax(sc->tt.num_tls_rx_ports, 1) *
11099 		    sizeof(sc->tt.tls_rx_ports[0])));
11100 
11101 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tlsrx");
11102 	if (rc)
11103 		return (rc);
11104 
11105 	if (hw_off_limits(sc)) {
11106 		rc = ENXIO;
11107 		goto done;
11108 	}
11109 
11110 	if (sc->tt.num_tls_rx_ports == 0) {
11111 		i = -1;
11112 		rc = SYSCTL_OUT(req, &i, sizeof(i));
11113 	} else
11114 		rc = SYSCTL_OUT(req, sc->tt.tls_rx_ports,
11115 		    sc->tt.num_tls_rx_ports * sizeof(sc->tt.tls_rx_ports[0]));
11116 	if (rc == 0 && req->newptr != NULL) {
11117 		new_count = req->newlen / sizeof(new_ports[0]);
11118 		new_ports = malloc(new_count * sizeof(new_ports[0]), M_CXGBE,
11119 		    M_WAITOK);
11120 		rc = SYSCTL_IN(req, new_ports, new_count *
11121 		    sizeof(new_ports[0]));
11122 		if (rc)
11123 			goto err;
11124 
11125 		/* Allow setting to a single '-1' to clear the list. */
11126 		if (new_count == 1 && new_ports[0] == -1) {
11127 			ADAPTER_LOCK(sc);
11128 			old_ports = sc->tt.tls_rx_ports;
11129 			sc->tt.tls_rx_ports = NULL;
11130 			sc->tt.num_tls_rx_ports = 0;
11131 			ADAPTER_UNLOCK(sc);
11132 			free(old_ports, M_CXGBE);
11133 		} else {
11134 			for (i = 0; i < new_count; i++) {
11135 				if (new_ports[i] < 1 ||
11136 				    new_ports[i] > IPPORT_MAX) {
11137 					rc = EINVAL;
11138 					goto err;
11139 				}
11140 			}
11141 
11142 			ADAPTER_LOCK(sc);
11143 			old_ports = sc->tt.tls_rx_ports;
11144 			sc->tt.tls_rx_ports = new_ports;
11145 			sc->tt.num_tls_rx_ports = new_count;
11146 			ADAPTER_UNLOCK(sc);
11147 			free(old_ports, M_CXGBE);
11148 			new_ports = NULL;
11149 		}
11150 	err:
11151 		free(new_ports, M_CXGBE);
11152 	}
11153 done:
11154 	end_synchronized_op(sc, 0);
11155 	return (rc);
11156 }
11157 
11158 static int
11159 sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS)
11160 {
11161 	struct adapter *sc = arg1;
11162 	int v, rc;
11163 
11164 	v = sc->tt.tls_rx_timeout;
11165 	rc = sysctl_handle_int(oidp, &v, 0, req);
11166 	if (rc != 0 || req->newptr == NULL)
11167 		return (rc);
11168 
11169 	if (v < 0)
11170 		return (EINVAL);
11171 
11172 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11173 		return (ENOTSUP);
11174 
11175 	sc->tt.tls_rx_timeout = v;
11176 
11177 	return (0);
11178 
11179 }
11180 
11181 static void
11182 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11183 {
11184 	u_int rem = val % factor;
11185 
11186 	if (rem == 0)
11187 		snprintf(buf, len, "%u", val / factor);
11188 	else {
11189 		while (rem % 10 == 0)
11190 			rem /= 10;
11191 		snprintf(buf, len, "%u.%u", val / factor, rem);
11192 	}
11193 }
11194 
11195 static int
11196 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11197 {
11198 	struct adapter *sc = arg1;
11199 	char buf[16];
11200 	u_int res, re;
11201 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11202 
11203 	mtx_lock(&sc->reg_lock);
11204 	if (hw_off_limits(sc))
11205 		res = (u_int)-1;
11206 	else
11207 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11208 	mtx_unlock(&sc->reg_lock);
11209 	if (res == (u_int)-1)
11210 		return (ENXIO);
11211 
11212 	switch (arg2) {
11213 	case 0:
11214 		/* timer_tick */
11215 		re = G_TIMERRESOLUTION(res);
11216 		break;
11217 	case 1:
11218 		/* TCP timestamp tick */
11219 		re = G_TIMESTAMPRESOLUTION(res);
11220 		break;
11221 	case 2:
11222 		/* DACK tick */
11223 		re = G_DELAYEDACKRESOLUTION(res);
11224 		break;
11225 	default:
11226 		return (EDOOFUS);
11227 	}
11228 
11229 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11230 
11231 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11232 }
11233 
11234 static int
11235 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11236 {
11237 	struct adapter *sc = arg1;
11238 	int rc;
11239 	u_int dack_tmr, dack_re, v;
11240 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11241 
11242 	mtx_lock(&sc->reg_lock);
11243 	if (hw_off_limits(sc))
11244 		rc = ENXIO;
11245 	else {
11246 		rc = 0;
11247 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11248 		    A_TP_TIMER_RESOLUTION));
11249 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11250 	}
11251 	mtx_unlock(&sc->reg_lock);
11252 	if (rc != 0)
11253 		return (rc);
11254 
11255 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11256 
11257 	return (sysctl_handle_int(oidp, &v, 0, req));
11258 }
11259 
11260 static int
11261 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11262 {
11263 	struct adapter *sc = arg1;
11264 	int rc, reg = arg2;
11265 	u_int tre;
11266 	u_long tp_tick_us, v;
11267 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11268 
11269 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11270 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11271 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11272 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11273 
11274 	mtx_lock(&sc->reg_lock);
11275 	if (hw_off_limits(sc))
11276 		rc = ENXIO;
11277 	else {
11278 		rc = 0;
11279 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11280 		tp_tick_us = (cclk_ps << tre) / 1000000;
11281 		if (reg == A_TP_INIT_SRTT)
11282 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11283 		else
11284 			v = tp_tick_us * t4_read_reg(sc, reg);
11285 	}
11286 	mtx_unlock(&sc->reg_lock);
11287 	if (rc != 0)
11288 		return (rc);
11289 	else
11290 		return (sysctl_handle_long(oidp, &v, 0, req));
11291 }
11292 
11293 /*
11294  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11295  * passed to this function.
11296  */
11297 static int
11298 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11299 {
11300 	struct adapter *sc = arg1;
11301 	int rc, idx = arg2;
11302 	u_int v;
11303 
11304 	MPASS(idx >= 0 && idx <= 24);
11305 
11306 	mtx_lock(&sc->reg_lock);
11307 	if (hw_off_limits(sc))
11308 		rc = ENXIO;
11309 	else {
11310 		rc = 0;
11311 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11312 	}
11313 	mtx_unlock(&sc->reg_lock);
11314 	if (rc != 0)
11315 		return (rc);
11316 	else
11317 		return (sysctl_handle_int(oidp, &v, 0, req));
11318 }
11319 
11320 static int
11321 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11322 {
11323 	struct adapter *sc = arg1;
11324 	int rc, idx = arg2;
11325 	u_int shift, v, r;
11326 
11327 	MPASS(idx >= 0 && idx < 16);
11328 
11329 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11330 	shift = (idx & 3) << 3;
11331 	mtx_lock(&sc->reg_lock);
11332 	if (hw_off_limits(sc))
11333 		rc = ENXIO;
11334 	else {
11335 		rc = 0;
11336 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11337 	}
11338 	mtx_unlock(&sc->reg_lock);
11339 	if (rc != 0)
11340 		return (rc);
11341 	else
11342 		return (sysctl_handle_int(oidp, &v, 0, req));
11343 }
11344 
11345 static int
11346 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11347 {
11348 	struct vi_info *vi = arg1;
11349 	struct adapter *sc = vi->adapter;
11350 	int idx, rc, i;
11351 	struct sge_ofld_rxq *ofld_rxq;
11352 	uint8_t v;
11353 
11354 	idx = vi->ofld_tmr_idx;
11355 
11356 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11357 	if (rc != 0 || req->newptr == NULL)
11358 		return (rc);
11359 
11360 	if (idx < 0 || idx >= SGE_NTIMERS)
11361 		return (EINVAL);
11362 
11363 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11364 	    "t4otmr");
11365 	if (rc)
11366 		return (rc);
11367 
11368 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11369 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11370 #ifdef atomic_store_rel_8
11371 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11372 #else
11373 		ofld_rxq->iq.intr_params = v;
11374 #endif
11375 	}
11376 	vi->ofld_tmr_idx = idx;
11377 
11378 	end_synchronized_op(sc, LOCK_HELD);
11379 	return (0);
11380 }
11381 
11382 static int
11383 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11384 {
11385 	struct vi_info *vi = arg1;
11386 	struct adapter *sc = vi->adapter;
11387 	int idx, rc;
11388 
11389 	idx = vi->ofld_pktc_idx;
11390 
11391 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11392 	if (rc != 0 || req->newptr == NULL)
11393 		return (rc);
11394 
11395 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11396 		return (EINVAL);
11397 
11398 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11399 	    "t4opktc");
11400 	if (rc)
11401 		return (rc);
11402 
11403 	if (vi->flags & VI_INIT_DONE)
11404 		rc = EBUSY; /* cannot be changed once the queues are created */
11405 	else
11406 		vi->ofld_pktc_idx = idx;
11407 
11408 	end_synchronized_op(sc, LOCK_HELD);
11409 	return (rc);
11410 }
11411 #endif
11412 
11413 static int
11414 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11415 {
11416 	int rc;
11417 
11418 	if (cntxt->cid > M_CTXTQID)
11419 		return (EINVAL);
11420 
11421 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11422 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11423 		return (EINVAL);
11424 
11425 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11426 	if (rc)
11427 		return (rc);
11428 
11429 	if (hw_off_limits(sc)) {
11430 		rc = ENXIO;
11431 		goto done;
11432 	}
11433 
11434 	if (sc->flags & FW_OK) {
11435 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11436 		    &cntxt->data[0]);
11437 		if (rc == 0)
11438 			goto done;
11439 	}
11440 
11441 	/*
11442 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11443 	 * the backdoor.
11444 	 */
11445 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11446 done:
11447 	end_synchronized_op(sc, 0);
11448 	return (rc);
11449 }
11450 
11451 static int
11452 load_fw(struct adapter *sc, struct t4_data *fw)
11453 {
11454 	int rc;
11455 	uint8_t *fw_data;
11456 
11457 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11458 	if (rc)
11459 		return (rc);
11460 
11461 	if (hw_off_limits(sc)) {
11462 		rc = ENXIO;
11463 		goto done;
11464 	}
11465 
11466 	/*
11467 	 * The firmware, with the sole exception of the memory parity error
11468 	 * handler, runs from memory and not flash.  It is almost always safe to
11469 	 * install a new firmware on a running system.  Just set bit 1 in
11470 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11471 	 */
11472 	if (sc->flags & FULL_INIT_DONE &&
11473 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11474 		rc = EBUSY;
11475 		goto done;
11476 	}
11477 
11478 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11479 
11480 	rc = copyin(fw->data, fw_data, fw->len);
11481 	if (rc == 0)
11482 		rc = -t4_load_fw(sc, fw_data, fw->len);
11483 
11484 	free(fw_data, M_CXGBE);
11485 done:
11486 	end_synchronized_op(sc, 0);
11487 	return (rc);
11488 }
11489 
11490 static int
11491 load_cfg(struct adapter *sc, struct t4_data *cfg)
11492 {
11493 	int rc;
11494 	uint8_t *cfg_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 (cfg->len == 0) {
11506 		/* clear */
11507 		rc = -t4_load_cfg(sc, NULL, 0);
11508 		goto done;
11509 	}
11510 
11511 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11512 
11513 	rc = copyin(cfg->data, cfg_data, cfg->len);
11514 	if (rc == 0)
11515 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11516 
11517 	free(cfg_data, M_CXGBE);
11518 done:
11519 	end_synchronized_op(sc, 0);
11520 	return (rc);
11521 }
11522 
11523 static int
11524 load_boot(struct adapter *sc, struct t4_bootrom *br)
11525 {
11526 	int rc;
11527 	uint8_t *br_data = NULL;
11528 	u_int offset;
11529 
11530 	if (br->len > 1024 * 1024)
11531 		return (EFBIG);
11532 
11533 	if (br->pf_offset == 0) {
11534 		/* pfidx */
11535 		if (br->pfidx_addr > 7)
11536 			return (EINVAL);
11537 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11538 		    A_PCIE_PF_EXPROM_OFST)));
11539 	} else if (br->pf_offset == 1) {
11540 		/* offset */
11541 		offset = G_OFFSET(br->pfidx_addr);
11542 	} else {
11543 		return (EINVAL);
11544 	}
11545 
11546 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11547 	if (rc)
11548 		return (rc);
11549 
11550 	if (hw_off_limits(sc)) {
11551 		rc = ENXIO;
11552 		goto done;
11553 	}
11554 
11555 	if (br->len == 0) {
11556 		/* clear */
11557 		rc = -t4_load_boot(sc, NULL, offset, 0);
11558 		goto done;
11559 	}
11560 
11561 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11562 
11563 	rc = copyin(br->data, br_data, br->len);
11564 	if (rc == 0)
11565 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11566 
11567 	free(br_data, M_CXGBE);
11568 done:
11569 	end_synchronized_op(sc, 0);
11570 	return (rc);
11571 }
11572 
11573 static int
11574 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11575 {
11576 	int rc;
11577 	uint8_t *bc_data = NULL;
11578 
11579 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11580 	if (rc)
11581 		return (rc);
11582 
11583 	if (hw_off_limits(sc)) {
11584 		rc = ENXIO;
11585 		goto done;
11586 	}
11587 
11588 	if (bc->len == 0) {
11589 		/* clear */
11590 		rc = -t4_load_bootcfg(sc, NULL, 0);
11591 		goto done;
11592 	}
11593 
11594 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11595 
11596 	rc = copyin(bc->data, bc_data, bc->len);
11597 	if (rc == 0)
11598 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11599 
11600 	free(bc_data, M_CXGBE);
11601 done:
11602 	end_synchronized_op(sc, 0);
11603 	return (rc);
11604 }
11605 
11606 static int
11607 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11608 {
11609 	int rc;
11610 	struct cudbg_init *cudbg;
11611 	void *handle, *buf;
11612 
11613 	/* buf is large, don't block if no memory is available */
11614 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11615 	if (buf == NULL)
11616 		return (ENOMEM);
11617 
11618 	handle = cudbg_alloc_handle();
11619 	if (handle == NULL) {
11620 		rc = ENOMEM;
11621 		goto done;
11622 	}
11623 
11624 	cudbg = cudbg_get_init(handle);
11625 	cudbg->adap = sc;
11626 	cudbg->print = (cudbg_print_cb)printf;
11627 
11628 #ifndef notyet
11629 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11630 	    __func__, dump->wr_flash, dump->len, dump->data);
11631 #endif
11632 
11633 	if (dump->wr_flash)
11634 		cudbg->use_flash = 1;
11635 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11636 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11637 
11638 	rc = cudbg_collect(handle, buf, &dump->len);
11639 	if (rc != 0)
11640 		goto done;
11641 
11642 	rc = copyout(buf, dump->data, dump->len);
11643 done:
11644 	cudbg_free_handle(handle);
11645 	free(buf, M_CXGBE);
11646 	return (rc);
11647 }
11648 
11649 static void
11650 free_offload_policy(struct t4_offload_policy *op)
11651 {
11652 	struct offload_rule *r;
11653 	int i;
11654 
11655 	if (op == NULL)
11656 		return;
11657 
11658 	r = &op->rule[0];
11659 	for (i = 0; i < op->nrules; i++, r++) {
11660 		free(r->bpf_prog.bf_insns, M_CXGBE);
11661 	}
11662 	free(op->rule, M_CXGBE);
11663 	free(op, M_CXGBE);
11664 }
11665 
11666 static int
11667 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11668 {
11669 	int i, rc, len;
11670 	struct t4_offload_policy *op, *old;
11671 	struct bpf_program *bf;
11672 	const struct offload_settings *s;
11673 	struct offload_rule *r;
11674 	void *u;
11675 
11676 	if (!is_offload(sc))
11677 		return (ENODEV);
11678 
11679 	if (uop->nrules == 0) {
11680 		/* Delete installed policies. */
11681 		op = NULL;
11682 		goto set_policy;
11683 	} else if (uop->nrules > 256) { /* arbitrary */
11684 		return (E2BIG);
11685 	}
11686 
11687 	/* Copy userspace offload policy to kernel */
11688 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11689 	op->nrules = uop->nrules;
11690 	len = op->nrules * sizeof(struct offload_rule);
11691 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11692 	rc = copyin(uop->rule, op->rule, len);
11693 	if (rc) {
11694 		free(op->rule, M_CXGBE);
11695 		free(op, M_CXGBE);
11696 		return (rc);
11697 	}
11698 
11699 	r = &op->rule[0];
11700 	for (i = 0; i < op->nrules; i++, r++) {
11701 
11702 		/* Validate open_type */
11703 		if (r->open_type != OPEN_TYPE_LISTEN &&
11704 		    r->open_type != OPEN_TYPE_ACTIVE &&
11705 		    r->open_type != OPEN_TYPE_PASSIVE &&
11706 		    r->open_type != OPEN_TYPE_DONTCARE) {
11707 error:
11708 			/*
11709 			 * Rules 0 to i have malloc'd filters that need to be
11710 			 * freed.  Rules i+1 to nrules have userspace pointers
11711 			 * and should be left alone.
11712 			 */
11713 			op->nrules = i;
11714 			free_offload_policy(op);
11715 			return (rc);
11716 		}
11717 
11718 		/* Validate settings */
11719 		s = &r->settings;
11720 		if ((s->offload != 0 && s->offload != 1) ||
11721 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11722 		    s->sched_class < -1 ||
11723 		    s->sched_class >= sc->params.nsched_cls) {
11724 			rc = EINVAL;
11725 			goto error;
11726 		}
11727 
11728 		bf = &r->bpf_prog;
11729 		u = bf->bf_insns;	/* userspace ptr */
11730 		bf->bf_insns = NULL;
11731 		if (bf->bf_len == 0) {
11732 			/* legal, matches everything */
11733 			continue;
11734 		}
11735 		len = bf->bf_len * sizeof(*bf->bf_insns);
11736 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11737 		rc = copyin(u, bf->bf_insns, len);
11738 		if (rc != 0)
11739 			goto error;
11740 
11741 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11742 			rc = EINVAL;
11743 			goto error;
11744 		}
11745 	}
11746 set_policy:
11747 	rw_wlock(&sc->policy_lock);
11748 	old = sc->policy;
11749 	sc->policy = op;
11750 	rw_wunlock(&sc->policy_lock);
11751 	free_offload_policy(old);
11752 
11753 	return (0);
11754 }
11755 
11756 #define MAX_READ_BUF_SIZE (128 * 1024)
11757 static int
11758 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11759 {
11760 	uint32_t addr, remaining, n;
11761 	uint32_t *buf;
11762 	int rc;
11763 	uint8_t *dst;
11764 
11765 	mtx_lock(&sc->reg_lock);
11766 	if (hw_off_limits(sc))
11767 		rc = ENXIO;
11768 	else
11769 		rc = validate_mem_range(sc, mr->addr, mr->len);
11770 	mtx_unlock(&sc->reg_lock);
11771 	if (rc != 0)
11772 		return (rc);
11773 
11774 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11775 	addr = mr->addr;
11776 	remaining = mr->len;
11777 	dst = (void *)mr->data;
11778 
11779 	while (remaining) {
11780 		n = min(remaining, MAX_READ_BUF_SIZE);
11781 		mtx_lock(&sc->reg_lock);
11782 		if (hw_off_limits(sc))
11783 			rc = ENXIO;
11784 		else
11785 			read_via_memwin(sc, 2, addr, buf, n);
11786 		mtx_unlock(&sc->reg_lock);
11787 		if (rc != 0)
11788 			break;
11789 
11790 		rc = copyout(buf, dst, n);
11791 		if (rc != 0)
11792 			break;
11793 
11794 		dst += n;
11795 		remaining -= n;
11796 		addr += n;
11797 	}
11798 
11799 	free(buf, M_CXGBE);
11800 	return (rc);
11801 }
11802 #undef MAX_READ_BUF_SIZE
11803 
11804 static int
11805 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11806 {
11807 	int rc;
11808 
11809 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11810 		return (EINVAL);
11811 
11812 	if (i2cd->len > sizeof(i2cd->data))
11813 		return (EFBIG);
11814 
11815 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11816 	if (rc)
11817 		return (rc);
11818 	if (hw_off_limits(sc))
11819 		rc = ENXIO;
11820 	else
11821 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11822 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11823 	end_synchronized_op(sc, 0);
11824 
11825 	return (rc);
11826 }
11827 
11828 static int
11829 clear_stats(struct adapter *sc, u_int port_id)
11830 {
11831 	int i, v, chan_map;
11832 	struct port_info *pi;
11833 	struct vi_info *vi;
11834 	struct sge_rxq *rxq;
11835 	struct sge_txq *txq;
11836 	struct sge_wrq *wrq;
11837 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11838 	struct sge_ofld_txq *ofld_txq;
11839 #endif
11840 #ifdef TCP_OFFLOAD
11841 	struct sge_ofld_rxq *ofld_rxq;
11842 #endif
11843 
11844 	if (port_id >= sc->params.nports)
11845 		return (EINVAL);
11846 	pi = sc->port[port_id];
11847 	if (pi == NULL)
11848 		return (EIO);
11849 
11850 	mtx_lock(&sc->reg_lock);
11851 	if (!hw_off_limits(sc)) {
11852 		/* MAC stats */
11853 		t4_clr_port_stats(sc, pi->tx_chan);
11854 		if (is_t6(sc)) {
11855 			if (pi->fcs_reg != -1)
11856 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11857 			else
11858 				pi->stats.rx_fcs_err = 0;
11859 		}
11860 		for_each_vi(pi, v, vi) {
11861 			if (vi->flags & VI_INIT_DONE)
11862 				t4_clr_vi_stats(sc, vi->vin);
11863 		}
11864 		chan_map = pi->rx_e_chan_map;
11865 		v = 0;	/* reuse */
11866 		while (chan_map) {
11867 			i = ffs(chan_map) - 1;
11868 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11869 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11870 			chan_map &= ~(1 << i);
11871 		}
11872 	}
11873 	mtx_unlock(&sc->reg_lock);
11874 	pi->tx_parse_error = 0;
11875 	pi->tnl_cong_drops = 0;
11876 
11877 	/*
11878 	 * Since this command accepts a port, clear stats for
11879 	 * all VIs on this port.
11880 	 */
11881 	for_each_vi(pi, v, vi) {
11882 		if (vi->flags & VI_INIT_DONE) {
11883 
11884 			for_each_rxq(vi, i, rxq) {
11885 #if defined(INET) || defined(INET6)
11886 				rxq->lro.lro_queued = 0;
11887 				rxq->lro.lro_flushed = 0;
11888 #endif
11889 				rxq->rxcsum = 0;
11890 				rxq->vlan_extraction = 0;
11891 				rxq->vxlan_rxcsum = 0;
11892 
11893 				rxq->fl.cl_allocated = 0;
11894 				rxq->fl.cl_recycled = 0;
11895 				rxq->fl.cl_fast_recycled = 0;
11896 			}
11897 
11898 			for_each_txq(vi, i, txq) {
11899 				txq->txcsum = 0;
11900 				txq->tso_wrs = 0;
11901 				txq->vlan_insertion = 0;
11902 				txq->imm_wrs = 0;
11903 				txq->sgl_wrs = 0;
11904 				txq->txpkt_wrs = 0;
11905 				txq->txpkts0_wrs = 0;
11906 				txq->txpkts1_wrs = 0;
11907 				txq->txpkts0_pkts = 0;
11908 				txq->txpkts1_pkts = 0;
11909 				txq->txpkts_flush = 0;
11910 				txq->raw_wrs = 0;
11911 				txq->vxlan_tso_wrs = 0;
11912 				txq->vxlan_txcsum = 0;
11913 				txq->kern_tls_records = 0;
11914 				txq->kern_tls_short = 0;
11915 				txq->kern_tls_partial = 0;
11916 				txq->kern_tls_full = 0;
11917 				txq->kern_tls_octets = 0;
11918 				txq->kern_tls_waste = 0;
11919 				txq->kern_tls_options = 0;
11920 				txq->kern_tls_header = 0;
11921 				txq->kern_tls_fin = 0;
11922 				txq->kern_tls_fin_short = 0;
11923 				txq->kern_tls_cbc = 0;
11924 				txq->kern_tls_gcm = 0;
11925 				mp_ring_reset_stats(txq->r);
11926 			}
11927 
11928 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11929 			for_each_ofld_txq(vi, i, ofld_txq) {
11930 				ofld_txq->wrq.tx_wrs_direct = 0;
11931 				ofld_txq->wrq.tx_wrs_copied = 0;
11932 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
11933 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
11934 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
11935 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
11936 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
11937 			}
11938 #endif
11939 #ifdef TCP_OFFLOAD
11940 			for_each_ofld_rxq(vi, i, ofld_rxq) {
11941 				ofld_rxq->fl.cl_allocated = 0;
11942 				ofld_rxq->fl.cl_recycled = 0;
11943 				ofld_rxq->fl.cl_fast_recycled = 0;
11944 				counter_u64_zero(
11945 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
11946 				counter_u64_zero(
11947 				    ofld_rxq->rx_iscsi_ddp_setup_error);
11948 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
11949 				ofld_rxq->rx_iscsi_ddp_octets = 0;
11950 				ofld_rxq->rx_iscsi_fl_pdus = 0;
11951 				ofld_rxq->rx_iscsi_fl_octets = 0;
11952 				ofld_rxq->rx_toe_tls_records = 0;
11953 				ofld_rxq->rx_toe_tls_octets = 0;
11954 			}
11955 #endif
11956 
11957 			if (IS_MAIN_VI(vi)) {
11958 				wrq = &sc->sge.ctrlq[pi->port_id];
11959 				wrq->tx_wrs_direct = 0;
11960 				wrq->tx_wrs_copied = 0;
11961 			}
11962 		}
11963 	}
11964 
11965 	return (0);
11966 }
11967 
11968 static int
11969 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
11970 {
11971 #ifdef INET6
11972 	struct in6_addr in6;
11973 
11974 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
11975 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
11976 		return (0);
11977 	else
11978 		return (EIO);
11979 #else
11980 	return (ENOTSUP);
11981 #endif
11982 }
11983 
11984 static int
11985 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
11986 {
11987 #ifdef INET6
11988 	struct in6_addr in6;
11989 
11990 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
11991 	return (t4_release_clip_addr(sc, &in6));
11992 #else
11993 	return (ENOTSUP);
11994 #endif
11995 }
11996 
11997 int
11998 t4_os_find_pci_capability(struct adapter *sc, int cap)
11999 {
12000 	int i;
12001 
12002 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
12003 }
12004 
12005 int
12006 t4_os_pci_save_state(struct adapter *sc)
12007 {
12008 	device_t dev;
12009 	struct pci_devinfo *dinfo;
12010 
12011 	dev = sc->dev;
12012 	dinfo = device_get_ivars(dev);
12013 
12014 	pci_cfg_save(dev, dinfo, 0);
12015 	return (0);
12016 }
12017 
12018 int
12019 t4_os_pci_restore_state(struct adapter *sc)
12020 {
12021 	device_t dev;
12022 	struct pci_devinfo *dinfo;
12023 
12024 	dev = sc->dev;
12025 	dinfo = device_get_ivars(dev);
12026 
12027 	pci_cfg_restore(dev, dinfo);
12028 	return (0);
12029 }
12030 
12031 void
12032 t4_os_portmod_changed(struct port_info *pi)
12033 {
12034 	struct adapter *sc = pi->adapter;
12035 	struct vi_info *vi;
12036 	struct ifnet *ifp;
12037 	static const char *mod_str[] = {
12038 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
12039 	};
12040 
12041 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
12042 	    ("%s: port_type %u", __func__, pi->port_type));
12043 
12044 	vi = &pi->vi[0];
12045 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12046 		PORT_LOCK(pi);
12047 		build_medialist(pi);
12048 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12049 			fixup_link_config(pi);
12050 			apply_link_config(pi);
12051 		}
12052 		PORT_UNLOCK(pi);
12053 		end_synchronized_op(sc, LOCK_HELD);
12054 	}
12055 
12056 	ifp = vi->ifp;
12057 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12058 		if_printf(ifp, "transceiver unplugged.\n");
12059 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12060 		if_printf(ifp, "unknown transceiver inserted.\n");
12061 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12062 		if_printf(ifp, "unsupported transceiver inserted.\n");
12063 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12064 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12065 		    port_top_speed(pi), mod_str[pi->mod_type]);
12066 	} else {
12067 		if_printf(ifp, "transceiver (type %d) inserted.\n",
12068 		    pi->mod_type);
12069 	}
12070 }
12071 
12072 void
12073 t4_os_link_changed(struct port_info *pi)
12074 {
12075 	struct vi_info *vi;
12076 	struct ifnet *ifp;
12077 	struct link_config *lc = &pi->link_cfg;
12078 	struct adapter *sc = pi->adapter;
12079 	int v;
12080 
12081 	PORT_LOCK_ASSERT_OWNED(pi);
12082 
12083 	if (is_t6(sc)) {
12084 		if (lc->link_ok) {
12085 			if (lc->speed > 25000 ||
12086 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12087 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12088 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12089 			} else {
12090 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12091 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12092 			}
12093 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12094 			pi->stats.rx_fcs_err = 0;
12095 		} else {
12096 			pi->fcs_reg = -1;
12097 		}
12098 	} else {
12099 		MPASS(pi->fcs_reg != -1);
12100 		MPASS(pi->fcs_base == 0);
12101 	}
12102 
12103 	for_each_vi(pi, v, vi) {
12104 		ifp = vi->ifp;
12105 		if (ifp == NULL)
12106 			continue;
12107 
12108 		if (lc->link_ok) {
12109 			ifp->if_baudrate = IF_Mbps(lc->speed);
12110 			if_link_state_change(ifp, LINK_STATE_UP);
12111 		} else {
12112 			if_link_state_change(ifp, LINK_STATE_DOWN);
12113 		}
12114 	}
12115 }
12116 
12117 void
12118 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12119 {
12120 	struct adapter *sc;
12121 
12122 	sx_slock(&t4_list_lock);
12123 	SLIST_FOREACH(sc, &t4_list, link) {
12124 		/*
12125 		 * func should not make any assumptions about what state sc is
12126 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12127 		 */
12128 		func(sc, arg);
12129 	}
12130 	sx_sunlock(&t4_list_lock);
12131 }
12132 
12133 static int
12134 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12135     struct thread *td)
12136 {
12137 	int rc;
12138 	struct adapter *sc = dev->si_drv1;
12139 
12140 	rc = priv_check(td, PRIV_DRIVER);
12141 	if (rc != 0)
12142 		return (rc);
12143 
12144 	switch (cmd) {
12145 	case CHELSIO_T4_GETREG: {
12146 		struct t4_reg *edata = (struct t4_reg *)data;
12147 
12148 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12149 			return (EFAULT);
12150 
12151 		mtx_lock(&sc->reg_lock);
12152 		if (hw_off_limits(sc))
12153 			rc = ENXIO;
12154 		else if (edata->size == 4)
12155 			edata->val = t4_read_reg(sc, edata->addr);
12156 		else if (edata->size == 8)
12157 			edata->val = t4_read_reg64(sc, edata->addr);
12158 		else
12159 			rc = EINVAL;
12160 		mtx_unlock(&sc->reg_lock);
12161 
12162 		break;
12163 	}
12164 	case CHELSIO_T4_SETREG: {
12165 		struct t4_reg *edata = (struct t4_reg *)data;
12166 
12167 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12168 			return (EFAULT);
12169 
12170 		mtx_lock(&sc->reg_lock);
12171 		if (hw_off_limits(sc))
12172 			rc = ENXIO;
12173 		else if (edata->size == 4) {
12174 			if (edata->val & 0xffffffff00000000)
12175 				rc = EINVAL;
12176 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12177 		} else if (edata->size == 8)
12178 			t4_write_reg64(sc, edata->addr, edata->val);
12179 		else
12180 			rc = EINVAL;
12181 		mtx_unlock(&sc->reg_lock);
12182 
12183 		break;
12184 	}
12185 	case CHELSIO_T4_REGDUMP: {
12186 		struct t4_regdump *regs = (struct t4_regdump *)data;
12187 		int reglen = t4_get_regs_len(sc);
12188 		uint8_t *buf;
12189 
12190 		if (regs->len < reglen) {
12191 			regs->len = reglen; /* hint to the caller */
12192 			return (ENOBUFS);
12193 		}
12194 
12195 		regs->len = reglen;
12196 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12197 		mtx_lock(&sc->reg_lock);
12198 		if (hw_off_limits(sc))
12199 			rc = ENXIO;
12200 		else
12201 			get_regs(sc, regs, buf);
12202 		mtx_unlock(&sc->reg_lock);
12203 		if (rc == 0)
12204 			rc = copyout(buf, regs->data, reglen);
12205 		free(buf, M_CXGBE);
12206 		break;
12207 	}
12208 	case CHELSIO_T4_GET_FILTER_MODE:
12209 		rc = get_filter_mode(sc, (uint32_t *)data);
12210 		break;
12211 	case CHELSIO_T4_SET_FILTER_MODE:
12212 		rc = set_filter_mode(sc, *(uint32_t *)data);
12213 		break;
12214 	case CHELSIO_T4_SET_FILTER_MASK:
12215 		rc = set_filter_mask(sc, *(uint32_t *)data);
12216 		break;
12217 	case CHELSIO_T4_GET_FILTER:
12218 		rc = get_filter(sc, (struct t4_filter *)data);
12219 		break;
12220 	case CHELSIO_T4_SET_FILTER:
12221 		rc = set_filter(sc, (struct t4_filter *)data);
12222 		break;
12223 	case CHELSIO_T4_DEL_FILTER:
12224 		rc = del_filter(sc, (struct t4_filter *)data);
12225 		break;
12226 	case CHELSIO_T4_GET_SGE_CONTEXT:
12227 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12228 		break;
12229 	case CHELSIO_T4_LOAD_FW:
12230 		rc = load_fw(sc, (struct t4_data *)data);
12231 		break;
12232 	case CHELSIO_T4_GET_MEM:
12233 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12234 		break;
12235 	case CHELSIO_T4_GET_I2C:
12236 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12237 		break;
12238 	case CHELSIO_T4_CLEAR_STATS:
12239 		rc = clear_stats(sc, *(uint32_t *)data);
12240 		break;
12241 	case CHELSIO_T4_SCHED_CLASS:
12242 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12243 		break;
12244 	case CHELSIO_T4_SCHED_QUEUE:
12245 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12246 		break;
12247 	case CHELSIO_T4_GET_TRACER:
12248 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12249 		break;
12250 	case CHELSIO_T4_SET_TRACER:
12251 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12252 		break;
12253 	case CHELSIO_T4_LOAD_CFG:
12254 		rc = load_cfg(sc, (struct t4_data *)data);
12255 		break;
12256 	case CHELSIO_T4_LOAD_BOOT:
12257 		rc = load_boot(sc, (struct t4_bootrom *)data);
12258 		break;
12259 	case CHELSIO_T4_LOAD_BOOTCFG:
12260 		rc = load_bootcfg(sc, (struct t4_data *)data);
12261 		break;
12262 	case CHELSIO_T4_CUDBG_DUMP:
12263 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12264 		break;
12265 	case CHELSIO_T4_SET_OFLD_POLICY:
12266 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12267 		break;
12268 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12269 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12270 		break;
12271 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12272 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12273 		break;
12274 	default:
12275 		rc = ENOTTY;
12276 	}
12277 
12278 	return (rc);
12279 }
12280 
12281 #ifdef TCP_OFFLOAD
12282 static int
12283 toe_capability(struct vi_info *vi, bool enable)
12284 {
12285 	int rc;
12286 	struct port_info *pi = vi->pi;
12287 	struct adapter *sc = pi->adapter;
12288 
12289 	ASSERT_SYNCHRONIZED_OP(sc);
12290 
12291 	if (!is_offload(sc))
12292 		return (ENODEV);
12293 	if (hw_off_limits(sc))
12294 		return (ENXIO);
12295 
12296 	if (enable) {
12297 #ifdef KERN_TLS
12298 		if (sc->flags & KERN_TLS_ON) {
12299 			int i, j, n;
12300 			struct port_info *p;
12301 			struct vi_info *v;
12302 
12303 			/*
12304 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12305 			 * on any ifnet.
12306 			 */
12307 			n = 0;
12308 			for_each_port(sc, i) {
12309 				p = sc->port[i];
12310 				for_each_vi(p, j, v) {
12311 					if (v->ifp->if_capenable & IFCAP_TXTLS) {
12312 						CH_WARN(sc,
12313 						    "%s has NIC TLS enabled.\n",
12314 						    device_get_nameunit(v->dev));
12315 						n++;
12316 					}
12317 				}
12318 			}
12319 			if (n > 0) {
12320 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12321 				    "associated with this adapter before "
12322 				    "trying to enable TOE.\n");
12323 				return (EAGAIN);
12324 			}
12325 			rc = t4_config_kern_tls(sc, false);
12326 			if (rc)
12327 				return (rc);
12328 		}
12329 #endif
12330 		if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
12331 			/* TOE is already enabled. */
12332 			return (0);
12333 		}
12334 
12335 		/*
12336 		 * We need the port's queues around so that we're able to send
12337 		 * and receive CPLs to/from the TOE even if the ifnet for this
12338 		 * port has never been UP'd administratively.
12339 		 */
12340 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12341 			return (rc);
12342 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12343 		    ((rc = vi_init(&pi->vi[0])) != 0))
12344 			return (rc);
12345 
12346 		if (isset(&sc->offload_map, pi->port_id)) {
12347 			/* TOE is enabled on another VI of this port. */
12348 			pi->uld_vis++;
12349 			return (0);
12350 		}
12351 
12352 		if (!uld_active(sc, ULD_TOM)) {
12353 			rc = t4_activate_uld(sc, ULD_TOM);
12354 			if (rc == EAGAIN) {
12355 				log(LOG_WARNING,
12356 				    "You must kldload t4_tom.ko before trying "
12357 				    "to enable TOE on a cxgbe interface.\n");
12358 			}
12359 			if (rc != 0)
12360 				return (rc);
12361 			KASSERT(sc->tom_softc != NULL,
12362 			    ("%s: TOM activated but softc NULL", __func__));
12363 			KASSERT(uld_active(sc, ULD_TOM),
12364 			    ("%s: TOM activated but flag not set", __func__));
12365 		}
12366 
12367 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12368 		if (!uld_active(sc, ULD_IWARP))
12369 			(void) t4_activate_uld(sc, ULD_IWARP);
12370 		if (!uld_active(sc, ULD_ISCSI))
12371 			(void) t4_activate_uld(sc, ULD_ISCSI);
12372 
12373 		pi->uld_vis++;
12374 		setbit(&sc->offload_map, pi->port_id);
12375 	} else {
12376 		pi->uld_vis--;
12377 
12378 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12379 			return (0);
12380 
12381 		KASSERT(uld_active(sc, ULD_TOM),
12382 		    ("%s: TOM never initialized?", __func__));
12383 		clrbit(&sc->offload_map, pi->port_id);
12384 	}
12385 
12386 	return (0);
12387 }
12388 
12389 /*
12390  * Add an upper layer driver to the global list.
12391  */
12392 int
12393 t4_register_uld(struct uld_info *ui)
12394 {
12395 	int rc = 0;
12396 	struct uld_info *u;
12397 
12398 	sx_xlock(&t4_uld_list_lock);
12399 	SLIST_FOREACH(u, &t4_uld_list, link) {
12400 	    if (u->uld_id == ui->uld_id) {
12401 		    rc = EEXIST;
12402 		    goto done;
12403 	    }
12404 	}
12405 
12406 	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
12407 	ui->refcount = 0;
12408 done:
12409 	sx_xunlock(&t4_uld_list_lock);
12410 	return (rc);
12411 }
12412 
12413 int
12414 t4_unregister_uld(struct uld_info *ui)
12415 {
12416 	int rc = EINVAL;
12417 	struct uld_info *u;
12418 
12419 	sx_xlock(&t4_uld_list_lock);
12420 
12421 	SLIST_FOREACH(u, &t4_uld_list, link) {
12422 	    if (u == ui) {
12423 		    if (ui->refcount > 0) {
12424 			    rc = EBUSY;
12425 			    goto done;
12426 		    }
12427 
12428 		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
12429 		    rc = 0;
12430 		    goto done;
12431 	    }
12432 	}
12433 done:
12434 	sx_xunlock(&t4_uld_list_lock);
12435 	return (rc);
12436 }
12437 
12438 int
12439 t4_activate_uld(struct adapter *sc, int id)
12440 {
12441 	int rc;
12442 	struct uld_info *ui;
12443 
12444 	ASSERT_SYNCHRONIZED_OP(sc);
12445 
12446 	if (id < 0 || id > ULD_MAX)
12447 		return (EINVAL);
12448 	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
12449 
12450 	sx_slock(&t4_uld_list_lock);
12451 
12452 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12453 		if (ui->uld_id == id) {
12454 			if (!(sc->flags & FULL_INIT_DONE)) {
12455 				rc = adapter_init(sc);
12456 				if (rc != 0)
12457 					break;
12458 			}
12459 
12460 			rc = ui->activate(sc);
12461 			if (rc == 0) {
12462 				setbit(&sc->active_ulds, id);
12463 				ui->refcount++;
12464 			}
12465 			break;
12466 		}
12467 	}
12468 
12469 	sx_sunlock(&t4_uld_list_lock);
12470 
12471 	return (rc);
12472 }
12473 
12474 int
12475 t4_deactivate_uld(struct adapter *sc, int id)
12476 {
12477 	int rc;
12478 	struct uld_info *ui;
12479 
12480 	ASSERT_SYNCHRONIZED_OP(sc);
12481 
12482 	if (id < 0 || id > ULD_MAX)
12483 		return (EINVAL);
12484 	rc = ENXIO;
12485 
12486 	sx_slock(&t4_uld_list_lock);
12487 
12488 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12489 		if (ui->uld_id == id) {
12490 			rc = ui->deactivate(sc);
12491 			if (rc == 0) {
12492 				clrbit(&sc->active_ulds, id);
12493 				ui->refcount--;
12494 			}
12495 			break;
12496 		}
12497 	}
12498 
12499 	sx_sunlock(&t4_uld_list_lock);
12500 
12501 	return (rc);
12502 }
12503 
12504 static void
12505 t4_async_event(void *arg, int n)
12506 {
12507 	struct uld_info *ui;
12508 	struct adapter *sc = (struct adapter *)arg;
12509 
12510 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
12511 		return;
12512 	sx_slock(&t4_uld_list_lock);
12513 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12514 		if (ui->uld_id == ULD_IWARP) {
12515 			ui->async_event(sc);
12516 			break;
12517 		}
12518 	}
12519 	sx_sunlock(&t4_uld_list_lock);
12520 	end_synchronized_op(sc, 0);
12521 }
12522 
12523 int
12524 uld_active(struct adapter *sc, int uld_id)
12525 {
12526 
12527 	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
12528 
12529 	return (isset(&sc->active_ulds, uld_id));
12530 }
12531 #endif
12532 
12533 #ifdef KERN_TLS
12534 static int
12535 ktls_capability(struct adapter *sc, bool enable)
12536 {
12537 	ASSERT_SYNCHRONIZED_OP(sc);
12538 
12539 	if (!is_ktls(sc))
12540 		return (ENODEV);
12541 	if (hw_off_limits(sc))
12542 		return (ENXIO);
12543 
12544 	if (enable) {
12545 		if (sc->flags & KERN_TLS_ON)
12546 			return (0);	/* already on */
12547 		if (sc->offload_map != 0) {
12548 			CH_WARN(sc,
12549 			    "Disable TOE on all interfaces associated with "
12550 			    "this adapter before trying to enable NIC TLS.\n");
12551 			return (EAGAIN);
12552 		}
12553 		return (t4_config_kern_tls(sc, true));
12554 	} else {
12555 		/*
12556 		 * Nothing to do for disable.  If TOE is enabled sometime later
12557 		 * then toe_capability will reconfigure the hardware.
12558 		 */
12559 		return (0);
12560 	}
12561 }
12562 #endif
12563 
12564 /*
12565  * t  = ptr to tunable.
12566  * nc = number of CPUs.
12567  * c  = compiled in default for that tunable.
12568  */
12569 static void
12570 calculate_nqueues(int *t, int nc, const int c)
12571 {
12572 	int nq;
12573 
12574 	if (*t > 0)
12575 		return;
12576 	nq = *t < 0 ? -*t : c;
12577 	*t = min(nc, nq);
12578 }
12579 
12580 /*
12581  * Come up with reasonable defaults for some of the tunables, provided they're
12582  * not set by the user (in which case we'll use the values as is).
12583  */
12584 static void
12585 tweak_tunables(void)
12586 {
12587 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12588 
12589 	if (t4_ntxq < 1) {
12590 #ifdef RSS
12591 		t4_ntxq = rss_getnumbuckets();
12592 #else
12593 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12594 #endif
12595 	}
12596 
12597 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12598 
12599 	if (t4_nrxq < 1) {
12600 #ifdef RSS
12601 		t4_nrxq = rss_getnumbuckets();
12602 #else
12603 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12604 #endif
12605 	}
12606 
12607 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12608 
12609 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12610 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12611 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12612 #endif
12613 #ifdef TCP_OFFLOAD
12614 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12615 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12616 #endif
12617 
12618 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12619 	if (t4_toecaps_allowed == -1)
12620 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12621 #else
12622 	if (t4_toecaps_allowed == -1)
12623 		t4_toecaps_allowed = 0;
12624 #endif
12625 
12626 #ifdef TCP_OFFLOAD
12627 	if (t4_rdmacaps_allowed == -1) {
12628 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12629 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12630 	}
12631 
12632 	if (t4_iscsicaps_allowed == -1) {
12633 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12634 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12635 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12636 	}
12637 
12638 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12639 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12640 
12641 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12642 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12643 
12644 	if (t4_toe_tls_rx_timeout < 0)
12645 		t4_toe_tls_rx_timeout = 0;
12646 #else
12647 	if (t4_rdmacaps_allowed == -1)
12648 		t4_rdmacaps_allowed = 0;
12649 
12650 	if (t4_iscsicaps_allowed == -1)
12651 		t4_iscsicaps_allowed = 0;
12652 #endif
12653 
12654 #ifdef DEV_NETMAP
12655 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12656 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12657 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12658 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12659 #endif
12660 
12661 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12662 		t4_tmr_idx = TMR_IDX;
12663 
12664 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12665 		t4_pktc_idx = PKTC_IDX;
12666 
12667 	if (t4_qsize_txq < 128)
12668 		t4_qsize_txq = 128;
12669 
12670 	if (t4_qsize_rxq < 128)
12671 		t4_qsize_rxq = 128;
12672 	while (t4_qsize_rxq & 7)
12673 		t4_qsize_rxq++;
12674 
12675 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12676 
12677 	/*
12678 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12679 	 * VI for the port.  The rest are additional virtual interfaces on the
12680 	 * same physical port.  Note that the main VI does not have native
12681 	 * netmap support but the extra VIs do.
12682 	 *
12683 	 * Limit the number of VIs per port to the number of available
12684 	 * MAC addresses per port.
12685 	 */
12686 	if (t4_num_vis < 1)
12687 		t4_num_vis = 1;
12688 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12689 		t4_num_vis = nitems(vi_mac_funcs);
12690 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12691 	}
12692 
12693 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12694 		pcie_relaxed_ordering = 1;
12695 #if defined(__i386__) || defined(__amd64__)
12696 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12697 			pcie_relaxed_ordering = 0;
12698 #endif
12699 	}
12700 }
12701 
12702 #ifdef DDB
12703 static void
12704 t4_dump_tcb(struct adapter *sc, int tid)
12705 {
12706 	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
12707 
12708 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12709 	save = t4_read_reg(sc, reg);
12710 	base = sc->memwin[2].mw_base;
12711 
12712 	/* Dump TCB for the tid */
12713 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12714 	tcb_addr += tid * TCB_SIZE;
12715 
12716 	if (is_t4(sc)) {
12717 		pf = 0;
12718 		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
12719 	} else {
12720 		pf = V_PFNUM(sc->pf);
12721 		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
12722 	}
12723 	t4_write_reg(sc, reg, win_pos | pf);
12724 	t4_read_reg(sc, reg);
12725 
12726 	off = tcb_addr - win_pos;
12727 	for (i = 0; i < 4; i++) {
12728 		uint32_t buf[8];
12729 		for (j = 0; j < 8; j++, off += 4)
12730 			buf[j] = htonl(t4_read_reg(sc, base + off));
12731 
12732 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12733 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12734 		    buf[7]);
12735 	}
12736 
12737 	t4_write_reg(sc, reg, save);
12738 	t4_read_reg(sc, reg);
12739 }
12740 
12741 static void
12742 t4_dump_devlog(struct adapter *sc)
12743 {
12744 	struct devlog_params *dparams = &sc->params.devlog;
12745 	struct fw_devlog_e e;
12746 	int i, first, j, m, nentries, rc;
12747 	uint64_t ftstamp = UINT64_MAX;
12748 
12749 	if (dparams->start == 0) {
12750 		db_printf("devlog params not valid\n");
12751 		return;
12752 	}
12753 
12754 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12755 	m = fwmtype_to_hwmtype(dparams->memtype);
12756 
12757 	/* Find the first entry. */
12758 	first = -1;
12759 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12760 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12761 		    sizeof(e), (void *)&e);
12762 		if (rc != 0)
12763 			break;
12764 
12765 		if (e.timestamp == 0)
12766 			break;
12767 
12768 		e.timestamp = be64toh(e.timestamp);
12769 		if (e.timestamp < ftstamp) {
12770 			ftstamp = e.timestamp;
12771 			first = i;
12772 		}
12773 	}
12774 
12775 	if (first == -1)
12776 		return;
12777 
12778 	i = first;
12779 	do {
12780 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12781 		    sizeof(e), (void *)&e);
12782 		if (rc != 0)
12783 			return;
12784 
12785 		if (e.timestamp == 0)
12786 			return;
12787 
12788 		e.timestamp = be64toh(e.timestamp);
12789 		e.seqno = be32toh(e.seqno);
12790 		for (j = 0; j < 8; j++)
12791 			e.params[j] = be32toh(e.params[j]);
12792 
12793 		db_printf("%10d  %15ju  %8s  %8s  ",
12794 		    e.seqno, e.timestamp,
12795 		    (e.level < nitems(devlog_level_strings) ?
12796 			devlog_level_strings[e.level] : "UNKNOWN"),
12797 		    (e.facility < nitems(devlog_facility_strings) ?
12798 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12799 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12800 		    e.params[3], e.params[4], e.params[5], e.params[6],
12801 		    e.params[7]);
12802 
12803 		if (++i == nentries)
12804 			i = 0;
12805 	} while (i != first && !db_pager_quit);
12806 }
12807 
12808 static struct command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
12809 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
12810 
12811 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
12812 {
12813 	device_t dev;
12814 	int t;
12815 	bool valid;
12816 
12817 	valid = false;
12818 	t = db_read_token();
12819 	if (t == tIDENT) {
12820 		dev = device_lookup_by_name(db_tok_string);
12821 		valid = true;
12822 	}
12823 	db_skip_to_eol();
12824 	if (!valid) {
12825 		db_printf("usage: show t4 devlog <nexus>\n");
12826 		return;
12827 	}
12828 
12829 	if (dev == NULL) {
12830 		db_printf("device not found\n");
12831 		return;
12832 	}
12833 
12834 	t4_dump_devlog(device_get_softc(dev));
12835 }
12836 
12837 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
12838 {
12839 	device_t dev;
12840 	int radix, tid, t;
12841 	bool valid;
12842 
12843 	valid = false;
12844 	radix = db_radix;
12845 	db_radix = 10;
12846 	t = db_read_token();
12847 	if (t == tIDENT) {
12848 		dev = device_lookup_by_name(db_tok_string);
12849 		t = db_read_token();
12850 		if (t == tNUMBER) {
12851 			tid = db_tok_number;
12852 			valid = true;
12853 		}
12854 	}
12855 	db_radix = radix;
12856 	db_skip_to_eol();
12857 	if (!valid) {
12858 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
12859 		return;
12860 	}
12861 
12862 	if (dev == NULL) {
12863 		db_printf("device not found\n");
12864 		return;
12865 	}
12866 	if (tid < 0) {
12867 		db_printf("invalid tid\n");
12868 		return;
12869 	}
12870 
12871 	t4_dump_tcb(device_get_softc(dev), tid);
12872 }
12873 #endif
12874 
12875 static eventhandler_tag vxlan_start_evtag;
12876 static eventhandler_tag vxlan_stop_evtag;
12877 
12878 struct vxlan_evargs {
12879 	struct ifnet *ifp;
12880 	uint16_t port;
12881 };
12882 
12883 static void
12884 enable_vxlan_rx(struct adapter *sc)
12885 {
12886 	int i, rc;
12887 	struct port_info *pi;
12888 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
12889 
12890 	ASSERT_SYNCHRONIZED_OP(sc);
12891 
12892 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
12893 	    F_VXLAN_EN);
12894 	for_each_port(sc, i) {
12895 		pi = sc->port[i];
12896 		if (pi->vxlan_tcam_entry == true)
12897 			continue;
12898 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
12899 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
12900 		    true);
12901 		if (rc < 0) {
12902 			rc = -rc;
12903 			CH_ERR(&pi->vi[0],
12904 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
12905 		} else {
12906 			MPASS(rc == sc->rawf_base + pi->port_id);
12907 			pi->vxlan_tcam_entry = true;
12908 		}
12909 	}
12910 }
12911 
12912 static void
12913 t4_vxlan_start(struct adapter *sc, void *arg)
12914 {
12915 	struct vxlan_evargs *v = arg;
12916 
12917 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
12918 		return;
12919 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
12920 		return;
12921 
12922 	if (sc->vxlan_refcount == 0) {
12923 		sc->vxlan_port = v->port;
12924 		sc->vxlan_refcount = 1;
12925 		if (!hw_off_limits(sc))
12926 			enable_vxlan_rx(sc);
12927 	} else if (sc->vxlan_port == v->port) {
12928 		sc->vxlan_refcount++;
12929 	} else {
12930 		CH_ERR(sc, "VXLAN already configured on port  %d; "
12931 		    "ignoring attempt to configure it on port %d\n",
12932 		    sc->vxlan_port, v->port);
12933 	}
12934 	end_synchronized_op(sc, 0);
12935 }
12936 
12937 static void
12938 t4_vxlan_stop(struct adapter *sc, void *arg)
12939 {
12940 	struct vxlan_evargs *v = arg;
12941 
12942 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
12943 		return;
12944 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
12945 		return;
12946 
12947 	/*
12948 	 * VXLANs may have been configured before the driver was loaded so we
12949 	 * may see more stops than starts.  This is not handled cleanly but at
12950 	 * least we keep the refcount sane.
12951 	 */
12952 	if (sc->vxlan_port != v->port)
12953 		goto done;
12954 	if (sc->vxlan_refcount == 0) {
12955 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
12956 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
12957 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
12958 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
12959 done:
12960 	end_synchronized_op(sc, 0);
12961 }
12962 
12963 static void
12964 t4_vxlan_start_handler(void *arg __unused, struct ifnet *ifp,
12965     sa_family_t family, u_int port)
12966 {
12967 	struct vxlan_evargs v;
12968 
12969 	MPASS(family == AF_INET || family == AF_INET6);
12970 	v.ifp = ifp;
12971 	v.port = port;
12972 
12973 	t4_iterate(t4_vxlan_start, &v);
12974 }
12975 
12976 static void
12977 t4_vxlan_stop_handler(void *arg __unused, struct ifnet *ifp, sa_family_t family,
12978     u_int port)
12979 {
12980 	struct vxlan_evargs v;
12981 
12982 	MPASS(family == AF_INET || family == AF_INET6);
12983 	v.ifp = ifp;
12984 	v.port = port;
12985 
12986 	t4_iterate(t4_vxlan_stop, &v);
12987 }
12988 
12989 
12990 static struct sx mlu;	/* mod load unload */
12991 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
12992 
12993 static int
12994 mod_event(module_t mod, int cmd, void *arg)
12995 {
12996 	int rc = 0;
12997 	static int loaded = 0;
12998 
12999 	switch (cmd) {
13000 	case MOD_LOAD:
13001 		sx_xlock(&mlu);
13002 		if (loaded++ == 0) {
13003 			t4_sge_modload();
13004 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13005 			    t4_filter_rpl, CPL_COOKIE_FILTER);
13006 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
13007 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
13008 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
13009 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
13010 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13011 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
13012 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
13013 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
13014 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
13015 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
13016 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
13017 			    do_smt_write_rpl);
13018 			sx_init(&t4_list_lock, "T4/T5 adapters");
13019 			SLIST_INIT(&t4_list);
13020 			callout_init(&fatal_callout, 1);
13021 #ifdef TCP_OFFLOAD
13022 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
13023 			SLIST_INIT(&t4_uld_list);
13024 #endif
13025 #ifdef INET6
13026 			t4_clip_modload();
13027 #endif
13028 #ifdef KERN_TLS
13029 			t6_ktls_modload();
13030 #endif
13031 			t4_tracer_modload();
13032 			tweak_tunables();
13033 			vxlan_start_evtag =
13034 			    EVENTHANDLER_REGISTER(vxlan_start,
13035 				t4_vxlan_start_handler, NULL,
13036 				EVENTHANDLER_PRI_ANY);
13037 			vxlan_stop_evtag =
13038 			    EVENTHANDLER_REGISTER(vxlan_stop,
13039 				t4_vxlan_stop_handler, NULL,
13040 				EVENTHANDLER_PRI_ANY);
13041 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
13042 			    taskqueue_thread_enqueue, &reset_tq);
13043 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
13044 			    "t4_rst_thr");
13045 		}
13046 		sx_xunlock(&mlu);
13047 		break;
13048 
13049 	case MOD_UNLOAD:
13050 		sx_xlock(&mlu);
13051 		if (--loaded == 0) {
13052 			int tries;
13053 
13054 			taskqueue_free(reset_tq);
13055 			sx_slock(&t4_list_lock);
13056 			if (!SLIST_EMPTY(&t4_list)) {
13057 				rc = EBUSY;
13058 				sx_sunlock(&t4_list_lock);
13059 				goto done_unload;
13060 			}
13061 #ifdef TCP_OFFLOAD
13062 			sx_slock(&t4_uld_list_lock);
13063 			if (!SLIST_EMPTY(&t4_uld_list)) {
13064 				rc = EBUSY;
13065 				sx_sunlock(&t4_uld_list_lock);
13066 				sx_sunlock(&t4_list_lock);
13067 				goto done_unload;
13068 			}
13069 #endif
13070 			tries = 0;
13071 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13072 				uprintf("%ju clusters with custom free routine "
13073 				    "still is use.\n", t4_sge_extfree_refs());
13074 				pause("t4unload", 2 * hz);
13075 			}
13076 #ifdef TCP_OFFLOAD
13077 			sx_sunlock(&t4_uld_list_lock);
13078 #endif
13079 			sx_sunlock(&t4_list_lock);
13080 
13081 			if (t4_sge_extfree_refs() == 0) {
13082 				EVENTHANDLER_DEREGISTER(vxlan_start,
13083 				    vxlan_start_evtag);
13084 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13085 				    vxlan_stop_evtag);
13086 				t4_tracer_modunload();
13087 #ifdef KERN_TLS
13088 				t6_ktls_modunload();
13089 #endif
13090 #ifdef INET6
13091 				t4_clip_modunload();
13092 #endif
13093 #ifdef TCP_OFFLOAD
13094 				sx_destroy(&t4_uld_list_lock);
13095 #endif
13096 				sx_destroy(&t4_list_lock);
13097 				t4_sge_modunload();
13098 				loaded = 0;
13099 			} else {
13100 				rc = EBUSY;
13101 				loaded++;	/* undo earlier decrement */
13102 			}
13103 		}
13104 done_unload:
13105 		sx_xunlock(&mlu);
13106 		break;
13107 	}
13108 
13109 	return (rc);
13110 }
13111 
13112 static devclass_t t4_devclass, t5_devclass, t6_devclass;
13113 static devclass_t cxgbe_devclass, cxl_devclass, cc_devclass;
13114 static devclass_t vcxgbe_devclass, vcxl_devclass, vcc_devclass;
13115 
13116 DRIVER_MODULE(t4nex, pci, t4_driver, t4_devclass, mod_event, 0);
13117 MODULE_VERSION(t4nex, 1);
13118 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13119 #ifdef DEV_NETMAP
13120 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13121 #endif /* DEV_NETMAP */
13122 
13123 DRIVER_MODULE(t5nex, pci, t5_driver, t5_devclass, mod_event, 0);
13124 MODULE_VERSION(t5nex, 1);
13125 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13126 #ifdef DEV_NETMAP
13127 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13128 #endif /* DEV_NETMAP */
13129 
13130 DRIVER_MODULE(t6nex, pci, t6_driver, t6_devclass, mod_event, 0);
13131 MODULE_VERSION(t6nex, 1);
13132 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13133 #ifdef DEV_NETMAP
13134 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13135 #endif /* DEV_NETMAP */
13136 
13137 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, cxgbe_devclass, 0, 0);
13138 MODULE_VERSION(cxgbe, 1);
13139 
13140 DRIVER_MODULE(cxl, t5nex, cxl_driver, cxl_devclass, 0, 0);
13141 MODULE_VERSION(cxl, 1);
13142 
13143 DRIVER_MODULE(cc, t6nex, cc_driver, cc_devclass, 0, 0);
13144 MODULE_VERSION(cc, 1);
13145 
13146 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, vcxgbe_devclass, 0, 0);
13147 MODULE_VERSION(vcxgbe, 1);
13148 
13149 DRIVER_MODULE(vcxl, cxl, vcxl_driver, vcxl_devclass, 0, 0);
13150 MODULE_VERSION(vcxl, 1);
13151 
13152 DRIVER_MODULE(vcc, cc, vcc_driver, vcc_devclass, 0, 0);
13153 MODULE_VERSION(vcc, 1);
13154