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