xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision 52fba9a943cca518d2978f7588e99a35da37e5f2)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 Chelsio Communications, Inc.
5  * All rights reserved.
6  * Written by: Navdeep Parhar <np@FreeBSD.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include "opt_ddb.h"
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_kern_tls.h"
37 #include "opt_ratelimit.h"
38 #include "opt_rss.h"
39 
40 #include <sys/param.h>
41 #include <sys/conf.h>
42 #include <sys/priv.h>
43 #include <sys/kernel.h>
44 #include <sys/bus.h>
45 #include <sys/eventhandler.h>
46 #include <sys/module.h>
47 #include <sys/malloc.h>
48 #include <sys/queue.h>
49 #include <sys/taskqueue.h>
50 #include <sys/pciio.h>
51 #include <dev/pci/pcireg.h>
52 #include <dev/pci/pcivar.h>
53 #include <dev/pci/pci_private.h>
54 #include <sys/firmware.h>
55 #include <sys/sbuf.h>
56 #include <sys/smp.h>
57 #include <sys/socket.h>
58 #include <sys/sockio.h>
59 #include <sys/sysctl.h>
60 #include <net/ethernet.h>
61 #include <net/if.h>
62 #include <net/if_types.h>
63 #include <net/if_dl.h>
64 #include <net/if_vlan_var.h>
65 #ifdef RSS
66 #include <net/rss_config.h>
67 #endif
68 #include <netinet/in.h>
69 #include <netinet/ip.h>
70 #ifdef KERN_TLS
71 #include <netinet/tcp_seq.h>
72 #endif
73 #if defined(__i386__) || defined(__amd64__)
74 #include <machine/md_var.h>
75 #include <machine/cputypes.h>
76 #include <vm/vm.h>
77 #include <vm/pmap.h>
78 #endif
79 #ifdef DDB
80 #include <ddb/ddb.h>
81 #include <ddb/db_lex.h>
82 #endif
83 
84 #include "common/common.h"
85 #include "common/t4_msg.h"
86 #include "common/t4_regs.h"
87 #include "common/t4_regs_values.h"
88 #include "cudbg/cudbg.h"
89 #include "t4_clip.h"
90 #include "t4_ioctl.h"
91 #include "t4_l2t.h"
92 #include "t4_mp_ring.h"
93 #include "t4_if.h"
94 #include "t4_smt.h"
95 
96 /* T4 bus driver interface */
97 static int t4_probe(device_t);
98 static int t4_attach(device_t);
99 static int t4_detach(device_t);
100 static int t4_child_location(device_t, device_t, struct sbuf *);
101 static int t4_ready(device_t);
102 static int t4_read_port_device(device_t, int, device_t *);
103 static int t4_suspend(device_t);
104 static int t4_resume(device_t);
105 static int t4_reset_prepare(device_t, device_t);
106 static int t4_reset_post(device_t, device_t);
107 static device_method_t t4_methods[] = {
108 	DEVMETHOD(device_probe,		t4_probe),
109 	DEVMETHOD(device_attach,	t4_attach),
110 	DEVMETHOD(device_detach,	t4_detach),
111 	DEVMETHOD(device_suspend,	t4_suspend),
112 	DEVMETHOD(device_resume,	t4_resume),
113 
114 	DEVMETHOD(bus_child_location,	t4_child_location),
115 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
116 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
117 
118 	DEVMETHOD(t4_is_main_ready,	t4_ready),
119 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
120 
121 	DEVMETHOD_END
122 };
123 static driver_t t4_driver = {
124 	"t4nex",
125 	t4_methods,
126 	sizeof(struct adapter)
127 };
128 
129 
130 /* T4 port (cxgbe) interface */
131 static int cxgbe_probe(device_t);
132 static int cxgbe_attach(device_t);
133 static int cxgbe_detach(device_t);
134 device_method_t cxgbe_methods[] = {
135 	DEVMETHOD(device_probe,		cxgbe_probe),
136 	DEVMETHOD(device_attach,	cxgbe_attach),
137 	DEVMETHOD(device_detach,	cxgbe_detach),
138 	{ 0, 0 }
139 };
140 static driver_t cxgbe_driver = {
141 	"cxgbe",
142 	cxgbe_methods,
143 	sizeof(struct port_info)
144 };
145 
146 /* T4 VI (vcxgbe) interface */
147 static int vcxgbe_probe(device_t);
148 static int vcxgbe_attach(device_t);
149 static int vcxgbe_detach(device_t);
150 static device_method_t vcxgbe_methods[] = {
151 	DEVMETHOD(device_probe,		vcxgbe_probe),
152 	DEVMETHOD(device_attach,	vcxgbe_attach),
153 	DEVMETHOD(device_detach,	vcxgbe_detach),
154 	{ 0, 0 }
155 };
156 static driver_t vcxgbe_driver = {
157 	"vcxgbe",
158 	vcxgbe_methods,
159 	sizeof(struct vi_info)
160 };
161 
162 static d_ioctl_t t4_ioctl;
163 
164 static struct cdevsw t4_cdevsw = {
165        .d_version = D_VERSION,
166        .d_ioctl = t4_ioctl,
167        .d_name = "t4nex",
168 };
169 
170 /* T5 bus driver interface */
171 static int t5_probe(device_t);
172 static device_method_t t5_methods[] = {
173 	DEVMETHOD(device_probe,		t5_probe),
174 	DEVMETHOD(device_attach,	t4_attach),
175 	DEVMETHOD(device_detach,	t4_detach),
176 	DEVMETHOD(device_suspend,	t4_suspend),
177 	DEVMETHOD(device_resume,	t4_resume),
178 
179 	DEVMETHOD(bus_child_location,	t4_child_location),
180 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
181 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
182 
183 	DEVMETHOD(t4_is_main_ready,	t4_ready),
184 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
185 
186 	DEVMETHOD_END
187 };
188 static driver_t t5_driver = {
189 	"t5nex",
190 	t5_methods,
191 	sizeof(struct adapter)
192 };
193 
194 
195 /* T5 port (cxl) interface */
196 static driver_t cxl_driver = {
197 	"cxl",
198 	cxgbe_methods,
199 	sizeof(struct port_info)
200 };
201 
202 /* T5 VI (vcxl) interface */
203 static driver_t vcxl_driver = {
204 	"vcxl",
205 	vcxgbe_methods,
206 	sizeof(struct vi_info)
207 };
208 
209 /* T6 bus driver interface */
210 static int t6_probe(device_t);
211 static device_method_t t6_methods[] = {
212 	DEVMETHOD(device_probe,		t6_probe),
213 	DEVMETHOD(device_attach,	t4_attach),
214 	DEVMETHOD(device_detach,	t4_detach),
215 	DEVMETHOD(device_suspend,	t4_suspend),
216 	DEVMETHOD(device_resume,	t4_resume),
217 
218 	DEVMETHOD(bus_child_location,	t4_child_location),
219 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
220 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
221 
222 	DEVMETHOD(t4_is_main_ready,	t4_ready),
223 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
224 
225 	DEVMETHOD_END
226 };
227 static driver_t t6_driver = {
228 	"t6nex",
229 	t6_methods,
230 	sizeof(struct adapter)
231 };
232 
233 
234 /* T6 port (cc) interface */
235 static driver_t cc_driver = {
236 	"cc",
237 	cxgbe_methods,
238 	sizeof(struct port_info)
239 };
240 
241 /* T6 VI (vcc) interface */
242 static driver_t vcc_driver = {
243 	"vcc",
244 	vcxgbe_methods,
245 	sizeof(struct vi_info)
246 };
247 
248 /* ifnet interface */
249 static void cxgbe_init(void *);
250 static int cxgbe_ioctl(struct ifnet *, unsigned long, caddr_t);
251 static int cxgbe_transmit(struct ifnet *, struct mbuf *);
252 static void cxgbe_qflush(struct ifnet *);
253 #if defined(KERN_TLS) || defined(RATELIMIT)
254 static int cxgbe_snd_tag_alloc(struct ifnet *, union if_snd_tag_alloc_params *,
255     struct m_snd_tag **);
256 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(device_t bus, device_t dev, struct sbuf *sb)
1576 {
1577 	struct adapter *sc;
1578 	struct port_info *pi;
1579 	int i;
1580 
1581 	sc = device_get_softc(bus);
1582 	for_each_port(sc, i) {
1583 		pi = sc->port[i];
1584 		if (pi != NULL && pi->dev == dev) {
1585 			sbuf_printf(sb, "port=%d", pi->port_id);
1586 			break;
1587 		}
1588 	}
1589 	return (0);
1590 }
1591 
1592 static int
1593 t4_ready(device_t dev)
1594 {
1595 	struct adapter *sc;
1596 
1597 	sc = device_get_softc(dev);
1598 	if (sc->flags & FW_OK)
1599 		return (0);
1600 	return (ENXIO);
1601 }
1602 
1603 static int
1604 t4_read_port_device(device_t dev, int port, device_t *child)
1605 {
1606 	struct adapter *sc;
1607 	struct port_info *pi;
1608 
1609 	sc = device_get_softc(dev);
1610 	if (port < 0 || port >= MAX_NPORTS)
1611 		return (EINVAL);
1612 	pi = sc->port[port];
1613 	if (pi == NULL || pi->dev == NULL)
1614 		return (ENXIO);
1615 	*child = pi->dev;
1616 	return (0);
1617 }
1618 
1619 static int
1620 notify_siblings(device_t dev, int detaching)
1621 {
1622 	device_t sibling;
1623 	int error, i;
1624 
1625 	error = 0;
1626 	for (i = 0; i < PCI_FUNCMAX; i++) {
1627 		if (i == pci_get_function(dev))
1628 			continue;
1629 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1630 		    pci_get_slot(dev), i);
1631 		if (sibling == NULL || !device_is_attached(sibling))
1632 			continue;
1633 		if (detaching)
1634 			error = T4_DETACH_CHILD(sibling);
1635 		else
1636 			(void)T4_ATTACH_CHILD(sibling);
1637 		if (error)
1638 			break;
1639 	}
1640 	return (error);
1641 }
1642 
1643 /*
1644  * Idempotent
1645  */
1646 static int
1647 t4_detach(device_t dev)
1648 {
1649 	struct adapter *sc;
1650 	int rc;
1651 
1652 	sc = device_get_softc(dev);
1653 
1654 	rc = notify_siblings(dev, 1);
1655 	if (rc) {
1656 		device_printf(dev,
1657 		    "failed to detach sibling devices: %d\n", rc);
1658 		return (rc);
1659 	}
1660 
1661 	return (t4_detach_common(dev));
1662 }
1663 
1664 int
1665 t4_detach_common(device_t dev)
1666 {
1667 	struct adapter *sc;
1668 	struct port_info *pi;
1669 	int i, rc;
1670 
1671 	sc = device_get_softc(dev);
1672 
1673 	if (sc->cdev) {
1674 		destroy_dev(sc->cdev);
1675 		sc->cdev = NULL;
1676 	}
1677 
1678 	sx_xlock(&t4_list_lock);
1679 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1680 	sx_xunlock(&t4_list_lock);
1681 
1682 	sc->flags &= ~CHK_MBOX_ACCESS;
1683 	if (sc->flags & FULL_INIT_DONE) {
1684 		if (!(sc->flags & IS_VF))
1685 			t4_intr_disable(sc);
1686 	}
1687 
1688 	if (device_is_attached(dev)) {
1689 		rc = bus_generic_detach(dev);
1690 		if (rc) {
1691 			device_printf(dev,
1692 			    "failed to detach child devices: %d\n", rc);
1693 			return (rc);
1694 		}
1695 	}
1696 
1697 #ifdef TCP_OFFLOAD
1698 	taskqueue_drain(taskqueue_thread, &sc->async_event_task);
1699 #endif
1700 
1701 	for (i = 0; i < sc->intr_count; i++)
1702 		t4_free_irq(sc, &sc->irq[i]);
1703 
1704 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1705 		t4_free_tx_sched(sc);
1706 
1707 	for (i = 0; i < MAX_NPORTS; i++) {
1708 		pi = sc->port[i];
1709 		if (pi) {
1710 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1711 			if (pi->dev)
1712 				device_delete_child(dev, pi->dev);
1713 
1714 			mtx_destroy(&pi->pi_lock);
1715 			free(pi->vi, M_CXGBE);
1716 			free(pi, M_CXGBE);
1717 		}
1718 	}
1719 
1720 	device_delete_children(dev);
1721 	adapter_full_uninit(sc);
1722 
1723 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1724 		t4_fw_bye(sc, sc->mbox);
1725 
1726 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1727 		pci_release_msi(dev);
1728 
1729 	if (sc->regs_res)
1730 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1731 		    sc->regs_res);
1732 
1733 	if (sc->udbs_res)
1734 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1735 		    sc->udbs_res);
1736 
1737 	if (sc->msix_res)
1738 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1739 		    sc->msix_res);
1740 
1741 	if (sc->l2t)
1742 		t4_free_l2t(sc->l2t);
1743 	if (sc->smt)
1744 		t4_free_smt(sc->smt);
1745 	t4_free_atid_table(sc);
1746 #ifdef RATELIMIT
1747 	t4_free_etid_table(sc);
1748 #endif
1749 	if (sc->key_map)
1750 		vmem_destroy(sc->key_map);
1751 #ifdef INET6
1752 	t4_destroy_clip_table(sc);
1753 #endif
1754 
1755 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1756 	free(sc->sge.ofld_txq, M_CXGBE);
1757 #endif
1758 #ifdef TCP_OFFLOAD
1759 	free(sc->sge.ofld_rxq, M_CXGBE);
1760 #endif
1761 #ifdef DEV_NETMAP
1762 	free(sc->sge.nm_rxq, M_CXGBE);
1763 	free(sc->sge.nm_txq, M_CXGBE);
1764 #endif
1765 	free(sc->irq, M_CXGBE);
1766 	free(sc->sge.rxq, M_CXGBE);
1767 	free(sc->sge.txq, M_CXGBE);
1768 	free(sc->sge.ctrlq, M_CXGBE);
1769 	free(sc->sge.iqmap, M_CXGBE);
1770 	free(sc->sge.eqmap, M_CXGBE);
1771 	free(sc->tids.ftid_tab, M_CXGBE);
1772 	free(sc->tids.hpftid_tab, M_CXGBE);
1773 	free_hftid_hash(&sc->tids);
1774 	free(sc->tids.tid_tab, M_CXGBE);
1775 	free(sc->tt.tls_rx_ports, M_CXGBE);
1776 	t4_destroy_dma_tag(sc);
1777 
1778 	callout_drain(&sc->ktls_tick);
1779 	callout_drain(&sc->sfl_callout);
1780 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1781 		mtx_destroy(&sc->tids.ftid_lock);
1782 		cv_destroy(&sc->tids.ftid_cv);
1783 	}
1784 	if (mtx_initialized(&sc->tids.atid_lock))
1785 		mtx_destroy(&sc->tids.atid_lock);
1786 	if (mtx_initialized(&sc->ifp_lock))
1787 		mtx_destroy(&sc->ifp_lock);
1788 
1789 	if (rw_initialized(&sc->policy_lock)) {
1790 		rw_destroy(&sc->policy_lock);
1791 #ifdef TCP_OFFLOAD
1792 		if (sc->policy != NULL)
1793 			free_offload_policy(sc->policy);
1794 #endif
1795 	}
1796 
1797 	for (i = 0; i < NUM_MEMWIN; i++) {
1798 		struct memwin *mw = &sc->memwin[i];
1799 
1800 		if (rw_initialized(&mw->mw_lock))
1801 			rw_destroy(&mw->mw_lock);
1802 	}
1803 
1804 	mtx_destroy(&sc->sfl_lock);
1805 	mtx_destroy(&sc->reg_lock);
1806 	mtx_destroy(&sc->sc_lock);
1807 
1808 	bzero(sc, sizeof(*sc));
1809 
1810 	return (0);
1811 }
1812 
1813 static inline bool
1814 ok_to_reset(struct adapter *sc)
1815 {
1816 	struct tid_info *t = &sc->tids;
1817 	struct port_info *pi;
1818 	struct vi_info *vi;
1819 	int i, j;
1820 	const int caps = IFCAP_TOE | IFCAP_TXTLS | IFCAP_NETMAP | IFCAP_TXRTLMT;
1821 
1822 	ASSERT_SYNCHRONIZED_OP(sc);
1823 	MPASS(!(sc->flags & IS_VF));
1824 
1825 	for_each_port(sc, i) {
1826 		pi = sc->port[i];
1827 		for_each_vi(pi, j, vi) {
1828 			if (vi->ifp->if_capenable & caps)
1829 				return (false);
1830 		}
1831 	}
1832 
1833 	if (atomic_load_int(&t->tids_in_use) > 0)
1834 		return (false);
1835 	if (atomic_load_int(&t->stids_in_use) > 0)
1836 		return (false);
1837 	if (atomic_load_int(&t->atids_in_use) > 0)
1838 		return (false);
1839 	if (atomic_load_int(&t->ftids_in_use) > 0)
1840 		return (false);
1841 	if (atomic_load_int(&t->hpftids_in_use) > 0)
1842 		return (false);
1843 	if (atomic_load_int(&t->etids_in_use) > 0)
1844 		return (false);
1845 
1846 	return (true);
1847 }
1848 
1849 static int
1850 t4_suspend(device_t dev)
1851 {
1852 	struct adapter *sc = device_get_softc(dev);
1853 	struct port_info *pi;
1854 	struct vi_info *vi;
1855 	struct ifnet *ifp;
1856 	struct sge_rxq *rxq;
1857 	struct sge_txq *txq;
1858 	struct sge_wrq *wrq;
1859 #ifdef TCP_OFFLOAD
1860 	struct sge_ofld_rxq *ofld_rxq;
1861 #endif
1862 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1863 	struct sge_ofld_txq *ofld_txq;
1864 #endif
1865 	int rc, i, j, k;
1866 
1867 	CH_ALERT(sc, "suspend requested\n");
1868 
1869 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4sus");
1870 	if (rc != 0)
1871 		return (ENXIO);
1872 
1873 	/* XXX: Can the kernel call suspend repeatedly without resume? */
1874 	MPASS(!hw_off_limits(sc));
1875 
1876 	if (!ok_to_reset(sc)) {
1877 		/* XXX: should list what resource is preventing suspend. */
1878 		CH_ERR(sc, "not safe to suspend.\n");
1879 		rc = EBUSY;
1880 		goto done;
1881 	}
1882 
1883 	/* No more DMA or interrupts. */
1884 	t4_shutdown_adapter(sc);
1885 
1886 	/* Quiesce all activity. */
1887 	for_each_port(sc, i) {
1888 		pi = sc->port[i];
1889 		pi->vxlan_tcam_entry = false;
1890 
1891 		PORT_LOCK(pi);
1892 		if (pi->up_vis > 0) {
1893 			/*
1894 			 * t4_shutdown_adapter has already shut down all the
1895 			 * PHYs but it also disables interrupts and DMA so there
1896 			 * won't be a link interrupt.  So we update the state
1897 			 * manually and inform the kernel.
1898 			 */
1899 			pi->link_cfg.link_ok = false;
1900 			t4_os_link_changed(pi);
1901 		}
1902 		PORT_UNLOCK(pi);
1903 
1904 		for_each_vi(pi, j, vi) {
1905 			vi->xact_addr_filt = -1;
1906 			if (!(vi->flags & VI_INIT_DONE))
1907 				continue;
1908 
1909 			ifp = vi->ifp;
1910 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1911 				mtx_lock(&vi->tick_mtx);
1912 				vi->flags |= VI_SKIP_STATS;
1913 				callout_stop(&vi->tick);
1914 				mtx_unlock(&vi->tick_mtx);
1915 				callout_drain(&vi->tick);
1916 			}
1917 
1918 			/*
1919 			 * Note that the HW is not available.
1920 			 */
1921 			for_each_txq(vi, k, txq) {
1922 				TXQ_LOCK(txq);
1923 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
1924 				TXQ_UNLOCK(txq);
1925 			}
1926 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1927 			for_each_ofld_txq(vi, k, ofld_txq) {
1928 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
1929 			}
1930 #endif
1931 			for_each_rxq(vi, k, rxq) {
1932 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1933 			}
1934 #if defined(TCP_OFFLOAD)
1935 			for_each_ofld_rxq(vi, k, ofld_rxq) {
1936 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1937 			}
1938 #endif
1939 
1940 			quiesce_vi(vi);
1941 		}
1942 
1943 		if (sc->flags & FULL_INIT_DONE) {
1944 			/* Control queue */
1945 			wrq = &sc->sge.ctrlq[i];
1946 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
1947 			quiesce_wrq(wrq);
1948 		}
1949 	}
1950 	if (sc->flags & FULL_INIT_DONE) {
1951 		/* Firmware event queue */
1952 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
1953 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
1954 	}
1955 
1956 	/* Mark the adapter totally off limits. */
1957 	mtx_lock(&sc->reg_lock);
1958 	sc->flags |= HW_OFF_LIMITS;
1959 	sc->flags &= ~(FW_OK | MASTER_PF);
1960 	sc->reset_thread = NULL;
1961 	mtx_unlock(&sc->reg_lock);
1962 
1963 	sc->num_resets++;
1964 	CH_ALERT(sc, "suspend completed.\n");
1965 done:
1966 	end_synchronized_op(sc, 0);
1967 	return (rc);
1968 }
1969 
1970 struct adapter_pre_reset_state {
1971 	u_int flags;
1972 	uint16_t nbmcaps;
1973 	uint16_t linkcaps;
1974 	uint16_t switchcaps;
1975 	uint16_t niccaps;
1976 	uint16_t toecaps;
1977 	uint16_t rdmacaps;
1978 	uint16_t cryptocaps;
1979 	uint16_t iscsicaps;
1980 	uint16_t fcoecaps;
1981 
1982 	u_int cfcsum;
1983 	char cfg_file[32];
1984 
1985 	struct adapter_params params;
1986 	struct t4_virt_res vres;
1987 	struct tid_info tids;
1988 	struct sge sge;
1989 
1990 	int rawf_base;
1991 	int nrawf;
1992 
1993 };
1994 
1995 static void
1996 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
1997 {
1998 
1999 	ASSERT_SYNCHRONIZED_OP(sc);
2000 
2001 	o->flags = sc->flags;
2002 
2003 	o->nbmcaps =  sc->nbmcaps;
2004 	o->linkcaps = sc->linkcaps;
2005 	o->switchcaps = sc->switchcaps;
2006 	o->niccaps = sc->niccaps;
2007 	o->toecaps = sc->toecaps;
2008 	o->rdmacaps = sc->rdmacaps;
2009 	o->cryptocaps = sc->cryptocaps;
2010 	o->iscsicaps = sc->iscsicaps;
2011 	o->fcoecaps = sc->fcoecaps;
2012 
2013 	o->cfcsum = sc->cfcsum;
2014 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2015 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2016 
2017 	o->params = sc->params;
2018 	o->vres = sc->vres;
2019 	o->tids = sc->tids;
2020 	o->sge = sc->sge;
2021 
2022 	o->rawf_base = sc->rawf_base;
2023 	o->nrawf = sc->nrawf;
2024 }
2025 
2026 static int
2027 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2028 {
2029 	int rc = 0;
2030 
2031 	ASSERT_SYNCHRONIZED_OP(sc);
2032 
2033 	/* Capabilities */
2034 #define COMPARE_CAPS(c) do { \
2035 	if (o->c##caps != sc->c##caps) { \
2036 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2037 		    sc->c##caps); \
2038 		rc = EINVAL; \
2039 	} \
2040 } while (0)
2041 	COMPARE_CAPS(nbm);
2042 	COMPARE_CAPS(link);
2043 	COMPARE_CAPS(switch);
2044 	COMPARE_CAPS(nic);
2045 	COMPARE_CAPS(toe);
2046 	COMPARE_CAPS(rdma);
2047 	COMPARE_CAPS(crypto);
2048 	COMPARE_CAPS(iscsi);
2049 	COMPARE_CAPS(fcoe);
2050 #undef COMPARE_CAPS
2051 
2052 	/* Firmware config file */
2053 	if (o->cfcsum != sc->cfcsum) {
2054 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2055 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2056 		rc = EINVAL;
2057 	}
2058 
2059 #define COMPARE_PARAM(p, name) do { \
2060 	if (o->p != sc->p) { \
2061 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2062 		rc = EINVAL; \
2063 	} \
2064 } while (0)
2065 	COMPARE_PARAM(sge.iq_start, iq_start);
2066 	COMPARE_PARAM(sge.eq_start, eq_start);
2067 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2068 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2069 	COMPARE_PARAM(tids.nftids, nftids);
2070 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2071 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2072 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2073 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2074 	COMPARE_PARAM(tids.tid_base, tid_base);
2075 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2076 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2077 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2078 	COMPARE_PARAM(rawf_base, rawf_base);
2079 	COMPARE_PARAM(nrawf, nrawf);
2080 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2081 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2082 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2083 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2084 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2085 	COMPARE_PARAM(tids.ntids, ntids);
2086 	COMPARE_PARAM(tids.etid_base, etid_base);
2087 	COMPARE_PARAM(tids.etid_end, etid_end);
2088 	COMPARE_PARAM(tids.netids, netids);
2089 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2090 	COMPARE_PARAM(params.ethoffload, ethoffload);
2091 	COMPARE_PARAM(tids.natids, natids);
2092 	COMPARE_PARAM(tids.stid_base, stid_base);
2093 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2094 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2095 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2096 	COMPARE_PARAM(vres.stag.start, stag_start);
2097 	COMPARE_PARAM(vres.stag.size, stag_size);
2098 	COMPARE_PARAM(vres.rq.start, rq_start);
2099 	COMPARE_PARAM(vres.rq.size, rq_size);
2100 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2101 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2102 	COMPARE_PARAM(vres.qp.start, qp_start);
2103 	COMPARE_PARAM(vres.qp.size, qp_size);
2104 	COMPARE_PARAM(vres.cq.start, cq_start);
2105 	COMPARE_PARAM(vres.cq.size, cq_size);
2106 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2107 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2108 	COMPARE_PARAM(vres.srq.start, srq_start);
2109 	COMPARE_PARAM(vres.srq.size, srq_size);
2110 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2111 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2112 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2113 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2114 	COMPARE_PARAM(vres.key.start, key_start);
2115 	COMPARE_PARAM(vres.key.size, key_size);
2116 #undef COMPARE_PARAM
2117 
2118 	return (rc);
2119 }
2120 
2121 static int
2122 t4_resume(device_t dev)
2123 {
2124 	struct adapter *sc = device_get_softc(dev);
2125 	struct adapter_pre_reset_state *old_state = NULL;
2126 	struct port_info *pi;
2127 	struct vi_info *vi;
2128 	struct ifnet *ifp;
2129 	struct sge_txq *txq;
2130 	int rc, i, j, k;
2131 
2132 	CH_ALERT(sc, "resume requested.\n");
2133 
2134 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4res");
2135 	if (rc != 0)
2136 		return (ENXIO);
2137 	MPASS(hw_off_limits(sc));
2138 	MPASS((sc->flags & FW_OK) == 0);
2139 	MPASS((sc->flags & MASTER_PF) == 0);
2140 	MPASS(sc->reset_thread == NULL);
2141 	sc->reset_thread = curthread;
2142 
2143 	/* Register access is expected to work by the time we're here. */
2144 	if (t4_read_reg(sc, A_PL_WHOAMI) == 0xffffffff) {
2145 		CH_ERR(sc, "%s: can't read device registers\n", __func__);
2146 		rc = ENXIO;
2147 		goto done;
2148 	}
2149 
2150 	/* Restore memory window. */
2151 	setup_memwin(sc);
2152 
2153 	/* Go no further if recovery mode has been requested. */
2154 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2155 		CH_ALERT(sc, "recovery mode on resume.\n");
2156 		rc = 0;
2157 		mtx_lock(&sc->reg_lock);
2158 		sc->flags &= ~HW_OFF_LIMITS;
2159 		mtx_unlock(&sc->reg_lock);
2160 		goto done;
2161 	}
2162 
2163 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2164 	save_caps_and_params(sc, old_state);
2165 
2166 	/* Reestablish contact with firmware and become the primary PF. */
2167 	rc = contact_firmware(sc);
2168 	if (rc != 0)
2169 		goto done; /* error message displayed already */
2170 	MPASS(sc->flags & FW_OK);
2171 
2172 	if (sc->flags & MASTER_PF) {
2173 		rc = partition_resources(sc);
2174 		if (rc != 0)
2175 			goto done; /* error message displayed already */
2176 		t4_intr_clear(sc);
2177 	}
2178 
2179 	rc = get_params__post_init(sc);
2180 	if (rc != 0)
2181 		goto done; /* error message displayed already */
2182 
2183 	rc = set_params__post_init(sc);
2184 	if (rc != 0)
2185 		goto done; /* error message displayed already */
2186 
2187 	rc = compare_caps_and_params(sc, old_state);
2188 	if (rc != 0)
2189 		goto done; /* error message displayed already */
2190 
2191 	for_each_port(sc, i) {
2192 		pi = sc->port[i];
2193 		MPASS(pi != NULL);
2194 		MPASS(pi->vi != NULL);
2195 		MPASS(pi->vi[0].dev == pi->dev);
2196 
2197 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2198 		if (rc != 0) {
2199 			CH_ERR(sc,
2200 			    "failed to re-initialize port %d: %d\n", i, rc);
2201 			goto done;
2202 		}
2203 		MPASS(sc->chan_map[pi->tx_chan] == i);
2204 
2205 		PORT_LOCK(pi);
2206 		fixup_link_config(pi);
2207 		build_medialist(pi);
2208 		PORT_UNLOCK(pi);
2209 		for_each_vi(pi, j, vi) {
2210 			if (IS_MAIN_VI(vi))
2211 				continue;
2212 			rc = alloc_extra_vi(sc, pi, vi);
2213 			if (rc != 0) {
2214 				CH_ERR(vi,
2215 				    "failed to re-allocate extra VI: %d\n", rc);
2216 				goto done;
2217 			}
2218 		}
2219 	}
2220 
2221 	/*
2222 	 * Interrupts and queues are about to be enabled and other threads will
2223 	 * want to access the hardware too.  It is safe to do so.  Note that
2224 	 * this thread is still in the middle of a synchronized_op.
2225 	 */
2226 	mtx_lock(&sc->reg_lock);
2227 	sc->flags &= ~HW_OFF_LIMITS;
2228 	mtx_unlock(&sc->reg_lock);
2229 
2230 	if (sc->flags & FULL_INIT_DONE) {
2231 		rc = adapter_full_init(sc);
2232 		if (rc != 0) {
2233 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2234 			goto done;
2235 		}
2236 
2237 		if (sc->vxlan_refcount > 0)
2238 			enable_vxlan_rx(sc);
2239 
2240 		for_each_port(sc, i) {
2241 			pi = sc->port[i];
2242 			for_each_vi(pi, j, vi) {
2243 				if (!(vi->flags & VI_INIT_DONE))
2244 					continue;
2245 				rc = vi_full_init(vi);
2246 				if (rc != 0) {
2247 					CH_ERR(vi, "failed to re-initialize "
2248 					    "interface: %d\n", rc);
2249 					goto done;
2250 				}
2251 
2252 				ifp = vi->ifp;
2253 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2254 					continue;
2255 				/*
2256 				 * Note that we do not setup multicast addresses
2257 				 * in the first pass.  This ensures that the
2258 				 * unicast DMACs for all VIs on all ports get an
2259 				 * MPS TCAM entry.
2260 				 */
2261 				rc = update_mac_settings(ifp, XGMAC_ALL &
2262 				    ~XGMAC_MCADDRS);
2263 				if (rc != 0) {
2264 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2265 					goto done;
2266 				}
2267 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2268 				    true);
2269 				if (rc != 0) {
2270 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2271 					goto done;
2272 				}
2273 				for_each_txq(vi, k, txq) {
2274 					TXQ_LOCK(txq);
2275 					txq->eq.flags |= EQ_ENABLED;
2276 					TXQ_UNLOCK(txq);
2277 				}
2278 				mtx_lock(&vi->tick_mtx);
2279 				vi->flags &= ~VI_SKIP_STATS;
2280 				callout_schedule(&vi->tick, hz);
2281 				mtx_unlock(&vi->tick_mtx);
2282 			}
2283 			PORT_LOCK(pi);
2284 			if (pi->up_vis > 0) {
2285 				t4_update_port_info(pi);
2286 				fixup_link_config(pi);
2287 				build_medialist(pi);
2288 				apply_link_config(pi);
2289 				if (pi->link_cfg.link_ok)
2290 					t4_os_link_changed(pi);
2291 			}
2292 			PORT_UNLOCK(pi);
2293 		}
2294 
2295 		/* Now reprogram the L2 multicast addresses. */
2296 		for_each_port(sc, i) {
2297 			pi = sc->port[i];
2298 			for_each_vi(pi, j, vi) {
2299 				if (!(vi->flags & VI_INIT_DONE))
2300 					continue;
2301 				ifp = vi->ifp;
2302 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2303 					continue;
2304 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2305 				if (rc != 0) {
2306 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2307 					rc = 0;	/* carry on */
2308 				}
2309 			}
2310 		}
2311 	}
2312 done:
2313 	if (rc == 0) {
2314 		sc->incarnation++;
2315 		CH_ALERT(sc, "resume completed.\n");
2316 	}
2317 	end_synchronized_op(sc, 0);
2318 	free(old_state, M_CXGBE);
2319 	return (rc);
2320 }
2321 
2322 static int
2323 t4_reset_prepare(device_t dev, device_t child)
2324 {
2325 	struct adapter *sc = device_get_softc(dev);
2326 
2327 	CH_ALERT(sc, "reset_prepare.\n");
2328 	return (0);
2329 }
2330 
2331 static int
2332 t4_reset_post(device_t dev, device_t child)
2333 {
2334 	struct adapter *sc = device_get_softc(dev);
2335 
2336 	CH_ALERT(sc, "reset_post.\n");
2337 	return (0);
2338 }
2339 
2340 static void
2341 reset_adapter(void *arg, int pending)
2342 {
2343 	struct adapter *sc = arg;
2344 	int rc;
2345 
2346 	CH_ALERT(sc, "reset requested.\n");
2347 
2348 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst1");
2349 	if (rc != 0)
2350 		return;
2351 
2352 	if (hw_off_limits(sc)) {
2353 		CH_ERR(sc, "adapter is suspended, use resume (not reset).\n");
2354 		rc = ENXIO;
2355 		goto done;
2356 	}
2357 
2358 	if (!ok_to_reset(sc)) {
2359 		/* XXX: should list what resource is preventing reset. */
2360 		CH_ERR(sc, "not safe to reset.\n");
2361 		rc = EBUSY;
2362 		goto done;
2363 	}
2364 
2365 done:
2366 	end_synchronized_op(sc, 0);
2367 	if (rc != 0)
2368 		return;	/* Error logged already. */
2369 
2370 	mtx_lock(&Giant);
2371 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2372 	mtx_unlock(&Giant);
2373 	if (rc != 0)
2374 		CH_ERR(sc, "bus_reset_child failed: %d.\n", rc);
2375 	else
2376 		CH_ALERT(sc, "bus_reset_child succeeded.\n");
2377 }
2378 
2379 static int
2380 cxgbe_probe(device_t dev)
2381 {
2382 	char buf[128];
2383 	struct port_info *pi = device_get_softc(dev);
2384 
2385 	snprintf(buf, sizeof(buf), "port %d", pi->port_id);
2386 	device_set_desc_copy(dev, buf);
2387 
2388 	return (BUS_PROBE_DEFAULT);
2389 }
2390 
2391 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2392     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2393     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2394     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2395 #define T4_CAP_ENABLE (T4_CAP)
2396 
2397 static int
2398 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2399 {
2400 	struct ifnet *ifp;
2401 	struct sbuf *sb;
2402 	struct sysctl_ctx_list *ctx;
2403 	struct sysctl_oid_list *children;
2404 	struct pfil_head_args pa;
2405 	struct adapter *sc = vi->adapter;
2406 
2407 	ctx = device_get_sysctl_ctx(vi->dev);
2408 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2409 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2410 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2411 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2412 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2413 #ifdef DEV_NETMAP
2414 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2415 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2416 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2417 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2418 #endif
2419 #ifdef TCP_OFFLOAD
2420 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2421 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2422 #endif
2423 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2424 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2425 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2426 #endif
2427 
2428 	vi->xact_addr_filt = -1;
2429 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2430 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2431 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2432 		vi->flags |= TX_USES_VM_WR;
2433 
2434 	/* Allocate an ifnet and set it up */
2435 	ifp = if_alloc_dev(IFT_ETHER, dev);
2436 	if (ifp == NULL) {
2437 		device_printf(dev, "Cannot allocate ifnet\n");
2438 		return (ENOMEM);
2439 	}
2440 	vi->ifp = ifp;
2441 	ifp->if_softc = vi;
2442 
2443 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2444 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
2445 
2446 	ifp->if_init = cxgbe_init;
2447 	ifp->if_ioctl = cxgbe_ioctl;
2448 	ifp->if_transmit = cxgbe_transmit;
2449 	ifp->if_qflush = cxgbe_qflush;
2450 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2451 		ifp->if_get_counter = vi_get_counter;
2452 	else
2453 		ifp->if_get_counter = cxgbe_get_counter;
2454 #if defined(KERN_TLS) || defined(RATELIMIT)
2455 	ifp->if_snd_tag_alloc = cxgbe_snd_tag_alloc;
2456 	ifp->if_snd_tag_modify = cxgbe_snd_tag_modify;
2457 	ifp->if_snd_tag_query = cxgbe_snd_tag_query;
2458 	ifp->if_snd_tag_free = cxgbe_snd_tag_free;
2459 #endif
2460 #ifdef RATELIMIT
2461 	ifp->if_ratelimit_query = cxgbe_ratelimit_query;
2462 #endif
2463 
2464 	ifp->if_capabilities = T4_CAP;
2465 	ifp->if_capenable = T4_CAP_ENABLE;
2466 	ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2467 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6;
2468 	if (chip_id(sc) >= CHELSIO_T6) {
2469 		ifp->if_capabilities |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2470 		ifp->if_capenable |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2471 		ifp->if_hwassist |= CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2472 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2473 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN;
2474 	}
2475 
2476 #ifdef TCP_OFFLOAD
2477 	if (vi->nofldrxq != 0)
2478 		ifp->if_capabilities |= IFCAP_TOE;
2479 #endif
2480 #ifdef RATELIMIT
2481 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2482 		ifp->if_capabilities |= IFCAP_TXRTLMT;
2483 		ifp->if_capenable |= IFCAP_TXRTLMT;
2484 	}
2485 #endif
2486 
2487 	ifp->if_hw_tsomax = IP_MAXPACKET;
2488 	if (vi->flags & TX_USES_VM_WR)
2489 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
2490 	else
2491 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
2492 #ifdef RATELIMIT
2493 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2494 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_EO_TSO;
2495 #endif
2496 	ifp->if_hw_tsomaxsegsize = 65536;
2497 #ifdef KERN_TLS
2498 	if (is_ktls(sc)) {
2499 		ifp->if_capabilities |= IFCAP_TXTLS;
2500 		if (sc->flags & KERN_TLS_ON)
2501 			ifp->if_capenable |= IFCAP_TXTLS;
2502 	}
2503 #endif
2504 
2505 	ether_ifattach(ifp, vi->hw_addr);
2506 #ifdef DEV_NETMAP
2507 	if (vi->nnmrxq != 0)
2508 		cxgbe_nm_attach(vi);
2509 #endif
2510 	sb = sbuf_new_auto();
2511 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2512 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2513 	switch (ifp->if_capabilities & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2514 	case IFCAP_TOE:
2515 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2516 		break;
2517 	case IFCAP_TOE | IFCAP_TXRTLMT:
2518 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2519 		break;
2520 	case IFCAP_TXRTLMT:
2521 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2522 		break;
2523 	}
2524 #endif
2525 #ifdef TCP_OFFLOAD
2526 	if (ifp->if_capabilities & IFCAP_TOE)
2527 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2528 #endif
2529 #ifdef DEV_NETMAP
2530 	if (ifp->if_capabilities & IFCAP_NETMAP)
2531 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2532 		    vi->nnmtxq, vi->nnmrxq);
2533 #endif
2534 	sbuf_finish(sb);
2535 	device_printf(dev, "%s\n", sbuf_data(sb));
2536 	sbuf_delete(sb);
2537 
2538 	vi_sysctls(vi);
2539 
2540 	pa.pa_version = PFIL_VERSION;
2541 	pa.pa_flags = PFIL_IN;
2542 	pa.pa_type = PFIL_TYPE_ETHERNET;
2543 	pa.pa_headname = ifp->if_xname;
2544 	vi->pfil = pfil_head_register(&pa);
2545 
2546 	return (0);
2547 }
2548 
2549 static int
2550 cxgbe_attach(device_t dev)
2551 {
2552 	struct port_info *pi = device_get_softc(dev);
2553 	struct adapter *sc = pi->adapter;
2554 	struct vi_info *vi;
2555 	int i, rc;
2556 
2557 	rc = cxgbe_vi_attach(dev, &pi->vi[0]);
2558 	if (rc)
2559 		return (rc);
2560 
2561 	for_each_vi(pi, i, vi) {
2562 		if (i == 0)
2563 			continue;
2564 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
2565 		if (vi->dev == NULL) {
2566 			device_printf(dev, "failed to add VI %d\n", i);
2567 			continue;
2568 		}
2569 		device_set_softc(vi->dev, vi);
2570 	}
2571 
2572 	cxgbe_sysctls(pi);
2573 
2574 	bus_generic_attach(dev);
2575 
2576 	return (0);
2577 }
2578 
2579 static void
2580 cxgbe_vi_detach(struct vi_info *vi)
2581 {
2582 	struct ifnet *ifp = vi->ifp;
2583 
2584 	if (vi->pfil != NULL) {
2585 		pfil_head_unregister(vi->pfil);
2586 		vi->pfil = NULL;
2587 	}
2588 
2589 	ether_ifdetach(ifp);
2590 
2591 	/* Let detach proceed even if these fail. */
2592 #ifdef DEV_NETMAP
2593 	if (ifp->if_capabilities & IFCAP_NETMAP)
2594 		cxgbe_nm_detach(vi);
2595 #endif
2596 	cxgbe_uninit_synchronized(vi);
2597 	callout_drain(&vi->tick);
2598 	vi_full_uninit(vi);
2599 
2600 	if_free(vi->ifp);
2601 	vi->ifp = NULL;
2602 }
2603 
2604 static int
2605 cxgbe_detach(device_t dev)
2606 {
2607 	struct port_info *pi = device_get_softc(dev);
2608 	struct adapter *sc = pi->adapter;
2609 	int rc;
2610 
2611 	/* Detach the extra VIs first. */
2612 	rc = bus_generic_detach(dev);
2613 	if (rc)
2614 		return (rc);
2615 	device_delete_children(dev);
2616 
2617 	doom_vi(sc, &pi->vi[0]);
2618 
2619 	if (pi->flags & HAS_TRACEQ) {
2620 		sc->traceq = -1;	/* cloner should not create ifnet */
2621 		t4_tracer_port_detach(sc);
2622 	}
2623 
2624 	cxgbe_vi_detach(&pi->vi[0]);
2625 	ifmedia_removeall(&pi->media);
2626 
2627 	end_synchronized_op(sc, 0);
2628 
2629 	return (0);
2630 }
2631 
2632 static void
2633 cxgbe_init(void *arg)
2634 {
2635 	struct vi_info *vi = arg;
2636 	struct adapter *sc = vi->adapter;
2637 
2638 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2639 		return;
2640 	cxgbe_init_synchronized(vi);
2641 	end_synchronized_op(sc, 0);
2642 }
2643 
2644 static int
2645 cxgbe_ioctl(struct ifnet *ifp, unsigned long cmd, caddr_t data)
2646 {
2647 	int rc = 0, mtu, flags;
2648 	struct vi_info *vi = ifp->if_softc;
2649 	struct port_info *pi = vi->pi;
2650 	struct adapter *sc = pi->adapter;
2651 	struct ifreq *ifr = (struct ifreq *)data;
2652 	uint32_t mask;
2653 
2654 	switch (cmd) {
2655 	case SIOCSIFMTU:
2656 		mtu = ifr->ifr_mtu;
2657 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2658 			return (EINVAL);
2659 
2660 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2661 		if (rc)
2662 			return (rc);
2663 		ifp->if_mtu = mtu;
2664 		if (vi->flags & VI_INIT_DONE) {
2665 			t4_update_fl_bufsize(ifp);
2666 			if (!hw_off_limits(sc) &&
2667 			    ifp->if_drv_flags & IFF_DRV_RUNNING)
2668 				rc = update_mac_settings(ifp, XGMAC_MTU);
2669 		}
2670 		end_synchronized_op(sc, 0);
2671 		break;
2672 
2673 	case SIOCSIFFLAGS:
2674 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2675 		if (rc)
2676 			return (rc);
2677 
2678 		if (hw_off_limits(sc)) {
2679 			rc = ENXIO;
2680 			goto fail;
2681 		}
2682 
2683 		if (ifp->if_flags & IFF_UP) {
2684 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2685 				flags = vi->if_flags;
2686 				if ((ifp->if_flags ^ flags) &
2687 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2688 					rc = update_mac_settings(ifp,
2689 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2690 				}
2691 			} else {
2692 				rc = cxgbe_init_synchronized(vi);
2693 			}
2694 			vi->if_flags = ifp->if_flags;
2695 		} else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2696 			rc = cxgbe_uninit_synchronized(vi);
2697 		}
2698 		end_synchronized_op(sc, 0);
2699 		break;
2700 
2701 	case SIOCADDMULTI:
2702 	case SIOCDELMULTI:
2703 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2704 		if (rc)
2705 			return (rc);
2706 		if (!hw_off_limits(sc) && ifp->if_drv_flags & IFF_DRV_RUNNING)
2707 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2708 		end_synchronized_op(sc, 0);
2709 		break;
2710 
2711 	case SIOCSIFCAP:
2712 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2713 		if (rc)
2714 			return (rc);
2715 
2716 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
2717 		if (mask & IFCAP_TXCSUM) {
2718 			ifp->if_capenable ^= IFCAP_TXCSUM;
2719 			ifp->if_hwassist ^= (CSUM_TCP | CSUM_UDP | CSUM_IP);
2720 
2721 			if (IFCAP_TSO4 & ifp->if_capenable &&
2722 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2723 				mask &= ~IFCAP_TSO4;
2724 				ifp->if_capenable &= ~IFCAP_TSO4;
2725 				if_printf(ifp,
2726 				    "tso4 disabled due to -txcsum.\n");
2727 			}
2728 		}
2729 		if (mask & IFCAP_TXCSUM_IPV6) {
2730 			ifp->if_capenable ^= IFCAP_TXCSUM_IPV6;
2731 			ifp->if_hwassist ^= (CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2732 
2733 			if (IFCAP_TSO6 & ifp->if_capenable &&
2734 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2735 				mask &= ~IFCAP_TSO6;
2736 				ifp->if_capenable &= ~IFCAP_TSO6;
2737 				if_printf(ifp,
2738 				    "tso6 disabled due to -txcsum6.\n");
2739 			}
2740 		}
2741 		if (mask & IFCAP_RXCSUM)
2742 			ifp->if_capenable ^= IFCAP_RXCSUM;
2743 		if (mask & IFCAP_RXCSUM_IPV6)
2744 			ifp->if_capenable ^= IFCAP_RXCSUM_IPV6;
2745 
2746 		/*
2747 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2748 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2749 		 * sending a TSO request our way, so it's sufficient to toggle
2750 		 * IFCAP_TSOx only.
2751 		 */
2752 		if (mask & IFCAP_TSO4) {
2753 			if (!(IFCAP_TSO4 & ifp->if_capenable) &&
2754 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2755 				if_printf(ifp, "enable txcsum first.\n");
2756 				rc = EAGAIN;
2757 				goto fail;
2758 			}
2759 			ifp->if_capenable ^= IFCAP_TSO4;
2760 		}
2761 		if (mask & IFCAP_TSO6) {
2762 			if (!(IFCAP_TSO6 & ifp->if_capenable) &&
2763 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2764 				if_printf(ifp, "enable txcsum6 first.\n");
2765 				rc = EAGAIN;
2766 				goto fail;
2767 			}
2768 			ifp->if_capenable ^= IFCAP_TSO6;
2769 		}
2770 		if (mask & IFCAP_LRO) {
2771 #if defined(INET) || defined(INET6)
2772 			int i;
2773 			struct sge_rxq *rxq;
2774 
2775 			ifp->if_capenable ^= IFCAP_LRO;
2776 			for_each_rxq(vi, i, rxq) {
2777 				if (ifp->if_capenable & IFCAP_LRO)
2778 					rxq->iq.flags |= IQ_LRO_ENABLED;
2779 				else
2780 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2781 			}
2782 #endif
2783 		}
2784 #ifdef TCP_OFFLOAD
2785 		if (mask & IFCAP_TOE) {
2786 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TOE;
2787 
2788 			rc = toe_capability(vi, enable);
2789 			if (rc != 0)
2790 				goto fail;
2791 
2792 			ifp->if_capenable ^= mask;
2793 		}
2794 #endif
2795 		if (mask & IFCAP_VLAN_HWTAGGING) {
2796 			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
2797 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2798 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2799 		}
2800 		if (mask & IFCAP_VLAN_MTU) {
2801 			ifp->if_capenable ^= IFCAP_VLAN_MTU;
2802 
2803 			/* Need to find out how to disable auto-mtu-inflation */
2804 		}
2805 		if (mask & IFCAP_VLAN_HWTSO)
2806 			ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
2807 		if (mask & IFCAP_VLAN_HWCSUM)
2808 			ifp->if_capenable ^= IFCAP_VLAN_HWCSUM;
2809 #ifdef RATELIMIT
2810 		if (mask & IFCAP_TXRTLMT)
2811 			ifp->if_capenable ^= IFCAP_TXRTLMT;
2812 #endif
2813 		if (mask & IFCAP_HWRXTSTMP) {
2814 			int i;
2815 			struct sge_rxq *rxq;
2816 
2817 			ifp->if_capenable ^= IFCAP_HWRXTSTMP;
2818 			for_each_rxq(vi, i, rxq) {
2819 				if (ifp->if_capenable & IFCAP_HWRXTSTMP)
2820 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2821 				else
2822 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2823 			}
2824 		}
2825 		if (mask & IFCAP_MEXTPG)
2826 			ifp->if_capenable ^= IFCAP_MEXTPG;
2827 
2828 #ifdef KERN_TLS
2829 		if (mask & IFCAP_TXTLS) {
2830 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TXTLS;
2831 
2832 			rc = ktls_capability(sc, enable);
2833 			if (rc != 0)
2834 				goto fail;
2835 
2836 			ifp->if_capenable ^= (mask & IFCAP_TXTLS);
2837 		}
2838 #endif
2839 		if (mask & IFCAP_VXLAN_HWCSUM) {
2840 			ifp->if_capenable ^= IFCAP_VXLAN_HWCSUM;
2841 			ifp->if_hwassist ^= CSUM_INNER_IP6_UDP |
2842 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
2843 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP;
2844 		}
2845 		if (mask & IFCAP_VXLAN_HWTSO) {
2846 			ifp->if_capenable ^= IFCAP_VXLAN_HWTSO;
2847 			ifp->if_hwassist ^= CSUM_INNER_IP6_TSO |
2848 			    CSUM_INNER_IP_TSO;
2849 		}
2850 
2851 #ifdef VLAN_CAPABILITIES
2852 		VLAN_CAPABILITIES(ifp);
2853 #endif
2854 fail:
2855 		end_synchronized_op(sc, 0);
2856 		break;
2857 
2858 	case SIOCSIFMEDIA:
2859 	case SIOCGIFMEDIA:
2860 	case SIOCGIFXMEDIA:
2861 		ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
2862 		break;
2863 
2864 	case SIOCGI2C: {
2865 		struct ifi2creq i2c;
2866 
2867 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
2868 		if (rc != 0)
2869 			break;
2870 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
2871 			rc = EPERM;
2872 			break;
2873 		}
2874 		if (i2c.len > sizeof(i2c.data)) {
2875 			rc = EINVAL;
2876 			break;
2877 		}
2878 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
2879 		if (rc)
2880 			return (rc);
2881 		if (hw_off_limits(sc))
2882 			rc = ENXIO;
2883 		else
2884 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
2885 			    i2c.offset, i2c.len, &i2c.data[0]);
2886 		end_synchronized_op(sc, 0);
2887 		if (rc == 0)
2888 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
2889 		break;
2890 	}
2891 
2892 	default:
2893 		rc = ether_ioctl(ifp, cmd, data);
2894 	}
2895 
2896 	return (rc);
2897 }
2898 
2899 static int
2900 cxgbe_transmit(struct ifnet *ifp, struct mbuf *m)
2901 {
2902 	struct vi_info *vi = ifp->if_softc;
2903 	struct port_info *pi = vi->pi;
2904 	struct adapter *sc;
2905 	struct sge_txq *txq;
2906 	void *items[1];
2907 	int rc;
2908 
2909 	M_ASSERTPKTHDR(m);
2910 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
2911 #if defined(KERN_TLS) || defined(RATELIMIT)
2912 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
2913 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
2914 #endif
2915 
2916 	if (__predict_false(pi->link_cfg.link_ok == false)) {
2917 		m_freem(m);
2918 		return (ENETDOWN);
2919 	}
2920 
2921 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
2922 	if (__predict_false(rc != 0)) {
2923 		MPASS(m == NULL);			/* was freed already */
2924 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
2925 		return (rc);
2926 	}
2927 #ifdef RATELIMIT
2928 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG) {
2929 		if (m->m_pkthdr.snd_tag->type == IF_SND_TAG_TYPE_RATE_LIMIT)
2930 			return (ethofld_transmit(ifp, m));
2931 	}
2932 #endif
2933 
2934 	/* Select a txq. */
2935 	sc = vi->adapter;
2936 	txq = &sc->sge.txq[vi->first_txq];
2937 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
2938 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
2939 		    vi->rsrv_noflowq);
2940 
2941 	items[0] = m;
2942 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
2943 	if (__predict_false(rc != 0))
2944 		m_freem(m);
2945 
2946 	return (rc);
2947 }
2948 
2949 static void
2950 cxgbe_qflush(struct ifnet *ifp)
2951 {
2952 	struct vi_info *vi = ifp->if_softc;
2953 	struct sge_txq *txq;
2954 	int i;
2955 
2956 	/* queues do not exist if !VI_INIT_DONE. */
2957 	if (vi->flags & VI_INIT_DONE) {
2958 		for_each_txq(vi, i, txq) {
2959 			TXQ_LOCK(txq);
2960 			txq->eq.flags |= EQ_QFLUSH;
2961 			TXQ_UNLOCK(txq);
2962 			while (!mp_ring_is_idle(txq->r)) {
2963 				mp_ring_check_drainage(txq->r, 4096);
2964 				pause("qflush", 1);
2965 			}
2966 			TXQ_LOCK(txq);
2967 			txq->eq.flags &= ~EQ_QFLUSH;
2968 			TXQ_UNLOCK(txq);
2969 		}
2970 	}
2971 	if_qflush(ifp);
2972 }
2973 
2974 static uint64_t
2975 vi_get_counter(struct ifnet *ifp, ift_counter c)
2976 {
2977 	struct vi_info *vi = ifp->if_softc;
2978 	struct fw_vi_stats_vf *s = &vi->stats;
2979 
2980 	mtx_lock(&vi->tick_mtx);
2981 	vi_refresh_stats(vi);
2982 	mtx_unlock(&vi->tick_mtx);
2983 
2984 	switch (c) {
2985 	case IFCOUNTER_IPACKETS:
2986 		return (s->rx_bcast_frames + s->rx_mcast_frames +
2987 		    s->rx_ucast_frames);
2988 	case IFCOUNTER_IERRORS:
2989 		return (s->rx_err_frames);
2990 	case IFCOUNTER_OPACKETS:
2991 		return (s->tx_bcast_frames + s->tx_mcast_frames +
2992 		    s->tx_ucast_frames + s->tx_offload_frames);
2993 	case IFCOUNTER_OERRORS:
2994 		return (s->tx_drop_frames);
2995 	case IFCOUNTER_IBYTES:
2996 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
2997 		    s->rx_ucast_bytes);
2998 	case IFCOUNTER_OBYTES:
2999 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3000 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3001 	case IFCOUNTER_IMCASTS:
3002 		return (s->rx_mcast_frames);
3003 	case IFCOUNTER_OMCASTS:
3004 		return (s->tx_mcast_frames);
3005 	case IFCOUNTER_OQDROPS: {
3006 		uint64_t drops;
3007 
3008 		drops = 0;
3009 		if (vi->flags & VI_INIT_DONE) {
3010 			int i;
3011 			struct sge_txq *txq;
3012 
3013 			for_each_txq(vi, i, txq)
3014 				drops += counter_u64_fetch(txq->r->dropped);
3015 		}
3016 
3017 		return (drops);
3018 
3019 	}
3020 
3021 	default:
3022 		return (if_get_counter_default(ifp, c));
3023 	}
3024 }
3025 
3026 static uint64_t
3027 cxgbe_get_counter(struct ifnet *ifp, ift_counter c)
3028 {
3029 	struct vi_info *vi = ifp->if_softc;
3030 	struct port_info *pi = vi->pi;
3031 	struct port_stats *s = &pi->stats;
3032 
3033 	mtx_lock(&vi->tick_mtx);
3034 	cxgbe_refresh_stats(vi);
3035 	mtx_unlock(&vi->tick_mtx);
3036 
3037 	switch (c) {
3038 	case IFCOUNTER_IPACKETS:
3039 		return (s->rx_frames);
3040 
3041 	case IFCOUNTER_IERRORS:
3042 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3043 		    s->rx_fcs_err + s->rx_len_err);
3044 
3045 	case IFCOUNTER_OPACKETS:
3046 		return (s->tx_frames);
3047 
3048 	case IFCOUNTER_OERRORS:
3049 		return (s->tx_error_frames);
3050 
3051 	case IFCOUNTER_IBYTES:
3052 		return (s->rx_octets);
3053 
3054 	case IFCOUNTER_OBYTES:
3055 		return (s->tx_octets);
3056 
3057 	case IFCOUNTER_IMCASTS:
3058 		return (s->rx_mcast_frames);
3059 
3060 	case IFCOUNTER_OMCASTS:
3061 		return (s->tx_mcast_frames);
3062 
3063 	case IFCOUNTER_IQDROPS:
3064 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3065 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3066 		    s->rx_trunc3 + pi->tnl_cong_drops);
3067 
3068 	case IFCOUNTER_OQDROPS: {
3069 		uint64_t drops;
3070 
3071 		drops = s->tx_drop;
3072 		if (vi->flags & VI_INIT_DONE) {
3073 			int i;
3074 			struct sge_txq *txq;
3075 
3076 			for_each_txq(vi, i, txq)
3077 				drops += counter_u64_fetch(txq->r->dropped);
3078 		}
3079 
3080 		return (drops);
3081 
3082 	}
3083 
3084 	default:
3085 		return (if_get_counter_default(ifp, c));
3086 	}
3087 }
3088 
3089 #if defined(KERN_TLS) || defined(RATELIMIT)
3090 static int
3091 cxgbe_snd_tag_alloc(struct ifnet *ifp, union if_snd_tag_alloc_params *params,
3092     struct m_snd_tag **pt)
3093 {
3094 	int error;
3095 
3096 	switch (params->hdr.type) {
3097 #ifdef RATELIMIT
3098 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3099 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3100 		break;
3101 #endif
3102 #ifdef KERN_TLS
3103 	case IF_SND_TAG_TYPE_TLS:
3104 		error = cxgbe_tls_tag_alloc(ifp, params, pt);
3105 		break;
3106 #endif
3107 	default:
3108 		error = EOPNOTSUPP;
3109 	}
3110 	return (error);
3111 }
3112 
3113 static int
3114 cxgbe_snd_tag_modify(struct m_snd_tag *mst,
3115     union if_snd_tag_modify_params *params)
3116 {
3117 
3118 	switch (mst->type) {
3119 #ifdef RATELIMIT
3120 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3121 		return (cxgbe_rate_tag_modify(mst, params));
3122 #endif
3123 	default:
3124 		return (EOPNOTSUPP);
3125 	}
3126 }
3127 
3128 static int
3129 cxgbe_snd_tag_query(struct m_snd_tag *mst,
3130     union if_snd_tag_query_params *params)
3131 {
3132 
3133 	switch (mst->type) {
3134 #ifdef RATELIMIT
3135 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3136 		return (cxgbe_rate_tag_query(mst, params));
3137 #endif
3138 	default:
3139 		return (EOPNOTSUPP);
3140 	}
3141 }
3142 
3143 static void
3144 cxgbe_snd_tag_free(struct m_snd_tag *mst)
3145 {
3146 
3147 	switch (mst->type) {
3148 #ifdef RATELIMIT
3149 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3150 		cxgbe_rate_tag_free(mst);
3151 		return;
3152 #endif
3153 #ifdef KERN_TLS
3154 	case IF_SND_TAG_TYPE_TLS:
3155 		cxgbe_tls_tag_free(mst);
3156 		return;
3157 #endif
3158 	default:
3159 		panic("shouldn't get here");
3160 	}
3161 }
3162 #endif
3163 
3164 /*
3165  * The kernel picks a media from the list we had provided but we still validate
3166  * the requeste.
3167  */
3168 int
3169 cxgbe_media_change(struct ifnet *ifp)
3170 {
3171 	struct vi_info *vi = ifp->if_softc;
3172 	struct port_info *pi = vi->pi;
3173 	struct ifmedia *ifm = &pi->media;
3174 	struct link_config *lc = &pi->link_cfg;
3175 	struct adapter *sc = pi->adapter;
3176 	int rc;
3177 
3178 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3179 	if (rc != 0)
3180 		return (rc);
3181 	PORT_LOCK(pi);
3182 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3183 		/* ifconfig .. media autoselect */
3184 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3185 			rc = ENOTSUP; /* AN not supported by transceiver */
3186 			goto done;
3187 		}
3188 		lc->requested_aneg = AUTONEG_ENABLE;
3189 		lc->requested_speed = 0;
3190 		lc->requested_fc |= PAUSE_AUTONEG;
3191 	} else {
3192 		lc->requested_aneg = AUTONEG_DISABLE;
3193 		lc->requested_speed =
3194 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3195 		lc->requested_fc = 0;
3196 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3197 			lc->requested_fc |= PAUSE_RX;
3198 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3199 			lc->requested_fc |= PAUSE_TX;
3200 	}
3201 	if (pi->up_vis > 0) {
3202 		fixup_link_config(pi);
3203 		rc = apply_link_config(pi);
3204 	}
3205 done:
3206 	PORT_UNLOCK(pi);
3207 	end_synchronized_op(sc, 0);
3208 	return (rc);
3209 }
3210 
3211 /*
3212  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3213  * given speed.
3214  */
3215 static int
3216 port_mword(struct port_info *pi, uint32_t speed)
3217 {
3218 
3219 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3220 	MPASS(powerof2(speed));
3221 
3222 	switch(pi->port_type) {
3223 	case FW_PORT_TYPE_BT_SGMII:
3224 	case FW_PORT_TYPE_BT_XFI:
3225 	case FW_PORT_TYPE_BT_XAUI:
3226 		/* BaseT */
3227 		switch (speed) {
3228 		case FW_PORT_CAP32_SPEED_100M:
3229 			return (IFM_100_T);
3230 		case FW_PORT_CAP32_SPEED_1G:
3231 			return (IFM_1000_T);
3232 		case FW_PORT_CAP32_SPEED_10G:
3233 			return (IFM_10G_T);
3234 		}
3235 		break;
3236 	case FW_PORT_TYPE_KX4:
3237 		if (speed == FW_PORT_CAP32_SPEED_10G)
3238 			return (IFM_10G_KX4);
3239 		break;
3240 	case FW_PORT_TYPE_CX4:
3241 		if (speed == FW_PORT_CAP32_SPEED_10G)
3242 			return (IFM_10G_CX4);
3243 		break;
3244 	case FW_PORT_TYPE_KX:
3245 		if (speed == FW_PORT_CAP32_SPEED_1G)
3246 			return (IFM_1000_KX);
3247 		break;
3248 	case FW_PORT_TYPE_KR:
3249 	case FW_PORT_TYPE_BP_AP:
3250 	case FW_PORT_TYPE_BP4_AP:
3251 	case FW_PORT_TYPE_BP40_BA:
3252 	case FW_PORT_TYPE_KR4_100G:
3253 	case FW_PORT_TYPE_KR_SFP28:
3254 	case FW_PORT_TYPE_KR_XLAUI:
3255 		switch (speed) {
3256 		case FW_PORT_CAP32_SPEED_1G:
3257 			return (IFM_1000_KX);
3258 		case FW_PORT_CAP32_SPEED_10G:
3259 			return (IFM_10G_KR);
3260 		case FW_PORT_CAP32_SPEED_25G:
3261 			return (IFM_25G_KR);
3262 		case FW_PORT_CAP32_SPEED_40G:
3263 			return (IFM_40G_KR4);
3264 		case FW_PORT_CAP32_SPEED_50G:
3265 			return (IFM_50G_KR2);
3266 		case FW_PORT_CAP32_SPEED_100G:
3267 			return (IFM_100G_KR4);
3268 		}
3269 		break;
3270 	case FW_PORT_TYPE_FIBER_XFI:
3271 	case FW_PORT_TYPE_FIBER_XAUI:
3272 	case FW_PORT_TYPE_SFP:
3273 	case FW_PORT_TYPE_QSFP_10G:
3274 	case FW_PORT_TYPE_QSA:
3275 	case FW_PORT_TYPE_QSFP:
3276 	case FW_PORT_TYPE_CR4_QSFP:
3277 	case FW_PORT_TYPE_CR_QSFP:
3278 	case FW_PORT_TYPE_CR2_QSFP:
3279 	case FW_PORT_TYPE_SFP28:
3280 		/* Pluggable transceiver */
3281 		switch (pi->mod_type) {
3282 		case FW_PORT_MOD_TYPE_LR:
3283 			switch (speed) {
3284 			case FW_PORT_CAP32_SPEED_1G:
3285 				return (IFM_1000_LX);
3286 			case FW_PORT_CAP32_SPEED_10G:
3287 				return (IFM_10G_LR);
3288 			case FW_PORT_CAP32_SPEED_25G:
3289 				return (IFM_25G_LR);
3290 			case FW_PORT_CAP32_SPEED_40G:
3291 				return (IFM_40G_LR4);
3292 			case FW_PORT_CAP32_SPEED_50G:
3293 				return (IFM_50G_LR2);
3294 			case FW_PORT_CAP32_SPEED_100G:
3295 				return (IFM_100G_LR4);
3296 			}
3297 			break;
3298 		case FW_PORT_MOD_TYPE_SR:
3299 			switch (speed) {
3300 			case FW_PORT_CAP32_SPEED_1G:
3301 				return (IFM_1000_SX);
3302 			case FW_PORT_CAP32_SPEED_10G:
3303 				return (IFM_10G_SR);
3304 			case FW_PORT_CAP32_SPEED_25G:
3305 				return (IFM_25G_SR);
3306 			case FW_PORT_CAP32_SPEED_40G:
3307 				return (IFM_40G_SR4);
3308 			case FW_PORT_CAP32_SPEED_50G:
3309 				return (IFM_50G_SR2);
3310 			case FW_PORT_CAP32_SPEED_100G:
3311 				return (IFM_100G_SR4);
3312 			}
3313 			break;
3314 		case FW_PORT_MOD_TYPE_ER:
3315 			if (speed == FW_PORT_CAP32_SPEED_10G)
3316 				return (IFM_10G_ER);
3317 			break;
3318 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3319 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3320 			switch (speed) {
3321 			case FW_PORT_CAP32_SPEED_1G:
3322 				return (IFM_1000_CX);
3323 			case FW_PORT_CAP32_SPEED_10G:
3324 				return (IFM_10G_TWINAX);
3325 			case FW_PORT_CAP32_SPEED_25G:
3326 				return (IFM_25G_CR);
3327 			case FW_PORT_CAP32_SPEED_40G:
3328 				return (IFM_40G_CR4);
3329 			case FW_PORT_CAP32_SPEED_50G:
3330 				return (IFM_50G_CR2);
3331 			case FW_PORT_CAP32_SPEED_100G:
3332 				return (IFM_100G_CR4);
3333 			}
3334 			break;
3335 		case FW_PORT_MOD_TYPE_LRM:
3336 			if (speed == FW_PORT_CAP32_SPEED_10G)
3337 				return (IFM_10G_LRM);
3338 			break;
3339 		case FW_PORT_MOD_TYPE_NA:
3340 			MPASS(0);	/* Not pluggable? */
3341 			/* fall throough */
3342 		case FW_PORT_MOD_TYPE_ERROR:
3343 		case FW_PORT_MOD_TYPE_UNKNOWN:
3344 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3345 			break;
3346 		case FW_PORT_MOD_TYPE_NONE:
3347 			return (IFM_NONE);
3348 		}
3349 		break;
3350 	case FW_PORT_TYPE_NONE:
3351 		return (IFM_NONE);
3352 	}
3353 
3354 	return (IFM_UNKNOWN);
3355 }
3356 
3357 void
3358 cxgbe_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
3359 {
3360 	struct vi_info *vi = ifp->if_softc;
3361 	struct port_info *pi = vi->pi;
3362 	struct adapter *sc = pi->adapter;
3363 	struct link_config *lc = &pi->link_cfg;
3364 
3365 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4med") != 0)
3366 		return;
3367 	PORT_LOCK(pi);
3368 
3369 	if (pi->up_vis == 0) {
3370 		/*
3371 		 * If all the interfaces are administratively down the firmware
3372 		 * does not report transceiver changes.  Refresh port info here
3373 		 * so that ifconfig displays accurate ifmedia at all times.
3374 		 * This is the only reason we have a synchronized op in this
3375 		 * function.  Just PORT_LOCK would have been enough otherwise.
3376 		 */
3377 		t4_update_port_info(pi);
3378 		build_medialist(pi);
3379 	}
3380 
3381 	/* ifm_status */
3382 	ifmr->ifm_status = IFM_AVALID;
3383 	if (lc->link_ok == false)
3384 		goto done;
3385 	ifmr->ifm_status |= IFM_ACTIVE;
3386 
3387 	/* ifm_active */
3388 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3389 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3390 	if (lc->fc & PAUSE_RX)
3391 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3392 	if (lc->fc & PAUSE_TX)
3393 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3394 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3395 done:
3396 	PORT_UNLOCK(pi);
3397 	end_synchronized_op(sc, 0);
3398 }
3399 
3400 static int
3401 vcxgbe_probe(device_t dev)
3402 {
3403 	char buf[128];
3404 	struct vi_info *vi = device_get_softc(dev);
3405 
3406 	snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
3407 	    vi - vi->pi->vi);
3408 	device_set_desc_copy(dev, buf);
3409 
3410 	return (BUS_PROBE_DEFAULT);
3411 }
3412 
3413 static int
3414 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3415 {
3416 	int func, index, rc;
3417 	uint32_t param, val;
3418 
3419 	ASSERT_SYNCHRONIZED_OP(sc);
3420 
3421 	index = vi - pi->vi;
3422 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3423 	KASSERT(index < nitems(vi_mac_funcs),
3424 	    ("%s: VI %s doesn't have a MAC func", __func__,
3425 	    device_get_nameunit(vi->dev)));
3426 	func = vi_mac_funcs[index];
3427 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3428 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3429 	if (rc < 0) {
3430 		CH_ERR(vi, "failed to allocate virtual interface %d"
3431 		    "for port %d: %d\n", index, pi->port_id, -rc);
3432 		return (-rc);
3433 	}
3434 	vi->viid = rc;
3435 
3436 	if (vi->rss_size == 1) {
3437 		/*
3438 		 * This VI didn't get a slice of the RSS table.  Reduce the
3439 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3440 		 * configuration file (nvi, rssnvi for this PF) if this is a
3441 		 * problem.
3442 		 */
3443 		device_printf(vi->dev, "RSS table not available.\n");
3444 		vi->rss_base = 0xffff;
3445 
3446 		return (0);
3447 	}
3448 
3449 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3450 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3451 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3452 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3453 	if (rc)
3454 		vi->rss_base = 0xffff;
3455 	else {
3456 		MPASS((val >> 16) == vi->rss_size);
3457 		vi->rss_base = val & 0xffff;
3458 	}
3459 
3460 	return (0);
3461 }
3462 
3463 static int
3464 vcxgbe_attach(device_t dev)
3465 {
3466 	struct vi_info *vi;
3467 	struct port_info *pi;
3468 	struct adapter *sc;
3469 	int rc;
3470 
3471 	vi = device_get_softc(dev);
3472 	pi = vi->pi;
3473 	sc = pi->adapter;
3474 
3475 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3476 	if (rc)
3477 		return (rc);
3478 	rc = alloc_extra_vi(sc, pi, vi);
3479 	end_synchronized_op(sc, 0);
3480 	if (rc)
3481 		return (rc);
3482 
3483 	rc = cxgbe_vi_attach(dev, vi);
3484 	if (rc) {
3485 		t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3486 		return (rc);
3487 	}
3488 	return (0);
3489 }
3490 
3491 static int
3492 vcxgbe_detach(device_t dev)
3493 {
3494 	struct vi_info *vi;
3495 	struct adapter *sc;
3496 
3497 	vi = device_get_softc(dev);
3498 	sc = vi->adapter;
3499 
3500 	doom_vi(sc, vi);
3501 
3502 	cxgbe_vi_detach(vi);
3503 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3504 
3505 	end_synchronized_op(sc, 0);
3506 
3507 	return (0);
3508 }
3509 
3510 static struct callout fatal_callout;
3511 static struct taskqueue *reset_tq;
3512 
3513 static void
3514 delayed_panic(void *arg)
3515 {
3516 	struct adapter *sc = arg;
3517 
3518 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3519 }
3520 
3521 void
3522 t4_fatal_err(struct adapter *sc, bool fw_error)
3523 {
3524 
3525 	t4_shutdown_adapter(sc);
3526 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped.\n",
3527 	    device_get_nameunit(sc->dev));
3528 	if (fw_error) {
3529 		if (sc->flags & CHK_MBOX_ACCESS)
3530 			ASSERT_SYNCHRONIZED_OP(sc);
3531 		sc->flags |= ADAP_ERR;
3532 	} else {
3533 		ADAPTER_LOCK(sc);
3534 		sc->flags |= ADAP_ERR;
3535 		ADAPTER_UNLOCK(sc);
3536 	}
3537 #ifdef TCP_OFFLOAD
3538 	taskqueue_enqueue(taskqueue_thread, &sc->async_event_task);
3539 #endif
3540 
3541 	if (t4_panic_on_fatal_err) {
3542 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3543 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3544 	} else if (t4_reset_on_fatal_err) {
3545 		CH_ALERT(sc, "resetting on fatal error.\n");
3546 		taskqueue_enqueue(reset_tq, &sc->reset_task);
3547 	}
3548 }
3549 
3550 void
3551 t4_add_adapter(struct adapter *sc)
3552 {
3553 	sx_xlock(&t4_list_lock);
3554 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3555 	sx_xunlock(&t4_list_lock);
3556 }
3557 
3558 int
3559 t4_map_bars_0_and_4(struct adapter *sc)
3560 {
3561 	sc->regs_rid = PCIR_BAR(0);
3562 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3563 	    &sc->regs_rid, RF_ACTIVE);
3564 	if (sc->regs_res == NULL) {
3565 		device_printf(sc->dev, "cannot map registers.\n");
3566 		return (ENXIO);
3567 	}
3568 	sc->bt = rman_get_bustag(sc->regs_res);
3569 	sc->bh = rman_get_bushandle(sc->regs_res);
3570 	sc->mmio_len = rman_get_size(sc->regs_res);
3571 	setbit(&sc->doorbells, DOORBELL_KDB);
3572 
3573 	sc->msix_rid = PCIR_BAR(4);
3574 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3575 	    &sc->msix_rid, RF_ACTIVE);
3576 	if (sc->msix_res == NULL) {
3577 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3578 		return (ENXIO);
3579 	}
3580 
3581 	return (0);
3582 }
3583 
3584 int
3585 t4_map_bar_2(struct adapter *sc)
3586 {
3587 
3588 	/*
3589 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3590 	 * to map it if RDMA is disabled.
3591 	 */
3592 	if (is_t4(sc) && sc->rdmacaps == 0)
3593 		return (0);
3594 
3595 	sc->udbs_rid = PCIR_BAR(2);
3596 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3597 	    &sc->udbs_rid, RF_ACTIVE);
3598 	if (sc->udbs_res == NULL) {
3599 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3600 		return (ENXIO);
3601 	}
3602 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3603 
3604 	if (chip_id(sc) >= CHELSIO_T5) {
3605 		setbit(&sc->doorbells, DOORBELL_UDB);
3606 #if defined(__i386__) || defined(__amd64__)
3607 		if (t5_write_combine) {
3608 			int rc, mode;
3609 
3610 			/*
3611 			 * Enable write combining on BAR2.  This is the
3612 			 * userspace doorbell BAR and is split into 128B
3613 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3614 			 * with an egress queue.  The first 64B has the doorbell
3615 			 * and the second 64B can be used to submit a tx work
3616 			 * request with an implicit doorbell.
3617 			 */
3618 
3619 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3620 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3621 			if (rc == 0) {
3622 				clrbit(&sc->doorbells, DOORBELL_UDB);
3623 				setbit(&sc->doorbells, DOORBELL_WCWR);
3624 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3625 			} else {
3626 				device_printf(sc->dev,
3627 				    "couldn't enable write combining: %d\n",
3628 				    rc);
3629 			}
3630 
3631 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3632 			t4_write_reg(sc, A_SGE_STAT_CFG,
3633 			    V_STATSOURCE_T5(7) | mode);
3634 		}
3635 #endif
3636 	}
3637 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3638 
3639 	return (0);
3640 }
3641 
3642 struct memwin_init {
3643 	uint32_t base;
3644 	uint32_t aperture;
3645 };
3646 
3647 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3648 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3649 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3650 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3651 };
3652 
3653 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3654 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3655 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3656 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3657 };
3658 
3659 static void
3660 setup_memwin(struct adapter *sc)
3661 {
3662 	const struct memwin_init *mw_init;
3663 	struct memwin *mw;
3664 	int i;
3665 	uint32_t bar0;
3666 
3667 	if (is_t4(sc)) {
3668 		/*
3669 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3670 		 * mechanism.  Works from within PCI passthrough environments
3671 		 * too, where rman_get_start() can return a different value.  We
3672 		 * need to program the T4 memory window decoders with the actual
3673 		 * addresses that will be coming across the PCIe link.
3674 		 */
3675 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3676 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3677 
3678 		mw_init = &t4_memwin[0];
3679 	} else {
3680 		/* T5+ use the relative offset inside the PCIe BAR */
3681 		bar0 = 0;
3682 
3683 		mw_init = &t5_memwin[0];
3684 	}
3685 
3686 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3687 		if (!rw_initialized(&mw->mw_lock)) {
3688 			rw_init(&mw->mw_lock, "memory window access");
3689 			mw->mw_base = mw_init->base;
3690 			mw->mw_aperture = mw_init->aperture;
3691 			mw->mw_curpos = 0;
3692 		}
3693 		t4_write_reg(sc,
3694 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3695 		    (mw->mw_base + bar0) | V_BIR(0) |
3696 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3697 		rw_wlock(&mw->mw_lock);
3698 		position_memwin(sc, i, mw->mw_curpos);
3699 		rw_wunlock(&mw->mw_lock);
3700 	}
3701 
3702 	/* flush */
3703 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3704 }
3705 
3706 /*
3707  * Positions the memory window at the given address in the card's address space.
3708  * There are some alignment requirements and the actual position may be at an
3709  * address prior to the requested address.  mw->mw_curpos always has the actual
3710  * position of the window.
3711  */
3712 static void
3713 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3714 {
3715 	struct memwin *mw;
3716 	uint32_t pf;
3717 	uint32_t reg;
3718 
3719 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3720 	mw = &sc->memwin[idx];
3721 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3722 
3723 	if (is_t4(sc)) {
3724 		pf = 0;
3725 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3726 	} else {
3727 		pf = V_PFNUM(sc->pf);
3728 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3729 	}
3730 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3731 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3732 	t4_read_reg(sc, reg);	/* flush */
3733 }
3734 
3735 int
3736 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3737     int len, int rw)
3738 {
3739 	struct memwin *mw;
3740 	uint32_t mw_end, v;
3741 
3742 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3743 
3744 	/* Memory can only be accessed in naturally aligned 4 byte units */
3745 	if (addr & 3 || len & 3 || len <= 0)
3746 		return (EINVAL);
3747 
3748 	mw = &sc->memwin[idx];
3749 	while (len > 0) {
3750 		rw_rlock(&mw->mw_lock);
3751 		mw_end = mw->mw_curpos + mw->mw_aperture;
3752 		if (addr >= mw_end || addr < mw->mw_curpos) {
3753 			/* Will need to reposition the window */
3754 			if (!rw_try_upgrade(&mw->mw_lock)) {
3755 				rw_runlock(&mw->mw_lock);
3756 				rw_wlock(&mw->mw_lock);
3757 			}
3758 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3759 			position_memwin(sc, idx, addr);
3760 			rw_downgrade(&mw->mw_lock);
3761 			mw_end = mw->mw_curpos + mw->mw_aperture;
3762 		}
3763 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3764 		while (addr < mw_end && len > 0) {
3765 			if (rw == 0) {
3766 				v = t4_read_reg(sc, mw->mw_base + addr -
3767 				    mw->mw_curpos);
3768 				*val++ = le32toh(v);
3769 			} else {
3770 				v = *val++;
3771 				t4_write_reg(sc, mw->mw_base + addr -
3772 				    mw->mw_curpos, htole32(v));
3773 			}
3774 			addr += 4;
3775 			len -= 4;
3776 		}
3777 		rw_runlock(&mw->mw_lock);
3778 	}
3779 
3780 	return (0);
3781 }
3782 
3783 static void
3784 t4_init_atid_table(struct adapter *sc)
3785 {
3786 	struct tid_info *t;
3787 	int i;
3788 
3789 	t = &sc->tids;
3790 	if (t->natids == 0)
3791 		return;
3792 
3793 	MPASS(t->atid_tab == NULL);
3794 
3795 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3796 	    M_ZERO | M_WAITOK);
3797 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3798 	t->afree = t->atid_tab;
3799 	t->atids_in_use = 0;
3800 	for (i = 1; i < t->natids; i++)
3801 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3802 	t->atid_tab[t->natids - 1].next = NULL;
3803 }
3804 
3805 static void
3806 t4_free_atid_table(struct adapter *sc)
3807 {
3808 	struct tid_info *t;
3809 
3810 	t = &sc->tids;
3811 
3812 	KASSERT(t->atids_in_use == 0,
3813 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3814 
3815 	if (mtx_initialized(&t->atid_lock))
3816 		mtx_destroy(&t->atid_lock);
3817 	free(t->atid_tab, M_CXGBE);
3818 	t->atid_tab = NULL;
3819 }
3820 
3821 int
3822 alloc_atid(struct adapter *sc, void *ctx)
3823 {
3824 	struct tid_info *t = &sc->tids;
3825 	int atid = -1;
3826 
3827 	mtx_lock(&t->atid_lock);
3828 	if (t->afree) {
3829 		union aopen_entry *p = t->afree;
3830 
3831 		atid = p - t->atid_tab;
3832 		MPASS(atid <= M_TID_TID);
3833 		t->afree = p->next;
3834 		p->data = ctx;
3835 		t->atids_in_use++;
3836 	}
3837 	mtx_unlock(&t->atid_lock);
3838 	return (atid);
3839 }
3840 
3841 void *
3842 lookup_atid(struct adapter *sc, int atid)
3843 {
3844 	struct tid_info *t = &sc->tids;
3845 
3846 	return (t->atid_tab[atid].data);
3847 }
3848 
3849 void
3850 free_atid(struct adapter *sc, int atid)
3851 {
3852 	struct tid_info *t = &sc->tids;
3853 	union aopen_entry *p = &t->atid_tab[atid];
3854 
3855 	mtx_lock(&t->atid_lock);
3856 	p->next = t->afree;
3857 	t->afree = p;
3858 	t->atids_in_use--;
3859 	mtx_unlock(&t->atid_lock);
3860 }
3861 
3862 static void
3863 queue_tid_release(struct adapter *sc, int tid)
3864 {
3865 
3866 	CXGBE_UNIMPLEMENTED("deferred tid release");
3867 }
3868 
3869 void
3870 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
3871 {
3872 	struct wrqe *wr;
3873 	struct cpl_tid_release *req;
3874 
3875 	wr = alloc_wrqe(sizeof(*req), ctrlq);
3876 	if (wr == NULL) {
3877 		queue_tid_release(sc, tid);	/* defer */
3878 		return;
3879 	}
3880 	req = wrtod(wr);
3881 
3882 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
3883 
3884 	t4_wrq_tx(sc, wr);
3885 }
3886 
3887 static int
3888 t4_range_cmp(const void *a, const void *b)
3889 {
3890 	return ((const struct t4_range *)a)->start -
3891 	       ((const struct t4_range *)b)->start;
3892 }
3893 
3894 /*
3895  * Verify that the memory range specified by the addr/len pair is valid within
3896  * the card's address space.
3897  */
3898 static int
3899 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
3900 {
3901 	struct t4_range mem_ranges[4], *r, *next;
3902 	uint32_t em, addr_len;
3903 	int i, n, remaining;
3904 
3905 	/* Memory can only be accessed in naturally aligned 4 byte units */
3906 	if (addr & 3 || len & 3 || len == 0)
3907 		return (EINVAL);
3908 
3909 	/* Enabled memories */
3910 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
3911 
3912 	r = &mem_ranges[0];
3913 	n = 0;
3914 	bzero(r, sizeof(mem_ranges));
3915 	if (em & F_EDRAM0_ENABLE) {
3916 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
3917 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
3918 		if (r->size > 0) {
3919 			r->start = G_EDRAM0_BASE(addr_len) << 20;
3920 			if (addr >= r->start &&
3921 			    addr + len <= r->start + r->size)
3922 				return (0);
3923 			r++;
3924 			n++;
3925 		}
3926 	}
3927 	if (em & F_EDRAM1_ENABLE) {
3928 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
3929 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
3930 		if (r->size > 0) {
3931 			r->start = G_EDRAM1_BASE(addr_len) << 20;
3932 			if (addr >= r->start &&
3933 			    addr + len <= r->start + r->size)
3934 				return (0);
3935 			r++;
3936 			n++;
3937 		}
3938 	}
3939 	if (em & F_EXT_MEM_ENABLE) {
3940 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
3941 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
3942 		if (r->size > 0) {
3943 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
3944 			if (addr >= r->start &&
3945 			    addr + len <= r->start + r->size)
3946 				return (0);
3947 			r++;
3948 			n++;
3949 		}
3950 	}
3951 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
3952 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
3953 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
3954 		if (r->size > 0) {
3955 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
3956 			if (addr >= r->start &&
3957 			    addr + len <= r->start + r->size)
3958 				return (0);
3959 			r++;
3960 			n++;
3961 		}
3962 	}
3963 	MPASS(n <= nitems(mem_ranges));
3964 
3965 	if (n > 1) {
3966 		/* Sort and merge the ranges. */
3967 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
3968 
3969 		/* Start from index 0 and examine the next n - 1 entries. */
3970 		r = &mem_ranges[0];
3971 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
3972 
3973 			MPASS(r->size > 0);	/* r is a valid entry. */
3974 			next = r + 1;
3975 			MPASS(next->size > 0);	/* and so is the next one. */
3976 
3977 			while (r->start + r->size >= next->start) {
3978 				/* Merge the next one into the current entry. */
3979 				r->size = max(r->start + r->size,
3980 				    next->start + next->size) - r->start;
3981 				n--;	/* One fewer entry in total. */
3982 				if (--remaining == 0)
3983 					goto done;	/* short circuit */
3984 				next++;
3985 			}
3986 			if (next != r + 1) {
3987 				/*
3988 				 * Some entries were merged into r and next
3989 				 * points to the first valid entry that couldn't
3990 				 * be merged.
3991 				 */
3992 				MPASS(next->size > 0);	/* must be valid */
3993 				memcpy(r + 1, next, remaining * sizeof(*r));
3994 #ifdef INVARIANTS
3995 				/*
3996 				 * This so that the foo->size assertion in the
3997 				 * next iteration of the loop do the right
3998 				 * thing for entries that were pulled up and are
3999 				 * no longer valid.
4000 				 */
4001 				MPASS(n < nitems(mem_ranges));
4002 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4003 				    sizeof(struct t4_range));
4004 #endif
4005 			}
4006 		}
4007 done:
4008 		/* Done merging the ranges. */
4009 		MPASS(n > 0);
4010 		r = &mem_ranges[0];
4011 		for (i = 0; i < n; i++, r++) {
4012 			if (addr >= r->start &&
4013 			    addr + len <= r->start + r->size)
4014 				return (0);
4015 		}
4016 	}
4017 
4018 	return (EFAULT);
4019 }
4020 
4021 static int
4022 fwmtype_to_hwmtype(int mtype)
4023 {
4024 
4025 	switch (mtype) {
4026 	case FW_MEMTYPE_EDC0:
4027 		return (MEM_EDC0);
4028 	case FW_MEMTYPE_EDC1:
4029 		return (MEM_EDC1);
4030 	case FW_MEMTYPE_EXTMEM:
4031 		return (MEM_MC0);
4032 	case FW_MEMTYPE_EXTMEM1:
4033 		return (MEM_MC1);
4034 	default:
4035 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4036 	}
4037 }
4038 
4039 /*
4040  * Verify that the memory range specified by the memtype/offset/len pair is
4041  * valid and lies entirely within the memtype specified.  The global address of
4042  * the start of the range is returned in addr.
4043  */
4044 static int
4045 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4046     uint32_t *addr)
4047 {
4048 	uint32_t em, addr_len, maddr;
4049 
4050 	/* Memory can only be accessed in naturally aligned 4 byte units */
4051 	if (off & 3 || len & 3 || len == 0)
4052 		return (EINVAL);
4053 
4054 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4055 	switch (fwmtype_to_hwmtype(mtype)) {
4056 	case MEM_EDC0:
4057 		if (!(em & F_EDRAM0_ENABLE))
4058 			return (EINVAL);
4059 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4060 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4061 		break;
4062 	case MEM_EDC1:
4063 		if (!(em & F_EDRAM1_ENABLE))
4064 			return (EINVAL);
4065 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4066 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4067 		break;
4068 	case MEM_MC:
4069 		if (!(em & F_EXT_MEM_ENABLE))
4070 			return (EINVAL);
4071 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4072 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4073 		break;
4074 	case MEM_MC1:
4075 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4076 			return (EINVAL);
4077 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4078 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4079 		break;
4080 	default:
4081 		return (EINVAL);
4082 	}
4083 
4084 	*addr = maddr + off;	/* global address */
4085 	return (validate_mem_range(sc, *addr, len));
4086 }
4087 
4088 static int
4089 fixup_devlog_params(struct adapter *sc)
4090 {
4091 	struct devlog_params *dparams = &sc->params.devlog;
4092 	int rc;
4093 
4094 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4095 	    dparams->size, &dparams->addr);
4096 
4097 	return (rc);
4098 }
4099 
4100 static void
4101 update_nirq(struct intrs_and_queues *iaq, int nports)
4102 {
4103 
4104 	iaq->nirq = T4_EXTRA_INTR;
4105 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4106 	iaq->nirq += nports * iaq->nofldrxq;
4107 	iaq->nirq += nports * (iaq->num_vis - 1) *
4108 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4109 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4110 }
4111 
4112 /*
4113  * Adjust requirements to fit the number of interrupts available.
4114  */
4115 static void
4116 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4117     int navail)
4118 {
4119 	int old_nirq;
4120 	const int nports = sc->params.nports;
4121 
4122 	MPASS(nports > 0);
4123 	MPASS(navail > 0);
4124 
4125 	bzero(iaq, sizeof(*iaq));
4126 	iaq->intr_type = itype;
4127 	iaq->num_vis = t4_num_vis;
4128 	iaq->ntxq = t4_ntxq;
4129 	iaq->ntxq_vi = t4_ntxq_vi;
4130 	iaq->nrxq = t4_nrxq;
4131 	iaq->nrxq_vi = t4_nrxq_vi;
4132 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4133 	if (is_offload(sc) || is_ethoffload(sc)) {
4134 		iaq->nofldtxq = t4_nofldtxq;
4135 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4136 	}
4137 #endif
4138 #ifdef TCP_OFFLOAD
4139 	if (is_offload(sc)) {
4140 		iaq->nofldrxq = t4_nofldrxq;
4141 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4142 	}
4143 #endif
4144 #ifdef DEV_NETMAP
4145 	if (t4_native_netmap & NN_MAIN_VI) {
4146 		iaq->nnmtxq = t4_nnmtxq;
4147 		iaq->nnmrxq = t4_nnmrxq;
4148 	}
4149 	if (t4_native_netmap & NN_EXTRA_VI) {
4150 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4151 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4152 	}
4153 #endif
4154 
4155 	update_nirq(iaq, nports);
4156 	if (iaq->nirq <= navail &&
4157 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4158 		/*
4159 		 * This is the normal case -- there are enough interrupts for
4160 		 * everything.
4161 		 */
4162 		goto done;
4163 	}
4164 
4165 	/*
4166 	 * If extra VIs have been configured try reducing their count and see if
4167 	 * that works.
4168 	 */
4169 	while (iaq->num_vis > 1) {
4170 		iaq->num_vis--;
4171 		update_nirq(iaq, nports);
4172 		if (iaq->nirq <= navail &&
4173 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4174 			device_printf(sc->dev, "virtual interfaces per port "
4175 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4176 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4177 			    "itype %d, navail %u, nirq %d.\n",
4178 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4179 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4180 			    itype, navail, iaq->nirq);
4181 			goto done;
4182 		}
4183 	}
4184 
4185 	/*
4186 	 * Extra VIs will not be created.  Log a message if they were requested.
4187 	 */
4188 	MPASS(iaq->num_vis == 1);
4189 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4190 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4191 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4192 	if (iaq->num_vis != t4_num_vis) {
4193 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4194 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4195 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4196 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4197 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4198 	}
4199 
4200 	/*
4201 	 * Keep reducing the number of NIC rx queues to the next lower power of
4202 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4203 	 * if that works.
4204 	 */
4205 	do {
4206 		if (iaq->nrxq > 1) {
4207 			do {
4208 				iaq->nrxq--;
4209 			} while (!powerof2(iaq->nrxq));
4210 			if (iaq->nnmrxq > iaq->nrxq)
4211 				iaq->nnmrxq = iaq->nrxq;
4212 		}
4213 		if (iaq->nofldrxq > 1)
4214 			iaq->nofldrxq >>= 1;
4215 
4216 		old_nirq = iaq->nirq;
4217 		update_nirq(iaq, nports);
4218 		if (iaq->nirq <= navail &&
4219 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4220 			device_printf(sc->dev, "running with reduced number of "
4221 			    "rx queues because of shortage of interrupts.  "
4222 			    "nrxq=%u, nofldrxq=%u.  "
4223 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4224 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4225 			goto done;
4226 		}
4227 	} while (old_nirq != iaq->nirq);
4228 
4229 	/* One interrupt for everything.  Ugh. */
4230 	device_printf(sc->dev, "running with minimal number of queues.  "
4231 	    "itype %d, navail %u.\n", itype, navail);
4232 	iaq->nirq = 1;
4233 	iaq->nrxq = 1;
4234 	iaq->ntxq = 1;
4235 	if (iaq->nofldrxq > 0) {
4236 		iaq->nofldrxq = 1;
4237 		iaq->nofldtxq = 1;
4238 	}
4239 	iaq->nnmtxq = 0;
4240 	iaq->nnmrxq = 0;
4241 done:
4242 	MPASS(iaq->num_vis > 0);
4243 	if (iaq->num_vis > 1) {
4244 		MPASS(iaq->nrxq_vi > 0);
4245 		MPASS(iaq->ntxq_vi > 0);
4246 	}
4247 	MPASS(iaq->nirq > 0);
4248 	MPASS(iaq->nrxq > 0);
4249 	MPASS(iaq->ntxq > 0);
4250 	if (itype == INTR_MSI) {
4251 		MPASS(powerof2(iaq->nirq));
4252 	}
4253 }
4254 
4255 static int
4256 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4257 {
4258 	int rc, itype, navail, nalloc;
4259 
4260 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4261 
4262 		if ((itype & t4_intr_types) == 0)
4263 			continue;	/* not allowed */
4264 
4265 		if (itype == INTR_MSIX)
4266 			navail = pci_msix_count(sc->dev);
4267 		else if (itype == INTR_MSI)
4268 			navail = pci_msi_count(sc->dev);
4269 		else
4270 			navail = 1;
4271 restart:
4272 		if (navail == 0)
4273 			continue;
4274 
4275 		calculate_iaq(sc, iaq, itype, navail);
4276 		nalloc = iaq->nirq;
4277 		rc = 0;
4278 		if (itype == INTR_MSIX)
4279 			rc = pci_alloc_msix(sc->dev, &nalloc);
4280 		else if (itype == INTR_MSI)
4281 			rc = pci_alloc_msi(sc->dev, &nalloc);
4282 
4283 		if (rc == 0 && nalloc > 0) {
4284 			if (nalloc == iaq->nirq)
4285 				return (0);
4286 
4287 			/*
4288 			 * Didn't get the number requested.  Use whatever number
4289 			 * the kernel is willing to allocate.
4290 			 */
4291 			device_printf(sc->dev, "fewer vectors than requested, "
4292 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4293 			    itype, iaq->nirq, nalloc);
4294 			pci_release_msi(sc->dev);
4295 			navail = nalloc;
4296 			goto restart;
4297 		}
4298 
4299 		device_printf(sc->dev,
4300 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4301 		    itype, rc, iaq->nirq, nalloc);
4302 	}
4303 
4304 	device_printf(sc->dev,
4305 	    "failed to find a usable interrupt type.  "
4306 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4307 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4308 
4309 	return (ENXIO);
4310 }
4311 
4312 #define FW_VERSION(chip) ( \
4313     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4314     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4315     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4316     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4317 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4318 
4319 /* Just enough of fw_hdr to cover all version info. */
4320 struct fw_h {
4321 	__u8	ver;
4322 	__u8	chip;
4323 	__be16	len512;
4324 	__be32	fw_ver;
4325 	__be32	tp_microcode_ver;
4326 	__u8	intfver_nic;
4327 	__u8	intfver_vnic;
4328 	__u8	intfver_ofld;
4329 	__u8	intfver_ri;
4330 	__u8	intfver_iscsipdu;
4331 	__u8	intfver_iscsi;
4332 	__u8	intfver_fcoepdu;
4333 	__u8	intfver_fcoe;
4334 };
4335 /* Spot check a couple of fields. */
4336 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4337 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4338 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4339 
4340 struct fw_info {
4341 	uint8_t chip;
4342 	char *kld_name;
4343 	char *fw_mod_name;
4344 	struct fw_h fw_h;
4345 } fw_info[] = {
4346 	{
4347 		.chip = CHELSIO_T4,
4348 		.kld_name = "t4fw_cfg",
4349 		.fw_mod_name = "t4fw",
4350 		.fw_h = {
4351 			.chip = FW_HDR_CHIP_T4,
4352 			.fw_ver = htobe32(FW_VERSION(T4)),
4353 			.intfver_nic = FW_INTFVER(T4, NIC),
4354 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4355 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4356 			.intfver_ri = FW_INTFVER(T4, RI),
4357 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4358 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4359 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4360 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4361 		},
4362 	}, {
4363 		.chip = CHELSIO_T5,
4364 		.kld_name = "t5fw_cfg",
4365 		.fw_mod_name = "t5fw",
4366 		.fw_h = {
4367 			.chip = FW_HDR_CHIP_T5,
4368 			.fw_ver = htobe32(FW_VERSION(T5)),
4369 			.intfver_nic = FW_INTFVER(T5, NIC),
4370 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4371 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4372 			.intfver_ri = FW_INTFVER(T5, RI),
4373 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4374 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4375 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4376 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4377 		},
4378 	}, {
4379 		.chip = CHELSIO_T6,
4380 		.kld_name = "t6fw_cfg",
4381 		.fw_mod_name = "t6fw",
4382 		.fw_h = {
4383 			.chip = FW_HDR_CHIP_T6,
4384 			.fw_ver = htobe32(FW_VERSION(T6)),
4385 			.intfver_nic = FW_INTFVER(T6, NIC),
4386 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4387 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4388 			.intfver_ri = FW_INTFVER(T6, RI),
4389 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4390 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4391 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4392 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4393 		},
4394 	}
4395 };
4396 
4397 static struct fw_info *
4398 find_fw_info(int chip)
4399 {
4400 	int i;
4401 
4402 	for (i = 0; i < nitems(fw_info); i++) {
4403 		if (fw_info[i].chip == chip)
4404 			return (&fw_info[i]);
4405 	}
4406 	return (NULL);
4407 }
4408 
4409 /*
4410  * Is the given firmware API compatible with the one the driver was compiled
4411  * with?
4412  */
4413 static int
4414 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4415 {
4416 
4417 	/* short circuit if it's the exact same firmware version */
4418 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4419 		return (1);
4420 
4421 	/*
4422 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4423 	 * features that are supported in the driver.
4424 	 */
4425 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4426 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4427 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4428 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4429 		return (1);
4430 #undef SAME_INTF
4431 
4432 	return (0);
4433 }
4434 
4435 static int
4436 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4437     const struct firmware **fw)
4438 {
4439 	struct fw_info *fw_info;
4440 
4441 	*dcfg = NULL;
4442 	if (fw != NULL)
4443 		*fw = NULL;
4444 
4445 	fw_info = find_fw_info(chip_id(sc));
4446 	if (fw_info == NULL) {
4447 		device_printf(sc->dev,
4448 		    "unable to look up firmware information for chip %d.\n",
4449 		    chip_id(sc));
4450 		return (EINVAL);
4451 	}
4452 
4453 	*dcfg = firmware_get(fw_info->kld_name);
4454 	if (*dcfg != NULL) {
4455 		if (fw != NULL)
4456 			*fw = firmware_get(fw_info->fw_mod_name);
4457 		return (0);
4458 	}
4459 
4460 	return (ENOENT);
4461 }
4462 
4463 static void
4464 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4465     const struct firmware *fw)
4466 {
4467 
4468 	if (fw != NULL)
4469 		firmware_put(fw, FIRMWARE_UNLOAD);
4470 	if (dcfg != NULL)
4471 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4472 }
4473 
4474 /*
4475  * Return values:
4476  * 0 means no firmware install attempted.
4477  * ERESTART means a firmware install was attempted and was successful.
4478  * +ve errno means a firmware install was attempted but failed.
4479  */
4480 static int
4481 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4482     const struct fw_h *drv_fw, const char *reason, int *already)
4483 {
4484 	const struct firmware *cfg, *fw;
4485 	const uint32_t c = be32toh(card_fw->fw_ver);
4486 	uint32_t d, k;
4487 	int rc, fw_install;
4488 	struct fw_h bundled_fw;
4489 	bool load_attempted;
4490 
4491 	cfg = fw = NULL;
4492 	load_attempted = false;
4493 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4494 
4495 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4496 	if (t4_fw_install < 0) {
4497 		rc = load_fw_module(sc, &cfg, &fw);
4498 		if (rc != 0 || fw == NULL) {
4499 			device_printf(sc->dev,
4500 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4501 			    " will use compiled-in firmware version for"
4502 			    "hw.cxgbe.fw_install checks.\n",
4503 			    rc, cfg, fw);
4504 		} else {
4505 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4506 		}
4507 		load_attempted = true;
4508 	}
4509 	d = be32toh(bundled_fw.fw_ver);
4510 
4511 	if (reason != NULL)
4512 		goto install;
4513 
4514 	if ((sc->flags & FW_OK) == 0) {
4515 
4516 		if (c == 0xffffffff) {
4517 			reason = "missing";
4518 			goto install;
4519 		}
4520 
4521 		rc = 0;
4522 		goto done;
4523 	}
4524 
4525 	if (!fw_compatible(card_fw, &bundled_fw)) {
4526 		reason = "incompatible or unusable";
4527 		goto install;
4528 	}
4529 
4530 	if (d > c) {
4531 		reason = "older than the version bundled with this driver";
4532 		goto install;
4533 	}
4534 
4535 	if (fw_install == 2 && d != c) {
4536 		reason = "different than the version bundled with this driver";
4537 		goto install;
4538 	}
4539 
4540 	/* No reason to do anything to the firmware already on the card. */
4541 	rc = 0;
4542 	goto done;
4543 
4544 install:
4545 	rc = 0;
4546 	if ((*already)++)
4547 		goto done;
4548 
4549 	if (fw_install == 0) {
4550 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4551 		    "but the driver is prohibited from installing a firmware "
4552 		    "on the card.\n",
4553 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4554 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4555 
4556 		goto done;
4557 	}
4558 
4559 	/*
4560 	 * We'll attempt to install a firmware.  Load the module first (if it
4561 	 * hasn't been loaded already).
4562 	 */
4563 	if (!load_attempted) {
4564 		rc = load_fw_module(sc, &cfg, &fw);
4565 		if (rc != 0 || fw == NULL) {
4566 			device_printf(sc->dev,
4567 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4568 			    rc, cfg, fw);
4569 			/* carry on */
4570 		}
4571 	}
4572 	if (fw == NULL) {
4573 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4574 		    "but the driver cannot take corrective action because it "
4575 		    "is unable to load the firmware module.\n",
4576 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4577 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4578 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4579 		goto done;
4580 	}
4581 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4582 	if (k != d) {
4583 		MPASS(t4_fw_install > 0);
4584 		device_printf(sc->dev,
4585 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4586 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4587 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4588 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4589 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4590 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4591 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4592 		goto done;
4593 	}
4594 
4595 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4596 	    "installing firmware %u.%u.%u.%u on card.\n",
4597 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4598 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4599 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4600 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4601 
4602 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4603 	if (rc != 0) {
4604 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4605 	} else {
4606 		/* Installed successfully, update the cached header too. */
4607 		rc = ERESTART;
4608 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4609 	}
4610 done:
4611 	unload_fw_module(sc, cfg, fw);
4612 
4613 	return (rc);
4614 }
4615 
4616 /*
4617  * Establish contact with the firmware and attempt to become the master driver.
4618  *
4619  * A firmware will be installed to the card if needed (if the driver is allowed
4620  * to do so).
4621  */
4622 static int
4623 contact_firmware(struct adapter *sc)
4624 {
4625 	int rc, already = 0;
4626 	enum dev_state state;
4627 	struct fw_info *fw_info;
4628 	struct fw_hdr *card_fw;		/* fw on the card */
4629 	const struct fw_h *drv_fw;
4630 
4631 	fw_info = find_fw_info(chip_id(sc));
4632 	if (fw_info == NULL) {
4633 		device_printf(sc->dev,
4634 		    "unable to look up firmware information for chip %d.\n",
4635 		    chip_id(sc));
4636 		return (EINVAL);
4637 	}
4638 	drv_fw = &fw_info->fw_h;
4639 
4640 	/* Read the header of the firmware on the card */
4641 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4642 restart:
4643 	rc = -t4_get_fw_hdr(sc, card_fw);
4644 	if (rc != 0) {
4645 		device_printf(sc->dev,
4646 		    "unable to read firmware header from card's flash: %d\n",
4647 		    rc);
4648 		goto done;
4649 	}
4650 
4651 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4652 	    &already);
4653 	if (rc == ERESTART)
4654 		goto restart;
4655 	if (rc != 0)
4656 		goto done;
4657 
4658 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4659 	if (rc < 0 || state == DEV_STATE_ERR) {
4660 		rc = -rc;
4661 		device_printf(sc->dev,
4662 		    "failed to connect to the firmware: %d, %d.  "
4663 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4664 #if 0
4665 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4666 		    "not responding properly to HELLO", &already) == ERESTART)
4667 			goto restart;
4668 #endif
4669 		goto done;
4670 	}
4671 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4672 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4673 
4674 	if (rc == sc->pf) {
4675 		sc->flags |= MASTER_PF;
4676 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4677 		    NULL, &already);
4678 		if (rc == ERESTART)
4679 			rc = 0;
4680 		else if (rc != 0)
4681 			goto done;
4682 	} else if (state == DEV_STATE_UNINIT) {
4683 		/*
4684 		 * We didn't get to be the master so we definitely won't be
4685 		 * configuring the chip.  It's a bug if someone else hasn't
4686 		 * configured it already.
4687 		 */
4688 		device_printf(sc->dev, "couldn't be master(%d), "
4689 		    "device not already initialized either(%d).  "
4690 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4691 		rc = EPROTO;
4692 		goto done;
4693 	} else {
4694 		/*
4695 		 * Some other PF is the master and has configured the chip.
4696 		 * This is allowed but untested.
4697 		 */
4698 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4699 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4700 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4701 		sc->cfcsum = 0;
4702 		rc = 0;
4703 	}
4704 done:
4705 	if (rc != 0 && sc->flags & FW_OK) {
4706 		t4_fw_bye(sc, sc->mbox);
4707 		sc->flags &= ~FW_OK;
4708 	}
4709 	free(card_fw, M_CXGBE);
4710 	return (rc);
4711 }
4712 
4713 static int
4714 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4715     uint32_t mtype, uint32_t moff)
4716 {
4717 	struct fw_info *fw_info;
4718 	const struct firmware *dcfg, *rcfg = NULL;
4719 	const uint32_t *cfdata;
4720 	uint32_t cflen, addr;
4721 	int rc;
4722 
4723 	load_fw_module(sc, &dcfg, NULL);
4724 
4725 	/* Card specific interpretation of "default". */
4726 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4727 		if (pci_get_device(sc->dev) == 0x440a)
4728 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4729 		if (is_fpga(sc))
4730 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4731 	}
4732 
4733 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4734 		if (dcfg == NULL) {
4735 			device_printf(sc->dev,
4736 			    "KLD with default config is not available.\n");
4737 			rc = ENOENT;
4738 			goto done;
4739 		}
4740 		cfdata = dcfg->data;
4741 		cflen = dcfg->datasize & ~3;
4742 	} else {
4743 		char s[32];
4744 
4745 		fw_info = find_fw_info(chip_id(sc));
4746 		if (fw_info == NULL) {
4747 			device_printf(sc->dev,
4748 			    "unable to look up firmware information for chip %d.\n",
4749 			    chip_id(sc));
4750 			rc = EINVAL;
4751 			goto done;
4752 		}
4753 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4754 
4755 		rcfg = firmware_get(s);
4756 		if (rcfg == NULL) {
4757 			device_printf(sc->dev,
4758 			    "unable to load module \"%s\" for configuration "
4759 			    "profile \"%s\".\n", s, cfg_file);
4760 			rc = ENOENT;
4761 			goto done;
4762 		}
4763 		cfdata = rcfg->data;
4764 		cflen = rcfg->datasize & ~3;
4765 	}
4766 
4767 	if (cflen > FLASH_CFG_MAX_SIZE) {
4768 		device_printf(sc->dev,
4769 		    "config file too long (%d, max allowed is %d).\n",
4770 		    cflen, FLASH_CFG_MAX_SIZE);
4771 		rc = EINVAL;
4772 		goto done;
4773 	}
4774 
4775 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4776 	if (rc != 0) {
4777 		device_printf(sc->dev,
4778 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4779 		    __func__, mtype, moff, cflen, rc);
4780 		rc = EINVAL;
4781 		goto done;
4782 	}
4783 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4784 done:
4785 	if (rcfg != NULL)
4786 		firmware_put(rcfg, FIRMWARE_UNLOAD);
4787 	unload_fw_module(sc, dcfg, NULL);
4788 	return (rc);
4789 }
4790 
4791 struct caps_allowed {
4792 	uint16_t nbmcaps;
4793 	uint16_t linkcaps;
4794 	uint16_t switchcaps;
4795 	uint16_t niccaps;
4796 	uint16_t toecaps;
4797 	uint16_t rdmacaps;
4798 	uint16_t cryptocaps;
4799 	uint16_t iscsicaps;
4800 	uint16_t fcoecaps;
4801 };
4802 
4803 #define FW_PARAM_DEV(param) \
4804 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4805 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4806 #define FW_PARAM_PFVF(param) \
4807 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4808 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4809 
4810 /*
4811  * Provide a configuration profile to the firmware and have it initialize the
4812  * chip accordingly.  This may involve uploading a configuration file to the
4813  * card.
4814  */
4815 static int
4816 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4817     const struct caps_allowed *caps_allowed)
4818 {
4819 	int rc;
4820 	struct fw_caps_config_cmd caps;
4821 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
4822 
4823 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4824 	if (rc != 0) {
4825 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
4826 		return (rc);
4827 	}
4828 
4829 	bzero(&caps, sizeof(caps));
4830 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4831 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
4832 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
4833 		mtype = 0;
4834 		moff = 0;
4835 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4836 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
4837 		mtype = FW_MEMTYPE_FLASH;
4838 		moff = t4_flash_cfg_addr(sc);
4839 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4840 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4841 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4842 		    FW_LEN16(caps));
4843 	} else {
4844 		/*
4845 		 * Ask the firmware where it wants us to upload the config file.
4846 		 */
4847 		param = FW_PARAM_DEV(CF);
4848 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4849 		if (rc != 0) {
4850 			/* No support for config file?  Shouldn't happen. */
4851 			device_printf(sc->dev,
4852 			    "failed to query config file location: %d.\n", rc);
4853 			goto done;
4854 		}
4855 		mtype = G_FW_PARAMS_PARAM_Y(val);
4856 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
4857 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4858 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4859 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4860 		    FW_LEN16(caps));
4861 
4862 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
4863 		if (rc != 0) {
4864 			device_printf(sc->dev,
4865 			    "failed to upload config file to card: %d.\n", rc);
4866 			goto done;
4867 		}
4868 	}
4869 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
4870 	if (rc != 0) {
4871 		device_printf(sc->dev, "failed to pre-process config file: %d "
4872 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
4873 		goto done;
4874 	}
4875 
4876 	finicsum = be32toh(caps.finicsum);
4877 	cfcsum = be32toh(caps.cfcsum);	/* actual */
4878 	if (finicsum != cfcsum) {
4879 		device_printf(sc->dev,
4880 		    "WARNING: config file checksum mismatch: %08x %08x\n",
4881 		    finicsum, cfcsum);
4882 	}
4883 	sc->cfcsum = cfcsum;
4884 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
4885 
4886 	/*
4887 	 * Let the firmware know what features will (not) be used so it can tune
4888 	 * things accordingly.
4889 	 */
4890 #define LIMIT_CAPS(x) do { \
4891 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
4892 } while (0)
4893 	LIMIT_CAPS(nbm);
4894 	LIMIT_CAPS(link);
4895 	LIMIT_CAPS(switch);
4896 	LIMIT_CAPS(nic);
4897 	LIMIT_CAPS(toe);
4898 	LIMIT_CAPS(rdma);
4899 	LIMIT_CAPS(crypto);
4900 	LIMIT_CAPS(iscsi);
4901 	LIMIT_CAPS(fcoe);
4902 #undef LIMIT_CAPS
4903 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
4904 		/*
4905 		 * TOE and hashfilters are mutually exclusive.  It is a config
4906 		 * file or firmware bug if both are reported as available.  Try
4907 		 * to cope with the situation in non-debug builds by disabling
4908 		 * TOE.
4909 		 */
4910 		MPASS(caps.toecaps == 0);
4911 
4912 		caps.toecaps = 0;
4913 		caps.rdmacaps = 0;
4914 		caps.iscsicaps = 0;
4915 	}
4916 
4917 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4918 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
4919 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4920 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
4921 	if (rc != 0) {
4922 		device_printf(sc->dev,
4923 		    "failed to process config file: %d.\n", rc);
4924 		goto done;
4925 	}
4926 
4927 	t4_tweak_chip_settings(sc);
4928 	set_params__pre_init(sc);
4929 
4930 	/* get basic stuff going */
4931 	rc = -t4_fw_initialize(sc, sc->mbox);
4932 	if (rc != 0) {
4933 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
4934 		goto done;
4935 	}
4936 done:
4937 	return (rc);
4938 }
4939 
4940 /*
4941  * Partition chip resources for use between various PFs, VFs, etc.
4942  */
4943 static int
4944 partition_resources(struct adapter *sc)
4945 {
4946 	char cfg_file[sizeof(t4_cfg_file)];
4947 	struct caps_allowed caps_allowed;
4948 	int rc;
4949 	bool fallback;
4950 
4951 	/* Only the master driver gets to configure the chip resources. */
4952 	MPASS(sc->flags & MASTER_PF);
4953 
4954 #define COPY_CAPS(x) do { \
4955 	caps_allowed.x##caps = t4_##x##caps_allowed; \
4956 } while (0)
4957 	bzero(&caps_allowed, sizeof(caps_allowed));
4958 	COPY_CAPS(nbm);
4959 	COPY_CAPS(link);
4960 	COPY_CAPS(switch);
4961 	COPY_CAPS(nic);
4962 	COPY_CAPS(toe);
4963 	COPY_CAPS(rdma);
4964 	COPY_CAPS(crypto);
4965 	COPY_CAPS(iscsi);
4966 	COPY_CAPS(fcoe);
4967 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
4968 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
4969 retry:
4970 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
4971 	if (rc != 0 && fallback) {
4972 		device_printf(sc->dev,
4973 		    "failed (%d) to configure card with \"%s\" profile, "
4974 		    "will fall back to a basic configuration and retry.\n",
4975 		    rc, cfg_file);
4976 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
4977 		bzero(&caps_allowed, sizeof(caps_allowed));
4978 		COPY_CAPS(switch);
4979 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
4980 		fallback = false;
4981 		goto retry;
4982 	}
4983 #undef COPY_CAPS
4984 	return (rc);
4985 }
4986 
4987 /*
4988  * Retrieve parameters that are needed (or nice to have) very early.
4989  */
4990 static int
4991 get_params__pre_init(struct adapter *sc)
4992 {
4993 	int rc;
4994 	uint32_t param[2], val[2];
4995 
4996 	t4_get_version_info(sc);
4997 
4998 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
4999 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5000 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5001 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5002 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5003 
5004 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5005 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5006 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5007 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5008 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5009 
5010 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5011 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5012 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5013 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5014 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5015 
5016 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5017 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5018 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5019 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5020 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5021 
5022 	param[0] = FW_PARAM_DEV(PORTVEC);
5023 	param[1] = FW_PARAM_DEV(CCLK);
5024 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5025 	if (rc != 0) {
5026 		device_printf(sc->dev,
5027 		    "failed to query parameters (pre_init): %d.\n", rc);
5028 		return (rc);
5029 	}
5030 
5031 	sc->params.portvec = val[0];
5032 	sc->params.nports = bitcount32(val[0]);
5033 	sc->params.vpd.cclk = val[1];
5034 
5035 	/* Read device log parameters. */
5036 	rc = -t4_init_devlog_params(sc, 1);
5037 	if (rc == 0)
5038 		fixup_devlog_params(sc);
5039 	else {
5040 		device_printf(sc->dev,
5041 		    "failed to get devlog parameters: %d.\n", rc);
5042 		rc = 0;	/* devlog isn't critical for device operation */
5043 	}
5044 
5045 	return (rc);
5046 }
5047 
5048 /*
5049  * Any params that need to be set before FW_INITIALIZE.
5050  */
5051 static int
5052 set_params__pre_init(struct adapter *sc)
5053 {
5054 	int rc = 0;
5055 	uint32_t param, val;
5056 
5057 	if (chip_id(sc) >= CHELSIO_T6) {
5058 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5059 		val = 1;
5060 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5061 		/* firmwares < 1.20.1.0 do not have this param. */
5062 		if (rc == FW_EINVAL &&
5063 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5064 			rc = 0;
5065 		}
5066 		if (rc != 0) {
5067 			device_printf(sc->dev,
5068 			    "failed to enable high priority filters :%d.\n",
5069 			    rc);
5070 		}
5071 	}
5072 
5073 	/* Enable opaque VIIDs with firmwares that support it. */
5074 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5075 	val = 1;
5076 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5077 	if (rc == 0 && val == 1)
5078 		sc->params.viid_smt_extn_support = true;
5079 	else
5080 		sc->params.viid_smt_extn_support = false;
5081 
5082 	return (rc);
5083 }
5084 
5085 /*
5086  * Retrieve various parameters that are of interest to the driver.  The device
5087  * has been initialized by the firmware at this point.
5088  */
5089 static int
5090 get_params__post_init(struct adapter *sc)
5091 {
5092 	int rc;
5093 	uint32_t param[7], val[7];
5094 	struct fw_caps_config_cmd caps;
5095 
5096 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5097 	param[1] = FW_PARAM_PFVF(EQ_START);
5098 	param[2] = FW_PARAM_PFVF(FILTER_START);
5099 	param[3] = FW_PARAM_PFVF(FILTER_END);
5100 	param[4] = FW_PARAM_PFVF(L2T_START);
5101 	param[5] = FW_PARAM_PFVF(L2T_END);
5102 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5103 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5104 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5105 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5106 	if (rc != 0) {
5107 		device_printf(sc->dev,
5108 		    "failed to query parameters (post_init): %d.\n", rc);
5109 		return (rc);
5110 	}
5111 
5112 	sc->sge.iq_start = val[0];
5113 	sc->sge.eq_start = val[1];
5114 	if ((int)val[3] > (int)val[2]) {
5115 		sc->tids.ftid_base = val[2];
5116 		sc->tids.ftid_end = val[3];
5117 		sc->tids.nftids = val[3] - val[2] + 1;
5118 	}
5119 	sc->vres.l2t.start = val[4];
5120 	sc->vres.l2t.size = val[5] - val[4] + 1;
5121 	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
5122 	    ("%s: L2 table size (%u) larger than expected (%u)",
5123 	    __func__, sc->vres.l2t.size, L2T_SIZE));
5124 	sc->params.core_vdd = val[6];
5125 
5126 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5127 	param[1] = FW_PARAM_PFVF(EQ_END);
5128 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5129 	if (rc != 0) {
5130 		device_printf(sc->dev,
5131 		    "failed to query parameters (post_init2): %d.\n", rc);
5132 		return (rc);
5133 	}
5134 	MPASS((int)val[0] >= sc->sge.iq_start);
5135 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5136 	MPASS((int)val[1] >= sc->sge.eq_start);
5137 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5138 
5139 	if (chip_id(sc) >= CHELSIO_T6) {
5140 
5141 		sc->tids.tid_base = t4_read_reg(sc,
5142 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5143 
5144 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5145 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5146 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5147 		if (rc != 0) {
5148 			device_printf(sc->dev,
5149 			   "failed to query hpfilter parameters: %d.\n", rc);
5150 			return (rc);
5151 		}
5152 		if ((int)val[1] > (int)val[0]) {
5153 			sc->tids.hpftid_base = val[0];
5154 			sc->tids.hpftid_end = val[1];
5155 			sc->tids.nhpftids = val[1] - val[0] + 1;
5156 
5157 			/*
5158 			 * These should go off if the layout changes and the
5159 			 * driver needs to catch up.
5160 			 */
5161 			MPASS(sc->tids.hpftid_base == 0);
5162 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5163 		}
5164 
5165 		param[0] = FW_PARAM_PFVF(RAWF_START);
5166 		param[1] = FW_PARAM_PFVF(RAWF_END);
5167 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5168 		if (rc != 0) {
5169 			device_printf(sc->dev,
5170 			   "failed to query rawf parameters: %d.\n", rc);
5171 			return (rc);
5172 		}
5173 		if ((int)val[1] > (int)val[0]) {
5174 			sc->rawf_base = val[0];
5175 			sc->nrawf = val[1] - val[0] + 1;
5176 		}
5177 	}
5178 
5179 	/*
5180 	 * MPSBGMAP is queried separately because only recent firmwares support
5181 	 * it as a parameter and we don't want the compound query above to fail
5182 	 * on older firmwares.
5183 	 */
5184 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5185 	val[0] = 0;
5186 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5187 	if (rc == 0)
5188 		sc->params.mps_bg_map = val[0];
5189 	else
5190 		sc->params.mps_bg_map = 0;
5191 
5192 	/*
5193 	 * Determine whether the firmware supports the filter2 work request.
5194 	 * This is queried separately for the same reason as MPSBGMAP above.
5195 	 */
5196 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5197 	val[0] = 0;
5198 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5199 	if (rc == 0)
5200 		sc->params.filter2_wr_support = val[0] != 0;
5201 	else
5202 		sc->params.filter2_wr_support = 0;
5203 
5204 	/*
5205 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5206 	 * This is queried separately for the same reason as other params above.
5207 	 */
5208 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5209 	val[0] = 0;
5210 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5211 	if (rc == 0)
5212 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5213 	else
5214 		sc->params.ulptx_memwrite_dsgl = false;
5215 
5216 	/* FW_RI_FR_NSMR_TPTE_WR support */
5217 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5218 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5219 	if (rc == 0)
5220 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5221 	else
5222 		sc->params.fr_nsmr_tpte_wr_support = false;
5223 
5224 	/* Support for 512 SGL entries per FR MR. */
5225 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5226 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5227 	if (rc == 0)
5228 		sc->params.dev_512sgl_mr = val[0] != 0;
5229 	else
5230 		sc->params.dev_512sgl_mr = false;
5231 
5232 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5233 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5234 	if (rc == 0)
5235 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5236 	else
5237 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5238 
5239 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5240 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5241 	if (rc == 0) {
5242 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5243 		sc->params.nsched_cls = val[0];
5244 	} else
5245 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5246 
5247 	/* get capabilites */
5248 	bzero(&caps, sizeof(caps));
5249 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5250 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5251 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5252 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5253 	if (rc != 0) {
5254 		device_printf(sc->dev,
5255 		    "failed to get card capabilities: %d.\n", rc);
5256 		return (rc);
5257 	}
5258 
5259 #define READ_CAPS(x) do { \
5260 	sc->x = htobe16(caps.x); \
5261 } while (0)
5262 	READ_CAPS(nbmcaps);
5263 	READ_CAPS(linkcaps);
5264 	READ_CAPS(switchcaps);
5265 	READ_CAPS(niccaps);
5266 	READ_CAPS(toecaps);
5267 	READ_CAPS(rdmacaps);
5268 	READ_CAPS(cryptocaps);
5269 	READ_CAPS(iscsicaps);
5270 	READ_CAPS(fcoecaps);
5271 
5272 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5273 		MPASS(chip_id(sc) > CHELSIO_T4);
5274 		MPASS(sc->toecaps == 0);
5275 		sc->toecaps = 0;
5276 
5277 		param[0] = FW_PARAM_DEV(NTID);
5278 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5279 		if (rc != 0) {
5280 			device_printf(sc->dev,
5281 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5282 			return (rc);
5283 		}
5284 		sc->tids.ntids = val[0];
5285 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5286 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5287 			sc->tids.ntids -= sc->tids.nhpftids;
5288 		}
5289 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5290 		sc->params.hash_filter = 1;
5291 	}
5292 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5293 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5294 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5295 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5296 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5297 		if (rc != 0) {
5298 			device_printf(sc->dev,
5299 			    "failed to query NIC parameters: %d.\n", rc);
5300 			return (rc);
5301 		}
5302 		if ((int)val[1] > (int)val[0]) {
5303 			sc->tids.etid_base = val[0];
5304 			sc->tids.etid_end = val[1];
5305 			sc->tids.netids = val[1] - val[0] + 1;
5306 			sc->params.eo_wr_cred = val[2];
5307 			sc->params.ethoffload = 1;
5308 		}
5309 	}
5310 	if (sc->toecaps) {
5311 		/* query offload-related parameters */
5312 		param[0] = FW_PARAM_DEV(NTID);
5313 		param[1] = FW_PARAM_PFVF(SERVER_START);
5314 		param[2] = FW_PARAM_PFVF(SERVER_END);
5315 		param[3] = FW_PARAM_PFVF(TDDP_START);
5316 		param[4] = FW_PARAM_PFVF(TDDP_END);
5317 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5318 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5319 		if (rc != 0) {
5320 			device_printf(sc->dev,
5321 			    "failed to query TOE parameters: %d.\n", rc);
5322 			return (rc);
5323 		}
5324 		sc->tids.ntids = val[0];
5325 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5326 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5327 			sc->tids.ntids -= sc->tids.nhpftids;
5328 		}
5329 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5330 		if ((int)val[2] > (int)val[1]) {
5331 			sc->tids.stid_base = val[1];
5332 			sc->tids.nstids = val[2] - val[1] + 1;
5333 		}
5334 		sc->vres.ddp.start = val[3];
5335 		sc->vres.ddp.size = val[4] - val[3] + 1;
5336 		sc->params.ofldq_wr_cred = val[5];
5337 		sc->params.offload = 1;
5338 	} else {
5339 		/*
5340 		 * The firmware attempts memfree TOE configuration for -SO cards
5341 		 * and will report toecaps=0 if it runs out of resources (this
5342 		 * depends on the config file).  It may not report 0 for other
5343 		 * capabilities dependent on the TOE in this case.  Set them to
5344 		 * 0 here so that the driver doesn't bother tracking resources
5345 		 * that will never be used.
5346 		 */
5347 		sc->iscsicaps = 0;
5348 		sc->rdmacaps = 0;
5349 	}
5350 	if (sc->rdmacaps) {
5351 		param[0] = FW_PARAM_PFVF(STAG_START);
5352 		param[1] = FW_PARAM_PFVF(STAG_END);
5353 		param[2] = FW_PARAM_PFVF(RQ_START);
5354 		param[3] = FW_PARAM_PFVF(RQ_END);
5355 		param[4] = FW_PARAM_PFVF(PBL_START);
5356 		param[5] = FW_PARAM_PFVF(PBL_END);
5357 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5358 		if (rc != 0) {
5359 			device_printf(sc->dev,
5360 			    "failed to query RDMA parameters(1): %d.\n", rc);
5361 			return (rc);
5362 		}
5363 		sc->vres.stag.start = val[0];
5364 		sc->vres.stag.size = val[1] - val[0] + 1;
5365 		sc->vres.rq.start = val[2];
5366 		sc->vres.rq.size = val[3] - val[2] + 1;
5367 		sc->vres.pbl.start = val[4];
5368 		sc->vres.pbl.size = val[5] - val[4] + 1;
5369 
5370 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5371 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5372 		param[2] = FW_PARAM_PFVF(CQ_START);
5373 		param[3] = FW_PARAM_PFVF(CQ_END);
5374 		param[4] = FW_PARAM_PFVF(OCQ_START);
5375 		param[5] = FW_PARAM_PFVF(OCQ_END);
5376 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5377 		if (rc != 0) {
5378 			device_printf(sc->dev,
5379 			    "failed to query RDMA parameters(2): %d.\n", rc);
5380 			return (rc);
5381 		}
5382 		sc->vres.qp.start = val[0];
5383 		sc->vres.qp.size = val[1] - val[0] + 1;
5384 		sc->vres.cq.start = val[2];
5385 		sc->vres.cq.size = val[3] - val[2] + 1;
5386 		sc->vres.ocq.start = val[4];
5387 		sc->vres.ocq.size = val[5] - val[4] + 1;
5388 
5389 		param[0] = FW_PARAM_PFVF(SRQ_START);
5390 		param[1] = FW_PARAM_PFVF(SRQ_END);
5391 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5392 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5393 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5394 		if (rc != 0) {
5395 			device_printf(sc->dev,
5396 			    "failed to query RDMA parameters(3): %d.\n", rc);
5397 			return (rc);
5398 		}
5399 		sc->vres.srq.start = val[0];
5400 		sc->vres.srq.size = val[1] - val[0] + 1;
5401 		sc->params.max_ordird_qp = val[2];
5402 		sc->params.max_ird_adapter = val[3];
5403 	}
5404 	if (sc->iscsicaps) {
5405 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5406 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5407 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5408 		if (rc != 0) {
5409 			device_printf(sc->dev,
5410 			    "failed to query iSCSI parameters: %d.\n", rc);
5411 			return (rc);
5412 		}
5413 		sc->vres.iscsi.start = val[0];
5414 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5415 	}
5416 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5417 		param[0] = FW_PARAM_PFVF(TLS_START);
5418 		param[1] = FW_PARAM_PFVF(TLS_END);
5419 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5420 		if (rc != 0) {
5421 			device_printf(sc->dev,
5422 			    "failed to query TLS parameters: %d.\n", rc);
5423 			return (rc);
5424 		}
5425 		sc->vres.key.start = val[0];
5426 		sc->vres.key.size = val[1] - val[0] + 1;
5427 	}
5428 
5429 	/*
5430 	 * We've got the params we wanted to query directly from the firmware.
5431 	 * Grab some others via other means.
5432 	 */
5433 	t4_init_sge_params(sc);
5434 	t4_init_tp_params(sc);
5435 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5436 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5437 
5438 	rc = t4_verify_chip_settings(sc);
5439 	if (rc != 0)
5440 		return (rc);
5441 	t4_init_rx_buf_info(sc);
5442 
5443 	return (rc);
5444 }
5445 
5446 #ifdef KERN_TLS
5447 static void
5448 ktls_tick(void *arg)
5449 {
5450 	struct adapter *sc;
5451 	uint32_t tstamp;
5452 
5453 	sc = arg;
5454 	if (sc->flags & KERN_TLS_ON) {
5455 		tstamp = tcp_ts_getticks();
5456 		t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5457 		t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5458 	}
5459 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5460 }
5461 
5462 static int
5463 t4_config_kern_tls(struct adapter *sc, bool enable)
5464 {
5465 	int rc;
5466 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5467 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5468 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5469 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5470 
5471 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5472 	if (rc != 0) {
5473 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5474 		    enable ?  "enable" : "disable", rc);
5475 		return (rc);
5476 	}
5477 
5478 	if (enable)
5479 		sc->flags |= KERN_TLS_ON;
5480 	else
5481 		sc->flags &= ~KERN_TLS_ON;
5482 
5483 	return (rc);
5484 }
5485 #endif
5486 
5487 static int
5488 set_params__post_init(struct adapter *sc)
5489 {
5490 	uint32_t mask, param, val;
5491 #ifdef TCP_OFFLOAD
5492 	int i, v, shift;
5493 #endif
5494 
5495 	/* ask for encapsulated CPLs */
5496 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5497 	val = 1;
5498 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5499 
5500 	/* Enable 32b port caps if the firmware supports it. */
5501 	param = FW_PARAM_PFVF(PORT_CAPS32);
5502 	val = 1;
5503 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5504 		sc->params.port_caps32 = 1;
5505 
5506 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5507 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5508 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5509 	    V_MASKFILTER(val - 1));
5510 
5511 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5512 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5513 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5514 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5515 	val = 0;
5516 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5517 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5518 		    F_ATTACKFILTERENABLE);
5519 		val |= F_DROPERRORATTACK;
5520 	}
5521 	if (t4_drop_ip_fragments != 0) {
5522 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5523 		    F_FRAGMENTDROP);
5524 		val |= F_DROPERRORFRAG;
5525 	}
5526 	if (t4_drop_pkts_with_l2_errors != 0)
5527 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5528 	if (t4_drop_pkts_with_l3_errors != 0) {
5529 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5530 		    F_DROPERRORCSUMIP;
5531 	}
5532 	if (t4_drop_pkts_with_l4_errors != 0) {
5533 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5534 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5535 	}
5536 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5537 
5538 #ifdef TCP_OFFLOAD
5539 	/*
5540 	 * Override the TOE timers with user provided tunables.  This is not the
5541 	 * recommended way to change the timers (the firmware config file is) so
5542 	 * these tunables are not documented.
5543 	 *
5544 	 * All the timer tunables are in microseconds.
5545 	 */
5546 	if (t4_toe_keepalive_idle != 0) {
5547 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5548 		v &= M_KEEPALIVEIDLE;
5549 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5550 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5551 	}
5552 	if (t4_toe_keepalive_interval != 0) {
5553 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5554 		v &= M_KEEPALIVEINTVL;
5555 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5556 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5557 	}
5558 	if (t4_toe_keepalive_count != 0) {
5559 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5560 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5561 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5562 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5563 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5564 	}
5565 	if (t4_toe_rexmt_min != 0) {
5566 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5567 		v &= M_RXTMIN;
5568 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5569 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5570 	}
5571 	if (t4_toe_rexmt_max != 0) {
5572 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5573 		v &= M_RXTMAX;
5574 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5575 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5576 	}
5577 	if (t4_toe_rexmt_count != 0) {
5578 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5579 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5580 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5581 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5582 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5583 	}
5584 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5585 		if (t4_toe_rexmt_backoff[i] != -1) {
5586 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5587 			shift = (i & 3) << 3;
5588 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5589 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5590 		}
5591 	}
5592 #endif
5593 
5594 #ifdef KERN_TLS
5595 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS &&
5596 	    sc->toecaps & FW_CAPS_CONFIG_TOE) {
5597 		/*
5598 		 * Limit TOE connections to 2 reassembly "islands".  This is
5599 		 * required for TOE TLS connections to downgrade to plain TOE
5600 		 * connections if an unsupported TLS version or ciphersuite is
5601 		 * used.
5602 		 */
5603 		t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG,
5604 		    V_PASSMODE(M_PASSMODE), V_PASSMODE(2));
5605 		if (is_ktls(sc)) {
5606 			sc->tlst.inline_keys = t4_tls_inline_keys;
5607 			sc->tlst.combo_wrs = t4_tls_combo_wrs;
5608 			if (t4_kern_tls != 0)
5609 				t4_config_kern_tls(sc, true);
5610 		}
5611 	}
5612 #endif
5613 	return (0);
5614 }
5615 
5616 #undef FW_PARAM_PFVF
5617 #undef FW_PARAM_DEV
5618 
5619 static void
5620 t4_set_desc(struct adapter *sc)
5621 {
5622 	char buf[128];
5623 	struct adapter_params *p = &sc->params;
5624 
5625 	snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
5626 
5627 	device_set_desc_copy(sc->dev, buf);
5628 }
5629 
5630 static inline void
5631 ifmedia_add4(struct ifmedia *ifm, int m)
5632 {
5633 
5634 	ifmedia_add(ifm, m, 0, NULL);
5635 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5636 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5637 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5638 }
5639 
5640 /*
5641  * This is the selected media, which is not quite the same as the active media.
5642  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5643  * and active are not the same, and "media: Ethernet selected" otherwise.
5644  */
5645 static void
5646 set_current_media(struct port_info *pi)
5647 {
5648 	struct link_config *lc;
5649 	struct ifmedia *ifm;
5650 	int mword;
5651 	u_int speed;
5652 
5653 	PORT_LOCK_ASSERT_OWNED(pi);
5654 
5655 	/* Leave current media alone if it's already set to IFM_NONE. */
5656 	ifm = &pi->media;
5657 	if (ifm->ifm_cur != NULL &&
5658 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5659 		return;
5660 
5661 	lc = &pi->link_cfg;
5662 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5663 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5664 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5665 		return;
5666 	}
5667 	mword = IFM_ETHER | IFM_FDX;
5668 	if (lc->requested_fc & PAUSE_TX)
5669 		mword |= IFM_ETH_TXPAUSE;
5670 	if (lc->requested_fc & PAUSE_RX)
5671 		mword |= IFM_ETH_RXPAUSE;
5672 	if (lc->requested_speed == 0)
5673 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5674 	else
5675 		speed = lc->requested_speed;
5676 	mword |= port_mword(pi, speed_to_fwcap(speed));
5677 	ifmedia_set(ifm, mword);
5678 }
5679 
5680 /*
5681  * Returns true if the ifmedia list for the port cannot change.
5682  */
5683 static bool
5684 fixed_ifmedia(struct port_info *pi)
5685 {
5686 
5687 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5688 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5689 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5690 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5691 	    pi->port_type == FW_PORT_TYPE_KX ||
5692 	    pi->port_type == FW_PORT_TYPE_KR ||
5693 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5694 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5695 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5696 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5697 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5698 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5699 }
5700 
5701 static void
5702 build_medialist(struct port_info *pi)
5703 {
5704 	uint32_t ss, speed;
5705 	int unknown, mword, bit;
5706 	struct link_config *lc;
5707 	struct ifmedia *ifm;
5708 
5709 	PORT_LOCK_ASSERT_OWNED(pi);
5710 
5711 	if (pi->flags & FIXED_IFMEDIA)
5712 		return;
5713 
5714 	/*
5715 	 * Rebuild the ifmedia list.
5716 	 */
5717 	ifm = &pi->media;
5718 	ifmedia_removeall(ifm);
5719 	lc = &pi->link_cfg;
5720 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5721 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5722 		MPASS(ss != 0);
5723 no_media:
5724 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5725 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5726 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5727 		return;
5728 	}
5729 
5730 	unknown = 0;
5731 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5732 		speed = 1 << bit;
5733 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5734 		if (ss & speed) {
5735 			mword = port_mword(pi, speed);
5736 			if (mword == IFM_NONE) {
5737 				goto no_media;
5738 			} else if (mword == IFM_UNKNOWN)
5739 				unknown++;
5740 			else
5741 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5742 		}
5743 	}
5744 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5745 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5746 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5747 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5748 
5749 	set_current_media(pi);
5750 }
5751 
5752 /*
5753  * Initialize the requested fields in the link config based on driver tunables.
5754  */
5755 static void
5756 init_link_config(struct port_info *pi)
5757 {
5758 	struct link_config *lc = &pi->link_cfg;
5759 
5760 	PORT_LOCK_ASSERT_OWNED(pi);
5761 
5762 	lc->requested_speed = 0;
5763 
5764 	if (t4_autoneg == 0)
5765 		lc->requested_aneg = AUTONEG_DISABLE;
5766 	else if (t4_autoneg == 1)
5767 		lc->requested_aneg = AUTONEG_ENABLE;
5768 	else
5769 		lc->requested_aneg = AUTONEG_AUTO;
5770 
5771 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5772 	    PAUSE_AUTONEG);
5773 
5774 	if (t4_fec & FEC_AUTO)
5775 		lc->requested_fec = FEC_AUTO;
5776 	else if (t4_fec == 0)
5777 		lc->requested_fec = FEC_NONE;
5778 	else {
5779 		/* -1 is handled by the FEC_AUTO block above and not here. */
5780 		lc->requested_fec = t4_fec &
5781 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5782 		if (lc->requested_fec == 0)
5783 			lc->requested_fec = FEC_AUTO;
5784 	}
5785 }
5786 
5787 /*
5788  * Makes sure that all requested settings comply with what's supported by the
5789  * port.  Returns the number of settings that were invalid and had to be fixed.
5790  */
5791 static int
5792 fixup_link_config(struct port_info *pi)
5793 {
5794 	int n = 0;
5795 	struct link_config *lc = &pi->link_cfg;
5796 	uint32_t fwspeed;
5797 
5798 	PORT_LOCK_ASSERT_OWNED(pi);
5799 
5800 	/* Speed (when not autonegotiating) */
5801 	if (lc->requested_speed != 0) {
5802 		fwspeed = speed_to_fwcap(lc->requested_speed);
5803 		if ((fwspeed & lc->pcaps) == 0) {
5804 			n++;
5805 			lc->requested_speed = 0;
5806 		}
5807 	}
5808 
5809 	/* Link autonegotiation */
5810 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5811 	    lc->requested_aneg == AUTONEG_DISABLE ||
5812 	    lc->requested_aneg == AUTONEG_AUTO);
5813 	if (lc->requested_aneg == AUTONEG_ENABLE &&
5814 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5815 		n++;
5816 		lc->requested_aneg = AUTONEG_AUTO;
5817 	}
5818 
5819 	/* Flow control */
5820 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5821 	if (lc->requested_fc & PAUSE_TX &&
5822 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5823 		n++;
5824 		lc->requested_fc &= ~PAUSE_TX;
5825 	}
5826 	if (lc->requested_fc & PAUSE_RX &&
5827 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
5828 		n++;
5829 		lc->requested_fc &= ~PAUSE_RX;
5830 	}
5831 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
5832 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
5833 		n++;
5834 		lc->requested_fc |= PAUSE_AUTONEG;
5835 	}
5836 
5837 	/* FEC */
5838 	if ((lc->requested_fec & FEC_RS &&
5839 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
5840 	    (lc->requested_fec & FEC_BASER_RS &&
5841 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
5842 		n++;
5843 		lc->requested_fec = FEC_AUTO;
5844 	}
5845 
5846 	return (n);
5847 }
5848 
5849 /*
5850  * Apply the requested L1 settings, which are expected to be valid, to the
5851  * hardware.
5852  */
5853 static int
5854 apply_link_config(struct port_info *pi)
5855 {
5856 	struct adapter *sc = pi->adapter;
5857 	struct link_config *lc = &pi->link_cfg;
5858 	int rc;
5859 
5860 #ifdef INVARIANTS
5861 	ASSERT_SYNCHRONIZED_OP(sc);
5862 	PORT_LOCK_ASSERT_OWNED(pi);
5863 
5864 	if (lc->requested_aneg == AUTONEG_ENABLE)
5865 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
5866 	if (!(lc->requested_fc & PAUSE_AUTONEG))
5867 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
5868 	if (lc->requested_fc & PAUSE_TX)
5869 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
5870 	if (lc->requested_fc & PAUSE_RX)
5871 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
5872 	if (lc->requested_fec & FEC_RS)
5873 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
5874 	if (lc->requested_fec & FEC_BASER_RS)
5875 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
5876 #endif
5877 	rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
5878 	if (rc != 0) {
5879 		/* Don't complain if the VF driver gets back an EPERM. */
5880 		if (!(sc->flags & IS_VF) || rc != FW_EPERM)
5881 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
5882 	} else {
5883 		/*
5884 		 * An L1_CFG will almost always result in a link-change event if
5885 		 * the link is up, and the driver will refresh the actual
5886 		 * fec/fc/etc. when the notification is processed.  If the link
5887 		 * is down then the actual settings are meaningless.
5888 		 *
5889 		 * This takes care of the case where a change in the L1 settings
5890 		 * may not result in a notification.
5891 		 */
5892 		if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
5893 			lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
5894 	}
5895 	return (rc);
5896 }
5897 
5898 #define FW_MAC_EXACT_CHUNK	7
5899 struct mcaddr_ctx {
5900 	struct ifnet *ifp;
5901 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
5902 	uint64_t hash;
5903 	int i;
5904 	int del;
5905 	int rc;
5906 };
5907 
5908 static u_int
5909 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
5910 {
5911 	struct mcaddr_ctx *ctx = arg;
5912 	struct vi_info *vi = ctx->ifp->if_softc;
5913 	struct port_info *pi = vi->pi;
5914 	struct adapter *sc = pi->adapter;
5915 
5916 	if (ctx->rc < 0)
5917 		return (0);
5918 
5919 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
5920 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
5921 	ctx->i++;
5922 
5923 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
5924 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
5925 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
5926 		if (ctx->rc < 0) {
5927 			int j;
5928 
5929 			for (j = 0; j < ctx->i; j++) {
5930 				if_printf(ctx->ifp,
5931 				    "failed to add mc address"
5932 				    " %02x:%02x:%02x:"
5933 				    "%02x:%02x:%02x rc=%d\n",
5934 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
5935 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
5936 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
5937 				    -ctx->rc);
5938 			}
5939 			return (0);
5940 		}
5941 		ctx->del = 0;
5942 		ctx->i = 0;
5943 	}
5944 
5945 	return (1);
5946 }
5947 
5948 /*
5949  * Program the port's XGMAC based on parameters in ifnet.  The caller also
5950  * indicates which parameters should be programmed (the rest are left alone).
5951  */
5952 int
5953 update_mac_settings(struct ifnet *ifp, int flags)
5954 {
5955 	int rc = 0;
5956 	struct vi_info *vi = ifp->if_softc;
5957 	struct port_info *pi = vi->pi;
5958 	struct adapter *sc = pi->adapter;
5959 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
5960 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
5961 
5962 	ASSERT_SYNCHRONIZED_OP(sc);
5963 	KASSERT(flags, ("%s: not told what to update.", __func__));
5964 
5965 	if (flags & XGMAC_MTU)
5966 		mtu = ifp->if_mtu;
5967 
5968 	if (flags & XGMAC_PROMISC)
5969 		promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
5970 
5971 	if (flags & XGMAC_ALLMULTI)
5972 		allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
5973 
5974 	if (flags & XGMAC_VLANEX)
5975 		vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
5976 
5977 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
5978 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
5979 		    allmulti, 1, vlanex, false);
5980 		if (rc) {
5981 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
5982 			    rc);
5983 			return (rc);
5984 		}
5985 	}
5986 
5987 	if (flags & XGMAC_UCADDR) {
5988 		uint8_t ucaddr[ETHER_ADDR_LEN];
5989 
5990 		bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
5991 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
5992 		    ucaddr, true, &vi->smt_idx);
5993 		if (rc < 0) {
5994 			rc = -rc;
5995 			if_printf(ifp, "change_mac failed: %d\n", rc);
5996 			return (rc);
5997 		} else {
5998 			vi->xact_addr_filt = rc;
5999 			rc = 0;
6000 		}
6001 	}
6002 
6003 	if (flags & XGMAC_MCADDRS) {
6004 		struct epoch_tracker et;
6005 		struct mcaddr_ctx ctx;
6006 		int j;
6007 
6008 		ctx.ifp = ifp;
6009 		ctx.hash = 0;
6010 		ctx.i = 0;
6011 		ctx.del = 1;
6012 		ctx.rc = 0;
6013 		/*
6014 		 * Unlike other drivers, we accumulate list of pointers into
6015 		 * interface address lists and we need to keep it safe even
6016 		 * after if_foreach_llmaddr() returns, thus we must enter the
6017 		 * network epoch.
6018 		 */
6019 		NET_EPOCH_ENTER(et);
6020 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6021 		if (ctx.rc < 0) {
6022 			NET_EPOCH_EXIT(et);
6023 			rc = -ctx.rc;
6024 			return (rc);
6025 		}
6026 		if (ctx.i > 0) {
6027 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6028 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6029 			NET_EPOCH_EXIT(et);
6030 			if (rc < 0) {
6031 				rc = -rc;
6032 				for (j = 0; j < ctx.i; j++) {
6033 					if_printf(ifp,
6034 					    "failed to add mcast address"
6035 					    " %02x:%02x:%02x:"
6036 					    "%02x:%02x:%02x rc=%d\n",
6037 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6038 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6039 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6040 					    rc);
6041 				}
6042 				return (rc);
6043 			}
6044 			ctx.del = 0;
6045 		} else
6046 			NET_EPOCH_EXIT(et);
6047 
6048 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6049 		if (rc != 0)
6050 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6051 			    rc);
6052 		if (ctx.del == 0) {
6053 			/* We clobbered the VXLAN entry if there was one. */
6054 			pi->vxlan_tcam_entry = false;
6055 		}
6056 	}
6057 
6058 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6059 	    pi->vxlan_tcam_entry == false) {
6060 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6061 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6062 		    true);
6063 		if (rc < 0) {
6064 			rc = -rc;
6065 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6066 			    rc);
6067 		} else {
6068 			MPASS(rc == sc->rawf_base + pi->port_id);
6069 			rc = 0;
6070 			pi->vxlan_tcam_entry = true;
6071 		}
6072 	}
6073 
6074 	return (rc);
6075 }
6076 
6077 /*
6078  * {begin|end}_synchronized_op must be called from the same thread.
6079  */
6080 int
6081 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6082     char *wmesg)
6083 {
6084 	int rc, pri;
6085 
6086 #ifdef WITNESS
6087 	/* the caller thinks it's ok to sleep, but is it really? */
6088 	if (flags & SLEEP_OK)
6089 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6090 		    "begin_synchronized_op");
6091 #endif
6092 
6093 	if (INTR_OK)
6094 		pri = PCATCH;
6095 	else
6096 		pri = 0;
6097 
6098 	ADAPTER_LOCK(sc);
6099 	for (;;) {
6100 
6101 		if (vi && IS_DOOMED(vi)) {
6102 			rc = ENXIO;
6103 			goto done;
6104 		}
6105 
6106 		if (!IS_BUSY(sc)) {
6107 			rc = 0;
6108 			break;
6109 		}
6110 
6111 		if (!(flags & SLEEP_OK)) {
6112 			rc = EBUSY;
6113 			goto done;
6114 		}
6115 
6116 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6117 			rc = EINTR;
6118 			goto done;
6119 		}
6120 	}
6121 
6122 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6123 	SET_BUSY(sc);
6124 #ifdef INVARIANTS
6125 	sc->last_op = wmesg;
6126 	sc->last_op_thr = curthread;
6127 	sc->last_op_flags = flags;
6128 #endif
6129 
6130 done:
6131 	if (!(flags & HOLD_LOCK) || rc)
6132 		ADAPTER_UNLOCK(sc);
6133 
6134 	return (rc);
6135 }
6136 
6137 /*
6138  * Tell if_ioctl and if_init that the VI is going away.  This is
6139  * special variant of begin_synchronized_op and must be paired with a
6140  * call to end_synchronized_op.
6141  */
6142 void
6143 doom_vi(struct adapter *sc, struct vi_info *vi)
6144 {
6145 
6146 	ADAPTER_LOCK(sc);
6147 	SET_DOOMED(vi);
6148 	wakeup(&sc->flags);
6149 	while (IS_BUSY(sc))
6150 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6151 	SET_BUSY(sc);
6152 #ifdef INVARIANTS
6153 	sc->last_op = "t4detach";
6154 	sc->last_op_thr = curthread;
6155 	sc->last_op_flags = 0;
6156 #endif
6157 	ADAPTER_UNLOCK(sc);
6158 }
6159 
6160 /*
6161  * {begin|end}_synchronized_op must be called from the same thread.
6162  */
6163 void
6164 end_synchronized_op(struct adapter *sc, int flags)
6165 {
6166 
6167 	if (flags & LOCK_HELD)
6168 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6169 	else
6170 		ADAPTER_LOCK(sc);
6171 
6172 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6173 	CLR_BUSY(sc);
6174 	wakeup(&sc->flags);
6175 	ADAPTER_UNLOCK(sc);
6176 }
6177 
6178 static int
6179 cxgbe_init_synchronized(struct vi_info *vi)
6180 {
6181 	struct port_info *pi = vi->pi;
6182 	struct adapter *sc = pi->adapter;
6183 	struct ifnet *ifp = vi->ifp;
6184 	int rc = 0, i;
6185 	struct sge_txq *txq;
6186 
6187 	ASSERT_SYNCHRONIZED_OP(sc);
6188 
6189 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
6190 		return (0);	/* already running */
6191 
6192 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6193 		return (rc);	/* error message displayed already */
6194 
6195 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6196 		return (rc); /* error message displayed already */
6197 
6198 	rc = update_mac_settings(ifp, XGMAC_ALL);
6199 	if (rc)
6200 		goto done;	/* error message displayed already */
6201 
6202 	PORT_LOCK(pi);
6203 	if (pi->up_vis == 0) {
6204 		t4_update_port_info(pi);
6205 		fixup_link_config(pi);
6206 		build_medialist(pi);
6207 		apply_link_config(pi);
6208 	}
6209 
6210 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6211 	if (rc != 0) {
6212 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6213 		PORT_UNLOCK(pi);
6214 		goto done;
6215 	}
6216 
6217 	/*
6218 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6219 	 * if this changes.
6220 	 */
6221 
6222 	for_each_txq(vi, i, txq) {
6223 		TXQ_LOCK(txq);
6224 		txq->eq.flags |= EQ_ENABLED;
6225 		TXQ_UNLOCK(txq);
6226 	}
6227 
6228 	/*
6229 	 * The first iq of the first port to come up is used for tracing.
6230 	 */
6231 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6232 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6233 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6234 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6235 		    V_QUEUENUMBER(sc->traceq));
6236 		pi->flags |= HAS_TRACEQ;
6237 	}
6238 
6239 	/* all ok */
6240 	pi->up_vis++;
6241 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
6242 	if (pi->link_cfg.link_ok)
6243 		t4_os_link_changed(pi);
6244 	PORT_UNLOCK(pi);
6245 
6246 	mtx_lock(&vi->tick_mtx);
6247 	if (ifp->if_get_counter == vi_get_counter)
6248 		callout_reset(&vi->tick, hz, vi_tick, vi);
6249 	else
6250 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6251 	mtx_unlock(&vi->tick_mtx);
6252 done:
6253 	if (rc != 0)
6254 		cxgbe_uninit_synchronized(vi);
6255 
6256 	return (rc);
6257 }
6258 
6259 /*
6260  * Idempotent.
6261  */
6262 static int
6263 cxgbe_uninit_synchronized(struct vi_info *vi)
6264 {
6265 	struct port_info *pi = vi->pi;
6266 	struct adapter *sc = pi->adapter;
6267 	struct ifnet *ifp = vi->ifp;
6268 	int rc, i;
6269 	struct sge_txq *txq;
6270 
6271 	ASSERT_SYNCHRONIZED_OP(sc);
6272 
6273 	if (!(vi->flags & VI_INIT_DONE)) {
6274 		if (__predict_false(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6275 			KASSERT(0, ("uninited VI is running"));
6276 			if_printf(ifp, "uninited VI with running ifnet.  "
6277 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6278 			    "if_drv_flags 0x%08x\n", vi->flags, ifp->if_flags,
6279 			    ifp->if_drv_flags);
6280 		}
6281 		return (0);
6282 	}
6283 
6284 	/*
6285 	 * Disable the VI so that all its data in either direction is discarded
6286 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6287 	 * tick) intact as the TP can deliver negative advice or data that it's
6288 	 * holding in its RAM (for an offloaded connection) even after the VI is
6289 	 * disabled.
6290 	 */
6291 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6292 	if (rc) {
6293 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6294 		return (rc);
6295 	}
6296 
6297 	for_each_txq(vi, i, txq) {
6298 		TXQ_LOCK(txq);
6299 		txq->eq.flags &= ~EQ_ENABLED;
6300 		TXQ_UNLOCK(txq);
6301 	}
6302 
6303 	mtx_lock(&vi->tick_mtx);
6304 	callout_stop(&vi->tick);
6305 	mtx_unlock(&vi->tick_mtx);
6306 
6307 	PORT_LOCK(pi);
6308 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6309 		PORT_UNLOCK(pi);
6310 		return (0);
6311 	}
6312 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
6313 	pi->up_vis--;
6314 	if (pi->up_vis > 0) {
6315 		PORT_UNLOCK(pi);
6316 		return (0);
6317 	}
6318 
6319 	pi->link_cfg.link_ok = false;
6320 	pi->link_cfg.speed = 0;
6321 	pi->link_cfg.link_down_rc = 255;
6322 	t4_os_link_changed(pi);
6323 	PORT_UNLOCK(pi);
6324 
6325 	return (0);
6326 }
6327 
6328 /*
6329  * It is ok for this function to fail midway and return right away.  t4_detach
6330  * will walk the entire sc->irq list and clean up whatever is valid.
6331  */
6332 int
6333 t4_setup_intr_handlers(struct adapter *sc)
6334 {
6335 	int rc, rid, p, q, v;
6336 	char s[8];
6337 	struct irq *irq;
6338 	struct port_info *pi;
6339 	struct vi_info *vi;
6340 	struct sge *sge = &sc->sge;
6341 	struct sge_rxq *rxq;
6342 #ifdef TCP_OFFLOAD
6343 	struct sge_ofld_rxq *ofld_rxq;
6344 #endif
6345 #ifdef DEV_NETMAP
6346 	struct sge_nm_rxq *nm_rxq;
6347 #endif
6348 #ifdef RSS
6349 	int nbuckets = rss_getnumbuckets();
6350 #endif
6351 
6352 	/*
6353 	 * Setup interrupts.
6354 	 */
6355 	irq = &sc->irq[0];
6356 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6357 	if (forwarding_intr_to_fwq(sc))
6358 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6359 
6360 	/* Multiple interrupts. */
6361 	if (sc->flags & IS_VF)
6362 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6363 		    ("%s: too few intr.", __func__));
6364 	else
6365 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6366 		    ("%s: too few intr.", __func__));
6367 
6368 	/* The first one is always error intr on PFs */
6369 	if (!(sc->flags & IS_VF)) {
6370 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6371 		if (rc != 0)
6372 			return (rc);
6373 		irq++;
6374 		rid++;
6375 	}
6376 
6377 	/* The second one is always the firmware event queue (first on VFs) */
6378 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6379 	if (rc != 0)
6380 		return (rc);
6381 	irq++;
6382 	rid++;
6383 
6384 	for_each_port(sc, p) {
6385 		pi = sc->port[p];
6386 		for_each_vi(pi, v, vi) {
6387 			vi->first_intr = rid - 1;
6388 
6389 			if (vi->nnmrxq > 0) {
6390 				int n = max(vi->nrxq, vi->nnmrxq);
6391 
6392 				rxq = &sge->rxq[vi->first_rxq];
6393 #ifdef DEV_NETMAP
6394 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6395 #endif
6396 				for (q = 0; q < n; q++) {
6397 					snprintf(s, sizeof(s), "%x%c%x", p,
6398 					    'a' + v, q);
6399 					if (q < vi->nrxq)
6400 						irq->rxq = rxq++;
6401 #ifdef DEV_NETMAP
6402 					if (q < vi->nnmrxq)
6403 						irq->nm_rxq = nm_rxq++;
6404 
6405 					if (irq->nm_rxq != NULL &&
6406 					    irq->rxq == NULL) {
6407 						/* Netmap rx only */
6408 						rc = t4_alloc_irq(sc, irq, rid,
6409 						    t4_nm_intr, irq->nm_rxq, s);
6410 					}
6411 					if (irq->nm_rxq != NULL &&
6412 					    irq->rxq != NULL) {
6413 						/* NIC and Netmap rx */
6414 						rc = t4_alloc_irq(sc, irq, rid,
6415 						    t4_vi_intr, irq, s);
6416 					}
6417 #endif
6418 					if (irq->rxq != NULL &&
6419 					    irq->nm_rxq == NULL) {
6420 						/* NIC rx only */
6421 						rc = t4_alloc_irq(sc, irq, rid,
6422 						    t4_intr, irq->rxq, s);
6423 					}
6424 					if (rc != 0)
6425 						return (rc);
6426 #ifdef RSS
6427 					if (q < vi->nrxq) {
6428 						bus_bind_intr(sc->dev, irq->res,
6429 						    rss_getcpu(q % nbuckets));
6430 					}
6431 #endif
6432 					irq++;
6433 					rid++;
6434 					vi->nintr++;
6435 				}
6436 			} else {
6437 				for_each_rxq(vi, q, rxq) {
6438 					snprintf(s, sizeof(s), "%x%c%x", p,
6439 					    'a' + v, q);
6440 					rc = t4_alloc_irq(sc, irq, rid,
6441 					    t4_intr, rxq, s);
6442 					if (rc != 0)
6443 						return (rc);
6444 #ifdef RSS
6445 					bus_bind_intr(sc->dev, irq->res,
6446 					    rss_getcpu(q % nbuckets));
6447 #endif
6448 					irq++;
6449 					rid++;
6450 					vi->nintr++;
6451 				}
6452 			}
6453 #ifdef TCP_OFFLOAD
6454 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6455 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6456 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6457 				    ofld_rxq, s);
6458 				if (rc != 0)
6459 					return (rc);
6460 				irq++;
6461 				rid++;
6462 				vi->nintr++;
6463 			}
6464 #endif
6465 		}
6466 	}
6467 	MPASS(irq == &sc->irq[sc->intr_count]);
6468 
6469 	return (0);
6470 }
6471 
6472 static void
6473 write_global_rss_key(struct adapter *sc)
6474 {
6475 #ifdef RSS
6476 	int i;
6477 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6478 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6479 
6480 	CTASSERT(RSS_KEYSIZE == 40);
6481 
6482 	rss_getkey((void *)&raw_rss_key[0]);
6483 	for (i = 0; i < nitems(rss_key); i++) {
6484 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6485 	}
6486 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6487 #endif
6488 }
6489 
6490 /*
6491  * Idempotent.
6492  */
6493 static int
6494 adapter_full_init(struct adapter *sc)
6495 {
6496 	int rc, i;
6497 
6498 	ASSERT_SYNCHRONIZED_OP(sc);
6499 
6500 	if (!(sc->flags & ADAP_SYSCTL_CTX)) {
6501 		sysctl_ctx_init(&sc->ctx);
6502 		sc->flags |= ADAP_SYSCTL_CTX;
6503 	}
6504 
6505 	/*
6506 	 * queues that belong to the adapter (not any particular port).
6507 	 */
6508 	rc = t4_setup_adapter_queues(sc);
6509 	if (rc != 0)
6510 		return (rc);
6511 
6512 	for (i = 0; i < nitems(sc->tq); i++) {
6513 		if (sc->tq[i] != NULL)
6514 			continue;
6515 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6516 		    taskqueue_thread_enqueue, &sc->tq[i]);
6517 		if (sc->tq[i] == NULL) {
6518 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6519 			return (ENOMEM);
6520 		}
6521 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6522 		    device_get_nameunit(sc->dev), i);
6523 	}
6524 
6525 	if (!(sc->flags & IS_VF)) {
6526 		write_global_rss_key(sc);
6527 		t4_intr_enable(sc);
6528 	}
6529 #ifdef KERN_TLS
6530 	if (is_ktls(sc))
6531 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
6532 		    C_HARDCLOCK);
6533 #endif
6534 	return (0);
6535 }
6536 
6537 int
6538 adapter_init(struct adapter *sc)
6539 {
6540 	int rc;
6541 
6542 	ASSERT_SYNCHRONIZED_OP(sc);
6543 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6544 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6545 	    ("%s: FULL_INIT_DONE already", __func__));
6546 
6547 	rc = adapter_full_init(sc);
6548 	if (rc != 0)
6549 		adapter_full_uninit(sc);
6550 	else
6551 		sc->flags |= FULL_INIT_DONE;
6552 
6553 	return (rc);
6554 }
6555 
6556 /*
6557  * Idempotent.
6558  */
6559 static void
6560 adapter_full_uninit(struct adapter *sc)
6561 {
6562 	int i;
6563 
6564 	/* Do this before freeing the adapter queues. */
6565 	if (sc->flags & ADAP_SYSCTL_CTX) {
6566 		sysctl_ctx_free(&sc->ctx);
6567 		sc->flags &= ~ADAP_SYSCTL_CTX;
6568 	}
6569 
6570 	t4_teardown_adapter_queues(sc);
6571 
6572 	for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
6573 		taskqueue_free(sc->tq[i]);
6574 		sc->tq[i] = NULL;
6575 	}
6576 
6577 	sc->flags &= ~FULL_INIT_DONE;
6578 }
6579 
6580 #ifdef RSS
6581 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6582     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6583     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6584     RSS_HASHTYPE_RSS_UDP_IPV6)
6585 
6586 /* Translates kernel hash types to hardware. */
6587 static int
6588 hashconfig_to_hashen(int hashconfig)
6589 {
6590 	int hashen = 0;
6591 
6592 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6593 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6594 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6595 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6596 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6597 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6598 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6599 	}
6600 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6601 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6602 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6603 	}
6604 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6605 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6606 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6607 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6608 
6609 	return (hashen);
6610 }
6611 
6612 /* Translates hardware hash types to kernel. */
6613 static int
6614 hashen_to_hashconfig(int hashen)
6615 {
6616 	int hashconfig = 0;
6617 
6618 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6619 		/*
6620 		 * If UDP hashing was enabled it must have been enabled for
6621 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6622 		 * enabling any 4-tuple hash is nonsense configuration.
6623 		 */
6624 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6625 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6626 
6627 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6628 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6629 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6630 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6631 	}
6632 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6633 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6634 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6635 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6636 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6637 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6638 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6639 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6640 
6641 	return (hashconfig);
6642 }
6643 #endif
6644 
6645 /*
6646  * Idempotent.
6647  */
6648 static int
6649 vi_full_init(struct vi_info *vi)
6650 {
6651 	struct adapter *sc = vi->adapter;
6652 	struct sge_rxq *rxq;
6653 	int rc, i, j;
6654 #ifdef RSS
6655 	int nbuckets = rss_getnumbuckets();
6656 	int hashconfig = rss_gethashconfig();
6657 	int extra;
6658 #endif
6659 
6660 	ASSERT_SYNCHRONIZED_OP(sc);
6661 
6662 	if (!(vi->flags & VI_SYSCTL_CTX)) {
6663 		sysctl_ctx_init(&vi->ctx);
6664 		vi->flags |= VI_SYSCTL_CTX;
6665 	}
6666 
6667 	/*
6668 	 * Allocate tx/rx/fl queues for this VI.
6669 	 */
6670 	rc = t4_setup_vi_queues(vi);
6671 	if (rc != 0)
6672 		return (rc);
6673 
6674 	/*
6675 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6676 	 */
6677 	if (vi->nrxq > vi->rss_size) {
6678 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6679 		    "some queues will never receive traffic.\n", vi->nrxq,
6680 		    vi->rss_size);
6681 	} else if (vi->rss_size % vi->nrxq) {
6682 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6683 		    "expect uneven traffic distribution.\n", vi->nrxq,
6684 		    vi->rss_size);
6685 	}
6686 #ifdef RSS
6687 	if (vi->nrxq != nbuckets) {
6688 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6689 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6690 	}
6691 #endif
6692 	if (vi->rss == NULL)
6693 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6694 		    M_ZERO | M_WAITOK);
6695 	for (i = 0; i < vi->rss_size;) {
6696 #ifdef RSS
6697 		j = rss_get_indirection_to_bucket(i);
6698 		j %= vi->nrxq;
6699 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6700 		vi->rss[i++] = rxq->iq.abs_id;
6701 #else
6702 		for_each_rxq(vi, j, rxq) {
6703 			vi->rss[i++] = rxq->iq.abs_id;
6704 			if (i == vi->rss_size)
6705 				break;
6706 		}
6707 #endif
6708 	}
6709 
6710 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6711 	    vi->rss, vi->rss_size);
6712 	if (rc != 0) {
6713 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6714 		return (rc);
6715 	}
6716 
6717 #ifdef RSS
6718 	vi->hashen = hashconfig_to_hashen(hashconfig);
6719 
6720 	/*
6721 	 * We may have had to enable some hashes even though the global config
6722 	 * wants them disabled.  This is a potential problem that must be
6723 	 * reported to the user.
6724 	 */
6725 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6726 
6727 	/*
6728 	 * If we consider only the supported hash types, then the enabled hashes
6729 	 * are a superset of the requested hashes.  In other words, there cannot
6730 	 * be any supported hash that was requested but not enabled, but there
6731 	 * can be hashes that were not requested but had to be enabled.
6732 	 */
6733 	extra &= SUPPORTED_RSS_HASHTYPES;
6734 	MPASS((extra & hashconfig) == 0);
6735 
6736 	if (extra) {
6737 		CH_ALERT(vi,
6738 		    "global RSS config (0x%x) cannot be accommodated.\n",
6739 		    hashconfig);
6740 	}
6741 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6742 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6743 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6744 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6745 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6746 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6747 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6748 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6749 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6750 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6751 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6752 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6753 #else
6754 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6755 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6756 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6757 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6758 #endif
6759 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6760 	    0, 0);
6761 	if (rc != 0) {
6762 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6763 		return (rc);
6764 	}
6765 
6766 	return (0);
6767 }
6768 
6769 int
6770 vi_init(struct vi_info *vi)
6771 {
6772 	int rc;
6773 
6774 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6775 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6776 	    ("%s: VI_INIT_DONE already", __func__));
6777 
6778 	rc = vi_full_init(vi);
6779 	if (rc != 0)
6780 		vi_full_uninit(vi);
6781 	else
6782 		vi->flags |= VI_INIT_DONE;
6783 
6784 	return (rc);
6785 }
6786 
6787 /*
6788  * Idempotent.
6789  */
6790 static void
6791 vi_full_uninit(struct vi_info *vi)
6792 {
6793 
6794 	if (vi->flags & VI_INIT_DONE) {
6795 		quiesce_vi(vi);
6796 		free(vi->rss, M_CXGBE);
6797 		free(vi->nm_rss, M_CXGBE);
6798 	}
6799 
6800 	/* Do this before freeing the VI queues. */
6801 	if (vi->flags & VI_SYSCTL_CTX) {
6802 		sysctl_ctx_free(&vi->ctx);
6803 		vi->flags &= ~VI_SYSCTL_CTX;
6804 	}
6805 
6806 	t4_teardown_vi_queues(vi);
6807 	vi->flags &= ~VI_INIT_DONE;
6808 }
6809 
6810 static void
6811 quiesce_txq(struct sge_txq *txq)
6812 {
6813 	struct sge_eq *eq = &txq->eq;
6814 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6815 
6816 	MPASS(eq->flags & EQ_SW_ALLOCATED);
6817 	MPASS(!(eq->flags & EQ_ENABLED));
6818 
6819 	/* Wait for the mp_ring to empty. */
6820 	while (!mp_ring_is_idle(txq->r)) {
6821 		mp_ring_check_drainage(txq->r, 4096);
6822 		pause("rquiesce", 1);
6823 	}
6824 	MPASS(txq->txp.npkt == 0);
6825 
6826 	if (eq->flags & EQ_HW_ALLOCATED) {
6827 		/*
6828 		 * Hardware is alive and working normally.  Wait for it to
6829 		 * finish and then wait for the driver to catch up and reclaim
6830 		 * all descriptors.
6831 		 */
6832 		while (spg->cidx != htobe16(eq->pidx))
6833 			pause("equiesce", 1);
6834 		while (eq->cidx != eq->pidx)
6835 			pause("dquiesce", 1);
6836 	} else {
6837 		/*
6838 		 * Hardware is unavailable.  Discard all pending tx and reclaim
6839 		 * descriptors directly.
6840 		 */
6841 		TXQ_LOCK(txq);
6842 		while (eq->cidx != eq->pidx) {
6843 			struct mbuf *m, *nextpkt;
6844 			struct tx_sdesc *txsd;
6845 
6846 			txsd = &txq->sdesc[eq->cidx];
6847 			for (m = txsd->m; m != NULL; m = nextpkt) {
6848 				nextpkt = m->m_nextpkt;
6849 				m->m_nextpkt = NULL;
6850 				m_freem(m);
6851 			}
6852 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
6853 		}
6854 		spg->pidx = spg->cidx = htobe16(eq->cidx);
6855 		TXQ_UNLOCK(txq);
6856 	}
6857 }
6858 
6859 static void
6860 quiesce_wrq(struct sge_wrq *wrq)
6861 {
6862 
6863 	/* XXXTX */
6864 }
6865 
6866 static void
6867 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
6868 {
6869 	/* Synchronize with the interrupt handler */
6870 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
6871 		pause("iqfree", 1);
6872 
6873 	if (fl != NULL) {
6874 		MPASS(iq->flags & IQ_HAS_FL);
6875 
6876 		mtx_lock(&sc->sfl_lock);
6877 		FL_LOCK(fl);
6878 		fl->flags |= FL_DOOMED;
6879 		FL_UNLOCK(fl);
6880 		callout_stop(&sc->sfl_callout);
6881 		mtx_unlock(&sc->sfl_lock);
6882 
6883 		KASSERT((fl->flags & FL_STARVING) == 0,
6884 		    ("%s: still starving", __func__));
6885 
6886 		/* Release all buffers if hardware is no longer available. */
6887 		if (!(iq->flags & IQ_HW_ALLOCATED))
6888 			free_fl_buffers(sc, fl);
6889 	}
6890 }
6891 
6892 /*
6893  * Wait for all activity on all the queues of the VI to complete.  It is assumed
6894  * that no new work is being enqueued by the hardware or the driver.  That part
6895  * should be arranged before calling this function.
6896  */
6897 static void
6898 quiesce_vi(struct vi_info *vi)
6899 {
6900 	int i;
6901 	struct adapter *sc = vi->adapter;
6902 	struct sge_rxq *rxq;
6903 	struct sge_txq *txq;
6904 #ifdef TCP_OFFLOAD
6905 	struct sge_ofld_rxq *ofld_rxq;
6906 #endif
6907 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6908 	struct sge_ofld_txq *ofld_txq;
6909 #endif
6910 
6911 	if (!(vi->flags & VI_INIT_DONE))
6912 		return;
6913 
6914 	for_each_txq(vi, i, txq) {
6915 		quiesce_txq(txq);
6916 	}
6917 
6918 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6919 	for_each_ofld_txq(vi, i, ofld_txq) {
6920 		quiesce_wrq(&ofld_txq->wrq);
6921 	}
6922 #endif
6923 
6924 	for_each_rxq(vi, i, rxq) {
6925 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
6926 	}
6927 
6928 #ifdef TCP_OFFLOAD
6929 	for_each_ofld_rxq(vi, i, ofld_rxq) {
6930 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
6931 	}
6932 #endif
6933 }
6934 
6935 static int
6936 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
6937     driver_intr_t *handler, void *arg, char *name)
6938 {
6939 	int rc;
6940 
6941 	irq->rid = rid;
6942 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
6943 	    RF_SHAREABLE | RF_ACTIVE);
6944 	if (irq->res == NULL) {
6945 		device_printf(sc->dev,
6946 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
6947 		return (ENOMEM);
6948 	}
6949 
6950 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
6951 	    NULL, handler, arg, &irq->tag);
6952 	if (rc != 0) {
6953 		device_printf(sc->dev,
6954 		    "failed to setup interrupt for rid %d, name %s: %d\n",
6955 		    rid, name, rc);
6956 	} else if (name)
6957 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
6958 
6959 	return (rc);
6960 }
6961 
6962 static int
6963 t4_free_irq(struct adapter *sc, struct irq *irq)
6964 {
6965 	if (irq->tag)
6966 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
6967 	if (irq->res)
6968 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
6969 
6970 	bzero(irq, sizeof(*irq));
6971 
6972 	return (0);
6973 }
6974 
6975 static void
6976 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
6977 {
6978 
6979 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
6980 	t4_get_regs(sc, buf, regs->len);
6981 }
6982 
6983 #define	A_PL_INDIR_CMD	0x1f8
6984 
6985 #define	S_PL_AUTOINC	31
6986 #define	M_PL_AUTOINC	0x1U
6987 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
6988 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
6989 
6990 #define	S_PL_VFID	20
6991 #define	M_PL_VFID	0xffU
6992 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
6993 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
6994 
6995 #define	S_PL_ADDR	0
6996 #define	M_PL_ADDR	0xfffffU
6997 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
6998 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
6999 
7000 #define	A_PL_INDIR_DATA	0x1fc
7001 
7002 static uint64_t
7003 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7004 {
7005 	u32 stats[2];
7006 
7007 	if (sc->flags & IS_VF) {
7008 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7009 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7010 	} else {
7011 		mtx_assert(&sc->reg_lock, MA_OWNED);
7012 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7013 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7014 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7015 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7016 	}
7017 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7018 }
7019 
7020 static void
7021 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7022 {
7023 
7024 #define GET_STAT(name) \
7025 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7026 
7027 	if (!(sc->flags & IS_VF))
7028 		mtx_lock(&sc->reg_lock);
7029 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7030 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7031 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7032 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7033 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7034 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7035 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7036 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7037 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7038 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7039 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7040 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7041 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7042 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7043 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7044 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7045 	if (!(sc->flags & IS_VF))
7046 		mtx_unlock(&sc->reg_lock);
7047 
7048 #undef GET_STAT
7049 }
7050 
7051 static void
7052 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7053 {
7054 	int reg;
7055 
7056 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7057 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7058 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7059 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7060 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7061 }
7062 
7063 static void
7064 vi_refresh_stats(struct vi_info *vi)
7065 {
7066 	struct timeval tv;
7067 	const struct timeval interval = {0, 250000};	/* 250ms */
7068 
7069 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7070 
7071 	if (!(vi->flags & VI_INIT_DONE) || vi->flags & VI_SKIP_STATS)
7072 		return;
7073 
7074 	getmicrotime(&tv);
7075 	timevalsub(&tv, &interval);
7076 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7077 		return;
7078 
7079 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7080 	getmicrotime(&vi->last_refreshed);
7081 }
7082 
7083 static void
7084 cxgbe_refresh_stats(struct vi_info *vi)
7085 {
7086 	u_int i, v, tnl_cong_drops, chan_map;
7087 	struct timeval tv;
7088 	const struct timeval interval = {0, 250000};	/* 250ms */
7089 	struct port_info *pi;
7090 	struct adapter *sc;
7091 
7092 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7093 
7094 	if (vi->flags & VI_SKIP_STATS)
7095 		return;
7096 
7097 	getmicrotime(&tv);
7098 	timevalsub(&tv, &interval);
7099 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7100 		return;
7101 
7102 	pi = vi->pi;
7103 	sc = vi->adapter;
7104 	tnl_cong_drops = 0;
7105 	t4_get_port_stats(sc, pi->tx_chan, &pi->stats);
7106 	chan_map = pi->rx_e_chan_map;
7107 	while (chan_map) {
7108 		i = ffs(chan_map) - 1;
7109 		mtx_lock(&sc->reg_lock);
7110 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7111 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7112 		mtx_unlock(&sc->reg_lock);
7113 		tnl_cong_drops += v;
7114 		chan_map &= ~(1 << i);
7115 	}
7116 	pi->tnl_cong_drops = tnl_cong_drops;
7117 	getmicrotime(&vi->last_refreshed);
7118 }
7119 
7120 static void
7121 cxgbe_tick(void *arg)
7122 {
7123 	struct vi_info *vi = arg;
7124 
7125 	MPASS(IS_MAIN_VI(vi));
7126 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7127 
7128 	cxgbe_refresh_stats(vi);
7129 	callout_schedule(&vi->tick, hz);
7130 }
7131 
7132 static void
7133 vi_tick(void *arg)
7134 {
7135 	struct vi_info *vi = arg;
7136 
7137 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7138 
7139 	vi_refresh_stats(vi);
7140 	callout_schedule(&vi->tick, hz);
7141 }
7142 
7143 /*
7144  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7145  */
7146 static char *caps_decoder[] = {
7147 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7148 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7149 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7150 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7151 	    "\006HASHFILTER\007ETHOFLD",
7152 	"\20\001TOE",					/* 4: TOE */
7153 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7154 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7155 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7156 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7157 	    "\007T10DIF"
7158 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7159 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7160 	    "\004TLS_HW",
7161 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7162 		    "\004PO_INITIATOR\005PO_TARGET",
7163 };
7164 
7165 void
7166 t4_sysctls(struct adapter *sc)
7167 {
7168 	struct sysctl_ctx_list *ctx;
7169 	struct sysctl_oid *oid;
7170 	struct sysctl_oid_list *children, *c0;
7171 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7172 
7173 	ctx = device_get_sysctl_ctx(sc->dev);
7174 
7175 	/*
7176 	 * dev.t4nex.X.
7177 	 */
7178 	oid = device_get_sysctl_tree(sc->dev);
7179 	c0 = children = SYSCTL_CHILDREN(oid);
7180 
7181 	sc->sc_do_rxcopy = 1;
7182 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7183 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7184 
7185 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7186 	    sc->params.nports, "# of ports");
7187 
7188 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7189 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7190 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7191 	    "available doorbells");
7192 
7193 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7194 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7195 
7196 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7197 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7198 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7199 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7200 
7201 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7202 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7203 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7204 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7205 
7206 	t4_sge_sysctls(sc, ctx, children);
7207 
7208 	sc->lro_timeout = 100;
7209 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7210 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7211 
7212 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7213 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7214 
7215 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7216 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7217 
7218 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7219 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7220 
7221 	if (sc->flags & IS_VF)
7222 		return;
7223 
7224 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7225 	    NULL, chip_rev(sc), "chip hardware revision");
7226 
7227 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7228 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7229 
7230 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7231 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7232 
7233 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7234 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7235 
7236 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7237 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7238 
7239 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7240 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7241 
7242 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7243 	    sc->er_version, 0, "expansion ROM version");
7244 
7245 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7246 	    sc->bs_version, 0, "bootstrap firmware version");
7247 
7248 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7249 	    NULL, sc->params.scfg_vers, "serial config version");
7250 
7251 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7252 	    NULL, sc->params.vpd_vers, "VPD version");
7253 
7254 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7255 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7256 
7257 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7258 	    sc->cfcsum, "config file checksum");
7259 
7260 #define SYSCTL_CAP(name, n, text) \
7261 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7262 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7263 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7264 	    "available " text " capabilities")
7265 
7266 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7267 	SYSCTL_CAP(linkcaps, 1, "link");
7268 	SYSCTL_CAP(switchcaps, 2, "switch");
7269 	SYSCTL_CAP(niccaps, 3, "NIC");
7270 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7271 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7272 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7273 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7274 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7275 #undef SYSCTL_CAP
7276 
7277 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7278 	    NULL, sc->tids.nftids, "number of filters");
7279 
7280 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7281 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7282 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7283 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7284 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7285 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7286 
7287 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7288 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7289 	    sysctl_loadavg, "A",
7290 	    "microprocessor load averages (debug firmwares only)");
7291 
7292 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7293 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7294 	    "I", "core Vdd (in mV)");
7295 
7296 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7297 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7298 	    sysctl_cpus, "A", "local CPUs");
7299 
7300 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7301 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7302 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7303 
7304 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7305 	    &sc->swintr, 0, "software triggered interrupts");
7306 
7307 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7308 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7309 	    "1 = reset adapter, 0 = zero reset counter");
7310 
7311 	/*
7312 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7313 	 */
7314 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7315 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7316 	    "logs and miscellaneous information");
7317 	children = SYSCTL_CHILDREN(oid);
7318 
7319 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7320 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7321 	    sysctl_cctrl, "A", "congestion control");
7322 
7323 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7324 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7325 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7326 
7327 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7328 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7329 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7330 
7331 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7332 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7333 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7334 
7335 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7336 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7337 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7338 
7339 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7340 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7341 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7342 
7343 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7344 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7345 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7346 
7347 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7348 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7349 	    sysctl_cim_la, "A", "CIM logic analyzer");
7350 
7351 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7352 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7353 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7354 
7355 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7356 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7357 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7358 
7359 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7360 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7361 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7362 
7363 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7364 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7365 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7366 
7367 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7368 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7369 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7370 
7371 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7372 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7373 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7374 
7375 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7376 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7377 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7378 
7379 	if (chip_id(sc) > CHELSIO_T4) {
7380 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7381 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7382 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7383 		    "CIM OBQ 6 (SGE0-RX)");
7384 
7385 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7386 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7387 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7388 		    "CIM OBQ 7 (SGE1-RX)");
7389 	}
7390 
7391 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7392 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7393 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7394 
7395 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7396 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7397 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7398 
7399 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7400 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7401 	    sysctl_cpl_stats, "A", "CPL statistics");
7402 
7403 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7404 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7405 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7406 
7407 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7408 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7409 	    sysctl_tid_stats, "A", "tid stats");
7410 
7411 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7412 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7413 	    sysctl_devlog, "A", "firmware's device log");
7414 
7415 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7416 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7417 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7418 
7419 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7420 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7421 	    sysctl_hw_sched, "A", "hardware scheduler ");
7422 
7423 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7424 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7425 	    sysctl_l2t, "A", "hardware L2 table");
7426 
7427 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7428 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7429 	    sysctl_smt, "A", "hardware source MAC table");
7430 
7431 #ifdef INET6
7432 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7433 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7434 	    sysctl_clip, "A", "active CLIP table entries");
7435 #endif
7436 
7437 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7438 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7439 	    sysctl_lb_stats, "A", "loopback statistics");
7440 
7441 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7442 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7443 	    sysctl_meminfo, "A", "memory regions");
7444 
7445 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7446 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7447 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7448 	    "A", "MPS TCAM entries");
7449 
7450 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7451 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7452 	    sysctl_path_mtus, "A", "path MTUs");
7453 
7454 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7455 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7456 	    sysctl_pm_stats, "A", "PM statistics");
7457 
7458 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7459 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7460 	    sysctl_rdma_stats, "A", "RDMA statistics");
7461 
7462 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7463 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7464 	    sysctl_tcp_stats, "A", "TCP statistics");
7465 
7466 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7467 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7468 	    sysctl_tids, "A", "TID information");
7469 
7470 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7471 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7472 	    sysctl_tp_err_stats, "A", "TP error statistics");
7473 
7474 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7475 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7476 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7477 
7478 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7479 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7480 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7481 
7482 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7483 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7484 	    sysctl_tp_la, "A", "TP logic analyzer");
7485 
7486 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7487 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7488 	    sysctl_tx_rate, "A", "Tx rate");
7489 
7490 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7491 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7492 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7493 
7494 	if (chip_id(sc) >= CHELSIO_T5) {
7495 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7496 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7497 		    sysctl_wcwr_stats, "A", "write combined work requests");
7498 	}
7499 
7500 #ifdef KERN_TLS
7501 	if (is_ktls(sc)) {
7502 		/*
7503 		 * dev.t4nex.0.tls.
7504 		 */
7505 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7506 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7507 		children = SYSCTL_CHILDREN(oid);
7508 
7509 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7510 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7511 		    "keys in work requests (1) or attempt to store TLS keys "
7512 		    "in card memory.");
7513 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7514 		    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to combine "
7515 		    "TCB field updates with TLS record work requests.");
7516 	}
7517 #endif
7518 
7519 #ifdef TCP_OFFLOAD
7520 	if (is_offload(sc)) {
7521 		int i;
7522 		char s[4];
7523 
7524 		/*
7525 		 * dev.t4nex.X.toe.
7526 		 */
7527 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7528 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7529 		children = SYSCTL_CHILDREN(oid);
7530 
7531 		sc->tt.cong_algorithm = -1;
7532 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7533 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7534 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7535 		    "3 = highspeed)");
7536 
7537 		sc->tt.sndbuf = -1;
7538 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7539 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7540 
7541 		sc->tt.ddp = 0;
7542 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7543 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7544 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7545 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7546 
7547 		sc->tt.rx_coalesce = -1;
7548 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7549 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7550 
7551 		sc->tt.tls = 0;
7552 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7553 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7554 		    "Inline TLS allowed");
7555 
7556 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_ports",
7557 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7558 		    sysctl_tls_rx_ports, "I",
7559 		    "TCP ports that use inline TLS+TOE RX");
7560 
7561 		sc->tt.tls_rx_timeout = t4_toe_tls_rx_timeout;
7562 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_timeout",
7563 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7564 		    sysctl_tls_rx_timeout, "I",
7565 		    "Timeout in seconds to downgrade TLS sockets to plain TOE");
7566 
7567 		sc->tt.tx_align = -1;
7568 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7569 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7570 
7571 		sc->tt.tx_zcopy = 0;
7572 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7573 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7574 		    "Enable zero-copy aio_write(2)");
7575 
7576 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7577 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7578 		    "cop_managed_offloading", CTLFLAG_RW,
7579 		    &sc->tt.cop_managed_offloading, 0,
7580 		    "COP (Connection Offload Policy) controls all TOE offload");
7581 
7582 		sc->tt.autorcvbuf_inc = 16 * 1024;
7583 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7584 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7585 		    "autorcvbuf increment");
7586 
7587 		sc->tt.update_hc_on_pmtu_change = 1;
7588 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7589 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7590 		    &sc->tt.update_hc_on_pmtu_change, 0,
7591 		    "Update hostcache entry if the PMTU changes");
7592 
7593 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7594 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7595 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7596 
7597 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7598 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7599 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7600 
7601 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7602 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7603 		    sysctl_tp_tick, "A", "DACK tick (us)");
7604 
7605 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7606 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7607 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7608 
7609 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7610 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7611 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7612 		    "Minimum retransmit interval (us)");
7613 
7614 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7615 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7616 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7617 		    "Maximum retransmit interval (us)");
7618 
7619 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7620 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7621 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7622 		    "Persist timer min (us)");
7623 
7624 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7625 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7626 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7627 		    "Persist timer max (us)");
7628 
7629 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7630 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7631 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7632 		    "Keepalive idle timer (us)");
7633 
7634 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7635 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7636 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7637 		    "Keepalive interval timer (us)");
7638 
7639 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7640 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7641 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7642 
7643 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7644 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7645 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7646 		    "FINWAIT2 timer (us)");
7647 
7648 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7649 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7650 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7651 		    "Number of SYN retransmissions before abort");
7652 
7653 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7654 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7655 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7656 		    "Number of retransmissions before abort");
7657 
7658 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7659 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7660 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7661 		    "Number of keepalive probes before abort");
7662 
7663 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7664 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7665 		    "TOE retransmit backoffs");
7666 		children = SYSCTL_CHILDREN(oid);
7667 		for (i = 0; i < 16; i++) {
7668 			snprintf(s, sizeof(s), "%u", i);
7669 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7670 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7671 			    i, sysctl_tp_backoff, "IU",
7672 			    "TOE retransmit backoff");
7673 		}
7674 	}
7675 #endif
7676 }
7677 
7678 void
7679 vi_sysctls(struct vi_info *vi)
7680 {
7681 	struct sysctl_ctx_list *ctx;
7682 	struct sysctl_oid *oid;
7683 	struct sysctl_oid_list *children;
7684 
7685 	ctx = device_get_sysctl_ctx(vi->dev);
7686 
7687 	/*
7688 	 * dev.v?(cxgbe|cxl).X.
7689 	 */
7690 	oid = device_get_sysctl_tree(vi->dev);
7691 	children = SYSCTL_CHILDREN(oid);
7692 
7693 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7694 	    vi->viid, "VI identifer");
7695 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7696 	    &vi->nrxq, 0, "# of rx queues");
7697 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7698 	    &vi->ntxq, 0, "# of tx queues");
7699 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7700 	    &vi->first_rxq, 0, "index of first rx queue");
7701 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7702 	    &vi->first_txq, 0, "index of first tx queue");
7703 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7704 	    vi->rss_base, "start of RSS indirection table");
7705 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7706 	    vi->rss_size, "size of RSS indirection table");
7707 
7708 	if (IS_MAIN_VI(vi)) {
7709 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7710 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7711 		    sysctl_noflowq, "IU",
7712 		    "Reserve queue 0 for non-flowid packets");
7713 	}
7714 
7715 	if (vi->adapter->flags & IS_VF) {
7716 		MPASS(vi->flags & TX_USES_VM_WR);
7717 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7718 		    NULL, 1, "use VM work requests for transmit");
7719 	} else {
7720 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7721 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7722 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7723 	}
7724 
7725 #ifdef TCP_OFFLOAD
7726 	if (vi->nofldrxq != 0) {
7727 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7728 		    &vi->nofldrxq, 0,
7729 		    "# of rx queues for offloaded TCP connections");
7730 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7731 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7732 		    "index of first TOE rx queue");
7733 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7734 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7735 		    sysctl_holdoff_tmr_idx_ofld, "I",
7736 		    "holdoff timer index for TOE queues");
7737 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7738 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7739 		    sysctl_holdoff_pktc_idx_ofld, "I",
7740 		    "holdoff packet counter index for TOE queues");
7741 	}
7742 #endif
7743 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7744 	if (vi->nofldtxq != 0) {
7745 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7746 		    &vi->nofldtxq, 0,
7747 		    "# of tx queues for TOE/ETHOFLD");
7748 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7749 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7750 		    "index of first TOE/ETHOFLD tx queue");
7751 	}
7752 #endif
7753 #ifdef DEV_NETMAP
7754 	if (vi->nnmrxq != 0) {
7755 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7756 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7757 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7758 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7759 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7760 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7761 		    "index of first netmap rx queue");
7762 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7763 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7764 		    "index of first netmap tx queue");
7765 	}
7766 #endif
7767 
7768 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7769 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7770 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7771 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7772 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7773 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7774 
7775 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7776 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7777 	    sysctl_qsize_rxq, "I", "rx queue size");
7778 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7779 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7780 	    sysctl_qsize_txq, "I", "tx queue size");
7781 }
7782 
7783 static void
7784 cxgbe_sysctls(struct port_info *pi)
7785 {
7786 	struct sysctl_ctx_list *ctx;
7787 	struct sysctl_oid *oid;
7788 	struct sysctl_oid_list *children, *children2;
7789 	struct adapter *sc = pi->adapter;
7790 	int i;
7791 	char name[16];
7792 	static char *tc_flags = {"\20\1USER"};
7793 
7794 	ctx = device_get_sysctl_ctx(pi->dev);
7795 
7796 	/*
7797 	 * dev.cxgbe.X.
7798 	 */
7799 	oid = device_get_sysctl_tree(pi->dev);
7800 	children = SYSCTL_CHILDREN(oid);
7801 
7802 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7803 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7804 	    sysctl_linkdnrc, "A", "reason why link is down");
7805 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7806 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7807 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7808 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
7809 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7810 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7811 		    sysctl_btphy, "I", "PHY firmware version");
7812 	}
7813 
7814 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7815 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7816 	    sysctl_pause_settings, "A",
7817 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7818 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fec",
7819 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7820 	    sysctl_fec, "A",
7821 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7822 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7823 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7824 	    "FEC recommended by the cable/transceiver");
7825 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7826 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7827 	    sysctl_autoneg, "I",
7828 	    "autonegotiation (-1 = not supported)");
7829 
7830 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7831 	    &pi->link_cfg.pcaps, 0, "port capabilities");
7832 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7833 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
7834 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7835 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7836 
7837 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7838 	    port_top_speed(pi), "max speed (in Gbps)");
7839 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7840 	    pi->mps_bg_map, "MPS buffer group map");
7841 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
7842 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
7843 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_c_chan", CTLFLAG_RD, NULL,
7844 	    pi->rx_c_chan, "TP rx c-channel");
7845 
7846 	if (sc->flags & IS_VF)
7847 		return;
7848 
7849 	/*
7850 	 * dev.(cxgbe|cxl).X.tc.
7851 	 */
7852 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
7853 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7854 	    "Tx scheduler traffic classes (cl_rl)");
7855 	children2 = SYSCTL_CHILDREN(oid);
7856 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
7857 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
7858 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
7859 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
7860 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
7861 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
7862 	for (i = 0; i < sc->params.nsched_cls; i++) {
7863 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
7864 
7865 		snprintf(name, sizeof(name), "%d", i);
7866 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
7867 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
7868 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
7869 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
7870 		    CTLFLAG_RD, &tc->state, 0, "current state");
7871 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
7872 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
7873 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
7874 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
7875 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
7876 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
7877 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7878 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
7879 		    "traffic class parameters");
7880 	}
7881 
7882 	/*
7883 	 * dev.cxgbe.X.stats.
7884 	 */
7885 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
7886 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
7887 	children = SYSCTL_CHILDREN(oid);
7888 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
7889 	    &pi->tx_parse_error, 0,
7890 	    "# of tx packets with invalid length or # of segments");
7891 
7892 #define T4_REGSTAT(name, stat, desc) \
7893     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
7894         CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
7895 	(is_t4(sc) ? PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L) : \
7896 	T5_PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L)), \
7897         sysctl_handle_t4_reg64, "QU", desc)
7898 
7899 /* We get these from port_stats and they may be stale by up to 1s */
7900 #define T4_PORTSTAT(name, desc) \
7901 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
7902 	    &pi->stats.name, desc)
7903 
7904 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
7905 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
7906 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
7907 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
7908 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
7909 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
7910 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
7911 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
7912 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
7913 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
7914 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
7915 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
7916 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
7917 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
7918 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
7919 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
7920 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
7921 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
7922 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
7923 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
7924 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
7925 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
7926 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
7927 
7928 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
7929 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
7930 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
7931 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
7932 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
7933 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
7934 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
7935 	if (is_t6(sc)) {
7936 		T4_PORTSTAT(rx_fcs_err,
7937 		    "# of frames received with bad FCS since last link up");
7938 	} else {
7939 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
7940 		    "# of frames received with bad FCS");
7941 	}
7942 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
7943 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
7944 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
7945 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
7946 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
7947 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
7948 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
7949 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
7950 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
7951 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
7952 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
7953 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
7954 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
7955 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
7956 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
7957 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
7958 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
7959 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
7960 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
7961 
7962 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
7963 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
7964 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
7965 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
7966 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
7967 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
7968 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
7969 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
7970 
7971 #undef T4_REGSTAT
7972 #undef T4_PORTSTAT
7973 }
7974 
7975 static int
7976 sysctl_int_array(SYSCTL_HANDLER_ARGS)
7977 {
7978 	int rc, *i, space = 0;
7979 	struct sbuf sb;
7980 
7981 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
7982 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
7983 		if (space)
7984 			sbuf_printf(&sb, " ");
7985 		sbuf_printf(&sb, "%d", *i);
7986 		space = 1;
7987 	}
7988 	rc = sbuf_finish(&sb);
7989 	sbuf_delete(&sb);
7990 	return (rc);
7991 }
7992 
7993 static int
7994 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
7995 {
7996 	int rc;
7997 	struct sbuf *sb;
7998 
7999 	rc = sysctl_wire_old_buffer(req, 0);
8000 	if (rc != 0)
8001 		return(rc);
8002 
8003 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8004 	if (sb == NULL)
8005 		return (ENOMEM);
8006 
8007 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8008 	rc = sbuf_finish(sb);
8009 	sbuf_delete(sb);
8010 
8011 	return (rc);
8012 }
8013 
8014 static int
8015 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8016 {
8017 	int rc;
8018 	struct sbuf *sb;
8019 
8020 	rc = sysctl_wire_old_buffer(req, 0);
8021 	if (rc != 0)
8022 		return(rc);
8023 
8024 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8025 	if (sb == NULL)
8026 		return (ENOMEM);
8027 
8028 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8029 	rc = sbuf_finish(sb);
8030 	sbuf_delete(sb);
8031 
8032 	return (rc);
8033 }
8034 
8035 static int
8036 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8037 {
8038 	struct port_info *pi = arg1;
8039 	int op = arg2;
8040 	struct adapter *sc = pi->adapter;
8041 	u_int v;
8042 	int rc;
8043 
8044 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8045 	if (rc)
8046 		return (rc);
8047 	if (hw_off_limits(sc))
8048 		rc = ENXIO;
8049 	else {
8050 		/* XXX: magic numbers */
8051 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8052 		    op ? 0x20 : 0xc820, &v);
8053 	}
8054 	end_synchronized_op(sc, 0);
8055 	if (rc)
8056 		return (rc);
8057 	if (op == 0)
8058 		v /= 256;
8059 
8060 	rc = sysctl_handle_int(oidp, &v, 0, req);
8061 	return (rc);
8062 }
8063 
8064 static int
8065 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8066 {
8067 	struct vi_info *vi = arg1;
8068 	int rc, val;
8069 
8070 	val = vi->rsrv_noflowq;
8071 	rc = sysctl_handle_int(oidp, &val, 0, req);
8072 	if (rc != 0 || req->newptr == NULL)
8073 		return (rc);
8074 
8075 	if ((val >= 1) && (vi->ntxq > 1))
8076 		vi->rsrv_noflowq = 1;
8077 	else
8078 		vi->rsrv_noflowq = 0;
8079 
8080 	return (rc);
8081 }
8082 
8083 static int
8084 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8085 {
8086 	struct vi_info *vi = arg1;
8087 	struct adapter *sc = vi->adapter;
8088 	int rc, val, i;
8089 
8090 	MPASS(!(sc->flags & IS_VF));
8091 
8092 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8093 	rc = sysctl_handle_int(oidp, &val, 0, req);
8094 	if (rc != 0 || req->newptr == NULL)
8095 		return (rc);
8096 
8097 	if (val != 0 && val != 1)
8098 		return (EINVAL);
8099 
8100 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8101 	    "t4txvm");
8102 	if (rc)
8103 		return (rc);
8104 	if (hw_off_limits(sc))
8105 		rc = ENXIO;
8106 	else if (vi->ifp->if_drv_flags & IFF_DRV_RUNNING) {
8107 		/*
8108 		 * We don't want parse_pkt to run with one setting (VF or PF)
8109 		 * and then eth_tx to see a different setting but still use
8110 		 * stale information calculated by parse_pkt.
8111 		 */
8112 		rc = EBUSY;
8113 	} else {
8114 		struct port_info *pi = vi->pi;
8115 		struct sge_txq *txq;
8116 		uint32_t ctrl0;
8117 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8118 
8119 		if (val) {
8120 			vi->flags |= TX_USES_VM_WR;
8121 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
8122 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8123 			    V_TXPKT_INTF(pi->tx_chan));
8124 			if (!(sc->flags & IS_VF))
8125 				npkt--;
8126 		} else {
8127 			vi->flags &= ~TX_USES_VM_WR;
8128 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
8129 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8130 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8131 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8132 		}
8133 		for_each_txq(vi, i, txq) {
8134 			txq->cpl_ctrl0 = ctrl0;
8135 			txq->txp.max_npkt = npkt;
8136 		}
8137 	}
8138 	end_synchronized_op(sc, LOCK_HELD);
8139 	return (rc);
8140 }
8141 
8142 static int
8143 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8144 {
8145 	struct vi_info *vi = arg1;
8146 	struct adapter *sc = vi->adapter;
8147 	int idx, rc, i;
8148 	struct sge_rxq *rxq;
8149 	uint8_t v;
8150 
8151 	idx = vi->tmr_idx;
8152 
8153 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8154 	if (rc != 0 || req->newptr == NULL)
8155 		return (rc);
8156 
8157 	if (idx < 0 || idx >= SGE_NTIMERS)
8158 		return (EINVAL);
8159 
8160 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8161 	    "t4tmr");
8162 	if (rc)
8163 		return (rc);
8164 
8165 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8166 	for_each_rxq(vi, i, rxq) {
8167 #ifdef atomic_store_rel_8
8168 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8169 #else
8170 		rxq->iq.intr_params = v;
8171 #endif
8172 	}
8173 	vi->tmr_idx = idx;
8174 
8175 	end_synchronized_op(sc, LOCK_HELD);
8176 	return (0);
8177 }
8178 
8179 static int
8180 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8181 {
8182 	struct vi_info *vi = arg1;
8183 	struct adapter *sc = vi->adapter;
8184 	int idx, rc;
8185 
8186 	idx = vi->pktc_idx;
8187 
8188 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8189 	if (rc != 0 || req->newptr == NULL)
8190 		return (rc);
8191 
8192 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8193 		return (EINVAL);
8194 
8195 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8196 	    "t4pktc");
8197 	if (rc)
8198 		return (rc);
8199 
8200 	if (vi->flags & VI_INIT_DONE)
8201 		rc = EBUSY; /* cannot be changed once the queues are created */
8202 	else
8203 		vi->pktc_idx = idx;
8204 
8205 	end_synchronized_op(sc, LOCK_HELD);
8206 	return (rc);
8207 }
8208 
8209 static int
8210 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8211 {
8212 	struct vi_info *vi = arg1;
8213 	struct adapter *sc = vi->adapter;
8214 	int qsize, rc;
8215 
8216 	qsize = vi->qsize_rxq;
8217 
8218 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8219 	if (rc != 0 || req->newptr == NULL)
8220 		return (rc);
8221 
8222 	if (qsize < 128 || (qsize & 7))
8223 		return (EINVAL);
8224 
8225 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8226 	    "t4rxqs");
8227 	if (rc)
8228 		return (rc);
8229 
8230 	if (vi->flags & VI_INIT_DONE)
8231 		rc = EBUSY; /* cannot be changed once the queues are created */
8232 	else
8233 		vi->qsize_rxq = qsize;
8234 
8235 	end_synchronized_op(sc, LOCK_HELD);
8236 	return (rc);
8237 }
8238 
8239 static int
8240 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8241 {
8242 	struct vi_info *vi = arg1;
8243 	struct adapter *sc = vi->adapter;
8244 	int qsize, rc;
8245 
8246 	qsize = vi->qsize_txq;
8247 
8248 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8249 	if (rc != 0 || req->newptr == NULL)
8250 		return (rc);
8251 
8252 	if (qsize < 128 || qsize > 65536)
8253 		return (EINVAL);
8254 
8255 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8256 	    "t4txqs");
8257 	if (rc)
8258 		return (rc);
8259 
8260 	if (vi->flags & VI_INIT_DONE)
8261 		rc = EBUSY; /* cannot be changed once the queues are created */
8262 	else
8263 		vi->qsize_txq = qsize;
8264 
8265 	end_synchronized_op(sc, LOCK_HELD);
8266 	return (rc);
8267 }
8268 
8269 static int
8270 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8271 {
8272 	struct port_info *pi = arg1;
8273 	struct adapter *sc = pi->adapter;
8274 	struct link_config *lc = &pi->link_cfg;
8275 	int rc;
8276 
8277 	if (req->newptr == NULL) {
8278 		struct sbuf *sb;
8279 		static char *bits = "\20\1RX\2TX\3AUTO";
8280 
8281 		rc = sysctl_wire_old_buffer(req, 0);
8282 		if (rc != 0)
8283 			return(rc);
8284 
8285 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8286 		if (sb == NULL)
8287 			return (ENOMEM);
8288 
8289 		if (lc->link_ok) {
8290 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8291 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8292 		} else {
8293 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8294 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8295 		}
8296 		rc = sbuf_finish(sb);
8297 		sbuf_delete(sb);
8298 	} else {
8299 		char s[2];
8300 		int n;
8301 
8302 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8303 		    PAUSE_AUTONEG));
8304 		s[1] = 0;
8305 
8306 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8307 		if (rc != 0)
8308 			return(rc);
8309 
8310 		if (s[1] != 0)
8311 			return (EINVAL);
8312 		if (s[0] < '0' || s[0] > '9')
8313 			return (EINVAL);	/* not a number */
8314 		n = s[0] - '0';
8315 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8316 			return (EINVAL);	/* some other bit is set too */
8317 
8318 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8319 		    "t4PAUSE");
8320 		if (rc)
8321 			return (rc);
8322 		if (!hw_off_limits(sc)) {
8323 			PORT_LOCK(pi);
8324 			lc->requested_fc = n;
8325 			fixup_link_config(pi);
8326 			if (pi->up_vis > 0)
8327 				rc = apply_link_config(pi);
8328 			set_current_media(pi);
8329 			PORT_UNLOCK(pi);
8330 		}
8331 		end_synchronized_op(sc, 0);
8332 	}
8333 
8334 	return (rc);
8335 }
8336 
8337 static int
8338 sysctl_fec(SYSCTL_HANDLER_ARGS)
8339 {
8340 	struct port_info *pi = arg1;
8341 	struct adapter *sc = pi->adapter;
8342 	struct link_config *lc = &pi->link_cfg;
8343 	int rc;
8344 	int8_t old;
8345 
8346 	if (req->newptr == NULL) {
8347 		struct sbuf *sb;
8348 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8349 		    "\5RSVD3\6auto\7module";
8350 
8351 		rc = sysctl_wire_old_buffer(req, 0);
8352 		if (rc != 0)
8353 			return(rc);
8354 
8355 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8356 		if (sb == NULL)
8357 			return (ENOMEM);
8358 
8359 		/*
8360 		 * Display the requested_fec when the link is down -- the actual
8361 		 * FEC makes sense only when the link is up.
8362 		 */
8363 		if (lc->link_ok) {
8364 			sbuf_printf(sb, "%b", (lc->fec & M_FW_PORT_CAP32_FEC) |
8365 			    (lc->requested_fec & (FEC_AUTO | FEC_MODULE)),
8366 			    bits);
8367 		} else {
8368 			sbuf_printf(sb, "%b", lc->requested_fec, bits);
8369 		}
8370 		rc = sbuf_finish(sb);
8371 		sbuf_delete(sb);
8372 	} else {
8373 		char s[8];
8374 		int n;
8375 
8376 		snprintf(s, sizeof(s), "%d",
8377 		    lc->requested_fec == FEC_AUTO ? -1 :
8378 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8379 
8380 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8381 		if (rc != 0)
8382 			return(rc);
8383 
8384 		n = strtol(&s[0], NULL, 0);
8385 		if (n < 0 || n & FEC_AUTO)
8386 			n = FEC_AUTO;
8387 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8388 			return (EINVAL);/* some other bit is set too */
8389 
8390 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8391 		    "t4fec");
8392 		if (rc)
8393 			return (rc);
8394 		PORT_LOCK(pi);
8395 		old = lc->requested_fec;
8396 		if (n == FEC_AUTO)
8397 			lc->requested_fec = FEC_AUTO;
8398 		else if (n == 0 || n == FEC_NONE)
8399 			lc->requested_fec = FEC_NONE;
8400 		else {
8401 			if ((lc->pcaps |
8402 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8403 			    lc->pcaps) {
8404 				rc = ENOTSUP;
8405 				goto done;
8406 			}
8407 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8408 			    FEC_MODULE);
8409 		}
8410 		if (!hw_off_limits(sc)) {
8411 			fixup_link_config(pi);
8412 			if (pi->up_vis > 0) {
8413 				rc = apply_link_config(pi);
8414 				if (rc != 0) {
8415 					lc->requested_fec = old;
8416 					if (rc == FW_EPROTO)
8417 						rc = ENOTSUP;
8418 				}
8419 			}
8420 		}
8421 done:
8422 		PORT_UNLOCK(pi);
8423 		end_synchronized_op(sc, 0);
8424 	}
8425 
8426 	return (rc);
8427 }
8428 
8429 static int
8430 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8431 {
8432 	struct port_info *pi = arg1;
8433 	struct adapter *sc = pi->adapter;
8434 	struct link_config *lc = &pi->link_cfg;
8435 	int rc;
8436 	int8_t fec;
8437 	struct sbuf *sb;
8438 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8439 
8440 	rc = sysctl_wire_old_buffer(req, 0);
8441 	if (rc != 0)
8442 		return (rc);
8443 
8444 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8445 	if (sb == NULL)
8446 		return (ENOMEM);
8447 
8448 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8449 		rc = EBUSY;
8450 		goto done;
8451 	}
8452 	if (hw_off_limits(sc)) {
8453 		rc = ENXIO;
8454 		goto done;
8455 	}
8456 	PORT_LOCK(pi);
8457 	if (pi->up_vis == 0) {
8458 		/*
8459 		 * If all the interfaces are administratively down the firmware
8460 		 * does not report transceiver changes.  Refresh port info here.
8461 		 * This is the only reason we have a synchronized op in this
8462 		 * function.  Just PORT_LOCK would have been enough otherwise.
8463 		 */
8464 		t4_update_port_info(pi);
8465 	}
8466 
8467 	fec = lc->fec_hint;
8468 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8469 	    !fec_supported(lc->pcaps)) {
8470 		sbuf_printf(sb, "n/a");
8471 	} else {
8472 		if (fec == 0)
8473 			fec = FEC_NONE;
8474 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8475 	}
8476 	rc = sbuf_finish(sb);
8477 	PORT_UNLOCK(pi);
8478 done:
8479 	sbuf_delete(sb);
8480 	end_synchronized_op(sc, 0);
8481 
8482 	return (rc);
8483 }
8484 
8485 static int
8486 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8487 {
8488 	struct port_info *pi = arg1;
8489 	struct adapter *sc = pi->adapter;
8490 	struct link_config *lc = &pi->link_cfg;
8491 	int rc, val;
8492 
8493 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8494 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8495 	else
8496 		val = -1;
8497 	rc = sysctl_handle_int(oidp, &val, 0, req);
8498 	if (rc != 0 || req->newptr == NULL)
8499 		return (rc);
8500 	if (val == 0)
8501 		val = AUTONEG_DISABLE;
8502 	else if (val == 1)
8503 		val = AUTONEG_ENABLE;
8504 	else
8505 		val = AUTONEG_AUTO;
8506 
8507 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8508 	    "t4aneg");
8509 	if (rc)
8510 		return (rc);
8511 	PORT_LOCK(pi);
8512 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8513 		rc = ENOTSUP;
8514 		goto done;
8515 	}
8516 	lc->requested_aneg = val;
8517 	if (!hw_off_limits(sc)) {
8518 		fixup_link_config(pi);
8519 		if (pi->up_vis > 0)
8520 			rc = apply_link_config(pi);
8521 		set_current_media(pi);
8522 	}
8523 done:
8524 	PORT_UNLOCK(pi);
8525 	end_synchronized_op(sc, 0);
8526 	return (rc);
8527 }
8528 
8529 static int
8530 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8531 {
8532 	struct adapter *sc = arg1;
8533 	int rc, reg = arg2;
8534 	uint64_t val;
8535 
8536 	mtx_lock(&sc->reg_lock);
8537 	if (hw_off_limits(sc))
8538 		rc = ENXIO;
8539 	else {
8540 		rc = 0;
8541 		val = t4_read_reg64(sc, reg);
8542 	}
8543 	mtx_unlock(&sc->reg_lock);
8544 	if (rc == 0)
8545 		rc = sysctl_handle_64(oidp, &val, 0, req);
8546 	return (rc);
8547 }
8548 
8549 static int
8550 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8551 {
8552 	struct adapter *sc = arg1;
8553 	int rc, t;
8554 	uint32_t param, val;
8555 
8556 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8557 	if (rc)
8558 		return (rc);
8559 	if (hw_off_limits(sc))
8560 		rc = ENXIO;
8561 	else {
8562 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8563 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8564 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8565 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8566 	}
8567 	end_synchronized_op(sc, 0);
8568 	if (rc)
8569 		return (rc);
8570 
8571 	/* unknown is returned as 0 but we display -1 in that case */
8572 	t = val == 0 ? -1 : val;
8573 
8574 	rc = sysctl_handle_int(oidp, &t, 0, req);
8575 	return (rc);
8576 }
8577 
8578 static int
8579 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8580 {
8581 	struct adapter *sc = arg1;
8582 	int rc;
8583 	uint32_t param, val;
8584 
8585 	if (sc->params.core_vdd == 0) {
8586 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8587 		    "t4vdd");
8588 		if (rc)
8589 			return (rc);
8590 		if (hw_off_limits(sc))
8591 			rc = ENXIO;
8592 		else {
8593 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8594 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8595 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8596 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8597 			    &param, &val);
8598 		}
8599 		end_synchronized_op(sc, 0);
8600 		if (rc)
8601 			return (rc);
8602 		sc->params.core_vdd = val;
8603 	}
8604 
8605 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8606 }
8607 
8608 static int
8609 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8610 {
8611 	struct adapter *sc = arg1;
8612 	int rc, v;
8613 	uint32_t param, val;
8614 
8615 	v = sc->sensor_resets;
8616 	rc = sysctl_handle_int(oidp, &v, 0, req);
8617 	if (rc != 0 || req->newptr == NULL || v <= 0)
8618 		return (rc);
8619 
8620 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8621 	    chip_id(sc) < CHELSIO_T5)
8622 		return (ENOTSUP);
8623 
8624 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8625 	if (rc)
8626 		return (rc);
8627 	if (hw_off_limits(sc))
8628 		rc = ENXIO;
8629 	else {
8630 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8631 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8632 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8633 		val = 1;
8634 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8635 	}
8636 	end_synchronized_op(sc, 0);
8637 	if (rc == 0)
8638 		sc->sensor_resets++;
8639 	return (rc);
8640 }
8641 
8642 static int
8643 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8644 {
8645 	struct adapter *sc = arg1;
8646 	struct sbuf *sb;
8647 	int rc;
8648 	uint32_t param, val;
8649 
8650 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8651 	if (rc)
8652 		return (rc);
8653 	if (hw_off_limits(sc))
8654 		rc = ENXIO;
8655 	else {
8656 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8657 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8658 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8659 	}
8660 	end_synchronized_op(sc, 0);
8661 	if (rc)
8662 		return (rc);
8663 
8664 	rc = sysctl_wire_old_buffer(req, 0);
8665 	if (rc != 0)
8666 		return (rc);
8667 
8668 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8669 	if (sb == NULL)
8670 		return (ENOMEM);
8671 
8672 	if (val == 0xffffffff) {
8673 		/* Only debug and custom firmwares report load averages. */
8674 		sbuf_printf(sb, "not available");
8675 	} else {
8676 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8677 		    (val >> 16) & 0xff);
8678 	}
8679 	rc = sbuf_finish(sb);
8680 	sbuf_delete(sb);
8681 
8682 	return (rc);
8683 }
8684 
8685 static int
8686 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8687 {
8688 	struct adapter *sc = arg1;
8689 	struct sbuf *sb;
8690 	int rc, i;
8691 	uint16_t incr[NMTUS][NCCTRL_WIN];
8692 	static const char *dec_fac[] = {
8693 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8694 		"0.9375"
8695 	};
8696 
8697 	rc = sysctl_wire_old_buffer(req, 0);
8698 	if (rc != 0)
8699 		return (rc);
8700 
8701 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8702 	if (sb == NULL)
8703 		return (ENOMEM);
8704 
8705 	mtx_lock(&sc->reg_lock);
8706 	if (hw_off_limits(sc))
8707 		rc = ENXIO;
8708 	else
8709 		t4_read_cong_tbl(sc, incr);
8710 	mtx_unlock(&sc->reg_lock);
8711 	if (rc)
8712 		goto done;
8713 
8714 	for (i = 0; i < NCCTRL_WIN; ++i) {
8715 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8716 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8717 		    incr[5][i], incr[6][i], incr[7][i]);
8718 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8719 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8720 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8721 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8722 	}
8723 
8724 	rc = sbuf_finish(sb);
8725 done:
8726 	sbuf_delete(sb);
8727 	return (rc);
8728 }
8729 
8730 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8731 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8732 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8733 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8734 };
8735 
8736 static int
8737 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8738 {
8739 	struct adapter *sc = arg1;
8740 	struct sbuf *sb;
8741 	int rc, i, n, qid = arg2;
8742 	uint32_t *buf, *p;
8743 	char *qtype;
8744 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8745 
8746 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8747 	    ("%s: bad qid %d\n", __func__, qid));
8748 
8749 	if (qid < CIM_NUM_IBQ) {
8750 		/* inbound queue */
8751 		qtype = "IBQ";
8752 		n = 4 * CIM_IBQ_SIZE;
8753 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8754 		mtx_lock(&sc->reg_lock);
8755 		if (hw_off_limits(sc))
8756 			rc = -ENXIO;
8757 		else
8758 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8759 		mtx_unlock(&sc->reg_lock);
8760 	} else {
8761 		/* outbound queue */
8762 		qtype = "OBQ";
8763 		qid -= CIM_NUM_IBQ;
8764 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8765 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8766 		mtx_lock(&sc->reg_lock);
8767 		if (hw_off_limits(sc))
8768 			rc = -ENXIO;
8769 		else
8770 			rc = t4_read_cim_obq(sc, qid, buf, n);
8771 		mtx_unlock(&sc->reg_lock);
8772 	}
8773 
8774 	if (rc < 0) {
8775 		rc = -rc;
8776 		goto done;
8777 	}
8778 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
8779 
8780 	rc = sysctl_wire_old_buffer(req, 0);
8781 	if (rc != 0)
8782 		goto done;
8783 
8784 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8785 	if (sb == NULL) {
8786 		rc = ENOMEM;
8787 		goto done;
8788 	}
8789 
8790 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8791 	for (i = 0, p = buf; i < n; i += 16, p += 4)
8792 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
8793 		    p[2], p[3]);
8794 
8795 	rc = sbuf_finish(sb);
8796 	sbuf_delete(sb);
8797 done:
8798 	free(buf, M_CXGBE);
8799 	return (rc);
8800 }
8801 
8802 static void
8803 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8804 {
8805 	uint32_t *p;
8806 
8807 	sbuf_printf(sb, "Status   Data      PC%s",
8808 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8809 	    "     LS0Stat  LS0Addr             LS0Data");
8810 
8811 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
8812 		if (cfg & F_UPDBGLACAPTPCONLY) {
8813 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
8814 			    p[6], p[7]);
8815 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
8816 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
8817 			    p[4] & 0xff, p[5] >> 8);
8818 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
8819 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8820 			    p[1] & 0xf, p[2] >> 4);
8821 		} else {
8822 			sbuf_printf(sb,
8823 			    "\n  %02x   %x%07x %x%07x %08x %08x "
8824 			    "%08x%08x%08x%08x",
8825 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8826 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
8827 			    p[6], p[7]);
8828 		}
8829 	}
8830 }
8831 
8832 static void
8833 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8834 {
8835 	uint32_t *p;
8836 
8837 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
8838 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8839 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
8840 
8841 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
8842 		if (cfg & F_UPDBGLACAPTPCONLY) {
8843 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
8844 			    p[3] & 0xff, p[2], p[1], p[0]);
8845 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
8846 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
8847 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
8848 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
8849 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
8850 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
8851 			    p[6] >> 16);
8852 		} else {
8853 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
8854 			    "%08x %08x %08x %08x %08x %08x",
8855 			    (p[9] >> 16) & 0xff,
8856 			    p[9] & 0xffff, p[8] >> 16,
8857 			    p[8] & 0xffff, p[7] >> 16,
8858 			    p[7] & 0xffff, p[6] >> 16,
8859 			    p[2], p[1], p[0], p[5], p[4], p[3]);
8860 		}
8861 	}
8862 }
8863 
8864 static int
8865 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
8866 {
8867 	uint32_t cfg, *buf;
8868 	int rc;
8869 
8870 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
8871 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
8872 	    M_ZERO | flags);
8873 	if (buf == NULL)
8874 		return (ENOMEM);
8875 
8876 	mtx_lock(&sc->reg_lock);
8877 	if (hw_off_limits(sc))
8878 		rc = ENXIO;
8879 	else {
8880 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
8881 		if (rc == 0)
8882 			rc = -t4_cim_read_la(sc, buf, NULL);
8883 	}
8884 	mtx_unlock(&sc->reg_lock);
8885 	if (rc == 0) {
8886 		if (chip_id(sc) < CHELSIO_T6)
8887 			sbuf_cim_la4(sc, sb, buf, cfg);
8888 		else
8889 			sbuf_cim_la6(sc, sb, buf, cfg);
8890 	}
8891 	free(buf, M_CXGBE);
8892 	return (rc);
8893 }
8894 
8895 static int
8896 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
8897 {
8898 	struct adapter *sc = arg1;
8899 	struct sbuf *sb;
8900 	int rc;
8901 
8902 	rc = sysctl_wire_old_buffer(req, 0);
8903 	if (rc != 0)
8904 		return (rc);
8905 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8906 	if (sb == NULL)
8907 		return (ENOMEM);
8908 
8909 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
8910 	if (rc == 0)
8911 		rc = sbuf_finish(sb);
8912 	sbuf_delete(sb);
8913 	return (rc);
8914 }
8915 
8916 bool
8917 t4_os_dump_cimla(struct adapter *sc, int arg, bool verbose)
8918 {
8919 	struct sbuf sb;
8920 	int rc;
8921 
8922 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
8923 		return (false);
8924 	rc = sbuf_cim_la(sc, &sb, M_NOWAIT);
8925 	if (rc == 0) {
8926 		rc = sbuf_finish(&sb);
8927 		if (rc == 0) {
8928 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s",
8929 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
8930 		}
8931 	}
8932 	sbuf_delete(&sb);
8933 	return (false);
8934 }
8935 
8936 static int
8937 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
8938 {
8939 	struct adapter *sc = arg1;
8940 	u_int i;
8941 	struct sbuf *sb;
8942 	uint32_t *buf, *p;
8943 	int rc;
8944 
8945 	rc = sysctl_wire_old_buffer(req, 0);
8946 	if (rc != 0)
8947 		return (rc);
8948 
8949 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8950 	if (sb == NULL)
8951 		return (ENOMEM);
8952 
8953 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
8954 	    M_ZERO | M_WAITOK);
8955 
8956 	mtx_lock(&sc->reg_lock);
8957 	if (hw_off_limits(sc))
8958 		rc = ENXIO;
8959 	else
8960 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
8961 	mtx_unlock(&sc->reg_lock);
8962 	if (rc)
8963 		goto done;
8964 
8965 	p = buf;
8966 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
8967 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
8968 		    p[1], p[0]);
8969 	}
8970 
8971 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
8972 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
8973 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
8974 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
8975 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
8976 		    (p[1] >> 2) | ((p[2] & 3) << 30),
8977 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
8978 		    p[0] & 1);
8979 	}
8980 	rc = sbuf_finish(sb);
8981 done:
8982 	sbuf_delete(sb);
8983 	free(buf, M_CXGBE);
8984 	return (rc);
8985 }
8986 
8987 static int
8988 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
8989 {
8990 	struct adapter *sc = arg1;
8991 	u_int i;
8992 	struct sbuf *sb;
8993 	uint32_t *buf, *p;
8994 	int rc;
8995 
8996 	rc = sysctl_wire_old_buffer(req, 0);
8997 	if (rc != 0)
8998 		return (rc);
8999 
9000 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9001 	if (sb == NULL)
9002 		return (ENOMEM);
9003 
9004 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9005 	    M_ZERO | M_WAITOK);
9006 
9007 	mtx_lock(&sc->reg_lock);
9008 	if (hw_off_limits(sc))
9009 		rc = ENXIO;
9010 	else
9011 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9012 	mtx_unlock(&sc->reg_lock);
9013 	if (rc)
9014 		goto done;
9015 
9016 	p = buf;
9017 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9018 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9019 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9020 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9021 		    p[4], p[3], p[2], p[1], p[0]);
9022 	}
9023 
9024 	sbuf_printf(sb, "\n\nCntl ID               Data");
9025 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9026 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9027 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9028 	}
9029 
9030 	rc = sbuf_finish(sb);
9031 done:
9032 	sbuf_delete(sb);
9033 	free(buf, M_CXGBE);
9034 	return (rc);
9035 }
9036 
9037 static int
9038 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9039 {
9040 	struct adapter *sc = arg1;
9041 	struct sbuf *sb;
9042 	int rc, i;
9043 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9044 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9045 	uint16_t thres[CIM_NUM_IBQ];
9046 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9047 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9048 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9049 
9050 	cim_num_obq = sc->chip_params->cim_num_obq;
9051 	if (is_t4(sc)) {
9052 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9053 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9054 	} else {
9055 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9056 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9057 	}
9058 	nq = CIM_NUM_IBQ + cim_num_obq;
9059 
9060 	mtx_lock(&sc->reg_lock);
9061 	if (hw_off_limits(sc))
9062 		rc = ENXIO;
9063 	else {
9064 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9065 		if (rc == 0) {
9066 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9067 			    obq_wr);
9068 			if (rc == 0)
9069 				t4_read_cimq_cfg(sc, base, size, thres);
9070 		}
9071 	}
9072 	mtx_unlock(&sc->reg_lock);
9073 	if (rc)
9074 		return (rc);
9075 
9076 	rc = sysctl_wire_old_buffer(req, 0);
9077 	if (rc != 0)
9078 		return (rc);
9079 
9080 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9081 	if (sb == NULL)
9082 		return (ENOMEM);
9083 
9084 	sbuf_printf(sb,
9085 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9086 
9087 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9088 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9089 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9090 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9091 		    G_QUEREMFLITS(p[2]) * 16);
9092 	for ( ; i < nq; i++, p += 4, wr += 2)
9093 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9094 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9095 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9096 		    G_QUEREMFLITS(p[2]) * 16);
9097 
9098 	rc = sbuf_finish(sb);
9099 	sbuf_delete(sb);
9100 
9101 	return (rc);
9102 }
9103 
9104 static int
9105 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9106 {
9107 	struct adapter *sc = arg1;
9108 	struct sbuf *sb;
9109 	int rc;
9110 	struct tp_cpl_stats stats;
9111 
9112 	rc = sysctl_wire_old_buffer(req, 0);
9113 	if (rc != 0)
9114 		return (rc);
9115 
9116 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9117 	if (sb == NULL)
9118 		return (ENOMEM);
9119 
9120 	mtx_lock(&sc->reg_lock);
9121 	if (hw_off_limits(sc))
9122 		rc = ENXIO;
9123 	else
9124 		t4_tp_get_cpl_stats(sc, &stats, 0);
9125 	mtx_unlock(&sc->reg_lock);
9126 	if (rc)
9127 		goto done;
9128 
9129 	if (sc->chip_params->nchan > 2) {
9130 		sbuf_printf(sb, "                 channel 0  channel 1"
9131 		    "  channel 2  channel 3");
9132 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9133 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9134 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9135 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9136 	} else {
9137 		sbuf_printf(sb, "                 channel 0  channel 1");
9138 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9139 		    stats.req[0], stats.req[1]);
9140 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9141 		    stats.rsp[0], stats.rsp[1]);
9142 	}
9143 
9144 	rc = sbuf_finish(sb);
9145 done:
9146 	sbuf_delete(sb);
9147 	return (rc);
9148 }
9149 
9150 static int
9151 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9152 {
9153 	struct adapter *sc = arg1;
9154 	struct sbuf *sb;
9155 	int rc;
9156 	struct tp_usm_stats stats;
9157 
9158 	rc = sysctl_wire_old_buffer(req, 0);
9159 	if (rc != 0)
9160 		return(rc);
9161 
9162 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9163 	if (sb == NULL)
9164 		return (ENOMEM);
9165 
9166 	mtx_lock(&sc->reg_lock);
9167 	if (hw_off_limits(sc))
9168 		rc = ENXIO;
9169 	else
9170 		t4_get_usm_stats(sc, &stats, 1);
9171 	mtx_unlock(&sc->reg_lock);
9172 	if (rc == 0) {
9173 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9174 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9175 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9176 		rc = sbuf_finish(sb);
9177 	}
9178 	sbuf_delete(sb);
9179 
9180 	return (rc);
9181 }
9182 
9183 static int
9184 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9185 {
9186 	struct adapter *sc = arg1;
9187 	struct sbuf *sb;
9188 	int rc;
9189 	struct tp_tid_stats stats;
9190 
9191 	rc = sysctl_wire_old_buffer(req, 0);
9192 	if (rc != 0)
9193 		return(rc);
9194 
9195 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9196 	if (sb == NULL)
9197 		return (ENOMEM);
9198 
9199 	mtx_lock(&sc->reg_lock);
9200 	if (hw_off_limits(sc))
9201 		rc = ENXIO;
9202 	else
9203 		t4_tp_get_tid_stats(sc, &stats, 1);
9204 	mtx_unlock(&sc->reg_lock);
9205 	if (rc == 0) {
9206 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9207 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9208 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9209 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9210 		rc = sbuf_finish(sb);
9211 	}
9212 	sbuf_delete(sb);
9213 
9214 	return (rc);
9215 }
9216 
9217 static const char * const devlog_level_strings[] = {
9218 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9219 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9220 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9221 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9222 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9223 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9224 };
9225 
9226 static const char * const devlog_facility_strings[] = {
9227 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9228 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9229 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9230 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9231 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9232 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9233 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9234 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9235 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9236 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9237 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9238 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9239 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9240 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9241 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9242 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9243 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9244 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9245 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9246 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9247 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9248 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9249 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9250 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9251 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9252 };
9253 
9254 static int
9255 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9256 {
9257 	int i, j, rc, nentries, first = 0;
9258 	struct devlog_params *dparams = &sc->params.devlog;
9259 	struct fw_devlog_e *buf, *e;
9260 	uint64_t ftstamp = UINT64_MAX;
9261 
9262 	if (dparams->addr == 0)
9263 		return (ENXIO);
9264 
9265 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9266 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9267 	if (buf == NULL)
9268 		return (ENOMEM);
9269 
9270 	mtx_lock(&sc->reg_lock);
9271 	if (hw_off_limits(sc))
9272 		rc = ENXIO;
9273 	else
9274 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9275 		    dparams->size);
9276 	mtx_unlock(&sc->reg_lock);
9277 	if (rc != 0)
9278 		goto done;
9279 
9280 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9281 	for (i = 0; i < nentries; i++) {
9282 		e = &buf[i];
9283 
9284 		if (e->timestamp == 0)
9285 			break;	/* end */
9286 
9287 		e->timestamp = be64toh(e->timestamp);
9288 		e->seqno = be32toh(e->seqno);
9289 		for (j = 0; j < 8; j++)
9290 			e->params[j] = be32toh(e->params[j]);
9291 
9292 		if (e->timestamp < ftstamp) {
9293 			ftstamp = e->timestamp;
9294 			first = i;
9295 		}
9296 	}
9297 
9298 	if (buf[first].timestamp == 0)
9299 		goto done;	/* nothing in the log */
9300 
9301 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9302 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9303 
9304 	i = first;
9305 	do {
9306 		e = &buf[i];
9307 		if (e->timestamp == 0)
9308 			break;	/* end */
9309 
9310 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9311 		    e->seqno, e->timestamp,
9312 		    (e->level < nitems(devlog_level_strings) ?
9313 			devlog_level_strings[e->level] : "UNKNOWN"),
9314 		    (e->facility < nitems(devlog_facility_strings) ?
9315 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9316 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9317 		    e->params[2], e->params[3], e->params[4],
9318 		    e->params[5], e->params[6], e->params[7]);
9319 
9320 		if (++i == nentries)
9321 			i = 0;
9322 	} while (i != first);
9323 done:
9324 	free(buf, M_CXGBE);
9325 	return (rc);
9326 }
9327 
9328 static int
9329 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9330 {
9331 	struct adapter *sc = arg1;
9332 	int rc;
9333 	struct sbuf *sb;
9334 
9335 	rc = sysctl_wire_old_buffer(req, 0);
9336 	if (rc != 0)
9337 		return (rc);
9338 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9339 	if (sb == NULL)
9340 		return (ENOMEM);
9341 
9342 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9343 	if (rc == 0)
9344 		rc = sbuf_finish(sb);
9345 	sbuf_delete(sb);
9346 	return (rc);
9347 }
9348 
9349 void
9350 t4_os_dump_devlog(struct adapter *sc)
9351 {
9352 	int rc;
9353 	struct sbuf sb;
9354 
9355 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
9356 		return;
9357 	rc = sbuf_devlog(sc, &sb, M_NOWAIT);
9358 	if (rc == 0) {
9359 		rc = sbuf_finish(&sb);
9360 		if (rc == 0) {
9361 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9362 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
9363 		}
9364 	}
9365 	sbuf_delete(&sb);
9366 }
9367 
9368 static int
9369 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9370 {
9371 	struct adapter *sc = arg1;
9372 	struct sbuf *sb;
9373 	int rc;
9374 	struct tp_fcoe_stats stats[MAX_NCHAN];
9375 	int i, nchan = sc->chip_params->nchan;
9376 
9377 	rc = sysctl_wire_old_buffer(req, 0);
9378 	if (rc != 0)
9379 		return (rc);
9380 
9381 	mtx_lock(&sc->reg_lock);
9382 	if (hw_off_limits(sc))
9383 		rc = ENXIO;
9384 	else {
9385 		for (i = 0; i < nchan; i++)
9386 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9387 	}
9388 	mtx_unlock(&sc->reg_lock);
9389 	if (rc != 0)
9390 		return (rc);
9391 
9392 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9393 	if (sb == NULL)
9394 		return (ENOMEM);
9395 
9396 	if (nchan > 2) {
9397 		sbuf_printf(sb, "                   channel 0        channel 1"
9398 		    "        channel 2        channel 3");
9399 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9400 		    stats[0].octets_ddp, stats[1].octets_ddp,
9401 		    stats[2].octets_ddp, stats[3].octets_ddp);
9402 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9403 		    stats[0].frames_ddp, stats[1].frames_ddp,
9404 		    stats[2].frames_ddp, stats[3].frames_ddp);
9405 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9406 		    stats[0].frames_drop, stats[1].frames_drop,
9407 		    stats[2].frames_drop, stats[3].frames_drop);
9408 	} else {
9409 		sbuf_printf(sb, "                   channel 0        channel 1");
9410 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9411 		    stats[0].octets_ddp, stats[1].octets_ddp);
9412 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9413 		    stats[0].frames_ddp, stats[1].frames_ddp);
9414 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9415 		    stats[0].frames_drop, stats[1].frames_drop);
9416 	}
9417 
9418 	rc = sbuf_finish(sb);
9419 	sbuf_delete(sb);
9420 
9421 	return (rc);
9422 }
9423 
9424 static int
9425 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9426 {
9427 	struct adapter *sc = arg1;
9428 	struct sbuf *sb;
9429 	int rc, i;
9430 	unsigned int map, kbps, ipg, mode;
9431 	unsigned int pace_tab[NTX_SCHED];
9432 
9433 	rc = sysctl_wire_old_buffer(req, 0);
9434 	if (rc != 0)
9435 		return (rc);
9436 
9437 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9438 	if (sb == NULL)
9439 		return (ENOMEM);
9440 
9441 	mtx_lock(&sc->reg_lock);
9442 	if (hw_off_limits(sc)) {
9443 		rc = ENXIO;
9444 		goto done;
9445 	}
9446 
9447 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9448 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9449 	t4_read_pace_tbl(sc, pace_tab);
9450 
9451 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9452 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9453 
9454 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9455 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9456 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9457 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9458 		if (kbps)
9459 			sbuf_printf(sb, "%9u     ", kbps);
9460 		else
9461 			sbuf_printf(sb, " disabled     ");
9462 
9463 		if (ipg)
9464 			sbuf_printf(sb, "%13u        ", ipg);
9465 		else
9466 			sbuf_printf(sb, "     disabled        ");
9467 
9468 		if (pace_tab[i])
9469 			sbuf_printf(sb, "%10u", pace_tab[i]);
9470 		else
9471 			sbuf_printf(sb, "  disabled");
9472 	}
9473 	rc = sbuf_finish(sb);
9474 done:
9475 	mtx_unlock(&sc->reg_lock);
9476 	sbuf_delete(sb);
9477 	return (rc);
9478 }
9479 
9480 static int
9481 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9482 {
9483 	struct adapter *sc = arg1;
9484 	struct sbuf *sb;
9485 	int rc, i, j;
9486 	uint64_t *p0, *p1;
9487 	struct lb_port_stats s[2];
9488 	static const char *stat_name[] = {
9489 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9490 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9491 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9492 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9493 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9494 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9495 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9496 	};
9497 
9498 	rc = sysctl_wire_old_buffer(req, 0);
9499 	if (rc != 0)
9500 		return (rc);
9501 
9502 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9503 	if (sb == NULL)
9504 		return (ENOMEM);
9505 
9506 	memset(s, 0, sizeof(s));
9507 
9508 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9509 		mtx_lock(&sc->reg_lock);
9510 		if (hw_off_limits(sc))
9511 			rc = ENXIO;
9512 		else {
9513 			t4_get_lb_stats(sc, i, &s[0]);
9514 			t4_get_lb_stats(sc, i + 1, &s[1]);
9515 		}
9516 		mtx_unlock(&sc->reg_lock);
9517 		if (rc != 0)
9518 			break;
9519 
9520 		p0 = &s[0].octets;
9521 		p1 = &s[1].octets;
9522 		sbuf_printf(sb, "%s                       Loopback %u"
9523 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9524 
9525 		for (j = 0; j < nitems(stat_name); j++)
9526 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9527 				   *p0++, *p1++);
9528 	}
9529 
9530 	rc = sbuf_finish(sb);
9531 	sbuf_delete(sb);
9532 
9533 	return (rc);
9534 }
9535 
9536 static int
9537 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9538 {
9539 	int rc = 0;
9540 	struct port_info *pi = arg1;
9541 	struct link_config *lc = &pi->link_cfg;
9542 	struct sbuf *sb;
9543 
9544 	rc = sysctl_wire_old_buffer(req, 0);
9545 	if (rc != 0)
9546 		return(rc);
9547 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9548 	if (sb == NULL)
9549 		return (ENOMEM);
9550 
9551 	if (lc->link_ok || lc->link_down_rc == 255)
9552 		sbuf_printf(sb, "n/a");
9553 	else
9554 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9555 
9556 	rc = sbuf_finish(sb);
9557 	sbuf_delete(sb);
9558 
9559 	return (rc);
9560 }
9561 
9562 struct mem_desc {
9563 	unsigned int base;
9564 	unsigned int limit;
9565 	unsigned int idx;
9566 };
9567 
9568 static int
9569 mem_desc_cmp(const void *a, const void *b)
9570 {
9571 	return ((const struct mem_desc *)a)->base -
9572 	       ((const struct mem_desc *)b)->base;
9573 }
9574 
9575 static void
9576 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9577     unsigned int to)
9578 {
9579 	unsigned int size;
9580 
9581 	if (from == to)
9582 		return;
9583 
9584 	size = to - from + 1;
9585 	if (size == 0)
9586 		return;
9587 
9588 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9589 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9590 }
9591 
9592 static int
9593 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9594 {
9595 	struct adapter *sc = arg1;
9596 	struct sbuf *sb;
9597 	int rc, i, n;
9598 	uint32_t lo, hi, used, alloc;
9599 	static const char *memory[] = {"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:"};
9600 	static const char *region[] = {
9601 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9602 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9603 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9604 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9605 		"RQUDP region:", "PBL region:", "TXPBL region:",
9606 		"DBVFIFO region:", "ULPRX state:", "ULPTX state:",
9607 		"On-chip queues:", "TLS keys:",
9608 	};
9609 	struct mem_desc avail[4];
9610 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9611 	struct mem_desc *md = mem;
9612 
9613 	rc = sysctl_wire_old_buffer(req, 0);
9614 	if (rc != 0)
9615 		return (rc);
9616 
9617 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9618 	if (sb == NULL)
9619 		return (ENOMEM);
9620 
9621 	for (i = 0; i < nitems(mem); i++) {
9622 		mem[i].limit = 0;
9623 		mem[i].idx = i;
9624 	}
9625 
9626 	mtx_lock(&sc->reg_lock);
9627 	if (hw_off_limits(sc)) {
9628 		rc = ENXIO;
9629 		goto done;
9630 	}
9631 
9632 	/* Find and sort the populated memory ranges */
9633 	i = 0;
9634 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9635 	if (lo & F_EDRAM0_ENABLE) {
9636 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9637 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9638 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9639 		avail[i].idx = 0;
9640 		i++;
9641 	}
9642 	if (lo & F_EDRAM1_ENABLE) {
9643 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9644 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9645 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9646 		avail[i].idx = 1;
9647 		i++;
9648 	}
9649 	if (lo & F_EXT_MEM_ENABLE) {
9650 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9651 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9652 		avail[i].limit = avail[i].base +
9653 		    (G_EXT_MEM_SIZE(hi) << 20);
9654 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9655 		i++;
9656 	}
9657 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9658 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9659 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9660 		avail[i].limit = avail[i].base +
9661 		    (G_EXT_MEM1_SIZE(hi) << 20);
9662 		avail[i].idx = 4;
9663 		i++;
9664 	}
9665 	if (!i)                                    /* no memory available */
9666 		goto done;
9667 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9668 
9669 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9670 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9671 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9672 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9673 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9674 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9675 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9676 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9677 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9678 
9679 	/* the next few have explicit upper bounds */
9680 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9681 	md->limit = md->base - 1 +
9682 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9683 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9684 	md++;
9685 
9686 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9687 	md->limit = md->base - 1 +
9688 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9689 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9690 	md++;
9691 
9692 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9693 		if (chip_id(sc) <= CHELSIO_T5)
9694 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9695 		else
9696 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9697 		md->limit = 0;
9698 	} else {
9699 		md->base = 0;
9700 		md->idx = nitems(region);  /* hide it */
9701 	}
9702 	md++;
9703 
9704 #define ulp_region(reg) \
9705 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9706 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9707 
9708 	ulp_region(RX_ISCSI);
9709 	ulp_region(RX_TDDP);
9710 	ulp_region(TX_TPT);
9711 	ulp_region(RX_STAG);
9712 	ulp_region(RX_RQ);
9713 	ulp_region(RX_RQUDP);
9714 	ulp_region(RX_PBL);
9715 	ulp_region(TX_PBL);
9716 #undef ulp_region
9717 
9718 	md->base = 0;
9719 	md->idx = nitems(region);
9720 	if (!is_t4(sc)) {
9721 		uint32_t size = 0;
9722 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9723 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9724 
9725 		if (is_t5(sc)) {
9726 			if (sge_ctrl & F_VFIFO_ENABLE)
9727 				size = G_DBVFIFO_SIZE(fifo_size);
9728 		} else
9729 			size = G_T6_DBVFIFO_SIZE(fifo_size);
9730 
9731 		if (size) {
9732 			md->base = G_BASEADDR(t4_read_reg(sc,
9733 			    A_SGE_DBVFIFO_BADDR));
9734 			md->limit = md->base + (size << 2) - 1;
9735 		}
9736 	}
9737 	md++;
9738 
9739 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9740 	md->limit = 0;
9741 	md++;
9742 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9743 	md->limit = 0;
9744 	md++;
9745 
9746 	md->base = sc->vres.ocq.start;
9747 	if (sc->vres.ocq.size)
9748 		md->limit = md->base + sc->vres.ocq.size - 1;
9749 	else
9750 		md->idx = nitems(region);  /* hide it */
9751 	md++;
9752 
9753 	md->base = sc->vres.key.start;
9754 	if (sc->vres.key.size)
9755 		md->limit = md->base + sc->vres.key.size - 1;
9756 	else
9757 		md->idx = nitems(region);  /* hide it */
9758 	md++;
9759 
9760 	/* add any address-space holes, there can be up to 3 */
9761 	for (n = 0; n < i - 1; n++)
9762 		if (avail[n].limit < avail[n + 1].base)
9763 			(md++)->base = avail[n].limit;
9764 	if (avail[n].limit)
9765 		(md++)->base = avail[n].limit;
9766 
9767 	n = md - mem;
9768 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
9769 
9770 	for (lo = 0; lo < i; lo++)
9771 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
9772 				avail[lo].limit - 1);
9773 
9774 	sbuf_printf(sb, "\n");
9775 	for (i = 0; i < n; i++) {
9776 		if (mem[i].idx >= nitems(region))
9777 			continue;                        /* skip holes */
9778 		if (!mem[i].limit)
9779 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
9780 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
9781 				mem[i].limit);
9782 	}
9783 
9784 	sbuf_printf(sb, "\n");
9785 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
9786 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
9787 	mem_region_show(sb, "uP RAM:", lo, hi);
9788 
9789 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
9790 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
9791 	mem_region_show(sb, "uP Extmem2:", lo, hi);
9792 
9793 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
9794 	sbuf_printf(sb, "\n%u Rx pages of size %uKiB for %u channels\n",
9795 		   G_PMRXMAXPAGE(lo),
9796 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
9797 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
9798 
9799 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
9800 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
9801 	sbuf_printf(sb, "%u Tx pages of size %u%ciB for %u channels\n",
9802 		   G_PMTXMAXPAGE(lo),
9803 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
9804 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
9805 	sbuf_printf(sb, "%u p-structs\n",
9806 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT));
9807 
9808 	for (i = 0; i < 4; i++) {
9809 		if (chip_id(sc) > CHELSIO_T5)
9810 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
9811 		else
9812 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
9813 		if (is_t5(sc)) {
9814 			used = G_T5_USED(lo);
9815 			alloc = G_T5_ALLOC(lo);
9816 		} else {
9817 			used = G_USED(lo);
9818 			alloc = G_ALLOC(lo);
9819 		}
9820 		/* For T6 these are MAC buffer groups */
9821 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
9822 		    i, used, alloc);
9823 	}
9824 	for (i = 0; i < sc->chip_params->nchan; i++) {
9825 		if (chip_id(sc) > CHELSIO_T5)
9826 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
9827 		else
9828 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
9829 		if (is_t5(sc)) {
9830 			used = G_T5_USED(lo);
9831 			alloc = G_T5_ALLOC(lo);
9832 		} else {
9833 			used = G_USED(lo);
9834 			alloc = G_ALLOC(lo);
9835 		}
9836 		/* For T6 these are MAC buffer groups */
9837 		sbuf_printf(sb,
9838 		    "\nLoopback %d using %u pages out of %u allocated",
9839 		    i, used, alloc);
9840 	}
9841 done:
9842 	mtx_unlock(&sc->reg_lock);
9843 	if (rc == 0)
9844 		rc = sbuf_finish(sb);
9845 	sbuf_delete(sb);
9846 	return (rc);
9847 }
9848 
9849 static inline void
9850 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
9851 {
9852 	*mask = x | y;
9853 	y = htobe64(y);
9854 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
9855 }
9856 
9857 static int
9858 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
9859 {
9860 	struct adapter *sc = arg1;
9861 	struct sbuf *sb;
9862 	int rc, i;
9863 
9864 	MPASS(chip_id(sc) <= CHELSIO_T5);
9865 
9866 	rc = sysctl_wire_old_buffer(req, 0);
9867 	if (rc != 0)
9868 		return (rc);
9869 
9870 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9871 	if (sb == NULL)
9872 		return (ENOMEM);
9873 
9874 	sbuf_printf(sb,
9875 	    "Idx  Ethernet address     Mask     Vld Ports PF"
9876 	    "  VF              Replication             P0 P1 P2 P3  ML");
9877 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
9878 		uint64_t tcamx, tcamy, mask;
9879 		uint32_t cls_lo, cls_hi;
9880 		uint8_t addr[ETHER_ADDR_LEN];
9881 
9882 		mtx_lock(&sc->reg_lock);
9883 		if (hw_off_limits(sc))
9884 			rc = ENXIO;
9885 		else {
9886 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
9887 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
9888 		}
9889 		mtx_unlock(&sc->reg_lock);
9890 		if (rc != 0)
9891 			break;
9892 		if (tcamx & tcamy)
9893 			continue;
9894 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
9895 		mtx_lock(&sc->reg_lock);
9896 		if (hw_off_limits(sc))
9897 			rc = ENXIO;
9898 		else {
9899 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
9900 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
9901 		}
9902 		mtx_unlock(&sc->reg_lock);
9903 		if (rc != 0)
9904 			break;
9905 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
9906 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
9907 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
9908 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
9909 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
9910 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
9911 
9912 		if (cls_lo & F_REPLICATE) {
9913 			struct fw_ldst_cmd ldst_cmd;
9914 
9915 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
9916 			ldst_cmd.op_to_addrspace =
9917 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
9918 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
9919 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
9920 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
9921 			ldst_cmd.u.mps.rplc.fid_idx =
9922 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
9923 				V_FW_LDST_CMD_IDX(i));
9924 
9925 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
9926 			    "t4mps");
9927 			if (rc)
9928 				break;
9929 			if (hw_off_limits(sc))
9930 				rc = ENXIO;
9931 			else
9932 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
9933 				    sizeof(ldst_cmd), &ldst_cmd);
9934 			end_synchronized_op(sc, 0);
9935 			if (rc != 0)
9936 				break;
9937 			else {
9938 				sbuf_printf(sb, " %08x %08x %08x %08x",
9939 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
9940 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
9941 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
9942 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
9943 			}
9944 		} else
9945 			sbuf_printf(sb, "%36s", "");
9946 
9947 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
9948 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
9949 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
9950 	}
9951 
9952 	if (rc)
9953 		(void) sbuf_finish(sb);
9954 	else
9955 		rc = sbuf_finish(sb);
9956 	sbuf_delete(sb);
9957 
9958 	return (rc);
9959 }
9960 
9961 static int
9962 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
9963 {
9964 	struct adapter *sc = arg1;
9965 	struct sbuf *sb;
9966 	int rc, i;
9967 
9968 	MPASS(chip_id(sc) > CHELSIO_T5);
9969 
9970 	rc = sysctl_wire_old_buffer(req, 0);
9971 	if (rc != 0)
9972 		return (rc);
9973 
9974 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9975 	if (sb == NULL)
9976 		return (ENOMEM);
9977 
9978 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
9979 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
9980 	    "                           Replication"
9981 	    "                                    P0 P1 P2 P3  ML\n");
9982 
9983 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
9984 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
9985 		uint16_t ivlan;
9986 		uint64_t tcamx, tcamy, val, mask;
9987 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
9988 		uint8_t addr[ETHER_ADDR_LEN];
9989 
9990 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
9991 		if (i < 256)
9992 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
9993 		else
9994 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
9995 		mtx_lock(&sc->reg_lock);
9996 		if (hw_off_limits(sc))
9997 			rc = ENXIO;
9998 		else {
9999 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10000 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10001 			tcamy = G_DMACH(val) << 32;
10002 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10003 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10004 		}
10005 		mtx_unlock(&sc->reg_lock);
10006 		if (rc != 0)
10007 			break;
10008 
10009 		lookup_type = G_DATALKPTYPE(data2);
10010 		port_num = G_DATAPORTNUM(data2);
10011 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10012 			/* Inner header VNI */
10013 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10014 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10015 			dip_hit = data2 & F_DATADIPHIT;
10016 			vlan_vld = 0;
10017 		} else {
10018 			vniy = 0;
10019 			dip_hit = 0;
10020 			vlan_vld = data2 & F_DATAVIDH2;
10021 			ivlan = G_VIDL(val);
10022 		}
10023 
10024 		ctl |= V_CTLXYBITSEL(1);
10025 		mtx_lock(&sc->reg_lock);
10026 		if (hw_off_limits(sc))
10027 			rc = ENXIO;
10028 		else {
10029 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10030 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10031 			tcamx = G_DMACH(val) << 32;
10032 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10033 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10034 		}
10035 		mtx_unlock(&sc->reg_lock);
10036 		if (rc != 0)
10037 			break;
10038 
10039 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10040 			/* Inner header VNI mask */
10041 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10042 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10043 		} else
10044 			vnix = 0;
10045 
10046 		if (tcamx & tcamy)
10047 			continue;
10048 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10049 
10050 		mtx_lock(&sc->reg_lock);
10051 		if (hw_off_limits(sc))
10052 			rc = ENXIO;
10053 		else {
10054 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10055 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10056 		}
10057 		mtx_unlock(&sc->reg_lock);
10058 		if (rc != 0)
10059 			break;
10060 
10061 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10062 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10063 			    "%012jx %06x %06x    -    -   %3c"
10064 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10065 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10066 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10067 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10068 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10069 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10070 		} else {
10071 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10072 			    "%012jx    -       -   ", i, addr[0], addr[1],
10073 			    addr[2], addr[3], addr[4], addr[5],
10074 			    (uintmax_t)mask);
10075 
10076 			if (vlan_vld)
10077 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10078 			else
10079 				sbuf_printf(sb, "  -    N     ");
10080 
10081 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10082 			    lookup_type ? 'I' : 'O', port_num,
10083 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10084 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10085 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10086 		}
10087 
10088 
10089 		if (cls_lo & F_T6_REPLICATE) {
10090 			struct fw_ldst_cmd ldst_cmd;
10091 
10092 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10093 			ldst_cmd.op_to_addrspace =
10094 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10095 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10096 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10097 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10098 			ldst_cmd.u.mps.rplc.fid_idx =
10099 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10100 				V_FW_LDST_CMD_IDX(i));
10101 
10102 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10103 			    "t6mps");
10104 			if (rc)
10105 				break;
10106 			if (hw_off_limits(sc))
10107 				rc = ENXIO;
10108 			else
10109 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10110 				    sizeof(ldst_cmd), &ldst_cmd);
10111 			end_synchronized_op(sc, 0);
10112 			if (rc != 0)
10113 				break;
10114 			else {
10115 				sbuf_printf(sb, " %08x %08x %08x %08x"
10116 				    " %08x %08x %08x %08x",
10117 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10118 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10119 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10120 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10121 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10122 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10123 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10124 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10125 			}
10126 		} else
10127 			sbuf_printf(sb, "%72s", "");
10128 
10129 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10130 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10131 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10132 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10133 	}
10134 
10135 	if (rc)
10136 		(void) sbuf_finish(sb);
10137 	else
10138 		rc = sbuf_finish(sb);
10139 	sbuf_delete(sb);
10140 
10141 	return (rc);
10142 }
10143 
10144 static int
10145 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10146 {
10147 	struct adapter *sc = arg1;
10148 	struct sbuf *sb;
10149 	int rc;
10150 	uint16_t mtus[NMTUS];
10151 
10152 	rc = sysctl_wire_old_buffer(req, 0);
10153 	if (rc != 0)
10154 		return (rc);
10155 
10156 	mtx_lock(&sc->reg_lock);
10157 	if (hw_off_limits(sc))
10158 		rc = ENXIO;
10159 	else
10160 		t4_read_mtu_tbl(sc, mtus, NULL);
10161 	mtx_unlock(&sc->reg_lock);
10162 	if (rc != 0)
10163 		return (rc);
10164 
10165 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10166 	if (sb == NULL)
10167 		return (ENOMEM);
10168 
10169 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10170 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10171 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10172 	    mtus[14], mtus[15]);
10173 
10174 	rc = sbuf_finish(sb);
10175 	sbuf_delete(sb);
10176 
10177 	return (rc);
10178 }
10179 
10180 static int
10181 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10182 {
10183 	struct adapter *sc = arg1;
10184 	struct sbuf *sb;
10185 	int rc, i;
10186 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10187 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10188 	static const char *tx_stats[MAX_PM_NSTATS] = {
10189 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10190 		"Tx FIFO wait", NULL, "Tx latency"
10191 	};
10192 	static const char *rx_stats[MAX_PM_NSTATS] = {
10193 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10194 		"Rx FIFO wait", NULL, "Rx latency"
10195 	};
10196 
10197 	rc = sysctl_wire_old_buffer(req, 0);
10198 	if (rc != 0)
10199 		return (rc);
10200 
10201 	mtx_lock(&sc->reg_lock);
10202 	if (hw_off_limits(sc))
10203 		rc = ENXIO;
10204 	else {
10205 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10206 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10207 	}
10208 	mtx_unlock(&sc->reg_lock);
10209 	if (rc != 0)
10210 		return (rc);
10211 
10212 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10213 	if (sb == NULL)
10214 		return (ENOMEM);
10215 
10216 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10217 	for (i = 0; i < 4; i++) {
10218 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10219 		    tx_cyc[i]);
10220 	}
10221 
10222 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10223 	for (i = 0; i < 4; i++) {
10224 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10225 		    rx_cyc[i]);
10226 	}
10227 
10228 	if (chip_id(sc) > CHELSIO_T5) {
10229 		sbuf_printf(sb,
10230 		    "\n              Total wait      Total occupancy");
10231 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10232 		    tx_cyc[i]);
10233 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10234 		    rx_cyc[i]);
10235 
10236 		i += 2;
10237 		MPASS(i < nitems(tx_stats));
10238 
10239 		sbuf_printf(sb,
10240 		    "\n                   Reads           Total wait");
10241 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10242 		    tx_cyc[i]);
10243 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10244 		    rx_cyc[i]);
10245 	}
10246 
10247 	rc = sbuf_finish(sb);
10248 	sbuf_delete(sb);
10249 
10250 	return (rc);
10251 }
10252 
10253 static int
10254 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10255 {
10256 	struct adapter *sc = arg1;
10257 	struct sbuf *sb;
10258 	int rc;
10259 	struct tp_rdma_stats stats;
10260 
10261 	rc = sysctl_wire_old_buffer(req, 0);
10262 	if (rc != 0)
10263 		return (rc);
10264 
10265 	mtx_lock(&sc->reg_lock);
10266 	if (hw_off_limits(sc))
10267 		rc = ENXIO;
10268 	else
10269 		t4_tp_get_rdma_stats(sc, &stats, 0);
10270 	mtx_unlock(&sc->reg_lock);
10271 	if (rc != 0)
10272 		return (rc);
10273 
10274 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10275 	if (sb == NULL)
10276 		return (ENOMEM);
10277 
10278 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10279 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10280 
10281 	rc = sbuf_finish(sb);
10282 	sbuf_delete(sb);
10283 
10284 	return (rc);
10285 }
10286 
10287 static int
10288 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10289 {
10290 	struct adapter *sc = arg1;
10291 	struct sbuf *sb;
10292 	int rc;
10293 	struct tp_tcp_stats v4, v6;
10294 
10295 	rc = sysctl_wire_old_buffer(req, 0);
10296 	if (rc != 0)
10297 		return (rc);
10298 
10299 	mtx_lock(&sc->reg_lock);
10300 	if (hw_off_limits(sc))
10301 		rc = ENXIO;
10302 	else
10303 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10304 	mtx_unlock(&sc->reg_lock);
10305 	if (rc != 0)
10306 		return (rc);
10307 
10308 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10309 	if (sb == NULL)
10310 		return (ENOMEM);
10311 
10312 	sbuf_printf(sb,
10313 	    "                                IP                 IPv6\n");
10314 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10315 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10316 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10317 	    v4.tcp_in_segs, v6.tcp_in_segs);
10318 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10319 	    v4.tcp_out_segs, v6.tcp_out_segs);
10320 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10321 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10322 
10323 	rc = sbuf_finish(sb);
10324 	sbuf_delete(sb);
10325 
10326 	return (rc);
10327 }
10328 
10329 static int
10330 sysctl_tids(SYSCTL_HANDLER_ARGS)
10331 {
10332 	struct adapter *sc = arg1;
10333 	struct sbuf *sb;
10334 	int rc;
10335 	uint32_t x, y;
10336 	struct tid_info *t = &sc->tids;
10337 
10338 	rc = sysctl_wire_old_buffer(req, 0);
10339 	if (rc != 0)
10340 		return (rc);
10341 
10342 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10343 	if (sb == NULL)
10344 		return (ENOMEM);
10345 
10346 	if (t->natids) {
10347 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10348 		    t->atids_in_use);
10349 	}
10350 
10351 	if (t->nhpftids) {
10352 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10353 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10354 	}
10355 
10356 	if (t->ntids) {
10357 		bool hashen = false;
10358 
10359 		mtx_lock(&sc->reg_lock);
10360 		if (hw_off_limits(sc))
10361 			rc = ENXIO;
10362 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10363 			hashen = true;
10364 			if (chip_id(sc) <= CHELSIO_T5) {
10365 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10366 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10367 			} else {
10368 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10369 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10370 			}
10371 		}
10372 		mtx_unlock(&sc->reg_lock);
10373 		if (rc != 0)
10374 			goto done;
10375 
10376 		sbuf_printf(sb, "TID range: ");
10377 		if (hashen) {
10378 			if (x)
10379 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10380 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10381 		} else {
10382 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10383 			    t->ntids - 1);
10384 		}
10385 		sbuf_printf(sb, ", in use: %u\n",
10386 		    atomic_load_acq_int(&t->tids_in_use));
10387 	}
10388 
10389 	if (t->nstids) {
10390 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10391 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10392 	}
10393 
10394 	if (t->nftids) {
10395 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10396 		    t->ftid_end, t->ftids_in_use);
10397 	}
10398 
10399 	if (t->netids) {
10400 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10401 		    t->etid_base + t->netids - 1, t->etids_in_use);
10402 	}
10403 
10404 	mtx_lock(&sc->reg_lock);
10405 	if (hw_off_limits(sc))
10406 		rc = ENXIO;
10407 	else {
10408 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10409 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10410 	}
10411 	mtx_unlock(&sc->reg_lock);
10412 	if (rc != 0)
10413 		goto done;
10414 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10415 done:
10416 	if (rc == 0)
10417 		rc = sbuf_finish(sb);
10418 	else
10419 		(void)sbuf_finish(sb);
10420 	sbuf_delete(sb);
10421 
10422 	return (rc);
10423 }
10424 
10425 static int
10426 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10427 {
10428 	struct adapter *sc = arg1;
10429 	struct sbuf *sb;
10430 	int rc;
10431 	struct tp_err_stats stats;
10432 
10433 	rc = sysctl_wire_old_buffer(req, 0);
10434 	if (rc != 0)
10435 		return (rc);
10436 
10437 	mtx_lock(&sc->reg_lock);
10438 	if (hw_off_limits(sc))
10439 		rc = ENXIO;
10440 	else
10441 		t4_tp_get_err_stats(sc, &stats, 0);
10442 	mtx_unlock(&sc->reg_lock);
10443 	if (rc != 0)
10444 		return (rc);
10445 
10446 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10447 	if (sb == NULL)
10448 		return (ENOMEM);
10449 
10450 	if (sc->chip_params->nchan > 2) {
10451 		sbuf_printf(sb, "                 channel 0  channel 1"
10452 		    "  channel 2  channel 3\n");
10453 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10454 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10455 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10456 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10457 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10458 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10459 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10460 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10461 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10462 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10463 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10464 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10465 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10466 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10467 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10468 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10469 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10470 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10471 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10472 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10473 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10474 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10475 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10476 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10477 	} else {
10478 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10479 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10480 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10481 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10482 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10483 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10484 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10485 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10486 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10487 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10488 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10489 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10490 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10491 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10492 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10493 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10494 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10495 	}
10496 
10497 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10498 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10499 
10500 	rc = sbuf_finish(sb);
10501 	sbuf_delete(sb);
10502 
10503 	return (rc);
10504 }
10505 
10506 static int
10507 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10508 {
10509 	struct adapter *sc = arg1;
10510 	struct sbuf *sb;
10511 	int rc;
10512 	struct tp_tnl_stats stats;
10513 
10514 	rc = sysctl_wire_old_buffer(req, 0);
10515 	if (rc != 0)
10516 		return(rc);
10517 
10518 	mtx_lock(&sc->reg_lock);
10519 	if (hw_off_limits(sc))
10520 		rc = ENXIO;
10521 	else
10522 		t4_tp_get_tnl_stats(sc, &stats, 1);
10523 	mtx_unlock(&sc->reg_lock);
10524 	if (rc != 0)
10525 		return (rc);
10526 
10527 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10528 	if (sb == NULL)
10529 		return (ENOMEM);
10530 
10531 	if (sc->chip_params->nchan > 2) {
10532 		sbuf_printf(sb, "           channel 0  channel 1"
10533 		    "  channel 2  channel 3\n");
10534 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10535 		    stats.out_pkt[0], stats.out_pkt[1],
10536 		    stats.out_pkt[2], stats.out_pkt[3]);
10537 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10538 		    stats.in_pkt[0], stats.in_pkt[1],
10539 		    stats.in_pkt[2], stats.in_pkt[3]);
10540 	} else {
10541 		sbuf_printf(sb, "           channel 0  channel 1\n");
10542 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10543 		    stats.out_pkt[0], stats.out_pkt[1]);
10544 		sbuf_printf(sb, "InPkts:   %10u %10u",
10545 		    stats.in_pkt[0], stats.in_pkt[1]);
10546 	}
10547 
10548 	rc = sbuf_finish(sb);
10549 	sbuf_delete(sb);
10550 
10551 	return (rc);
10552 }
10553 
10554 static int
10555 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10556 {
10557 	struct adapter *sc = arg1;
10558 	struct tp_params *tpp = &sc->params.tp;
10559 	u_int mask;
10560 	int rc;
10561 
10562 	mask = tpp->la_mask >> 16;
10563 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10564 	if (rc != 0 || req->newptr == NULL)
10565 		return (rc);
10566 	if (mask > 0xffff)
10567 		return (EINVAL);
10568 	mtx_lock(&sc->reg_lock);
10569 	if (hw_off_limits(sc))
10570 		rc = ENXIO;
10571 	else {
10572 		tpp->la_mask = mask << 16;
10573 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10574 		    tpp->la_mask);
10575 	}
10576 	mtx_unlock(&sc->reg_lock);
10577 
10578 	return (rc);
10579 }
10580 
10581 struct field_desc {
10582 	const char *name;
10583 	u_int start;
10584 	u_int width;
10585 };
10586 
10587 static void
10588 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10589 {
10590 	char buf[32];
10591 	int line_size = 0;
10592 
10593 	while (f->name) {
10594 		uint64_t mask = (1ULL << f->width) - 1;
10595 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10596 		    ((uintmax_t)v >> f->start) & mask);
10597 
10598 		if (line_size + len >= 79) {
10599 			line_size = 8;
10600 			sbuf_printf(sb, "\n        ");
10601 		}
10602 		sbuf_printf(sb, "%s ", buf);
10603 		line_size += len + 1;
10604 		f++;
10605 	}
10606 	sbuf_printf(sb, "\n");
10607 }
10608 
10609 static const struct field_desc tp_la0[] = {
10610 	{ "RcfOpCodeOut", 60, 4 },
10611 	{ "State", 56, 4 },
10612 	{ "WcfState", 52, 4 },
10613 	{ "RcfOpcSrcOut", 50, 2 },
10614 	{ "CRxError", 49, 1 },
10615 	{ "ERxError", 48, 1 },
10616 	{ "SanityFailed", 47, 1 },
10617 	{ "SpuriousMsg", 46, 1 },
10618 	{ "FlushInputMsg", 45, 1 },
10619 	{ "FlushInputCpl", 44, 1 },
10620 	{ "RssUpBit", 43, 1 },
10621 	{ "RssFilterHit", 42, 1 },
10622 	{ "Tid", 32, 10 },
10623 	{ "InitTcb", 31, 1 },
10624 	{ "LineNumber", 24, 7 },
10625 	{ "Emsg", 23, 1 },
10626 	{ "EdataOut", 22, 1 },
10627 	{ "Cmsg", 21, 1 },
10628 	{ "CdataOut", 20, 1 },
10629 	{ "EreadPdu", 19, 1 },
10630 	{ "CreadPdu", 18, 1 },
10631 	{ "TunnelPkt", 17, 1 },
10632 	{ "RcfPeerFin", 16, 1 },
10633 	{ "RcfReasonOut", 12, 4 },
10634 	{ "TxCchannel", 10, 2 },
10635 	{ "RcfTxChannel", 8, 2 },
10636 	{ "RxEchannel", 6, 2 },
10637 	{ "RcfRxChannel", 5, 1 },
10638 	{ "RcfDataOutSrdy", 4, 1 },
10639 	{ "RxDvld", 3, 1 },
10640 	{ "RxOoDvld", 2, 1 },
10641 	{ "RxCongestion", 1, 1 },
10642 	{ "TxCongestion", 0, 1 },
10643 	{ NULL }
10644 };
10645 
10646 static const struct field_desc tp_la1[] = {
10647 	{ "CplCmdIn", 56, 8 },
10648 	{ "CplCmdOut", 48, 8 },
10649 	{ "ESynOut", 47, 1 },
10650 	{ "EAckOut", 46, 1 },
10651 	{ "EFinOut", 45, 1 },
10652 	{ "ERstOut", 44, 1 },
10653 	{ "SynIn", 43, 1 },
10654 	{ "AckIn", 42, 1 },
10655 	{ "FinIn", 41, 1 },
10656 	{ "RstIn", 40, 1 },
10657 	{ "DataIn", 39, 1 },
10658 	{ "DataInVld", 38, 1 },
10659 	{ "PadIn", 37, 1 },
10660 	{ "RxBufEmpty", 36, 1 },
10661 	{ "RxDdp", 35, 1 },
10662 	{ "RxFbCongestion", 34, 1 },
10663 	{ "TxFbCongestion", 33, 1 },
10664 	{ "TxPktSumSrdy", 32, 1 },
10665 	{ "RcfUlpType", 28, 4 },
10666 	{ "Eread", 27, 1 },
10667 	{ "Ebypass", 26, 1 },
10668 	{ "Esave", 25, 1 },
10669 	{ "Static0", 24, 1 },
10670 	{ "Cread", 23, 1 },
10671 	{ "Cbypass", 22, 1 },
10672 	{ "Csave", 21, 1 },
10673 	{ "CPktOut", 20, 1 },
10674 	{ "RxPagePoolFull", 18, 2 },
10675 	{ "RxLpbkPkt", 17, 1 },
10676 	{ "TxLpbkPkt", 16, 1 },
10677 	{ "RxVfValid", 15, 1 },
10678 	{ "SynLearned", 14, 1 },
10679 	{ "SetDelEntry", 13, 1 },
10680 	{ "SetInvEntry", 12, 1 },
10681 	{ "CpcmdDvld", 11, 1 },
10682 	{ "CpcmdSave", 10, 1 },
10683 	{ "RxPstructsFull", 8, 2 },
10684 	{ "EpcmdDvld", 7, 1 },
10685 	{ "EpcmdFlush", 6, 1 },
10686 	{ "EpcmdTrimPrefix", 5, 1 },
10687 	{ "EpcmdTrimPostfix", 4, 1 },
10688 	{ "ERssIp4Pkt", 3, 1 },
10689 	{ "ERssIp6Pkt", 2, 1 },
10690 	{ "ERssTcpUdpPkt", 1, 1 },
10691 	{ "ERssFceFipPkt", 0, 1 },
10692 	{ NULL }
10693 };
10694 
10695 static const struct field_desc tp_la2[] = {
10696 	{ "CplCmdIn", 56, 8 },
10697 	{ "MpsVfVld", 55, 1 },
10698 	{ "MpsPf", 52, 3 },
10699 	{ "MpsVf", 44, 8 },
10700 	{ "SynIn", 43, 1 },
10701 	{ "AckIn", 42, 1 },
10702 	{ "FinIn", 41, 1 },
10703 	{ "RstIn", 40, 1 },
10704 	{ "DataIn", 39, 1 },
10705 	{ "DataInVld", 38, 1 },
10706 	{ "PadIn", 37, 1 },
10707 	{ "RxBufEmpty", 36, 1 },
10708 	{ "RxDdp", 35, 1 },
10709 	{ "RxFbCongestion", 34, 1 },
10710 	{ "TxFbCongestion", 33, 1 },
10711 	{ "TxPktSumSrdy", 32, 1 },
10712 	{ "RcfUlpType", 28, 4 },
10713 	{ "Eread", 27, 1 },
10714 	{ "Ebypass", 26, 1 },
10715 	{ "Esave", 25, 1 },
10716 	{ "Static0", 24, 1 },
10717 	{ "Cread", 23, 1 },
10718 	{ "Cbypass", 22, 1 },
10719 	{ "Csave", 21, 1 },
10720 	{ "CPktOut", 20, 1 },
10721 	{ "RxPagePoolFull", 18, 2 },
10722 	{ "RxLpbkPkt", 17, 1 },
10723 	{ "TxLpbkPkt", 16, 1 },
10724 	{ "RxVfValid", 15, 1 },
10725 	{ "SynLearned", 14, 1 },
10726 	{ "SetDelEntry", 13, 1 },
10727 	{ "SetInvEntry", 12, 1 },
10728 	{ "CpcmdDvld", 11, 1 },
10729 	{ "CpcmdSave", 10, 1 },
10730 	{ "RxPstructsFull", 8, 2 },
10731 	{ "EpcmdDvld", 7, 1 },
10732 	{ "EpcmdFlush", 6, 1 },
10733 	{ "EpcmdTrimPrefix", 5, 1 },
10734 	{ "EpcmdTrimPostfix", 4, 1 },
10735 	{ "ERssIp4Pkt", 3, 1 },
10736 	{ "ERssIp6Pkt", 2, 1 },
10737 	{ "ERssTcpUdpPkt", 1, 1 },
10738 	{ "ERssFceFipPkt", 0, 1 },
10739 	{ NULL }
10740 };
10741 
10742 static void
10743 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10744 {
10745 
10746 	field_desc_show(sb, *p, tp_la0);
10747 }
10748 
10749 static void
10750 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10751 {
10752 
10753 	if (idx)
10754 		sbuf_printf(sb, "\n");
10755 	field_desc_show(sb, p[0], tp_la0);
10756 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10757 		field_desc_show(sb, p[1], tp_la0);
10758 }
10759 
10760 static void
10761 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
10762 {
10763 
10764 	if (idx)
10765 		sbuf_printf(sb, "\n");
10766 	field_desc_show(sb, p[0], tp_la0);
10767 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10768 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
10769 }
10770 
10771 static int
10772 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
10773 {
10774 	struct adapter *sc = arg1;
10775 	struct sbuf *sb;
10776 	uint64_t *buf, *p;
10777 	int rc;
10778 	u_int i, inc;
10779 	void (*show_func)(struct sbuf *, uint64_t *, int);
10780 
10781 	rc = sysctl_wire_old_buffer(req, 0);
10782 	if (rc != 0)
10783 		return (rc);
10784 
10785 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10786 	if (sb == NULL)
10787 		return (ENOMEM);
10788 
10789 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
10790 
10791 	mtx_lock(&sc->reg_lock);
10792 	if (hw_off_limits(sc))
10793 		rc = ENXIO;
10794 	else {
10795 		t4_tp_read_la(sc, buf, NULL);
10796 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
10797 		case 2:
10798 			inc = 2;
10799 			show_func = tp_la_show2;
10800 			break;
10801 		case 3:
10802 			inc = 2;
10803 			show_func = tp_la_show3;
10804 			break;
10805 		default:
10806 			inc = 1;
10807 			show_func = tp_la_show;
10808 		}
10809 	}
10810 	mtx_unlock(&sc->reg_lock);
10811 	if (rc != 0)
10812 		goto done;
10813 
10814 	p = buf;
10815 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
10816 		(*show_func)(sb, p, i);
10817 	rc = sbuf_finish(sb);
10818 done:
10819 	sbuf_delete(sb);
10820 	free(buf, M_CXGBE);
10821 	return (rc);
10822 }
10823 
10824 static int
10825 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
10826 {
10827 	struct adapter *sc = arg1;
10828 	struct sbuf *sb;
10829 	int rc;
10830 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
10831 
10832 	rc = sysctl_wire_old_buffer(req, 0);
10833 	if (rc != 0)
10834 		return (rc);
10835 
10836 	mtx_lock(&sc->reg_lock);
10837 	if (hw_off_limits(sc))
10838 		rc = ENXIO;
10839 	else
10840 		t4_get_chan_txrate(sc, nrate, orate);
10841 	mtx_unlock(&sc->reg_lock);
10842 	if (rc != 0)
10843 		return (rc);
10844 
10845 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10846 	if (sb == NULL)
10847 		return (ENOMEM);
10848 
10849 	if (sc->chip_params->nchan > 2) {
10850 		sbuf_printf(sb, "              channel 0   channel 1"
10851 		    "   channel 2   channel 3\n");
10852 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
10853 		    nrate[0], nrate[1], nrate[2], nrate[3]);
10854 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
10855 		    orate[0], orate[1], orate[2], orate[3]);
10856 	} else {
10857 		sbuf_printf(sb, "              channel 0   channel 1\n");
10858 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
10859 		    nrate[0], nrate[1]);
10860 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
10861 		    orate[0], orate[1]);
10862 	}
10863 
10864 	rc = sbuf_finish(sb);
10865 	sbuf_delete(sb);
10866 
10867 	return (rc);
10868 }
10869 
10870 static int
10871 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
10872 {
10873 	struct adapter *sc = arg1;
10874 	struct sbuf *sb;
10875 	uint32_t *buf, *p;
10876 	int rc, i;
10877 
10878 	rc = sysctl_wire_old_buffer(req, 0);
10879 	if (rc != 0)
10880 		return (rc);
10881 
10882 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10883 	if (sb == NULL)
10884 		return (ENOMEM);
10885 
10886 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
10887 	    M_ZERO | M_WAITOK);
10888 
10889 	mtx_lock(&sc->reg_lock);
10890 	if (hw_off_limits(sc))
10891 		rc = ENXIO;
10892 	else
10893 		t4_ulprx_read_la(sc, buf);
10894 	mtx_unlock(&sc->reg_lock);
10895 	if (rc != 0)
10896 		goto done;
10897 
10898 	p = buf;
10899 	sbuf_printf(sb, "      Pcmd        Type   Message"
10900 	    "                Data");
10901 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
10902 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
10903 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
10904 	}
10905 	rc = sbuf_finish(sb);
10906 done:
10907 	sbuf_delete(sb);
10908 	free(buf, M_CXGBE);
10909 	return (rc);
10910 }
10911 
10912 static int
10913 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
10914 {
10915 	struct adapter *sc = arg1;
10916 	struct sbuf *sb;
10917 	int rc;
10918 	uint32_t cfg, s1, s2;
10919 
10920 	MPASS(chip_id(sc) >= CHELSIO_T5);
10921 
10922 	rc = sysctl_wire_old_buffer(req, 0);
10923 	if (rc != 0)
10924 		return (rc);
10925 
10926 	mtx_lock(&sc->reg_lock);
10927 	if (hw_off_limits(sc))
10928 		rc = ENXIO;
10929 	else {
10930 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
10931 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
10932 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
10933 	}
10934 	mtx_unlock(&sc->reg_lock);
10935 	if (rc != 0)
10936 		return (rc);
10937 
10938 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10939 	if (sb == NULL)
10940 		return (ENOMEM);
10941 
10942 	if (G_STATSOURCE_T5(cfg) == 7) {
10943 		int mode;
10944 
10945 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
10946 		if (mode == 0)
10947 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
10948 		else if (mode == 1)
10949 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
10950 		else
10951 			sbuf_printf(sb, "unknown mode %d", mode);
10952 	}
10953 	rc = sbuf_finish(sb);
10954 	sbuf_delete(sb);
10955 
10956 	return (rc);
10957 }
10958 
10959 static int
10960 sysctl_cpus(SYSCTL_HANDLER_ARGS)
10961 {
10962 	struct adapter *sc = arg1;
10963 	enum cpu_sets op = arg2;
10964 	cpuset_t cpuset;
10965 	struct sbuf *sb;
10966 	int i, rc;
10967 
10968 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
10969 
10970 	CPU_ZERO(&cpuset);
10971 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
10972 	if (rc != 0)
10973 		return (rc);
10974 
10975 	rc = sysctl_wire_old_buffer(req, 0);
10976 	if (rc != 0)
10977 		return (rc);
10978 
10979 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10980 	if (sb == NULL)
10981 		return (ENOMEM);
10982 
10983 	CPU_FOREACH(i)
10984 		sbuf_printf(sb, "%d ", i);
10985 	rc = sbuf_finish(sb);
10986 	sbuf_delete(sb);
10987 
10988 	return (rc);
10989 }
10990 
10991 static int
10992 sysctl_reset(SYSCTL_HANDLER_ARGS)
10993 {
10994 	struct adapter *sc = arg1;
10995 	u_int val;
10996 	int rc;
10997 
10998 	val = sc->num_resets;
10999 	rc = sysctl_handle_int(oidp, &val, 0, req);
11000 	if (rc != 0 || req->newptr == NULL)
11001 		return (rc);
11002 
11003 	if (val == 0) {
11004 		/* Zero out the counter that tracks reset. */
11005 		sc->num_resets = 0;
11006 		return (0);
11007 	}
11008 
11009 	if (val != 1)
11010 		return (EINVAL);	/* 0 or 1 are the only legal values */
11011 
11012 	if (hw_off_limits(sc))		/* harmless race */
11013 		return (EALREADY);
11014 
11015 	taskqueue_enqueue(reset_tq, &sc->reset_task);
11016 	return (0);
11017 }
11018 
11019 #ifdef TCP_OFFLOAD
11020 static int
11021 sysctl_tls(SYSCTL_HANDLER_ARGS)
11022 {
11023 	struct adapter *sc = arg1;
11024 	int i, j, v, rc;
11025 	struct vi_info *vi;
11026 
11027 	v = sc->tt.tls;
11028 	rc = sysctl_handle_int(oidp, &v, 0, req);
11029 	if (rc != 0 || req->newptr == NULL)
11030 		return (rc);
11031 
11032 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11033 		return (ENOTSUP);
11034 
11035 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11036 	if (rc)
11037 		return (rc);
11038 	if (hw_off_limits(sc))
11039 		rc = ENXIO;
11040 	else {
11041 		sc->tt.tls = !!v;
11042 		for_each_port(sc, i) {
11043 			for_each_vi(sc->port[i], j, vi) {
11044 				if (vi->flags & VI_INIT_DONE)
11045 					t4_update_fl_bufsize(vi->ifp);
11046 			}
11047 		}
11048 	}
11049 	end_synchronized_op(sc, 0);
11050 
11051 	return (rc);
11052 
11053 }
11054 
11055 static int
11056 sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS)
11057 {
11058 	struct adapter *sc = arg1;
11059 	int *old_ports, *new_ports;
11060 	int i, new_count, rc;
11061 
11062 	if (req->newptr == NULL && req->oldptr == NULL)
11063 		return (SYSCTL_OUT(req, NULL, imax(sc->tt.num_tls_rx_ports, 1) *
11064 		    sizeof(sc->tt.tls_rx_ports[0])));
11065 
11066 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tlsrx");
11067 	if (rc)
11068 		return (rc);
11069 
11070 	if (hw_off_limits(sc)) {
11071 		rc = ENXIO;
11072 		goto done;
11073 	}
11074 
11075 	if (sc->tt.num_tls_rx_ports == 0) {
11076 		i = -1;
11077 		rc = SYSCTL_OUT(req, &i, sizeof(i));
11078 	} else
11079 		rc = SYSCTL_OUT(req, sc->tt.tls_rx_ports,
11080 		    sc->tt.num_tls_rx_ports * sizeof(sc->tt.tls_rx_ports[0]));
11081 	if (rc == 0 && req->newptr != NULL) {
11082 		new_count = req->newlen / sizeof(new_ports[0]);
11083 		new_ports = malloc(new_count * sizeof(new_ports[0]), M_CXGBE,
11084 		    M_WAITOK);
11085 		rc = SYSCTL_IN(req, new_ports, new_count *
11086 		    sizeof(new_ports[0]));
11087 		if (rc)
11088 			goto err;
11089 
11090 		/* Allow setting to a single '-1' to clear the list. */
11091 		if (new_count == 1 && new_ports[0] == -1) {
11092 			ADAPTER_LOCK(sc);
11093 			old_ports = sc->tt.tls_rx_ports;
11094 			sc->tt.tls_rx_ports = NULL;
11095 			sc->tt.num_tls_rx_ports = 0;
11096 			ADAPTER_UNLOCK(sc);
11097 			free(old_ports, M_CXGBE);
11098 		} else {
11099 			for (i = 0; i < new_count; i++) {
11100 				if (new_ports[i] < 1 ||
11101 				    new_ports[i] > IPPORT_MAX) {
11102 					rc = EINVAL;
11103 					goto err;
11104 				}
11105 			}
11106 
11107 			ADAPTER_LOCK(sc);
11108 			old_ports = sc->tt.tls_rx_ports;
11109 			sc->tt.tls_rx_ports = new_ports;
11110 			sc->tt.num_tls_rx_ports = new_count;
11111 			ADAPTER_UNLOCK(sc);
11112 			free(old_ports, M_CXGBE);
11113 			new_ports = NULL;
11114 		}
11115 	err:
11116 		free(new_ports, M_CXGBE);
11117 	}
11118 done:
11119 	end_synchronized_op(sc, 0);
11120 	return (rc);
11121 }
11122 
11123 static int
11124 sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS)
11125 {
11126 	struct adapter *sc = arg1;
11127 	int v, rc;
11128 
11129 	v = sc->tt.tls_rx_timeout;
11130 	rc = sysctl_handle_int(oidp, &v, 0, req);
11131 	if (rc != 0 || req->newptr == NULL)
11132 		return (rc);
11133 
11134 	if (v < 0)
11135 		return (EINVAL);
11136 
11137 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11138 		return (ENOTSUP);
11139 
11140 	sc->tt.tls_rx_timeout = v;
11141 
11142 	return (0);
11143 
11144 }
11145 
11146 static void
11147 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11148 {
11149 	u_int rem = val % factor;
11150 
11151 	if (rem == 0)
11152 		snprintf(buf, len, "%u", val / factor);
11153 	else {
11154 		while (rem % 10 == 0)
11155 			rem /= 10;
11156 		snprintf(buf, len, "%u.%u", val / factor, rem);
11157 	}
11158 }
11159 
11160 static int
11161 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11162 {
11163 	struct adapter *sc = arg1;
11164 	char buf[16];
11165 	u_int res, re;
11166 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11167 
11168 	mtx_lock(&sc->reg_lock);
11169 	if (hw_off_limits(sc))
11170 		res = (u_int)-1;
11171 	else
11172 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11173 	mtx_unlock(&sc->reg_lock);
11174 	if (res == (u_int)-1)
11175 		return (ENXIO);
11176 
11177 	switch (arg2) {
11178 	case 0:
11179 		/* timer_tick */
11180 		re = G_TIMERRESOLUTION(res);
11181 		break;
11182 	case 1:
11183 		/* TCP timestamp tick */
11184 		re = G_TIMESTAMPRESOLUTION(res);
11185 		break;
11186 	case 2:
11187 		/* DACK tick */
11188 		re = G_DELAYEDACKRESOLUTION(res);
11189 		break;
11190 	default:
11191 		return (EDOOFUS);
11192 	}
11193 
11194 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11195 
11196 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11197 }
11198 
11199 static int
11200 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11201 {
11202 	struct adapter *sc = arg1;
11203 	int rc;
11204 	u_int dack_tmr, dack_re, v;
11205 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11206 
11207 	mtx_lock(&sc->reg_lock);
11208 	if (hw_off_limits(sc))
11209 		rc = ENXIO;
11210 	else {
11211 		rc = 0;
11212 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11213 		    A_TP_TIMER_RESOLUTION));
11214 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11215 	}
11216 	mtx_unlock(&sc->reg_lock);
11217 	if (rc != 0)
11218 		return (rc);
11219 
11220 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11221 
11222 	return (sysctl_handle_int(oidp, &v, 0, req));
11223 }
11224 
11225 static int
11226 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11227 {
11228 	struct adapter *sc = arg1;
11229 	int rc, reg = arg2;
11230 	u_int tre;
11231 	u_long tp_tick_us, v;
11232 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11233 
11234 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11235 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11236 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11237 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11238 
11239 	mtx_lock(&sc->reg_lock);
11240 	if (hw_off_limits(sc))
11241 		rc = ENXIO;
11242 	else {
11243 		rc = 0;
11244 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11245 		tp_tick_us = (cclk_ps << tre) / 1000000;
11246 		if (reg == A_TP_INIT_SRTT)
11247 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11248 		else
11249 			v = tp_tick_us * t4_read_reg(sc, reg);
11250 	}
11251 	mtx_unlock(&sc->reg_lock);
11252 	if (rc != 0)
11253 		return (rc);
11254 	else
11255 		return (sysctl_handle_long(oidp, &v, 0, req));
11256 }
11257 
11258 /*
11259  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11260  * passed to this function.
11261  */
11262 static int
11263 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11264 {
11265 	struct adapter *sc = arg1;
11266 	int rc, idx = arg2;
11267 	u_int v;
11268 
11269 	MPASS(idx >= 0 && idx <= 24);
11270 
11271 	mtx_lock(&sc->reg_lock);
11272 	if (hw_off_limits(sc))
11273 		rc = ENXIO;
11274 	else {
11275 		rc = 0;
11276 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11277 	}
11278 	mtx_unlock(&sc->reg_lock);
11279 	if (rc != 0)
11280 		return (rc);
11281 	else
11282 		return (sysctl_handle_int(oidp, &v, 0, req));
11283 }
11284 
11285 static int
11286 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11287 {
11288 	struct adapter *sc = arg1;
11289 	int rc, idx = arg2;
11290 	u_int shift, v, r;
11291 
11292 	MPASS(idx >= 0 && idx < 16);
11293 
11294 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11295 	shift = (idx & 3) << 3;
11296 	mtx_lock(&sc->reg_lock);
11297 	if (hw_off_limits(sc))
11298 		rc = ENXIO;
11299 	else {
11300 		rc = 0;
11301 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11302 	}
11303 	mtx_unlock(&sc->reg_lock);
11304 	if (rc != 0)
11305 		return (rc);
11306 	else
11307 		return (sysctl_handle_int(oidp, &v, 0, req));
11308 }
11309 
11310 static int
11311 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11312 {
11313 	struct vi_info *vi = arg1;
11314 	struct adapter *sc = vi->adapter;
11315 	int idx, rc, i;
11316 	struct sge_ofld_rxq *ofld_rxq;
11317 	uint8_t v;
11318 
11319 	idx = vi->ofld_tmr_idx;
11320 
11321 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11322 	if (rc != 0 || req->newptr == NULL)
11323 		return (rc);
11324 
11325 	if (idx < 0 || idx >= SGE_NTIMERS)
11326 		return (EINVAL);
11327 
11328 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11329 	    "t4otmr");
11330 	if (rc)
11331 		return (rc);
11332 
11333 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11334 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11335 #ifdef atomic_store_rel_8
11336 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11337 #else
11338 		ofld_rxq->iq.intr_params = v;
11339 #endif
11340 	}
11341 	vi->ofld_tmr_idx = idx;
11342 
11343 	end_synchronized_op(sc, LOCK_HELD);
11344 	return (0);
11345 }
11346 
11347 static int
11348 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11349 {
11350 	struct vi_info *vi = arg1;
11351 	struct adapter *sc = vi->adapter;
11352 	int idx, rc;
11353 
11354 	idx = vi->ofld_pktc_idx;
11355 
11356 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11357 	if (rc != 0 || req->newptr == NULL)
11358 		return (rc);
11359 
11360 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11361 		return (EINVAL);
11362 
11363 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11364 	    "t4opktc");
11365 	if (rc)
11366 		return (rc);
11367 
11368 	if (vi->flags & VI_INIT_DONE)
11369 		rc = EBUSY; /* cannot be changed once the queues are created */
11370 	else
11371 		vi->ofld_pktc_idx = idx;
11372 
11373 	end_synchronized_op(sc, LOCK_HELD);
11374 	return (rc);
11375 }
11376 #endif
11377 
11378 static int
11379 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11380 {
11381 	int rc;
11382 
11383 	if (cntxt->cid > M_CTXTQID)
11384 		return (EINVAL);
11385 
11386 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11387 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11388 		return (EINVAL);
11389 
11390 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11391 	if (rc)
11392 		return (rc);
11393 
11394 	if (hw_off_limits(sc)) {
11395 		rc = ENXIO;
11396 		goto done;
11397 	}
11398 
11399 	if (sc->flags & FW_OK) {
11400 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11401 		    &cntxt->data[0]);
11402 		if (rc == 0)
11403 			goto done;
11404 	}
11405 
11406 	/*
11407 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11408 	 * the backdoor.
11409 	 */
11410 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11411 done:
11412 	end_synchronized_op(sc, 0);
11413 	return (rc);
11414 }
11415 
11416 static int
11417 load_fw(struct adapter *sc, struct t4_data *fw)
11418 {
11419 	int rc;
11420 	uint8_t *fw_data;
11421 
11422 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11423 	if (rc)
11424 		return (rc);
11425 
11426 	if (hw_off_limits(sc)) {
11427 		rc = ENXIO;
11428 		goto done;
11429 	}
11430 
11431 	/*
11432 	 * The firmware, with the sole exception of the memory parity error
11433 	 * handler, runs from memory and not flash.  It is almost always safe to
11434 	 * install a new firmware on a running system.  Just set bit 1 in
11435 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11436 	 */
11437 	if (sc->flags & FULL_INIT_DONE &&
11438 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11439 		rc = EBUSY;
11440 		goto done;
11441 	}
11442 
11443 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11444 
11445 	rc = copyin(fw->data, fw_data, fw->len);
11446 	if (rc == 0)
11447 		rc = -t4_load_fw(sc, fw_data, fw->len);
11448 
11449 	free(fw_data, M_CXGBE);
11450 done:
11451 	end_synchronized_op(sc, 0);
11452 	return (rc);
11453 }
11454 
11455 static int
11456 load_cfg(struct adapter *sc, struct t4_data *cfg)
11457 {
11458 	int rc;
11459 	uint8_t *cfg_data = NULL;
11460 
11461 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11462 	if (rc)
11463 		return (rc);
11464 
11465 	if (hw_off_limits(sc)) {
11466 		rc = ENXIO;
11467 		goto done;
11468 	}
11469 
11470 	if (cfg->len == 0) {
11471 		/* clear */
11472 		rc = -t4_load_cfg(sc, NULL, 0);
11473 		goto done;
11474 	}
11475 
11476 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11477 
11478 	rc = copyin(cfg->data, cfg_data, cfg->len);
11479 	if (rc == 0)
11480 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11481 
11482 	free(cfg_data, M_CXGBE);
11483 done:
11484 	end_synchronized_op(sc, 0);
11485 	return (rc);
11486 }
11487 
11488 static int
11489 load_boot(struct adapter *sc, struct t4_bootrom *br)
11490 {
11491 	int rc;
11492 	uint8_t *br_data = NULL;
11493 	u_int offset;
11494 
11495 	if (br->len > 1024 * 1024)
11496 		return (EFBIG);
11497 
11498 	if (br->pf_offset == 0) {
11499 		/* pfidx */
11500 		if (br->pfidx_addr > 7)
11501 			return (EINVAL);
11502 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11503 		    A_PCIE_PF_EXPROM_OFST)));
11504 	} else if (br->pf_offset == 1) {
11505 		/* offset */
11506 		offset = G_OFFSET(br->pfidx_addr);
11507 	} else {
11508 		return (EINVAL);
11509 	}
11510 
11511 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11512 	if (rc)
11513 		return (rc);
11514 
11515 	if (hw_off_limits(sc)) {
11516 		rc = ENXIO;
11517 		goto done;
11518 	}
11519 
11520 	if (br->len == 0) {
11521 		/* clear */
11522 		rc = -t4_load_boot(sc, NULL, offset, 0);
11523 		goto done;
11524 	}
11525 
11526 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11527 
11528 	rc = copyin(br->data, br_data, br->len);
11529 	if (rc == 0)
11530 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11531 
11532 	free(br_data, M_CXGBE);
11533 done:
11534 	end_synchronized_op(sc, 0);
11535 	return (rc);
11536 }
11537 
11538 static int
11539 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11540 {
11541 	int rc;
11542 	uint8_t *bc_data = NULL;
11543 
11544 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11545 	if (rc)
11546 		return (rc);
11547 
11548 	if (hw_off_limits(sc)) {
11549 		rc = ENXIO;
11550 		goto done;
11551 	}
11552 
11553 	if (bc->len == 0) {
11554 		/* clear */
11555 		rc = -t4_load_bootcfg(sc, NULL, 0);
11556 		goto done;
11557 	}
11558 
11559 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11560 
11561 	rc = copyin(bc->data, bc_data, bc->len);
11562 	if (rc == 0)
11563 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11564 
11565 	free(bc_data, M_CXGBE);
11566 done:
11567 	end_synchronized_op(sc, 0);
11568 	return (rc);
11569 }
11570 
11571 static int
11572 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11573 {
11574 	int rc;
11575 	struct cudbg_init *cudbg;
11576 	void *handle, *buf;
11577 
11578 	/* buf is large, don't block if no memory is available */
11579 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11580 	if (buf == NULL)
11581 		return (ENOMEM);
11582 
11583 	handle = cudbg_alloc_handle();
11584 	if (handle == NULL) {
11585 		rc = ENOMEM;
11586 		goto done;
11587 	}
11588 
11589 	cudbg = cudbg_get_init(handle);
11590 	cudbg->adap = sc;
11591 	cudbg->print = (cudbg_print_cb)printf;
11592 
11593 #ifndef notyet
11594 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11595 	    __func__, dump->wr_flash, dump->len, dump->data);
11596 #endif
11597 
11598 	if (dump->wr_flash)
11599 		cudbg->use_flash = 1;
11600 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11601 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11602 
11603 	rc = cudbg_collect(handle, buf, &dump->len);
11604 	if (rc != 0)
11605 		goto done;
11606 
11607 	rc = copyout(buf, dump->data, dump->len);
11608 done:
11609 	cudbg_free_handle(handle);
11610 	free(buf, M_CXGBE);
11611 	return (rc);
11612 }
11613 
11614 static void
11615 free_offload_policy(struct t4_offload_policy *op)
11616 {
11617 	struct offload_rule *r;
11618 	int i;
11619 
11620 	if (op == NULL)
11621 		return;
11622 
11623 	r = &op->rule[0];
11624 	for (i = 0; i < op->nrules; i++, r++) {
11625 		free(r->bpf_prog.bf_insns, M_CXGBE);
11626 	}
11627 	free(op->rule, M_CXGBE);
11628 	free(op, M_CXGBE);
11629 }
11630 
11631 static int
11632 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11633 {
11634 	int i, rc, len;
11635 	struct t4_offload_policy *op, *old;
11636 	struct bpf_program *bf;
11637 	const struct offload_settings *s;
11638 	struct offload_rule *r;
11639 	void *u;
11640 
11641 	if (!is_offload(sc))
11642 		return (ENODEV);
11643 
11644 	if (uop->nrules == 0) {
11645 		/* Delete installed policies. */
11646 		op = NULL;
11647 		goto set_policy;
11648 	} else if (uop->nrules > 256) { /* arbitrary */
11649 		return (E2BIG);
11650 	}
11651 
11652 	/* Copy userspace offload policy to kernel */
11653 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11654 	op->nrules = uop->nrules;
11655 	len = op->nrules * sizeof(struct offload_rule);
11656 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11657 	rc = copyin(uop->rule, op->rule, len);
11658 	if (rc) {
11659 		free(op->rule, M_CXGBE);
11660 		free(op, M_CXGBE);
11661 		return (rc);
11662 	}
11663 
11664 	r = &op->rule[0];
11665 	for (i = 0; i < op->nrules; i++, r++) {
11666 
11667 		/* Validate open_type */
11668 		if (r->open_type != OPEN_TYPE_LISTEN &&
11669 		    r->open_type != OPEN_TYPE_ACTIVE &&
11670 		    r->open_type != OPEN_TYPE_PASSIVE &&
11671 		    r->open_type != OPEN_TYPE_DONTCARE) {
11672 error:
11673 			/*
11674 			 * Rules 0 to i have malloc'd filters that need to be
11675 			 * freed.  Rules i+1 to nrules have userspace pointers
11676 			 * and should be left alone.
11677 			 */
11678 			op->nrules = i;
11679 			free_offload_policy(op);
11680 			return (rc);
11681 		}
11682 
11683 		/* Validate settings */
11684 		s = &r->settings;
11685 		if ((s->offload != 0 && s->offload != 1) ||
11686 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11687 		    s->sched_class < -1 ||
11688 		    s->sched_class >= sc->params.nsched_cls) {
11689 			rc = EINVAL;
11690 			goto error;
11691 		}
11692 
11693 		bf = &r->bpf_prog;
11694 		u = bf->bf_insns;	/* userspace ptr */
11695 		bf->bf_insns = NULL;
11696 		if (bf->bf_len == 0) {
11697 			/* legal, matches everything */
11698 			continue;
11699 		}
11700 		len = bf->bf_len * sizeof(*bf->bf_insns);
11701 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11702 		rc = copyin(u, bf->bf_insns, len);
11703 		if (rc != 0)
11704 			goto error;
11705 
11706 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11707 			rc = EINVAL;
11708 			goto error;
11709 		}
11710 	}
11711 set_policy:
11712 	rw_wlock(&sc->policy_lock);
11713 	old = sc->policy;
11714 	sc->policy = op;
11715 	rw_wunlock(&sc->policy_lock);
11716 	free_offload_policy(old);
11717 
11718 	return (0);
11719 }
11720 
11721 #define MAX_READ_BUF_SIZE (128 * 1024)
11722 static int
11723 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11724 {
11725 	uint32_t addr, remaining, n;
11726 	uint32_t *buf;
11727 	int rc;
11728 	uint8_t *dst;
11729 
11730 	mtx_lock(&sc->reg_lock);
11731 	if (hw_off_limits(sc))
11732 		rc = ENXIO;
11733 	else
11734 		rc = validate_mem_range(sc, mr->addr, mr->len);
11735 	mtx_unlock(&sc->reg_lock);
11736 	if (rc != 0)
11737 		return (rc);
11738 
11739 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11740 	addr = mr->addr;
11741 	remaining = mr->len;
11742 	dst = (void *)mr->data;
11743 
11744 	while (remaining) {
11745 		n = min(remaining, MAX_READ_BUF_SIZE);
11746 		mtx_lock(&sc->reg_lock);
11747 		if (hw_off_limits(sc))
11748 			rc = ENXIO;
11749 		else
11750 			read_via_memwin(sc, 2, addr, buf, n);
11751 		mtx_unlock(&sc->reg_lock);
11752 		if (rc != 0)
11753 			break;
11754 
11755 		rc = copyout(buf, dst, n);
11756 		if (rc != 0)
11757 			break;
11758 
11759 		dst += n;
11760 		remaining -= n;
11761 		addr += n;
11762 	}
11763 
11764 	free(buf, M_CXGBE);
11765 	return (rc);
11766 }
11767 #undef MAX_READ_BUF_SIZE
11768 
11769 static int
11770 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11771 {
11772 	int rc;
11773 
11774 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11775 		return (EINVAL);
11776 
11777 	if (i2cd->len > sizeof(i2cd->data))
11778 		return (EFBIG);
11779 
11780 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11781 	if (rc)
11782 		return (rc);
11783 	if (hw_off_limits(sc))
11784 		rc = ENXIO;
11785 	else
11786 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11787 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11788 	end_synchronized_op(sc, 0);
11789 
11790 	return (rc);
11791 }
11792 
11793 static int
11794 clear_stats(struct adapter *sc, u_int port_id)
11795 {
11796 	int i, v, chan_map;
11797 	struct port_info *pi;
11798 	struct vi_info *vi;
11799 	struct sge_rxq *rxq;
11800 	struct sge_txq *txq;
11801 	struct sge_wrq *wrq;
11802 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11803 	struct sge_ofld_txq *ofld_txq;
11804 #endif
11805 #ifdef TCP_OFFLOAD
11806 	struct sge_ofld_rxq *ofld_rxq;
11807 #endif
11808 
11809 	if (port_id >= sc->params.nports)
11810 		return (EINVAL);
11811 	pi = sc->port[port_id];
11812 	if (pi == NULL)
11813 		return (EIO);
11814 
11815 	mtx_lock(&sc->reg_lock);
11816 	if (!hw_off_limits(sc)) {
11817 		/* MAC stats */
11818 		t4_clr_port_stats(sc, pi->tx_chan);
11819 		if (is_t6(sc)) {
11820 			if (pi->fcs_reg != -1)
11821 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11822 			else
11823 				pi->stats.rx_fcs_err = 0;
11824 		}
11825 		for_each_vi(pi, v, vi) {
11826 			if (vi->flags & VI_INIT_DONE)
11827 				t4_clr_vi_stats(sc, vi->vin);
11828 		}
11829 		chan_map = pi->rx_e_chan_map;
11830 		v = 0;	/* reuse */
11831 		while (chan_map) {
11832 			i = ffs(chan_map) - 1;
11833 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11834 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11835 			chan_map &= ~(1 << i);
11836 		}
11837 	}
11838 	mtx_unlock(&sc->reg_lock);
11839 	pi->tx_parse_error = 0;
11840 	pi->tnl_cong_drops = 0;
11841 
11842 	/*
11843 	 * Since this command accepts a port, clear stats for
11844 	 * all VIs on this port.
11845 	 */
11846 	for_each_vi(pi, v, vi) {
11847 		if (vi->flags & VI_INIT_DONE) {
11848 
11849 			for_each_rxq(vi, i, rxq) {
11850 #if defined(INET) || defined(INET6)
11851 				rxq->lro.lro_queued = 0;
11852 				rxq->lro.lro_flushed = 0;
11853 #endif
11854 				rxq->rxcsum = 0;
11855 				rxq->vlan_extraction = 0;
11856 				rxq->vxlan_rxcsum = 0;
11857 
11858 				rxq->fl.cl_allocated = 0;
11859 				rxq->fl.cl_recycled = 0;
11860 				rxq->fl.cl_fast_recycled = 0;
11861 			}
11862 
11863 			for_each_txq(vi, i, txq) {
11864 				txq->txcsum = 0;
11865 				txq->tso_wrs = 0;
11866 				txq->vlan_insertion = 0;
11867 				txq->imm_wrs = 0;
11868 				txq->sgl_wrs = 0;
11869 				txq->txpkt_wrs = 0;
11870 				txq->txpkts0_wrs = 0;
11871 				txq->txpkts1_wrs = 0;
11872 				txq->txpkts0_pkts = 0;
11873 				txq->txpkts1_pkts = 0;
11874 				txq->txpkts_flush = 0;
11875 				txq->raw_wrs = 0;
11876 				txq->vxlan_tso_wrs = 0;
11877 				txq->vxlan_txcsum = 0;
11878 				txq->kern_tls_records = 0;
11879 				txq->kern_tls_short = 0;
11880 				txq->kern_tls_partial = 0;
11881 				txq->kern_tls_full = 0;
11882 				txq->kern_tls_octets = 0;
11883 				txq->kern_tls_waste = 0;
11884 				txq->kern_tls_options = 0;
11885 				txq->kern_tls_header = 0;
11886 				txq->kern_tls_fin = 0;
11887 				txq->kern_tls_fin_short = 0;
11888 				txq->kern_tls_cbc = 0;
11889 				txq->kern_tls_gcm = 0;
11890 				mp_ring_reset_stats(txq->r);
11891 			}
11892 
11893 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11894 			for_each_ofld_txq(vi, i, ofld_txq) {
11895 				ofld_txq->wrq.tx_wrs_direct = 0;
11896 				ofld_txq->wrq.tx_wrs_copied = 0;
11897 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
11898 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
11899 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
11900 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
11901 			}
11902 #endif
11903 #ifdef TCP_OFFLOAD
11904 			for_each_ofld_rxq(vi, i, ofld_rxq) {
11905 				ofld_rxq->fl.cl_allocated = 0;
11906 				ofld_rxq->fl.cl_recycled = 0;
11907 				ofld_rxq->fl.cl_fast_recycled = 0;
11908 				counter_u64_zero(
11909 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
11910 				counter_u64_zero(
11911 				    ofld_rxq->rx_iscsi_ddp_setup_error);
11912 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
11913 				ofld_rxq->rx_iscsi_ddp_octets = 0;
11914 				ofld_rxq->rx_iscsi_fl_pdus = 0;
11915 				ofld_rxq->rx_iscsi_fl_octets = 0;
11916 				ofld_rxq->rx_toe_tls_records = 0;
11917 				ofld_rxq->rx_toe_tls_octets = 0;
11918 			}
11919 #endif
11920 
11921 			if (IS_MAIN_VI(vi)) {
11922 				wrq = &sc->sge.ctrlq[pi->port_id];
11923 				wrq->tx_wrs_direct = 0;
11924 				wrq->tx_wrs_copied = 0;
11925 			}
11926 		}
11927 	}
11928 
11929 	return (0);
11930 }
11931 
11932 static int
11933 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
11934 {
11935 #ifdef INET6
11936 	struct in6_addr in6;
11937 
11938 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
11939 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
11940 		return (0);
11941 	else
11942 		return (EIO);
11943 #else
11944 	return (ENOTSUP);
11945 #endif
11946 }
11947 
11948 static int
11949 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
11950 {
11951 #ifdef INET6
11952 	struct in6_addr in6;
11953 
11954 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
11955 	return (t4_release_clip_addr(sc, &in6));
11956 #else
11957 	return (ENOTSUP);
11958 #endif
11959 }
11960 
11961 int
11962 t4_os_find_pci_capability(struct adapter *sc, int cap)
11963 {
11964 	int i;
11965 
11966 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
11967 }
11968 
11969 int
11970 t4_os_pci_save_state(struct adapter *sc)
11971 {
11972 	device_t dev;
11973 	struct pci_devinfo *dinfo;
11974 
11975 	dev = sc->dev;
11976 	dinfo = device_get_ivars(dev);
11977 
11978 	pci_cfg_save(dev, dinfo, 0);
11979 	return (0);
11980 }
11981 
11982 int
11983 t4_os_pci_restore_state(struct adapter *sc)
11984 {
11985 	device_t dev;
11986 	struct pci_devinfo *dinfo;
11987 
11988 	dev = sc->dev;
11989 	dinfo = device_get_ivars(dev);
11990 
11991 	pci_cfg_restore(dev, dinfo);
11992 	return (0);
11993 }
11994 
11995 void
11996 t4_os_portmod_changed(struct port_info *pi)
11997 {
11998 	struct adapter *sc = pi->adapter;
11999 	struct vi_info *vi;
12000 	struct ifnet *ifp;
12001 	static const char *mod_str[] = {
12002 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
12003 	};
12004 
12005 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
12006 	    ("%s: port_type %u", __func__, pi->port_type));
12007 
12008 	vi = &pi->vi[0];
12009 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12010 		PORT_LOCK(pi);
12011 		build_medialist(pi);
12012 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12013 			fixup_link_config(pi);
12014 			apply_link_config(pi);
12015 		}
12016 		PORT_UNLOCK(pi);
12017 		end_synchronized_op(sc, LOCK_HELD);
12018 	}
12019 
12020 	ifp = vi->ifp;
12021 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12022 		if_printf(ifp, "transceiver unplugged.\n");
12023 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12024 		if_printf(ifp, "unknown transceiver inserted.\n");
12025 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12026 		if_printf(ifp, "unsupported transceiver inserted.\n");
12027 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12028 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12029 		    port_top_speed(pi), mod_str[pi->mod_type]);
12030 	} else {
12031 		if_printf(ifp, "transceiver (type %d) inserted.\n",
12032 		    pi->mod_type);
12033 	}
12034 }
12035 
12036 void
12037 t4_os_link_changed(struct port_info *pi)
12038 {
12039 	struct vi_info *vi;
12040 	struct ifnet *ifp;
12041 	struct link_config *lc = &pi->link_cfg;
12042 	struct adapter *sc = pi->adapter;
12043 	int v;
12044 
12045 	PORT_LOCK_ASSERT_OWNED(pi);
12046 
12047 	if (is_t6(sc)) {
12048 		if (lc->link_ok) {
12049 			if (lc->speed > 25000 ||
12050 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12051 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12052 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12053 			} else {
12054 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12055 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12056 			}
12057 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12058 			pi->stats.rx_fcs_err = 0;
12059 		} else {
12060 			pi->fcs_reg = -1;
12061 		}
12062 	} else {
12063 		MPASS(pi->fcs_reg != -1);
12064 		MPASS(pi->fcs_base == 0);
12065 	}
12066 
12067 	for_each_vi(pi, v, vi) {
12068 		ifp = vi->ifp;
12069 		if (ifp == NULL)
12070 			continue;
12071 
12072 		if (lc->link_ok) {
12073 			ifp->if_baudrate = IF_Mbps(lc->speed);
12074 			if_link_state_change(ifp, LINK_STATE_UP);
12075 		} else {
12076 			if_link_state_change(ifp, LINK_STATE_DOWN);
12077 		}
12078 	}
12079 }
12080 
12081 void
12082 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12083 {
12084 	struct adapter *sc;
12085 
12086 	sx_slock(&t4_list_lock);
12087 	SLIST_FOREACH(sc, &t4_list, link) {
12088 		/*
12089 		 * func should not make any assumptions about what state sc is
12090 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12091 		 */
12092 		func(sc, arg);
12093 	}
12094 	sx_sunlock(&t4_list_lock);
12095 }
12096 
12097 static int
12098 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12099     struct thread *td)
12100 {
12101 	int rc;
12102 	struct adapter *sc = dev->si_drv1;
12103 
12104 	rc = priv_check(td, PRIV_DRIVER);
12105 	if (rc != 0)
12106 		return (rc);
12107 
12108 	switch (cmd) {
12109 	case CHELSIO_T4_GETREG: {
12110 		struct t4_reg *edata = (struct t4_reg *)data;
12111 
12112 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12113 			return (EFAULT);
12114 
12115 		mtx_lock(&sc->reg_lock);
12116 		if (hw_off_limits(sc))
12117 			rc = ENXIO;
12118 		else if (edata->size == 4)
12119 			edata->val = t4_read_reg(sc, edata->addr);
12120 		else if (edata->size == 8)
12121 			edata->val = t4_read_reg64(sc, edata->addr);
12122 		else
12123 			rc = EINVAL;
12124 		mtx_unlock(&sc->reg_lock);
12125 
12126 		break;
12127 	}
12128 	case CHELSIO_T4_SETREG: {
12129 		struct t4_reg *edata = (struct t4_reg *)data;
12130 
12131 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12132 			return (EFAULT);
12133 
12134 		mtx_lock(&sc->reg_lock);
12135 		if (hw_off_limits(sc))
12136 			rc = ENXIO;
12137 		else if (edata->size == 4) {
12138 			if (edata->val & 0xffffffff00000000)
12139 				rc = EINVAL;
12140 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12141 		} else if (edata->size == 8)
12142 			t4_write_reg64(sc, edata->addr, edata->val);
12143 		else
12144 			rc = EINVAL;
12145 		mtx_unlock(&sc->reg_lock);
12146 
12147 		break;
12148 	}
12149 	case CHELSIO_T4_REGDUMP: {
12150 		struct t4_regdump *regs = (struct t4_regdump *)data;
12151 		int reglen = t4_get_regs_len(sc);
12152 		uint8_t *buf;
12153 
12154 		if (regs->len < reglen) {
12155 			regs->len = reglen; /* hint to the caller */
12156 			return (ENOBUFS);
12157 		}
12158 
12159 		regs->len = reglen;
12160 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12161 		mtx_lock(&sc->reg_lock);
12162 		if (hw_off_limits(sc))
12163 			rc = ENXIO;
12164 		else
12165 			get_regs(sc, regs, buf);
12166 		mtx_unlock(&sc->reg_lock);
12167 		if (rc == 0)
12168 			rc = copyout(buf, regs->data, reglen);
12169 		free(buf, M_CXGBE);
12170 		break;
12171 	}
12172 	case CHELSIO_T4_GET_FILTER_MODE:
12173 		rc = get_filter_mode(sc, (uint32_t *)data);
12174 		break;
12175 	case CHELSIO_T4_SET_FILTER_MODE:
12176 		rc = set_filter_mode(sc, *(uint32_t *)data);
12177 		break;
12178 	case CHELSIO_T4_SET_FILTER_MASK:
12179 		rc = set_filter_mask(sc, *(uint32_t *)data);
12180 		break;
12181 	case CHELSIO_T4_GET_FILTER:
12182 		rc = get_filter(sc, (struct t4_filter *)data);
12183 		break;
12184 	case CHELSIO_T4_SET_FILTER:
12185 		rc = set_filter(sc, (struct t4_filter *)data);
12186 		break;
12187 	case CHELSIO_T4_DEL_FILTER:
12188 		rc = del_filter(sc, (struct t4_filter *)data);
12189 		break;
12190 	case CHELSIO_T4_GET_SGE_CONTEXT:
12191 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12192 		break;
12193 	case CHELSIO_T4_LOAD_FW:
12194 		rc = load_fw(sc, (struct t4_data *)data);
12195 		break;
12196 	case CHELSIO_T4_GET_MEM:
12197 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12198 		break;
12199 	case CHELSIO_T4_GET_I2C:
12200 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12201 		break;
12202 	case CHELSIO_T4_CLEAR_STATS:
12203 		rc = clear_stats(sc, *(uint32_t *)data);
12204 		break;
12205 	case CHELSIO_T4_SCHED_CLASS:
12206 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12207 		break;
12208 	case CHELSIO_T4_SCHED_QUEUE:
12209 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12210 		break;
12211 	case CHELSIO_T4_GET_TRACER:
12212 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12213 		break;
12214 	case CHELSIO_T4_SET_TRACER:
12215 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12216 		break;
12217 	case CHELSIO_T4_LOAD_CFG:
12218 		rc = load_cfg(sc, (struct t4_data *)data);
12219 		break;
12220 	case CHELSIO_T4_LOAD_BOOT:
12221 		rc = load_boot(sc, (struct t4_bootrom *)data);
12222 		break;
12223 	case CHELSIO_T4_LOAD_BOOTCFG:
12224 		rc = load_bootcfg(sc, (struct t4_data *)data);
12225 		break;
12226 	case CHELSIO_T4_CUDBG_DUMP:
12227 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12228 		break;
12229 	case CHELSIO_T4_SET_OFLD_POLICY:
12230 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12231 		break;
12232 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12233 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12234 		break;
12235 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12236 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12237 		break;
12238 	default:
12239 		rc = ENOTTY;
12240 	}
12241 
12242 	return (rc);
12243 }
12244 
12245 #ifdef TCP_OFFLOAD
12246 static int
12247 toe_capability(struct vi_info *vi, bool enable)
12248 {
12249 	int rc;
12250 	struct port_info *pi = vi->pi;
12251 	struct adapter *sc = pi->adapter;
12252 
12253 	ASSERT_SYNCHRONIZED_OP(sc);
12254 
12255 	if (!is_offload(sc))
12256 		return (ENODEV);
12257 	if (hw_off_limits(sc))
12258 		return (ENXIO);
12259 
12260 	if (enable) {
12261 #ifdef KERN_TLS
12262 		if (sc->flags & KERN_TLS_ON) {
12263 			int i, j, n;
12264 			struct port_info *p;
12265 			struct vi_info *v;
12266 
12267 			/*
12268 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12269 			 * on any ifnet.
12270 			 */
12271 			n = 0;
12272 			for_each_port(sc, i) {
12273 				p = sc->port[i];
12274 				for_each_vi(p, j, v) {
12275 					if (v->ifp->if_capenable & IFCAP_TXTLS) {
12276 						CH_WARN(sc,
12277 						    "%s has NIC TLS enabled.\n",
12278 						    device_get_nameunit(v->dev));
12279 						n++;
12280 					}
12281 				}
12282 			}
12283 			if (n > 0) {
12284 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12285 				    "associated with this adapter before "
12286 				    "trying to enable TOE.\n");
12287 				return (EAGAIN);
12288 			}
12289 			rc = t4_config_kern_tls(sc, false);
12290 			if (rc)
12291 				return (rc);
12292 		}
12293 #endif
12294 		if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
12295 			/* TOE is already enabled. */
12296 			return (0);
12297 		}
12298 
12299 		/*
12300 		 * We need the port's queues around so that we're able to send
12301 		 * and receive CPLs to/from the TOE even if the ifnet for this
12302 		 * port has never been UP'd administratively.
12303 		 */
12304 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12305 			return (rc);
12306 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12307 		    ((rc = vi_init(&pi->vi[0])) != 0))
12308 			return (rc);
12309 
12310 		if (isset(&sc->offload_map, pi->port_id)) {
12311 			/* TOE is enabled on another VI of this port. */
12312 			pi->uld_vis++;
12313 			return (0);
12314 		}
12315 
12316 		if (!uld_active(sc, ULD_TOM)) {
12317 			rc = t4_activate_uld(sc, ULD_TOM);
12318 			if (rc == EAGAIN) {
12319 				log(LOG_WARNING,
12320 				    "You must kldload t4_tom.ko before trying "
12321 				    "to enable TOE on a cxgbe interface.\n");
12322 			}
12323 			if (rc != 0)
12324 				return (rc);
12325 			KASSERT(sc->tom_softc != NULL,
12326 			    ("%s: TOM activated but softc NULL", __func__));
12327 			KASSERT(uld_active(sc, ULD_TOM),
12328 			    ("%s: TOM activated but flag not set", __func__));
12329 		}
12330 
12331 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12332 		if (!uld_active(sc, ULD_IWARP))
12333 			(void) t4_activate_uld(sc, ULD_IWARP);
12334 		if (!uld_active(sc, ULD_ISCSI))
12335 			(void) t4_activate_uld(sc, ULD_ISCSI);
12336 
12337 		pi->uld_vis++;
12338 		setbit(&sc->offload_map, pi->port_id);
12339 	} else {
12340 		pi->uld_vis--;
12341 
12342 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12343 			return (0);
12344 
12345 		KASSERT(uld_active(sc, ULD_TOM),
12346 		    ("%s: TOM never initialized?", __func__));
12347 		clrbit(&sc->offload_map, pi->port_id);
12348 	}
12349 
12350 	return (0);
12351 }
12352 
12353 /*
12354  * Add an upper layer driver to the global list.
12355  */
12356 int
12357 t4_register_uld(struct uld_info *ui)
12358 {
12359 	int rc = 0;
12360 	struct uld_info *u;
12361 
12362 	sx_xlock(&t4_uld_list_lock);
12363 	SLIST_FOREACH(u, &t4_uld_list, link) {
12364 	    if (u->uld_id == ui->uld_id) {
12365 		    rc = EEXIST;
12366 		    goto done;
12367 	    }
12368 	}
12369 
12370 	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
12371 	ui->refcount = 0;
12372 done:
12373 	sx_xunlock(&t4_uld_list_lock);
12374 	return (rc);
12375 }
12376 
12377 int
12378 t4_unregister_uld(struct uld_info *ui)
12379 {
12380 	int rc = EINVAL;
12381 	struct uld_info *u;
12382 
12383 	sx_xlock(&t4_uld_list_lock);
12384 
12385 	SLIST_FOREACH(u, &t4_uld_list, link) {
12386 	    if (u == ui) {
12387 		    if (ui->refcount > 0) {
12388 			    rc = EBUSY;
12389 			    goto done;
12390 		    }
12391 
12392 		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
12393 		    rc = 0;
12394 		    goto done;
12395 	    }
12396 	}
12397 done:
12398 	sx_xunlock(&t4_uld_list_lock);
12399 	return (rc);
12400 }
12401 
12402 int
12403 t4_activate_uld(struct adapter *sc, int id)
12404 {
12405 	int rc;
12406 	struct uld_info *ui;
12407 
12408 	ASSERT_SYNCHRONIZED_OP(sc);
12409 
12410 	if (id < 0 || id > ULD_MAX)
12411 		return (EINVAL);
12412 	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
12413 
12414 	sx_slock(&t4_uld_list_lock);
12415 
12416 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12417 		if (ui->uld_id == id) {
12418 			if (!(sc->flags & FULL_INIT_DONE)) {
12419 				rc = adapter_init(sc);
12420 				if (rc != 0)
12421 					break;
12422 			}
12423 
12424 			rc = ui->activate(sc);
12425 			if (rc == 0) {
12426 				setbit(&sc->active_ulds, id);
12427 				ui->refcount++;
12428 			}
12429 			break;
12430 		}
12431 	}
12432 
12433 	sx_sunlock(&t4_uld_list_lock);
12434 
12435 	return (rc);
12436 }
12437 
12438 int
12439 t4_deactivate_uld(struct adapter *sc, int id)
12440 {
12441 	int rc;
12442 	struct uld_info *ui;
12443 
12444 	ASSERT_SYNCHRONIZED_OP(sc);
12445 
12446 	if (id < 0 || id > ULD_MAX)
12447 		return (EINVAL);
12448 	rc = ENXIO;
12449 
12450 	sx_slock(&t4_uld_list_lock);
12451 
12452 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12453 		if (ui->uld_id == id) {
12454 			rc = ui->deactivate(sc);
12455 			if (rc == 0) {
12456 				clrbit(&sc->active_ulds, id);
12457 				ui->refcount--;
12458 			}
12459 			break;
12460 		}
12461 	}
12462 
12463 	sx_sunlock(&t4_uld_list_lock);
12464 
12465 	return (rc);
12466 }
12467 
12468 static void
12469 t4_async_event(void *arg, int n)
12470 {
12471 	struct uld_info *ui;
12472 	struct adapter *sc = (struct adapter *)arg;
12473 
12474 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
12475 		return;
12476 	sx_slock(&t4_uld_list_lock);
12477 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12478 		if (ui->uld_id == ULD_IWARP) {
12479 			ui->async_event(sc);
12480 			break;
12481 		}
12482 	}
12483 	sx_sunlock(&t4_uld_list_lock);
12484 	end_synchronized_op(sc, 0);
12485 }
12486 
12487 int
12488 uld_active(struct adapter *sc, int uld_id)
12489 {
12490 
12491 	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
12492 
12493 	return (isset(&sc->active_ulds, uld_id));
12494 }
12495 #endif
12496 
12497 #ifdef KERN_TLS
12498 static int
12499 ktls_capability(struct adapter *sc, bool enable)
12500 {
12501 	ASSERT_SYNCHRONIZED_OP(sc);
12502 
12503 	if (!is_ktls(sc))
12504 		return (ENODEV);
12505 	if (hw_off_limits(sc))
12506 		return (ENXIO);
12507 
12508 	if (enable) {
12509 		if (sc->flags & KERN_TLS_ON)
12510 			return (0);	/* already on */
12511 		if (sc->offload_map != 0) {
12512 			CH_WARN(sc,
12513 			    "Disable TOE on all interfaces associated with "
12514 			    "this adapter before trying to enable NIC TLS.\n");
12515 			return (EAGAIN);
12516 		}
12517 		return (t4_config_kern_tls(sc, true));
12518 	} else {
12519 		/*
12520 		 * Nothing to do for disable.  If TOE is enabled sometime later
12521 		 * then toe_capability will reconfigure the hardware.
12522 		 */
12523 		return (0);
12524 	}
12525 }
12526 #endif
12527 
12528 /*
12529  * t  = ptr to tunable.
12530  * nc = number of CPUs.
12531  * c  = compiled in default for that tunable.
12532  */
12533 static void
12534 calculate_nqueues(int *t, int nc, const int c)
12535 {
12536 	int nq;
12537 
12538 	if (*t > 0)
12539 		return;
12540 	nq = *t < 0 ? -*t : c;
12541 	*t = min(nc, nq);
12542 }
12543 
12544 /*
12545  * Come up with reasonable defaults for some of the tunables, provided they're
12546  * not set by the user (in which case we'll use the values as is).
12547  */
12548 static void
12549 tweak_tunables(void)
12550 {
12551 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12552 
12553 	if (t4_ntxq < 1) {
12554 #ifdef RSS
12555 		t4_ntxq = rss_getnumbuckets();
12556 #else
12557 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12558 #endif
12559 	}
12560 
12561 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12562 
12563 	if (t4_nrxq < 1) {
12564 #ifdef RSS
12565 		t4_nrxq = rss_getnumbuckets();
12566 #else
12567 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12568 #endif
12569 	}
12570 
12571 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12572 
12573 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12574 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12575 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12576 #endif
12577 #ifdef TCP_OFFLOAD
12578 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12579 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12580 #endif
12581 
12582 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12583 	if (t4_toecaps_allowed == -1)
12584 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12585 #else
12586 	if (t4_toecaps_allowed == -1)
12587 		t4_toecaps_allowed = 0;
12588 #endif
12589 
12590 #ifdef TCP_OFFLOAD
12591 	if (t4_rdmacaps_allowed == -1) {
12592 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12593 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12594 	}
12595 
12596 	if (t4_iscsicaps_allowed == -1) {
12597 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12598 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12599 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12600 	}
12601 
12602 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12603 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12604 
12605 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12606 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12607 
12608 	if (t4_toe_tls_rx_timeout < 0)
12609 		t4_toe_tls_rx_timeout = 0;
12610 #else
12611 	if (t4_rdmacaps_allowed == -1)
12612 		t4_rdmacaps_allowed = 0;
12613 
12614 	if (t4_iscsicaps_allowed == -1)
12615 		t4_iscsicaps_allowed = 0;
12616 #endif
12617 
12618 #ifdef DEV_NETMAP
12619 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12620 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12621 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12622 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12623 #endif
12624 
12625 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12626 		t4_tmr_idx = TMR_IDX;
12627 
12628 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12629 		t4_pktc_idx = PKTC_IDX;
12630 
12631 	if (t4_qsize_txq < 128)
12632 		t4_qsize_txq = 128;
12633 
12634 	if (t4_qsize_rxq < 128)
12635 		t4_qsize_rxq = 128;
12636 	while (t4_qsize_rxq & 7)
12637 		t4_qsize_rxq++;
12638 
12639 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12640 
12641 	/*
12642 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12643 	 * VI for the port.  The rest are additional virtual interfaces on the
12644 	 * same physical port.  Note that the main VI does not have native
12645 	 * netmap support but the extra VIs do.
12646 	 *
12647 	 * Limit the number of VIs per port to the number of available
12648 	 * MAC addresses per port.
12649 	 */
12650 	if (t4_num_vis < 1)
12651 		t4_num_vis = 1;
12652 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12653 		t4_num_vis = nitems(vi_mac_funcs);
12654 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12655 	}
12656 
12657 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12658 		pcie_relaxed_ordering = 1;
12659 #if defined(__i386__) || defined(__amd64__)
12660 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12661 			pcie_relaxed_ordering = 0;
12662 #endif
12663 	}
12664 }
12665 
12666 #ifdef DDB
12667 static void
12668 t4_dump_tcb(struct adapter *sc, int tid)
12669 {
12670 	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
12671 
12672 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12673 	save = t4_read_reg(sc, reg);
12674 	base = sc->memwin[2].mw_base;
12675 
12676 	/* Dump TCB for the tid */
12677 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12678 	tcb_addr += tid * TCB_SIZE;
12679 
12680 	if (is_t4(sc)) {
12681 		pf = 0;
12682 		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
12683 	} else {
12684 		pf = V_PFNUM(sc->pf);
12685 		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
12686 	}
12687 	t4_write_reg(sc, reg, win_pos | pf);
12688 	t4_read_reg(sc, reg);
12689 
12690 	off = tcb_addr - win_pos;
12691 	for (i = 0; i < 4; i++) {
12692 		uint32_t buf[8];
12693 		for (j = 0; j < 8; j++, off += 4)
12694 			buf[j] = htonl(t4_read_reg(sc, base + off));
12695 
12696 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12697 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12698 		    buf[7]);
12699 	}
12700 
12701 	t4_write_reg(sc, reg, save);
12702 	t4_read_reg(sc, reg);
12703 }
12704 
12705 static void
12706 t4_dump_devlog(struct adapter *sc)
12707 {
12708 	struct devlog_params *dparams = &sc->params.devlog;
12709 	struct fw_devlog_e e;
12710 	int i, first, j, m, nentries, rc;
12711 	uint64_t ftstamp = UINT64_MAX;
12712 
12713 	if (dparams->start == 0) {
12714 		db_printf("devlog params not valid\n");
12715 		return;
12716 	}
12717 
12718 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12719 	m = fwmtype_to_hwmtype(dparams->memtype);
12720 
12721 	/* Find the first entry. */
12722 	first = -1;
12723 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12724 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12725 		    sizeof(e), (void *)&e);
12726 		if (rc != 0)
12727 			break;
12728 
12729 		if (e.timestamp == 0)
12730 			break;
12731 
12732 		e.timestamp = be64toh(e.timestamp);
12733 		if (e.timestamp < ftstamp) {
12734 			ftstamp = e.timestamp;
12735 			first = i;
12736 		}
12737 	}
12738 
12739 	if (first == -1)
12740 		return;
12741 
12742 	i = first;
12743 	do {
12744 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12745 		    sizeof(e), (void *)&e);
12746 		if (rc != 0)
12747 			return;
12748 
12749 		if (e.timestamp == 0)
12750 			return;
12751 
12752 		e.timestamp = be64toh(e.timestamp);
12753 		e.seqno = be32toh(e.seqno);
12754 		for (j = 0; j < 8; j++)
12755 			e.params[j] = be32toh(e.params[j]);
12756 
12757 		db_printf("%10d  %15ju  %8s  %8s  ",
12758 		    e.seqno, e.timestamp,
12759 		    (e.level < nitems(devlog_level_strings) ?
12760 			devlog_level_strings[e.level] : "UNKNOWN"),
12761 		    (e.facility < nitems(devlog_facility_strings) ?
12762 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12763 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12764 		    e.params[3], e.params[4], e.params[5], e.params[6],
12765 		    e.params[7]);
12766 
12767 		if (++i == nentries)
12768 			i = 0;
12769 	} while (i != first && !db_pager_quit);
12770 }
12771 
12772 static struct command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
12773 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
12774 
12775 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
12776 {
12777 	device_t dev;
12778 	int t;
12779 	bool valid;
12780 
12781 	valid = false;
12782 	t = db_read_token();
12783 	if (t == tIDENT) {
12784 		dev = device_lookup_by_name(db_tok_string);
12785 		valid = true;
12786 	}
12787 	db_skip_to_eol();
12788 	if (!valid) {
12789 		db_printf("usage: show t4 devlog <nexus>\n");
12790 		return;
12791 	}
12792 
12793 	if (dev == NULL) {
12794 		db_printf("device not found\n");
12795 		return;
12796 	}
12797 
12798 	t4_dump_devlog(device_get_softc(dev));
12799 }
12800 
12801 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
12802 {
12803 	device_t dev;
12804 	int radix, tid, t;
12805 	bool valid;
12806 
12807 	valid = false;
12808 	radix = db_radix;
12809 	db_radix = 10;
12810 	t = db_read_token();
12811 	if (t == tIDENT) {
12812 		dev = device_lookup_by_name(db_tok_string);
12813 		t = db_read_token();
12814 		if (t == tNUMBER) {
12815 			tid = db_tok_number;
12816 			valid = true;
12817 		}
12818 	}
12819 	db_radix = radix;
12820 	db_skip_to_eol();
12821 	if (!valid) {
12822 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
12823 		return;
12824 	}
12825 
12826 	if (dev == NULL) {
12827 		db_printf("device not found\n");
12828 		return;
12829 	}
12830 	if (tid < 0) {
12831 		db_printf("invalid tid\n");
12832 		return;
12833 	}
12834 
12835 	t4_dump_tcb(device_get_softc(dev), tid);
12836 }
12837 #endif
12838 
12839 static eventhandler_tag vxlan_start_evtag;
12840 static eventhandler_tag vxlan_stop_evtag;
12841 
12842 struct vxlan_evargs {
12843 	struct ifnet *ifp;
12844 	uint16_t port;
12845 };
12846 
12847 static void
12848 enable_vxlan_rx(struct adapter *sc)
12849 {
12850 	int i, rc;
12851 	struct port_info *pi;
12852 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
12853 
12854 	ASSERT_SYNCHRONIZED_OP(sc);
12855 
12856 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
12857 	    F_VXLAN_EN);
12858 	for_each_port(sc, i) {
12859 		pi = sc->port[i];
12860 		if (pi->vxlan_tcam_entry == true)
12861 			continue;
12862 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
12863 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
12864 		    true);
12865 		if (rc < 0) {
12866 			rc = -rc;
12867 			CH_ERR(&pi->vi[0],
12868 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
12869 		} else {
12870 			MPASS(rc == sc->rawf_base + pi->port_id);
12871 			pi->vxlan_tcam_entry = true;
12872 		}
12873 	}
12874 }
12875 
12876 static void
12877 t4_vxlan_start(struct adapter *sc, void *arg)
12878 {
12879 	struct vxlan_evargs *v = arg;
12880 
12881 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
12882 		return;
12883 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
12884 		return;
12885 
12886 	if (sc->vxlan_refcount == 0) {
12887 		sc->vxlan_port = v->port;
12888 		sc->vxlan_refcount = 1;
12889 		if (!hw_off_limits(sc))
12890 			enable_vxlan_rx(sc);
12891 	} else if (sc->vxlan_port == v->port) {
12892 		sc->vxlan_refcount++;
12893 	} else {
12894 		CH_ERR(sc, "VXLAN already configured on port  %d; "
12895 		    "ignoring attempt to configure it on port %d\n",
12896 		    sc->vxlan_port, v->port);
12897 	}
12898 	end_synchronized_op(sc, 0);
12899 }
12900 
12901 static void
12902 t4_vxlan_stop(struct adapter *sc, void *arg)
12903 {
12904 	struct vxlan_evargs *v = arg;
12905 
12906 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
12907 		return;
12908 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
12909 		return;
12910 
12911 	/*
12912 	 * VXLANs may have been configured before the driver was loaded so we
12913 	 * may see more stops than starts.  This is not handled cleanly but at
12914 	 * least we keep the refcount sane.
12915 	 */
12916 	if (sc->vxlan_port != v->port)
12917 		goto done;
12918 	if (sc->vxlan_refcount == 0) {
12919 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
12920 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
12921 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
12922 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
12923 done:
12924 	end_synchronized_op(sc, 0);
12925 }
12926 
12927 static void
12928 t4_vxlan_start_handler(void *arg __unused, struct ifnet *ifp,
12929     sa_family_t family, u_int port)
12930 {
12931 	struct vxlan_evargs v;
12932 
12933 	MPASS(family == AF_INET || family == AF_INET6);
12934 	v.ifp = ifp;
12935 	v.port = port;
12936 
12937 	t4_iterate(t4_vxlan_start, &v);
12938 }
12939 
12940 static void
12941 t4_vxlan_stop_handler(void *arg __unused, struct ifnet *ifp, sa_family_t family,
12942     u_int port)
12943 {
12944 	struct vxlan_evargs v;
12945 
12946 	MPASS(family == AF_INET || family == AF_INET6);
12947 	v.ifp = ifp;
12948 	v.port = port;
12949 
12950 	t4_iterate(t4_vxlan_stop, &v);
12951 }
12952 
12953 
12954 static struct sx mlu;	/* mod load unload */
12955 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
12956 
12957 static int
12958 mod_event(module_t mod, int cmd, void *arg)
12959 {
12960 	int rc = 0;
12961 	static int loaded = 0;
12962 
12963 	switch (cmd) {
12964 	case MOD_LOAD:
12965 		sx_xlock(&mlu);
12966 		if (loaded++ == 0) {
12967 			t4_sge_modload();
12968 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
12969 			    t4_filter_rpl, CPL_COOKIE_FILTER);
12970 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
12971 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
12972 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
12973 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
12974 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
12975 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
12976 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
12977 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
12978 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
12979 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
12980 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
12981 			    do_smt_write_rpl);
12982 			sx_init(&t4_list_lock, "T4/T5 adapters");
12983 			SLIST_INIT(&t4_list);
12984 			callout_init(&fatal_callout, 1);
12985 #ifdef TCP_OFFLOAD
12986 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
12987 			SLIST_INIT(&t4_uld_list);
12988 #endif
12989 #ifdef INET6
12990 			t4_clip_modload();
12991 #endif
12992 #ifdef KERN_TLS
12993 			t6_ktls_modload();
12994 #endif
12995 			t4_tracer_modload();
12996 			tweak_tunables();
12997 			vxlan_start_evtag =
12998 			    EVENTHANDLER_REGISTER(vxlan_start,
12999 				t4_vxlan_start_handler, NULL,
13000 				EVENTHANDLER_PRI_ANY);
13001 			vxlan_stop_evtag =
13002 			    EVENTHANDLER_REGISTER(vxlan_stop,
13003 				t4_vxlan_stop_handler, NULL,
13004 				EVENTHANDLER_PRI_ANY);
13005 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
13006 			    taskqueue_thread_enqueue, &reset_tq);
13007 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
13008 			    "t4_rst_thr");
13009 		}
13010 		sx_xunlock(&mlu);
13011 		break;
13012 
13013 	case MOD_UNLOAD:
13014 		sx_xlock(&mlu);
13015 		if (--loaded == 0) {
13016 			int tries;
13017 
13018 			taskqueue_free(reset_tq);
13019 			sx_slock(&t4_list_lock);
13020 			if (!SLIST_EMPTY(&t4_list)) {
13021 				rc = EBUSY;
13022 				sx_sunlock(&t4_list_lock);
13023 				goto done_unload;
13024 			}
13025 #ifdef TCP_OFFLOAD
13026 			sx_slock(&t4_uld_list_lock);
13027 			if (!SLIST_EMPTY(&t4_uld_list)) {
13028 				rc = EBUSY;
13029 				sx_sunlock(&t4_uld_list_lock);
13030 				sx_sunlock(&t4_list_lock);
13031 				goto done_unload;
13032 			}
13033 #endif
13034 			tries = 0;
13035 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13036 				uprintf("%ju clusters with custom free routine "
13037 				    "still is use.\n", t4_sge_extfree_refs());
13038 				pause("t4unload", 2 * hz);
13039 			}
13040 #ifdef TCP_OFFLOAD
13041 			sx_sunlock(&t4_uld_list_lock);
13042 #endif
13043 			sx_sunlock(&t4_list_lock);
13044 
13045 			if (t4_sge_extfree_refs() == 0) {
13046 				EVENTHANDLER_DEREGISTER(vxlan_start,
13047 				    vxlan_start_evtag);
13048 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13049 				    vxlan_stop_evtag);
13050 				t4_tracer_modunload();
13051 #ifdef KERN_TLS
13052 				t6_ktls_modunload();
13053 #endif
13054 #ifdef INET6
13055 				t4_clip_modunload();
13056 #endif
13057 #ifdef TCP_OFFLOAD
13058 				sx_destroy(&t4_uld_list_lock);
13059 #endif
13060 				sx_destroy(&t4_list_lock);
13061 				t4_sge_modunload();
13062 				loaded = 0;
13063 			} else {
13064 				rc = EBUSY;
13065 				loaded++;	/* undo earlier decrement */
13066 			}
13067 		}
13068 done_unload:
13069 		sx_xunlock(&mlu);
13070 		break;
13071 	}
13072 
13073 	return (rc);
13074 }
13075 
13076 static devclass_t t4_devclass, t5_devclass, t6_devclass;
13077 static devclass_t cxgbe_devclass, cxl_devclass, cc_devclass;
13078 static devclass_t vcxgbe_devclass, vcxl_devclass, vcc_devclass;
13079 
13080 DRIVER_MODULE(t4nex, pci, t4_driver, t4_devclass, mod_event, 0);
13081 MODULE_VERSION(t4nex, 1);
13082 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13083 #ifdef DEV_NETMAP
13084 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13085 #endif /* DEV_NETMAP */
13086 
13087 DRIVER_MODULE(t5nex, pci, t5_driver, t5_devclass, mod_event, 0);
13088 MODULE_VERSION(t5nex, 1);
13089 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13090 #ifdef DEV_NETMAP
13091 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13092 #endif /* DEV_NETMAP */
13093 
13094 DRIVER_MODULE(t6nex, pci, t6_driver, t6_devclass, mod_event, 0);
13095 MODULE_VERSION(t6nex, 1);
13096 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13097 #ifdef DEV_NETMAP
13098 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13099 #endif /* DEV_NETMAP */
13100 
13101 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, cxgbe_devclass, 0, 0);
13102 MODULE_VERSION(cxgbe, 1);
13103 
13104 DRIVER_MODULE(cxl, t5nex, cxl_driver, cxl_devclass, 0, 0);
13105 MODULE_VERSION(cxl, 1);
13106 
13107 DRIVER_MODULE(cc, t6nex, cc_driver, cc_devclass, 0, 0);
13108 MODULE_VERSION(cc, 1);
13109 
13110 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, vcxgbe_devclass, 0, 0);
13111 MODULE_VERSION(vcxgbe, 1);
13112 
13113 DRIVER_MODULE(vcxl, cxl, vcxl_driver, vcxl_devclass, 0, 0);
13114 MODULE_VERSION(vcxl, 1);
13115 
13116 DRIVER_MODULE(vcc, cc, vcc_driver, vcc_devclass, 0, 0);
13117 MODULE_VERSION(vcc, 1);
13118