xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision dd41de95a84d979615a2ef11df6850622bf6184e)
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_str(device_t, device_t, char *, size_t);
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_str, t4_child_location_str),
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_str, t4_child_location_str),
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_str, t4_child_location_str),
219 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
220 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
221 
222 	DEVMETHOD(t4_is_main_ready,	t4_ready),
223 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
224 
225 	DEVMETHOD_END
226 };
227 static driver_t t6_driver = {
228 	"t6nex",
229 	t6_methods,
230 	sizeof(struct adapter)
231 };
232 
233 
234 /* T6 port (cc) interface */
235 static driver_t cc_driver = {
236 	"cc",
237 	cxgbe_methods,
238 	sizeof(struct port_info)
239 };
240 
241 /* T6 VI (vcc) interface */
242 static driver_t vcc_driver = {
243 	"vcc",
244 	vcxgbe_methods,
245 	sizeof(struct vi_info)
246 };
247 
248 /* ifnet interface */
249 static void cxgbe_init(void *);
250 static int cxgbe_ioctl(struct ifnet *, unsigned long, caddr_t);
251 static int cxgbe_transmit(struct ifnet *, struct mbuf *);
252 static void cxgbe_qflush(struct ifnet *);
253 #if defined(KERN_TLS) || defined(RATELIMIT)
254 static int cxgbe_snd_tag_alloc(struct ifnet *, union if_snd_tag_alloc_params *,
255     struct m_snd_tag **);
256 static int cxgbe_snd_tag_modify(struct m_snd_tag *,
257     union if_snd_tag_modify_params *);
258 static int cxgbe_snd_tag_query(struct m_snd_tag *,
259     union if_snd_tag_query_params *);
260 static void cxgbe_snd_tag_free(struct m_snd_tag *);
261 #endif
262 
263 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
264 
265 /*
266  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
267  * then ADAPTER_LOCK, then t4_uld_list_lock.
268  */
269 static struct sx t4_list_lock;
270 SLIST_HEAD(, adapter) t4_list;
271 #ifdef TCP_OFFLOAD
272 static struct sx t4_uld_list_lock;
273 SLIST_HEAD(, uld_info) t4_uld_list;
274 #endif
275 
276 /*
277  * Tunables.  See tweak_tunables() too.
278  *
279  * Each tunable is set to a default value here if it's known at compile-time.
280  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
281  * provide a reasonable default (upto n) when the driver is loaded.
282  *
283  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
284  * T5 are under hw.cxl.
285  */
286 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
287     "cxgbe(4) parameters");
288 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
289     "cxgbe(4) T5+ parameters");
290 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
291     "cxgbe(4) TOE parameters");
292 
293 /*
294  * Number of queues for tx and rx, NIC and offload.
295  */
296 #define NTXQ 16
297 int t4_ntxq = -NTXQ;
298 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
299     "Number of TX queues per port");
300 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);	/* Old name, undocumented */
301 
302 #define NRXQ 8
303 int t4_nrxq = -NRXQ;
304 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
305     "Number of RX queues per port");
306 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);	/* Old name, undocumented */
307 
308 #define NTXQ_VI 1
309 static int t4_ntxq_vi = -NTXQ_VI;
310 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
311     "Number of TX queues per VI");
312 
313 #define NRXQ_VI 1
314 static int t4_nrxq_vi = -NRXQ_VI;
315 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
316     "Number of RX queues per VI");
317 
318 static int t4_rsrv_noflowq = 0;
319 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
320     0, "Reserve TX queue 0 of each VI for non-flowid packets");
321 
322 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
323 #define NOFLDTXQ 8
324 static int t4_nofldtxq = -NOFLDTXQ;
325 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
326     "Number of offload TX queues per port");
327 
328 #define NOFLDRXQ 2
329 static int t4_nofldrxq = -NOFLDRXQ;
330 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
331     "Number of offload RX queues per port");
332 
333 #define NOFLDTXQ_VI 1
334 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
335 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
336     "Number of offload TX queues per VI");
337 
338 #define NOFLDRXQ_VI 1
339 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
340 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
341     "Number of offload RX queues per VI");
342 
343 #define TMR_IDX_OFLD 1
344 int t4_tmr_idx_ofld = TMR_IDX_OFLD;
345 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
346     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
347 
348 #define PKTC_IDX_OFLD (-1)
349 int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
350 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
351     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
352 
353 /* 0 means chip/fw default, non-zero number is value in microseconds */
354 static u_long t4_toe_keepalive_idle = 0;
355 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
356     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
357 
358 /* 0 means chip/fw default, non-zero number is value in microseconds */
359 static u_long t4_toe_keepalive_interval = 0;
360 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
361     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
362 
363 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
364 static int t4_toe_keepalive_count = 0;
365 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
366     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
367 
368 /* 0 means chip/fw default, non-zero number is value in microseconds */
369 static u_long t4_toe_rexmt_min = 0;
370 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
371     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
372 
373 /* 0 means chip/fw default, non-zero number is value in microseconds */
374 static u_long t4_toe_rexmt_max = 0;
375 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
376     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
377 
378 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
379 static int t4_toe_rexmt_count = 0;
380 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
381     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
382 
383 /* -1 means chip/fw default, other values are raw backoff values to use */
384 static int t4_toe_rexmt_backoff[16] = {
385 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
386 };
387 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
388     CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
389     "cxgbe(4) TOE retransmit backoff values");
390 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
391     &t4_toe_rexmt_backoff[0], 0, "");
392 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
393     &t4_toe_rexmt_backoff[1], 0, "");
394 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
395     &t4_toe_rexmt_backoff[2], 0, "");
396 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
397     &t4_toe_rexmt_backoff[3], 0, "");
398 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
399     &t4_toe_rexmt_backoff[4], 0, "");
400 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
401     &t4_toe_rexmt_backoff[5], 0, "");
402 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
403     &t4_toe_rexmt_backoff[6], 0, "");
404 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
405     &t4_toe_rexmt_backoff[7], 0, "");
406 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
407     &t4_toe_rexmt_backoff[8], 0, "");
408 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
409     &t4_toe_rexmt_backoff[9], 0, "");
410 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
411     &t4_toe_rexmt_backoff[10], 0, "");
412 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
413     &t4_toe_rexmt_backoff[11], 0, "");
414 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
415     &t4_toe_rexmt_backoff[12], 0, "");
416 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
417     &t4_toe_rexmt_backoff[13], 0, "");
418 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
419     &t4_toe_rexmt_backoff[14], 0, "");
420 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
421     &t4_toe_rexmt_backoff[15], 0, "");
422 
423 static int t4_toe_tls_rx_timeout = 5;
424 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, tls_rx_timeout, CTLFLAG_RDTUN,
425     &t4_toe_tls_rx_timeout, 0,
426     "Timeout in seconds to downgrade TLS sockets to plain TOE");
427 #endif
428 
429 #ifdef DEV_NETMAP
430 #define NN_MAIN_VI	(1 << 0)	/* Native netmap on the main VI */
431 #define NN_EXTRA_VI	(1 << 1)	/* Native netmap on the extra VI(s) */
432 static int t4_native_netmap = NN_EXTRA_VI;
433 SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
434     0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
435 
436 #define NNMTXQ 8
437 static int t4_nnmtxq = -NNMTXQ;
438 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
439     "Number of netmap TX queues");
440 
441 #define NNMRXQ 8
442 static int t4_nnmrxq = -NNMRXQ;
443 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
444     "Number of netmap RX queues");
445 
446 #define NNMTXQ_VI 2
447 static int t4_nnmtxq_vi = -NNMTXQ_VI;
448 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
449     "Number of netmap TX queues per VI");
450 
451 #define NNMRXQ_VI 2
452 static int t4_nnmrxq_vi = -NNMRXQ_VI;
453 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
454     "Number of netmap RX queues per VI");
455 #endif
456 
457 /*
458  * Holdoff parameters for ports.
459  */
460 #define TMR_IDX 1
461 int t4_tmr_idx = TMR_IDX;
462 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
463     0, "Holdoff timer index");
464 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);	/* Old name */
465 
466 #define PKTC_IDX (-1)
467 int t4_pktc_idx = PKTC_IDX;
468 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
469     0, "Holdoff packet counter index");
470 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);	/* Old name */
471 
472 /*
473  * Size (# of entries) of each tx and rx queue.
474  */
475 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
476 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
477     "Number of descriptors in each TX queue");
478 
479 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
480 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
481     "Number of descriptors in each RX queue");
482 
483 /*
484  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
485  */
486 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
487 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
488     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
489 
490 /*
491  * Configuration file.  All the _CF names here are special.
492  */
493 #define DEFAULT_CF	"default"
494 #define BUILTIN_CF	"built-in"
495 #define FLASH_CF	"flash"
496 #define UWIRE_CF	"uwire"
497 #define FPGA_CF		"fpga"
498 static char t4_cfg_file[32] = DEFAULT_CF;
499 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
500     sizeof(t4_cfg_file), "Firmware configuration file");
501 
502 /*
503  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
504  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
505  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
506  *            mark or when signalled to do so, 0 to never emit PAUSE.
507  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
508  *                 negotiated settings will override rx_pause/tx_pause.
509  *                 Otherwise rx_pause/tx_pause are applied forcibly.
510  */
511 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
512 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
513     &t4_pause_settings, 0,
514     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
515 
516 /*
517  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
518  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
519  *  0 to disable FEC.
520  */
521 static int t4_fec = -1;
522 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
523     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
524 
525 /*
526  * Link autonegotiation.
527  * -1 to run with the firmware default.
528  *  0 to disable.
529  *  1 to enable.
530  */
531 static int t4_autoneg = -1;
532 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
533     "Link autonegotiation");
534 
535 /*
536  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
537  * encouraged respectively).  '-n' is the same as 'n' except the firmware
538  * version used in the checks is read from the firmware bundled with the driver.
539  */
540 static int t4_fw_install = 1;
541 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
542     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
543 
544 /*
545  * ASIC features that will be used.  Disable the ones you don't want so that the
546  * chip resources aren't wasted on features that will not be used.
547  */
548 static int t4_nbmcaps_allowed = 0;
549 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
550     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
551 
552 static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
553 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
554     &t4_linkcaps_allowed, 0, "Default link capabilities");
555 
556 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
557     FW_CAPS_CONFIG_SWITCH_EGRESS;
558 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
559     &t4_switchcaps_allowed, 0, "Default switch capabilities");
560 
561 #ifdef RATELIMIT
562 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
563 	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
564 #else
565 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
566 	FW_CAPS_CONFIG_NIC_HASHFILTER;
567 #endif
568 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
569     &t4_niccaps_allowed, 0, "Default NIC capabilities");
570 
571 static int t4_toecaps_allowed = -1;
572 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
573     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
574 
575 static int t4_rdmacaps_allowed = -1;
576 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
577     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
578 
579 static int t4_cryptocaps_allowed = -1;
580 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
581     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
582 
583 static int t4_iscsicaps_allowed = -1;
584 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
585     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
586 
587 static int t4_fcoecaps_allowed = 0;
588 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
589     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
590 
591 static int t5_write_combine = 0;
592 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
593     0, "Use WC instead of UC for BAR2");
594 
595 static int t4_num_vis = 1;
596 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
597     "Number of VIs per port");
598 
599 /*
600  * PCIe Relaxed Ordering.
601  * -1: driver should figure out a good value.
602  * 0: disable RO.
603  * 1: enable RO.
604  * 2: leave RO alone.
605  */
606 static int pcie_relaxed_ordering = -1;
607 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
608     &pcie_relaxed_ordering, 0,
609     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
610 
611 static int t4_panic_on_fatal_err = 0;
612 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
613     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
614 
615 static int t4_reset_on_fatal_err = 0;
616 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
617     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
618 
619 static int t4_tx_vm_wr = 0;
620 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
621     "Use VM work requests to transmit packets.");
622 
623 /*
624  * Set to non-zero to enable the attack filter.  A packet that matches any of
625  * these conditions will get dropped on ingress:
626  * 1) IP && source address == destination address.
627  * 2) TCP/IP && source address is not a unicast address.
628  * 3) TCP/IP && destination address is not a unicast address.
629  * 4) IP && source address is loopback (127.x.y.z).
630  * 5) IP && destination address is loopback (127.x.y.z).
631  * 6) IPv6 && source address == destination address.
632  * 7) IPv6 && source address is not a unicast address.
633  * 8) IPv6 && source address is loopback (::1/128).
634  * 9) IPv6 && destination address is loopback (::1/128).
635  * 10) IPv6 && source address is unspecified (::/128).
636  * 11) IPv6 && destination address is unspecified (::/128).
637  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
638  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
639  */
640 static int t4_attack_filter = 0;
641 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
642     &t4_attack_filter, 0, "Drop suspicious traffic");
643 
644 static int t4_drop_ip_fragments = 0;
645 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
646     &t4_drop_ip_fragments, 0, "Drop IP fragments");
647 
648 static int t4_drop_pkts_with_l2_errors = 1;
649 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
650     &t4_drop_pkts_with_l2_errors, 0,
651     "Drop all frames with Layer 2 length or checksum errors");
652 
653 static int t4_drop_pkts_with_l3_errors = 0;
654 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
655     &t4_drop_pkts_with_l3_errors, 0,
656     "Drop all frames with IP version, length, or checksum errors");
657 
658 static int t4_drop_pkts_with_l4_errors = 0;
659 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
660     &t4_drop_pkts_with_l4_errors, 0,
661     "Drop all frames with Layer 4 length, checksum, or other errors");
662 
663 #ifdef TCP_OFFLOAD
664 /*
665  * TOE tunables.
666  */
667 static int t4_cop_managed_offloading = 0;
668 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
669     &t4_cop_managed_offloading, 0,
670     "COP (Connection Offload Policy) controls all TOE offload");
671 #endif
672 
673 #ifdef KERN_TLS
674 /*
675  * This enables KERN_TLS for all adapters if set.
676  */
677 static int t4_kern_tls = 0;
678 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
679     "Enable KERN_TLS mode for all supported adapters");
680 
681 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
682     "cxgbe(4) KERN_TLS parameters");
683 
684 static int t4_tls_inline_keys = 0;
685 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
686     &t4_tls_inline_keys, 0,
687     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
688     "in card memory.");
689 
690 static int t4_tls_combo_wrs = 0;
691 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
692     0, "Attempt to combine TCB field updates with TLS record work requests.");
693 #endif
694 
695 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
696 static int vi_mac_funcs[] = {
697 	FW_VI_FUNC_ETH,
698 	FW_VI_FUNC_OFLD,
699 	FW_VI_FUNC_IWARP,
700 	FW_VI_FUNC_OPENISCSI,
701 	FW_VI_FUNC_OPENFCOE,
702 	FW_VI_FUNC_FOISCSI,
703 	FW_VI_FUNC_FOFCOE,
704 };
705 
706 struct intrs_and_queues {
707 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
708 	uint16_t num_vis;	/* number of VIs for each port */
709 	uint16_t nirq;		/* Total # of vectors */
710 	uint16_t ntxq;		/* # of NIC txq's for each port */
711 	uint16_t nrxq;		/* # of NIC rxq's for each port */
712 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
713 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
714 	uint16_t nnmtxq;	/* # of netmap txq's */
715 	uint16_t nnmrxq;	/* # of netmap rxq's */
716 
717 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
718 	uint16_t ntxq_vi;	/* # of NIC txq's */
719 	uint16_t nrxq_vi;	/* # of NIC rxq's */
720 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
721 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
722 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
723 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
724 };
725 
726 static void setup_memwin(struct adapter *);
727 static void position_memwin(struct adapter *, int, uint32_t);
728 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
729 static int fwmtype_to_hwmtype(int);
730 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
731     uint32_t *);
732 static int fixup_devlog_params(struct adapter *);
733 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
734 static int contact_firmware(struct adapter *);
735 static int partition_resources(struct adapter *);
736 static int get_params__pre_init(struct adapter *);
737 static int set_params__pre_init(struct adapter *);
738 static int get_params__post_init(struct adapter *);
739 static int set_params__post_init(struct adapter *);
740 static void t4_set_desc(struct adapter *);
741 static bool fixed_ifmedia(struct port_info *);
742 static void build_medialist(struct port_info *);
743 static void init_link_config(struct port_info *);
744 static int fixup_link_config(struct port_info *);
745 static int apply_link_config(struct port_info *);
746 static int cxgbe_init_synchronized(struct vi_info *);
747 static int cxgbe_uninit_synchronized(struct vi_info *);
748 static int adapter_full_init(struct adapter *);
749 static void adapter_full_uninit(struct adapter *);
750 static int vi_full_init(struct vi_info *);
751 static void vi_full_uninit(struct vi_info *);
752 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
753 static void quiesce_txq(struct sge_txq *);
754 static void quiesce_wrq(struct sge_wrq *);
755 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
756 static void quiesce_vi(struct vi_info *);
757 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
758     driver_intr_t *, void *, char *);
759 static int t4_free_irq(struct adapter *, struct irq *);
760 static void t4_init_atid_table(struct adapter *);
761 static void t4_free_atid_table(struct adapter *);
762 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
763 static void vi_refresh_stats(struct vi_info *);
764 static void cxgbe_refresh_stats(struct vi_info *);
765 static void cxgbe_tick(void *);
766 static void vi_tick(void *);
767 static void cxgbe_sysctls(struct port_info *);
768 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
769 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
770 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
771 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
772 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
773 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
774 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
775 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
776 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
777 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
778 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
779 static int sysctl_fec(SYSCTL_HANDLER_ARGS);
780 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
781 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
782 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
783 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
784 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
785 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
786 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
787 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
788 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
789 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
790 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
791 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
792 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
793 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
794 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
795 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
796 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
797 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
798 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
799 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
800 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
801 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
802 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
803 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
804 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
805 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
806 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
807 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
808 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
809 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
810 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
811 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
812 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
813 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
814 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
815 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
816 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
817 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
818 #ifdef TCP_OFFLOAD
819 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
820 static int sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS);
821 static int sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS);
822 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
823 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
824 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
825 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
826 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
827 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
828 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
829 #endif
830 static int get_sge_context(struct adapter *, struct t4_sge_context *);
831 static int load_fw(struct adapter *, struct t4_data *);
832 static int load_cfg(struct adapter *, struct t4_data *);
833 static int load_boot(struct adapter *, struct t4_bootrom *);
834 static int load_bootcfg(struct adapter *, struct t4_data *);
835 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
836 static void free_offload_policy(struct t4_offload_policy *);
837 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
838 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
839 static int read_i2c(struct adapter *, struct t4_i2c_data *);
840 static int clear_stats(struct adapter *, u_int);
841 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
842 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
843 #ifdef TCP_OFFLOAD
844 static int toe_capability(struct vi_info *, bool);
845 static void t4_async_event(void *, int);
846 #endif
847 #ifdef KERN_TLS
848 static int ktls_capability(struct adapter *, bool);
849 #endif
850 static int mod_event(module_t, int, void *);
851 static int notify_siblings(device_t, int);
852 static uint64_t vi_get_counter(struct ifnet *, ift_counter);
853 static uint64_t cxgbe_get_counter(struct ifnet *, ift_counter);
854 static void enable_vxlan_rx(struct adapter *);
855 static void reset_adapter(void *, int);
856 
857 struct {
858 	uint16_t device;
859 	char *desc;
860 } t4_pciids[] = {
861 	{0xa000, "Chelsio Terminator 4 FPGA"},
862 	{0x4400, "Chelsio T440-dbg"},
863 	{0x4401, "Chelsio T420-CR"},
864 	{0x4402, "Chelsio T422-CR"},
865 	{0x4403, "Chelsio T440-CR"},
866 	{0x4404, "Chelsio T420-BCH"},
867 	{0x4405, "Chelsio T440-BCH"},
868 	{0x4406, "Chelsio T440-CH"},
869 	{0x4407, "Chelsio T420-SO"},
870 	{0x4408, "Chelsio T420-CX"},
871 	{0x4409, "Chelsio T420-BT"},
872 	{0x440a, "Chelsio T404-BT"},
873 	{0x440e, "Chelsio T440-LP-CR"},
874 }, t5_pciids[] = {
875 	{0xb000, "Chelsio Terminator 5 FPGA"},
876 	{0x5400, "Chelsio T580-dbg"},
877 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
878 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
879 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
880 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
881 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
882 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
883 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
884 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
885 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
886 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
887 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
888 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
889 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
890 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
891 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
892 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
893 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
894 
895 	/* Custom */
896 	{0x5483, "Custom T540-CR"},
897 	{0x5484, "Custom T540-BT"},
898 }, t6_pciids[] = {
899 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
900 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
901 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
902 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
903 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
904 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
905 	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
906 	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
907 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
908 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
909 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
910 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
911 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
912 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
913 	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
914 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
915 
916 	/* Custom */
917 	{0x6480, "Custom T6225-CR"},
918 	{0x6481, "Custom T62100-CR"},
919 	{0x6482, "Custom T6225-CR"},
920 	{0x6483, "Custom T62100-CR"},
921 	{0x6484, "Custom T64100-CR"},
922 	{0x6485, "Custom T6240-SO"},
923 	{0x6486, "Custom T6225-SO-CR"},
924 	{0x6487, "Custom T6225-CR"},
925 };
926 
927 #ifdef TCP_OFFLOAD
928 /*
929  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
930  * be exactly the same for both rxq and ofld_rxq.
931  */
932 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
933 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
934 #endif
935 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
936 
937 static int
938 t4_probe(device_t dev)
939 {
940 	int i;
941 	uint16_t v = pci_get_vendor(dev);
942 	uint16_t d = pci_get_device(dev);
943 	uint8_t f = pci_get_function(dev);
944 
945 	if (v != PCI_VENDOR_ID_CHELSIO)
946 		return (ENXIO);
947 
948 	/* Attach only to PF0 of the FPGA */
949 	if (d == 0xa000 && f != 0)
950 		return (ENXIO);
951 
952 	for (i = 0; i < nitems(t4_pciids); i++) {
953 		if (d == t4_pciids[i].device) {
954 			device_set_desc(dev, t4_pciids[i].desc);
955 			return (BUS_PROBE_DEFAULT);
956 		}
957 	}
958 
959 	return (ENXIO);
960 }
961 
962 static int
963 t5_probe(device_t dev)
964 {
965 	int i;
966 	uint16_t v = pci_get_vendor(dev);
967 	uint16_t d = pci_get_device(dev);
968 	uint8_t f = pci_get_function(dev);
969 
970 	if (v != PCI_VENDOR_ID_CHELSIO)
971 		return (ENXIO);
972 
973 	/* Attach only to PF0 of the FPGA */
974 	if (d == 0xb000 && f != 0)
975 		return (ENXIO);
976 
977 	for (i = 0; i < nitems(t5_pciids); i++) {
978 		if (d == t5_pciids[i].device) {
979 			device_set_desc(dev, t5_pciids[i].desc);
980 			return (BUS_PROBE_DEFAULT);
981 		}
982 	}
983 
984 	return (ENXIO);
985 }
986 
987 static int
988 t6_probe(device_t dev)
989 {
990 	int i;
991 	uint16_t v = pci_get_vendor(dev);
992 	uint16_t d = pci_get_device(dev);
993 
994 	if (v != PCI_VENDOR_ID_CHELSIO)
995 		return (ENXIO);
996 
997 	for (i = 0; i < nitems(t6_pciids); i++) {
998 		if (d == t6_pciids[i].device) {
999 			device_set_desc(dev, t6_pciids[i].desc);
1000 			return (BUS_PROBE_DEFAULT);
1001 		}
1002 	}
1003 
1004 	return (ENXIO);
1005 }
1006 
1007 static void
1008 t5_attribute_workaround(device_t dev)
1009 {
1010 	device_t root_port;
1011 	uint32_t v;
1012 
1013 	/*
1014 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1015 	 * Ordering attributes when replying to a TLP from a Root
1016 	 * Port.  As a workaround, find the parent Root Port and
1017 	 * disable No Snoop and Relaxed Ordering.  Note that this
1018 	 * affects all devices under this root port.
1019 	 */
1020 	root_port = pci_find_pcie_root_port(dev);
1021 	if (root_port == NULL) {
1022 		device_printf(dev, "Unable to find parent root port\n");
1023 		return;
1024 	}
1025 
1026 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1027 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1028 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1029 	    0)
1030 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1031 		    device_get_nameunit(root_port));
1032 }
1033 
1034 static const struct devnames devnames[] = {
1035 	{
1036 		.nexus_name = "t4nex",
1037 		.ifnet_name = "cxgbe",
1038 		.vi_ifnet_name = "vcxgbe",
1039 		.pf03_drv_name = "t4iov",
1040 		.vf_nexus_name = "t4vf",
1041 		.vf_ifnet_name = "cxgbev"
1042 	}, {
1043 		.nexus_name = "t5nex",
1044 		.ifnet_name = "cxl",
1045 		.vi_ifnet_name = "vcxl",
1046 		.pf03_drv_name = "t5iov",
1047 		.vf_nexus_name = "t5vf",
1048 		.vf_ifnet_name = "cxlv"
1049 	}, {
1050 		.nexus_name = "t6nex",
1051 		.ifnet_name = "cc",
1052 		.vi_ifnet_name = "vcc",
1053 		.pf03_drv_name = "t6iov",
1054 		.vf_nexus_name = "t6vf",
1055 		.vf_ifnet_name = "ccv"
1056 	}
1057 };
1058 
1059 void
1060 t4_init_devnames(struct adapter *sc)
1061 {
1062 	int id;
1063 
1064 	id = chip_id(sc);
1065 	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1066 		sc->names = &devnames[id - CHELSIO_T4];
1067 	else {
1068 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1069 		sc->names = NULL;
1070 	}
1071 }
1072 
1073 static int
1074 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1075 {
1076 	const char *parent, *name;
1077 	long value;
1078 	int line, unit;
1079 
1080 	line = 0;
1081 	parent = device_get_nameunit(sc->dev);
1082 	name = sc->names->ifnet_name;
1083 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1084 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1085 		    value == pi->port_id)
1086 			return (unit);
1087 	}
1088 	return (-1);
1089 }
1090 
1091 static int
1092 t4_attach(device_t dev)
1093 {
1094 	struct adapter *sc;
1095 	int rc = 0, i, j, rqidx, tqidx, nports;
1096 	struct make_dev_args mda;
1097 	struct intrs_and_queues iaq;
1098 	struct sge *s;
1099 	uint32_t *buf;
1100 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1101 	int ofld_tqidx;
1102 #endif
1103 #ifdef TCP_OFFLOAD
1104 	int ofld_rqidx;
1105 #endif
1106 #ifdef DEV_NETMAP
1107 	int nm_rqidx, nm_tqidx;
1108 #endif
1109 	int num_vis;
1110 
1111 	sc = device_get_softc(dev);
1112 	sc->dev = dev;
1113 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1114 
1115 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1116 		t5_attribute_workaround(dev);
1117 	pci_enable_busmaster(dev);
1118 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1119 		uint32_t v;
1120 
1121 		pci_set_max_read_req(dev, 4096);
1122 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1123 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1124 		if (pcie_relaxed_ordering == 0 &&
1125 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1126 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1127 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1128 		} else if (pcie_relaxed_ordering == 1 &&
1129 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1130 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1131 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1132 		}
1133 	}
1134 
1135 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1136 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1137 	sc->traceq = -1;
1138 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1139 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1140 	    device_get_nameunit(dev));
1141 
1142 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1143 	    device_get_nameunit(dev));
1144 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1145 	t4_add_adapter(sc);
1146 
1147 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1148 	TAILQ_INIT(&sc->sfl);
1149 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1150 
1151 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1152 
1153 	sc->policy = NULL;
1154 	rw_init(&sc->policy_lock, "connection offload policy");
1155 
1156 	callout_init(&sc->ktls_tick, 1);
1157 
1158 #ifdef TCP_OFFLOAD
1159 	TASK_INIT(&sc->async_event_task, 0, t4_async_event, sc);
1160 #endif
1161 
1162 	refcount_init(&sc->vxlan_refcount, 0);
1163 
1164 	TASK_INIT(&sc->reset_task, 0, reset_adapter, sc);
1165 
1166 	sc->ctrlq_oid = SYSCTL_ADD_NODE(device_get_sysctl_ctx(sc->dev),
1167 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1168 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1169 	sc->fwq_oid = SYSCTL_ADD_NODE(device_get_sysctl_ctx(sc->dev),
1170 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1171 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1172 
1173 	rc = t4_map_bars_0_and_4(sc);
1174 	if (rc != 0)
1175 		goto done; /* error message displayed already */
1176 
1177 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1178 
1179 	/* Prepare the adapter for operation. */
1180 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1181 	rc = -t4_prep_adapter(sc, buf);
1182 	free(buf, M_CXGBE);
1183 	if (rc != 0) {
1184 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1185 		goto done;
1186 	}
1187 
1188 	/*
1189 	 * This is the real PF# to which we're attaching.  Works from within PCI
1190 	 * passthrough environments too, where pci_get_function() could return a
1191 	 * different PF# depending on the passthrough configuration.  We need to
1192 	 * use the real PF# in all our communication with the firmware.
1193 	 */
1194 	j = t4_read_reg(sc, A_PL_WHOAMI);
1195 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1196 	sc->mbox = sc->pf;
1197 
1198 	t4_init_devnames(sc);
1199 	if (sc->names == NULL) {
1200 		rc = ENOTSUP;
1201 		goto done; /* error message displayed already */
1202 	}
1203 
1204 	/*
1205 	 * Do this really early, with the memory windows set up even before the
1206 	 * character device.  The userland tool's register i/o and mem read
1207 	 * will work even in "recovery mode".
1208 	 */
1209 	setup_memwin(sc);
1210 	if (t4_init_devlog_params(sc, 0) == 0)
1211 		fixup_devlog_params(sc);
1212 	make_dev_args_init(&mda);
1213 	mda.mda_devsw = &t4_cdevsw;
1214 	mda.mda_uid = UID_ROOT;
1215 	mda.mda_gid = GID_WHEEL;
1216 	mda.mda_mode = 0600;
1217 	mda.mda_si_drv1 = sc;
1218 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1219 	if (rc != 0)
1220 		device_printf(dev, "failed to create nexus char device: %d.\n",
1221 		    rc);
1222 
1223 	/* Go no further if recovery mode has been requested. */
1224 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1225 		device_printf(dev, "recovery mode.\n");
1226 		goto done;
1227 	}
1228 
1229 #if defined(__i386__)
1230 	if ((cpu_feature & CPUID_CX8) == 0) {
1231 		device_printf(dev, "64 bit atomics not available.\n");
1232 		rc = ENOTSUP;
1233 		goto done;
1234 	}
1235 #endif
1236 
1237 	/* Contact the firmware and try to become the master driver. */
1238 	rc = contact_firmware(sc);
1239 	if (rc != 0)
1240 		goto done; /* error message displayed already */
1241 	MPASS(sc->flags & FW_OK);
1242 
1243 	rc = get_params__pre_init(sc);
1244 	if (rc != 0)
1245 		goto done; /* error message displayed already */
1246 
1247 	if (sc->flags & MASTER_PF) {
1248 		rc = partition_resources(sc);
1249 		if (rc != 0)
1250 			goto done; /* error message displayed already */
1251 		t4_intr_clear(sc);
1252 	}
1253 
1254 	rc = get_params__post_init(sc);
1255 	if (rc != 0)
1256 		goto done; /* error message displayed already */
1257 
1258 	rc = set_params__post_init(sc);
1259 	if (rc != 0)
1260 		goto done; /* error message displayed already */
1261 
1262 	rc = t4_map_bar_2(sc);
1263 	if (rc != 0)
1264 		goto done; /* error message displayed already */
1265 
1266 	rc = t4_create_dma_tag(sc);
1267 	if (rc != 0)
1268 		goto done; /* error message displayed already */
1269 
1270 	/*
1271 	 * First pass over all the ports - allocate VIs and initialize some
1272 	 * basic parameters like mac address, port type, etc.
1273 	 */
1274 	for_each_port(sc, i) {
1275 		struct port_info *pi;
1276 
1277 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1278 		sc->port[i] = pi;
1279 
1280 		/* These must be set before t4_port_init */
1281 		pi->adapter = sc;
1282 		pi->port_id = i;
1283 		/*
1284 		 * XXX: vi[0] is special so we can't delay this allocation until
1285 		 * pi->nvi's final value is known.
1286 		 */
1287 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1288 		    M_ZERO | M_WAITOK);
1289 
1290 		/*
1291 		 * Allocate the "main" VI and initialize parameters
1292 		 * like mac addr.
1293 		 */
1294 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1295 		if (rc != 0) {
1296 			device_printf(dev, "unable to initialize port %d: %d\n",
1297 			    i, rc);
1298 			free(pi->vi, M_CXGBE);
1299 			free(pi, M_CXGBE);
1300 			sc->port[i] = NULL;
1301 			goto done;
1302 		}
1303 
1304 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1305 		    device_get_nameunit(dev), i);
1306 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1307 		sc->chan_map[pi->tx_chan] = i;
1308 
1309 		/*
1310 		 * The MPS counter for FCS errors doesn't work correctly on the
1311 		 * T6 so we use the MAC counter here.  Which MAC is in use
1312 		 * depends on the link settings which will be known when the
1313 		 * link comes up.
1314 		 */
1315 		if (is_t6(sc)) {
1316 			pi->fcs_reg = -1;
1317 		} else if (is_t4(sc)) {
1318 			pi->fcs_reg = PORT_REG(pi->tx_chan,
1319 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1320 		} else {
1321 			pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
1322 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1323 		}
1324 		pi->fcs_base = 0;
1325 
1326 		/* All VIs on this port share this media. */
1327 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1328 		    cxgbe_media_status);
1329 
1330 		PORT_LOCK(pi);
1331 		init_link_config(pi);
1332 		fixup_link_config(pi);
1333 		build_medialist(pi);
1334 		if (fixed_ifmedia(pi))
1335 			pi->flags |= FIXED_IFMEDIA;
1336 		PORT_UNLOCK(pi);
1337 
1338 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1339 		    t4_ifnet_unit(sc, pi));
1340 		if (pi->dev == NULL) {
1341 			device_printf(dev,
1342 			    "failed to add device for port %d.\n", i);
1343 			rc = ENXIO;
1344 			goto done;
1345 		}
1346 		pi->vi[0].dev = pi->dev;
1347 		device_set_softc(pi->dev, pi);
1348 	}
1349 
1350 	/*
1351 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1352 	 */
1353 	nports = sc->params.nports;
1354 	rc = cfg_itype_and_nqueues(sc, &iaq);
1355 	if (rc != 0)
1356 		goto done; /* error message displayed already */
1357 
1358 	num_vis = iaq.num_vis;
1359 	sc->intr_type = iaq.intr_type;
1360 	sc->intr_count = iaq.nirq;
1361 
1362 	s = &sc->sge;
1363 	s->nrxq = nports * iaq.nrxq;
1364 	s->ntxq = nports * iaq.ntxq;
1365 	if (num_vis > 1) {
1366 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1367 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1368 	}
1369 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1370 	s->neq += nports;		/* ctrl queues: 1 per port */
1371 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1372 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1373 	if (is_offload(sc) || is_ethoffload(sc)) {
1374 		s->nofldtxq = nports * iaq.nofldtxq;
1375 		if (num_vis > 1)
1376 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1377 		s->neq += s->nofldtxq;
1378 
1379 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1380 		    M_CXGBE, M_ZERO | M_WAITOK);
1381 	}
1382 #endif
1383 #ifdef TCP_OFFLOAD
1384 	if (is_offload(sc)) {
1385 		s->nofldrxq = nports * iaq.nofldrxq;
1386 		if (num_vis > 1)
1387 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1388 		s->neq += s->nofldrxq;	/* free list */
1389 		s->niq += s->nofldrxq;
1390 
1391 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1392 		    M_CXGBE, M_ZERO | M_WAITOK);
1393 	}
1394 #endif
1395 #ifdef DEV_NETMAP
1396 	s->nnmrxq = 0;
1397 	s->nnmtxq = 0;
1398 	if (t4_native_netmap & NN_MAIN_VI) {
1399 		s->nnmrxq += nports * iaq.nnmrxq;
1400 		s->nnmtxq += nports * iaq.nnmtxq;
1401 	}
1402 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1403 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1404 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1405 	}
1406 	s->neq += s->nnmtxq + s->nnmrxq;
1407 	s->niq += s->nnmrxq;
1408 
1409 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1410 	    M_CXGBE, M_ZERO | M_WAITOK);
1411 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1412 	    M_CXGBE, M_ZERO | M_WAITOK);
1413 #endif
1414 	MPASS(s->niq <= s->iqmap_sz);
1415 	MPASS(s->neq <= s->eqmap_sz);
1416 
1417 	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1418 	    M_ZERO | M_WAITOK);
1419 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1420 	    M_ZERO | M_WAITOK);
1421 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1422 	    M_ZERO | M_WAITOK);
1423 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1424 	    M_ZERO | M_WAITOK);
1425 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1426 	    M_ZERO | M_WAITOK);
1427 
1428 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1429 	    M_ZERO | M_WAITOK);
1430 
1431 	t4_init_l2t(sc, M_WAITOK);
1432 	t4_init_smt(sc, M_WAITOK);
1433 	t4_init_tx_sched(sc);
1434 	t4_init_atid_table(sc);
1435 #ifdef RATELIMIT
1436 	t4_init_etid_table(sc);
1437 #endif
1438 #ifdef INET6
1439 	t4_init_clip_table(sc);
1440 #endif
1441 	if (sc->vres.key.size != 0)
1442 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1443 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1444 
1445 	/*
1446 	 * Second pass over the ports.  This time we know the number of rx and
1447 	 * tx queues that each port should get.
1448 	 */
1449 	rqidx = tqidx = 0;
1450 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1451 	ofld_tqidx = 0;
1452 #endif
1453 #ifdef TCP_OFFLOAD
1454 	ofld_rqidx = 0;
1455 #endif
1456 #ifdef DEV_NETMAP
1457 	nm_rqidx = nm_tqidx = 0;
1458 #endif
1459 	for_each_port(sc, i) {
1460 		struct port_info *pi = sc->port[i];
1461 		struct vi_info *vi;
1462 
1463 		if (pi == NULL)
1464 			continue;
1465 
1466 		pi->nvi = num_vis;
1467 		for_each_vi(pi, j, vi) {
1468 			vi->pi = pi;
1469 			vi->adapter = sc;
1470 			vi->first_intr = -1;
1471 			vi->qsize_rxq = t4_qsize_rxq;
1472 			vi->qsize_txq = t4_qsize_txq;
1473 
1474 			vi->first_rxq = rqidx;
1475 			vi->first_txq = tqidx;
1476 			vi->tmr_idx = t4_tmr_idx;
1477 			vi->pktc_idx = t4_pktc_idx;
1478 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1479 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1480 
1481 			rqidx += vi->nrxq;
1482 			tqidx += vi->ntxq;
1483 
1484 			if (j == 0 && vi->ntxq > 1)
1485 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1486 			else
1487 				vi->rsrv_noflowq = 0;
1488 
1489 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1490 			vi->first_ofld_txq = ofld_tqidx;
1491 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1492 			ofld_tqidx += vi->nofldtxq;
1493 #endif
1494 #ifdef TCP_OFFLOAD
1495 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1496 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1497 			vi->first_ofld_rxq = ofld_rqidx;
1498 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1499 
1500 			ofld_rqidx += vi->nofldrxq;
1501 #endif
1502 #ifdef DEV_NETMAP
1503 			vi->first_nm_rxq = nm_rqidx;
1504 			vi->first_nm_txq = nm_tqidx;
1505 			if (j == 0) {
1506 				vi->nnmrxq = iaq.nnmrxq;
1507 				vi->nnmtxq = iaq.nnmtxq;
1508 			} else {
1509 				vi->nnmrxq = iaq.nnmrxq_vi;
1510 				vi->nnmtxq = iaq.nnmtxq_vi;
1511 			}
1512 			nm_rqidx += vi->nnmrxq;
1513 			nm_tqidx += vi->nnmtxq;
1514 #endif
1515 		}
1516 	}
1517 
1518 	rc = t4_setup_intr_handlers(sc);
1519 	if (rc != 0) {
1520 		device_printf(dev,
1521 		    "failed to setup interrupt handlers: %d\n", rc);
1522 		goto done;
1523 	}
1524 
1525 	rc = bus_generic_probe(dev);
1526 	if (rc != 0) {
1527 		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1528 		goto done;
1529 	}
1530 
1531 	/*
1532 	 * Ensure thread-safe mailbox access (in debug builds).
1533 	 *
1534 	 * So far this was the only thread accessing the mailbox but various
1535 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1536 	 * will access the mailbox from different threads.
1537 	 */
1538 	sc->flags |= CHK_MBOX_ACCESS;
1539 
1540 	rc = bus_generic_attach(dev);
1541 	if (rc != 0) {
1542 		device_printf(dev,
1543 		    "failed to attach all child ports: %d\n", rc);
1544 		goto done;
1545 	}
1546 
1547 	device_printf(dev,
1548 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1549 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1550 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1551 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1552 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1553 
1554 	t4_set_desc(sc);
1555 
1556 	notify_siblings(dev, 0);
1557 
1558 done:
1559 	if (rc != 0 && sc->cdev) {
1560 		/* cdev was created and so cxgbetool works; recover that way. */
1561 		device_printf(dev,
1562 		    "error during attach, adapter is now in recovery mode.\n");
1563 		rc = 0;
1564 	}
1565 
1566 	if (rc != 0)
1567 		t4_detach_common(dev);
1568 	else
1569 		t4_sysctls(sc);
1570 
1571 	return (rc);
1572 }
1573 
1574 static int
1575 t4_child_location_str(device_t bus, device_t dev, char *buf, size_t buflen)
1576 {
1577 	struct adapter *sc;
1578 	struct port_info *pi;
1579 	int i;
1580 
1581 	sc = device_get_softc(bus);
1582 	buf[0] = '\0';
1583 	for_each_port(sc, i) {
1584 		pi = sc->port[i];
1585 		if (pi != NULL && pi->dev == dev) {
1586 			snprintf(buf, buflen, "port=%d", pi->port_id);
1587 			break;
1588 		}
1589 	}
1590 	return (0);
1591 }
1592 
1593 static int
1594 t4_ready(device_t dev)
1595 {
1596 	struct adapter *sc;
1597 
1598 	sc = device_get_softc(dev);
1599 	if (sc->flags & FW_OK)
1600 		return (0);
1601 	return (ENXIO);
1602 }
1603 
1604 static int
1605 t4_read_port_device(device_t dev, int port, device_t *child)
1606 {
1607 	struct adapter *sc;
1608 	struct port_info *pi;
1609 
1610 	sc = device_get_softc(dev);
1611 	if (port < 0 || port >= MAX_NPORTS)
1612 		return (EINVAL);
1613 	pi = sc->port[port];
1614 	if (pi == NULL || pi->dev == NULL)
1615 		return (ENXIO);
1616 	*child = pi->dev;
1617 	return (0);
1618 }
1619 
1620 static int
1621 notify_siblings(device_t dev, int detaching)
1622 {
1623 	device_t sibling;
1624 	int error, i;
1625 
1626 	error = 0;
1627 	for (i = 0; i < PCI_FUNCMAX; i++) {
1628 		if (i == pci_get_function(dev))
1629 			continue;
1630 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1631 		    pci_get_slot(dev), i);
1632 		if (sibling == NULL || !device_is_attached(sibling))
1633 			continue;
1634 		if (detaching)
1635 			error = T4_DETACH_CHILD(sibling);
1636 		else
1637 			(void)T4_ATTACH_CHILD(sibling);
1638 		if (error)
1639 			break;
1640 	}
1641 	return (error);
1642 }
1643 
1644 /*
1645  * Idempotent
1646  */
1647 static int
1648 t4_detach(device_t dev)
1649 {
1650 	struct adapter *sc;
1651 	int rc;
1652 
1653 	sc = device_get_softc(dev);
1654 
1655 	rc = notify_siblings(dev, 1);
1656 	if (rc) {
1657 		device_printf(dev,
1658 		    "failed to detach sibling devices: %d\n", rc);
1659 		return (rc);
1660 	}
1661 
1662 	return (t4_detach_common(dev));
1663 }
1664 
1665 int
1666 t4_detach_common(device_t dev)
1667 {
1668 	struct adapter *sc;
1669 	struct port_info *pi;
1670 	int i, rc;
1671 
1672 	sc = device_get_softc(dev);
1673 
1674 	if (sc->cdev) {
1675 		destroy_dev(sc->cdev);
1676 		sc->cdev = NULL;
1677 	}
1678 
1679 	sx_xlock(&t4_list_lock);
1680 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1681 	sx_xunlock(&t4_list_lock);
1682 
1683 	sc->flags &= ~CHK_MBOX_ACCESS;
1684 	if (sc->flags & FULL_INIT_DONE) {
1685 		if (!(sc->flags & IS_VF))
1686 			t4_intr_disable(sc);
1687 	}
1688 
1689 	if (device_is_attached(dev)) {
1690 		rc = bus_generic_detach(dev);
1691 		if (rc) {
1692 			device_printf(dev,
1693 			    "failed to detach child devices: %d\n", rc);
1694 			return (rc);
1695 		}
1696 	}
1697 
1698 #ifdef TCP_OFFLOAD
1699 	taskqueue_drain(taskqueue_thread, &sc->async_event_task);
1700 #endif
1701 
1702 	for (i = 0; i < sc->intr_count; i++)
1703 		t4_free_irq(sc, &sc->irq[i]);
1704 
1705 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1706 		t4_free_tx_sched(sc);
1707 
1708 	for (i = 0; i < MAX_NPORTS; i++) {
1709 		pi = sc->port[i];
1710 		if (pi) {
1711 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1712 			if (pi->dev)
1713 				device_delete_child(dev, pi->dev);
1714 
1715 			mtx_destroy(&pi->pi_lock);
1716 			free(pi->vi, M_CXGBE);
1717 			free(pi, M_CXGBE);
1718 		}
1719 	}
1720 
1721 	device_delete_children(dev);
1722 	adapter_full_uninit(sc);
1723 
1724 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1725 		t4_fw_bye(sc, sc->mbox);
1726 
1727 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1728 		pci_release_msi(dev);
1729 
1730 	if (sc->regs_res)
1731 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1732 		    sc->regs_res);
1733 
1734 	if (sc->udbs_res)
1735 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1736 		    sc->udbs_res);
1737 
1738 	if (sc->msix_res)
1739 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1740 		    sc->msix_res);
1741 
1742 	if (sc->l2t)
1743 		t4_free_l2t(sc->l2t);
1744 	if (sc->smt)
1745 		t4_free_smt(sc->smt);
1746 	t4_free_atid_table(sc);
1747 #ifdef RATELIMIT
1748 	t4_free_etid_table(sc);
1749 #endif
1750 	if (sc->key_map)
1751 		vmem_destroy(sc->key_map);
1752 #ifdef INET6
1753 	t4_destroy_clip_table(sc);
1754 #endif
1755 
1756 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1757 	free(sc->sge.ofld_txq, M_CXGBE);
1758 #endif
1759 #ifdef TCP_OFFLOAD
1760 	free(sc->sge.ofld_rxq, M_CXGBE);
1761 #endif
1762 #ifdef DEV_NETMAP
1763 	free(sc->sge.nm_rxq, M_CXGBE);
1764 	free(sc->sge.nm_txq, M_CXGBE);
1765 #endif
1766 	free(sc->irq, M_CXGBE);
1767 	free(sc->sge.rxq, M_CXGBE);
1768 	free(sc->sge.txq, M_CXGBE);
1769 	free(sc->sge.ctrlq, M_CXGBE);
1770 	free(sc->sge.iqmap, M_CXGBE);
1771 	free(sc->sge.eqmap, M_CXGBE);
1772 	free(sc->tids.ftid_tab, M_CXGBE);
1773 	free(sc->tids.hpftid_tab, M_CXGBE);
1774 	free_hftid_hash(&sc->tids);
1775 	free(sc->tids.tid_tab, M_CXGBE);
1776 	free(sc->tt.tls_rx_ports, M_CXGBE);
1777 	t4_destroy_dma_tag(sc);
1778 
1779 	callout_drain(&sc->ktls_tick);
1780 	callout_drain(&sc->sfl_callout);
1781 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1782 		mtx_destroy(&sc->tids.ftid_lock);
1783 		cv_destroy(&sc->tids.ftid_cv);
1784 	}
1785 	if (mtx_initialized(&sc->tids.atid_lock))
1786 		mtx_destroy(&sc->tids.atid_lock);
1787 	if (mtx_initialized(&sc->ifp_lock))
1788 		mtx_destroy(&sc->ifp_lock);
1789 
1790 	if (rw_initialized(&sc->policy_lock)) {
1791 		rw_destroy(&sc->policy_lock);
1792 #ifdef TCP_OFFLOAD
1793 		if (sc->policy != NULL)
1794 			free_offload_policy(sc->policy);
1795 #endif
1796 	}
1797 
1798 	for (i = 0; i < NUM_MEMWIN; i++) {
1799 		struct memwin *mw = &sc->memwin[i];
1800 
1801 		if (rw_initialized(&mw->mw_lock))
1802 			rw_destroy(&mw->mw_lock);
1803 	}
1804 
1805 	mtx_destroy(&sc->sfl_lock);
1806 	mtx_destroy(&sc->reg_lock);
1807 	mtx_destroy(&sc->sc_lock);
1808 
1809 	bzero(sc, sizeof(*sc));
1810 
1811 	return (0);
1812 }
1813 
1814 static inline bool
1815 ok_to_reset(struct adapter *sc)
1816 {
1817 	struct tid_info *t = &sc->tids;
1818 	struct port_info *pi;
1819 	struct vi_info *vi;
1820 	int i, j;
1821 	const int caps = IFCAP_TOE | IFCAP_TXTLS | IFCAP_NETMAP | IFCAP_TXRTLMT;
1822 
1823 	ASSERT_SYNCHRONIZED_OP(sc);
1824 	MPASS(!(sc->flags & IS_VF));
1825 
1826 	for_each_port(sc, i) {
1827 		pi = sc->port[i];
1828 		for_each_vi(pi, j, vi) {
1829 			if (vi->ifp->if_capenable & caps)
1830 				return (false);
1831 		}
1832 	}
1833 
1834 	if (atomic_load_int(&t->tids_in_use) > 0)
1835 		return (false);
1836 	if (atomic_load_int(&t->stids_in_use) > 0)
1837 		return (false);
1838 	if (atomic_load_int(&t->atids_in_use) > 0)
1839 		return (false);
1840 	if (atomic_load_int(&t->ftids_in_use) > 0)
1841 		return (false);
1842 	if (atomic_load_int(&t->hpftids_in_use) > 0)
1843 		return (false);
1844 	if (atomic_load_int(&t->etids_in_use) > 0)
1845 		return (false);
1846 
1847 	return (true);
1848 }
1849 
1850 static int
1851 t4_suspend(device_t dev)
1852 {
1853 	struct adapter *sc = device_get_softc(dev);
1854 	struct port_info *pi;
1855 	struct vi_info *vi;
1856 	struct ifnet *ifp;
1857 	struct sge_rxq *rxq;
1858 	struct sge_txq *txq;
1859 	struct sge_wrq *wrq;
1860 #ifdef TCP_OFFLOAD
1861 	struct sge_ofld_rxq *ofld_rxq;
1862 #endif
1863 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1864 	struct sge_ofld_txq *ofld_txq;
1865 #endif
1866 	int rc, i, j, k;
1867 
1868 	CH_ALERT(sc, "suspend requested\n");
1869 
1870 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4sus");
1871 	if (rc != 0)
1872 		return (ENXIO);
1873 
1874 	/* XXX: Can the kernel call suspend repeatedly without resume? */
1875 	MPASS(!hw_off_limits(sc));
1876 
1877 	if (!ok_to_reset(sc)) {
1878 		/* XXX: should list what resource is preventing suspend. */
1879 		CH_ERR(sc, "not safe to suspend.\n");
1880 		rc = EBUSY;
1881 		goto done;
1882 	}
1883 
1884 	/* No more DMA or interrupts. */
1885 	t4_shutdown_adapter(sc);
1886 
1887 	/* Quiesce all activity. */
1888 	for_each_port(sc, i) {
1889 		pi = sc->port[i];
1890 		pi->vxlan_tcam_entry = false;
1891 
1892 		PORT_LOCK(pi);
1893 		if (pi->up_vis > 0) {
1894 			/*
1895 			 * t4_shutdown_adapter has already shut down all the
1896 			 * PHYs but it also disables interrupts and DMA so there
1897 			 * won't be a link interrupt.  So we update the state
1898 			 * manually and inform the kernel.
1899 			 */
1900 			pi->link_cfg.link_ok = false;
1901 			t4_os_link_changed(pi);
1902 		}
1903 		PORT_UNLOCK(pi);
1904 
1905 		for_each_vi(pi, j, vi) {
1906 			vi->xact_addr_filt = -1;
1907 			if (!(vi->flags & VI_INIT_DONE))
1908 				continue;
1909 
1910 			ifp = vi->ifp;
1911 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1912 				mtx_lock(&vi->tick_mtx);
1913 				vi->flags |= VI_SKIP_STATS;
1914 				callout_stop(&vi->tick);
1915 				mtx_unlock(&vi->tick_mtx);
1916 				callout_drain(&vi->tick);
1917 			}
1918 
1919 			/*
1920 			 * Note that the HW is not available.
1921 			 */
1922 			for_each_txq(vi, k, txq) {
1923 				TXQ_LOCK(txq);
1924 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
1925 				TXQ_UNLOCK(txq);
1926 			}
1927 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1928 			for_each_ofld_txq(vi, k, ofld_txq) {
1929 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
1930 			}
1931 #endif
1932 			for_each_rxq(vi, k, rxq) {
1933 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1934 			}
1935 #if defined(TCP_OFFLOAD)
1936 			for_each_ofld_rxq(vi, k, ofld_rxq) {
1937 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1938 			}
1939 #endif
1940 
1941 			quiesce_vi(vi);
1942 		}
1943 
1944 		if (sc->flags & FULL_INIT_DONE) {
1945 			/* Control queue */
1946 			wrq = &sc->sge.ctrlq[i];
1947 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
1948 			quiesce_wrq(wrq);
1949 		}
1950 	}
1951 	if (sc->flags & FULL_INIT_DONE) {
1952 		/* Firmware event queue */
1953 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
1954 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
1955 	}
1956 
1957 	/* Mark the adapter totally off limits. */
1958 	mtx_lock(&sc->reg_lock);
1959 	sc->flags |= HW_OFF_LIMITS;
1960 	sc->flags &= ~(FW_OK | MASTER_PF);
1961 	sc->reset_thread = NULL;
1962 	mtx_unlock(&sc->reg_lock);
1963 
1964 	sc->num_resets++;
1965 	CH_ALERT(sc, "suspend completed.\n");
1966 done:
1967 	end_synchronized_op(sc, 0);
1968 	return (rc);
1969 }
1970 
1971 struct adapter_pre_reset_state {
1972 	u_int flags;
1973 	uint16_t nbmcaps;
1974 	uint16_t linkcaps;
1975 	uint16_t switchcaps;
1976 	uint16_t niccaps;
1977 	uint16_t toecaps;
1978 	uint16_t rdmacaps;
1979 	uint16_t cryptocaps;
1980 	uint16_t iscsicaps;
1981 	uint16_t fcoecaps;
1982 
1983 	u_int cfcsum;
1984 	char cfg_file[32];
1985 
1986 	struct adapter_params params;
1987 	struct t4_virt_res vres;
1988 	struct tid_info tids;
1989 	struct sge sge;
1990 
1991 	int rawf_base;
1992 	int nrawf;
1993 
1994 };
1995 
1996 static void
1997 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
1998 {
1999 
2000 	ASSERT_SYNCHRONIZED_OP(sc);
2001 
2002 	o->flags = sc->flags;
2003 
2004 	o->nbmcaps =  sc->nbmcaps;
2005 	o->linkcaps = sc->linkcaps;
2006 	o->switchcaps = sc->switchcaps;
2007 	o->niccaps = sc->niccaps;
2008 	o->toecaps = sc->toecaps;
2009 	o->rdmacaps = sc->rdmacaps;
2010 	o->cryptocaps = sc->cryptocaps;
2011 	o->iscsicaps = sc->iscsicaps;
2012 	o->fcoecaps = sc->fcoecaps;
2013 
2014 	o->cfcsum = sc->cfcsum;
2015 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2016 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2017 
2018 	o->params = sc->params;
2019 	o->vres = sc->vres;
2020 	o->tids = sc->tids;
2021 	o->sge = sc->sge;
2022 
2023 	o->rawf_base = sc->rawf_base;
2024 	o->nrawf = sc->nrawf;
2025 }
2026 
2027 static int
2028 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2029 {
2030 	int rc = 0;
2031 
2032 	ASSERT_SYNCHRONIZED_OP(sc);
2033 
2034 	/* Capabilities */
2035 #define COMPARE_CAPS(c) do { \
2036 	if (o->c##caps != sc->c##caps) { \
2037 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2038 		    sc->c##caps); \
2039 		rc = EINVAL; \
2040 	} \
2041 } while (0)
2042 	COMPARE_CAPS(nbm);
2043 	COMPARE_CAPS(link);
2044 	COMPARE_CAPS(switch);
2045 	COMPARE_CAPS(nic);
2046 	COMPARE_CAPS(toe);
2047 	COMPARE_CAPS(rdma);
2048 	COMPARE_CAPS(crypto);
2049 	COMPARE_CAPS(iscsi);
2050 	COMPARE_CAPS(fcoe);
2051 #undef COMPARE_CAPS
2052 
2053 	/* Firmware config file */
2054 	if (o->cfcsum != sc->cfcsum) {
2055 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2056 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2057 		rc = EINVAL;
2058 	}
2059 
2060 #define COMPARE_PARAM(p, name) do { \
2061 	if (o->p != sc->p) { \
2062 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2063 		rc = EINVAL; \
2064 	} \
2065 } while (0)
2066 	COMPARE_PARAM(sge.iq_start, iq_start);
2067 	COMPARE_PARAM(sge.eq_start, eq_start);
2068 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2069 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2070 	COMPARE_PARAM(tids.nftids, nftids);
2071 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2072 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2073 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2074 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2075 	COMPARE_PARAM(tids.tid_base, tid_base);
2076 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2077 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2078 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2079 	COMPARE_PARAM(rawf_base, rawf_base);
2080 	COMPARE_PARAM(nrawf, nrawf);
2081 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2082 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2083 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2084 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2085 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2086 	COMPARE_PARAM(tids.ntids, ntids);
2087 	COMPARE_PARAM(tids.etid_base, etid_base);
2088 	COMPARE_PARAM(tids.etid_end, etid_end);
2089 	COMPARE_PARAM(tids.netids, netids);
2090 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2091 	COMPARE_PARAM(params.ethoffload, ethoffload);
2092 	COMPARE_PARAM(tids.natids, natids);
2093 	COMPARE_PARAM(tids.stid_base, stid_base);
2094 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2095 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2096 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2097 	COMPARE_PARAM(vres.stag.start, stag_start);
2098 	COMPARE_PARAM(vres.stag.size, stag_size);
2099 	COMPARE_PARAM(vres.rq.start, rq_start);
2100 	COMPARE_PARAM(vres.rq.size, rq_size);
2101 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2102 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2103 	COMPARE_PARAM(vres.qp.start, qp_start);
2104 	COMPARE_PARAM(vres.qp.size, qp_size);
2105 	COMPARE_PARAM(vres.cq.start, cq_start);
2106 	COMPARE_PARAM(vres.cq.size, cq_size);
2107 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2108 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2109 	COMPARE_PARAM(vres.srq.start, srq_start);
2110 	COMPARE_PARAM(vres.srq.size, srq_size);
2111 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2112 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2113 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2114 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2115 	COMPARE_PARAM(vres.key.start, key_start);
2116 	COMPARE_PARAM(vres.key.size, key_size);
2117 #undef COMPARE_PARAM
2118 
2119 	return (rc);
2120 }
2121 
2122 static int
2123 t4_resume(device_t dev)
2124 {
2125 	struct adapter *sc = device_get_softc(dev);
2126 	struct adapter_pre_reset_state *old_state = NULL;
2127 	struct port_info *pi;
2128 	struct vi_info *vi;
2129 	struct ifnet *ifp;
2130 	struct sge_txq *txq;
2131 	int rc, i, j, k;
2132 
2133 	CH_ALERT(sc, "resume requested.\n");
2134 
2135 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4res");
2136 	if (rc != 0)
2137 		return (ENXIO);
2138 	MPASS(hw_off_limits(sc));
2139 	MPASS((sc->flags & FW_OK) == 0);
2140 	MPASS((sc->flags & MASTER_PF) == 0);
2141 	MPASS(sc->reset_thread == NULL);
2142 	sc->reset_thread = curthread;
2143 
2144 	/* Register access is expected to work by the time we're here. */
2145 	if (t4_read_reg(sc, A_PL_WHOAMI) == 0xffffffff) {
2146 		CH_ERR(sc, "%s: can't read device registers\n", __func__);
2147 		rc = ENXIO;
2148 		goto done;
2149 	}
2150 
2151 	/* Restore memory window. */
2152 	setup_memwin(sc);
2153 
2154 	/* Go no further if recovery mode has been requested. */
2155 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2156 		CH_ALERT(sc, "recovery mode on resume.\n");
2157 		rc = 0;
2158 		mtx_lock(&sc->reg_lock);
2159 		sc->flags &= ~HW_OFF_LIMITS;
2160 		mtx_unlock(&sc->reg_lock);
2161 		goto done;
2162 	}
2163 
2164 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2165 	save_caps_and_params(sc, old_state);
2166 
2167 	/* Reestablish contact with firmware and become the primary PF. */
2168 	rc = contact_firmware(sc);
2169 	if (rc != 0)
2170 		goto done; /* error message displayed already */
2171 	MPASS(sc->flags & FW_OK);
2172 
2173 	if (sc->flags & MASTER_PF) {
2174 		rc = partition_resources(sc);
2175 		if (rc != 0)
2176 			goto done; /* error message displayed already */
2177 		t4_intr_clear(sc);
2178 	}
2179 
2180 	rc = get_params__post_init(sc);
2181 	if (rc != 0)
2182 		goto done; /* error message displayed already */
2183 
2184 	rc = set_params__post_init(sc);
2185 	if (rc != 0)
2186 		goto done; /* error message displayed already */
2187 
2188 	rc = compare_caps_and_params(sc, old_state);
2189 	if (rc != 0)
2190 		goto done; /* error message displayed already */
2191 
2192 	for_each_port(sc, i) {
2193 		pi = sc->port[i];
2194 		MPASS(pi != NULL);
2195 		MPASS(pi->vi != NULL);
2196 		MPASS(pi->vi[0].dev == pi->dev);
2197 
2198 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2199 		if (rc != 0) {
2200 			CH_ERR(sc,
2201 			    "failed to re-initialize port %d: %d\n", i, rc);
2202 			goto done;
2203 		}
2204 		MPASS(sc->chan_map[pi->tx_chan] == i);
2205 
2206 		PORT_LOCK(pi);
2207 		fixup_link_config(pi);
2208 		build_medialist(pi);
2209 		PORT_UNLOCK(pi);
2210 		for_each_vi(pi, j, vi) {
2211 			if (IS_MAIN_VI(vi))
2212 				continue;
2213 			rc = alloc_extra_vi(sc, pi, vi);
2214 			if (rc != 0) {
2215 				CH_ERR(vi,
2216 				    "failed to re-allocate extra VI: %d\n", rc);
2217 				goto done;
2218 			}
2219 		}
2220 	}
2221 
2222 	/*
2223 	 * Interrupts and queues are about to be enabled and other threads will
2224 	 * want to access the hardware too.  It is safe to do so.  Note that
2225 	 * this thread is still in the middle of a synchronized_op.
2226 	 */
2227 	mtx_lock(&sc->reg_lock);
2228 	sc->flags &= ~HW_OFF_LIMITS;
2229 	mtx_unlock(&sc->reg_lock);
2230 
2231 	if (sc->flags & FULL_INIT_DONE) {
2232 		rc = adapter_full_init(sc);
2233 		if (rc != 0) {
2234 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2235 			goto done;
2236 		}
2237 
2238 		if (sc->vxlan_refcount > 0)
2239 			enable_vxlan_rx(sc);
2240 
2241 		for_each_port(sc, i) {
2242 			pi = sc->port[i];
2243 			for_each_vi(pi, j, vi) {
2244 				if (!(vi->flags & VI_INIT_DONE))
2245 					continue;
2246 				rc = vi_full_init(vi);
2247 				if (rc != 0) {
2248 					CH_ERR(vi, "failed to re-initialize "
2249 					    "interface: %d\n", rc);
2250 					goto done;
2251 				}
2252 
2253 				ifp = vi->ifp;
2254 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2255 					continue;
2256 				/*
2257 				 * Note that we do not setup multicast addresses
2258 				 * in the first pass.  This ensures that the
2259 				 * unicast DMACs for all VIs on all ports get an
2260 				 * MPS TCAM entry.
2261 				 */
2262 				rc = update_mac_settings(ifp, XGMAC_ALL &
2263 				    ~XGMAC_MCADDRS);
2264 				if (rc != 0) {
2265 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2266 					goto done;
2267 				}
2268 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2269 				    true);
2270 				if (rc != 0) {
2271 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2272 					goto done;
2273 				}
2274 				for_each_txq(vi, k, txq) {
2275 					TXQ_LOCK(txq);
2276 					txq->eq.flags |= EQ_ENABLED;
2277 					TXQ_UNLOCK(txq);
2278 				}
2279 				mtx_lock(&vi->tick_mtx);
2280 				vi->flags &= ~VI_SKIP_STATS;
2281 				callout_schedule(&vi->tick, hz);
2282 				mtx_unlock(&vi->tick_mtx);
2283 			}
2284 			PORT_LOCK(pi);
2285 			if (pi->up_vis > 0) {
2286 				t4_update_port_info(pi);
2287 				fixup_link_config(pi);
2288 				build_medialist(pi);
2289 				apply_link_config(pi);
2290 				if (pi->link_cfg.link_ok)
2291 					t4_os_link_changed(pi);
2292 			}
2293 			PORT_UNLOCK(pi);
2294 		}
2295 
2296 		/* Now reprogram the L2 multicast addresses. */
2297 		for_each_port(sc, i) {
2298 			pi = sc->port[i];
2299 			for_each_vi(pi, j, vi) {
2300 				if (!(vi->flags & VI_INIT_DONE))
2301 					continue;
2302 				ifp = vi->ifp;
2303 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2304 					continue;
2305 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2306 				if (rc != 0) {
2307 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2308 					rc = 0;	/* carry on */
2309 				}
2310 			}
2311 		}
2312 	}
2313 done:
2314 	if (rc == 0) {
2315 		sc->incarnation++;
2316 		CH_ALERT(sc, "resume completed.\n");
2317 	}
2318 	end_synchronized_op(sc, 0);
2319 	free(old_state, M_CXGBE);
2320 	return (rc);
2321 }
2322 
2323 static int
2324 t4_reset_prepare(device_t dev, device_t child)
2325 {
2326 	struct adapter *sc = device_get_softc(dev);
2327 
2328 	CH_ALERT(sc, "reset_prepare.\n");
2329 	return (0);
2330 }
2331 
2332 static int
2333 t4_reset_post(device_t dev, device_t child)
2334 {
2335 	struct adapter *sc = device_get_softc(dev);
2336 
2337 	CH_ALERT(sc, "reset_post.\n");
2338 	return (0);
2339 }
2340 
2341 static void
2342 reset_adapter(void *arg, int pending)
2343 {
2344 	struct adapter *sc = arg;
2345 	int rc;
2346 
2347 	CH_ALERT(sc, "reset requested.\n");
2348 
2349 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst1");
2350 	if (rc != 0)
2351 		return;
2352 
2353 	if (hw_off_limits(sc)) {
2354 		CH_ERR(sc, "adapter is suspended, use resume (not reset).\n");
2355 		rc = ENXIO;
2356 		goto done;
2357 	}
2358 
2359 	if (!ok_to_reset(sc)) {
2360 		/* XXX: should list what resource is preventing reset. */
2361 		CH_ERR(sc, "not safe to reset.\n");
2362 		rc = EBUSY;
2363 		goto done;
2364 	}
2365 
2366 done:
2367 	end_synchronized_op(sc, 0);
2368 	if (rc != 0)
2369 		return;	/* Error logged already. */
2370 
2371 	mtx_lock(&Giant);
2372 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2373 	mtx_unlock(&Giant);
2374 	if (rc != 0)
2375 		CH_ERR(sc, "bus_reset_child failed: %d.\n", rc);
2376 	else
2377 		CH_ALERT(sc, "bus_reset_child succeeded.\n");
2378 }
2379 
2380 static int
2381 cxgbe_probe(device_t dev)
2382 {
2383 	char buf[128];
2384 	struct port_info *pi = device_get_softc(dev);
2385 
2386 	snprintf(buf, sizeof(buf), "port %d", pi->port_id);
2387 	device_set_desc_copy(dev, buf);
2388 
2389 	return (BUS_PROBE_DEFAULT);
2390 }
2391 
2392 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2393     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2394     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2395     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2396 #define T4_CAP_ENABLE (T4_CAP)
2397 
2398 static int
2399 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2400 {
2401 	struct ifnet *ifp;
2402 	struct sbuf *sb;
2403 	struct sysctl_ctx_list *ctx;
2404 	struct sysctl_oid_list *children;
2405 	struct pfil_head_args pa;
2406 	struct adapter *sc = vi->adapter;
2407 
2408 	ctx = device_get_sysctl_ctx(vi->dev);
2409 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2410 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2411 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2412 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2413 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2414 #ifdef DEV_NETMAP
2415 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2416 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2417 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2418 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2419 #endif
2420 #ifdef TCP_OFFLOAD
2421 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2422 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2423 #endif
2424 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2425 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2426 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2427 #endif
2428 
2429 	vi->xact_addr_filt = -1;
2430 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2431 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2432 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2433 		vi->flags |= TX_USES_VM_WR;
2434 
2435 	/* Allocate an ifnet and set it up */
2436 	ifp = if_alloc_dev(IFT_ETHER, dev);
2437 	if (ifp == NULL) {
2438 		device_printf(dev, "Cannot allocate ifnet\n");
2439 		return (ENOMEM);
2440 	}
2441 	vi->ifp = ifp;
2442 	ifp->if_softc = vi;
2443 
2444 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2445 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
2446 
2447 	ifp->if_init = cxgbe_init;
2448 	ifp->if_ioctl = cxgbe_ioctl;
2449 	ifp->if_transmit = cxgbe_transmit;
2450 	ifp->if_qflush = cxgbe_qflush;
2451 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2452 		ifp->if_get_counter = vi_get_counter;
2453 	else
2454 		ifp->if_get_counter = cxgbe_get_counter;
2455 #if defined(KERN_TLS) || defined(RATELIMIT)
2456 	ifp->if_snd_tag_alloc = cxgbe_snd_tag_alloc;
2457 	ifp->if_snd_tag_modify = cxgbe_snd_tag_modify;
2458 	ifp->if_snd_tag_query = cxgbe_snd_tag_query;
2459 	ifp->if_snd_tag_free = cxgbe_snd_tag_free;
2460 #endif
2461 #ifdef RATELIMIT
2462 	ifp->if_ratelimit_query = cxgbe_ratelimit_query;
2463 #endif
2464 
2465 	ifp->if_capabilities = T4_CAP;
2466 	ifp->if_capenable = T4_CAP_ENABLE;
2467 	ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2468 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6;
2469 	if (chip_id(sc) >= CHELSIO_T6) {
2470 		ifp->if_capabilities |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2471 		ifp->if_capenable |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2472 		ifp->if_hwassist |= CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2473 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2474 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN;
2475 	}
2476 
2477 #ifdef TCP_OFFLOAD
2478 	if (vi->nofldrxq != 0)
2479 		ifp->if_capabilities |= IFCAP_TOE;
2480 #endif
2481 #ifdef RATELIMIT
2482 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2483 		ifp->if_capabilities |= IFCAP_TXRTLMT;
2484 		ifp->if_capenable |= IFCAP_TXRTLMT;
2485 	}
2486 #endif
2487 
2488 	ifp->if_hw_tsomax = IP_MAXPACKET;
2489 	if (vi->flags & TX_USES_VM_WR)
2490 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
2491 	else
2492 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
2493 #ifdef RATELIMIT
2494 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2495 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_EO_TSO;
2496 #endif
2497 	ifp->if_hw_tsomaxsegsize = 65536;
2498 #ifdef KERN_TLS
2499 	if (is_ktls(sc)) {
2500 		ifp->if_capabilities |= IFCAP_TXTLS;
2501 		if (sc->flags & KERN_TLS_ON)
2502 			ifp->if_capenable |= IFCAP_TXTLS;
2503 	}
2504 #endif
2505 
2506 	ether_ifattach(ifp, vi->hw_addr);
2507 #ifdef DEV_NETMAP
2508 	if (vi->nnmrxq != 0)
2509 		cxgbe_nm_attach(vi);
2510 #endif
2511 	sb = sbuf_new_auto();
2512 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2513 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2514 	switch (ifp->if_capabilities & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2515 	case IFCAP_TOE:
2516 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2517 		break;
2518 	case IFCAP_TOE | IFCAP_TXRTLMT:
2519 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2520 		break;
2521 	case IFCAP_TXRTLMT:
2522 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2523 		break;
2524 	}
2525 #endif
2526 #ifdef TCP_OFFLOAD
2527 	if (ifp->if_capabilities & IFCAP_TOE)
2528 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2529 #endif
2530 #ifdef DEV_NETMAP
2531 	if (ifp->if_capabilities & IFCAP_NETMAP)
2532 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2533 		    vi->nnmtxq, vi->nnmrxq);
2534 #endif
2535 	sbuf_finish(sb);
2536 	device_printf(dev, "%s\n", sbuf_data(sb));
2537 	sbuf_delete(sb);
2538 
2539 	vi_sysctls(vi);
2540 
2541 	pa.pa_version = PFIL_VERSION;
2542 	pa.pa_flags = PFIL_IN;
2543 	pa.pa_type = PFIL_TYPE_ETHERNET;
2544 	pa.pa_headname = ifp->if_xname;
2545 	vi->pfil = pfil_head_register(&pa);
2546 
2547 	return (0);
2548 }
2549 
2550 static int
2551 cxgbe_attach(device_t dev)
2552 {
2553 	struct port_info *pi = device_get_softc(dev);
2554 	struct adapter *sc = pi->adapter;
2555 	struct vi_info *vi;
2556 	int i, rc;
2557 
2558 	rc = cxgbe_vi_attach(dev, &pi->vi[0]);
2559 	if (rc)
2560 		return (rc);
2561 
2562 	for_each_vi(pi, i, vi) {
2563 		if (i == 0)
2564 			continue;
2565 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
2566 		if (vi->dev == NULL) {
2567 			device_printf(dev, "failed to add VI %d\n", i);
2568 			continue;
2569 		}
2570 		device_set_softc(vi->dev, vi);
2571 	}
2572 
2573 	cxgbe_sysctls(pi);
2574 
2575 	bus_generic_attach(dev);
2576 
2577 	return (0);
2578 }
2579 
2580 static void
2581 cxgbe_vi_detach(struct vi_info *vi)
2582 {
2583 	struct ifnet *ifp = vi->ifp;
2584 
2585 	if (vi->pfil != NULL) {
2586 		pfil_head_unregister(vi->pfil);
2587 		vi->pfil = NULL;
2588 	}
2589 
2590 	ether_ifdetach(ifp);
2591 
2592 	/* Let detach proceed even if these fail. */
2593 #ifdef DEV_NETMAP
2594 	if (ifp->if_capabilities & IFCAP_NETMAP)
2595 		cxgbe_nm_detach(vi);
2596 #endif
2597 	cxgbe_uninit_synchronized(vi);
2598 	callout_drain(&vi->tick);
2599 	vi_full_uninit(vi);
2600 
2601 	if_free(vi->ifp);
2602 	vi->ifp = NULL;
2603 }
2604 
2605 static int
2606 cxgbe_detach(device_t dev)
2607 {
2608 	struct port_info *pi = device_get_softc(dev);
2609 	struct adapter *sc = pi->adapter;
2610 	int rc;
2611 
2612 	/* Detach the extra VIs first. */
2613 	rc = bus_generic_detach(dev);
2614 	if (rc)
2615 		return (rc);
2616 	device_delete_children(dev);
2617 
2618 	doom_vi(sc, &pi->vi[0]);
2619 
2620 	if (pi->flags & HAS_TRACEQ) {
2621 		sc->traceq = -1;	/* cloner should not create ifnet */
2622 		t4_tracer_port_detach(sc);
2623 	}
2624 
2625 	cxgbe_vi_detach(&pi->vi[0]);
2626 	ifmedia_removeall(&pi->media);
2627 
2628 	end_synchronized_op(sc, 0);
2629 
2630 	return (0);
2631 }
2632 
2633 static void
2634 cxgbe_init(void *arg)
2635 {
2636 	struct vi_info *vi = arg;
2637 	struct adapter *sc = vi->adapter;
2638 
2639 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2640 		return;
2641 	cxgbe_init_synchronized(vi);
2642 	end_synchronized_op(sc, 0);
2643 }
2644 
2645 static int
2646 cxgbe_ioctl(struct ifnet *ifp, unsigned long cmd, caddr_t data)
2647 {
2648 	int rc = 0, mtu, flags;
2649 	struct vi_info *vi = ifp->if_softc;
2650 	struct port_info *pi = vi->pi;
2651 	struct adapter *sc = pi->adapter;
2652 	struct ifreq *ifr = (struct ifreq *)data;
2653 	uint32_t mask;
2654 
2655 	switch (cmd) {
2656 	case SIOCSIFMTU:
2657 		mtu = ifr->ifr_mtu;
2658 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2659 			return (EINVAL);
2660 
2661 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2662 		if (rc)
2663 			return (rc);
2664 		ifp->if_mtu = mtu;
2665 		if (vi->flags & VI_INIT_DONE) {
2666 			t4_update_fl_bufsize(ifp);
2667 			if (!hw_off_limits(sc) &&
2668 			    ifp->if_drv_flags & IFF_DRV_RUNNING)
2669 				rc = update_mac_settings(ifp, XGMAC_MTU);
2670 		}
2671 		end_synchronized_op(sc, 0);
2672 		break;
2673 
2674 	case SIOCSIFFLAGS:
2675 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2676 		if (rc)
2677 			return (rc);
2678 
2679 		if (hw_off_limits(sc)) {
2680 			rc = ENXIO;
2681 			goto fail;
2682 		}
2683 
2684 		if (ifp->if_flags & IFF_UP) {
2685 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2686 				flags = vi->if_flags;
2687 				if ((ifp->if_flags ^ flags) &
2688 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2689 					rc = update_mac_settings(ifp,
2690 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2691 				}
2692 			} else {
2693 				rc = cxgbe_init_synchronized(vi);
2694 			}
2695 			vi->if_flags = ifp->if_flags;
2696 		} else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2697 			rc = cxgbe_uninit_synchronized(vi);
2698 		}
2699 		end_synchronized_op(sc, 0);
2700 		break;
2701 
2702 	case SIOCADDMULTI:
2703 	case SIOCDELMULTI:
2704 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2705 		if (rc)
2706 			return (rc);
2707 		if (!hw_off_limits(sc) && ifp->if_drv_flags & IFF_DRV_RUNNING)
2708 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2709 		end_synchronized_op(sc, 0);
2710 		break;
2711 
2712 	case SIOCSIFCAP:
2713 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2714 		if (rc)
2715 			return (rc);
2716 
2717 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
2718 		if (mask & IFCAP_TXCSUM) {
2719 			ifp->if_capenable ^= IFCAP_TXCSUM;
2720 			ifp->if_hwassist ^= (CSUM_TCP | CSUM_UDP | CSUM_IP);
2721 
2722 			if (IFCAP_TSO4 & ifp->if_capenable &&
2723 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2724 				mask &= ~IFCAP_TSO4;
2725 				ifp->if_capenable &= ~IFCAP_TSO4;
2726 				if_printf(ifp,
2727 				    "tso4 disabled due to -txcsum.\n");
2728 			}
2729 		}
2730 		if (mask & IFCAP_TXCSUM_IPV6) {
2731 			ifp->if_capenable ^= IFCAP_TXCSUM_IPV6;
2732 			ifp->if_hwassist ^= (CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2733 
2734 			if (IFCAP_TSO6 & ifp->if_capenable &&
2735 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2736 				mask &= ~IFCAP_TSO6;
2737 				ifp->if_capenable &= ~IFCAP_TSO6;
2738 				if_printf(ifp,
2739 				    "tso6 disabled due to -txcsum6.\n");
2740 			}
2741 		}
2742 		if (mask & IFCAP_RXCSUM)
2743 			ifp->if_capenable ^= IFCAP_RXCSUM;
2744 		if (mask & IFCAP_RXCSUM_IPV6)
2745 			ifp->if_capenable ^= IFCAP_RXCSUM_IPV6;
2746 
2747 		/*
2748 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2749 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2750 		 * sending a TSO request our way, so it's sufficient to toggle
2751 		 * IFCAP_TSOx only.
2752 		 */
2753 		if (mask & IFCAP_TSO4) {
2754 			if (!(IFCAP_TSO4 & ifp->if_capenable) &&
2755 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2756 				if_printf(ifp, "enable txcsum first.\n");
2757 				rc = EAGAIN;
2758 				goto fail;
2759 			}
2760 			ifp->if_capenable ^= IFCAP_TSO4;
2761 		}
2762 		if (mask & IFCAP_TSO6) {
2763 			if (!(IFCAP_TSO6 & ifp->if_capenable) &&
2764 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2765 				if_printf(ifp, "enable txcsum6 first.\n");
2766 				rc = EAGAIN;
2767 				goto fail;
2768 			}
2769 			ifp->if_capenable ^= IFCAP_TSO6;
2770 		}
2771 		if (mask & IFCAP_LRO) {
2772 #if defined(INET) || defined(INET6)
2773 			int i;
2774 			struct sge_rxq *rxq;
2775 
2776 			ifp->if_capenable ^= IFCAP_LRO;
2777 			for_each_rxq(vi, i, rxq) {
2778 				if (ifp->if_capenable & IFCAP_LRO)
2779 					rxq->iq.flags |= IQ_LRO_ENABLED;
2780 				else
2781 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2782 			}
2783 #endif
2784 		}
2785 #ifdef TCP_OFFLOAD
2786 		if (mask & IFCAP_TOE) {
2787 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TOE;
2788 
2789 			rc = toe_capability(vi, enable);
2790 			if (rc != 0)
2791 				goto fail;
2792 
2793 			ifp->if_capenable ^= mask;
2794 		}
2795 #endif
2796 		if (mask & IFCAP_VLAN_HWTAGGING) {
2797 			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
2798 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2799 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2800 		}
2801 		if (mask & IFCAP_VLAN_MTU) {
2802 			ifp->if_capenable ^= IFCAP_VLAN_MTU;
2803 
2804 			/* Need to find out how to disable auto-mtu-inflation */
2805 		}
2806 		if (mask & IFCAP_VLAN_HWTSO)
2807 			ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
2808 		if (mask & IFCAP_VLAN_HWCSUM)
2809 			ifp->if_capenable ^= IFCAP_VLAN_HWCSUM;
2810 #ifdef RATELIMIT
2811 		if (mask & IFCAP_TXRTLMT)
2812 			ifp->if_capenable ^= IFCAP_TXRTLMT;
2813 #endif
2814 		if (mask & IFCAP_HWRXTSTMP) {
2815 			int i;
2816 			struct sge_rxq *rxq;
2817 
2818 			ifp->if_capenable ^= IFCAP_HWRXTSTMP;
2819 			for_each_rxq(vi, i, rxq) {
2820 				if (ifp->if_capenable & IFCAP_HWRXTSTMP)
2821 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2822 				else
2823 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2824 			}
2825 		}
2826 		if (mask & IFCAP_MEXTPG)
2827 			ifp->if_capenable ^= IFCAP_MEXTPG;
2828 
2829 #ifdef KERN_TLS
2830 		if (mask & IFCAP_TXTLS) {
2831 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TXTLS;
2832 
2833 			rc = ktls_capability(sc, enable);
2834 			if (rc != 0)
2835 				goto fail;
2836 
2837 			ifp->if_capenable ^= (mask & IFCAP_TXTLS);
2838 		}
2839 #endif
2840 		if (mask & IFCAP_VXLAN_HWCSUM) {
2841 			ifp->if_capenable ^= IFCAP_VXLAN_HWCSUM;
2842 			ifp->if_hwassist ^= CSUM_INNER_IP6_UDP |
2843 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
2844 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP;
2845 		}
2846 		if (mask & IFCAP_VXLAN_HWTSO) {
2847 			ifp->if_capenable ^= IFCAP_VXLAN_HWTSO;
2848 			ifp->if_hwassist ^= CSUM_INNER_IP6_TSO |
2849 			    CSUM_INNER_IP_TSO;
2850 		}
2851 
2852 #ifdef VLAN_CAPABILITIES
2853 		VLAN_CAPABILITIES(ifp);
2854 #endif
2855 fail:
2856 		end_synchronized_op(sc, 0);
2857 		break;
2858 
2859 	case SIOCSIFMEDIA:
2860 	case SIOCGIFMEDIA:
2861 	case SIOCGIFXMEDIA:
2862 		ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
2863 		break;
2864 
2865 	case SIOCGI2C: {
2866 		struct ifi2creq i2c;
2867 
2868 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
2869 		if (rc != 0)
2870 			break;
2871 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
2872 			rc = EPERM;
2873 			break;
2874 		}
2875 		if (i2c.len > sizeof(i2c.data)) {
2876 			rc = EINVAL;
2877 			break;
2878 		}
2879 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
2880 		if (rc)
2881 			return (rc);
2882 		if (hw_off_limits(sc))
2883 			rc = ENXIO;
2884 		else
2885 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
2886 			    i2c.offset, i2c.len, &i2c.data[0]);
2887 		end_synchronized_op(sc, 0);
2888 		if (rc == 0)
2889 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
2890 		break;
2891 	}
2892 
2893 	default:
2894 		rc = ether_ioctl(ifp, cmd, data);
2895 	}
2896 
2897 	return (rc);
2898 }
2899 
2900 static int
2901 cxgbe_transmit(struct ifnet *ifp, struct mbuf *m)
2902 {
2903 	struct vi_info *vi = ifp->if_softc;
2904 	struct port_info *pi = vi->pi;
2905 	struct adapter *sc;
2906 	struct sge_txq *txq;
2907 	void *items[1];
2908 	int rc;
2909 
2910 	M_ASSERTPKTHDR(m);
2911 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
2912 #if defined(KERN_TLS) || defined(RATELIMIT)
2913 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
2914 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
2915 #endif
2916 
2917 	if (__predict_false(pi->link_cfg.link_ok == false)) {
2918 		m_freem(m);
2919 		return (ENETDOWN);
2920 	}
2921 
2922 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
2923 	if (__predict_false(rc != 0)) {
2924 		MPASS(m == NULL);			/* was freed already */
2925 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
2926 		return (rc);
2927 	}
2928 #ifdef RATELIMIT
2929 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG) {
2930 		if (m->m_pkthdr.snd_tag->type == IF_SND_TAG_TYPE_RATE_LIMIT)
2931 			return (ethofld_transmit(ifp, m));
2932 	}
2933 #endif
2934 
2935 	/* Select a txq. */
2936 	sc = vi->adapter;
2937 	txq = &sc->sge.txq[vi->first_txq];
2938 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
2939 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
2940 		    vi->rsrv_noflowq);
2941 
2942 	items[0] = m;
2943 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
2944 	if (__predict_false(rc != 0))
2945 		m_freem(m);
2946 
2947 	return (rc);
2948 }
2949 
2950 static void
2951 cxgbe_qflush(struct ifnet *ifp)
2952 {
2953 	struct vi_info *vi = ifp->if_softc;
2954 	struct sge_txq *txq;
2955 	int i;
2956 
2957 	/* queues do not exist if !VI_INIT_DONE. */
2958 	if (vi->flags & VI_INIT_DONE) {
2959 		for_each_txq(vi, i, txq) {
2960 			TXQ_LOCK(txq);
2961 			txq->eq.flags |= EQ_QFLUSH;
2962 			TXQ_UNLOCK(txq);
2963 			while (!mp_ring_is_idle(txq->r)) {
2964 				mp_ring_check_drainage(txq->r, 4096);
2965 				pause("qflush", 1);
2966 			}
2967 			TXQ_LOCK(txq);
2968 			txq->eq.flags &= ~EQ_QFLUSH;
2969 			TXQ_UNLOCK(txq);
2970 		}
2971 	}
2972 	if_qflush(ifp);
2973 }
2974 
2975 static uint64_t
2976 vi_get_counter(struct ifnet *ifp, ift_counter c)
2977 {
2978 	struct vi_info *vi = ifp->if_softc;
2979 	struct fw_vi_stats_vf *s = &vi->stats;
2980 
2981 	mtx_lock(&vi->tick_mtx);
2982 	vi_refresh_stats(vi);
2983 	mtx_unlock(&vi->tick_mtx);
2984 
2985 	switch (c) {
2986 	case IFCOUNTER_IPACKETS:
2987 		return (s->rx_bcast_frames + s->rx_mcast_frames +
2988 		    s->rx_ucast_frames);
2989 	case IFCOUNTER_IERRORS:
2990 		return (s->rx_err_frames);
2991 	case IFCOUNTER_OPACKETS:
2992 		return (s->tx_bcast_frames + s->tx_mcast_frames +
2993 		    s->tx_ucast_frames + s->tx_offload_frames);
2994 	case IFCOUNTER_OERRORS:
2995 		return (s->tx_drop_frames);
2996 	case IFCOUNTER_IBYTES:
2997 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
2998 		    s->rx_ucast_bytes);
2999 	case IFCOUNTER_OBYTES:
3000 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3001 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3002 	case IFCOUNTER_IMCASTS:
3003 		return (s->rx_mcast_frames);
3004 	case IFCOUNTER_OMCASTS:
3005 		return (s->tx_mcast_frames);
3006 	case IFCOUNTER_OQDROPS: {
3007 		uint64_t drops;
3008 
3009 		drops = 0;
3010 		if (vi->flags & VI_INIT_DONE) {
3011 			int i;
3012 			struct sge_txq *txq;
3013 
3014 			for_each_txq(vi, i, txq)
3015 				drops += counter_u64_fetch(txq->r->dropped);
3016 		}
3017 
3018 		return (drops);
3019 
3020 	}
3021 
3022 	default:
3023 		return (if_get_counter_default(ifp, c));
3024 	}
3025 }
3026 
3027 static uint64_t
3028 cxgbe_get_counter(struct ifnet *ifp, ift_counter c)
3029 {
3030 	struct vi_info *vi = ifp->if_softc;
3031 	struct port_info *pi = vi->pi;
3032 	struct port_stats *s = &pi->stats;
3033 
3034 	mtx_lock(&vi->tick_mtx);
3035 	cxgbe_refresh_stats(vi);
3036 	mtx_unlock(&vi->tick_mtx);
3037 
3038 	switch (c) {
3039 	case IFCOUNTER_IPACKETS:
3040 		return (s->rx_frames);
3041 
3042 	case IFCOUNTER_IERRORS:
3043 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3044 		    s->rx_fcs_err + s->rx_len_err);
3045 
3046 	case IFCOUNTER_OPACKETS:
3047 		return (s->tx_frames);
3048 
3049 	case IFCOUNTER_OERRORS:
3050 		return (s->tx_error_frames);
3051 
3052 	case IFCOUNTER_IBYTES:
3053 		return (s->rx_octets);
3054 
3055 	case IFCOUNTER_OBYTES:
3056 		return (s->tx_octets);
3057 
3058 	case IFCOUNTER_IMCASTS:
3059 		return (s->rx_mcast_frames);
3060 
3061 	case IFCOUNTER_OMCASTS:
3062 		return (s->tx_mcast_frames);
3063 
3064 	case IFCOUNTER_IQDROPS:
3065 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3066 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3067 		    s->rx_trunc3 + pi->tnl_cong_drops);
3068 
3069 	case IFCOUNTER_OQDROPS: {
3070 		uint64_t drops;
3071 
3072 		drops = s->tx_drop;
3073 		if (vi->flags & VI_INIT_DONE) {
3074 			int i;
3075 			struct sge_txq *txq;
3076 
3077 			for_each_txq(vi, i, txq)
3078 				drops += counter_u64_fetch(txq->r->dropped);
3079 		}
3080 
3081 		return (drops);
3082 
3083 	}
3084 
3085 	default:
3086 		return (if_get_counter_default(ifp, c));
3087 	}
3088 }
3089 
3090 #if defined(KERN_TLS) || defined(RATELIMIT)
3091 static int
3092 cxgbe_snd_tag_alloc(struct ifnet *ifp, union if_snd_tag_alloc_params *params,
3093     struct m_snd_tag **pt)
3094 {
3095 	int error;
3096 
3097 	switch (params->hdr.type) {
3098 #ifdef RATELIMIT
3099 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3100 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3101 		break;
3102 #endif
3103 #ifdef KERN_TLS
3104 	case IF_SND_TAG_TYPE_TLS:
3105 		error = cxgbe_tls_tag_alloc(ifp, params, pt);
3106 		break;
3107 #endif
3108 	default:
3109 		error = EOPNOTSUPP;
3110 	}
3111 	return (error);
3112 }
3113 
3114 static int
3115 cxgbe_snd_tag_modify(struct m_snd_tag *mst,
3116     union if_snd_tag_modify_params *params)
3117 {
3118 
3119 	switch (mst->type) {
3120 #ifdef RATELIMIT
3121 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3122 		return (cxgbe_rate_tag_modify(mst, params));
3123 #endif
3124 	default:
3125 		return (EOPNOTSUPP);
3126 	}
3127 }
3128 
3129 static int
3130 cxgbe_snd_tag_query(struct m_snd_tag *mst,
3131     union if_snd_tag_query_params *params)
3132 {
3133 
3134 	switch (mst->type) {
3135 #ifdef RATELIMIT
3136 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3137 		return (cxgbe_rate_tag_query(mst, params));
3138 #endif
3139 	default:
3140 		return (EOPNOTSUPP);
3141 	}
3142 }
3143 
3144 static void
3145 cxgbe_snd_tag_free(struct m_snd_tag *mst)
3146 {
3147 
3148 	switch (mst->type) {
3149 #ifdef RATELIMIT
3150 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3151 		cxgbe_rate_tag_free(mst);
3152 		return;
3153 #endif
3154 #ifdef KERN_TLS
3155 	case IF_SND_TAG_TYPE_TLS:
3156 		cxgbe_tls_tag_free(mst);
3157 		return;
3158 #endif
3159 	default:
3160 		panic("shouldn't get here");
3161 	}
3162 }
3163 #endif
3164 
3165 /*
3166  * The kernel picks a media from the list we had provided but we still validate
3167  * the requeste.
3168  */
3169 int
3170 cxgbe_media_change(struct ifnet *ifp)
3171 {
3172 	struct vi_info *vi = ifp->if_softc;
3173 	struct port_info *pi = vi->pi;
3174 	struct ifmedia *ifm = &pi->media;
3175 	struct link_config *lc = &pi->link_cfg;
3176 	struct adapter *sc = pi->adapter;
3177 	int rc;
3178 
3179 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3180 	if (rc != 0)
3181 		return (rc);
3182 	PORT_LOCK(pi);
3183 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3184 		/* ifconfig .. media autoselect */
3185 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3186 			rc = ENOTSUP; /* AN not supported by transceiver */
3187 			goto done;
3188 		}
3189 		lc->requested_aneg = AUTONEG_ENABLE;
3190 		lc->requested_speed = 0;
3191 		lc->requested_fc |= PAUSE_AUTONEG;
3192 	} else {
3193 		lc->requested_aneg = AUTONEG_DISABLE;
3194 		lc->requested_speed =
3195 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3196 		lc->requested_fc = 0;
3197 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3198 			lc->requested_fc |= PAUSE_RX;
3199 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3200 			lc->requested_fc |= PAUSE_TX;
3201 	}
3202 	if (pi->up_vis > 0) {
3203 		fixup_link_config(pi);
3204 		rc = apply_link_config(pi);
3205 	}
3206 done:
3207 	PORT_UNLOCK(pi);
3208 	end_synchronized_op(sc, 0);
3209 	return (rc);
3210 }
3211 
3212 /*
3213  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3214  * given speed.
3215  */
3216 static int
3217 port_mword(struct port_info *pi, uint32_t speed)
3218 {
3219 
3220 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3221 	MPASS(powerof2(speed));
3222 
3223 	switch(pi->port_type) {
3224 	case FW_PORT_TYPE_BT_SGMII:
3225 	case FW_PORT_TYPE_BT_XFI:
3226 	case FW_PORT_TYPE_BT_XAUI:
3227 		/* BaseT */
3228 		switch (speed) {
3229 		case FW_PORT_CAP32_SPEED_100M:
3230 			return (IFM_100_T);
3231 		case FW_PORT_CAP32_SPEED_1G:
3232 			return (IFM_1000_T);
3233 		case FW_PORT_CAP32_SPEED_10G:
3234 			return (IFM_10G_T);
3235 		}
3236 		break;
3237 	case FW_PORT_TYPE_KX4:
3238 		if (speed == FW_PORT_CAP32_SPEED_10G)
3239 			return (IFM_10G_KX4);
3240 		break;
3241 	case FW_PORT_TYPE_CX4:
3242 		if (speed == FW_PORT_CAP32_SPEED_10G)
3243 			return (IFM_10G_CX4);
3244 		break;
3245 	case FW_PORT_TYPE_KX:
3246 		if (speed == FW_PORT_CAP32_SPEED_1G)
3247 			return (IFM_1000_KX);
3248 		break;
3249 	case FW_PORT_TYPE_KR:
3250 	case FW_PORT_TYPE_BP_AP:
3251 	case FW_PORT_TYPE_BP4_AP:
3252 	case FW_PORT_TYPE_BP40_BA:
3253 	case FW_PORT_TYPE_KR4_100G:
3254 	case FW_PORT_TYPE_KR_SFP28:
3255 	case FW_PORT_TYPE_KR_XLAUI:
3256 		switch (speed) {
3257 		case FW_PORT_CAP32_SPEED_1G:
3258 			return (IFM_1000_KX);
3259 		case FW_PORT_CAP32_SPEED_10G:
3260 			return (IFM_10G_KR);
3261 		case FW_PORT_CAP32_SPEED_25G:
3262 			return (IFM_25G_KR);
3263 		case FW_PORT_CAP32_SPEED_40G:
3264 			return (IFM_40G_KR4);
3265 		case FW_PORT_CAP32_SPEED_50G:
3266 			return (IFM_50G_KR2);
3267 		case FW_PORT_CAP32_SPEED_100G:
3268 			return (IFM_100G_KR4);
3269 		}
3270 		break;
3271 	case FW_PORT_TYPE_FIBER_XFI:
3272 	case FW_PORT_TYPE_FIBER_XAUI:
3273 	case FW_PORT_TYPE_SFP:
3274 	case FW_PORT_TYPE_QSFP_10G:
3275 	case FW_PORT_TYPE_QSA:
3276 	case FW_PORT_TYPE_QSFP:
3277 	case FW_PORT_TYPE_CR4_QSFP:
3278 	case FW_PORT_TYPE_CR_QSFP:
3279 	case FW_PORT_TYPE_CR2_QSFP:
3280 	case FW_PORT_TYPE_SFP28:
3281 		/* Pluggable transceiver */
3282 		switch (pi->mod_type) {
3283 		case FW_PORT_MOD_TYPE_LR:
3284 			switch (speed) {
3285 			case FW_PORT_CAP32_SPEED_1G:
3286 				return (IFM_1000_LX);
3287 			case FW_PORT_CAP32_SPEED_10G:
3288 				return (IFM_10G_LR);
3289 			case FW_PORT_CAP32_SPEED_25G:
3290 				return (IFM_25G_LR);
3291 			case FW_PORT_CAP32_SPEED_40G:
3292 				return (IFM_40G_LR4);
3293 			case FW_PORT_CAP32_SPEED_50G:
3294 				return (IFM_50G_LR2);
3295 			case FW_PORT_CAP32_SPEED_100G:
3296 				return (IFM_100G_LR4);
3297 			}
3298 			break;
3299 		case FW_PORT_MOD_TYPE_SR:
3300 			switch (speed) {
3301 			case FW_PORT_CAP32_SPEED_1G:
3302 				return (IFM_1000_SX);
3303 			case FW_PORT_CAP32_SPEED_10G:
3304 				return (IFM_10G_SR);
3305 			case FW_PORT_CAP32_SPEED_25G:
3306 				return (IFM_25G_SR);
3307 			case FW_PORT_CAP32_SPEED_40G:
3308 				return (IFM_40G_SR4);
3309 			case FW_PORT_CAP32_SPEED_50G:
3310 				return (IFM_50G_SR2);
3311 			case FW_PORT_CAP32_SPEED_100G:
3312 				return (IFM_100G_SR4);
3313 			}
3314 			break;
3315 		case FW_PORT_MOD_TYPE_ER:
3316 			if (speed == FW_PORT_CAP32_SPEED_10G)
3317 				return (IFM_10G_ER);
3318 			break;
3319 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3320 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3321 			switch (speed) {
3322 			case FW_PORT_CAP32_SPEED_1G:
3323 				return (IFM_1000_CX);
3324 			case FW_PORT_CAP32_SPEED_10G:
3325 				return (IFM_10G_TWINAX);
3326 			case FW_PORT_CAP32_SPEED_25G:
3327 				return (IFM_25G_CR);
3328 			case FW_PORT_CAP32_SPEED_40G:
3329 				return (IFM_40G_CR4);
3330 			case FW_PORT_CAP32_SPEED_50G:
3331 				return (IFM_50G_CR2);
3332 			case FW_PORT_CAP32_SPEED_100G:
3333 				return (IFM_100G_CR4);
3334 			}
3335 			break;
3336 		case FW_PORT_MOD_TYPE_LRM:
3337 			if (speed == FW_PORT_CAP32_SPEED_10G)
3338 				return (IFM_10G_LRM);
3339 			break;
3340 		case FW_PORT_MOD_TYPE_NA:
3341 			MPASS(0);	/* Not pluggable? */
3342 			/* fall throough */
3343 		case FW_PORT_MOD_TYPE_ERROR:
3344 		case FW_PORT_MOD_TYPE_UNKNOWN:
3345 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3346 			break;
3347 		case FW_PORT_MOD_TYPE_NONE:
3348 			return (IFM_NONE);
3349 		}
3350 		break;
3351 	case FW_PORT_TYPE_NONE:
3352 		return (IFM_NONE);
3353 	}
3354 
3355 	return (IFM_UNKNOWN);
3356 }
3357 
3358 void
3359 cxgbe_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
3360 {
3361 	struct vi_info *vi = ifp->if_softc;
3362 	struct port_info *pi = vi->pi;
3363 	struct adapter *sc = pi->adapter;
3364 	struct link_config *lc = &pi->link_cfg;
3365 
3366 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4med") != 0)
3367 		return;
3368 	PORT_LOCK(pi);
3369 
3370 	if (pi->up_vis == 0) {
3371 		/*
3372 		 * If all the interfaces are administratively down the firmware
3373 		 * does not report transceiver changes.  Refresh port info here
3374 		 * so that ifconfig displays accurate ifmedia at all times.
3375 		 * This is the only reason we have a synchronized op in this
3376 		 * function.  Just PORT_LOCK would have been enough otherwise.
3377 		 */
3378 		t4_update_port_info(pi);
3379 		build_medialist(pi);
3380 	}
3381 
3382 	/* ifm_status */
3383 	ifmr->ifm_status = IFM_AVALID;
3384 	if (lc->link_ok == false)
3385 		goto done;
3386 	ifmr->ifm_status |= IFM_ACTIVE;
3387 
3388 	/* ifm_active */
3389 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3390 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3391 	if (lc->fc & PAUSE_RX)
3392 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3393 	if (lc->fc & PAUSE_TX)
3394 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3395 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3396 done:
3397 	PORT_UNLOCK(pi);
3398 	end_synchronized_op(sc, 0);
3399 }
3400 
3401 static int
3402 vcxgbe_probe(device_t dev)
3403 {
3404 	char buf[128];
3405 	struct vi_info *vi = device_get_softc(dev);
3406 
3407 	snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
3408 	    vi - vi->pi->vi);
3409 	device_set_desc_copy(dev, buf);
3410 
3411 	return (BUS_PROBE_DEFAULT);
3412 }
3413 
3414 static int
3415 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3416 {
3417 	int func, index, rc;
3418 	uint32_t param, val;
3419 
3420 	ASSERT_SYNCHRONIZED_OP(sc);
3421 
3422 	index = vi - pi->vi;
3423 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3424 	KASSERT(index < nitems(vi_mac_funcs),
3425 	    ("%s: VI %s doesn't have a MAC func", __func__,
3426 	    device_get_nameunit(vi->dev)));
3427 	func = vi_mac_funcs[index];
3428 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3429 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3430 	if (rc < 0) {
3431 		CH_ERR(vi, "failed to allocate virtual interface %d"
3432 		    "for port %d: %d\n", index, pi->port_id, -rc);
3433 		return (-rc);
3434 	}
3435 	vi->viid = rc;
3436 
3437 	if (vi->rss_size == 1) {
3438 		/*
3439 		 * This VI didn't get a slice of the RSS table.  Reduce the
3440 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3441 		 * configuration file (nvi, rssnvi for this PF) if this is a
3442 		 * problem.
3443 		 */
3444 		device_printf(vi->dev, "RSS table not available.\n");
3445 		vi->rss_base = 0xffff;
3446 
3447 		return (0);
3448 	}
3449 
3450 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3451 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3452 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3453 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3454 	if (rc)
3455 		vi->rss_base = 0xffff;
3456 	else {
3457 		MPASS((val >> 16) == vi->rss_size);
3458 		vi->rss_base = val & 0xffff;
3459 	}
3460 
3461 	return (0);
3462 }
3463 
3464 static int
3465 vcxgbe_attach(device_t dev)
3466 {
3467 	struct vi_info *vi;
3468 	struct port_info *pi;
3469 	struct adapter *sc;
3470 	int rc;
3471 
3472 	vi = device_get_softc(dev);
3473 	pi = vi->pi;
3474 	sc = pi->adapter;
3475 
3476 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3477 	if (rc)
3478 		return (rc);
3479 	rc = alloc_extra_vi(sc, pi, vi);
3480 	end_synchronized_op(sc, 0);
3481 	if (rc)
3482 		return (rc);
3483 
3484 	rc = cxgbe_vi_attach(dev, vi);
3485 	if (rc) {
3486 		t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3487 		return (rc);
3488 	}
3489 	return (0);
3490 }
3491 
3492 static int
3493 vcxgbe_detach(device_t dev)
3494 {
3495 	struct vi_info *vi;
3496 	struct adapter *sc;
3497 
3498 	vi = device_get_softc(dev);
3499 	sc = vi->adapter;
3500 
3501 	doom_vi(sc, vi);
3502 
3503 	cxgbe_vi_detach(vi);
3504 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3505 
3506 	end_synchronized_op(sc, 0);
3507 
3508 	return (0);
3509 }
3510 
3511 static struct callout fatal_callout;
3512 static struct taskqueue *reset_tq;
3513 
3514 static void
3515 delayed_panic(void *arg)
3516 {
3517 	struct adapter *sc = arg;
3518 
3519 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3520 }
3521 
3522 void
3523 t4_fatal_err(struct adapter *sc, bool fw_error)
3524 {
3525 
3526 	t4_shutdown_adapter(sc);
3527 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped.\n",
3528 	    device_get_nameunit(sc->dev));
3529 	if (fw_error) {
3530 		if (sc->flags & CHK_MBOX_ACCESS)
3531 			ASSERT_SYNCHRONIZED_OP(sc);
3532 		sc->flags |= ADAP_ERR;
3533 	} else {
3534 		ADAPTER_LOCK(sc);
3535 		sc->flags |= ADAP_ERR;
3536 		ADAPTER_UNLOCK(sc);
3537 	}
3538 #ifdef TCP_OFFLOAD
3539 	taskqueue_enqueue(taskqueue_thread, &sc->async_event_task);
3540 #endif
3541 
3542 	if (t4_panic_on_fatal_err) {
3543 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3544 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3545 	} else if (t4_reset_on_fatal_err) {
3546 		CH_ALERT(sc, "resetting on fatal error.\n");
3547 		taskqueue_enqueue(reset_tq, &sc->reset_task);
3548 	}
3549 }
3550 
3551 void
3552 t4_add_adapter(struct adapter *sc)
3553 {
3554 	sx_xlock(&t4_list_lock);
3555 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3556 	sx_xunlock(&t4_list_lock);
3557 }
3558 
3559 int
3560 t4_map_bars_0_and_4(struct adapter *sc)
3561 {
3562 	sc->regs_rid = PCIR_BAR(0);
3563 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3564 	    &sc->regs_rid, RF_ACTIVE);
3565 	if (sc->regs_res == NULL) {
3566 		device_printf(sc->dev, "cannot map registers.\n");
3567 		return (ENXIO);
3568 	}
3569 	sc->bt = rman_get_bustag(sc->regs_res);
3570 	sc->bh = rman_get_bushandle(sc->regs_res);
3571 	sc->mmio_len = rman_get_size(sc->regs_res);
3572 	setbit(&sc->doorbells, DOORBELL_KDB);
3573 
3574 	sc->msix_rid = PCIR_BAR(4);
3575 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3576 	    &sc->msix_rid, RF_ACTIVE);
3577 	if (sc->msix_res == NULL) {
3578 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3579 		return (ENXIO);
3580 	}
3581 
3582 	return (0);
3583 }
3584 
3585 int
3586 t4_map_bar_2(struct adapter *sc)
3587 {
3588 
3589 	/*
3590 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3591 	 * to map it if RDMA is disabled.
3592 	 */
3593 	if (is_t4(sc) && sc->rdmacaps == 0)
3594 		return (0);
3595 
3596 	sc->udbs_rid = PCIR_BAR(2);
3597 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3598 	    &sc->udbs_rid, RF_ACTIVE);
3599 	if (sc->udbs_res == NULL) {
3600 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3601 		return (ENXIO);
3602 	}
3603 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3604 
3605 	if (chip_id(sc) >= CHELSIO_T5) {
3606 		setbit(&sc->doorbells, DOORBELL_UDB);
3607 #if defined(__i386__) || defined(__amd64__)
3608 		if (t5_write_combine) {
3609 			int rc, mode;
3610 
3611 			/*
3612 			 * Enable write combining on BAR2.  This is the
3613 			 * userspace doorbell BAR and is split into 128B
3614 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3615 			 * with an egress queue.  The first 64B has the doorbell
3616 			 * and the second 64B can be used to submit a tx work
3617 			 * request with an implicit doorbell.
3618 			 */
3619 
3620 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3621 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3622 			if (rc == 0) {
3623 				clrbit(&sc->doorbells, DOORBELL_UDB);
3624 				setbit(&sc->doorbells, DOORBELL_WCWR);
3625 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3626 			} else {
3627 				device_printf(sc->dev,
3628 				    "couldn't enable write combining: %d\n",
3629 				    rc);
3630 			}
3631 
3632 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3633 			t4_write_reg(sc, A_SGE_STAT_CFG,
3634 			    V_STATSOURCE_T5(7) | mode);
3635 		}
3636 #endif
3637 	}
3638 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3639 
3640 	return (0);
3641 }
3642 
3643 struct memwin_init {
3644 	uint32_t base;
3645 	uint32_t aperture;
3646 };
3647 
3648 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3649 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3650 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3651 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3652 };
3653 
3654 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3655 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3656 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3657 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3658 };
3659 
3660 static void
3661 setup_memwin(struct adapter *sc)
3662 {
3663 	const struct memwin_init *mw_init;
3664 	struct memwin *mw;
3665 	int i;
3666 	uint32_t bar0;
3667 
3668 	if (is_t4(sc)) {
3669 		/*
3670 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3671 		 * mechanism.  Works from within PCI passthrough environments
3672 		 * too, where rman_get_start() can return a different value.  We
3673 		 * need to program the T4 memory window decoders with the actual
3674 		 * addresses that will be coming across the PCIe link.
3675 		 */
3676 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3677 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3678 
3679 		mw_init = &t4_memwin[0];
3680 	} else {
3681 		/* T5+ use the relative offset inside the PCIe BAR */
3682 		bar0 = 0;
3683 
3684 		mw_init = &t5_memwin[0];
3685 	}
3686 
3687 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3688 		if (!rw_initialized(&mw->mw_lock)) {
3689 			rw_init(&mw->mw_lock, "memory window access");
3690 			mw->mw_base = mw_init->base;
3691 			mw->mw_aperture = mw_init->aperture;
3692 			mw->mw_curpos = 0;
3693 		}
3694 		t4_write_reg(sc,
3695 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3696 		    (mw->mw_base + bar0) | V_BIR(0) |
3697 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3698 		rw_wlock(&mw->mw_lock);
3699 		position_memwin(sc, i, mw->mw_curpos);
3700 		rw_wunlock(&mw->mw_lock);
3701 	}
3702 
3703 	/* flush */
3704 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3705 }
3706 
3707 /*
3708  * Positions the memory window at the given address in the card's address space.
3709  * There are some alignment requirements and the actual position may be at an
3710  * address prior to the requested address.  mw->mw_curpos always has the actual
3711  * position of the window.
3712  */
3713 static void
3714 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3715 {
3716 	struct memwin *mw;
3717 	uint32_t pf;
3718 	uint32_t reg;
3719 
3720 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3721 	mw = &sc->memwin[idx];
3722 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3723 
3724 	if (is_t4(sc)) {
3725 		pf = 0;
3726 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3727 	} else {
3728 		pf = V_PFNUM(sc->pf);
3729 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3730 	}
3731 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3732 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3733 	t4_read_reg(sc, reg);	/* flush */
3734 }
3735 
3736 int
3737 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3738     int len, int rw)
3739 {
3740 	struct memwin *mw;
3741 	uint32_t mw_end, v;
3742 
3743 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3744 
3745 	/* Memory can only be accessed in naturally aligned 4 byte units */
3746 	if (addr & 3 || len & 3 || len <= 0)
3747 		return (EINVAL);
3748 
3749 	mw = &sc->memwin[idx];
3750 	while (len > 0) {
3751 		rw_rlock(&mw->mw_lock);
3752 		mw_end = mw->mw_curpos + mw->mw_aperture;
3753 		if (addr >= mw_end || addr < mw->mw_curpos) {
3754 			/* Will need to reposition the window */
3755 			if (!rw_try_upgrade(&mw->mw_lock)) {
3756 				rw_runlock(&mw->mw_lock);
3757 				rw_wlock(&mw->mw_lock);
3758 			}
3759 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3760 			position_memwin(sc, idx, addr);
3761 			rw_downgrade(&mw->mw_lock);
3762 			mw_end = mw->mw_curpos + mw->mw_aperture;
3763 		}
3764 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3765 		while (addr < mw_end && len > 0) {
3766 			if (rw == 0) {
3767 				v = t4_read_reg(sc, mw->mw_base + addr -
3768 				    mw->mw_curpos);
3769 				*val++ = le32toh(v);
3770 			} else {
3771 				v = *val++;
3772 				t4_write_reg(sc, mw->mw_base + addr -
3773 				    mw->mw_curpos, htole32(v));
3774 			}
3775 			addr += 4;
3776 			len -= 4;
3777 		}
3778 		rw_runlock(&mw->mw_lock);
3779 	}
3780 
3781 	return (0);
3782 }
3783 
3784 static void
3785 t4_init_atid_table(struct adapter *sc)
3786 {
3787 	struct tid_info *t;
3788 	int i;
3789 
3790 	t = &sc->tids;
3791 	if (t->natids == 0)
3792 		return;
3793 
3794 	MPASS(t->atid_tab == NULL);
3795 
3796 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3797 	    M_ZERO | M_WAITOK);
3798 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3799 	t->afree = t->atid_tab;
3800 	t->atids_in_use = 0;
3801 	for (i = 1; i < t->natids; i++)
3802 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3803 	t->atid_tab[t->natids - 1].next = NULL;
3804 }
3805 
3806 static void
3807 t4_free_atid_table(struct adapter *sc)
3808 {
3809 	struct tid_info *t;
3810 
3811 	t = &sc->tids;
3812 
3813 	KASSERT(t->atids_in_use == 0,
3814 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3815 
3816 	if (mtx_initialized(&t->atid_lock))
3817 		mtx_destroy(&t->atid_lock);
3818 	free(t->atid_tab, M_CXGBE);
3819 	t->atid_tab = NULL;
3820 }
3821 
3822 int
3823 alloc_atid(struct adapter *sc, void *ctx)
3824 {
3825 	struct tid_info *t = &sc->tids;
3826 	int atid = -1;
3827 
3828 	mtx_lock(&t->atid_lock);
3829 	if (t->afree) {
3830 		union aopen_entry *p = t->afree;
3831 
3832 		atid = p - t->atid_tab;
3833 		MPASS(atid <= M_TID_TID);
3834 		t->afree = p->next;
3835 		p->data = ctx;
3836 		t->atids_in_use++;
3837 	}
3838 	mtx_unlock(&t->atid_lock);
3839 	return (atid);
3840 }
3841 
3842 void *
3843 lookup_atid(struct adapter *sc, int atid)
3844 {
3845 	struct tid_info *t = &sc->tids;
3846 
3847 	return (t->atid_tab[atid].data);
3848 }
3849 
3850 void
3851 free_atid(struct adapter *sc, int atid)
3852 {
3853 	struct tid_info *t = &sc->tids;
3854 	union aopen_entry *p = &t->atid_tab[atid];
3855 
3856 	mtx_lock(&t->atid_lock);
3857 	p->next = t->afree;
3858 	t->afree = p;
3859 	t->atids_in_use--;
3860 	mtx_unlock(&t->atid_lock);
3861 }
3862 
3863 static void
3864 queue_tid_release(struct adapter *sc, int tid)
3865 {
3866 
3867 	CXGBE_UNIMPLEMENTED("deferred tid release");
3868 }
3869 
3870 void
3871 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
3872 {
3873 	struct wrqe *wr;
3874 	struct cpl_tid_release *req;
3875 
3876 	wr = alloc_wrqe(sizeof(*req), ctrlq);
3877 	if (wr == NULL) {
3878 		queue_tid_release(sc, tid);	/* defer */
3879 		return;
3880 	}
3881 	req = wrtod(wr);
3882 
3883 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
3884 
3885 	t4_wrq_tx(sc, wr);
3886 }
3887 
3888 static int
3889 t4_range_cmp(const void *a, const void *b)
3890 {
3891 	return ((const struct t4_range *)a)->start -
3892 	       ((const struct t4_range *)b)->start;
3893 }
3894 
3895 /*
3896  * Verify that the memory range specified by the addr/len pair is valid within
3897  * the card's address space.
3898  */
3899 static int
3900 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
3901 {
3902 	struct t4_range mem_ranges[4], *r, *next;
3903 	uint32_t em, addr_len;
3904 	int i, n, remaining;
3905 
3906 	/* Memory can only be accessed in naturally aligned 4 byte units */
3907 	if (addr & 3 || len & 3 || len == 0)
3908 		return (EINVAL);
3909 
3910 	/* Enabled memories */
3911 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
3912 
3913 	r = &mem_ranges[0];
3914 	n = 0;
3915 	bzero(r, sizeof(mem_ranges));
3916 	if (em & F_EDRAM0_ENABLE) {
3917 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
3918 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
3919 		if (r->size > 0) {
3920 			r->start = G_EDRAM0_BASE(addr_len) << 20;
3921 			if (addr >= r->start &&
3922 			    addr + len <= r->start + r->size)
3923 				return (0);
3924 			r++;
3925 			n++;
3926 		}
3927 	}
3928 	if (em & F_EDRAM1_ENABLE) {
3929 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
3930 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
3931 		if (r->size > 0) {
3932 			r->start = G_EDRAM1_BASE(addr_len) << 20;
3933 			if (addr >= r->start &&
3934 			    addr + len <= r->start + r->size)
3935 				return (0);
3936 			r++;
3937 			n++;
3938 		}
3939 	}
3940 	if (em & F_EXT_MEM_ENABLE) {
3941 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
3942 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
3943 		if (r->size > 0) {
3944 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
3945 			if (addr >= r->start &&
3946 			    addr + len <= r->start + r->size)
3947 				return (0);
3948 			r++;
3949 			n++;
3950 		}
3951 	}
3952 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
3953 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
3954 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
3955 		if (r->size > 0) {
3956 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
3957 			if (addr >= r->start &&
3958 			    addr + len <= r->start + r->size)
3959 				return (0);
3960 			r++;
3961 			n++;
3962 		}
3963 	}
3964 	MPASS(n <= nitems(mem_ranges));
3965 
3966 	if (n > 1) {
3967 		/* Sort and merge the ranges. */
3968 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
3969 
3970 		/* Start from index 0 and examine the next n - 1 entries. */
3971 		r = &mem_ranges[0];
3972 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
3973 
3974 			MPASS(r->size > 0);	/* r is a valid entry. */
3975 			next = r + 1;
3976 			MPASS(next->size > 0);	/* and so is the next one. */
3977 
3978 			while (r->start + r->size >= next->start) {
3979 				/* Merge the next one into the current entry. */
3980 				r->size = max(r->start + r->size,
3981 				    next->start + next->size) - r->start;
3982 				n--;	/* One fewer entry in total. */
3983 				if (--remaining == 0)
3984 					goto done;	/* short circuit */
3985 				next++;
3986 			}
3987 			if (next != r + 1) {
3988 				/*
3989 				 * Some entries were merged into r and next
3990 				 * points to the first valid entry that couldn't
3991 				 * be merged.
3992 				 */
3993 				MPASS(next->size > 0);	/* must be valid */
3994 				memcpy(r + 1, next, remaining * sizeof(*r));
3995 #ifdef INVARIANTS
3996 				/*
3997 				 * This so that the foo->size assertion in the
3998 				 * next iteration of the loop do the right
3999 				 * thing for entries that were pulled up and are
4000 				 * no longer valid.
4001 				 */
4002 				MPASS(n < nitems(mem_ranges));
4003 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4004 				    sizeof(struct t4_range));
4005 #endif
4006 			}
4007 		}
4008 done:
4009 		/* Done merging the ranges. */
4010 		MPASS(n > 0);
4011 		r = &mem_ranges[0];
4012 		for (i = 0; i < n; i++, r++) {
4013 			if (addr >= r->start &&
4014 			    addr + len <= r->start + r->size)
4015 				return (0);
4016 		}
4017 	}
4018 
4019 	return (EFAULT);
4020 }
4021 
4022 static int
4023 fwmtype_to_hwmtype(int mtype)
4024 {
4025 
4026 	switch (mtype) {
4027 	case FW_MEMTYPE_EDC0:
4028 		return (MEM_EDC0);
4029 	case FW_MEMTYPE_EDC1:
4030 		return (MEM_EDC1);
4031 	case FW_MEMTYPE_EXTMEM:
4032 		return (MEM_MC0);
4033 	case FW_MEMTYPE_EXTMEM1:
4034 		return (MEM_MC1);
4035 	default:
4036 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4037 	}
4038 }
4039 
4040 /*
4041  * Verify that the memory range specified by the memtype/offset/len pair is
4042  * valid and lies entirely within the memtype specified.  The global address of
4043  * the start of the range is returned in addr.
4044  */
4045 static int
4046 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4047     uint32_t *addr)
4048 {
4049 	uint32_t em, addr_len, maddr;
4050 
4051 	/* Memory can only be accessed in naturally aligned 4 byte units */
4052 	if (off & 3 || len & 3 || len == 0)
4053 		return (EINVAL);
4054 
4055 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4056 	switch (fwmtype_to_hwmtype(mtype)) {
4057 	case MEM_EDC0:
4058 		if (!(em & F_EDRAM0_ENABLE))
4059 			return (EINVAL);
4060 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4061 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4062 		break;
4063 	case MEM_EDC1:
4064 		if (!(em & F_EDRAM1_ENABLE))
4065 			return (EINVAL);
4066 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4067 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4068 		break;
4069 	case MEM_MC:
4070 		if (!(em & F_EXT_MEM_ENABLE))
4071 			return (EINVAL);
4072 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4073 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4074 		break;
4075 	case MEM_MC1:
4076 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4077 			return (EINVAL);
4078 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4079 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4080 		break;
4081 	default:
4082 		return (EINVAL);
4083 	}
4084 
4085 	*addr = maddr + off;	/* global address */
4086 	return (validate_mem_range(sc, *addr, len));
4087 }
4088 
4089 static int
4090 fixup_devlog_params(struct adapter *sc)
4091 {
4092 	struct devlog_params *dparams = &sc->params.devlog;
4093 	int rc;
4094 
4095 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4096 	    dparams->size, &dparams->addr);
4097 
4098 	return (rc);
4099 }
4100 
4101 static void
4102 update_nirq(struct intrs_and_queues *iaq, int nports)
4103 {
4104 
4105 	iaq->nirq = T4_EXTRA_INTR;
4106 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4107 	iaq->nirq += nports * iaq->nofldrxq;
4108 	iaq->nirq += nports * (iaq->num_vis - 1) *
4109 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4110 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4111 }
4112 
4113 /*
4114  * Adjust requirements to fit the number of interrupts available.
4115  */
4116 static void
4117 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4118     int navail)
4119 {
4120 	int old_nirq;
4121 	const int nports = sc->params.nports;
4122 
4123 	MPASS(nports > 0);
4124 	MPASS(navail > 0);
4125 
4126 	bzero(iaq, sizeof(*iaq));
4127 	iaq->intr_type = itype;
4128 	iaq->num_vis = t4_num_vis;
4129 	iaq->ntxq = t4_ntxq;
4130 	iaq->ntxq_vi = t4_ntxq_vi;
4131 	iaq->nrxq = t4_nrxq;
4132 	iaq->nrxq_vi = t4_nrxq_vi;
4133 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4134 	if (is_offload(sc) || is_ethoffload(sc)) {
4135 		iaq->nofldtxq = t4_nofldtxq;
4136 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4137 	}
4138 #endif
4139 #ifdef TCP_OFFLOAD
4140 	if (is_offload(sc)) {
4141 		iaq->nofldrxq = t4_nofldrxq;
4142 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4143 	}
4144 #endif
4145 #ifdef DEV_NETMAP
4146 	if (t4_native_netmap & NN_MAIN_VI) {
4147 		iaq->nnmtxq = t4_nnmtxq;
4148 		iaq->nnmrxq = t4_nnmrxq;
4149 	}
4150 	if (t4_native_netmap & NN_EXTRA_VI) {
4151 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4152 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4153 	}
4154 #endif
4155 
4156 	update_nirq(iaq, nports);
4157 	if (iaq->nirq <= navail &&
4158 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4159 		/*
4160 		 * This is the normal case -- there are enough interrupts for
4161 		 * everything.
4162 		 */
4163 		goto done;
4164 	}
4165 
4166 	/*
4167 	 * If extra VIs have been configured try reducing their count and see if
4168 	 * that works.
4169 	 */
4170 	while (iaq->num_vis > 1) {
4171 		iaq->num_vis--;
4172 		update_nirq(iaq, nports);
4173 		if (iaq->nirq <= navail &&
4174 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4175 			device_printf(sc->dev, "virtual interfaces per port "
4176 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4177 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4178 			    "itype %d, navail %u, nirq %d.\n",
4179 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4180 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4181 			    itype, navail, iaq->nirq);
4182 			goto done;
4183 		}
4184 	}
4185 
4186 	/*
4187 	 * Extra VIs will not be created.  Log a message if they were requested.
4188 	 */
4189 	MPASS(iaq->num_vis == 1);
4190 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4191 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4192 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4193 	if (iaq->num_vis != t4_num_vis) {
4194 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4195 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4196 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4197 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4198 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4199 	}
4200 
4201 	/*
4202 	 * Keep reducing the number of NIC rx queues to the next lower power of
4203 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4204 	 * if that works.
4205 	 */
4206 	do {
4207 		if (iaq->nrxq > 1) {
4208 			do {
4209 				iaq->nrxq--;
4210 			} while (!powerof2(iaq->nrxq));
4211 			if (iaq->nnmrxq > iaq->nrxq)
4212 				iaq->nnmrxq = iaq->nrxq;
4213 		}
4214 		if (iaq->nofldrxq > 1)
4215 			iaq->nofldrxq >>= 1;
4216 
4217 		old_nirq = iaq->nirq;
4218 		update_nirq(iaq, nports);
4219 		if (iaq->nirq <= navail &&
4220 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4221 			device_printf(sc->dev, "running with reduced number of "
4222 			    "rx queues because of shortage of interrupts.  "
4223 			    "nrxq=%u, nofldrxq=%u.  "
4224 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4225 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4226 			goto done;
4227 		}
4228 	} while (old_nirq != iaq->nirq);
4229 
4230 	/* One interrupt for everything.  Ugh. */
4231 	device_printf(sc->dev, "running with minimal number of queues.  "
4232 	    "itype %d, navail %u.\n", itype, navail);
4233 	iaq->nirq = 1;
4234 	iaq->nrxq = 1;
4235 	iaq->ntxq = 1;
4236 	if (iaq->nofldrxq > 0) {
4237 		iaq->nofldrxq = 1;
4238 		iaq->nofldtxq = 1;
4239 	}
4240 	iaq->nnmtxq = 0;
4241 	iaq->nnmrxq = 0;
4242 done:
4243 	MPASS(iaq->num_vis > 0);
4244 	if (iaq->num_vis > 1) {
4245 		MPASS(iaq->nrxq_vi > 0);
4246 		MPASS(iaq->ntxq_vi > 0);
4247 	}
4248 	MPASS(iaq->nirq > 0);
4249 	MPASS(iaq->nrxq > 0);
4250 	MPASS(iaq->ntxq > 0);
4251 	if (itype == INTR_MSI) {
4252 		MPASS(powerof2(iaq->nirq));
4253 	}
4254 }
4255 
4256 static int
4257 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4258 {
4259 	int rc, itype, navail, nalloc;
4260 
4261 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4262 
4263 		if ((itype & t4_intr_types) == 0)
4264 			continue;	/* not allowed */
4265 
4266 		if (itype == INTR_MSIX)
4267 			navail = pci_msix_count(sc->dev);
4268 		else if (itype == INTR_MSI)
4269 			navail = pci_msi_count(sc->dev);
4270 		else
4271 			navail = 1;
4272 restart:
4273 		if (navail == 0)
4274 			continue;
4275 
4276 		calculate_iaq(sc, iaq, itype, navail);
4277 		nalloc = iaq->nirq;
4278 		rc = 0;
4279 		if (itype == INTR_MSIX)
4280 			rc = pci_alloc_msix(sc->dev, &nalloc);
4281 		else if (itype == INTR_MSI)
4282 			rc = pci_alloc_msi(sc->dev, &nalloc);
4283 
4284 		if (rc == 0 && nalloc > 0) {
4285 			if (nalloc == iaq->nirq)
4286 				return (0);
4287 
4288 			/*
4289 			 * Didn't get the number requested.  Use whatever number
4290 			 * the kernel is willing to allocate.
4291 			 */
4292 			device_printf(sc->dev, "fewer vectors than requested, "
4293 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4294 			    itype, iaq->nirq, nalloc);
4295 			pci_release_msi(sc->dev);
4296 			navail = nalloc;
4297 			goto restart;
4298 		}
4299 
4300 		device_printf(sc->dev,
4301 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4302 		    itype, rc, iaq->nirq, nalloc);
4303 	}
4304 
4305 	device_printf(sc->dev,
4306 	    "failed to find a usable interrupt type.  "
4307 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4308 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4309 
4310 	return (ENXIO);
4311 }
4312 
4313 #define FW_VERSION(chip) ( \
4314     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4315     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4316     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4317     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4318 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4319 
4320 /* Just enough of fw_hdr to cover all version info. */
4321 struct fw_h {
4322 	__u8	ver;
4323 	__u8	chip;
4324 	__be16	len512;
4325 	__be32	fw_ver;
4326 	__be32	tp_microcode_ver;
4327 	__u8	intfver_nic;
4328 	__u8	intfver_vnic;
4329 	__u8	intfver_ofld;
4330 	__u8	intfver_ri;
4331 	__u8	intfver_iscsipdu;
4332 	__u8	intfver_iscsi;
4333 	__u8	intfver_fcoepdu;
4334 	__u8	intfver_fcoe;
4335 };
4336 /* Spot check a couple of fields. */
4337 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4338 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4339 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4340 
4341 struct fw_info {
4342 	uint8_t chip;
4343 	char *kld_name;
4344 	char *fw_mod_name;
4345 	struct fw_h fw_h;
4346 } fw_info[] = {
4347 	{
4348 		.chip = CHELSIO_T4,
4349 		.kld_name = "t4fw_cfg",
4350 		.fw_mod_name = "t4fw",
4351 		.fw_h = {
4352 			.chip = FW_HDR_CHIP_T4,
4353 			.fw_ver = htobe32(FW_VERSION(T4)),
4354 			.intfver_nic = FW_INTFVER(T4, NIC),
4355 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4356 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4357 			.intfver_ri = FW_INTFVER(T4, RI),
4358 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4359 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4360 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4361 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4362 		},
4363 	}, {
4364 		.chip = CHELSIO_T5,
4365 		.kld_name = "t5fw_cfg",
4366 		.fw_mod_name = "t5fw",
4367 		.fw_h = {
4368 			.chip = FW_HDR_CHIP_T5,
4369 			.fw_ver = htobe32(FW_VERSION(T5)),
4370 			.intfver_nic = FW_INTFVER(T5, NIC),
4371 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4372 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4373 			.intfver_ri = FW_INTFVER(T5, RI),
4374 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4375 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4376 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4377 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4378 		},
4379 	}, {
4380 		.chip = CHELSIO_T6,
4381 		.kld_name = "t6fw_cfg",
4382 		.fw_mod_name = "t6fw",
4383 		.fw_h = {
4384 			.chip = FW_HDR_CHIP_T6,
4385 			.fw_ver = htobe32(FW_VERSION(T6)),
4386 			.intfver_nic = FW_INTFVER(T6, NIC),
4387 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4388 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4389 			.intfver_ri = FW_INTFVER(T6, RI),
4390 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4391 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4392 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4393 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4394 		},
4395 	}
4396 };
4397 
4398 static struct fw_info *
4399 find_fw_info(int chip)
4400 {
4401 	int i;
4402 
4403 	for (i = 0; i < nitems(fw_info); i++) {
4404 		if (fw_info[i].chip == chip)
4405 			return (&fw_info[i]);
4406 	}
4407 	return (NULL);
4408 }
4409 
4410 /*
4411  * Is the given firmware API compatible with the one the driver was compiled
4412  * with?
4413  */
4414 static int
4415 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4416 {
4417 
4418 	/* short circuit if it's the exact same firmware version */
4419 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4420 		return (1);
4421 
4422 	/*
4423 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4424 	 * features that are supported in the driver.
4425 	 */
4426 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4427 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4428 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4429 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4430 		return (1);
4431 #undef SAME_INTF
4432 
4433 	return (0);
4434 }
4435 
4436 static int
4437 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4438     const struct firmware **fw)
4439 {
4440 	struct fw_info *fw_info;
4441 
4442 	*dcfg = NULL;
4443 	if (fw != NULL)
4444 		*fw = NULL;
4445 
4446 	fw_info = find_fw_info(chip_id(sc));
4447 	if (fw_info == NULL) {
4448 		device_printf(sc->dev,
4449 		    "unable to look up firmware information for chip %d.\n",
4450 		    chip_id(sc));
4451 		return (EINVAL);
4452 	}
4453 
4454 	*dcfg = firmware_get(fw_info->kld_name);
4455 	if (*dcfg != NULL) {
4456 		if (fw != NULL)
4457 			*fw = firmware_get(fw_info->fw_mod_name);
4458 		return (0);
4459 	}
4460 
4461 	return (ENOENT);
4462 }
4463 
4464 static void
4465 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4466     const struct firmware *fw)
4467 {
4468 
4469 	if (fw != NULL)
4470 		firmware_put(fw, FIRMWARE_UNLOAD);
4471 	if (dcfg != NULL)
4472 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4473 }
4474 
4475 /*
4476  * Return values:
4477  * 0 means no firmware install attempted.
4478  * ERESTART means a firmware install was attempted and was successful.
4479  * +ve errno means a firmware install was attempted but failed.
4480  */
4481 static int
4482 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4483     const struct fw_h *drv_fw, const char *reason, int *already)
4484 {
4485 	const struct firmware *cfg, *fw;
4486 	const uint32_t c = be32toh(card_fw->fw_ver);
4487 	uint32_t d, k;
4488 	int rc, fw_install;
4489 	struct fw_h bundled_fw;
4490 	bool load_attempted;
4491 
4492 	cfg = fw = NULL;
4493 	load_attempted = false;
4494 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4495 
4496 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4497 	if (t4_fw_install < 0) {
4498 		rc = load_fw_module(sc, &cfg, &fw);
4499 		if (rc != 0 || fw == NULL) {
4500 			device_printf(sc->dev,
4501 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4502 			    " will use compiled-in firmware version for"
4503 			    "hw.cxgbe.fw_install checks.\n",
4504 			    rc, cfg, fw);
4505 		} else {
4506 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4507 		}
4508 		load_attempted = true;
4509 	}
4510 	d = be32toh(bundled_fw.fw_ver);
4511 
4512 	if (reason != NULL)
4513 		goto install;
4514 
4515 	if ((sc->flags & FW_OK) == 0) {
4516 
4517 		if (c == 0xffffffff) {
4518 			reason = "missing";
4519 			goto install;
4520 		}
4521 
4522 		rc = 0;
4523 		goto done;
4524 	}
4525 
4526 	if (!fw_compatible(card_fw, &bundled_fw)) {
4527 		reason = "incompatible or unusable";
4528 		goto install;
4529 	}
4530 
4531 	if (d > c) {
4532 		reason = "older than the version bundled with this driver";
4533 		goto install;
4534 	}
4535 
4536 	if (fw_install == 2 && d != c) {
4537 		reason = "different than the version bundled with this driver";
4538 		goto install;
4539 	}
4540 
4541 	/* No reason to do anything to the firmware already on the card. */
4542 	rc = 0;
4543 	goto done;
4544 
4545 install:
4546 	rc = 0;
4547 	if ((*already)++)
4548 		goto done;
4549 
4550 	if (fw_install == 0) {
4551 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4552 		    "but the driver is prohibited from installing a firmware "
4553 		    "on the card.\n",
4554 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4555 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4556 
4557 		goto done;
4558 	}
4559 
4560 	/*
4561 	 * We'll attempt to install a firmware.  Load the module first (if it
4562 	 * hasn't been loaded already).
4563 	 */
4564 	if (!load_attempted) {
4565 		rc = load_fw_module(sc, &cfg, &fw);
4566 		if (rc != 0 || fw == NULL) {
4567 			device_printf(sc->dev,
4568 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4569 			    rc, cfg, fw);
4570 			/* carry on */
4571 		}
4572 	}
4573 	if (fw == NULL) {
4574 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4575 		    "but the driver cannot take corrective action because it "
4576 		    "is unable to load the firmware module.\n",
4577 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4578 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4579 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4580 		goto done;
4581 	}
4582 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4583 	if (k != d) {
4584 		MPASS(t4_fw_install > 0);
4585 		device_printf(sc->dev,
4586 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4587 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4588 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4589 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4590 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4591 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4592 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4593 		goto done;
4594 	}
4595 
4596 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4597 	    "installing firmware %u.%u.%u.%u on card.\n",
4598 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4599 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4600 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4601 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4602 
4603 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4604 	if (rc != 0) {
4605 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4606 	} else {
4607 		/* Installed successfully, update the cached header too. */
4608 		rc = ERESTART;
4609 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4610 	}
4611 done:
4612 	unload_fw_module(sc, cfg, fw);
4613 
4614 	return (rc);
4615 }
4616 
4617 /*
4618  * Establish contact with the firmware and attempt to become the master driver.
4619  *
4620  * A firmware will be installed to the card if needed (if the driver is allowed
4621  * to do so).
4622  */
4623 static int
4624 contact_firmware(struct adapter *sc)
4625 {
4626 	int rc, already = 0;
4627 	enum dev_state state;
4628 	struct fw_info *fw_info;
4629 	struct fw_hdr *card_fw;		/* fw on the card */
4630 	const struct fw_h *drv_fw;
4631 
4632 	fw_info = find_fw_info(chip_id(sc));
4633 	if (fw_info == NULL) {
4634 		device_printf(sc->dev,
4635 		    "unable to look up firmware information for chip %d.\n",
4636 		    chip_id(sc));
4637 		return (EINVAL);
4638 	}
4639 	drv_fw = &fw_info->fw_h;
4640 
4641 	/* Read the header of the firmware on the card */
4642 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4643 restart:
4644 	rc = -t4_get_fw_hdr(sc, card_fw);
4645 	if (rc != 0) {
4646 		device_printf(sc->dev,
4647 		    "unable to read firmware header from card's flash: %d\n",
4648 		    rc);
4649 		goto done;
4650 	}
4651 
4652 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4653 	    &already);
4654 	if (rc == ERESTART)
4655 		goto restart;
4656 	if (rc != 0)
4657 		goto done;
4658 
4659 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4660 	if (rc < 0 || state == DEV_STATE_ERR) {
4661 		rc = -rc;
4662 		device_printf(sc->dev,
4663 		    "failed to connect to the firmware: %d, %d.  "
4664 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4665 #if 0
4666 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4667 		    "not responding properly to HELLO", &already) == ERESTART)
4668 			goto restart;
4669 #endif
4670 		goto done;
4671 	}
4672 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4673 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4674 
4675 	if (rc == sc->pf) {
4676 		sc->flags |= MASTER_PF;
4677 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4678 		    NULL, &already);
4679 		if (rc == ERESTART)
4680 			rc = 0;
4681 		else if (rc != 0)
4682 			goto done;
4683 	} else if (state == DEV_STATE_UNINIT) {
4684 		/*
4685 		 * We didn't get to be the master so we definitely won't be
4686 		 * configuring the chip.  It's a bug if someone else hasn't
4687 		 * configured it already.
4688 		 */
4689 		device_printf(sc->dev, "couldn't be master(%d), "
4690 		    "device not already initialized either(%d).  "
4691 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4692 		rc = EPROTO;
4693 		goto done;
4694 	} else {
4695 		/*
4696 		 * Some other PF is the master and has configured the chip.
4697 		 * This is allowed but untested.
4698 		 */
4699 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4700 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4701 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4702 		sc->cfcsum = 0;
4703 		rc = 0;
4704 	}
4705 done:
4706 	if (rc != 0 && sc->flags & FW_OK) {
4707 		t4_fw_bye(sc, sc->mbox);
4708 		sc->flags &= ~FW_OK;
4709 	}
4710 	free(card_fw, M_CXGBE);
4711 	return (rc);
4712 }
4713 
4714 static int
4715 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4716     uint32_t mtype, uint32_t moff)
4717 {
4718 	struct fw_info *fw_info;
4719 	const struct firmware *dcfg, *rcfg = NULL;
4720 	const uint32_t *cfdata;
4721 	uint32_t cflen, addr;
4722 	int rc;
4723 
4724 	load_fw_module(sc, &dcfg, NULL);
4725 
4726 	/* Card specific interpretation of "default". */
4727 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4728 		if (pci_get_device(sc->dev) == 0x440a)
4729 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4730 		if (is_fpga(sc))
4731 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4732 	}
4733 
4734 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4735 		if (dcfg == NULL) {
4736 			device_printf(sc->dev,
4737 			    "KLD with default config is not available.\n");
4738 			rc = ENOENT;
4739 			goto done;
4740 		}
4741 		cfdata = dcfg->data;
4742 		cflen = dcfg->datasize & ~3;
4743 	} else {
4744 		char s[32];
4745 
4746 		fw_info = find_fw_info(chip_id(sc));
4747 		if (fw_info == NULL) {
4748 			device_printf(sc->dev,
4749 			    "unable to look up firmware information for chip %d.\n",
4750 			    chip_id(sc));
4751 			rc = EINVAL;
4752 			goto done;
4753 		}
4754 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4755 
4756 		rcfg = firmware_get(s);
4757 		if (rcfg == NULL) {
4758 			device_printf(sc->dev,
4759 			    "unable to load module \"%s\" for configuration "
4760 			    "profile \"%s\".\n", s, cfg_file);
4761 			rc = ENOENT;
4762 			goto done;
4763 		}
4764 		cfdata = rcfg->data;
4765 		cflen = rcfg->datasize & ~3;
4766 	}
4767 
4768 	if (cflen > FLASH_CFG_MAX_SIZE) {
4769 		device_printf(sc->dev,
4770 		    "config file too long (%d, max allowed is %d).\n",
4771 		    cflen, FLASH_CFG_MAX_SIZE);
4772 		rc = EINVAL;
4773 		goto done;
4774 	}
4775 
4776 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4777 	if (rc != 0) {
4778 		device_printf(sc->dev,
4779 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4780 		    __func__, mtype, moff, cflen, rc);
4781 		rc = EINVAL;
4782 		goto done;
4783 	}
4784 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4785 done:
4786 	if (rcfg != NULL)
4787 		firmware_put(rcfg, FIRMWARE_UNLOAD);
4788 	unload_fw_module(sc, dcfg, NULL);
4789 	return (rc);
4790 }
4791 
4792 struct caps_allowed {
4793 	uint16_t nbmcaps;
4794 	uint16_t linkcaps;
4795 	uint16_t switchcaps;
4796 	uint16_t niccaps;
4797 	uint16_t toecaps;
4798 	uint16_t rdmacaps;
4799 	uint16_t cryptocaps;
4800 	uint16_t iscsicaps;
4801 	uint16_t fcoecaps;
4802 };
4803 
4804 #define FW_PARAM_DEV(param) \
4805 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4806 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4807 #define FW_PARAM_PFVF(param) \
4808 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4809 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4810 
4811 /*
4812  * Provide a configuration profile to the firmware and have it initialize the
4813  * chip accordingly.  This may involve uploading a configuration file to the
4814  * card.
4815  */
4816 static int
4817 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4818     const struct caps_allowed *caps_allowed)
4819 {
4820 	int rc;
4821 	struct fw_caps_config_cmd caps;
4822 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
4823 
4824 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4825 	if (rc != 0) {
4826 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
4827 		return (rc);
4828 	}
4829 
4830 	bzero(&caps, sizeof(caps));
4831 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4832 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
4833 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
4834 		mtype = 0;
4835 		moff = 0;
4836 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4837 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
4838 		mtype = FW_MEMTYPE_FLASH;
4839 		moff = t4_flash_cfg_addr(sc);
4840 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4841 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4842 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4843 		    FW_LEN16(caps));
4844 	} else {
4845 		/*
4846 		 * Ask the firmware where it wants us to upload the config file.
4847 		 */
4848 		param = FW_PARAM_DEV(CF);
4849 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4850 		if (rc != 0) {
4851 			/* No support for config file?  Shouldn't happen. */
4852 			device_printf(sc->dev,
4853 			    "failed to query config file location: %d.\n", rc);
4854 			goto done;
4855 		}
4856 		mtype = G_FW_PARAMS_PARAM_Y(val);
4857 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
4858 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4859 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4860 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4861 		    FW_LEN16(caps));
4862 
4863 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
4864 		if (rc != 0) {
4865 			device_printf(sc->dev,
4866 			    "failed to upload config file to card: %d.\n", rc);
4867 			goto done;
4868 		}
4869 	}
4870 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
4871 	if (rc != 0) {
4872 		device_printf(sc->dev, "failed to pre-process config file: %d "
4873 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
4874 		goto done;
4875 	}
4876 
4877 	finicsum = be32toh(caps.finicsum);
4878 	cfcsum = be32toh(caps.cfcsum);	/* actual */
4879 	if (finicsum != cfcsum) {
4880 		device_printf(sc->dev,
4881 		    "WARNING: config file checksum mismatch: %08x %08x\n",
4882 		    finicsum, cfcsum);
4883 	}
4884 	sc->cfcsum = cfcsum;
4885 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
4886 
4887 	/*
4888 	 * Let the firmware know what features will (not) be used so it can tune
4889 	 * things accordingly.
4890 	 */
4891 #define LIMIT_CAPS(x) do { \
4892 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
4893 } while (0)
4894 	LIMIT_CAPS(nbm);
4895 	LIMIT_CAPS(link);
4896 	LIMIT_CAPS(switch);
4897 	LIMIT_CAPS(nic);
4898 	LIMIT_CAPS(toe);
4899 	LIMIT_CAPS(rdma);
4900 	LIMIT_CAPS(crypto);
4901 	LIMIT_CAPS(iscsi);
4902 	LIMIT_CAPS(fcoe);
4903 #undef LIMIT_CAPS
4904 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
4905 		/*
4906 		 * TOE and hashfilters are mutually exclusive.  It is a config
4907 		 * file or firmware bug if both are reported as available.  Try
4908 		 * to cope with the situation in non-debug builds by disabling
4909 		 * TOE.
4910 		 */
4911 		MPASS(caps.toecaps == 0);
4912 
4913 		caps.toecaps = 0;
4914 		caps.rdmacaps = 0;
4915 		caps.iscsicaps = 0;
4916 	}
4917 
4918 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4919 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
4920 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4921 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
4922 	if (rc != 0) {
4923 		device_printf(sc->dev,
4924 		    "failed to process config file: %d.\n", rc);
4925 		goto done;
4926 	}
4927 
4928 	t4_tweak_chip_settings(sc);
4929 	set_params__pre_init(sc);
4930 
4931 	/* get basic stuff going */
4932 	rc = -t4_fw_initialize(sc, sc->mbox);
4933 	if (rc != 0) {
4934 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
4935 		goto done;
4936 	}
4937 done:
4938 	return (rc);
4939 }
4940 
4941 /*
4942  * Partition chip resources for use between various PFs, VFs, etc.
4943  */
4944 static int
4945 partition_resources(struct adapter *sc)
4946 {
4947 	char cfg_file[sizeof(t4_cfg_file)];
4948 	struct caps_allowed caps_allowed;
4949 	int rc;
4950 	bool fallback;
4951 
4952 	/* Only the master driver gets to configure the chip resources. */
4953 	MPASS(sc->flags & MASTER_PF);
4954 
4955 #define COPY_CAPS(x) do { \
4956 	caps_allowed.x##caps = t4_##x##caps_allowed; \
4957 } while (0)
4958 	bzero(&caps_allowed, sizeof(caps_allowed));
4959 	COPY_CAPS(nbm);
4960 	COPY_CAPS(link);
4961 	COPY_CAPS(switch);
4962 	COPY_CAPS(nic);
4963 	COPY_CAPS(toe);
4964 	COPY_CAPS(rdma);
4965 	COPY_CAPS(crypto);
4966 	COPY_CAPS(iscsi);
4967 	COPY_CAPS(fcoe);
4968 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
4969 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
4970 retry:
4971 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
4972 	if (rc != 0 && fallback) {
4973 		device_printf(sc->dev,
4974 		    "failed (%d) to configure card with \"%s\" profile, "
4975 		    "will fall back to a basic configuration and retry.\n",
4976 		    rc, cfg_file);
4977 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
4978 		bzero(&caps_allowed, sizeof(caps_allowed));
4979 		COPY_CAPS(switch);
4980 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
4981 		fallback = false;
4982 		goto retry;
4983 	}
4984 #undef COPY_CAPS
4985 	return (rc);
4986 }
4987 
4988 /*
4989  * Retrieve parameters that are needed (or nice to have) very early.
4990  */
4991 static int
4992 get_params__pre_init(struct adapter *sc)
4993 {
4994 	int rc;
4995 	uint32_t param[2], val[2];
4996 
4997 	t4_get_version_info(sc);
4998 
4999 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5000 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5001 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5002 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5003 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5004 
5005 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5006 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5007 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5008 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5009 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5010 
5011 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5012 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5013 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5014 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5015 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5016 
5017 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5018 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5019 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5020 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5021 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5022 
5023 	param[0] = FW_PARAM_DEV(PORTVEC);
5024 	param[1] = FW_PARAM_DEV(CCLK);
5025 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5026 	if (rc != 0) {
5027 		device_printf(sc->dev,
5028 		    "failed to query parameters (pre_init): %d.\n", rc);
5029 		return (rc);
5030 	}
5031 
5032 	sc->params.portvec = val[0];
5033 	sc->params.nports = bitcount32(val[0]);
5034 	sc->params.vpd.cclk = val[1];
5035 
5036 	/* Read device log parameters. */
5037 	rc = -t4_init_devlog_params(sc, 1);
5038 	if (rc == 0)
5039 		fixup_devlog_params(sc);
5040 	else {
5041 		device_printf(sc->dev,
5042 		    "failed to get devlog parameters: %d.\n", rc);
5043 		rc = 0;	/* devlog isn't critical for device operation */
5044 	}
5045 
5046 	return (rc);
5047 }
5048 
5049 /*
5050  * Any params that need to be set before FW_INITIALIZE.
5051  */
5052 static int
5053 set_params__pre_init(struct adapter *sc)
5054 {
5055 	int rc = 0;
5056 	uint32_t param, val;
5057 
5058 	if (chip_id(sc) >= CHELSIO_T6) {
5059 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5060 		val = 1;
5061 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5062 		/* firmwares < 1.20.1.0 do not have this param. */
5063 		if (rc == FW_EINVAL &&
5064 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5065 			rc = 0;
5066 		}
5067 		if (rc != 0) {
5068 			device_printf(sc->dev,
5069 			    "failed to enable high priority filters :%d.\n",
5070 			    rc);
5071 		}
5072 	}
5073 
5074 	/* Enable opaque VIIDs with firmwares that support it. */
5075 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5076 	val = 1;
5077 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5078 	if (rc == 0 && val == 1)
5079 		sc->params.viid_smt_extn_support = true;
5080 	else
5081 		sc->params.viid_smt_extn_support = false;
5082 
5083 	return (rc);
5084 }
5085 
5086 /*
5087  * Retrieve various parameters that are of interest to the driver.  The device
5088  * has been initialized by the firmware at this point.
5089  */
5090 static int
5091 get_params__post_init(struct adapter *sc)
5092 {
5093 	int rc;
5094 	uint32_t param[7], val[7];
5095 	struct fw_caps_config_cmd caps;
5096 
5097 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5098 	param[1] = FW_PARAM_PFVF(EQ_START);
5099 	param[2] = FW_PARAM_PFVF(FILTER_START);
5100 	param[3] = FW_PARAM_PFVF(FILTER_END);
5101 	param[4] = FW_PARAM_PFVF(L2T_START);
5102 	param[5] = FW_PARAM_PFVF(L2T_END);
5103 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5104 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5105 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5106 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5107 	if (rc != 0) {
5108 		device_printf(sc->dev,
5109 		    "failed to query parameters (post_init): %d.\n", rc);
5110 		return (rc);
5111 	}
5112 
5113 	sc->sge.iq_start = val[0];
5114 	sc->sge.eq_start = val[1];
5115 	if ((int)val[3] > (int)val[2]) {
5116 		sc->tids.ftid_base = val[2];
5117 		sc->tids.ftid_end = val[3];
5118 		sc->tids.nftids = val[3] - val[2] + 1;
5119 	}
5120 	sc->vres.l2t.start = val[4];
5121 	sc->vres.l2t.size = val[5] - val[4] + 1;
5122 	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
5123 	    ("%s: L2 table size (%u) larger than expected (%u)",
5124 	    __func__, sc->vres.l2t.size, L2T_SIZE));
5125 	sc->params.core_vdd = val[6];
5126 
5127 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5128 	param[1] = FW_PARAM_PFVF(EQ_END);
5129 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5130 	if (rc != 0) {
5131 		device_printf(sc->dev,
5132 		    "failed to query parameters (post_init2): %d.\n", rc);
5133 		return (rc);
5134 	}
5135 	MPASS((int)val[0] >= sc->sge.iq_start);
5136 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5137 	MPASS((int)val[1] >= sc->sge.eq_start);
5138 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5139 
5140 	if (chip_id(sc) >= CHELSIO_T6) {
5141 
5142 		sc->tids.tid_base = t4_read_reg(sc,
5143 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5144 
5145 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5146 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5147 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5148 		if (rc != 0) {
5149 			device_printf(sc->dev,
5150 			   "failed to query hpfilter parameters: %d.\n", rc);
5151 			return (rc);
5152 		}
5153 		if ((int)val[1] > (int)val[0]) {
5154 			sc->tids.hpftid_base = val[0];
5155 			sc->tids.hpftid_end = val[1];
5156 			sc->tids.nhpftids = val[1] - val[0] + 1;
5157 
5158 			/*
5159 			 * These should go off if the layout changes and the
5160 			 * driver needs to catch up.
5161 			 */
5162 			MPASS(sc->tids.hpftid_base == 0);
5163 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5164 		}
5165 
5166 		param[0] = FW_PARAM_PFVF(RAWF_START);
5167 		param[1] = FW_PARAM_PFVF(RAWF_END);
5168 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5169 		if (rc != 0) {
5170 			device_printf(sc->dev,
5171 			   "failed to query rawf parameters: %d.\n", rc);
5172 			return (rc);
5173 		}
5174 		if ((int)val[1] > (int)val[0]) {
5175 			sc->rawf_base = val[0];
5176 			sc->nrawf = val[1] - val[0] + 1;
5177 		}
5178 	}
5179 
5180 	/*
5181 	 * MPSBGMAP is queried separately because only recent firmwares support
5182 	 * it as a parameter and we don't want the compound query above to fail
5183 	 * on older firmwares.
5184 	 */
5185 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5186 	val[0] = 0;
5187 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5188 	if (rc == 0)
5189 		sc->params.mps_bg_map = val[0];
5190 	else
5191 		sc->params.mps_bg_map = 0;
5192 
5193 	/*
5194 	 * Determine whether the firmware supports the filter2 work request.
5195 	 * This is queried separately for the same reason as MPSBGMAP above.
5196 	 */
5197 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5198 	val[0] = 0;
5199 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5200 	if (rc == 0)
5201 		sc->params.filter2_wr_support = val[0] != 0;
5202 	else
5203 		sc->params.filter2_wr_support = 0;
5204 
5205 	/*
5206 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5207 	 * This is queried separately for the same reason as other params above.
5208 	 */
5209 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5210 	val[0] = 0;
5211 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5212 	if (rc == 0)
5213 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5214 	else
5215 		sc->params.ulptx_memwrite_dsgl = false;
5216 
5217 	/* FW_RI_FR_NSMR_TPTE_WR support */
5218 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5219 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5220 	if (rc == 0)
5221 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5222 	else
5223 		sc->params.fr_nsmr_tpte_wr_support = false;
5224 
5225 	/* Support for 512 SGL entries per FR MR. */
5226 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5227 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5228 	if (rc == 0)
5229 		sc->params.dev_512sgl_mr = val[0] != 0;
5230 	else
5231 		sc->params.dev_512sgl_mr = false;
5232 
5233 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5234 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5235 	if (rc == 0)
5236 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5237 	else
5238 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5239 
5240 	/* get capabilites */
5241 	bzero(&caps, sizeof(caps));
5242 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5243 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5244 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5245 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5246 	if (rc != 0) {
5247 		device_printf(sc->dev,
5248 		    "failed to get card capabilities: %d.\n", rc);
5249 		return (rc);
5250 	}
5251 
5252 #define READ_CAPS(x) do { \
5253 	sc->x = htobe16(caps.x); \
5254 } while (0)
5255 	READ_CAPS(nbmcaps);
5256 	READ_CAPS(linkcaps);
5257 	READ_CAPS(switchcaps);
5258 	READ_CAPS(niccaps);
5259 	READ_CAPS(toecaps);
5260 	READ_CAPS(rdmacaps);
5261 	READ_CAPS(cryptocaps);
5262 	READ_CAPS(iscsicaps);
5263 	READ_CAPS(fcoecaps);
5264 
5265 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5266 		MPASS(chip_id(sc) > CHELSIO_T4);
5267 		MPASS(sc->toecaps == 0);
5268 		sc->toecaps = 0;
5269 
5270 		param[0] = FW_PARAM_DEV(NTID);
5271 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5272 		if (rc != 0) {
5273 			device_printf(sc->dev,
5274 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5275 			return (rc);
5276 		}
5277 		sc->tids.ntids = val[0];
5278 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5279 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5280 			sc->tids.ntids -= sc->tids.nhpftids;
5281 		}
5282 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5283 		sc->params.hash_filter = 1;
5284 	}
5285 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5286 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5287 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5288 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5289 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5290 		if (rc != 0) {
5291 			device_printf(sc->dev,
5292 			    "failed to query NIC parameters: %d.\n", rc);
5293 			return (rc);
5294 		}
5295 		if ((int)val[1] > (int)val[0]) {
5296 			sc->tids.etid_base = val[0];
5297 			sc->tids.etid_end = val[1];
5298 			sc->tids.netids = val[1] - val[0] + 1;
5299 			sc->params.eo_wr_cred = val[2];
5300 			sc->params.ethoffload = 1;
5301 		}
5302 	}
5303 	if (sc->toecaps) {
5304 		/* query offload-related parameters */
5305 		param[0] = FW_PARAM_DEV(NTID);
5306 		param[1] = FW_PARAM_PFVF(SERVER_START);
5307 		param[2] = FW_PARAM_PFVF(SERVER_END);
5308 		param[3] = FW_PARAM_PFVF(TDDP_START);
5309 		param[4] = FW_PARAM_PFVF(TDDP_END);
5310 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5311 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5312 		if (rc != 0) {
5313 			device_printf(sc->dev,
5314 			    "failed to query TOE parameters: %d.\n", rc);
5315 			return (rc);
5316 		}
5317 		sc->tids.ntids = val[0];
5318 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5319 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5320 			sc->tids.ntids -= sc->tids.nhpftids;
5321 		}
5322 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5323 		if ((int)val[2] > (int)val[1]) {
5324 			sc->tids.stid_base = val[1];
5325 			sc->tids.nstids = val[2] - val[1] + 1;
5326 		}
5327 		sc->vres.ddp.start = val[3];
5328 		sc->vres.ddp.size = val[4] - val[3] + 1;
5329 		sc->params.ofldq_wr_cred = val[5];
5330 		sc->params.offload = 1;
5331 	} else {
5332 		/*
5333 		 * The firmware attempts memfree TOE configuration for -SO cards
5334 		 * and will report toecaps=0 if it runs out of resources (this
5335 		 * depends on the config file).  It may not report 0 for other
5336 		 * capabilities dependent on the TOE in this case.  Set them to
5337 		 * 0 here so that the driver doesn't bother tracking resources
5338 		 * that will never be used.
5339 		 */
5340 		sc->iscsicaps = 0;
5341 		sc->rdmacaps = 0;
5342 	}
5343 	if (sc->rdmacaps) {
5344 		param[0] = FW_PARAM_PFVF(STAG_START);
5345 		param[1] = FW_PARAM_PFVF(STAG_END);
5346 		param[2] = FW_PARAM_PFVF(RQ_START);
5347 		param[3] = FW_PARAM_PFVF(RQ_END);
5348 		param[4] = FW_PARAM_PFVF(PBL_START);
5349 		param[5] = FW_PARAM_PFVF(PBL_END);
5350 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5351 		if (rc != 0) {
5352 			device_printf(sc->dev,
5353 			    "failed to query RDMA parameters(1): %d.\n", rc);
5354 			return (rc);
5355 		}
5356 		sc->vres.stag.start = val[0];
5357 		sc->vres.stag.size = val[1] - val[0] + 1;
5358 		sc->vres.rq.start = val[2];
5359 		sc->vres.rq.size = val[3] - val[2] + 1;
5360 		sc->vres.pbl.start = val[4];
5361 		sc->vres.pbl.size = val[5] - val[4] + 1;
5362 
5363 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5364 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5365 		param[2] = FW_PARAM_PFVF(CQ_START);
5366 		param[3] = FW_PARAM_PFVF(CQ_END);
5367 		param[4] = FW_PARAM_PFVF(OCQ_START);
5368 		param[5] = FW_PARAM_PFVF(OCQ_END);
5369 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5370 		if (rc != 0) {
5371 			device_printf(sc->dev,
5372 			    "failed to query RDMA parameters(2): %d.\n", rc);
5373 			return (rc);
5374 		}
5375 		sc->vres.qp.start = val[0];
5376 		sc->vres.qp.size = val[1] - val[0] + 1;
5377 		sc->vres.cq.start = val[2];
5378 		sc->vres.cq.size = val[3] - val[2] + 1;
5379 		sc->vres.ocq.start = val[4];
5380 		sc->vres.ocq.size = val[5] - val[4] + 1;
5381 
5382 		param[0] = FW_PARAM_PFVF(SRQ_START);
5383 		param[1] = FW_PARAM_PFVF(SRQ_END);
5384 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5385 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5386 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5387 		if (rc != 0) {
5388 			device_printf(sc->dev,
5389 			    "failed to query RDMA parameters(3): %d.\n", rc);
5390 			return (rc);
5391 		}
5392 		sc->vres.srq.start = val[0];
5393 		sc->vres.srq.size = val[1] - val[0] + 1;
5394 		sc->params.max_ordird_qp = val[2];
5395 		sc->params.max_ird_adapter = val[3];
5396 	}
5397 	if (sc->iscsicaps) {
5398 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5399 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5400 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5401 		if (rc != 0) {
5402 			device_printf(sc->dev,
5403 			    "failed to query iSCSI parameters: %d.\n", rc);
5404 			return (rc);
5405 		}
5406 		sc->vres.iscsi.start = val[0];
5407 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5408 	}
5409 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5410 		param[0] = FW_PARAM_PFVF(TLS_START);
5411 		param[1] = FW_PARAM_PFVF(TLS_END);
5412 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5413 		if (rc != 0) {
5414 			device_printf(sc->dev,
5415 			    "failed to query TLS parameters: %d.\n", rc);
5416 			return (rc);
5417 		}
5418 		sc->vres.key.start = val[0];
5419 		sc->vres.key.size = val[1] - val[0] + 1;
5420 	}
5421 
5422 	/*
5423 	 * We've got the params we wanted to query directly from the firmware.
5424 	 * Grab some others via other means.
5425 	 */
5426 	t4_init_sge_params(sc);
5427 	t4_init_tp_params(sc);
5428 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5429 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5430 
5431 	rc = t4_verify_chip_settings(sc);
5432 	if (rc != 0)
5433 		return (rc);
5434 	t4_init_rx_buf_info(sc);
5435 
5436 	return (rc);
5437 }
5438 
5439 #ifdef KERN_TLS
5440 static void
5441 ktls_tick(void *arg)
5442 {
5443 	struct adapter *sc;
5444 	uint32_t tstamp;
5445 
5446 	sc = arg;
5447 	if (sc->flags & KERN_TLS_ON) {
5448 		tstamp = tcp_ts_getticks();
5449 		t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5450 		t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5451 	}
5452 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5453 }
5454 
5455 static int
5456 t4_config_kern_tls(struct adapter *sc, bool enable)
5457 {
5458 	int rc;
5459 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5460 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5461 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5462 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5463 
5464 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5465 	if (rc != 0) {
5466 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5467 		    enable ?  "enable" : "disable", rc);
5468 		return (rc);
5469 	}
5470 
5471 	if (enable)
5472 		sc->flags |= KERN_TLS_ON;
5473 	else
5474 		sc->flags &= ~KERN_TLS_ON;
5475 
5476 	return (rc);
5477 }
5478 #endif
5479 
5480 static int
5481 set_params__post_init(struct adapter *sc)
5482 {
5483 	uint32_t mask, param, val;
5484 #ifdef TCP_OFFLOAD
5485 	int i, v, shift;
5486 #endif
5487 
5488 	/* ask for encapsulated CPLs */
5489 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5490 	val = 1;
5491 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5492 
5493 	/* Enable 32b port caps if the firmware supports it. */
5494 	param = FW_PARAM_PFVF(PORT_CAPS32);
5495 	val = 1;
5496 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5497 		sc->params.port_caps32 = 1;
5498 
5499 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5500 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5501 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5502 	    V_MASKFILTER(val - 1));
5503 
5504 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5505 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5506 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5507 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5508 	val = 0;
5509 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5510 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5511 		    F_ATTACKFILTERENABLE);
5512 		val |= F_DROPERRORATTACK;
5513 	}
5514 	if (t4_drop_ip_fragments != 0) {
5515 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5516 		    F_FRAGMENTDROP);
5517 		val |= F_DROPERRORFRAG;
5518 	}
5519 	if (t4_drop_pkts_with_l2_errors != 0)
5520 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5521 	if (t4_drop_pkts_with_l3_errors != 0) {
5522 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5523 		    F_DROPERRORCSUMIP;
5524 	}
5525 	if (t4_drop_pkts_with_l4_errors != 0) {
5526 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5527 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5528 	}
5529 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5530 
5531 #ifdef TCP_OFFLOAD
5532 	/*
5533 	 * Override the TOE timers with user provided tunables.  This is not the
5534 	 * recommended way to change the timers (the firmware config file is) so
5535 	 * these tunables are not documented.
5536 	 *
5537 	 * All the timer tunables are in microseconds.
5538 	 */
5539 	if (t4_toe_keepalive_idle != 0) {
5540 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5541 		v &= M_KEEPALIVEIDLE;
5542 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5543 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5544 	}
5545 	if (t4_toe_keepalive_interval != 0) {
5546 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5547 		v &= M_KEEPALIVEINTVL;
5548 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5549 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5550 	}
5551 	if (t4_toe_keepalive_count != 0) {
5552 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5553 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5554 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5555 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5556 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5557 	}
5558 	if (t4_toe_rexmt_min != 0) {
5559 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5560 		v &= M_RXTMIN;
5561 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5562 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5563 	}
5564 	if (t4_toe_rexmt_max != 0) {
5565 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5566 		v &= M_RXTMAX;
5567 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5568 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5569 	}
5570 	if (t4_toe_rexmt_count != 0) {
5571 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5572 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5573 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5574 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5575 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5576 	}
5577 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5578 		if (t4_toe_rexmt_backoff[i] != -1) {
5579 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5580 			shift = (i & 3) << 3;
5581 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5582 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5583 		}
5584 	}
5585 #endif
5586 
5587 #ifdef KERN_TLS
5588 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS &&
5589 	    sc->toecaps & FW_CAPS_CONFIG_TOE) {
5590 		/*
5591 		 * Limit TOE connections to 2 reassembly "islands".  This is
5592 		 * required for TOE TLS connections to downgrade to plain TOE
5593 		 * connections if an unsupported TLS version or ciphersuite is
5594 		 * used.
5595 		 */
5596 		t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG,
5597 		    V_PASSMODE(M_PASSMODE), V_PASSMODE(2));
5598 		if (is_ktls(sc)) {
5599 			sc->tlst.inline_keys = t4_tls_inline_keys;
5600 			sc->tlst.combo_wrs = t4_tls_combo_wrs;
5601 			if (t4_kern_tls != 0)
5602 				t4_config_kern_tls(sc, true);
5603 		}
5604 	}
5605 #endif
5606 	return (0);
5607 }
5608 
5609 #undef FW_PARAM_PFVF
5610 #undef FW_PARAM_DEV
5611 
5612 static void
5613 t4_set_desc(struct adapter *sc)
5614 {
5615 	char buf[128];
5616 	struct adapter_params *p = &sc->params;
5617 
5618 	snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
5619 
5620 	device_set_desc_copy(sc->dev, buf);
5621 }
5622 
5623 static inline void
5624 ifmedia_add4(struct ifmedia *ifm, int m)
5625 {
5626 
5627 	ifmedia_add(ifm, m, 0, NULL);
5628 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5629 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5630 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5631 }
5632 
5633 /*
5634  * This is the selected media, which is not quite the same as the active media.
5635  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5636  * and active are not the same, and "media: Ethernet selected" otherwise.
5637  */
5638 static void
5639 set_current_media(struct port_info *pi)
5640 {
5641 	struct link_config *lc;
5642 	struct ifmedia *ifm;
5643 	int mword;
5644 	u_int speed;
5645 
5646 	PORT_LOCK_ASSERT_OWNED(pi);
5647 
5648 	/* Leave current media alone if it's already set to IFM_NONE. */
5649 	ifm = &pi->media;
5650 	if (ifm->ifm_cur != NULL &&
5651 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5652 		return;
5653 
5654 	lc = &pi->link_cfg;
5655 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5656 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5657 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5658 		return;
5659 	}
5660 	mword = IFM_ETHER | IFM_FDX;
5661 	if (lc->requested_fc & PAUSE_TX)
5662 		mword |= IFM_ETH_TXPAUSE;
5663 	if (lc->requested_fc & PAUSE_RX)
5664 		mword |= IFM_ETH_RXPAUSE;
5665 	if (lc->requested_speed == 0)
5666 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5667 	else
5668 		speed = lc->requested_speed;
5669 	mword |= port_mword(pi, speed_to_fwcap(speed));
5670 	ifmedia_set(ifm, mword);
5671 }
5672 
5673 /*
5674  * Returns true if the ifmedia list for the port cannot change.
5675  */
5676 static bool
5677 fixed_ifmedia(struct port_info *pi)
5678 {
5679 
5680 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5681 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5682 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5683 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5684 	    pi->port_type == FW_PORT_TYPE_KX ||
5685 	    pi->port_type == FW_PORT_TYPE_KR ||
5686 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5687 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5688 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5689 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5690 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5691 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5692 }
5693 
5694 static void
5695 build_medialist(struct port_info *pi)
5696 {
5697 	uint32_t ss, speed;
5698 	int unknown, mword, bit;
5699 	struct link_config *lc;
5700 	struct ifmedia *ifm;
5701 
5702 	PORT_LOCK_ASSERT_OWNED(pi);
5703 
5704 	if (pi->flags & FIXED_IFMEDIA)
5705 		return;
5706 
5707 	/*
5708 	 * Rebuild the ifmedia list.
5709 	 */
5710 	ifm = &pi->media;
5711 	ifmedia_removeall(ifm);
5712 	lc = &pi->link_cfg;
5713 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5714 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5715 		MPASS(ss != 0);
5716 no_media:
5717 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5718 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5719 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5720 		return;
5721 	}
5722 
5723 	unknown = 0;
5724 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5725 		speed = 1 << bit;
5726 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5727 		if (ss & speed) {
5728 			mword = port_mword(pi, speed);
5729 			if (mword == IFM_NONE) {
5730 				goto no_media;
5731 			} else if (mword == IFM_UNKNOWN)
5732 				unknown++;
5733 			else
5734 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5735 		}
5736 	}
5737 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5738 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5739 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5740 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5741 
5742 	set_current_media(pi);
5743 }
5744 
5745 /*
5746  * Initialize the requested fields in the link config based on driver tunables.
5747  */
5748 static void
5749 init_link_config(struct port_info *pi)
5750 {
5751 	struct link_config *lc = &pi->link_cfg;
5752 
5753 	PORT_LOCK_ASSERT_OWNED(pi);
5754 
5755 	lc->requested_speed = 0;
5756 
5757 	if (t4_autoneg == 0)
5758 		lc->requested_aneg = AUTONEG_DISABLE;
5759 	else if (t4_autoneg == 1)
5760 		lc->requested_aneg = AUTONEG_ENABLE;
5761 	else
5762 		lc->requested_aneg = AUTONEG_AUTO;
5763 
5764 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5765 	    PAUSE_AUTONEG);
5766 
5767 	if (t4_fec & FEC_AUTO)
5768 		lc->requested_fec = FEC_AUTO;
5769 	else if (t4_fec == 0)
5770 		lc->requested_fec = FEC_NONE;
5771 	else {
5772 		/* -1 is handled by the FEC_AUTO block above and not here. */
5773 		lc->requested_fec = t4_fec &
5774 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5775 		if (lc->requested_fec == 0)
5776 			lc->requested_fec = FEC_AUTO;
5777 	}
5778 }
5779 
5780 /*
5781  * Makes sure that all requested settings comply with what's supported by the
5782  * port.  Returns the number of settings that were invalid and had to be fixed.
5783  */
5784 static int
5785 fixup_link_config(struct port_info *pi)
5786 {
5787 	int n = 0;
5788 	struct link_config *lc = &pi->link_cfg;
5789 	uint32_t fwspeed;
5790 
5791 	PORT_LOCK_ASSERT_OWNED(pi);
5792 
5793 	/* Speed (when not autonegotiating) */
5794 	if (lc->requested_speed != 0) {
5795 		fwspeed = speed_to_fwcap(lc->requested_speed);
5796 		if ((fwspeed & lc->pcaps) == 0) {
5797 			n++;
5798 			lc->requested_speed = 0;
5799 		}
5800 	}
5801 
5802 	/* Link autonegotiation */
5803 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5804 	    lc->requested_aneg == AUTONEG_DISABLE ||
5805 	    lc->requested_aneg == AUTONEG_AUTO);
5806 	if (lc->requested_aneg == AUTONEG_ENABLE &&
5807 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5808 		n++;
5809 		lc->requested_aneg = AUTONEG_AUTO;
5810 	}
5811 
5812 	/* Flow control */
5813 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5814 	if (lc->requested_fc & PAUSE_TX &&
5815 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5816 		n++;
5817 		lc->requested_fc &= ~PAUSE_TX;
5818 	}
5819 	if (lc->requested_fc & PAUSE_RX &&
5820 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
5821 		n++;
5822 		lc->requested_fc &= ~PAUSE_RX;
5823 	}
5824 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
5825 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
5826 		n++;
5827 		lc->requested_fc |= PAUSE_AUTONEG;
5828 	}
5829 
5830 	/* FEC */
5831 	if ((lc->requested_fec & FEC_RS &&
5832 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
5833 	    (lc->requested_fec & FEC_BASER_RS &&
5834 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
5835 		n++;
5836 		lc->requested_fec = FEC_AUTO;
5837 	}
5838 
5839 	return (n);
5840 }
5841 
5842 /*
5843  * Apply the requested L1 settings, which are expected to be valid, to the
5844  * hardware.
5845  */
5846 static int
5847 apply_link_config(struct port_info *pi)
5848 {
5849 	struct adapter *sc = pi->adapter;
5850 	struct link_config *lc = &pi->link_cfg;
5851 	int rc;
5852 
5853 #ifdef INVARIANTS
5854 	ASSERT_SYNCHRONIZED_OP(sc);
5855 	PORT_LOCK_ASSERT_OWNED(pi);
5856 
5857 	if (lc->requested_aneg == AUTONEG_ENABLE)
5858 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
5859 	if (!(lc->requested_fc & PAUSE_AUTONEG))
5860 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
5861 	if (lc->requested_fc & PAUSE_TX)
5862 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
5863 	if (lc->requested_fc & PAUSE_RX)
5864 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
5865 	if (lc->requested_fec & FEC_RS)
5866 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
5867 	if (lc->requested_fec & FEC_BASER_RS)
5868 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
5869 #endif
5870 	rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
5871 	if (rc != 0) {
5872 		/* Don't complain if the VF driver gets back an EPERM. */
5873 		if (!(sc->flags & IS_VF) || rc != FW_EPERM)
5874 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
5875 	} else {
5876 		/*
5877 		 * An L1_CFG will almost always result in a link-change event if
5878 		 * the link is up, and the driver will refresh the actual
5879 		 * fec/fc/etc. when the notification is processed.  If the link
5880 		 * is down then the actual settings are meaningless.
5881 		 *
5882 		 * This takes care of the case where a change in the L1 settings
5883 		 * may not result in a notification.
5884 		 */
5885 		if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
5886 			lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
5887 	}
5888 	return (rc);
5889 }
5890 
5891 #define FW_MAC_EXACT_CHUNK	7
5892 struct mcaddr_ctx {
5893 	struct ifnet *ifp;
5894 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
5895 	uint64_t hash;
5896 	int i;
5897 	int del;
5898 	int rc;
5899 };
5900 
5901 static u_int
5902 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
5903 {
5904 	struct mcaddr_ctx *ctx = arg;
5905 	struct vi_info *vi = ctx->ifp->if_softc;
5906 	struct port_info *pi = vi->pi;
5907 	struct adapter *sc = pi->adapter;
5908 
5909 	if (ctx->rc < 0)
5910 		return (0);
5911 
5912 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
5913 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
5914 	ctx->i++;
5915 
5916 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
5917 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
5918 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
5919 		if (ctx->rc < 0) {
5920 			int j;
5921 
5922 			for (j = 0; j < ctx->i; j++) {
5923 				if_printf(ctx->ifp,
5924 				    "failed to add mc address"
5925 				    " %02x:%02x:%02x:"
5926 				    "%02x:%02x:%02x rc=%d\n",
5927 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
5928 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
5929 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
5930 				    -ctx->rc);
5931 			}
5932 			return (0);
5933 		}
5934 		ctx->del = 0;
5935 		ctx->i = 0;
5936 	}
5937 
5938 	return (1);
5939 }
5940 
5941 /*
5942  * Program the port's XGMAC based on parameters in ifnet.  The caller also
5943  * indicates which parameters should be programmed (the rest are left alone).
5944  */
5945 int
5946 update_mac_settings(struct ifnet *ifp, int flags)
5947 {
5948 	int rc = 0;
5949 	struct vi_info *vi = ifp->if_softc;
5950 	struct port_info *pi = vi->pi;
5951 	struct adapter *sc = pi->adapter;
5952 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
5953 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
5954 
5955 	ASSERT_SYNCHRONIZED_OP(sc);
5956 	KASSERT(flags, ("%s: not told what to update.", __func__));
5957 
5958 	if (flags & XGMAC_MTU)
5959 		mtu = ifp->if_mtu;
5960 
5961 	if (flags & XGMAC_PROMISC)
5962 		promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
5963 
5964 	if (flags & XGMAC_ALLMULTI)
5965 		allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
5966 
5967 	if (flags & XGMAC_VLANEX)
5968 		vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
5969 
5970 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
5971 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
5972 		    allmulti, 1, vlanex, false);
5973 		if (rc) {
5974 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
5975 			    rc);
5976 			return (rc);
5977 		}
5978 	}
5979 
5980 	if (flags & XGMAC_UCADDR) {
5981 		uint8_t ucaddr[ETHER_ADDR_LEN];
5982 
5983 		bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
5984 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
5985 		    ucaddr, true, &vi->smt_idx);
5986 		if (rc < 0) {
5987 			rc = -rc;
5988 			if_printf(ifp, "change_mac failed: %d\n", rc);
5989 			return (rc);
5990 		} else {
5991 			vi->xact_addr_filt = rc;
5992 			rc = 0;
5993 		}
5994 	}
5995 
5996 	if (flags & XGMAC_MCADDRS) {
5997 		struct epoch_tracker et;
5998 		struct mcaddr_ctx ctx;
5999 		int j;
6000 
6001 		ctx.ifp = ifp;
6002 		ctx.hash = 0;
6003 		ctx.i = 0;
6004 		ctx.del = 1;
6005 		ctx.rc = 0;
6006 		/*
6007 		 * Unlike other drivers, we accumulate list of pointers into
6008 		 * interface address lists and we need to keep it safe even
6009 		 * after if_foreach_llmaddr() returns, thus we must enter the
6010 		 * network epoch.
6011 		 */
6012 		NET_EPOCH_ENTER(et);
6013 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6014 		if (ctx.rc < 0) {
6015 			NET_EPOCH_EXIT(et);
6016 			rc = -ctx.rc;
6017 			return (rc);
6018 		}
6019 		if (ctx.i > 0) {
6020 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6021 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6022 			NET_EPOCH_EXIT(et);
6023 			if (rc < 0) {
6024 				rc = -rc;
6025 				for (j = 0; j < ctx.i; j++) {
6026 					if_printf(ifp,
6027 					    "failed to add mcast address"
6028 					    " %02x:%02x:%02x:"
6029 					    "%02x:%02x:%02x rc=%d\n",
6030 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6031 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6032 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6033 					    rc);
6034 				}
6035 				return (rc);
6036 			}
6037 			ctx.del = 0;
6038 		} else
6039 			NET_EPOCH_EXIT(et);
6040 
6041 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6042 		if (rc != 0)
6043 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6044 			    rc);
6045 		if (ctx.del == 0) {
6046 			/* We clobbered the VXLAN entry if there was one. */
6047 			pi->vxlan_tcam_entry = false;
6048 		}
6049 	}
6050 
6051 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6052 	    pi->vxlan_tcam_entry == false) {
6053 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6054 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6055 		    true);
6056 		if (rc < 0) {
6057 			rc = -rc;
6058 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6059 			    rc);
6060 		} else {
6061 			MPASS(rc == sc->rawf_base + pi->port_id);
6062 			rc = 0;
6063 			pi->vxlan_tcam_entry = true;
6064 		}
6065 	}
6066 
6067 	return (rc);
6068 }
6069 
6070 /*
6071  * {begin|end}_synchronized_op must be called from the same thread.
6072  */
6073 int
6074 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6075     char *wmesg)
6076 {
6077 	int rc, pri;
6078 
6079 #ifdef WITNESS
6080 	/* the caller thinks it's ok to sleep, but is it really? */
6081 	if (flags & SLEEP_OK)
6082 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6083 		    "begin_synchronized_op");
6084 #endif
6085 
6086 	if (INTR_OK)
6087 		pri = PCATCH;
6088 	else
6089 		pri = 0;
6090 
6091 	ADAPTER_LOCK(sc);
6092 	for (;;) {
6093 
6094 		if (vi && IS_DOOMED(vi)) {
6095 			rc = ENXIO;
6096 			goto done;
6097 		}
6098 
6099 		if (!IS_BUSY(sc)) {
6100 			rc = 0;
6101 			break;
6102 		}
6103 
6104 		if (!(flags & SLEEP_OK)) {
6105 			rc = EBUSY;
6106 			goto done;
6107 		}
6108 
6109 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6110 			rc = EINTR;
6111 			goto done;
6112 		}
6113 	}
6114 
6115 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6116 	SET_BUSY(sc);
6117 #ifdef INVARIANTS
6118 	sc->last_op = wmesg;
6119 	sc->last_op_thr = curthread;
6120 	sc->last_op_flags = flags;
6121 #endif
6122 
6123 done:
6124 	if (!(flags & HOLD_LOCK) || rc)
6125 		ADAPTER_UNLOCK(sc);
6126 
6127 	return (rc);
6128 }
6129 
6130 /*
6131  * Tell if_ioctl and if_init that the VI is going away.  This is
6132  * special variant of begin_synchronized_op and must be paired with a
6133  * call to end_synchronized_op.
6134  */
6135 void
6136 doom_vi(struct adapter *sc, struct vi_info *vi)
6137 {
6138 
6139 	ADAPTER_LOCK(sc);
6140 	SET_DOOMED(vi);
6141 	wakeup(&sc->flags);
6142 	while (IS_BUSY(sc))
6143 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6144 	SET_BUSY(sc);
6145 #ifdef INVARIANTS
6146 	sc->last_op = "t4detach";
6147 	sc->last_op_thr = curthread;
6148 	sc->last_op_flags = 0;
6149 #endif
6150 	ADAPTER_UNLOCK(sc);
6151 }
6152 
6153 /*
6154  * {begin|end}_synchronized_op must be called from the same thread.
6155  */
6156 void
6157 end_synchronized_op(struct adapter *sc, int flags)
6158 {
6159 
6160 	if (flags & LOCK_HELD)
6161 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6162 	else
6163 		ADAPTER_LOCK(sc);
6164 
6165 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6166 	CLR_BUSY(sc);
6167 	wakeup(&sc->flags);
6168 	ADAPTER_UNLOCK(sc);
6169 }
6170 
6171 static int
6172 cxgbe_init_synchronized(struct vi_info *vi)
6173 {
6174 	struct port_info *pi = vi->pi;
6175 	struct adapter *sc = pi->adapter;
6176 	struct ifnet *ifp = vi->ifp;
6177 	int rc = 0, i;
6178 	struct sge_txq *txq;
6179 
6180 	ASSERT_SYNCHRONIZED_OP(sc);
6181 
6182 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
6183 		return (0);	/* already running */
6184 
6185 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6186 		return (rc);	/* error message displayed already */
6187 
6188 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6189 		return (rc); /* error message displayed already */
6190 
6191 	rc = update_mac_settings(ifp, XGMAC_ALL);
6192 	if (rc)
6193 		goto done;	/* error message displayed already */
6194 
6195 	PORT_LOCK(pi);
6196 	if (pi->up_vis == 0) {
6197 		t4_update_port_info(pi);
6198 		fixup_link_config(pi);
6199 		build_medialist(pi);
6200 		apply_link_config(pi);
6201 	}
6202 
6203 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6204 	if (rc != 0) {
6205 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6206 		PORT_UNLOCK(pi);
6207 		goto done;
6208 	}
6209 
6210 	/*
6211 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6212 	 * if this changes.
6213 	 */
6214 
6215 	for_each_txq(vi, i, txq) {
6216 		TXQ_LOCK(txq);
6217 		txq->eq.flags |= EQ_ENABLED;
6218 		TXQ_UNLOCK(txq);
6219 	}
6220 
6221 	/*
6222 	 * The first iq of the first port to come up is used for tracing.
6223 	 */
6224 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6225 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6226 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6227 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6228 		    V_QUEUENUMBER(sc->traceq));
6229 		pi->flags |= HAS_TRACEQ;
6230 	}
6231 
6232 	/* all ok */
6233 	pi->up_vis++;
6234 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
6235 	if (pi->link_cfg.link_ok)
6236 		t4_os_link_changed(pi);
6237 	PORT_UNLOCK(pi);
6238 
6239 	mtx_lock(&vi->tick_mtx);
6240 	if (ifp->if_get_counter == vi_get_counter)
6241 		callout_reset(&vi->tick, hz, vi_tick, vi);
6242 	else
6243 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6244 	mtx_unlock(&vi->tick_mtx);
6245 done:
6246 	if (rc != 0)
6247 		cxgbe_uninit_synchronized(vi);
6248 
6249 	return (rc);
6250 }
6251 
6252 /*
6253  * Idempotent.
6254  */
6255 static int
6256 cxgbe_uninit_synchronized(struct vi_info *vi)
6257 {
6258 	struct port_info *pi = vi->pi;
6259 	struct adapter *sc = pi->adapter;
6260 	struct ifnet *ifp = vi->ifp;
6261 	int rc, i;
6262 	struct sge_txq *txq;
6263 
6264 	ASSERT_SYNCHRONIZED_OP(sc);
6265 
6266 	if (!(vi->flags & VI_INIT_DONE)) {
6267 		if (__predict_false(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6268 			KASSERT(0, ("uninited VI is running"));
6269 			if_printf(ifp, "uninited VI with running ifnet.  "
6270 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6271 			    "if_drv_flags 0x%08x\n", vi->flags, ifp->if_flags,
6272 			    ifp->if_drv_flags);
6273 		}
6274 		return (0);
6275 	}
6276 
6277 	/*
6278 	 * Disable the VI so that all its data in either direction is discarded
6279 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6280 	 * tick) intact as the TP can deliver negative advice or data that it's
6281 	 * holding in its RAM (for an offloaded connection) even after the VI is
6282 	 * disabled.
6283 	 */
6284 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6285 	if (rc) {
6286 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6287 		return (rc);
6288 	}
6289 
6290 	for_each_txq(vi, i, txq) {
6291 		TXQ_LOCK(txq);
6292 		txq->eq.flags &= ~EQ_ENABLED;
6293 		TXQ_UNLOCK(txq);
6294 	}
6295 
6296 	mtx_lock(&vi->tick_mtx);
6297 	callout_stop(&vi->tick);
6298 	mtx_unlock(&vi->tick_mtx);
6299 
6300 	PORT_LOCK(pi);
6301 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6302 		PORT_UNLOCK(pi);
6303 		return (0);
6304 	}
6305 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
6306 	pi->up_vis--;
6307 	if (pi->up_vis > 0) {
6308 		PORT_UNLOCK(pi);
6309 		return (0);
6310 	}
6311 
6312 	pi->link_cfg.link_ok = false;
6313 	pi->link_cfg.speed = 0;
6314 	pi->link_cfg.link_down_rc = 255;
6315 	t4_os_link_changed(pi);
6316 	PORT_UNLOCK(pi);
6317 
6318 	return (0);
6319 }
6320 
6321 /*
6322  * It is ok for this function to fail midway and return right away.  t4_detach
6323  * will walk the entire sc->irq list and clean up whatever is valid.
6324  */
6325 int
6326 t4_setup_intr_handlers(struct adapter *sc)
6327 {
6328 	int rc, rid, p, q, v;
6329 	char s[8];
6330 	struct irq *irq;
6331 	struct port_info *pi;
6332 	struct vi_info *vi;
6333 	struct sge *sge = &sc->sge;
6334 	struct sge_rxq *rxq;
6335 #ifdef TCP_OFFLOAD
6336 	struct sge_ofld_rxq *ofld_rxq;
6337 #endif
6338 #ifdef DEV_NETMAP
6339 	struct sge_nm_rxq *nm_rxq;
6340 #endif
6341 #ifdef RSS
6342 	int nbuckets = rss_getnumbuckets();
6343 #endif
6344 
6345 	/*
6346 	 * Setup interrupts.
6347 	 */
6348 	irq = &sc->irq[0];
6349 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6350 	if (forwarding_intr_to_fwq(sc))
6351 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6352 
6353 	/* Multiple interrupts. */
6354 	if (sc->flags & IS_VF)
6355 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6356 		    ("%s: too few intr.", __func__));
6357 	else
6358 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6359 		    ("%s: too few intr.", __func__));
6360 
6361 	/* The first one is always error intr on PFs */
6362 	if (!(sc->flags & IS_VF)) {
6363 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6364 		if (rc != 0)
6365 			return (rc);
6366 		irq++;
6367 		rid++;
6368 	}
6369 
6370 	/* The second one is always the firmware event queue (first on VFs) */
6371 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6372 	if (rc != 0)
6373 		return (rc);
6374 	irq++;
6375 	rid++;
6376 
6377 	for_each_port(sc, p) {
6378 		pi = sc->port[p];
6379 		for_each_vi(pi, v, vi) {
6380 			vi->first_intr = rid - 1;
6381 
6382 			if (vi->nnmrxq > 0) {
6383 				int n = max(vi->nrxq, vi->nnmrxq);
6384 
6385 				rxq = &sge->rxq[vi->first_rxq];
6386 #ifdef DEV_NETMAP
6387 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6388 #endif
6389 				for (q = 0; q < n; q++) {
6390 					snprintf(s, sizeof(s), "%x%c%x", p,
6391 					    'a' + v, q);
6392 					if (q < vi->nrxq)
6393 						irq->rxq = rxq++;
6394 #ifdef DEV_NETMAP
6395 					if (q < vi->nnmrxq)
6396 						irq->nm_rxq = nm_rxq++;
6397 
6398 					if (irq->nm_rxq != NULL &&
6399 					    irq->rxq == NULL) {
6400 						/* Netmap rx only */
6401 						rc = t4_alloc_irq(sc, irq, rid,
6402 						    t4_nm_intr, irq->nm_rxq, s);
6403 					}
6404 					if (irq->nm_rxq != NULL &&
6405 					    irq->rxq != NULL) {
6406 						/* NIC and Netmap rx */
6407 						rc = t4_alloc_irq(sc, irq, rid,
6408 						    t4_vi_intr, irq, s);
6409 					}
6410 #endif
6411 					if (irq->rxq != NULL &&
6412 					    irq->nm_rxq == NULL) {
6413 						/* NIC rx only */
6414 						rc = t4_alloc_irq(sc, irq, rid,
6415 						    t4_intr, irq->rxq, s);
6416 					}
6417 					if (rc != 0)
6418 						return (rc);
6419 #ifdef RSS
6420 					if (q < vi->nrxq) {
6421 						bus_bind_intr(sc->dev, irq->res,
6422 						    rss_getcpu(q % nbuckets));
6423 					}
6424 #endif
6425 					irq++;
6426 					rid++;
6427 					vi->nintr++;
6428 				}
6429 			} else {
6430 				for_each_rxq(vi, q, rxq) {
6431 					snprintf(s, sizeof(s), "%x%c%x", p,
6432 					    'a' + v, q);
6433 					rc = t4_alloc_irq(sc, irq, rid,
6434 					    t4_intr, rxq, s);
6435 					if (rc != 0)
6436 						return (rc);
6437 #ifdef RSS
6438 					bus_bind_intr(sc->dev, irq->res,
6439 					    rss_getcpu(q % nbuckets));
6440 #endif
6441 					irq++;
6442 					rid++;
6443 					vi->nintr++;
6444 				}
6445 			}
6446 #ifdef TCP_OFFLOAD
6447 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6448 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6449 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6450 				    ofld_rxq, s);
6451 				if (rc != 0)
6452 					return (rc);
6453 				irq++;
6454 				rid++;
6455 				vi->nintr++;
6456 			}
6457 #endif
6458 		}
6459 	}
6460 	MPASS(irq == &sc->irq[sc->intr_count]);
6461 
6462 	return (0);
6463 }
6464 
6465 static void
6466 write_global_rss_key(struct adapter *sc)
6467 {
6468 #ifdef RSS
6469 	int i;
6470 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6471 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6472 
6473 	CTASSERT(RSS_KEYSIZE == 40);
6474 
6475 	rss_getkey((void *)&raw_rss_key[0]);
6476 	for (i = 0; i < nitems(rss_key); i++) {
6477 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6478 	}
6479 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6480 #endif
6481 }
6482 
6483 /*
6484  * Idempotent.
6485  */
6486 static int
6487 adapter_full_init(struct adapter *sc)
6488 {
6489 	int rc, i;
6490 
6491 	ASSERT_SYNCHRONIZED_OP(sc);
6492 
6493 	if (!(sc->flags & ADAP_SYSCTL_CTX)) {
6494 		sysctl_ctx_init(&sc->ctx);
6495 		sc->flags |= ADAP_SYSCTL_CTX;
6496 	}
6497 
6498 	/*
6499 	 * queues that belong to the adapter (not any particular port).
6500 	 */
6501 	rc = t4_setup_adapter_queues(sc);
6502 	if (rc != 0)
6503 		return (rc);
6504 
6505 	for (i = 0; i < nitems(sc->tq); i++) {
6506 		if (sc->tq[i] != NULL)
6507 			continue;
6508 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6509 		    taskqueue_thread_enqueue, &sc->tq[i]);
6510 		if (sc->tq[i] == NULL) {
6511 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6512 			return (ENOMEM);
6513 		}
6514 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6515 		    device_get_nameunit(sc->dev), i);
6516 	}
6517 
6518 	if (!(sc->flags & IS_VF)) {
6519 		write_global_rss_key(sc);
6520 		t4_intr_enable(sc);
6521 	}
6522 #ifdef KERN_TLS
6523 	if (is_ktls(sc))
6524 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
6525 		    C_HARDCLOCK);
6526 #endif
6527 	return (0);
6528 }
6529 
6530 int
6531 adapter_init(struct adapter *sc)
6532 {
6533 	int rc;
6534 
6535 	ASSERT_SYNCHRONIZED_OP(sc);
6536 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6537 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6538 	    ("%s: FULL_INIT_DONE already", __func__));
6539 
6540 	rc = adapter_full_init(sc);
6541 	if (rc != 0)
6542 		adapter_full_uninit(sc);
6543 	else
6544 		sc->flags |= FULL_INIT_DONE;
6545 
6546 	return (rc);
6547 }
6548 
6549 /*
6550  * Idempotent.
6551  */
6552 static void
6553 adapter_full_uninit(struct adapter *sc)
6554 {
6555 	int i;
6556 
6557 	/* Do this before freeing the adapter queues. */
6558 	if (sc->flags & ADAP_SYSCTL_CTX) {
6559 		sysctl_ctx_free(&sc->ctx);
6560 		sc->flags &= ~ADAP_SYSCTL_CTX;
6561 	}
6562 
6563 	t4_teardown_adapter_queues(sc);
6564 
6565 	for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
6566 		taskqueue_free(sc->tq[i]);
6567 		sc->tq[i] = NULL;
6568 	}
6569 
6570 	sc->flags &= ~FULL_INIT_DONE;
6571 }
6572 
6573 #ifdef RSS
6574 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6575     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6576     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6577     RSS_HASHTYPE_RSS_UDP_IPV6)
6578 
6579 /* Translates kernel hash types to hardware. */
6580 static int
6581 hashconfig_to_hashen(int hashconfig)
6582 {
6583 	int hashen = 0;
6584 
6585 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6586 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6587 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6588 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6589 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6590 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6591 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6592 	}
6593 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6594 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6595 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6596 	}
6597 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6598 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6599 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6600 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6601 
6602 	return (hashen);
6603 }
6604 
6605 /* Translates hardware hash types to kernel. */
6606 static int
6607 hashen_to_hashconfig(int hashen)
6608 {
6609 	int hashconfig = 0;
6610 
6611 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6612 		/*
6613 		 * If UDP hashing was enabled it must have been enabled for
6614 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6615 		 * enabling any 4-tuple hash is nonsense configuration.
6616 		 */
6617 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6618 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6619 
6620 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6621 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6622 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6623 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6624 	}
6625 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6626 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6627 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6628 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6629 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6630 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6631 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6632 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6633 
6634 	return (hashconfig);
6635 }
6636 #endif
6637 
6638 /*
6639  * Idempotent.
6640  */
6641 static int
6642 vi_full_init(struct vi_info *vi)
6643 {
6644 	struct adapter *sc = vi->adapter;
6645 	struct sge_rxq *rxq;
6646 	int rc, i, j;
6647 #ifdef RSS
6648 	int nbuckets = rss_getnumbuckets();
6649 	int hashconfig = rss_gethashconfig();
6650 	int extra;
6651 #endif
6652 
6653 	ASSERT_SYNCHRONIZED_OP(sc);
6654 
6655 	if (!(vi->flags & VI_SYSCTL_CTX)) {
6656 		sysctl_ctx_init(&vi->ctx);
6657 		vi->flags |= VI_SYSCTL_CTX;
6658 	}
6659 
6660 	/*
6661 	 * Allocate tx/rx/fl queues for this VI.
6662 	 */
6663 	rc = t4_setup_vi_queues(vi);
6664 	if (rc != 0)
6665 		return (rc);
6666 
6667 	/*
6668 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6669 	 */
6670 	if (vi->nrxq > vi->rss_size) {
6671 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6672 		    "some queues will never receive traffic.\n", vi->nrxq,
6673 		    vi->rss_size);
6674 	} else if (vi->rss_size % vi->nrxq) {
6675 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6676 		    "expect uneven traffic distribution.\n", vi->nrxq,
6677 		    vi->rss_size);
6678 	}
6679 #ifdef RSS
6680 	if (vi->nrxq != nbuckets) {
6681 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6682 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6683 	}
6684 #endif
6685 	if (vi->rss == NULL)
6686 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6687 		    M_ZERO | M_WAITOK);
6688 	for (i = 0; i < vi->rss_size;) {
6689 #ifdef RSS
6690 		j = rss_get_indirection_to_bucket(i);
6691 		j %= vi->nrxq;
6692 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6693 		vi->rss[i++] = rxq->iq.abs_id;
6694 #else
6695 		for_each_rxq(vi, j, rxq) {
6696 			vi->rss[i++] = rxq->iq.abs_id;
6697 			if (i == vi->rss_size)
6698 				break;
6699 		}
6700 #endif
6701 	}
6702 
6703 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6704 	    vi->rss, vi->rss_size);
6705 	if (rc != 0) {
6706 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6707 		return (rc);
6708 	}
6709 
6710 #ifdef RSS
6711 	vi->hashen = hashconfig_to_hashen(hashconfig);
6712 
6713 	/*
6714 	 * We may have had to enable some hashes even though the global config
6715 	 * wants them disabled.  This is a potential problem that must be
6716 	 * reported to the user.
6717 	 */
6718 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6719 
6720 	/*
6721 	 * If we consider only the supported hash types, then the enabled hashes
6722 	 * are a superset of the requested hashes.  In other words, there cannot
6723 	 * be any supported hash that was requested but not enabled, but there
6724 	 * can be hashes that were not requested but had to be enabled.
6725 	 */
6726 	extra &= SUPPORTED_RSS_HASHTYPES;
6727 	MPASS((extra & hashconfig) == 0);
6728 
6729 	if (extra) {
6730 		CH_ALERT(vi,
6731 		    "global RSS config (0x%x) cannot be accommodated.\n",
6732 		    hashconfig);
6733 	}
6734 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6735 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6736 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6737 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6738 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6739 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6740 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6741 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6742 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6743 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6744 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6745 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6746 #else
6747 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6748 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6749 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6750 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6751 #endif
6752 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6753 	    0, 0);
6754 	if (rc != 0) {
6755 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6756 		return (rc);
6757 	}
6758 
6759 	return (0);
6760 }
6761 
6762 int
6763 vi_init(struct vi_info *vi)
6764 {
6765 	int rc;
6766 
6767 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6768 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6769 	    ("%s: VI_INIT_DONE already", __func__));
6770 
6771 	rc = vi_full_init(vi);
6772 	if (rc != 0)
6773 		vi_full_uninit(vi);
6774 	else
6775 		vi->flags |= VI_INIT_DONE;
6776 
6777 	return (rc);
6778 }
6779 
6780 /*
6781  * Idempotent.
6782  */
6783 static void
6784 vi_full_uninit(struct vi_info *vi)
6785 {
6786 
6787 	if (vi->flags & VI_INIT_DONE) {
6788 		quiesce_vi(vi);
6789 		free(vi->rss, M_CXGBE);
6790 		free(vi->nm_rss, M_CXGBE);
6791 	}
6792 
6793 	/* Do this before freeing the VI queues. */
6794 	if (vi->flags & VI_SYSCTL_CTX) {
6795 		sysctl_ctx_free(&vi->ctx);
6796 		vi->flags &= ~VI_SYSCTL_CTX;
6797 	}
6798 
6799 	t4_teardown_vi_queues(vi);
6800 	vi->flags &= ~VI_INIT_DONE;
6801 }
6802 
6803 static void
6804 quiesce_txq(struct sge_txq *txq)
6805 {
6806 	struct sge_eq *eq = &txq->eq;
6807 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6808 
6809 	MPASS(eq->flags & EQ_SW_ALLOCATED);
6810 	MPASS(!(eq->flags & EQ_ENABLED));
6811 
6812 	/* Wait for the mp_ring to empty. */
6813 	while (!mp_ring_is_idle(txq->r)) {
6814 		mp_ring_check_drainage(txq->r, 4096);
6815 		pause("rquiesce", 1);
6816 	}
6817 	MPASS(txq->txp.npkt == 0);
6818 
6819 	if (eq->flags & EQ_HW_ALLOCATED) {
6820 		/*
6821 		 * Hardware is alive and working normally.  Wait for it to
6822 		 * finish and then wait for the driver to catch up and reclaim
6823 		 * all descriptors.
6824 		 */
6825 		while (spg->cidx != htobe16(eq->pidx))
6826 			pause("equiesce", 1);
6827 		while (eq->cidx != eq->pidx)
6828 			pause("dquiesce", 1);
6829 	} else {
6830 		/*
6831 		 * Hardware is unavailable.  Discard all pending tx and reclaim
6832 		 * descriptors directly.
6833 		 */
6834 		TXQ_LOCK(txq);
6835 		while (eq->cidx != eq->pidx) {
6836 			struct mbuf *m, *nextpkt;
6837 			struct tx_sdesc *txsd;
6838 
6839 			txsd = &txq->sdesc[eq->cidx];
6840 			for (m = txsd->m; m != NULL; m = nextpkt) {
6841 				nextpkt = m->m_nextpkt;
6842 				m->m_nextpkt = NULL;
6843 				m_freem(m);
6844 			}
6845 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
6846 		}
6847 		spg->pidx = spg->cidx = htobe16(eq->cidx);
6848 		TXQ_UNLOCK(txq);
6849 	}
6850 }
6851 
6852 static void
6853 quiesce_wrq(struct sge_wrq *wrq)
6854 {
6855 
6856 	/* XXXTX */
6857 }
6858 
6859 static void
6860 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
6861 {
6862 	/* Synchronize with the interrupt handler */
6863 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
6864 		pause("iqfree", 1);
6865 
6866 	if (fl != NULL) {
6867 		MPASS(iq->flags & IQ_HAS_FL);
6868 
6869 		mtx_lock(&sc->sfl_lock);
6870 		FL_LOCK(fl);
6871 		fl->flags |= FL_DOOMED;
6872 		FL_UNLOCK(fl);
6873 		callout_stop(&sc->sfl_callout);
6874 		mtx_unlock(&sc->sfl_lock);
6875 
6876 		KASSERT((fl->flags & FL_STARVING) == 0,
6877 		    ("%s: still starving", __func__));
6878 
6879 		/* Release all buffers if hardware is no longer available. */
6880 		if (!(iq->flags & IQ_HW_ALLOCATED))
6881 			free_fl_buffers(sc, fl);
6882 	}
6883 }
6884 
6885 /*
6886  * Wait for all activity on all the queues of the VI to complete.  It is assumed
6887  * that no new work is being enqueued by the hardware or the driver.  That part
6888  * should be arranged before calling this function.
6889  */
6890 static void
6891 quiesce_vi(struct vi_info *vi)
6892 {
6893 	int i;
6894 	struct adapter *sc = vi->adapter;
6895 	struct sge_rxq *rxq;
6896 	struct sge_txq *txq;
6897 #ifdef TCP_OFFLOAD
6898 	struct sge_ofld_rxq *ofld_rxq;
6899 #endif
6900 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6901 	struct sge_ofld_txq *ofld_txq;
6902 #endif
6903 
6904 	if (!(vi->flags & VI_INIT_DONE))
6905 		return;
6906 
6907 	for_each_txq(vi, i, txq) {
6908 		quiesce_txq(txq);
6909 	}
6910 
6911 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6912 	for_each_ofld_txq(vi, i, ofld_txq) {
6913 		quiesce_wrq(&ofld_txq->wrq);
6914 	}
6915 #endif
6916 
6917 	for_each_rxq(vi, i, rxq) {
6918 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
6919 	}
6920 
6921 #ifdef TCP_OFFLOAD
6922 	for_each_ofld_rxq(vi, i, ofld_rxq) {
6923 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
6924 	}
6925 #endif
6926 }
6927 
6928 static int
6929 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
6930     driver_intr_t *handler, void *arg, char *name)
6931 {
6932 	int rc;
6933 
6934 	irq->rid = rid;
6935 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
6936 	    RF_SHAREABLE | RF_ACTIVE);
6937 	if (irq->res == NULL) {
6938 		device_printf(sc->dev,
6939 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
6940 		return (ENOMEM);
6941 	}
6942 
6943 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
6944 	    NULL, handler, arg, &irq->tag);
6945 	if (rc != 0) {
6946 		device_printf(sc->dev,
6947 		    "failed to setup interrupt for rid %d, name %s: %d\n",
6948 		    rid, name, rc);
6949 	} else if (name)
6950 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
6951 
6952 	return (rc);
6953 }
6954 
6955 static int
6956 t4_free_irq(struct adapter *sc, struct irq *irq)
6957 {
6958 	if (irq->tag)
6959 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
6960 	if (irq->res)
6961 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
6962 
6963 	bzero(irq, sizeof(*irq));
6964 
6965 	return (0);
6966 }
6967 
6968 static void
6969 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
6970 {
6971 
6972 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
6973 	t4_get_regs(sc, buf, regs->len);
6974 }
6975 
6976 #define	A_PL_INDIR_CMD	0x1f8
6977 
6978 #define	S_PL_AUTOINC	31
6979 #define	M_PL_AUTOINC	0x1U
6980 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
6981 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
6982 
6983 #define	S_PL_VFID	20
6984 #define	M_PL_VFID	0xffU
6985 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
6986 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
6987 
6988 #define	S_PL_ADDR	0
6989 #define	M_PL_ADDR	0xfffffU
6990 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
6991 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
6992 
6993 #define	A_PL_INDIR_DATA	0x1fc
6994 
6995 static uint64_t
6996 read_vf_stat(struct adapter *sc, u_int vin, int reg)
6997 {
6998 	u32 stats[2];
6999 
7000 	if (sc->flags & IS_VF) {
7001 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7002 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7003 	} else {
7004 		mtx_assert(&sc->reg_lock, MA_OWNED);
7005 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7006 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7007 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7008 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7009 	}
7010 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7011 }
7012 
7013 static void
7014 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7015 {
7016 
7017 #define GET_STAT(name) \
7018 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7019 
7020 	if (!(sc->flags & IS_VF))
7021 		mtx_lock(&sc->reg_lock);
7022 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7023 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7024 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7025 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7026 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7027 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7028 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7029 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7030 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7031 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7032 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7033 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7034 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7035 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7036 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7037 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7038 	if (!(sc->flags & IS_VF))
7039 		mtx_unlock(&sc->reg_lock);
7040 
7041 #undef GET_STAT
7042 }
7043 
7044 static void
7045 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7046 {
7047 	int reg;
7048 
7049 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7050 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7051 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7052 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7053 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7054 }
7055 
7056 static void
7057 vi_refresh_stats(struct vi_info *vi)
7058 {
7059 	struct timeval tv;
7060 	const struct timeval interval = {0, 250000};	/* 250ms */
7061 
7062 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7063 
7064 	if (!(vi->flags & VI_INIT_DONE) || vi->flags & VI_SKIP_STATS)
7065 		return;
7066 
7067 	getmicrotime(&tv);
7068 	timevalsub(&tv, &interval);
7069 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7070 		return;
7071 
7072 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7073 	getmicrotime(&vi->last_refreshed);
7074 }
7075 
7076 static void
7077 cxgbe_refresh_stats(struct vi_info *vi)
7078 {
7079 	u_int i, v, tnl_cong_drops, chan_map;
7080 	struct timeval tv;
7081 	const struct timeval interval = {0, 250000};	/* 250ms */
7082 	struct port_info *pi;
7083 	struct adapter *sc;
7084 
7085 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7086 
7087 	if (vi->flags & VI_SKIP_STATS)
7088 		return;
7089 
7090 	getmicrotime(&tv);
7091 	timevalsub(&tv, &interval);
7092 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7093 		return;
7094 
7095 	pi = vi->pi;
7096 	sc = vi->adapter;
7097 	tnl_cong_drops = 0;
7098 	t4_get_port_stats(sc, pi->tx_chan, &pi->stats);
7099 	chan_map = pi->rx_e_chan_map;
7100 	while (chan_map) {
7101 		i = ffs(chan_map) - 1;
7102 		mtx_lock(&sc->reg_lock);
7103 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7104 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7105 		mtx_unlock(&sc->reg_lock);
7106 		tnl_cong_drops += v;
7107 		chan_map &= ~(1 << i);
7108 	}
7109 	pi->tnl_cong_drops = tnl_cong_drops;
7110 	getmicrotime(&vi->last_refreshed);
7111 }
7112 
7113 static void
7114 cxgbe_tick(void *arg)
7115 {
7116 	struct vi_info *vi = arg;
7117 
7118 	MPASS(IS_MAIN_VI(vi));
7119 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7120 
7121 	cxgbe_refresh_stats(vi);
7122 	callout_schedule(&vi->tick, hz);
7123 }
7124 
7125 static void
7126 vi_tick(void *arg)
7127 {
7128 	struct vi_info *vi = arg;
7129 
7130 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7131 
7132 	vi_refresh_stats(vi);
7133 	callout_schedule(&vi->tick, hz);
7134 }
7135 
7136 /*
7137  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7138  */
7139 static char *caps_decoder[] = {
7140 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7141 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7142 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7143 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7144 	    "\006HASHFILTER\007ETHOFLD",
7145 	"\20\001TOE",					/* 4: TOE */
7146 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7147 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7148 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7149 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7150 	    "\007T10DIF"
7151 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7152 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7153 	    "\004TLS_HW",
7154 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7155 		    "\004PO_INITIATOR\005PO_TARGET",
7156 };
7157 
7158 void
7159 t4_sysctls(struct adapter *sc)
7160 {
7161 	struct sysctl_ctx_list *ctx;
7162 	struct sysctl_oid *oid;
7163 	struct sysctl_oid_list *children, *c0;
7164 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7165 
7166 	ctx = device_get_sysctl_ctx(sc->dev);
7167 
7168 	/*
7169 	 * dev.t4nex.X.
7170 	 */
7171 	oid = device_get_sysctl_tree(sc->dev);
7172 	c0 = children = SYSCTL_CHILDREN(oid);
7173 
7174 	sc->sc_do_rxcopy = 1;
7175 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7176 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7177 
7178 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7179 	    sc->params.nports, "# of ports");
7180 
7181 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7182 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7183 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7184 	    "available doorbells");
7185 
7186 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7187 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7188 
7189 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7190 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7191 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7192 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7193 
7194 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7195 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7196 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7197 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7198 
7199 	t4_sge_sysctls(sc, ctx, children);
7200 
7201 	sc->lro_timeout = 100;
7202 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7203 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7204 
7205 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7206 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7207 
7208 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7209 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7210 
7211 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7212 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7213 
7214 	if (sc->flags & IS_VF)
7215 		return;
7216 
7217 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7218 	    NULL, chip_rev(sc), "chip hardware revision");
7219 
7220 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7221 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7222 
7223 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7224 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7225 
7226 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7227 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7228 
7229 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7230 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7231 
7232 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7233 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7234 
7235 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7236 	    sc->er_version, 0, "expansion ROM version");
7237 
7238 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7239 	    sc->bs_version, 0, "bootstrap firmware version");
7240 
7241 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7242 	    NULL, sc->params.scfg_vers, "serial config version");
7243 
7244 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7245 	    NULL, sc->params.vpd_vers, "VPD version");
7246 
7247 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7248 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7249 
7250 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7251 	    sc->cfcsum, "config file checksum");
7252 
7253 #define SYSCTL_CAP(name, n, text) \
7254 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7255 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7256 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7257 	    "available " text " capabilities")
7258 
7259 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7260 	SYSCTL_CAP(linkcaps, 1, "link");
7261 	SYSCTL_CAP(switchcaps, 2, "switch");
7262 	SYSCTL_CAP(niccaps, 3, "NIC");
7263 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7264 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7265 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7266 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7267 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7268 #undef SYSCTL_CAP
7269 
7270 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7271 	    NULL, sc->tids.nftids, "number of filters");
7272 
7273 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7274 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7275 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7276 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7277 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7278 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7279 
7280 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7281 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7282 	    sysctl_loadavg, "A",
7283 	    "microprocessor load averages (debug firmwares only)");
7284 
7285 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7286 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7287 	    "I", "core Vdd (in mV)");
7288 
7289 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7290 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7291 	    sysctl_cpus, "A", "local CPUs");
7292 
7293 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7294 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7295 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7296 
7297 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7298 	    &sc->swintr, 0, "software triggered interrupts");
7299 
7300 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7301 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7302 	    "1 = reset adapter, 0 = zero reset counter");
7303 
7304 	/*
7305 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7306 	 */
7307 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7308 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7309 	    "logs and miscellaneous information");
7310 	children = SYSCTL_CHILDREN(oid);
7311 
7312 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7313 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7314 	    sysctl_cctrl, "A", "congestion control");
7315 
7316 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7317 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7318 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7319 
7320 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7321 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7322 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7323 
7324 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7325 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7326 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7327 
7328 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7329 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7330 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7331 
7332 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7333 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7334 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7335 
7336 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7337 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7338 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7339 
7340 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7341 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7342 	    sysctl_cim_la, "A", "CIM logic analyzer");
7343 
7344 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7345 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7346 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7347 
7348 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7349 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7350 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7351 
7352 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7353 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7354 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7355 
7356 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7357 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7358 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7359 
7360 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7361 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7362 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7363 
7364 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7365 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7366 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7367 
7368 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7369 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7370 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7371 
7372 	if (chip_id(sc) > CHELSIO_T4) {
7373 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7374 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7375 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7376 		    "CIM OBQ 6 (SGE0-RX)");
7377 
7378 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7379 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7380 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7381 		    "CIM OBQ 7 (SGE1-RX)");
7382 	}
7383 
7384 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7385 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7386 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7387 
7388 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7389 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7390 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7391 
7392 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7393 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7394 	    sysctl_cpl_stats, "A", "CPL statistics");
7395 
7396 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7397 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7398 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7399 
7400 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7401 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7402 	    sysctl_tid_stats, "A", "tid stats");
7403 
7404 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7405 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7406 	    sysctl_devlog, "A", "firmware's device log");
7407 
7408 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7409 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7410 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7411 
7412 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7413 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7414 	    sysctl_hw_sched, "A", "hardware scheduler ");
7415 
7416 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7417 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7418 	    sysctl_l2t, "A", "hardware L2 table");
7419 
7420 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7421 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7422 	    sysctl_smt, "A", "hardware source MAC table");
7423 
7424 #ifdef INET6
7425 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7426 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7427 	    sysctl_clip, "A", "active CLIP table entries");
7428 #endif
7429 
7430 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7431 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7432 	    sysctl_lb_stats, "A", "loopback statistics");
7433 
7434 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7435 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7436 	    sysctl_meminfo, "A", "memory regions");
7437 
7438 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7439 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7440 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7441 	    "A", "MPS TCAM entries");
7442 
7443 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7444 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7445 	    sysctl_path_mtus, "A", "path MTUs");
7446 
7447 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7448 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7449 	    sysctl_pm_stats, "A", "PM statistics");
7450 
7451 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7452 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7453 	    sysctl_rdma_stats, "A", "RDMA statistics");
7454 
7455 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7456 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7457 	    sysctl_tcp_stats, "A", "TCP statistics");
7458 
7459 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7460 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7461 	    sysctl_tids, "A", "TID information");
7462 
7463 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7464 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7465 	    sysctl_tp_err_stats, "A", "TP error statistics");
7466 
7467 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7468 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7469 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7470 
7471 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7472 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7473 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7474 
7475 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7476 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7477 	    sysctl_tp_la, "A", "TP logic analyzer");
7478 
7479 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7480 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7481 	    sysctl_tx_rate, "A", "Tx rate");
7482 
7483 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7484 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7485 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7486 
7487 	if (chip_id(sc) >= CHELSIO_T5) {
7488 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7489 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7490 		    sysctl_wcwr_stats, "A", "write combined work requests");
7491 	}
7492 
7493 #ifdef KERN_TLS
7494 	if (is_ktls(sc)) {
7495 		/*
7496 		 * dev.t4nex.0.tls.
7497 		 */
7498 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7499 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7500 		children = SYSCTL_CHILDREN(oid);
7501 
7502 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7503 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7504 		    "keys in work requests (1) or attempt to store TLS keys "
7505 		    "in card memory.");
7506 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7507 		    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to combine "
7508 		    "TCB field updates with TLS record work requests.");
7509 	}
7510 #endif
7511 
7512 #ifdef TCP_OFFLOAD
7513 	if (is_offload(sc)) {
7514 		int i;
7515 		char s[4];
7516 
7517 		/*
7518 		 * dev.t4nex.X.toe.
7519 		 */
7520 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7521 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7522 		children = SYSCTL_CHILDREN(oid);
7523 
7524 		sc->tt.cong_algorithm = -1;
7525 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7526 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7527 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7528 		    "3 = highspeed)");
7529 
7530 		sc->tt.sndbuf = -1;
7531 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7532 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7533 
7534 		sc->tt.ddp = 0;
7535 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7536 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7537 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7538 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7539 
7540 		sc->tt.rx_coalesce = -1;
7541 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7542 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7543 
7544 		sc->tt.tls = 0;
7545 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7546 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7547 		    "Inline TLS allowed");
7548 
7549 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_ports",
7550 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7551 		    sysctl_tls_rx_ports, "I",
7552 		    "TCP ports that use inline TLS+TOE RX");
7553 
7554 		sc->tt.tls_rx_timeout = t4_toe_tls_rx_timeout;
7555 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_timeout",
7556 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7557 		    sysctl_tls_rx_timeout, "I",
7558 		    "Timeout in seconds to downgrade TLS sockets to plain TOE");
7559 
7560 		sc->tt.tx_align = -1;
7561 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7562 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7563 
7564 		sc->tt.tx_zcopy = 0;
7565 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7566 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7567 		    "Enable zero-copy aio_write(2)");
7568 
7569 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7570 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7571 		    "cop_managed_offloading", CTLFLAG_RW,
7572 		    &sc->tt.cop_managed_offloading, 0,
7573 		    "COP (Connection Offload Policy) controls all TOE offload");
7574 
7575 		sc->tt.autorcvbuf_inc = 16 * 1024;
7576 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7577 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7578 		    "autorcvbuf increment");
7579 
7580 		sc->tt.update_hc_on_pmtu_change = 1;
7581 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7582 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7583 		    &sc->tt.update_hc_on_pmtu_change, 0,
7584 		    "Update hostcache entry if the PMTU changes");
7585 
7586 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7587 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7588 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7589 
7590 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7591 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7592 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7593 
7594 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7595 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7596 		    sysctl_tp_tick, "A", "DACK tick (us)");
7597 
7598 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7599 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7600 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7601 
7602 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7603 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7604 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7605 		    "Minimum retransmit interval (us)");
7606 
7607 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7608 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7609 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7610 		    "Maximum retransmit interval (us)");
7611 
7612 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7613 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7614 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7615 		    "Persist timer min (us)");
7616 
7617 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7618 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7619 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7620 		    "Persist timer max (us)");
7621 
7622 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7623 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7624 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7625 		    "Keepalive idle timer (us)");
7626 
7627 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7628 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7629 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7630 		    "Keepalive interval timer (us)");
7631 
7632 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7633 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7634 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7635 
7636 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7637 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7638 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7639 		    "FINWAIT2 timer (us)");
7640 
7641 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7642 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7643 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7644 		    "Number of SYN retransmissions before abort");
7645 
7646 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7647 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7648 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7649 		    "Number of retransmissions before abort");
7650 
7651 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7652 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7653 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7654 		    "Number of keepalive probes before abort");
7655 
7656 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7657 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7658 		    "TOE retransmit backoffs");
7659 		children = SYSCTL_CHILDREN(oid);
7660 		for (i = 0; i < 16; i++) {
7661 			snprintf(s, sizeof(s), "%u", i);
7662 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7663 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7664 			    i, sysctl_tp_backoff, "IU",
7665 			    "TOE retransmit backoff");
7666 		}
7667 	}
7668 #endif
7669 }
7670 
7671 void
7672 vi_sysctls(struct vi_info *vi)
7673 {
7674 	struct sysctl_ctx_list *ctx;
7675 	struct sysctl_oid *oid;
7676 	struct sysctl_oid_list *children;
7677 
7678 	ctx = device_get_sysctl_ctx(vi->dev);
7679 
7680 	/*
7681 	 * dev.v?(cxgbe|cxl).X.
7682 	 */
7683 	oid = device_get_sysctl_tree(vi->dev);
7684 	children = SYSCTL_CHILDREN(oid);
7685 
7686 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7687 	    vi->viid, "VI identifer");
7688 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7689 	    &vi->nrxq, 0, "# of rx queues");
7690 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7691 	    &vi->ntxq, 0, "# of tx queues");
7692 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7693 	    &vi->first_rxq, 0, "index of first rx queue");
7694 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7695 	    &vi->first_txq, 0, "index of first tx queue");
7696 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7697 	    vi->rss_base, "start of RSS indirection table");
7698 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7699 	    vi->rss_size, "size of RSS indirection table");
7700 
7701 	if (IS_MAIN_VI(vi)) {
7702 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7703 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7704 		    sysctl_noflowq, "IU",
7705 		    "Reserve queue 0 for non-flowid packets");
7706 	}
7707 
7708 	if (vi->adapter->flags & IS_VF) {
7709 		MPASS(vi->flags & TX_USES_VM_WR);
7710 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7711 		    NULL, 1, "use VM work requests for transmit");
7712 	} else {
7713 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7714 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7715 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7716 	}
7717 
7718 #ifdef TCP_OFFLOAD
7719 	if (vi->nofldrxq != 0) {
7720 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7721 		    &vi->nofldrxq, 0,
7722 		    "# of rx queues for offloaded TCP connections");
7723 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7724 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7725 		    "index of first TOE rx queue");
7726 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7727 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7728 		    sysctl_holdoff_tmr_idx_ofld, "I",
7729 		    "holdoff timer index for TOE queues");
7730 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7731 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7732 		    sysctl_holdoff_pktc_idx_ofld, "I",
7733 		    "holdoff packet counter index for TOE queues");
7734 	}
7735 #endif
7736 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7737 	if (vi->nofldtxq != 0) {
7738 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7739 		    &vi->nofldtxq, 0,
7740 		    "# of tx queues for TOE/ETHOFLD");
7741 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7742 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7743 		    "index of first TOE/ETHOFLD tx queue");
7744 	}
7745 #endif
7746 #ifdef DEV_NETMAP
7747 	if (vi->nnmrxq != 0) {
7748 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7749 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7750 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7751 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7752 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7753 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7754 		    "index of first netmap rx queue");
7755 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7756 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7757 		    "index of first netmap tx queue");
7758 	}
7759 #endif
7760 
7761 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7762 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7763 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7764 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7765 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7766 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7767 
7768 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7769 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7770 	    sysctl_qsize_rxq, "I", "rx queue size");
7771 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7772 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7773 	    sysctl_qsize_txq, "I", "tx queue size");
7774 }
7775 
7776 static void
7777 cxgbe_sysctls(struct port_info *pi)
7778 {
7779 	struct sysctl_ctx_list *ctx;
7780 	struct sysctl_oid *oid;
7781 	struct sysctl_oid_list *children, *children2;
7782 	struct adapter *sc = pi->adapter;
7783 	int i;
7784 	char name[16];
7785 	static char *tc_flags = {"\20\1USER\2SYNC\3ASYNC\4ERR"};
7786 
7787 	ctx = device_get_sysctl_ctx(pi->dev);
7788 
7789 	/*
7790 	 * dev.cxgbe.X.
7791 	 */
7792 	oid = device_get_sysctl_tree(pi->dev);
7793 	children = SYSCTL_CHILDREN(oid);
7794 
7795 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7796 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7797 	    sysctl_linkdnrc, "A", "reason why link is down");
7798 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7799 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7800 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7801 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
7802 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7803 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7804 		    sysctl_btphy, "I", "PHY firmware version");
7805 	}
7806 
7807 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7808 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7809 	    sysctl_pause_settings, "A",
7810 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7811 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fec",
7812 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7813 	    sysctl_fec, "A",
7814 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7815 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7816 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7817 	    "FEC recommended by the cable/transceiver");
7818 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7819 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7820 	    sysctl_autoneg, "I",
7821 	    "autonegotiation (-1 = not supported)");
7822 
7823 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7824 	    &pi->link_cfg.pcaps, 0, "port capabilities");
7825 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7826 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
7827 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7828 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7829 
7830 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7831 	    port_top_speed(pi), "max speed (in Gbps)");
7832 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7833 	    pi->mps_bg_map, "MPS buffer group map");
7834 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
7835 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
7836 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_c_chan", CTLFLAG_RD, NULL,
7837 	    pi->rx_c_chan, "TP rx c-channel");
7838 
7839 	if (sc->flags & IS_VF)
7840 		return;
7841 
7842 	/*
7843 	 * dev.(cxgbe|cxl).X.tc.
7844 	 */
7845 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
7846 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7847 	    "Tx scheduler traffic classes (cl_rl)");
7848 	children2 = SYSCTL_CHILDREN(oid);
7849 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
7850 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
7851 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
7852 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
7853 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
7854 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
7855 	for (i = 0; i < sc->chip_params->nsched_cls; i++) {
7856 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
7857 
7858 		snprintf(name, sizeof(name), "%d", i);
7859 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
7860 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
7861 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
7862 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
7863 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
7864 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
7865 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
7866 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
7867 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
7868 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7869 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
7870 		    "traffic class parameters");
7871 	}
7872 
7873 	/*
7874 	 * dev.cxgbe.X.stats.
7875 	 */
7876 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
7877 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
7878 	children = SYSCTL_CHILDREN(oid);
7879 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
7880 	    &pi->tx_parse_error, 0,
7881 	    "# of tx packets with invalid length or # of segments");
7882 
7883 #define T4_REGSTAT(name, stat, desc) \
7884     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
7885         CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
7886 	(is_t4(sc) ? PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L) : \
7887 	T5_PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L)), \
7888         sysctl_handle_t4_reg64, "QU", desc)
7889 
7890 /* We get these from port_stats and they may be stale by up to 1s */
7891 #define T4_PORTSTAT(name, desc) \
7892 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
7893 	    &pi->stats.name, desc)
7894 
7895 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
7896 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
7897 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
7898 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
7899 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
7900 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
7901 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
7902 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
7903 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
7904 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
7905 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
7906 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
7907 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
7908 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
7909 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
7910 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
7911 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
7912 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
7913 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
7914 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
7915 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
7916 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
7917 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
7918 
7919 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
7920 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
7921 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
7922 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
7923 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
7924 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
7925 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
7926 	if (is_t6(sc)) {
7927 		T4_PORTSTAT(rx_fcs_err,
7928 		    "# of frames received with bad FCS since last link up");
7929 	} else {
7930 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
7931 		    "# of frames received with bad FCS");
7932 	}
7933 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
7934 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
7935 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
7936 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
7937 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
7938 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
7939 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
7940 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
7941 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
7942 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
7943 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
7944 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
7945 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
7946 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
7947 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
7948 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
7949 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
7950 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
7951 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
7952 
7953 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
7954 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
7955 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
7956 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
7957 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
7958 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
7959 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
7960 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
7961 
7962 #undef T4_REGSTAT
7963 #undef T4_PORTSTAT
7964 }
7965 
7966 static int
7967 sysctl_int_array(SYSCTL_HANDLER_ARGS)
7968 {
7969 	int rc, *i, space = 0;
7970 	struct sbuf sb;
7971 
7972 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
7973 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
7974 		if (space)
7975 			sbuf_printf(&sb, " ");
7976 		sbuf_printf(&sb, "%d", *i);
7977 		space = 1;
7978 	}
7979 	rc = sbuf_finish(&sb);
7980 	sbuf_delete(&sb);
7981 	return (rc);
7982 }
7983 
7984 static int
7985 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
7986 {
7987 	int rc;
7988 	struct sbuf *sb;
7989 
7990 	rc = sysctl_wire_old_buffer(req, 0);
7991 	if (rc != 0)
7992 		return(rc);
7993 
7994 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7995 	if (sb == NULL)
7996 		return (ENOMEM);
7997 
7998 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
7999 	rc = sbuf_finish(sb);
8000 	sbuf_delete(sb);
8001 
8002 	return (rc);
8003 }
8004 
8005 static int
8006 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8007 {
8008 	int rc;
8009 	struct sbuf *sb;
8010 
8011 	rc = sysctl_wire_old_buffer(req, 0);
8012 	if (rc != 0)
8013 		return(rc);
8014 
8015 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8016 	if (sb == NULL)
8017 		return (ENOMEM);
8018 
8019 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8020 	rc = sbuf_finish(sb);
8021 	sbuf_delete(sb);
8022 
8023 	return (rc);
8024 }
8025 
8026 static int
8027 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8028 {
8029 	struct port_info *pi = arg1;
8030 	int op = arg2;
8031 	struct adapter *sc = pi->adapter;
8032 	u_int v;
8033 	int rc;
8034 
8035 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8036 	if (rc)
8037 		return (rc);
8038 	if (hw_off_limits(sc))
8039 		rc = ENXIO;
8040 	else {
8041 		/* XXX: magic numbers */
8042 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8043 		    op ? 0x20 : 0xc820, &v);
8044 	}
8045 	end_synchronized_op(sc, 0);
8046 	if (rc)
8047 		return (rc);
8048 	if (op == 0)
8049 		v /= 256;
8050 
8051 	rc = sysctl_handle_int(oidp, &v, 0, req);
8052 	return (rc);
8053 }
8054 
8055 static int
8056 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8057 {
8058 	struct vi_info *vi = arg1;
8059 	int rc, val;
8060 
8061 	val = vi->rsrv_noflowq;
8062 	rc = sysctl_handle_int(oidp, &val, 0, req);
8063 	if (rc != 0 || req->newptr == NULL)
8064 		return (rc);
8065 
8066 	if ((val >= 1) && (vi->ntxq > 1))
8067 		vi->rsrv_noflowq = 1;
8068 	else
8069 		vi->rsrv_noflowq = 0;
8070 
8071 	return (rc);
8072 }
8073 
8074 static int
8075 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8076 {
8077 	struct vi_info *vi = arg1;
8078 	struct adapter *sc = vi->adapter;
8079 	int rc, val, i;
8080 
8081 	MPASS(!(sc->flags & IS_VF));
8082 
8083 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8084 	rc = sysctl_handle_int(oidp, &val, 0, req);
8085 	if (rc != 0 || req->newptr == NULL)
8086 		return (rc);
8087 
8088 	if (val != 0 && val != 1)
8089 		return (EINVAL);
8090 
8091 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8092 	    "t4txvm");
8093 	if (rc)
8094 		return (rc);
8095 	if (hw_off_limits(sc))
8096 		rc = ENXIO;
8097 	else if (vi->ifp->if_drv_flags & IFF_DRV_RUNNING) {
8098 		/*
8099 		 * We don't want parse_pkt to run with one setting (VF or PF)
8100 		 * and then eth_tx to see a different setting but still use
8101 		 * stale information calculated by parse_pkt.
8102 		 */
8103 		rc = EBUSY;
8104 	} else {
8105 		struct port_info *pi = vi->pi;
8106 		struct sge_txq *txq;
8107 		uint32_t ctrl0;
8108 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8109 
8110 		if (val) {
8111 			vi->flags |= TX_USES_VM_WR;
8112 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
8113 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8114 			    V_TXPKT_INTF(pi->tx_chan));
8115 			if (!(sc->flags & IS_VF))
8116 				npkt--;
8117 		} else {
8118 			vi->flags &= ~TX_USES_VM_WR;
8119 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
8120 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8121 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8122 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8123 		}
8124 		for_each_txq(vi, i, txq) {
8125 			txq->cpl_ctrl0 = ctrl0;
8126 			txq->txp.max_npkt = npkt;
8127 		}
8128 	}
8129 	end_synchronized_op(sc, LOCK_HELD);
8130 	return (rc);
8131 }
8132 
8133 static int
8134 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8135 {
8136 	struct vi_info *vi = arg1;
8137 	struct adapter *sc = vi->adapter;
8138 	int idx, rc, i;
8139 	struct sge_rxq *rxq;
8140 	uint8_t v;
8141 
8142 	idx = vi->tmr_idx;
8143 
8144 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8145 	if (rc != 0 || req->newptr == NULL)
8146 		return (rc);
8147 
8148 	if (idx < 0 || idx >= SGE_NTIMERS)
8149 		return (EINVAL);
8150 
8151 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8152 	    "t4tmr");
8153 	if (rc)
8154 		return (rc);
8155 
8156 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8157 	for_each_rxq(vi, i, rxq) {
8158 #ifdef atomic_store_rel_8
8159 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8160 #else
8161 		rxq->iq.intr_params = v;
8162 #endif
8163 	}
8164 	vi->tmr_idx = idx;
8165 
8166 	end_synchronized_op(sc, LOCK_HELD);
8167 	return (0);
8168 }
8169 
8170 static int
8171 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8172 {
8173 	struct vi_info *vi = arg1;
8174 	struct adapter *sc = vi->adapter;
8175 	int idx, rc;
8176 
8177 	idx = vi->pktc_idx;
8178 
8179 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8180 	if (rc != 0 || req->newptr == NULL)
8181 		return (rc);
8182 
8183 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8184 		return (EINVAL);
8185 
8186 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8187 	    "t4pktc");
8188 	if (rc)
8189 		return (rc);
8190 
8191 	if (vi->flags & VI_INIT_DONE)
8192 		rc = EBUSY; /* cannot be changed once the queues are created */
8193 	else
8194 		vi->pktc_idx = idx;
8195 
8196 	end_synchronized_op(sc, LOCK_HELD);
8197 	return (rc);
8198 }
8199 
8200 static int
8201 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8202 {
8203 	struct vi_info *vi = arg1;
8204 	struct adapter *sc = vi->adapter;
8205 	int qsize, rc;
8206 
8207 	qsize = vi->qsize_rxq;
8208 
8209 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8210 	if (rc != 0 || req->newptr == NULL)
8211 		return (rc);
8212 
8213 	if (qsize < 128 || (qsize & 7))
8214 		return (EINVAL);
8215 
8216 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8217 	    "t4rxqs");
8218 	if (rc)
8219 		return (rc);
8220 
8221 	if (vi->flags & VI_INIT_DONE)
8222 		rc = EBUSY; /* cannot be changed once the queues are created */
8223 	else
8224 		vi->qsize_rxq = qsize;
8225 
8226 	end_synchronized_op(sc, LOCK_HELD);
8227 	return (rc);
8228 }
8229 
8230 static int
8231 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8232 {
8233 	struct vi_info *vi = arg1;
8234 	struct adapter *sc = vi->adapter;
8235 	int qsize, rc;
8236 
8237 	qsize = vi->qsize_txq;
8238 
8239 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8240 	if (rc != 0 || req->newptr == NULL)
8241 		return (rc);
8242 
8243 	if (qsize < 128 || qsize > 65536)
8244 		return (EINVAL);
8245 
8246 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8247 	    "t4txqs");
8248 	if (rc)
8249 		return (rc);
8250 
8251 	if (vi->flags & VI_INIT_DONE)
8252 		rc = EBUSY; /* cannot be changed once the queues are created */
8253 	else
8254 		vi->qsize_txq = qsize;
8255 
8256 	end_synchronized_op(sc, LOCK_HELD);
8257 	return (rc);
8258 }
8259 
8260 static int
8261 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8262 {
8263 	struct port_info *pi = arg1;
8264 	struct adapter *sc = pi->adapter;
8265 	struct link_config *lc = &pi->link_cfg;
8266 	int rc;
8267 
8268 	if (req->newptr == NULL) {
8269 		struct sbuf *sb;
8270 		static char *bits = "\20\1RX\2TX\3AUTO";
8271 
8272 		rc = sysctl_wire_old_buffer(req, 0);
8273 		if (rc != 0)
8274 			return(rc);
8275 
8276 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8277 		if (sb == NULL)
8278 			return (ENOMEM);
8279 
8280 		if (lc->link_ok) {
8281 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8282 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8283 		} else {
8284 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8285 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8286 		}
8287 		rc = sbuf_finish(sb);
8288 		sbuf_delete(sb);
8289 	} else {
8290 		char s[2];
8291 		int n;
8292 
8293 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8294 		    PAUSE_AUTONEG));
8295 		s[1] = 0;
8296 
8297 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8298 		if (rc != 0)
8299 			return(rc);
8300 
8301 		if (s[1] != 0)
8302 			return (EINVAL);
8303 		if (s[0] < '0' || s[0] > '9')
8304 			return (EINVAL);	/* not a number */
8305 		n = s[0] - '0';
8306 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8307 			return (EINVAL);	/* some other bit is set too */
8308 
8309 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8310 		    "t4PAUSE");
8311 		if (rc)
8312 			return (rc);
8313 		if (!hw_off_limits(sc)) {
8314 			PORT_LOCK(pi);
8315 			lc->requested_fc = n;
8316 			fixup_link_config(pi);
8317 			if (pi->up_vis > 0)
8318 				rc = apply_link_config(pi);
8319 			set_current_media(pi);
8320 			PORT_UNLOCK(pi);
8321 		}
8322 		end_synchronized_op(sc, 0);
8323 	}
8324 
8325 	return (rc);
8326 }
8327 
8328 static int
8329 sysctl_fec(SYSCTL_HANDLER_ARGS)
8330 {
8331 	struct port_info *pi = arg1;
8332 	struct adapter *sc = pi->adapter;
8333 	struct link_config *lc = &pi->link_cfg;
8334 	int rc;
8335 	int8_t old;
8336 
8337 	if (req->newptr == NULL) {
8338 		struct sbuf *sb;
8339 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8340 		    "\5RSVD3\6auto\7module";
8341 
8342 		rc = sysctl_wire_old_buffer(req, 0);
8343 		if (rc != 0)
8344 			return(rc);
8345 
8346 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8347 		if (sb == NULL)
8348 			return (ENOMEM);
8349 
8350 		/*
8351 		 * Display the requested_fec when the link is down -- the actual
8352 		 * FEC makes sense only when the link is up.
8353 		 */
8354 		if (lc->link_ok) {
8355 			sbuf_printf(sb, "%b", (lc->fec & M_FW_PORT_CAP32_FEC) |
8356 			    (lc->requested_fec & (FEC_AUTO | FEC_MODULE)),
8357 			    bits);
8358 		} else {
8359 			sbuf_printf(sb, "%b", lc->requested_fec, bits);
8360 		}
8361 		rc = sbuf_finish(sb);
8362 		sbuf_delete(sb);
8363 	} else {
8364 		char s[8];
8365 		int n;
8366 
8367 		snprintf(s, sizeof(s), "%d",
8368 		    lc->requested_fec == FEC_AUTO ? -1 :
8369 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8370 
8371 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8372 		if (rc != 0)
8373 			return(rc);
8374 
8375 		n = strtol(&s[0], NULL, 0);
8376 		if (n < 0 || n & FEC_AUTO)
8377 			n = FEC_AUTO;
8378 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8379 			return (EINVAL);/* some other bit is set too */
8380 
8381 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8382 		    "t4fec");
8383 		if (rc)
8384 			return (rc);
8385 		PORT_LOCK(pi);
8386 		old = lc->requested_fec;
8387 		if (n == FEC_AUTO)
8388 			lc->requested_fec = FEC_AUTO;
8389 		else if (n == 0 || n == FEC_NONE)
8390 			lc->requested_fec = FEC_NONE;
8391 		else {
8392 			if ((lc->pcaps |
8393 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8394 			    lc->pcaps) {
8395 				rc = ENOTSUP;
8396 				goto done;
8397 			}
8398 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8399 			    FEC_MODULE);
8400 		}
8401 		if (!hw_off_limits(sc)) {
8402 			fixup_link_config(pi);
8403 			if (pi->up_vis > 0) {
8404 				rc = apply_link_config(pi);
8405 				if (rc != 0) {
8406 					lc->requested_fec = old;
8407 					if (rc == FW_EPROTO)
8408 						rc = ENOTSUP;
8409 				}
8410 			}
8411 		}
8412 done:
8413 		PORT_UNLOCK(pi);
8414 		end_synchronized_op(sc, 0);
8415 	}
8416 
8417 	return (rc);
8418 }
8419 
8420 static int
8421 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8422 {
8423 	struct port_info *pi = arg1;
8424 	struct adapter *sc = pi->adapter;
8425 	struct link_config *lc = &pi->link_cfg;
8426 	int rc;
8427 	int8_t fec;
8428 	struct sbuf *sb;
8429 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8430 
8431 	rc = sysctl_wire_old_buffer(req, 0);
8432 	if (rc != 0)
8433 		return (rc);
8434 
8435 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8436 	if (sb == NULL)
8437 		return (ENOMEM);
8438 
8439 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8440 		rc = EBUSY;
8441 		goto done;
8442 	}
8443 	if (hw_off_limits(sc)) {
8444 		rc = ENXIO;
8445 		goto done;
8446 	}
8447 	PORT_LOCK(pi);
8448 	if (pi->up_vis == 0) {
8449 		/*
8450 		 * If all the interfaces are administratively down the firmware
8451 		 * does not report transceiver changes.  Refresh port info here.
8452 		 * This is the only reason we have a synchronized op in this
8453 		 * function.  Just PORT_LOCK would have been enough otherwise.
8454 		 */
8455 		t4_update_port_info(pi);
8456 	}
8457 
8458 	fec = lc->fec_hint;
8459 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8460 	    !fec_supported(lc->pcaps)) {
8461 		sbuf_printf(sb, "n/a");
8462 	} else {
8463 		if (fec == 0)
8464 			fec = FEC_NONE;
8465 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8466 	}
8467 	rc = sbuf_finish(sb);
8468 	PORT_UNLOCK(pi);
8469 done:
8470 	sbuf_delete(sb);
8471 	end_synchronized_op(sc, 0);
8472 
8473 	return (rc);
8474 }
8475 
8476 static int
8477 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8478 {
8479 	struct port_info *pi = arg1;
8480 	struct adapter *sc = pi->adapter;
8481 	struct link_config *lc = &pi->link_cfg;
8482 	int rc, val;
8483 
8484 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8485 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8486 	else
8487 		val = -1;
8488 	rc = sysctl_handle_int(oidp, &val, 0, req);
8489 	if (rc != 0 || req->newptr == NULL)
8490 		return (rc);
8491 	if (val == 0)
8492 		val = AUTONEG_DISABLE;
8493 	else if (val == 1)
8494 		val = AUTONEG_ENABLE;
8495 	else
8496 		val = AUTONEG_AUTO;
8497 
8498 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8499 	    "t4aneg");
8500 	if (rc)
8501 		return (rc);
8502 	PORT_LOCK(pi);
8503 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8504 		rc = ENOTSUP;
8505 		goto done;
8506 	}
8507 	lc->requested_aneg = val;
8508 	if (!hw_off_limits(sc)) {
8509 		fixup_link_config(pi);
8510 		if (pi->up_vis > 0)
8511 			rc = apply_link_config(pi);
8512 		set_current_media(pi);
8513 	}
8514 done:
8515 	PORT_UNLOCK(pi);
8516 	end_synchronized_op(sc, 0);
8517 	return (rc);
8518 }
8519 
8520 static int
8521 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8522 {
8523 	struct adapter *sc = arg1;
8524 	int rc, reg = arg2;
8525 	uint64_t val;
8526 
8527 	mtx_lock(&sc->reg_lock);
8528 	if (hw_off_limits(sc))
8529 		rc = ENXIO;
8530 	else {
8531 		rc = 0;
8532 		val = t4_read_reg64(sc, reg);
8533 	}
8534 	mtx_unlock(&sc->reg_lock);
8535 	if (rc == 0)
8536 		rc = sysctl_handle_64(oidp, &val, 0, req);
8537 	return (rc);
8538 }
8539 
8540 static int
8541 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8542 {
8543 	struct adapter *sc = arg1;
8544 	int rc, t;
8545 	uint32_t param, val;
8546 
8547 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8548 	if (rc)
8549 		return (rc);
8550 	if (hw_off_limits(sc))
8551 		rc = ENXIO;
8552 	else {
8553 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8554 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8555 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8556 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8557 	}
8558 	end_synchronized_op(sc, 0);
8559 	if (rc)
8560 		return (rc);
8561 
8562 	/* unknown is returned as 0 but we display -1 in that case */
8563 	t = val == 0 ? -1 : val;
8564 
8565 	rc = sysctl_handle_int(oidp, &t, 0, req);
8566 	return (rc);
8567 }
8568 
8569 static int
8570 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8571 {
8572 	struct adapter *sc = arg1;
8573 	int rc;
8574 	uint32_t param, val;
8575 
8576 	if (sc->params.core_vdd == 0) {
8577 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8578 		    "t4vdd");
8579 		if (rc)
8580 			return (rc);
8581 		if (hw_off_limits(sc))
8582 			rc = ENXIO;
8583 		else {
8584 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8585 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8586 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8587 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8588 			    &param, &val);
8589 		}
8590 		end_synchronized_op(sc, 0);
8591 		if (rc)
8592 			return (rc);
8593 		sc->params.core_vdd = val;
8594 	}
8595 
8596 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8597 }
8598 
8599 static int
8600 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8601 {
8602 	struct adapter *sc = arg1;
8603 	int rc, v;
8604 	uint32_t param, val;
8605 
8606 	v = sc->sensor_resets;
8607 	rc = sysctl_handle_int(oidp, &v, 0, req);
8608 	if (rc != 0 || req->newptr == NULL || v <= 0)
8609 		return (rc);
8610 
8611 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8612 	    chip_id(sc) < CHELSIO_T5)
8613 		return (ENOTSUP);
8614 
8615 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8616 	if (rc)
8617 		return (rc);
8618 	if (hw_off_limits(sc))
8619 		rc = ENXIO;
8620 	else {
8621 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8622 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8623 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8624 		val = 1;
8625 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8626 	}
8627 	end_synchronized_op(sc, 0);
8628 	if (rc == 0)
8629 		sc->sensor_resets++;
8630 	return (rc);
8631 }
8632 
8633 static int
8634 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8635 {
8636 	struct adapter *sc = arg1;
8637 	struct sbuf *sb;
8638 	int rc;
8639 	uint32_t param, val;
8640 
8641 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8642 	if (rc)
8643 		return (rc);
8644 	if (hw_off_limits(sc))
8645 		rc = ENXIO;
8646 	else {
8647 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8648 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8649 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8650 	}
8651 	end_synchronized_op(sc, 0);
8652 	if (rc)
8653 		return (rc);
8654 
8655 	rc = sysctl_wire_old_buffer(req, 0);
8656 	if (rc != 0)
8657 		return (rc);
8658 
8659 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8660 	if (sb == NULL)
8661 		return (ENOMEM);
8662 
8663 	if (val == 0xffffffff) {
8664 		/* Only debug and custom firmwares report load averages. */
8665 		sbuf_printf(sb, "not available");
8666 	} else {
8667 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8668 		    (val >> 16) & 0xff);
8669 	}
8670 	rc = sbuf_finish(sb);
8671 	sbuf_delete(sb);
8672 
8673 	return (rc);
8674 }
8675 
8676 static int
8677 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8678 {
8679 	struct adapter *sc = arg1;
8680 	struct sbuf *sb;
8681 	int rc, i;
8682 	uint16_t incr[NMTUS][NCCTRL_WIN];
8683 	static const char *dec_fac[] = {
8684 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8685 		"0.9375"
8686 	};
8687 
8688 	rc = sysctl_wire_old_buffer(req, 0);
8689 	if (rc != 0)
8690 		return (rc);
8691 
8692 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8693 	if (sb == NULL)
8694 		return (ENOMEM);
8695 
8696 	mtx_lock(&sc->reg_lock);
8697 	if (hw_off_limits(sc))
8698 		rc = ENXIO;
8699 	else
8700 		t4_read_cong_tbl(sc, incr);
8701 	mtx_unlock(&sc->reg_lock);
8702 	if (rc)
8703 		goto done;
8704 
8705 	for (i = 0; i < NCCTRL_WIN; ++i) {
8706 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8707 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8708 		    incr[5][i], incr[6][i], incr[7][i]);
8709 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8710 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8711 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8712 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8713 	}
8714 
8715 	rc = sbuf_finish(sb);
8716 done:
8717 	sbuf_delete(sb);
8718 	return (rc);
8719 }
8720 
8721 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8722 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8723 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8724 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8725 };
8726 
8727 static int
8728 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8729 {
8730 	struct adapter *sc = arg1;
8731 	struct sbuf *sb;
8732 	int rc, i, n, qid = arg2;
8733 	uint32_t *buf, *p;
8734 	char *qtype;
8735 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8736 
8737 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8738 	    ("%s: bad qid %d\n", __func__, qid));
8739 
8740 	if (qid < CIM_NUM_IBQ) {
8741 		/* inbound queue */
8742 		qtype = "IBQ";
8743 		n = 4 * CIM_IBQ_SIZE;
8744 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8745 		mtx_lock(&sc->reg_lock);
8746 		if (hw_off_limits(sc))
8747 			rc = -ENXIO;
8748 		else
8749 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8750 		mtx_unlock(&sc->reg_lock);
8751 	} else {
8752 		/* outbound queue */
8753 		qtype = "OBQ";
8754 		qid -= CIM_NUM_IBQ;
8755 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8756 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8757 		mtx_lock(&sc->reg_lock);
8758 		if (hw_off_limits(sc))
8759 			rc = -ENXIO;
8760 		else
8761 			rc = t4_read_cim_obq(sc, qid, buf, n);
8762 		mtx_unlock(&sc->reg_lock);
8763 	}
8764 
8765 	if (rc < 0) {
8766 		rc = -rc;
8767 		goto done;
8768 	}
8769 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
8770 
8771 	rc = sysctl_wire_old_buffer(req, 0);
8772 	if (rc != 0)
8773 		goto done;
8774 
8775 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8776 	if (sb == NULL) {
8777 		rc = ENOMEM;
8778 		goto done;
8779 	}
8780 
8781 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8782 	for (i = 0, p = buf; i < n; i += 16, p += 4)
8783 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
8784 		    p[2], p[3]);
8785 
8786 	rc = sbuf_finish(sb);
8787 	sbuf_delete(sb);
8788 done:
8789 	free(buf, M_CXGBE);
8790 	return (rc);
8791 }
8792 
8793 static void
8794 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8795 {
8796 	uint32_t *p;
8797 
8798 	sbuf_printf(sb, "Status   Data      PC%s",
8799 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8800 	    "     LS0Stat  LS0Addr             LS0Data");
8801 
8802 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
8803 		if (cfg & F_UPDBGLACAPTPCONLY) {
8804 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
8805 			    p[6], p[7]);
8806 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
8807 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
8808 			    p[4] & 0xff, p[5] >> 8);
8809 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
8810 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8811 			    p[1] & 0xf, p[2] >> 4);
8812 		} else {
8813 			sbuf_printf(sb,
8814 			    "\n  %02x   %x%07x %x%07x %08x %08x "
8815 			    "%08x%08x%08x%08x",
8816 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8817 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
8818 			    p[6], p[7]);
8819 		}
8820 	}
8821 }
8822 
8823 static void
8824 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8825 {
8826 	uint32_t *p;
8827 
8828 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
8829 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8830 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
8831 
8832 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
8833 		if (cfg & F_UPDBGLACAPTPCONLY) {
8834 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
8835 			    p[3] & 0xff, p[2], p[1], p[0]);
8836 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
8837 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
8838 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
8839 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
8840 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
8841 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
8842 			    p[6] >> 16);
8843 		} else {
8844 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
8845 			    "%08x %08x %08x %08x %08x %08x",
8846 			    (p[9] >> 16) & 0xff,
8847 			    p[9] & 0xffff, p[8] >> 16,
8848 			    p[8] & 0xffff, p[7] >> 16,
8849 			    p[7] & 0xffff, p[6] >> 16,
8850 			    p[2], p[1], p[0], p[5], p[4], p[3]);
8851 		}
8852 	}
8853 }
8854 
8855 static int
8856 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
8857 {
8858 	uint32_t cfg, *buf;
8859 	int rc;
8860 
8861 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
8862 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
8863 	    M_ZERO | flags);
8864 	if (buf == NULL)
8865 		return (ENOMEM);
8866 
8867 	mtx_lock(&sc->reg_lock);
8868 	if (hw_off_limits(sc))
8869 		rc = ENXIO;
8870 	else {
8871 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
8872 		if (rc == 0)
8873 			rc = -t4_cim_read_la(sc, buf, NULL);
8874 	}
8875 	mtx_unlock(&sc->reg_lock);
8876 	if (rc == 0) {
8877 		if (chip_id(sc) < CHELSIO_T6)
8878 			sbuf_cim_la4(sc, sb, buf, cfg);
8879 		else
8880 			sbuf_cim_la6(sc, sb, buf, cfg);
8881 	}
8882 	free(buf, M_CXGBE);
8883 	return (rc);
8884 }
8885 
8886 static int
8887 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
8888 {
8889 	struct adapter *sc = arg1;
8890 	struct sbuf *sb;
8891 	int rc;
8892 
8893 	rc = sysctl_wire_old_buffer(req, 0);
8894 	if (rc != 0)
8895 		return (rc);
8896 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8897 	if (sb == NULL)
8898 		return (ENOMEM);
8899 
8900 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
8901 	if (rc == 0)
8902 		rc = sbuf_finish(sb);
8903 	sbuf_delete(sb);
8904 	return (rc);
8905 }
8906 
8907 bool
8908 t4_os_dump_cimla(struct adapter *sc, int arg, bool verbose)
8909 {
8910 	struct sbuf sb;
8911 	int rc;
8912 
8913 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
8914 		return (false);
8915 	rc = sbuf_cim_la(sc, &sb, M_NOWAIT);
8916 	if (rc == 0) {
8917 		rc = sbuf_finish(&sb);
8918 		if (rc == 0) {
8919 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s",
8920 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
8921 		}
8922 	}
8923 	sbuf_delete(&sb);
8924 	return (false);
8925 }
8926 
8927 static int
8928 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
8929 {
8930 	struct adapter *sc = arg1;
8931 	u_int i;
8932 	struct sbuf *sb;
8933 	uint32_t *buf, *p;
8934 	int rc;
8935 
8936 	rc = sysctl_wire_old_buffer(req, 0);
8937 	if (rc != 0)
8938 		return (rc);
8939 
8940 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8941 	if (sb == NULL)
8942 		return (ENOMEM);
8943 
8944 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
8945 	    M_ZERO | M_WAITOK);
8946 
8947 	mtx_lock(&sc->reg_lock);
8948 	if (hw_off_limits(sc))
8949 		rc = ENXIO;
8950 	else
8951 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
8952 	mtx_unlock(&sc->reg_lock);
8953 	if (rc)
8954 		goto done;
8955 
8956 	p = buf;
8957 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
8958 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
8959 		    p[1], p[0]);
8960 	}
8961 
8962 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
8963 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
8964 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
8965 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
8966 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
8967 		    (p[1] >> 2) | ((p[2] & 3) << 30),
8968 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
8969 		    p[0] & 1);
8970 	}
8971 	rc = sbuf_finish(sb);
8972 done:
8973 	sbuf_delete(sb);
8974 	free(buf, M_CXGBE);
8975 	return (rc);
8976 }
8977 
8978 static int
8979 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
8980 {
8981 	struct adapter *sc = arg1;
8982 	u_int i;
8983 	struct sbuf *sb;
8984 	uint32_t *buf, *p;
8985 	int rc;
8986 
8987 	rc = sysctl_wire_old_buffer(req, 0);
8988 	if (rc != 0)
8989 		return (rc);
8990 
8991 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8992 	if (sb == NULL)
8993 		return (ENOMEM);
8994 
8995 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
8996 	    M_ZERO | M_WAITOK);
8997 
8998 	mtx_lock(&sc->reg_lock);
8999 	if (hw_off_limits(sc))
9000 		rc = ENXIO;
9001 	else
9002 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9003 	mtx_unlock(&sc->reg_lock);
9004 	if (rc)
9005 		goto done;
9006 
9007 	p = buf;
9008 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9009 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9010 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9011 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9012 		    p[4], p[3], p[2], p[1], p[0]);
9013 	}
9014 
9015 	sbuf_printf(sb, "\n\nCntl ID               Data");
9016 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9017 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9018 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9019 	}
9020 
9021 	rc = sbuf_finish(sb);
9022 done:
9023 	sbuf_delete(sb);
9024 	free(buf, M_CXGBE);
9025 	return (rc);
9026 }
9027 
9028 static int
9029 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9030 {
9031 	struct adapter *sc = arg1;
9032 	struct sbuf *sb;
9033 	int rc, i;
9034 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9035 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9036 	uint16_t thres[CIM_NUM_IBQ];
9037 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9038 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9039 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9040 
9041 	cim_num_obq = sc->chip_params->cim_num_obq;
9042 	if (is_t4(sc)) {
9043 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9044 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9045 	} else {
9046 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9047 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9048 	}
9049 	nq = CIM_NUM_IBQ + cim_num_obq;
9050 
9051 	mtx_lock(&sc->reg_lock);
9052 	if (hw_off_limits(sc))
9053 		rc = ENXIO;
9054 	else {
9055 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9056 		if (rc == 0) {
9057 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9058 			    obq_wr);
9059 			if (rc == 0)
9060 				t4_read_cimq_cfg(sc, base, size, thres);
9061 		}
9062 	}
9063 	mtx_unlock(&sc->reg_lock);
9064 	if (rc)
9065 		return (rc);
9066 
9067 	rc = sysctl_wire_old_buffer(req, 0);
9068 	if (rc != 0)
9069 		return (rc);
9070 
9071 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9072 	if (sb == NULL)
9073 		return (ENOMEM);
9074 
9075 	sbuf_printf(sb,
9076 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9077 
9078 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9079 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9080 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9081 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9082 		    G_QUEREMFLITS(p[2]) * 16);
9083 	for ( ; i < nq; i++, p += 4, wr += 2)
9084 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9085 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9086 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9087 		    G_QUEREMFLITS(p[2]) * 16);
9088 
9089 	rc = sbuf_finish(sb);
9090 	sbuf_delete(sb);
9091 
9092 	return (rc);
9093 }
9094 
9095 static int
9096 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9097 {
9098 	struct adapter *sc = arg1;
9099 	struct sbuf *sb;
9100 	int rc;
9101 	struct tp_cpl_stats stats;
9102 
9103 	rc = sysctl_wire_old_buffer(req, 0);
9104 	if (rc != 0)
9105 		return (rc);
9106 
9107 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9108 	if (sb == NULL)
9109 		return (ENOMEM);
9110 
9111 	mtx_lock(&sc->reg_lock);
9112 	if (hw_off_limits(sc))
9113 		rc = ENXIO;
9114 	else
9115 		t4_tp_get_cpl_stats(sc, &stats, 0);
9116 	mtx_unlock(&sc->reg_lock);
9117 	if (rc)
9118 		goto done;
9119 
9120 	if (sc->chip_params->nchan > 2) {
9121 		sbuf_printf(sb, "                 channel 0  channel 1"
9122 		    "  channel 2  channel 3");
9123 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9124 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9125 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9126 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9127 	} else {
9128 		sbuf_printf(sb, "                 channel 0  channel 1");
9129 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9130 		    stats.req[0], stats.req[1]);
9131 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9132 		    stats.rsp[0], stats.rsp[1]);
9133 	}
9134 
9135 	rc = sbuf_finish(sb);
9136 done:
9137 	sbuf_delete(sb);
9138 	return (rc);
9139 }
9140 
9141 static int
9142 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9143 {
9144 	struct adapter *sc = arg1;
9145 	struct sbuf *sb;
9146 	int rc;
9147 	struct tp_usm_stats stats;
9148 
9149 	rc = sysctl_wire_old_buffer(req, 0);
9150 	if (rc != 0)
9151 		return(rc);
9152 
9153 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9154 	if (sb == NULL)
9155 		return (ENOMEM);
9156 
9157 	mtx_lock(&sc->reg_lock);
9158 	if (hw_off_limits(sc))
9159 		rc = ENXIO;
9160 	else
9161 		t4_get_usm_stats(sc, &stats, 1);
9162 	mtx_unlock(&sc->reg_lock);
9163 	if (rc == 0) {
9164 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9165 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9166 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9167 		rc = sbuf_finish(sb);
9168 	}
9169 	sbuf_delete(sb);
9170 
9171 	return (rc);
9172 }
9173 
9174 static int
9175 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9176 {
9177 	struct adapter *sc = arg1;
9178 	struct sbuf *sb;
9179 	int rc;
9180 	struct tp_tid_stats stats;
9181 
9182 	rc = sysctl_wire_old_buffer(req, 0);
9183 	if (rc != 0)
9184 		return(rc);
9185 
9186 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9187 	if (sb == NULL)
9188 		return (ENOMEM);
9189 
9190 	mtx_lock(&sc->reg_lock);
9191 	if (hw_off_limits(sc))
9192 		rc = ENXIO;
9193 	else
9194 		t4_tp_get_tid_stats(sc, &stats, 1);
9195 	mtx_unlock(&sc->reg_lock);
9196 	if (rc == 0) {
9197 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9198 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9199 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9200 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9201 		rc = sbuf_finish(sb);
9202 	}
9203 	sbuf_delete(sb);
9204 
9205 	return (rc);
9206 }
9207 
9208 static const char * const devlog_level_strings[] = {
9209 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9210 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9211 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9212 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9213 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9214 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9215 };
9216 
9217 static const char * const devlog_facility_strings[] = {
9218 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9219 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9220 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9221 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9222 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9223 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9224 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9225 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9226 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9227 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9228 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9229 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9230 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9231 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9232 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9233 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9234 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9235 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9236 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9237 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9238 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9239 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9240 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9241 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9242 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9243 };
9244 
9245 static int
9246 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9247 {
9248 	int i, j, rc, nentries, first = 0;
9249 	struct devlog_params *dparams = &sc->params.devlog;
9250 	struct fw_devlog_e *buf, *e;
9251 	uint64_t ftstamp = UINT64_MAX;
9252 
9253 	if (dparams->addr == 0)
9254 		return (ENXIO);
9255 
9256 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9257 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9258 	if (buf == NULL)
9259 		return (ENOMEM);
9260 
9261 	mtx_lock(&sc->reg_lock);
9262 	if (hw_off_limits(sc))
9263 		rc = ENXIO;
9264 	else
9265 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9266 		    dparams->size);
9267 	mtx_unlock(&sc->reg_lock);
9268 	if (rc != 0)
9269 		goto done;
9270 
9271 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9272 	for (i = 0; i < nentries; i++) {
9273 		e = &buf[i];
9274 
9275 		if (e->timestamp == 0)
9276 			break;	/* end */
9277 
9278 		e->timestamp = be64toh(e->timestamp);
9279 		e->seqno = be32toh(e->seqno);
9280 		for (j = 0; j < 8; j++)
9281 			e->params[j] = be32toh(e->params[j]);
9282 
9283 		if (e->timestamp < ftstamp) {
9284 			ftstamp = e->timestamp;
9285 			first = i;
9286 		}
9287 	}
9288 
9289 	if (buf[first].timestamp == 0)
9290 		goto done;	/* nothing in the log */
9291 
9292 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9293 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9294 
9295 	i = first;
9296 	do {
9297 		e = &buf[i];
9298 		if (e->timestamp == 0)
9299 			break;	/* end */
9300 
9301 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9302 		    e->seqno, e->timestamp,
9303 		    (e->level < nitems(devlog_level_strings) ?
9304 			devlog_level_strings[e->level] : "UNKNOWN"),
9305 		    (e->facility < nitems(devlog_facility_strings) ?
9306 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9307 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9308 		    e->params[2], e->params[3], e->params[4],
9309 		    e->params[5], e->params[6], e->params[7]);
9310 
9311 		if (++i == nentries)
9312 			i = 0;
9313 	} while (i != first);
9314 done:
9315 	free(buf, M_CXGBE);
9316 	return (rc);
9317 }
9318 
9319 static int
9320 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9321 {
9322 	struct adapter *sc = arg1;
9323 	int rc;
9324 	struct sbuf *sb;
9325 
9326 	rc = sysctl_wire_old_buffer(req, 0);
9327 	if (rc != 0)
9328 		return (rc);
9329 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9330 	if (sb == NULL)
9331 		return (ENOMEM);
9332 
9333 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9334 	if (rc == 0)
9335 		rc = sbuf_finish(sb);
9336 	sbuf_delete(sb);
9337 	return (rc);
9338 }
9339 
9340 void
9341 t4_os_dump_devlog(struct adapter *sc)
9342 {
9343 	int rc;
9344 	struct sbuf sb;
9345 
9346 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
9347 		return;
9348 	rc = sbuf_devlog(sc, &sb, M_NOWAIT);
9349 	if (rc == 0) {
9350 		rc = sbuf_finish(&sb);
9351 		if (rc == 0) {
9352 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9353 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
9354 		}
9355 	}
9356 	sbuf_delete(&sb);
9357 }
9358 
9359 static int
9360 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9361 {
9362 	struct adapter *sc = arg1;
9363 	struct sbuf *sb;
9364 	int rc;
9365 	struct tp_fcoe_stats stats[MAX_NCHAN];
9366 	int i, nchan = sc->chip_params->nchan;
9367 
9368 	rc = sysctl_wire_old_buffer(req, 0);
9369 	if (rc != 0)
9370 		return (rc);
9371 
9372 	mtx_lock(&sc->reg_lock);
9373 	if (hw_off_limits(sc))
9374 		rc = ENXIO;
9375 	else {
9376 		for (i = 0; i < nchan; i++)
9377 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9378 	}
9379 	mtx_unlock(&sc->reg_lock);
9380 	if (rc != 0)
9381 		return (rc);
9382 
9383 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9384 	if (sb == NULL)
9385 		return (ENOMEM);
9386 
9387 	if (nchan > 2) {
9388 		sbuf_printf(sb, "                   channel 0        channel 1"
9389 		    "        channel 2        channel 3");
9390 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9391 		    stats[0].octets_ddp, stats[1].octets_ddp,
9392 		    stats[2].octets_ddp, stats[3].octets_ddp);
9393 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9394 		    stats[0].frames_ddp, stats[1].frames_ddp,
9395 		    stats[2].frames_ddp, stats[3].frames_ddp);
9396 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9397 		    stats[0].frames_drop, stats[1].frames_drop,
9398 		    stats[2].frames_drop, stats[3].frames_drop);
9399 	} else {
9400 		sbuf_printf(sb, "                   channel 0        channel 1");
9401 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9402 		    stats[0].octets_ddp, stats[1].octets_ddp);
9403 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9404 		    stats[0].frames_ddp, stats[1].frames_ddp);
9405 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9406 		    stats[0].frames_drop, stats[1].frames_drop);
9407 	}
9408 
9409 	rc = sbuf_finish(sb);
9410 	sbuf_delete(sb);
9411 
9412 	return (rc);
9413 }
9414 
9415 static int
9416 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9417 {
9418 	struct adapter *sc = arg1;
9419 	struct sbuf *sb;
9420 	int rc, i;
9421 	unsigned int map, kbps, ipg, mode;
9422 	unsigned int pace_tab[NTX_SCHED];
9423 
9424 	rc = sysctl_wire_old_buffer(req, 0);
9425 	if (rc != 0)
9426 		return (rc);
9427 
9428 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9429 	if (sb == NULL)
9430 		return (ENOMEM);
9431 
9432 	mtx_lock(&sc->reg_lock);
9433 	if (hw_off_limits(sc)) {
9434 		rc = ENXIO;
9435 		goto done;
9436 	}
9437 
9438 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9439 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9440 	t4_read_pace_tbl(sc, pace_tab);
9441 
9442 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9443 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9444 
9445 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9446 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9447 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9448 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9449 		if (kbps)
9450 			sbuf_printf(sb, "%9u     ", kbps);
9451 		else
9452 			sbuf_printf(sb, " disabled     ");
9453 
9454 		if (ipg)
9455 			sbuf_printf(sb, "%13u        ", ipg);
9456 		else
9457 			sbuf_printf(sb, "     disabled        ");
9458 
9459 		if (pace_tab[i])
9460 			sbuf_printf(sb, "%10u", pace_tab[i]);
9461 		else
9462 			sbuf_printf(sb, "  disabled");
9463 	}
9464 	rc = sbuf_finish(sb);
9465 done:
9466 	mtx_unlock(&sc->reg_lock);
9467 	sbuf_delete(sb);
9468 	return (rc);
9469 }
9470 
9471 static int
9472 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9473 {
9474 	struct adapter *sc = arg1;
9475 	struct sbuf *sb;
9476 	int rc, i, j;
9477 	uint64_t *p0, *p1;
9478 	struct lb_port_stats s[2];
9479 	static const char *stat_name[] = {
9480 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9481 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9482 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9483 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9484 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9485 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9486 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9487 	};
9488 
9489 	rc = sysctl_wire_old_buffer(req, 0);
9490 	if (rc != 0)
9491 		return (rc);
9492 
9493 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9494 	if (sb == NULL)
9495 		return (ENOMEM);
9496 
9497 	memset(s, 0, sizeof(s));
9498 
9499 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9500 		mtx_lock(&sc->reg_lock);
9501 		if (hw_off_limits(sc))
9502 			rc = ENXIO;
9503 		else {
9504 			t4_get_lb_stats(sc, i, &s[0]);
9505 			t4_get_lb_stats(sc, i + 1, &s[1]);
9506 		}
9507 		mtx_unlock(&sc->reg_lock);
9508 		if (rc != 0)
9509 			break;
9510 
9511 		p0 = &s[0].octets;
9512 		p1 = &s[1].octets;
9513 		sbuf_printf(sb, "%s                       Loopback %u"
9514 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9515 
9516 		for (j = 0; j < nitems(stat_name); j++)
9517 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9518 				   *p0++, *p1++);
9519 	}
9520 
9521 	rc = sbuf_finish(sb);
9522 	sbuf_delete(sb);
9523 
9524 	return (rc);
9525 }
9526 
9527 static int
9528 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9529 {
9530 	int rc = 0;
9531 	struct port_info *pi = arg1;
9532 	struct link_config *lc = &pi->link_cfg;
9533 	struct sbuf *sb;
9534 
9535 	rc = sysctl_wire_old_buffer(req, 0);
9536 	if (rc != 0)
9537 		return(rc);
9538 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9539 	if (sb == NULL)
9540 		return (ENOMEM);
9541 
9542 	if (lc->link_ok || lc->link_down_rc == 255)
9543 		sbuf_printf(sb, "n/a");
9544 	else
9545 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9546 
9547 	rc = sbuf_finish(sb);
9548 	sbuf_delete(sb);
9549 
9550 	return (rc);
9551 }
9552 
9553 struct mem_desc {
9554 	unsigned int base;
9555 	unsigned int limit;
9556 	unsigned int idx;
9557 };
9558 
9559 static int
9560 mem_desc_cmp(const void *a, const void *b)
9561 {
9562 	return ((const struct mem_desc *)a)->base -
9563 	       ((const struct mem_desc *)b)->base;
9564 }
9565 
9566 static void
9567 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9568     unsigned int to)
9569 {
9570 	unsigned int size;
9571 
9572 	if (from == to)
9573 		return;
9574 
9575 	size = to - from + 1;
9576 	if (size == 0)
9577 		return;
9578 
9579 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9580 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9581 }
9582 
9583 static int
9584 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9585 {
9586 	struct adapter *sc = arg1;
9587 	struct sbuf *sb;
9588 	int rc, i, n;
9589 	uint32_t lo, hi, used, alloc;
9590 	static const char *memory[] = {"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:"};
9591 	static const char *region[] = {
9592 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9593 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9594 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9595 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9596 		"RQUDP region:", "PBL region:", "TXPBL region:",
9597 		"DBVFIFO region:", "ULPRX state:", "ULPTX state:",
9598 		"On-chip queues:", "TLS keys:",
9599 	};
9600 	struct mem_desc avail[4];
9601 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9602 	struct mem_desc *md = mem;
9603 
9604 	rc = sysctl_wire_old_buffer(req, 0);
9605 	if (rc != 0)
9606 		return (rc);
9607 
9608 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9609 	if (sb == NULL)
9610 		return (ENOMEM);
9611 
9612 	for (i = 0; i < nitems(mem); i++) {
9613 		mem[i].limit = 0;
9614 		mem[i].idx = i;
9615 	}
9616 
9617 	mtx_lock(&sc->reg_lock);
9618 	if (hw_off_limits(sc)) {
9619 		rc = ENXIO;
9620 		goto done;
9621 	}
9622 
9623 	/* Find and sort the populated memory ranges */
9624 	i = 0;
9625 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9626 	if (lo & F_EDRAM0_ENABLE) {
9627 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9628 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9629 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9630 		avail[i].idx = 0;
9631 		i++;
9632 	}
9633 	if (lo & F_EDRAM1_ENABLE) {
9634 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9635 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9636 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9637 		avail[i].idx = 1;
9638 		i++;
9639 	}
9640 	if (lo & F_EXT_MEM_ENABLE) {
9641 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9642 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9643 		avail[i].limit = avail[i].base +
9644 		    (G_EXT_MEM_SIZE(hi) << 20);
9645 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9646 		i++;
9647 	}
9648 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9649 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9650 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9651 		avail[i].limit = avail[i].base +
9652 		    (G_EXT_MEM1_SIZE(hi) << 20);
9653 		avail[i].idx = 4;
9654 		i++;
9655 	}
9656 	if (!i)                                    /* no memory available */
9657 		goto done;
9658 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9659 
9660 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9661 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9662 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9663 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9664 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9665 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9666 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9667 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9668 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9669 
9670 	/* the next few have explicit upper bounds */
9671 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9672 	md->limit = md->base - 1 +
9673 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9674 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9675 	md++;
9676 
9677 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9678 	md->limit = md->base - 1 +
9679 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9680 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9681 	md++;
9682 
9683 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9684 		if (chip_id(sc) <= CHELSIO_T5)
9685 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9686 		else
9687 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9688 		md->limit = 0;
9689 	} else {
9690 		md->base = 0;
9691 		md->idx = nitems(region);  /* hide it */
9692 	}
9693 	md++;
9694 
9695 #define ulp_region(reg) \
9696 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9697 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9698 
9699 	ulp_region(RX_ISCSI);
9700 	ulp_region(RX_TDDP);
9701 	ulp_region(TX_TPT);
9702 	ulp_region(RX_STAG);
9703 	ulp_region(RX_RQ);
9704 	ulp_region(RX_RQUDP);
9705 	ulp_region(RX_PBL);
9706 	ulp_region(TX_PBL);
9707 #undef ulp_region
9708 
9709 	md->base = 0;
9710 	md->idx = nitems(region);
9711 	if (!is_t4(sc)) {
9712 		uint32_t size = 0;
9713 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9714 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9715 
9716 		if (is_t5(sc)) {
9717 			if (sge_ctrl & F_VFIFO_ENABLE)
9718 				size = G_DBVFIFO_SIZE(fifo_size);
9719 		} else
9720 			size = G_T6_DBVFIFO_SIZE(fifo_size);
9721 
9722 		if (size) {
9723 			md->base = G_BASEADDR(t4_read_reg(sc,
9724 			    A_SGE_DBVFIFO_BADDR));
9725 			md->limit = md->base + (size << 2) - 1;
9726 		}
9727 	}
9728 	md++;
9729 
9730 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9731 	md->limit = 0;
9732 	md++;
9733 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9734 	md->limit = 0;
9735 	md++;
9736 
9737 	md->base = sc->vres.ocq.start;
9738 	if (sc->vres.ocq.size)
9739 		md->limit = md->base + sc->vres.ocq.size - 1;
9740 	else
9741 		md->idx = nitems(region);  /* hide it */
9742 	md++;
9743 
9744 	md->base = sc->vres.key.start;
9745 	if (sc->vres.key.size)
9746 		md->limit = md->base + sc->vres.key.size - 1;
9747 	else
9748 		md->idx = nitems(region);  /* hide it */
9749 	md++;
9750 
9751 	/* add any address-space holes, there can be up to 3 */
9752 	for (n = 0; n < i - 1; n++)
9753 		if (avail[n].limit < avail[n + 1].base)
9754 			(md++)->base = avail[n].limit;
9755 	if (avail[n].limit)
9756 		(md++)->base = avail[n].limit;
9757 
9758 	n = md - mem;
9759 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
9760 
9761 	for (lo = 0; lo < i; lo++)
9762 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
9763 				avail[lo].limit - 1);
9764 
9765 	sbuf_printf(sb, "\n");
9766 	for (i = 0; i < n; i++) {
9767 		if (mem[i].idx >= nitems(region))
9768 			continue;                        /* skip holes */
9769 		if (!mem[i].limit)
9770 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
9771 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
9772 				mem[i].limit);
9773 	}
9774 
9775 	sbuf_printf(sb, "\n");
9776 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
9777 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
9778 	mem_region_show(sb, "uP RAM:", lo, hi);
9779 
9780 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
9781 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
9782 	mem_region_show(sb, "uP Extmem2:", lo, hi);
9783 
9784 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
9785 	sbuf_printf(sb, "\n%u Rx pages of size %uKiB for %u channels\n",
9786 		   G_PMRXMAXPAGE(lo),
9787 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
9788 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
9789 
9790 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
9791 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
9792 	sbuf_printf(sb, "%u Tx pages of size %u%ciB for %u channels\n",
9793 		   G_PMTXMAXPAGE(lo),
9794 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
9795 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
9796 	sbuf_printf(sb, "%u p-structs\n",
9797 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT));
9798 
9799 	for (i = 0; i < 4; i++) {
9800 		if (chip_id(sc) > CHELSIO_T5)
9801 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
9802 		else
9803 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
9804 		if (is_t5(sc)) {
9805 			used = G_T5_USED(lo);
9806 			alloc = G_T5_ALLOC(lo);
9807 		} else {
9808 			used = G_USED(lo);
9809 			alloc = G_ALLOC(lo);
9810 		}
9811 		/* For T6 these are MAC buffer groups */
9812 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
9813 		    i, used, alloc);
9814 	}
9815 	for (i = 0; i < sc->chip_params->nchan; i++) {
9816 		if (chip_id(sc) > CHELSIO_T5)
9817 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
9818 		else
9819 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
9820 		if (is_t5(sc)) {
9821 			used = G_T5_USED(lo);
9822 			alloc = G_T5_ALLOC(lo);
9823 		} else {
9824 			used = G_USED(lo);
9825 			alloc = G_ALLOC(lo);
9826 		}
9827 		/* For T6 these are MAC buffer groups */
9828 		sbuf_printf(sb,
9829 		    "\nLoopback %d using %u pages out of %u allocated",
9830 		    i, used, alloc);
9831 	}
9832 done:
9833 	mtx_unlock(&sc->reg_lock);
9834 	if (rc == 0)
9835 		rc = sbuf_finish(sb);
9836 	sbuf_delete(sb);
9837 	return (rc);
9838 }
9839 
9840 static inline void
9841 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
9842 {
9843 	*mask = x | y;
9844 	y = htobe64(y);
9845 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
9846 }
9847 
9848 static int
9849 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
9850 {
9851 	struct adapter *sc = arg1;
9852 	struct sbuf *sb;
9853 	int rc, i;
9854 
9855 	MPASS(chip_id(sc) <= CHELSIO_T5);
9856 
9857 	rc = sysctl_wire_old_buffer(req, 0);
9858 	if (rc != 0)
9859 		return (rc);
9860 
9861 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9862 	if (sb == NULL)
9863 		return (ENOMEM);
9864 
9865 	sbuf_printf(sb,
9866 	    "Idx  Ethernet address     Mask     Vld Ports PF"
9867 	    "  VF              Replication             P0 P1 P2 P3  ML");
9868 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
9869 		uint64_t tcamx, tcamy, mask;
9870 		uint32_t cls_lo, cls_hi;
9871 		uint8_t addr[ETHER_ADDR_LEN];
9872 
9873 		mtx_lock(&sc->reg_lock);
9874 		if (hw_off_limits(sc))
9875 			rc = ENXIO;
9876 		else {
9877 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
9878 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
9879 		}
9880 		mtx_unlock(&sc->reg_lock);
9881 		if (rc != 0)
9882 			break;
9883 		if (tcamx & tcamy)
9884 			continue;
9885 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
9886 		mtx_lock(&sc->reg_lock);
9887 		if (hw_off_limits(sc))
9888 			rc = ENXIO;
9889 		else {
9890 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
9891 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
9892 		}
9893 		mtx_unlock(&sc->reg_lock);
9894 		if (rc != 0)
9895 			break;
9896 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
9897 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
9898 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
9899 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
9900 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
9901 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
9902 
9903 		if (cls_lo & F_REPLICATE) {
9904 			struct fw_ldst_cmd ldst_cmd;
9905 
9906 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
9907 			ldst_cmd.op_to_addrspace =
9908 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
9909 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
9910 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
9911 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
9912 			ldst_cmd.u.mps.rplc.fid_idx =
9913 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
9914 				V_FW_LDST_CMD_IDX(i));
9915 
9916 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
9917 			    "t4mps");
9918 			if (rc)
9919 				break;
9920 			if (hw_off_limits(sc))
9921 				rc = ENXIO;
9922 			else
9923 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
9924 				    sizeof(ldst_cmd), &ldst_cmd);
9925 			end_synchronized_op(sc, 0);
9926 			if (rc != 0)
9927 				break;
9928 			else {
9929 				sbuf_printf(sb, " %08x %08x %08x %08x",
9930 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
9931 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
9932 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
9933 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
9934 			}
9935 		} else
9936 			sbuf_printf(sb, "%36s", "");
9937 
9938 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
9939 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
9940 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
9941 	}
9942 
9943 	if (rc)
9944 		(void) sbuf_finish(sb);
9945 	else
9946 		rc = sbuf_finish(sb);
9947 	sbuf_delete(sb);
9948 
9949 	return (rc);
9950 }
9951 
9952 static int
9953 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
9954 {
9955 	struct adapter *sc = arg1;
9956 	struct sbuf *sb;
9957 	int rc, i;
9958 
9959 	MPASS(chip_id(sc) > CHELSIO_T5);
9960 
9961 	rc = sysctl_wire_old_buffer(req, 0);
9962 	if (rc != 0)
9963 		return (rc);
9964 
9965 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9966 	if (sb == NULL)
9967 		return (ENOMEM);
9968 
9969 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
9970 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
9971 	    "                           Replication"
9972 	    "                                    P0 P1 P2 P3  ML\n");
9973 
9974 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
9975 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
9976 		uint16_t ivlan;
9977 		uint64_t tcamx, tcamy, val, mask;
9978 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
9979 		uint8_t addr[ETHER_ADDR_LEN];
9980 
9981 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
9982 		if (i < 256)
9983 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
9984 		else
9985 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
9986 		mtx_lock(&sc->reg_lock);
9987 		if (hw_off_limits(sc))
9988 			rc = ENXIO;
9989 		else {
9990 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
9991 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
9992 			tcamy = G_DMACH(val) << 32;
9993 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
9994 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
9995 		}
9996 		mtx_unlock(&sc->reg_lock);
9997 		if (rc != 0)
9998 			break;
9999 
10000 		lookup_type = G_DATALKPTYPE(data2);
10001 		port_num = G_DATAPORTNUM(data2);
10002 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10003 			/* Inner header VNI */
10004 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10005 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10006 			dip_hit = data2 & F_DATADIPHIT;
10007 			vlan_vld = 0;
10008 		} else {
10009 			vniy = 0;
10010 			dip_hit = 0;
10011 			vlan_vld = data2 & F_DATAVIDH2;
10012 			ivlan = G_VIDL(val);
10013 		}
10014 
10015 		ctl |= V_CTLXYBITSEL(1);
10016 		mtx_lock(&sc->reg_lock);
10017 		if (hw_off_limits(sc))
10018 			rc = ENXIO;
10019 		else {
10020 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10021 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10022 			tcamx = G_DMACH(val) << 32;
10023 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10024 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10025 		}
10026 		mtx_unlock(&sc->reg_lock);
10027 		if (rc != 0)
10028 			break;
10029 
10030 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10031 			/* Inner header VNI mask */
10032 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10033 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10034 		} else
10035 			vnix = 0;
10036 
10037 		if (tcamx & tcamy)
10038 			continue;
10039 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10040 
10041 		mtx_lock(&sc->reg_lock);
10042 		if (hw_off_limits(sc))
10043 			rc = ENXIO;
10044 		else {
10045 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10046 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10047 		}
10048 		mtx_unlock(&sc->reg_lock);
10049 		if (rc != 0)
10050 			break;
10051 
10052 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10053 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10054 			    "%012jx %06x %06x    -    -   %3c"
10055 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10056 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10057 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10058 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10059 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10060 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10061 		} else {
10062 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10063 			    "%012jx    -       -   ", i, addr[0], addr[1],
10064 			    addr[2], addr[3], addr[4], addr[5],
10065 			    (uintmax_t)mask);
10066 
10067 			if (vlan_vld)
10068 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10069 			else
10070 				sbuf_printf(sb, "  -    N     ");
10071 
10072 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10073 			    lookup_type ? 'I' : 'O', port_num,
10074 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10075 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10076 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10077 		}
10078 
10079 
10080 		if (cls_lo & F_T6_REPLICATE) {
10081 			struct fw_ldst_cmd ldst_cmd;
10082 
10083 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10084 			ldst_cmd.op_to_addrspace =
10085 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10086 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10087 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10088 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10089 			ldst_cmd.u.mps.rplc.fid_idx =
10090 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10091 				V_FW_LDST_CMD_IDX(i));
10092 
10093 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10094 			    "t6mps");
10095 			if (rc)
10096 				break;
10097 			if (hw_off_limits(sc))
10098 				rc = ENXIO;
10099 			else
10100 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10101 				    sizeof(ldst_cmd), &ldst_cmd);
10102 			end_synchronized_op(sc, 0);
10103 			if (rc != 0)
10104 				break;
10105 			else {
10106 				sbuf_printf(sb, " %08x %08x %08x %08x"
10107 				    " %08x %08x %08x %08x",
10108 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10109 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10110 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10111 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10112 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10113 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10114 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10115 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10116 			}
10117 		} else
10118 			sbuf_printf(sb, "%72s", "");
10119 
10120 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10121 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10122 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10123 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10124 	}
10125 
10126 	if (rc)
10127 		(void) sbuf_finish(sb);
10128 	else
10129 		rc = sbuf_finish(sb);
10130 	sbuf_delete(sb);
10131 
10132 	return (rc);
10133 }
10134 
10135 static int
10136 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10137 {
10138 	struct adapter *sc = arg1;
10139 	struct sbuf *sb;
10140 	int rc;
10141 	uint16_t mtus[NMTUS];
10142 
10143 	rc = sysctl_wire_old_buffer(req, 0);
10144 	if (rc != 0)
10145 		return (rc);
10146 
10147 	mtx_lock(&sc->reg_lock);
10148 	if (hw_off_limits(sc))
10149 		rc = ENXIO;
10150 	else
10151 		t4_read_mtu_tbl(sc, mtus, NULL);
10152 	mtx_unlock(&sc->reg_lock);
10153 	if (rc != 0)
10154 		return (rc);
10155 
10156 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10157 	if (sb == NULL)
10158 		return (ENOMEM);
10159 
10160 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10161 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10162 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10163 	    mtus[14], mtus[15]);
10164 
10165 	rc = sbuf_finish(sb);
10166 	sbuf_delete(sb);
10167 
10168 	return (rc);
10169 }
10170 
10171 static int
10172 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10173 {
10174 	struct adapter *sc = arg1;
10175 	struct sbuf *sb;
10176 	int rc, i;
10177 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10178 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10179 	static const char *tx_stats[MAX_PM_NSTATS] = {
10180 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10181 		"Tx FIFO wait", NULL, "Tx latency"
10182 	};
10183 	static const char *rx_stats[MAX_PM_NSTATS] = {
10184 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10185 		"Rx FIFO wait", NULL, "Rx latency"
10186 	};
10187 
10188 	rc = sysctl_wire_old_buffer(req, 0);
10189 	if (rc != 0)
10190 		return (rc);
10191 
10192 	mtx_lock(&sc->reg_lock);
10193 	if (hw_off_limits(sc))
10194 		rc = ENXIO;
10195 	else {
10196 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10197 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10198 	}
10199 	mtx_unlock(&sc->reg_lock);
10200 	if (rc != 0)
10201 		return (rc);
10202 
10203 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10204 	if (sb == NULL)
10205 		return (ENOMEM);
10206 
10207 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10208 	for (i = 0; i < 4; i++) {
10209 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10210 		    tx_cyc[i]);
10211 	}
10212 
10213 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10214 	for (i = 0; i < 4; i++) {
10215 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10216 		    rx_cyc[i]);
10217 	}
10218 
10219 	if (chip_id(sc) > CHELSIO_T5) {
10220 		sbuf_printf(sb,
10221 		    "\n              Total wait      Total occupancy");
10222 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10223 		    tx_cyc[i]);
10224 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10225 		    rx_cyc[i]);
10226 
10227 		i += 2;
10228 		MPASS(i < nitems(tx_stats));
10229 
10230 		sbuf_printf(sb,
10231 		    "\n                   Reads           Total wait");
10232 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10233 		    tx_cyc[i]);
10234 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10235 		    rx_cyc[i]);
10236 	}
10237 
10238 	rc = sbuf_finish(sb);
10239 	sbuf_delete(sb);
10240 
10241 	return (rc);
10242 }
10243 
10244 static int
10245 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10246 {
10247 	struct adapter *sc = arg1;
10248 	struct sbuf *sb;
10249 	int rc;
10250 	struct tp_rdma_stats stats;
10251 
10252 	rc = sysctl_wire_old_buffer(req, 0);
10253 	if (rc != 0)
10254 		return (rc);
10255 
10256 	mtx_lock(&sc->reg_lock);
10257 	if (hw_off_limits(sc))
10258 		rc = ENXIO;
10259 	else
10260 		t4_tp_get_rdma_stats(sc, &stats, 0);
10261 	mtx_unlock(&sc->reg_lock);
10262 	if (rc != 0)
10263 		return (rc);
10264 
10265 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10266 	if (sb == NULL)
10267 		return (ENOMEM);
10268 
10269 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10270 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10271 
10272 	rc = sbuf_finish(sb);
10273 	sbuf_delete(sb);
10274 
10275 	return (rc);
10276 }
10277 
10278 static int
10279 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10280 {
10281 	struct adapter *sc = arg1;
10282 	struct sbuf *sb;
10283 	int rc;
10284 	struct tp_tcp_stats v4, v6;
10285 
10286 	rc = sysctl_wire_old_buffer(req, 0);
10287 	if (rc != 0)
10288 		return (rc);
10289 
10290 	mtx_lock(&sc->reg_lock);
10291 	if (hw_off_limits(sc))
10292 		rc = ENXIO;
10293 	else
10294 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10295 	mtx_unlock(&sc->reg_lock);
10296 	if (rc != 0)
10297 		return (rc);
10298 
10299 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10300 	if (sb == NULL)
10301 		return (ENOMEM);
10302 
10303 	sbuf_printf(sb,
10304 	    "                                IP                 IPv6\n");
10305 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10306 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10307 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10308 	    v4.tcp_in_segs, v6.tcp_in_segs);
10309 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10310 	    v4.tcp_out_segs, v6.tcp_out_segs);
10311 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10312 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10313 
10314 	rc = sbuf_finish(sb);
10315 	sbuf_delete(sb);
10316 
10317 	return (rc);
10318 }
10319 
10320 static int
10321 sysctl_tids(SYSCTL_HANDLER_ARGS)
10322 {
10323 	struct adapter *sc = arg1;
10324 	struct sbuf *sb;
10325 	int rc;
10326 	uint32_t x, y;
10327 	struct tid_info *t = &sc->tids;
10328 
10329 	rc = sysctl_wire_old_buffer(req, 0);
10330 	if (rc != 0)
10331 		return (rc);
10332 
10333 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10334 	if (sb == NULL)
10335 		return (ENOMEM);
10336 
10337 	if (t->natids) {
10338 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10339 		    t->atids_in_use);
10340 	}
10341 
10342 	if (t->nhpftids) {
10343 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10344 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10345 	}
10346 
10347 	if (t->ntids) {
10348 		bool hashen = false;
10349 
10350 		mtx_lock(&sc->reg_lock);
10351 		if (hw_off_limits(sc))
10352 			rc = ENXIO;
10353 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10354 			hashen = true;
10355 			if (chip_id(sc) <= CHELSIO_T5) {
10356 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10357 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10358 			} else {
10359 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10360 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10361 			}
10362 		}
10363 		mtx_unlock(&sc->reg_lock);
10364 		if (rc != 0)
10365 			goto done;
10366 
10367 		sbuf_printf(sb, "TID range: ");
10368 		if (hashen) {
10369 			if (x)
10370 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10371 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10372 		} else {
10373 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10374 			    t->ntids - 1);
10375 		}
10376 		sbuf_printf(sb, ", in use: %u\n",
10377 		    atomic_load_acq_int(&t->tids_in_use));
10378 	}
10379 
10380 	if (t->nstids) {
10381 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10382 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10383 	}
10384 
10385 	if (t->nftids) {
10386 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10387 		    t->ftid_end, t->ftids_in_use);
10388 	}
10389 
10390 	if (t->netids) {
10391 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10392 		    t->etid_base + t->netids - 1, t->etids_in_use);
10393 	}
10394 
10395 	mtx_lock(&sc->reg_lock);
10396 	if (hw_off_limits(sc))
10397 		rc = ENXIO;
10398 	else {
10399 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10400 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10401 	}
10402 	mtx_unlock(&sc->reg_lock);
10403 	if (rc != 0)
10404 		goto done;
10405 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10406 done:
10407 	if (rc == 0)
10408 		rc = sbuf_finish(sb);
10409 	else
10410 		(void)sbuf_finish(sb);
10411 	sbuf_delete(sb);
10412 
10413 	return (rc);
10414 }
10415 
10416 static int
10417 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10418 {
10419 	struct adapter *sc = arg1;
10420 	struct sbuf *sb;
10421 	int rc;
10422 	struct tp_err_stats stats;
10423 
10424 	rc = sysctl_wire_old_buffer(req, 0);
10425 	if (rc != 0)
10426 		return (rc);
10427 
10428 	mtx_lock(&sc->reg_lock);
10429 	if (hw_off_limits(sc))
10430 		rc = ENXIO;
10431 	else
10432 		t4_tp_get_err_stats(sc, &stats, 0);
10433 	mtx_unlock(&sc->reg_lock);
10434 	if (rc != 0)
10435 		return (rc);
10436 
10437 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10438 	if (sb == NULL)
10439 		return (ENOMEM);
10440 
10441 	if (sc->chip_params->nchan > 2) {
10442 		sbuf_printf(sb, "                 channel 0  channel 1"
10443 		    "  channel 2  channel 3\n");
10444 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10445 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10446 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10447 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10448 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10449 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10450 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10451 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10452 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10453 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10454 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10455 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10456 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10457 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10458 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10459 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10460 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10461 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10462 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10463 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10464 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10465 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10466 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10467 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10468 	} else {
10469 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10470 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10471 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10472 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10473 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10474 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10475 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10476 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10477 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10478 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10479 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10480 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10481 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10482 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10483 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10484 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10485 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10486 	}
10487 
10488 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10489 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10490 
10491 	rc = sbuf_finish(sb);
10492 	sbuf_delete(sb);
10493 
10494 	return (rc);
10495 }
10496 
10497 static int
10498 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10499 {
10500 	struct adapter *sc = arg1;
10501 	struct sbuf *sb;
10502 	int rc;
10503 	struct tp_tnl_stats stats;
10504 
10505 	rc = sysctl_wire_old_buffer(req, 0);
10506 	if (rc != 0)
10507 		return(rc);
10508 
10509 	mtx_lock(&sc->reg_lock);
10510 	if (hw_off_limits(sc))
10511 		rc = ENXIO;
10512 	else
10513 		t4_tp_get_tnl_stats(sc, &stats, 1);
10514 	mtx_unlock(&sc->reg_lock);
10515 	if (rc != 0)
10516 		return (rc);
10517 
10518 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10519 	if (sb == NULL)
10520 		return (ENOMEM);
10521 
10522 	if (sc->chip_params->nchan > 2) {
10523 		sbuf_printf(sb, "           channel 0  channel 1"
10524 		    "  channel 2  channel 3\n");
10525 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10526 		    stats.out_pkt[0], stats.out_pkt[1],
10527 		    stats.out_pkt[2], stats.out_pkt[3]);
10528 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10529 		    stats.in_pkt[0], stats.in_pkt[1],
10530 		    stats.in_pkt[2], stats.in_pkt[3]);
10531 	} else {
10532 		sbuf_printf(sb, "           channel 0  channel 1\n");
10533 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10534 		    stats.out_pkt[0], stats.out_pkt[1]);
10535 		sbuf_printf(sb, "InPkts:   %10u %10u",
10536 		    stats.in_pkt[0], stats.in_pkt[1]);
10537 	}
10538 
10539 	rc = sbuf_finish(sb);
10540 	sbuf_delete(sb);
10541 
10542 	return (rc);
10543 }
10544 
10545 static int
10546 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10547 {
10548 	struct adapter *sc = arg1;
10549 	struct tp_params *tpp = &sc->params.tp;
10550 	u_int mask;
10551 	int rc;
10552 
10553 	mask = tpp->la_mask >> 16;
10554 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10555 	if (rc != 0 || req->newptr == NULL)
10556 		return (rc);
10557 	if (mask > 0xffff)
10558 		return (EINVAL);
10559 	mtx_lock(&sc->reg_lock);
10560 	if (hw_off_limits(sc))
10561 		rc = ENXIO;
10562 	else {
10563 		tpp->la_mask = mask << 16;
10564 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10565 		    tpp->la_mask);
10566 	}
10567 	mtx_unlock(&sc->reg_lock);
10568 
10569 	return (rc);
10570 }
10571 
10572 struct field_desc {
10573 	const char *name;
10574 	u_int start;
10575 	u_int width;
10576 };
10577 
10578 static void
10579 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10580 {
10581 	char buf[32];
10582 	int line_size = 0;
10583 
10584 	while (f->name) {
10585 		uint64_t mask = (1ULL << f->width) - 1;
10586 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10587 		    ((uintmax_t)v >> f->start) & mask);
10588 
10589 		if (line_size + len >= 79) {
10590 			line_size = 8;
10591 			sbuf_printf(sb, "\n        ");
10592 		}
10593 		sbuf_printf(sb, "%s ", buf);
10594 		line_size += len + 1;
10595 		f++;
10596 	}
10597 	sbuf_printf(sb, "\n");
10598 }
10599 
10600 static const struct field_desc tp_la0[] = {
10601 	{ "RcfOpCodeOut", 60, 4 },
10602 	{ "State", 56, 4 },
10603 	{ "WcfState", 52, 4 },
10604 	{ "RcfOpcSrcOut", 50, 2 },
10605 	{ "CRxError", 49, 1 },
10606 	{ "ERxError", 48, 1 },
10607 	{ "SanityFailed", 47, 1 },
10608 	{ "SpuriousMsg", 46, 1 },
10609 	{ "FlushInputMsg", 45, 1 },
10610 	{ "FlushInputCpl", 44, 1 },
10611 	{ "RssUpBit", 43, 1 },
10612 	{ "RssFilterHit", 42, 1 },
10613 	{ "Tid", 32, 10 },
10614 	{ "InitTcb", 31, 1 },
10615 	{ "LineNumber", 24, 7 },
10616 	{ "Emsg", 23, 1 },
10617 	{ "EdataOut", 22, 1 },
10618 	{ "Cmsg", 21, 1 },
10619 	{ "CdataOut", 20, 1 },
10620 	{ "EreadPdu", 19, 1 },
10621 	{ "CreadPdu", 18, 1 },
10622 	{ "TunnelPkt", 17, 1 },
10623 	{ "RcfPeerFin", 16, 1 },
10624 	{ "RcfReasonOut", 12, 4 },
10625 	{ "TxCchannel", 10, 2 },
10626 	{ "RcfTxChannel", 8, 2 },
10627 	{ "RxEchannel", 6, 2 },
10628 	{ "RcfRxChannel", 5, 1 },
10629 	{ "RcfDataOutSrdy", 4, 1 },
10630 	{ "RxDvld", 3, 1 },
10631 	{ "RxOoDvld", 2, 1 },
10632 	{ "RxCongestion", 1, 1 },
10633 	{ "TxCongestion", 0, 1 },
10634 	{ NULL }
10635 };
10636 
10637 static const struct field_desc tp_la1[] = {
10638 	{ "CplCmdIn", 56, 8 },
10639 	{ "CplCmdOut", 48, 8 },
10640 	{ "ESynOut", 47, 1 },
10641 	{ "EAckOut", 46, 1 },
10642 	{ "EFinOut", 45, 1 },
10643 	{ "ERstOut", 44, 1 },
10644 	{ "SynIn", 43, 1 },
10645 	{ "AckIn", 42, 1 },
10646 	{ "FinIn", 41, 1 },
10647 	{ "RstIn", 40, 1 },
10648 	{ "DataIn", 39, 1 },
10649 	{ "DataInVld", 38, 1 },
10650 	{ "PadIn", 37, 1 },
10651 	{ "RxBufEmpty", 36, 1 },
10652 	{ "RxDdp", 35, 1 },
10653 	{ "RxFbCongestion", 34, 1 },
10654 	{ "TxFbCongestion", 33, 1 },
10655 	{ "TxPktSumSrdy", 32, 1 },
10656 	{ "RcfUlpType", 28, 4 },
10657 	{ "Eread", 27, 1 },
10658 	{ "Ebypass", 26, 1 },
10659 	{ "Esave", 25, 1 },
10660 	{ "Static0", 24, 1 },
10661 	{ "Cread", 23, 1 },
10662 	{ "Cbypass", 22, 1 },
10663 	{ "Csave", 21, 1 },
10664 	{ "CPktOut", 20, 1 },
10665 	{ "RxPagePoolFull", 18, 2 },
10666 	{ "RxLpbkPkt", 17, 1 },
10667 	{ "TxLpbkPkt", 16, 1 },
10668 	{ "RxVfValid", 15, 1 },
10669 	{ "SynLearned", 14, 1 },
10670 	{ "SetDelEntry", 13, 1 },
10671 	{ "SetInvEntry", 12, 1 },
10672 	{ "CpcmdDvld", 11, 1 },
10673 	{ "CpcmdSave", 10, 1 },
10674 	{ "RxPstructsFull", 8, 2 },
10675 	{ "EpcmdDvld", 7, 1 },
10676 	{ "EpcmdFlush", 6, 1 },
10677 	{ "EpcmdTrimPrefix", 5, 1 },
10678 	{ "EpcmdTrimPostfix", 4, 1 },
10679 	{ "ERssIp4Pkt", 3, 1 },
10680 	{ "ERssIp6Pkt", 2, 1 },
10681 	{ "ERssTcpUdpPkt", 1, 1 },
10682 	{ "ERssFceFipPkt", 0, 1 },
10683 	{ NULL }
10684 };
10685 
10686 static const struct field_desc tp_la2[] = {
10687 	{ "CplCmdIn", 56, 8 },
10688 	{ "MpsVfVld", 55, 1 },
10689 	{ "MpsPf", 52, 3 },
10690 	{ "MpsVf", 44, 8 },
10691 	{ "SynIn", 43, 1 },
10692 	{ "AckIn", 42, 1 },
10693 	{ "FinIn", 41, 1 },
10694 	{ "RstIn", 40, 1 },
10695 	{ "DataIn", 39, 1 },
10696 	{ "DataInVld", 38, 1 },
10697 	{ "PadIn", 37, 1 },
10698 	{ "RxBufEmpty", 36, 1 },
10699 	{ "RxDdp", 35, 1 },
10700 	{ "RxFbCongestion", 34, 1 },
10701 	{ "TxFbCongestion", 33, 1 },
10702 	{ "TxPktSumSrdy", 32, 1 },
10703 	{ "RcfUlpType", 28, 4 },
10704 	{ "Eread", 27, 1 },
10705 	{ "Ebypass", 26, 1 },
10706 	{ "Esave", 25, 1 },
10707 	{ "Static0", 24, 1 },
10708 	{ "Cread", 23, 1 },
10709 	{ "Cbypass", 22, 1 },
10710 	{ "Csave", 21, 1 },
10711 	{ "CPktOut", 20, 1 },
10712 	{ "RxPagePoolFull", 18, 2 },
10713 	{ "RxLpbkPkt", 17, 1 },
10714 	{ "TxLpbkPkt", 16, 1 },
10715 	{ "RxVfValid", 15, 1 },
10716 	{ "SynLearned", 14, 1 },
10717 	{ "SetDelEntry", 13, 1 },
10718 	{ "SetInvEntry", 12, 1 },
10719 	{ "CpcmdDvld", 11, 1 },
10720 	{ "CpcmdSave", 10, 1 },
10721 	{ "RxPstructsFull", 8, 2 },
10722 	{ "EpcmdDvld", 7, 1 },
10723 	{ "EpcmdFlush", 6, 1 },
10724 	{ "EpcmdTrimPrefix", 5, 1 },
10725 	{ "EpcmdTrimPostfix", 4, 1 },
10726 	{ "ERssIp4Pkt", 3, 1 },
10727 	{ "ERssIp6Pkt", 2, 1 },
10728 	{ "ERssTcpUdpPkt", 1, 1 },
10729 	{ "ERssFceFipPkt", 0, 1 },
10730 	{ NULL }
10731 };
10732 
10733 static void
10734 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10735 {
10736 
10737 	field_desc_show(sb, *p, tp_la0);
10738 }
10739 
10740 static void
10741 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10742 {
10743 
10744 	if (idx)
10745 		sbuf_printf(sb, "\n");
10746 	field_desc_show(sb, p[0], tp_la0);
10747 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10748 		field_desc_show(sb, p[1], tp_la0);
10749 }
10750 
10751 static void
10752 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
10753 {
10754 
10755 	if (idx)
10756 		sbuf_printf(sb, "\n");
10757 	field_desc_show(sb, p[0], tp_la0);
10758 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10759 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
10760 }
10761 
10762 static int
10763 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
10764 {
10765 	struct adapter *sc = arg1;
10766 	struct sbuf *sb;
10767 	uint64_t *buf, *p;
10768 	int rc;
10769 	u_int i, inc;
10770 	void (*show_func)(struct sbuf *, uint64_t *, int);
10771 
10772 	rc = sysctl_wire_old_buffer(req, 0);
10773 	if (rc != 0)
10774 		return (rc);
10775 
10776 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10777 	if (sb == NULL)
10778 		return (ENOMEM);
10779 
10780 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
10781 
10782 	mtx_lock(&sc->reg_lock);
10783 	if (hw_off_limits(sc))
10784 		rc = ENXIO;
10785 	else {
10786 		t4_tp_read_la(sc, buf, NULL);
10787 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
10788 		case 2:
10789 			inc = 2;
10790 			show_func = tp_la_show2;
10791 			break;
10792 		case 3:
10793 			inc = 2;
10794 			show_func = tp_la_show3;
10795 			break;
10796 		default:
10797 			inc = 1;
10798 			show_func = tp_la_show;
10799 		}
10800 	}
10801 	mtx_unlock(&sc->reg_lock);
10802 	if (rc != 0)
10803 		goto done;
10804 
10805 	p = buf;
10806 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
10807 		(*show_func)(sb, p, i);
10808 	rc = sbuf_finish(sb);
10809 done:
10810 	sbuf_delete(sb);
10811 	free(buf, M_CXGBE);
10812 	return (rc);
10813 }
10814 
10815 static int
10816 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
10817 {
10818 	struct adapter *sc = arg1;
10819 	struct sbuf *sb;
10820 	int rc;
10821 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
10822 
10823 	rc = sysctl_wire_old_buffer(req, 0);
10824 	if (rc != 0)
10825 		return (rc);
10826 
10827 	mtx_lock(&sc->reg_lock);
10828 	if (hw_off_limits(sc))
10829 		rc = ENXIO;
10830 	else
10831 		t4_get_chan_txrate(sc, nrate, orate);
10832 	mtx_unlock(&sc->reg_lock);
10833 	if (rc != 0)
10834 		return (rc);
10835 
10836 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10837 	if (sb == NULL)
10838 		return (ENOMEM);
10839 
10840 	if (sc->chip_params->nchan > 2) {
10841 		sbuf_printf(sb, "              channel 0   channel 1"
10842 		    "   channel 2   channel 3\n");
10843 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
10844 		    nrate[0], nrate[1], nrate[2], nrate[3]);
10845 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
10846 		    orate[0], orate[1], orate[2], orate[3]);
10847 	} else {
10848 		sbuf_printf(sb, "              channel 0   channel 1\n");
10849 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
10850 		    nrate[0], nrate[1]);
10851 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
10852 		    orate[0], orate[1]);
10853 	}
10854 
10855 	rc = sbuf_finish(sb);
10856 	sbuf_delete(sb);
10857 
10858 	return (rc);
10859 }
10860 
10861 static int
10862 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
10863 {
10864 	struct adapter *sc = arg1;
10865 	struct sbuf *sb;
10866 	uint32_t *buf, *p;
10867 	int rc, i;
10868 
10869 	rc = sysctl_wire_old_buffer(req, 0);
10870 	if (rc != 0)
10871 		return (rc);
10872 
10873 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10874 	if (sb == NULL)
10875 		return (ENOMEM);
10876 
10877 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
10878 	    M_ZERO | M_WAITOK);
10879 
10880 	mtx_lock(&sc->reg_lock);
10881 	if (hw_off_limits(sc))
10882 		rc = ENXIO;
10883 	else
10884 		t4_ulprx_read_la(sc, buf);
10885 	mtx_unlock(&sc->reg_lock);
10886 	if (rc != 0)
10887 		goto done;
10888 
10889 	p = buf;
10890 	sbuf_printf(sb, "      Pcmd        Type   Message"
10891 	    "                Data");
10892 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
10893 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
10894 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
10895 	}
10896 	rc = sbuf_finish(sb);
10897 done:
10898 	sbuf_delete(sb);
10899 	free(buf, M_CXGBE);
10900 	return (rc);
10901 }
10902 
10903 static int
10904 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
10905 {
10906 	struct adapter *sc = arg1;
10907 	struct sbuf *sb;
10908 	int rc;
10909 	uint32_t cfg, s1, s2;
10910 
10911 	MPASS(chip_id(sc) >= CHELSIO_T5);
10912 
10913 	rc = sysctl_wire_old_buffer(req, 0);
10914 	if (rc != 0)
10915 		return (rc);
10916 
10917 	mtx_lock(&sc->reg_lock);
10918 	if (hw_off_limits(sc))
10919 		rc = ENXIO;
10920 	else {
10921 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
10922 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
10923 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
10924 	}
10925 	mtx_unlock(&sc->reg_lock);
10926 	if (rc != 0)
10927 		return (rc);
10928 
10929 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10930 	if (sb == NULL)
10931 		return (ENOMEM);
10932 
10933 	if (G_STATSOURCE_T5(cfg) == 7) {
10934 		int mode;
10935 
10936 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
10937 		if (mode == 0)
10938 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
10939 		else if (mode == 1)
10940 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
10941 		else
10942 			sbuf_printf(sb, "unknown mode %d", mode);
10943 	}
10944 	rc = sbuf_finish(sb);
10945 	sbuf_delete(sb);
10946 
10947 	return (rc);
10948 }
10949 
10950 static int
10951 sysctl_cpus(SYSCTL_HANDLER_ARGS)
10952 {
10953 	struct adapter *sc = arg1;
10954 	enum cpu_sets op = arg2;
10955 	cpuset_t cpuset;
10956 	struct sbuf *sb;
10957 	int i, rc;
10958 
10959 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
10960 
10961 	CPU_ZERO(&cpuset);
10962 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
10963 	if (rc != 0)
10964 		return (rc);
10965 
10966 	rc = sysctl_wire_old_buffer(req, 0);
10967 	if (rc != 0)
10968 		return (rc);
10969 
10970 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10971 	if (sb == NULL)
10972 		return (ENOMEM);
10973 
10974 	CPU_FOREACH(i)
10975 		sbuf_printf(sb, "%d ", i);
10976 	rc = sbuf_finish(sb);
10977 	sbuf_delete(sb);
10978 
10979 	return (rc);
10980 }
10981 
10982 static int
10983 sysctl_reset(SYSCTL_HANDLER_ARGS)
10984 {
10985 	struct adapter *sc = arg1;
10986 	u_int val;
10987 	int rc;
10988 
10989 	val = sc->num_resets;
10990 	rc = sysctl_handle_int(oidp, &val, 0, req);
10991 	if (rc != 0 || req->newptr == NULL)
10992 		return (rc);
10993 
10994 	if (val == 0) {
10995 		/* Zero out the counter that tracks reset. */
10996 		sc->num_resets = 0;
10997 		return (0);
10998 	}
10999 
11000 	if (val != 1)
11001 		return (EINVAL);	/* 0 or 1 are the only legal values */
11002 
11003 	if (hw_off_limits(sc))		/* harmless race */
11004 		return (EALREADY);
11005 
11006 	taskqueue_enqueue(reset_tq, &sc->reset_task);
11007 	return (0);
11008 }
11009 
11010 #ifdef TCP_OFFLOAD
11011 static int
11012 sysctl_tls(SYSCTL_HANDLER_ARGS)
11013 {
11014 	struct adapter *sc = arg1;
11015 	int i, j, v, rc;
11016 	struct vi_info *vi;
11017 
11018 	v = sc->tt.tls;
11019 	rc = sysctl_handle_int(oidp, &v, 0, req);
11020 	if (rc != 0 || req->newptr == NULL)
11021 		return (rc);
11022 
11023 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11024 		return (ENOTSUP);
11025 
11026 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11027 	if (rc)
11028 		return (rc);
11029 	if (hw_off_limits(sc))
11030 		rc = ENXIO;
11031 	else {
11032 		sc->tt.tls = !!v;
11033 		for_each_port(sc, i) {
11034 			for_each_vi(sc->port[i], j, vi) {
11035 				if (vi->flags & VI_INIT_DONE)
11036 					t4_update_fl_bufsize(vi->ifp);
11037 			}
11038 		}
11039 	}
11040 	end_synchronized_op(sc, 0);
11041 
11042 	return (rc);
11043 
11044 }
11045 
11046 static int
11047 sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS)
11048 {
11049 	struct adapter *sc = arg1;
11050 	int *old_ports, *new_ports;
11051 	int i, new_count, rc;
11052 
11053 	if (req->newptr == NULL && req->oldptr == NULL)
11054 		return (SYSCTL_OUT(req, NULL, imax(sc->tt.num_tls_rx_ports, 1) *
11055 		    sizeof(sc->tt.tls_rx_ports[0])));
11056 
11057 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tlsrx");
11058 	if (rc)
11059 		return (rc);
11060 
11061 	if (hw_off_limits(sc)) {
11062 		rc = ENXIO;
11063 		goto done;
11064 	}
11065 
11066 	if (sc->tt.num_tls_rx_ports == 0) {
11067 		i = -1;
11068 		rc = SYSCTL_OUT(req, &i, sizeof(i));
11069 	} else
11070 		rc = SYSCTL_OUT(req, sc->tt.tls_rx_ports,
11071 		    sc->tt.num_tls_rx_ports * sizeof(sc->tt.tls_rx_ports[0]));
11072 	if (rc == 0 && req->newptr != NULL) {
11073 		new_count = req->newlen / sizeof(new_ports[0]);
11074 		new_ports = malloc(new_count * sizeof(new_ports[0]), M_CXGBE,
11075 		    M_WAITOK);
11076 		rc = SYSCTL_IN(req, new_ports, new_count *
11077 		    sizeof(new_ports[0]));
11078 		if (rc)
11079 			goto err;
11080 
11081 		/* Allow setting to a single '-1' to clear the list. */
11082 		if (new_count == 1 && new_ports[0] == -1) {
11083 			ADAPTER_LOCK(sc);
11084 			old_ports = sc->tt.tls_rx_ports;
11085 			sc->tt.tls_rx_ports = NULL;
11086 			sc->tt.num_tls_rx_ports = 0;
11087 			ADAPTER_UNLOCK(sc);
11088 			free(old_ports, M_CXGBE);
11089 		} else {
11090 			for (i = 0; i < new_count; i++) {
11091 				if (new_ports[i] < 1 ||
11092 				    new_ports[i] > IPPORT_MAX) {
11093 					rc = EINVAL;
11094 					goto err;
11095 				}
11096 			}
11097 
11098 			ADAPTER_LOCK(sc);
11099 			old_ports = sc->tt.tls_rx_ports;
11100 			sc->tt.tls_rx_ports = new_ports;
11101 			sc->tt.num_tls_rx_ports = new_count;
11102 			ADAPTER_UNLOCK(sc);
11103 			free(old_ports, M_CXGBE);
11104 			new_ports = NULL;
11105 		}
11106 	err:
11107 		free(new_ports, M_CXGBE);
11108 	}
11109 done:
11110 	end_synchronized_op(sc, 0);
11111 	return (rc);
11112 }
11113 
11114 static int
11115 sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS)
11116 {
11117 	struct adapter *sc = arg1;
11118 	int v, rc;
11119 
11120 	v = sc->tt.tls_rx_timeout;
11121 	rc = sysctl_handle_int(oidp, &v, 0, req);
11122 	if (rc != 0 || req->newptr == NULL)
11123 		return (rc);
11124 
11125 	if (v < 0)
11126 		return (EINVAL);
11127 
11128 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11129 		return (ENOTSUP);
11130 
11131 	sc->tt.tls_rx_timeout = v;
11132 
11133 	return (0);
11134 
11135 }
11136 
11137 static void
11138 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11139 {
11140 	u_int rem = val % factor;
11141 
11142 	if (rem == 0)
11143 		snprintf(buf, len, "%u", val / factor);
11144 	else {
11145 		while (rem % 10 == 0)
11146 			rem /= 10;
11147 		snprintf(buf, len, "%u.%u", val / factor, rem);
11148 	}
11149 }
11150 
11151 static int
11152 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11153 {
11154 	struct adapter *sc = arg1;
11155 	char buf[16];
11156 	u_int res, re;
11157 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11158 
11159 	mtx_lock(&sc->reg_lock);
11160 	if (hw_off_limits(sc))
11161 		res = (u_int)-1;
11162 	else
11163 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11164 	mtx_unlock(&sc->reg_lock);
11165 	if (res == (u_int)-1)
11166 		return (ENXIO);
11167 
11168 	switch (arg2) {
11169 	case 0:
11170 		/* timer_tick */
11171 		re = G_TIMERRESOLUTION(res);
11172 		break;
11173 	case 1:
11174 		/* TCP timestamp tick */
11175 		re = G_TIMESTAMPRESOLUTION(res);
11176 		break;
11177 	case 2:
11178 		/* DACK tick */
11179 		re = G_DELAYEDACKRESOLUTION(res);
11180 		break;
11181 	default:
11182 		return (EDOOFUS);
11183 	}
11184 
11185 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11186 
11187 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11188 }
11189 
11190 static int
11191 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11192 {
11193 	struct adapter *sc = arg1;
11194 	int rc;
11195 	u_int dack_tmr, dack_re, v;
11196 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11197 
11198 	mtx_lock(&sc->reg_lock);
11199 	if (hw_off_limits(sc))
11200 		rc = ENXIO;
11201 	else {
11202 		rc = 0;
11203 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11204 		    A_TP_TIMER_RESOLUTION));
11205 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11206 	}
11207 	mtx_unlock(&sc->reg_lock);
11208 	if (rc != 0)
11209 		return (rc);
11210 
11211 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11212 
11213 	return (sysctl_handle_int(oidp, &v, 0, req));
11214 }
11215 
11216 static int
11217 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11218 {
11219 	struct adapter *sc = arg1;
11220 	int rc, reg = arg2;
11221 	u_int tre;
11222 	u_long tp_tick_us, v;
11223 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11224 
11225 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11226 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11227 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11228 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11229 
11230 	mtx_lock(&sc->reg_lock);
11231 	if (hw_off_limits(sc))
11232 		rc = ENXIO;
11233 	else {
11234 		rc = 0;
11235 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11236 		tp_tick_us = (cclk_ps << tre) / 1000000;
11237 		if (reg == A_TP_INIT_SRTT)
11238 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11239 		else
11240 			v = tp_tick_us * t4_read_reg(sc, reg);
11241 	}
11242 	mtx_unlock(&sc->reg_lock);
11243 	if (rc != 0)
11244 		return (rc);
11245 	else
11246 		return (sysctl_handle_long(oidp, &v, 0, req));
11247 }
11248 
11249 /*
11250  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11251  * passed to this function.
11252  */
11253 static int
11254 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11255 {
11256 	struct adapter *sc = arg1;
11257 	int rc, idx = arg2;
11258 	u_int v;
11259 
11260 	MPASS(idx >= 0 && idx <= 24);
11261 
11262 	mtx_lock(&sc->reg_lock);
11263 	if (hw_off_limits(sc))
11264 		rc = ENXIO;
11265 	else {
11266 		rc = 0;
11267 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11268 	}
11269 	mtx_unlock(&sc->reg_lock);
11270 	if (rc != 0)
11271 		return (rc);
11272 	else
11273 		return (sysctl_handle_int(oidp, &v, 0, req));
11274 }
11275 
11276 static int
11277 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11278 {
11279 	struct adapter *sc = arg1;
11280 	int rc, idx = arg2;
11281 	u_int shift, v, r;
11282 
11283 	MPASS(idx >= 0 && idx < 16);
11284 
11285 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11286 	shift = (idx & 3) << 3;
11287 	mtx_lock(&sc->reg_lock);
11288 	if (hw_off_limits(sc))
11289 		rc = ENXIO;
11290 	else {
11291 		rc = 0;
11292 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11293 	}
11294 	mtx_unlock(&sc->reg_lock);
11295 	if (rc != 0)
11296 		return (rc);
11297 	else
11298 		return (sysctl_handle_int(oidp, &v, 0, req));
11299 }
11300 
11301 static int
11302 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11303 {
11304 	struct vi_info *vi = arg1;
11305 	struct adapter *sc = vi->adapter;
11306 	int idx, rc, i;
11307 	struct sge_ofld_rxq *ofld_rxq;
11308 	uint8_t v;
11309 
11310 	idx = vi->ofld_tmr_idx;
11311 
11312 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11313 	if (rc != 0 || req->newptr == NULL)
11314 		return (rc);
11315 
11316 	if (idx < 0 || idx >= SGE_NTIMERS)
11317 		return (EINVAL);
11318 
11319 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11320 	    "t4otmr");
11321 	if (rc)
11322 		return (rc);
11323 
11324 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11325 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11326 #ifdef atomic_store_rel_8
11327 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11328 #else
11329 		ofld_rxq->iq.intr_params = v;
11330 #endif
11331 	}
11332 	vi->ofld_tmr_idx = idx;
11333 
11334 	end_synchronized_op(sc, LOCK_HELD);
11335 	return (0);
11336 }
11337 
11338 static int
11339 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11340 {
11341 	struct vi_info *vi = arg1;
11342 	struct adapter *sc = vi->adapter;
11343 	int idx, rc;
11344 
11345 	idx = vi->ofld_pktc_idx;
11346 
11347 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11348 	if (rc != 0 || req->newptr == NULL)
11349 		return (rc);
11350 
11351 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11352 		return (EINVAL);
11353 
11354 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11355 	    "t4opktc");
11356 	if (rc)
11357 		return (rc);
11358 
11359 	if (vi->flags & VI_INIT_DONE)
11360 		rc = EBUSY; /* cannot be changed once the queues are created */
11361 	else
11362 		vi->ofld_pktc_idx = idx;
11363 
11364 	end_synchronized_op(sc, LOCK_HELD);
11365 	return (rc);
11366 }
11367 #endif
11368 
11369 static int
11370 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11371 {
11372 	int rc;
11373 
11374 	if (cntxt->cid > M_CTXTQID)
11375 		return (EINVAL);
11376 
11377 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11378 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11379 		return (EINVAL);
11380 
11381 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11382 	if (rc)
11383 		return (rc);
11384 
11385 	if (hw_off_limits(sc)) {
11386 		rc = ENXIO;
11387 		goto done;
11388 	}
11389 
11390 	if (sc->flags & FW_OK) {
11391 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11392 		    &cntxt->data[0]);
11393 		if (rc == 0)
11394 			goto done;
11395 	}
11396 
11397 	/*
11398 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11399 	 * the backdoor.
11400 	 */
11401 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11402 done:
11403 	end_synchronized_op(sc, 0);
11404 	return (rc);
11405 }
11406 
11407 static int
11408 load_fw(struct adapter *sc, struct t4_data *fw)
11409 {
11410 	int rc;
11411 	uint8_t *fw_data;
11412 
11413 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11414 	if (rc)
11415 		return (rc);
11416 
11417 	if (hw_off_limits(sc)) {
11418 		rc = ENXIO;
11419 		goto done;
11420 	}
11421 
11422 	/*
11423 	 * The firmware, with the sole exception of the memory parity error
11424 	 * handler, runs from memory and not flash.  It is almost always safe to
11425 	 * install a new firmware on a running system.  Just set bit 1 in
11426 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11427 	 */
11428 	if (sc->flags & FULL_INIT_DONE &&
11429 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11430 		rc = EBUSY;
11431 		goto done;
11432 	}
11433 
11434 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11435 
11436 	rc = copyin(fw->data, fw_data, fw->len);
11437 	if (rc == 0)
11438 		rc = -t4_load_fw(sc, fw_data, fw->len);
11439 
11440 	free(fw_data, M_CXGBE);
11441 done:
11442 	end_synchronized_op(sc, 0);
11443 	return (rc);
11444 }
11445 
11446 static int
11447 load_cfg(struct adapter *sc, struct t4_data *cfg)
11448 {
11449 	int rc;
11450 	uint8_t *cfg_data = NULL;
11451 
11452 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11453 	if (rc)
11454 		return (rc);
11455 
11456 	if (hw_off_limits(sc)) {
11457 		rc = ENXIO;
11458 		goto done;
11459 	}
11460 
11461 	if (cfg->len == 0) {
11462 		/* clear */
11463 		rc = -t4_load_cfg(sc, NULL, 0);
11464 		goto done;
11465 	}
11466 
11467 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11468 
11469 	rc = copyin(cfg->data, cfg_data, cfg->len);
11470 	if (rc == 0)
11471 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11472 
11473 	free(cfg_data, M_CXGBE);
11474 done:
11475 	end_synchronized_op(sc, 0);
11476 	return (rc);
11477 }
11478 
11479 static int
11480 load_boot(struct adapter *sc, struct t4_bootrom *br)
11481 {
11482 	int rc;
11483 	uint8_t *br_data = NULL;
11484 	u_int offset;
11485 
11486 	if (br->len > 1024 * 1024)
11487 		return (EFBIG);
11488 
11489 	if (br->pf_offset == 0) {
11490 		/* pfidx */
11491 		if (br->pfidx_addr > 7)
11492 			return (EINVAL);
11493 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11494 		    A_PCIE_PF_EXPROM_OFST)));
11495 	} else if (br->pf_offset == 1) {
11496 		/* offset */
11497 		offset = G_OFFSET(br->pfidx_addr);
11498 	} else {
11499 		return (EINVAL);
11500 	}
11501 
11502 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11503 	if (rc)
11504 		return (rc);
11505 
11506 	if (hw_off_limits(sc)) {
11507 		rc = ENXIO;
11508 		goto done;
11509 	}
11510 
11511 	if (br->len == 0) {
11512 		/* clear */
11513 		rc = -t4_load_boot(sc, NULL, offset, 0);
11514 		goto done;
11515 	}
11516 
11517 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11518 
11519 	rc = copyin(br->data, br_data, br->len);
11520 	if (rc == 0)
11521 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11522 
11523 	free(br_data, M_CXGBE);
11524 done:
11525 	end_synchronized_op(sc, 0);
11526 	return (rc);
11527 }
11528 
11529 static int
11530 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11531 {
11532 	int rc;
11533 	uint8_t *bc_data = NULL;
11534 
11535 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11536 	if (rc)
11537 		return (rc);
11538 
11539 	if (hw_off_limits(sc)) {
11540 		rc = ENXIO;
11541 		goto done;
11542 	}
11543 
11544 	if (bc->len == 0) {
11545 		/* clear */
11546 		rc = -t4_load_bootcfg(sc, NULL, 0);
11547 		goto done;
11548 	}
11549 
11550 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11551 
11552 	rc = copyin(bc->data, bc_data, bc->len);
11553 	if (rc == 0)
11554 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11555 
11556 	free(bc_data, M_CXGBE);
11557 done:
11558 	end_synchronized_op(sc, 0);
11559 	return (rc);
11560 }
11561 
11562 static int
11563 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11564 {
11565 	int rc;
11566 	struct cudbg_init *cudbg;
11567 	void *handle, *buf;
11568 
11569 	/* buf is large, don't block if no memory is available */
11570 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11571 	if (buf == NULL)
11572 		return (ENOMEM);
11573 
11574 	handle = cudbg_alloc_handle();
11575 	if (handle == NULL) {
11576 		rc = ENOMEM;
11577 		goto done;
11578 	}
11579 
11580 	cudbg = cudbg_get_init(handle);
11581 	cudbg->adap = sc;
11582 	cudbg->print = (cudbg_print_cb)printf;
11583 
11584 #ifndef notyet
11585 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11586 	    __func__, dump->wr_flash, dump->len, dump->data);
11587 #endif
11588 
11589 	if (dump->wr_flash)
11590 		cudbg->use_flash = 1;
11591 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11592 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11593 
11594 	rc = cudbg_collect(handle, buf, &dump->len);
11595 	if (rc != 0)
11596 		goto done;
11597 
11598 	rc = copyout(buf, dump->data, dump->len);
11599 done:
11600 	cudbg_free_handle(handle);
11601 	free(buf, M_CXGBE);
11602 	return (rc);
11603 }
11604 
11605 static void
11606 free_offload_policy(struct t4_offload_policy *op)
11607 {
11608 	struct offload_rule *r;
11609 	int i;
11610 
11611 	if (op == NULL)
11612 		return;
11613 
11614 	r = &op->rule[0];
11615 	for (i = 0; i < op->nrules; i++, r++) {
11616 		free(r->bpf_prog.bf_insns, M_CXGBE);
11617 	}
11618 	free(op->rule, M_CXGBE);
11619 	free(op, M_CXGBE);
11620 }
11621 
11622 static int
11623 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11624 {
11625 	int i, rc, len;
11626 	struct t4_offload_policy *op, *old;
11627 	struct bpf_program *bf;
11628 	const struct offload_settings *s;
11629 	struct offload_rule *r;
11630 	void *u;
11631 
11632 	if (!is_offload(sc))
11633 		return (ENODEV);
11634 
11635 	if (uop->nrules == 0) {
11636 		/* Delete installed policies. */
11637 		op = NULL;
11638 		goto set_policy;
11639 	} else if (uop->nrules > 256) { /* arbitrary */
11640 		return (E2BIG);
11641 	}
11642 
11643 	/* Copy userspace offload policy to kernel */
11644 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11645 	op->nrules = uop->nrules;
11646 	len = op->nrules * sizeof(struct offload_rule);
11647 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11648 	rc = copyin(uop->rule, op->rule, len);
11649 	if (rc) {
11650 		free(op->rule, M_CXGBE);
11651 		free(op, M_CXGBE);
11652 		return (rc);
11653 	}
11654 
11655 	r = &op->rule[0];
11656 	for (i = 0; i < op->nrules; i++, r++) {
11657 
11658 		/* Validate open_type */
11659 		if (r->open_type != OPEN_TYPE_LISTEN &&
11660 		    r->open_type != OPEN_TYPE_ACTIVE &&
11661 		    r->open_type != OPEN_TYPE_PASSIVE &&
11662 		    r->open_type != OPEN_TYPE_DONTCARE) {
11663 error:
11664 			/*
11665 			 * Rules 0 to i have malloc'd filters that need to be
11666 			 * freed.  Rules i+1 to nrules have userspace pointers
11667 			 * and should be left alone.
11668 			 */
11669 			op->nrules = i;
11670 			free_offload_policy(op);
11671 			return (rc);
11672 		}
11673 
11674 		/* Validate settings */
11675 		s = &r->settings;
11676 		if ((s->offload != 0 && s->offload != 1) ||
11677 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11678 		    s->sched_class < -1 ||
11679 		    s->sched_class >= sc->chip_params->nsched_cls) {
11680 			rc = EINVAL;
11681 			goto error;
11682 		}
11683 
11684 		bf = &r->bpf_prog;
11685 		u = bf->bf_insns;	/* userspace ptr */
11686 		bf->bf_insns = NULL;
11687 		if (bf->bf_len == 0) {
11688 			/* legal, matches everything */
11689 			continue;
11690 		}
11691 		len = bf->bf_len * sizeof(*bf->bf_insns);
11692 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11693 		rc = copyin(u, bf->bf_insns, len);
11694 		if (rc != 0)
11695 			goto error;
11696 
11697 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11698 			rc = EINVAL;
11699 			goto error;
11700 		}
11701 	}
11702 set_policy:
11703 	rw_wlock(&sc->policy_lock);
11704 	old = sc->policy;
11705 	sc->policy = op;
11706 	rw_wunlock(&sc->policy_lock);
11707 	free_offload_policy(old);
11708 
11709 	return (0);
11710 }
11711 
11712 #define MAX_READ_BUF_SIZE (128 * 1024)
11713 static int
11714 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11715 {
11716 	uint32_t addr, remaining, n;
11717 	uint32_t *buf;
11718 	int rc;
11719 	uint8_t *dst;
11720 
11721 	mtx_lock(&sc->reg_lock);
11722 	if (hw_off_limits(sc))
11723 		rc = ENXIO;
11724 	else
11725 		rc = validate_mem_range(sc, mr->addr, mr->len);
11726 	mtx_unlock(&sc->reg_lock);
11727 	if (rc != 0)
11728 		return (rc);
11729 
11730 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11731 	addr = mr->addr;
11732 	remaining = mr->len;
11733 	dst = (void *)mr->data;
11734 
11735 	while (remaining) {
11736 		n = min(remaining, MAX_READ_BUF_SIZE);
11737 		mtx_lock(&sc->reg_lock);
11738 		if (hw_off_limits(sc))
11739 			rc = ENXIO;
11740 		else
11741 			read_via_memwin(sc, 2, addr, buf, n);
11742 		mtx_unlock(&sc->reg_lock);
11743 		if (rc != 0)
11744 			break;
11745 
11746 		rc = copyout(buf, dst, n);
11747 		if (rc != 0)
11748 			break;
11749 
11750 		dst += n;
11751 		remaining -= n;
11752 		addr += n;
11753 	}
11754 
11755 	free(buf, M_CXGBE);
11756 	return (rc);
11757 }
11758 #undef MAX_READ_BUF_SIZE
11759 
11760 static int
11761 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11762 {
11763 	int rc;
11764 
11765 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11766 		return (EINVAL);
11767 
11768 	if (i2cd->len > sizeof(i2cd->data))
11769 		return (EFBIG);
11770 
11771 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11772 	if (rc)
11773 		return (rc);
11774 	if (hw_off_limits(sc))
11775 		rc = ENXIO;
11776 	else
11777 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11778 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11779 	end_synchronized_op(sc, 0);
11780 
11781 	return (rc);
11782 }
11783 
11784 static int
11785 clear_stats(struct adapter *sc, u_int port_id)
11786 {
11787 	int i, v, chan_map;
11788 	struct port_info *pi;
11789 	struct vi_info *vi;
11790 	struct sge_rxq *rxq;
11791 	struct sge_txq *txq;
11792 	struct sge_wrq *wrq;
11793 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11794 	struct sge_ofld_txq *ofld_txq;
11795 #endif
11796 #ifdef TCP_OFFLOAD
11797 	struct sge_ofld_rxq *ofld_rxq;
11798 #endif
11799 
11800 	if (port_id >= sc->params.nports)
11801 		return (EINVAL);
11802 	pi = sc->port[port_id];
11803 	if (pi == NULL)
11804 		return (EIO);
11805 
11806 	mtx_lock(&sc->reg_lock);
11807 	if (!hw_off_limits(sc)) {
11808 		/* MAC stats */
11809 		t4_clr_port_stats(sc, pi->tx_chan);
11810 		if (is_t6(sc)) {
11811 			if (pi->fcs_reg != -1)
11812 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11813 			else
11814 				pi->stats.rx_fcs_err = 0;
11815 		}
11816 		for_each_vi(pi, v, vi) {
11817 			if (vi->flags & VI_INIT_DONE)
11818 				t4_clr_vi_stats(sc, vi->vin);
11819 		}
11820 		chan_map = pi->rx_e_chan_map;
11821 		v = 0;	/* reuse */
11822 		while (chan_map) {
11823 			i = ffs(chan_map) - 1;
11824 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11825 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11826 			chan_map &= ~(1 << i);
11827 		}
11828 	}
11829 	mtx_unlock(&sc->reg_lock);
11830 	pi->tx_parse_error = 0;
11831 	pi->tnl_cong_drops = 0;
11832 
11833 	/*
11834 	 * Since this command accepts a port, clear stats for
11835 	 * all VIs on this port.
11836 	 */
11837 	for_each_vi(pi, v, vi) {
11838 		if (vi->flags & VI_INIT_DONE) {
11839 
11840 			for_each_rxq(vi, i, rxq) {
11841 #if defined(INET) || defined(INET6)
11842 				rxq->lro.lro_queued = 0;
11843 				rxq->lro.lro_flushed = 0;
11844 #endif
11845 				rxq->rxcsum = 0;
11846 				rxq->vlan_extraction = 0;
11847 				rxq->vxlan_rxcsum = 0;
11848 
11849 				rxq->fl.cl_allocated = 0;
11850 				rxq->fl.cl_recycled = 0;
11851 				rxq->fl.cl_fast_recycled = 0;
11852 			}
11853 
11854 			for_each_txq(vi, i, txq) {
11855 				txq->txcsum = 0;
11856 				txq->tso_wrs = 0;
11857 				txq->vlan_insertion = 0;
11858 				txq->imm_wrs = 0;
11859 				txq->sgl_wrs = 0;
11860 				txq->txpkt_wrs = 0;
11861 				txq->txpkts0_wrs = 0;
11862 				txq->txpkts1_wrs = 0;
11863 				txq->txpkts0_pkts = 0;
11864 				txq->txpkts1_pkts = 0;
11865 				txq->txpkts_flush = 0;
11866 				txq->raw_wrs = 0;
11867 				txq->vxlan_tso_wrs = 0;
11868 				txq->vxlan_txcsum = 0;
11869 				txq->kern_tls_records = 0;
11870 				txq->kern_tls_short = 0;
11871 				txq->kern_tls_partial = 0;
11872 				txq->kern_tls_full = 0;
11873 				txq->kern_tls_octets = 0;
11874 				txq->kern_tls_waste = 0;
11875 				txq->kern_tls_options = 0;
11876 				txq->kern_tls_header = 0;
11877 				txq->kern_tls_fin = 0;
11878 				txq->kern_tls_fin_short = 0;
11879 				txq->kern_tls_cbc = 0;
11880 				txq->kern_tls_gcm = 0;
11881 				mp_ring_reset_stats(txq->r);
11882 			}
11883 
11884 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11885 			for_each_ofld_txq(vi, i, ofld_txq) {
11886 				ofld_txq->wrq.tx_wrs_direct = 0;
11887 				ofld_txq->wrq.tx_wrs_copied = 0;
11888 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
11889 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
11890 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
11891 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
11892 			}
11893 #endif
11894 #ifdef TCP_OFFLOAD
11895 			for_each_ofld_rxq(vi, i, ofld_rxq) {
11896 				ofld_rxq->fl.cl_allocated = 0;
11897 				ofld_rxq->fl.cl_recycled = 0;
11898 				ofld_rxq->fl.cl_fast_recycled = 0;
11899 				counter_u64_zero(
11900 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
11901 				counter_u64_zero(
11902 				    ofld_rxq->rx_iscsi_ddp_setup_error);
11903 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
11904 				ofld_rxq->rx_iscsi_ddp_octets = 0;
11905 				ofld_rxq->rx_iscsi_fl_pdus = 0;
11906 				ofld_rxq->rx_iscsi_fl_octets = 0;
11907 				ofld_rxq->rx_toe_tls_records = 0;
11908 				ofld_rxq->rx_toe_tls_octets = 0;
11909 			}
11910 #endif
11911 
11912 			if (IS_MAIN_VI(vi)) {
11913 				wrq = &sc->sge.ctrlq[pi->port_id];
11914 				wrq->tx_wrs_direct = 0;
11915 				wrq->tx_wrs_copied = 0;
11916 			}
11917 		}
11918 	}
11919 
11920 	return (0);
11921 }
11922 
11923 static int
11924 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
11925 {
11926 #ifdef INET6
11927 	struct in6_addr in6;
11928 
11929 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
11930 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
11931 		return (0);
11932 	else
11933 		return (EIO);
11934 #else
11935 	return (ENOTSUP);
11936 #endif
11937 }
11938 
11939 static int
11940 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
11941 {
11942 #ifdef INET6
11943 	struct in6_addr in6;
11944 
11945 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
11946 	return (t4_release_clip_addr(sc, &in6));
11947 #else
11948 	return (ENOTSUP);
11949 #endif
11950 }
11951 
11952 int
11953 t4_os_find_pci_capability(struct adapter *sc, int cap)
11954 {
11955 	int i;
11956 
11957 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
11958 }
11959 
11960 int
11961 t4_os_pci_save_state(struct adapter *sc)
11962 {
11963 	device_t dev;
11964 	struct pci_devinfo *dinfo;
11965 
11966 	dev = sc->dev;
11967 	dinfo = device_get_ivars(dev);
11968 
11969 	pci_cfg_save(dev, dinfo, 0);
11970 	return (0);
11971 }
11972 
11973 int
11974 t4_os_pci_restore_state(struct adapter *sc)
11975 {
11976 	device_t dev;
11977 	struct pci_devinfo *dinfo;
11978 
11979 	dev = sc->dev;
11980 	dinfo = device_get_ivars(dev);
11981 
11982 	pci_cfg_restore(dev, dinfo);
11983 	return (0);
11984 }
11985 
11986 void
11987 t4_os_portmod_changed(struct port_info *pi)
11988 {
11989 	struct adapter *sc = pi->adapter;
11990 	struct vi_info *vi;
11991 	struct ifnet *ifp;
11992 	static const char *mod_str[] = {
11993 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
11994 	};
11995 
11996 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
11997 	    ("%s: port_type %u", __func__, pi->port_type));
11998 
11999 	vi = &pi->vi[0];
12000 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12001 		PORT_LOCK(pi);
12002 		build_medialist(pi);
12003 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12004 			fixup_link_config(pi);
12005 			apply_link_config(pi);
12006 		}
12007 		PORT_UNLOCK(pi);
12008 		end_synchronized_op(sc, LOCK_HELD);
12009 	}
12010 
12011 	ifp = vi->ifp;
12012 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12013 		if_printf(ifp, "transceiver unplugged.\n");
12014 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12015 		if_printf(ifp, "unknown transceiver inserted.\n");
12016 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12017 		if_printf(ifp, "unsupported transceiver inserted.\n");
12018 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12019 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12020 		    port_top_speed(pi), mod_str[pi->mod_type]);
12021 	} else {
12022 		if_printf(ifp, "transceiver (type %d) inserted.\n",
12023 		    pi->mod_type);
12024 	}
12025 }
12026 
12027 void
12028 t4_os_link_changed(struct port_info *pi)
12029 {
12030 	struct vi_info *vi;
12031 	struct ifnet *ifp;
12032 	struct link_config *lc = &pi->link_cfg;
12033 	struct adapter *sc = pi->adapter;
12034 	int v;
12035 
12036 	PORT_LOCK_ASSERT_OWNED(pi);
12037 
12038 	if (is_t6(sc)) {
12039 		if (lc->link_ok) {
12040 			if (lc->speed > 25000 ||
12041 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12042 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12043 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12044 			} else {
12045 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12046 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12047 			}
12048 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12049 			pi->stats.rx_fcs_err = 0;
12050 		} else {
12051 			pi->fcs_reg = -1;
12052 		}
12053 	} else {
12054 		MPASS(pi->fcs_reg != -1);
12055 		MPASS(pi->fcs_base == 0);
12056 	}
12057 
12058 	for_each_vi(pi, v, vi) {
12059 		ifp = vi->ifp;
12060 		if (ifp == NULL)
12061 			continue;
12062 
12063 		if (lc->link_ok) {
12064 			ifp->if_baudrate = IF_Mbps(lc->speed);
12065 			if_link_state_change(ifp, LINK_STATE_UP);
12066 		} else {
12067 			if_link_state_change(ifp, LINK_STATE_DOWN);
12068 		}
12069 	}
12070 }
12071 
12072 void
12073 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12074 {
12075 	struct adapter *sc;
12076 
12077 	sx_slock(&t4_list_lock);
12078 	SLIST_FOREACH(sc, &t4_list, link) {
12079 		/*
12080 		 * func should not make any assumptions about what state sc is
12081 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12082 		 */
12083 		func(sc, arg);
12084 	}
12085 	sx_sunlock(&t4_list_lock);
12086 }
12087 
12088 static int
12089 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12090     struct thread *td)
12091 {
12092 	int rc;
12093 	struct adapter *sc = dev->si_drv1;
12094 
12095 	rc = priv_check(td, PRIV_DRIVER);
12096 	if (rc != 0)
12097 		return (rc);
12098 
12099 	switch (cmd) {
12100 	case CHELSIO_T4_GETREG: {
12101 		struct t4_reg *edata = (struct t4_reg *)data;
12102 
12103 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12104 			return (EFAULT);
12105 
12106 		mtx_lock(&sc->reg_lock);
12107 		if (hw_off_limits(sc))
12108 			rc = ENXIO;
12109 		else if (edata->size == 4)
12110 			edata->val = t4_read_reg(sc, edata->addr);
12111 		else if (edata->size == 8)
12112 			edata->val = t4_read_reg64(sc, edata->addr);
12113 		else
12114 			rc = EINVAL;
12115 		mtx_unlock(&sc->reg_lock);
12116 
12117 		break;
12118 	}
12119 	case CHELSIO_T4_SETREG: {
12120 		struct t4_reg *edata = (struct t4_reg *)data;
12121 
12122 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12123 			return (EFAULT);
12124 
12125 		mtx_lock(&sc->reg_lock);
12126 		if (hw_off_limits(sc))
12127 			rc = ENXIO;
12128 		else if (edata->size == 4) {
12129 			if (edata->val & 0xffffffff00000000)
12130 				rc = EINVAL;
12131 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12132 		} else if (edata->size == 8)
12133 			t4_write_reg64(sc, edata->addr, edata->val);
12134 		else
12135 			rc = EINVAL;
12136 		mtx_unlock(&sc->reg_lock);
12137 
12138 		break;
12139 	}
12140 	case CHELSIO_T4_REGDUMP: {
12141 		struct t4_regdump *regs = (struct t4_regdump *)data;
12142 		int reglen = t4_get_regs_len(sc);
12143 		uint8_t *buf;
12144 
12145 		if (regs->len < reglen) {
12146 			regs->len = reglen; /* hint to the caller */
12147 			return (ENOBUFS);
12148 		}
12149 
12150 		regs->len = reglen;
12151 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12152 		mtx_lock(&sc->reg_lock);
12153 		if (hw_off_limits(sc))
12154 			rc = ENXIO;
12155 		else
12156 			get_regs(sc, regs, buf);
12157 		mtx_unlock(&sc->reg_lock);
12158 		if (rc == 0)
12159 			rc = copyout(buf, regs->data, reglen);
12160 		free(buf, M_CXGBE);
12161 		break;
12162 	}
12163 	case CHELSIO_T4_GET_FILTER_MODE:
12164 		rc = get_filter_mode(sc, (uint32_t *)data);
12165 		break;
12166 	case CHELSIO_T4_SET_FILTER_MODE:
12167 		rc = set_filter_mode(sc, *(uint32_t *)data);
12168 		break;
12169 	case CHELSIO_T4_SET_FILTER_MASK:
12170 		rc = set_filter_mask(sc, *(uint32_t *)data);
12171 		break;
12172 	case CHELSIO_T4_GET_FILTER:
12173 		rc = get_filter(sc, (struct t4_filter *)data);
12174 		break;
12175 	case CHELSIO_T4_SET_FILTER:
12176 		rc = set_filter(sc, (struct t4_filter *)data);
12177 		break;
12178 	case CHELSIO_T4_DEL_FILTER:
12179 		rc = del_filter(sc, (struct t4_filter *)data);
12180 		break;
12181 	case CHELSIO_T4_GET_SGE_CONTEXT:
12182 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12183 		break;
12184 	case CHELSIO_T4_LOAD_FW:
12185 		rc = load_fw(sc, (struct t4_data *)data);
12186 		break;
12187 	case CHELSIO_T4_GET_MEM:
12188 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12189 		break;
12190 	case CHELSIO_T4_GET_I2C:
12191 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12192 		break;
12193 	case CHELSIO_T4_CLEAR_STATS:
12194 		rc = clear_stats(sc, *(uint32_t *)data);
12195 		break;
12196 	case CHELSIO_T4_SCHED_CLASS:
12197 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12198 		break;
12199 	case CHELSIO_T4_SCHED_QUEUE:
12200 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12201 		break;
12202 	case CHELSIO_T4_GET_TRACER:
12203 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12204 		break;
12205 	case CHELSIO_T4_SET_TRACER:
12206 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12207 		break;
12208 	case CHELSIO_T4_LOAD_CFG:
12209 		rc = load_cfg(sc, (struct t4_data *)data);
12210 		break;
12211 	case CHELSIO_T4_LOAD_BOOT:
12212 		rc = load_boot(sc, (struct t4_bootrom *)data);
12213 		break;
12214 	case CHELSIO_T4_LOAD_BOOTCFG:
12215 		rc = load_bootcfg(sc, (struct t4_data *)data);
12216 		break;
12217 	case CHELSIO_T4_CUDBG_DUMP:
12218 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12219 		break;
12220 	case CHELSIO_T4_SET_OFLD_POLICY:
12221 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12222 		break;
12223 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12224 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12225 		break;
12226 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12227 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12228 		break;
12229 	default:
12230 		rc = ENOTTY;
12231 	}
12232 
12233 	return (rc);
12234 }
12235 
12236 #ifdef TCP_OFFLOAD
12237 static int
12238 toe_capability(struct vi_info *vi, bool enable)
12239 {
12240 	int rc;
12241 	struct port_info *pi = vi->pi;
12242 	struct adapter *sc = pi->adapter;
12243 
12244 	ASSERT_SYNCHRONIZED_OP(sc);
12245 
12246 	if (!is_offload(sc))
12247 		return (ENODEV);
12248 	if (hw_off_limits(sc))
12249 		return (ENXIO);
12250 
12251 	if (enable) {
12252 #ifdef KERN_TLS
12253 		if (sc->flags & KERN_TLS_ON) {
12254 			int i, j, n;
12255 			struct port_info *p;
12256 			struct vi_info *v;
12257 
12258 			/*
12259 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12260 			 * on any ifnet.
12261 			 */
12262 			n = 0;
12263 			for_each_port(sc, i) {
12264 				p = sc->port[i];
12265 				for_each_vi(p, j, v) {
12266 					if (v->ifp->if_capenable & IFCAP_TXTLS) {
12267 						CH_WARN(sc,
12268 						    "%s has NIC TLS enabled.\n",
12269 						    device_get_nameunit(v->dev));
12270 						n++;
12271 					}
12272 				}
12273 			}
12274 			if (n > 0) {
12275 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12276 				    "associated with this adapter before "
12277 				    "trying to enable TOE.\n");
12278 				return (EAGAIN);
12279 			}
12280 			rc = t4_config_kern_tls(sc, false);
12281 			if (rc)
12282 				return (rc);
12283 		}
12284 #endif
12285 		if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
12286 			/* TOE is already enabled. */
12287 			return (0);
12288 		}
12289 
12290 		/*
12291 		 * We need the port's queues around so that we're able to send
12292 		 * and receive CPLs to/from the TOE even if the ifnet for this
12293 		 * port has never been UP'd administratively.
12294 		 */
12295 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12296 			return (rc);
12297 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12298 		    ((rc = vi_init(&pi->vi[0])) != 0))
12299 			return (rc);
12300 
12301 		if (isset(&sc->offload_map, pi->port_id)) {
12302 			/* TOE is enabled on another VI of this port. */
12303 			pi->uld_vis++;
12304 			return (0);
12305 		}
12306 
12307 		if (!uld_active(sc, ULD_TOM)) {
12308 			rc = t4_activate_uld(sc, ULD_TOM);
12309 			if (rc == EAGAIN) {
12310 				log(LOG_WARNING,
12311 				    "You must kldload t4_tom.ko before trying "
12312 				    "to enable TOE on a cxgbe interface.\n");
12313 			}
12314 			if (rc != 0)
12315 				return (rc);
12316 			KASSERT(sc->tom_softc != NULL,
12317 			    ("%s: TOM activated but softc NULL", __func__));
12318 			KASSERT(uld_active(sc, ULD_TOM),
12319 			    ("%s: TOM activated but flag not set", __func__));
12320 		}
12321 
12322 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12323 		if (!uld_active(sc, ULD_IWARP))
12324 			(void) t4_activate_uld(sc, ULD_IWARP);
12325 		if (!uld_active(sc, ULD_ISCSI))
12326 			(void) t4_activate_uld(sc, ULD_ISCSI);
12327 
12328 		pi->uld_vis++;
12329 		setbit(&sc->offload_map, pi->port_id);
12330 	} else {
12331 		pi->uld_vis--;
12332 
12333 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12334 			return (0);
12335 
12336 		KASSERT(uld_active(sc, ULD_TOM),
12337 		    ("%s: TOM never initialized?", __func__));
12338 		clrbit(&sc->offload_map, pi->port_id);
12339 	}
12340 
12341 	return (0);
12342 }
12343 
12344 /*
12345  * Add an upper layer driver to the global list.
12346  */
12347 int
12348 t4_register_uld(struct uld_info *ui)
12349 {
12350 	int rc = 0;
12351 	struct uld_info *u;
12352 
12353 	sx_xlock(&t4_uld_list_lock);
12354 	SLIST_FOREACH(u, &t4_uld_list, link) {
12355 	    if (u->uld_id == ui->uld_id) {
12356 		    rc = EEXIST;
12357 		    goto done;
12358 	    }
12359 	}
12360 
12361 	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
12362 	ui->refcount = 0;
12363 done:
12364 	sx_xunlock(&t4_uld_list_lock);
12365 	return (rc);
12366 }
12367 
12368 int
12369 t4_unregister_uld(struct uld_info *ui)
12370 {
12371 	int rc = EINVAL;
12372 	struct uld_info *u;
12373 
12374 	sx_xlock(&t4_uld_list_lock);
12375 
12376 	SLIST_FOREACH(u, &t4_uld_list, link) {
12377 	    if (u == ui) {
12378 		    if (ui->refcount > 0) {
12379 			    rc = EBUSY;
12380 			    goto done;
12381 		    }
12382 
12383 		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
12384 		    rc = 0;
12385 		    goto done;
12386 	    }
12387 	}
12388 done:
12389 	sx_xunlock(&t4_uld_list_lock);
12390 	return (rc);
12391 }
12392 
12393 int
12394 t4_activate_uld(struct adapter *sc, int id)
12395 {
12396 	int rc;
12397 	struct uld_info *ui;
12398 
12399 	ASSERT_SYNCHRONIZED_OP(sc);
12400 
12401 	if (id < 0 || id > ULD_MAX)
12402 		return (EINVAL);
12403 	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
12404 
12405 	sx_slock(&t4_uld_list_lock);
12406 
12407 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12408 		if (ui->uld_id == id) {
12409 			if (!(sc->flags & FULL_INIT_DONE)) {
12410 				rc = adapter_init(sc);
12411 				if (rc != 0)
12412 					break;
12413 			}
12414 
12415 			rc = ui->activate(sc);
12416 			if (rc == 0) {
12417 				setbit(&sc->active_ulds, id);
12418 				ui->refcount++;
12419 			}
12420 			break;
12421 		}
12422 	}
12423 
12424 	sx_sunlock(&t4_uld_list_lock);
12425 
12426 	return (rc);
12427 }
12428 
12429 int
12430 t4_deactivate_uld(struct adapter *sc, int id)
12431 {
12432 	int rc;
12433 	struct uld_info *ui;
12434 
12435 	ASSERT_SYNCHRONIZED_OP(sc);
12436 
12437 	if (id < 0 || id > ULD_MAX)
12438 		return (EINVAL);
12439 	rc = ENXIO;
12440 
12441 	sx_slock(&t4_uld_list_lock);
12442 
12443 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12444 		if (ui->uld_id == id) {
12445 			rc = ui->deactivate(sc);
12446 			if (rc == 0) {
12447 				clrbit(&sc->active_ulds, id);
12448 				ui->refcount--;
12449 			}
12450 			break;
12451 		}
12452 	}
12453 
12454 	sx_sunlock(&t4_uld_list_lock);
12455 
12456 	return (rc);
12457 }
12458 
12459 static void
12460 t4_async_event(void *arg, int n)
12461 {
12462 	struct uld_info *ui;
12463 	struct adapter *sc = (struct adapter *)arg;
12464 
12465 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
12466 		return;
12467 	sx_slock(&t4_uld_list_lock);
12468 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12469 		if (ui->uld_id == ULD_IWARP) {
12470 			ui->async_event(sc);
12471 			break;
12472 		}
12473 	}
12474 	sx_sunlock(&t4_uld_list_lock);
12475 	end_synchronized_op(sc, 0);
12476 }
12477 
12478 int
12479 uld_active(struct adapter *sc, int uld_id)
12480 {
12481 
12482 	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
12483 
12484 	return (isset(&sc->active_ulds, uld_id));
12485 }
12486 #endif
12487 
12488 #ifdef KERN_TLS
12489 static int
12490 ktls_capability(struct adapter *sc, bool enable)
12491 {
12492 	ASSERT_SYNCHRONIZED_OP(sc);
12493 
12494 	if (!is_ktls(sc))
12495 		return (ENODEV);
12496 	if (hw_off_limits(sc))
12497 		return (ENXIO);
12498 
12499 	if (enable) {
12500 		if (sc->flags & KERN_TLS_ON)
12501 			return (0);	/* already on */
12502 		if (sc->offload_map != 0) {
12503 			CH_WARN(sc,
12504 			    "Disable TOE on all interfaces associated with "
12505 			    "this adapter before trying to enable NIC TLS.\n");
12506 			return (EAGAIN);
12507 		}
12508 		return (t4_config_kern_tls(sc, true));
12509 	} else {
12510 		/*
12511 		 * Nothing to do for disable.  If TOE is enabled sometime later
12512 		 * then toe_capability will reconfigure the hardware.
12513 		 */
12514 		return (0);
12515 	}
12516 }
12517 #endif
12518 
12519 /*
12520  * t  = ptr to tunable.
12521  * nc = number of CPUs.
12522  * c  = compiled in default for that tunable.
12523  */
12524 static void
12525 calculate_nqueues(int *t, int nc, const int c)
12526 {
12527 	int nq;
12528 
12529 	if (*t > 0)
12530 		return;
12531 	nq = *t < 0 ? -*t : c;
12532 	*t = min(nc, nq);
12533 }
12534 
12535 /*
12536  * Come up with reasonable defaults for some of the tunables, provided they're
12537  * not set by the user (in which case we'll use the values as is).
12538  */
12539 static void
12540 tweak_tunables(void)
12541 {
12542 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12543 
12544 	if (t4_ntxq < 1) {
12545 #ifdef RSS
12546 		t4_ntxq = rss_getnumbuckets();
12547 #else
12548 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12549 #endif
12550 	}
12551 
12552 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12553 
12554 	if (t4_nrxq < 1) {
12555 #ifdef RSS
12556 		t4_nrxq = rss_getnumbuckets();
12557 #else
12558 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12559 #endif
12560 	}
12561 
12562 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12563 
12564 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12565 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12566 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12567 #endif
12568 #ifdef TCP_OFFLOAD
12569 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12570 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12571 #endif
12572 
12573 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12574 	if (t4_toecaps_allowed == -1)
12575 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12576 #else
12577 	if (t4_toecaps_allowed == -1)
12578 		t4_toecaps_allowed = 0;
12579 #endif
12580 
12581 #ifdef TCP_OFFLOAD
12582 	if (t4_rdmacaps_allowed == -1) {
12583 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12584 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12585 	}
12586 
12587 	if (t4_iscsicaps_allowed == -1) {
12588 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12589 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12590 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12591 	}
12592 
12593 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12594 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12595 
12596 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12597 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12598 
12599 	if (t4_toe_tls_rx_timeout < 0)
12600 		t4_toe_tls_rx_timeout = 0;
12601 #else
12602 	if (t4_rdmacaps_allowed == -1)
12603 		t4_rdmacaps_allowed = 0;
12604 
12605 	if (t4_iscsicaps_allowed == -1)
12606 		t4_iscsicaps_allowed = 0;
12607 #endif
12608 
12609 #ifdef DEV_NETMAP
12610 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12611 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12612 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12613 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12614 #endif
12615 
12616 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12617 		t4_tmr_idx = TMR_IDX;
12618 
12619 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12620 		t4_pktc_idx = PKTC_IDX;
12621 
12622 	if (t4_qsize_txq < 128)
12623 		t4_qsize_txq = 128;
12624 
12625 	if (t4_qsize_rxq < 128)
12626 		t4_qsize_rxq = 128;
12627 	while (t4_qsize_rxq & 7)
12628 		t4_qsize_rxq++;
12629 
12630 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12631 
12632 	/*
12633 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12634 	 * VI for the port.  The rest are additional virtual interfaces on the
12635 	 * same physical port.  Note that the main VI does not have native
12636 	 * netmap support but the extra VIs do.
12637 	 *
12638 	 * Limit the number of VIs per port to the number of available
12639 	 * MAC addresses per port.
12640 	 */
12641 	if (t4_num_vis < 1)
12642 		t4_num_vis = 1;
12643 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12644 		t4_num_vis = nitems(vi_mac_funcs);
12645 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12646 	}
12647 
12648 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12649 		pcie_relaxed_ordering = 1;
12650 #if defined(__i386__) || defined(__amd64__)
12651 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12652 			pcie_relaxed_ordering = 0;
12653 #endif
12654 	}
12655 }
12656 
12657 #ifdef DDB
12658 static void
12659 t4_dump_tcb(struct adapter *sc, int tid)
12660 {
12661 	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
12662 
12663 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12664 	save = t4_read_reg(sc, reg);
12665 	base = sc->memwin[2].mw_base;
12666 
12667 	/* Dump TCB for the tid */
12668 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12669 	tcb_addr += tid * TCB_SIZE;
12670 
12671 	if (is_t4(sc)) {
12672 		pf = 0;
12673 		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
12674 	} else {
12675 		pf = V_PFNUM(sc->pf);
12676 		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
12677 	}
12678 	t4_write_reg(sc, reg, win_pos | pf);
12679 	t4_read_reg(sc, reg);
12680 
12681 	off = tcb_addr - win_pos;
12682 	for (i = 0; i < 4; i++) {
12683 		uint32_t buf[8];
12684 		for (j = 0; j < 8; j++, off += 4)
12685 			buf[j] = htonl(t4_read_reg(sc, base + off));
12686 
12687 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12688 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12689 		    buf[7]);
12690 	}
12691 
12692 	t4_write_reg(sc, reg, save);
12693 	t4_read_reg(sc, reg);
12694 }
12695 
12696 static void
12697 t4_dump_devlog(struct adapter *sc)
12698 {
12699 	struct devlog_params *dparams = &sc->params.devlog;
12700 	struct fw_devlog_e e;
12701 	int i, first, j, m, nentries, rc;
12702 	uint64_t ftstamp = UINT64_MAX;
12703 
12704 	if (dparams->start == 0) {
12705 		db_printf("devlog params not valid\n");
12706 		return;
12707 	}
12708 
12709 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12710 	m = fwmtype_to_hwmtype(dparams->memtype);
12711 
12712 	/* Find the first entry. */
12713 	first = -1;
12714 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12715 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12716 		    sizeof(e), (void *)&e);
12717 		if (rc != 0)
12718 			break;
12719 
12720 		if (e.timestamp == 0)
12721 			break;
12722 
12723 		e.timestamp = be64toh(e.timestamp);
12724 		if (e.timestamp < ftstamp) {
12725 			ftstamp = e.timestamp;
12726 			first = i;
12727 		}
12728 	}
12729 
12730 	if (first == -1)
12731 		return;
12732 
12733 	i = first;
12734 	do {
12735 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12736 		    sizeof(e), (void *)&e);
12737 		if (rc != 0)
12738 			return;
12739 
12740 		if (e.timestamp == 0)
12741 			return;
12742 
12743 		e.timestamp = be64toh(e.timestamp);
12744 		e.seqno = be32toh(e.seqno);
12745 		for (j = 0; j < 8; j++)
12746 			e.params[j] = be32toh(e.params[j]);
12747 
12748 		db_printf("%10d  %15ju  %8s  %8s  ",
12749 		    e.seqno, e.timestamp,
12750 		    (e.level < nitems(devlog_level_strings) ?
12751 			devlog_level_strings[e.level] : "UNKNOWN"),
12752 		    (e.facility < nitems(devlog_facility_strings) ?
12753 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12754 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12755 		    e.params[3], e.params[4], e.params[5], e.params[6],
12756 		    e.params[7]);
12757 
12758 		if (++i == nentries)
12759 			i = 0;
12760 	} while (i != first && !db_pager_quit);
12761 }
12762 
12763 static struct command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
12764 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
12765 
12766 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
12767 {
12768 	device_t dev;
12769 	int t;
12770 	bool valid;
12771 
12772 	valid = false;
12773 	t = db_read_token();
12774 	if (t == tIDENT) {
12775 		dev = device_lookup_by_name(db_tok_string);
12776 		valid = true;
12777 	}
12778 	db_skip_to_eol();
12779 	if (!valid) {
12780 		db_printf("usage: show t4 devlog <nexus>\n");
12781 		return;
12782 	}
12783 
12784 	if (dev == NULL) {
12785 		db_printf("device not found\n");
12786 		return;
12787 	}
12788 
12789 	t4_dump_devlog(device_get_softc(dev));
12790 }
12791 
12792 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
12793 {
12794 	device_t dev;
12795 	int radix, tid, t;
12796 	bool valid;
12797 
12798 	valid = false;
12799 	radix = db_radix;
12800 	db_radix = 10;
12801 	t = db_read_token();
12802 	if (t == tIDENT) {
12803 		dev = device_lookup_by_name(db_tok_string);
12804 		t = db_read_token();
12805 		if (t == tNUMBER) {
12806 			tid = db_tok_number;
12807 			valid = true;
12808 		}
12809 	}
12810 	db_radix = radix;
12811 	db_skip_to_eol();
12812 	if (!valid) {
12813 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
12814 		return;
12815 	}
12816 
12817 	if (dev == NULL) {
12818 		db_printf("device not found\n");
12819 		return;
12820 	}
12821 	if (tid < 0) {
12822 		db_printf("invalid tid\n");
12823 		return;
12824 	}
12825 
12826 	t4_dump_tcb(device_get_softc(dev), tid);
12827 }
12828 #endif
12829 
12830 static eventhandler_tag vxlan_start_evtag;
12831 static eventhandler_tag vxlan_stop_evtag;
12832 
12833 struct vxlan_evargs {
12834 	struct ifnet *ifp;
12835 	uint16_t port;
12836 };
12837 
12838 static void
12839 enable_vxlan_rx(struct adapter *sc)
12840 {
12841 	int i, rc;
12842 	struct port_info *pi;
12843 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
12844 
12845 	ASSERT_SYNCHRONIZED_OP(sc);
12846 
12847 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
12848 	    F_VXLAN_EN);
12849 	for_each_port(sc, i) {
12850 		pi = sc->port[i];
12851 		if (pi->vxlan_tcam_entry == true)
12852 			continue;
12853 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
12854 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
12855 		    true);
12856 		if (rc < 0) {
12857 			rc = -rc;
12858 			CH_ERR(&pi->vi[0],
12859 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
12860 		} else {
12861 			MPASS(rc == sc->rawf_base + pi->port_id);
12862 			pi->vxlan_tcam_entry = true;
12863 		}
12864 	}
12865 }
12866 
12867 static void
12868 t4_vxlan_start(struct adapter *sc, void *arg)
12869 {
12870 	struct vxlan_evargs *v = arg;
12871 
12872 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
12873 		return;
12874 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
12875 		return;
12876 
12877 	if (sc->vxlan_refcount == 0) {
12878 		sc->vxlan_port = v->port;
12879 		sc->vxlan_refcount = 1;
12880 		if (!hw_off_limits(sc))
12881 			enable_vxlan_rx(sc);
12882 	} else if (sc->vxlan_port == v->port) {
12883 		sc->vxlan_refcount++;
12884 	} else {
12885 		CH_ERR(sc, "VXLAN already configured on port  %d; "
12886 		    "ignoring attempt to configure it on port %d\n",
12887 		    sc->vxlan_port, v->port);
12888 	}
12889 	end_synchronized_op(sc, 0);
12890 }
12891 
12892 static void
12893 t4_vxlan_stop(struct adapter *sc, void *arg)
12894 {
12895 	struct vxlan_evargs *v = arg;
12896 
12897 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
12898 		return;
12899 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
12900 		return;
12901 
12902 	/*
12903 	 * VXLANs may have been configured before the driver was loaded so we
12904 	 * may see more stops than starts.  This is not handled cleanly but at
12905 	 * least we keep the refcount sane.
12906 	 */
12907 	if (sc->vxlan_port != v->port)
12908 		goto done;
12909 	if (sc->vxlan_refcount == 0) {
12910 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
12911 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
12912 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
12913 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
12914 done:
12915 	end_synchronized_op(sc, 0);
12916 }
12917 
12918 static void
12919 t4_vxlan_start_handler(void *arg __unused, struct ifnet *ifp,
12920     sa_family_t family, u_int port)
12921 {
12922 	struct vxlan_evargs v;
12923 
12924 	MPASS(family == AF_INET || family == AF_INET6);
12925 	v.ifp = ifp;
12926 	v.port = port;
12927 
12928 	t4_iterate(t4_vxlan_start, &v);
12929 }
12930 
12931 static void
12932 t4_vxlan_stop_handler(void *arg __unused, struct ifnet *ifp, sa_family_t family,
12933     u_int port)
12934 {
12935 	struct vxlan_evargs v;
12936 
12937 	MPASS(family == AF_INET || family == AF_INET6);
12938 	v.ifp = ifp;
12939 	v.port = port;
12940 
12941 	t4_iterate(t4_vxlan_stop, &v);
12942 }
12943 
12944 
12945 static struct sx mlu;	/* mod load unload */
12946 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
12947 
12948 static int
12949 mod_event(module_t mod, int cmd, void *arg)
12950 {
12951 	int rc = 0;
12952 	static int loaded = 0;
12953 
12954 	switch (cmd) {
12955 	case MOD_LOAD:
12956 		sx_xlock(&mlu);
12957 		if (loaded++ == 0) {
12958 			t4_sge_modload();
12959 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
12960 			    t4_filter_rpl, CPL_COOKIE_FILTER);
12961 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
12962 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
12963 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
12964 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
12965 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
12966 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
12967 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
12968 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
12969 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
12970 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
12971 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
12972 			    do_smt_write_rpl);
12973 			sx_init(&t4_list_lock, "T4/T5 adapters");
12974 			SLIST_INIT(&t4_list);
12975 			callout_init(&fatal_callout, 1);
12976 #ifdef TCP_OFFLOAD
12977 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
12978 			SLIST_INIT(&t4_uld_list);
12979 #endif
12980 #ifdef INET6
12981 			t4_clip_modload();
12982 #endif
12983 #ifdef KERN_TLS
12984 			t6_ktls_modload();
12985 #endif
12986 			t4_tracer_modload();
12987 			tweak_tunables();
12988 			vxlan_start_evtag =
12989 			    EVENTHANDLER_REGISTER(vxlan_start,
12990 				t4_vxlan_start_handler, NULL,
12991 				EVENTHANDLER_PRI_ANY);
12992 			vxlan_stop_evtag =
12993 			    EVENTHANDLER_REGISTER(vxlan_stop,
12994 				t4_vxlan_stop_handler, NULL,
12995 				EVENTHANDLER_PRI_ANY);
12996 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
12997 			    taskqueue_thread_enqueue, &reset_tq);
12998 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
12999 			    "t4_rst_thr");
13000 		}
13001 		sx_xunlock(&mlu);
13002 		break;
13003 
13004 	case MOD_UNLOAD:
13005 		sx_xlock(&mlu);
13006 		if (--loaded == 0) {
13007 			int tries;
13008 
13009 			taskqueue_free(reset_tq);
13010 			sx_slock(&t4_list_lock);
13011 			if (!SLIST_EMPTY(&t4_list)) {
13012 				rc = EBUSY;
13013 				sx_sunlock(&t4_list_lock);
13014 				goto done_unload;
13015 			}
13016 #ifdef TCP_OFFLOAD
13017 			sx_slock(&t4_uld_list_lock);
13018 			if (!SLIST_EMPTY(&t4_uld_list)) {
13019 				rc = EBUSY;
13020 				sx_sunlock(&t4_uld_list_lock);
13021 				sx_sunlock(&t4_list_lock);
13022 				goto done_unload;
13023 			}
13024 #endif
13025 			tries = 0;
13026 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13027 				uprintf("%ju clusters with custom free routine "
13028 				    "still is use.\n", t4_sge_extfree_refs());
13029 				pause("t4unload", 2 * hz);
13030 			}
13031 #ifdef TCP_OFFLOAD
13032 			sx_sunlock(&t4_uld_list_lock);
13033 #endif
13034 			sx_sunlock(&t4_list_lock);
13035 
13036 			if (t4_sge_extfree_refs() == 0) {
13037 				EVENTHANDLER_DEREGISTER(vxlan_start,
13038 				    vxlan_start_evtag);
13039 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13040 				    vxlan_stop_evtag);
13041 				t4_tracer_modunload();
13042 #ifdef KERN_TLS
13043 				t6_ktls_modunload();
13044 #endif
13045 #ifdef INET6
13046 				t4_clip_modunload();
13047 #endif
13048 #ifdef TCP_OFFLOAD
13049 				sx_destroy(&t4_uld_list_lock);
13050 #endif
13051 				sx_destroy(&t4_list_lock);
13052 				t4_sge_modunload();
13053 				loaded = 0;
13054 			} else {
13055 				rc = EBUSY;
13056 				loaded++;	/* undo earlier decrement */
13057 			}
13058 		}
13059 done_unload:
13060 		sx_xunlock(&mlu);
13061 		break;
13062 	}
13063 
13064 	return (rc);
13065 }
13066 
13067 static devclass_t t4_devclass, t5_devclass, t6_devclass;
13068 static devclass_t cxgbe_devclass, cxl_devclass, cc_devclass;
13069 static devclass_t vcxgbe_devclass, vcxl_devclass, vcc_devclass;
13070 
13071 DRIVER_MODULE(t4nex, pci, t4_driver, t4_devclass, mod_event, 0);
13072 MODULE_VERSION(t4nex, 1);
13073 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13074 #ifdef DEV_NETMAP
13075 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13076 #endif /* DEV_NETMAP */
13077 
13078 DRIVER_MODULE(t5nex, pci, t5_driver, t5_devclass, mod_event, 0);
13079 MODULE_VERSION(t5nex, 1);
13080 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13081 #ifdef DEV_NETMAP
13082 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13083 #endif /* DEV_NETMAP */
13084 
13085 DRIVER_MODULE(t6nex, pci, t6_driver, t6_devclass, mod_event, 0);
13086 MODULE_VERSION(t6nex, 1);
13087 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13088 #ifdef DEV_NETMAP
13089 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13090 #endif /* DEV_NETMAP */
13091 
13092 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, cxgbe_devclass, 0, 0);
13093 MODULE_VERSION(cxgbe, 1);
13094 
13095 DRIVER_MODULE(cxl, t5nex, cxl_driver, cxl_devclass, 0, 0);
13096 MODULE_VERSION(cxl, 1);
13097 
13098 DRIVER_MODULE(cc, t6nex, cc_driver, cc_devclass, 0, 0);
13099 MODULE_VERSION(cc, 1);
13100 
13101 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, vcxgbe_devclass, 0, 0);
13102 MODULE_VERSION(vcxgbe, 1);
13103 
13104 DRIVER_MODULE(vcxl, cxl, vcxl_driver, vcxl_devclass, 0, 0);
13105 MODULE_VERSION(vcxl, 1);
13106 
13107 DRIVER_MODULE(vcc, cc, vcc_driver, vcc_devclass, 0, 0);
13108 MODULE_VERSION(vcc, 1);
13109