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