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