xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision f7c32ed617858bcd22f8d1b03199099d50125721)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 Chelsio Communications, Inc.
5  * All rights reserved.
6  * Written by: Navdeep Parhar <np@FreeBSD.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include "opt_ddb.h"
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_kern_tls.h"
37 #include "opt_ratelimit.h"
38 #include "opt_rss.h"
39 
40 #include <sys/param.h>
41 #include <sys/conf.h>
42 #include <sys/priv.h>
43 #include <sys/kernel.h>
44 #include <sys/bus.h>
45 #include <sys/eventhandler.h>
46 #include <sys/module.h>
47 #include <sys/malloc.h>
48 #include <sys/queue.h>
49 #include <sys/taskqueue.h>
50 #include <sys/pciio.h>
51 #include <dev/pci/pcireg.h>
52 #include <dev/pci/pcivar.h>
53 #include <dev/pci/pci_private.h>
54 #include <sys/firmware.h>
55 #include <sys/sbuf.h>
56 #include <sys/smp.h>
57 #include <sys/socket.h>
58 #include <sys/sockio.h>
59 #include <sys/sysctl.h>
60 #include <net/ethernet.h>
61 #include <net/if.h>
62 #include <net/if_types.h>
63 #include <net/if_dl.h>
64 #include <net/if_vlan_var.h>
65 #ifdef RSS
66 #include <net/rss_config.h>
67 #endif
68 #include <netinet/in.h>
69 #include <netinet/ip.h>
70 #ifdef KERN_TLS
71 #include <netinet/tcp_seq.h>
72 #endif
73 #if defined(__i386__) || defined(__amd64__)
74 #include <machine/md_var.h>
75 #include <machine/cputypes.h>
76 #include <vm/vm.h>
77 #include <vm/pmap.h>
78 #endif
79 #ifdef DDB
80 #include <ddb/ddb.h>
81 #include <ddb/db_lex.h>
82 #endif
83 
84 #include "common/common.h"
85 #include "common/t4_msg.h"
86 #include "common/t4_regs.h"
87 #include "common/t4_regs_values.h"
88 #include "cudbg/cudbg.h"
89 #include "t4_clip.h"
90 #include "t4_ioctl.h"
91 #include "t4_l2t.h"
92 #include "t4_mp_ring.h"
93 #include "t4_if.h"
94 #include "t4_smt.h"
95 
96 /* T4 bus driver interface */
97 static int t4_probe(device_t);
98 static int t4_attach(device_t);
99 static int t4_detach(device_t);
100 static int t4_child_location(device_t, device_t, struct sbuf *);
101 static int t4_ready(device_t);
102 static int t4_read_port_device(device_t, int, device_t *);
103 static int t4_suspend(device_t);
104 static int t4_resume(device_t);
105 static int t4_reset_prepare(device_t, device_t);
106 static int t4_reset_post(device_t, device_t);
107 static device_method_t t4_methods[] = {
108 	DEVMETHOD(device_probe,		t4_probe),
109 	DEVMETHOD(device_attach,	t4_attach),
110 	DEVMETHOD(device_detach,	t4_detach),
111 	DEVMETHOD(device_suspend,	t4_suspend),
112 	DEVMETHOD(device_resume,	t4_resume),
113 
114 	DEVMETHOD(bus_child_location,	t4_child_location),
115 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
116 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
117 
118 	DEVMETHOD(t4_is_main_ready,	t4_ready),
119 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
120 
121 	DEVMETHOD_END
122 };
123 static driver_t t4_driver = {
124 	"t4nex",
125 	t4_methods,
126 	sizeof(struct adapter)
127 };
128 
129 
130 /* T4 port (cxgbe) interface */
131 static int cxgbe_probe(device_t);
132 static int cxgbe_attach(device_t);
133 static int cxgbe_detach(device_t);
134 device_method_t cxgbe_methods[] = {
135 	DEVMETHOD(device_probe,		cxgbe_probe),
136 	DEVMETHOD(device_attach,	cxgbe_attach),
137 	DEVMETHOD(device_detach,	cxgbe_detach),
138 	{ 0, 0 }
139 };
140 static driver_t cxgbe_driver = {
141 	"cxgbe",
142 	cxgbe_methods,
143 	sizeof(struct port_info)
144 };
145 
146 /* T4 VI (vcxgbe) interface */
147 static int vcxgbe_probe(device_t);
148 static int vcxgbe_attach(device_t);
149 static int vcxgbe_detach(device_t);
150 static device_method_t vcxgbe_methods[] = {
151 	DEVMETHOD(device_probe,		vcxgbe_probe),
152 	DEVMETHOD(device_attach,	vcxgbe_attach),
153 	DEVMETHOD(device_detach,	vcxgbe_detach),
154 	{ 0, 0 }
155 };
156 static driver_t vcxgbe_driver = {
157 	"vcxgbe",
158 	vcxgbe_methods,
159 	sizeof(struct vi_info)
160 };
161 
162 static d_ioctl_t t4_ioctl;
163 
164 static struct cdevsw t4_cdevsw = {
165        .d_version = D_VERSION,
166        .d_ioctl = t4_ioctl,
167        .d_name = "t4nex",
168 };
169 
170 /* T5 bus driver interface */
171 static int t5_probe(device_t);
172 static device_method_t t5_methods[] = {
173 	DEVMETHOD(device_probe,		t5_probe),
174 	DEVMETHOD(device_attach,	t4_attach),
175 	DEVMETHOD(device_detach,	t4_detach),
176 	DEVMETHOD(device_suspend,	t4_suspend),
177 	DEVMETHOD(device_resume,	t4_resume),
178 
179 	DEVMETHOD(bus_child_location,	t4_child_location),
180 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
181 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
182 
183 	DEVMETHOD(t4_is_main_ready,	t4_ready),
184 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
185 
186 	DEVMETHOD_END
187 };
188 static driver_t t5_driver = {
189 	"t5nex",
190 	t5_methods,
191 	sizeof(struct adapter)
192 };
193 
194 
195 /* T5 port (cxl) interface */
196 static driver_t cxl_driver = {
197 	"cxl",
198 	cxgbe_methods,
199 	sizeof(struct port_info)
200 };
201 
202 /* T5 VI (vcxl) interface */
203 static driver_t vcxl_driver = {
204 	"vcxl",
205 	vcxgbe_methods,
206 	sizeof(struct vi_info)
207 };
208 
209 /* T6 bus driver interface */
210 static int t6_probe(device_t);
211 static device_method_t t6_methods[] = {
212 	DEVMETHOD(device_probe,		t6_probe),
213 	DEVMETHOD(device_attach,	t4_attach),
214 	DEVMETHOD(device_detach,	t4_detach),
215 	DEVMETHOD(device_suspend,	t4_suspend),
216 	DEVMETHOD(device_resume,	t4_resume),
217 
218 	DEVMETHOD(bus_child_location,	t4_child_location),
219 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
220 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
221 
222 	DEVMETHOD(t4_is_main_ready,	t4_ready),
223 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
224 
225 	DEVMETHOD_END
226 };
227 static driver_t t6_driver = {
228 	"t6nex",
229 	t6_methods,
230 	sizeof(struct adapter)
231 };
232 
233 
234 /* T6 port (cc) interface */
235 static driver_t cc_driver = {
236 	"cc",
237 	cxgbe_methods,
238 	sizeof(struct port_info)
239 };
240 
241 /* T6 VI (vcc) interface */
242 static driver_t vcc_driver = {
243 	"vcc",
244 	vcxgbe_methods,
245 	sizeof(struct vi_info)
246 };
247 
248 /* ifnet interface */
249 static void cxgbe_init(void *);
250 static int cxgbe_ioctl(struct ifnet *, unsigned long, caddr_t);
251 static int cxgbe_transmit(struct ifnet *, struct mbuf *);
252 static void cxgbe_qflush(struct ifnet *);
253 #if defined(KERN_TLS) || defined(RATELIMIT)
254 static int cxgbe_snd_tag_alloc(struct ifnet *, union if_snd_tag_alloc_params *,
255     struct m_snd_tag **);
256 #endif
257 
258 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
259 
260 /*
261  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
262  * then ADAPTER_LOCK, then t4_uld_list_lock.
263  */
264 static struct sx t4_list_lock;
265 SLIST_HEAD(, adapter) t4_list;
266 #ifdef TCP_OFFLOAD
267 static struct sx t4_uld_list_lock;
268 SLIST_HEAD(, uld_info) t4_uld_list;
269 #endif
270 
271 /*
272  * Tunables.  See tweak_tunables() too.
273  *
274  * Each tunable is set to a default value here if it's known at compile-time.
275  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
276  * provide a reasonable default (upto n) when the driver is loaded.
277  *
278  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
279  * T5 are under hw.cxl.
280  */
281 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
282     "cxgbe(4) parameters");
283 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
284     "cxgbe(4) T5+ parameters");
285 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
286     "cxgbe(4) TOE parameters");
287 
288 /*
289  * Number of queues for tx and rx, NIC and offload.
290  */
291 #define NTXQ 16
292 int t4_ntxq = -NTXQ;
293 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
294     "Number of TX queues per port");
295 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);	/* Old name, undocumented */
296 
297 #define NRXQ 8
298 int t4_nrxq = -NRXQ;
299 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
300     "Number of RX queues per port");
301 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);	/* Old name, undocumented */
302 
303 #define NTXQ_VI 1
304 static int t4_ntxq_vi = -NTXQ_VI;
305 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
306     "Number of TX queues per VI");
307 
308 #define NRXQ_VI 1
309 static int t4_nrxq_vi = -NRXQ_VI;
310 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
311     "Number of RX queues per VI");
312 
313 static int t4_rsrv_noflowq = 0;
314 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
315     0, "Reserve TX queue 0 of each VI for non-flowid packets");
316 
317 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
318 #define NOFLDTXQ 8
319 static int t4_nofldtxq = -NOFLDTXQ;
320 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
321     "Number of offload TX queues per port");
322 
323 #define NOFLDRXQ 2
324 static int t4_nofldrxq = -NOFLDRXQ;
325 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
326     "Number of offload RX queues per port");
327 
328 #define NOFLDTXQ_VI 1
329 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
330 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
331     "Number of offload TX queues per VI");
332 
333 #define NOFLDRXQ_VI 1
334 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
335 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
336     "Number of offload RX queues per VI");
337 
338 #define TMR_IDX_OFLD 1
339 int t4_tmr_idx_ofld = TMR_IDX_OFLD;
340 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
341     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
342 
343 #define PKTC_IDX_OFLD (-1)
344 int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
345 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
346     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
347 
348 /* 0 means chip/fw default, non-zero number is value in microseconds */
349 static u_long t4_toe_keepalive_idle = 0;
350 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
351     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
352 
353 /* 0 means chip/fw default, non-zero number is value in microseconds */
354 static u_long t4_toe_keepalive_interval = 0;
355 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
356     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
357 
358 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
359 static int t4_toe_keepalive_count = 0;
360 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
361     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
362 
363 /* 0 means chip/fw default, non-zero number is value in microseconds */
364 static u_long t4_toe_rexmt_min = 0;
365 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
366     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
367 
368 /* 0 means chip/fw default, non-zero number is value in microseconds */
369 static u_long t4_toe_rexmt_max = 0;
370 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
371     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
372 
373 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
374 static int t4_toe_rexmt_count = 0;
375 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
376     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
377 
378 /* -1 means chip/fw default, other values are raw backoff values to use */
379 static int t4_toe_rexmt_backoff[16] = {
380 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
381 };
382 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
383     CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
384     "cxgbe(4) TOE retransmit backoff values");
385 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
386     &t4_toe_rexmt_backoff[0], 0, "");
387 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
388     &t4_toe_rexmt_backoff[1], 0, "");
389 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
390     &t4_toe_rexmt_backoff[2], 0, "");
391 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
392     &t4_toe_rexmt_backoff[3], 0, "");
393 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
394     &t4_toe_rexmt_backoff[4], 0, "");
395 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
396     &t4_toe_rexmt_backoff[5], 0, "");
397 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
398     &t4_toe_rexmt_backoff[6], 0, "");
399 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
400     &t4_toe_rexmt_backoff[7], 0, "");
401 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
402     &t4_toe_rexmt_backoff[8], 0, "");
403 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
404     &t4_toe_rexmt_backoff[9], 0, "");
405 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
406     &t4_toe_rexmt_backoff[10], 0, "");
407 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
408     &t4_toe_rexmt_backoff[11], 0, "");
409 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
410     &t4_toe_rexmt_backoff[12], 0, "");
411 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
412     &t4_toe_rexmt_backoff[13], 0, "");
413 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
414     &t4_toe_rexmt_backoff[14], 0, "");
415 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
416     &t4_toe_rexmt_backoff[15], 0, "");
417 
418 static int t4_toe_tls_rx_timeout = 5;
419 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, tls_rx_timeout, CTLFLAG_RDTUN,
420     &t4_toe_tls_rx_timeout, 0,
421     "Timeout in seconds to downgrade TLS sockets to plain TOE");
422 #endif
423 
424 #ifdef DEV_NETMAP
425 #define NN_MAIN_VI	(1 << 0)	/* Native netmap on the main VI */
426 #define NN_EXTRA_VI	(1 << 1)	/* Native netmap on the extra VI(s) */
427 static int t4_native_netmap = NN_EXTRA_VI;
428 SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
429     0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
430 
431 #define NNMTXQ 8
432 static int t4_nnmtxq = -NNMTXQ;
433 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
434     "Number of netmap TX queues");
435 
436 #define NNMRXQ 8
437 static int t4_nnmrxq = -NNMRXQ;
438 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
439     "Number of netmap RX queues");
440 
441 #define NNMTXQ_VI 2
442 static int t4_nnmtxq_vi = -NNMTXQ_VI;
443 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
444     "Number of netmap TX queues per VI");
445 
446 #define NNMRXQ_VI 2
447 static int t4_nnmrxq_vi = -NNMRXQ_VI;
448 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
449     "Number of netmap RX queues per VI");
450 #endif
451 
452 /*
453  * Holdoff parameters for ports.
454  */
455 #define TMR_IDX 1
456 int t4_tmr_idx = TMR_IDX;
457 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
458     0, "Holdoff timer index");
459 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);	/* Old name */
460 
461 #define PKTC_IDX (-1)
462 int t4_pktc_idx = PKTC_IDX;
463 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
464     0, "Holdoff packet counter index");
465 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);	/* Old name */
466 
467 /*
468  * Size (# of entries) of each tx and rx queue.
469  */
470 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
471 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
472     "Number of descriptors in each TX queue");
473 
474 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
475 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
476     "Number of descriptors in each RX queue");
477 
478 /*
479  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
480  */
481 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
482 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
483     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
484 
485 /*
486  * Configuration file.  All the _CF names here are special.
487  */
488 #define DEFAULT_CF	"default"
489 #define BUILTIN_CF	"built-in"
490 #define FLASH_CF	"flash"
491 #define UWIRE_CF	"uwire"
492 #define FPGA_CF		"fpga"
493 static char t4_cfg_file[32] = DEFAULT_CF;
494 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
495     sizeof(t4_cfg_file), "Firmware configuration file");
496 
497 /*
498  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
499  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
500  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
501  *            mark or when signalled to do so, 0 to never emit PAUSE.
502  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
503  *                 negotiated settings will override rx_pause/tx_pause.
504  *                 Otherwise rx_pause/tx_pause are applied forcibly.
505  */
506 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
507 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
508     &t4_pause_settings, 0,
509     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
510 
511 /*
512  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
513  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
514  *  0 to disable FEC.
515  */
516 static int t4_fec = -1;
517 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
518     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
519 
520 /*
521  * Controls when the driver sets the FORCE_FEC bit in the L1_CFG32 that it
522  * issues to the firmware.  If the firmware doesn't support FORCE_FEC then the
523  * driver runs as if this is set to 0.
524  * -1 to set FORCE_FEC iff requested_fec != AUTO. Multiple FEC bits are okay.
525  *  0 to never set FORCE_FEC. requested_fec = AUTO means use the hint from the
526  *    transceiver. Multiple FEC bits may not be okay but will be passed on to
527  *    the firmware anyway (may result in l1cfg errors with old firmwares).
528  *  1 to always set FORCE_FEC. Multiple FEC bits are okay. requested_fec = AUTO
529  *    means set all FEC bits that are valid for the speed.
530  */
531 static int t4_force_fec = -1;
532 SYSCTL_INT(_hw_cxgbe, OID_AUTO, force_fec, CTLFLAG_RDTUN, &t4_force_fec, 0,
533     "Controls the use of FORCE_FEC bit in L1 configuration.");
534 
535 /*
536  * Link autonegotiation.
537  * -1 to run with the firmware default.
538  *  0 to disable.
539  *  1 to enable.
540  */
541 static int t4_autoneg = -1;
542 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
543     "Link autonegotiation");
544 
545 /*
546  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
547  * encouraged respectively).  '-n' is the same as 'n' except the firmware
548  * version used in the checks is read from the firmware bundled with the driver.
549  */
550 static int t4_fw_install = 1;
551 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
552     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
553 
554 /*
555  * ASIC features that will be used.  Disable the ones you don't want so that the
556  * chip resources aren't wasted on features that will not be used.
557  */
558 static int t4_nbmcaps_allowed = 0;
559 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
560     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
561 
562 static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
563 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
564     &t4_linkcaps_allowed, 0, "Default link capabilities");
565 
566 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
567     FW_CAPS_CONFIG_SWITCH_EGRESS;
568 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
569     &t4_switchcaps_allowed, 0, "Default switch capabilities");
570 
571 #ifdef RATELIMIT
572 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
573 	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
574 #else
575 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
576 	FW_CAPS_CONFIG_NIC_HASHFILTER;
577 #endif
578 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
579     &t4_niccaps_allowed, 0, "Default NIC capabilities");
580 
581 static int t4_toecaps_allowed = -1;
582 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
583     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
584 
585 static int t4_rdmacaps_allowed = -1;
586 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
587     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
588 
589 static int t4_cryptocaps_allowed = -1;
590 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
591     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
592 
593 static int t4_iscsicaps_allowed = -1;
594 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
595     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
596 
597 static int t4_fcoecaps_allowed = 0;
598 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
599     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
600 
601 static int t5_write_combine = 0;
602 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
603     0, "Use WC instead of UC for BAR2");
604 
605 static int t4_num_vis = 1;
606 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
607     "Number of VIs per port");
608 
609 /*
610  * PCIe Relaxed Ordering.
611  * -1: driver should figure out a good value.
612  * 0: disable RO.
613  * 1: enable RO.
614  * 2: leave RO alone.
615  */
616 static int pcie_relaxed_ordering = -1;
617 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
618     &pcie_relaxed_ordering, 0,
619     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
620 
621 static int t4_panic_on_fatal_err = 0;
622 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
623     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
624 
625 static int t4_reset_on_fatal_err = 0;
626 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
627     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
628 
629 static int t4_tx_vm_wr = 0;
630 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
631     "Use VM work requests to transmit packets.");
632 
633 /*
634  * Set to non-zero to enable the attack filter.  A packet that matches any of
635  * these conditions will get dropped on ingress:
636  * 1) IP && source address == destination address.
637  * 2) TCP/IP && source address is not a unicast address.
638  * 3) TCP/IP && destination address is not a unicast address.
639  * 4) IP && source address is loopback (127.x.y.z).
640  * 5) IP && destination address is loopback (127.x.y.z).
641  * 6) IPv6 && source address == destination address.
642  * 7) IPv6 && source address is not a unicast address.
643  * 8) IPv6 && source address is loopback (::1/128).
644  * 9) IPv6 && destination address is loopback (::1/128).
645  * 10) IPv6 && source address is unspecified (::/128).
646  * 11) IPv6 && destination address is unspecified (::/128).
647  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
648  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
649  */
650 static int t4_attack_filter = 0;
651 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
652     &t4_attack_filter, 0, "Drop suspicious traffic");
653 
654 static int t4_drop_ip_fragments = 0;
655 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
656     &t4_drop_ip_fragments, 0, "Drop IP fragments");
657 
658 static int t4_drop_pkts_with_l2_errors = 1;
659 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
660     &t4_drop_pkts_with_l2_errors, 0,
661     "Drop all frames with Layer 2 length or checksum errors");
662 
663 static int t4_drop_pkts_with_l3_errors = 0;
664 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
665     &t4_drop_pkts_with_l3_errors, 0,
666     "Drop all frames with IP version, length, or checksum errors");
667 
668 static int t4_drop_pkts_with_l4_errors = 0;
669 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
670     &t4_drop_pkts_with_l4_errors, 0,
671     "Drop all frames with Layer 4 length, checksum, or other errors");
672 
673 #ifdef TCP_OFFLOAD
674 /*
675  * TOE tunables.
676  */
677 static int t4_cop_managed_offloading = 0;
678 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
679     &t4_cop_managed_offloading, 0,
680     "COP (Connection Offload Policy) controls all TOE offload");
681 #endif
682 
683 #ifdef KERN_TLS
684 /*
685  * This enables KERN_TLS for all adapters if set.
686  */
687 static int t4_kern_tls = 0;
688 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
689     "Enable KERN_TLS mode for all supported adapters");
690 
691 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
692     "cxgbe(4) KERN_TLS parameters");
693 
694 static int t4_tls_inline_keys = 0;
695 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
696     &t4_tls_inline_keys, 0,
697     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
698     "in card memory.");
699 
700 static int t4_tls_combo_wrs = 0;
701 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
702     0, "Attempt to combine TCB field updates with TLS record work requests.");
703 #endif
704 
705 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
706 static int vi_mac_funcs[] = {
707 	FW_VI_FUNC_ETH,
708 	FW_VI_FUNC_OFLD,
709 	FW_VI_FUNC_IWARP,
710 	FW_VI_FUNC_OPENISCSI,
711 	FW_VI_FUNC_OPENFCOE,
712 	FW_VI_FUNC_FOISCSI,
713 	FW_VI_FUNC_FOFCOE,
714 };
715 
716 struct intrs_and_queues {
717 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
718 	uint16_t num_vis;	/* number of VIs for each port */
719 	uint16_t nirq;		/* Total # of vectors */
720 	uint16_t ntxq;		/* # of NIC txq's for each port */
721 	uint16_t nrxq;		/* # of NIC rxq's for each port */
722 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
723 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
724 	uint16_t nnmtxq;	/* # of netmap txq's */
725 	uint16_t nnmrxq;	/* # of netmap rxq's */
726 
727 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
728 	uint16_t ntxq_vi;	/* # of NIC txq's */
729 	uint16_t nrxq_vi;	/* # of NIC rxq's */
730 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
731 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
732 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
733 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
734 };
735 
736 static void setup_memwin(struct adapter *);
737 static void position_memwin(struct adapter *, int, uint32_t);
738 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
739 static int fwmtype_to_hwmtype(int);
740 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
741     uint32_t *);
742 static int fixup_devlog_params(struct adapter *);
743 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
744 static int contact_firmware(struct adapter *);
745 static int partition_resources(struct adapter *);
746 static int get_params__pre_init(struct adapter *);
747 static int set_params__pre_init(struct adapter *);
748 static int get_params__post_init(struct adapter *);
749 static int set_params__post_init(struct adapter *);
750 static void t4_set_desc(struct adapter *);
751 static bool fixed_ifmedia(struct port_info *);
752 static void build_medialist(struct port_info *);
753 static void init_link_config(struct port_info *);
754 static int fixup_link_config(struct port_info *);
755 static int apply_link_config(struct port_info *);
756 static int cxgbe_init_synchronized(struct vi_info *);
757 static int cxgbe_uninit_synchronized(struct vi_info *);
758 static int adapter_full_init(struct adapter *);
759 static void adapter_full_uninit(struct adapter *);
760 static int vi_full_init(struct vi_info *);
761 static void vi_full_uninit(struct vi_info *);
762 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
763 static void quiesce_txq(struct sge_txq *);
764 static void quiesce_wrq(struct sge_wrq *);
765 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
766 static void quiesce_vi(struct vi_info *);
767 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
768     driver_intr_t *, void *, char *);
769 static int t4_free_irq(struct adapter *, struct irq *);
770 static void t4_init_atid_table(struct adapter *);
771 static void t4_free_atid_table(struct adapter *);
772 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
773 static void vi_refresh_stats(struct vi_info *);
774 static void cxgbe_refresh_stats(struct vi_info *);
775 static void cxgbe_tick(void *);
776 static void vi_tick(void *);
777 static void cxgbe_sysctls(struct port_info *);
778 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
779 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
780 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
781 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
782 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
783 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
784 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
785 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
786 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
787 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
788 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
789 static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
790 static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
791 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
792 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
793 static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
794 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
795 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
796 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
797 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
798 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
799 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
800 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
801 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
802 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
803 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
804 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
805 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
806 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
807 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
808 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
809 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
810 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
811 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
812 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
813 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
814 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
815 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
816 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
817 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
818 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
819 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
820 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
821 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
822 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
823 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
824 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
825 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
826 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
827 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
828 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
829 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
830 #ifdef TCP_OFFLOAD
831 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
832 static int sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS);
833 static int sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS);
834 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
835 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
836 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
837 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
838 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
839 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
840 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
841 #endif
842 static int get_sge_context(struct adapter *, struct t4_sge_context *);
843 static int load_fw(struct adapter *, struct t4_data *);
844 static int load_cfg(struct adapter *, struct t4_data *);
845 static int load_boot(struct adapter *, struct t4_bootrom *);
846 static int load_bootcfg(struct adapter *, struct t4_data *);
847 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
848 static void free_offload_policy(struct t4_offload_policy *);
849 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
850 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
851 static int read_i2c(struct adapter *, struct t4_i2c_data *);
852 static int clear_stats(struct adapter *, u_int);
853 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
854 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
855 #ifdef TCP_OFFLOAD
856 static int toe_capability(struct vi_info *, bool);
857 static void t4_async_event(void *, int);
858 #endif
859 #ifdef KERN_TLS
860 static int ktls_capability(struct adapter *, bool);
861 #endif
862 static int mod_event(module_t, int, void *);
863 static int notify_siblings(device_t, int);
864 static uint64_t vi_get_counter(struct ifnet *, ift_counter);
865 static uint64_t cxgbe_get_counter(struct ifnet *, ift_counter);
866 static void enable_vxlan_rx(struct adapter *);
867 static void reset_adapter(void *, int);
868 
869 struct {
870 	uint16_t device;
871 	char *desc;
872 } t4_pciids[] = {
873 	{0xa000, "Chelsio Terminator 4 FPGA"},
874 	{0x4400, "Chelsio T440-dbg"},
875 	{0x4401, "Chelsio T420-CR"},
876 	{0x4402, "Chelsio T422-CR"},
877 	{0x4403, "Chelsio T440-CR"},
878 	{0x4404, "Chelsio T420-BCH"},
879 	{0x4405, "Chelsio T440-BCH"},
880 	{0x4406, "Chelsio T440-CH"},
881 	{0x4407, "Chelsio T420-SO"},
882 	{0x4408, "Chelsio T420-CX"},
883 	{0x4409, "Chelsio T420-BT"},
884 	{0x440a, "Chelsio T404-BT"},
885 	{0x440e, "Chelsio T440-LP-CR"},
886 }, t5_pciids[] = {
887 	{0xb000, "Chelsio Terminator 5 FPGA"},
888 	{0x5400, "Chelsio T580-dbg"},
889 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
890 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
891 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
892 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
893 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
894 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
895 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
896 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
897 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
898 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
899 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
900 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
901 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
902 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
903 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
904 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
905 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
906 
907 	/* Custom */
908 	{0x5483, "Custom T540-CR"},
909 	{0x5484, "Custom T540-BT"},
910 }, t6_pciids[] = {
911 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
912 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
913 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
914 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
915 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
916 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
917 	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
918 	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
919 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
920 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
921 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
922 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
923 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
924 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
925 	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
926 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
927 
928 	/* Custom */
929 	{0x6480, "Custom T6225-CR"},
930 	{0x6481, "Custom T62100-CR"},
931 	{0x6482, "Custom T6225-CR"},
932 	{0x6483, "Custom T62100-CR"},
933 	{0x6484, "Custom T64100-CR"},
934 	{0x6485, "Custom T6240-SO"},
935 	{0x6486, "Custom T6225-SO-CR"},
936 	{0x6487, "Custom T6225-CR"},
937 };
938 
939 #ifdef TCP_OFFLOAD
940 /*
941  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
942  * be exactly the same for both rxq and ofld_rxq.
943  */
944 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
945 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
946 #endif
947 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
948 
949 static int
950 t4_probe(device_t dev)
951 {
952 	int i;
953 	uint16_t v = pci_get_vendor(dev);
954 	uint16_t d = pci_get_device(dev);
955 	uint8_t f = pci_get_function(dev);
956 
957 	if (v != PCI_VENDOR_ID_CHELSIO)
958 		return (ENXIO);
959 
960 	/* Attach only to PF0 of the FPGA */
961 	if (d == 0xa000 && f != 0)
962 		return (ENXIO);
963 
964 	for (i = 0; i < nitems(t4_pciids); i++) {
965 		if (d == t4_pciids[i].device) {
966 			device_set_desc(dev, t4_pciids[i].desc);
967 			return (BUS_PROBE_DEFAULT);
968 		}
969 	}
970 
971 	return (ENXIO);
972 }
973 
974 static int
975 t5_probe(device_t dev)
976 {
977 	int i;
978 	uint16_t v = pci_get_vendor(dev);
979 	uint16_t d = pci_get_device(dev);
980 	uint8_t f = pci_get_function(dev);
981 
982 	if (v != PCI_VENDOR_ID_CHELSIO)
983 		return (ENXIO);
984 
985 	/* Attach only to PF0 of the FPGA */
986 	if (d == 0xb000 && f != 0)
987 		return (ENXIO);
988 
989 	for (i = 0; i < nitems(t5_pciids); i++) {
990 		if (d == t5_pciids[i].device) {
991 			device_set_desc(dev, t5_pciids[i].desc);
992 			return (BUS_PROBE_DEFAULT);
993 		}
994 	}
995 
996 	return (ENXIO);
997 }
998 
999 static int
1000 t6_probe(device_t dev)
1001 {
1002 	int i;
1003 	uint16_t v = pci_get_vendor(dev);
1004 	uint16_t d = pci_get_device(dev);
1005 
1006 	if (v != PCI_VENDOR_ID_CHELSIO)
1007 		return (ENXIO);
1008 
1009 	for (i = 0; i < nitems(t6_pciids); i++) {
1010 		if (d == t6_pciids[i].device) {
1011 			device_set_desc(dev, t6_pciids[i].desc);
1012 			return (BUS_PROBE_DEFAULT);
1013 		}
1014 	}
1015 
1016 	return (ENXIO);
1017 }
1018 
1019 static void
1020 t5_attribute_workaround(device_t dev)
1021 {
1022 	device_t root_port;
1023 	uint32_t v;
1024 
1025 	/*
1026 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1027 	 * Ordering attributes when replying to a TLP from a Root
1028 	 * Port.  As a workaround, find the parent Root Port and
1029 	 * disable No Snoop and Relaxed Ordering.  Note that this
1030 	 * affects all devices under this root port.
1031 	 */
1032 	root_port = pci_find_pcie_root_port(dev);
1033 	if (root_port == NULL) {
1034 		device_printf(dev, "Unable to find parent root port\n");
1035 		return;
1036 	}
1037 
1038 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1039 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1040 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1041 	    0)
1042 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1043 		    device_get_nameunit(root_port));
1044 }
1045 
1046 static const struct devnames devnames[] = {
1047 	{
1048 		.nexus_name = "t4nex",
1049 		.ifnet_name = "cxgbe",
1050 		.vi_ifnet_name = "vcxgbe",
1051 		.pf03_drv_name = "t4iov",
1052 		.vf_nexus_name = "t4vf",
1053 		.vf_ifnet_name = "cxgbev"
1054 	}, {
1055 		.nexus_name = "t5nex",
1056 		.ifnet_name = "cxl",
1057 		.vi_ifnet_name = "vcxl",
1058 		.pf03_drv_name = "t5iov",
1059 		.vf_nexus_name = "t5vf",
1060 		.vf_ifnet_name = "cxlv"
1061 	}, {
1062 		.nexus_name = "t6nex",
1063 		.ifnet_name = "cc",
1064 		.vi_ifnet_name = "vcc",
1065 		.pf03_drv_name = "t6iov",
1066 		.vf_nexus_name = "t6vf",
1067 		.vf_ifnet_name = "ccv"
1068 	}
1069 };
1070 
1071 void
1072 t4_init_devnames(struct adapter *sc)
1073 {
1074 	int id;
1075 
1076 	id = chip_id(sc);
1077 	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1078 		sc->names = &devnames[id - CHELSIO_T4];
1079 	else {
1080 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1081 		sc->names = NULL;
1082 	}
1083 }
1084 
1085 static int
1086 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1087 {
1088 	const char *parent, *name;
1089 	long value;
1090 	int line, unit;
1091 
1092 	line = 0;
1093 	parent = device_get_nameunit(sc->dev);
1094 	name = sc->names->ifnet_name;
1095 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1096 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1097 		    value == pi->port_id)
1098 			return (unit);
1099 	}
1100 	return (-1);
1101 }
1102 
1103 static int
1104 t4_attach(device_t dev)
1105 {
1106 	struct adapter *sc;
1107 	int rc = 0, i, j, rqidx, tqidx, nports;
1108 	struct make_dev_args mda;
1109 	struct intrs_and_queues iaq;
1110 	struct sge *s;
1111 	uint32_t *buf;
1112 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1113 	int ofld_tqidx;
1114 #endif
1115 #ifdef TCP_OFFLOAD
1116 	int ofld_rqidx;
1117 #endif
1118 #ifdef DEV_NETMAP
1119 	int nm_rqidx, nm_tqidx;
1120 #endif
1121 	int num_vis;
1122 
1123 	sc = device_get_softc(dev);
1124 	sc->dev = dev;
1125 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1126 
1127 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1128 		t5_attribute_workaround(dev);
1129 	pci_enable_busmaster(dev);
1130 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1131 		uint32_t v;
1132 
1133 		pci_set_max_read_req(dev, 4096);
1134 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1135 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1136 		if (pcie_relaxed_ordering == 0 &&
1137 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1138 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1139 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1140 		} else if (pcie_relaxed_ordering == 1 &&
1141 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1142 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1143 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1144 		}
1145 	}
1146 
1147 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1148 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1149 	sc->traceq = -1;
1150 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1151 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1152 	    device_get_nameunit(dev));
1153 
1154 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1155 	    device_get_nameunit(dev));
1156 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1157 	t4_add_adapter(sc);
1158 
1159 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1160 	TAILQ_INIT(&sc->sfl);
1161 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1162 
1163 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1164 
1165 	sc->policy = NULL;
1166 	rw_init(&sc->policy_lock, "connection offload policy");
1167 
1168 	callout_init(&sc->ktls_tick, 1);
1169 
1170 #ifdef TCP_OFFLOAD
1171 	TASK_INIT(&sc->async_event_task, 0, t4_async_event, sc);
1172 #endif
1173 
1174 	refcount_init(&sc->vxlan_refcount, 0);
1175 
1176 	TASK_INIT(&sc->reset_task, 0, reset_adapter, sc);
1177 
1178 	sc->ctrlq_oid = SYSCTL_ADD_NODE(device_get_sysctl_ctx(sc->dev),
1179 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1180 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1181 	sc->fwq_oid = SYSCTL_ADD_NODE(device_get_sysctl_ctx(sc->dev),
1182 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1183 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1184 
1185 	rc = t4_map_bars_0_and_4(sc);
1186 	if (rc != 0)
1187 		goto done; /* error message displayed already */
1188 
1189 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1190 
1191 	/* Prepare the adapter for operation. */
1192 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1193 	rc = -t4_prep_adapter(sc, buf);
1194 	free(buf, M_CXGBE);
1195 	if (rc != 0) {
1196 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1197 		goto done;
1198 	}
1199 
1200 	/*
1201 	 * This is the real PF# to which we're attaching.  Works from within PCI
1202 	 * passthrough environments too, where pci_get_function() could return a
1203 	 * different PF# depending on the passthrough configuration.  We need to
1204 	 * use the real PF# in all our communication with the firmware.
1205 	 */
1206 	j = t4_read_reg(sc, A_PL_WHOAMI);
1207 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1208 	sc->mbox = sc->pf;
1209 
1210 	t4_init_devnames(sc);
1211 	if (sc->names == NULL) {
1212 		rc = ENOTSUP;
1213 		goto done; /* error message displayed already */
1214 	}
1215 
1216 	/*
1217 	 * Do this really early, with the memory windows set up even before the
1218 	 * character device.  The userland tool's register i/o and mem read
1219 	 * will work even in "recovery mode".
1220 	 */
1221 	setup_memwin(sc);
1222 	if (t4_init_devlog_params(sc, 0) == 0)
1223 		fixup_devlog_params(sc);
1224 	make_dev_args_init(&mda);
1225 	mda.mda_devsw = &t4_cdevsw;
1226 	mda.mda_uid = UID_ROOT;
1227 	mda.mda_gid = GID_WHEEL;
1228 	mda.mda_mode = 0600;
1229 	mda.mda_si_drv1 = sc;
1230 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1231 	if (rc != 0)
1232 		device_printf(dev, "failed to create nexus char device: %d.\n",
1233 		    rc);
1234 
1235 	/* Go no further if recovery mode has been requested. */
1236 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1237 		device_printf(dev, "recovery mode.\n");
1238 		goto done;
1239 	}
1240 
1241 #if defined(__i386__)
1242 	if ((cpu_feature & CPUID_CX8) == 0) {
1243 		device_printf(dev, "64 bit atomics not available.\n");
1244 		rc = ENOTSUP;
1245 		goto done;
1246 	}
1247 #endif
1248 
1249 	/* Contact the firmware and try to become the master driver. */
1250 	rc = contact_firmware(sc);
1251 	if (rc != 0)
1252 		goto done; /* error message displayed already */
1253 	MPASS(sc->flags & FW_OK);
1254 
1255 	rc = get_params__pre_init(sc);
1256 	if (rc != 0)
1257 		goto done; /* error message displayed already */
1258 
1259 	if (sc->flags & MASTER_PF) {
1260 		rc = partition_resources(sc);
1261 		if (rc != 0)
1262 			goto done; /* error message displayed already */
1263 		t4_intr_clear(sc);
1264 	}
1265 
1266 	rc = get_params__post_init(sc);
1267 	if (rc != 0)
1268 		goto done; /* error message displayed already */
1269 
1270 	rc = set_params__post_init(sc);
1271 	if (rc != 0)
1272 		goto done; /* error message displayed already */
1273 
1274 	rc = t4_map_bar_2(sc);
1275 	if (rc != 0)
1276 		goto done; /* error message displayed already */
1277 
1278 	rc = t4_create_dma_tag(sc);
1279 	if (rc != 0)
1280 		goto done; /* error message displayed already */
1281 
1282 	/*
1283 	 * First pass over all the ports - allocate VIs and initialize some
1284 	 * basic parameters like mac address, port type, etc.
1285 	 */
1286 	for_each_port(sc, i) {
1287 		struct port_info *pi;
1288 
1289 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1290 		sc->port[i] = pi;
1291 
1292 		/* These must be set before t4_port_init */
1293 		pi->adapter = sc;
1294 		pi->port_id = i;
1295 		/*
1296 		 * XXX: vi[0] is special so we can't delay this allocation until
1297 		 * pi->nvi's final value is known.
1298 		 */
1299 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1300 		    M_ZERO | M_WAITOK);
1301 
1302 		/*
1303 		 * Allocate the "main" VI and initialize parameters
1304 		 * like mac addr.
1305 		 */
1306 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1307 		if (rc != 0) {
1308 			device_printf(dev, "unable to initialize port %d: %d\n",
1309 			    i, rc);
1310 			free(pi->vi, M_CXGBE);
1311 			free(pi, M_CXGBE);
1312 			sc->port[i] = NULL;
1313 			goto done;
1314 		}
1315 
1316 		if (is_bt(pi->port_type))
1317 			setbit(&sc->bt_map, pi->tx_chan);
1318 		else
1319 			MPASS(!isset(&sc->bt_map, pi->tx_chan));
1320 
1321 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1322 		    device_get_nameunit(dev), i);
1323 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1324 		sc->chan_map[pi->tx_chan] = i;
1325 
1326 		/*
1327 		 * The MPS counter for FCS errors doesn't work correctly on the
1328 		 * T6 so we use the MAC counter here.  Which MAC is in use
1329 		 * depends on the link settings which will be known when the
1330 		 * link comes up.
1331 		 */
1332 		if (is_t6(sc)) {
1333 			pi->fcs_reg = -1;
1334 		} else if (is_t4(sc)) {
1335 			pi->fcs_reg = PORT_REG(pi->tx_chan,
1336 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1337 		} else {
1338 			pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
1339 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1340 		}
1341 		pi->fcs_base = 0;
1342 
1343 		/* All VIs on this port share this media. */
1344 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1345 		    cxgbe_media_status);
1346 
1347 		PORT_LOCK(pi);
1348 		init_link_config(pi);
1349 		fixup_link_config(pi);
1350 		build_medialist(pi);
1351 		if (fixed_ifmedia(pi))
1352 			pi->flags |= FIXED_IFMEDIA;
1353 		PORT_UNLOCK(pi);
1354 
1355 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1356 		    t4_ifnet_unit(sc, pi));
1357 		if (pi->dev == NULL) {
1358 			device_printf(dev,
1359 			    "failed to add device for port %d.\n", i);
1360 			rc = ENXIO;
1361 			goto done;
1362 		}
1363 		pi->vi[0].dev = pi->dev;
1364 		device_set_softc(pi->dev, pi);
1365 	}
1366 
1367 	/*
1368 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1369 	 */
1370 	nports = sc->params.nports;
1371 	rc = cfg_itype_and_nqueues(sc, &iaq);
1372 	if (rc != 0)
1373 		goto done; /* error message displayed already */
1374 
1375 	num_vis = iaq.num_vis;
1376 	sc->intr_type = iaq.intr_type;
1377 	sc->intr_count = iaq.nirq;
1378 
1379 	s = &sc->sge;
1380 	s->nrxq = nports * iaq.nrxq;
1381 	s->ntxq = nports * iaq.ntxq;
1382 	if (num_vis > 1) {
1383 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1384 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1385 	}
1386 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1387 	s->neq += nports;		/* ctrl queues: 1 per port */
1388 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1389 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1390 	if (is_offload(sc) || is_ethoffload(sc)) {
1391 		s->nofldtxq = nports * iaq.nofldtxq;
1392 		if (num_vis > 1)
1393 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1394 		s->neq += s->nofldtxq;
1395 
1396 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1397 		    M_CXGBE, M_ZERO | M_WAITOK);
1398 	}
1399 #endif
1400 #ifdef TCP_OFFLOAD
1401 	if (is_offload(sc)) {
1402 		s->nofldrxq = nports * iaq.nofldrxq;
1403 		if (num_vis > 1)
1404 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1405 		s->neq += s->nofldrxq;	/* free list */
1406 		s->niq += s->nofldrxq;
1407 
1408 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1409 		    M_CXGBE, M_ZERO | M_WAITOK);
1410 	}
1411 #endif
1412 #ifdef DEV_NETMAP
1413 	s->nnmrxq = 0;
1414 	s->nnmtxq = 0;
1415 	if (t4_native_netmap & NN_MAIN_VI) {
1416 		s->nnmrxq += nports * iaq.nnmrxq;
1417 		s->nnmtxq += nports * iaq.nnmtxq;
1418 	}
1419 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1420 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1421 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1422 	}
1423 	s->neq += s->nnmtxq + s->nnmrxq;
1424 	s->niq += s->nnmrxq;
1425 
1426 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1427 	    M_CXGBE, M_ZERO | M_WAITOK);
1428 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1429 	    M_CXGBE, M_ZERO | M_WAITOK);
1430 #endif
1431 	MPASS(s->niq <= s->iqmap_sz);
1432 	MPASS(s->neq <= s->eqmap_sz);
1433 
1434 	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1435 	    M_ZERO | M_WAITOK);
1436 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1437 	    M_ZERO | M_WAITOK);
1438 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1439 	    M_ZERO | M_WAITOK);
1440 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1441 	    M_ZERO | M_WAITOK);
1442 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1443 	    M_ZERO | M_WAITOK);
1444 
1445 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1446 	    M_ZERO | M_WAITOK);
1447 
1448 	t4_init_l2t(sc, M_WAITOK);
1449 	t4_init_smt(sc, M_WAITOK);
1450 	t4_init_tx_sched(sc);
1451 	t4_init_atid_table(sc);
1452 #ifdef RATELIMIT
1453 	t4_init_etid_table(sc);
1454 #endif
1455 #ifdef INET6
1456 	t4_init_clip_table(sc);
1457 #endif
1458 	if (sc->vres.key.size != 0)
1459 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1460 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1461 
1462 	/*
1463 	 * Second pass over the ports.  This time we know the number of rx and
1464 	 * tx queues that each port should get.
1465 	 */
1466 	rqidx = tqidx = 0;
1467 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1468 	ofld_tqidx = 0;
1469 #endif
1470 #ifdef TCP_OFFLOAD
1471 	ofld_rqidx = 0;
1472 #endif
1473 #ifdef DEV_NETMAP
1474 	nm_rqidx = nm_tqidx = 0;
1475 #endif
1476 	for_each_port(sc, i) {
1477 		struct port_info *pi = sc->port[i];
1478 		struct vi_info *vi;
1479 
1480 		if (pi == NULL)
1481 			continue;
1482 
1483 		pi->nvi = num_vis;
1484 		for_each_vi(pi, j, vi) {
1485 			vi->pi = pi;
1486 			vi->adapter = sc;
1487 			vi->first_intr = -1;
1488 			vi->qsize_rxq = t4_qsize_rxq;
1489 			vi->qsize_txq = t4_qsize_txq;
1490 
1491 			vi->first_rxq = rqidx;
1492 			vi->first_txq = tqidx;
1493 			vi->tmr_idx = t4_tmr_idx;
1494 			vi->pktc_idx = t4_pktc_idx;
1495 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1496 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1497 
1498 			rqidx += vi->nrxq;
1499 			tqidx += vi->ntxq;
1500 
1501 			if (j == 0 && vi->ntxq > 1)
1502 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1503 			else
1504 				vi->rsrv_noflowq = 0;
1505 
1506 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1507 			vi->first_ofld_txq = ofld_tqidx;
1508 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1509 			ofld_tqidx += vi->nofldtxq;
1510 #endif
1511 #ifdef TCP_OFFLOAD
1512 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1513 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1514 			vi->first_ofld_rxq = ofld_rqidx;
1515 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1516 
1517 			ofld_rqidx += vi->nofldrxq;
1518 #endif
1519 #ifdef DEV_NETMAP
1520 			vi->first_nm_rxq = nm_rqidx;
1521 			vi->first_nm_txq = nm_tqidx;
1522 			if (j == 0) {
1523 				vi->nnmrxq = iaq.nnmrxq;
1524 				vi->nnmtxq = iaq.nnmtxq;
1525 			} else {
1526 				vi->nnmrxq = iaq.nnmrxq_vi;
1527 				vi->nnmtxq = iaq.nnmtxq_vi;
1528 			}
1529 			nm_rqidx += vi->nnmrxq;
1530 			nm_tqidx += vi->nnmtxq;
1531 #endif
1532 		}
1533 	}
1534 
1535 	rc = t4_setup_intr_handlers(sc);
1536 	if (rc != 0) {
1537 		device_printf(dev,
1538 		    "failed to setup interrupt handlers: %d\n", rc);
1539 		goto done;
1540 	}
1541 
1542 	rc = bus_generic_probe(dev);
1543 	if (rc != 0) {
1544 		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1545 		goto done;
1546 	}
1547 
1548 	/*
1549 	 * Ensure thread-safe mailbox access (in debug builds).
1550 	 *
1551 	 * So far this was the only thread accessing the mailbox but various
1552 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1553 	 * will access the mailbox from different threads.
1554 	 */
1555 	sc->flags |= CHK_MBOX_ACCESS;
1556 
1557 	rc = bus_generic_attach(dev);
1558 	if (rc != 0) {
1559 		device_printf(dev,
1560 		    "failed to attach all child ports: %d\n", rc);
1561 		goto done;
1562 	}
1563 
1564 	device_printf(dev,
1565 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1566 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1567 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1568 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1569 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1570 
1571 	t4_set_desc(sc);
1572 
1573 	notify_siblings(dev, 0);
1574 
1575 done:
1576 	if (rc != 0 && sc->cdev) {
1577 		/* cdev was created and so cxgbetool works; recover that way. */
1578 		device_printf(dev,
1579 		    "error during attach, adapter is now in recovery mode.\n");
1580 		rc = 0;
1581 	}
1582 
1583 	if (rc != 0)
1584 		t4_detach_common(dev);
1585 	else
1586 		t4_sysctls(sc);
1587 
1588 	return (rc);
1589 }
1590 
1591 static int
1592 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1593 {
1594 	struct adapter *sc;
1595 	struct port_info *pi;
1596 	int i;
1597 
1598 	sc = device_get_softc(bus);
1599 	for_each_port(sc, i) {
1600 		pi = sc->port[i];
1601 		if (pi != NULL && pi->dev == dev) {
1602 			sbuf_printf(sb, "port=%d", pi->port_id);
1603 			break;
1604 		}
1605 	}
1606 	return (0);
1607 }
1608 
1609 static int
1610 t4_ready(device_t dev)
1611 {
1612 	struct adapter *sc;
1613 
1614 	sc = device_get_softc(dev);
1615 	if (sc->flags & FW_OK)
1616 		return (0);
1617 	return (ENXIO);
1618 }
1619 
1620 static int
1621 t4_read_port_device(device_t dev, int port, device_t *child)
1622 {
1623 	struct adapter *sc;
1624 	struct port_info *pi;
1625 
1626 	sc = device_get_softc(dev);
1627 	if (port < 0 || port >= MAX_NPORTS)
1628 		return (EINVAL);
1629 	pi = sc->port[port];
1630 	if (pi == NULL || pi->dev == NULL)
1631 		return (ENXIO);
1632 	*child = pi->dev;
1633 	return (0);
1634 }
1635 
1636 static int
1637 notify_siblings(device_t dev, int detaching)
1638 {
1639 	device_t sibling;
1640 	int error, i;
1641 
1642 	error = 0;
1643 	for (i = 0; i < PCI_FUNCMAX; i++) {
1644 		if (i == pci_get_function(dev))
1645 			continue;
1646 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1647 		    pci_get_slot(dev), i);
1648 		if (sibling == NULL || !device_is_attached(sibling))
1649 			continue;
1650 		if (detaching)
1651 			error = T4_DETACH_CHILD(sibling);
1652 		else
1653 			(void)T4_ATTACH_CHILD(sibling);
1654 		if (error)
1655 			break;
1656 	}
1657 	return (error);
1658 }
1659 
1660 /*
1661  * Idempotent
1662  */
1663 static int
1664 t4_detach(device_t dev)
1665 {
1666 	struct adapter *sc;
1667 	int rc;
1668 
1669 	sc = device_get_softc(dev);
1670 
1671 	rc = notify_siblings(dev, 1);
1672 	if (rc) {
1673 		device_printf(dev,
1674 		    "failed to detach sibling devices: %d\n", rc);
1675 		return (rc);
1676 	}
1677 
1678 	return (t4_detach_common(dev));
1679 }
1680 
1681 int
1682 t4_detach_common(device_t dev)
1683 {
1684 	struct adapter *sc;
1685 	struct port_info *pi;
1686 	int i, rc;
1687 
1688 	sc = device_get_softc(dev);
1689 
1690 	if (sc->cdev) {
1691 		destroy_dev(sc->cdev);
1692 		sc->cdev = NULL;
1693 	}
1694 
1695 	sx_xlock(&t4_list_lock);
1696 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1697 	sx_xunlock(&t4_list_lock);
1698 
1699 	sc->flags &= ~CHK_MBOX_ACCESS;
1700 	if (sc->flags & FULL_INIT_DONE) {
1701 		if (!(sc->flags & IS_VF))
1702 			t4_intr_disable(sc);
1703 	}
1704 
1705 	if (device_is_attached(dev)) {
1706 		rc = bus_generic_detach(dev);
1707 		if (rc) {
1708 			device_printf(dev,
1709 			    "failed to detach child devices: %d\n", rc);
1710 			return (rc);
1711 		}
1712 	}
1713 
1714 #ifdef TCP_OFFLOAD
1715 	taskqueue_drain(taskqueue_thread, &sc->async_event_task);
1716 #endif
1717 
1718 	for (i = 0; i < sc->intr_count; i++)
1719 		t4_free_irq(sc, &sc->irq[i]);
1720 
1721 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1722 		t4_free_tx_sched(sc);
1723 
1724 	for (i = 0; i < MAX_NPORTS; i++) {
1725 		pi = sc->port[i];
1726 		if (pi) {
1727 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1728 			if (pi->dev)
1729 				device_delete_child(dev, pi->dev);
1730 
1731 			mtx_destroy(&pi->pi_lock);
1732 			free(pi->vi, M_CXGBE);
1733 			free(pi, M_CXGBE);
1734 		}
1735 	}
1736 
1737 	device_delete_children(dev);
1738 	adapter_full_uninit(sc);
1739 
1740 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1741 		t4_fw_bye(sc, sc->mbox);
1742 
1743 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1744 		pci_release_msi(dev);
1745 
1746 	if (sc->regs_res)
1747 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1748 		    sc->regs_res);
1749 
1750 	if (sc->udbs_res)
1751 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1752 		    sc->udbs_res);
1753 
1754 	if (sc->msix_res)
1755 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1756 		    sc->msix_res);
1757 
1758 	if (sc->l2t)
1759 		t4_free_l2t(sc->l2t);
1760 	if (sc->smt)
1761 		t4_free_smt(sc->smt);
1762 	t4_free_atid_table(sc);
1763 #ifdef RATELIMIT
1764 	t4_free_etid_table(sc);
1765 #endif
1766 	if (sc->key_map)
1767 		vmem_destroy(sc->key_map);
1768 #ifdef INET6
1769 	t4_destroy_clip_table(sc);
1770 #endif
1771 
1772 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1773 	free(sc->sge.ofld_txq, M_CXGBE);
1774 #endif
1775 #ifdef TCP_OFFLOAD
1776 	free(sc->sge.ofld_rxq, M_CXGBE);
1777 #endif
1778 #ifdef DEV_NETMAP
1779 	free(sc->sge.nm_rxq, M_CXGBE);
1780 	free(sc->sge.nm_txq, M_CXGBE);
1781 #endif
1782 	free(sc->irq, M_CXGBE);
1783 	free(sc->sge.rxq, M_CXGBE);
1784 	free(sc->sge.txq, M_CXGBE);
1785 	free(sc->sge.ctrlq, M_CXGBE);
1786 	free(sc->sge.iqmap, M_CXGBE);
1787 	free(sc->sge.eqmap, M_CXGBE);
1788 	free(sc->tids.ftid_tab, M_CXGBE);
1789 	free(sc->tids.hpftid_tab, M_CXGBE);
1790 	free_hftid_hash(&sc->tids);
1791 	free(sc->tids.tid_tab, M_CXGBE);
1792 	free(sc->tt.tls_rx_ports, M_CXGBE);
1793 	t4_destroy_dma_tag(sc);
1794 
1795 	callout_drain(&sc->ktls_tick);
1796 	callout_drain(&sc->sfl_callout);
1797 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1798 		mtx_destroy(&sc->tids.ftid_lock);
1799 		cv_destroy(&sc->tids.ftid_cv);
1800 	}
1801 	if (mtx_initialized(&sc->tids.atid_lock))
1802 		mtx_destroy(&sc->tids.atid_lock);
1803 	if (mtx_initialized(&sc->ifp_lock))
1804 		mtx_destroy(&sc->ifp_lock);
1805 
1806 	if (rw_initialized(&sc->policy_lock)) {
1807 		rw_destroy(&sc->policy_lock);
1808 #ifdef TCP_OFFLOAD
1809 		if (sc->policy != NULL)
1810 			free_offload_policy(sc->policy);
1811 #endif
1812 	}
1813 
1814 	for (i = 0; i < NUM_MEMWIN; i++) {
1815 		struct memwin *mw = &sc->memwin[i];
1816 
1817 		if (rw_initialized(&mw->mw_lock))
1818 			rw_destroy(&mw->mw_lock);
1819 	}
1820 
1821 	mtx_destroy(&sc->sfl_lock);
1822 	mtx_destroy(&sc->reg_lock);
1823 	mtx_destroy(&sc->sc_lock);
1824 
1825 	bzero(sc, sizeof(*sc));
1826 
1827 	return (0);
1828 }
1829 
1830 static inline bool
1831 ok_to_reset(struct adapter *sc)
1832 {
1833 	struct tid_info *t = &sc->tids;
1834 	struct port_info *pi;
1835 	struct vi_info *vi;
1836 	int i, j;
1837 	const int caps = IFCAP_TOE | IFCAP_TXTLS | IFCAP_NETMAP | IFCAP_TXRTLMT;
1838 
1839 	ASSERT_SYNCHRONIZED_OP(sc);
1840 	MPASS(!(sc->flags & IS_VF));
1841 
1842 	for_each_port(sc, i) {
1843 		pi = sc->port[i];
1844 		for_each_vi(pi, j, vi) {
1845 			if (vi->ifp->if_capenable & caps)
1846 				return (false);
1847 		}
1848 	}
1849 
1850 	if (atomic_load_int(&t->tids_in_use) > 0)
1851 		return (false);
1852 	if (atomic_load_int(&t->stids_in_use) > 0)
1853 		return (false);
1854 	if (atomic_load_int(&t->atids_in_use) > 0)
1855 		return (false);
1856 	if (atomic_load_int(&t->ftids_in_use) > 0)
1857 		return (false);
1858 	if (atomic_load_int(&t->hpftids_in_use) > 0)
1859 		return (false);
1860 	if (atomic_load_int(&t->etids_in_use) > 0)
1861 		return (false);
1862 
1863 	return (true);
1864 }
1865 
1866 static int
1867 t4_suspend(device_t dev)
1868 {
1869 	struct adapter *sc = device_get_softc(dev);
1870 	struct port_info *pi;
1871 	struct vi_info *vi;
1872 	struct ifnet *ifp;
1873 	struct sge_rxq *rxq;
1874 	struct sge_txq *txq;
1875 	struct sge_wrq *wrq;
1876 #ifdef TCP_OFFLOAD
1877 	struct sge_ofld_rxq *ofld_rxq;
1878 #endif
1879 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1880 	struct sge_ofld_txq *ofld_txq;
1881 #endif
1882 	int rc, i, j, k;
1883 
1884 	CH_ALERT(sc, "suspend requested\n");
1885 
1886 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4sus");
1887 	if (rc != 0)
1888 		return (ENXIO);
1889 
1890 	/* XXX: Can the kernel call suspend repeatedly without resume? */
1891 	MPASS(!hw_off_limits(sc));
1892 
1893 	if (!ok_to_reset(sc)) {
1894 		/* XXX: should list what resource is preventing suspend. */
1895 		CH_ERR(sc, "not safe to suspend.\n");
1896 		rc = EBUSY;
1897 		goto done;
1898 	}
1899 
1900 	/* No more DMA or interrupts. */
1901 	t4_shutdown_adapter(sc);
1902 
1903 	/* Quiesce all activity. */
1904 	for_each_port(sc, i) {
1905 		pi = sc->port[i];
1906 		pi->vxlan_tcam_entry = false;
1907 
1908 		PORT_LOCK(pi);
1909 		if (pi->up_vis > 0) {
1910 			/*
1911 			 * t4_shutdown_adapter has already shut down all the
1912 			 * PHYs but it also disables interrupts and DMA so there
1913 			 * won't be a link interrupt.  So we update the state
1914 			 * manually and inform the kernel.
1915 			 */
1916 			pi->link_cfg.link_ok = false;
1917 			t4_os_link_changed(pi);
1918 		}
1919 		PORT_UNLOCK(pi);
1920 
1921 		for_each_vi(pi, j, vi) {
1922 			vi->xact_addr_filt = -1;
1923 			if (!(vi->flags & VI_INIT_DONE))
1924 				continue;
1925 
1926 			ifp = vi->ifp;
1927 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1928 				mtx_lock(&vi->tick_mtx);
1929 				vi->flags |= VI_SKIP_STATS;
1930 				callout_stop(&vi->tick);
1931 				mtx_unlock(&vi->tick_mtx);
1932 				callout_drain(&vi->tick);
1933 			}
1934 
1935 			/*
1936 			 * Note that the HW is not available.
1937 			 */
1938 			for_each_txq(vi, k, txq) {
1939 				TXQ_LOCK(txq);
1940 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
1941 				TXQ_UNLOCK(txq);
1942 			}
1943 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1944 			for_each_ofld_txq(vi, k, ofld_txq) {
1945 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
1946 			}
1947 #endif
1948 			for_each_rxq(vi, k, rxq) {
1949 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1950 			}
1951 #if defined(TCP_OFFLOAD)
1952 			for_each_ofld_rxq(vi, k, ofld_rxq) {
1953 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1954 			}
1955 #endif
1956 
1957 			quiesce_vi(vi);
1958 		}
1959 
1960 		if (sc->flags & FULL_INIT_DONE) {
1961 			/* Control queue */
1962 			wrq = &sc->sge.ctrlq[i];
1963 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
1964 			quiesce_wrq(wrq);
1965 		}
1966 	}
1967 	if (sc->flags & FULL_INIT_DONE) {
1968 		/* Firmware event queue */
1969 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
1970 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
1971 	}
1972 
1973 	/* Mark the adapter totally off limits. */
1974 	mtx_lock(&sc->reg_lock);
1975 	sc->flags |= HW_OFF_LIMITS;
1976 	sc->flags &= ~(FW_OK | MASTER_PF);
1977 	sc->reset_thread = NULL;
1978 	mtx_unlock(&sc->reg_lock);
1979 
1980 	sc->num_resets++;
1981 	CH_ALERT(sc, "suspend completed.\n");
1982 done:
1983 	end_synchronized_op(sc, 0);
1984 	return (rc);
1985 }
1986 
1987 struct adapter_pre_reset_state {
1988 	u_int flags;
1989 	uint16_t nbmcaps;
1990 	uint16_t linkcaps;
1991 	uint16_t switchcaps;
1992 	uint16_t niccaps;
1993 	uint16_t toecaps;
1994 	uint16_t rdmacaps;
1995 	uint16_t cryptocaps;
1996 	uint16_t iscsicaps;
1997 	uint16_t fcoecaps;
1998 
1999 	u_int cfcsum;
2000 	char cfg_file[32];
2001 
2002 	struct adapter_params params;
2003 	struct t4_virt_res vres;
2004 	struct tid_info tids;
2005 	struct sge sge;
2006 
2007 	int rawf_base;
2008 	int nrawf;
2009 
2010 };
2011 
2012 static void
2013 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2014 {
2015 
2016 	ASSERT_SYNCHRONIZED_OP(sc);
2017 
2018 	o->flags = sc->flags;
2019 
2020 	o->nbmcaps =  sc->nbmcaps;
2021 	o->linkcaps = sc->linkcaps;
2022 	o->switchcaps = sc->switchcaps;
2023 	o->niccaps = sc->niccaps;
2024 	o->toecaps = sc->toecaps;
2025 	o->rdmacaps = sc->rdmacaps;
2026 	o->cryptocaps = sc->cryptocaps;
2027 	o->iscsicaps = sc->iscsicaps;
2028 	o->fcoecaps = sc->fcoecaps;
2029 
2030 	o->cfcsum = sc->cfcsum;
2031 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2032 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2033 
2034 	o->params = sc->params;
2035 	o->vres = sc->vres;
2036 	o->tids = sc->tids;
2037 	o->sge = sc->sge;
2038 
2039 	o->rawf_base = sc->rawf_base;
2040 	o->nrawf = sc->nrawf;
2041 }
2042 
2043 static int
2044 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2045 {
2046 	int rc = 0;
2047 
2048 	ASSERT_SYNCHRONIZED_OP(sc);
2049 
2050 	/* Capabilities */
2051 #define COMPARE_CAPS(c) do { \
2052 	if (o->c##caps != sc->c##caps) { \
2053 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2054 		    sc->c##caps); \
2055 		rc = EINVAL; \
2056 	} \
2057 } while (0)
2058 	COMPARE_CAPS(nbm);
2059 	COMPARE_CAPS(link);
2060 	COMPARE_CAPS(switch);
2061 	COMPARE_CAPS(nic);
2062 	COMPARE_CAPS(toe);
2063 	COMPARE_CAPS(rdma);
2064 	COMPARE_CAPS(crypto);
2065 	COMPARE_CAPS(iscsi);
2066 	COMPARE_CAPS(fcoe);
2067 #undef COMPARE_CAPS
2068 
2069 	/* Firmware config file */
2070 	if (o->cfcsum != sc->cfcsum) {
2071 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2072 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2073 		rc = EINVAL;
2074 	}
2075 
2076 #define COMPARE_PARAM(p, name) do { \
2077 	if (o->p != sc->p) { \
2078 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2079 		rc = EINVAL; \
2080 	} \
2081 } while (0)
2082 	COMPARE_PARAM(sge.iq_start, iq_start);
2083 	COMPARE_PARAM(sge.eq_start, eq_start);
2084 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2085 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2086 	COMPARE_PARAM(tids.nftids, nftids);
2087 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2088 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2089 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2090 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2091 	COMPARE_PARAM(tids.tid_base, tid_base);
2092 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2093 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2094 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2095 	COMPARE_PARAM(rawf_base, rawf_base);
2096 	COMPARE_PARAM(nrawf, nrawf);
2097 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2098 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2099 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2100 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2101 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2102 	COMPARE_PARAM(tids.ntids, ntids);
2103 	COMPARE_PARAM(tids.etid_base, etid_base);
2104 	COMPARE_PARAM(tids.etid_end, etid_end);
2105 	COMPARE_PARAM(tids.netids, netids);
2106 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2107 	COMPARE_PARAM(params.ethoffload, ethoffload);
2108 	COMPARE_PARAM(tids.natids, natids);
2109 	COMPARE_PARAM(tids.stid_base, stid_base);
2110 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2111 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2112 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2113 	COMPARE_PARAM(vres.stag.start, stag_start);
2114 	COMPARE_PARAM(vres.stag.size, stag_size);
2115 	COMPARE_PARAM(vres.rq.start, rq_start);
2116 	COMPARE_PARAM(vres.rq.size, rq_size);
2117 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2118 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2119 	COMPARE_PARAM(vres.qp.start, qp_start);
2120 	COMPARE_PARAM(vres.qp.size, qp_size);
2121 	COMPARE_PARAM(vres.cq.start, cq_start);
2122 	COMPARE_PARAM(vres.cq.size, cq_size);
2123 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2124 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2125 	COMPARE_PARAM(vres.srq.start, srq_start);
2126 	COMPARE_PARAM(vres.srq.size, srq_size);
2127 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2128 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2129 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2130 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2131 	COMPARE_PARAM(vres.key.start, key_start);
2132 	COMPARE_PARAM(vres.key.size, key_size);
2133 #undef COMPARE_PARAM
2134 
2135 	return (rc);
2136 }
2137 
2138 static int
2139 t4_resume(device_t dev)
2140 {
2141 	struct adapter *sc = device_get_softc(dev);
2142 	struct adapter_pre_reset_state *old_state = NULL;
2143 	struct port_info *pi;
2144 	struct vi_info *vi;
2145 	struct ifnet *ifp;
2146 	struct sge_txq *txq;
2147 	int rc, i, j, k;
2148 
2149 	CH_ALERT(sc, "resume requested.\n");
2150 
2151 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4res");
2152 	if (rc != 0)
2153 		return (ENXIO);
2154 	MPASS(hw_off_limits(sc));
2155 	MPASS((sc->flags & FW_OK) == 0);
2156 	MPASS((sc->flags & MASTER_PF) == 0);
2157 	MPASS(sc->reset_thread == NULL);
2158 	sc->reset_thread = curthread;
2159 
2160 	/* Register access is expected to work by the time we're here. */
2161 	if (t4_read_reg(sc, A_PL_WHOAMI) == 0xffffffff) {
2162 		CH_ERR(sc, "%s: can't read device registers\n", __func__);
2163 		rc = ENXIO;
2164 		goto done;
2165 	}
2166 
2167 	/* Restore memory window. */
2168 	setup_memwin(sc);
2169 
2170 	/* Go no further if recovery mode has been requested. */
2171 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2172 		CH_ALERT(sc, "recovery mode on resume.\n");
2173 		rc = 0;
2174 		mtx_lock(&sc->reg_lock);
2175 		sc->flags &= ~HW_OFF_LIMITS;
2176 		mtx_unlock(&sc->reg_lock);
2177 		goto done;
2178 	}
2179 
2180 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2181 	save_caps_and_params(sc, old_state);
2182 
2183 	/* Reestablish contact with firmware and become the primary PF. */
2184 	rc = contact_firmware(sc);
2185 	if (rc != 0)
2186 		goto done; /* error message displayed already */
2187 	MPASS(sc->flags & FW_OK);
2188 
2189 	if (sc->flags & MASTER_PF) {
2190 		rc = partition_resources(sc);
2191 		if (rc != 0)
2192 			goto done; /* error message displayed already */
2193 		t4_intr_clear(sc);
2194 	}
2195 
2196 	rc = get_params__post_init(sc);
2197 	if (rc != 0)
2198 		goto done; /* error message displayed already */
2199 
2200 	rc = set_params__post_init(sc);
2201 	if (rc != 0)
2202 		goto done; /* error message displayed already */
2203 
2204 	rc = compare_caps_and_params(sc, old_state);
2205 	if (rc != 0)
2206 		goto done; /* error message displayed already */
2207 
2208 	for_each_port(sc, i) {
2209 		pi = sc->port[i];
2210 		MPASS(pi != NULL);
2211 		MPASS(pi->vi != NULL);
2212 		MPASS(pi->vi[0].dev == pi->dev);
2213 
2214 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2215 		if (rc != 0) {
2216 			CH_ERR(sc,
2217 			    "failed to re-initialize port %d: %d\n", i, rc);
2218 			goto done;
2219 		}
2220 		MPASS(sc->chan_map[pi->tx_chan] == i);
2221 
2222 		PORT_LOCK(pi);
2223 		fixup_link_config(pi);
2224 		build_medialist(pi);
2225 		PORT_UNLOCK(pi);
2226 		for_each_vi(pi, j, vi) {
2227 			if (IS_MAIN_VI(vi))
2228 				continue;
2229 			rc = alloc_extra_vi(sc, pi, vi);
2230 			if (rc != 0) {
2231 				CH_ERR(vi,
2232 				    "failed to re-allocate extra VI: %d\n", rc);
2233 				goto done;
2234 			}
2235 		}
2236 	}
2237 
2238 	/*
2239 	 * Interrupts and queues are about to be enabled and other threads will
2240 	 * want to access the hardware too.  It is safe to do so.  Note that
2241 	 * this thread is still in the middle of a synchronized_op.
2242 	 */
2243 	mtx_lock(&sc->reg_lock);
2244 	sc->flags &= ~HW_OFF_LIMITS;
2245 	mtx_unlock(&sc->reg_lock);
2246 
2247 	if (sc->flags & FULL_INIT_DONE) {
2248 		rc = adapter_full_init(sc);
2249 		if (rc != 0) {
2250 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2251 			goto done;
2252 		}
2253 
2254 		if (sc->vxlan_refcount > 0)
2255 			enable_vxlan_rx(sc);
2256 
2257 		for_each_port(sc, i) {
2258 			pi = sc->port[i];
2259 			for_each_vi(pi, j, vi) {
2260 				if (!(vi->flags & VI_INIT_DONE))
2261 					continue;
2262 				rc = vi_full_init(vi);
2263 				if (rc != 0) {
2264 					CH_ERR(vi, "failed to re-initialize "
2265 					    "interface: %d\n", rc);
2266 					goto done;
2267 				}
2268 
2269 				ifp = vi->ifp;
2270 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2271 					continue;
2272 				/*
2273 				 * Note that we do not setup multicast addresses
2274 				 * in the first pass.  This ensures that the
2275 				 * unicast DMACs for all VIs on all ports get an
2276 				 * MPS TCAM entry.
2277 				 */
2278 				rc = update_mac_settings(ifp, XGMAC_ALL &
2279 				    ~XGMAC_MCADDRS);
2280 				if (rc != 0) {
2281 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2282 					goto done;
2283 				}
2284 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2285 				    true);
2286 				if (rc != 0) {
2287 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2288 					goto done;
2289 				}
2290 				for_each_txq(vi, k, txq) {
2291 					TXQ_LOCK(txq);
2292 					txq->eq.flags |= EQ_ENABLED;
2293 					TXQ_UNLOCK(txq);
2294 				}
2295 				mtx_lock(&vi->tick_mtx);
2296 				vi->flags &= ~VI_SKIP_STATS;
2297 				callout_schedule(&vi->tick, hz);
2298 				mtx_unlock(&vi->tick_mtx);
2299 			}
2300 			PORT_LOCK(pi);
2301 			if (pi->up_vis > 0) {
2302 				t4_update_port_info(pi);
2303 				fixup_link_config(pi);
2304 				build_medialist(pi);
2305 				apply_link_config(pi);
2306 				if (pi->link_cfg.link_ok)
2307 					t4_os_link_changed(pi);
2308 			}
2309 			PORT_UNLOCK(pi);
2310 		}
2311 
2312 		/* Now reprogram the L2 multicast addresses. */
2313 		for_each_port(sc, i) {
2314 			pi = sc->port[i];
2315 			for_each_vi(pi, j, vi) {
2316 				if (!(vi->flags & VI_INIT_DONE))
2317 					continue;
2318 				ifp = vi->ifp;
2319 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2320 					continue;
2321 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2322 				if (rc != 0) {
2323 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2324 					rc = 0;	/* carry on */
2325 				}
2326 			}
2327 		}
2328 	}
2329 done:
2330 	if (rc == 0) {
2331 		sc->incarnation++;
2332 		CH_ALERT(sc, "resume completed.\n");
2333 	}
2334 	end_synchronized_op(sc, 0);
2335 	free(old_state, M_CXGBE);
2336 	return (rc);
2337 }
2338 
2339 static int
2340 t4_reset_prepare(device_t dev, device_t child)
2341 {
2342 	struct adapter *sc = device_get_softc(dev);
2343 
2344 	CH_ALERT(sc, "reset_prepare.\n");
2345 	return (0);
2346 }
2347 
2348 static int
2349 t4_reset_post(device_t dev, device_t child)
2350 {
2351 	struct adapter *sc = device_get_softc(dev);
2352 
2353 	CH_ALERT(sc, "reset_post.\n");
2354 	return (0);
2355 }
2356 
2357 static void
2358 reset_adapter(void *arg, int pending)
2359 {
2360 	struct adapter *sc = arg;
2361 	int rc;
2362 
2363 	CH_ALERT(sc, "reset requested.\n");
2364 
2365 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst1");
2366 	if (rc != 0)
2367 		return;
2368 
2369 	if (hw_off_limits(sc)) {
2370 		CH_ERR(sc, "adapter is suspended, use resume (not reset).\n");
2371 		rc = ENXIO;
2372 		goto done;
2373 	}
2374 
2375 	if (!ok_to_reset(sc)) {
2376 		/* XXX: should list what resource is preventing reset. */
2377 		CH_ERR(sc, "not safe to reset.\n");
2378 		rc = EBUSY;
2379 		goto done;
2380 	}
2381 
2382 done:
2383 	end_synchronized_op(sc, 0);
2384 	if (rc != 0)
2385 		return;	/* Error logged already. */
2386 
2387 	mtx_lock(&Giant);
2388 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2389 	mtx_unlock(&Giant);
2390 	if (rc != 0)
2391 		CH_ERR(sc, "bus_reset_child failed: %d.\n", rc);
2392 	else
2393 		CH_ALERT(sc, "bus_reset_child succeeded.\n");
2394 }
2395 
2396 static int
2397 cxgbe_probe(device_t dev)
2398 {
2399 	char buf[128];
2400 	struct port_info *pi = device_get_softc(dev);
2401 
2402 	snprintf(buf, sizeof(buf), "port %d", pi->port_id);
2403 	device_set_desc_copy(dev, buf);
2404 
2405 	return (BUS_PROBE_DEFAULT);
2406 }
2407 
2408 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2409     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2410     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2411     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2412 #define T4_CAP_ENABLE (T4_CAP)
2413 
2414 static int
2415 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2416 {
2417 	struct ifnet *ifp;
2418 	struct sbuf *sb;
2419 	struct sysctl_ctx_list *ctx;
2420 	struct sysctl_oid_list *children;
2421 	struct pfil_head_args pa;
2422 	struct adapter *sc = vi->adapter;
2423 
2424 	ctx = device_get_sysctl_ctx(vi->dev);
2425 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2426 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2427 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2428 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2429 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2430 #ifdef DEV_NETMAP
2431 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2432 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2433 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2434 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2435 #endif
2436 #ifdef TCP_OFFLOAD
2437 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2438 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2439 #endif
2440 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2441 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2442 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2443 #endif
2444 
2445 	vi->xact_addr_filt = -1;
2446 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2447 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2448 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2449 		vi->flags |= TX_USES_VM_WR;
2450 
2451 	/* Allocate an ifnet and set it up */
2452 	ifp = if_alloc_dev(IFT_ETHER, dev);
2453 	if (ifp == NULL) {
2454 		device_printf(dev, "Cannot allocate ifnet\n");
2455 		return (ENOMEM);
2456 	}
2457 	vi->ifp = ifp;
2458 	ifp->if_softc = vi;
2459 
2460 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2461 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
2462 
2463 	ifp->if_init = cxgbe_init;
2464 	ifp->if_ioctl = cxgbe_ioctl;
2465 	ifp->if_transmit = cxgbe_transmit;
2466 	ifp->if_qflush = cxgbe_qflush;
2467 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2468 		ifp->if_get_counter = vi_get_counter;
2469 	else
2470 		ifp->if_get_counter = cxgbe_get_counter;
2471 #if defined(KERN_TLS) || defined(RATELIMIT)
2472 	ifp->if_snd_tag_alloc = cxgbe_snd_tag_alloc;
2473 #endif
2474 #ifdef RATELIMIT
2475 	ifp->if_ratelimit_query = cxgbe_ratelimit_query;
2476 #endif
2477 
2478 	ifp->if_capabilities = T4_CAP;
2479 	ifp->if_capenable = T4_CAP_ENABLE;
2480 	ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2481 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6;
2482 	if (chip_id(sc) >= CHELSIO_T6) {
2483 		ifp->if_capabilities |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2484 		ifp->if_capenable |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2485 		ifp->if_hwassist |= CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2486 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2487 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN;
2488 	}
2489 
2490 #ifdef TCP_OFFLOAD
2491 	if (vi->nofldrxq != 0)
2492 		ifp->if_capabilities |= IFCAP_TOE;
2493 #endif
2494 #ifdef RATELIMIT
2495 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2496 		ifp->if_capabilities |= IFCAP_TXRTLMT;
2497 		ifp->if_capenable |= IFCAP_TXRTLMT;
2498 	}
2499 #endif
2500 
2501 	ifp->if_hw_tsomax = IP_MAXPACKET;
2502 	if (vi->flags & TX_USES_VM_WR)
2503 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
2504 	else
2505 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
2506 #ifdef RATELIMIT
2507 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2508 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_EO_TSO;
2509 #endif
2510 	ifp->if_hw_tsomaxsegsize = 65536;
2511 #ifdef KERN_TLS
2512 	if (is_ktls(sc)) {
2513 		ifp->if_capabilities |= IFCAP_TXTLS;
2514 		if (sc->flags & KERN_TLS_ON)
2515 			ifp->if_capenable |= IFCAP_TXTLS;
2516 	}
2517 #endif
2518 
2519 	ether_ifattach(ifp, vi->hw_addr);
2520 #ifdef DEV_NETMAP
2521 	if (vi->nnmrxq != 0)
2522 		cxgbe_nm_attach(vi);
2523 #endif
2524 	sb = sbuf_new_auto();
2525 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2526 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2527 	switch (ifp->if_capabilities & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2528 	case IFCAP_TOE:
2529 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2530 		break;
2531 	case IFCAP_TOE | IFCAP_TXRTLMT:
2532 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2533 		break;
2534 	case IFCAP_TXRTLMT:
2535 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2536 		break;
2537 	}
2538 #endif
2539 #ifdef TCP_OFFLOAD
2540 	if (ifp->if_capabilities & IFCAP_TOE)
2541 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2542 #endif
2543 #ifdef DEV_NETMAP
2544 	if (ifp->if_capabilities & IFCAP_NETMAP)
2545 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2546 		    vi->nnmtxq, vi->nnmrxq);
2547 #endif
2548 	sbuf_finish(sb);
2549 	device_printf(dev, "%s\n", sbuf_data(sb));
2550 	sbuf_delete(sb);
2551 
2552 	vi_sysctls(vi);
2553 
2554 	pa.pa_version = PFIL_VERSION;
2555 	pa.pa_flags = PFIL_IN;
2556 	pa.pa_type = PFIL_TYPE_ETHERNET;
2557 	pa.pa_headname = ifp->if_xname;
2558 	vi->pfil = pfil_head_register(&pa);
2559 
2560 	return (0);
2561 }
2562 
2563 static int
2564 cxgbe_attach(device_t dev)
2565 {
2566 	struct port_info *pi = device_get_softc(dev);
2567 	struct adapter *sc = pi->adapter;
2568 	struct vi_info *vi;
2569 	int i, rc;
2570 
2571 	rc = cxgbe_vi_attach(dev, &pi->vi[0]);
2572 	if (rc)
2573 		return (rc);
2574 
2575 	for_each_vi(pi, i, vi) {
2576 		if (i == 0)
2577 			continue;
2578 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
2579 		if (vi->dev == NULL) {
2580 			device_printf(dev, "failed to add VI %d\n", i);
2581 			continue;
2582 		}
2583 		device_set_softc(vi->dev, vi);
2584 	}
2585 
2586 	cxgbe_sysctls(pi);
2587 
2588 	bus_generic_attach(dev);
2589 
2590 	return (0);
2591 }
2592 
2593 static void
2594 cxgbe_vi_detach(struct vi_info *vi)
2595 {
2596 	struct ifnet *ifp = vi->ifp;
2597 
2598 	if (vi->pfil != NULL) {
2599 		pfil_head_unregister(vi->pfil);
2600 		vi->pfil = NULL;
2601 	}
2602 
2603 	ether_ifdetach(ifp);
2604 
2605 	/* Let detach proceed even if these fail. */
2606 #ifdef DEV_NETMAP
2607 	if (ifp->if_capabilities & IFCAP_NETMAP)
2608 		cxgbe_nm_detach(vi);
2609 #endif
2610 	cxgbe_uninit_synchronized(vi);
2611 	callout_drain(&vi->tick);
2612 	vi_full_uninit(vi);
2613 
2614 	if_free(vi->ifp);
2615 	vi->ifp = NULL;
2616 }
2617 
2618 static int
2619 cxgbe_detach(device_t dev)
2620 {
2621 	struct port_info *pi = device_get_softc(dev);
2622 	struct adapter *sc = pi->adapter;
2623 	int rc;
2624 
2625 	/* Detach the extra VIs first. */
2626 	rc = bus_generic_detach(dev);
2627 	if (rc)
2628 		return (rc);
2629 	device_delete_children(dev);
2630 
2631 	doom_vi(sc, &pi->vi[0]);
2632 
2633 	if (pi->flags & HAS_TRACEQ) {
2634 		sc->traceq = -1;	/* cloner should not create ifnet */
2635 		t4_tracer_port_detach(sc);
2636 	}
2637 
2638 	cxgbe_vi_detach(&pi->vi[0]);
2639 	ifmedia_removeall(&pi->media);
2640 
2641 	end_synchronized_op(sc, 0);
2642 
2643 	return (0);
2644 }
2645 
2646 static void
2647 cxgbe_init(void *arg)
2648 {
2649 	struct vi_info *vi = arg;
2650 	struct adapter *sc = vi->adapter;
2651 
2652 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2653 		return;
2654 	cxgbe_init_synchronized(vi);
2655 	end_synchronized_op(sc, 0);
2656 }
2657 
2658 static int
2659 cxgbe_ioctl(struct ifnet *ifp, unsigned long cmd, caddr_t data)
2660 {
2661 	int rc = 0, mtu, flags;
2662 	struct vi_info *vi = ifp->if_softc;
2663 	struct port_info *pi = vi->pi;
2664 	struct adapter *sc = pi->adapter;
2665 	struct ifreq *ifr = (struct ifreq *)data;
2666 	uint32_t mask;
2667 
2668 	switch (cmd) {
2669 	case SIOCSIFMTU:
2670 		mtu = ifr->ifr_mtu;
2671 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2672 			return (EINVAL);
2673 
2674 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2675 		if (rc)
2676 			return (rc);
2677 		ifp->if_mtu = mtu;
2678 		if (vi->flags & VI_INIT_DONE) {
2679 			t4_update_fl_bufsize(ifp);
2680 			if (!hw_off_limits(sc) &&
2681 			    ifp->if_drv_flags & IFF_DRV_RUNNING)
2682 				rc = update_mac_settings(ifp, XGMAC_MTU);
2683 		}
2684 		end_synchronized_op(sc, 0);
2685 		break;
2686 
2687 	case SIOCSIFFLAGS:
2688 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2689 		if (rc)
2690 			return (rc);
2691 
2692 		if (hw_off_limits(sc)) {
2693 			rc = ENXIO;
2694 			goto fail;
2695 		}
2696 
2697 		if (ifp->if_flags & IFF_UP) {
2698 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2699 				flags = vi->if_flags;
2700 				if ((ifp->if_flags ^ flags) &
2701 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2702 					rc = update_mac_settings(ifp,
2703 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2704 				}
2705 			} else {
2706 				rc = cxgbe_init_synchronized(vi);
2707 			}
2708 			vi->if_flags = ifp->if_flags;
2709 		} else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2710 			rc = cxgbe_uninit_synchronized(vi);
2711 		}
2712 		end_synchronized_op(sc, 0);
2713 		break;
2714 
2715 	case SIOCADDMULTI:
2716 	case SIOCDELMULTI:
2717 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2718 		if (rc)
2719 			return (rc);
2720 		if (!hw_off_limits(sc) && ifp->if_drv_flags & IFF_DRV_RUNNING)
2721 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2722 		end_synchronized_op(sc, 0);
2723 		break;
2724 
2725 	case SIOCSIFCAP:
2726 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2727 		if (rc)
2728 			return (rc);
2729 
2730 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
2731 		if (mask & IFCAP_TXCSUM) {
2732 			ifp->if_capenable ^= IFCAP_TXCSUM;
2733 			ifp->if_hwassist ^= (CSUM_TCP | CSUM_UDP | CSUM_IP);
2734 
2735 			if (IFCAP_TSO4 & ifp->if_capenable &&
2736 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2737 				mask &= ~IFCAP_TSO4;
2738 				ifp->if_capenable &= ~IFCAP_TSO4;
2739 				if_printf(ifp,
2740 				    "tso4 disabled due to -txcsum.\n");
2741 			}
2742 		}
2743 		if (mask & IFCAP_TXCSUM_IPV6) {
2744 			ifp->if_capenable ^= IFCAP_TXCSUM_IPV6;
2745 			ifp->if_hwassist ^= (CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2746 
2747 			if (IFCAP_TSO6 & ifp->if_capenable &&
2748 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2749 				mask &= ~IFCAP_TSO6;
2750 				ifp->if_capenable &= ~IFCAP_TSO6;
2751 				if_printf(ifp,
2752 				    "tso6 disabled due to -txcsum6.\n");
2753 			}
2754 		}
2755 		if (mask & IFCAP_RXCSUM)
2756 			ifp->if_capenable ^= IFCAP_RXCSUM;
2757 		if (mask & IFCAP_RXCSUM_IPV6)
2758 			ifp->if_capenable ^= IFCAP_RXCSUM_IPV6;
2759 
2760 		/*
2761 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2762 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2763 		 * sending a TSO request our way, so it's sufficient to toggle
2764 		 * IFCAP_TSOx only.
2765 		 */
2766 		if (mask & IFCAP_TSO4) {
2767 			if (!(IFCAP_TSO4 & ifp->if_capenable) &&
2768 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2769 				if_printf(ifp, "enable txcsum first.\n");
2770 				rc = EAGAIN;
2771 				goto fail;
2772 			}
2773 			ifp->if_capenable ^= IFCAP_TSO4;
2774 		}
2775 		if (mask & IFCAP_TSO6) {
2776 			if (!(IFCAP_TSO6 & ifp->if_capenable) &&
2777 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2778 				if_printf(ifp, "enable txcsum6 first.\n");
2779 				rc = EAGAIN;
2780 				goto fail;
2781 			}
2782 			ifp->if_capenable ^= IFCAP_TSO6;
2783 		}
2784 		if (mask & IFCAP_LRO) {
2785 #if defined(INET) || defined(INET6)
2786 			int i;
2787 			struct sge_rxq *rxq;
2788 
2789 			ifp->if_capenable ^= IFCAP_LRO;
2790 			for_each_rxq(vi, i, rxq) {
2791 				if (ifp->if_capenable & IFCAP_LRO)
2792 					rxq->iq.flags |= IQ_LRO_ENABLED;
2793 				else
2794 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2795 			}
2796 #endif
2797 		}
2798 #ifdef TCP_OFFLOAD
2799 		if (mask & IFCAP_TOE) {
2800 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TOE;
2801 
2802 			rc = toe_capability(vi, enable);
2803 			if (rc != 0)
2804 				goto fail;
2805 
2806 			ifp->if_capenable ^= mask;
2807 		}
2808 #endif
2809 		if (mask & IFCAP_VLAN_HWTAGGING) {
2810 			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
2811 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2812 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2813 		}
2814 		if (mask & IFCAP_VLAN_MTU) {
2815 			ifp->if_capenable ^= IFCAP_VLAN_MTU;
2816 
2817 			/* Need to find out how to disable auto-mtu-inflation */
2818 		}
2819 		if (mask & IFCAP_VLAN_HWTSO)
2820 			ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
2821 		if (mask & IFCAP_VLAN_HWCSUM)
2822 			ifp->if_capenable ^= IFCAP_VLAN_HWCSUM;
2823 #ifdef RATELIMIT
2824 		if (mask & IFCAP_TXRTLMT)
2825 			ifp->if_capenable ^= IFCAP_TXRTLMT;
2826 #endif
2827 		if (mask & IFCAP_HWRXTSTMP) {
2828 			int i;
2829 			struct sge_rxq *rxq;
2830 
2831 			ifp->if_capenable ^= IFCAP_HWRXTSTMP;
2832 			for_each_rxq(vi, i, rxq) {
2833 				if (ifp->if_capenable & IFCAP_HWRXTSTMP)
2834 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2835 				else
2836 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2837 			}
2838 		}
2839 		if (mask & IFCAP_MEXTPG)
2840 			ifp->if_capenable ^= IFCAP_MEXTPG;
2841 
2842 #ifdef KERN_TLS
2843 		if (mask & IFCAP_TXTLS) {
2844 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TXTLS;
2845 
2846 			rc = ktls_capability(sc, enable);
2847 			if (rc != 0)
2848 				goto fail;
2849 
2850 			ifp->if_capenable ^= (mask & IFCAP_TXTLS);
2851 		}
2852 #endif
2853 		if (mask & IFCAP_VXLAN_HWCSUM) {
2854 			ifp->if_capenable ^= IFCAP_VXLAN_HWCSUM;
2855 			ifp->if_hwassist ^= CSUM_INNER_IP6_UDP |
2856 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
2857 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP;
2858 		}
2859 		if (mask & IFCAP_VXLAN_HWTSO) {
2860 			ifp->if_capenable ^= IFCAP_VXLAN_HWTSO;
2861 			ifp->if_hwassist ^= CSUM_INNER_IP6_TSO |
2862 			    CSUM_INNER_IP_TSO;
2863 		}
2864 
2865 #ifdef VLAN_CAPABILITIES
2866 		VLAN_CAPABILITIES(ifp);
2867 #endif
2868 fail:
2869 		end_synchronized_op(sc, 0);
2870 		break;
2871 
2872 	case SIOCSIFMEDIA:
2873 	case SIOCGIFMEDIA:
2874 	case SIOCGIFXMEDIA:
2875 		ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
2876 		break;
2877 
2878 	case SIOCGI2C: {
2879 		struct ifi2creq i2c;
2880 
2881 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
2882 		if (rc != 0)
2883 			break;
2884 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
2885 			rc = EPERM;
2886 			break;
2887 		}
2888 		if (i2c.len > sizeof(i2c.data)) {
2889 			rc = EINVAL;
2890 			break;
2891 		}
2892 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
2893 		if (rc)
2894 			return (rc);
2895 		if (hw_off_limits(sc))
2896 			rc = ENXIO;
2897 		else
2898 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
2899 			    i2c.offset, i2c.len, &i2c.data[0]);
2900 		end_synchronized_op(sc, 0);
2901 		if (rc == 0)
2902 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
2903 		break;
2904 	}
2905 
2906 	default:
2907 		rc = ether_ioctl(ifp, cmd, data);
2908 	}
2909 
2910 	return (rc);
2911 }
2912 
2913 static int
2914 cxgbe_transmit(struct ifnet *ifp, struct mbuf *m)
2915 {
2916 	struct vi_info *vi = ifp->if_softc;
2917 	struct port_info *pi = vi->pi;
2918 	struct adapter *sc;
2919 	struct sge_txq *txq;
2920 	void *items[1];
2921 	int rc;
2922 
2923 	M_ASSERTPKTHDR(m);
2924 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
2925 #if defined(KERN_TLS) || defined(RATELIMIT)
2926 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
2927 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
2928 #endif
2929 
2930 	if (__predict_false(pi->link_cfg.link_ok == false)) {
2931 		m_freem(m);
2932 		return (ENETDOWN);
2933 	}
2934 
2935 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
2936 	if (__predict_false(rc != 0)) {
2937 		MPASS(m == NULL);			/* was freed already */
2938 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
2939 		return (rc);
2940 	}
2941 #ifdef RATELIMIT
2942 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG) {
2943 		if (m->m_pkthdr.snd_tag->sw->type == IF_SND_TAG_TYPE_RATE_LIMIT)
2944 			return (ethofld_transmit(ifp, m));
2945 	}
2946 #endif
2947 
2948 	/* Select a txq. */
2949 	sc = vi->adapter;
2950 	txq = &sc->sge.txq[vi->first_txq];
2951 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
2952 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
2953 		    vi->rsrv_noflowq);
2954 
2955 	items[0] = m;
2956 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
2957 	if (__predict_false(rc != 0))
2958 		m_freem(m);
2959 
2960 	return (rc);
2961 }
2962 
2963 static void
2964 cxgbe_qflush(struct ifnet *ifp)
2965 {
2966 	struct vi_info *vi = ifp->if_softc;
2967 	struct sge_txq *txq;
2968 	int i;
2969 
2970 	/* queues do not exist if !VI_INIT_DONE. */
2971 	if (vi->flags & VI_INIT_DONE) {
2972 		for_each_txq(vi, i, txq) {
2973 			TXQ_LOCK(txq);
2974 			txq->eq.flags |= EQ_QFLUSH;
2975 			TXQ_UNLOCK(txq);
2976 			while (!mp_ring_is_idle(txq->r)) {
2977 				mp_ring_check_drainage(txq->r, 4096);
2978 				pause("qflush", 1);
2979 			}
2980 			TXQ_LOCK(txq);
2981 			txq->eq.flags &= ~EQ_QFLUSH;
2982 			TXQ_UNLOCK(txq);
2983 		}
2984 	}
2985 	if_qflush(ifp);
2986 }
2987 
2988 static uint64_t
2989 vi_get_counter(struct ifnet *ifp, ift_counter c)
2990 {
2991 	struct vi_info *vi = ifp->if_softc;
2992 	struct fw_vi_stats_vf *s = &vi->stats;
2993 
2994 	mtx_lock(&vi->tick_mtx);
2995 	vi_refresh_stats(vi);
2996 	mtx_unlock(&vi->tick_mtx);
2997 
2998 	switch (c) {
2999 	case IFCOUNTER_IPACKETS:
3000 		return (s->rx_bcast_frames + s->rx_mcast_frames +
3001 		    s->rx_ucast_frames);
3002 	case IFCOUNTER_IERRORS:
3003 		return (s->rx_err_frames);
3004 	case IFCOUNTER_OPACKETS:
3005 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3006 		    s->tx_ucast_frames + s->tx_offload_frames);
3007 	case IFCOUNTER_OERRORS:
3008 		return (s->tx_drop_frames);
3009 	case IFCOUNTER_IBYTES:
3010 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3011 		    s->rx_ucast_bytes);
3012 	case IFCOUNTER_OBYTES:
3013 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3014 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3015 	case IFCOUNTER_IMCASTS:
3016 		return (s->rx_mcast_frames);
3017 	case IFCOUNTER_OMCASTS:
3018 		return (s->tx_mcast_frames);
3019 	case IFCOUNTER_OQDROPS: {
3020 		uint64_t drops;
3021 
3022 		drops = 0;
3023 		if (vi->flags & VI_INIT_DONE) {
3024 			int i;
3025 			struct sge_txq *txq;
3026 
3027 			for_each_txq(vi, i, txq)
3028 				drops += counter_u64_fetch(txq->r->dropped);
3029 		}
3030 
3031 		return (drops);
3032 
3033 	}
3034 
3035 	default:
3036 		return (if_get_counter_default(ifp, c));
3037 	}
3038 }
3039 
3040 static uint64_t
3041 cxgbe_get_counter(struct ifnet *ifp, ift_counter c)
3042 {
3043 	struct vi_info *vi = ifp->if_softc;
3044 	struct port_info *pi = vi->pi;
3045 	struct port_stats *s = &pi->stats;
3046 
3047 	mtx_lock(&vi->tick_mtx);
3048 	cxgbe_refresh_stats(vi);
3049 	mtx_unlock(&vi->tick_mtx);
3050 
3051 	switch (c) {
3052 	case IFCOUNTER_IPACKETS:
3053 		return (s->rx_frames);
3054 
3055 	case IFCOUNTER_IERRORS:
3056 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3057 		    s->rx_fcs_err + s->rx_len_err);
3058 
3059 	case IFCOUNTER_OPACKETS:
3060 		return (s->tx_frames);
3061 
3062 	case IFCOUNTER_OERRORS:
3063 		return (s->tx_error_frames);
3064 
3065 	case IFCOUNTER_IBYTES:
3066 		return (s->rx_octets);
3067 
3068 	case IFCOUNTER_OBYTES:
3069 		return (s->tx_octets);
3070 
3071 	case IFCOUNTER_IMCASTS:
3072 		return (s->rx_mcast_frames);
3073 
3074 	case IFCOUNTER_OMCASTS:
3075 		return (s->tx_mcast_frames);
3076 
3077 	case IFCOUNTER_IQDROPS:
3078 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3079 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3080 		    s->rx_trunc3 + pi->tnl_cong_drops);
3081 
3082 	case IFCOUNTER_OQDROPS: {
3083 		uint64_t drops;
3084 
3085 		drops = s->tx_drop;
3086 		if (vi->flags & VI_INIT_DONE) {
3087 			int i;
3088 			struct sge_txq *txq;
3089 
3090 			for_each_txq(vi, i, txq)
3091 				drops += counter_u64_fetch(txq->r->dropped);
3092 		}
3093 
3094 		return (drops);
3095 
3096 	}
3097 
3098 	default:
3099 		return (if_get_counter_default(ifp, c));
3100 	}
3101 }
3102 
3103 #if defined(KERN_TLS) || defined(RATELIMIT)
3104 static int
3105 cxgbe_snd_tag_alloc(struct ifnet *ifp, union if_snd_tag_alloc_params *params,
3106     struct m_snd_tag **pt)
3107 {
3108 	int error;
3109 
3110 	switch (params->hdr.type) {
3111 #ifdef RATELIMIT
3112 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3113 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3114 		break;
3115 #endif
3116 #ifdef KERN_TLS
3117 	case IF_SND_TAG_TYPE_TLS:
3118 		error = cxgbe_tls_tag_alloc(ifp, params, pt);
3119 		break;
3120 #endif
3121 	default:
3122 		error = EOPNOTSUPP;
3123 	}
3124 	return (error);
3125 }
3126 #endif
3127 
3128 /*
3129  * The kernel picks a media from the list we had provided but we still validate
3130  * the requeste.
3131  */
3132 int
3133 cxgbe_media_change(struct ifnet *ifp)
3134 {
3135 	struct vi_info *vi = ifp->if_softc;
3136 	struct port_info *pi = vi->pi;
3137 	struct ifmedia *ifm = &pi->media;
3138 	struct link_config *lc = &pi->link_cfg;
3139 	struct adapter *sc = pi->adapter;
3140 	int rc;
3141 
3142 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3143 	if (rc != 0)
3144 		return (rc);
3145 	PORT_LOCK(pi);
3146 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3147 		/* ifconfig .. media autoselect */
3148 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3149 			rc = ENOTSUP; /* AN not supported by transceiver */
3150 			goto done;
3151 		}
3152 		lc->requested_aneg = AUTONEG_ENABLE;
3153 		lc->requested_speed = 0;
3154 		lc->requested_fc |= PAUSE_AUTONEG;
3155 	} else {
3156 		lc->requested_aneg = AUTONEG_DISABLE;
3157 		lc->requested_speed =
3158 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3159 		lc->requested_fc = 0;
3160 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3161 			lc->requested_fc |= PAUSE_RX;
3162 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3163 			lc->requested_fc |= PAUSE_TX;
3164 	}
3165 	if (pi->up_vis > 0) {
3166 		fixup_link_config(pi);
3167 		rc = apply_link_config(pi);
3168 	}
3169 done:
3170 	PORT_UNLOCK(pi);
3171 	end_synchronized_op(sc, 0);
3172 	return (rc);
3173 }
3174 
3175 /*
3176  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3177  * given speed.
3178  */
3179 static int
3180 port_mword(struct port_info *pi, uint32_t speed)
3181 {
3182 
3183 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3184 	MPASS(powerof2(speed));
3185 
3186 	switch(pi->port_type) {
3187 	case FW_PORT_TYPE_BT_SGMII:
3188 	case FW_PORT_TYPE_BT_XFI:
3189 	case FW_PORT_TYPE_BT_XAUI:
3190 		/* BaseT */
3191 		switch (speed) {
3192 		case FW_PORT_CAP32_SPEED_100M:
3193 			return (IFM_100_T);
3194 		case FW_PORT_CAP32_SPEED_1G:
3195 			return (IFM_1000_T);
3196 		case FW_PORT_CAP32_SPEED_10G:
3197 			return (IFM_10G_T);
3198 		}
3199 		break;
3200 	case FW_PORT_TYPE_KX4:
3201 		if (speed == FW_PORT_CAP32_SPEED_10G)
3202 			return (IFM_10G_KX4);
3203 		break;
3204 	case FW_PORT_TYPE_CX4:
3205 		if (speed == FW_PORT_CAP32_SPEED_10G)
3206 			return (IFM_10G_CX4);
3207 		break;
3208 	case FW_PORT_TYPE_KX:
3209 		if (speed == FW_PORT_CAP32_SPEED_1G)
3210 			return (IFM_1000_KX);
3211 		break;
3212 	case FW_PORT_TYPE_KR:
3213 	case FW_PORT_TYPE_BP_AP:
3214 	case FW_PORT_TYPE_BP4_AP:
3215 	case FW_PORT_TYPE_BP40_BA:
3216 	case FW_PORT_TYPE_KR4_100G:
3217 	case FW_PORT_TYPE_KR_SFP28:
3218 	case FW_PORT_TYPE_KR_XLAUI:
3219 		switch (speed) {
3220 		case FW_PORT_CAP32_SPEED_1G:
3221 			return (IFM_1000_KX);
3222 		case FW_PORT_CAP32_SPEED_10G:
3223 			return (IFM_10G_KR);
3224 		case FW_PORT_CAP32_SPEED_25G:
3225 			return (IFM_25G_KR);
3226 		case FW_PORT_CAP32_SPEED_40G:
3227 			return (IFM_40G_KR4);
3228 		case FW_PORT_CAP32_SPEED_50G:
3229 			return (IFM_50G_KR2);
3230 		case FW_PORT_CAP32_SPEED_100G:
3231 			return (IFM_100G_KR4);
3232 		}
3233 		break;
3234 	case FW_PORT_TYPE_FIBER_XFI:
3235 	case FW_PORT_TYPE_FIBER_XAUI:
3236 	case FW_PORT_TYPE_SFP:
3237 	case FW_PORT_TYPE_QSFP_10G:
3238 	case FW_PORT_TYPE_QSA:
3239 	case FW_PORT_TYPE_QSFP:
3240 	case FW_PORT_TYPE_CR4_QSFP:
3241 	case FW_PORT_TYPE_CR_QSFP:
3242 	case FW_PORT_TYPE_CR2_QSFP:
3243 	case FW_PORT_TYPE_SFP28:
3244 		/* Pluggable transceiver */
3245 		switch (pi->mod_type) {
3246 		case FW_PORT_MOD_TYPE_LR:
3247 			switch (speed) {
3248 			case FW_PORT_CAP32_SPEED_1G:
3249 				return (IFM_1000_LX);
3250 			case FW_PORT_CAP32_SPEED_10G:
3251 				return (IFM_10G_LR);
3252 			case FW_PORT_CAP32_SPEED_25G:
3253 				return (IFM_25G_LR);
3254 			case FW_PORT_CAP32_SPEED_40G:
3255 				return (IFM_40G_LR4);
3256 			case FW_PORT_CAP32_SPEED_50G:
3257 				return (IFM_50G_LR2);
3258 			case FW_PORT_CAP32_SPEED_100G:
3259 				return (IFM_100G_LR4);
3260 			}
3261 			break;
3262 		case FW_PORT_MOD_TYPE_SR:
3263 			switch (speed) {
3264 			case FW_PORT_CAP32_SPEED_1G:
3265 				return (IFM_1000_SX);
3266 			case FW_PORT_CAP32_SPEED_10G:
3267 				return (IFM_10G_SR);
3268 			case FW_PORT_CAP32_SPEED_25G:
3269 				return (IFM_25G_SR);
3270 			case FW_PORT_CAP32_SPEED_40G:
3271 				return (IFM_40G_SR4);
3272 			case FW_PORT_CAP32_SPEED_50G:
3273 				return (IFM_50G_SR2);
3274 			case FW_PORT_CAP32_SPEED_100G:
3275 				return (IFM_100G_SR4);
3276 			}
3277 			break;
3278 		case FW_PORT_MOD_TYPE_ER:
3279 			if (speed == FW_PORT_CAP32_SPEED_10G)
3280 				return (IFM_10G_ER);
3281 			break;
3282 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3283 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3284 			switch (speed) {
3285 			case FW_PORT_CAP32_SPEED_1G:
3286 				return (IFM_1000_CX);
3287 			case FW_PORT_CAP32_SPEED_10G:
3288 				return (IFM_10G_TWINAX);
3289 			case FW_PORT_CAP32_SPEED_25G:
3290 				return (IFM_25G_CR);
3291 			case FW_PORT_CAP32_SPEED_40G:
3292 				return (IFM_40G_CR4);
3293 			case FW_PORT_CAP32_SPEED_50G:
3294 				return (IFM_50G_CR2);
3295 			case FW_PORT_CAP32_SPEED_100G:
3296 				return (IFM_100G_CR4);
3297 			}
3298 			break;
3299 		case FW_PORT_MOD_TYPE_LRM:
3300 			if (speed == FW_PORT_CAP32_SPEED_10G)
3301 				return (IFM_10G_LRM);
3302 			break;
3303 		case FW_PORT_MOD_TYPE_NA:
3304 			MPASS(0);	/* Not pluggable? */
3305 			/* fall throough */
3306 		case FW_PORT_MOD_TYPE_ERROR:
3307 		case FW_PORT_MOD_TYPE_UNKNOWN:
3308 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3309 			break;
3310 		case FW_PORT_MOD_TYPE_NONE:
3311 			return (IFM_NONE);
3312 		}
3313 		break;
3314 	case FW_PORT_TYPE_NONE:
3315 		return (IFM_NONE);
3316 	}
3317 
3318 	return (IFM_UNKNOWN);
3319 }
3320 
3321 void
3322 cxgbe_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
3323 {
3324 	struct vi_info *vi = ifp->if_softc;
3325 	struct port_info *pi = vi->pi;
3326 	struct adapter *sc = pi->adapter;
3327 	struct link_config *lc = &pi->link_cfg;
3328 
3329 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4med") != 0)
3330 		return;
3331 	PORT_LOCK(pi);
3332 
3333 	if (pi->up_vis == 0) {
3334 		/*
3335 		 * If all the interfaces are administratively down the firmware
3336 		 * does not report transceiver changes.  Refresh port info here
3337 		 * so that ifconfig displays accurate ifmedia at all times.
3338 		 * This is the only reason we have a synchronized op in this
3339 		 * function.  Just PORT_LOCK would have been enough otherwise.
3340 		 */
3341 		t4_update_port_info(pi);
3342 		build_medialist(pi);
3343 	}
3344 
3345 	/* ifm_status */
3346 	ifmr->ifm_status = IFM_AVALID;
3347 	if (lc->link_ok == false)
3348 		goto done;
3349 	ifmr->ifm_status |= IFM_ACTIVE;
3350 
3351 	/* ifm_active */
3352 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3353 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3354 	if (lc->fc & PAUSE_RX)
3355 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3356 	if (lc->fc & PAUSE_TX)
3357 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3358 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3359 done:
3360 	PORT_UNLOCK(pi);
3361 	end_synchronized_op(sc, 0);
3362 }
3363 
3364 static int
3365 vcxgbe_probe(device_t dev)
3366 {
3367 	char buf[128];
3368 	struct vi_info *vi = device_get_softc(dev);
3369 
3370 	snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
3371 	    vi - vi->pi->vi);
3372 	device_set_desc_copy(dev, buf);
3373 
3374 	return (BUS_PROBE_DEFAULT);
3375 }
3376 
3377 static int
3378 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3379 {
3380 	int func, index, rc;
3381 	uint32_t param, val;
3382 
3383 	ASSERT_SYNCHRONIZED_OP(sc);
3384 
3385 	index = vi - pi->vi;
3386 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3387 	KASSERT(index < nitems(vi_mac_funcs),
3388 	    ("%s: VI %s doesn't have a MAC func", __func__,
3389 	    device_get_nameunit(vi->dev)));
3390 	func = vi_mac_funcs[index];
3391 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3392 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3393 	if (rc < 0) {
3394 		CH_ERR(vi, "failed to allocate virtual interface %d"
3395 		    "for port %d: %d\n", index, pi->port_id, -rc);
3396 		return (-rc);
3397 	}
3398 	vi->viid = rc;
3399 
3400 	if (vi->rss_size == 1) {
3401 		/*
3402 		 * This VI didn't get a slice of the RSS table.  Reduce the
3403 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3404 		 * configuration file (nvi, rssnvi for this PF) if this is a
3405 		 * problem.
3406 		 */
3407 		device_printf(vi->dev, "RSS table not available.\n");
3408 		vi->rss_base = 0xffff;
3409 
3410 		return (0);
3411 	}
3412 
3413 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3414 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3415 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3416 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3417 	if (rc)
3418 		vi->rss_base = 0xffff;
3419 	else {
3420 		MPASS((val >> 16) == vi->rss_size);
3421 		vi->rss_base = val & 0xffff;
3422 	}
3423 
3424 	return (0);
3425 }
3426 
3427 static int
3428 vcxgbe_attach(device_t dev)
3429 {
3430 	struct vi_info *vi;
3431 	struct port_info *pi;
3432 	struct adapter *sc;
3433 	int rc;
3434 
3435 	vi = device_get_softc(dev);
3436 	pi = vi->pi;
3437 	sc = pi->adapter;
3438 
3439 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3440 	if (rc)
3441 		return (rc);
3442 	rc = alloc_extra_vi(sc, pi, vi);
3443 	end_synchronized_op(sc, 0);
3444 	if (rc)
3445 		return (rc);
3446 
3447 	rc = cxgbe_vi_attach(dev, vi);
3448 	if (rc) {
3449 		t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3450 		return (rc);
3451 	}
3452 	return (0);
3453 }
3454 
3455 static int
3456 vcxgbe_detach(device_t dev)
3457 {
3458 	struct vi_info *vi;
3459 	struct adapter *sc;
3460 
3461 	vi = device_get_softc(dev);
3462 	sc = vi->adapter;
3463 
3464 	doom_vi(sc, vi);
3465 
3466 	cxgbe_vi_detach(vi);
3467 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3468 
3469 	end_synchronized_op(sc, 0);
3470 
3471 	return (0);
3472 }
3473 
3474 static struct callout fatal_callout;
3475 static struct taskqueue *reset_tq;
3476 
3477 static void
3478 delayed_panic(void *arg)
3479 {
3480 	struct adapter *sc = arg;
3481 
3482 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3483 }
3484 
3485 void
3486 t4_fatal_err(struct adapter *sc, bool fw_error)
3487 {
3488 
3489 	t4_shutdown_adapter(sc);
3490 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped.\n",
3491 	    device_get_nameunit(sc->dev));
3492 	if (fw_error) {
3493 		if (sc->flags & CHK_MBOX_ACCESS)
3494 			ASSERT_SYNCHRONIZED_OP(sc);
3495 		sc->flags |= ADAP_ERR;
3496 	} else {
3497 		ADAPTER_LOCK(sc);
3498 		sc->flags |= ADAP_ERR;
3499 		ADAPTER_UNLOCK(sc);
3500 	}
3501 #ifdef TCP_OFFLOAD
3502 	taskqueue_enqueue(taskqueue_thread, &sc->async_event_task);
3503 #endif
3504 
3505 	if (t4_panic_on_fatal_err) {
3506 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3507 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3508 	} else if (t4_reset_on_fatal_err) {
3509 		CH_ALERT(sc, "resetting on fatal error.\n");
3510 		taskqueue_enqueue(reset_tq, &sc->reset_task);
3511 	}
3512 }
3513 
3514 void
3515 t4_add_adapter(struct adapter *sc)
3516 {
3517 	sx_xlock(&t4_list_lock);
3518 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3519 	sx_xunlock(&t4_list_lock);
3520 }
3521 
3522 int
3523 t4_map_bars_0_and_4(struct adapter *sc)
3524 {
3525 	sc->regs_rid = PCIR_BAR(0);
3526 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3527 	    &sc->regs_rid, RF_ACTIVE);
3528 	if (sc->regs_res == NULL) {
3529 		device_printf(sc->dev, "cannot map registers.\n");
3530 		return (ENXIO);
3531 	}
3532 	sc->bt = rman_get_bustag(sc->regs_res);
3533 	sc->bh = rman_get_bushandle(sc->regs_res);
3534 	sc->mmio_len = rman_get_size(sc->regs_res);
3535 	setbit(&sc->doorbells, DOORBELL_KDB);
3536 
3537 	sc->msix_rid = PCIR_BAR(4);
3538 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3539 	    &sc->msix_rid, RF_ACTIVE);
3540 	if (sc->msix_res == NULL) {
3541 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3542 		return (ENXIO);
3543 	}
3544 
3545 	return (0);
3546 }
3547 
3548 int
3549 t4_map_bar_2(struct adapter *sc)
3550 {
3551 
3552 	/*
3553 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3554 	 * to map it if RDMA is disabled.
3555 	 */
3556 	if (is_t4(sc) && sc->rdmacaps == 0)
3557 		return (0);
3558 
3559 	sc->udbs_rid = PCIR_BAR(2);
3560 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3561 	    &sc->udbs_rid, RF_ACTIVE);
3562 	if (sc->udbs_res == NULL) {
3563 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3564 		return (ENXIO);
3565 	}
3566 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3567 
3568 	if (chip_id(sc) >= CHELSIO_T5) {
3569 		setbit(&sc->doorbells, DOORBELL_UDB);
3570 #if defined(__i386__) || defined(__amd64__)
3571 		if (t5_write_combine) {
3572 			int rc, mode;
3573 
3574 			/*
3575 			 * Enable write combining on BAR2.  This is the
3576 			 * userspace doorbell BAR and is split into 128B
3577 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3578 			 * with an egress queue.  The first 64B has the doorbell
3579 			 * and the second 64B can be used to submit a tx work
3580 			 * request with an implicit doorbell.
3581 			 */
3582 
3583 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3584 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3585 			if (rc == 0) {
3586 				clrbit(&sc->doorbells, DOORBELL_UDB);
3587 				setbit(&sc->doorbells, DOORBELL_WCWR);
3588 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3589 			} else {
3590 				device_printf(sc->dev,
3591 				    "couldn't enable write combining: %d\n",
3592 				    rc);
3593 			}
3594 
3595 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3596 			t4_write_reg(sc, A_SGE_STAT_CFG,
3597 			    V_STATSOURCE_T5(7) | mode);
3598 		}
3599 #endif
3600 	}
3601 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3602 
3603 	return (0);
3604 }
3605 
3606 struct memwin_init {
3607 	uint32_t base;
3608 	uint32_t aperture;
3609 };
3610 
3611 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3612 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3613 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3614 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3615 };
3616 
3617 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3618 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3619 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3620 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3621 };
3622 
3623 static void
3624 setup_memwin(struct adapter *sc)
3625 {
3626 	const struct memwin_init *mw_init;
3627 	struct memwin *mw;
3628 	int i;
3629 	uint32_t bar0;
3630 
3631 	if (is_t4(sc)) {
3632 		/*
3633 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3634 		 * mechanism.  Works from within PCI passthrough environments
3635 		 * too, where rman_get_start() can return a different value.  We
3636 		 * need to program the T4 memory window decoders with the actual
3637 		 * addresses that will be coming across the PCIe link.
3638 		 */
3639 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3640 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3641 
3642 		mw_init = &t4_memwin[0];
3643 	} else {
3644 		/* T5+ use the relative offset inside the PCIe BAR */
3645 		bar0 = 0;
3646 
3647 		mw_init = &t5_memwin[0];
3648 	}
3649 
3650 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3651 		if (!rw_initialized(&mw->mw_lock)) {
3652 			rw_init(&mw->mw_lock, "memory window access");
3653 			mw->mw_base = mw_init->base;
3654 			mw->mw_aperture = mw_init->aperture;
3655 			mw->mw_curpos = 0;
3656 		}
3657 		t4_write_reg(sc,
3658 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3659 		    (mw->mw_base + bar0) | V_BIR(0) |
3660 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3661 		rw_wlock(&mw->mw_lock);
3662 		position_memwin(sc, i, mw->mw_curpos);
3663 		rw_wunlock(&mw->mw_lock);
3664 	}
3665 
3666 	/* flush */
3667 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3668 }
3669 
3670 /*
3671  * Positions the memory window at the given address in the card's address space.
3672  * There are some alignment requirements and the actual position may be at an
3673  * address prior to the requested address.  mw->mw_curpos always has the actual
3674  * position of the window.
3675  */
3676 static void
3677 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3678 {
3679 	struct memwin *mw;
3680 	uint32_t pf;
3681 	uint32_t reg;
3682 
3683 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3684 	mw = &sc->memwin[idx];
3685 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3686 
3687 	if (is_t4(sc)) {
3688 		pf = 0;
3689 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3690 	} else {
3691 		pf = V_PFNUM(sc->pf);
3692 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3693 	}
3694 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3695 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3696 	t4_read_reg(sc, reg);	/* flush */
3697 }
3698 
3699 int
3700 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3701     int len, int rw)
3702 {
3703 	struct memwin *mw;
3704 	uint32_t mw_end, v;
3705 
3706 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3707 
3708 	/* Memory can only be accessed in naturally aligned 4 byte units */
3709 	if (addr & 3 || len & 3 || len <= 0)
3710 		return (EINVAL);
3711 
3712 	mw = &sc->memwin[idx];
3713 	while (len > 0) {
3714 		rw_rlock(&mw->mw_lock);
3715 		mw_end = mw->mw_curpos + mw->mw_aperture;
3716 		if (addr >= mw_end || addr < mw->mw_curpos) {
3717 			/* Will need to reposition the window */
3718 			if (!rw_try_upgrade(&mw->mw_lock)) {
3719 				rw_runlock(&mw->mw_lock);
3720 				rw_wlock(&mw->mw_lock);
3721 			}
3722 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3723 			position_memwin(sc, idx, addr);
3724 			rw_downgrade(&mw->mw_lock);
3725 			mw_end = mw->mw_curpos + mw->mw_aperture;
3726 		}
3727 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3728 		while (addr < mw_end && len > 0) {
3729 			if (rw == 0) {
3730 				v = t4_read_reg(sc, mw->mw_base + addr -
3731 				    mw->mw_curpos);
3732 				*val++ = le32toh(v);
3733 			} else {
3734 				v = *val++;
3735 				t4_write_reg(sc, mw->mw_base + addr -
3736 				    mw->mw_curpos, htole32(v));
3737 			}
3738 			addr += 4;
3739 			len -= 4;
3740 		}
3741 		rw_runlock(&mw->mw_lock);
3742 	}
3743 
3744 	return (0);
3745 }
3746 
3747 static void
3748 t4_init_atid_table(struct adapter *sc)
3749 {
3750 	struct tid_info *t;
3751 	int i;
3752 
3753 	t = &sc->tids;
3754 	if (t->natids == 0)
3755 		return;
3756 
3757 	MPASS(t->atid_tab == NULL);
3758 
3759 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3760 	    M_ZERO | M_WAITOK);
3761 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3762 	t->afree = t->atid_tab;
3763 	t->atids_in_use = 0;
3764 	for (i = 1; i < t->natids; i++)
3765 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3766 	t->atid_tab[t->natids - 1].next = NULL;
3767 }
3768 
3769 static void
3770 t4_free_atid_table(struct adapter *sc)
3771 {
3772 	struct tid_info *t;
3773 
3774 	t = &sc->tids;
3775 
3776 	KASSERT(t->atids_in_use == 0,
3777 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3778 
3779 	if (mtx_initialized(&t->atid_lock))
3780 		mtx_destroy(&t->atid_lock);
3781 	free(t->atid_tab, M_CXGBE);
3782 	t->atid_tab = NULL;
3783 }
3784 
3785 int
3786 alloc_atid(struct adapter *sc, void *ctx)
3787 {
3788 	struct tid_info *t = &sc->tids;
3789 	int atid = -1;
3790 
3791 	mtx_lock(&t->atid_lock);
3792 	if (t->afree) {
3793 		union aopen_entry *p = t->afree;
3794 
3795 		atid = p - t->atid_tab;
3796 		MPASS(atid <= M_TID_TID);
3797 		t->afree = p->next;
3798 		p->data = ctx;
3799 		t->atids_in_use++;
3800 	}
3801 	mtx_unlock(&t->atid_lock);
3802 	return (atid);
3803 }
3804 
3805 void *
3806 lookup_atid(struct adapter *sc, int atid)
3807 {
3808 	struct tid_info *t = &sc->tids;
3809 
3810 	return (t->atid_tab[atid].data);
3811 }
3812 
3813 void
3814 free_atid(struct adapter *sc, int atid)
3815 {
3816 	struct tid_info *t = &sc->tids;
3817 	union aopen_entry *p = &t->atid_tab[atid];
3818 
3819 	mtx_lock(&t->atid_lock);
3820 	p->next = t->afree;
3821 	t->afree = p;
3822 	t->atids_in_use--;
3823 	mtx_unlock(&t->atid_lock);
3824 }
3825 
3826 static void
3827 queue_tid_release(struct adapter *sc, int tid)
3828 {
3829 
3830 	CXGBE_UNIMPLEMENTED("deferred tid release");
3831 }
3832 
3833 void
3834 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
3835 {
3836 	struct wrqe *wr;
3837 	struct cpl_tid_release *req;
3838 
3839 	wr = alloc_wrqe(sizeof(*req), ctrlq);
3840 	if (wr == NULL) {
3841 		queue_tid_release(sc, tid);	/* defer */
3842 		return;
3843 	}
3844 	req = wrtod(wr);
3845 
3846 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
3847 
3848 	t4_wrq_tx(sc, wr);
3849 }
3850 
3851 static int
3852 t4_range_cmp(const void *a, const void *b)
3853 {
3854 	return ((const struct t4_range *)a)->start -
3855 	       ((const struct t4_range *)b)->start;
3856 }
3857 
3858 /*
3859  * Verify that the memory range specified by the addr/len pair is valid within
3860  * the card's address space.
3861  */
3862 static int
3863 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
3864 {
3865 	struct t4_range mem_ranges[4], *r, *next;
3866 	uint32_t em, addr_len;
3867 	int i, n, remaining;
3868 
3869 	/* Memory can only be accessed in naturally aligned 4 byte units */
3870 	if (addr & 3 || len & 3 || len == 0)
3871 		return (EINVAL);
3872 
3873 	/* Enabled memories */
3874 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
3875 
3876 	r = &mem_ranges[0];
3877 	n = 0;
3878 	bzero(r, sizeof(mem_ranges));
3879 	if (em & F_EDRAM0_ENABLE) {
3880 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
3881 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
3882 		if (r->size > 0) {
3883 			r->start = G_EDRAM0_BASE(addr_len) << 20;
3884 			if (addr >= r->start &&
3885 			    addr + len <= r->start + r->size)
3886 				return (0);
3887 			r++;
3888 			n++;
3889 		}
3890 	}
3891 	if (em & F_EDRAM1_ENABLE) {
3892 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
3893 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
3894 		if (r->size > 0) {
3895 			r->start = G_EDRAM1_BASE(addr_len) << 20;
3896 			if (addr >= r->start &&
3897 			    addr + len <= r->start + r->size)
3898 				return (0);
3899 			r++;
3900 			n++;
3901 		}
3902 	}
3903 	if (em & F_EXT_MEM_ENABLE) {
3904 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
3905 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
3906 		if (r->size > 0) {
3907 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
3908 			if (addr >= r->start &&
3909 			    addr + len <= r->start + r->size)
3910 				return (0);
3911 			r++;
3912 			n++;
3913 		}
3914 	}
3915 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
3916 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
3917 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
3918 		if (r->size > 0) {
3919 			r->start = G_EXT_MEM1_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 	MPASS(n <= nitems(mem_ranges));
3928 
3929 	if (n > 1) {
3930 		/* Sort and merge the ranges. */
3931 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
3932 
3933 		/* Start from index 0 and examine the next n - 1 entries. */
3934 		r = &mem_ranges[0];
3935 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
3936 
3937 			MPASS(r->size > 0);	/* r is a valid entry. */
3938 			next = r + 1;
3939 			MPASS(next->size > 0);	/* and so is the next one. */
3940 
3941 			while (r->start + r->size >= next->start) {
3942 				/* Merge the next one into the current entry. */
3943 				r->size = max(r->start + r->size,
3944 				    next->start + next->size) - r->start;
3945 				n--;	/* One fewer entry in total. */
3946 				if (--remaining == 0)
3947 					goto done;	/* short circuit */
3948 				next++;
3949 			}
3950 			if (next != r + 1) {
3951 				/*
3952 				 * Some entries were merged into r and next
3953 				 * points to the first valid entry that couldn't
3954 				 * be merged.
3955 				 */
3956 				MPASS(next->size > 0);	/* must be valid */
3957 				memcpy(r + 1, next, remaining * sizeof(*r));
3958 #ifdef INVARIANTS
3959 				/*
3960 				 * This so that the foo->size assertion in the
3961 				 * next iteration of the loop do the right
3962 				 * thing for entries that were pulled up and are
3963 				 * no longer valid.
3964 				 */
3965 				MPASS(n < nitems(mem_ranges));
3966 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
3967 				    sizeof(struct t4_range));
3968 #endif
3969 			}
3970 		}
3971 done:
3972 		/* Done merging the ranges. */
3973 		MPASS(n > 0);
3974 		r = &mem_ranges[0];
3975 		for (i = 0; i < n; i++, r++) {
3976 			if (addr >= r->start &&
3977 			    addr + len <= r->start + r->size)
3978 				return (0);
3979 		}
3980 	}
3981 
3982 	return (EFAULT);
3983 }
3984 
3985 static int
3986 fwmtype_to_hwmtype(int mtype)
3987 {
3988 
3989 	switch (mtype) {
3990 	case FW_MEMTYPE_EDC0:
3991 		return (MEM_EDC0);
3992 	case FW_MEMTYPE_EDC1:
3993 		return (MEM_EDC1);
3994 	case FW_MEMTYPE_EXTMEM:
3995 		return (MEM_MC0);
3996 	case FW_MEMTYPE_EXTMEM1:
3997 		return (MEM_MC1);
3998 	default:
3999 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4000 	}
4001 }
4002 
4003 /*
4004  * Verify that the memory range specified by the memtype/offset/len pair is
4005  * valid and lies entirely within the memtype specified.  The global address of
4006  * the start of the range is returned in addr.
4007  */
4008 static int
4009 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4010     uint32_t *addr)
4011 {
4012 	uint32_t em, addr_len, maddr;
4013 
4014 	/* Memory can only be accessed in naturally aligned 4 byte units */
4015 	if (off & 3 || len & 3 || len == 0)
4016 		return (EINVAL);
4017 
4018 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4019 	switch (fwmtype_to_hwmtype(mtype)) {
4020 	case MEM_EDC0:
4021 		if (!(em & F_EDRAM0_ENABLE))
4022 			return (EINVAL);
4023 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4024 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4025 		break;
4026 	case MEM_EDC1:
4027 		if (!(em & F_EDRAM1_ENABLE))
4028 			return (EINVAL);
4029 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4030 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4031 		break;
4032 	case MEM_MC:
4033 		if (!(em & F_EXT_MEM_ENABLE))
4034 			return (EINVAL);
4035 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4036 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4037 		break;
4038 	case MEM_MC1:
4039 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4040 			return (EINVAL);
4041 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4042 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4043 		break;
4044 	default:
4045 		return (EINVAL);
4046 	}
4047 
4048 	*addr = maddr + off;	/* global address */
4049 	return (validate_mem_range(sc, *addr, len));
4050 }
4051 
4052 static int
4053 fixup_devlog_params(struct adapter *sc)
4054 {
4055 	struct devlog_params *dparams = &sc->params.devlog;
4056 	int rc;
4057 
4058 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4059 	    dparams->size, &dparams->addr);
4060 
4061 	return (rc);
4062 }
4063 
4064 static void
4065 update_nirq(struct intrs_and_queues *iaq, int nports)
4066 {
4067 
4068 	iaq->nirq = T4_EXTRA_INTR;
4069 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4070 	iaq->nirq += nports * iaq->nofldrxq;
4071 	iaq->nirq += nports * (iaq->num_vis - 1) *
4072 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4073 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4074 }
4075 
4076 /*
4077  * Adjust requirements to fit the number of interrupts available.
4078  */
4079 static void
4080 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4081     int navail)
4082 {
4083 	int old_nirq;
4084 	const int nports = sc->params.nports;
4085 
4086 	MPASS(nports > 0);
4087 	MPASS(navail > 0);
4088 
4089 	bzero(iaq, sizeof(*iaq));
4090 	iaq->intr_type = itype;
4091 	iaq->num_vis = t4_num_vis;
4092 	iaq->ntxq = t4_ntxq;
4093 	iaq->ntxq_vi = t4_ntxq_vi;
4094 	iaq->nrxq = t4_nrxq;
4095 	iaq->nrxq_vi = t4_nrxq_vi;
4096 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4097 	if (is_offload(sc) || is_ethoffload(sc)) {
4098 		iaq->nofldtxq = t4_nofldtxq;
4099 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4100 	}
4101 #endif
4102 #ifdef TCP_OFFLOAD
4103 	if (is_offload(sc)) {
4104 		iaq->nofldrxq = t4_nofldrxq;
4105 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4106 	}
4107 #endif
4108 #ifdef DEV_NETMAP
4109 	if (t4_native_netmap & NN_MAIN_VI) {
4110 		iaq->nnmtxq = t4_nnmtxq;
4111 		iaq->nnmrxq = t4_nnmrxq;
4112 	}
4113 	if (t4_native_netmap & NN_EXTRA_VI) {
4114 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4115 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4116 	}
4117 #endif
4118 
4119 	update_nirq(iaq, nports);
4120 	if (iaq->nirq <= navail &&
4121 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4122 		/*
4123 		 * This is the normal case -- there are enough interrupts for
4124 		 * everything.
4125 		 */
4126 		goto done;
4127 	}
4128 
4129 	/*
4130 	 * If extra VIs have been configured try reducing their count and see if
4131 	 * that works.
4132 	 */
4133 	while (iaq->num_vis > 1) {
4134 		iaq->num_vis--;
4135 		update_nirq(iaq, nports);
4136 		if (iaq->nirq <= navail &&
4137 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4138 			device_printf(sc->dev, "virtual interfaces per port "
4139 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4140 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4141 			    "itype %d, navail %u, nirq %d.\n",
4142 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4143 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4144 			    itype, navail, iaq->nirq);
4145 			goto done;
4146 		}
4147 	}
4148 
4149 	/*
4150 	 * Extra VIs will not be created.  Log a message if they were requested.
4151 	 */
4152 	MPASS(iaq->num_vis == 1);
4153 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4154 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4155 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4156 	if (iaq->num_vis != t4_num_vis) {
4157 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4158 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4159 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4160 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4161 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4162 	}
4163 
4164 	/*
4165 	 * Keep reducing the number of NIC rx queues to the next lower power of
4166 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4167 	 * if that works.
4168 	 */
4169 	do {
4170 		if (iaq->nrxq > 1) {
4171 			do {
4172 				iaq->nrxq--;
4173 			} while (!powerof2(iaq->nrxq));
4174 			if (iaq->nnmrxq > iaq->nrxq)
4175 				iaq->nnmrxq = iaq->nrxq;
4176 		}
4177 		if (iaq->nofldrxq > 1)
4178 			iaq->nofldrxq >>= 1;
4179 
4180 		old_nirq = iaq->nirq;
4181 		update_nirq(iaq, nports);
4182 		if (iaq->nirq <= navail &&
4183 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4184 			device_printf(sc->dev, "running with reduced number of "
4185 			    "rx queues because of shortage of interrupts.  "
4186 			    "nrxq=%u, nofldrxq=%u.  "
4187 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4188 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4189 			goto done;
4190 		}
4191 	} while (old_nirq != iaq->nirq);
4192 
4193 	/* One interrupt for everything.  Ugh. */
4194 	device_printf(sc->dev, "running with minimal number of queues.  "
4195 	    "itype %d, navail %u.\n", itype, navail);
4196 	iaq->nirq = 1;
4197 	iaq->nrxq = 1;
4198 	iaq->ntxq = 1;
4199 	if (iaq->nofldrxq > 0) {
4200 		iaq->nofldrxq = 1;
4201 		iaq->nofldtxq = 1;
4202 	}
4203 	iaq->nnmtxq = 0;
4204 	iaq->nnmrxq = 0;
4205 done:
4206 	MPASS(iaq->num_vis > 0);
4207 	if (iaq->num_vis > 1) {
4208 		MPASS(iaq->nrxq_vi > 0);
4209 		MPASS(iaq->ntxq_vi > 0);
4210 	}
4211 	MPASS(iaq->nirq > 0);
4212 	MPASS(iaq->nrxq > 0);
4213 	MPASS(iaq->ntxq > 0);
4214 	if (itype == INTR_MSI) {
4215 		MPASS(powerof2(iaq->nirq));
4216 	}
4217 }
4218 
4219 static int
4220 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4221 {
4222 	int rc, itype, navail, nalloc;
4223 
4224 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4225 
4226 		if ((itype & t4_intr_types) == 0)
4227 			continue;	/* not allowed */
4228 
4229 		if (itype == INTR_MSIX)
4230 			navail = pci_msix_count(sc->dev);
4231 		else if (itype == INTR_MSI)
4232 			navail = pci_msi_count(sc->dev);
4233 		else
4234 			navail = 1;
4235 restart:
4236 		if (navail == 0)
4237 			continue;
4238 
4239 		calculate_iaq(sc, iaq, itype, navail);
4240 		nalloc = iaq->nirq;
4241 		rc = 0;
4242 		if (itype == INTR_MSIX)
4243 			rc = pci_alloc_msix(sc->dev, &nalloc);
4244 		else if (itype == INTR_MSI)
4245 			rc = pci_alloc_msi(sc->dev, &nalloc);
4246 
4247 		if (rc == 0 && nalloc > 0) {
4248 			if (nalloc == iaq->nirq)
4249 				return (0);
4250 
4251 			/*
4252 			 * Didn't get the number requested.  Use whatever number
4253 			 * the kernel is willing to allocate.
4254 			 */
4255 			device_printf(sc->dev, "fewer vectors than requested, "
4256 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4257 			    itype, iaq->nirq, nalloc);
4258 			pci_release_msi(sc->dev);
4259 			navail = nalloc;
4260 			goto restart;
4261 		}
4262 
4263 		device_printf(sc->dev,
4264 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4265 		    itype, rc, iaq->nirq, nalloc);
4266 	}
4267 
4268 	device_printf(sc->dev,
4269 	    "failed to find a usable interrupt type.  "
4270 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4271 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4272 
4273 	return (ENXIO);
4274 }
4275 
4276 #define FW_VERSION(chip) ( \
4277     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4278     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4279     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4280     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4281 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4282 
4283 /* Just enough of fw_hdr to cover all version info. */
4284 struct fw_h {
4285 	__u8	ver;
4286 	__u8	chip;
4287 	__be16	len512;
4288 	__be32	fw_ver;
4289 	__be32	tp_microcode_ver;
4290 	__u8	intfver_nic;
4291 	__u8	intfver_vnic;
4292 	__u8	intfver_ofld;
4293 	__u8	intfver_ri;
4294 	__u8	intfver_iscsipdu;
4295 	__u8	intfver_iscsi;
4296 	__u8	intfver_fcoepdu;
4297 	__u8	intfver_fcoe;
4298 };
4299 /* Spot check a couple of fields. */
4300 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4301 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4302 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4303 
4304 struct fw_info {
4305 	uint8_t chip;
4306 	char *kld_name;
4307 	char *fw_mod_name;
4308 	struct fw_h fw_h;
4309 } fw_info[] = {
4310 	{
4311 		.chip = CHELSIO_T4,
4312 		.kld_name = "t4fw_cfg",
4313 		.fw_mod_name = "t4fw",
4314 		.fw_h = {
4315 			.chip = FW_HDR_CHIP_T4,
4316 			.fw_ver = htobe32(FW_VERSION(T4)),
4317 			.intfver_nic = FW_INTFVER(T4, NIC),
4318 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4319 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4320 			.intfver_ri = FW_INTFVER(T4, RI),
4321 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4322 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4323 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4324 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4325 		},
4326 	}, {
4327 		.chip = CHELSIO_T5,
4328 		.kld_name = "t5fw_cfg",
4329 		.fw_mod_name = "t5fw",
4330 		.fw_h = {
4331 			.chip = FW_HDR_CHIP_T5,
4332 			.fw_ver = htobe32(FW_VERSION(T5)),
4333 			.intfver_nic = FW_INTFVER(T5, NIC),
4334 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4335 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4336 			.intfver_ri = FW_INTFVER(T5, RI),
4337 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4338 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4339 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4340 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4341 		},
4342 	}, {
4343 		.chip = CHELSIO_T6,
4344 		.kld_name = "t6fw_cfg",
4345 		.fw_mod_name = "t6fw",
4346 		.fw_h = {
4347 			.chip = FW_HDR_CHIP_T6,
4348 			.fw_ver = htobe32(FW_VERSION(T6)),
4349 			.intfver_nic = FW_INTFVER(T6, NIC),
4350 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4351 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4352 			.intfver_ri = FW_INTFVER(T6, RI),
4353 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4354 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4355 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4356 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4357 		},
4358 	}
4359 };
4360 
4361 static struct fw_info *
4362 find_fw_info(int chip)
4363 {
4364 	int i;
4365 
4366 	for (i = 0; i < nitems(fw_info); i++) {
4367 		if (fw_info[i].chip == chip)
4368 			return (&fw_info[i]);
4369 	}
4370 	return (NULL);
4371 }
4372 
4373 /*
4374  * Is the given firmware API compatible with the one the driver was compiled
4375  * with?
4376  */
4377 static int
4378 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4379 {
4380 
4381 	/* short circuit if it's the exact same firmware version */
4382 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4383 		return (1);
4384 
4385 	/*
4386 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4387 	 * features that are supported in the driver.
4388 	 */
4389 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4390 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4391 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4392 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4393 		return (1);
4394 #undef SAME_INTF
4395 
4396 	return (0);
4397 }
4398 
4399 static int
4400 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4401     const struct firmware **fw)
4402 {
4403 	struct fw_info *fw_info;
4404 
4405 	*dcfg = NULL;
4406 	if (fw != NULL)
4407 		*fw = NULL;
4408 
4409 	fw_info = find_fw_info(chip_id(sc));
4410 	if (fw_info == NULL) {
4411 		device_printf(sc->dev,
4412 		    "unable to look up firmware information for chip %d.\n",
4413 		    chip_id(sc));
4414 		return (EINVAL);
4415 	}
4416 
4417 	*dcfg = firmware_get(fw_info->kld_name);
4418 	if (*dcfg != NULL) {
4419 		if (fw != NULL)
4420 			*fw = firmware_get(fw_info->fw_mod_name);
4421 		return (0);
4422 	}
4423 
4424 	return (ENOENT);
4425 }
4426 
4427 static void
4428 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4429     const struct firmware *fw)
4430 {
4431 
4432 	if (fw != NULL)
4433 		firmware_put(fw, FIRMWARE_UNLOAD);
4434 	if (dcfg != NULL)
4435 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4436 }
4437 
4438 /*
4439  * Return values:
4440  * 0 means no firmware install attempted.
4441  * ERESTART means a firmware install was attempted and was successful.
4442  * +ve errno means a firmware install was attempted but failed.
4443  */
4444 static int
4445 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4446     const struct fw_h *drv_fw, const char *reason, int *already)
4447 {
4448 	const struct firmware *cfg, *fw;
4449 	const uint32_t c = be32toh(card_fw->fw_ver);
4450 	uint32_t d, k;
4451 	int rc, fw_install;
4452 	struct fw_h bundled_fw;
4453 	bool load_attempted;
4454 
4455 	cfg = fw = NULL;
4456 	load_attempted = false;
4457 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4458 
4459 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4460 	if (t4_fw_install < 0) {
4461 		rc = load_fw_module(sc, &cfg, &fw);
4462 		if (rc != 0 || fw == NULL) {
4463 			device_printf(sc->dev,
4464 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4465 			    " will use compiled-in firmware version for"
4466 			    "hw.cxgbe.fw_install checks.\n",
4467 			    rc, cfg, fw);
4468 		} else {
4469 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4470 		}
4471 		load_attempted = true;
4472 	}
4473 	d = be32toh(bundled_fw.fw_ver);
4474 
4475 	if (reason != NULL)
4476 		goto install;
4477 
4478 	if ((sc->flags & FW_OK) == 0) {
4479 
4480 		if (c == 0xffffffff) {
4481 			reason = "missing";
4482 			goto install;
4483 		}
4484 
4485 		rc = 0;
4486 		goto done;
4487 	}
4488 
4489 	if (!fw_compatible(card_fw, &bundled_fw)) {
4490 		reason = "incompatible or unusable";
4491 		goto install;
4492 	}
4493 
4494 	if (d > c) {
4495 		reason = "older than the version bundled with this driver";
4496 		goto install;
4497 	}
4498 
4499 	if (fw_install == 2 && d != c) {
4500 		reason = "different than the version bundled with this driver";
4501 		goto install;
4502 	}
4503 
4504 	/* No reason to do anything to the firmware already on the card. */
4505 	rc = 0;
4506 	goto done;
4507 
4508 install:
4509 	rc = 0;
4510 	if ((*already)++)
4511 		goto done;
4512 
4513 	if (fw_install == 0) {
4514 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4515 		    "but the driver is prohibited from installing a firmware "
4516 		    "on the card.\n",
4517 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4518 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4519 
4520 		goto done;
4521 	}
4522 
4523 	/*
4524 	 * We'll attempt to install a firmware.  Load the module first (if it
4525 	 * hasn't been loaded already).
4526 	 */
4527 	if (!load_attempted) {
4528 		rc = load_fw_module(sc, &cfg, &fw);
4529 		if (rc != 0 || fw == NULL) {
4530 			device_printf(sc->dev,
4531 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4532 			    rc, cfg, fw);
4533 			/* carry on */
4534 		}
4535 	}
4536 	if (fw == NULL) {
4537 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4538 		    "but the driver cannot take corrective action because it "
4539 		    "is unable to load the firmware module.\n",
4540 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4541 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4542 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4543 		goto done;
4544 	}
4545 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4546 	if (k != d) {
4547 		MPASS(t4_fw_install > 0);
4548 		device_printf(sc->dev,
4549 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4550 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4551 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4552 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4553 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4554 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4555 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4556 		goto done;
4557 	}
4558 
4559 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4560 	    "installing firmware %u.%u.%u.%u on card.\n",
4561 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4562 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4563 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4564 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4565 
4566 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4567 	if (rc != 0) {
4568 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4569 	} else {
4570 		/* Installed successfully, update the cached header too. */
4571 		rc = ERESTART;
4572 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4573 	}
4574 done:
4575 	unload_fw_module(sc, cfg, fw);
4576 
4577 	return (rc);
4578 }
4579 
4580 /*
4581  * Establish contact with the firmware and attempt to become the master driver.
4582  *
4583  * A firmware will be installed to the card if needed (if the driver is allowed
4584  * to do so).
4585  */
4586 static int
4587 contact_firmware(struct adapter *sc)
4588 {
4589 	int rc, already = 0;
4590 	enum dev_state state;
4591 	struct fw_info *fw_info;
4592 	struct fw_hdr *card_fw;		/* fw on the card */
4593 	const struct fw_h *drv_fw;
4594 
4595 	fw_info = find_fw_info(chip_id(sc));
4596 	if (fw_info == NULL) {
4597 		device_printf(sc->dev,
4598 		    "unable to look up firmware information for chip %d.\n",
4599 		    chip_id(sc));
4600 		return (EINVAL);
4601 	}
4602 	drv_fw = &fw_info->fw_h;
4603 
4604 	/* Read the header of the firmware on the card */
4605 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4606 restart:
4607 	rc = -t4_get_fw_hdr(sc, card_fw);
4608 	if (rc != 0) {
4609 		device_printf(sc->dev,
4610 		    "unable to read firmware header from card's flash: %d\n",
4611 		    rc);
4612 		goto done;
4613 	}
4614 
4615 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4616 	    &already);
4617 	if (rc == ERESTART)
4618 		goto restart;
4619 	if (rc != 0)
4620 		goto done;
4621 
4622 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4623 	if (rc < 0 || state == DEV_STATE_ERR) {
4624 		rc = -rc;
4625 		device_printf(sc->dev,
4626 		    "failed to connect to the firmware: %d, %d.  "
4627 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4628 #if 0
4629 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4630 		    "not responding properly to HELLO", &already) == ERESTART)
4631 			goto restart;
4632 #endif
4633 		goto done;
4634 	}
4635 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4636 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4637 
4638 	if (rc == sc->pf) {
4639 		sc->flags |= MASTER_PF;
4640 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4641 		    NULL, &already);
4642 		if (rc == ERESTART)
4643 			rc = 0;
4644 		else if (rc != 0)
4645 			goto done;
4646 	} else if (state == DEV_STATE_UNINIT) {
4647 		/*
4648 		 * We didn't get to be the master so we definitely won't be
4649 		 * configuring the chip.  It's a bug if someone else hasn't
4650 		 * configured it already.
4651 		 */
4652 		device_printf(sc->dev, "couldn't be master(%d), "
4653 		    "device not already initialized either(%d).  "
4654 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4655 		rc = EPROTO;
4656 		goto done;
4657 	} else {
4658 		/*
4659 		 * Some other PF is the master and has configured the chip.
4660 		 * This is allowed but untested.
4661 		 */
4662 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4663 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4664 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4665 		sc->cfcsum = 0;
4666 		rc = 0;
4667 	}
4668 done:
4669 	if (rc != 0 && sc->flags & FW_OK) {
4670 		t4_fw_bye(sc, sc->mbox);
4671 		sc->flags &= ~FW_OK;
4672 	}
4673 	free(card_fw, M_CXGBE);
4674 	return (rc);
4675 }
4676 
4677 static int
4678 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4679     uint32_t mtype, uint32_t moff)
4680 {
4681 	struct fw_info *fw_info;
4682 	const struct firmware *dcfg, *rcfg = NULL;
4683 	const uint32_t *cfdata;
4684 	uint32_t cflen, addr;
4685 	int rc;
4686 
4687 	load_fw_module(sc, &dcfg, NULL);
4688 
4689 	/* Card specific interpretation of "default". */
4690 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4691 		if (pci_get_device(sc->dev) == 0x440a)
4692 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4693 		if (is_fpga(sc))
4694 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4695 	}
4696 
4697 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4698 		if (dcfg == NULL) {
4699 			device_printf(sc->dev,
4700 			    "KLD with default config is not available.\n");
4701 			rc = ENOENT;
4702 			goto done;
4703 		}
4704 		cfdata = dcfg->data;
4705 		cflen = dcfg->datasize & ~3;
4706 	} else {
4707 		char s[32];
4708 
4709 		fw_info = find_fw_info(chip_id(sc));
4710 		if (fw_info == NULL) {
4711 			device_printf(sc->dev,
4712 			    "unable to look up firmware information for chip %d.\n",
4713 			    chip_id(sc));
4714 			rc = EINVAL;
4715 			goto done;
4716 		}
4717 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4718 
4719 		rcfg = firmware_get(s);
4720 		if (rcfg == NULL) {
4721 			device_printf(sc->dev,
4722 			    "unable to load module \"%s\" for configuration "
4723 			    "profile \"%s\".\n", s, cfg_file);
4724 			rc = ENOENT;
4725 			goto done;
4726 		}
4727 		cfdata = rcfg->data;
4728 		cflen = rcfg->datasize & ~3;
4729 	}
4730 
4731 	if (cflen > FLASH_CFG_MAX_SIZE) {
4732 		device_printf(sc->dev,
4733 		    "config file too long (%d, max allowed is %d).\n",
4734 		    cflen, FLASH_CFG_MAX_SIZE);
4735 		rc = EINVAL;
4736 		goto done;
4737 	}
4738 
4739 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4740 	if (rc != 0) {
4741 		device_printf(sc->dev,
4742 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4743 		    __func__, mtype, moff, cflen, rc);
4744 		rc = EINVAL;
4745 		goto done;
4746 	}
4747 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4748 done:
4749 	if (rcfg != NULL)
4750 		firmware_put(rcfg, FIRMWARE_UNLOAD);
4751 	unload_fw_module(sc, dcfg, NULL);
4752 	return (rc);
4753 }
4754 
4755 struct caps_allowed {
4756 	uint16_t nbmcaps;
4757 	uint16_t linkcaps;
4758 	uint16_t switchcaps;
4759 	uint16_t niccaps;
4760 	uint16_t toecaps;
4761 	uint16_t rdmacaps;
4762 	uint16_t cryptocaps;
4763 	uint16_t iscsicaps;
4764 	uint16_t fcoecaps;
4765 };
4766 
4767 #define FW_PARAM_DEV(param) \
4768 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4769 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4770 #define FW_PARAM_PFVF(param) \
4771 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4772 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4773 
4774 /*
4775  * Provide a configuration profile to the firmware and have it initialize the
4776  * chip accordingly.  This may involve uploading a configuration file to the
4777  * card.
4778  */
4779 static int
4780 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4781     const struct caps_allowed *caps_allowed)
4782 {
4783 	int rc;
4784 	struct fw_caps_config_cmd caps;
4785 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
4786 
4787 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4788 	if (rc != 0) {
4789 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
4790 		return (rc);
4791 	}
4792 
4793 	bzero(&caps, sizeof(caps));
4794 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4795 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
4796 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
4797 		mtype = 0;
4798 		moff = 0;
4799 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4800 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
4801 		mtype = FW_MEMTYPE_FLASH;
4802 		moff = t4_flash_cfg_addr(sc);
4803 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4804 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4805 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4806 		    FW_LEN16(caps));
4807 	} else {
4808 		/*
4809 		 * Ask the firmware where it wants us to upload the config file.
4810 		 */
4811 		param = FW_PARAM_DEV(CF);
4812 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4813 		if (rc != 0) {
4814 			/* No support for config file?  Shouldn't happen. */
4815 			device_printf(sc->dev,
4816 			    "failed to query config file location: %d.\n", rc);
4817 			goto done;
4818 		}
4819 		mtype = G_FW_PARAMS_PARAM_Y(val);
4820 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
4821 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4822 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4823 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4824 		    FW_LEN16(caps));
4825 
4826 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
4827 		if (rc != 0) {
4828 			device_printf(sc->dev,
4829 			    "failed to upload config file to card: %d.\n", rc);
4830 			goto done;
4831 		}
4832 	}
4833 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
4834 	if (rc != 0) {
4835 		device_printf(sc->dev, "failed to pre-process config file: %d "
4836 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
4837 		goto done;
4838 	}
4839 
4840 	finicsum = be32toh(caps.finicsum);
4841 	cfcsum = be32toh(caps.cfcsum);	/* actual */
4842 	if (finicsum != cfcsum) {
4843 		device_printf(sc->dev,
4844 		    "WARNING: config file checksum mismatch: %08x %08x\n",
4845 		    finicsum, cfcsum);
4846 	}
4847 	sc->cfcsum = cfcsum;
4848 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
4849 
4850 	/*
4851 	 * Let the firmware know what features will (not) be used so it can tune
4852 	 * things accordingly.
4853 	 */
4854 #define LIMIT_CAPS(x) do { \
4855 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
4856 } while (0)
4857 	LIMIT_CAPS(nbm);
4858 	LIMIT_CAPS(link);
4859 	LIMIT_CAPS(switch);
4860 	LIMIT_CAPS(nic);
4861 	LIMIT_CAPS(toe);
4862 	LIMIT_CAPS(rdma);
4863 	LIMIT_CAPS(crypto);
4864 	LIMIT_CAPS(iscsi);
4865 	LIMIT_CAPS(fcoe);
4866 #undef LIMIT_CAPS
4867 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
4868 		/*
4869 		 * TOE and hashfilters are mutually exclusive.  It is a config
4870 		 * file or firmware bug if both are reported as available.  Try
4871 		 * to cope with the situation in non-debug builds by disabling
4872 		 * TOE.
4873 		 */
4874 		MPASS(caps.toecaps == 0);
4875 
4876 		caps.toecaps = 0;
4877 		caps.rdmacaps = 0;
4878 		caps.iscsicaps = 0;
4879 	}
4880 
4881 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4882 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
4883 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4884 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
4885 	if (rc != 0) {
4886 		device_printf(sc->dev,
4887 		    "failed to process config file: %d.\n", rc);
4888 		goto done;
4889 	}
4890 
4891 	t4_tweak_chip_settings(sc);
4892 	set_params__pre_init(sc);
4893 
4894 	/* get basic stuff going */
4895 	rc = -t4_fw_initialize(sc, sc->mbox);
4896 	if (rc != 0) {
4897 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
4898 		goto done;
4899 	}
4900 done:
4901 	return (rc);
4902 }
4903 
4904 /*
4905  * Partition chip resources for use between various PFs, VFs, etc.
4906  */
4907 static int
4908 partition_resources(struct adapter *sc)
4909 {
4910 	char cfg_file[sizeof(t4_cfg_file)];
4911 	struct caps_allowed caps_allowed;
4912 	int rc;
4913 	bool fallback;
4914 
4915 	/* Only the master driver gets to configure the chip resources. */
4916 	MPASS(sc->flags & MASTER_PF);
4917 
4918 #define COPY_CAPS(x) do { \
4919 	caps_allowed.x##caps = t4_##x##caps_allowed; \
4920 } while (0)
4921 	bzero(&caps_allowed, sizeof(caps_allowed));
4922 	COPY_CAPS(nbm);
4923 	COPY_CAPS(link);
4924 	COPY_CAPS(switch);
4925 	COPY_CAPS(nic);
4926 	COPY_CAPS(toe);
4927 	COPY_CAPS(rdma);
4928 	COPY_CAPS(crypto);
4929 	COPY_CAPS(iscsi);
4930 	COPY_CAPS(fcoe);
4931 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
4932 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
4933 retry:
4934 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
4935 	if (rc != 0 && fallback) {
4936 		device_printf(sc->dev,
4937 		    "failed (%d) to configure card with \"%s\" profile, "
4938 		    "will fall back to a basic configuration and retry.\n",
4939 		    rc, cfg_file);
4940 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
4941 		bzero(&caps_allowed, sizeof(caps_allowed));
4942 		COPY_CAPS(switch);
4943 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
4944 		fallback = false;
4945 		goto retry;
4946 	}
4947 #undef COPY_CAPS
4948 	return (rc);
4949 }
4950 
4951 /*
4952  * Retrieve parameters that are needed (or nice to have) very early.
4953  */
4954 static int
4955 get_params__pre_init(struct adapter *sc)
4956 {
4957 	int rc;
4958 	uint32_t param[2], val[2];
4959 
4960 	t4_get_version_info(sc);
4961 
4962 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
4963 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
4964 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
4965 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
4966 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
4967 
4968 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
4969 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
4970 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
4971 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
4972 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
4973 
4974 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
4975 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
4976 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
4977 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
4978 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
4979 
4980 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
4981 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
4982 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
4983 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
4984 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
4985 
4986 	param[0] = FW_PARAM_DEV(PORTVEC);
4987 	param[1] = FW_PARAM_DEV(CCLK);
4988 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4989 	if (rc != 0) {
4990 		device_printf(sc->dev,
4991 		    "failed to query parameters (pre_init): %d.\n", rc);
4992 		return (rc);
4993 	}
4994 
4995 	sc->params.portvec = val[0];
4996 	sc->params.nports = bitcount32(val[0]);
4997 	sc->params.vpd.cclk = val[1];
4998 
4999 	/* Read device log parameters. */
5000 	rc = -t4_init_devlog_params(sc, 1);
5001 	if (rc == 0)
5002 		fixup_devlog_params(sc);
5003 	else {
5004 		device_printf(sc->dev,
5005 		    "failed to get devlog parameters: %d.\n", rc);
5006 		rc = 0;	/* devlog isn't critical for device operation */
5007 	}
5008 
5009 	return (rc);
5010 }
5011 
5012 /*
5013  * Any params that need to be set before FW_INITIALIZE.
5014  */
5015 static int
5016 set_params__pre_init(struct adapter *sc)
5017 {
5018 	int rc = 0;
5019 	uint32_t param, val;
5020 
5021 	if (chip_id(sc) >= CHELSIO_T6) {
5022 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5023 		val = 1;
5024 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5025 		/* firmwares < 1.20.1.0 do not have this param. */
5026 		if (rc == FW_EINVAL &&
5027 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5028 			rc = 0;
5029 		}
5030 		if (rc != 0) {
5031 			device_printf(sc->dev,
5032 			    "failed to enable high priority filters :%d.\n",
5033 			    rc);
5034 		}
5035 	}
5036 
5037 	/* Enable opaque VIIDs with firmwares that support it. */
5038 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5039 	val = 1;
5040 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5041 	if (rc == 0 && val == 1)
5042 		sc->params.viid_smt_extn_support = true;
5043 	else
5044 		sc->params.viid_smt_extn_support = false;
5045 
5046 	return (rc);
5047 }
5048 
5049 /*
5050  * Retrieve various parameters that are of interest to the driver.  The device
5051  * has been initialized by the firmware at this point.
5052  */
5053 static int
5054 get_params__post_init(struct adapter *sc)
5055 {
5056 	int rc;
5057 	uint32_t param[7], val[7];
5058 	struct fw_caps_config_cmd caps;
5059 
5060 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5061 	param[1] = FW_PARAM_PFVF(EQ_START);
5062 	param[2] = FW_PARAM_PFVF(FILTER_START);
5063 	param[3] = FW_PARAM_PFVF(FILTER_END);
5064 	param[4] = FW_PARAM_PFVF(L2T_START);
5065 	param[5] = FW_PARAM_PFVF(L2T_END);
5066 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5067 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5068 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5069 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5070 	if (rc != 0) {
5071 		device_printf(sc->dev,
5072 		    "failed to query parameters (post_init): %d.\n", rc);
5073 		return (rc);
5074 	}
5075 
5076 	sc->sge.iq_start = val[0];
5077 	sc->sge.eq_start = val[1];
5078 	if ((int)val[3] > (int)val[2]) {
5079 		sc->tids.ftid_base = val[2];
5080 		sc->tids.ftid_end = val[3];
5081 		sc->tids.nftids = val[3] - val[2] + 1;
5082 	}
5083 	sc->vres.l2t.start = val[4];
5084 	sc->vres.l2t.size = val[5] - val[4] + 1;
5085 	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
5086 	    ("%s: L2 table size (%u) larger than expected (%u)",
5087 	    __func__, sc->vres.l2t.size, L2T_SIZE));
5088 	sc->params.core_vdd = val[6];
5089 
5090 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5091 	param[1] = FW_PARAM_PFVF(EQ_END);
5092 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5093 	if (rc != 0) {
5094 		device_printf(sc->dev,
5095 		    "failed to query parameters (post_init2): %d.\n", rc);
5096 		return (rc);
5097 	}
5098 	MPASS((int)val[0] >= sc->sge.iq_start);
5099 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5100 	MPASS((int)val[1] >= sc->sge.eq_start);
5101 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5102 
5103 	if (chip_id(sc) >= CHELSIO_T6) {
5104 
5105 		sc->tids.tid_base = t4_read_reg(sc,
5106 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5107 
5108 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5109 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5110 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5111 		if (rc != 0) {
5112 			device_printf(sc->dev,
5113 			   "failed to query hpfilter parameters: %d.\n", rc);
5114 			return (rc);
5115 		}
5116 		if ((int)val[1] > (int)val[0]) {
5117 			sc->tids.hpftid_base = val[0];
5118 			sc->tids.hpftid_end = val[1];
5119 			sc->tids.nhpftids = val[1] - val[0] + 1;
5120 
5121 			/*
5122 			 * These should go off if the layout changes and the
5123 			 * driver needs to catch up.
5124 			 */
5125 			MPASS(sc->tids.hpftid_base == 0);
5126 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5127 		}
5128 
5129 		param[0] = FW_PARAM_PFVF(RAWF_START);
5130 		param[1] = FW_PARAM_PFVF(RAWF_END);
5131 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5132 		if (rc != 0) {
5133 			device_printf(sc->dev,
5134 			   "failed to query rawf parameters: %d.\n", rc);
5135 			return (rc);
5136 		}
5137 		if ((int)val[1] > (int)val[0]) {
5138 			sc->rawf_base = val[0];
5139 			sc->nrawf = val[1] - val[0] + 1;
5140 		}
5141 	}
5142 
5143 	/*
5144 	 * MPSBGMAP is queried separately because only recent firmwares support
5145 	 * it as a parameter and we don't want the compound query above to fail
5146 	 * on older firmwares.
5147 	 */
5148 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5149 	val[0] = 0;
5150 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5151 	if (rc == 0)
5152 		sc->params.mps_bg_map = val[0];
5153 	else
5154 		sc->params.mps_bg_map = 0;
5155 
5156 	/*
5157 	 * Determine whether the firmware supports the filter2 work request.
5158 	 * This is queried separately for the same reason as MPSBGMAP above.
5159 	 */
5160 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5161 	val[0] = 0;
5162 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5163 	if (rc == 0)
5164 		sc->params.filter2_wr_support = val[0] != 0;
5165 	else
5166 		sc->params.filter2_wr_support = 0;
5167 
5168 	/*
5169 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5170 	 * This is queried separately for the same reason as other params above.
5171 	 */
5172 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5173 	val[0] = 0;
5174 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5175 	if (rc == 0)
5176 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5177 	else
5178 		sc->params.ulptx_memwrite_dsgl = false;
5179 
5180 	/* FW_RI_FR_NSMR_TPTE_WR support */
5181 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5182 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5183 	if (rc == 0)
5184 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5185 	else
5186 		sc->params.fr_nsmr_tpte_wr_support = false;
5187 
5188 	/* Support for 512 SGL entries per FR MR. */
5189 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5190 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5191 	if (rc == 0)
5192 		sc->params.dev_512sgl_mr = val[0] != 0;
5193 	else
5194 		sc->params.dev_512sgl_mr = false;
5195 
5196 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5197 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5198 	if (rc == 0)
5199 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5200 	else
5201 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5202 
5203 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5204 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5205 	if (rc == 0) {
5206 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5207 		sc->params.nsched_cls = val[0];
5208 	} else
5209 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5210 
5211 	/* get capabilites */
5212 	bzero(&caps, sizeof(caps));
5213 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5214 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5215 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5216 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5217 	if (rc != 0) {
5218 		device_printf(sc->dev,
5219 		    "failed to get card capabilities: %d.\n", rc);
5220 		return (rc);
5221 	}
5222 
5223 #define READ_CAPS(x) do { \
5224 	sc->x = htobe16(caps.x); \
5225 } while (0)
5226 	READ_CAPS(nbmcaps);
5227 	READ_CAPS(linkcaps);
5228 	READ_CAPS(switchcaps);
5229 	READ_CAPS(niccaps);
5230 	READ_CAPS(toecaps);
5231 	READ_CAPS(rdmacaps);
5232 	READ_CAPS(cryptocaps);
5233 	READ_CAPS(iscsicaps);
5234 	READ_CAPS(fcoecaps);
5235 
5236 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5237 		MPASS(chip_id(sc) > CHELSIO_T4);
5238 		MPASS(sc->toecaps == 0);
5239 		sc->toecaps = 0;
5240 
5241 		param[0] = FW_PARAM_DEV(NTID);
5242 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5243 		if (rc != 0) {
5244 			device_printf(sc->dev,
5245 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5246 			return (rc);
5247 		}
5248 		sc->tids.ntids = val[0];
5249 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5250 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5251 			sc->tids.ntids -= sc->tids.nhpftids;
5252 		}
5253 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5254 		sc->params.hash_filter = 1;
5255 	}
5256 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5257 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5258 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5259 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5260 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5261 		if (rc != 0) {
5262 			device_printf(sc->dev,
5263 			    "failed to query NIC parameters: %d.\n", rc);
5264 			return (rc);
5265 		}
5266 		if ((int)val[1] > (int)val[0]) {
5267 			sc->tids.etid_base = val[0];
5268 			sc->tids.etid_end = val[1];
5269 			sc->tids.netids = val[1] - val[0] + 1;
5270 			sc->params.eo_wr_cred = val[2];
5271 			sc->params.ethoffload = 1;
5272 		}
5273 	}
5274 	if (sc->toecaps) {
5275 		/* query offload-related parameters */
5276 		param[0] = FW_PARAM_DEV(NTID);
5277 		param[1] = FW_PARAM_PFVF(SERVER_START);
5278 		param[2] = FW_PARAM_PFVF(SERVER_END);
5279 		param[3] = FW_PARAM_PFVF(TDDP_START);
5280 		param[4] = FW_PARAM_PFVF(TDDP_END);
5281 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5282 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5283 		if (rc != 0) {
5284 			device_printf(sc->dev,
5285 			    "failed to query TOE parameters: %d.\n", rc);
5286 			return (rc);
5287 		}
5288 		sc->tids.ntids = val[0];
5289 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5290 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5291 			sc->tids.ntids -= sc->tids.nhpftids;
5292 		}
5293 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5294 		if ((int)val[2] > (int)val[1]) {
5295 			sc->tids.stid_base = val[1];
5296 			sc->tids.nstids = val[2] - val[1] + 1;
5297 		}
5298 		sc->vres.ddp.start = val[3];
5299 		sc->vres.ddp.size = val[4] - val[3] + 1;
5300 		sc->params.ofldq_wr_cred = val[5];
5301 		sc->params.offload = 1;
5302 	} else {
5303 		/*
5304 		 * The firmware attempts memfree TOE configuration for -SO cards
5305 		 * and will report toecaps=0 if it runs out of resources (this
5306 		 * depends on the config file).  It may not report 0 for other
5307 		 * capabilities dependent on the TOE in this case.  Set them to
5308 		 * 0 here so that the driver doesn't bother tracking resources
5309 		 * that will never be used.
5310 		 */
5311 		sc->iscsicaps = 0;
5312 		sc->rdmacaps = 0;
5313 	}
5314 	if (sc->rdmacaps) {
5315 		param[0] = FW_PARAM_PFVF(STAG_START);
5316 		param[1] = FW_PARAM_PFVF(STAG_END);
5317 		param[2] = FW_PARAM_PFVF(RQ_START);
5318 		param[3] = FW_PARAM_PFVF(RQ_END);
5319 		param[4] = FW_PARAM_PFVF(PBL_START);
5320 		param[5] = FW_PARAM_PFVF(PBL_END);
5321 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5322 		if (rc != 0) {
5323 			device_printf(sc->dev,
5324 			    "failed to query RDMA parameters(1): %d.\n", rc);
5325 			return (rc);
5326 		}
5327 		sc->vres.stag.start = val[0];
5328 		sc->vres.stag.size = val[1] - val[0] + 1;
5329 		sc->vres.rq.start = val[2];
5330 		sc->vres.rq.size = val[3] - val[2] + 1;
5331 		sc->vres.pbl.start = val[4];
5332 		sc->vres.pbl.size = val[5] - val[4] + 1;
5333 
5334 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5335 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5336 		param[2] = FW_PARAM_PFVF(CQ_START);
5337 		param[3] = FW_PARAM_PFVF(CQ_END);
5338 		param[4] = FW_PARAM_PFVF(OCQ_START);
5339 		param[5] = FW_PARAM_PFVF(OCQ_END);
5340 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5341 		if (rc != 0) {
5342 			device_printf(sc->dev,
5343 			    "failed to query RDMA parameters(2): %d.\n", rc);
5344 			return (rc);
5345 		}
5346 		sc->vres.qp.start = val[0];
5347 		sc->vres.qp.size = val[1] - val[0] + 1;
5348 		sc->vres.cq.start = val[2];
5349 		sc->vres.cq.size = val[3] - val[2] + 1;
5350 		sc->vres.ocq.start = val[4];
5351 		sc->vres.ocq.size = val[5] - val[4] + 1;
5352 
5353 		param[0] = FW_PARAM_PFVF(SRQ_START);
5354 		param[1] = FW_PARAM_PFVF(SRQ_END);
5355 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5356 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5357 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5358 		if (rc != 0) {
5359 			device_printf(sc->dev,
5360 			    "failed to query RDMA parameters(3): %d.\n", rc);
5361 			return (rc);
5362 		}
5363 		sc->vres.srq.start = val[0];
5364 		sc->vres.srq.size = val[1] - val[0] + 1;
5365 		sc->params.max_ordird_qp = val[2];
5366 		sc->params.max_ird_adapter = val[3];
5367 	}
5368 	if (sc->iscsicaps) {
5369 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5370 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5371 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5372 		if (rc != 0) {
5373 			device_printf(sc->dev,
5374 			    "failed to query iSCSI parameters: %d.\n", rc);
5375 			return (rc);
5376 		}
5377 		sc->vres.iscsi.start = val[0];
5378 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5379 	}
5380 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5381 		param[0] = FW_PARAM_PFVF(TLS_START);
5382 		param[1] = FW_PARAM_PFVF(TLS_END);
5383 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5384 		if (rc != 0) {
5385 			device_printf(sc->dev,
5386 			    "failed to query TLS parameters: %d.\n", rc);
5387 			return (rc);
5388 		}
5389 		sc->vres.key.start = val[0];
5390 		sc->vres.key.size = val[1] - val[0] + 1;
5391 	}
5392 
5393 	/*
5394 	 * We've got the params we wanted to query directly from the firmware.
5395 	 * Grab some others via other means.
5396 	 */
5397 	t4_init_sge_params(sc);
5398 	t4_init_tp_params(sc);
5399 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5400 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5401 
5402 	rc = t4_verify_chip_settings(sc);
5403 	if (rc != 0)
5404 		return (rc);
5405 	t4_init_rx_buf_info(sc);
5406 
5407 	return (rc);
5408 }
5409 
5410 #ifdef KERN_TLS
5411 static void
5412 ktls_tick(void *arg)
5413 {
5414 	struct adapter *sc;
5415 	uint32_t tstamp;
5416 
5417 	sc = arg;
5418 	tstamp = tcp_ts_getticks();
5419 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5420 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5421 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5422 }
5423 
5424 static int
5425 t4_config_kern_tls(struct adapter *sc, bool enable)
5426 {
5427 	int rc;
5428 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5429 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5430 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5431 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5432 
5433 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5434 	if (rc != 0) {
5435 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5436 		    enable ?  "enable" : "disable", rc);
5437 		return (rc);
5438 	}
5439 
5440 	if (enable) {
5441 		sc->flags |= KERN_TLS_ON;
5442 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5443 		    C_HARDCLOCK);
5444 	} else {
5445 		sc->flags &= ~KERN_TLS_ON;
5446 		callout_stop(&sc->ktls_tick);
5447 	}
5448 
5449 	return (rc);
5450 }
5451 #endif
5452 
5453 static int
5454 set_params__post_init(struct adapter *sc)
5455 {
5456 	uint32_t mask, param, val;
5457 #ifdef TCP_OFFLOAD
5458 	int i, v, shift;
5459 #endif
5460 
5461 	/* ask for encapsulated CPLs */
5462 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5463 	val = 1;
5464 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5465 
5466 	/* Enable 32b port caps if the firmware supports it. */
5467 	param = FW_PARAM_PFVF(PORT_CAPS32);
5468 	val = 1;
5469 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5470 		sc->params.port_caps32 = 1;
5471 
5472 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5473 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5474 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5475 	    V_MASKFILTER(val - 1));
5476 
5477 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5478 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5479 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5480 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5481 	val = 0;
5482 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5483 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5484 		    F_ATTACKFILTERENABLE);
5485 		val |= F_DROPERRORATTACK;
5486 	}
5487 	if (t4_drop_ip_fragments != 0) {
5488 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5489 		    F_FRAGMENTDROP);
5490 		val |= F_DROPERRORFRAG;
5491 	}
5492 	if (t4_drop_pkts_with_l2_errors != 0)
5493 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5494 	if (t4_drop_pkts_with_l3_errors != 0) {
5495 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5496 		    F_DROPERRORCSUMIP;
5497 	}
5498 	if (t4_drop_pkts_with_l4_errors != 0) {
5499 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5500 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5501 	}
5502 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5503 
5504 #ifdef TCP_OFFLOAD
5505 	/*
5506 	 * Override the TOE timers with user provided tunables.  This is not the
5507 	 * recommended way to change the timers (the firmware config file is) so
5508 	 * these tunables are not documented.
5509 	 *
5510 	 * All the timer tunables are in microseconds.
5511 	 */
5512 	if (t4_toe_keepalive_idle != 0) {
5513 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5514 		v &= M_KEEPALIVEIDLE;
5515 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5516 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5517 	}
5518 	if (t4_toe_keepalive_interval != 0) {
5519 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5520 		v &= M_KEEPALIVEINTVL;
5521 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5522 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5523 	}
5524 	if (t4_toe_keepalive_count != 0) {
5525 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5526 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5527 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5528 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5529 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5530 	}
5531 	if (t4_toe_rexmt_min != 0) {
5532 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5533 		v &= M_RXTMIN;
5534 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5535 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5536 	}
5537 	if (t4_toe_rexmt_max != 0) {
5538 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5539 		v &= M_RXTMAX;
5540 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5541 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5542 	}
5543 	if (t4_toe_rexmt_count != 0) {
5544 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5545 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5546 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5547 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5548 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5549 	}
5550 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5551 		if (t4_toe_rexmt_backoff[i] != -1) {
5552 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5553 			shift = (i & 3) << 3;
5554 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5555 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5556 		}
5557 	}
5558 #endif
5559 
5560 #ifdef KERN_TLS
5561 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS &&
5562 	    sc->toecaps & FW_CAPS_CONFIG_TOE) {
5563 		/*
5564 		 * Limit TOE connections to 2 reassembly "islands".  This is
5565 		 * required for TOE TLS connections to downgrade to plain TOE
5566 		 * connections if an unsupported TLS version or ciphersuite is
5567 		 * used.
5568 		 */
5569 		t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG,
5570 		    V_PASSMODE(M_PASSMODE), V_PASSMODE(2));
5571 		if (is_ktls(sc)) {
5572 			sc->tlst.inline_keys = t4_tls_inline_keys;
5573 			sc->tlst.combo_wrs = t4_tls_combo_wrs;
5574 			if (t4_kern_tls != 0)
5575 				t4_config_kern_tls(sc, true);
5576 		}
5577 	}
5578 #endif
5579 	return (0);
5580 }
5581 
5582 #undef FW_PARAM_PFVF
5583 #undef FW_PARAM_DEV
5584 
5585 static void
5586 t4_set_desc(struct adapter *sc)
5587 {
5588 	char buf[128];
5589 	struct adapter_params *p = &sc->params;
5590 
5591 	snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
5592 
5593 	device_set_desc_copy(sc->dev, buf);
5594 }
5595 
5596 static inline void
5597 ifmedia_add4(struct ifmedia *ifm, int m)
5598 {
5599 
5600 	ifmedia_add(ifm, m, 0, NULL);
5601 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5602 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5603 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5604 }
5605 
5606 /*
5607  * This is the selected media, which is not quite the same as the active media.
5608  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5609  * and active are not the same, and "media: Ethernet selected" otherwise.
5610  */
5611 static void
5612 set_current_media(struct port_info *pi)
5613 {
5614 	struct link_config *lc;
5615 	struct ifmedia *ifm;
5616 	int mword;
5617 	u_int speed;
5618 
5619 	PORT_LOCK_ASSERT_OWNED(pi);
5620 
5621 	/* Leave current media alone if it's already set to IFM_NONE. */
5622 	ifm = &pi->media;
5623 	if (ifm->ifm_cur != NULL &&
5624 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5625 		return;
5626 
5627 	lc = &pi->link_cfg;
5628 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5629 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5630 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5631 		return;
5632 	}
5633 	mword = IFM_ETHER | IFM_FDX;
5634 	if (lc->requested_fc & PAUSE_TX)
5635 		mword |= IFM_ETH_TXPAUSE;
5636 	if (lc->requested_fc & PAUSE_RX)
5637 		mword |= IFM_ETH_RXPAUSE;
5638 	if (lc->requested_speed == 0)
5639 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5640 	else
5641 		speed = lc->requested_speed;
5642 	mword |= port_mword(pi, speed_to_fwcap(speed));
5643 	ifmedia_set(ifm, mword);
5644 }
5645 
5646 /*
5647  * Returns true if the ifmedia list for the port cannot change.
5648  */
5649 static bool
5650 fixed_ifmedia(struct port_info *pi)
5651 {
5652 
5653 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5654 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5655 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5656 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5657 	    pi->port_type == FW_PORT_TYPE_KX ||
5658 	    pi->port_type == FW_PORT_TYPE_KR ||
5659 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5660 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5661 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5662 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5663 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5664 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5665 }
5666 
5667 static void
5668 build_medialist(struct port_info *pi)
5669 {
5670 	uint32_t ss, speed;
5671 	int unknown, mword, bit;
5672 	struct link_config *lc;
5673 	struct ifmedia *ifm;
5674 
5675 	PORT_LOCK_ASSERT_OWNED(pi);
5676 
5677 	if (pi->flags & FIXED_IFMEDIA)
5678 		return;
5679 
5680 	/*
5681 	 * Rebuild the ifmedia list.
5682 	 */
5683 	ifm = &pi->media;
5684 	ifmedia_removeall(ifm);
5685 	lc = &pi->link_cfg;
5686 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5687 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5688 		MPASS(ss != 0);
5689 no_media:
5690 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5691 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5692 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5693 		return;
5694 	}
5695 
5696 	unknown = 0;
5697 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5698 		speed = 1 << bit;
5699 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5700 		if (ss & speed) {
5701 			mword = port_mword(pi, speed);
5702 			if (mword == IFM_NONE) {
5703 				goto no_media;
5704 			} else if (mword == IFM_UNKNOWN)
5705 				unknown++;
5706 			else
5707 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5708 		}
5709 	}
5710 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5711 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5712 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5713 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5714 
5715 	set_current_media(pi);
5716 }
5717 
5718 /*
5719  * Initialize the requested fields in the link config based on driver tunables.
5720  */
5721 static void
5722 init_link_config(struct port_info *pi)
5723 {
5724 	struct link_config *lc = &pi->link_cfg;
5725 
5726 	PORT_LOCK_ASSERT_OWNED(pi);
5727 	MPASS(lc->pcaps != 0);
5728 
5729 	lc->requested_caps = 0;
5730 	lc->requested_speed = 0;
5731 
5732 	if (t4_autoneg == 0)
5733 		lc->requested_aneg = AUTONEG_DISABLE;
5734 	else if (t4_autoneg == 1)
5735 		lc->requested_aneg = AUTONEG_ENABLE;
5736 	else
5737 		lc->requested_aneg = AUTONEG_AUTO;
5738 
5739 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5740 	    PAUSE_AUTONEG);
5741 
5742 	if (t4_fec & FEC_AUTO)
5743 		lc->requested_fec = FEC_AUTO;
5744 	else if (t4_fec == 0)
5745 		lc->requested_fec = FEC_NONE;
5746 	else {
5747 		/* -1 is handled by the FEC_AUTO block above and not here. */
5748 		lc->requested_fec = t4_fec &
5749 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5750 		if (lc->requested_fec == 0)
5751 			lc->requested_fec = FEC_AUTO;
5752 	}
5753 	lc->force_fec = 0;
5754 	if (lc->pcaps & FW_PORT_CAP32_FORCE_FEC) {
5755 		if (t4_force_fec < 0)
5756 			lc->force_fec = -1;
5757 		else if (t4_force_fec > 0)
5758 			lc->force_fec = 1;
5759 	}
5760 }
5761 
5762 /*
5763  * Makes sure that all requested settings comply with what's supported by the
5764  * port.  Returns the number of settings that were invalid and had to be fixed.
5765  */
5766 static int
5767 fixup_link_config(struct port_info *pi)
5768 {
5769 	int n = 0;
5770 	struct link_config *lc = &pi->link_cfg;
5771 	uint32_t fwspeed;
5772 
5773 	PORT_LOCK_ASSERT_OWNED(pi);
5774 
5775 	/* Speed (when not autonegotiating) */
5776 	if (lc->requested_speed != 0) {
5777 		fwspeed = speed_to_fwcap(lc->requested_speed);
5778 		if ((fwspeed & lc->pcaps) == 0) {
5779 			n++;
5780 			lc->requested_speed = 0;
5781 		}
5782 	}
5783 
5784 	/* Link autonegotiation */
5785 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5786 	    lc->requested_aneg == AUTONEG_DISABLE ||
5787 	    lc->requested_aneg == AUTONEG_AUTO);
5788 	if (lc->requested_aneg == AUTONEG_ENABLE &&
5789 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5790 		n++;
5791 		lc->requested_aneg = AUTONEG_AUTO;
5792 	}
5793 
5794 	/* Flow control */
5795 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5796 	if (lc->requested_fc & PAUSE_TX &&
5797 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5798 		n++;
5799 		lc->requested_fc &= ~PAUSE_TX;
5800 	}
5801 	if (lc->requested_fc & PAUSE_RX &&
5802 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
5803 		n++;
5804 		lc->requested_fc &= ~PAUSE_RX;
5805 	}
5806 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
5807 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
5808 		n++;
5809 		lc->requested_fc |= PAUSE_AUTONEG;
5810 	}
5811 
5812 	/* FEC */
5813 	if ((lc->requested_fec & FEC_RS &&
5814 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
5815 	    (lc->requested_fec & FEC_BASER_RS &&
5816 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
5817 		n++;
5818 		lc->requested_fec = FEC_AUTO;
5819 	}
5820 
5821 	return (n);
5822 }
5823 
5824 /*
5825  * Apply the requested L1 settings, which are expected to be valid, to the
5826  * hardware.
5827  */
5828 static int
5829 apply_link_config(struct port_info *pi)
5830 {
5831 	struct adapter *sc = pi->adapter;
5832 	struct link_config *lc = &pi->link_cfg;
5833 	int rc;
5834 
5835 #ifdef INVARIANTS
5836 	ASSERT_SYNCHRONIZED_OP(sc);
5837 	PORT_LOCK_ASSERT_OWNED(pi);
5838 
5839 	if (lc->requested_aneg == AUTONEG_ENABLE)
5840 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
5841 	if (!(lc->requested_fc & PAUSE_AUTONEG))
5842 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
5843 	if (lc->requested_fc & PAUSE_TX)
5844 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
5845 	if (lc->requested_fc & PAUSE_RX)
5846 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
5847 	if (lc->requested_fec & FEC_RS)
5848 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
5849 	if (lc->requested_fec & FEC_BASER_RS)
5850 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
5851 #endif
5852 	rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
5853 	if (rc != 0) {
5854 		/* Don't complain if the VF driver gets back an EPERM. */
5855 		if (!(sc->flags & IS_VF) || rc != FW_EPERM)
5856 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
5857 	} else {
5858 		/*
5859 		 * An L1_CFG will almost always result in a link-change event if
5860 		 * the link is up, and the driver will refresh the actual
5861 		 * fec/fc/etc. when the notification is processed.  If the link
5862 		 * is down then the actual settings are meaningless.
5863 		 *
5864 		 * This takes care of the case where a change in the L1 settings
5865 		 * may not result in a notification.
5866 		 */
5867 		if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
5868 			lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
5869 	}
5870 	return (rc);
5871 }
5872 
5873 #define FW_MAC_EXACT_CHUNK	7
5874 struct mcaddr_ctx {
5875 	struct ifnet *ifp;
5876 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
5877 	uint64_t hash;
5878 	int i;
5879 	int del;
5880 	int rc;
5881 };
5882 
5883 static u_int
5884 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
5885 {
5886 	struct mcaddr_ctx *ctx = arg;
5887 	struct vi_info *vi = ctx->ifp->if_softc;
5888 	struct port_info *pi = vi->pi;
5889 	struct adapter *sc = pi->adapter;
5890 
5891 	if (ctx->rc < 0)
5892 		return (0);
5893 
5894 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
5895 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
5896 	ctx->i++;
5897 
5898 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
5899 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
5900 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
5901 		if (ctx->rc < 0) {
5902 			int j;
5903 
5904 			for (j = 0; j < ctx->i; j++) {
5905 				if_printf(ctx->ifp,
5906 				    "failed to add mc address"
5907 				    " %02x:%02x:%02x:"
5908 				    "%02x:%02x:%02x rc=%d\n",
5909 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
5910 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
5911 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
5912 				    -ctx->rc);
5913 			}
5914 			return (0);
5915 		}
5916 		ctx->del = 0;
5917 		ctx->i = 0;
5918 	}
5919 
5920 	return (1);
5921 }
5922 
5923 /*
5924  * Program the port's XGMAC based on parameters in ifnet.  The caller also
5925  * indicates which parameters should be programmed (the rest are left alone).
5926  */
5927 int
5928 update_mac_settings(struct ifnet *ifp, int flags)
5929 {
5930 	int rc = 0;
5931 	struct vi_info *vi = ifp->if_softc;
5932 	struct port_info *pi = vi->pi;
5933 	struct adapter *sc = pi->adapter;
5934 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
5935 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
5936 
5937 	ASSERT_SYNCHRONIZED_OP(sc);
5938 	KASSERT(flags, ("%s: not told what to update.", __func__));
5939 
5940 	if (flags & XGMAC_MTU)
5941 		mtu = ifp->if_mtu;
5942 
5943 	if (flags & XGMAC_PROMISC)
5944 		promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
5945 
5946 	if (flags & XGMAC_ALLMULTI)
5947 		allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
5948 
5949 	if (flags & XGMAC_VLANEX)
5950 		vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
5951 
5952 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
5953 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
5954 		    allmulti, 1, vlanex, false);
5955 		if (rc) {
5956 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
5957 			    rc);
5958 			return (rc);
5959 		}
5960 	}
5961 
5962 	if (flags & XGMAC_UCADDR) {
5963 		uint8_t ucaddr[ETHER_ADDR_LEN];
5964 
5965 		bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
5966 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
5967 		    ucaddr, true, &vi->smt_idx);
5968 		if (rc < 0) {
5969 			rc = -rc;
5970 			if_printf(ifp, "change_mac failed: %d\n", rc);
5971 			return (rc);
5972 		} else {
5973 			vi->xact_addr_filt = rc;
5974 			rc = 0;
5975 		}
5976 	}
5977 
5978 	if (flags & XGMAC_MCADDRS) {
5979 		struct epoch_tracker et;
5980 		struct mcaddr_ctx ctx;
5981 		int j;
5982 
5983 		ctx.ifp = ifp;
5984 		ctx.hash = 0;
5985 		ctx.i = 0;
5986 		ctx.del = 1;
5987 		ctx.rc = 0;
5988 		/*
5989 		 * Unlike other drivers, we accumulate list of pointers into
5990 		 * interface address lists and we need to keep it safe even
5991 		 * after if_foreach_llmaddr() returns, thus we must enter the
5992 		 * network epoch.
5993 		 */
5994 		NET_EPOCH_ENTER(et);
5995 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
5996 		if (ctx.rc < 0) {
5997 			NET_EPOCH_EXIT(et);
5998 			rc = -ctx.rc;
5999 			return (rc);
6000 		}
6001 		if (ctx.i > 0) {
6002 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6003 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6004 			NET_EPOCH_EXIT(et);
6005 			if (rc < 0) {
6006 				rc = -rc;
6007 				for (j = 0; j < ctx.i; j++) {
6008 					if_printf(ifp,
6009 					    "failed to add mcast address"
6010 					    " %02x:%02x:%02x:"
6011 					    "%02x:%02x:%02x rc=%d\n",
6012 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6013 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6014 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6015 					    rc);
6016 				}
6017 				return (rc);
6018 			}
6019 			ctx.del = 0;
6020 		} else
6021 			NET_EPOCH_EXIT(et);
6022 
6023 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6024 		if (rc != 0)
6025 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6026 			    rc);
6027 		if (ctx.del == 0) {
6028 			/* We clobbered the VXLAN entry if there was one. */
6029 			pi->vxlan_tcam_entry = false;
6030 		}
6031 	}
6032 
6033 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6034 	    pi->vxlan_tcam_entry == false) {
6035 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6036 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6037 		    true);
6038 		if (rc < 0) {
6039 			rc = -rc;
6040 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6041 			    rc);
6042 		} else {
6043 			MPASS(rc == sc->rawf_base + pi->port_id);
6044 			rc = 0;
6045 			pi->vxlan_tcam_entry = true;
6046 		}
6047 	}
6048 
6049 	return (rc);
6050 }
6051 
6052 /*
6053  * {begin|end}_synchronized_op must be called from the same thread.
6054  */
6055 int
6056 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6057     char *wmesg)
6058 {
6059 	int rc, pri;
6060 
6061 #ifdef WITNESS
6062 	/* the caller thinks it's ok to sleep, but is it really? */
6063 	if (flags & SLEEP_OK)
6064 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6065 		    "begin_synchronized_op");
6066 #endif
6067 
6068 	if (INTR_OK)
6069 		pri = PCATCH;
6070 	else
6071 		pri = 0;
6072 
6073 	ADAPTER_LOCK(sc);
6074 	for (;;) {
6075 
6076 		if (vi && IS_DOOMED(vi)) {
6077 			rc = ENXIO;
6078 			goto done;
6079 		}
6080 
6081 		if (!IS_BUSY(sc)) {
6082 			rc = 0;
6083 			break;
6084 		}
6085 
6086 		if (!(flags & SLEEP_OK)) {
6087 			rc = EBUSY;
6088 			goto done;
6089 		}
6090 
6091 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6092 			rc = EINTR;
6093 			goto done;
6094 		}
6095 	}
6096 
6097 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6098 	SET_BUSY(sc);
6099 #ifdef INVARIANTS
6100 	sc->last_op = wmesg;
6101 	sc->last_op_thr = curthread;
6102 	sc->last_op_flags = flags;
6103 #endif
6104 
6105 done:
6106 	if (!(flags & HOLD_LOCK) || rc)
6107 		ADAPTER_UNLOCK(sc);
6108 
6109 	return (rc);
6110 }
6111 
6112 /*
6113  * Tell if_ioctl and if_init that the VI is going away.  This is
6114  * special variant of begin_synchronized_op and must be paired with a
6115  * call to end_synchronized_op.
6116  */
6117 void
6118 doom_vi(struct adapter *sc, struct vi_info *vi)
6119 {
6120 
6121 	ADAPTER_LOCK(sc);
6122 	SET_DOOMED(vi);
6123 	wakeup(&sc->flags);
6124 	while (IS_BUSY(sc))
6125 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6126 	SET_BUSY(sc);
6127 #ifdef INVARIANTS
6128 	sc->last_op = "t4detach";
6129 	sc->last_op_thr = curthread;
6130 	sc->last_op_flags = 0;
6131 #endif
6132 	ADAPTER_UNLOCK(sc);
6133 }
6134 
6135 /*
6136  * {begin|end}_synchronized_op must be called from the same thread.
6137  */
6138 void
6139 end_synchronized_op(struct adapter *sc, int flags)
6140 {
6141 
6142 	if (flags & LOCK_HELD)
6143 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6144 	else
6145 		ADAPTER_LOCK(sc);
6146 
6147 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6148 	CLR_BUSY(sc);
6149 	wakeup(&sc->flags);
6150 	ADAPTER_UNLOCK(sc);
6151 }
6152 
6153 static int
6154 cxgbe_init_synchronized(struct vi_info *vi)
6155 {
6156 	struct port_info *pi = vi->pi;
6157 	struct adapter *sc = pi->adapter;
6158 	struct ifnet *ifp = vi->ifp;
6159 	int rc = 0, i;
6160 	struct sge_txq *txq;
6161 
6162 	ASSERT_SYNCHRONIZED_OP(sc);
6163 
6164 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
6165 		return (0);	/* already running */
6166 
6167 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6168 		return (rc);	/* error message displayed already */
6169 
6170 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6171 		return (rc); /* error message displayed already */
6172 
6173 	rc = update_mac_settings(ifp, XGMAC_ALL);
6174 	if (rc)
6175 		goto done;	/* error message displayed already */
6176 
6177 	PORT_LOCK(pi);
6178 	if (pi->up_vis == 0) {
6179 		t4_update_port_info(pi);
6180 		fixup_link_config(pi);
6181 		build_medialist(pi);
6182 		apply_link_config(pi);
6183 	}
6184 
6185 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6186 	if (rc != 0) {
6187 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6188 		PORT_UNLOCK(pi);
6189 		goto done;
6190 	}
6191 
6192 	/*
6193 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6194 	 * if this changes.
6195 	 */
6196 
6197 	for_each_txq(vi, i, txq) {
6198 		TXQ_LOCK(txq);
6199 		txq->eq.flags |= EQ_ENABLED;
6200 		TXQ_UNLOCK(txq);
6201 	}
6202 
6203 	/*
6204 	 * The first iq of the first port to come up is used for tracing.
6205 	 */
6206 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6207 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6208 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6209 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6210 		    V_QUEUENUMBER(sc->traceq));
6211 		pi->flags |= HAS_TRACEQ;
6212 	}
6213 
6214 	/* all ok */
6215 	pi->up_vis++;
6216 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
6217 	if (pi->link_cfg.link_ok)
6218 		t4_os_link_changed(pi);
6219 	PORT_UNLOCK(pi);
6220 
6221 	mtx_lock(&vi->tick_mtx);
6222 	if (ifp->if_get_counter == vi_get_counter)
6223 		callout_reset(&vi->tick, hz, vi_tick, vi);
6224 	else
6225 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6226 	mtx_unlock(&vi->tick_mtx);
6227 done:
6228 	if (rc != 0)
6229 		cxgbe_uninit_synchronized(vi);
6230 
6231 	return (rc);
6232 }
6233 
6234 /*
6235  * Idempotent.
6236  */
6237 static int
6238 cxgbe_uninit_synchronized(struct vi_info *vi)
6239 {
6240 	struct port_info *pi = vi->pi;
6241 	struct adapter *sc = pi->adapter;
6242 	struct ifnet *ifp = vi->ifp;
6243 	int rc, i;
6244 	struct sge_txq *txq;
6245 
6246 	ASSERT_SYNCHRONIZED_OP(sc);
6247 
6248 	if (!(vi->flags & VI_INIT_DONE)) {
6249 		if (__predict_false(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6250 			KASSERT(0, ("uninited VI is running"));
6251 			if_printf(ifp, "uninited VI with running ifnet.  "
6252 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6253 			    "if_drv_flags 0x%08x\n", vi->flags, ifp->if_flags,
6254 			    ifp->if_drv_flags);
6255 		}
6256 		return (0);
6257 	}
6258 
6259 	/*
6260 	 * Disable the VI so that all its data in either direction is discarded
6261 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6262 	 * tick) intact as the TP can deliver negative advice or data that it's
6263 	 * holding in its RAM (for an offloaded connection) even after the VI is
6264 	 * disabled.
6265 	 */
6266 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6267 	if (rc) {
6268 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6269 		return (rc);
6270 	}
6271 
6272 	for_each_txq(vi, i, txq) {
6273 		TXQ_LOCK(txq);
6274 		txq->eq.flags &= ~EQ_ENABLED;
6275 		TXQ_UNLOCK(txq);
6276 	}
6277 
6278 	mtx_lock(&vi->tick_mtx);
6279 	callout_stop(&vi->tick);
6280 	mtx_unlock(&vi->tick_mtx);
6281 
6282 	PORT_LOCK(pi);
6283 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6284 		PORT_UNLOCK(pi);
6285 		return (0);
6286 	}
6287 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
6288 	pi->up_vis--;
6289 	if (pi->up_vis > 0) {
6290 		PORT_UNLOCK(pi);
6291 		return (0);
6292 	}
6293 
6294 	pi->link_cfg.link_ok = false;
6295 	pi->link_cfg.speed = 0;
6296 	pi->link_cfg.link_down_rc = 255;
6297 	t4_os_link_changed(pi);
6298 	PORT_UNLOCK(pi);
6299 
6300 	return (0);
6301 }
6302 
6303 /*
6304  * It is ok for this function to fail midway and return right away.  t4_detach
6305  * will walk the entire sc->irq list and clean up whatever is valid.
6306  */
6307 int
6308 t4_setup_intr_handlers(struct adapter *sc)
6309 {
6310 	int rc, rid, p, q, v;
6311 	char s[8];
6312 	struct irq *irq;
6313 	struct port_info *pi;
6314 	struct vi_info *vi;
6315 	struct sge *sge = &sc->sge;
6316 	struct sge_rxq *rxq;
6317 #ifdef TCP_OFFLOAD
6318 	struct sge_ofld_rxq *ofld_rxq;
6319 #endif
6320 #ifdef DEV_NETMAP
6321 	struct sge_nm_rxq *nm_rxq;
6322 #endif
6323 #ifdef RSS
6324 	int nbuckets = rss_getnumbuckets();
6325 #endif
6326 
6327 	/*
6328 	 * Setup interrupts.
6329 	 */
6330 	irq = &sc->irq[0];
6331 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6332 	if (forwarding_intr_to_fwq(sc))
6333 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6334 
6335 	/* Multiple interrupts. */
6336 	if (sc->flags & IS_VF)
6337 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6338 		    ("%s: too few intr.", __func__));
6339 	else
6340 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6341 		    ("%s: too few intr.", __func__));
6342 
6343 	/* The first one is always error intr on PFs */
6344 	if (!(sc->flags & IS_VF)) {
6345 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6346 		if (rc != 0)
6347 			return (rc);
6348 		irq++;
6349 		rid++;
6350 	}
6351 
6352 	/* The second one is always the firmware event queue (first on VFs) */
6353 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6354 	if (rc != 0)
6355 		return (rc);
6356 	irq++;
6357 	rid++;
6358 
6359 	for_each_port(sc, p) {
6360 		pi = sc->port[p];
6361 		for_each_vi(pi, v, vi) {
6362 			vi->first_intr = rid - 1;
6363 
6364 			if (vi->nnmrxq > 0) {
6365 				int n = max(vi->nrxq, vi->nnmrxq);
6366 
6367 				rxq = &sge->rxq[vi->first_rxq];
6368 #ifdef DEV_NETMAP
6369 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6370 #endif
6371 				for (q = 0; q < n; q++) {
6372 					snprintf(s, sizeof(s), "%x%c%x", p,
6373 					    'a' + v, q);
6374 					if (q < vi->nrxq)
6375 						irq->rxq = rxq++;
6376 #ifdef DEV_NETMAP
6377 					if (q < vi->nnmrxq)
6378 						irq->nm_rxq = nm_rxq++;
6379 
6380 					if (irq->nm_rxq != NULL &&
6381 					    irq->rxq == NULL) {
6382 						/* Netmap rx only */
6383 						rc = t4_alloc_irq(sc, irq, rid,
6384 						    t4_nm_intr, irq->nm_rxq, s);
6385 					}
6386 					if (irq->nm_rxq != NULL &&
6387 					    irq->rxq != NULL) {
6388 						/* NIC and Netmap rx */
6389 						rc = t4_alloc_irq(sc, irq, rid,
6390 						    t4_vi_intr, irq, s);
6391 					}
6392 #endif
6393 					if (irq->rxq != NULL &&
6394 					    irq->nm_rxq == NULL) {
6395 						/* NIC rx only */
6396 						rc = t4_alloc_irq(sc, irq, rid,
6397 						    t4_intr, irq->rxq, s);
6398 					}
6399 					if (rc != 0)
6400 						return (rc);
6401 #ifdef RSS
6402 					if (q < vi->nrxq) {
6403 						bus_bind_intr(sc->dev, irq->res,
6404 						    rss_getcpu(q % nbuckets));
6405 					}
6406 #endif
6407 					irq++;
6408 					rid++;
6409 					vi->nintr++;
6410 				}
6411 			} else {
6412 				for_each_rxq(vi, q, rxq) {
6413 					snprintf(s, sizeof(s), "%x%c%x", p,
6414 					    'a' + v, q);
6415 					rc = t4_alloc_irq(sc, irq, rid,
6416 					    t4_intr, rxq, s);
6417 					if (rc != 0)
6418 						return (rc);
6419 #ifdef RSS
6420 					bus_bind_intr(sc->dev, irq->res,
6421 					    rss_getcpu(q % nbuckets));
6422 #endif
6423 					irq++;
6424 					rid++;
6425 					vi->nintr++;
6426 				}
6427 			}
6428 #ifdef TCP_OFFLOAD
6429 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6430 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6431 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6432 				    ofld_rxq, s);
6433 				if (rc != 0)
6434 					return (rc);
6435 				irq++;
6436 				rid++;
6437 				vi->nintr++;
6438 			}
6439 #endif
6440 		}
6441 	}
6442 	MPASS(irq == &sc->irq[sc->intr_count]);
6443 
6444 	return (0);
6445 }
6446 
6447 static void
6448 write_global_rss_key(struct adapter *sc)
6449 {
6450 #ifdef RSS
6451 	int i;
6452 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6453 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6454 
6455 	CTASSERT(RSS_KEYSIZE == 40);
6456 
6457 	rss_getkey((void *)&raw_rss_key[0]);
6458 	for (i = 0; i < nitems(rss_key); i++) {
6459 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6460 	}
6461 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6462 #endif
6463 }
6464 
6465 /*
6466  * Idempotent.
6467  */
6468 static int
6469 adapter_full_init(struct adapter *sc)
6470 {
6471 	int rc, i;
6472 
6473 	ASSERT_SYNCHRONIZED_OP(sc);
6474 
6475 	if (!(sc->flags & ADAP_SYSCTL_CTX)) {
6476 		sysctl_ctx_init(&sc->ctx);
6477 		sc->flags |= ADAP_SYSCTL_CTX;
6478 	}
6479 
6480 	/*
6481 	 * queues that belong to the adapter (not any particular port).
6482 	 */
6483 	rc = t4_setup_adapter_queues(sc);
6484 	if (rc != 0)
6485 		return (rc);
6486 
6487 	for (i = 0; i < nitems(sc->tq); i++) {
6488 		if (sc->tq[i] != NULL)
6489 			continue;
6490 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6491 		    taskqueue_thread_enqueue, &sc->tq[i]);
6492 		if (sc->tq[i] == NULL) {
6493 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6494 			return (ENOMEM);
6495 		}
6496 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6497 		    device_get_nameunit(sc->dev), i);
6498 	}
6499 
6500 	if (!(sc->flags & IS_VF)) {
6501 		write_global_rss_key(sc);
6502 		t4_intr_enable(sc);
6503 	}
6504 	return (0);
6505 }
6506 
6507 int
6508 adapter_init(struct adapter *sc)
6509 {
6510 	int rc;
6511 
6512 	ASSERT_SYNCHRONIZED_OP(sc);
6513 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6514 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6515 	    ("%s: FULL_INIT_DONE already", __func__));
6516 
6517 	rc = adapter_full_init(sc);
6518 	if (rc != 0)
6519 		adapter_full_uninit(sc);
6520 	else
6521 		sc->flags |= FULL_INIT_DONE;
6522 
6523 	return (rc);
6524 }
6525 
6526 /*
6527  * Idempotent.
6528  */
6529 static void
6530 adapter_full_uninit(struct adapter *sc)
6531 {
6532 	int i;
6533 
6534 	/* Do this before freeing the adapter queues. */
6535 	if (sc->flags & ADAP_SYSCTL_CTX) {
6536 		sysctl_ctx_free(&sc->ctx);
6537 		sc->flags &= ~ADAP_SYSCTL_CTX;
6538 	}
6539 
6540 	t4_teardown_adapter_queues(sc);
6541 
6542 	for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
6543 		taskqueue_free(sc->tq[i]);
6544 		sc->tq[i] = NULL;
6545 	}
6546 
6547 	sc->flags &= ~FULL_INIT_DONE;
6548 }
6549 
6550 #ifdef RSS
6551 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6552     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6553     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6554     RSS_HASHTYPE_RSS_UDP_IPV6)
6555 
6556 /* Translates kernel hash types to hardware. */
6557 static int
6558 hashconfig_to_hashen(int hashconfig)
6559 {
6560 	int hashen = 0;
6561 
6562 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6563 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6564 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6565 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6566 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6567 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6568 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6569 	}
6570 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6571 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6572 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6573 	}
6574 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6575 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6576 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6577 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6578 
6579 	return (hashen);
6580 }
6581 
6582 /* Translates hardware hash types to kernel. */
6583 static int
6584 hashen_to_hashconfig(int hashen)
6585 {
6586 	int hashconfig = 0;
6587 
6588 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6589 		/*
6590 		 * If UDP hashing was enabled it must have been enabled for
6591 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6592 		 * enabling any 4-tuple hash is nonsense configuration.
6593 		 */
6594 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6595 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6596 
6597 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6598 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6599 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6600 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6601 	}
6602 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6603 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6604 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6605 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6606 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6607 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6608 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6609 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6610 
6611 	return (hashconfig);
6612 }
6613 #endif
6614 
6615 /*
6616  * Idempotent.
6617  */
6618 static int
6619 vi_full_init(struct vi_info *vi)
6620 {
6621 	struct adapter *sc = vi->adapter;
6622 	struct sge_rxq *rxq;
6623 	int rc, i, j;
6624 #ifdef RSS
6625 	int nbuckets = rss_getnumbuckets();
6626 	int hashconfig = rss_gethashconfig();
6627 	int extra;
6628 #endif
6629 
6630 	ASSERT_SYNCHRONIZED_OP(sc);
6631 
6632 	if (!(vi->flags & VI_SYSCTL_CTX)) {
6633 		sysctl_ctx_init(&vi->ctx);
6634 		vi->flags |= VI_SYSCTL_CTX;
6635 	}
6636 
6637 	/*
6638 	 * Allocate tx/rx/fl queues for this VI.
6639 	 */
6640 	rc = t4_setup_vi_queues(vi);
6641 	if (rc != 0)
6642 		return (rc);
6643 
6644 	/*
6645 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6646 	 */
6647 	if (vi->nrxq > vi->rss_size) {
6648 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6649 		    "some queues will never receive traffic.\n", vi->nrxq,
6650 		    vi->rss_size);
6651 	} else if (vi->rss_size % vi->nrxq) {
6652 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6653 		    "expect uneven traffic distribution.\n", vi->nrxq,
6654 		    vi->rss_size);
6655 	}
6656 #ifdef RSS
6657 	if (vi->nrxq != nbuckets) {
6658 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6659 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6660 	}
6661 #endif
6662 	if (vi->rss == NULL)
6663 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6664 		    M_ZERO | M_WAITOK);
6665 	for (i = 0; i < vi->rss_size;) {
6666 #ifdef RSS
6667 		j = rss_get_indirection_to_bucket(i);
6668 		j %= vi->nrxq;
6669 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6670 		vi->rss[i++] = rxq->iq.abs_id;
6671 #else
6672 		for_each_rxq(vi, j, rxq) {
6673 			vi->rss[i++] = rxq->iq.abs_id;
6674 			if (i == vi->rss_size)
6675 				break;
6676 		}
6677 #endif
6678 	}
6679 
6680 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6681 	    vi->rss, vi->rss_size);
6682 	if (rc != 0) {
6683 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6684 		return (rc);
6685 	}
6686 
6687 #ifdef RSS
6688 	vi->hashen = hashconfig_to_hashen(hashconfig);
6689 
6690 	/*
6691 	 * We may have had to enable some hashes even though the global config
6692 	 * wants them disabled.  This is a potential problem that must be
6693 	 * reported to the user.
6694 	 */
6695 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6696 
6697 	/*
6698 	 * If we consider only the supported hash types, then the enabled hashes
6699 	 * are a superset of the requested hashes.  In other words, there cannot
6700 	 * be any supported hash that was requested but not enabled, but there
6701 	 * can be hashes that were not requested but had to be enabled.
6702 	 */
6703 	extra &= SUPPORTED_RSS_HASHTYPES;
6704 	MPASS((extra & hashconfig) == 0);
6705 
6706 	if (extra) {
6707 		CH_ALERT(vi,
6708 		    "global RSS config (0x%x) cannot be accommodated.\n",
6709 		    hashconfig);
6710 	}
6711 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6712 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6713 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6714 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6715 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6716 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6717 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6718 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6719 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6720 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6721 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6722 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6723 #else
6724 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6725 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6726 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6727 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6728 #endif
6729 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6730 	    0, 0);
6731 	if (rc != 0) {
6732 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6733 		return (rc);
6734 	}
6735 
6736 	return (0);
6737 }
6738 
6739 int
6740 vi_init(struct vi_info *vi)
6741 {
6742 	int rc;
6743 
6744 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6745 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6746 	    ("%s: VI_INIT_DONE already", __func__));
6747 
6748 	rc = vi_full_init(vi);
6749 	if (rc != 0)
6750 		vi_full_uninit(vi);
6751 	else
6752 		vi->flags |= VI_INIT_DONE;
6753 
6754 	return (rc);
6755 }
6756 
6757 /*
6758  * Idempotent.
6759  */
6760 static void
6761 vi_full_uninit(struct vi_info *vi)
6762 {
6763 
6764 	if (vi->flags & VI_INIT_DONE) {
6765 		quiesce_vi(vi);
6766 		free(vi->rss, M_CXGBE);
6767 		free(vi->nm_rss, M_CXGBE);
6768 	}
6769 
6770 	/* Do this before freeing the VI queues. */
6771 	if (vi->flags & VI_SYSCTL_CTX) {
6772 		sysctl_ctx_free(&vi->ctx);
6773 		vi->flags &= ~VI_SYSCTL_CTX;
6774 	}
6775 
6776 	t4_teardown_vi_queues(vi);
6777 	vi->flags &= ~VI_INIT_DONE;
6778 }
6779 
6780 static void
6781 quiesce_txq(struct sge_txq *txq)
6782 {
6783 	struct sge_eq *eq = &txq->eq;
6784 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6785 
6786 	MPASS(eq->flags & EQ_SW_ALLOCATED);
6787 	MPASS(!(eq->flags & EQ_ENABLED));
6788 
6789 	/* Wait for the mp_ring to empty. */
6790 	while (!mp_ring_is_idle(txq->r)) {
6791 		mp_ring_check_drainage(txq->r, 4096);
6792 		pause("rquiesce", 1);
6793 	}
6794 	MPASS(txq->txp.npkt == 0);
6795 
6796 	if (eq->flags & EQ_HW_ALLOCATED) {
6797 		/*
6798 		 * Hardware is alive and working normally.  Wait for it to
6799 		 * finish and then wait for the driver to catch up and reclaim
6800 		 * all descriptors.
6801 		 */
6802 		while (spg->cidx != htobe16(eq->pidx))
6803 			pause("equiesce", 1);
6804 		while (eq->cidx != eq->pidx)
6805 			pause("dquiesce", 1);
6806 	} else {
6807 		/*
6808 		 * Hardware is unavailable.  Discard all pending tx and reclaim
6809 		 * descriptors directly.
6810 		 */
6811 		TXQ_LOCK(txq);
6812 		while (eq->cidx != eq->pidx) {
6813 			struct mbuf *m, *nextpkt;
6814 			struct tx_sdesc *txsd;
6815 
6816 			txsd = &txq->sdesc[eq->cidx];
6817 			for (m = txsd->m; m != NULL; m = nextpkt) {
6818 				nextpkt = m->m_nextpkt;
6819 				m->m_nextpkt = NULL;
6820 				m_freem(m);
6821 			}
6822 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
6823 		}
6824 		spg->pidx = spg->cidx = htobe16(eq->cidx);
6825 		TXQ_UNLOCK(txq);
6826 	}
6827 }
6828 
6829 static void
6830 quiesce_wrq(struct sge_wrq *wrq)
6831 {
6832 
6833 	/* XXXTX */
6834 }
6835 
6836 static void
6837 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
6838 {
6839 	/* Synchronize with the interrupt handler */
6840 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
6841 		pause("iqfree", 1);
6842 
6843 	if (fl != NULL) {
6844 		MPASS(iq->flags & IQ_HAS_FL);
6845 
6846 		mtx_lock(&sc->sfl_lock);
6847 		FL_LOCK(fl);
6848 		fl->flags |= FL_DOOMED;
6849 		FL_UNLOCK(fl);
6850 		callout_stop(&sc->sfl_callout);
6851 		mtx_unlock(&sc->sfl_lock);
6852 
6853 		KASSERT((fl->flags & FL_STARVING) == 0,
6854 		    ("%s: still starving", __func__));
6855 
6856 		/* Release all buffers if hardware is no longer available. */
6857 		if (!(iq->flags & IQ_HW_ALLOCATED))
6858 			free_fl_buffers(sc, fl);
6859 	}
6860 }
6861 
6862 /*
6863  * Wait for all activity on all the queues of the VI to complete.  It is assumed
6864  * that no new work is being enqueued by the hardware or the driver.  That part
6865  * should be arranged before calling this function.
6866  */
6867 static void
6868 quiesce_vi(struct vi_info *vi)
6869 {
6870 	int i;
6871 	struct adapter *sc = vi->adapter;
6872 	struct sge_rxq *rxq;
6873 	struct sge_txq *txq;
6874 #ifdef TCP_OFFLOAD
6875 	struct sge_ofld_rxq *ofld_rxq;
6876 #endif
6877 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6878 	struct sge_ofld_txq *ofld_txq;
6879 #endif
6880 
6881 	if (!(vi->flags & VI_INIT_DONE))
6882 		return;
6883 
6884 	for_each_txq(vi, i, txq) {
6885 		quiesce_txq(txq);
6886 	}
6887 
6888 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6889 	for_each_ofld_txq(vi, i, ofld_txq) {
6890 		quiesce_wrq(&ofld_txq->wrq);
6891 	}
6892 #endif
6893 
6894 	for_each_rxq(vi, i, rxq) {
6895 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
6896 	}
6897 
6898 #ifdef TCP_OFFLOAD
6899 	for_each_ofld_rxq(vi, i, ofld_rxq) {
6900 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
6901 	}
6902 #endif
6903 }
6904 
6905 static int
6906 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
6907     driver_intr_t *handler, void *arg, char *name)
6908 {
6909 	int rc;
6910 
6911 	irq->rid = rid;
6912 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
6913 	    RF_SHAREABLE | RF_ACTIVE);
6914 	if (irq->res == NULL) {
6915 		device_printf(sc->dev,
6916 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
6917 		return (ENOMEM);
6918 	}
6919 
6920 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
6921 	    NULL, handler, arg, &irq->tag);
6922 	if (rc != 0) {
6923 		device_printf(sc->dev,
6924 		    "failed to setup interrupt for rid %d, name %s: %d\n",
6925 		    rid, name, rc);
6926 	} else if (name)
6927 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
6928 
6929 	return (rc);
6930 }
6931 
6932 static int
6933 t4_free_irq(struct adapter *sc, struct irq *irq)
6934 {
6935 	if (irq->tag)
6936 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
6937 	if (irq->res)
6938 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
6939 
6940 	bzero(irq, sizeof(*irq));
6941 
6942 	return (0);
6943 }
6944 
6945 static void
6946 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
6947 {
6948 
6949 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
6950 	t4_get_regs(sc, buf, regs->len);
6951 }
6952 
6953 #define	A_PL_INDIR_CMD	0x1f8
6954 
6955 #define	S_PL_AUTOINC	31
6956 #define	M_PL_AUTOINC	0x1U
6957 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
6958 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
6959 
6960 #define	S_PL_VFID	20
6961 #define	M_PL_VFID	0xffU
6962 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
6963 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
6964 
6965 #define	S_PL_ADDR	0
6966 #define	M_PL_ADDR	0xfffffU
6967 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
6968 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
6969 
6970 #define	A_PL_INDIR_DATA	0x1fc
6971 
6972 static uint64_t
6973 read_vf_stat(struct adapter *sc, u_int vin, int reg)
6974 {
6975 	u32 stats[2];
6976 
6977 	if (sc->flags & IS_VF) {
6978 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
6979 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
6980 	} else {
6981 		mtx_assert(&sc->reg_lock, MA_OWNED);
6982 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
6983 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
6984 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
6985 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
6986 	}
6987 	return (((uint64_t)stats[1]) << 32 | stats[0]);
6988 }
6989 
6990 static void
6991 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
6992 {
6993 
6994 #define GET_STAT(name) \
6995 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
6996 
6997 	if (!(sc->flags & IS_VF))
6998 		mtx_lock(&sc->reg_lock);
6999 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7000 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7001 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7002 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7003 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7004 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7005 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7006 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7007 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7008 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7009 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7010 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7011 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7012 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7013 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7014 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7015 	if (!(sc->flags & IS_VF))
7016 		mtx_unlock(&sc->reg_lock);
7017 
7018 #undef GET_STAT
7019 }
7020 
7021 static void
7022 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7023 {
7024 	int reg;
7025 
7026 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7027 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7028 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7029 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7030 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7031 }
7032 
7033 static void
7034 vi_refresh_stats(struct vi_info *vi)
7035 {
7036 	struct timeval tv;
7037 	const struct timeval interval = {0, 250000};	/* 250ms */
7038 
7039 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7040 
7041 	if (!(vi->flags & VI_INIT_DONE) || vi->flags & VI_SKIP_STATS)
7042 		return;
7043 
7044 	getmicrotime(&tv);
7045 	timevalsub(&tv, &interval);
7046 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7047 		return;
7048 
7049 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7050 	getmicrotime(&vi->last_refreshed);
7051 }
7052 
7053 static void
7054 cxgbe_refresh_stats(struct vi_info *vi)
7055 {
7056 	u_int i, v, tnl_cong_drops, chan_map;
7057 	struct timeval tv;
7058 	const struct timeval interval = {0, 250000};	/* 250ms */
7059 	struct port_info *pi;
7060 	struct adapter *sc;
7061 
7062 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7063 
7064 	if (vi->flags & VI_SKIP_STATS)
7065 		return;
7066 
7067 	getmicrotime(&tv);
7068 	timevalsub(&tv, &interval);
7069 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7070 		return;
7071 
7072 	pi = vi->pi;
7073 	sc = vi->adapter;
7074 	tnl_cong_drops = 0;
7075 	t4_get_port_stats(sc, pi->tx_chan, &pi->stats);
7076 	chan_map = pi->rx_e_chan_map;
7077 	while (chan_map) {
7078 		i = ffs(chan_map) - 1;
7079 		mtx_lock(&sc->reg_lock);
7080 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7081 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7082 		mtx_unlock(&sc->reg_lock);
7083 		tnl_cong_drops += v;
7084 		chan_map &= ~(1 << i);
7085 	}
7086 	pi->tnl_cong_drops = tnl_cong_drops;
7087 	getmicrotime(&vi->last_refreshed);
7088 }
7089 
7090 static void
7091 cxgbe_tick(void *arg)
7092 {
7093 	struct vi_info *vi = arg;
7094 
7095 	MPASS(IS_MAIN_VI(vi));
7096 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7097 
7098 	cxgbe_refresh_stats(vi);
7099 	callout_schedule(&vi->tick, hz);
7100 }
7101 
7102 static void
7103 vi_tick(void *arg)
7104 {
7105 	struct vi_info *vi = arg;
7106 
7107 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7108 
7109 	vi_refresh_stats(vi);
7110 	callout_schedule(&vi->tick, hz);
7111 }
7112 
7113 /*
7114  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7115  */
7116 static char *caps_decoder[] = {
7117 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7118 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7119 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7120 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7121 	    "\006HASHFILTER\007ETHOFLD",
7122 	"\20\001TOE",					/* 4: TOE */
7123 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7124 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7125 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7126 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7127 	    "\007T10DIF"
7128 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7129 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7130 	    "\004TLS_HW",
7131 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7132 		    "\004PO_INITIATOR\005PO_TARGET",
7133 };
7134 
7135 void
7136 t4_sysctls(struct adapter *sc)
7137 {
7138 	struct sysctl_ctx_list *ctx;
7139 	struct sysctl_oid *oid;
7140 	struct sysctl_oid_list *children, *c0;
7141 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7142 
7143 	ctx = device_get_sysctl_ctx(sc->dev);
7144 
7145 	/*
7146 	 * dev.t4nex.X.
7147 	 */
7148 	oid = device_get_sysctl_tree(sc->dev);
7149 	c0 = children = SYSCTL_CHILDREN(oid);
7150 
7151 	sc->sc_do_rxcopy = 1;
7152 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7153 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7154 
7155 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7156 	    sc->params.nports, "# of ports");
7157 
7158 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7159 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7160 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7161 	    "available doorbells");
7162 
7163 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7164 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7165 
7166 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7167 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7168 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7169 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7170 
7171 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7172 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7173 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7174 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7175 
7176 	t4_sge_sysctls(sc, ctx, children);
7177 
7178 	sc->lro_timeout = 100;
7179 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7180 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7181 
7182 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7183 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7184 
7185 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7186 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7187 
7188 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7189 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7190 
7191 	if (sc->flags & IS_VF)
7192 		return;
7193 
7194 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7195 	    NULL, chip_rev(sc), "chip hardware revision");
7196 
7197 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7198 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7199 
7200 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7201 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7202 
7203 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7204 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7205 
7206 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7207 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7208 
7209 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7210 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7211 
7212 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7213 	    sc->er_version, 0, "expansion ROM version");
7214 
7215 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7216 	    sc->bs_version, 0, "bootstrap firmware version");
7217 
7218 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7219 	    NULL, sc->params.scfg_vers, "serial config version");
7220 
7221 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7222 	    NULL, sc->params.vpd_vers, "VPD version");
7223 
7224 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7225 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7226 
7227 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7228 	    sc->cfcsum, "config file checksum");
7229 
7230 #define SYSCTL_CAP(name, n, text) \
7231 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7232 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7233 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7234 	    "available " text " capabilities")
7235 
7236 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7237 	SYSCTL_CAP(linkcaps, 1, "link");
7238 	SYSCTL_CAP(switchcaps, 2, "switch");
7239 	SYSCTL_CAP(niccaps, 3, "NIC");
7240 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7241 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7242 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7243 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7244 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7245 #undef SYSCTL_CAP
7246 
7247 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7248 	    NULL, sc->tids.nftids, "number of filters");
7249 
7250 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7251 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7252 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7253 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7254 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7255 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7256 
7257 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7258 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7259 	    sysctl_loadavg, "A",
7260 	    "microprocessor load averages (debug firmwares only)");
7261 
7262 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7263 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7264 	    "I", "core Vdd (in mV)");
7265 
7266 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7267 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7268 	    sysctl_cpus, "A", "local CPUs");
7269 
7270 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7271 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7272 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7273 
7274 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7275 	    &sc->swintr, 0, "software triggered interrupts");
7276 
7277 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7278 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7279 	    "1 = reset adapter, 0 = zero reset counter");
7280 
7281 	/*
7282 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7283 	 */
7284 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7285 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7286 	    "logs and miscellaneous information");
7287 	children = SYSCTL_CHILDREN(oid);
7288 
7289 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7290 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7291 	    sysctl_cctrl, "A", "congestion control");
7292 
7293 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7294 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7295 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7296 
7297 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7298 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7299 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7300 
7301 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7302 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7303 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7304 
7305 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7306 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7307 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7308 
7309 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7310 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7311 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7312 
7313 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7314 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7315 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7316 
7317 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7318 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7319 	    sysctl_cim_la, "A", "CIM logic analyzer");
7320 
7321 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7322 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7323 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7324 
7325 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7326 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7327 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7328 
7329 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7330 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7331 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7332 
7333 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7334 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7335 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7336 
7337 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7338 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7339 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7340 
7341 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7342 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7343 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7344 
7345 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7346 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7347 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7348 
7349 	if (chip_id(sc) > CHELSIO_T4) {
7350 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7351 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7352 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7353 		    "CIM OBQ 6 (SGE0-RX)");
7354 
7355 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7356 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7357 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7358 		    "CIM OBQ 7 (SGE1-RX)");
7359 	}
7360 
7361 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7362 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7363 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7364 
7365 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7366 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7367 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7368 
7369 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7370 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7371 	    sysctl_cpl_stats, "A", "CPL statistics");
7372 
7373 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7374 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7375 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7376 
7377 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7378 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7379 	    sysctl_tid_stats, "A", "tid stats");
7380 
7381 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7382 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7383 	    sysctl_devlog, "A", "firmware's device log");
7384 
7385 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7386 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7387 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7388 
7389 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7390 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7391 	    sysctl_hw_sched, "A", "hardware scheduler ");
7392 
7393 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7394 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7395 	    sysctl_l2t, "A", "hardware L2 table");
7396 
7397 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7398 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7399 	    sysctl_smt, "A", "hardware source MAC table");
7400 
7401 #ifdef INET6
7402 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7403 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7404 	    sysctl_clip, "A", "active CLIP table entries");
7405 #endif
7406 
7407 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7408 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7409 	    sysctl_lb_stats, "A", "loopback statistics");
7410 
7411 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7412 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7413 	    sysctl_meminfo, "A", "memory regions");
7414 
7415 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7416 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7417 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7418 	    "A", "MPS TCAM entries");
7419 
7420 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7421 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7422 	    sysctl_path_mtus, "A", "path MTUs");
7423 
7424 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7425 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7426 	    sysctl_pm_stats, "A", "PM statistics");
7427 
7428 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7429 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7430 	    sysctl_rdma_stats, "A", "RDMA statistics");
7431 
7432 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7433 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7434 	    sysctl_tcp_stats, "A", "TCP statistics");
7435 
7436 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7437 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7438 	    sysctl_tids, "A", "TID information");
7439 
7440 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7441 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7442 	    sysctl_tp_err_stats, "A", "TP error statistics");
7443 
7444 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7445 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7446 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7447 
7448 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7449 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7450 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7451 
7452 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7453 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7454 	    sysctl_tp_la, "A", "TP logic analyzer");
7455 
7456 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7457 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7458 	    sysctl_tx_rate, "A", "Tx rate");
7459 
7460 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7461 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7462 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7463 
7464 	if (chip_id(sc) >= CHELSIO_T5) {
7465 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7466 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7467 		    sysctl_wcwr_stats, "A", "write combined work requests");
7468 	}
7469 
7470 #ifdef KERN_TLS
7471 	if (is_ktls(sc)) {
7472 		/*
7473 		 * dev.t4nex.0.tls.
7474 		 */
7475 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7476 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7477 		children = SYSCTL_CHILDREN(oid);
7478 
7479 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7480 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7481 		    "keys in work requests (1) or attempt to store TLS keys "
7482 		    "in card memory.");
7483 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7484 		    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to combine "
7485 		    "TCB field updates with TLS record work requests.");
7486 	}
7487 #endif
7488 
7489 #ifdef TCP_OFFLOAD
7490 	if (is_offload(sc)) {
7491 		int i;
7492 		char s[4];
7493 
7494 		/*
7495 		 * dev.t4nex.X.toe.
7496 		 */
7497 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7498 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7499 		children = SYSCTL_CHILDREN(oid);
7500 
7501 		sc->tt.cong_algorithm = -1;
7502 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7503 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7504 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7505 		    "3 = highspeed)");
7506 
7507 		sc->tt.sndbuf = -1;
7508 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7509 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7510 
7511 		sc->tt.ddp = 0;
7512 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7513 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7514 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7515 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7516 
7517 		sc->tt.rx_coalesce = -1;
7518 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7519 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7520 
7521 		sc->tt.tls = 0;
7522 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7523 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7524 		    "Inline TLS allowed");
7525 
7526 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_ports",
7527 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7528 		    sysctl_tls_rx_ports, "I",
7529 		    "TCP ports that use inline TLS+TOE RX");
7530 
7531 		sc->tt.tls_rx_timeout = t4_toe_tls_rx_timeout;
7532 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_timeout",
7533 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7534 		    sysctl_tls_rx_timeout, "I",
7535 		    "Timeout in seconds to downgrade TLS sockets to plain TOE");
7536 
7537 		sc->tt.tx_align = -1;
7538 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7539 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7540 
7541 		sc->tt.tx_zcopy = 0;
7542 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7543 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7544 		    "Enable zero-copy aio_write(2)");
7545 
7546 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7547 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7548 		    "cop_managed_offloading", CTLFLAG_RW,
7549 		    &sc->tt.cop_managed_offloading, 0,
7550 		    "COP (Connection Offload Policy) controls all TOE offload");
7551 
7552 		sc->tt.autorcvbuf_inc = 16 * 1024;
7553 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7554 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7555 		    "autorcvbuf increment");
7556 
7557 		sc->tt.update_hc_on_pmtu_change = 1;
7558 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7559 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7560 		    &sc->tt.update_hc_on_pmtu_change, 0,
7561 		    "Update hostcache entry if the PMTU changes");
7562 
7563 		sc->tt.iso = 1;
7564 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7565 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7566 
7567 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7568 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7569 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7570 
7571 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7572 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7573 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7574 
7575 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7576 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7577 		    sysctl_tp_tick, "A", "DACK tick (us)");
7578 
7579 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7580 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7581 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7582 
7583 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7584 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7585 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7586 		    "Minimum retransmit interval (us)");
7587 
7588 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7589 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7590 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7591 		    "Maximum retransmit interval (us)");
7592 
7593 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7594 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7595 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7596 		    "Persist timer min (us)");
7597 
7598 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7599 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7600 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7601 		    "Persist timer max (us)");
7602 
7603 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7604 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7605 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7606 		    "Keepalive idle timer (us)");
7607 
7608 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7609 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7610 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7611 		    "Keepalive interval timer (us)");
7612 
7613 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7614 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7615 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7616 
7617 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7618 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7619 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7620 		    "FINWAIT2 timer (us)");
7621 
7622 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7623 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7624 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7625 		    "Number of SYN retransmissions before abort");
7626 
7627 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7628 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7629 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7630 		    "Number of retransmissions before abort");
7631 
7632 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7633 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7634 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7635 		    "Number of keepalive probes before abort");
7636 
7637 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7638 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7639 		    "TOE retransmit backoffs");
7640 		children = SYSCTL_CHILDREN(oid);
7641 		for (i = 0; i < 16; i++) {
7642 			snprintf(s, sizeof(s), "%u", i);
7643 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7644 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7645 			    i, sysctl_tp_backoff, "IU",
7646 			    "TOE retransmit backoff");
7647 		}
7648 	}
7649 #endif
7650 }
7651 
7652 void
7653 vi_sysctls(struct vi_info *vi)
7654 {
7655 	struct sysctl_ctx_list *ctx;
7656 	struct sysctl_oid *oid;
7657 	struct sysctl_oid_list *children;
7658 
7659 	ctx = device_get_sysctl_ctx(vi->dev);
7660 
7661 	/*
7662 	 * dev.v?(cxgbe|cxl).X.
7663 	 */
7664 	oid = device_get_sysctl_tree(vi->dev);
7665 	children = SYSCTL_CHILDREN(oid);
7666 
7667 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7668 	    vi->viid, "VI identifer");
7669 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7670 	    &vi->nrxq, 0, "# of rx queues");
7671 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7672 	    &vi->ntxq, 0, "# of tx queues");
7673 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7674 	    &vi->first_rxq, 0, "index of first rx queue");
7675 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7676 	    &vi->first_txq, 0, "index of first tx queue");
7677 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7678 	    vi->rss_base, "start of RSS indirection table");
7679 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7680 	    vi->rss_size, "size of RSS indirection table");
7681 
7682 	if (IS_MAIN_VI(vi)) {
7683 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7684 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7685 		    sysctl_noflowq, "IU",
7686 		    "Reserve queue 0 for non-flowid packets");
7687 	}
7688 
7689 	if (vi->adapter->flags & IS_VF) {
7690 		MPASS(vi->flags & TX_USES_VM_WR);
7691 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7692 		    NULL, 1, "use VM work requests for transmit");
7693 	} else {
7694 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7695 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7696 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7697 	}
7698 
7699 #ifdef TCP_OFFLOAD
7700 	if (vi->nofldrxq != 0) {
7701 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7702 		    &vi->nofldrxq, 0,
7703 		    "# of rx queues for offloaded TCP connections");
7704 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7705 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7706 		    "index of first TOE rx queue");
7707 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7708 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7709 		    sysctl_holdoff_tmr_idx_ofld, "I",
7710 		    "holdoff timer index for TOE queues");
7711 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7712 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7713 		    sysctl_holdoff_pktc_idx_ofld, "I",
7714 		    "holdoff packet counter index for TOE queues");
7715 	}
7716 #endif
7717 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7718 	if (vi->nofldtxq != 0) {
7719 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7720 		    &vi->nofldtxq, 0,
7721 		    "# of tx queues for TOE/ETHOFLD");
7722 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7723 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7724 		    "index of first TOE/ETHOFLD tx queue");
7725 	}
7726 #endif
7727 #ifdef DEV_NETMAP
7728 	if (vi->nnmrxq != 0) {
7729 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7730 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7731 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7732 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7733 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7734 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7735 		    "index of first netmap rx queue");
7736 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7737 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7738 		    "index of first netmap tx queue");
7739 	}
7740 #endif
7741 
7742 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7743 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7744 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7745 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7746 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7747 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7748 
7749 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7750 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7751 	    sysctl_qsize_rxq, "I", "rx queue size");
7752 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7753 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7754 	    sysctl_qsize_txq, "I", "tx queue size");
7755 }
7756 
7757 static void
7758 cxgbe_sysctls(struct port_info *pi)
7759 {
7760 	struct sysctl_ctx_list *ctx;
7761 	struct sysctl_oid *oid;
7762 	struct sysctl_oid_list *children, *children2;
7763 	struct adapter *sc = pi->adapter;
7764 	int i;
7765 	char name[16];
7766 	static char *tc_flags = {"\20\1USER"};
7767 
7768 	ctx = device_get_sysctl_ctx(pi->dev);
7769 
7770 	/*
7771 	 * dev.cxgbe.X.
7772 	 */
7773 	oid = device_get_sysctl_tree(pi->dev);
7774 	children = SYSCTL_CHILDREN(oid);
7775 
7776 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7777 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7778 	    sysctl_linkdnrc, "A", "reason why link is down");
7779 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7780 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7781 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7782 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
7783 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7784 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7785 		    sysctl_btphy, "I", "PHY firmware version");
7786 	}
7787 
7788 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7789 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7790 	    sysctl_pause_settings, "A",
7791 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7792 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
7793 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
7794 	    "FEC in use on the link");
7795 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
7796 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7797 	    sysctl_requested_fec, "A",
7798 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7799 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7800 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7801 	    "FEC recommended by the cable/transceiver");
7802 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7803 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7804 	    sysctl_autoneg, "I",
7805 	    "autonegotiation (-1 = not supported)");
7806 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
7807 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7808 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
7809 
7810 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
7811 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
7812 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7813 	    &pi->link_cfg.pcaps, 0, "port capabilities");
7814 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7815 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
7816 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7817 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7818 
7819 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7820 	    port_top_speed(pi), "max speed (in Gbps)");
7821 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7822 	    pi->mps_bg_map, "MPS buffer group map");
7823 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
7824 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
7825 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_c_chan", CTLFLAG_RD, NULL,
7826 	    pi->rx_c_chan, "TP rx c-channel");
7827 
7828 	if (sc->flags & IS_VF)
7829 		return;
7830 
7831 	/*
7832 	 * dev.(cxgbe|cxl).X.tc.
7833 	 */
7834 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
7835 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7836 	    "Tx scheduler traffic classes (cl_rl)");
7837 	children2 = SYSCTL_CHILDREN(oid);
7838 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
7839 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
7840 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
7841 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
7842 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
7843 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
7844 	for (i = 0; i < sc->params.nsched_cls; i++) {
7845 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
7846 
7847 		snprintf(name, sizeof(name), "%d", i);
7848 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
7849 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
7850 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
7851 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
7852 		    CTLFLAG_RD, &tc->state, 0, "current state");
7853 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
7854 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
7855 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
7856 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
7857 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
7858 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
7859 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7860 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
7861 		    "traffic class parameters");
7862 	}
7863 
7864 	/*
7865 	 * dev.cxgbe.X.stats.
7866 	 */
7867 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
7868 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
7869 	children = SYSCTL_CHILDREN(oid);
7870 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
7871 	    &pi->tx_parse_error, 0,
7872 	    "# of tx packets with invalid length or # of segments");
7873 
7874 #define T4_REGSTAT(name, stat, desc) \
7875     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
7876         CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
7877 	(is_t4(sc) ? PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L) : \
7878 	T5_PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L)), \
7879         sysctl_handle_t4_reg64, "QU", desc)
7880 
7881 /* We get these from port_stats and they may be stale by up to 1s */
7882 #define T4_PORTSTAT(name, desc) \
7883 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
7884 	    &pi->stats.name, desc)
7885 
7886 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
7887 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
7888 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
7889 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
7890 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
7891 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
7892 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
7893 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
7894 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
7895 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
7896 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
7897 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
7898 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
7899 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
7900 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
7901 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
7902 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
7903 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
7904 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
7905 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
7906 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
7907 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
7908 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
7909 
7910 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
7911 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
7912 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
7913 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
7914 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
7915 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
7916 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
7917 	if (is_t6(sc)) {
7918 		T4_PORTSTAT(rx_fcs_err,
7919 		    "# of frames received with bad FCS since last link up");
7920 	} else {
7921 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
7922 		    "# of frames received with bad FCS");
7923 	}
7924 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
7925 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
7926 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
7927 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
7928 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
7929 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
7930 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
7931 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
7932 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
7933 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
7934 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
7935 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
7936 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
7937 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
7938 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
7939 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
7940 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
7941 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
7942 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
7943 
7944 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
7945 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
7946 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
7947 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
7948 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
7949 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
7950 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
7951 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
7952 
7953 #undef T4_REGSTAT
7954 #undef T4_PORTSTAT
7955 }
7956 
7957 static int
7958 sysctl_int_array(SYSCTL_HANDLER_ARGS)
7959 {
7960 	int rc, *i, space = 0;
7961 	struct sbuf sb;
7962 
7963 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
7964 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
7965 		if (space)
7966 			sbuf_printf(&sb, " ");
7967 		sbuf_printf(&sb, "%d", *i);
7968 		space = 1;
7969 	}
7970 	rc = sbuf_finish(&sb);
7971 	sbuf_delete(&sb);
7972 	return (rc);
7973 }
7974 
7975 static int
7976 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
7977 {
7978 	int rc;
7979 	struct sbuf *sb;
7980 
7981 	rc = sysctl_wire_old_buffer(req, 0);
7982 	if (rc != 0)
7983 		return(rc);
7984 
7985 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7986 	if (sb == NULL)
7987 		return (ENOMEM);
7988 
7989 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
7990 	rc = sbuf_finish(sb);
7991 	sbuf_delete(sb);
7992 
7993 	return (rc);
7994 }
7995 
7996 static int
7997 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
7998 {
7999 	int rc;
8000 	struct sbuf *sb;
8001 
8002 	rc = sysctl_wire_old_buffer(req, 0);
8003 	if (rc != 0)
8004 		return(rc);
8005 
8006 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8007 	if (sb == NULL)
8008 		return (ENOMEM);
8009 
8010 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8011 	rc = sbuf_finish(sb);
8012 	sbuf_delete(sb);
8013 
8014 	return (rc);
8015 }
8016 
8017 static int
8018 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8019 {
8020 	struct port_info *pi = arg1;
8021 	int op = arg2;
8022 	struct adapter *sc = pi->adapter;
8023 	u_int v;
8024 	int rc;
8025 
8026 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8027 	if (rc)
8028 		return (rc);
8029 	if (hw_off_limits(sc))
8030 		rc = ENXIO;
8031 	else {
8032 		/* XXX: magic numbers */
8033 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8034 		    op ? 0x20 : 0xc820, &v);
8035 	}
8036 	end_synchronized_op(sc, 0);
8037 	if (rc)
8038 		return (rc);
8039 	if (op == 0)
8040 		v /= 256;
8041 
8042 	rc = sysctl_handle_int(oidp, &v, 0, req);
8043 	return (rc);
8044 }
8045 
8046 static int
8047 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8048 {
8049 	struct vi_info *vi = arg1;
8050 	int rc, val;
8051 
8052 	val = vi->rsrv_noflowq;
8053 	rc = sysctl_handle_int(oidp, &val, 0, req);
8054 	if (rc != 0 || req->newptr == NULL)
8055 		return (rc);
8056 
8057 	if ((val >= 1) && (vi->ntxq > 1))
8058 		vi->rsrv_noflowq = 1;
8059 	else
8060 		vi->rsrv_noflowq = 0;
8061 
8062 	return (rc);
8063 }
8064 
8065 static int
8066 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8067 {
8068 	struct vi_info *vi = arg1;
8069 	struct adapter *sc = vi->adapter;
8070 	int rc, val, i;
8071 
8072 	MPASS(!(sc->flags & IS_VF));
8073 
8074 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8075 	rc = sysctl_handle_int(oidp, &val, 0, req);
8076 	if (rc != 0 || req->newptr == NULL)
8077 		return (rc);
8078 
8079 	if (val != 0 && val != 1)
8080 		return (EINVAL);
8081 
8082 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8083 	    "t4txvm");
8084 	if (rc)
8085 		return (rc);
8086 	if (hw_off_limits(sc))
8087 		rc = ENXIO;
8088 	else if (vi->ifp->if_drv_flags & IFF_DRV_RUNNING) {
8089 		/*
8090 		 * We don't want parse_pkt to run with one setting (VF or PF)
8091 		 * and then eth_tx to see a different setting but still use
8092 		 * stale information calculated by parse_pkt.
8093 		 */
8094 		rc = EBUSY;
8095 	} else {
8096 		struct port_info *pi = vi->pi;
8097 		struct sge_txq *txq;
8098 		uint32_t ctrl0;
8099 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8100 
8101 		if (val) {
8102 			vi->flags |= TX_USES_VM_WR;
8103 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
8104 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8105 			    V_TXPKT_INTF(pi->tx_chan));
8106 			if (!(sc->flags & IS_VF))
8107 				npkt--;
8108 		} else {
8109 			vi->flags &= ~TX_USES_VM_WR;
8110 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
8111 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8112 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8113 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8114 		}
8115 		for_each_txq(vi, i, txq) {
8116 			txq->cpl_ctrl0 = ctrl0;
8117 			txq->txp.max_npkt = npkt;
8118 		}
8119 	}
8120 	end_synchronized_op(sc, LOCK_HELD);
8121 	return (rc);
8122 }
8123 
8124 static int
8125 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8126 {
8127 	struct vi_info *vi = arg1;
8128 	struct adapter *sc = vi->adapter;
8129 	int idx, rc, i;
8130 	struct sge_rxq *rxq;
8131 	uint8_t v;
8132 
8133 	idx = vi->tmr_idx;
8134 
8135 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8136 	if (rc != 0 || req->newptr == NULL)
8137 		return (rc);
8138 
8139 	if (idx < 0 || idx >= SGE_NTIMERS)
8140 		return (EINVAL);
8141 
8142 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8143 	    "t4tmr");
8144 	if (rc)
8145 		return (rc);
8146 
8147 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8148 	for_each_rxq(vi, i, rxq) {
8149 #ifdef atomic_store_rel_8
8150 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8151 #else
8152 		rxq->iq.intr_params = v;
8153 #endif
8154 	}
8155 	vi->tmr_idx = idx;
8156 
8157 	end_synchronized_op(sc, LOCK_HELD);
8158 	return (0);
8159 }
8160 
8161 static int
8162 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8163 {
8164 	struct vi_info *vi = arg1;
8165 	struct adapter *sc = vi->adapter;
8166 	int idx, rc;
8167 
8168 	idx = vi->pktc_idx;
8169 
8170 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8171 	if (rc != 0 || req->newptr == NULL)
8172 		return (rc);
8173 
8174 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8175 		return (EINVAL);
8176 
8177 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8178 	    "t4pktc");
8179 	if (rc)
8180 		return (rc);
8181 
8182 	if (vi->flags & VI_INIT_DONE)
8183 		rc = EBUSY; /* cannot be changed once the queues are created */
8184 	else
8185 		vi->pktc_idx = idx;
8186 
8187 	end_synchronized_op(sc, LOCK_HELD);
8188 	return (rc);
8189 }
8190 
8191 static int
8192 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8193 {
8194 	struct vi_info *vi = arg1;
8195 	struct adapter *sc = vi->adapter;
8196 	int qsize, rc;
8197 
8198 	qsize = vi->qsize_rxq;
8199 
8200 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8201 	if (rc != 0 || req->newptr == NULL)
8202 		return (rc);
8203 
8204 	if (qsize < 128 || (qsize & 7))
8205 		return (EINVAL);
8206 
8207 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8208 	    "t4rxqs");
8209 	if (rc)
8210 		return (rc);
8211 
8212 	if (vi->flags & VI_INIT_DONE)
8213 		rc = EBUSY; /* cannot be changed once the queues are created */
8214 	else
8215 		vi->qsize_rxq = qsize;
8216 
8217 	end_synchronized_op(sc, LOCK_HELD);
8218 	return (rc);
8219 }
8220 
8221 static int
8222 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8223 {
8224 	struct vi_info *vi = arg1;
8225 	struct adapter *sc = vi->adapter;
8226 	int qsize, rc;
8227 
8228 	qsize = vi->qsize_txq;
8229 
8230 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8231 	if (rc != 0 || req->newptr == NULL)
8232 		return (rc);
8233 
8234 	if (qsize < 128 || qsize > 65536)
8235 		return (EINVAL);
8236 
8237 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8238 	    "t4txqs");
8239 	if (rc)
8240 		return (rc);
8241 
8242 	if (vi->flags & VI_INIT_DONE)
8243 		rc = EBUSY; /* cannot be changed once the queues are created */
8244 	else
8245 		vi->qsize_txq = qsize;
8246 
8247 	end_synchronized_op(sc, LOCK_HELD);
8248 	return (rc);
8249 }
8250 
8251 static int
8252 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8253 {
8254 	struct port_info *pi = arg1;
8255 	struct adapter *sc = pi->adapter;
8256 	struct link_config *lc = &pi->link_cfg;
8257 	int rc;
8258 
8259 	if (req->newptr == NULL) {
8260 		struct sbuf *sb;
8261 		static char *bits = "\20\1RX\2TX\3AUTO";
8262 
8263 		rc = sysctl_wire_old_buffer(req, 0);
8264 		if (rc != 0)
8265 			return(rc);
8266 
8267 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8268 		if (sb == NULL)
8269 			return (ENOMEM);
8270 
8271 		if (lc->link_ok) {
8272 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8273 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8274 		} else {
8275 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8276 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8277 		}
8278 		rc = sbuf_finish(sb);
8279 		sbuf_delete(sb);
8280 	} else {
8281 		char s[2];
8282 		int n;
8283 
8284 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8285 		    PAUSE_AUTONEG));
8286 		s[1] = 0;
8287 
8288 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8289 		if (rc != 0)
8290 			return(rc);
8291 
8292 		if (s[1] != 0)
8293 			return (EINVAL);
8294 		if (s[0] < '0' || s[0] > '9')
8295 			return (EINVAL);	/* not a number */
8296 		n = s[0] - '0';
8297 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8298 			return (EINVAL);	/* some other bit is set too */
8299 
8300 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8301 		    "t4PAUSE");
8302 		if (rc)
8303 			return (rc);
8304 		if (!hw_off_limits(sc)) {
8305 			PORT_LOCK(pi);
8306 			lc->requested_fc = n;
8307 			fixup_link_config(pi);
8308 			if (pi->up_vis > 0)
8309 				rc = apply_link_config(pi);
8310 			set_current_media(pi);
8311 			PORT_UNLOCK(pi);
8312 		}
8313 		end_synchronized_op(sc, 0);
8314 	}
8315 
8316 	return (rc);
8317 }
8318 
8319 static int
8320 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
8321 {
8322 	struct port_info *pi = arg1;
8323 	struct link_config *lc = &pi->link_cfg;
8324 	int rc;
8325 	struct sbuf *sb;
8326 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2";
8327 
8328 	rc = sysctl_wire_old_buffer(req, 0);
8329 	if (rc != 0)
8330 		return(rc);
8331 
8332 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8333 	if (sb == NULL)
8334 		return (ENOMEM);
8335 	if (lc->link_ok)
8336 		sbuf_printf(sb, "%b", lc->fec, bits);
8337 	else
8338 		sbuf_printf(sb, "no link");
8339 	rc = sbuf_finish(sb);
8340 	sbuf_delete(sb);
8341 
8342 	return (rc);
8343 }
8344 
8345 static int
8346 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
8347 {
8348 	struct port_info *pi = arg1;
8349 	struct adapter *sc = pi->adapter;
8350 	struct link_config *lc = &pi->link_cfg;
8351 	int rc;
8352 	int8_t old;
8353 
8354 	if (req->newptr == NULL) {
8355 		struct sbuf *sb;
8356 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8357 		    "\5RSVD3\6auto\7module";
8358 
8359 		rc = sysctl_wire_old_buffer(req, 0);
8360 		if (rc != 0)
8361 			return(rc);
8362 
8363 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8364 		if (sb == NULL)
8365 			return (ENOMEM);
8366 
8367 		sbuf_printf(sb, "%b", lc->requested_fec, bits);
8368 		rc = sbuf_finish(sb);
8369 		sbuf_delete(sb);
8370 	} else {
8371 		char s[8];
8372 		int n;
8373 
8374 		snprintf(s, sizeof(s), "%d",
8375 		    lc->requested_fec == FEC_AUTO ? -1 :
8376 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8377 
8378 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8379 		if (rc != 0)
8380 			return(rc);
8381 
8382 		n = strtol(&s[0], NULL, 0);
8383 		if (n < 0 || n & FEC_AUTO)
8384 			n = FEC_AUTO;
8385 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8386 			return (EINVAL);/* some other bit is set too */
8387 
8388 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8389 		    "t4reqf");
8390 		if (rc)
8391 			return (rc);
8392 		PORT_LOCK(pi);
8393 		old = lc->requested_fec;
8394 		if (n == FEC_AUTO)
8395 			lc->requested_fec = FEC_AUTO;
8396 		else if (n == 0 || n == FEC_NONE)
8397 			lc->requested_fec = FEC_NONE;
8398 		else {
8399 			if ((lc->pcaps |
8400 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8401 			    lc->pcaps) {
8402 				rc = ENOTSUP;
8403 				goto done;
8404 			}
8405 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8406 			    FEC_MODULE);
8407 		}
8408 		if (!hw_off_limits(sc)) {
8409 			fixup_link_config(pi);
8410 			if (pi->up_vis > 0) {
8411 				rc = apply_link_config(pi);
8412 				if (rc != 0) {
8413 					lc->requested_fec = old;
8414 					if (rc == FW_EPROTO)
8415 						rc = ENOTSUP;
8416 				}
8417 			}
8418 		}
8419 done:
8420 		PORT_UNLOCK(pi);
8421 		end_synchronized_op(sc, 0);
8422 	}
8423 
8424 	return (rc);
8425 }
8426 
8427 static int
8428 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8429 {
8430 	struct port_info *pi = arg1;
8431 	struct adapter *sc = pi->adapter;
8432 	struct link_config *lc = &pi->link_cfg;
8433 	int rc;
8434 	int8_t fec;
8435 	struct sbuf *sb;
8436 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8437 
8438 	rc = sysctl_wire_old_buffer(req, 0);
8439 	if (rc != 0)
8440 		return (rc);
8441 
8442 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8443 	if (sb == NULL)
8444 		return (ENOMEM);
8445 
8446 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8447 		rc = EBUSY;
8448 		goto done;
8449 	}
8450 	if (hw_off_limits(sc)) {
8451 		rc = ENXIO;
8452 		goto done;
8453 	}
8454 	PORT_LOCK(pi);
8455 	if (pi->up_vis == 0) {
8456 		/*
8457 		 * If all the interfaces are administratively down the firmware
8458 		 * does not report transceiver changes.  Refresh port info here.
8459 		 * This is the only reason we have a synchronized op in this
8460 		 * function.  Just PORT_LOCK would have been enough otherwise.
8461 		 */
8462 		t4_update_port_info(pi);
8463 	}
8464 
8465 	fec = lc->fec_hint;
8466 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8467 	    !fec_supported(lc->pcaps)) {
8468 		sbuf_printf(sb, "n/a");
8469 	} else {
8470 		if (fec == 0)
8471 			fec = FEC_NONE;
8472 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8473 	}
8474 	rc = sbuf_finish(sb);
8475 	PORT_UNLOCK(pi);
8476 done:
8477 	sbuf_delete(sb);
8478 	end_synchronized_op(sc, 0);
8479 
8480 	return (rc);
8481 }
8482 
8483 static int
8484 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8485 {
8486 	struct port_info *pi = arg1;
8487 	struct adapter *sc = pi->adapter;
8488 	struct link_config *lc = &pi->link_cfg;
8489 	int rc, val;
8490 
8491 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8492 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8493 	else
8494 		val = -1;
8495 	rc = sysctl_handle_int(oidp, &val, 0, req);
8496 	if (rc != 0 || req->newptr == NULL)
8497 		return (rc);
8498 	if (val == 0)
8499 		val = AUTONEG_DISABLE;
8500 	else if (val == 1)
8501 		val = AUTONEG_ENABLE;
8502 	else
8503 		val = AUTONEG_AUTO;
8504 
8505 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8506 	    "t4aneg");
8507 	if (rc)
8508 		return (rc);
8509 	PORT_LOCK(pi);
8510 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8511 		rc = ENOTSUP;
8512 		goto done;
8513 	}
8514 	lc->requested_aneg = val;
8515 	if (!hw_off_limits(sc)) {
8516 		fixup_link_config(pi);
8517 		if (pi->up_vis > 0)
8518 			rc = apply_link_config(pi);
8519 		set_current_media(pi);
8520 	}
8521 done:
8522 	PORT_UNLOCK(pi);
8523 	end_synchronized_op(sc, 0);
8524 	return (rc);
8525 }
8526 
8527 static int
8528 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
8529 {
8530 	struct port_info *pi = arg1;
8531 	struct adapter *sc = pi->adapter;
8532 	struct link_config *lc = &pi->link_cfg;
8533 	int rc, val;
8534 
8535 	val = lc->force_fec;
8536 	MPASS(val >= -1 && val <= 1);
8537 	rc = sysctl_handle_int(oidp, &val, 0, req);
8538 	if (rc != 0 || req->newptr == NULL)
8539 		return (rc);
8540 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
8541 		return (ENOTSUP);
8542 	if (val < -1 || val > 1)
8543 		return (EINVAL);
8544 
8545 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
8546 	if (rc)
8547 		return (rc);
8548 	PORT_LOCK(pi);
8549 	lc->force_fec = val;
8550 	if (!hw_off_limits(sc)) {
8551 		fixup_link_config(pi);
8552 		if (pi->up_vis > 0)
8553 			rc = apply_link_config(pi);
8554 	}
8555 	PORT_UNLOCK(pi);
8556 	end_synchronized_op(sc, 0);
8557 	return (rc);
8558 }
8559 
8560 static int
8561 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8562 {
8563 	struct adapter *sc = arg1;
8564 	int rc, reg = arg2;
8565 	uint64_t val;
8566 
8567 	mtx_lock(&sc->reg_lock);
8568 	if (hw_off_limits(sc))
8569 		rc = ENXIO;
8570 	else {
8571 		rc = 0;
8572 		val = t4_read_reg64(sc, reg);
8573 	}
8574 	mtx_unlock(&sc->reg_lock);
8575 	if (rc == 0)
8576 		rc = sysctl_handle_64(oidp, &val, 0, req);
8577 	return (rc);
8578 }
8579 
8580 static int
8581 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8582 {
8583 	struct adapter *sc = arg1;
8584 	int rc, t;
8585 	uint32_t param, val;
8586 
8587 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
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_TMP);
8596 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8597 	}
8598 	end_synchronized_op(sc, 0);
8599 	if (rc)
8600 		return (rc);
8601 
8602 	/* unknown is returned as 0 but we display -1 in that case */
8603 	t = val == 0 ? -1 : val;
8604 
8605 	rc = sysctl_handle_int(oidp, &t, 0, req);
8606 	return (rc);
8607 }
8608 
8609 static int
8610 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8611 {
8612 	struct adapter *sc = arg1;
8613 	int rc;
8614 	uint32_t param, val;
8615 
8616 	if (sc->params.core_vdd == 0) {
8617 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8618 		    "t4vdd");
8619 		if (rc)
8620 			return (rc);
8621 		if (hw_off_limits(sc))
8622 			rc = ENXIO;
8623 		else {
8624 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8625 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8626 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8627 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8628 			    &param, &val);
8629 		}
8630 		end_synchronized_op(sc, 0);
8631 		if (rc)
8632 			return (rc);
8633 		sc->params.core_vdd = val;
8634 	}
8635 
8636 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8637 }
8638 
8639 static int
8640 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8641 {
8642 	struct adapter *sc = arg1;
8643 	int rc, v;
8644 	uint32_t param, val;
8645 
8646 	v = sc->sensor_resets;
8647 	rc = sysctl_handle_int(oidp, &v, 0, req);
8648 	if (rc != 0 || req->newptr == NULL || v <= 0)
8649 		return (rc);
8650 
8651 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8652 	    chip_id(sc) < CHELSIO_T5)
8653 		return (ENOTSUP);
8654 
8655 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8656 	if (rc)
8657 		return (rc);
8658 	if (hw_off_limits(sc))
8659 		rc = ENXIO;
8660 	else {
8661 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8662 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8663 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8664 		val = 1;
8665 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8666 	}
8667 	end_synchronized_op(sc, 0);
8668 	if (rc == 0)
8669 		sc->sensor_resets++;
8670 	return (rc);
8671 }
8672 
8673 static int
8674 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8675 {
8676 	struct adapter *sc = arg1;
8677 	struct sbuf *sb;
8678 	int rc;
8679 	uint32_t param, val;
8680 
8681 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8682 	if (rc)
8683 		return (rc);
8684 	if (hw_off_limits(sc))
8685 		rc = ENXIO;
8686 	else {
8687 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8688 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8689 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8690 	}
8691 	end_synchronized_op(sc, 0);
8692 	if (rc)
8693 		return (rc);
8694 
8695 	rc = sysctl_wire_old_buffer(req, 0);
8696 	if (rc != 0)
8697 		return (rc);
8698 
8699 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8700 	if (sb == NULL)
8701 		return (ENOMEM);
8702 
8703 	if (val == 0xffffffff) {
8704 		/* Only debug and custom firmwares report load averages. */
8705 		sbuf_printf(sb, "not available");
8706 	} else {
8707 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8708 		    (val >> 16) & 0xff);
8709 	}
8710 	rc = sbuf_finish(sb);
8711 	sbuf_delete(sb);
8712 
8713 	return (rc);
8714 }
8715 
8716 static int
8717 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8718 {
8719 	struct adapter *sc = arg1;
8720 	struct sbuf *sb;
8721 	int rc, i;
8722 	uint16_t incr[NMTUS][NCCTRL_WIN];
8723 	static const char *dec_fac[] = {
8724 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8725 		"0.9375"
8726 	};
8727 
8728 	rc = sysctl_wire_old_buffer(req, 0);
8729 	if (rc != 0)
8730 		return (rc);
8731 
8732 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8733 	if (sb == NULL)
8734 		return (ENOMEM);
8735 
8736 	mtx_lock(&sc->reg_lock);
8737 	if (hw_off_limits(sc))
8738 		rc = ENXIO;
8739 	else
8740 		t4_read_cong_tbl(sc, incr);
8741 	mtx_unlock(&sc->reg_lock);
8742 	if (rc)
8743 		goto done;
8744 
8745 	for (i = 0; i < NCCTRL_WIN; ++i) {
8746 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8747 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8748 		    incr[5][i], incr[6][i], incr[7][i]);
8749 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8750 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8751 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8752 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8753 	}
8754 
8755 	rc = sbuf_finish(sb);
8756 done:
8757 	sbuf_delete(sb);
8758 	return (rc);
8759 }
8760 
8761 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8762 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8763 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8764 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8765 };
8766 
8767 static int
8768 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8769 {
8770 	struct adapter *sc = arg1;
8771 	struct sbuf *sb;
8772 	int rc, i, n, qid = arg2;
8773 	uint32_t *buf, *p;
8774 	char *qtype;
8775 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8776 
8777 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8778 	    ("%s: bad qid %d\n", __func__, qid));
8779 
8780 	if (qid < CIM_NUM_IBQ) {
8781 		/* inbound queue */
8782 		qtype = "IBQ";
8783 		n = 4 * CIM_IBQ_SIZE;
8784 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8785 		mtx_lock(&sc->reg_lock);
8786 		if (hw_off_limits(sc))
8787 			rc = -ENXIO;
8788 		else
8789 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8790 		mtx_unlock(&sc->reg_lock);
8791 	} else {
8792 		/* outbound queue */
8793 		qtype = "OBQ";
8794 		qid -= CIM_NUM_IBQ;
8795 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8796 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8797 		mtx_lock(&sc->reg_lock);
8798 		if (hw_off_limits(sc))
8799 			rc = -ENXIO;
8800 		else
8801 			rc = t4_read_cim_obq(sc, qid, buf, n);
8802 		mtx_unlock(&sc->reg_lock);
8803 	}
8804 
8805 	if (rc < 0) {
8806 		rc = -rc;
8807 		goto done;
8808 	}
8809 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
8810 
8811 	rc = sysctl_wire_old_buffer(req, 0);
8812 	if (rc != 0)
8813 		goto done;
8814 
8815 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8816 	if (sb == NULL) {
8817 		rc = ENOMEM;
8818 		goto done;
8819 	}
8820 
8821 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8822 	for (i = 0, p = buf; i < n; i += 16, p += 4)
8823 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
8824 		    p[2], p[3]);
8825 
8826 	rc = sbuf_finish(sb);
8827 	sbuf_delete(sb);
8828 done:
8829 	free(buf, M_CXGBE);
8830 	return (rc);
8831 }
8832 
8833 static void
8834 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8835 {
8836 	uint32_t *p;
8837 
8838 	sbuf_printf(sb, "Status   Data      PC%s",
8839 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8840 	    "     LS0Stat  LS0Addr             LS0Data");
8841 
8842 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
8843 		if (cfg & F_UPDBGLACAPTPCONLY) {
8844 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
8845 			    p[6], p[7]);
8846 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
8847 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
8848 			    p[4] & 0xff, p[5] >> 8);
8849 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
8850 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8851 			    p[1] & 0xf, p[2] >> 4);
8852 		} else {
8853 			sbuf_printf(sb,
8854 			    "\n  %02x   %x%07x %x%07x %08x %08x "
8855 			    "%08x%08x%08x%08x",
8856 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8857 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
8858 			    p[6], p[7]);
8859 		}
8860 	}
8861 }
8862 
8863 static void
8864 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8865 {
8866 	uint32_t *p;
8867 
8868 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
8869 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8870 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
8871 
8872 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
8873 		if (cfg & F_UPDBGLACAPTPCONLY) {
8874 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
8875 			    p[3] & 0xff, p[2], p[1], p[0]);
8876 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
8877 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
8878 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
8879 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
8880 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
8881 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
8882 			    p[6] >> 16);
8883 		} else {
8884 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
8885 			    "%08x %08x %08x %08x %08x %08x",
8886 			    (p[9] >> 16) & 0xff,
8887 			    p[9] & 0xffff, p[8] >> 16,
8888 			    p[8] & 0xffff, p[7] >> 16,
8889 			    p[7] & 0xffff, p[6] >> 16,
8890 			    p[2], p[1], p[0], p[5], p[4], p[3]);
8891 		}
8892 	}
8893 }
8894 
8895 static int
8896 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
8897 {
8898 	uint32_t cfg, *buf;
8899 	int rc;
8900 
8901 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
8902 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
8903 	    M_ZERO | flags);
8904 	if (buf == NULL)
8905 		return (ENOMEM);
8906 
8907 	mtx_lock(&sc->reg_lock);
8908 	if (hw_off_limits(sc))
8909 		rc = ENXIO;
8910 	else {
8911 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
8912 		if (rc == 0)
8913 			rc = -t4_cim_read_la(sc, buf, NULL);
8914 	}
8915 	mtx_unlock(&sc->reg_lock);
8916 	if (rc == 0) {
8917 		if (chip_id(sc) < CHELSIO_T6)
8918 			sbuf_cim_la4(sc, sb, buf, cfg);
8919 		else
8920 			sbuf_cim_la6(sc, sb, buf, cfg);
8921 	}
8922 	free(buf, M_CXGBE);
8923 	return (rc);
8924 }
8925 
8926 static int
8927 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
8928 {
8929 	struct adapter *sc = arg1;
8930 	struct sbuf *sb;
8931 	int rc;
8932 
8933 	rc = sysctl_wire_old_buffer(req, 0);
8934 	if (rc != 0)
8935 		return (rc);
8936 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8937 	if (sb == NULL)
8938 		return (ENOMEM);
8939 
8940 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
8941 	if (rc == 0)
8942 		rc = sbuf_finish(sb);
8943 	sbuf_delete(sb);
8944 	return (rc);
8945 }
8946 
8947 bool
8948 t4_os_dump_cimla(struct adapter *sc, int arg, bool verbose)
8949 {
8950 	struct sbuf sb;
8951 	int rc;
8952 
8953 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
8954 		return (false);
8955 	rc = sbuf_cim_la(sc, &sb, M_NOWAIT);
8956 	if (rc == 0) {
8957 		rc = sbuf_finish(&sb);
8958 		if (rc == 0) {
8959 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s",
8960 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
8961 		}
8962 	}
8963 	sbuf_delete(&sb);
8964 	return (false);
8965 }
8966 
8967 static int
8968 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
8969 {
8970 	struct adapter *sc = arg1;
8971 	u_int i;
8972 	struct sbuf *sb;
8973 	uint32_t *buf, *p;
8974 	int rc;
8975 
8976 	rc = sysctl_wire_old_buffer(req, 0);
8977 	if (rc != 0)
8978 		return (rc);
8979 
8980 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8981 	if (sb == NULL)
8982 		return (ENOMEM);
8983 
8984 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
8985 	    M_ZERO | M_WAITOK);
8986 
8987 	mtx_lock(&sc->reg_lock);
8988 	if (hw_off_limits(sc))
8989 		rc = ENXIO;
8990 	else
8991 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
8992 	mtx_unlock(&sc->reg_lock);
8993 	if (rc)
8994 		goto done;
8995 
8996 	p = buf;
8997 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
8998 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
8999 		    p[1], p[0]);
9000 	}
9001 
9002 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9003 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9004 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9005 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9006 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9007 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9008 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9009 		    p[0] & 1);
9010 	}
9011 	rc = sbuf_finish(sb);
9012 done:
9013 	sbuf_delete(sb);
9014 	free(buf, M_CXGBE);
9015 	return (rc);
9016 }
9017 
9018 static int
9019 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9020 {
9021 	struct adapter *sc = arg1;
9022 	u_int i;
9023 	struct sbuf *sb;
9024 	uint32_t *buf, *p;
9025 	int rc;
9026 
9027 	rc = sysctl_wire_old_buffer(req, 0);
9028 	if (rc != 0)
9029 		return (rc);
9030 
9031 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9032 	if (sb == NULL)
9033 		return (ENOMEM);
9034 
9035 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9036 	    M_ZERO | M_WAITOK);
9037 
9038 	mtx_lock(&sc->reg_lock);
9039 	if (hw_off_limits(sc))
9040 		rc = ENXIO;
9041 	else
9042 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9043 	mtx_unlock(&sc->reg_lock);
9044 	if (rc)
9045 		goto done;
9046 
9047 	p = buf;
9048 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9049 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9050 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9051 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9052 		    p[4], p[3], p[2], p[1], p[0]);
9053 	}
9054 
9055 	sbuf_printf(sb, "\n\nCntl ID               Data");
9056 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9057 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9058 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9059 	}
9060 
9061 	rc = sbuf_finish(sb);
9062 done:
9063 	sbuf_delete(sb);
9064 	free(buf, M_CXGBE);
9065 	return (rc);
9066 }
9067 
9068 static int
9069 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9070 {
9071 	struct adapter *sc = arg1;
9072 	struct sbuf *sb;
9073 	int rc, i;
9074 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9075 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9076 	uint16_t thres[CIM_NUM_IBQ];
9077 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9078 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9079 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9080 
9081 	cim_num_obq = sc->chip_params->cim_num_obq;
9082 	if (is_t4(sc)) {
9083 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9084 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9085 	} else {
9086 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9087 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9088 	}
9089 	nq = CIM_NUM_IBQ + cim_num_obq;
9090 
9091 	mtx_lock(&sc->reg_lock);
9092 	if (hw_off_limits(sc))
9093 		rc = ENXIO;
9094 	else {
9095 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9096 		if (rc == 0) {
9097 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9098 			    obq_wr);
9099 			if (rc == 0)
9100 				t4_read_cimq_cfg(sc, base, size, thres);
9101 		}
9102 	}
9103 	mtx_unlock(&sc->reg_lock);
9104 	if (rc)
9105 		return (rc);
9106 
9107 	rc = sysctl_wire_old_buffer(req, 0);
9108 	if (rc != 0)
9109 		return (rc);
9110 
9111 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9112 	if (sb == NULL)
9113 		return (ENOMEM);
9114 
9115 	sbuf_printf(sb,
9116 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9117 
9118 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9119 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9120 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9121 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9122 		    G_QUEREMFLITS(p[2]) * 16);
9123 	for ( ; i < nq; i++, p += 4, wr += 2)
9124 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9125 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9126 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9127 		    G_QUEREMFLITS(p[2]) * 16);
9128 
9129 	rc = sbuf_finish(sb);
9130 	sbuf_delete(sb);
9131 
9132 	return (rc);
9133 }
9134 
9135 static int
9136 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9137 {
9138 	struct adapter *sc = arg1;
9139 	struct sbuf *sb;
9140 	int rc;
9141 	struct tp_cpl_stats stats;
9142 
9143 	rc = sysctl_wire_old_buffer(req, 0);
9144 	if (rc != 0)
9145 		return (rc);
9146 
9147 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9148 	if (sb == NULL)
9149 		return (ENOMEM);
9150 
9151 	mtx_lock(&sc->reg_lock);
9152 	if (hw_off_limits(sc))
9153 		rc = ENXIO;
9154 	else
9155 		t4_tp_get_cpl_stats(sc, &stats, 0);
9156 	mtx_unlock(&sc->reg_lock);
9157 	if (rc)
9158 		goto done;
9159 
9160 	if (sc->chip_params->nchan > 2) {
9161 		sbuf_printf(sb, "                 channel 0  channel 1"
9162 		    "  channel 2  channel 3");
9163 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9164 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9165 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9166 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9167 	} else {
9168 		sbuf_printf(sb, "                 channel 0  channel 1");
9169 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9170 		    stats.req[0], stats.req[1]);
9171 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9172 		    stats.rsp[0], stats.rsp[1]);
9173 	}
9174 
9175 	rc = sbuf_finish(sb);
9176 done:
9177 	sbuf_delete(sb);
9178 	return (rc);
9179 }
9180 
9181 static int
9182 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9183 {
9184 	struct adapter *sc = arg1;
9185 	struct sbuf *sb;
9186 	int rc;
9187 	struct tp_usm_stats stats;
9188 
9189 	rc = sysctl_wire_old_buffer(req, 0);
9190 	if (rc != 0)
9191 		return(rc);
9192 
9193 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9194 	if (sb == NULL)
9195 		return (ENOMEM);
9196 
9197 	mtx_lock(&sc->reg_lock);
9198 	if (hw_off_limits(sc))
9199 		rc = ENXIO;
9200 	else
9201 		t4_get_usm_stats(sc, &stats, 1);
9202 	mtx_unlock(&sc->reg_lock);
9203 	if (rc == 0) {
9204 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9205 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9206 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9207 		rc = sbuf_finish(sb);
9208 	}
9209 	sbuf_delete(sb);
9210 
9211 	return (rc);
9212 }
9213 
9214 static int
9215 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9216 {
9217 	struct adapter *sc = arg1;
9218 	struct sbuf *sb;
9219 	int rc;
9220 	struct tp_tid_stats stats;
9221 
9222 	rc = sysctl_wire_old_buffer(req, 0);
9223 	if (rc != 0)
9224 		return(rc);
9225 
9226 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9227 	if (sb == NULL)
9228 		return (ENOMEM);
9229 
9230 	mtx_lock(&sc->reg_lock);
9231 	if (hw_off_limits(sc))
9232 		rc = ENXIO;
9233 	else
9234 		t4_tp_get_tid_stats(sc, &stats, 1);
9235 	mtx_unlock(&sc->reg_lock);
9236 	if (rc == 0) {
9237 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9238 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9239 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9240 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9241 		rc = sbuf_finish(sb);
9242 	}
9243 	sbuf_delete(sb);
9244 
9245 	return (rc);
9246 }
9247 
9248 static const char * const devlog_level_strings[] = {
9249 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9250 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9251 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9252 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9253 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9254 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9255 };
9256 
9257 static const char * const devlog_facility_strings[] = {
9258 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9259 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9260 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9261 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9262 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9263 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9264 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9265 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9266 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9267 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9268 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9269 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9270 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9271 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9272 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9273 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9274 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9275 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9276 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9277 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9278 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9279 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9280 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9281 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9282 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9283 };
9284 
9285 static int
9286 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9287 {
9288 	int i, j, rc, nentries, first = 0;
9289 	struct devlog_params *dparams = &sc->params.devlog;
9290 	struct fw_devlog_e *buf, *e;
9291 	uint64_t ftstamp = UINT64_MAX;
9292 
9293 	if (dparams->addr == 0)
9294 		return (ENXIO);
9295 
9296 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9297 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9298 	if (buf == NULL)
9299 		return (ENOMEM);
9300 
9301 	mtx_lock(&sc->reg_lock);
9302 	if (hw_off_limits(sc))
9303 		rc = ENXIO;
9304 	else
9305 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9306 		    dparams->size);
9307 	mtx_unlock(&sc->reg_lock);
9308 	if (rc != 0)
9309 		goto done;
9310 
9311 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9312 	for (i = 0; i < nentries; i++) {
9313 		e = &buf[i];
9314 
9315 		if (e->timestamp == 0)
9316 			break;	/* end */
9317 
9318 		e->timestamp = be64toh(e->timestamp);
9319 		e->seqno = be32toh(e->seqno);
9320 		for (j = 0; j < 8; j++)
9321 			e->params[j] = be32toh(e->params[j]);
9322 
9323 		if (e->timestamp < ftstamp) {
9324 			ftstamp = e->timestamp;
9325 			first = i;
9326 		}
9327 	}
9328 
9329 	if (buf[first].timestamp == 0)
9330 		goto done;	/* nothing in the log */
9331 
9332 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9333 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9334 
9335 	i = first;
9336 	do {
9337 		e = &buf[i];
9338 		if (e->timestamp == 0)
9339 			break;	/* end */
9340 
9341 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9342 		    e->seqno, e->timestamp,
9343 		    (e->level < nitems(devlog_level_strings) ?
9344 			devlog_level_strings[e->level] : "UNKNOWN"),
9345 		    (e->facility < nitems(devlog_facility_strings) ?
9346 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9347 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9348 		    e->params[2], e->params[3], e->params[4],
9349 		    e->params[5], e->params[6], e->params[7]);
9350 
9351 		if (++i == nentries)
9352 			i = 0;
9353 	} while (i != first);
9354 done:
9355 	free(buf, M_CXGBE);
9356 	return (rc);
9357 }
9358 
9359 static int
9360 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9361 {
9362 	struct adapter *sc = arg1;
9363 	int rc;
9364 	struct sbuf *sb;
9365 
9366 	rc = sysctl_wire_old_buffer(req, 0);
9367 	if (rc != 0)
9368 		return (rc);
9369 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9370 	if (sb == NULL)
9371 		return (ENOMEM);
9372 
9373 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9374 	if (rc == 0)
9375 		rc = sbuf_finish(sb);
9376 	sbuf_delete(sb);
9377 	return (rc);
9378 }
9379 
9380 void
9381 t4_os_dump_devlog(struct adapter *sc)
9382 {
9383 	int rc;
9384 	struct sbuf sb;
9385 
9386 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
9387 		return;
9388 	rc = sbuf_devlog(sc, &sb, M_NOWAIT);
9389 	if (rc == 0) {
9390 		rc = sbuf_finish(&sb);
9391 		if (rc == 0) {
9392 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9393 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
9394 		}
9395 	}
9396 	sbuf_delete(&sb);
9397 }
9398 
9399 static int
9400 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9401 {
9402 	struct adapter *sc = arg1;
9403 	struct sbuf *sb;
9404 	int rc;
9405 	struct tp_fcoe_stats stats[MAX_NCHAN];
9406 	int i, nchan = sc->chip_params->nchan;
9407 
9408 	rc = sysctl_wire_old_buffer(req, 0);
9409 	if (rc != 0)
9410 		return (rc);
9411 
9412 	mtx_lock(&sc->reg_lock);
9413 	if (hw_off_limits(sc))
9414 		rc = ENXIO;
9415 	else {
9416 		for (i = 0; i < nchan; i++)
9417 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9418 	}
9419 	mtx_unlock(&sc->reg_lock);
9420 	if (rc != 0)
9421 		return (rc);
9422 
9423 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9424 	if (sb == NULL)
9425 		return (ENOMEM);
9426 
9427 	if (nchan > 2) {
9428 		sbuf_printf(sb, "                   channel 0        channel 1"
9429 		    "        channel 2        channel 3");
9430 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9431 		    stats[0].octets_ddp, stats[1].octets_ddp,
9432 		    stats[2].octets_ddp, stats[3].octets_ddp);
9433 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9434 		    stats[0].frames_ddp, stats[1].frames_ddp,
9435 		    stats[2].frames_ddp, stats[3].frames_ddp);
9436 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9437 		    stats[0].frames_drop, stats[1].frames_drop,
9438 		    stats[2].frames_drop, stats[3].frames_drop);
9439 	} else {
9440 		sbuf_printf(sb, "                   channel 0        channel 1");
9441 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9442 		    stats[0].octets_ddp, stats[1].octets_ddp);
9443 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9444 		    stats[0].frames_ddp, stats[1].frames_ddp);
9445 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9446 		    stats[0].frames_drop, stats[1].frames_drop);
9447 	}
9448 
9449 	rc = sbuf_finish(sb);
9450 	sbuf_delete(sb);
9451 
9452 	return (rc);
9453 }
9454 
9455 static int
9456 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9457 {
9458 	struct adapter *sc = arg1;
9459 	struct sbuf *sb;
9460 	int rc, i;
9461 	unsigned int map, kbps, ipg, mode;
9462 	unsigned int pace_tab[NTX_SCHED];
9463 
9464 	rc = sysctl_wire_old_buffer(req, 0);
9465 	if (rc != 0)
9466 		return (rc);
9467 
9468 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9469 	if (sb == NULL)
9470 		return (ENOMEM);
9471 
9472 	mtx_lock(&sc->reg_lock);
9473 	if (hw_off_limits(sc)) {
9474 		rc = ENXIO;
9475 		goto done;
9476 	}
9477 
9478 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9479 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9480 	t4_read_pace_tbl(sc, pace_tab);
9481 
9482 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9483 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9484 
9485 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9486 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9487 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9488 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9489 		if (kbps)
9490 			sbuf_printf(sb, "%9u     ", kbps);
9491 		else
9492 			sbuf_printf(sb, " disabled     ");
9493 
9494 		if (ipg)
9495 			sbuf_printf(sb, "%13u        ", ipg);
9496 		else
9497 			sbuf_printf(sb, "     disabled        ");
9498 
9499 		if (pace_tab[i])
9500 			sbuf_printf(sb, "%10u", pace_tab[i]);
9501 		else
9502 			sbuf_printf(sb, "  disabled");
9503 	}
9504 	rc = sbuf_finish(sb);
9505 done:
9506 	mtx_unlock(&sc->reg_lock);
9507 	sbuf_delete(sb);
9508 	return (rc);
9509 }
9510 
9511 static int
9512 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9513 {
9514 	struct adapter *sc = arg1;
9515 	struct sbuf *sb;
9516 	int rc, i, j;
9517 	uint64_t *p0, *p1;
9518 	struct lb_port_stats s[2];
9519 	static const char *stat_name[] = {
9520 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9521 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9522 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9523 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9524 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9525 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9526 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9527 	};
9528 
9529 	rc = sysctl_wire_old_buffer(req, 0);
9530 	if (rc != 0)
9531 		return (rc);
9532 
9533 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9534 	if (sb == NULL)
9535 		return (ENOMEM);
9536 
9537 	memset(s, 0, sizeof(s));
9538 
9539 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9540 		mtx_lock(&sc->reg_lock);
9541 		if (hw_off_limits(sc))
9542 			rc = ENXIO;
9543 		else {
9544 			t4_get_lb_stats(sc, i, &s[0]);
9545 			t4_get_lb_stats(sc, i + 1, &s[1]);
9546 		}
9547 		mtx_unlock(&sc->reg_lock);
9548 		if (rc != 0)
9549 			break;
9550 
9551 		p0 = &s[0].octets;
9552 		p1 = &s[1].octets;
9553 		sbuf_printf(sb, "%s                       Loopback %u"
9554 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9555 
9556 		for (j = 0; j < nitems(stat_name); j++)
9557 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9558 				   *p0++, *p1++);
9559 	}
9560 
9561 	rc = sbuf_finish(sb);
9562 	sbuf_delete(sb);
9563 
9564 	return (rc);
9565 }
9566 
9567 static int
9568 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9569 {
9570 	int rc = 0;
9571 	struct port_info *pi = arg1;
9572 	struct link_config *lc = &pi->link_cfg;
9573 	struct sbuf *sb;
9574 
9575 	rc = sysctl_wire_old_buffer(req, 0);
9576 	if (rc != 0)
9577 		return(rc);
9578 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9579 	if (sb == NULL)
9580 		return (ENOMEM);
9581 
9582 	if (lc->link_ok || lc->link_down_rc == 255)
9583 		sbuf_printf(sb, "n/a");
9584 	else
9585 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9586 
9587 	rc = sbuf_finish(sb);
9588 	sbuf_delete(sb);
9589 
9590 	return (rc);
9591 }
9592 
9593 struct mem_desc {
9594 	unsigned int base;
9595 	unsigned int limit;
9596 	unsigned int idx;
9597 };
9598 
9599 static int
9600 mem_desc_cmp(const void *a, const void *b)
9601 {
9602 	return ((const struct mem_desc *)a)->base -
9603 	       ((const struct mem_desc *)b)->base;
9604 }
9605 
9606 static void
9607 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9608     unsigned int to)
9609 {
9610 	unsigned int size;
9611 
9612 	if (from == to)
9613 		return;
9614 
9615 	size = to - from + 1;
9616 	if (size == 0)
9617 		return;
9618 
9619 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9620 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9621 }
9622 
9623 static int
9624 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9625 {
9626 	struct adapter *sc = arg1;
9627 	struct sbuf *sb;
9628 	int rc, i, n;
9629 	uint32_t lo, hi, used, alloc;
9630 	static const char *memory[] = {
9631 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9632 	};
9633 	static const char *region[] = {
9634 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9635 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9636 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9637 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9638 		"RQUDP region:", "PBL region:", "TXPBL region:",
9639 		"DBVFIFO region:", "ULPRX state:", "ULPTX state:",
9640 		"On-chip queues:", "TLS keys:",
9641 	};
9642 	struct mem_desc avail[4];
9643 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9644 	struct mem_desc *md = mem;
9645 
9646 	rc = sysctl_wire_old_buffer(req, 0);
9647 	if (rc != 0)
9648 		return (rc);
9649 
9650 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9651 	if (sb == NULL)
9652 		return (ENOMEM);
9653 
9654 	for (i = 0; i < nitems(mem); i++) {
9655 		mem[i].limit = 0;
9656 		mem[i].idx = i;
9657 	}
9658 
9659 	mtx_lock(&sc->reg_lock);
9660 	if (hw_off_limits(sc)) {
9661 		rc = ENXIO;
9662 		goto done;
9663 	}
9664 
9665 	/* Find and sort the populated memory ranges */
9666 	i = 0;
9667 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9668 	if (lo & F_EDRAM0_ENABLE) {
9669 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9670 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9671 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9672 		avail[i].idx = 0;
9673 		i++;
9674 	}
9675 	if (lo & F_EDRAM1_ENABLE) {
9676 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9677 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9678 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9679 		avail[i].idx = 1;
9680 		i++;
9681 	}
9682 	if (lo & F_EXT_MEM_ENABLE) {
9683 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9684 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9685 		avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9686 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9687 		i++;
9688 	}
9689 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9690 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9691 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9692 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9693 		avail[i].idx = 4;
9694 		i++;
9695 	}
9696 	if (is_t6(sc) && lo & F_HMA_MUX) {
9697 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9698 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9699 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9700 		avail[i].idx = 5;
9701 		i++;
9702 	}
9703 	MPASS(i <= nitems(avail));
9704 	if (!i)                                    /* no memory available */
9705 		goto done;
9706 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9707 
9708 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9709 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9710 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9711 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9712 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9713 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9714 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9715 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9716 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9717 
9718 	/* the next few have explicit upper bounds */
9719 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9720 	md->limit = md->base - 1 +
9721 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9722 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9723 	md++;
9724 
9725 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9726 	md->limit = md->base - 1 +
9727 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9728 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9729 	md++;
9730 
9731 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9732 		if (chip_id(sc) <= CHELSIO_T5)
9733 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9734 		else
9735 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9736 		md->limit = 0;
9737 	} else {
9738 		md->base = 0;
9739 		md->idx = nitems(region);  /* hide it */
9740 	}
9741 	md++;
9742 
9743 #define ulp_region(reg) \
9744 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9745 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9746 
9747 	ulp_region(RX_ISCSI);
9748 	ulp_region(RX_TDDP);
9749 	ulp_region(TX_TPT);
9750 	ulp_region(RX_STAG);
9751 	ulp_region(RX_RQ);
9752 	ulp_region(RX_RQUDP);
9753 	ulp_region(RX_PBL);
9754 	ulp_region(TX_PBL);
9755 #undef ulp_region
9756 
9757 	md->base = 0;
9758 	if (is_t4(sc))
9759 		md->idx = nitems(region);
9760 	else {
9761 		uint32_t size = 0;
9762 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9763 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9764 
9765 		if (is_t5(sc)) {
9766 			if (sge_ctrl & F_VFIFO_ENABLE)
9767 				size = fifo_size << 2;
9768 		} else
9769 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9770 
9771 		if (size) {
9772 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
9773 			md->limit = md->base + size - 1;
9774 		} else
9775 			md->idx = nitems(region);
9776 	}
9777 	md++;
9778 
9779 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9780 	md->limit = 0;
9781 	md++;
9782 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9783 	md->limit = 0;
9784 	md++;
9785 
9786 	md->base = sc->vres.ocq.start;
9787 	if (sc->vres.ocq.size)
9788 		md->limit = md->base + sc->vres.ocq.size - 1;
9789 	else
9790 		md->idx = nitems(region);  /* hide it */
9791 	md++;
9792 
9793 	md->base = sc->vres.key.start;
9794 	if (sc->vres.key.size)
9795 		md->limit = md->base + sc->vres.key.size - 1;
9796 	else
9797 		md->idx = nitems(region);  /* hide it */
9798 	md++;
9799 
9800 	/* add any address-space holes, there can be up to 3 */
9801 	for (n = 0; n < i - 1; n++)
9802 		if (avail[n].limit < avail[n + 1].base)
9803 			(md++)->base = avail[n].limit;
9804 	if (avail[n].limit)
9805 		(md++)->base = avail[n].limit;
9806 
9807 	n = md - mem;
9808 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
9809 
9810 	for (lo = 0; lo < i; lo++)
9811 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
9812 				avail[lo].limit - 1);
9813 
9814 	sbuf_printf(sb, "\n");
9815 	for (i = 0; i < n; i++) {
9816 		if (mem[i].idx >= nitems(region))
9817 			continue;                        /* skip holes */
9818 		if (!mem[i].limit)
9819 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
9820 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
9821 				mem[i].limit);
9822 	}
9823 
9824 	sbuf_printf(sb, "\n");
9825 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
9826 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
9827 	mem_region_show(sb, "uP RAM:", lo, hi);
9828 
9829 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
9830 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
9831 	mem_region_show(sb, "uP Extmem2:", lo, hi);
9832 
9833 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
9834 	sbuf_printf(sb, "\n%u Rx pages of size %uKiB for %u channels\n",
9835 		   G_PMRXMAXPAGE(lo),
9836 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
9837 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
9838 
9839 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
9840 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
9841 	sbuf_printf(sb, "%u Tx pages of size %u%ciB for %u channels\n",
9842 		   G_PMTXMAXPAGE(lo),
9843 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
9844 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
9845 	sbuf_printf(sb, "%u p-structs\n",
9846 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT));
9847 
9848 	for (i = 0; i < 4; i++) {
9849 		if (chip_id(sc) > CHELSIO_T5)
9850 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
9851 		else
9852 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
9853 		if (is_t5(sc)) {
9854 			used = G_T5_USED(lo);
9855 			alloc = G_T5_ALLOC(lo);
9856 		} else {
9857 			used = G_USED(lo);
9858 			alloc = G_ALLOC(lo);
9859 		}
9860 		/* For T6 these are MAC buffer groups */
9861 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
9862 		    i, used, alloc);
9863 	}
9864 	for (i = 0; i < sc->chip_params->nchan; i++) {
9865 		if (chip_id(sc) > CHELSIO_T5)
9866 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
9867 		else
9868 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
9869 		if (is_t5(sc)) {
9870 			used = G_T5_USED(lo);
9871 			alloc = G_T5_ALLOC(lo);
9872 		} else {
9873 			used = G_USED(lo);
9874 			alloc = G_ALLOC(lo);
9875 		}
9876 		/* For T6 these are MAC buffer groups */
9877 		sbuf_printf(sb,
9878 		    "\nLoopback %d using %u pages out of %u allocated",
9879 		    i, used, alloc);
9880 	}
9881 done:
9882 	mtx_unlock(&sc->reg_lock);
9883 	if (rc == 0)
9884 		rc = sbuf_finish(sb);
9885 	sbuf_delete(sb);
9886 	return (rc);
9887 }
9888 
9889 static inline void
9890 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
9891 {
9892 	*mask = x | y;
9893 	y = htobe64(y);
9894 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
9895 }
9896 
9897 static int
9898 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
9899 {
9900 	struct adapter *sc = arg1;
9901 	struct sbuf *sb;
9902 	int rc, i;
9903 
9904 	MPASS(chip_id(sc) <= CHELSIO_T5);
9905 
9906 	rc = sysctl_wire_old_buffer(req, 0);
9907 	if (rc != 0)
9908 		return (rc);
9909 
9910 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9911 	if (sb == NULL)
9912 		return (ENOMEM);
9913 
9914 	sbuf_printf(sb,
9915 	    "Idx  Ethernet address     Mask     Vld Ports PF"
9916 	    "  VF              Replication             P0 P1 P2 P3  ML");
9917 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
9918 		uint64_t tcamx, tcamy, mask;
9919 		uint32_t cls_lo, cls_hi;
9920 		uint8_t addr[ETHER_ADDR_LEN];
9921 
9922 		mtx_lock(&sc->reg_lock);
9923 		if (hw_off_limits(sc))
9924 			rc = ENXIO;
9925 		else {
9926 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
9927 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
9928 		}
9929 		mtx_unlock(&sc->reg_lock);
9930 		if (rc != 0)
9931 			break;
9932 		if (tcamx & tcamy)
9933 			continue;
9934 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
9935 		mtx_lock(&sc->reg_lock);
9936 		if (hw_off_limits(sc))
9937 			rc = ENXIO;
9938 		else {
9939 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
9940 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
9941 		}
9942 		mtx_unlock(&sc->reg_lock);
9943 		if (rc != 0)
9944 			break;
9945 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
9946 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
9947 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
9948 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
9949 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
9950 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
9951 
9952 		if (cls_lo & F_REPLICATE) {
9953 			struct fw_ldst_cmd ldst_cmd;
9954 
9955 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
9956 			ldst_cmd.op_to_addrspace =
9957 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
9958 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
9959 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
9960 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
9961 			ldst_cmd.u.mps.rplc.fid_idx =
9962 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
9963 				V_FW_LDST_CMD_IDX(i));
9964 
9965 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
9966 			    "t4mps");
9967 			if (rc)
9968 				break;
9969 			if (hw_off_limits(sc))
9970 				rc = ENXIO;
9971 			else
9972 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
9973 				    sizeof(ldst_cmd), &ldst_cmd);
9974 			end_synchronized_op(sc, 0);
9975 			if (rc != 0)
9976 				break;
9977 			else {
9978 				sbuf_printf(sb, " %08x %08x %08x %08x",
9979 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
9980 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
9981 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
9982 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
9983 			}
9984 		} else
9985 			sbuf_printf(sb, "%36s", "");
9986 
9987 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
9988 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
9989 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
9990 	}
9991 
9992 	if (rc)
9993 		(void) sbuf_finish(sb);
9994 	else
9995 		rc = sbuf_finish(sb);
9996 	sbuf_delete(sb);
9997 
9998 	return (rc);
9999 }
10000 
10001 static int
10002 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
10003 {
10004 	struct adapter *sc = arg1;
10005 	struct sbuf *sb;
10006 	int rc, i;
10007 
10008 	MPASS(chip_id(sc) > CHELSIO_T5);
10009 
10010 	rc = sysctl_wire_old_buffer(req, 0);
10011 	if (rc != 0)
10012 		return (rc);
10013 
10014 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10015 	if (sb == NULL)
10016 		return (ENOMEM);
10017 
10018 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
10019 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
10020 	    "                           Replication"
10021 	    "                                    P0 P1 P2 P3  ML\n");
10022 
10023 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10024 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
10025 		uint16_t ivlan;
10026 		uint64_t tcamx, tcamy, val, mask;
10027 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10028 		uint8_t addr[ETHER_ADDR_LEN];
10029 
10030 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10031 		if (i < 256)
10032 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10033 		else
10034 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10035 		mtx_lock(&sc->reg_lock);
10036 		if (hw_off_limits(sc))
10037 			rc = ENXIO;
10038 		else {
10039 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10040 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10041 			tcamy = G_DMACH(val) << 32;
10042 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10043 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10044 		}
10045 		mtx_unlock(&sc->reg_lock);
10046 		if (rc != 0)
10047 			break;
10048 
10049 		lookup_type = G_DATALKPTYPE(data2);
10050 		port_num = G_DATAPORTNUM(data2);
10051 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10052 			/* Inner header VNI */
10053 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10054 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10055 			dip_hit = data2 & F_DATADIPHIT;
10056 			vlan_vld = 0;
10057 		} else {
10058 			vniy = 0;
10059 			dip_hit = 0;
10060 			vlan_vld = data2 & F_DATAVIDH2;
10061 			ivlan = G_VIDL(val);
10062 		}
10063 
10064 		ctl |= V_CTLXYBITSEL(1);
10065 		mtx_lock(&sc->reg_lock);
10066 		if (hw_off_limits(sc))
10067 			rc = ENXIO;
10068 		else {
10069 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10070 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10071 			tcamx = G_DMACH(val) << 32;
10072 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10073 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10074 		}
10075 		mtx_unlock(&sc->reg_lock);
10076 		if (rc != 0)
10077 			break;
10078 
10079 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10080 			/* Inner header VNI mask */
10081 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10082 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10083 		} else
10084 			vnix = 0;
10085 
10086 		if (tcamx & tcamy)
10087 			continue;
10088 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10089 
10090 		mtx_lock(&sc->reg_lock);
10091 		if (hw_off_limits(sc))
10092 			rc = ENXIO;
10093 		else {
10094 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10095 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10096 		}
10097 		mtx_unlock(&sc->reg_lock);
10098 		if (rc != 0)
10099 			break;
10100 
10101 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10102 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10103 			    "%012jx %06x %06x    -    -   %3c"
10104 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10105 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10106 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10107 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10108 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10109 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10110 		} else {
10111 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10112 			    "%012jx    -       -   ", i, addr[0], addr[1],
10113 			    addr[2], addr[3], addr[4], addr[5],
10114 			    (uintmax_t)mask);
10115 
10116 			if (vlan_vld)
10117 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10118 			else
10119 				sbuf_printf(sb, "  -    N     ");
10120 
10121 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10122 			    lookup_type ? 'I' : 'O', port_num,
10123 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10124 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10125 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10126 		}
10127 
10128 
10129 		if (cls_lo & F_T6_REPLICATE) {
10130 			struct fw_ldst_cmd ldst_cmd;
10131 
10132 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10133 			ldst_cmd.op_to_addrspace =
10134 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10135 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10136 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10137 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10138 			ldst_cmd.u.mps.rplc.fid_idx =
10139 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10140 				V_FW_LDST_CMD_IDX(i));
10141 
10142 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10143 			    "t6mps");
10144 			if (rc)
10145 				break;
10146 			if (hw_off_limits(sc))
10147 				rc = ENXIO;
10148 			else
10149 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10150 				    sizeof(ldst_cmd), &ldst_cmd);
10151 			end_synchronized_op(sc, 0);
10152 			if (rc != 0)
10153 				break;
10154 			else {
10155 				sbuf_printf(sb, " %08x %08x %08x %08x"
10156 				    " %08x %08x %08x %08x",
10157 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10158 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10159 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10160 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10161 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10162 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10163 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10164 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10165 			}
10166 		} else
10167 			sbuf_printf(sb, "%72s", "");
10168 
10169 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10170 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10171 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10172 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10173 	}
10174 
10175 	if (rc)
10176 		(void) sbuf_finish(sb);
10177 	else
10178 		rc = sbuf_finish(sb);
10179 	sbuf_delete(sb);
10180 
10181 	return (rc);
10182 }
10183 
10184 static int
10185 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10186 {
10187 	struct adapter *sc = arg1;
10188 	struct sbuf *sb;
10189 	int rc;
10190 	uint16_t mtus[NMTUS];
10191 
10192 	rc = sysctl_wire_old_buffer(req, 0);
10193 	if (rc != 0)
10194 		return (rc);
10195 
10196 	mtx_lock(&sc->reg_lock);
10197 	if (hw_off_limits(sc))
10198 		rc = ENXIO;
10199 	else
10200 		t4_read_mtu_tbl(sc, mtus, NULL);
10201 	mtx_unlock(&sc->reg_lock);
10202 	if (rc != 0)
10203 		return (rc);
10204 
10205 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10206 	if (sb == NULL)
10207 		return (ENOMEM);
10208 
10209 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10210 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10211 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10212 	    mtus[14], mtus[15]);
10213 
10214 	rc = sbuf_finish(sb);
10215 	sbuf_delete(sb);
10216 
10217 	return (rc);
10218 }
10219 
10220 static int
10221 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10222 {
10223 	struct adapter *sc = arg1;
10224 	struct sbuf *sb;
10225 	int rc, i;
10226 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10227 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10228 	static const char *tx_stats[MAX_PM_NSTATS] = {
10229 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10230 		"Tx FIFO wait", NULL, "Tx latency"
10231 	};
10232 	static const char *rx_stats[MAX_PM_NSTATS] = {
10233 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10234 		"Rx FIFO wait", NULL, "Rx latency"
10235 	};
10236 
10237 	rc = sysctl_wire_old_buffer(req, 0);
10238 	if (rc != 0)
10239 		return (rc);
10240 
10241 	mtx_lock(&sc->reg_lock);
10242 	if (hw_off_limits(sc))
10243 		rc = ENXIO;
10244 	else {
10245 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10246 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10247 	}
10248 	mtx_unlock(&sc->reg_lock);
10249 	if (rc != 0)
10250 		return (rc);
10251 
10252 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10253 	if (sb == NULL)
10254 		return (ENOMEM);
10255 
10256 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10257 	for (i = 0; i < 4; i++) {
10258 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10259 		    tx_cyc[i]);
10260 	}
10261 
10262 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10263 	for (i = 0; i < 4; i++) {
10264 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10265 		    rx_cyc[i]);
10266 	}
10267 
10268 	if (chip_id(sc) > CHELSIO_T5) {
10269 		sbuf_printf(sb,
10270 		    "\n              Total wait      Total occupancy");
10271 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10272 		    tx_cyc[i]);
10273 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10274 		    rx_cyc[i]);
10275 
10276 		i += 2;
10277 		MPASS(i < nitems(tx_stats));
10278 
10279 		sbuf_printf(sb,
10280 		    "\n                   Reads           Total wait");
10281 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10282 		    tx_cyc[i]);
10283 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10284 		    rx_cyc[i]);
10285 	}
10286 
10287 	rc = sbuf_finish(sb);
10288 	sbuf_delete(sb);
10289 
10290 	return (rc);
10291 }
10292 
10293 static int
10294 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10295 {
10296 	struct adapter *sc = arg1;
10297 	struct sbuf *sb;
10298 	int rc;
10299 	struct tp_rdma_stats stats;
10300 
10301 	rc = sysctl_wire_old_buffer(req, 0);
10302 	if (rc != 0)
10303 		return (rc);
10304 
10305 	mtx_lock(&sc->reg_lock);
10306 	if (hw_off_limits(sc))
10307 		rc = ENXIO;
10308 	else
10309 		t4_tp_get_rdma_stats(sc, &stats, 0);
10310 	mtx_unlock(&sc->reg_lock);
10311 	if (rc != 0)
10312 		return (rc);
10313 
10314 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10315 	if (sb == NULL)
10316 		return (ENOMEM);
10317 
10318 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10319 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10320 
10321 	rc = sbuf_finish(sb);
10322 	sbuf_delete(sb);
10323 
10324 	return (rc);
10325 }
10326 
10327 static int
10328 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10329 {
10330 	struct adapter *sc = arg1;
10331 	struct sbuf *sb;
10332 	int rc;
10333 	struct tp_tcp_stats v4, v6;
10334 
10335 	rc = sysctl_wire_old_buffer(req, 0);
10336 	if (rc != 0)
10337 		return (rc);
10338 
10339 	mtx_lock(&sc->reg_lock);
10340 	if (hw_off_limits(sc))
10341 		rc = ENXIO;
10342 	else
10343 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10344 	mtx_unlock(&sc->reg_lock);
10345 	if (rc != 0)
10346 		return (rc);
10347 
10348 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10349 	if (sb == NULL)
10350 		return (ENOMEM);
10351 
10352 	sbuf_printf(sb,
10353 	    "                                IP                 IPv6\n");
10354 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10355 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10356 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10357 	    v4.tcp_in_segs, v6.tcp_in_segs);
10358 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10359 	    v4.tcp_out_segs, v6.tcp_out_segs);
10360 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10361 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10362 
10363 	rc = sbuf_finish(sb);
10364 	sbuf_delete(sb);
10365 
10366 	return (rc);
10367 }
10368 
10369 static int
10370 sysctl_tids(SYSCTL_HANDLER_ARGS)
10371 {
10372 	struct adapter *sc = arg1;
10373 	struct sbuf *sb;
10374 	int rc;
10375 	uint32_t x, y;
10376 	struct tid_info *t = &sc->tids;
10377 
10378 	rc = sysctl_wire_old_buffer(req, 0);
10379 	if (rc != 0)
10380 		return (rc);
10381 
10382 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10383 	if (sb == NULL)
10384 		return (ENOMEM);
10385 
10386 	if (t->natids) {
10387 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10388 		    t->atids_in_use);
10389 	}
10390 
10391 	if (t->nhpftids) {
10392 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10393 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10394 	}
10395 
10396 	if (t->ntids) {
10397 		bool hashen = false;
10398 
10399 		mtx_lock(&sc->reg_lock);
10400 		if (hw_off_limits(sc))
10401 			rc = ENXIO;
10402 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10403 			hashen = true;
10404 			if (chip_id(sc) <= CHELSIO_T5) {
10405 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10406 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10407 			} else {
10408 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10409 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10410 			}
10411 		}
10412 		mtx_unlock(&sc->reg_lock);
10413 		if (rc != 0)
10414 			goto done;
10415 
10416 		sbuf_printf(sb, "TID range: ");
10417 		if (hashen) {
10418 			if (x)
10419 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10420 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10421 		} else {
10422 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10423 			    t->ntids - 1);
10424 		}
10425 		sbuf_printf(sb, ", in use: %u\n",
10426 		    atomic_load_acq_int(&t->tids_in_use));
10427 	}
10428 
10429 	if (t->nstids) {
10430 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10431 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10432 	}
10433 
10434 	if (t->nftids) {
10435 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10436 		    t->ftid_end, t->ftids_in_use);
10437 	}
10438 
10439 	if (t->netids) {
10440 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10441 		    t->etid_base + t->netids - 1, t->etids_in_use);
10442 	}
10443 
10444 	mtx_lock(&sc->reg_lock);
10445 	if (hw_off_limits(sc))
10446 		rc = ENXIO;
10447 	else {
10448 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10449 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10450 	}
10451 	mtx_unlock(&sc->reg_lock);
10452 	if (rc != 0)
10453 		goto done;
10454 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10455 done:
10456 	if (rc == 0)
10457 		rc = sbuf_finish(sb);
10458 	else
10459 		(void)sbuf_finish(sb);
10460 	sbuf_delete(sb);
10461 
10462 	return (rc);
10463 }
10464 
10465 static int
10466 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10467 {
10468 	struct adapter *sc = arg1;
10469 	struct sbuf *sb;
10470 	int rc;
10471 	struct tp_err_stats stats;
10472 
10473 	rc = sysctl_wire_old_buffer(req, 0);
10474 	if (rc != 0)
10475 		return (rc);
10476 
10477 	mtx_lock(&sc->reg_lock);
10478 	if (hw_off_limits(sc))
10479 		rc = ENXIO;
10480 	else
10481 		t4_tp_get_err_stats(sc, &stats, 0);
10482 	mtx_unlock(&sc->reg_lock);
10483 	if (rc != 0)
10484 		return (rc);
10485 
10486 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10487 	if (sb == NULL)
10488 		return (ENOMEM);
10489 
10490 	if (sc->chip_params->nchan > 2) {
10491 		sbuf_printf(sb, "                 channel 0  channel 1"
10492 		    "  channel 2  channel 3\n");
10493 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10494 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10495 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10496 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10497 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10498 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10499 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10500 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10501 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10502 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10503 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10504 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10505 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10506 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10507 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10508 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10509 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10510 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10511 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10512 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10513 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10514 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10515 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10516 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10517 	} else {
10518 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10519 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10520 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10521 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10522 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10523 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10524 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10525 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10526 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10527 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10528 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10529 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10530 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10531 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10532 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10533 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10534 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10535 	}
10536 
10537 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10538 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10539 
10540 	rc = sbuf_finish(sb);
10541 	sbuf_delete(sb);
10542 
10543 	return (rc);
10544 }
10545 
10546 static int
10547 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10548 {
10549 	struct adapter *sc = arg1;
10550 	struct sbuf *sb;
10551 	int rc;
10552 	struct tp_tnl_stats stats;
10553 
10554 	rc = sysctl_wire_old_buffer(req, 0);
10555 	if (rc != 0)
10556 		return(rc);
10557 
10558 	mtx_lock(&sc->reg_lock);
10559 	if (hw_off_limits(sc))
10560 		rc = ENXIO;
10561 	else
10562 		t4_tp_get_tnl_stats(sc, &stats, 1);
10563 	mtx_unlock(&sc->reg_lock);
10564 	if (rc != 0)
10565 		return (rc);
10566 
10567 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10568 	if (sb == NULL)
10569 		return (ENOMEM);
10570 
10571 	if (sc->chip_params->nchan > 2) {
10572 		sbuf_printf(sb, "           channel 0  channel 1"
10573 		    "  channel 2  channel 3\n");
10574 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10575 		    stats.out_pkt[0], stats.out_pkt[1],
10576 		    stats.out_pkt[2], stats.out_pkt[3]);
10577 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10578 		    stats.in_pkt[0], stats.in_pkt[1],
10579 		    stats.in_pkt[2], stats.in_pkt[3]);
10580 	} else {
10581 		sbuf_printf(sb, "           channel 0  channel 1\n");
10582 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10583 		    stats.out_pkt[0], stats.out_pkt[1]);
10584 		sbuf_printf(sb, "InPkts:   %10u %10u",
10585 		    stats.in_pkt[0], stats.in_pkt[1]);
10586 	}
10587 
10588 	rc = sbuf_finish(sb);
10589 	sbuf_delete(sb);
10590 
10591 	return (rc);
10592 }
10593 
10594 static int
10595 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10596 {
10597 	struct adapter *sc = arg1;
10598 	struct tp_params *tpp = &sc->params.tp;
10599 	u_int mask;
10600 	int rc;
10601 
10602 	mask = tpp->la_mask >> 16;
10603 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10604 	if (rc != 0 || req->newptr == NULL)
10605 		return (rc);
10606 	if (mask > 0xffff)
10607 		return (EINVAL);
10608 	mtx_lock(&sc->reg_lock);
10609 	if (hw_off_limits(sc))
10610 		rc = ENXIO;
10611 	else {
10612 		tpp->la_mask = mask << 16;
10613 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10614 		    tpp->la_mask);
10615 	}
10616 	mtx_unlock(&sc->reg_lock);
10617 
10618 	return (rc);
10619 }
10620 
10621 struct field_desc {
10622 	const char *name;
10623 	u_int start;
10624 	u_int width;
10625 };
10626 
10627 static void
10628 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10629 {
10630 	char buf[32];
10631 	int line_size = 0;
10632 
10633 	while (f->name) {
10634 		uint64_t mask = (1ULL << f->width) - 1;
10635 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10636 		    ((uintmax_t)v >> f->start) & mask);
10637 
10638 		if (line_size + len >= 79) {
10639 			line_size = 8;
10640 			sbuf_printf(sb, "\n        ");
10641 		}
10642 		sbuf_printf(sb, "%s ", buf);
10643 		line_size += len + 1;
10644 		f++;
10645 	}
10646 	sbuf_printf(sb, "\n");
10647 }
10648 
10649 static const struct field_desc tp_la0[] = {
10650 	{ "RcfOpCodeOut", 60, 4 },
10651 	{ "State", 56, 4 },
10652 	{ "WcfState", 52, 4 },
10653 	{ "RcfOpcSrcOut", 50, 2 },
10654 	{ "CRxError", 49, 1 },
10655 	{ "ERxError", 48, 1 },
10656 	{ "SanityFailed", 47, 1 },
10657 	{ "SpuriousMsg", 46, 1 },
10658 	{ "FlushInputMsg", 45, 1 },
10659 	{ "FlushInputCpl", 44, 1 },
10660 	{ "RssUpBit", 43, 1 },
10661 	{ "RssFilterHit", 42, 1 },
10662 	{ "Tid", 32, 10 },
10663 	{ "InitTcb", 31, 1 },
10664 	{ "LineNumber", 24, 7 },
10665 	{ "Emsg", 23, 1 },
10666 	{ "EdataOut", 22, 1 },
10667 	{ "Cmsg", 21, 1 },
10668 	{ "CdataOut", 20, 1 },
10669 	{ "EreadPdu", 19, 1 },
10670 	{ "CreadPdu", 18, 1 },
10671 	{ "TunnelPkt", 17, 1 },
10672 	{ "RcfPeerFin", 16, 1 },
10673 	{ "RcfReasonOut", 12, 4 },
10674 	{ "TxCchannel", 10, 2 },
10675 	{ "RcfTxChannel", 8, 2 },
10676 	{ "RxEchannel", 6, 2 },
10677 	{ "RcfRxChannel", 5, 1 },
10678 	{ "RcfDataOutSrdy", 4, 1 },
10679 	{ "RxDvld", 3, 1 },
10680 	{ "RxOoDvld", 2, 1 },
10681 	{ "RxCongestion", 1, 1 },
10682 	{ "TxCongestion", 0, 1 },
10683 	{ NULL }
10684 };
10685 
10686 static const struct field_desc tp_la1[] = {
10687 	{ "CplCmdIn", 56, 8 },
10688 	{ "CplCmdOut", 48, 8 },
10689 	{ "ESynOut", 47, 1 },
10690 	{ "EAckOut", 46, 1 },
10691 	{ "EFinOut", 45, 1 },
10692 	{ "ERstOut", 44, 1 },
10693 	{ "SynIn", 43, 1 },
10694 	{ "AckIn", 42, 1 },
10695 	{ "FinIn", 41, 1 },
10696 	{ "RstIn", 40, 1 },
10697 	{ "DataIn", 39, 1 },
10698 	{ "DataInVld", 38, 1 },
10699 	{ "PadIn", 37, 1 },
10700 	{ "RxBufEmpty", 36, 1 },
10701 	{ "RxDdp", 35, 1 },
10702 	{ "RxFbCongestion", 34, 1 },
10703 	{ "TxFbCongestion", 33, 1 },
10704 	{ "TxPktSumSrdy", 32, 1 },
10705 	{ "RcfUlpType", 28, 4 },
10706 	{ "Eread", 27, 1 },
10707 	{ "Ebypass", 26, 1 },
10708 	{ "Esave", 25, 1 },
10709 	{ "Static0", 24, 1 },
10710 	{ "Cread", 23, 1 },
10711 	{ "Cbypass", 22, 1 },
10712 	{ "Csave", 21, 1 },
10713 	{ "CPktOut", 20, 1 },
10714 	{ "RxPagePoolFull", 18, 2 },
10715 	{ "RxLpbkPkt", 17, 1 },
10716 	{ "TxLpbkPkt", 16, 1 },
10717 	{ "RxVfValid", 15, 1 },
10718 	{ "SynLearned", 14, 1 },
10719 	{ "SetDelEntry", 13, 1 },
10720 	{ "SetInvEntry", 12, 1 },
10721 	{ "CpcmdDvld", 11, 1 },
10722 	{ "CpcmdSave", 10, 1 },
10723 	{ "RxPstructsFull", 8, 2 },
10724 	{ "EpcmdDvld", 7, 1 },
10725 	{ "EpcmdFlush", 6, 1 },
10726 	{ "EpcmdTrimPrefix", 5, 1 },
10727 	{ "EpcmdTrimPostfix", 4, 1 },
10728 	{ "ERssIp4Pkt", 3, 1 },
10729 	{ "ERssIp6Pkt", 2, 1 },
10730 	{ "ERssTcpUdpPkt", 1, 1 },
10731 	{ "ERssFceFipPkt", 0, 1 },
10732 	{ NULL }
10733 };
10734 
10735 static const struct field_desc tp_la2[] = {
10736 	{ "CplCmdIn", 56, 8 },
10737 	{ "MpsVfVld", 55, 1 },
10738 	{ "MpsPf", 52, 3 },
10739 	{ "MpsVf", 44, 8 },
10740 	{ "SynIn", 43, 1 },
10741 	{ "AckIn", 42, 1 },
10742 	{ "FinIn", 41, 1 },
10743 	{ "RstIn", 40, 1 },
10744 	{ "DataIn", 39, 1 },
10745 	{ "DataInVld", 38, 1 },
10746 	{ "PadIn", 37, 1 },
10747 	{ "RxBufEmpty", 36, 1 },
10748 	{ "RxDdp", 35, 1 },
10749 	{ "RxFbCongestion", 34, 1 },
10750 	{ "TxFbCongestion", 33, 1 },
10751 	{ "TxPktSumSrdy", 32, 1 },
10752 	{ "RcfUlpType", 28, 4 },
10753 	{ "Eread", 27, 1 },
10754 	{ "Ebypass", 26, 1 },
10755 	{ "Esave", 25, 1 },
10756 	{ "Static0", 24, 1 },
10757 	{ "Cread", 23, 1 },
10758 	{ "Cbypass", 22, 1 },
10759 	{ "Csave", 21, 1 },
10760 	{ "CPktOut", 20, 1 },
10761 	{ "RxPagePoolFull", 18, 2 },
10762 	{ "RxLpbkPkt", 17, 1 },
10763 	{ "TxLpbkPkt", 16, 1 },
10764 	{ "RxVfValid", 15, 1 },
10765 	{ "SynLearned", 14, 1 },
10766 	{ "SetDelEntry", 13, 1 },
10767 	{ "SetInvEntry", 12, 1 },
10768 	{ "CpcmdDvld", 11, 1 },
10769 	{ "CpcmdSave", 10, 1 },
10770 	{ "RxPstructsFull", 8, 2 },
10771 	{ "EpcmdDvld", 7, 1 },
10772 	{ "EpcmdFlush", 6, 1 },
10773 	{ "EpcmdTrimPrefix", 5, 1 },
10774 	{ "EpcmdTrimPostfix", 4, 1 },
10775 	{ "ERssIp4Pkt", 3, 1 },
10776 	{ "ERssIp6Pkt", 2, 1 },
10777 	{ "ERssTcpUdpPkt", 1, 1 },
10778 	{ "ERssFceFipPkt", 0, 1 },
10779 	{ NULL }
10780 };
10781 
10782 static void
10783 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10784 {
10785 
10786 	field_desc_show(sb, *p, tp_la0);
10787 }
10788 
10789 static void
10790 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10791 {
10792 
10793 	if (idx)
10794 		sbuf_printf(sb, "\n");
10795 	field_desc_show(sb, p[0], tp_la0);
10796 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10797 		field_desc_show(sb, p[1], tp_la0);
10798 }
10799 
10800 static void
10801 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
10802 {
10803 
10804 	if (idx)
10805 		sbuf_printf(sb, "\n");
10806 	field_desc_show(sb, p[0], tp_la0);
10807 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10808 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
10809 }
10810 
10811 static int
10812 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
10813 {
10814 	struct adapter *sc = arg1;
10815 	struct sbuf *sb;
10816 	uint64_t *buf, *p;
10817 	int rc;
10818 	u_int i, inc;
10819 	void (*show_func)(struct sbuf *, uint64_t *, int);
10820 
10821 	rc = sysctl_wire_old_buffer(req, 0);
10822 	if (rc != 0)
10823 		return (rc);
10824 
10825 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10826 	if (sb == NULL)
10827 		return (ENOMEM);
10828 
10829 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
10830 
10831 	mtx_lock(&sc->reg_lock);
10832 	if (hw_off_limits(sc))
10833 		rc = ENXIO;
10834 	else {
10835 		t4_tp_read_la(sc, buf, NULL);
10836 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
10837 		case 2:
10838 			inc = 2;
10839 			show_func = tp_la_show2;
10840 			break;
10841 		case 3:
10842 			inc = 2;
10843 			show_func = tp_la_show3;
10844 			break;
10845 		default:
10846 			inc = 1;
10847 			show_func = tp_la_show;
10848 		}
10849 	}
10850 	mtx_unlock(&sc->reg_lock);
10851 	if (rc != 0)
10852 		goto done;
10853 
10854 	p = buf;
10855 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
10856 		(*show_func)(sb, p, i);
10857 	rc = sbuf_finish(sb);
10858 done:
10859 	sbuf_delete(sb);
10860 	free(buf, M_CXGBE);
10861 	return (rc);
10862 }
10863 
10864 static int
10865 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
10866 {
10867 	struct adapter *sc = arg1;
10868 	struct sbuf *sb;
10869 	int rc;
10870 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
10871 
10872 	rc = sysctl_wire_old_buffer(req, 0);
10873 	if (rc != 0)
10874 		return (rc);
10875 
10876 	mtx_lock(&sc->reg_lock);
10877 	if (hw_off_limits(sc))
10878 		rc = ENXIO;
10879 	else
10880 		t4_get_chan_txrate(sc, nrate, orate);
10881 	mtx_unlock(&sc->reg_lock);
10882 	if (rc != 0)
10883 		return (rc);
10884 
10885 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10886 	if (sb == NULL)
10887 		return (ENOMEM);
10888 
10889 	if (sc->chip_params->nchan > 2) {
10890 		sbuf_printf(sb, "              channel 0   channel 1"
10891 		    "   channel 2   channel 3\n");
10892 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
10893 		    nrate[0], nrate[1], nrate[2], nrate[3]);
10894 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
10895 		    orate[0], orate[1], orate[2], orate[3]);
10896 	} else {
10897 		sbuf_printf(sb, "              channel 0   channel 1\n");
10898 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
10899 		    nrate[0], nrate[1]);
10900 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
10901 		    orate[0], orate[1]);
10902 	}
10903 
10904 	rc = sbuf_finish(sb);
10905 	sbuf_delete(sb);
10906 
10907 	return (rc);
10908 }
10909 
10910 static int
10911 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
10912 {
10913 	struct adapter *sc = arg1;
10914 	struct sbuf *sb;
10915 	uint32_t *buf, *p;
10916 	int rc, i;
10917 
10918 	rc = sysctl_wire_old_buffer(req, 0);
10919 	if (rc != 0)
10920 		return (rc);
10921 
10922 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10923 	if (sb == NULL)
10924 		return (ENOMEM);
10925 
10926 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
10927 	    M_ZERO | M_WAITOK);
10928 
10929 	mtx_lock(&sc->reg_lock);
10930 	if (hw_off_limits(sc))
10931 		rc = ENXIO;
10932 	else
10933 		t4_ulprx_read_la(sc, buf);
10934 	mtx_unlock(&sc->reg_lock);
10935 	if (rc != 0)
10936 		goto done;
10937 
10938 	p = buf;
10939 	sbuf_printf(sb, "      Pcmd        Type   Message"
10940 	    "                Data");
10941 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
10942 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
10943 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
10944 	}
10945 	rc = sbuf_finish(sb);
10946 done:
10947 	sbuf_delete(sb);
10948 	free(buf, M_CXGBE);
10949 	return (rc);
10950 }
10951 
10952 static int
10953 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
10954 {
10955 	struct adapter *sc = arg1;
10956 	struct sbuf *sb;
10957 	int rc;
10958 	uint32_t cfg, s1, s2;
10959 
10960 	MPASS(chip_id(sc) >= CHELSIO_T5);
10961 
10962 	rc = sysctl_wire_old_buffer(req, 0);
10963 	if (rc != 0)
10964 		return (rc);
10965 
10966 	mtx_lock(&sc->reg_lock);
10967 	if (hw_off_limits(sc))
10968 		rc = ENXIO;
10969 	else {
10970 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
10971 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
10972 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
10973 	}
10974 	mtx_unlock(&sc->reg_lock);
10975 	if (rc != 0)
10976 		return (rc);
10977 
10978 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10979 	if (sb == NULL)
10980 		return (ENOMEM);
10981 
10982 	if (G_STATSOURCE_T5(cfg) == 7) {
10983 		int mode;
10984 
10985 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
10986 		if (mode == 0)
10987 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
10988 		else if (mode == 1)
10989 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
10990 		else
10991 			sbuf_printf(sb, "unknown mode %d", mode);
10992 	}
10993 	rc = sbuf_finish(sb);
10994 	sbuf_delete(sb);
10995 
10996 	return (rc);
10997 }
10998 
10999 static int
11000 sysctl_cpus(SYSCTL_HANDLER_ARGS)
11001 {
11002 	struct adapter *sc = arg1;
11003 	enum cpu_sets op = arg2;
11004 	cpuset_t cpuset;
11005 	struct sbuf *sb;
11006 	int i, rc;
11007 
11008 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
11009 
11010 	CPU_ZERO(&cpuset);
11011 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
11012 	if (rc != 0)
11013 		return (rc);
11014 
11015 	rc = sysctl_wire_old_buffer(req, 0);
11016 	if (rc != 0)
11017 		return (rc);
11018 
11019 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11020 	if (sb == NULL)
11021 		return (ENOMEM);
11022 
11023 	CPU_FOREACH(i)
11024 		sbuf_printf(sb, "%d ", i);
11025 	rc = sbuf_finish(sb);
11026 	sbuf_delete(sb);
11027 
11028 	return (rc);
11029 }
11030 
11031 static int
11032 sysctl_reset(SYSCTL_HANDLER_ARGS)
11033 {
11034 	struct adapter *sc = arg1;
11035 	u_int val;
11036 	int rc;
11037 
11038 	val = sc->num_resets;
11039 	rc = sysctl_handle_int(oidp, &val, 0, req);
11040 	if (rc != 0 || req->newptr == NULL)
11041 		return (rc);
11042 
11043 	if (val == 0) {
11044 		/* Zero out the counter that tracks reset. */
11045 		sc->num_resets = 0;
11046 		return (0);
11047 	}
11048 
11049 	if (val != 1)
11050 		return (EINVAL);	/* 0 or 1 are the only legal values */
11051 
11052 	if (hw_off_limits(sc))		/* harmless race */
11053 		return (EALREADY);
11054 
11055 	taskqueue_enqueue(reset_tq, &sc->reset_task);
11056 	return (0);
11057 }
11058 
11059 #ifdef TCP_OFFLOAD
11060 static int
11061 sysctl_tls(SYSCTL_HANDLER_ARGS)
11062 {
11063 	struct adapter *sc = arg1;
11064 	int i, j, v, rc;
11065 	struct vi_info *vi;
11066 
11067 	v = sc->tt.tls;
11068 	rc = sysctl_handle_int(oidp, &v, 0, req);
11069 	if (rc != 0 || req->newptr == NULL)
11070 		return (rc);
11071 
11072 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11073 		return (ENOTSUP);
11074 
11075 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11076 	if (rc)
11077 		return (rc);
11078 	if (hw_off_limits(sc))
11079 		rc = ENXIO;
11080 	else {
11081 		sc->tt.tls = !!v;
11082 		for_each_port(sc, i) {
11083 			for_each_vi(sc->port[i], j, vi) {
11084 				if (vi->flags & VI_INIT_DONE)
11085 					t4_update_fl_bufsize(vi->ifp);
11086 			}
11087 		}
11088 	}
11089 	end_synchronized_op(sc, 0);
11090 
11091 	return (rc);
11092 
11093 }
11094 
11095 static int
11096 sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS)
11097 {
11098 	struct adapter *sc = arg1;
11099 	int *old_ports, *new_ports;
11100 	int i, new_count, rc;
11101 
11102 	if (req->newptr == NULL && req->oldptr == NULL)
11103 		return (SYSCTL_OUT(req, NULL, imax(sc->tt.num_tls_rx_ports, 1) *
11104 		    sizeof(sc->tt.tls_rx_ports[0])));
11105 
11106 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tlsrx");
11107 	if (rc)
11108 		return (rc);
11109 
11110 	if (hw_off_limits(sc)) {
11111 		rc = ENXIO;
11112 		goto done;
11113 	}
11114 
11115 	if (sc->tt.num_tls_rx_ports == 0) {
11116 		i = -1;
11117 		rc = SYSCTL_OUT(req, &i, sizeof(i));
11118 	} else
11119 		rc = SYSCTL_OUT(req, sc->tt.tls_rx_ports,
11120 		    sc->tt.num_tls_rx_ports * sizeof(sc->tt.tls_rx_ports[0]));
11121 	if (rc == 0 && req->newptr != NULL) {
11122 		new_count = req->newlen / sizeof(new_ports[0]);
11123 		new_ports = malloc(new_count * sizeof(new_ports[0]), M_CXGBE,
11124 		    M_WAITOK);
11125 		rc = SYSCTL_IN(req, new_ports, new_count *
11126 		    sizeof(new_ports[0]));
11127 		if (rc)
11128 			goto err;
11129 
11130 		/* Allow setting to a single '-1' to clear the list. */
11131 		if (new_count == 1 && new_ports[0] == -1) {
11132 			ADAPTER_LOCK(sc);
11133 			old_ports = sc->tt.tls_rx_ports;
11134 			sc->tt.tls_rx_ports = NULL;
11135 			sc->tt.num_tls_rx_ports = 0;
11136 			ADAPTER_UNLOCK(sc);
11137 			free(old_ports, M_CXGBE);
11138 		} else {
11139 			for (i = 0; i < new_count; i++) {
11140 				if (new_ports[i] < 1 ||
11141 				    new_ports[i] > IPPORT_MAX) {
11142 					rc = EINVAL;
11143 					goto err;
11144 				}
11145 			}
11146 
11147 			ADAPTER_LOCK(sc);
11148 			old_ports = sc->tt.tls_rx_ports;
11149 			sc->tt.tls_rx_ports = new_ports;
11150 			sc->tt.num_tls_rx_ports = new_count;
11151 			ADAPTER_UNLOCK(sc);
11152 			free(old_ports, M_CXGBE);
11153 			new_ports = NULL;
11154 		}
11155 	err:
11156 		free(new_ports, M_CXGBE);
11157 	}
11158 done:
11159 	end_synchronized_op(sc, 0);
11160 	return (rc);
11161 }
11162 
11163 static int
11164 sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS)
11165 {
11166 	struct adapter *sc = arg1;
11167 	int v, rc;
11168 
11169 	v = sc->tt.tls_rx_timeout;
11170 	rc = sysctl_handle_int(oidp, &v, 0, req);
11171 	if (rc != 0 || req->newptr == NULL)
11172 		return (rc);
11173 
11174 	if (v < 0)
11175 		return (EINVAL);
11176 
11177 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11178 		return (ENOTSUP);
11179 
11180 	sc->tt.tls_rx_timeout = v;
11181 
11182 	return (0);
11183 
11184 }
11185 
11186 static void
11187 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11188 {
11189 	u_int rem = val % factor;
11190 
11191 	if (rem == 0)
11192 		snprintf(buf, len, "%u", val / factor);
11193 	else {
11194 		while (rem % 10 == 0)
11195 			rem /= 10;
11196 		snprintf(buf, len, "%u.%u", val / factor, rem);
11197 	}
11198 }
11199 
11200 static int
11201 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11202 {
11203 	struct adapter *sc = arg1;
11204 	char buf[16];
11205 	u_int res, re;
11206 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11207 
11208 	mtx_lock(&sc->reg_lock);
11209 	if (hw_off_limits(sc))
11210 		res = (u_int)-1;
11211 	else
11212 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11213 	mtx_unlock(&sc->reg_lock);
11214 	if (res == (u_int)-1)
11215 		return (ENXIO);
11216 
11217 	switch (arg2) {
11218 	case 0:
11219 		/* timer_tick */
11220 		re = G_TIMERRESOLUTION(res);
11221 		break;
11222 	case 1:
11223 		/* TCP timestamp tick */
11224 		re = G_TIMESTAMPRESOLUTION(res);
11225 		break;
11226 	case 2:
11227 		/* DACK tick */
11228 		re = G_DELAYEDACKRESOLUTION(res);
11229 		break;
11230 	default:
11231 		return (EDOOFUS);
11232 	}
11233 
11234 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11235 
11236 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11237 }
11238 
11239 static int
11240 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11241 {
11242 	struct adapter *sc = arg1;
11243 	int rc;
11244 	u_int dack_tmr, dack_re, v;
11245 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11246 
11247 	mtx_lock(&sc->reg_lock);
11248 	if (hw_off_limits(sc))
11249 		rc = ENXIO;
11250 	else {
11251 		rc = 0;
11252 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11253 		    A_TP_TIMER_RESOLUTION));
11254 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11255 	}
11256 	mtx_unlock(&sc->reg_lock);
11257 	if (rc != 0)
11258 		return (rc);
11259 
11260 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11261 
11262 	return (sysctl_handle_int(oidp, &v, 0, req));
11263 }
11264 
11265 static int
11266 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11267 {
11268 	struct adapter *sc = arg1;
11269 	int rc, reg = arg2;
11270 	u_int tre;
11271 	u_long tp_tick_us, v;
11272 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11273 
11274 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11275 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11276 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11277 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11278 
11279 	mtx_lock(&sc->reg_lock);
11280 	if (hw_off_limits(sc))
11281 		rc = ENXIO;
11282 	else {
11283 		rc = 0;
11284 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11285 		tp_tick_us = (cclk_ps << tre) / 1000000;
11286 		if (reg == A_TP_INIT_SRTT)
11287 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11288 		else
11289 			v = tp_tick_us * t4_read_reg(sc, reg);
11290 	}
11291 	mtx_unlock(&sc->reg_lock);
11292 	if (rc != 0)
11293 		return (rc);
11294 	else
11295 		return (sysctl_handle_long(oidp, &v, 0, req));
11296 }
11297 
11298 /*
11299  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11300  * passed to this function.
11301  */
11302 static int
11303 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11304 {
11305 	struct adapter *sc = arg1;
11306 	int rc, idx = arg2;
11307 	u_int v;
11308 
11309 	MPASS(idx >= 0 && idx <= 24);
11310 
11311 	mtx_lock(&sc->reg_lock);
11312 	if (hw_off_limits(sc))
11313 		rc = ENXIO;
11314 	else {
11315 		rc = 0;
11316 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11317 	}
11318 	mtx_unlock(&sc->reg_lock);
11319 	if (rc != 0)
11320 		return (rc);
11321 	else
11322 		return (sysctl_handle_int(oidp, &v, 0, req));
11323 }
11324 
11325 static int
11326 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11327 {
11328 	struct adapter *sc = arg1;
11329 	int rc, idx = arg2;
11330 	u_int shift, v, r;
11331 
11332 	MPASS(idx >= 0 && idx < 16);
11333 
11334 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11335 	shift = (idx & 3) << 3;
11336 	mtx_lock(&sc->reg_lock);
11337 	if (hw_off_limits(sc))
11338 		rc = ENXIO;
11339 	else {
11340 		rc = 0;
11341 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11342 	}
11343 	mtx_unlock(&sc->reg_lock);
11344 	if (rc != 0)
11345 		return (rc);
11346 	else
11347 		return (sysctl_handle_int(oidp, &v, 0, req));
11348 }
11349 
11350 static int
11351 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11352 {
11353 	struct vi_info *vi = arg1;
11354 	struct adapter *sc = vi->adapter;
11355 	int idx, rc, i;
11356 	struct sge_ofld_rxq *ofld_rxq;
11357 	uint8_t v;
11358 
11359 	idx = vi->ofld_tmr_idx;
11360 
11361 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11362 	if (rc != 0 || req->newptr == NULL)
11363 		return (rc);
11364 
11365 	if (idx < 0 || idx >= SGE_NTIMERS)
11366 		return (EINVAL);
11367 
11368 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11369 	    "t4otmr");
11370 	if (rc)
11371 		return (rc);
11372 
11373 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11374 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11375 #ifdef atomic_store_rel_8
11376 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11377 #else
11378 		ofld_rxq->iq.intr_params = v;
11379 #endif
11380 	}
11381 	vi->ofld_tmr_idx = idx;
11382 
11383 	end_synchronized_op(sc, LOCK_HELD);
11384 	return (0);
11385 }
11386 
11387 static int
11388 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11389 {
11390 	struct vi_info *vi = arg1;
11391 	struct adapter *sc = vi->adapter;
11392 	int idx, rc;
11393 
11394 	idx = vi->ofld_pktc_idx;
11395 
11396 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11397 	if (rc != 0 || req->newptr == NULL)
11398 		return (rc);
11399 
11400 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11401 		return (EINVAL);
11402 
11403 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11404 	    "t4opktc");
11405 	if (rc)
11406 		return (rc);
11407 
11408 	if (vi->flags & VI_INIT_DONE)
11409 		rc = EBUSY; /* cannot be changed once the queues are created */
11410 	else
11411 		vi->ofld_pktc_idx = idx;
11412 
11413 	end_synchronized_op(sc, LOCK_HELD);
11414 	return (rc);
11415 }
11416 #endif
11417 
11418 static int
11419 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11420 {
11421 	int rc;
11422 
11423 	if (cntxt->cid > M_CTXTQID)
11424 		return (EINVAL);
11425 
11426 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11427 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11428 		return (EINVAL);
11429 
11430 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11431 	if (rc)
11432 		return (rc);
11433 
11434 	if (hw_off_limits(sc)) {
11435 		rc = ENXIO;
11436 		goto done;
11437 	}
11438 
11439 	if (sc->flags & FW_OK) {
11440 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11441 		    &cntxt->data[0]);
11442 		if (rc == 0)
11443 			goto done;
11444 	}
11445 
11446 	/*
11447 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11448 	 * the backdoor.
11449 	 */
11450 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11451 done:
11452 	end_synchronized_op(sc, 0);
11453 	return (rc);
11454 }
11455 
11456 static int
11457 load_fw(struct adapter *sc, struct t4_data *fw)
11458 {
11459 	int rc;
11460 	uint8_t *fw_data;
11461 
11462 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11463 	if (rc)
11464 		return (rc);
11465 
11466 	if (hw_off_limits(sc)) {
11467 		rc = ENXIO;
11468 		goto done;
11469 	}
11470 
11471 	/*
11472 	 * The firmware, with the sole exception of the memory parity error
11473 	 * handler, runs from memory and not flash.  It is almost always safe to
11474 	 * install a new firmware on a running system.  Just set bit 1 in
11475 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11476 	 */
11477 	if (sc->flags & FULL_INIT_DONE &&
11478 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11479 		rc = EBUSY;
11480 		goto done;
11481 	}
11482 
11483 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11484 
11485 	rc = copyin(fw->data, fw_data, fw->len);
11486 	if (rc == 0)
11487 		rc = -t4_load_fw(sc, fw_data, fw->len);
11488 
11489 	free(fw_data, M_CXGBE);
11490 done:
11491 	end_synchronized_op(sc, 0);
11492 	return (rc);
11493 }
11494 
11495 static int
11496 load_cfg(struct adapter *sc, struct t4_data *cfg)
11497 {
11498 	int rc;
11499 	uint8_t *cfg_data = NULL;
11500 
11501 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11502 	if (rc)
11503 		return (rc);
11504 
11505 	if (hw_off_limits(sc)) {
11506 		rc = ENXIO;
11507 		goto done;
11508 	}
11509 
11510 	if (cfg->len == 0) {
11511 		/* clear */
11512 		rc = -t4_load_cfg(sc, NULL, 0);
11513 		goto done;
11514 	}
11515 
11516 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11517 
11518 	rc = copyin(cfg->data, cfg_data, cfg->len);
11519 	if (rc == 0)
11520 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11521 
11522 	free(cfg_data, M_CXGBE);
11523 done:
11524 	end_synchronized_op(sc, 0);
11525 	return (rc);
11526 }
11527 
11528 static int
11529 load_boot(struct adapter *sc, struct t4_bootrom *br)
11530 {
11531 	int rc;
11532 	uint8_t *br_data = NULL;
11533 	u_int offset;
11534 
11535 	if (br->len > 1024 * 1024)
11536 		return (EFBIG);
11537 
11538 	if (br->pf_offset == 0) {
11539 		/* pfidx */
11540 		if (br->pfidx_addr > 7)
11541 			return (EINVAL);
11542 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11543 		    A_PCIE_PF_EXPROM_OFST)));
11544 	} else if (br->pf_offset == 1) {
11545 		/* offset */
11546 		offset = G_OFFSET(br->pfidx_addr);
11547 	} else {
11548 		return (EINVAL);
11549 	}
11550 
11551 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11552 	if (rc)
11553 		return (rc);
11554 
11555 	if (hw_off_limits(sc)) {
11556 		rc = ENXIO;
11557 		goto done;
11558 	}
11559 
11560 	if (br->len == 0) {
11561 		/* clear */
11562 		rc = -t4_load_boot(sc, NULL, offset, 0);
11563 		goto done;
11564 	}
11565 
11566 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11567 
11568 	rc = copyin(br->data, br_data, br->len);
11569 	if (rc == 0)
11570 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11571 
11572 	free(br_data, M_CXGBE);
11573 done:
11574 	end_synchronized_op(sc, 0);
11575 	return (rc);
11576 }
11577 
11578 static int
11579 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11580 {
11581 	int rc;
11582 	uint8_t *bc_data = NULL;
11583 
11584 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11585 	if (rc)
11586 		return (rc);
11587 
11588 	if (hw_off_limits(sc)) {
11589 		rc = ENXIO;
11590 		goto done;
11591 	}
11592 
11593 	if (bc->len == 0) {
11594 		/* clear */
11595 		rc = -t4_load_bootcfg(sc, NULL, 0);
11596 		goto done;
11597 	}
11598 
11599 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11600 
11601 	rc = copyin(bc->data, bc_data, bc->len);
11602 	if (rc == 0)
11603 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11604 
11605 	free(bc_data, M_CXGBE);
11606 done:
11607 	end_synchronized_op(sc, 0);
11608 	return (rc);
11609 }
11610 
11611 static int
11612 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11613 {
11614 	int rc;
11615 	struct cudbg_init *cudbg;
11616 	void *handle, *buf;
11617 
11618 	/* buf is large, don't block if no memory is available */
11619 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11620 	if (buf == NULL)
11621 		return (ENOMEM);
11622 
11623 	handle = cudbg_alloc_handle();
11624 	if (handle == NULL) {
11625 		rc = ENOMEM;
11626 		goto done;
11627 	}
11628 
11629 	cudbg = cudbg_get_init(handle);
11630 	cudbg->adap = sc;
11631 	cudbg->print = (cudbg_print_cb)printf;
11632 
11633 #ifndef notyet
11634 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11635 	    __func__, dump->wr_flash, dump->len, dump->data);
11636 #endif
11637 
11638 	if (dump->wr_flash)
11639 		cudbg->use_flash = 1;
11640 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11641 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11642 
11643 	rc = cudbg_collect(handle, buf, &dump->len);
11644 	if (rc != 0)
11645 		goto done;
11646 
11647 	rc = copyout(buf, dump->data, dump->len);
11648 done:
11649 	cudbg_free_handle(handle);
11650 	free(buf, M_CXGBE);
11651 	return (rc);
11652 }
11653 
11654 static void
11655 free_offload_policy(struct t4_offload_policy *op)
11656 {
11657 	struct offload_rule *r;
11658 	int i;
11659 
11660 	if (op == NULL)
11661 		return;
11662 
11663 	r = &op->rule[0];
11664 	for (i = 0; i < op->nrules; i++, r++) {
11665 		free(r->bpf_prog.bf_insns, M_CXGBE);
11666 	}
11667 	free(op->rule, M_CXGBE);
11668 	free(op, M_CXGBE);
11669 }
11670 
11671 static int
11672 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11673 {
11674 	int i, rc, len;
11675 	struct t4_offload_policy *op, *old;
11676 	struct bpf_program *bf;
11677 	const struct offload_settings *s;
11678 	struct offload_rule *r;
11679 	void *u;
11680 
11681 	if (!is_offload(sc))
11682 		return (ENODEV);
11683 
11684 	if (uop->nrules == 0) {
11685 		/* Delete installed policies. */
11686 		op = NULL;
11687 		goto set_policy;
11688 	} else if (uop->nrules > 256) { /* arbitrary */
11689 		return (E2BIG);
11690 	}
11691 
11692 	/* Copy userspace offload policy to kernel */
11693 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11694 	op->nrules = uop->nrules;
11695 	len = op->nrules * sizeof(struct offload_rule);
11696 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11697 	rc = copyin(uop->rule, op->rule, len);
11698 	if (rc) {
11699 		free(op->rule, M_CXGBE);
11700 		free(op, M_CXGBE);
11701 		return (rc);
11702 	}
11703 
11704 	r = &op->rule[0];
11705 	for (i = 0; i < op->nrules; i++, r++) {
11706 
11707 		/* Validate open_type */
11708 		if (r->open_type != OPEN_TYPE_LISTEN &&
11709 		    r->open_type != OPEN_TYPE_ACTIVE &&
11710 		    r->open_type != OPEN_TYPE_PASSIVE &&
11711 		    r->open_type != OPEN_TYPE_DONTCARE) {
11712 error:
11713 			/*
11714 			 * Rules 0 to i have malloc'd filters that need to be
11715 			 * freed.  Rules i+1 to nrules have userspace pointers
11716 			 * and should be left alone.
11717 			 */
11718 			op->nrules = i;
11719 			free_offload_policy(op);
11720 			return (rc);
11721 		}
11722 
11723 		/* Validate settings */
11724 		s = &r->settings;
11725 		if ((s->offload != 0 && s->offload != 1) ||
11726 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11727 		    s->sched_class < -1 ||
11728 		    s->sched_class >= sc->params.nsched_cls) {
11729 			rc = EINVAL;
11730 			goto error;
11731 		}
11732 
11733 		bf = &r->bpf_prog;
11734 		u = bf->bf_insns;	/* userspace ptr */
11735 		bf->bf_insns = NULL;
11736 		if (bf->bf_len == 0) {
11737 			/* legal, matches everything */
11738 			continue;
11739 		}
11740 		len = bf->bf_len * sizeof(*bf->bf_insns);
11741 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11742 		rc = copyin(u, bf->bf_insns, len);
11743 		if (rc != 0)
11744 			goto error;
11745 
11746 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11747 			rc = EINVAL;
11748 			goto error;
11749 		}
11750 	}
11751 set_policy:
11752 	rw_wlock(&sc->policy_lock);
11753 	old = sc->policy;
11754 	sc->policy = op;
11755 	rw_wunlock(&sc->policy_lock);
11756 	free_offload_policy(old);
11757 
11758 	return (0);
11759 }
11760 
11761 #define MAX_READ_BUF_SIZE (128 * 1024)
11762 static int
11763 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11764 {
11765 	uint32_t addr, remaining, n;
11766 	uint32_t *buf;
11767 	int rc;
11768 	uint8_t *dst;
11769 
11770 	mtx_lock(&sc->reg_lock);
11771 	if (hw_off_limits(sc))
11772 		rc = ENXIO;
11773 	else
11774 		rc = validate_mem_range(sc, mr->addr, mr->len);
11775 	mtx_unlock(&sc->reg_lock);
11776 	if (rc != 0)
11777 		return (rc);
11778 
11779 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11780 	addr = mr->addr;
11781 	remaining = mr->len;
11782 	dst = (void *)mr->data;
11783 
11784 	while (remaining) {
11785 		n = min(remaining, MAX_READ_BUF_SIZE);
11786 		mtx_lock(&sc->reg_lock);
11787 		if (hw_off_limits(sc))
11788 			rc = ENXIO;
11789 		else
11790 			read_via_memwin(sc, 2, addr, buf, n);
11791 		mtx_unlock(&sc->reg_lock);
11792 		if (rc != 0)
11793 			break;
11794 
11795 		rc = copyout(buf, dst, n);
11796 		if (rc != 0)
11797 			break;
11798 
11799 		dst += n;
11800 		remaining -= n;
11801 		addr += n;
11802 	}
11803 
11804 	free(buf, M_CXGBE);
11805 	return (rc);
11806 }
11807 #undef MAX_READ_BUF_SIZE
11808 
11809 static int
11810 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11811 {
11812 	int rc;
11813 
11814 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11815 		return (EINVAL);
11816 
11817 	if (i2cd->len > sizeof(i2cd->data))
11818 		return (EFBIG);
11819 
11820 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11821 	if (rc)
11822 		return (rc);
11823 	if (hw_off_limits(sc))
11824 		rc = ENXIO;
11825 	else
11826 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11827 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11828 	end_synchronized_op(sc, 0);
11829 
11830 	return (rc);
11831 }
11832 
11833 static int
11834 clear_stats(struct adapter *sc, u_int port_id)
11835 {
11836 	int i, v, chan_map;
11837 	struct port_info *pi;
11838 	struct vi_info *vi;
11839 	struct sge_rxq *rxq;
11840 	struct sge_txq *txq;
11841 	struct sge_wrq *wrq;
11842 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11843 	struct sge_ofld_txq *ofld_txq;
11844 #endif
11845 #ifdef TCP_OFFLOAD
11846 	struct sge_ofld_rxq *ofld_rxq;
11847 #endif
11848 
11849 	if (port_id >= sc->params.nports)
11850 		return (EINVAL);
11851 	pi = sc->port[port_id];
11852 	if (pi == NULL)
11853 		return (EIO);
11854 
11855 	mtx_lock(&sc->reg_lock);
11856 	if (!hw_off_limits(sc)) {
11857 		/* MAC stats */
11858 		t4_clr_port_stats(sc, pi->tx_chan);
11859 		if (is_t6(sc)) {
11860 			if (pi->fcs_reg != -1)
11861 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11862 			else
11863 				pi->stats.rx_fcs_err = 0;
11864 		}
11865 		for_each_vi(pi, v, vi) {
11866 			if (vi->flags & VI_INIT_DONE)
11867 				t4_clr_vi_stats(sc, vi->vin);
11868 		}
11869 		chan_map = pi->rx_e_chan_map;
11870 		v = 0;	/* reuse */
11871 		while (chan_map) {
11872 			i = ffs(chan_map) - 1;
11873 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11874 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11875 			chan_map &= ~(1 << i);
11876 		}
11877 	}
11878 	mtx_unlock(&sc->reg_lock);
11879 	pi->tx_parse_error = 0;
11880 	pi->tnl_cong_drops = 0;
11881 
11882 	/*
11883 	 * Since this command accepts a port, clear stats for
11884 	 * all VIs on this port.
11885 	 */
11886 	for_each_vi(pi, v, vi) {
11887 		if (vi->flags & VI_INIT_DONE) {
11888 
11889 			for_each_rxq(vi, i, rxq) {
11890 #if defined(INET) || defined(INET6)
11891 				rxq->lro.lro_queued = 0;
11892 				rxq->lro.lro_flushed = 0;
11893 #endif
11894 				rxq->rxcsum = 0;
11895 				rxq->vlan_extraction = 0;
11896 				rxq->vxlan_rxcsum = 0;
11897 
11898 				rxq->fl.cl_allocated = 0;
11899 				rxq->fl.cl_recycled = 0;
11900 				rxq->fl.cl_fast_recycled = 0;
11901 			}
11902 
11903 			for_each_txq(vi, i, txq) {
11904 				txq->txcsum = 0;
11905 				txq->tso_wrs = 0;
11906 				txq->vlan_insertion = 0;
11907 				txq->imm_wrs = 0;
11908 				txq->sgl_wrs = 0;
11909 				txq->txpkt_wrs = 0;
11910 				txq->txpkts0_wrs = 0;
11911 				txq->txpkts1_wrs = 0;
11912 				txq->txpkts0_pkts = 0;
11913 				txq->txpkts1_pkts = 0;
11914 				txq->txpkts_flush = 0;
11915 				txq->raw_wrs = 0;
11916 				txq->vxlan_tso_wrs = 0;
11917 				txq->vxlan_txcsum = 0;
11918 				txq->kern_tls_records = 0;
11919 				txq->kern_tls_short = 0;
11920 				txq->kern_tls_partial = 0;
11921 				txq->kern_tls_full = 0;
11922 				txq->kern_tls_octets = 0;
11923 				txq->kern_tls_waste = 0;
11924 				txq->kern_tls_options = 0;
11925 				txq->kern_tls_header = 0;
11926 				txq->kern_tls_fin = 0;
11927 				txq->kern_tls_fin_short = 0;
11928 				txq->kern_tls_cbc = 0;
11929 				txq->kern_tls_gcm = 0;
11930 				mp_ring_reset_stats(txq->r);
11931 			}
11932 
11933 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11934 			for_each_ofld_txq(vi, i, ofld_txq) {
11935 				ofld_txq->wrq.tx_wrs_direct = 0;
11936 				ofld_txq->wrq.tx_wrs_copied = 0;
11937 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
11938 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
11939 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
11940 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
11941 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
11942 			}
11943 #endif
11944 #ifdef TCP_OFFLOAD
11945 			for_each_ofld_rxq(vi, i, ofld_rxq) {
11946 				ofld_rxq->fl.cl_allocated = 0;
11947 				ofld_rxq->fl.cl_recycled = 0;
11948 				ofld_rxq->fl.cl_fast_recycled = 0;
11949 				counter_u64_zero(
11950 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
11951 				counter_u64_zero(
11952 				    ofld_rxq->rx_iscsi_ddp_setup_error);
11953 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
11954 				ofld_rxq->rx_iscsi_ddp_octets = 0;
11955 				ofld_rxq->rx_iscsi_fl_pdus = 0;
11956 				ofld_rxq->rx_iscsi_fl_octets = 0;
11957 				ofld_rxq->rx_toe_tls_records = 0;
11958 				ofld_rxq->rx_toe_tls_octets = 0;
11959 			}
11960 #endif
11961 
11962 			if (IS_MAIN_VI(vi)) {
11963 				wrq = &sc->sge.ctrlq[pi->port_id];
11964 				wrq->tx_wrs_direct = 0;
11965 				wrq->tx_wrs_copied = 0;
11966 			}
11967 		}
11968 	}
11969 
11970 	return (0);
11971 }
11972 
11973 static int
11974 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
11975 {
11976 #ifdef INET6
11977 	struct in6_addr in6;
11978 
11979 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
11980 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
11981 		return (0);
11982 	else
11983 		return (EIO);
11984 #else
11985 	return (ENOTSUP);
11986 #endif
11987 }
11988 
11989 static int
11990 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
11991 {
11992 #ifdef INET6
11993 	struct in6_addr in6;
11994 
11995 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
11996 	return (t4_release_clip_addr(sc, &in6));
11997 #else
11998 	return (ENOTSUP);
11999 #endif
12000 }
12001 
12002 int
12003 t4_os_find_pci_capability(struct adapter *sc, int cap)
12004 {
12005 	int i;
12006 
12007 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
12008 }
12009 
12010 int
12011 t4_os_pci_save_state(struct adapter *sc)
12012 {
12013 	device_t dev;
12014 	struct pci_devinfo *dinfo;
12015 
12016 	dev = sc->dev;
12017 	dinfo = device_get_ivars(dev);
12018 
12019 	pci_cfg_save(dev, dinfo, 0);
12020 	return (0);
12021 }
12022 
12023 int
12024 t4_os_pci_restore_state(struct adapter *sc)
12025 {
12026 	device_t dev;
12027 	struct pci_devinfo *dinfo;
12028 
12029 	dev = sc->dev;
12030 	dinfo = device_get_ivars(dev);
12031 
12032 	pci_cfg_restore(dev, dinfo);
12033 	return (0);
12034 }
12035 
12036 void
12037 t4_os_portmod_changed(struct port_info *pi)
12038 {
12039 	struct adapter *sc = pi->adapter;
12040 	struct vi_info *vi;
12041 	struct ifnet *ifp;
12042 	static const char *mod_str[] = {
12043 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
12044 	};
12045 
12046 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
12047 	    ("%s: port_type %u", __func__, pi->port_type));
12048 
12049 	vi = &pi->vi[0];
12050 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12051 		PORT_LOCK(pi);
12052 		build_medialist(pi);
12053 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12054 			fixup_link_config(pi);
12055 			apply_link_config(pi);
12056 		}
12057 		PORT_UNLOCK(pi);
12058 		end_synchronized_op(sc, LOCK_HELD);
12059 	}
12060 
12061 	ifp = vi->ifp;
12062 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12063 		if_printf(ifp, "transceiver unplugged.\n");
12064 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12065 		if_printf(ifp, "unknown transceiver inserted.\n");
12066 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12067 		if_printf(ifp, "unsupported transceiver inserted.\n");
12068 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12069 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12070 		    port_top_speed(pi), mod_str[pi->mod_type]);
12071 	} else {
12072 		if_printf(ifp, "transceiver (type %d) inserted.\n",
12073 		    pi->mod_type);
12074 	}
12075 }
12076 
12077 void
12078 t4_os_link_changed(struct port_info *pi)
12079 {
12080 	struct vi_info *vi;
12081 	struct ifnet *ifp;
12082 	struct link_config *lc = &pi->link_cfg;
12083 	struct adapter *sc = pi->adapter;
12084 	int v;
12085 
12086 	PORT_LOCK_ASSERT_OWNED(pi);
12087 
12088 	if (is_t6(sc)) {
12089 		if (lc->link_ok) {
12090 			if (lc->speed > 25000 ||
12091 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12092 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12093 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12094 			} else {
12095 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12096 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12097 			}
12098 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12099 			pi->stats.rx_fcs_err = 0;
12100 		} else {
12101 			pi->fcs_reg = -1;
12102 		}
12103 	} else {
12104 		MPASS(pi->fcs_reg != -1);
12105 		MPASS(pi->fcs_base == 0);
12106 	}
12107 
12108 	for_each_vi(pi, v, vi) {
12109 		ifp = vi->ifp;
12110 		if (ifp == NULL)
12111 			continue;
12112 
12113 		if (lc->link_ok) {
12114 			ifp->if_baudrate = IF_Mbps(lc->speed);
12115 			if_link_state_change(ifp, LINK_STATE_UP);
12116 		} else {
12117 			if_link_state_change(ifp, LINK_STATE_DOWN);
12118 		}
12119 	}
12120 }
12121 
12122 void
12123 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12124 {
12125 	struct adapter *sc;
12126 
12127 	sx_slock(&t4_list_lock);
12128 	SLIST_FOREACH(sc, &t4_list, link) {
12129 		/*
12130 		 * func should not make any assumptions about what state sc is
12131 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12132 		 */
12133 		func(sc, arg);
12134 	}
12135 	sx_sunlock(&t4_list_lock);
12136 }
12137 
12138 static int
12139 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12140     struct thread *td)
12141 {
12142 	int rc;
12143 	struct adapter *sc = dev->si_drv1;
12144 
12145 	rc = priv_check(td, PRIV_DRIVER);
12146 	if (rc != 0)
12147 		return (rc);
12148 
12149 	switch (cmd) {
12150 	case CHELSIO_T4_GETREG: {
12151 		struct t4_reg *edata = (struct t4_reg *)data;
12152 
12153 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12154 			return (EFAULT);
12155 
12156 		mtx_lock(&sc->reg_lock);
12157 		if (hw_off_limits(sc))
12158 			rc = ENXIO;
12159 		else if (edata->size == 4)
12160 			edata->val = t4_read_reg(sc, edata->addr);
12161 		else if (edata->size == 8)
12162 			edata->val = t4_read_reg64(sc, edata->addr);
12163 		else
12164 			rc = EINVAL;
12165 		mtx_unlock(&sc->reg_lock);
12166 
12167 		break;
12168 	}
12169 	case CHELSIO_T4_SETREG: {
12170 		struct t4_reg *edata = (struct t4_reg *)data;
12171 
12172 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12173 			return (EFAULT);
12174 
12175 		mtx_lock(&sc->reg_lock);
12176 		if (hw_off_limits(sc))
12177 			rc = ENXIO;
12178 		else if (edata->size == 4) {
12179 			if (edata->val & 0xffffffff00000000)
12180 				rc = EINVAL;
12181 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12182 		} else if (edata->size == 8)
12183 			t4_write_reg64(sc, edata->addr, edata->val);
12184 		else
12185 			rc = EINVAL;
12186 		mtx_unlock(&sc->reg_lock);
12187 
12188 		break;
12189 	}
12190 	case CHELSIO_T4_REGDUMP: {
12191 		struct t4_regdump *regs = (struct t4_regdump *)data;
12192 		int reglen = t4_get_regs_len(sc);
12193 		uint8_t *buf;
12194 
12195 		if (regs->len < reglen) {
12196 			regs->len = reglen; /* hint to the caller */
12197 			return (ENOBUFS);
12198 		}
12199 
12200 		regs->len = reglen;
12201 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12202 		mtx_lock(&sc->reg_lock);
12203 		if (hw_off_limits(sc))
12204 			rc = ENXIO;
12205 		else
12206 			get_regs(sc, regs, buf);
12207 		mtx_unlock(&sc->reg_lock);
12208 		if (rc == 0)
12209 			rc = copyout(buf, regs->data, reglen);
12210 		free(buf, M_CXGBE);
12211 		break;
12212 	}
12213 	case CHELSIO_T4_GET_FILTER_MODE:
12214 		rc = get_filter_mode(sc, (uint32_t *)data);
12215 		break;
12216 	case CHELSIO_T4_SET_FILTER_MODE:
12217 		rc = set_filter_mode(sc, *(uint32_t *)data);
12218 		break;
12219 	case CHELSIO_T4_SET_FILTER_MASK:
12220 		rc = set_filter_mask(sc, *(uint32_t *)data);
12221 		break;
12222 	case CHELSIO_T4_GET_FILTER:
12223 		rc = get_filter(sc, (struct t4_filter *)data);
12224 		break;
12225 	case CHELSIO_T4_SET_FILTER:
12226 		rc = set_filter(sc, (struct t4_filter *)data);
12227 		break;
12228 	case CHELSIO_T4_DEL_FILTER:
12229 		rc = del_filter(sc, (struct t4_filter *)data);
12230 		break;
12231 	case CHELSIO_T4_GET_SGE_CONTEXT:
12232 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12233 		break;
12234 	case CHELSIO_T4_LOAD_FW:
12235 		rc = load_fw(sc, (struct t4_data *)data);
12236 		break;
12237 	case CHELSIO_T4_GET_MEM:
12238 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12239 		break;
12240 	case CHELSIO_T4_GET_I2C:
12241 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12242 		break;
12243 	case CHELSIO_T4_CLEAR_STATS:
12244 		rc = clear_stats(sc, *(uint32_t *)data);
12245 		break;
12246 	case CHELSIO_T4_SCHED_CLASS:
12247 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12248 		break;
12249 	case CHELSIO_T4_SCHED_QUEUE:
12250 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12251 		break;
12252 	case CHELSIO_T4_GET_TRACER:
12253 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12254 		break;
12255 	case CHELSIO_T4_SET_TRACER:
12256 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12257 		break;
12258 	case CHELSIO_T4_LOAD_CFG:
12259 		rc = load_cfg(sc, (struct t4_data *)data);
12260 		break;
12261 	case CHELSIO_T4_LOAD_BOOT:
12262 		rc = load_boot(sc, (struct t4_bootrom *)data);
12263 		break;
12264 	case CHELSIO_T4_LOAD_BOOTCFG:
12265 		rc = load_bootcfg(sc, (struct t4_data *)data);
12266 		break;
12267 	case CHELSIO_T4_CUDBG_DUMP:
12268 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12269 		break;
12270 	case CHELSIO_T4_SET_OFLD_POLICY:
12271 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12272 		break;
12273 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12274 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12275 		break;
12276 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12277 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12278 		break;
12279 	default:
12280 		rc = ENOTTY;
12281 	}
12282 
12283 	return (rc);
12284 }
12285 
12286 #ifdef TCP_OFFLOAD
12287 static int
12288 toe_capability(struct vi_info *vi, bool enable)
12289 {
12290 	int rc;
12291 	struct port_info *pi = vi->pi;
12292 	struct adapter *sc = pi->adapter;
12293 
12294 	ASSERT_SYNCHRONIZED_OP(sc);
12295 
12296 	if (!is_offload(sc))
12297 		return (ENODEV);
12298 	if (hw_off_limits(sc))
12299 		return (ENXIO);
12300 
12301 	if (enable) {
12302 #ifdef KERN_TLS
12303 		if (sc->flags & KERN_TLS_ON) {
12304 			int i, j, n;
12305 			struct port_info *p;
12306 			struct vi_info *v;
12307 
12308 			/*
12309 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12310 			 * on any ifnet.
12311 			 */
12312 			n = 0;
12313 			for_each_port(sc, i) {
12314 				p = sc->port[i];
12315 				for_each_vi(p, j, v) {
12316 					if (v->ifp->if_capenable & IFCAP_TXTLS) {
12317 						CH_WARN(sc,
12318 						    "%s has NIC TLS enabled.\n",
12319 						    device_get_nameunit(v->dev));
12320 						n++;
12321 					}
12322 				}
12323 			}
12324 			if (n > 0) {
12325 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12326 				    "associated with this adapter before "
12327 				    "trying to enable TOE.\n");
12328 				return (EAGAIN);
12329 			}
12330 			rc = t4_config_kern_tls(sc, false);
12331 			if (rc)
12332 				return (rc);
12333 		}
12334 #endif
12335 		if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
12336 			/* TOE is already enabled. */
12337 			return (0);
12338 		}
12339 
12340 		/*
12341 		 * We need the port's queues around so that we're able to send
12342 		 * and receive CPLs to/from the TOE even if the ifnet for this
12343 		 * port has never been UP'd administratively.
12344 		 */
12345 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12346 			return (rc);
12347 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12348 		    ((rc = vi_init(&pi->vi[0])) != 0))
12349 			return (rc);
12350 
12351 		if (isset(&sc->offload_map, pi->port_id)) {
12352 			/* TOE is enabled on another VI of this port. */
12353 			pi->uld_vis++;
12354 			return (0);
12355 		}
12356 
12357 		if (!uld_active(sc, ULD_TOM)) {
12358 			rc = t4_activate_uld(sc, ULD_TOM);
12359 			if (rc == EAGAIN) {
12360 				log(LOG_WARNING,
12361 				    "You must kldload t4_tom.ko before trying "
12362 				    "to enable TOE on a cxgbe interface.\n");
12363 			}
12364 			if (rc != 0)
12365 				return (rc);
12366 			KASSERT(sc->tom_softc != NULL,
12367 			    ("%s: TOM activated but softc NULL", __func__));
12368 			KASSERT(uld_active(sc, ULD_TOM),
12369 			    ("%s: TOM activated but flag not set", __func__));
12370 		}
12371 
12372 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12373 		if (!uld_active(sc, ULD_IWARP))
12374 			(void) t4_activate_uld(sc, ULD_IWARP);
12375 		if (!uld_active(sc, ULD_ISCSI))
12376 			(void) t4_activate_uld(sc, ULD_ISCSI);
12377 
12378 		pi->uld_vis++;
12379 		setbit(&sc->offload_map, pi->port_id);
12380 	} else {
12381 		pi->uld_vis--;
12382 
12383 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12384 			return (0);
12385 
12386 		KASSERT(uld_active(sc, ULD_TOM),
12387 		    ("%s: TOM never initialized?", __func__));
12388 		clrbit(&sc->offload_map, pi->port_id);
12389 	}
12390 
12391 	return (0);
12392 }
12393 
12394 /*
12395  * Add an upper layer driver to the global list.
12396  */
12397 int
12398 t4_register_uld(struct uld_info *ui)
12399 {
12400 	int rc = 0;
12401 	struct uld_info *u;
12402 
12403 	sx_xlock(&t4_uld_list_lock);
12404 	SLIST_FOREACH(u, &t4_uld_list, link) {
12405 	    if (u->uld_id == ui->uld_id) {
12406 		    rc = EEXIST;
12407 		    goto done;
12408 	    }
12409 	}
12410 
12411 	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
12412 	ui->refcount = 0;
12413 done:
12414 	sx_xunlock(&t4_uld_list_lock);
12415 	return (rc);
12416 }
12417 
12418 int
12419 t4_unregister_uld(struct uld_info *ui)
12420 {
12421 	int rc = EINVAL;
12422 	struct uld_info *u;
12423 
12424 	sx_xlock(&t4_uld_list_lock);
12425 
12426 	SLIST_FOREACH(u, &t4_uld_list, link) {
12427 	    if (u == ui) {
12428 		    if (ui->refcount > 0) {
12429 			    rc = EBUSY;
12430 			    goto done;
12431 		    }
12432 
12433 		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
12434 		    rc = 0;
12435 		    goto done;
12436 	    }
12437 	}
12438 done:
12439 	sx_xunlock(&t4_uld_list_lock);
12440 	return (rc);
12441 }
12442 
12443 int
12444 t4_activate_uld(struct adapter *sc, int id)
12445 {
12446 	int rc;
12447 	struct uld_info *ui;
12448 
12449 	ASSERT_SYNCHRONIZED_OP(sc);
12450 
12451 	if (id < 0 || id > ULD_MAX)
12452 		return (EINVAL);
12453 	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
12454 
12455 	sx_slock(&t4_uld_list_lock);
12456 
12457 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12458 		if (ui->uld_id == id) {
12459 			if (!(sc->flags & FULL_INIT_DONE)) {
12460 				rc = adapter_init(sc);
12461 				if (rc != 0)
12462 					break;
12463 			}
12464 
12465 			rc = ui->activate(sc);
12466 			if (rc == 0) {
12467 				setbit(&sc->active_ulds, id);
12468 				ui->refcount++;
12469 			}
12470 			break;
12471 		}
12472 	}
12473 
12474 	sx_sunlock(&t4_uld_list_lock);
12475 
12476 	return (rc);
12477 }
12478 
12479 int
12480 t4_deactivate_uld(struct adapter *sc, int id)
12481 {
12482 	int rc;
12483 	struct uld_info *ui;
12484 
12485 	ASSERT_SYNCHRONIZED_OP(sc);
12486 
12487 	if (id < 0 || id > ULD_MAX)
12488 		return (EINVAL);
12489 	rc = ENXIO;
12490 
12491 	sx_slock(&t4_uld_list_lock);
12492 
12493 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12494 		if (ui->uld_id == id) {
12495 			rc = ui->deactivate(sc);
12496 			if (rc == 0) {
12497 				clrbit(&sc->active_ulds, id);
12498 				ui->refcount--;
12499 			}
12500 			break;
12501 		}
12502 	}
12503 
12504 	sx_sunlock(&t4_uld_list_lock);
12505 
12506 	return (rc);
12507 }
12508 
12509 static void
12510 t4_async_event(void *arg, int n)
12511 {
12512 	struct uld_info *ui;
12513 	struct adapter *sc = (struct adapter *)arg;
12514 
12515 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
12516 		return;
12517 	sx_slock(&t4_uld_list_lock);
12518 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12519 		if (ui->uld_id == ULD_IWARP) {
12520 			ui->async_event(sc);
12521 			break;
12522 		}
12523 	}
12524 	sx_sunlock(&t4_uld_list_lock);
12525 	end_synchronized_op(sc, 0);
12526 }
12527 
12528 int
12529 uld_active(struct adapter *sc, int uld_id)
12530 {
12531 
12532 	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
12533 
12534 	return (isset(&sc->active_ulds, uld_id));
12535 }
12536 #endif
12537 
12538 #ifdef KERN_TLS
12539 static int
12540 ktls_capability(struct adapter *sc, bool enable)
12541 {
12542 	ASSERT_SYNCHRONIZED_OP(sc);
12543 
12544 	if (!is_ktls(sc))
12545 		return (ENODEV);
12546 	if (hw_off_limits(sc))
12547 		return (ENXIO);
12548 
12549 	if (enable) {
12550 		if (sc->flags & KERN_TLS_ON)
12551 			return (0);	/* already on */
12552 		if (sc->offload_map != 0) {
12553 			CH_WARN(sc,
12554 			    "Disable TOE on all interfaces associated with "
12555 			    "this adapter before trying to enable NIC TLS.\n");
12556 			return (EAGAIN);
12557 		}
12558 		return (t4_config_kern_tls(sc, true));
12559 	} else {
12560 		/*
12561 		 * Nothing to do for disable.  If TOE is enabled sometime later
12562 		 * then toe_capability will reconfigure the hardware.
12563 		 */
12564 		return (0);
12565 	}
12566 }
12567 #endif
12568 
12569 /*
12570  * t  = ptr to tunable.
12571  * nc = number of CPUs.
12572  * c  = compiled in default for that tunable.
12573  */
12574 static void
12575 calculate_nqueues(int *t, int nc, const int c)
12576 {
12577 	int nq;
12578 
12579 	if (*t > 0)
12580 		return;
12581 	nq = *t < 0 ? -*t : c;
12582 	*t = min(nc, nq);
12583 }
12584 
12585 /*
12586  * Come up with reasonable defaults for some of the tunables, provided they're
12587  * not set by the user (in which case we'll use the values as is).
12588  */
12589 static void
12590 tweak_tunables(void)
12591 {
12592 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12593 
12594 	if (t4_ntxq < 1) {
12595 #ifdef RSS
12596 		t4_ntxq = rss_getnumbuckets();
12597 #else
12598 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12599 #endif
12600 	}
12601 
12602 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12603 
12604 	if (t4_nrxq < 1) {
12605 #ifdef RSS
12606 		t4_nrxq = rss_getnumbuckets();
12607 #else
12608 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12609 #endif
12610 	}
12611 
12612 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12613 
12614 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12615 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12616 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12617 #endif
12618 #ifdef TCP_OFFLOAD
12619 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12620 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12621 #endif
12622 
12623 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12624 	if (t4_toecaps_allowed == -1)
12625 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12626 #else
12627 	if (t4_toecaps_allowed == -1)
12628 		t4_toecaps_allowed = 0;
12629 #endif
12630 
12631 #ifdef TCP_OFFLOAD
12632 	if (t4_rdmacaps_allowed == -1) {
12633 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12634 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12635 	}
12636 
12637 	if (t4_iscsicaps_allowed == -1) {
12638 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12639 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12640 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12641 	}
12642 
12643 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12644 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12645 
12646 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12647 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12648 
12649 	if (t4_toe_tls_rx_timeout < 0)
12650 		t4_toe_tls_rx_timeout = 0;
12651 #else
12652 	if (t4_rdmacaps_allowed == -1)
12653 		t4_rdmacaps_allowed = 0;
12654 
12655 	if (t4_iscsicaps_allowed == -1)
12656 		t4_iscsicaps_allowed = 0;
12657 #endif
12658 
12659 #ifdef DEV_NETMAP
12660 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12661 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12662 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12663 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12664 #endif
12665 
12666 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12667 		t4_tmr_idx = TMR_IDX;
12668 
12669 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12670 		t4_pktc_idx = PKTC_IDX;
12671 
12672 	if (t4_qsize_txq < 128)
12673 		t4_qsize_txq = 128;
12674 
12675 	if (t4_qsize_rxq < 128)
12676 		t4_qsize_rxq = 128;
12677 	while (t4_qsize_rxq & 7)
12678 		t4_qsize_rxq++;
12679 
12680 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12681 
12682 	/*
12683 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12684 	 * VI for the port.  The rest are additional virtual interfaces on the
12685 	 * same physical port.  Note that the main VI does not have native
12686 	 * netmap support but the extra VIs do.
12687 	 *
12688 	 * Limit the number of VIs per port to the number of available
12689 	 * MAC addresses per port.
12690 	 */
12691 	if (t4_num_vis < 1)
12692 		t4_num_vis = 1;
12693 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12694 		t4_num_vis = nitems(vi_mac_funcs);
12695 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12696 	}
12697 
12698 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12699 		pcie_relaxed_ordering = 1;
12700 #if defined(__i386__) || defined(__amd64__)
12701 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12702 			pcie_relaxed_ordering = 0;
12703 #endif
12704 	}
12705 }
12706 
12707 #ifdef DDB
12708 static void
12709 t4_dump_tcb(struct adapter *sc, int tid)
12710 {
12711 	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
12712 
12713 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12714 	save = t4_read_reg(sc, reg);
12715 	base = sc->memwin[2].mw_base;
12716 
12717 	/* Dump TCB for the tid */
12718 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12719 	tcb_addr += tid * TCB_SIZE;
12720 
12721 	if (is_t4(sc)) {
12722 		pf = 0;
12723 		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
12724 	} else {
12725 		pf = V_PFNUM(sc->pf);
12726 		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
12727 	}
12728 	t4_write_reg(sc, reg, win_pos | pf);
12729 	t4_read_reg(sc, reg);
12730 
12731 	off = tcb_addr - win_pos;
12732 	for (i = 0; i < 4; i++) {
12733 		uint32_t buf[8];
12734 		for (j = 0; j < 8; j++, off += 4)
12735 			buf[j] = htonl(t4_read_reg(sc, base + off));
12736 
12737 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12738 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12739 		    buf[7]);
12740 	}
12741 
12742 	t4_write_reg(sc, reg, save);
12743 	t4_read_reg(sc, reg);
12744 }
12745 
12746 static void
12747 t4_dump_devlog(struct adapter *sc)
12748 {
12749 	struct devlog_params *dparams = &sc->params.devlog;
12750 	struct fw_devlog_e e;
12751 	int i, first, j, m, nentries, rc;
12752 	uint64_t ftstamp = UINT64_MAX;
12753 
12754 	if (dparams->start == 0) {
12755 		db_printf("devlog params not valid\n");
12756 		return;
12757 	}
12758 
12759 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12760 	m = fwmtype_to_hwmtype(dparams->memtype);
12761 
12762 	/* Find the first entry. */
12763 	first = -1;
12764 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12765 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12766 		    sizeof(e), (void *)&e);
12767 		if (rc != 0)
12768 			break;
12769 
12770 		if (e.timestamp == 0)
12771 			break;
12772 
12773 		e.timestamp = be64toh(e.timestamp);
12774 		if (e.timestamp < ftstamp) {
12775 			ftstamp = e.timestamp;
12776 			first = i;
12777 		}
12778 	}
12779 
12780 	if (first == -1)
12781 		return;
12782 
12783 	i = first;
12784 	do {
12785 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12786 		    sizeof(e), (void *)&e);
12787 		if (rc != 0)
12788 			return;
12789 
12790 		if (e.timestamp == 0)
12791 			return;
12792 
12793 		e.timestamp = be64toh(e.timestamp);
12794 		e.seqno = be32toh(e.seqno);
12795 		for (j = 0; j < 8; j++)
12796 			e.params[j] = be32toh(e.params[j]);
12797 
12798 		db_printf("%10d  %15ju  %8s  %8s  ",
12799 		    e.seqno, e.timestamp,
12800 		    (e.level < nitems(devlog_level_strings) ?
12801 			devlog_level_strings[e.level] : "UNKNOWN"),
12802 		    (e.facility < nitems(devlog_facility_strings) ?
12803 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12804 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12805 		    e.params[3], e.params[4], e.params[5], e.params[6],
12806 		    e.params[7]);
12807 
12808 		if (++i == nentries)
12809 			i = 0;
12810 	} while (i != first && !db_pager_quit);
12811 }
12812 
12813 static struct command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
12814 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
12815 
12816 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
12817 {
12818 	device_t dev;
12819 	int t;
12820 	bool valid;
12821 
12822 	valid = false;
12823 	t = db_read_token();
12824 	if (t == tIDENT) {
12825 		dev = device_lookup_by_name(db_tok_string);
12826 		valid = true;
12827 	}
12828 	db_skip_to_eol();
12829 	if (!valid) {
12830 		db_printf("usage: show t4 devlog <nexus>\n");
12831 		return;
12832 	}
12833 
12834 	if (dev == NULL) {
12835 		db_printf("device not found\n");
12836 		return;
12837 	}
12838 
12839 	t4_dump_devlog(device_get_softc(dev));
12840 }
12841 
12842 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
12843 {
12844 	device_t dev;
12845 	int radix, tid, t;
12846 	bool valid;
12847 
12848 	valid = false;
12849 	radix = db_radix;
12850 	db_radix = 10;
12851 	t = db_read_token();
12852 	if (t == tIDENT) {
12853 		dev = device_lookup_by_name(db_tok_string);
12854 		t = db_read_token();
12855 		if (t == tNUMBER) {
12856 			tid = db_tok_number;
12857 			valid = true;
12858 		}
12859 	}
12860 	db_radix = radix;
12861 	db_skip_to_eol();
12862 	if (!valid) {
12863 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
12864 		return;
12865 	}
12866 
12867 	if (dev == NULL) {
12868 		db_printf("device not found\n");
12869 		return;
12870 	}
12871 	if (tid < 0) {
12872 		db_printf("invalid tid\n");
12873 		return;
12874 	}
12875 
12876 	t4_dump_tcb(device_get_softc(dev), tid);
12877 }
12878 #endif
12879 
12880 static eventhandler_tag vxlan_start_evtag;
12881 static eventhandler_tag vxlan_stop_evtag;
12882 
12883 struct vxlan_evargs {
12884 	struct ifnet *ifp;
12885 	uint16_t port;
12886 };
12887 
12888 static void
12889 enable_vxlan_rx(struct adapter *sc)
12890 {
12891 	int i, rc;
12892 	struct port_info *pi;
12893 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
12894 
12895 	ASSERT_SYNCHRONIZED_OP(sc);
12896 
12897 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
12898 	    F_VXLAN_EN);
12899 	for_each_port(sc, i) {
12900 		pi = sc->port[i];
12901 		if (pi->vxlan_tcam_entry == true)
12902 			continue;
12903 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
12904 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
12905 		    true);
12906 		if (rc < 0) {
12907 			rc = -rc;
12908 			CH_ERR(&pi->vi[0],
12909 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
12910 		} else {
12911 			MPASS(rc == sc->rawf_base + pi->port_id);
12912 			pi->vxlan_tcam_entry = true;
12913 		}
12914 	}
12915 }
12916 
12917 static void
12918 t4_vxlan_start(struct adapter *sc, void *arg)
12919 {
12920 	struct vxlan_evargs *v = arg;
12921 
12922 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
12923 		return;
12924 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
12925 		return;
12926 
12927 	if (sc->vxlan_refcount == 0) {
12928 		sc->vxlan_port = v->port;
12929 		sc->vxlan_refcount = 1;
12930 		if (!hw_off_limits(sc))
12931 			enable_vxlan_rx(sc);
12932 	} else if (sc->vxlan_port == v->port) {
12933 		sc->vxlan_refcount++;
12934 	} else {
12935 		CH_ERR(sc, "VXLAN already configured on port  %d; "
12936 		    "ignoring attempt to configure it on port %d\n",
12937 		    sc->vxlan_port, v->port);
12938 	}
12939 	end_synchronized_op(sc, 0);
12940 }
12941 
12942 static void
12943 t4_vxlan_stop(struct adapter *sc, void *arg)
12944 {
12945 	struct vxlan_evargs *v = arg;
12946 
12947 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
12948 		return;
12949 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
12950 		return;
12951 
12952 	/*
12953 	 * VXLANs may have been configured before the driver was loaded so we
12954 	 * may see more stops than starts.  This is not handled cleanly but at
12955 	 * least we keep the refcount sane.
12956 	 */
12957 	if (sc->vxlan_port != v->port)
12958 		goto done;
12959 	if (sc->vxlan_refcount == 0) {
12960 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
12961 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
12962 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
12963 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
12964 done:
12965 	end_synchronized_op(sc, 0);
12966 }
12967 
12968 static void
12969 t4_vxlan_start_handler(void *arg __unused, struct ifnet *ifp,
12970     sa_family_t family, u_int port)
12971 {
12972 	struct vxlan_evargs v;
12973 
12974 	MPASS(family == AF_INET || family == AF_INET6);
12975 	v.ifp = ifp;
12976 	v.port = port;
12977 
12978 	t4_iterate(t4_vxlan_start, &v);
12979 }
12980 
12981 static void
12982 t4_vxlan_stop_handler(void *arg __unused, struct ifnet *ifp, sa_family_t family,
12983     u_int port)
12984 {
12985 	struct vxlan_evargs v;
12986 
12987 	MPASS(family == AF_INET || family == AF_INET6);
12988 	v.ifp = ifp;
12989 	v.port = port;
12990 
12991 	t4_iterate(t4_vxlan_stop, &v);
12992 }
12993 
12994 
12995 static struct sx mlu;	/* mod load unload */
12996 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
12997 
12998 static int
12999 mod_event(module_t mod, int cmd, void *arg)
13000 {
13001 	int rc = 0;
13002 	static int loaded = 0;
13003 
13004 	switch (cmd) {
13005 	case MOD_LOAD:
13006 		sx_xlock(&mlu);
13007 		if (loaded++ == 0) {
13008 			t4_sge_modload();
13009 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13010 			    t4_filter_rpl, CPL_COOKIE_FILTER);
13011 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
13012 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
13013 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
13014 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
13015 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13016 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
13017 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
13018 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
13019 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
13020 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
13021 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
13022 			    do_smt_write_rpl);
13023 			sx_init(&t4_list_lock, "T4/T5 adapters");
13024 			SLIST_INIT(&t4_list);
13025 			callout_init(&fatal_callout, 1);
13026 #ifdef TCP_OFFLOAD
13027 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
13028 			SLIST_INIT(&t4_uld_list);
13029 #endif
13030 #ifdef INET6
13031 			t4_clip_modload();
13032 #endif
13033 #ifdef KERN_TLS
13034 			t6_ktls_modload();
13035 #endif
13036 			t4_tracer_modload();
13037 			tweak_tunables();
13038 			vxlan_start_evtag =
13039 			    EVENTHANDLER_REGISTER(vxlan_start,
13040 				t4_vxlan_start_handler, NULL,
13041 				EVENTHANDLER_PRI_ANY);
13042 			vxlan_stop_evtag =
13043 			    EVENTHANDLER_REGISTER(vxlan_stop,
13044 				t4_vxlan_stop_handler, NULL,
13045 				EVENTHANDLER_PRI_ANY);
13046 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
13047 			    taskqueue_thread_enqueue, &reset_tq);
13048 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
13049 			    "t4_rst_thr");
13050 		}
13051 		sx_xunlock(&mlu);
13052 		break;
13053 
13054 	case MOD_UNLOAD:
13055 		sx_xlock(&mlu);
13056 		if (--loaded == 0) {
13057 			int tries;
13058 
13059 			taskqueue_free(reset_tq);
13060 			sx_slock(&t4_list_lock);
13061 			if (!SLIST_EMPTY(&t4_list)) {
13062 				rc = EBUSY;
13063 				sx_sunlock(&t4_list_lock);
13064 				goto done_unload;
13065 			}
13066 #ifdef TCP_OFFLOAD
13067 			sx_slock(&t4_uld_list_lock);
13068 			if (!SLIST_EMPTY(&t4_uld_list)) {
13069 				rc = EBUSY;
13070 				sx_sunlock(&t4_uld_list_lock);
13071 				sx_sunlock(&t4_list_lock);
13072 				goto done_unload;
13073 			}
13074 #endif
13075 			tries = 0;
13076 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13077 				uprintf("%ju clusters with custom free routine "
13078 				    "still is use.\n", t4_sge_extfree_refs());
13079 				pause("t4unload", 2 * hz);
13080 			}
13081 #ifdef TCP_OFFLOAD
13082 			sx_sunlock(&t4_uld_list_lock);
13083 #endif
13084 			sx_sunlock(&t4_list_lock);
13085 
13086 			if (t4_sge_extfree_refs() == 0) {
13087 				EVENTHANDLER_DEREGISTER(vxlan_start,
13088 				    vxlan_start_evtag);
13089 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13090 				    vxlan_stop_evtag);
13091 				t4_tracer_modunload();
13092 #ifdef KERN_TLS
13093 				t6_ktls_modunload();
13094 #endif
13095 #ifdef INET6
13096 				t4_clip_modunload();
13097 #endif
13098 #ifdef TCP_OFFLOAD
13099 				sx_destroy(&t4_uld_list_lock);
13100 #endif
13101 				sx_destroy(&t4_list_lock);
13102 				t4_sge_modunload();
13103 				loaded = 0;
13104 			} else {
13105 				rc = EBUSY;
13106 				loaded++;	/* undo earlier decrement */
13107 			}
13108 		}
13109 done_unload:
13110 		sx_xunlock(&mlu);
13111 		break;
13112 	}
13113 
13114 	return (rc);
13115 }
13116 
13117 static devclass_t t4_devclass, t5_devclass, t6_devclass;
13118 static devclass_t cxgbe_devclass, cxl_devclass, cc_devclass;
13119 static devclass_t vcxgbe_devclass, vcxl_devclass, vcc_devclass;
13120 
13121 DRIVER_MODULE(t4nex, pci, t4_driver, t4_devclass, mod_event, 0);
13122 MODULE_VERSION(t4nex, 1);
13123 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13124 #ifdef DEV_NETMAP
13125 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13126 #endif /* DEV_NETMAP */
13127 
13128 DRIVER_MODULE(t5nex, pci, t5_driver, t5_devclass, mod_event, 0);
13129 MODULE_VERSION(t5nex, 1);
13130 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13131 #ifdef DEV_NETMAP
13132 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13133 #endif /* DEV_NETMAP */
13134 
13135 DRIVER_MODULE(t6nex, pci, t6_driver, t6_devclass, mod_event, 0);
13136 MODULE_VERSION(t6nex, 1);
13137 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13138 #ifdef DEV_NETMAP
13139 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13140 #endif /* DEV_NETMAP */
13141 
13142 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, cxgbe_devclass, 0, 0);
13143 MODULE_VERSION(cxgbe, 1);
13144 
13145 DRIVER_MODULE(cxl, t5nex, cxl_driver, cxl_devclass, 0, 0);
13146 MODULE_VERSION(cxl, 1);
13147 
13148 DRIVER_MODULE(cc, t6nex, cc_driver, cc_devclass, 0, 0);
13149 MODULE_VERSION(cc, 1);
13150 
13151 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, vcxgbe_devclass, 0, 0);
13152 MODULE_VERSION(vcxgbe, 1);
13153 
13154 DRIVER_MODULE(vcxl, cxl, vcxl_driver, vcxl_devclass, 0, 0);
13155 MODULE_VERSION(vcxl, 1);
13156 
13157 DRIVER_MODULE(vcc, cc, vcc_driver, vcc_devclass, 0, 0);
13158 MODULE_VERSION(vcc, 1);
13159