xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision 8ddb146abcdf061be9f2c0db7e391697dafad85c)
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_clock_gate_on_suspend = 0;
630 SYSCTL_INT(_hw_cxgbe, OID_AUTO, clock_gate_on_suspend, CTLFLAG_RWTUN,
631     &t4_clock_gate_on_suspend, 0, "gate the clock on suspend");
632 
633 static int t4_tx_vm_wr = 0;
634 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
635     "Use VM work requests to transmit packets.");
636 
637 /*
638  * Set to non-zero to enable the attack filter.  A packet that matches any of
639  * these conditions will get dropped on ingress:
640  * 1) IP && source address == destination address.
641  * 2) TCP/IP && source address is not a unicast address.
642  * 3) TCP/IP && destination address is not a unicast address.
643  * 4) IP && source address is loopback (127.x.y.z).
644  * 5) IP && destination address is loopback (127.x.y.z).
645  * 6) IPv6 && source address == destination address.
646  * 7) IPv6 && source address is not a unicast address.
647  * 8) IPv6 && source address is loopback (::1/128).
648  * 9) IPv6 && destination address is loopback (::1/128).
649  * 10) IPv6 && source address is unspecified (::/128).
650  * 11) IPv6 && destination address is unspecified (::/128).
651  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
652  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
653  */
654 static int t4_attack_filter = 0;
655 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
656     &t4_attack_filter, 0, "Drop suspicious traffic");
657 
658 static int t4_drop_ip_fragments = 0;
659 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
660     &t4_drop_ip_fragments, 0, "Drop IP fragments");
661 
662 static int t4_drop_pkts_with_l2_errors = 1;
663 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
664     &t4_drop_pkts_with_l2_errors, 0,
665     "Drop all frames with Layer 2 length or checksum errors");
666 
667 static int t4_drop_pkts_with_l3_errors = 0;
668 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
669     &t4_drop_pkts_with_l3_errors, 0,
670     "Drop all frames with IP version, length, or checksum errors");
671 
672 static int t4_drop_pkts_with_l4_errors = 0;
673 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
674     &t4_drop_pkts_with_l4_errors, 0,
675     "Drop all frames with Layer 4 length, checksum, or other errors");
676 
677 #ifdef TCP_OFFLOAD
678 /*
679  * TOE tunables.
680  */
681 static int t4_cop_managed_offloading = 0;
682 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
683     &t4_cop_managed_offloading, 0,
684     "COP (Connection Offload Policy) controls all TOE offload");
685 #endif
686 
687 #ifdef KERN_TLS
688 /*
689  * This enables KERN_TLS for all adapters if set.
690  */
691 static int t4_kern_tls = 0;
692 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
693     "Enable KERN_TLS mode for T6 adapters");
694 
695 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
696     "cxgbe(4) KERN_TLS parameters");
697 
698 static int t4_tls_inline_keys = 0;
699 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
700     &t4_tls_inline_keys, 0,
701     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
702     "in card memory.");
703 
704 static int t4_tls_combo_wrs = 0;
705 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
706     0, "Attempt to combine TCB field updates with TLS record work requests.");
707 #endif
708 
709 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
710 static int vi_mac_funcs[] = {
711 	FW_VI_FUNC_ETH,
712 	FW_VI_FUNC_OFLD,
713 	FW_VI_FUNC_IWARP,
714 	FW_VI_FUNC_OPENISCSI,
715 	FW_VI_FUNC_OPENFCOE,
716 	FW_VI_FUNC_FOISCSI,
717 	FW_VI_FUNC_FOFCOE,
718 };
719 
720 struct intrs_and_queues {
721 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
722 	uint16_t num_vis;	/* number of VIs for each port */
723 	uint16_t nirq;		/* Total # of vectors */
724 	uint16_t ntxq;		/* # of NIC txq's for each port */
725 	uint16_t nrxq;		/* # of NIC rxq's for each port */
726 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
727 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
728 	uint16_t nnmtxq;	/* # of netmap txq's */
729 	uint16_t nnmrxq;	/* # of netmap rxq's */
730 
731 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
732 	uint16_t ntxq_vi;	/* # of NIC txq's */
733 	uint16_t nrxq_vi;	/* # of NIC rxq's */
734 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
735 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
736 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
737 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
738 };
739 
740 static void setup_memwin(struct adapter *);
741 static void position_memwin(struct adapter *, int, uint32_t);
742 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
743 static int fwmtype_to_hwmtype(int);
744 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
745     uint32_t *);
746 static int fixup_devlog_params(struct adapter *);
747 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
748 static int contact_firmware(struct adapter *);
749 static int partition_resources(struct adapter *);
750 static int get_params__pre_init(struct adapter *);
751 static int set_params__pre_init(struct adapter *);
752 static int get_params__post_init(struct adapter *);
753 static int set_params__post_init(struct adapter *);
754 static void t4_set_desc(struct adapter *);
755 static bool fixed_ifmedia(struct port_info *);
756 static void build_medialist(struct port_info *);
757 static void init_link_config(struct port_info *);
758 static int fixup_link_config(struct port_info *);
759 static int apply_link_config(struct port_info *);
760 static int cxgbe_init_synchronized(struct vi_info *);
761 static int cxgbe_uninit_synchronized(struct vi_info *);
762 static int adapter_full_init(struct adapter *);
763 static void adapter_full_uninit(struct adapter *);
764 static int vi_full_init(struct vi_info *);
765 static void vi_full_uninit(struct vi_info *);
766 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
767 static void quiesce_txq(struct sge_txq *);
768 static void quiesce_wrq(struct sge_wrq *);
769 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
770 static void quiesce_vi(struct vi_info *);
771 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
772     driver_intr_t *, void *, char *);
773 static int t4_free_irq(struct adapter *, struct irq *);
774 static void t4_init_atid_table(struct adapter *);
775 static void t4_free_atid_table(struct adapter *);
776 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
777 static void vi_refresh_stats(struct vi_info *);
778 static void cxgbe_refresh_stats(struct vi_info *);
779 static void cxgbe_tick(void *);
780 static void vi_tick(void *);
781 static void cxgbe_sysctls(struct port_info *);
782 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
783 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
784 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
785 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
786 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
787 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
788 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
789 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
790 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
791 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
792 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
793 static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
794 static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
795 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
796 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
797 static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
798 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
799 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
800 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
801 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
802 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
803 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
804 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
805 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
806 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
807 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
808 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
809 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
810 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
811 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
812 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
813 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
814 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
815 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
816 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
817 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
818 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
819 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
820 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
821 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
822 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
823 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
824 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
825 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
826 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
827 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
828 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
829 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
830 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
831 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
832 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
833 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
834 #ifdef TCP_OFFLOAD
835 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
836 static int sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS);
837 static int sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS);
838 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
839 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
840 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
841 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
842 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
843 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
844 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
845 #endif
846 static int get_sge_context(struct adapter *, struct t4_sge_context *);
847 static int load_fw(struct adapter *, struct t4_data *);
848 static int load_cfg(struct adapter *, struct t4_data *);
849 static int load_boot(struct adapter *, struct t4_bootrom *);
850 static int load_bootcfg(struct adapter *, struct t4_data *);
851 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
852 static void free_offload_policy(struct t4_offload_policy *);
853 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
854 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
855 static int read_i2c(struct adapter *, struct t4_i2c_data *);
856 static int clear_stats(struct adapter *, u_int);
857 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
858 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
859 #ifdef TCP_OFFLOAD
860 static int toe_capability(struct vi_info *, bool);
861 static int t4_deactivate_all_uld(struct adapter *);
862 static void t4_async_event(struct adapter *);
863 #endif
864 #ifdef KERN_TLS
865 static int ktls_capability(struct adapter *, bool);
866 #endif
867 static int mod_event(module_t, int, void *);
868 static int notify_siblings(device_t, int);
869 static uint64_t vi_get_counter(struct ifnet *, ift_counter);
870 static uint64_t cxgbe_get_counter(struct ifnet *, ift_counter);
871 static void enable_vxlan_rx(struct adapter *);
872 static void reset_adapter_task(void *, int);
873 static void fatal_error_task(void *, int);
874 static void dump_devlog(struct adapter *);
875 static void dump_cim_regs(struct adapter *);
876 static void dump_cimla(struct adapter *);
877 
878 struct {
879 	uint16_t device;
880 	char *desc;
881 } t4_pciids[] = {
882 	{0xa000, "Chelsio Terminator 4 FPGA"},
883 	{0x4400, "Chelsio T440-dbg"},
884 	{0x4401, "Chelsio T420-CR"},
885 	{0x4402, "Chelsio T422-CR"},
886 	{0x4403, "Chelsio T440-CR"},
887 	{0x4404, "Chelsio T420-BCH"},
888 	{0x4405, "Chelsio T440-BCH"},
889 	{0x4406, "Chelsio T440-CH"},
890 	{0x4407, "Chelsio T420-SO"},
891 	{0x4408, "Chelsio T420-CX"},
892 	{0x4409, "Chelsio T420-BT"},
893 	{0x440a, "Chelsio T404-BT"},
894 	{0x440e, "Chelsio T440-LP-CR"},
895 }, t5_pciids[] = {
896 	{0xb000, "Chelsio Terminator 5 FPGA"},
897 	{0x5400, "Chelsio T580-dbg"},
898 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
899 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
900 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
901 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
902 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
903 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
904 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
905 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
906 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
907 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
908 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
909 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
910 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
911 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
912 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
913 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
914 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
915 
916 	/* Custom */
917 	{0x5483, "Custom T540-CR"},
918 	{0x5484, "Custom T540-BT"},
919 }, t6_pciids[] = {
920 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
921 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
922 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
923 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
924 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
925 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
926 	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
927 	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
928 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
929 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
930 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
931 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
932 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
933 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
934 	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
935 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
936 
937 	/* Custom */
938 	{0x6480, "Custom T6225-CR"},
939 	{0x6481, "Custom T62100-CR"},
940 	{0x6482, "Custom T6225-CR"},
941 	{0x6483, "Custom T62100-CR"},
942 	{0x6484, "Custom T64100-CR"},
943 	{0x6485, "Custom T6240-SO"},
944 	{0x6486, "Custom T6225-SO-CR"},
945 	{0x6487, "Custom T6225-CR"},
946 };
947 
948 #ifdef TCP_OFFLOAD
949 /*
950  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
951  * be exactly the same for both rxq and ofld_rxq.
952  */
953 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
954 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
955 #endif
956 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
957 
958 static int
959 t4_probe(device_t dev)
960 {
961 	int i;
962 	uint16_t v = pci_get_vendor(dev);
963 	uint16_t d = pci_get_device(dev);
964 	uint8_t f = pci_get_function(dev);
965 
966 	if (v != PCI_VENDOR_ID_CHELSIO)
967 		return (ENXIO);
968 
969 	/* Attach only to PF0 of the FPGA */
970 	if (d == 0xa000 && f != 0)
971 		return (ENXIO);
972 
973 	for (i = 0; i < nitems(t4_pciids); i++) {
974 		if (d == t4_pciids[i].device) {
975 			device_set_desc(dev, t4_pciids[i].desc);
976 			return (BUS_PROBE_DEFAULT);
977 		}
978 	}
979 
980 	return (ENXIO);
981 }
982 
983 static int
984 t5_probe(device_t dev)
985 {
986 	int i;
987 	uint16_t v = pci_get_vendor(dev);
988 	uint16_t d = pci_get_device(dev);
989 	uint8_t f = pci_get_function(dev);
990 
991 	if (v != PCI_VENDOR_ID_CHELSIO)
992 		return (ENXIO);
993 
994 	/* Attach only to PF0 of the FPGA */
995 	if (d == 0xb000 && f != 0)
996 		return (ENXIO);
997 
998 	for (i = 0; i < nitems(t5_pciids); i++) {
999 		if (d == t5_pciids[i].device) {
1000 			device_set_desc(dev, t5_pciids[i].desc);
1001 			return (BUS_PROBE_DEFAULT);
1002 		}
1003 	}
1004 
1005 	return (ENXIO);
1006 }
1007 
1008 static int
1009 t6_probe(device_t dev)
1010 {
1011 	int i;
1012 	uint16_t v = pci_get_vendor(dev);
1013 	uint16_t d = pci_get_device(dev);
1014 
1015 	if (v != PCI_VENDOR_ID_CHELSIO)
1016 		return (ENXIO);
1017 
1018 	for (i = 0; i < nitems(t6_pciids); i++) {
1019 		if (d == t6_pciids[i].device) {
1020 			device_set_desc(dev, t6_pciids[i].desc);
1021 			return (BUS_PROBE_DEFAULT);
1022 		}
1023 	}
1024 
1025 	return (ENXIO);
1026 }
1027 
1028 static void
1029 t5_attribute_workaround(device_t dev)
1030 {
1031 	device_t root_port;
1032 	uint32_t v;
1033 
1034 	/*
1035 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1036 	 * Ordering attributes when replying to a TLP from a Root
1037 	 * Port.  As a workaround, find the parent Root Port and
1038 	 * disable No Snoop and Relaxed Ordering.  Note that this
1039 	 * affects all devices under this root port.
1040 	 */
1041 	root_port = pci_find_pcie_root_port(dev);
1042 	if (root_port == NULL) {
1043 		device_printf(dev, "Unable to find parent root port\n");
1044 		return;
1045 	}
1046 
1047 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1048 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1049 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1050 	    0)
1051 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1052 		    device_get_nameunit(root_port));
1053 }
1054 
1055 static const struct devnames devnames[] = {
1056 	{
1057 		.nexus_name = "t4nex",
1058 		.ifnet_name = "cxgbe",
1059 		.vi_ifnet_name = "vcxgbe",
1060 		.pf03_drv_name = "t4iov",
1061 		.vf_nexus_name = "t4vf",
1062 		.vf_ifnet_name = "cxgbev"
1063 	}, {
1064 		.nexus_name = "t5nex",
1065 		.ifnet_name = "cxl",
1066 		.vi_ifnet_name = "vcxl",
1067 		.pf03_drv_name = "t5iov",
1068 		.vf_nexus_name = "t5vf",
1069 		.vf_ifnet_name = "cxlv"
1070 	}, {
1071 		.nexus_name = "t6nex",
1072 		.ifnet_name = "cc",
1073 		.vi_ifnet_name = "vcc",
1074 		.pf03_drv_name = "t6iov",
1075 		.vf_nexus_name = "t6vf",
1076 		.vf_ifnet_name = "ccv"
1077 	}
1078 };
1079 
1080 void
1081 t4_init_devnames(struct adapter *sc)
1082 {
1083 	int id;
1084 
1085 	id = chip_id(sc);
1086 	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1087 		sc->names = &devnames[id - CHELSIO_T4];
1088 	else {
1089 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1090 		sc->names = NULL;
1091 	}
1092 }
1093 
1094 static int
1095 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1096 {
1097 	const char *parent, *name;
1098 	long value;
1099 	int line, unit;
1100 
1101 	line = 0;
1102 	parent = device_get_nameunit(sc->dev);
1103 	name = sc->names->ifnet_name;
1104 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1105 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1106 		    value == pi->port_id)
1107 			return (unit);
1108 	}
1109 	return (-1);
1110 }
1111 
1112 static int
1113 t4_attach(device_t dev)
1114 {
1115 	struct adapter *sc;
1116 	int rc = 0, i, j, rqidx, tqidx, nports;
1117 	struct make_dev_args mda;
1118 	struct intrs_and_queues iaq;
1119 	struct sge *s;
1120 	uint32_t *buf;
1121 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1122 	int ofld_tqidx;
1123 #endif
1124 #ifdef TCP_OFFLOAD
1125 	int ofld_rqidx;
1126 #endif
1127 #ifdef DEV_NETMAP
1128 	int nm_rqidx, nm_tqidx;
1129 #endif
1130 	int num_vis;
1131 
1132 	sc = device_get_softc(dev);
1133 	sc->dev = dev;
1134 	sysctl_ctx_init(&sc->ctx);
1135 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1136 
1137 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1138 		t5_attribute_workaround(dev);
1139 	pci_enable_busmaster(dev);
1140 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1141 		uint32_t v;
1142 
1143 		pci_set_max_read_req(dev, 4096);
1144 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1145 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1146 		if (pcie_relaxed_ordering == 0 &&
1147 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1148 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1149 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1150 		} else if (pcie_relaxed_ordering == 1 &&
1151 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1152 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1153 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1154 		}
1155 	}
1156 
1157 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1158 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1159 	sc->traceq = -1;
1160 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1161 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1162 	    device_get_nameunit(dev));
1163 
1164 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1165 	    device_get_nameunit(dev));
1166 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1167 	t4_add_adapter(sc);
1168 
1169 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1170 	TAILQ_INIT(&sc->sfl);
1171 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1172 
1173 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1174 
1175 	sc->policy = NULL;
1176 	rw_init(&sc->policy_lock, "connection offload policy");
1177 
1178 	callout_init(&sc->ktls_tick, 1);
1179 
1180 	refcount_init(&sc->vxlan_refcount, 0);
1181 
1182 	TASK_INIT(&sc->reset_task, 0, reset_adapter_task, sc);
1183 	TASK_INIT(&sc->fatal_error_task, 0, fatal_error_task, sc);
1184 
1185 	sc->ctrlq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1186 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1187 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1188 	sc->fwq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1189 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1190 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1191 
1192 	rc = t4_map_bars_0_and_4(sc);
1193 	if (rc != 0)
1194 		goto done; /* error message displayed already */
1195 
1196 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1197 
1198 	/* Prepare the adapter for operation. */
1199 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1200 	rc = -t4_prep_adapter(sc, buf);
1201 	free(buf, M_CXGBE);
1202 	if (rc != 0) {
1203 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1204 		goto done;
1205 	}
1206 
1207 	/*
1208 	 * This is the real PF# to which we're attaching.  Works from within PCI
1209 	 * passthrough environments too, where pci_get_function() could return a
1210 	 * different PF# depending on the passthrough configuration.  We need to
1211 	 * use the real PF# in all our communication with the firmware.
1212 	 */
1213 	j = t4_read_reg(sc, A_PL_WHOAMI);
1214 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1215 	sc->mbox = sc->pf;
1216 
1217 	t4_init_devnames(sc);
1218 	if (sc->names == NULL) {
1219 		rc = ENOTSUP;
1220 		goto done; /* error message displayed already */
1221 	}
1222 
1223 	/*
1224 	 * Do this really early, with the memory windows set up even before the
1225 	 * character device.  The userland tool's register i/o and mem read
1226 	 * will work even in "recovery mode".
1227 	 */
1228 	setup_memwin(sc);
1229 	if (t4_init_devlog_params(sc, 0) == 0)
1230 		fixup_devlog_params(sc);
1231 	make_dev_args_init(&mda);
1232 	mda.mda_devsw = &t4_cdevsw;
1233 	mda.mda_uid = UID_ROOT;
1234 	mda.mda_gid = GID_WHEEL;
1235 	mda.mda_mode = 0600;
1236 	mda.mda_si_drv1 = sc;
1237 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1238 	if (rc != 0)
1239 		device_printf(dev, "failed to create nexus char device: %d.\n",
1240 		    rc);
1241 
1242 	/* Go no further if recovery mode has been requested. */
1243 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1244 		device_printf(dev, "recovery mode.\n");
1245 		goto done;
1246 	}
1247 
1248 #if defined(__i386__)
1249 	if ((cpu_feature & CPUID_CX8) == 0) {
1250 		device_printf(dev, "64 bit atomics not available.\n");
1251 		rc = ENOTSUP;
1252 		goto done;
1253 	}
1254 #endif
1255 
1256 	/* Contact the firmware and try to become the master driver. */
1257 	rc = contact_firmware(sc);
1258 	if (rc != 0)
1259 		goto done; /* error message displayed already */
1260 	MPASS(sc->flags & FW_OK);
1261 
1262 	rc = get_params__pre_init(sc);
1263 	if (rc != 0)
1264 		goto done; /* error message displayed already */
1265 
1266 	if (sc->flags & MASTER_PF) {
1267 		rc = partition_resources(sc);
1268 		if (rc != 0)
1269 			goto done; /* error message displayed already */
1270 		t4_intr_clear(sc);
1271 	}
1272 
1273 	rc = get_params__post_init(sc);
1274 	if (rc != 0)
1275 		goto done; /* error message displayed already */
1276 
1277 	rc = set_params__post_init(sc);
1278 	if (rc != 0)
1279 		goto done; /* error message displayed already */
1280 
1281 	rc = t4_map_bar_2(sc);
1282 	if (rc != 0)
1283 		goto done; /* error message displayed already */
1284 
1285 	rc = t4_create_dma_tag(sc);
1286 	if (rc != 0)
1287 		goto done; /* error message displayed already */
1288 
1289 	/*
1290 	 * First pass over all the ports - allocate VIs and initialize some
1291 	 * basic parameters like mac address, port type, etc.
1292 	 */
1293 	for_each_port(sc, i) {
1294 		struct port_info *pi;
1295 
1296 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1297 		sc->port[i] = pi;
1298 
1299 		/* These must be set before t4_port_init */
1300 		pi->adapter = sc;
1301 		pi->port_id = i;
1302 		/*
1303 		 * XXX: vi[0] is special so we can't delay this allocation until
1304 		 * pi->nvi's final value is known.
1305 		 */
1306 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1307 		    M_ZERO | M_WAITOK);
1308 
1309 		/*
1310 		 * Allocate the "main" VI and initialize parameters
1311 		 * like mac addr.
1312 		 */
1313 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1314 		if (rc != 0) {
1315 			device_printf(dev, "unable to initialize port %d: %d\n",
1316 			    i, rc);
1317 			free(pi->vi, M_CXGBE);
1318 			free(pi, M_CXGBE);
1319 			sc->port[i] = NULL;
1320 			goto done;
1321 		}
1322 
1323 		if (is_bt(pi->port_type))
1324 			setbit(&sc->bt_map, pi->tx_chan);
1325 		else
1326 			MPASS(!isset(&sc->bt_map, pi->tx_chan));
1327 
1328 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1329 		    device_get_nameunit(dev), i);
1330 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1331 		sc->chan_map[pi->tx_chan] = i;
1332 
1333 		/*
1334 		 * The MPS counter for FCS errors doesn't work correctly on the
1335 		 * T6 so we use the MAC counter here.  Which MAC is in use
1336 		 * depends on the link settings which will be known when the
1337 		 * link comes up.
1338 		 */
1339 		if (is_t6(sc)) {
1340 			pi->fcs_reg = -1;
1341 		} else if (is_t4(sc)) {
1342 			pi->fcs_reg = PORT_REG(pi->tx_chan,
1343 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1344 		} else {
1345 			pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
1346 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1347 		}
1348 		pi->fcs_base = 0;
1349 
1350 		/* All VIs on this port share this media. */
1351 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1352 		    cxgbe_media_status);
1353 
1354 		PORT_LOCK(pi);
1355 		init_link_config(pi);
1356 		fixup_link_config(pi);
1357 		build_medialist(pi);
1358 		if (fixed_ifmedia(pi))
1359 			pi->flags |= FIXED_IFMEDIA;
1360 		PORT_UNLOCK(pi);
1361 
1362 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1363 		    t4_ifnet_unit(sc, pi));
1364 		if (pi->dev == NULL) {
1365 			device_printf(dev,
1366 			    "failed to add device for port %d.\n", i);
1367 			rc = ENXIO;
1368 			goto done;
1369 		}
1370 		pi->vi[0].dev = pi->dev;
1371 		device_set_softc(pi->dev, pi);
1372 	}
1373 
1374 	/*
1375 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1376 	 */
1377 	nports = sc->params.nports;
1378 	rc = cfg_itype_and_nqueues(sc, &iaq);
1379 	if (rc != 0)
1380 		goto done; /* error message displayed already */
1381 
1382 	num_vis = iaq.num_vis;
1383 	sc->intr_type = iaq.intr_type;
1384 	sc->intr_count = iaq.nirq;
1385 
1386 	s = &sc->sge;
1387 	s->nrxq = nports * iaq.nrxq;
1388 	s->ntxq = nports * iaq.ntxq;
1389 	if (num_vis > 1) {
1390 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1391 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1392 	}
1393 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1394 	s->neq += nports;		/* ctrl queues: 1 per port */
1395 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1396 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1397 	if (is_offload(sc) || is_ethoffload(sc)) {
1398 		s->nofldtxq = nports * iaq.nofldtxq;
1399 		if (num_vis > 1)
1400 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1401 		s->neq += s->nofldtxq;
1402 
1403 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1404 		    M_CXGBE, M_ZERO | M_WAITOK);
1405 	}
1406 #endif
1407 #ifdef TCP_OFFLOAD
1408 	if (is_offload(sc)) {
1409 		s->nofldrxq = nports * iaq.nofldrxq;
1410 		if (num_vis > 1)
1411 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1412 		s->neq += s->nofldrxq;	/* free list */
1413 		s->niq += s->nofldrxq;
1414 
1415 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1416 		    M_CXGBE, M_ZERO | M_WAITOK);
1417 	}
1418 #endif
1419 #ifdef DEV_NETMAP
1420 	s->nnmrxq = 0;
1421 	s->nnmtxq = 0;
1422 	if (t4_native_netmap & NN_MAIN_VI) {
1423 		s->nnmrxq += nports * iaq.nnmrxq;
1424 		s->nnmtxq += nports * iaq.nnmtxq;
1425 	}
1426 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1427 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1428 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1429 	}
1430 	s->neq += s->nnmtxq + s->nnmrxq;
1431 	s->niq += s->nnmrxq;
1432 
1433 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1434 	    M_CXGBE, M_ZERO | M_WAITOK);
1435 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1436 	    M_CXGBE, M_ZERO | M_WAITOK);
1437 #endif
1438 	MPASS(s->niq <= s->iqmap_sz);
1439 	MPASS(s->neq <= s->eqmap_sz);
1440 
1441 	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1442 	    M_ZERO | M_WAITOK);
1443 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1444 	    M_ZERO | M_WAITOK);
1445 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1446 	    M_ZERO | M_WAITOK);
1447 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1448 	    M_ZERO | M_WAITOK);
1449 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1450 	    M_ZERO | M_WAITOK);
1451 
1452 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1453 	    M_ZERO | M_WAITOK);
1454 
1455 	t4_init_l2t(sc, M_WAITOK);
1456 	t4_init_smt(sc, M_WAITOK);
1457 	t4_init_tx_sched(sc);
1458 	t4_init_atid_table(sc);
1459 #ifdef RATELIMIT
1460 	t4_init_etid_table(sc);
1461 #endif
1462 #ifdef INET6
1463 	t4_init_clip_table(sc);
1464 #endif
1465 	if (sc->vres.key.size != 0)
1466 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1467 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1468 
1469 	/*
1470 	 * Second pass over the ports.  This time we know the number of rx and
1471 	 * tx queues that each port should get.
1472 	 */
1473 	rqidx = tqidx = 0;
1474 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1475 	ofld_tqidx = 0;
1476 #endif
1477 #ifdef TCP_OFFLOAD
1478 	ofld_rqidx = 0;
1479 #endif
1480 #ifdef DEV_NETMAP
1481 	nm_rqidx = nm_tqidx = 0;
1482 #endif
1483 	for_each_port(sc, i) {
1484 		struct port_info *pi = sc->port[i];
1485 		struct vi_info *vi;
1486 
1487 		if (pi == NULL)
1488 			continue;
1489 
1490 		pi->nvi = num_vis;
1491 		for_each_vi(pi, j, vi) {
1492 			vi->pi = pi;
1493 			vi->adapter = sc;
1494 			vi->first_intr = -1;
1495 			vi->qsize_rxq = t4_qsize_rxq;
1496 			vi->qsize_txq = t4_qsize_txq;
1497 
1498 			vi->first_rxq = rqidx;
1499 			vi->first_txq = tqidx;
1500 			vi->tmr_idx = t4_tmr_idx;
1501 			vi->pktc_idx = t4_pktc_idx;
1502 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1503 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1504 
1505 			rqidx += vi->nrxq;
1506 			tqidx += vi->ntxq;
1507 
1508 			if (j == 0 && vi->ntxq > 1)
1509 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1510 			else
1511 				vi->rsrv_noflowq = 0;
1512 
1513 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1514 			vi->first_ofld_txq = ofld_tqidx;
1515 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1516 			ofld_tqidx += vi->nofldtxq;
1517 #endif
1518 #ifdef TCP_OFFLOAD
1519 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1520 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1521 			vi->first_ofld_rxq = ofld_rqidx;
1522 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1523 
1524 			ofld_rqidx += vi->nofldrxq;
1525 #endif
1526 #ifdef DEV_NETMAP
1527 			vi->first_nm_rxq = nm_rqidx;
1528 			vi->first_nm_txq = nm_tqidx;
1529 			if (j == 0) {
1530 				vi->nnmrxq = iaq.nnmrxq;
1531 				vi->nnmtxq = iaq.nnmtxq;
1532 			} else {
1533 				vi->nnmrxq = iaq.nnmrxq_vi;
1534 				vi->nnmtxq = iaq.nnmtxq_vi;
1535 			}
1536 			nm_rqidx += vi->nnmrxq;
1537 			nm_tqidx += vi->nnmtxq;
1538 #endif
1539 		}
1540 	}
1541 
1542 	rc = t4_setup_intr_handlers(sc);
1543 	if (rc != 0) {
1544 		device_printf(dev,
1545 		    "failed to setup interrupt handlers: %d\n", rc);
1546 		goto done;
1547 	}
1548 
1549 	rc = bus_generic_probe(dev);
1550 	if (rc != 0) {
1551 		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1552 		goto done;
1553 	}
1554 
1555 	/*
1556 	 * Ensure thread-safe mailbox access (in debug builds).
1557 	 *
1558 	 * So far this was the only thread accessing the mailbox but various
1559 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1560 	 * will access the mailbox from different threads.
1561 	 */
1562 	sc->flags |= CHK_MBOX_ACCESS;
1563 
1564 	rc = bus_generic_attach(dev);
1565 	if (rc != 0) {
1566 		device_printf(dev,
1567 		    "failed to attach all child ports: %d\n", rc);
1568 		goto done;
1569 	}
1570 
1571 	device_printf(dev,
1572 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1573 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1574 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1575 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1576 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1577 
1578 	t4_set_desc(sc);
1579 
1580 	notify_siblings(dev, 0);
1581 
1582 done:
1583 	if (rc != 0 && sc->cdev) {
1584 		/* cdev was created and so cxgbetool works; recover that way. */
1585 		device_printf(dev,
1586 		    "error during attach, adapter is now in recovery mode.\n");
1587 		rc = 0;
1588 	}
1589 
1590 	if (rc != 0)
1591 		t4_detach_common(dev);
1592 	else
1593 		t4_sysctls(sc);
1594 
1595 	return (rc);
1596 }
1597 
1598 static int
1599 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1600 {
1601 	struct adapter *sc;
1602 	struct port_info *pi;
1603 	int i;
1604 
1605 	sc = device_get_softc(bus);
1606 	for_each_port(sc, i) {
1607 		pi = sc->port[i];
1608 		if (pi != NULL && pi->dev == dev) {
1609 			sbuf_printf(sb, "port=%d", pi->port_id);
1610 			break;
1611 		}
1612 	}
1613 	return (0);
1614 }
1615 
1616 static int
1617 t4_ready(device_t dev)
1618 {
1619 	struct adapter *sc;
1620 
1621 	sc = device_get_softc(dev);
1622 	if (sc->flags & FW_OK)
1623 		return (0);
1624 	return (ENXIO);
1625 }
1626 
1627 static int
1628 t4_read_port_device(device_t dev, int port, device_t *child)
1629 {
1630 	struct adapter *sc;
1631 	struct port_info *pi;
1632 
1633 	sc = device_get_softc(dev);
1634 	if (port < 0 || port >= MAX_NPORTS)
1635 		return (EINVAL);
1636 	pi = sc->port[port];
1637 	if (pi == NULL || pi->dev == NULL)
1638 		return (ENXIO);
1639 	*child = pi->dev;
1640 	return (0);
1641 }
1642 
1643 static int
1644 notify_siblings(device_t dev, int detaching)
1645 {
1646 	device_t sibling;
1647 	int error, i;
1648 
1649 	error = 0;
1650 	for (i = 0; i < PCI_FUNCMAX; i++) {
1651 		if (i == pci_get_function(dev))
1652 			continue;
1653 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1654 		    pci_get_slot(dev), i);
1655 		if (sibling == NULL || !device_is_attached(sibling))
1656 			continue;
1657 		if (detaching)
1658 			error = T4_DETACH_CHILD(sibling);
1659 		else
1660 			(void)T4_ATTACH_CHILD(sibling);
1661 		if (error)
1662 			break;
1663 	}
1664 	return (error);
1665 }
1666 
1667 /*
1668  * Idempotent
1669  */
1670 static int
1671 t4_detach(device_t dev)
1672 {
1673 	int rc;
1674 
1675 	rc = notify_siblings(dev, 1);
1676 	if (rc) {
1677 		device_printf(dev,
1678 		    "failed to detach sibling devices: %d\n", rc);
1679 		return (rc);
1680 	}
1681 
1682 	return (t4_detach_common(dev));
1683 }
1684 
1685 int
1686 t4_detach_common(device_t dev)
1687 {
1688 	struct adapter *sc;
1689 	struct port_info *pi;
1690 	int i, rc;
1691 
1692 	sc = device_get_softc(dev);
1693 
1694 #ifdef TCP_OFFLOAD
1695 	rc = t4_deactivate_all_uld(sc);
1696 	if (rc) {
1697 		device_printf(dev,
1698 		    "failed to detach upper layer drivers: %d\n", rc);
1699 		return (rc);
1700 	}
1701 #endif
1702 
1703 	if (sc->cdev) {
1704 		destroy_dev(sc->cdev);
1705 		sc->cdev = NULL;
1706 	}
1707 
1708 	sx_xlock(&t4_list_lock);
1709 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1710 	sx_xunlock(&t4_list_lock);
1711 
1712 	sc->flags &= ~CHK_MBOX_ACCESS;
1713 	if (sc->flags & FULL_INIT_DONE) {
1714 		if (!(sc->flags & IS_VF))
1715 			t4_intr_disable(sc);
1716 	}
1717 
1718 	if (device_is_attached(dev)) {
1719 		rc = bus_generic_detach(dev);
1720 		if (rc) {
1721 			device_printf(dev,
1722 			    "failed to detach child devices: %d\n", rc);
1723 			return (rc);
1724 		}
1725 	}
1726 
1727 	for (i = 0; i < sc->intr_count; i++)
1728 		t4_free_irq(sc, &sc->irq[i]);
1729 
1730 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1731 		t4_free_tx_sched(sc);
1732 
1733 	for (i = 0; i < MAX_NPORTS; i++) {
1734 		pi = sc->port[i];
1735 		if (pi) {
1736 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1737 			if (pi->dev)
1738 				device_delete_child(dev, pi->dev);
1739 
1740 			mtx_destroy(&pi->pi_lock);
1741 			free(pi->vi, M_CXGBE);
1742 			free(pi, M_CXGBE);
1743 		}
1744 	}
1745 
1746 	device_delete_children(dev);
1747 	sysctl_ctx_free(&sc->ctx);
1748 	adapter_full_uninit(sc);
1749 
1750 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1751 		t4_fw_bye(sc, sc->mbox);
1752 
1753 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1754 		pci_release_msi(dev);
1755 
1756 	if (sc->regs_res)
1757 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1758 		    sc->regs_res);
1759 
1760 	if (sc->udbs_res)
1761 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1762 		    sc->udbs_res);
1763 
1764 	if (sc->msix_res)
1765 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1766 		    sc->msix_res);
1767 
1768 	if (sc->l2t)
1769 		t4_free_l2t(sc->l2t);
1770 	if (sc->smt)
1771 		t4_free_smt(sc->smt);
1772 	t4_free_atid_table(sc);
1773 #ifdef RATELIMIT
1774 	t4_free_etid_table(sc);
1775 #endif
1776 	if (sc->key_map)
1777 		vmem_destroy(sc->key_map);
1778 #ifdef INET6
1779 	t4_destroy_clip_table(sc);
1780 #endif
1781 
1782 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1783 	free(sc->sge.ofld_txq, M_CXGBE);
1784 #endif
1785 #ifdef TCP_OFFLOAD
1786 	free(sc->sge.ofld_rxq, M_CXGBE);
1787 #endif
1788 #ifdef DEV_NETMAP
1789 	free(sc->sge.nm_rxq, M_CXGBE);
1790 	free(sc->sge.nm_txq, M_CXGBE);
1791 #endif
1792 	free(sc->irq, M_CXGBE);
1793 	free(sc->sge.rxq, M_CXGBE);
1794 	free(sc->sge.txq, M_CXGBE);
1795 	free(sc->sge.ctrlq, M_CXGBE);
1796 	free(sc->sge.iqmap, M_CXGBE);
1797 	free(sc->sge.eqmap, M_CXGBE);
1798 	free(sc->tids.ftid_tab, M_CXGBE);
1799 	free(sc->tids.hpftid_tab, M_CXGBE);
1800 	free_hftid_hash(&sc->tids);
1801 	free(sc->tids.tid_tab, M_CXGBE);
1802 	free(sc->tt.tls_rx_ports, M_CXGBE);
1803 	t4_destroy_dma_tag(sc);
1804 
1805 	callout_drain(&sc->ktls_tick);
1806 	callout_drain(&sc->sfl_callout);
1807 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1808 		mtx_destroy(&sc->tids.ftid_lock);
1809 		cv_destroy(&sc->tids.ftid_cv);
1810 	}
1811 	if (mtx_initialized(&sc->tids.atid_lock))
1812 		mtx_destroy(&sc->tids.atid_lock);
1813 	if (mtx_initialized(&sc->ifp_lock))
1814 		mtx_destroy(&sc->ifp_lock);
1815 
1816 	if (rw_initialized(&sc->policy_lock)) {
1817 		rw_destroy(&sc->policy_lock);
1818 #ifdef TCP_OFFLOAD
1819 		if (sc->policy != NULL)
1820 			free_offload_policy(sc->policy);
1821 #endif
1822 	}
1823 
1824 	for (i = 0; i < NUM_MEMWIN; i++) {
1825 		struct memwin *mw = &sc->memwin[i];
1826 
1827 		if (rw_initialized(&mw->mw_lock))
1828 			rw_destroy(&mw->mw_lock);
1829 	}
1830 
1831 	mtx_destroy(&sc->sfl_lock);
1832 	mtx_destroy(&sc->reg_lock);
1833 	mtx_destroy(&sc->sc_lock);
1834 
1835 	bzero(sc, sizeof(*sc));
1836 
1837 	return (0);
1838 }
1839 
1840 static inline bool
1841 ok_to_reset(struct adapter *sc)
1842 {
1843 	struct tid_info *t = &sc->tids;
1844 	struct port_info *pi;
1845 	struct vi_info *vi;
1846 	int i, j;
1847 	int caps = IFCAP_TOE | IFCAP_NETMAP | IFCAP_TXRTLMT;
1848 
1849 	if (is_t6(sc))
1850 		caps |= IFCAP_TXTLS;
1851 
1852 	ASSERT_SYNCHRONIZED_OP(sc);
1853 	MPASS(!(sc->flags & IS_VF));
1854 
1855 	for_each_port(sc, i) {
1856 		pi = sc->port[i];
1857 		for_each_vi(pi, j, vi) {
1858 			if (vi->ifp->if_capenable & caps)
1859 				return (false);
1860 		}
1861 	}
1862 
1863 	if (atomic_load_int(&t->tids_in_use) > 0)
1864 		return (false);
1865 	if (atomic_load_int(&t->stids_in_use) > 0)
1866 		return (false);
1867 	if (atomic_load_int(&t->atids_in_use) > 0)
1868 		return (false);
1869 	if (atomic_load_int(&t->ftids_in_use) > 0)
1870 		return (false);
1871 	if (atomic_load_int(&t->hpftids_in_use) > 0)
1872 		return (false);
1873 	if (atomic_load_int(&t->etids_in_use) > 0)
1874 		return (false);
1875 
1876 	return (true);
1877 }
1878 
1879 static inline int
1880 stop_adapter(struct adapter *sc)
1881 {
1882 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_STOPPED)))
1883 		return (1);		/* Already stopped. */
1884 	return (t4_shutdown_adapter(sc));
1885 }
1886 
1887 static int
1888 t4_suspend(device_t dev)
1889 {
1890 	struct adapter *sc = device_get_softc(dev);
1891 	struct port_info *pi;
1892 	struct vi_info *vi;
1893 	struct ifnet *ifp;
1894 	struct sge_rxq *rxq;
1895 	struct sge_txq *txq;
1896 	struct sge_wrq *wrq;
1897 #ifdef TCP_OFFLOAD
1898 	struct sge_ofld_rxq *ofld_rxq;
1899 #endif
1900 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1901 	struct sge_ofld_txq *ofld_txq;
1902 #endif
1903 	int rc, i, j, k;
1904 
1905 	CH_ALERT(sc, "suspend requested\n");
1906 
1907 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4sus");
1908 	if (rc != 0)
1909 		return (ENXIO);
1910 
1911 	/* XXX: Can the kernel call suspend repeatedly without resume? */
1912 	MPASS(!hw_off_limits(sc));
1913 
1914 	if (!ok_to_reset(sc)) {
1915 		/* XXX: should list what resource is preventing suspend. */
1916 		CH_ERR(sc, "not safe to suspend.\n");
1917 		rc = EBUSY;
1918 		goto done;
1919 	}
1920 
1921 	/* No more DMA or interrupts. */
1922 	stop_adapter(sc);
1923 
1924 	/* Quiesce all activity. */
1925 	for_each_port(sc, i) {
1926 		pi = sc->port[i];
1927 		pi->vxlan_tcam_entry = false;
1928 
1929 		PORT_LOCK(pi);
1930 		if (pi->up_vis > 0) {
1931 			/*
1932 			 * t4_shutdown_adapter has already shut down all the
1933 			 * PHYs but it also disables interrupts and DMA so there
1934 			 * won't be a link interrupt.  So we update the state
1935 			 * manually and inform the kernel.
1936 			 */
1937 			pi->link_cfg.link_ok = false;
1938 			t4_os_link_changed(pi);
1939 		}
1940 		PORT_UNLOCK(pi);
1941 
1942 		for_each_vi(pi, j, vi) {
1943 			vi->xact_addr_filt = -1;
1944 			mtx_lock(&vi->tick_mtx);
1945 			vi->flags |= VI_SKIP_STATS;
1946 			mtx_unlock(&vi->tick_mtx);
1947 			if (!(vi->flags & VI_INIT_DONE))
1948 				continue;
1949 
1950 			ifp = vi->ifp;
1951 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1952 				mtx_lock(&vi->tick_mtx);
1953 				callout_stop(&vi->tick);
1954 				mtx_unlock(&vi->tick_mtx);
1955 				callout_drain(&vi->tick);
1956 			}
1957 
1958 			/*
1959 			 * Note that the HW is not available.
1960 			 */
1961 			for_each_txq(vi, k, txq) {
1962 				TXQ_LOCK(txq);
1963 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
1964 				TXQ_UNLOCK(txq);
1965 			}
1966 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1967 			for_each_ofld_txq(vi, k, ofld_txq) {
1968 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
1969 			}
1970 #endif
1971 			for_each_rxq(vi, k, rxq) {
1972 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1973 			}
1974 #if defined(TCP_OFFLOAD)
1975 			for_each_ofld_rxq(vi, k, ofld_rxq) {
1976 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1977 			}
1978 #endif
1979 
1980 			quiesce_vi(vi);
1981 		}
1982 
1983 		if (sc->flags & FULL_INIT_DONE) {
1984 			/* Control queue */
1985 			wrq = &sc->sge.ctrlq[i];
1986 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
1987 			quiesce_wrq(wrq);
1988 		}
1989 	}
1990 	if (sc->flags & FULL_INIT_DONE) {
1991 		/* Firmware event queue */
1992 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
1993 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
1994 	}
1995 
1996 	/* Mark the adapter totally off limits. */
1997 	mtx_lock(&sc->reg_lock);
1998 	atomic_set_int(&sc->error_flags, HW_OFF_LIMITS);
1999 	sc->flags &= ~(FW_OK | MASTER_PF);
2000 	sc->reset_thread = NULL;
2001 	mtx_unlock(&sc->reg_lock);
2002 
2003 	if (t4_clock_gate_on_suspend) {
2004 		t4_set_reg_field(sc, A_PMU_PART_CG_PWRMODE, F_MA_PART_CGEN |
2005 		    F_LE_PART_CGEN | F_EDC1_PART_CGEN | F_EDC0_PART_CGEN |
2006 		    F_TP_PART_CGEN | F_PDP_PART_CGEN | F_SGE_PART_CGEN, 0);
2007 	}
2008 
2009 	CH_ALERT(sc, "suspend completed.\n");
2010 done:
2011 	end_synchronized_op(sc, 0);
2012 	return (rc);
2013 }
2014 
2015 struct adapter_pre_reset_state {
2016 	u_int flags;
2017 	uint16_t nbmcaps;
2018 	uint16_t linkcaps;
2019 	uint16_t switchcaps;
2020 	uint16_t niccaps;
2021 	uint16_t toecaps;
2022 	uint16_t rdmacaps;
2023 	uint16_t cryptocaps;
2024 	uint16_t iscsicaps;
2025 	uint16_t fcoecaps;
2026 
2027 	u_int cfcsum;
2028 	char cfg_file[32];
2029 
2030 	struct adapter_params params;
2031 	struct t4_virt_res vres;
2032 	struct tid_info tids;
2033 	struct sge sge;
2034 
2035 	int rawf_base;
2036 	int nrawf;
2037 
2038 };
2039 
2040 static void
2041 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2042 {
2043 
2044 	ASSERT_SYNCHRONIZED_OP(sc);
2045 
2046 	o->flags = sc->flags;
2047 
2048 	o->nbmcaps =  sc->nbmcaps;
2049 	o->linkcaps = sc->linkcaps;
2050 	o->switchcaps = sc->switchcaps;
2051 	o->niccaps = sc->niccaps;
2052 	o->toecaps = sc->toecaps;
2053 	o->rdmacaps = sc->rdmacaps;
2054 	o->cryptocaps = sc->cryptocaps;
2055 	o->iscsicaps = sc->iscsicaps;
2056 	o->fcoecaps = sc->fcoecaps;
2057 
2058 	o->cfcsum = sc->cfcsum;
2059 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2060 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2061 
2062 	o->params = sc->params;
2063 	o->vres = sc->vres;
2064 	o->tids = sc->tids;
2065 	o->sge = sc->sge;
2066 
2067 	o->rawf_base = sc->rawf_base;
2068 	o->nrawf = sc->nrawf;
2069 }
2070 
2071 static int
2072 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2073 {
2074 	int rc = 0;
2075 
2076 	ASSERT_SYNCHRONIZED_OP(sc);
2077 
2078 	/* Capabilities */
2079 #define COMPARE_CAPS(c) do { \
2080 	if (o->c##caps != sc->c##caps) { \
2081 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2082 		    sc->c##caps); \
2083 		rc = EINVAL; \
2084 	} \
2085 } while (0)
2086 	COMPARE_CAPS(nbm);
2087 	COMPARE_CAPS(link);
2088 	COMPARE_CAPS(switch);
2089 	COMPARE_CAPS(nic);
2090 	COMPARE_CAPS(toe);
2091 	COMPARE_CAPS(rdma);
2092 	COMPARE_CAPS(crypto);
2093 	COMPARE_CAPS(iscsi);
2094 	COMPARE_CAPS(fcoe);
2095 #undef COMPARE_CAPS
2096 
2097 	/* Firmware config file */
2098 	if (o->cfcsum != sc->cfcsum) {
2099 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2100 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2101 		rc = EINVAL;
2102 	}
2103 
2104 #define COMPARE_PARAM(p, name) do { \
2105 	if (o->p != sc->p) { \
2106 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2107 		rc = EINVAL; \
2108 	} \
2109 } while (0)
2110 	COMPARE_PARAM(sge.iq_start, iq_start);
2111 	COMPARE_PARAM(sge.eq_start, eq_start);
2112 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2113 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2114 	COMPARE_PARAM(tids.nftids, nftids);
2115 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2116 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2117 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2118 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2119 	COMPARE_PARAM(tids.tid_base, tid_base);
2120 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2121 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2122 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2123 	COMPARE_PARAM(rawf_base, rawf_base);
2124 	COMPARE_PARAM(nrawf, nrawf);
2125 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2126 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2127 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2128 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2129 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2130 	COMPARE_PARAM(tids.ntids, ntids);
2131 	COMPARE_PARAM(tids.etid_base, etid_base);
2132 	COMPARE_PARAM(tids.etid_end, etid_end);
2133 	COMPARE_PARAM(tids.netids, netids);
2134 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2135 	COMPARE_PARAM(params.ethoffload, ethoffload);
2136 	COMPARE_PARAM(tids.natids, natids);
2137 	COMPARE_PARAM(tids.stid_base, stid_base);
2138 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2139 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2140 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2141 	COMPARE_PARAM(vres.stag.start, stag_start);
2142 	COMPARE_PARAM(vres.stag.size, stag_size);
2143 	COMPARE_PARAM(vres.rq.start, rq_start);
2144 	COMPARE_PARAM(vres.rq.size, rq_size);
2145 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2146 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2147 	COMPARE_PARAM(vres.qp.start, qp_start);
2148 	COMPARE_PARAM(vres.qp.size, qp_size);
2149 	COMPARE_PARAM(vres.cq.start, cq_start);
2150 	COMPARE_PARAM(vres.cq.size, cq_size);
2151 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2152 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2153 	COMPARE_PARAM(vres.srq.start, srq_start);
2154 	COMPARE_PARAM(vres.srq.size, srq_size);
2155 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2156 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2157 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2158 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2159 	COMPARE_PARAM(vres.key.start, key_start);
2160 	COMPARE_PARAM(vres.key.size, key_size);
2161 #undef COMPARE_PARAM
2162 
2163 	return (rc);
2164 }
2165 
2166 static int
2167 t4_resume(device_t dev)
2168 {
2169 	struct adapter *sc = device_get_softc(dev);
2170 	struct adapter_pre_reset_state *old_state = NULL;
2171 	struct port_info *pi;
2172 	struct vi_info *vi;
2173 	struct ifnet *ifp;
2174 	struct sge_txq *txq;
2175 	int rc, i, j, k;
2176 
2177 	CH_ALERT(sc, "resume requested.\n");
2178 
2179 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4res");
2180 	if (rc != 0)
2181 		return (ENXIO);
2182 	MPASS(hw_off_limits(sc));
2183 	MPASS((sc->flags & FW_OK) == 0);
2184 	MPASS((sc->flags & MASTER_PF) == 0);
2185 	MPASS(sc->reset_thread == NULL);
2186 	sc->reset_thread = curthread;
2187 
2188 	/* Register access is expected to work by the time we're here. */
2189 	if (t4_read_reg(sc, A_PL_WHOAMI) == 0xffffffff) {
2190 		CH_ERR(sc, "%s: can't read device registers\n", __func__);
2191 		rc = ENXIO;
2192 		goto done;
2193 	}
2194 
2195 	/* Note that HW_OFF_LIMITS is cleared a bit later. */
2196 	atomic_clear_int(&sc->error_flags, ADAP_FATAL_ERR | ADAP_STOPPED);
2197 
2198 	/* Restore memory window. */
2199 	setup_memwin(sc);
2200 
2201 	/* Go no further if recovery mode has been requested. */
2202 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2203 		CH_ALERT(sc, "recovery mode on resume.\n");
2204 		rc = 0;
2205 		mtx_lock(&sc->reg_lock);
2206 		atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2207 		mtx_unlock(&sc->reg_lock);
2208 		goto done;
2209 	}
2210 
2211 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2212 	save_caps_and_params(sc, old_state);
2213 
2214 	/* Reestablish contact with firmware and become the primary PF. */
2215 	rc = contact_firmware(sc);
2216 	if (rc != 0)
2217 		goto done; /* error message displayed already */
2218 	MPASS(sc->flags & FW_OK);
2219 
2220 	if (sc->flags & MASTER_PF) {
2221 		rc = partition_resources(sc);
2222 		if (rc != 0)
2223 			goto done; /* error message displayed already */
2224 		t4_intr_clear(sc);
2225 	}
2226 
2227 	rc = get_params__post_init(sc);
2228 	if (rc != 0)
2229 		goto done; /* error message displayed already */
2230 
2231 	rc = set_params__post_init(sc);
2232 	if (rc != 0)
2233 		goto done; /* error message displayed already */
2234 
2235 	rc = compare_caps_and_params(sc, old_state);
2236 	if (rc != 0)
2237 		goto done; /* error message displayed already */
2238 
2239 	for_each_port(sc, i) {
2240 		pi = sc->port[i];
2241 		MPASS(pi != NULL);
2242 		MPASS(pi->vi != NULL);
2243 		MPASS(pi->vi[0].dev == pi->dev);
2244 
2245 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2246 		if (rc != 0) {
2247 			CH_ERR(sc,
2248 			    "failed to re-initialize port %d: %d\n", i, rc);
2249 			goto done;
2250 		}
2251 		MPASS(sc->chan_map[pi->tx_chan] == i);
2252 
2253 		PORT_LOCK(pi);
2254 		fixup_link_config(pi);
2255 		build_medialist(pi);
2256 		PORT_UNLOCK(pi);
2257 		for_each_vi(pi, j, vi) {
2258 			if (IS_MAIN_VI(vi))
2259 				continue;
2260 			rc = alloc_extra_vi(sc, pi, vi);
2261 			if (rc != 0) {
2262 				CH_ERR(vi,
2263 				    "failed to re-allocate extra VI: %d\n", rc);
2264 				goto done;
2265 			}
2266 		}
2267 	}
2268 
2269 	/*
2270 	 * Interrupts and queues are about to be enabled and other threads will
2271 	 * want to access the hardware too.  It is safe to do so.  Note that
2272 	 * this thread is still in the middle of a synchronized_op.
2273 	 */
2274 	mtx_lock(&sc->reg_lock);
2275 	atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2276 	mtx_unlock(&sc->reg_lock);
2277 
2278 	if (sc->flags & FULL_INIT_DONE) {
2279 		rc = adapter_full_init(sc);
2280 		if (rc != 0) {
2281 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2282 			goto done;
2283 		}
2284 
2285 		if (sc->vxlan_refcount > 0)
2286 			enable_vxlan_rx(sc);
2287 
2288 		for_each_port(sc, i) {
2289 			pi = sc->port[i];
2290 			for_each_vi(pi, j, vi) {
2291 				mtx_lock(&vi->tick_mtx);
2292 				vi->flags &= ~VI_SKIP_STATS;
2293 				mtx_unlock(&vi->tick_mtx);
2294 				if (!(vi->flags & VI_INIT_DONE))
2295 					continue;
2296 				rc = vi_full_init(vi);
2297 				if (rc != 0) {
2298 					CH_ERR(vi, "failed to re-initialize "
2299 					    "interface: %d\n", rc);
2300 					goto done;
2301 				}
2302 
2303 				ifp = vi->ifp;
2304 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2305 					continue;
2306 				/*
2307 				 * Note that we do not setup multicast addresses
2308 				 * in the first pass.  This ensures that the
2309 				 * unicast DMACs for all VIs on all ports get an
2310 				 * MPS TCAM entry.
2311 				 */
2312 				rc = update_mac_settings(ifp, XGMAC_ALL &
2313 				    ~XGMAC_MCADDRS);
2314 				if (rc != 0) {
2315 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2316 					goto done;
2317 				}
2318 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2319 				    true);
2320 				if (rc != 0) {
2321 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2322 					goto done;
2323 				}
2324 				for_each_txq(vi, k, txq) {
2325 					TXQ_LOCK(txq);
2326 					txq->eq.flags |= EQ_ENABLED;
2327 					TXQ_UNLOCK(txq);
2328 				}
2329 				mtx_lock(&vi->tick_mtx);
2330 				callout_schedule(&vi->tick, hz);
2331 				mtx_unlock(&vi->tick_mtx);
2332 			}
2333 			PORT_LOCK(pi);
2334 			if (pi->up_vis > 0) {
2335 				t4_update_port_info(pi);
2336 				fixup_link_config(pi);
2337 				build_medialist(pi);
2338 				apply_link_config(pi);
2339 				if (pi->link_cfg.link_ok)
2340 					t4_os_link_changed(pi);
2341 			}
2342 			PORT_UNLOCK(pi);
2343 		}
2344 
2345 		/* Now reprogram the L2 multicast addresses. */
2346 		for_each_port(sc, i) {
2347 			pi = sc->port[i];
2348 			for_each_vi(pi, j, vi) {
2349 				if (!(vi->flags & VI_INIT_DONE))
2350 					continue;
2351 				ifp = vi->ifp;
2352 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2353 					continue;
2354 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2355 				if (rc != 0) {
2356 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2357 					rc = 0;	/* carry on */
2358 				}
2359 			}
2360 		}
2361 	}
2362 done:
2363 	if (rc == 0) {
2364 		sc->incarnation++;
2365 		CH_ALERT(sc, "resume completed.\n");
2366 	}
2367 	end_synchronized_op(sc, 0);
2368 	free(old_state, M_CXGBE);
2369 	return (rc);
2370 }
2371 
2372 static int
2373 t4_reset_prepare(device_t dev, device_t child)
2374 {
2375 	struct adapter *sc = device_get_softc(dev);
2376 
2377 	CH_ALERT(sc, "reset_prepare.\n");
2378 	return (0);
2379 }
2380 
2381 static int
2382 t4_reset_post(device_t dev, device_t child)
2383 {
2384 	struct adapter *sc = device_get_softc(dev);
2385 
2386 	CH_ALERT(sc, "reset_post.\n");
2387 	return (0);
2388 }
2389 
2390 static int
2391 reset_adapter(struct adapter *sc)
2392 {
2393 	int rc, oldinc, error_flags;
2394 
2395 	CH_ALERT(sc, "reset requested.\n");
2396 
2397 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst1");
2398 	if (rc != 0)
2399 		return (EBUSY);
2400 
2401 	if (hw_off_limits(sc)) {
2402 		CH_ERR(sc, "adapter is suspended, use resume (not reset).\n");
2403 		rc = ENXIO;
2404 		goto done;
2405 	}
2406 
2407 	if (!ok_to_reset(sc)) {
2408 		/* XXX: should list what resource is preventing reset. */
2409 		CH_ERR(sc, "not safe to reset.\n");
2410 		rc = EBUSY;
2411 		goto done;
2412 	}
2413 
2414 done:
2415 	oldinc = sc->incarnation;
2416 	end_synchronized_op(sc, 0);
2417 	if (rc != 0)
2418 		return (rc);	/* Error logged already. */
2419 
2420 	atomic_add_int(&sc->num_resets, 1);
2421 	mtx_lock(&Giant);
2422 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2423 	mtx_unlock(&Giant);
2424 	if (rc != 0)
2425 		CH_ERR(sc, "bus_reset_child failed: %d.\n", rc);
2426 	else {
2427 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst2");
2428 		if (rc != 0)
2429 			return (EBUSY);
2430 		error_flags = atomic_load_int(&sc->error_flags);
2431 		if (sc->incarnation > oldinc && error_flags == 0) {
2432 			CH_ALERT(sc, "bus_reset_child succeeded.\n");
2433 		} else {
2434 			CH_ERR(sc, "adapter did not reset properly, flags "
2435 			    "0x%08x, error_flags 0x%08x.\n", sc->flags,
2436 			    error_flags);
2437 			rc = ENXIO;
2438 		}
2439 		end_synchronized_op(sc, 0);
2440 	}
2441 
2442 	return (rc);
2443 }
2444 
2445 static void
2446 reset_adapter_task(void *arg, int pending)
2447 {
2448 	/* XXX: t4_async_event here? */
2449 	reset_adapter(arg);
2450 }
2451 
2452 static int
2453 cxgbe_probe(device_t dev)
2454 {
2455 	char buf[128];
2456 	struct port_info *pi = device_get_softc(dev);
2457 
2458 	snprintf(buf, sizeof(buf), "port %d", pi->port_id);
2459 	device_set_desc_copy(dev, buf);
2460 
2461 	return (BUS_PROBE_DEFAULT);
2462 }
2463 
2464 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2465     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2466     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2467     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2468 #define T4_CAP_ENABLE (T4_CAP)
2469 
2470 static int
2471 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2472 {
2473 	struct ifnet *ifp;
2474 	struct sbuf *sb;
2475 	struct sysctl_ctx_list *ctx = &vi->ctx;
2476 	struct sysctl_oid_list *children;
2477 	struct pfil_head_args pa;
2478 	struct adapter *sc = vi->adapter;
2479 
2480 	sysctl_ctx_init(ctx);
2481 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2482 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2483 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2484 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2485 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2486 #ifdef DEV_NETMAP
2487 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2488 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2489 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2490 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2491 #endif
2492 #ifdef TCP_OFFLOAD
2493 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2494 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2495 #endif
2496 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2497 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2498 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2499 #endif
2500 
2501 	vi->xact_addr_filt = -1;
2502 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2503 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2504 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2505 		vi->flags |= TX_USES_VM_WR;
2506 
2507 	/* Allocate an ifnet and set it up */
2508 	ifp = if_alloc_dev(IFT_ETHER, dev);
2509 	if (ifp == NULL) {
2510 		device_printf(dev, "Cannot allocate ifnet\n");
2511 		return (ENOMEM);
2512 	}
2513 	vi->ifp = ifp;
2514 	ifp->if_softc = vi;
2515 
2516 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2517 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
2518 
2519 	ifp->if_init = cxgbe_init;
2520 	ifp->if_ioctl = cxgbe_ioctl;
2521 	ifp->if_transmit = cxgbe_transmit;
2522 	ifp->if_qflush = cxgbe_qflush;
2523 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2524 		ifp->if_get_counter = vi_get_counter;
2525 	else
2526 		ifp->if_get_counter = cxgbe_get_counter;
2527 #if defined(KERN_TLS) || defined(RATELIMIT)
2528 	ifp->if_snd_tag_alloc = cxgbe_snd_tag_alloc;
2529 #endif
2530 #ifdef RATELIMIT
2531 	ifp->if_ratelimit_query = cxgbe_ratelimit_query;
2532 #endif
2533 
2534 	ifp->if_capabilities = T4_CAP;
2535 	ifp->if_capenable = T4_CAP_ENABLE;
2536 	ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2537 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6;
2538 	if (chip_id(sc) >= CHELSIO_T6) {
2539 		ifp->if_capabilities |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2540 		ifp->if_capenable |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2541 		ifp->if_hwassist |= CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2542 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2543 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN;
2544 	}
2545 
2546 #ifdef TCP_OFFLOAD
2547 	if (vi->nofldrxq != 0)
2548 		ifp->if_capabilities |= IFCAP_TOE;
2549 #endif
2550 #ifdef RATELIMIT
2551 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2552 		ifp->if_capabilities |= IFCAP_TXRTLMT;
2553 		ifp->if_capenable |= IFCAP_TXRTLMT;
2554 	}
2555 #endif
2556 
2557 	ifp->if_hw_tsomax = IP_MAXPACKET;
2558 	if (vi->flags & TX_USES_VM_WR)
2559 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
2560 	else
2561 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
2562 #ifdef RATELIMIT
2563 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2564 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_EO_TSO;
2565 #endif
2566 	ifp->if_hw_tsomaxsegsize = 65536;
2567 #ifdef KERN_TLS
2568 	if (is_ktls(sc)) {
2569 		ifp->if_capabilities |= IFCAP_TXTLS;
2570 		if (sc->flags & KERN_TLS_ON || !is_t6(sc))
2571 			ifp->if_capenable |= IFCAP_TXTLS;
2572 	}
2573 #endif
2574 
2575 	ether_ifattach(ifp, vi->hw_addr);
2576 #ifdef DEV_NETMAP
2577 	if (vi->nnmrxq != 0)
2578 		cxgbe_nm_attach(vi);
2579 #endif
2580 	sb = sbuf_new_auto();
2581 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2582 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2583 	switch (ifp->if_capabilities & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2584 	case IFCAP_TOE:
2585 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2586 		break;
2587 	case IFCAP_TOE | IFCAP_TXRTLMT:
2588 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2589 		break;
2590 	case IFCAP_TXRTLMT:
2591 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2592 		break;
2593 	}
2594 #endif
2595 #ifdef TCP_OFFLOAD
2596 	if (ifp->if_capabilities & IFCAP_TOE)
2597 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2598 #endif
2599 #ifdef DEV_NETMAP
2600 	if (ifp->if_capabilities & IFCAP_NETMAP)
2601 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2602 		    vi->nnmtxq, vi->nnmrxq);
2603 #endif
2604 	sbuf_finish(sb);
2605 	device_printf(dev, "%s\n", sbuf_data(sb));
2606 	sbuf_delete(sb);
2607 
2608 	vi_sysctls(vi);
2609 
2610 	pa.pa_version = PFIL_VERSION;
2611 	pa.pa_flags = PFIL_IN;
2612 	pa.pa_type = PFIL_TYPE_ETHERNET;
2613 	pa.pa_headname = ifp->if_xname;
2614 	vi->pfil = pfil_head_register(&pa);
2615 
2616 	return (0);
2617 }
2618 
2619 static int
2620 cxgbe_attach(device_t dev)
2621 {
2622 	struct port_info *pi = device_get_softc(dev);
2623 	struct adapter *sc = pi->adapter;
2624 	struct vi_info *vi;
2625 	int i, rc;
2626 
2627 	sysctl_ctx_init(&pi->ctx);
2628 
2629 	rc = cxgbe_vi_attach(dev, &pi->vi[0]);
2630 	if (rc)
2631 		return (rc);
2632 
2633 	for_each_vi(pi, i, vi) {
2634 		if (i == 0)
2635 			continue;
2636 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
2637 		if (vi->dev == NULL) {
2638 			device_printf(dev, "failed to add VI %d\n", i);
2639 			continue;
2640 		}
2641 		device_set_softc(vi->dev, vi);
2642 	}
2643 
2644 	cxgbe_sysctls(pi);
2645 
2646 	bus_generic_attach(dev);
2647 
2648 	return (0);
2649 }
2650 
2651 static void
2652 cxgbe_vi_detach(struct vi_info *vi)
2653 {
2654 	struct ifnet *ifp = vi->ifp;
2655 
2656 	if (vi->pfil != NULL) {
2657 		pfil_head_unregister(vi->pfil);
2658 		vi->pfil = NULL;
2659 	}
2660 
2661 	ether_ifdetach(ifp);
2662 
2663 	/* Let detach proceed even if these fail. */
2664 #ifdef DEV_NETMAP
2665 	if (ifp->if_capabilities & IFCAP_NETMAP)
2666 		cxgbe_nm_detach(vi);
2667 #endif
2668 	cxgbe_uninit_synchronized(vi);
2669 	callout_drain(&vi->tick);
2670 	sysctl_ctx_free(&vi->ctx);
2671 	vi_full_uninit(vi);
2672 
2673 	if_free(vi->ifp);
2674 	vi->ifp = NULL;
2675 }
2676 
2677 static int
2678 cxgbe_detach(device_t dev)
2679 {
2680 	struct port_info *pi = device_get_softc(dev);
2681 	struct adapter *sc = pi->adapter;
2682 	int rc;
2683 
2684 	/* Detach the extra VIs first. */
2685 	rc = bus_generic_detach(dev);
2686 	if (rc)
2687 		return (rc);
2688 	device_delete_children(dev);
2689 
2690 	sysctl_ctx_free(&pi->ctx);
2691 	doom_vi(sc, &pi->vi[0]);
2692 
2693 	if (pi->flags & HAS_TRACEQ) {
2694 		sc->traceq = -1;	/* cloner should not create ifnet */
2695 		t4_tracer_port_detach(sc);
2696 	}
2697 
2698 	cxgbe_vi_detach(&pi->vi[0]);
2699 	ifmedia_removeall(&pi->media);
2700 
2701 	end_synchronized_op(sc, 0);
2702 
2703 	return (0);
2704 }
2705 
2706 static void
2707 cxgbe_init(void *arg)
2708 {
2709 	struct vi_info *vi = arg;
2710 	struct adapter *sc = vi->adapter;
2711 
2712 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2713 		return;
2714 	cxgbe_init_synchronized(vi);
2715 	end_synchronized_op(sc, 0);
2716 }
2717 
2718 static int
2719 cxgbe_ioctl(struct ifnet *ifp, unsigned long cmd, caddr_t data)
2720 {
2721 	int rc = 0, mtu, flags;
2722 	struct vi_info *vi = ifp->if_softc;
2723 	struct port_info *pi = vi->pi;
2724 	struct adapter *sc = pi->adapter;
2725 	struct ifreq *ifr = (struct ifreq *)data;
2726 	uint32_t mask;
2727 
2728 	switch (cmd) {
2729 	case SIOCSIFMTU:
2730 		mtu = ifr->ifr_mtu;
2731 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2732 			return (EINVAL);
2733 
2734 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2735 		if (rc)
2736 			return (rc);
2737 		ifp->if_mtu = mtu;
2738 		if (vi->flags & VI_INIT_DONE) {
2739 			t4_update_fl_bufsize(ifp);
2740 			if (!hw_off_limits(sc) &&
2741 			    ifp->if_drv_flags & IFF_DRV_RUNNING)
2742 				rc = update_mac_settings(ifp, XGMAC_MTU);
2743 		}
2744 		end_synchronized_op(sc, 0);
2745 		break;
2746 
2747 	case SIOCSIFFLAGS:
2748 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2749 		if (rc)
2750 			return (rc);
2751 
2752 		if (hw_off_limits(sc)) {
2753 			rc = ENXIO;
2754 			goto fail;
2755 		}
2756 
2757 		if (ifp->if_flags & IFF_UP) {
2758 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2759 				flags = vi->if_flags;
2760 				if ((ifp->if_flags ^ flags) &
2761 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2762 					rc = update_mac_settings(ifp,
2763 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2764 				}
2765 			} else {
2766 				rc = cxgbe_init_synchronized(vi);
2767 			}
2768 			vi->if_flags = ifp->if_flags;
2769 		} else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2770 			rc = cxgbe_uninit_synchronized(vi);
2771 		}
2772 		end_synchronized_op(sc, 0);
2773 		break;
2774 
2775 	case SIOCADDMULTI:
2776 	case SIOCDELMULTI:
2777 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2778 		if (rc)
2779 			return (rc);
2780 		if (!hw_off_limits(sc) && ifp->if_drv_flags & IFF_DRV_RUNNING)
2781 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2782 		end_synchronized_op(sc, 0);
2783 		break;
2784 
2785 	case SIOCSIFCAP:
2786 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2787 		if (rc)
2788 			return (rc);
2789 
2790 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
2791 		if (mask & IFCAP_TXCSUM) {
2792 			ifp->if_capenable ^= IFCAP_TXCSUM;
2793 			ifp->if_hwassist ^= (CSUM_TCP | CSUM_UDP | CSUM_IP);
2794 
2795 			if (IFCAP_TSO4 & ifp->if_capenable &&
2796 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2797 				mask &= ~IFCAP_TSO4;
2798 				ifp->if_capenable &= ~IFCAP_TSO4;
2799 				if_printf(ifp,
2800 				    "tso4 disabled due to -txcsum.\n");
2801 			}
2802 		}
2803 		if (mask & IFCAP_TXCSUM_IPV6) {
2804 			ifp->if_capenable ^= IFCAP_TXCSUM_IPV6;
2805 			ifp->if_hwassist ^= (CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2806 
2807 			if (IFCAP_TSO6 & ifp->if_capenable &&
2808 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2809 				mask &= ~IFCAP_TSO6;
2810 				ifp->if_capenable &= ~IFCAP_TSO6;
2811 				if_printf(ifp,
2812 				    "tso6 disabled due to -txcsum6.\n");
2813 			}
2814 		}
2815 		if (mask & IFCAP_RXCSUM)
2816 			ifp->if_capenable ^= IFCAP_RXCSUM;
2817 		if (mask & IFCAP_RXCSUM_IPV6)
2818 			ifp->if_capenable ^= IFCAP_RXCSUM_IPV6;
2819 
2820 		/*
2821 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2822 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2823 		 * sending a TSO request our way, so it's sufficient to toggle
2824 		 * IFCAP_TSOx only.
2825 		 */
2826 		if (mask & IFCAP_TSO4) {
2827 			if (!(IFCAP_TSO4 & ifp->if_capenable) &&
2828 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2829 				if_printf(ifp, "enable txcsum first.\n");
2830 				rc = EAGAIN;
2831 				goto fail;
2832 			}
2833 			ifp->if_capenable ^= IFCAP_TSO4;
2834 		}
2835 		if (mask & IFCAP_TSO6) {
2836 			if (!(IFCAP_TSO6 & ifp->if_capenable) &&
2837 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2838 				if_printf(ifp, "enable txcsum6 first.\n");
2839 				rc = EAGAIN;
2840 				goto fail;
2841 			}
2842 			ifp->if_capenable ^= IFCAP_TSO6;
2843 		}
2844 		if (mask & IFCAP_LRO) {
2845 #if defined(INET) || defined(INET6)
2846 			int i;
2847 			struct sge_rxq *rxq;
2848 
2849 			ifp->if_capenable ^= IFCAP_LRO;
2850 			for_each_rxq(vi, i, rxq) {
2851 				if (ifp->if_capenable & IFCAP_LRO)
2852 					rxq->iq.flags |= IQ_LRO_ENABLED;
2853 				else
2854 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2855 			}
2856 #endif
2857 		}
2858 #ifdef TCP_OFFLOAD
2859 		if (mask & IFCAP_TOE) {
2860 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TOE;
2861 
2862 			rc = toe_capability(vi, enable);
2863 			if (rc != 0)
2864 				goto fail;
2865 
2866 			ifp->if_capenable ^= mask;
2867 		}
2868 #endif
2869 		if (mask & IFCAP_VLAN_HWTAGGING) {
2870 			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
2871 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2872 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2873 		}
2874 		if (mask & IFCAP_VLAN_MTU) {
2875 			ifp->if_capenable ^= IFCAP_VLAN_MTU;
2876 
2877 			/* Need to find out how to disable auto-mtu-inflation */
2878 		}
2879 		if (mask & IFCAP_VLAN_HWTSO)
2880 			ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
2881 		if (mask & IFCAP_VLAN_HWCSUM)
2882 			ifp->if_capenable ^= IFCAP_VLAN_HWCSUM;
2883 #ifdef RATELIMIT
2884 		if (mask & IFCAP_TXRTLMT)
2885 			ifp->if_capenable ^= IFCAP_TXRTLMT;
2886 #endif
2887 		if (mask & IFCAP_HWRXTSTMP) {
2888 			int i;
2889 			struct sge_rxq *rxq;
2890 
2891 			ifp->if_capenable ^= IFCAP_HWRXTSTMP;
2892 			for_each_rxq(vi, i, rxq) {
2893 				if (ifp->if_capenable & IFCAP_HWRXTSTMP)
2894 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2895 				else
2896 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2897 			}
2898 		}
2899 		if (mask & IFCAP_MEXTPG)
2900 			ifp->if_capenable ^= IFCAP_MEXTPG;
2901 
2902 #ifdef KERN_TLS
2903 		if (mask & IFCAP_TXTLS) {
2904 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TXTLS;
2905 
2906 			rc = ktls_capability(sc, enable);
2907 			if (rc != 0)
2908 				goto fail;
2909 
2910 			ifp->if_capenable ^= (mask & IFCAP_TXTLS);
2911 		}
2912 #endif
2913 		if (mask & IFCAP_VXLAN_HWCSUM) {
2914 			ifp->if_capenable ^= IFCAP_VXLAN_HWCSUM;
2915 			ifp->if_hwassist ^= CSUM_INNER_IP6_UDP |
2916 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
2917 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP;
2918 		}
2919 		if (mask & IFCAP_VXLAN_HWTSO) {
2920 			ifp->if_capenable ^= IFCAP_VXLAN_HWTSO;
2921 			ifp->if_hwassist ^= CSUM_INNER_IP6_TSO |
2922 			    CSUM_INNER_IP_TSO;
2923 		}
2924 
2925 #ifdef VLAN_CAPABILITIES
2926 		VLAN_CAPABILITIES(ifp);
2927 #endif
2928 fail:
2929 		end_synchronized_op(sc, 0);
2930 		break;
2931 
2932 	case SIOCSIFMEDIA:
2933 	case SIOCGIFMEDIA:
2934 	case SIOCGIFXMEDIA:
2935 		rc = ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
2936 		break;
2937 
2938 	case SIOCGI2C: {
2939 		struct ifi2creq i2c;
2940 
2941 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
2942 		if (rc != 0)
2943 			break;
2944 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
2945 			rc = EPERM;
2946 			break;
2947 		}
2948 		if (i2c.len > sizeof(i2c.data)) {
2949 			rc = EINVAL;
2950 			break;
2951 		}
2952 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
2953 		if (rc)
2954 			return (rc);
2955 		if (hw_off_limits(sc))
2956 			rc = ENXIO;
2957 		else
2958 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
2959 			    i2c.offset, i2c.len, &i2c.data[0]);
2960 		end_synchronized_op(sc, 0);
2961 		if (rc == 0)
2962 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
2963 		break;
2964 	}
2965 
2966 	default:
2967 		rc = ether_ioctl(ifp, cmd, data);
2968 	}
2969 
2970 	return (rc);
2971 }
2972 
2973 static int
2974 cxgbe_transmit(struct ifnet *ifp, struct mbuf *m)
2975 {
2976 	struct vi_info *vi = ifp->if_softc;
2977 	struct port_info *pi = vi->pi;
2978 	struct adapter *sc;
2979 	struct sge_txq *txq;
2980 	void *items[1];
2981 	int rc;
2982 
2983 	M_ASSERTPKTHDR(m);
2984 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
2985 #if defined(KERN_TLS) || defined(RATELIMIT)
2986 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
2987 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
2988 #endif
2989 
2990 	if (__predict_false(pi->link_cfg.link_ok == false)) {
2991 		m_freem(m);
2992 		return (ENETDOWN);
2993 	}
2994 
2995 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
2996 	if (__predict_false(rc != 0)) {
2997 		MPASS(m == NULL);			/* was freed already */
2998 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
2999 		return (rc);
3000 	}
3001 #ifdef RATELIMIT
3002 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG) {
3003 		if (m->m_pkthdr.snd_tag->sw->type == IF_SND_TAG_TYPE_RATE_LIMIT)
3004 			return (ethofld_transmit(ifp, m));
3005 	}
3006 #endif
3007 
3008 	/* Select a txq. */
3009 	sc = vi->adapter;
3010 	txq = &sc->sge.txq[vi->first_txq];
3011 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
3012 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
3013 		    vi->rsrv_noflowq);
3014 
3015 	items[0] = m;
3016 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
3017 	if (__predict_false(rc != 0))
3018 		m_freem(m);
3019 
3020 	return (rc);
3021 }
3022 
3023 static void
3024 cxgbe_qflush(struct ifnet *ifp)
3025 {
3026 	struct vi_info *vi = ifp->if_softc;
3027 	struct sge_txq *txq;
3028 	int i;
3029 
3030 	/* queues do not exist if !VI_INIT_DONE. */
3031 	if (vi->flags & VI_INIT_DONE) {
3032 		for_each_txq(vi, i, txq) {
3033 			TXQ_LOCK(txq);
3034 			txq->eq.flags |= EQ_QFLUSH;
3035 			TXQ_UNLOCK(txq);
3036 			while (!mp_ring_is_idle(txq->r)) {
3037 				mp_ring_check_drainage(txq->r, 4096);
3038 				pause("qflush", 1);
3039 			}
3040 			TXQ_LOCK(txq);
3041 			txq->eq.flags &= ~EQ_QFLUSH;
3042 			TXQ_UNLOCK(txq);
3043 		}
3044 	}
3045 	if_qflush(ifp);
3046 }
3047 
3048 static uint64_t
3049 vi_get_counter(struct ifnet *ifp, ift_counter c)
3050 {
3051 	struct vi_info *vi = ifp->if_softc;
3052 	struct fw_vi_stats_vf *s = &vi->stats;
3053 
3054 	mtx_lock(&vi->tick_mtx);
3055 	vi_refresh_stats(vi);
3056 	mtx_unlock(&vi->tick_mtx);
3057 
3058 	switch (c) {
3059 	case IFCOUNTER_IPACKETS:
3060 		return (s->rx_bcast_frames + s->rx_mcast_frames +
3061 		    s->rx_ucast_frames);
3062 	case IFCOUNTER_IERRORS:
3063 		return (s->rx_err_frames);
3064 	case IFCOUNTER_OPACKETS:
3065 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3066 		    s->tx_ucast_frames + s->tx_offload_frames);
3067 	case IFCOUNTER_OERRORS:
3068 		return (s->tx_drop_frames);
3069 	case IFCOUNTER_IBYTES:
3070 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3071 		    s->rx_ucast_bytes);
3072 	case IFCOUNTER_OBYTES:
3073 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3074 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3075 	case IFCOUNTER_IMCASTS:
3076 		return (s->rx_mcast_frames);
3077 	case IFCOUNTER_OMCASTS:
3078 		return (s->tx_mcast_frames);
3079 	case IFCOUNTER_OQDROPS: {
3080 		uint64_t drops;
3081 
3082 		drops = 0;
3083 		if (vi->flags & VI_INIT_DONE) {
3084 			int i;
3085 			struct sge_txq *txq;
3086 
3087 			for_each_txq(vi, i, txq)
3088 				drops += counter_u64_fetch(txq->r->dropped);
3089 		}
3090 
3091 		return (drops);
3092 
3093 	}
3094 
3095 	default:
3096 		return (if_get_counter_default(ifp, c));
3097 	}
3098 }
3099 
3100 static uint64_t
3101 cxgbe_get_counter(struct ifnet *ifp, ift_counter c)
3102 {
3103 	struct vi_info *vi = ifp->if_softc;
3104 	struct port_info *pi = vi->pi;
3105 	struct port_stats *s = &pi->stats;
3106 
3107 	mtx_lock(&vi->tick_mtx);
3108 	cxgbe_refresh_stats(vi);
3109 	mtx_unlock(&vi->tick_mtx);
3110 
3111 	switch (c) {
3112 	case IFCOUNTER_IPACKETS:
3113 		return (s->rx_frames);
3114 
3115 	case IFCOUNTER_IERRORS:
3116 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3117 		    s->rx_fcs_err + s->rx_len_err);
3118 
3119 	case IFCOUNTER_OPACKETS:
3120 		return (s->tx_frames);
3121 
3122 	case IFCOUNTER_OERRORS:
3123 		return (s->tx_error_frames);
3124 
3125 	case IFCOUNTER_IBYTES:
3126 		return (s->rx_octets);
3127 
3128 	case IFCOUNTER_OBYTES:
3129 		return (s->tx_octets);
3130 
3131 	case IFCOUNTER_IMCASTS:
3132 		return (s->rx_mcast_frames);
3133 
3134 	case IFCOUNTER_OMCASTS:
3135 		return (s->tx_mcast_frames);
3136 
3137 	case IFCOUNTER_IQDROPS:
3138 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3139 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3140 		    s->rx_trunc3 + pi->tnl_cong_drops);
3141 
3142 	case IFCOUNTER_OQDROPS: {
3143 		uint64_t drops;
3144 
3145 		drops = s->tx_drop;
3146 		if (vi->flags & VI_INIT_DONE) {
3147 			int i;
3148 			struct sge_txq *txq;
3149 
3150 			for_each_txq(vi, i, txq)
3151 				drops += counter_u64_fetch(txq->r->dropped);
3152 		}
3153 
3154 		return (drops);
3155 
3156 	}
3157 
3158 	default:
3159 		return (if_get_counter_default(ifp, c));
3160 	}
3161 }
3162 
3163 #if defined(KERN_TLS) || defined(RATELIMIT)
3164 static int
3165 cxgbe_snd_tag_alloc(struct ifnet *ifp, union if_snd_tag_alloc_params *params,
3166     struct m_snd_tag **pt)
3167 {
3168 	int error;
3169 
3170 	switch (params->hdr.type) {
3171 #ifdef RATELIMIT
3172 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3173 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3174 		break;
3175 #endif
3176 #ifdef KERN_TLS
3177 	case IF_SND_TAG_TYPE_TLS:
3178 	{
3179 		struct vi_info *vi = ifp->if_softc;
3180 
3181 		if (is_t6(vi->pi->adapter))
3182 			error = t6_tls_tag_alloc(ifp, params, pt);
3183 		else
3184 			error = EOPNOTSUPP;
3185 		break;
3186 	}
3187 #endif
3188 	default:
3189 		error = EOPNOTSUPP;
3190 	}
3191 	return (error);
3192 }
3193 #endif
3194 
3195 /*
3196  * The kernel picks a media from the list we had provided but we still validate
3197  * the requeste.
3198  */
3199 int
3200 cxgbe_media_change(struct ifnet *ifp)
3201 {
3202 	struct vi_info *vi = ifp->if_softc;
3203 	struct port_info *pi = vi->pi;
3204 	struct ifmedia *ifm = &pi->media;
3205 	struct link_config *lc = &pi->link_cfg;
3206 	struct adapter *sc = pi->adapter;
3207 	int rc;
3208 
3209 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3210 	if (rc != 0)
3211 		return (rc);
3212 	PORT_LOCK(pi);
3213 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3214 		/* ifconfig .. media autoselect */
3215 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3216 			rc = ENOTSUP; /* AN not supported by transceiver */
3217 			goto done;
3218 		}
3219 		lc->requested_aneg = AUTONEG_ENABLE;
3220 		lc->requested_speed = 0;
3221 		lc->requested_fc |= PAUSE_AUTONEG;
3222 	} else {
3223 		lc->requested_aneg = AUTONEG_DISABLE;
3224 		lc->requested_speed =
3225 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3226 		lc->requested_fc = 0;
3227 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3228 			lc->requested_fc |= PAUSE_RX;
3229 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3230 			lc->requested_fc |= PAUSE_TX;
3231 	}
3232 	if (pi->up_vis > 0 && !hw_off_limits(sc)) {
3233 		fixup_link_config(pi);
3234 		rc = apply_link_config(pi);
3235 	}
3236 done:
3237 	PORT_UNLOCK(pi);
3238 	end_synchronized_op(sc, 0);
3239 	return (rc);
3240 }
3241 
3242 /*
3243  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3244  * given speed.
3245  */
3246 static int
3247 port_mword(struct port_info *pi, uint32_t speed)
3248 {
3249 
3250 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3251 	MPASS(powerof2(speed));
3252 
3253 	switch(pi->port_type) {
3254 	case FW_PORT_TYPE_BT_SGMII:
3255 	case FW_PORT_TYPE_BT_XFI:
3256 	case FW_PORT_TYPE_BT_XAUI:
3257 		/* BaseT */
3258 		switch (speed) {
3259 		case FW_PORT_CAP32_SPEED_100M:
3260 			return (IFM_100_T);
3261 		case FW_PORT_CAP32_SPEED_1G:
3262 			return (IFM_1000_T);
3263 		case FW_PORT_CAP32_SPEED_10G:
3264 			return (IFM_10G_T);
3265 		}
3266 		break;
3267 	case FW_PORT_TYPE_KX4:
3268 		if (speed == FW_PORT_CAP32_SPEED_10G)
3269 			return (IFM_10G_KX4);
3270 		break;
3271 	case FW_PORT_TYPE_CX4:
3272 		if (speed == FW_PORT_CAP32_SPEED_10G)
3273 			return (IFM_10G_CX4);
3274 		break;
3275 	case FW_PORT_TYPE_KX:
3276 		if (speed == FW_PORT_CAP32_SPEED_1G)
3277 			return (IFM_1000_KX);
3278 		break;
3279 	case FW_PORT_TYPE_KR:
3280 	case FW_PORT_TYPE_BP_AP:
3281 	case FW_PORT_TYPE_BP4_AP:
3282 	case FW_PORT_TYPE_BP40_BA:
3283 	case FW_PORT_TYPE_KR4_100G:
3284 	case FW_PORT_TYPE_KR_SFP28:
3285 	case FW_PORT_TYPE_KR_XLAUI:
3286 		switch (speed) {
3287 		case FW_PORT_CAP32_SPEED_1G:
3288 			return (IFM_1000_KX);
3289 		case FW_PORT_CAP32_SPEED_10G:
3290 			return (IFM_10G_KR);
3291 		case FW_PORT_CAP32_SPEED_25G:
3292 			return (IFM_25G_KR);
3293 		case FW_PORT_CAP32_SPEED_40G:
3294 			return (IFM_40G_KR4);
3295 		case FW_PORT_CAP32_SPEED_50G:
3296 			return (IFM_50G_KR2);
3297 		case FW_PORT_CAP32_SPEED_100G:
3298 			return (IFM_100G_KR4);
3299 		}
3300 		break;
3301 	case FW_PORT_TYPE_FIBER_XFI:
3302 	case FW_PORT_TYPE_FIBER_XAUI:
3303 	case FW_PORT_TYPE_SFP:
3304 	case FW_PORT_TYPE_QSFP_10G:
3305 	case FW_PORT_TYPE_QSA:
3306 	case FW_PORT_TYPE_QSFP:
3307 	case FW_PORT_TYPE_CR4_QSFP:
3308 	case FW_PORT_TYPE_CR_QSFP:
3309 	case FW_PORT_TYPE_CR2_QSFP:
3310 	case FW_PORT_TYPE_SFP28:
3311 		/* Pluggable transceiver */
3312 		switch (pi->mod_type) {
3313 		case FW_PORT_MOD_TYPE_LR:
3314 			switch (speed) {
3315 			case FW_PORT_CAP32_SPEED_1G:
3316 				return (IFM_1000_LX);
3317 			case FW_PORT_CAP32_SPEED_10G:
3318 				return (IFM_10G_LR);
3319 			case FW_PORT_CAP32_SPEED_25G:
3320 				return (IFM_25G_LR);
3321 			case FW_PORT_CAP32_SPEED_40G:
3322 				return (IFM_40G_LR4);
3323 			case FW_PORT_CAP32_SPEED_50G:
3324 				return (IFM_50G_LR2);
3325 			case FW_PORT_CAP32_SPEED_100G:
3326 				return (IFM_100G_LR4);
3327 			}
3328 			break;
3329 		case FW_PORT_MOD_TYPE_SR:
3330 			switch (speed) {
3331 			case FW_PORT_CAP32_SPEED_1G:
3332 				return (IFM_1000_SX);
3333 			case FW_PORT_CAP32_SPEED_10G:
3334 				return (IFM_10G_SR);
3335 			case FW_PORT_CAP32_SPEED_25G:
3336 				return (IFM_25G_SR);
3337 			case FW_PORT_CAP32_SPEED_40G:
3338 				return (IFM_40G_SR4);
3339 			case FW_PORT_CAP32_SPEED_50G:
3340 				return (IFM_50G_SR2);
3341 			case FW_PORT_CAP32_SPEED_100G:
3342 				return (IFM_100G_SR4);
3343 			}
3344 			break;
3345 		case FW_PORT_MOD_TYPE_ER:
3346 			if (speed == FW_PORT_CAP32_SPEED_10G)
3347 				return (IFM_10G_ER);
3348 			break;
3349 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3350 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3351 			switch (speed) {
3352 			case FW_PORT_CAP32_SPEED_1G:
3353 				return (IFM_1000_CX);
3354 			case FW_PORT_CAP32_SPEED_10G:
3355 				return (IFM_10G_TWINAX);
3356 			case FW_PORT_CAP32_SPEED_25G:
3357 				return (IFM_25G_CR);
3358 			case FW_PORT_CAP32_SPEED_40G:
3359 				return (IFM_40G_CR4);
3360 			case FW_PORT_CAP32_SPEED_50G:
3361 				return (IFM_50G_CR2);
3362 			case FW_PORT_CAP32_SPEED_100G:
3363 				return (IFM_100G_CR4);
3364 			}
3365 			break;
3366 		case FW_PORT_MOD_TYPE_LRM:
3367 			if (speed == FW_PORT_CAP32_SPEED_10G)
3368 				return (IFM_10G_LRM);
3369 			break;
3370 		case FW_PORT_MOD_TYPE_NA:
3371 			MPASS(0);	/* Not pluggable? */
3372 			/* fall throough */
3373 		case FW_PORT_MOD_TYPE_ERROR:
3374 		case FW_PORT_MOD_TYPE_UNKNOWN:
3375 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3376 			break;
3377 		case FW_PORT_MOD_TYPE_NONE:
3378 			return (IFM_NONE);
3379 		}
3380 		break;
3381 	case FW_PORT_TYPE_NONE:
3382 		return (IFM_NONE);
3383 	}
3384 
3385 	return (IFM_UNKNOWN);
3386 }
3387 
3388 void
3389 cxgbe_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
3390 {
3391 	struct vi_info *vi = ifp->if_softc;
3392 	struct port_info *pi = vi->pi;
3393 	struct adapter *sc = pi->adapter;
3394 	struct link_config *lc = &pi->link_cfg;
3395 
3396 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4med") != 0)
3397 		return;
3398 	PORT_LOCK(pi);
3399 
3400 	if (pi->up_vis == 0 && !hw_off_limits(sc)) {
3401 		/*
3402 		 * If all the interfaces are administratively down the firmware
3403 		 * does not report transceiver changes.  Refresh port info here
3404 		 * so that ifconfig displays accurate ifmedia at all times.
3405 		 * This is the only reason we have a synchronized op in this
3406 		 * function.  Just PORT_LOCK would have been enough otherwise.
3407 		 */
3408 		t4_update_port_info(pi);
3409 		build_medialist(pi);
3410 	}
3411 
3412 	/* ifm_status */
3413 	ifmr->ifm_status = IFM_AVALID;
3414 	if (lc->link_ok == false)
3415 		goto done;
3416 	ifmr->ifm_status |= IFM_ACTIVE;
3417 
3418 	/* ifm_active */
3419 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3420 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3421 	if (lc->fc & PAUSE_RX)
3422 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3423 	if (lc->fc & PAUSE_TX)
3424 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3425 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3426 done:
3427 	PORT_UNLOCK(pi);
3428 	end_synchronized_op(sc, 0);
3429 }
3430 
3431 static int
3432 vcxgbe_probe(device_t dev)
3433 {
3434 	char buf[128];
3435 	struct vi_info *vi = device_get_softc(dev);
3436 
3437 	snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
3438 	    vi - vi->pi->vi);
3439 	device_set_desc_copy(dev, buf);
3440 
3441 	return (BUS_PROBE_DEFAULT);
3442 }
3443 
3444 static int
3445 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3446 {
3447 	int func, index, rc;
3448 	uint32_t param, val;
3449 
3450 	ASSERT_SYNCHRONIZED_OP(sc);
3451 
3452 	index = vi - pi->vi;
3453 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3454 	KASSERT(index < nitems(vi_mac_funcs),
3455 	    ("%s: VI %s doesn't have a MAC func", __func__,
3456 	    device_get_nameunit(vi->dev)));
3457 	func = vi_mac_funcs[index];
3458 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3459 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3460 	if (rc < 0) {
3461 		CH_ERR(vi, "failed to allocate virtual interface %d"
3462 		    "for port %d: %d\n", index, pi->port_id, -rc);
3463 		return (-rc);
3464 	}
3465 	vi->viid = rc;
3466 
3467 	if (vi->rss_size == 1) {
3468 		/*
3469 		 * This VI didn't get a slice of the RSS table.  Reduce the
3470 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3471 		 * configuration file (nvi, rssnvi for this PF) if this is a
3472 		 * problem.
3473 		 */
3474 		device_printf(vi->dev, "RSS table not available.\n");
3475 		vi->rss_base = 0xffff;
3476 
3477 		return (0);
3478 	}
3479 
3480 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3481 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3482 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3483 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3484 	if (rc)
3485 		vi->rss_base = 0xffff;
3486 	else {
3487 		MPASS((val >> 16) == vi->rss_size);
3488 		vi->rss_base = val & 0xffff;
3489 	}
3490 
3491 	return (0);
3492 }
3493 
3494 static int
3495 vcxgbe_attach(device_t dev)
3496 {
3497 	struct vi_info *vi;
3498 	struct port_info *pi;
3499 	struct adapter *sc;
3500 	int rc;
3501 
3502 	vi = device_get_softc(dev);
3503 	pi = vi->pi;
3504 	sc = pi->adapter;
3505 
3506 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3507 	if (rc)
3508 		return (rc);
3509 	rc = alloc_extra_vi(sc, pi, vi);
3510 	end_synchronized_op(sc, 0);
3511 	if (rc)
3512 		return (rc);
3513 
3514 	rc = cxgbe_vi_attach(dev, vi);
3515 	if (rc) {
3516 		t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3517 		return (rc);
3518 	}
3519 	return (0);
3520 }
3521 
3522 static int
3523 vcxgbe_detach(device_t dev)
3524 {
3525 	struct vi_info *vi;
3526 	struct adapter *sc;
3527 
3528 	vi = device_get_softc(dev);
3529 	sc = vi->adapter;
3530 
3531 	doom_vi(sc, vi);
3532 
3533 	cxgbe_vi_detach(vi);
3534 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3535 
3536 	end_synchronized_op(sc, 0);
3537 
3538 	return (0);
3539 }
3540 
3541 static struct callout fatal_callout;
3542 static struct taskqueue *reset_tq;
3543 
3544 static void
3545 delayed_panic(void *arg)
3546 {
3547 	struct adapter *sc = arg;
3548 
3549 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3550 }
3551 
3552 static void
3553 fatal_error_task(void *arg, int pending)
3554 {
3555 	struct adapter *sc = arg;
3556 	int rc;
3557 
3558 #ifdef TCP_OFFLOAD
3559 	t4_async_event(sc);
3560 #endif
3561 	if (atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_CIM_ERR))) {
3562 		dump_cim_regs(sc);
3563 		dump_cimla(sc);
3564 		dump_devlog(sc);
3565 	}
3566 
3567 	if (t4_reset_on_fatal_err) {
3568 		CH_ALERT(sc, "resetting on fatal error.\n");
3569 		rc = reset_adapter(sc);
3570 		if (rc == 0 && t4_panic_on_fatal_err) {
3571 			CH_ALERT(sc, "reset was successful, "
3572 			    "system will NOT panic.\n");
3573 			return;
3574 		}
3575 	}
3576 
3577 	if (t4_panic_on_fatal_err) {
3578 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3579 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3580 	}
3581 }
3582 
3583 void
3584 t4_fatal_err(struct adapter *sc, bool fw_error)
3585 {
3586 	const bool verbose = (sc->debug_flags & DF_VERBOSE_SLOWINTR) != 0;
3587 
3588 	stop_adapter(sc);
3589 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_FATAL_ERR)))
3590 		return;
3591 	if (fw_error) {
3592 		/*
3593 		 * We are here because of a firmware error/timeout and not
3594 		 * because of a hardware interrupt.  It is possible (although
3595 		 * not very likely) that an error interrupt was also raised but
3596 		 * this thread ran first and inhibited t4_intr_err.  We walk the
3597 		 * main INT_CAUSE registers here to make sure we haven't missed
3598 		 * anything interesting.
3599 		 */
3600 		t4_slow_intr_handler(sc, verbose);
3601 		atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
3602 	}
3603 	t4_report_fw_error(sc);
3604 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped (%d).\n",
3605 	    device_get_nameunit(sc->dev), fw_error);
3606 	taskqueue_enqueue(reset_tq, &sc->fatal_error_task);
3607 }
3608 
3609 void
3610 t4_add_adapter(struct adapter *sc)
3611 {
3612 	sx_xlock(&t4_list_lock);
3613 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3614 	sx_xunlock(&t4_list_lock);
3615 }
3616 
3617 int
3618 t4_map_bars_0_and_4(struct adapter *sc)
3619 {
3620 	sc->regs_rid = PCIR_BAR(0);
3621 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3622 	    &sc->regs_rid, RF_ACTIVE);
3623 	if (sc->regs_res == NULL) {
3624 		device_printf(sc->dev, "cannot map registers.\n");
3625 		return (ENXIO);
3626 	}
3627 	sc->bt = rman_get_bustag(sc->regs_res);
3628 	sc->bh = rman_get_bushandle(sc->regs_res);
3629 	sc->mmio_len = rman_get_size(sc->regs_res);
3630 	setbit(&sc->doorbells, DOORBELL_KDB);
3631 
3632 	sc->msix_rid = PCIR_BAR(4);
3633 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3634 	    &sc->msix_rid, RF_ACTIVE);
3635 	if (sc->msix_res == NULL) {
3636 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3637 		return (ENXIO);
3638 	}
3639 
3640 	return (0);
3641 }
3642 
3643 int
3644 t4_map_bar_2(struct adapter *sc)
3645 {
3646 
3647 	/*
3648 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3649 	 * to map it if RDMA is disabled.
3650 	 */
3651 	if (is_t4(sc) && sc->rdmacaps == 0)
3652 		return (0);
3653 
3654 	sc->udbs_rid = PCIR_BAR(2);
3655 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3656 	    &sc->udbs_rid, RF_ACTIVE);
3657 	if (sc->udbs_res == NULL) {
3658 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3659 		return (ENXIO);
3660 	}
3661 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3662 
3663 	if (chip_id(sc) >= CHELSIO_T5) {
3664 		setbit(&sc->doorbells, DOORBELL_UDB);
3665 #if defined(__i386__) || defined(__amd64__)
3666 		if (t5_write_combine) {
3667 			int rc, mode;
3668 
3669 			/*
3670 			 * Enable write combining on BAR2.  This is the
3671 			 * userspace doorbell BAR and is split into 128B
3672 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3673 			 * with an egress queue.  The first 64B has the doorbell
3674 			 * and the second 64B can be used to submit a tx work
3675 			 * request with an implicit doorbell.
3676 			 */
3677 
3678 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3679 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3680 			if (rc == 0) {
3681 				clrbit(&sc->doorbells, DOORBELL_UDB);
3682 				setbit(&sc->doorbells, DOORBELL_WCWR);
3683 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3684 			} else {
3685 				device_printf(sc->dev,
3686 				    "couldn't enable write combining: %d\n",
3687 				    rc);
3688 			}
3689 
3690 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3691 			t4_write_reg(sc, A_SGE_STAT_CFG,
3692 			    V_STATSOURCE_T5(7) | mode);
3693 		}
3694 #endif
3695 	}
3696 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3697 
3698 	return (0);
3699 }
3700 
3701 struct memwin_init {
3702 	uint32_t base;
3703 	uint32_t aperture;
3704 };
3705 
3706 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3707 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3708 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3709 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3710 };
3711 
3712 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3713 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3714 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3715 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3716 };
3717 
3718 static void
3719 setup_memwin(struct adapter *sc)
3720 {
3721 	const struct memwin_init *mw_init;
3722 	struct memwin *mw;
3723 	int i;
3724 	uint32_t bar0;
3725 
3726 	if (is_t4(sc)) {
3727 		/*
3728 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3729 		 * mechanism.  Works from within PCI passthrough environments
3730 		 * too, where rman_get_start() can return a different value.  We
3731 		 * need to program the T4 memory window decoders with the actual
3732 		 * addresses that will be coming across the PCIe link.
3733 		 */
3734 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3735 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3736 
3737 		mw_init = &t4_memwin[0];
3738 	} else {
3739 		/* T5+ use the relative offset inside the PCIe BAR */
3740 		bar0 = 0;
3741 
3742 		mw_init = &t5_memwin[0];
3743 	}
3744 
3745 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3746 		if (!rw_initialized(&mw->mw_lock)) {
3747 			rw_init(&mw->mw_lock, "memory window access");
3748 			mw->mw_base = mw_init->base;
3749 			mw->mw_aperture = mw_init->aperture;
3750 			mw->mw_curpos = 0;
3751 		}
3752 		t4_write_reg(sc,
3753 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3754 		    (mw->mw_base + bar0) | V_BIR(0) |
3755 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3756 		rw_wlock(&mw->mw_lock);
3757 		position_memwin(sc, i, mw->mw_curpos);
3758 		rw_wunlock(&mw->mw_lock);
3759 	}
3760 
3761 	/* flush */
3762 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3763 }
3764 
3765 /*
3766  * Positions the memory window at the given address in the card's address space.
3767  * There are some alignment requirements and the actual position may be at an
3768  * address prior to the requested address.  mw->mw_curpos always has the actual
3769  * position of the window.
3770  */
3771 static void
3772 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3773 {
3774 	struct memwin *mw;
3775 	uint32_t pf;
3776 	uint32_t reg;
3777 
3778 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3779 	mw = &sc->memwin[idx];
3780 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3781 
3782 	if (is_t4(sc)) {
3783 		pf = 0;
3784 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3785 	} else {
3786 		pf = V_PFNUM(sc->pf);
3787 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3788 	}
3789 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3790 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3791 	t4_read_reg(sc, reg);	/* flush */
3792 }
3793 
3794 int
3795 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3796     int len, int rw)
3797 {
3798 	struct memwin *mw;
3799 	uint32_t mw_end, v;
3800 
3801 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3802 
3803 	/* Memory can only be accessed in naturally aligned 4 byte units */
3804 	if (addr & 3 || len & 3 || len <= 0)
3805 		return (EINVAL);
3806 
3807 	mw = &sc->memwin[idx];
3808 	while (len > 0) {
3809 		rw_rlock(&mw->mw_lock);
3810 		mw_end = mw->mw_curpos + mw->mw_aperture;
3811 		if (addr >= mw_end || addr < mw->mw_curpos) {
3812 			/* Will need to reposition the window */
3813 			if (!rw_try_upgrade(&mw->mw_lock)) {
3814 				rw_runlock(&mw->mw_lock);
3815 				rw_wlock(&mw->mw_lock);
3816 			}
3817 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3818 			position_memwin(sc, idx, addr);
3819 			rw_downgrade(&mw->mw_lock);
3820 			mw_end = mw->mw_curpos + mw->mw_aperture;
3821 		}
3822 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3823 		while (addr < mw_end && len > 0) {
3824 			if (rw == 0) {
3825 				v = t4_read_reg(sc, mw->mw_base + addr -
3826 				    mw->mw_curpos);
3827 				*val++ = le32toh(v);
3828 			} else {
3829 				v = *val++;
3830 				t4_write_reg(sc, mw->mw_base + addr -
3831 				    mw->mw_curpos, htole32(v));
3832 			}
3833 			addr += 4;
3834 			len -= 4;
3835 		}
3836 		rw_runlock(&mw->mw_lock);
3837 	}
3838 
3839 	return (0);
3840 }
3841 
3842 static void
3843 t4_init_atid_table(struct adapter *sc)
3844 {
3845 	struct tid_info *t;
3846 	int i;
3847 
3848 	t = &sc->tids;
3849 	if (t->natids == 0)
3850 		return;
3851 
3852 	MPASS(t->atid_tab == NULL);
3853 
3854 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3855 	    M_ZERO | M_WAITOK);
3856 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3857 	t->afree = t->atid_tab;
3858 	t->atids_in_use = 0;
3859 	for (i = 1; i < t->natids; i++)
3860 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3861 	t->atid_tab[t->natids - 1].next = NULL;
3862 }
3863 
3864 static void
3865 t4_free_atid_table(struct adapter *sc)
3866 {
3867 	struct tid_info *t;
3868 
3869 	t = &sc->tids;
3870 
3871 	KASSERT(t->atids_in_use == 0,
3872 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3873 
3874 	if (mtx_initialized(&t->atid_lock))
3875 		mtx_destroy(&t->atid_lock);
3876 	free(t->atid_tab, M_CXGBE);
3877 	t->atid_tab = NULL;
3878 }
3879 
3880 int
3881 alloc_atid(struct adapter *sc, void *ctx)
3882 {
3883 	struct tid_info *t = &sc->tids;
3884 	int atid = -1;
3885 
3886 	mtx_lock(&t->atid_lock);
3887 	if (t->afree) {
3888 		union aopen_entry *p = t->afree;
3889 
3890 		atid = p - t->atid_tab;
3891 		MPASS(atid <= M_TID_TID);
3892 		t->afree = p->next;
3893 		p->data = ctx;
3894 		t->atids_in_use++;
3895 	}
3896 	mtx_unlock(&t->atid_lock);
3897 	return (atid);
3898 }
3899 
3900 void *
3901 lookup_atid(struct adapter *sc, int atid)
3902 {
3903 	struct tid_info *t = &sc->tids;
3904 
3905 	return (t->atid_tab[atid].data);
3906 }
3907 
3908 void
3909 free_atid(struct adapter *sc, int atid)
3910 {
3911 	struct tid_info *t = &sc->tids;
3912 	union aopen_entry *p = &t->atid_tab[atid];
3913 
3914 	mtx_lock(&t->atid_lock);
3915 	p->next = t->afree;
3916 	t->afree = p;
3917 	t->atids_in_use--;
3918 	mtx_unlock(&t->atid_lock);
3919 }
3920 
3921 static void
3922 queue_tid_release(struct adapter *sc, int tid)
3923 {
3924 
3925 	CXGBE_UNIMPLEMENTED("deferred tid release");
3926 }
3927 
3928 void
3929 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
3930 {
3931 	struct wrqe *wr;
3932 	struct cpl_tid_release *req;
3933 
3934 	wr = alloc_wrqe(sizeof(*req), ctrlq);
3935 	if (wr == NULL) {
3936 		queue_tid_release(sc, tid);	/* defer */
3937 		return;
3938 	}
3939 	req = wrtod(wr);
3940 
3941 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
3942 
3943 	t4_wrq_tx(sc, wr);
3944 }
3945 
3946 static int
3947 t4_range_cmp(const void *a, const void *b)
3948 {
3949 	return ((const struct t4_range *)a)->start -
3950 	       ((const struct t4_range *)b)->start;
3951 }
3952 
3953 /*
3954  * Verify that the memory range specified by the addr/len pair is valid within
3955  * the card's address space.
3956  */
3957 static int
3958 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
3959 {
3960 	struct t4_range mem_ranges[4], *r, *next;
3961 	uint32_t em, addr_len;
3962 	int i, n, remaining;
3963 
3964 	/* Memory can only be accessed in naturally aligned 4 byte units */
3965 	if (addr & 3 || len & 3 || len == 0)
3966 		return (EINVAL);
3967 
3968 	/* Enabled memories */
3969 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
3970 
3971 	r = &mem_ranges[0];
3972 	n = 0;
3973 	bzero(r, sizeof(mem_ranges));
3974 	if (em & F_EDRAM0_ENABLE) {
3975 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
3976 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
3977 		if (r->size > 0) {
3978 			r->start = G_EDRAM0_BASE(addr_len) << 20;
3979 			if (addr >= r->start &&
3980 			    addr + len <= r->start + r->size)
3981 				return (0);
3982 			r++;
3983 			n++;
3984 		}
3985 	}
3986 	if (em & F_EDRAM1_ENABLE) {
3987 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
3988 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
3989 		if (r->size > 0) {
3990 			r->start = G_EDRAM1_BASE(addr_len) << 20;
3991 			if (addr >= r->start &&
3992 			    addr + len <= r->start + r->size)
3993 				return (0);
3994 			r++;
3995 			n++;
3996 		}
3997 	}
3998 	if (em & F_EXT_MEM_ENABLE) {
3999 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4000 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
4001 		if (r->size > 0) {
4002 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
4003 			if (addr >= r->start &&
4004 			    addr + len <= r->start + r->size)
4005 				return (0);
4006 			r++;
4007 			n++;
4008 		}
4009 	}
4010 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
4011 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4012 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
4013 		if (r->size > 0) {
4014 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
4015 			if (addr >= r->start &&
4016 			    addr + len <= r->start + r->size)
4017 				return (0);
4018 			r++;
4019 			n++;
4020 		}
4021 	}
4022 	MPASS(n <= nitems(mem_ranges));
4023 
4024 	if (n > 1) {
4025 		/* Sort and merge the ranges. */
4026 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
4027 
4028 		/* Start from index 0 and examine the next n - 1 entries. */
4029 		r = &mem_ranges[0];
4030 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
4031 
4032 			MPASS(r->size > 0);	/* r is a valid entry. */
4033 			next = r + 1;
4034 			MPASS(next->size > 0);	/* and so is the next one. */
4035 
4036 			while (r->start + r->size >= next->start) {
4037 				/* Merge the next one into the current entry. */
4038 				r->size = max(r->start + r->size,
4039 				    next->start + next->size) - r->start;
4040 				n--;	/* One fewer entry in total. */
4041 				if (--remaining == 0)
4042 					goto done;	/* short circuit */
4043 				next++;
4044 			}
4045 			if (next != r + 1) {
4046 				/*
4047 				 * Some entries were merged into r and next
4048 				 * points to the first valid entry that couldn't
4049 				 * be merged.
4050 				 */
4051 				MPASS(next->size > 0);	/* must be valid */
4052 				memcpy(r + 1, next, remaining * sizeof(*r));
4053 #ifdef INVARIANTS
4054 				/*
4055 				 * This so that the foo->size assertion in the
4056 				 * next iteration of the loop do the right
4057 				 * thing for entries that were pulled up and are
4058 				 * no longer valid.
4059 				 */
4060 				MPASS(n < nitems(mem_ranges));
4061 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4062 				    sizeof(struct t4_range));
4063 #endif
4064 			}
4065 		}
4066 done:
4067 		/* Done merging the ranges. */
4068 		MPASS(n > 0);
4069 		r = &mem_ranges[0];
4070 		for (i = 0; i < n; i++, r++) {
4071 			if (addr >= r->start &&
4072 			    addr + len <= r->start + r->size)
4073 				return (0);
4074 		}
4075 	}
4076 
4077 	return (EFAULT);
4078 }
4079 
4080 static int
4081 fwmtype_to_hwmtype(int mtype)
4082 {
4083 
4084 	switch (mtype) {
4085 	case FW_MEMTYPE_EDC0:
4086 		return (MEM_EDC0);
4087 	case FW_MEMTYPE_EDC1:
4088 		return (MEM_EDC1);
4089 	case FW_MEMTYPE_EXTMEM:
4090 		return (MEM_MC0);
4091 	case FW_MEMTYPE_EXTMEM1:
4092 		return (MEM_MC1);
4093 	default:
4094 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4095 	}
4096 }
4097 
4098 /*
4099  * Verify that the memory range specified by the memtype/offset/len pair is
4100  * valid and lies entirely within the memtype specified.  The global address of
4101  * the start of the range is returned in addr.
4102  */
4103 static int
4104 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4105     uint32_t *addr)
4106 {
4107 	uint32_t em, addr_len, maddr;
4108 
4109 	/* Memory can only be accessed in naturally aligned 4 byte units */
4110 	if (off & 3 || len & 3 || len == 0)
4111 		return (EINVAL);
4112 
4113 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4114 	switch (fwmtype_to_hwmtype(mtype)) {
4115 	case MEM_EDC0:
4116 		if (!(em & F_EDRAM0_ENABLE))
4117 			return (EINVAL);
4118 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4119 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4120 		break;
4121 	case MEM_EDC1:
4122 		if (!(em & F_EDRAM1_ENABLE))
4123 			return (EINVAL);
4124 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4125 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4126 		break;
4127 	case MEM_MC:
4128 		if (!(em & F_EXT_MEM_ENABLE))
4129 			return (EINVAL);
4130 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4131 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4132 		break;
4133 	case MEM_MC1:
4134 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4135 			return (EINVAL);
4136 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4137 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4138 		break;
4139 	default:
4140 		return (EINVAL);
4141 	}
4142 
4143 	*addr = maddr + off;	/* global address */
4144 	return (validate_mem_range(sc, *addr, len));
4145 }
4146 
4147 static int
4148 fixup_devlog_params(struct adapter *sc)
4149 {
4150 	struct devlog_params *dparams = &sc->params.devlog;
4151 	int rc;
4152 
4153 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4154 	    dparams->size, &dparams->addr);
4155 
4156 	return (rc);
4157 }
4158 
4159 static void
4160 update_nirq(struct intrs_and_queues *iaq, int nports)
4161 {
4162 
4163 	iaq->nirq = T4_EXTRA_INTR;
4164 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4165 	iaq->nirq += nports * iaq->nofldrxq;
4166 	iaq->nirq += nports * (iaq->num_vis - 1) *
4167 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4168 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4169 }
4170 
4171 /*
4172  * Adjust requirements to fit the number of interrupts available.
4173  */
4174 static void
4175 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4176     int navail)
4177 {
4178 	int old_nirq;
4179 	const int nports = sc->params.nports;
4180 
4181 	MPASS(nports > 0);
4182 	MPASS(navail > 0);
4183 
4184 	bzero(iaq, sizeof(*iaq));
4185 	iaq->intr_type = itype;
4186 	iaq->num_vis = t4_num_vis;
4187 	iaq->ntxq = t4_ntxq;
4188 	iaq->ntxq_vi = t4_ntxq_vi;
4189 	iaq->nrxq = t4_nrxq;
4190 	iaq->nrxq_vi = t4_nrxq_vi;
4191 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4192 	if (is_offload(sc) || is_ethoffload(sc)) {
4193 		iaq->nofldtxq = t4_nofldtxq;
4194 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4195 	}
4196 #endif
4197 #ifdef TCP_OFFLOAD
4198 	if (is_offload(sc)) {
4199 		iaq->nofldrxq = t4_nofldrxq;
4200 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4201 	}
4202 #endif
4203 #ifdef DEV_NETMAP
4204 	if (t4_native_netmap & NN_MAIN_VI) {
4205 		iaq->nnmtxq = t4_nnmtxq;
4206 		iaq->nnmrxq = t4_nnmrxq;
4207 	}
4208 	if (t4_native_netmap & NN_EXTRA_VI) {
4209 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4210 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4211 	}
4212 #endif
4213 
4214 	update_nirq(iaq, nports);
4215 	if (iaq->nirq <= navail &&
4216 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4217 		/*
4218 		 * This is the normal case -- there are enough interrupts for
4219 		 * everything.
4220 		 */
4221 		goto done;
4222 	}
4223 
4224 	/*
4225 	 * If extra VIs have been configured try reducing their count and see if
4226 	 * that works.
4227 	 */
4228 	while (iaq->num_vis > 1) {
4229 		iaq->num_vis--;
4230 		update_nirq(iaq, nports);
4231 		if (iaq->nirq <= navail &&
4232 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4233 			device_printf(sc->dev, "virtual interfaces per port "
4234 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4235 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4236 			    "itype %d, navail %u, nirq %d.\n",
4237 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4238 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4239 			    itype, navail, iaq->nirq);
4240 			goto done;
4241 		}
4242 	}
4243 
4244 	/*
4245 	 * Extra VIs will not be created.  Log a message if they were requested.
4246 	 */
4247 	MPASS(iaq->num_vis == 1);
4248 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4249 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4250 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4251 	if (iaq->num_vis != t4_num_vis) {
4252 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4253 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4254 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4255 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4256 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4257 	}
4258 
4259 	/*
4260 	 * Keep reducing the number of NIC rx queues to the next lower power of
4261 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4262 	 * if that works.
4263 	 */
4264 	do {
4265 		if (iaq->nrxq > 1) {
4266 			do {
4267 				iaq->nrxq--;
4268 			} while (!powerof2(iaq->nrxq));
4269 			if (iaq->nnmrxq > iaq->nrxq)
4270 				iaq->nnmrxq = iaq->nrxq;
4271 		}
4272 		if (iaq->nofldrxq > 1)
4273 			iaq->nofldrxq >>= 1;
4274 
4275 		old_nirq = iaq->nirq;
4276 		update_nirq(iaq, nports);
4277 		if (iaq->nirq <= navail &&
4278 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4279 			device_printf(sc->dev, "running with reduced number of "
4280 			    "rx queues because of shortage of interrupts.  "
4281 			    "nrxq=%u, nofldrxq=%u.  "
4282 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4283 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4284 			goto done;
4285 		}
4286 	} while (old_nirq != iaq->nirq);
4287 
4288 	/* One interrupt for everything.  Ugh. */
4289 	device_printf(sc->dev, "running with minimal number of queues.  "
4290 	    "itype %d, navail %u.\n", itype, navail);
4291 	iaq->nirq = 1;
4292 	iaq->nrxq = 1;
4293 	iaq->ntxq = 1;
4294 	if (iaq->nofldrxq > 0) {
4295 		iaq->nofldrxq = 1;
4296 		iaq->nofldtxq = 1;
4297 	}
4298 	iaq->nnmtxq = 0;
4299 	iaq->nnmrxq = 0;
4300 done:
4301 	MPASS(iaq->num_vis > 0);
4302 	if (iaq->num_vis > 1) {
4303 		MPASS(iaq->nrxq_vi > 0);
4304 		MPASS(iaq->ntxq_vi > 0);
4305 	}
4306 	MPASS(iaq->nirq > 0);
4307 	MPASS(iaq->nrxq > 0);
4308 	MPASS(iaq->ntxq > 0);
4309 	if (itype == INTR_MSI) {
4310 		MPASS(powerof2(iaq->nirq));
4311 	}
4312 }
4313 
4314 static int
4315 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4316 {
4317 	int rc, itype, navail, nalloc;
4318 
4319 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4320 
4321 		if ((itype & t4_intr_types) == 0)
4322 			continue;	/* not allowed */
4323 
4324 		if (itype == INTR_MSIX)
4325 			navail = pci_msix_count(sc->dev);
4326 		else if (itype == INTR_MSI)
4327 			navail = pci_msi_count(sc->dev);
4328 		else
4329 			navail = 1;
4330 restart:
4331 		if (navail == 0)
4332 			continue;
4333 
4334 		calculate_iaq(sc, iaq, itype, navail);
4335 		nalloc = iaq->nirq;
4336 		rc = 0;
4337 		if (itype == INTR_MSIX)
4338 			rc = pci_alloc_msix(sc->dev, &nalloc);
4339 		else if (itype == INTR_MSI)
4340 			rc = pci_alloc_msi(sc->dev, &nalloc);
4341 
4342 		if (rc == 0 && nalloc > 0) {
4343 			if (nalloc == iaq->nirq)
4344 				return (0);
4345 
4346 			/*
4347 			 * Didn't get the number requested.  Use whatever number
4348 			 * the kernel is willing to allocate.
4349 			 */
4350 			device_printf(sc->dev, "fewer vectors than requested, "
4351 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4352 			    itype, iaq->nirq, nalloc);
4353 			pci_release_msi(sc->dev);
4354 			navail = nalloc;
4355 			goto restart;
4356 		}
4357 
4358 		device_printf(sc->dev,
4359 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4360 		    itype, rc, iaq->nirq, nalloc);
4361 	}
4362 
4363 	device_printf(sc->dev,
4364 	    "failed to find a usable interrupt type.  "
4365 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4366 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4367 
4368 	return (ENXIO);
4369 }
4370 
4371 #define FW_VERSION(chip) ( \
4372     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4373     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4374     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4375     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4376 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4377 
4378 /* Just enough of fw_hdr to cover all version info. */
4379 struct fw_h {
4380 	__u8	ver;
4381 	__u8	chip;
4382 	__be16	len512;
4383 	__be32	fw_ver;
4384 	__be32	tp_microcode_ver;
4385 	__u8	intfver_nic;
4386 	__u8	intfver_vnic;
4387 	__u8	intfver_ofld;
4388 	__u8	intfver_ri;
4389 	__u8	intfver_iscsipdu;
4390 	__u8	intfver_iscsi;
4391 	__u8	intfver_fcoepdu;
4392 	__u8	intfver_fcoe;
4393 };
4394 /* Spot check a couple of fields. */
4395 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4396 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4397 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4398 
4399 struct fw_info {
4400 	uint8_t chip;
4401 	char *kld_name;
4402 	char *fw_mod_name;
4403 	struct fw_h fw_h;
4404 } fw_info[] = {
4405 	{
4406 		.chip = CHELSIO_T4,
4407 		.kld_name = "t4fw_cfg",
4408 		.fw_mod_name = "t4fw",
4409 		.fw_h = {
4410 			.chip = FW_HDR_CHIP_T4,
4411 			.fw_ver = htobe32(FW_VERSION(T4)),
4412 			.intfver_nic = FW_INTFVER(T4, NIC),
4413 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4414 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4415 			.intfver_ri = FW_INTFVER(T4, RI),
4416 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4417 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4418 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4419 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4420 		},
4421 	}, {
4422 		.chip = CHELSIO_T5,
4423 		.kld_name = "t5fw_cfg",
4424 		.fw_mod_name = "t5fw",
4425 		.fw_h = {
4426 			.chip = FW_HDR_CHIP_T5,
4427 			.fw_ver = htobe32(FW_VERSION(T5)),
4428 			.intfver_nic = FW_INTFVER(T5, NIC),
4429 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4430 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4431 			.intfver_ri = FW_INTFVER(T5, RI),
4432 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4433 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4434 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4435 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4436 		},
4437 	}, {
4438 		.chip = CHELSIO_T6,
4439 		.kld_name = "t6fw_cfg",
4440 		.fw_mod_name = "t6fw",
4441 		.fw_h = {
4442 			.chip = FW_HDR_CHIP_T6,
4443 			.fw_ver = htobe32(FW_VERSION(T6)),
4444 			.intfver_nic = FW_INTFVER(T6, NIC),
4445 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4446 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4447 			.intfver_ri = FW_INTFVER(T6, RI),
4448 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4449 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4450 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4451 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4452 		},
4453 	}
4454 };
4455 
4456 static struct fw_info *
4457 find_fw_info(int chip)
4458 {
4459 	int i;
4460 
4461 	for (i = 0; i < nitems(fw_info); i++) {
4462 		if (fw_info[i].chip == chip)
4463 			return (&fw_info[i]);
4464 	}
4465 	return (NULL);
4466 }
4467 
4468 /*
4469  * Is the given firmware API compatible with the one the driver was compiled
4470  * with?
4471  */
4472 static int
4473 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4474 {
4475 
4476 	/* short circuit if it's the exact same firmware version */
4477 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4478 		return (1);
4479 
4480 	/*
4481 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4482 	 * features that are supported in the driver.
4483 	 */
4484 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4485 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4486 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4487 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4488 		return (1);
4489 #undef SAME_INTF
4490 
4491 	return (0);
4492 }
4493 
4494 static int
4495 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4496     const struct firmware **fw)
4497 {
4498 	struct fw_info *fw_info;
4499 
4500 	*dcfg = NULL;
4501 	if (fw != NULL)
4502 		*fw = NULL;
4503 
4504 	fw_info = find_fw_info(chip_id(sc));
4505 	if (fw_info == NULL) {
4506 		device_printf(sc->dev,
4507 		    "unable to look up firmware information for chip %d.\n",
4508 		    chip_id(sc));
4509 		return (EINVAL);
4510 	}
4511 
4512 	*dcfg = firmware_get(fw_info->kld_name);
4513 	if (*dcfg != NULL) {
4514 		if (fw != NULL)
4515 			*fw = firmware_get(fw_info->fw_mod_name);
4516 		return (0);
4517 	}
4518 
4519 	return (ENOENT);
4520 }
4521 
4522 static void
4523 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4524     const struct firmware *fw)
4525 {
4526 
4527 	if (fw != NULL)
4528 		firmware_put(fw, FIRMWARE_UNLOAD);
4529 	if (dcfg != NULL)
4530 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4531 }
4532 
4533 /*
4534  * Return values:
4535  * 0 means no firmware install attempted.
4536  * ERESTART means a firmware install was attempted and was successful.
4537  * +ve errno means a firmware install was attempted but failed.
4538  */
4539 static int
4540 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4541     const struct fw_h *drv_fw, const char *reason, int *already)
4542 {
4543 	const struct firmware *cfg, *fw;
4544 	const uint32_t c = be32toh(card_fw->fw_ver);
4545 	uint32_t d, k;
4546 	int rc, fw_install;
4547 	struct fw_h bundled_fw;
4548 	bool load_attempted;
4549 
4550 	cfg = fw = NULL;
4551 	load_attempted = false;
4552 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4553 
4554 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4555 	if (t4_fw_install < 0) {
4556 		rc = load_fw_module(sc, &cfg, &fw);
4557 		if (rc != 0 || fw == NULL) {
4558 			device_printf(sc->dev,
4559 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4560 			    " will use compiled-in firmware version for"
4561 			    "hw.cxgbe.fw_install checks.\n",
4562 			    rc, cfg, fw);
4563 		} else {
4564 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4565 		}
4566 		load_attempted = true;
4567 	}
4568 	d = be32toh(bundled_fw.fw_ver);
4569 
4570 	if (reason != NULL)
4571 		goto install;
4572 
4573 	if ((sc->flags & FW_OK) == 0) {
4574 
4575 		if (c == 0xffffffff) {
4576 			reason = "missing";
4577 			goto install;
4578 		}
4579 
4580 		rc = 0;
4581 		goto done;
4582 	}
4583 
4584 	if (!fw_compatible(card_fw, &bundled_fw)) {
4585 		reason = "incompatible or unusable";
4586 		goto install;
4587 	}
4588 
4589 	if (d > c) {
4590 		reason = "older than the version bundled with this driver";
4591 		goto install;
4592 	}
4593 
4594 	if (fw_install == 2 && d != c) {
4595 		reason = "different than the version bundled with this driver";
4596 		goto install;
4597 	}
4598 
4599 	/* No reason to do anything to the firmware already on the card. */
4600 	rc = 0;
4601 	goto done;
4602 
4603 install:
4604 	rc = 0;
4605 	if ((*already)++)
4606 		goto done;
4607 
4608 	if (fw_install == 0) {
4609 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4610 		    "but the driver is prohibited from installing a firmware "
4611 		    "on the card.\n",
4612 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4613 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4614 
4615 		goto done;
4616 	}
4617 
4618 	/*
4619 	 * We'll attempt to install a firmware.  Load the module first (if it
4620 	 * hasn't been loaded already).
4621 	 */
4622 	if (!load_attempted) {
4623 		rc = load_fw_module(sc, &cfg, &fw);
4624 		if (rc != 0 || fw == NULL) {
4625 			device_printf(sc->dev,
4626 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4627 			    rc, cfg, fw);
4628 			/* carry on */
4629 		}
4630 	}
4631 	if (fw == NULL) {
4632 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4633 		    "but the driver cannot take corrective action because it "
4634 		    "is unable to load the firmware module.\n",
4635 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4636 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4637 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4638 		goto done;
4639 	}
4640 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4641 	if (k != d) {
4642 		MPASS(t4_fw_install > 0);
4643 		device_printf(sc->dev,
4644 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4645 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4646 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4647 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4648 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4649 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4650 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4651 		goto done;
4652 	}
4653 
4654 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4655 	    "installing firmware %u.%u.%u.%u on card.\n",
4656 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4657 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4658 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4659 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4660 
4661 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4662 	if (rc != 0) {
4663 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4664 	} else {
4665 		/* Installed successfully, update the cached header too. */
4666 		rc = ERESTART;
4667 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4668 	}
4669 done:
4670 	unload_fw_module(sc, cfg, fw);
4671 
4672 	return (rc);
4673 }
4674 
4675 /*
4676  * Establish contact with the firmware and attempt to become the master driver.
4677  *
4678  * A firmware will be installed to the card if needed (if the driver is allowed
4679  * to do so).
4680  */
4681 static int
4682 contact_firmware(struct adapter *sc)
4683 {
4684 	int rc, already = 0;
4685 	enum dev_state state;
4686 	struct fw_info *fw_info;
4687 	struct fw_hdr *card_fw;		/* fw on the card */
4688 	const struct fw_h *drv_fw;
4689 
4690 	fw_info = find_fw_info(chip_id(sc));
4691 	if (fw_info == NULL) {
4692 		device_printf(sc->dev,
4693 		    "unable to look up firmware information for chip %d.\n",
4694 		    chip_id(sc));
4695 		return (EINVAL);
4696 	}
4697 	drv_fw = &fw_info->fw_h;
4698 
4699 	/* Read the header of the firmware on the card */
4700 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4701 restart:
4702 	rc = -t4_get_fw_hdr(sc, card_fw);
4703 	if (rc != 0) {
4704 		device_printf(sc->dev,
4705 		    "unable to read firmware header from card's flash: %d\n",
4706 		    rc);
4707 		goto done;
4708 	}
4709 
4710 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4711 	    &already);
4712 	if (rc == ERESTART)
4713 		goto restart;
4714 	if (rc != 0)
4715 		goto done;
4716 
4717 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4718 	if (rc < 0 || state == DEV_STATE_ERR) {
4719 		rc = -rc;
4720 		device_printf(sc->dev,
4721 		    "failed to connect to the firmware: %d, %d.  "
4722 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4723 #if 0
4724 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4725 		    "not responding properly to HELLO", &already) == ERESTART)
4726 			goto restart;
4727 #endif
4728 		goto done;
4729 	}
4730 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4731 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4732 
4733 	if (rc == sc->pf) {
4734 		sc->flags |= MASTER_PF;
4735 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4736 		    NULL, &already);
4737 		if (rc == ERESTART)
4738 			rc = 0;
4739 		else if (rc != 0)
4740 			goto done;
4741 	} else if (state == DEV_STATE_UNINIT) {
4742 		/*
4743 		 * We didn't get to be the master so we definitely won't be
4744 		 * configuring the chip.  It's a bug if someone else hasn't
4745 		 * configured it already.
4746 		 */
4747 		device_printf(sc->dev, "couldn't be master(%d), "
4748 		    "device not already initialized either(%d).  "
4749 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4750 		rc = EPROTO;
4751 		goto done;
4752 	} else {
4753 		/*
4754 		 * Some other PF is the master and has configured the chip.
4755 		 * This is allowed but untested.
4756 		 */
4757 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4758 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4759 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4760 		sc->cfcsum = 0;
4761 		rc = 0;
4762 	}
4763 done:
4764 	if (rc != 0 && sc->flags & FW_OK) {
4765 		t4_fw_bye(sc, sc->mbox);
4766 		sc->flags &= ~FW_OK;
4767 	}
4768 	free(card_fw, M_CXGBE);
4769 	return (rc);
4770 }
4771 
4772 static int
4773 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4774     uint32_t mtype, uint32_t moff)
4775 {
4776 	struct fw_info *fw_info;
4777 	const struct firmware *dcfg, *rcfg = NULL;
4778 	const uint32_t *cfdata;
4779 	uint32_t cflen, addr;
4780 	int rc;
4781 
4782 	load_fw_module(sc, &dcfg, NULL);
4783 
4784 	/* Card specific interpretation of "default". */
4785 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4786 		if (pci_get_device(sc->dev) == 0x440a)
4787 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4788 		if (is_fpga(sc))
4789 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4790 	}
4791 
4792 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4793 		if (dcfg == NULL) {
4794 			device_printf(sc->dev,
4795 			    "KLD with default config is not available.\n");
4796 			rc = ENOENT;
4797 			goto done;
4798 		}
4799 		cfdata = dcfg->data;
4800 		cflen = dcfg->datasize & ~3;
4801 	} else {
4802 		char s[32];
4803 
4804 		fw_info = find_fw_info(chip_id(sc));
4805 		if (fw_info == NULL) {
4806 			device_printf(sc->dev,
4807 			    "unable to look up firmware information for chip %d.\n",
4808 			    chip_id(sc));
4809 			rc = EINVAL;
4810 			goto done;
4811 		}
4812 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4813 
4814 		rcfg = firmware_get(s);
4815 		if (rcfg == NULL) {
4816 			device_printf(sc->dev,
4817 			    "unable to load module \"%s\" for configuration "
4818 			    "profile \"%s\".\n", s, cfg_file);
4819 			rc = ENOENT;
4820 			goto done;
4821 		}
4822 		cfdata = rcfg->data;
4823 		cflen = rcfg->datasize & ~3;
4824 	}
4825 
4826 	if (cflen > FLASH_CFG_MAX_SIZE) {
4827 		device_printf(sc->dev,
4828 		    "config file too long (%d, max allowed is %d).\n",
4829 		    cflen, FLASH_CFG_MAX_SIZE);
4830 		rc = EINVAL;
4831 		goto done;
4832 	}
4833 
4834 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4835 	if (rc != 0) {
4836 		device_printf(sc->dev,
4837 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4838 		    __func__, mtype, moff, cflen, rc);
4839 		rc = EINVAL;
4840 		goto done;
4841 	}
4842 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4843 done:
4844 	if (rcfg != NULL)
4845 		firmware_put(rcfg, FIRMWARE_UNLOAD);
4846 	unload_fw_module(sc, dcfg, NULL);
4847 	return (rc);
4848 }
4849 
4850 struct caps_allowed {
4851 	uint16_t nbmcaps;
4852 	uint16_t linkcaps;
4853 	uint16_t switchcaps;
4854 	uint16_t niccaps;
4855 	uint16_t toecaps;
4856 	uint16_t rdmacaps;
4857 	uint16_t cryptocaps;
4858 	uint16_t iscsicaps;
4859 	uint16_t fcoecaps;
4860 };
4861 
4862 #define FW_PARAM_DEV(param) \
4863 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4864 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4865 #define FW_PARAM_PFVF(param) \
4866 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4867 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4868 
4869 /*
4870  * Provide a configuration profile to the firmware and have it initialize the
4871  * chip accordingly.  This may involve uploading a configuration file to the
4872  * card.
4873  */
4874 static int
4875 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4876     const struct caps_allowed *caps_allowed)
4877 {
4878 	int rc;
4879 	struct fw_caps_config_cmd caps;
4880 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
4881 
4882 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4883 	if (rc != 0) {
4884 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
4885 		return (rc);
4886 	}
4887 
4888 	bzero(&caps, sizeof(caps));
4889 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4890 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
4891 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
4892 		mtype = 0;
4893 		moff = 0;
4894 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4895 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
4896 		mtype = FW_MEMTYPE_FLASH;
4897 		moff = t4_flash_cfg_addr(sc);
4898 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4899 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4900 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4901 		    FW_LEN16(caps));
4902 	} else {
4903 		/*
4904 		 * Ask the firmware where it wants us to upload the config file.
4905 		 */
4906 		param = FW_PARAM_DEV(CF);
4907 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4908 		if (rc != 0) {
4909 			/* No support for config file?  Shouldn't happen. */
4910 			device_printf(sc->dev,
4911 			    "failed to query config file location: %d.\n", rc);
4912 			goto done;
4913 		}
4914 		mtype = G_FW_PARAMS_PARAM_Y(val);
4915 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
4916 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4917 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4918 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4919 		    FW_LEN16(caps));
4920 
4921 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
4922 		if (rc != 0) {
4923 			device_printf(sc->dev,
4924 			    "failed to upload config file to card: %d.\n", rc);
4925 			goto done;
4926 		}
4927 	}
4928 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
4929 	if (rc != 0) {
4930 		device_printf(sc->dev, "failed to pre-process config file: %d "
4931 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
4932 		goto done;
4933 	}
4934 
4935 	finicsum = be32toh(caps.finicsum);
4936 	cfcsum = be32toh(caps.cfcsum);	/* actual */
4937 	if (finicsum != cfcsum) {
4938 		device_printf(sc->dev,
4939 		    "WARNING: config file checksum mismatch: %08x %08x\n",
4940 		    finicsum, cfcsum);
4941 	}
4942 	sc->cfcsum = cfcsum;
4943 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
4944 
4945 	/*
4946 	 * Let the firmware know what features will (not) be used so it can tune
4947 	 * things accordingly.
4948 	 */
4949 #define LIMIT_CAPS(x) do { \
4950 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
4951 } while (0)
4952 	LIMIT_CAPS(nbm);
4953 	LIMIT_CAPS(link);
4954 	LIMIT_CAPS(switch);
4955 	LIMIT_CAPS(nic);
4956 	LIMIT_CAPS(toe);
4957 	LIMIT_CAPS(rdma);
4958 	LIMIT_CAPS(crypto);
4959 	LIMIT_CAPS(iscsi);
4960 	LIMIT_CAPS(fcoe);
4961 #undef LIMIT_CAPS
4962 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
4963 		/*
4964 		 * TOE and hashfilters are mutually exclusive.  It is a config
4965 		 * file or firmware bug if both are reported as available.  Try
4966 		 * to cope with the situation in non-debug builds by disabling
4967 		 * TOE.
4968 		 */
4969 		MPASS(caps.toecaps == 0);
4970 
4971 		caps.toecaps = 0;
4972 		caps.rdmacaps = 0;
4973 		caps.iscsicaps = 0;
4974 	}
4975 
4976 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4977 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
4978 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4979 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
4980 	if (rc != 0) {
4981 		device_printf(sc->dev,
4982 		    "failed to process config file: %d.\n", rc);
4983 		goto done;
4984 	}
4985 
4986 	t4_tweak_chip_settings(sc);
4987 	set_params__pre_init(sc);
4988 
4989 	/* get basic stuff going */
4990 	rc = -t4_fw_initialize(sc, sc->mbox);
4991 	if (rc != 0) {
4992 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
4993 		goto done;
4994 	}
4995 done:
4996 	return (rc);
4997 }
4998 
4999 /*
5000  * Partition chip resources for use between various PFs, VFs, etc.
5001  */
5002 static int
5003 partition_resources(struct adapter *sc)
5004 {
5005 	char cfg_file[sizeof(t4_cfg_file)];
5006 	struct caps_allowed caps_allowed;
5007 	int rc;
5008 	bool fallback;
5009 
5010 	/* Only the master driver gets to configure the chip resources. */
5011 	MPASS(sc->flags & MASTER_PF);
5012 
5013 #define COPY_CAPS(x) do { \
5014 	caps_allowed.x##caps = t4_##x##caps_allowed; \
5015 } while (0)
5016 	bzero(&caps_allowed, sizeof(caps_allowed));
5017 	COPY_CAPS(nbm);
5018 	COPY_CAPS(link);
5019 	COPY_CAPS(switch);
5020 	COPY_CAPS(nic);
5021 	COPY_CAPS(toe);
5022 	COPY_CAPS(rdma);
5023 	COPY_CAPS(crypto);
5024 	COPY_CAPS(iscsi);
5025 	COPY_CAPS(fcoe);
5026 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
5027 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
5028 retry:
5029 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
5030 	if (rc != 0 && fallback) {
5031 		device_printf(sc->dev,
5032 		    "failed (%d) to configure card with \"%s\" profile, "
5033 		    "will fall back to a basic configuration and retry.\n",
5034 		    rc, cfg_file);
5035 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
5036 		bzero(&caps_allowed, sizeof(caps_allowed));
5037 		COPY_CAPS(switch);
5038 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
5039 		fallback = false;
5040 		goto retry;
5041 	}
5042 #undef COPY_CAPS
5043 	return (rc);
5044 }
5045 
5046 /*
5047  * Retrieve parameters that are needed (or nice to have) very early.
5048  */
5049 static int
5050 get_params__pre_init(struct adapter *sc)
5051 {
5052 	int rc;
5053 	uint32_t param[2], val[2];
5054 
5055 	t4_get_version_info(sc);
5056 
5057 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5058 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5059 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5060 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5061 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5062 
5063 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5064 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5065 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5066 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5067 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5068 
5069 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5070 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5071 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5072 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5073 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5074 
5075 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5076 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5077 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5078 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5079 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5080 
5081 	param[0] = FW_PARAM_DEV(PORTVEC);
5082 	param[1] = FW_PARAM_DEV(CCLK);
5083 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5084 	if (rc != 0) {
5085 		device_printf(sc->dev,
5086 		    "failed to query parameters (pre_init): %d.\n", rc);
5087 		return (rc);
5088 	}
5089 
5090 	sc->params.portvec = val[0];
5091 	sc->params.nports = bitcount32(val[0]);
5092 	sc->params.vpd.cclk = val[1];
5093 
5094 	/* Read device log parameters. */
5095 	rc = -t4_init_devlog_params(sc, 1);
5096 	if (rc == 0)
5097 		fixup_devlog_params(sc);
5098 	else {
5099 		device_printf(sc->dev,
5100 		    "failed to get devlog parameters: %d.\n", rc);
5101 		rc = 0;	/* devlog isn't critical for device operation */
5102 	}
5103 
5104 	return (rc);
5105 }
5106 
5107 /*
5108  * Any params that need to be set before FW_INITIALIZE.
5109  */
5110 static int
5111 set_params__pre_init(struct adapter *sc)
5112 {
5113 	int rc = 0;
5114 	uint32_t param, val;
5115 
5116 	if (chip_id(sc) >= CHELSIO_T6) {
5117 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5118 		val = 1;
5119 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5120 		/* firmwares < 1.20.1.0 do not have this param. */
5121 		if (rc == FW_EINVAL &&
5122 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5123 			rc = 0;
5124 		}
5125 		if (rc != 0) {
5126 			device_printf(sc->dev,
5127 			    "failed to enable high priority filters :%d.\n",
5128 			    rc);
5129 		}
5130 
5131 		param = FW_PARAM_DEV(PPOD_EDRAM);
5132 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5133 		if (rc == 0 && val == 1) {
5134 			rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param,
5135 			    &val);
5136 			if (rc != 0) {
5137 				device_printf(sc->dev,
5138 				    "failed to set PPOD_EDRAM: %d.\n", rc);
5139 			}
5140 		}
5141 	}
5142 
5143 	/* Enable opaque VIIDs with firmwares that support it. */
5144 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5145 	val = 1;
5146 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5147 	if (rc == 0 && val == 1)
5148 		sc->params.viid_smt_extn_support = true;
5149 	else
5150 		sc->params.viid_smt_extn_support = false;
5151 
5152 	return (rc);
5153 }
5154 
5155 /*
5156  * Retrieve various parameters that are of interest to the driver.  The device
5157  * has been initialized by the firmware at this point.
5158  */
5159 static int
5160 get_params__post_init(struct adapter *sc)
5161 {
5162 	int rc;
5163 	uint32_t param[7], val[7];
5164 	struct fw_caps_config_cmd caps;
5165 
5166 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5167 	param[1] = FW_PARAM_PFVF(EQ_START);
5168 	param[2] = FW_PARAM_PFVF(FILTER_START);
5169 	param[3] = FW_PARAM_PFVF(FILTER_END);
5170 	param[4] = FW_PARAM_PFVF(L2T_START);
5171 	param[5] = FW_PARAM_PFVF(L2T_END);
5172 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5173 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5174 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5175 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5176 	if (rc != 0) {
5177 		device_printf(sc->dev,
5178 		    "failed to query parameters (post_init): %d.\n", rc);
5179 		return (rc);
5180 	}
5181 
5182 	sc->sge.iq_start = val[0];
5183 	sc->sge.eq_start = val[1];
5184 	if ((int)val[3] > (int)val[2]) {
5185 		sc->tids.ftid_base = val[2];
5186 		sc->tids.ftid_end = val[3];
5187 		sc->tids.nftids = val[3] - val[2] + 1;
5188 	}
5189 	sc->vres.l2t.start = val[4];
5190 	sc->vres.l2t.size = val[5] - val[4] + 1;
5191 	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
5192 	    ("%s: L2 table size (%u) larger than expected (%u)",
5193 	    __func__, sc->vres.l2t.size, L2T_SIZE));
5194 	sc->params.core_vdd = val[6];
5195 
5196 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5197 	param[1] = FW_PARAM_PFVF(EQ_END);
5198 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5199 	if (rc != 0) {
5200 		device_printf(sc->dev,
5201 		    "failed to query parameters (post_init2): %d.\n", rc);
5202 		return (rc);
5203 	}
5204 	MPASS((int)val[0] >= sc->sge.iq_start);
5205 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5206 	MPASS((int)val[1] >= sc->sge.eq_start);
5207 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5208 
5209 	if (chip_id(sc) >= CHELSIO_T6) {
5210 
5211 		sc->tids.tid_base = t4_read_reg(sc,
5212 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5213 
5214 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5215 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5216 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5217 		if (rc != 0) {
5218 			device_printf(sc->dev,
5219 			   "failed to query hpfilter parameters: %d.\n", rc);
5220 			return (rc);
5221 		}
5222 		if ((int)val[1] > (int)val[0]) {
5223 			sc->tids.hpftid_base = val[0];
5224 			sc->tids.hpftid_end = val[1];
5225 			sc->tids.nhpftids = val[1] - val[0] + 1;
5226 
5227 			/*
5228 			 * These should go off if the layout changes and the
5229 			 * driver needs to catch up.
5230 			 */
5231 			MPASS(sc->tids.hpftid_base == 0);
5232 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5233 		}
5234 
5235 		param[0] = FW_PARAM_PFVF(RAWF_START);
5236 		param[1] = FW_PARAM_PFVF(RAWF_END);
5237 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5238 		if (rc != 0) {
5239 			device_printf(sc->dev,
5240 			   "failed to query rawf parameters: %d.\n", rc);
5241 			return (rc);
5242 		}
5243 		if ((int)val[1] > (int)val[0]) {
5244 			sc->rawf_base = val[0];
5245 			sc->nrawf = val[1] - val[0] + 1;
5246 		}
5247 	}
5248 
5249 	/*
5250 	 * MPSBGMAP is queried separately because only recent firmwares support
5251 	 * it as a parameter and we don't want the compound query above to fail
5252 	 * on older firmwares.
5253 	 */
5254 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5255 	val[0] = 0;
5256 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5257 	if (rc == 0)
5258 		sc->params.mps_bg_map = val[0];
5259 	else
5260 		sc->params.mps_bg_map = 0;
5261 
5262 	/*
5263 	 * Determine whether the firmware supports the filter2 work request.
5264 	 * This is queried separately for the same reason as MPSBGMAP above.
5265 	 */
5266 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5267 	val[0] = 0;
5268 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5269 	if (rc == 0)
5270 		sc->params.filter2_wr_support = val[0] != 0;
5271 	else
5272 		sc->params.filter2_wr_support = 0;
5273 
5274 	/*
5275 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5276 	 * This is queried separately for the same reason as other params above.
5277 	 */
5278 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5279 	val[0] = 0;
5280 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5281 	if (rc == 0)
5282 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5283 	else
5284 		sc->params.ulptx_memwrite_dsgl = false;
5285 
5286 	/* FW_RI_FR_NSMR_TPTE_WR support */
5287 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5288 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5289 	if (rc == 0)
5290 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5291 	else
5292 		sc->params.fr_nsmr_tpte_wr_support = false;
5293 
5294 	/* Support for 512 SGL entries per FR MR. */
5295 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5296 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5297 	if (rc == 0)
5298 		sc->params.dev_512sgl_mr = val[0] != 0;
5299 	else
5300 		sc->params.dev_512sgl_mr = false;
5301 
5302 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5303 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5304 	if (rc == 0)
5305 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5306 	else
5307 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5308 
5309 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5310 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5311 	if (rc == 0) {
5312 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5313 		sc->params.nsched_cls = val[0];
5314 	} else
5315 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5316 
5317 	/* get capabilites */
5318 	bzero(&caps, sizeof(caps));
5319 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5320 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5321 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5322 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5323 	if (rc != 0) {
5324 		device_printf(sc->dev,
5325 		    "failed to get card capabilities: %d.\n", rc);
5326 		return (rc);
5327 	}
5328 
5329 #define READ_CAPS(x) do { \
5330 	sc->x = htobe16(caps.x); \
5331 } while (0)
5332 	READ_CAPS(nbmcaps);
5333 	READ_CAPS(linkcaps);
5334 	READ_CAPS(switchcaps);
5335 	READ_CAPS(niccaps);
5336 	READ_CAPS(toecaps);
5337 	READ_CAPS(rdmacaps);
5338 	READ_CAPS(cryptocaps);
5339 	READ_CAPS(iscsicaps);
5340 	READ_CAPS(fcoecaps);
5341 
5342 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5343 		MPASS(chip_id(sc) > CHELSIO_T4);
5344 		MPASS(sc->toecaps == 0);
5345 		sc->toecaps = 0;
5346 
5347 		param[0] = FW_PARAM_DEV(NTID);
5348 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5349 		if (rc != 0) {
5350 			device_printf(sc->dev,
5351 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5352 			return (rc);
5353 		}
5354 		sc->tids.ntids = val[0];
5355 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5356 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5357 			sc->tids.ntids -= sc->tids.nhpftids;
5358 		}
5359 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5360 		sc->params.hash_filter = 1;
5361 	}
5362 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5363 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5364 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5365 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5366 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5367 		if (rc != 0) {
5368 			device_printf(sc->dev,
5369 			    "failed to query NIC parameters: %d.\n", rc);
5370 			return (rc);
5371 		}
5372 		if ((int)val[1] > (int)val[0]) {
5373 			sc->tids.etid_base = val[0];
5374 			sc->tids.etid_end = val[1];
5375 			sc->tids.netids = val[1] - val[0] + 1;
5376 			sc->params.eo_wr_cred = val[2];
5377 			sc->params.ethoffload = 1;
5378 		}
5379 	}
5380 	if (sc->toecaps) {
5381 		/* query offload-related parameters */
5382 		param[0] = FW_PARAM_DEV(NTID);
5383 		param[1] = FW_PARAM_PFVF(SERVER_START);
5384 		param[2] = FW_PARAM_PFVF(SERVER_END);
5385 		param[3] = FW_PARAM_PFVF(TDDP_START);
5386 		param[4] = FW_PARAM_PFVF(TDDP_END);
5387 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5388 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5389 		if (rc != 0) {
5390 			device_printf(sc->dev,
5391 			    "failed to query TOE parameters: %d.\n", rc);
5392 			return (rc);
5393 		}
5394 		sc->tids.ntids = val[0];
5395 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5396 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5397 			sc->tids.ntids -= sc->tids.nhpftids;
5398 		}
5399 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5400 		if ((int)val[2] > (int)val[1]) {
5401 			sc->tids.stid_base = val[1];
5402 			sc->tids.nstids = val[2] - val[1] + 1;
5403 		}
5404 		sc->vres.ddp.start = val[3];
5405 		sc->vres.ddp.size = val[4] - val[3] + 1;
5406 		sc->params.ofldq_wr_cred = val[5];
5407 		sc->params.offload = 1;
5408 	} else {
5409 		/*
5410 		 * The firmware attempts memfree TOE configuration for -SO cards
5411 		 * and will report toecaps=0 if it runs out of resources (this
5412 		 * depends on the config file).  It may not report 0 for other
5413 		 * capabilities dependent on the TOE in this case.  Set them to
5414 		 * 0 here so that the driver doesn't bother tracking resources
5415 		 * that will never be used.
5416 		 */
5417 		sc->iscsicaps = 0;
5418 		sc->rdmacaps = 0;
5419 	}
5420 	if (sc->rdmacaps) {
5421 		param[0] = FW_PARAM_PFVF(STAG_START);
5422 		param[1] = FW_PARAM_PFVF(STAG_END);
5423 		param[2] = FW_PARAM_PFVF(RQ_START);
5424 		param[3] = FW_PARAM_PFVF(RQ_END);
5425 		param[4] = FW_PARAM_PFVF(PBL_START);
5426 		param[5] = FW_PARAM_PFVF(PBL_END);
5427 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5428 		if (rc != 0) {
5429 			device_printf(sc->dev,
5430 			    "failed to query RDMA parameters(1): %d.\n", rc);
5431 			return (rc);
5432 		}
5433 		sc->vres.stag.start = val[0];
5434 		sc->vres.stag.size = val[1] - val[0] + 1;
5435 		sc->vres.rq.start = val[2];
5436 		sc->vres.rq.size = val[3] - val[2] + 1;
5437 		sc->vres.pbl.start = val[4];
5438 		sc->vres.pbl.size = val[5] - val[4] + 1;
5439 
5440 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5441 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5442 		param[2] = FW_PARAM_PFVF(CQ_START);
5443 		param[3] = FW_PARAM_PFVF(CQ_END);
5444 		param[4] = FW_PARAM_PFVF(OCQ_START);
5445 		param[5] = FW_PARAM_PFVF(OCQ_END);
5446 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5447 		if (rc != 0) {
5448 			device_printf(sc->dev,
5449 			    "failed to query RDMA parameters(2): %d.\n", rc);
5450 			return (rc);
5451 		}
5452 		sc->vres.qp.start = val[0];
5453 		sc->vres.qp.size = val[1] - val[0] + 1;
5454 		sc->vres.cq.start = val[2];
5455 		sc->vres.cq.size = val[3] - val[2] + 1;
5456 		sc->vres.ocq.start = val[4];
5457 		sc->vres.ocq.size = val[5] - val[4] + 1;
5458 
5459 		param[0] = FW_PARAM_PFVF(SRQ_START);
5460 		param[1] = FW_PARAM_PFVF(SRQ_END);
5461 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5462 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5463 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5464 		if (rc != 0) {
5465 			device_printf(sc->dev,
5466 			    "failed to query RDMA parameters(3): %d.\n", rc);
5467 			return (rc);
5468 		}
5469 		sc->vres.srq.start = val[0];
5470 		sc->vres.srq.size = val[1] - val[0] + 1;
5471 		sc->params.max_ordird_qp = val[2];
5472 		sc->params.max_ird_adapter = val[3];
5473 	}
5474 	if (sc->iscsicaps) {
5475 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5476 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5477 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5478 		if (rc != 0) {
5479 			device_printf(sc->dev,
5480 			    "failed to query iSCSI parameters: %d.\n", rc);
5481 			return (rc);
5482 		}
5483 		sc->vres.iscsi.start = val[0];
5484 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5485 	}
5486 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5487 		param[0] = FW_PARAM_PFVF(TLS_START);
5488 		param[1] = FW_PARAM_PFVF(TLS_END);
5489 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5490 		if (rc != 0) {
5491 			device_printf(sc->dev,
5492 			    "failed to query TLS parameters: %d.\n", rc);
5493 			return (rc);
5494 		}
5495 		sc->vres.key.start = val[0];
5496 		sc->vres.key.size = val[1] - val[0] + 1;
5497 	}
5498 
5499 	/*
5500 	 * We've got the params we wanted to query directly from the firmware.
5501 	 * Grab some others via other means.
5502 	 */
5503 	t4_init_sge_params(sc);
5504 	t4_init_tp_params(sc);
5505 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5506 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5507 
5508 	rc = t4_verify_chip_settings(sc);
5509 	if (rc != 0)
5510 		return (rc);
5511 	t4_init_rx_buf_info(sc);
5512 
5513 	return (rc);
5514 }
5515 
5516 #ifdef KERN_TLS
5517 static void
5518 ktls_tick(void *arg)
5519 {
5520 	struct adapter *sc;
5521 	uint32_t tstamp;
5522 
5523 	sc = arg;
5524 	tstamp = tcp_ts_getticks();
5525 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5526 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5527 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5528 }
5529 
5530 static int
5531 t6_config_kern_tls(struct adapter *sc, bool enable)
5532 {
5533 	int rc;
5534 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5535 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5536 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5537 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5538 
5539 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5540 	if (rc != 0) {
5541 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5542 		    enable ?  "enable" : "disable", rc);
5543 		return (rc);
5544 	}
5545 
5546 	if (enable) {
5547 		sc->flags |= KERN_TLS_ON;
5548 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5549 		    C_HARDCLOCK);
5550 	} else {
5551 		sc->flags &= ~KERN_TLS_ON;
5552 		callout_stop(&sc->ktls_tick);
5553 	}
5554 
5555 	return (rc);
5556 }
5557 #endif
5558 
5559 static int
5560 set_params__post_init(struct adapter *sc)
5561 {
5562 	uint32_t mask, param, val;
5563 #ifdef TCP_OFFLOAD
5564 	int i, v, shift;
5565 #endif
5566 
5567 	/* ask for encapsulated CPLs */
5568 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5569 	val = 1;
5570 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5571 
5572 	/* Enable 32b port caps if the firmware supports it. */
5573 	param = FW_PARAM_PFVF(PORT_CAPS32);
5574 	val = 1;
5575 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5576 		sc->params.port_caps32 = 1;
5577 
5578 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5579 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5580 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5581 	    V_MASKFILTER(val - 1));
5582 
5583 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5584 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5585 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5586 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5587 	val = 0;
5588 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5589 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5590 		    F_ATTACKFILTERENABLE);
5591 		val |= F_DROPERRORATTACK;
5592 	}
5593 	if (t4_drop_ip_fragments != 0) {
5594 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5595 		    F_FRAGMENTDROP);
5596 		val |= F_DROPERRORFRAG;
5597 	}
5598 	if (t4_drop_pkts_with_l2_errors != 0)
5599 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5600 	if (t4_drop_pkts_with_l3_errors != 0) {
5601 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5602 		    F_DROPERRORCSUMIP;
5603 	}
5604 	if (t4_drop_pkts_with_l4_errors != 0) {
5605 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5606 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5607 	}
5608 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5609 
5610 #ifdef TCP_OFFLOAD
5611 	/*
5612 	 * Override the TOE timers with user provided tunables.  This is not the
5613 	 * recommended way to change the timers (the firmware config file is) so
5614 	 * these tunables are not documented.
5615 	 *
5616 	 * All the timer tunables are in microseconds.
5617 	 */
5618 	if (t4_toe_keepalive_idle != 0) {
5619 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5620 		v &= M_KEEPALIVEIDLE;
5621 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5622 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5623 	}
5624 	if (t4_toe_keepalive_interval != 0) {
5625 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5626 		v &= M_KEEPALIVEINTVL;
5627 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5628 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5629 	}
5630 	if (t4_toe_keepalive_count != 0) {
5631 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5632 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5633 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5634 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5635 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5636 	}
5637 	if (t4_toe_rexmt_min != 0) {
5638 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5639 		v &= M_RXTMIN;
5640 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5641 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5642 	}
5643 	if (t4_toe_rexmt_max != 0) {
5644 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5645 		v &= M_RXTMAX;
5646 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5647 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5648 	}
5649 	if (t4_toe_rexmt_count != 0) {
5650 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5651 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5652 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5653 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5654 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5655 	}
5656 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5657 		if (t4_toe_rexmt_backoff[i] != -1) {
5658 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5659 			shift = (i & 3) << 3;
5660 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5661 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5662 		}
5663 	}
5664 #endif
5665 
5666 #ifdef KERN_TLS
5667 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS &&
5668 	    sc->toecaps & FW_CAPS_CONFIG_TOE) {
5669 		/*
5670 		 * Limit TOE connections to 2 reassembly "islands".  This is
5671 		 * required for TOE TLS connections to downgrade to plain TOE
5672 		 * connections if an unsupported TLS version or ciphersuite is
5673 		 * used.
5674 		 */
5675 		t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG,
5676 		    V_PASSMODE(M_PASSMODE), V_PASSMODE(2));
5677 	}
5678 
5679 	if (is_ktls(sc)) {
5680 		sc->tlst.inline_keys = t4_tls_inline_keys;
5681 		sc->tlst.combo_wrs = t4_tls_combo_wrs;
5682 		if (t4_kern_tls != 0 && is_t6(sc))
5683 			t6_config_kern_tls(sc, true);
5684 	}
5685 #endif
5686 	return (0);
5687 }
5688 
5689 #undef FW_PARAM_PFVF
5690 #undef FW_PARAM_DEV
5691 
5692 static void
5693 t4_set_desc(struct adapter *sc)
5694 {
5695 	char buf[128];
5696 	struct adapter_params *p = &sc->params;
5697 
5698 	snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
5699 
5700 	device_set_desc_copy(sc->dev, buf);
5701 }
5702 
5703 static inline void
5704 ifmedia_add4(struct ifmedia *ifm, int m)
5705 {
5706 
5707 	ifmedia_add(ifm, m, 0, NULL);
5708 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5709 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5710 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5711 }
5712 
5713 /*
5714  * This is the selected media, which is not quite the same as the active media.
5715  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5716  * and active are not the same, and "media: Ethernet selected" otherwise.
5717  */
5718 static void
5719 set_current_media(struct port_info *pi)
5720 {
5721 	struct link_config *lc;
5722 	struct ifmedia *ifm;
5723 	int mword;
5724 	u_int speed;
5725 
5726 	PORT_LOCK_ASSERT_OWNED(pi);
5727 
5728 	/* Leave current media alone if it's already set to IFM_NONE. */
5729 	ifm = &pi->media;
5730 	if (ifm->ifm_cur != NULL &&
5731 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5732 		return;
5733 
5734 	lc = &pi->link_cfg;
5735 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5736 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5737 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5738 		return;
5739 	}
5740 	mword = IFM_ETHER | IFM_FDX;
5741 	if (lc->requested_fc & PAUSE_TX)
5742 		mword |= IFM_ETH_TXPAUSE;
5743 	if (lc->requested_fc & PAUSE_RX)
5744 		mword |= IFM_ETH_RXPAUSE;
5745 	if (lc->requested_speed == 0)
5746 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5747 	else
5748 		speed = lc->requested_speed;
5749 	mword |= port_mword(pi, speed_to_fwcap(speed));
5750 	ifmedia_set(ifm, mword);
5751 }
5752 
5753 /*
5754  * Returns true if the ifmedia list for the port cannot change.
5755  */
5756 static bool
5757 fixed_ifmedia(struct port_info *pi)
5758 {
5759 
5760 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5761 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5762 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5763 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5764 	    pi->port_type == FW_PORT_TYPE_KX ||
5765 	    pi->port_type == FW_PORT_TYPE_KR ||
5766 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5767 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5768 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5769 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5770 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5771 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5772 }
5773 
5774 static void
5775 build_medialist(struct port_info *pi)
5776 {
5777 	uint32_t ss, speed;
5778 	int unknown, mword, bit;
5779 	struct link_config *lc;
5780 	struct ifmedia *ifm;
5781 
5782 	PORT_LOCK_ASSERT_OWNED(pi);
5783 
5784 	if (pi->flags & FIXED_IFMEDIA)
5785 		return;
5786 
5787 	/*
5788 	 * Rebuild the ifmedia list.
5789 	 */
5790 	ifm = &pi->media;
5791 	ifmedia_removeall(ifm);
5792 	lc = &pi->link_cfg;
5793 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5794 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5795 		MPASS(ss != 0);
5796 no_media:
5797 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5798 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5799 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5800 		return;
5801 	}
5802 
5803 	unknown = 0;
5804 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5805 		speed = 1 << bit;
5806 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5807 		if (ss & speed) {
5808 			mword = port_mword(pi, speed);
5809 			if (mword == IFM_NONE) {
5810 				goto no_media;
5811 			} else if (mword == IFM_UNKNOWN)
5812 				unknown++;
5813 			else
5814 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5815 		}
5816 	}
5817 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5818 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5819 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5820 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5821 
5822 	set_current_media(pi);
5823 }
5824 
5825 /*
5826  * Initialize the requested fields in the link config based on driver tunables.
5827  */
5828 static void
5829 init_link_config(struct port_info *pi)
5830 {
5831 	struct link_config *lc = &pi->link_cfg;
5832 
5833 	PORT_LOCK_ASSERT_OWNED(pi);
5834 
5835 	lc->requested_caps = 0;
5836 	lc->requested_speed = 0;
5837 
5838 	if (t4_autoneg == 0)
5839 		lc->requested_aneg = AUTONEG_DISABLE;
5840 	else if (t4_autoneg == 1)
5841 		lc->requested_aneg = AUTONEG_ENABLE;
5842 	else
5843 		lc->requested_aneg = AUTONEG_AUTO;
5844 
5845 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5846 	    PAUSE_AUTONEG);
5847 
5848 	if (t4_fec & FEC_AUTO)
5849 		lc->requested_fec = FEC_AUTO;
5850 	else if (t4_fec == 0)
5851 		lc->requested_fec = FEC_NONE;
5852 	else {
5853 		/* -1 is handled by the FEC_AUTO block above and not here. */
5854 		lc->requested_fec = t4_fec &
5855 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5856 		if (lc->requested_fec == 0)
5857 			lc->requested_fec = FEC_AUTO;
5858 	}
5859 	if (t4_force_fec < 0)
5860 		lc->force_fec = -1;
5861 	else if (t4_force_fec > 0)
5862 		lc->force_fec = 1;
5863 	else
5864 		lc->force_fec = 0;
5865 }
5866 
5867 /*
5868  * Makes sure that all requested settings comply with what's supported by the
5869  * port.  Returns the number of settings that were invalid and had to be fixed.
5870  */
5871 static int
5872 fixup_link_config(struct port_info *pi)
5873 {
5874 	int n = 0;
5875 	struct link_config *lc = &pi->link_cfg;
5876 	uint32_t fwspeed;
5877 
5878 	PORT_LOCK_ASSERT_OWNED(pi);
5879 
5880 	/* Speed (when not autonegotiating) */
5881 	if (lc->requested_speed != 0) {
5882 		fwspeed = speed_to_fwcap(lc->requested_speed);
5883 		if ((fwspeed & lc->pcaps) == 0) {
5884 			n++;
5885 			lc->requested_speed = 0;
5886 		}
5887 	}
5888 
5889 	/* Link autonegotiation */
5890 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5891 	    lc->requested_aneg == AUTONEG_DISABLE ||
5892 	    lc->requested_aneg == AUTONEG_AUTO);
5893 	if (lc->requested_aneg == AUTONEG_ENABLE &&
5894 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5895 		n++;
5896 		lc->requested_aneg = AUTONEG_AUTO;
5897 	}
5898 
5899 	/* Flow control */
5900 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5901 	if (lc->requested_fc & PAUSE_TX &&
5902 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5903 		n++;
5904 		lc->requested_fc &= ~PAUSE_TX;
5905 	}
5906 	if (lc->requested_fc & PAUSE_RX &&
5907 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
5908 		n++;
5909 		lc->requested_fc &= ~PAUSE_RX;
5910 	}
5911 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
5912 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
5913 		n++;
5914 		lc->requested_fc |= PAUSE_AUTONEG;
5915 	}
5916 
5917 	/* FEC */
5918 	if ((lc->requested_fec & FEC_RS &&
5919 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
5920 	    (lc->requested_fec & FEC_BASER_RS &&
5921 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
5922 		n++;
5923 		lc->requested_fec = FEC_AUTO;
5924 	}
5925 
5926 	return (n);
5927 }
5928 
5929 /*
5930  * Apply the requested L1 settings, which are expected to be valid, to the
5931  * hardware.
5932  */
5933 static int
5934 apply_link_config(struct port_info *pi)
5935 {
5936 	struct adapter *sc = pi->adapter;
5937 	struct link_config *lc = &pi->link_cfg;
5938 	int rc;
5939 
5940 #ifdef INVARIANTS
5941 	ASSERT_SYNCHRONIZED_OP(sc);
5942 	PORT_LOCK_ASSERT_OWNED(pi);
5943 
5944 	if (lc->requested_aneg == AUTONEG_ENABLE)
5945 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
5946 	if (!(lc->requested_fc & PAUSE_AUTONEG))
5947 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
5948 	if (lc->requested_fc & PAUSE_TX)
5949 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
5950 	if (lc->requested_fc & PAUSE_RX)
5951 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
5952 	if (lc->requested_fec & FEC_RS)
5953 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
5954 	if (lc->requested_fec & FEC_BASER_RS)
5955 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
5956 #endif
5957 	rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
5958 	if (rc != 0) {
5959 		/* Don't complain if the VF driver gets back an EPERM. */
5960 		if (!(sc->flags & IS_VF) || rc != FW_EPERM)
5961 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
5962 	} else {
5963 		/*
5964 		 * An L1_CFG will almost always result in a link-change event if
5965 		 * the link is up, and the driver will refresh the actual
5966 		 * fec/fc/etc. when the notification is processed.  If the link
5967 		 * is down then the actual settings are meaningless.
5968 		 *
5969 		 * This takes care of the case where a change in the L1 settings
5970 		 * may not result in a notification.
5971 		 */
5972 		if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
5973 			lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
5974 	}
5975 	return (rc);
5976 }
5977 
5978 #define FW_MAC_EXACT_CHUNK	7
5979 struct mcaddr_ctx {
5980 	struct ifnet *ifp;
5981 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
5982 	uint64_t hash;
5983 	int i;
5984 	int del;
5985 	int rc;
5986 };
5987 
5988 static u_int
5989 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
5990 {
5991 	struct mcaddr_ctx *ctx = arg;
5992 	struct vi_info *vi = ctx->ifp->if_softc;
5993 	struct port_info *pi = vi->pi;
5994 	struct adapter *sc = pi->adapter;
5995 
5996 	if (ctx->rc < 0)
5997 		return (0);
5998 
5999 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
6000 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
6001 	ctx->i++;
6002 
6003 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
6004 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
6005 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
6006 		if (ctx->rc < 0) {
6007 			int j;
6008 
6009 			for (j = 0; j < ctx->i; j++) {
6010 				if_printf(ctx->ifp,
6011 				    "failed to add mc address"
6012 				    " %02x:%02x:%02x:"
6013 				    "%02x:%02x:%02x rc=%d\n",
6014 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
6015 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
6016 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
6017 				    -ctx->rc);
6018 			}
6019 			return (0);
6020 		}
6021 		ctx->del = 0;
6022 		ctx->i = 0;
6023 	}
6024 
6025 	return (1);
6026 }
6027 
6028 /*
6029  * Program the port's XGMAC based on parameters in ifnet.  The caller also
6030  * indicates which parameters should be programmed (the rest are left alone).
6031  */
6032 int
6033 update_mac_settings(struct ifnet *ifp, int flags)
6034 {
6035 	int rc = 0;
6036 	struct vi_info *vi = ifp->if_softc;
6037 	struct port_info *pi = vi->pi;
6038 	struct adapter *sc = pi->adapter;
6039 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
6040 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
6041 
6042 	ASSERT_SYNCHRONIZED_OP(sc);
6043 	KASSERT(flags, ("%s: not told what to update.", __func__));
6044 
6045 	if (flags & XGMAC_MTU)
6046 		mtu = ifp->if_mtu;
6047 
6048 	if (flags & XGMAC_PROMISC)
6049 		promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
6050 
6051 	if (flags & XGMAC_ALLMULTI)
6052 		allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
6053 
6054 	if (flags & XGMAC_VLANEX)
6055 		vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
6056 
6057 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
6058 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
6059 		    allmulti, 1, vlanex, false);
6060 		if (rc) {
6061 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
6062 			    rc);
6063 			return (rc);
6064 		}
6065 	}
6066 
6067 	if (flags & XGMAC_UCADDR) {
6068 		uint8_t ucaddr[ETHER_ADDR_LEN];
6069 
6070 		bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
6071 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
6072 		    ucaddr, true, &vi->smt_idx);
6073 		if (rc < 0) {
6074 			rc = -rc;
6075 			if_printf(ifp, "change_mac failed: %d\n", rc);
6076 			return (rc);
6077 		} else {
6078 			vi->xact_addr_filt = rc;
6079 			rc = 0;
6080 		}
6081 	}
6082 
6083 	if (flags & XGMAC_MCADDRS) {
6084 		struct epoch_tracker et;
6085 		struct mcaddr_ctx ctx;
6086 		int j;
6087 
6088 		ctx.ifp = ifp;
6089 		ctx.hash = 0;
6090 		ctx.i = 0;
6091 		ctx.del = 1;
6092 		ctx.rc = 0;
6093 		/*
6094 		 * Unlike other drivers, we accumulate list of pointers into
6095 		 * interface address lists and we need to keep it safe even
6096 		 * after if_foreach_llmaddr() returns, thus we must enter the
6097 		 * network epoch.
6098 		 */
6099 		NET_EPOCH_ENTER(et);
6100 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6101 		if (ctx.rc < 0) {
6102 			NET_EPOCH_EXIT(et);
6103 			rc = -ctx.rc;
6104 			return (rc);
6105 		}
6106 		if (ctx.i > 0) {
6107 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6108 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6109 			NET_EPOCH_EXIT(et);
6110 			if (rc < 0) {
6111 				rc = -rc;
6112 				for (j = 0; j < ctx.i; j++) {
6113 					if_printf(ifp,
6114 					    "failed to add mcast address"
6115 					    " %02x:%02x:%02x:"
6116 					    "%02x:%02x:%02x rc=%d\n",
6117 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6118 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6119 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6120 					    rc);
6121 				}
6122 				return (rc);
6123 			}
6124 			ctx.del = 0;
6125 		} else
6126 			NET_EPOCH_EXIT(et);
6127 
6128 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6129 		if (rc != 0)
6130 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6131 			    rc);
6132 		if (ctx.del == 0) {
6133 			/* We clobbered the VXLAN entry if there was one. */
6134 			pi->vxlan_tcam_entry = false;
6135 		}
6136 	}
6137 
6138 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6139 	    pi->vxlan_tcam_entry == false) {
6140 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6141 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6142 		    true);
6143 		if (rc < 0) {
6144 			rc = -rc;
6145 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6146 			    rc);
6147 		} else {
6148 			MPASS(rc == sc->rawf_base + pi->port_id);
6149 			rc = 0;
6150 			pi->vxlan_tcam_entry = true;
6151 		}
6152 	}
6153 
6154 	return (rc);
6155 }
6156 
6157 /*
6158  * {begin|end}_synchronized_op must be called from the same thread.
6159  */
6160 int
6161 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6162     char *wmesg)
6163 {
6164 	int rc, pri;
6165 
6166 #ifdef WITNESS
6167 	/* the caller thinks it's ok to sleep, but is it really? */
6168 	if (flags & SLEEP_OK)
6169 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6170 		    "begin_synchronized_op");
6171 #endif
6172 
6173 	if (INTR_OK)
6174 		pri = PCATCH;
6175 	else
6176 		pri = 0;
6177 
6178 	ADAPTER_LOCK(sc);
6179 	for (;;) {
6180 
6181 		if (vi && IS_DOOMED(vi)) {
6182 			rc = ENXIO;
6183 			goto done;
6184 		}
6185 
6186 		if (!IS_BUSY(sc)) {
6187 			rc = 0;
6188 			break;
6189 		}
6190 
6191 		if (!(flags & SLEEP_OK)) {
6192 			rc = EBUSY;
6193 			goto done;
6194 		}
6195 
6196 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6197 			rc = EINTR;
6198 			goto done;
6199 		}
6200 	}
6201 
6202 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6203 	SET_BUSY(sc);
6204 #ifdef INVARIANTS
6205 	sc->last_op = wmesg;
6206 	sc->last_op_thr = curthread;
6207 	sc->last_op_flags = flags;
6208 #endif
6209 
6210 done:
6211 	if (!(flags & HOLD_LOCK) || rc)
6212 		ADAPTER_UNLOCK(sc);
6213 
6214 	return (rc);
6215 }
6216 
6217 /*
6218  * Tell if_ioctl and if_init that the VI is going away.  This is
6219  * special variant of begin_synchronized_op and must be paired with a
6220  * call to end_synchronized_op.
6221  */
6222 void
6223 doom_vi(struct adapter *sc, struct vi_info *vi)
6224 {
6225 
6226 	ADAPTER_LOCK(sc);
6227 	SET_DOOMED(vi);
6228 	wakeup(&sc->flags);
6229 	while (IS_BUSY(sc))
6230 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6231 	SET_BUSY(sc);
6232 #ifdef INVARIANTS
6233 	sc->last_op = "t4detach";
6234 	sc->last_op_thr = curthread;
6235 	sc->last_op_flags = 0;
6236 #endif
6237 	ADAPTER_UNLOCK(sc);
6238 }
6239 
6240 /*
6241  * {begin|end}_synchronized_op must be called from the same thread.
6242  */
6243 void
6244 end_synchronized_op(struct adapter *sc, int flags)
6245 {
6246 
6247 	if (flags & LOCK_HELD)
6248 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6249 	else
6250 		ADAPTER_LOCK(sc);
6251 
6252 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6253 	CLR_BUSY(sc);
6254 	wakeup(&sc->flags);
6255 	ADAPTER_UNLOCK(sc);
6256 }
6257 
6258 static int
6259 cxgbe_init_synchronized(struct vi_info *vi)
6260 {
6261 	struct port_info *pi = vi->pi;
6262 	struct adapter *sc = pi->adapter;
6263 	struct ifnet *ifp = vi->ifp;
6264 	int rc = 0, i;
6265 	struct sge_txq *txq;
6266 
6267 	ASSERT_SYNCHRONIZED_OP(sc);
6268 
6269 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
6270 		return (0);	/* already running */
6271 
6272 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6273 		return (rc);	/* error message displayed already */
6274 
6275 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6276 		return (rc); /* error message displayed already */
6277 
6278 	rc = update_mac_settings(ifp, XGMAC_ALL);
6279 	if (rc)
6280 		goto done;	/* error message displayed already */
6281 
6282 	PORT_LOCK(pi);
6283 	if (pi->up_vis == 0) {
6284 		t4_update_port_info(pi);
6285 		fixup_link_config(pi);
6286 		build_medialist(pi);
6287 		apply_link_config(pi);
6288 	}
6289 
6290 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6291 	if (rc != 0) {
6292 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6293 		PORT_UNLOCK(pi);
6294 		goto done;
6295 	}
6296 
6297 	/*
6298 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6299 	 * if this changes.
6300 	 */
6301 
6302 	for_each_txq(vi, i, txq) {
6303 		TXQ_LOCK(txq);
6304 		txq->eq.flags |= EQ_ENABLED;
6305 		TXQ_UNLOCK(txq);
6306 	}
6307 
6308 	/*
6309 	 * The first iq of the first port to come up is used for tracing.
6310 	 */
6311 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6312 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6313 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6314 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6315 		    V_QUEUENUMBER(sc->traceq));
6316 		pi->flags |= HAS_TRACEQ;
6317 	}
6318 
6319 	/* all ok */
6320 	pi->up_vis++;
6321 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
6322 	if (pi->link_cfg.link_ok)
6323 		t4_os_link_changed(pi);
6324 	PORT_UNLOCK(pi);
6325 
6326 	mtx_lock(&vi->tick_mtx);
6327 	if (ifp->if_get_counter == vi_get_counter)
6328 		callout_reset(&vi->tick, hz, vi_tick, vi);
6329 	else
6330 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6331 	mtx_unlock(&vi->tick_mtx);
6332 done:
6333 	if (rc != 0)
6334 		cxgbe_uninit_synchronized(vi);
6335 
6336 	return (rc);
6337 }
6338 
6339 /*
6340  * Idempotent.
6341  */
6342 static int
6343 cxgbe_uninit_synchronized(struct vi_info *vi)
6344 {
6345 	struct port_info *pi = vi->pi;
6346 	struct adapter *sc = pi->adapter;
6347 	struct ifnet *ifp = vi->ifp;
6348 	int rc, i;
6349 	struct sge_txq *txq;
6350 
6351 	ASSERT_SYNCHRONIZED_OP(sc);
6352 
6353 	if (!(vi->flags & VI_INIT_DONE)) {
6354 		if (__predict_false(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6355 			KASSERT(0, ("uninited VI is running"));
6356 			if_printf(ifp, "uninited VI with running ifnet.  "
6357 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6358 			    "if_drv_flags 0x%08x\n", vi->flags, ifp->if_flags,
6359 			    ifp->if_drv_flags);
6360 		}
6361 		return (0);
6362 	}
6363 
6364 	/*
6365 	 * Disable the VI so that all its data in either direction is discarded
6366 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6367 	 * tick) intact as the TP can deliver negative advice or data that it's
6368 	 * holding in its RAM (for an offloaded connection) even after the VI is
6369 	 * disabled.
6370 	 */
6371 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6372 	if (rc) {
6373 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6374 		return (rc);
6375 	}
6376 
6377 	for_each_txq(vi, i, txq) {
6378 		TXQ_LOCK(txq);
6379 		txq->eq.flags &= ~EQ_ENABLED;
6380 		TXQ_UNLOCK(txq);
6381 	}
6382 
6383 	mtx_lock(&vi->tick_mtx);
6384 	callout_stop(&vi->tick);
6385 	mtx_unlock(&vi->tick_mtx);
6386 
6387 	PORT_LOCK(pi);
6388 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6389 		PORT_UNLOCK(pi);
6390 		return (0);
6391 	}
6392 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
6393 	pi->up_vis--;
6394 	if (pi->up_vis > 0) {
6395 		PORT_UNLOCK(pi);
6396 		return (0);
6397 	}
6398 
6399 	pi->link_cfg.link_ok = false;
6400 	pi->link_cfg.speed = 0;
6401 	pi->link_cfg.link_down_rc = 255;
6402 	t4_os_link_changed(pi);
6403 	PORT_UNLOCK(pi);
6404 
6405 	return (0);
6406 }
6407 
6408 /*
6409  * It is ok for this function to fail midway and return right away.  t4_detach
6410  * will walk the entire sc->irq list and clean up whatever is valid.
6411  */
6412 int
6413 t4_setup_intr_handlers(struct adapter *sc)
6414 {
6415 	int rc, rid, p, q, v;
6416 	char s[8];
6417 	struct irq *irq;
6418 	struct port_info *pi;
6419 	struct vi_info *vi;
6420 	struct sge *sge = &sc->sge;
6421 	struct sge_rxq *rxq;
6422 #ifdef TCP_OFFLOAD
6423 	struct sge_ofld_rxq *ofld_rxq;
6424 #endif
6425 #ifdef DEV_NETMAP
6426 	struct sge_nm_rxq *nm_rxq;
6427 #endif
6428 #ifdef RSS
6429 	int nbuckets = rss_getnumbuckets();
6430 #endif
6431 
6432 	/*
6433 	 * Setup interrupts.
6434 	 */
6435 	irq = &sc->irq[0];
6436 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6437 	if (forwarding_intr_to_fwq(sc))
6438 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6439 
6440 	/* Multiple interrupts. */
6441 	if (sc->flags & IS_VF)
6442 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6443 		    ("%s: too few intr.", __func__));
6444 	else
6445 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6446 		    ("%s: too few intr.", __func__));
6447 
6448 	/* The first one is always error intr on PFs */
6449 	if (!(sc->flags & IS_VF)) {
6450 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6451 		if (rc != 0)
6452 			return (rc);
6453 		irq++;
6454 		rid++;
6455 	}
6456 
6457 	/* The second one is always the firmware event queue (first on VFs) */
6458 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6459 	if (rc != 0)
6460 		return (rc);
6461 	irq++;
6462 	rid++;
6463 
6464 	for_each_port(sc, p) {
6465 		pi = sc->port[p];
6466 		for_each_vi(pi, v, vi) {
6467 			vi->first_intr = rid - 1;
6468 
6469 			if (vi->nnmrxq > 0) {
6470 				int n = max(vi->nrxq, vi->nnmrxq);
6471 
6472 				rxq = &sge->rxq[vi->first_rxq];
6473 #ifdef DEV_NETMAP
6474 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6475 #endif
6476 				for (q = 0; q < n; q++) {
6477 					snprintf(s, sizeof(s), "%x%c%x", p,
6478 					    'a' + v, q);
6479 					if (q < vi->nrxq)
6480 						irq->rxq = rxq++;
6481 #ifdef DEV_NETMAP
6482 					if (q < vi->nnmrxq)
6483 						irq->nm_rxq = nm_rxq++;
6484 
6485 					if (irq->nm_rxq != NULL &&
6486 					    irq->rxq == NULL) {
6487 						/* Netmap rx only */
6488 						rc = t4_alloc_irq(sc, irq, rid,
6489 						    t4_nm_intr, irq->nm_rxq, s);
6490 					}
6491 					if (irq->nm_rxq != NULL &&
6492 					    irq->rxq != NULL) {
6493 						/* NIC and Netmap rx */
6494 						rc = t4_alloc_irq(sc, irq, rid,
6495 						    t4_vi_intr, irq, s);
6496 					}
6497 #endif
6498 					if (irq->rxq != NULL &&
6499 					    irq->nm_rxq == NULL) {
6500 						/* NIC rx only */
6501 						rc = t4_alloc_irq(sc, irq, rid,
6502 						    t4_intr, irq->rxq, s);
6503 					}
6504 					if (rc != 0)
6505 						return (rc);
6506 #ifdef RSS
6507 					if (q < vi->nrxq) {
6508 						bus_bind_intr(sc->dev, irq->res,
6509 						    rss_getcpu(q % nbuckets));
6510 					}
6511 #endif
6512 					irq++;
6513 					rid++;
6514 					vi->nintr++;
6515 				}
6516 			} else {
6517 				for_each_rxq(vi, q, rxq) {
6518 					snprintf(s, sizeof(s), "%x%c%x", p,
6519 					    'a' + v, q);
6520 					rc = t4_alloc_irq(sc, irq, rid,
6521 					    t4_intr, rxq, s);
6522 					if (rc != 0)
6523 						return (rc);
6524 #ifdef RSS
6525 					bus_bind_intr(sc->dev, irq->res,
6526 					    rss_getcpu(q % nbuckets));
6527 #endif
6528 					irq++;
6529 					rid++;
6530 					vi->nintr++;
6531 				}
6532 			}
6533 #ifdef TCP_OFFLOAD
6534 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6535 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6536 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6537 				    ofld_rxq, s);
6538 				if (rc != 0)
6539 					return (rc);
6540 				irq++;
6541 				rid++;
6542 				vi->nintr++;
6543 			}
6544 #endif
6545 		}
6546 	}
6547 	MPASS(irq == &sc->irq[sc->intr_count]);
6548 
6549 	return (0);
6550 }
6551 
6552 static void
6553 write_global_rss_key(struct adapter *sc)
6554 {
6555 #ifdef RSS
6556 	int i;
6557 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6558 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6559 
6560 	CTASSERT(RSS_KEYSIZE == 40);
6561 
6562 	rss_getkey((void *)&raw_rss_key[0]);
6563 	for (i = 0; i < nitems(rss_key); i++) {
6564 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6565 	}
6566 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6567 #endif
6568 }
6569 
6570 /*
6571  * Idempotent.
6572  */
6573 static int
6574 adapter_full_init(struct adapter *sc)
6575 {
6576 	int rc, i;
6577 
6578 	ASSERT_SYNCHRONIZED_OP(sc);
6579 
6580 	/*
6581 	 * queues that belong to the adapter (not any particular port).
6582 	 */
6583 	rc = t4_setup_adapter_queues(sc);
6584 	if (rc != 0)
6585 		return (rc);
6586 
6587 	for (i = 0; i < nitems(sc->tq); i++) {
6588 		if (sc->tq[i] != NULL)
6589 			continue;
6590 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6591 		    taskqueue_thread_enqueue, &sc->tq[i]);
6592 		if (sc->tq[i] == NULL) {
6593 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6594 			return (ENOMEM);
6595 		}
6596 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6597 		    device_get_nameunit(sc->dev), i);
6598 	}
6599 
6600 	if (!(sc->flags & IS_VF)) {
6601 		write_global_rss_key(sc);
6602 		t4_intr_enable(sc);
6603 	}
6604 	return (0);
6605 }
6606 
6607 int
6608 adapter_init(struct adapter *sc)
6609 {
6610 	int rc;
6611 
6612 	ASSERT_SYNCHRONIZED_OP(sc);
6613 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6614 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6615 	    ("%s: FULL_INIT_DONE already", __func__));
6616 
6617 	rc = adapter_full_init(sc);
6618 	if (rc != 0)
6619 		adapter_full_uninit(sc);
6620 	else
6621 		sc->flags |= FULL_INIT_DONE;
6622 
6623 	return (rc);
6624 }
6625 
6626 /*
6627  * Idempotent.
6628  */
6629 static void
6630 adapter_full_uninit(struct adapter *sc)
6631 {
6632 	int i;
6633 
6634 	t4_teardown_adapter_queues(sc);
6635 
6636 	for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
6637 		taskqueue_free(sc->tq[i]);
6638 		sc->tq[i] = NULL;
6639 	}
6640 
6641 	sc->flags &= ~FULL_INIT_DONE;
6642 }
6643 
6644 #ifdef RSS
6645 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6646     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6647     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6648     RSS_HASHTYPE_RSS_UDP_IPV6)
6649 
6650 /* Translates kernel hash types to hardware. */
6651 static int
6652 hashconfig_to_hashen(int hashconfig)
6653 {
6654 	int hashen = 0;
6655 
6656 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6657 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6658 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6659 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6660 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6661 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6662 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6663 	}
6664 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6665 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6666 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6667 	}
6668 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6669 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6670 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6671 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6672 
6673 	return (hashen);
6674 }
6675 
6676 /* Translates hardware hash types to kernel. */
6677 static int
6678 hashen_to_hashconfig(int hashen)
6679 {
6680 	int hashconfig = 0;
6681 
6682 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6683 		/*
6684 		 * If UDP hashing was enabled it must have been enabled for
6685 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6686 		 * enabling any 4-tuple hash is nonsense configuration.
6687 		 */
6688 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6689 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6690 
6691 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6692 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6693 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6694 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6695 	}
6696 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6697 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6698 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6699 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6700 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6701 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6702 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6703 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6704 
6705 	return (hashconfig);
6706 }
6707 #endif
6708 
6709 /*
6710  * Idempotent.
6711  */
6712 static int
6713 vi_full_init(struct vi_info *vi)
6714 {
6715 	struct adapter *sc = vi->adapter;
6716 	struct sge_rxq *rxq;
6717 	int rc, i, j;
6718 #ifdef RSS
6719 	int nbuckets = rss_getnumbuckets();
6720 	int hashconfig = rss_gethashconfig();
6721 	int extra;
6722 #endif
6723 
6724 	ASSERT_SYNCHRONIZED_OP(sc);
6725 
6726 	/*
6727 	 * Allocate tx/rx/fl queues for this VI.
6728 	 */
6729 	rc = t4_setup_vi_queues(vi);
6730 	if (rc != 0)
6731 		return (rc);
6732 
6733 	/*
6734 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6735 	 */
6736 	if (vi->nrxq > vi->rss_size) {
6737 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6738 		    "some queues will never receive traffic.\n", vi->nrxq,
6739 		    vi->rss_size);
6740 	} else if (vi->rss_size % vi->nrxq) {
6741 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6742 		    "expect uneven traffic distribution.\n", vi->nrxq,
6743 		    vi->rss_size);
6744 	}
6745 #ifdef RSS
6746 	if (vi->nrxq != nbuckets) {
6747 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6748 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6749 	}
6750 #endif
6751 	if (vi->rss == NULL)
6752 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6753 		    M_ZERO | M_WAITOK);
6754 	for (i = 0; i < vi->rss_size;) {
6755 #ifdef RSS
6756 		j = rss_get_indirection_to_bucket(i);
6757 		j %= vi->nrxq;
6758 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6759 		vi->rss[i++] = rxq->iq.abs_id;
6760 #else
6761 		for_each_rxq(vi, j, rxq) {
6762 			vi->rss[i++] = rxq->iq.abs_id;
6763 			if (i == vi->rss_size)
6764 				break;
6765 		}
6766 #endif
6767 	}
6768 
6769 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6770 	    vi->rss, vi->rss_size);
6771 	if (rc != 0) {
6772 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6773 		return (rc);
6774 	}
6775 
6776 #ifdef RSS
6777 	vi->hashen = hashconfig_to_hashen(hashconfig);
6778 
6779 	/*
6780 	 * We may have had to enable some hashes even though the global config
6781 	 * wants them disabled.  This is a potential problem that must be
6782 	 * reported to the user.
6783 	 */
6784 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6785 
6786 	/*
6787 	 * If we consider only the supported hash types, then the enabled hashes
6788 	 * are a superset of the requested hashes.  In other words, there cannot
6789 	 * be any supported hash that was requested but not enabled, but there
6790 	 * can be hashes that were not requested but had to be enabled.
6791 	 */
6792 	extra &= SUPPORTED_RSS_HASHTYPES;
6793 	MPASS((extra & hashconfig) == 0);
6794 
6795 	if (extra) {
6796 		CH_ALERT(vi,
6797 		    "global RSS config (0x%x) cannot be accommodated.\n",
6798 		    hashconfig);
6799 	}
6800 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6801 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6802 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6803 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6804 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6805 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6806 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6807 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6808 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6809 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6810 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6811 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6812 #else
6813 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6814 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6815 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6816 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6817 #endif
6818 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6819 	    0, 0);
6820 	if (rc != 0) {
6821 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6822 		return (rc);
6823 	}
6824 
6825 	return (0);
6826 }
6827 
6828 int
6829 vi_init(struct vi_info *vi)
6830 {
6831 	int rc;
6832 
6833 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6834 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6835 	    ("%s: VI_INIT_DONE already", __func__));
6836 
6837 	rc = vi_full_init(vi);
6838 	if (rc != 0)
6839 		vi_full_uninit(vi);
6840 	else
6841 		vi->flags |= VI_INIT_DONE;
6842 
6843 	return (rc);
6844 }
6845 
6846 /*
6847  * Idempotent.
6848  */
6849 static void
6850 vi_full_uninit(struct vi_info *vi)
6851 {
6852 
6853 	if (vi->flags & VI_INIT_DONE) {
6854 		quiesce_vi(vi);
6855 		free(vi->rss, M_CXGBE);
6856 		free(vi->nm_rss, M_CXGBE);
6857 	}
6858 
6859 	t4_teardown_vi_queues(vi);
6860 	vi->flags &= ~VI_INIT_DONE;
6861 }
6862 
6863 static void
6864 quiesce_txq(struct sge_txq *txq)
6865 {
6866 	struct sge_eq *eq = &txq->eq;
6867 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6868 
6869 	MPASS(eq->flags & EQ_SW_ALLOCATED);
6870 	MPASS(!(eq->flags & EQ_ENABLED));
6871 
6872 	/* Wait for the mp_ring to empty. */
6873 	while (!mp_ring_is_idle(txq->r)) {
6874 		mp_ring_check_drainage(txq->r, 4096);
6875 		pause("rquiesce", 1);
6876 	}
6877 	MPASS(txq->txp.npkt == 0);
6878 
6879 	if (eq->flags & EQ_HW_ALLOCATED) {
6880 		/*
6881 		 * Hardware is alive and working normally.  Wait for it to
6882 		 * finish and then wait for the driver to catch up and reclaim
6883 		 * all descriptors.
6884 		 */
6885 		while (spg->cidx != htobe16(eq->pidx))
6886 			pause("equiesce", 1);
6887 		while (eq->cidx != eq->pidx)
6888 			pause("dquiesce", 1);
6889 	} else {
6890 		/*
6891 		 * Hardware is unavailable.  Discard all pending tx and reclaim
6892 		 * descriptors directly.
6893 		 */
6894 		TXQ_LOCK(txq);
6895 		while (eq->cidx != eq->pidx) {
6896 			struct mbuf *m, *nextpkt;
6897 			struct tx_sdesc *txsd;
6898 
6899 			txsd = &txq->sdesc[eq->cidx];
6900 			for (m = txsd->m; m != NULL; m = nextpkt) {
6901 				nextpkt = m->m_nextpkt;
6902 				m->m_nextpkt = NULL;
6903 				m_freem(m);
6904 			}
6905 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
6906 		}
6907 		spg->pidx = spg->cidx = htobe16(eq->cidx);
6908 		TXQ_UNLOCK(txq);
6909 	}
6910 }
6911 
6912 static void
6913 quiesce_wrq(struct sge_wrq *wrq)
6914 {
6915 
6916 	/* XXXTX */
6917 }
6918 
6919 static void
6920 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
6921 {
6922 	/* Synchronize with the interrupt handler */
6923 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
6924 		pause("iqfree", 1);
6925 
6926 	if (fl != NULL) {
6927 		MPASS(iq->flags & IQ_HAS_FL);
6928 
6929 		mtx_lock(&sc->sfl_lock);
6930 		FL_LOCK(fl);
6931 		fl->flags |= FL_DOOMED;
6932 		FL_UNLOCK(fl);
6933 		callout_stop(&sc->sfl_callout);
6934 		mtx_unlock(&sc->sfl_lock);
6935 
6936 		KASSERT((fl->flags & FL_STARVING) == 0,
6937 		    ("%s: still starving", __func__));
6938 
6939 		/* Release all buffers if hardware is no longer available. */
6940 		if (!(iq->flags & IQ_HW_ALLOCATED))
6941 			free_fl_buffers(sc, fl);
6942 	}
6943 }
6944 
6945 /*
6946  * Wait for all activity on all the queues of the VI to complete.  It is assumed
6947  * that no new work is being enqueued by the hardware or the driver.  That part
6948  * should be arranged before calling this function.
6949  */
6950 static void
6951 quiesce_vi(struct vi_info *vi)
6952 {
6953 	int i;
6954 	struct adapter *sc = vi->adapter;
6955 	struct sge_rxq *rxq;
6956 	struct sge_txq *txq;
6957 #ifdef TCP_OFFLOAD
6958 	struct sge_ofld_rxq *ofld_rxq;
6959 #endif
6960 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6961 	struct sge_ofld_txq *ofld_txq;
6962 #endif
6963 
6964 	if (!(vi->flags & VI_INIT_DONE))
6965 		return;
6966 
6967 	for_each_txq(vi, i, txq) {
6968 		quiesce_txq(txq);
6969 	}
6970 
6971 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6972 	for_each_ofld_txq(vi, i, ofld_txq) {
6973 		quiesce_wrq(&ofld_txq->wrq);
6974 	}
6975 #endif
6976 
6977 	for_each_rxq(vi, i, rxq) {
6978 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
6979 	}
6980 
6981 #ifdef TCP_OFFLOAD
6982 	for_each_ofld_rxq(vi, i, ofld_rxq) {
6983 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
6984 	}
6985 #endif
6986 }
6987 
6988 static int
6989 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
6990     driver_intr_t *handler, void *arg, char *name)
6991 {
6992 	int rc;
6993 
6994 	irq->rid = rid;
6995 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
6996 	    RF_SHAREABLE | RF_ACTIVE);
6997 	if (irq->res == NULL) {
6998 		device_printf(sc->dev,
6999 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
7000 		return (ENOMEM);
7001 	}
7002 
7003 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
7004 	    NULL, handler, arg, &irq->tag);
7005 	if (rc != 0) {
7006 		device_printf(sc->dev,
7007 		    "failed to setup interrupt for rid %d, name %s: %d\n",
7008 		    rid, name, rc);
7009 	} else if (name)
7010 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
7011 
7012 	return (rc);
7013 }
7014 
7015 static int
7016 t4_free_irq(struct adapter *sc, struct irq *irq)
7017 {
7018 	if (irq->tag)
7019 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
7020 	if (irq->res)
7021 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
7022 
7023 	bzero(irq, sizeof(*irq));
7024 
7025 	return (0);
7026 }
7027 
7028 static void
7029 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
7030 {
7031 
7032 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
7033 	t4_get_regs(sc, buf, regs->len);
7034 }
7035 
7036 #define	A_PL_INDIR_CMD	0x1f8
7037 
7038 #define	S_PL_AUTOINC	31
7039 #define	M_PL_AUTOINC	0x1U
7040 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
7041 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
7042 
7043 #define	S_PL_VFID	20
7044 #define	M_PL_VFID	0xffU
7045 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
7046 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
7047 
7048 #define	S_PL_ADDR	0
7049 #define	M_PL_ADDR	0xfffffU
7050 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
7051 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
7052 
7053 #define	A_PL_INDIR_DATA	0x1fc
7054 
7055 static uint64_t
7056 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7057 {
7058 	u32 stats[2];
7059 
7060 	if (sc->flags & IS_VF) {
7061 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7062 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7063 	} else {
7064 		mtx_assert(&sc->reg_lock, MA_OWNED);
7065 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7066 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7067 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7068 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7069 	}
7070 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7071 }
7072 
7073 static void
7074 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7075 {
7076 
7077 #define GET_STAT(name) \
7078 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7079 
7080 	if (!(sc->flags & IS_VF))
7081 		mtx_lock(&sc->reg_lock);
7082 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7083 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7084 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7085 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7086 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7087 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7088 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7089 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7090 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7091 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7092 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7093 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7094 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7095 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7096 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7097 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7098 	if (!(sc->flags & IS_VF))
7099 		mtx_unlock(&sc->reg_lock);
7100 
7101 #undef GET_STAT
7102 }
7103 
7104 static void
7105 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7106 {
7107 	int reg;
7108 
7109 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7110 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7111 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7112 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7113 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7114 }
7115 
7116 static void
7117 vi_refresh_stats(struct vi_info *vi)
7118 {
7119 	struct timeval tv;
7120 	const struct timeval interval = {0, 250000};	/* 250ms */
7121 
7122 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7123 
7124 	if (vi->flags & VI_SKIP_STATS)
7125 		return;
7126 
7127 	getmicrotime(&tv);
7128 	timevalsub(&tv, &interval);
7129 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7130 		return;
7131 
7132 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7133 	getmicrotime(&vi->last_refreshed);
7134 }
7135 
7136 static void
7137 cxgbe_refresh_stats(struct vi_info *vi)
7138 {
7139 	u_int i, v, tnl_cong_drops, chan_map;
7140 	struct timeval tv;
7141 	const struct timeval interval = {0, 250000};	/* 250ms */
7142 	struct port_info *pi;
7143 	struct adapter *sc;
7144 
7145 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7146 
7147 	if (vi->flags & VI_SKIP_STATS)
7148 		return;
7149 
7150 	getmicrotime(&tv);
7151 	timevalsub(&tv, &interval);
7152 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7153 		return;
7154 
7155 	pi = vi->pi;
7156 	sc = vi->adapter;
7157 	tnl_cong_drops = 0;
7158 	t4_get_port_stats(sc, pi->port_id, &pi->stats);
7159 	chan_map = pi->rx_e_chan_map;
7160 	while (chan_map) {
7161 		i = ffs(chan_map) - 1;
7162 		mtx_lock(&sc->reg_lock);
7163 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7164 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7165 		mtx_unlock(&sc->reg_lock);
7166 		tnl_cong_drops += v;
7167 		chan_map &= ~(1 << i);
7168 	}
7169 	pi->tnl_cong_drops = tnl_cong_drops;
7170 	getmicrotime(&vi->last_refreshed);
7171 }
7172 
7173 static void
7174 cxgbe_tick(void *arg)
7175 {
7176 	struct vi_info *vi = arg;
7177 
7178 	MPASS(IS_MAIN_VI(vi));
7179 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7180 
7181 	cxgbe_refresh_stats(vi);
7182 	callout_schedule(&vi->tick, hz);
7183 }
7184 
7185 static void
7186 vi_tick(void *arg)
7187 {
7188 	struct vi_info *vi = arg;
7189 
7190 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7191 
7192 	vi_refresh_stats(vi);
7193 	callout_schedule(&vi->tick, hz);
7194 }
7195 
7196 /*
7197  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7198  */
7199 static char *caps_decoder[] = {
7200 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7201 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7202 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7203 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7204 	    "\006HASHFILTER\007ETHOFLD",
7205 	"\20\001TOE",					/* 4: TOE */
7206 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7207 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7208 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7209 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7210 	    "\007T10DIF"
7211 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7212 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7213 	    "\004TLS_HW",
7214 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7215 		    "\004PO_INITIATOR\005PO_TARGET",
7216 };
7217 
7218 void
7219 t4_sysctls(struct adapter *sc)
7220 {
7221 	struct sysctl_ctx_list *ctx = &sc->ctx;
7222 	struct sysctl_oid *oid;
7223 	struct sysctl_oid_list *children, *c0;
7224 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7225 
7226 	/*
7227 	 * dev.t4nex.X.
7228 	 */
7229 	oid = device_get_sysctl_tree(sc->dev);
7230 	c0 = children = SYSCTL_CHILDREN(oid);
7231 
7232 	sc->sc_do_rxcopy = 1;
7233 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7234 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7235 
7236 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7237 	    sc->params.nports, "# of ports");
7238 
7239 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7240 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7241 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7242 	    "available doorbells");
7243 
7244 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7245 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7246 
7247 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7248 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7249 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7250 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7251 
7252 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7253 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7254 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7255 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7256 
7257 	t4_sge_sysctls(sc, ctx, children);
7258 
7259 	sc->lro_timeout = 100;
7260 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7261 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7262 
7263 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7264 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7265 
7266 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7267 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7268 
7269 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7270 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7271 
7272 	if (sc->flags & IS_VF)
7273 		return;
7274 
7275 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7276 	    NULL, chip_rev(sc), "chip hardware revision");
7277 
7278 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7279 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7280 
7281 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7282 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7283 
7284 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7285 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7286 
7287 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7288 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7289 
7290 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7291 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7292 
7293 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7294 	    sc->er_version, 0, "expansion ROM version");
7295 
7296 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7297 	    sc->bs_version, 0, "bootstrap firmware version");
7298 
7299 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7300 	    NULL, sc->params.scfg_vers, "serial config version");
7301 
7302 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7303 	    NULL, sc->params.vpd_vers, "VPD version");
7304 
7305 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7306 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7307 
7308 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7309 	    sc->cfcsum, "config file checksum");
7310 
7311 #define SYSCTL_CAP(name, n, text) \
7312 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7313 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7314 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7315 	    "available " text " capabilities")
7316 
7317 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7318 	SYSCTL_CAP(linkcaps, 1, "link");
7319 	SYSCTL_CAP(switchcaps, 2, "switch");
7320 	SYSCTL_CAP(niccaps, 3, "NIC");
7321 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7322 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7323 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7324 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7325 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7326 #undef SYSCTL_CAP
7327 
7328 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7329 	    NULL, sc->tids.nftids, "number of filters");
7330 
7331 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7332 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7333 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7334 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7335 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7336 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7337 
7338 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7339 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7340 	    sysctl_loadavg, "A",
7341 	    "microprocessor load averages (debug firmwares only)");
7342 
7343 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7344 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7345 	    "I", "core Vdd (in mV)");
7346 
7347 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7348 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7349 	    sysctl_cpus, "A", "local CPUs");
7350 
7351 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7352 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7353 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7354 
7355 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7356 	    &sc->swintr, 0, "software triggered interrupts");
7357 
7358 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7359 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7360 	    "1 = reset adapter, 0 = zero reset counter");
7361 
7362 	/*
7363 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7364 	 */
7365 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7366 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7367 	    "logs and miscellaneous information");
7368 	children = SYSCTL_CHILDREN(oid);
7369 
7370 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7371 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7372 	    sysctl_cctrl, "A", "congestion control");
7373 
7374 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7375 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7376 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7377 
7378 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7379 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7380 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7381 
7382 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7383 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7384 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7385 
7386 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7387 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7388 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7389 
7390 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7391 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7392 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7393 
7394 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7395 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7396 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7397 
7398 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7399 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7400 	    sysctl_cim_la, "A", "CIM logic analyzer");
7401 
7402 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7403 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7404 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7405 
7406 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7407 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7408 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7409 
7410 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7411 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7412 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7413 
7414 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7415 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7416 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7417 
7418 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7419 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7420 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7421 
7422 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7423 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7424 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7425 
7426 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7427 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7428 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7429 
7430 	if (chip_id(sc) > CHELSIO_T4) {
7431 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7432 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7433 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7434 		    "CIM OBQ 6 (SGE0-RX)");
7435 
7436 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7437 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7438 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7439 		    "CIM OBQ 7 (SGE1-RX)");
7440 	}
7441 
7442 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7443 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7444 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7445 
7446 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7447 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7448 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7449 
7450 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7451 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7452 	    sysctl_cpl_stats, "A", "CPL statistics");
7453 
7454 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7455 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7456 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7457 
7458 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7459 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7460 	    sysctl_tid_stats, "A", "tid stats");
7461 
7462 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7463 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7464 	    sysctl_devlog, "A", "firmware's device log");
7465 
7466 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7467 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7468 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7469 
7470 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7471 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7472 	    sysctl_hw_sched, "A", "hardware scheduler ");
7473 
7474 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7475 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7476 	    sysctl_l2t, "A", "hardware L2 table");
7477 
7478 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7479 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7480 	    sysctl_smt, "A", "hardware source MAC table");
7481 
7482 #ifdef INET6
7483 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7484 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7485 	    sysctl_clip, "A", "active CLIP table entries");
7486 #endif
7487 
7488 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7489 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7490 	    sysctl_lb_stats, "A", "loopback statistics");
7491 
7492 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7493 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7494 	    sysctl_meminfo, "A", "memory regions");
7495 
7496 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7497 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7498 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7499 	    "A", "MPS TCAM entries");
7500 
7501 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7502 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7503 	    sysctl_path_mtus, "A", "path MTUs");
7504 
7505 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7506 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7507 	    sysctl_pm_stats, "A", "PM statistics");
7508 
7509 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7510 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7511 	    sysctl_rdma_stats, "A", "RDMA statistics");
7512 
7513 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7514 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7515 	    sysctl_tcp_stats, "A", "TCP statistics");
7516 
7517 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7518 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7519 	    sysctl_tids, "A", "TID information");
7520 
7521 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7522 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7523 	    sysctl_tp_err_stats, "A", "TP error statistics");
7524 
7525 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7526 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7527 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7528 
7529 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7530 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7531 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7532 
7533 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7534 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7535 	    sysctl_tp_la, "A", "TP logic analyzer");
7536 
7537 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7538 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7539 	    sysctl_tx_rate, "A", "Tx rate");
7540 
7541 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7542 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7543 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7544 
7545 	if (chip_id(sc) >= CHELSIO_T5) {
7546 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7547 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7548 		    sysctl_wcwr_stats, "A", "write combined work requests");
7549 	}
7550 
7551 #ifdef KERN_TLS
7552 	if (is_ktls(sc)) {
7553 		/*
7554 		 * dev.t4nex.0.tls.
7555 		 */
7556 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7557 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7558 		children = SYSCTL_CHILDREN(oid);
7559 
7560 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7561 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7562 		    "keys in work requests (1) or attempt to store TLS keys "
7563 		    "in card memory.");
7564 
7565 		if (is_t6(sc))
7566 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7567 			    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to "
7568 			    "combine TCB field updates with TLS record work "
7569 			    "requests.");
7570 	}
7571 #endif
7572 
7573 #ifdef TCP_OFFLOAD
7574 	if (is_offload(sc)) {
7575 		int i;
7576 		char s[4];
7577 
7578 		/*
7579 		 * dev.t4nex.X.toe.
7580 		 */
7581 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7582 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7583 		children = SYSCTL_CHILDREN(oid);
7584 
7585 		sc->tt.cong_algorithm = -1;
7586 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7587 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7588 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7589 		    "3 = highspeed)");
7590 
7591 		sc->tt.sndbuf = -1;
7592 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7593 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7594 
7595 		sc->tt.ddp = 0;
7596 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7597 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7598 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7599 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7600 
7601 		sc->tt.rx_coalesce = -1;
7602 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7603 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7604 
7605 		sc->tt.tls = 0;
7606 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7607 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7608 		    "Inline TLS allowed");
7609 
7610 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_ports",
7611 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7612 		    sysctl_tls_rx_ports, "I",
7613 		    "TCP ports that use inline TLS+TOE RX");
7614 
7615 		sc->tt.tls_rx_timeout = t4_toe_tls_rx_timeout;
7616 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_timeout",
7617 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7618 		    sysctl_tls_rx_timeout, "I",
7619 		    "Timeout in seconds to downgrade TLS sockets to plain TOE");
7620 
7621 		sc->tt.tx_align = -1;
7622 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7623 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7624 
7625 		sc->tt.tx_zcopy = 0;
7626 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7627 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7628 		    "Enable zero-copy aio_write(2)");
7629 
7630 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7631 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7632 		    "cop_managed_offloading", CTLFLAG_RW,
7633 		    &sc->tt.cop_managed_offloading, 0,
7634 		    "COP (Connection Offload Policy) controls all TOE offload");
7635 
7636 		sc->tt.autorcvbuf_inc = 16 * 1024;
7637 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7638 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7639 		    "autorcvbuf increment");
7640 
7641 		sc->tt.update_hc_on_pmtu_change = 1;
7642 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7643 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7644 		    &sc->tt.update_hc_on_pmtu_change, 0,
7645 		    "Update hostcache entry if the PMTU changes");
7646 
7647 		sc->tt.iso = 1;
7648 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7649 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7650 
7651 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7652 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7653 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7654 
7655 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7656 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7657 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7658 
7659 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7660 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7661 		    sysctl_tp_tick, "A", "DACK tick (us)");
7662 
7663 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7664 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7665 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7666 
7667 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7668 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7669 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7670 		    "Minimum retransmit interval (us)");
7671 
7672 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7673 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7674 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7675 		    "Maximum retransmit interval (us)");
7676 
7677 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7678 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7679 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7680 		    "Persist timer min (us)");
7681 
7682 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7683 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7684 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7685 		    "Persist timer max (us)");
7686 
7687 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7688 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7689 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7690 		    "Keepalive idle timer (us)");
7691 
7692 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7693 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7694 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7695 		    "Keepalive interval timer (us)");
7696 
7697 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7698 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7699 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7700 
7701 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7702 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7703 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7704 		    "FINWAIT2 timer (us)");
7705 
7706 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7707 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7708 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7709 		    "Number of SYN retransmissions before abort");
7710 
7711 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7712 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7713 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7714 		    "Number of retransmissions before abort");
7715 
7716 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7717 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7718 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7719 		    "Number of keepalive probes before abort");
7720 
7721 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7722 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7723 		    "TOE retransmit backoffs");
7724 		children = SYSCTL_CHILDREN(oid);
7725 		for (i = 0; i < 16; i++) {
7726 			snprintf(s, sizeof(s), "%u", i);
7727 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7728 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7729 			    i, sysctl_tp_backoff, "IU",
7730 			    "TOE retransmit backoff");
7731 		}
7732 	}
7733 #endif
7734 }
7735 
7736 void
7737 vi_sysctls(struct vi_info *vi)
7738 {
7739 	struct sysctl_ctx_list *ctx = &vi->ctx;
7740 	struct sysctl_oid *oid;
7741 	struct sysctl_oid_list *children;
7742 
7743 	/*
7744 	 * dev.v?(cxgbe|cxl).X.
7745 	 */
7746 	oid = device_get_sysctl_tree(vi->dev);
7747 	children = SYSCTL_CHILDREN(oid);
7748 
7749 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7750 	    vi->viid, "VI identifer");
7751 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7752 	    &vi->nrxq, 0, "# of rx queues");
7753 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7754 	    &vi->ntxq, 0, "# of tx queues");
7755 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7756 	    &vi->first_rxq, 0, "index of first rx queue");
7757 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7758 	    &vi->first_txq, 0, "index of first tx queue");
7759 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7760 	    vi->rss_base, "start of RSS indirection table");
7761 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7762 	    vi->rss_size, "size of RSS indirection table");
7763 
7764 	if (IS_MAIN_VI(vi)) {
7765 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7766 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7767 		    sysctl_noflowq, "IU",
7768 		    "Reserve queue 0 for non-flowid packets");
7769 	}
7770 
7771 	if (vi->adapter->flags & IS_VF) {
7772 		MPASS(vi->flags & TX_USES_VM_WR);
7773 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7774 		    NULL, 1, "use VM work requests for transmit");
7775 	} else {
7776 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7777 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7778 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7779 	}
7780 
7781 #ifdef TCP_OFFLOAD
7782 	if (vi->nofldrxq != 0) {
7783 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7784 		    &vi->nofldrxq, 0,
7785 		    "# of rx queues for offloaded TCP connections");
7786 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7787 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7788 		    "index of first TOE rx queue");
7789 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7790 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7791 		    sysctl_holdoff_tmr_idx_ofld, "I",
7792 		    "holdoff timer index for TOE queues");
7793 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7794 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7795 		    sysctl_holdoff_pktc_idx_ofld, "I",
7796 		    "holdoff packet counter index for TOE queues");
7797 	}
7798 #endif
7799 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7800 	if (vi->nofldtxq != 0) {
7801 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7802 		    &vi->nofldtxq, 0,
7803 		    "# of tx queues for TOE/ETHOFLD");
7804 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7805 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7806 		    "index of first TOE/ETHOFLD tx queue");
7807 	}
7808 #endif
7809 #ifdef DEV_NETMAP
7810 	if (vi->nnmrxq != 0) {
7811 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7812 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7813 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7814 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7815 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7816 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7817 		    "index of first netmap rx queue");
7818 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7819 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7820 		    "index of first netmap tx queue");
7821 	}
7822 #endif
7823 
7824 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7825 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7826 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7827 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7828 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7829 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7830 
7831 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7832 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7833 	    sysctl_qsize_rxq, "I", "rx queue size");
7834 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7835 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7836 	    sysctl_qsize_txq, "I", "tx queue size");
7837 }
7838 
7839 static void
7840 cxgbe_sysctls(struct port_info *pi)
7841 {
7842 	struct sysctl_ctx_list *ctx = &pi->ctx;
7843 	struct sysctl_oid *oid;
7844 	struct sysctl_oid_list *children, *children2;
7845 	struct adapter *sc = pi->adapter;
7846 	int i;
7847 	char name[16];
7848 	static char *tc_flags = {"\20\1USER"};
7849 
7850 	/*
7851 	 * dev.cxgbe.X.
7852 	 */
7853 	oid = device_get_sysctl_tree(pi->dev);
7854 	children = SYSCTL_CHILDREN(oid);
7855 
7856 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7857 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7858 	    sysctl_linkdnrc, "A", "reason why link is down");
7859 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7860 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7861 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7862 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
7863 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7864 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7865 		    sysctl_btphy, "I", "PHY firmware version");
7866 	}
7867 
7868 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7869 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7870 	    sysctl_pause_settings, "A",
7871 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7872 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
7873 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
7874 	    "FEC in use on the link");
7875 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
7876 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7877 	    sysctl_requested_fec, "A",
7878 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7879 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7880 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7881 	    "FEC recommended by the cable/transceiver");
7882 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7883 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7884 	    sysctl_autoneg, "I",
7885 	    "autonegotiation (-1 = not supported)");
7886 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
7887 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7888 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
7889 
7890 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
7891 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
7892 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7893 	    &pi->link_cfg.pcaps, 0, "port capabilities");
7894 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7895 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
7896 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7897 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7898 
7899 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7900 	    port_top_speed(pi), "max speed (in Gbps)");
7901 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7902 	    pi->mps_bg_map, "MPS buffer group map");
7903 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
7904 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
7905 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_c_chan", CTLFLAG_RD, NULL,
7906 	    pi->rx_c_chan, "TP rx c-channel");
7907 
7908 	if (sc->flags & IS_VF)
7909 		return;
7910 
7911 	/*
7912 	 * dev.(cxgbe|cxl).X.tc.
7913 	 */
7914 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
7915 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7916 	    "Tx scheduler traffic classes (cl_rl)");
7917 	children2 = SYSCTL_CHILDREN(oid);
7918 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
7919 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
7920 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
7921 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
7922 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
7923 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
7924 	for (i = 0; i < sc->params.nsched_cls; i++) {
7925 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
7926 
7927 		snprintf(name, sizeof(name), "%d", i);
7928 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
7929 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
7930 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
7931 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
7932 		    CTLFLAG_RD, &tc->state, 0, "current state");
7933 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
7934 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
7935 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
7936 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
7937 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
7938 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
7939 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7940 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
7941 		    "traffic class parameters");
7942 	}
7943 
7944 	/*
7945 	 * dev.cxgbe.X.stats.
7946 	 */
7947 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
7948 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
7949 	children = SYSCTL_CHILDREN(oid);
7950 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
7951 	    &pi->tx_parse_error, 0,
7952 	    "# of tx packets with invalid length or # of segments");
7953 
7954 #define T4_REGSTAT(name, stat, desc) \
7955     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
7956         CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
7957 	(is_t4(sc) ? PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L) : \
7958 	T5_PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L)), \
7959         sysctl_handle_t4_reg64, "QU", desc)
7960 
7961 /* We get these from port_stats and they may be stale by up to 1s */
7962 #define T4_PORTSTAT(name, desc) \
7963 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
7964 	    &pi->stats.name, desc)
7965 
7966 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
7967 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
7968 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
7969 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
7970 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
7971 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
7972 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
7973 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
7974 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
7975 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
7976 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
7977 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
7978 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
7979 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
7980 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
7981 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
7982 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
7983 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
7984 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
7985 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
7986 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
7987 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
7988 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
7989 
7990 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
7991 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
7992 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
7993 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
7994 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
7995 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
7996 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
7997 	if (is_t6(sc)) {
7998 		T4_PORTSTAT(rx_fcs_err,
7999 		    "# of frames received with bad FCS since last link up");
8000 	} else {
8001 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
8002 		    "# of frames received with bad FCS");
8003 	}
8004 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
8005 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
8006 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
8007 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
8008 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
8009 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
8010 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
8011 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
8012 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
8013 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
8014 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
8015 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
8016 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
8017 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
8018 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
8019 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
8020 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
8021 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
8022 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
8023 
8024 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
8025 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
8026 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
8027 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
8028 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
8029 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
8030 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
8031 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
8032 
8033 #undef T4_REGSTAT
8034 #undef T4_PORTSTAT
8035 }
8036 
8037 static int
8038 sysctl_int_array(SYSCTL_HANDLER_ARGS)
8039 {
8040 	int rc, *i, space = 0;
8041 	struct sbuf sb;
8042 
8043 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
8044 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
8045 		if (space)
8046 			sbuf_printf(&sb, " ");
8047 		sbuf_printf(&sb, "%d", *i);
8048 		space = 1;
8049 	}
8050 	rc = sbuf_finish(&sb);
8051 	sbuf_delete(&sb);
8052 	return (rc);
8053 }
8054 
8055 static int
8056 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
8057 {
8058 	int rc;
8059 	struct sbuf *sb;
8060 
8061 	rc = sysctl_wire_old_buffer(req, 0);
8062 	if (rc != 0)
8063 		return(rc);
8064 
8065 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8066 	if (sb == NULL)
8067 		return (ENOMEM);
8068 
8069 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8070 	rc = sbuf_finish(sb);
8071 	sbuf_delete(sb);
8072 
8073 	return (rc);
8074 }
8075 
8076 static int
8077 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8078 {
8079 	int rc;
8080 	struct sbuf *sb;
8081 
8082 	rc = sysctl_wire_old_buffer(req, 0);
8083 	if (rc != 0)
8084 		return(rc);
8085 
8086 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8087 	if (sb == NULL)
8088 		return (ENOMEM);
8089 
8090 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8091 	rc = sbuf_finish(sb);
8092 	sbuf_delete(sb);
8093 
8094 	return (rc);
8095 }
8096 
8097 static int
8098 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8099 {
8100 	struct port_info *pi = arg1;
8101 	int op = arg2;
8102 	struct adapter *sc = pi->adapter;
8103 	u_int v;
8104 	int rc;
8105 
8106 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8107 	if (rc)
8108 		return (rc);
8109 	if (hw_off_limits(sc))
8110 		rc = ENXIO;
8111 	else {
8112 		/* XXX: magic numbers */
8113 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8114 		    op ? 0x20 : 0xc820, &v);
8115 	}
8116 	end_synchronized_op(sc, 0);
8117 	if (rc)
8118 		return (rc);
8119 	if (op == 0)
8120 		v /= 256;
8121 
8122 	rc = sysctl_handle_int(oidp, &v, 0, req);
8123 	return (rc);
8124 }
8125 
8126 static int
8127 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8128 {
8129 	struct vi_info *vi = arg1;
8130 	int rc, val;
8131 
8132 	val = vi->rsrv_noflowq;
8133 	rc = sysctl_handle_int(oidp, &val, 0, req);
8134 	if (rc != 0 || req->newptr == NULL)
8135 		return (rc);
8136 
8137 	if ((val >= 1) && (vi->ntxq > 1))
8138 		vi->rsrv_noflowq = 1;
8139 	else
8140 		vi->rsrv_noflowq = 0;
8141 
8142 	return (rc);
8143 }
8144 
8145 static int
8146 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8147 {
8148 	struct vi_info *vi = arg1;
8149 	struct adapter *sc = vi->adapter;
8150 	int rc, val, i;
8151 
8152 	MPASS(!(sc->flags & IS_VF));
8153 
8154 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8155 	rc = sysctl_handle_int(oidp, &val, 0, req);
8156 	if (rc != 0 || req->newptr == NULL)
8157 		return (rc);
8158 
8159 	if (val != 0 && val != 1)
8160 		return (EINVAL);
8161 
8162 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8163 	    "t4txvm");
8164 	if (rc)
8165 		return (rc);
8166 	if (hw_off_limits(sc))
8167 		rc = ENXIO;
8168 	else if (vi->ifp->if_drv_flags & IFF_DRV_RUNNING) {
8169 		/*
8170 		 * We don't want parse_pkt to run with one setting (VF or PF)
8171 		 * and then eth_tx to see a different setting but still use
8172 		 * stale information calculated by parse_pkt.
8173 		 */
8174 		rc = EBUSY;
8175 	} else {
8176 		struct port_info *pi = vi->pi;
8177 		struct sge_txq *txq;
8178 		uint32_t ctrl0;
8179 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8180 
8181 		if (val) {
8182 			vi->flags |= TX_USES_VM_WR;
8183 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
8184 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8185 			    V_TXPKT_INTF(pi->tx_chan));
8186 			if (!(sc->flags & IS_VF))
8187 				npkt--;
8188 		} else {
8189 			vi->flags &= ~TX_USES_VM_WR;
8190 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
8191 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8192 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8193 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8194 		}
8195 		for_each_txq(vi, i, txq) {
8196 			txq->cpl_ctrl0 = ctrl0;
8197 			txq->txp.max_npkt = npkt;
8198 		}
8199 	}
8200 	end_synchronized_op(sc, LOCK_HELD);
8201 	return (rc);
8202 }
8203 
8204 static int
8205 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8206 {
8207 	struct vi_info *vi = arg1;
8208 	struct adapter *sc = vi->adapter;
8209 	int idx, rc, i;
8210 	struct sge_rxq *rxq;
8211 	uint8_t v;
8212 
8213 	idx = vi->tmr_idx;
8214 
8215 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8216 	if (rc != 0 || req->newptr == NULL)
8217 		return (rc);
8218 
8219 	if (idx < 0 || idx >= SGE_NTIMERS)
8220 		return (EINVAL);
8221 
8222 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8223 	    "t4tmr");
8224 	if (rc)
8225 		return (rc);
8226 
8227 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8228 	for_each_rxq(vi, i, rxq) {
8229 #ifdef atomic_store_rel_8
8230 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8231 #else
8232 		rxq->iq.intr_params = v;
8233 #endif
8234 	}
8235 	vi->tmr_idx = idx;
8236 
8237 	end_synchronized_op(sc, LOCK_HELD);
8238 	return (0);
8239 }
8240 
8241 static int
8242 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8243 {
8244 	struct vi_info *vi = arg1;
8245 	struct adapter *sc = vi->adapter;
8246 	int idx, rc;
8247 
8248 	idx = vi->pktc_idx;
8249 
8250 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8251 	if (rc != 0 || req->newptr == NULL)
8252 		return (rc);
8253 
8254 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8255 		return (EINVAL);
8256 
8257 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8258 	    "t4pktc");
8259 	if (rc)
8260 		return (rc);
8261 
8262 	if (vi->flags & VI_INIT_DONE)
8263 		rc = EBUSY; /* cannot be changed once the queues are created */
8264 	else
8265 		vi->pktc_idx = idx;
8266 
8267 	end_synchronized_op(sc, LOCK_HELD);
8268 	return (rc);
8269 }
8270 
8271 static int
8272 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8273 {
8274 	struct vi_info *vi = arg1;
8275 	struct adapter *sc = vi->adapter;
8276 	int qsize, rc;
8277 
8278 	qsize = vi->qsize_rxq;
8279 
8280 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8281 	if (rc != 0 || req->newptr == NULL)
8282 		return (rc);
8283 
8284 	if (qsize < 128 || (qsize & 7))
8285 		return (EINVAL);
8286 
8287 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8288 	    "t4rxqs");
8289 	if (rc)
8290 		return (rc);
8291 
8292 	if (vi->flags & VI_INIT_DONE)
8293 		rc = EBUSY; /* cannot be changed once the queues are created */
8294 	else
8295 		vi->qsize_rxq = qsize;
8296 
8297 	end_synchronized_op(sc, LOCK_HELD);
8298 	return (rc);
8299 }
8300 
8301 static int
8302 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8303 {
8304 	struct vi_info *vi = arg1;
8305 	struct adapter *sc = vi->adapter;
8306 	int qsize, rc;
8307 
8308 	qsize = vi->qsize_txq;
8309 
8310 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8311 	if (rc != 0 || req->newptr == NULL)
8312 		return (rc);
8313 
8314 	if (qsize < 128 || qsize > 65536)
8315 		return (EINVAL);
8316 
8317 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8318 	    "t4txqs");
8319 	if (rc)
8320 		return (rc);
8321 
8322 	if (vi->flags & VI_INIT_DONE)
8323 		rc = EBUSY; /* cannot be changed once the queues are created */
8324 	else
8325 		vi->qsize_txq = qsize;
8326 
8327 	end_synchronized_op(sc, LOCK_HELD);
8328 	return (rc);
8329 }
8330 
8331 static int
8332 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8333 {
8334 	struct port_info *pi = arg1;
8335 	struct adapter *sc = pi->adapter;
8336 	struct link_config *lc = &pi->link_cfg;
8337 	int rc;
8338 
8339 	if (req->newptr == NULL) {
8340 		struct sbuf *sb;
8341 		static char *bits = "\20\1RX\2TX\3AUTO";
8342 
8343 		rc = sysctl_wire_old_buffer(req, 0);
8344 		if (rc != 0)
8345 			return(rc);
8346 
8347 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8348 		if (sb == NULL)
8349 			return (ENOMEM);
8350 
8351 		if (lc->link_ok) {
8352 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8353 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8354 		} else {
8355 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8356 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8357 		}
8358 		rc = sbuf_finish(sb);
8359 		sbuf_delete(sb);
8360 	} else {
8361 		char s[2];
8362 		int n;
8363 
8364 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8365 		    PAUSE_AUTONEG));
8366 		s[1] = 0;
8367 
8368 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8369 		if (rc != 0)
8370 			return(rc);
8371 
8372 		if (s[1] != 0)
8373 			return (EINVAL);
8374 		if (s[0] < '0' || s[0] > '9')
8375 			return (EINVAL);	/* not a number */
8376 		n = s[0] - '0';
8377 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8378 			return (EINVAL);	/* some other bit is set too */
8379 
8380 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8381 		    "t4PAUSE");
8382 		if (rc)
8383 			return (rc);
8384 		if (!hw_off_limits(sc)) {
8385 			PORT_LOCK(pi);
8386 			lc->requested_fc = n;
8387 			fixup_link_config(pi);
8388 			if (pi->up_vis > 0)
8389 				rc = apply_link_config(pi);
8390 			set_current_media(pi);
8391 			PORT_UNLOCK(pi);
8392 		}
8393 		end_synchronized_op(sc, 0);
8394 	}
8395 
8396 	return (rc);
8397 }
8398 
8399 static int
8400 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
8401 {
8402 	struct port_info *pi = arg1;
8403 	struct link_config *lc = &pi->link_cfg;
8404 	int rc;
8405 	struct sbuf *sb;
8406 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2";
8407 
8408 	rc = sysctl_wire_old_buffer(req, 0);
8409 	if (rc != 0)
8410 		return(rc);
8411 
8412 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8413 	if (sb == NULL)
8414 		return (ENOMEM);
8415 	if (lc->link_ok)
8416 		sbuf_printf(sb, "%b", lc->fec, bits);
8417 	else
8418 		sbuf_printf(sb, "no link");
8419 	rc = sbuf_finish(sb);
8420 	sbuf_delete(sb);
8421 
8422 	return (rc);
8423 }
8424 
8425 static int
8426 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
8427 {
8428 	struct port_info *pi = arg1;
8429 	struct adapter *sc = pi->adapter;
8430 	struct link_config *lc = &pi->link_cfg;
8431 	int rc;
8432 	int8_t old;
8433 
8434 	if (req->newptr == NULL) {
8435 		struct sbuf *sb;
8436 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8437 		    "\5RSVD3\6auto\7module";
8438 
8439 		rc = sysctl_wire_old_buffer(req, 0);
8440 		if (rc != 0)
8441 			return(rc);
8442 
8443 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8444 		if (sb == NULL)
8445 			return (ENOMEM);
8446 
8447 		sbuf_printf(sb, "%b", lc->requested_fec, bits);
8448 		rc = sbuf_finish(sb);
8449 		sbuf_delete(sb);
8450 	} else {
8451 		char s[8];
8452 		int n;
8453 
8454 		snprintf(s, sizeof(s), "%d",
8455 		    lc->requested_fec == FEC_AUTO ? -1 :
8456 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8457 
8458 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8459 		if (rc != 0)
8460 			return(rc);
8461 
8462 		n = strtol(&s[0], NULL, 0);
8463 		if (n < 0 || n & FEC_AUTO)
8464 			n = FEC_AUTO;
8465 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8466 			return (EINVAL);/* some other bit is set too */
8467 
8468 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8469 		    "t4reqf");
8470 		if (rc)
8471 			return (rc);
8472 		PORT_LOCK(pi);
8473 		old = lc->requested_fec;
8474 		if (n == FEC_AUTO)
8475 			lc->requested_fec = FEC_AUTO;
8476 		else if (n == 0 || n == FEC_NONE)
8477 			lc->requested_fec = FEC_NONE;
8478 		else {
8479 			if ((lc->pcaps |
8480 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8481 			    lc->pcaps) {
8482 				rc = ENOTSUP;
8483 				goto done;
8484 			}
8485 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8486 			    FEC_MODULE);
8487 		}
8488 		if (!hw_off_limits(sc)) {
8489 			fixup_link_config(pi);
8490 			if (pi->up_vis > 0) {
8491 				rc = apply_link_config(pi);
8492 				if (rc != 0) {
8493 					lc->requested_fec = old;
8494 					if (rc == FW_EPROTO)
8495 						rc = ENOTSUP;
8496 				}
8497 			}
8498 		}
8499 done:
8500 		PORT_UNLOCK(pi);
8501 		end_synchronized_op(sc, 0);
8502 	}
8503 
8504 	return (rc);
8505 }
8506 
8507 static int
8508 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8509 {
8510 	struct port_info *pi = arg1;
8511 	struct adapter *sc = pi->adapter;
8512 	struct link_config *lc = &pi->link_cfg;
8513 	int rc;
8514 	int8_t fec;
8515 	struct sbuf *sb;
8516 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8517 
8518 	rc = sysctl_wire_old_buffer(req, 0);
8519 	if (rc != 0)
8520 		return (rc);
8521 
8522 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8523 	if (sb == NULL)
8524 		return (ENOMEM);
8525 
8526 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8527 		rc = EBUSY;
8528 		goto done;
8529 	}
8530 	if (hw_off_limits(sc)) {
8531 		rc = ENXIO;
8532 		goto done;
8533 	}
8534 	PORT_LOCK(pi);
8535 	if (pi->up_vis == 0) {
8536 		/*
8537 		 * If all the interfaces are administratively down the firmware
8538 		 * does not report transceiver changes.  Refresh port info here.
8539 		 * This is the only reason we have a synchronized op in this
8540 		 * function.  Just PORT_LOCK would have been enough otherwise.
8541 		 */
8542 		t4_update_port_info(pi);
8543 	}
8544 
8545 	fec = lc->fec_hint;
8546 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8547 	    !fec_supported(lc->pcaps)) {
8548 		sbuf_printf(sb, "n/a");
8549 	} else {
8550 		if (fec == 0)
8551 			fec = FEC_NONE;
8552 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8553 	}
8554 	rc = sbuf_finish(sb);
8555 	PORT_UNLOCK(pi);
8556 done:
8557 	sbuf_delete(sb);
8558 	end_synchronized_op(sc, 0);
8559 
8560 	return (rc);
8561 }
8562 
8563 static int
8564 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8565 {
8566 	struct port_info *pi = arg1;
8567 	struct adapter *sc = pi->adapter;
8568 	struct link_config *lc = &pi->link_cfg;
8569 	int rc, val;
8570 
8571 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8572 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8573 	else
8574 		val = -1;
8575 	rc = sysctl_handle_int(oidp, &val, 0, req);
8576 	if (rc != 0 || req->newptr == NULL)
8577 		return (rc);
8578 	if (val == 0)
8579 		val = AUTONEG_DISABLE;
8580 	else if (val == 1)
8581 		val = AUTONEG_ENABLE;
8582 	else
8583 		val = AUTONEG_AUTO;
8584 
8585 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8586 	    "t4aneg");
8587 	if (rc)
8588 		return (rc);
8589 	PORT_LOCK(pi);
8590 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8591 		rc = ENOTSUP;
8592 		goto done;
8593 	}
8594 	lc->requested_aneg = val;
8595 	if (!hw_off_limits(sc)) {
8596 		fixup_link_config(pi);
8597 		if (pi->up_vis > 0)
8598 			rc = apply_link_config(pi);
8599 		set_current_media(pi);
8600 	}
8601 done:
8602 	PORT_UNLOCK(pi);
8603 	end_synchronized_op(sc, 0);
8604 	return (rc);
8605 }
8606 
8607 static int
8608 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
8609 {
8610 	struct port_info *pi = arg1;
8611 	struct adapter *sc = pi->adapter;
8612 	struct link_config *lc = &pi->link_cfg;
8613 	int rc, val;
8614 
8615 	val = lc->force_fec;
8616 	MPASS(val >= -1 && val <= 1);
8617 	rc = sysctl_handle_int(oidp, &val, 0, req);
8618 	if (rc != 0 || req->newptr == NULL)
8619 		return (rc);
8620 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
8621 		return (ENOTSUP);
8622 	if (val < -1 || val > 1)
8623 		return (EINVAL);
8624 
8625 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
8626 	if (rc)
8627 		return (rc);
8628 	PORT_LOCK(pi);
8629 	lc->force_fec = val;
8630 	if (!hw_off_limits(sc)) {
8631 		fixup_link_config(pi);
8632 		if (pi->up_vis > 0)
8633 			rc = apply_link_config(pi);
8634 	}
8635 	PORT_UNLOCK(pi);
8636 	end_synchronized_op(sc, 0);
8637 	return (rc);
8638 }
8639 
8640 static int
8641 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8642 {
8643 	struct adapter *sc = arg1;
8644 	int rc, reg = arg2;
8645 	uint64_t val;
8646 
8647 	mtx_lock(&sc->reg_lock);
8648 	if (hw_off_limits(sc))
8649 		rc = ENXIO;
8650 	else {
8651 		rc = 0;
8652 		val = t4_read_reg64(sc, reg);
8653 	}
8654 	mtx_unlock(&sc->reg_lock);
8655 	if (rc == 0)
8656 		rc = sysctl_handle_64(oidp, &val, 0, req);
8657 	return (rc);
8658 }
8659 
8660 static int
8661 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8662 {
8663 	struct adapter *sc = arg1;
8664 	int rc, t;
8665 	uint32_t param, val;
8666 
8667 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8668 	if (rc)
8669 		return (rc);
8670 	if (hw_off_limits(sc))
8671 		rc = ENXIO;
8672 	else {
8673 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8674 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8675 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8676 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8677 	}
8678 	end_synchronized_op(sc, 0);
8679 	if (rc)
8680 		return (rc);
8681 
8682 	/* unknown is returned as 0 but we display -1 in that case */
8683 	t = val == 0 ? -1 : val;
8684 
8685 	rc = sysctl_handle_int(oidp, &t, 0, req);
8686 	return (rc);
8687 }
8688 
8689 static int
8690 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8691 {
8692 	struct adapter *sc = arg1;
8693 	int rc;
8694 	uint32_t param, val;
8695 
8696 	if (sc->params.core_vdd == 0) {
8697 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8698 		    "t4vdd");
8699 		if (rc)
8700 			return (rc);
8701 		if (hw_off_limits(sc))
8702 			rc = ENXIO;
8703 		else {
8704 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8705 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8706 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8707 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8708 			    &param, &val);
8709 		}
8710 		end_synchronized_op(sc, 0);
8711 		if (rc)
8712 			return (rc);
8713 		sc->params.core_vdd = val;
8714 	}
8715 
8716 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8717 }
8718 
8719 static int
8720 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8721 {
8722 	struct adapter *sc = arg1;
8723 	int rc, v;
8724 	uint32_t param, val;
8725 
8726 	v = sc->sensor_resets;
8727 	rc = sysctl_handle_int(oidp, &v, 0, req);
8728 	if (rc != 0 || req->newptr == NULL || v <= 0)
8729 		return (rc);
8730 
8731 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8732 	    chip_id(sc) < CHELSIO_T5)
8733 		return (ENOTSUP);
8734 
8735 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8736 	if (rc)
8737 		return (rc);
8738 	if (hw_off_limits(sc))
8739 		rc = ENXIO;
8740 	else {
8741 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8742 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8743 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8744 		val = 1;
8745 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8746 	}
8747 	end_synchronized_op(sc, 0);
8748 	if (rc == 0)
8749 		sc->sensor_resets++;
8750 	return (rc);
8751 }
8752 
8753 static int
8754 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8755 {
8756 	struct adapter *sc = arg1;
8757 	struct sbuf *sb;
8758 	int rc;
8759 	uint32_t param, val;
8760 
8761 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8762 	if (rc)
8763 		return (rc);
8764 	if (hw_off_limits(sc))
8765 		rc = ENXIO;
8766 	else {
8767 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8768 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8769 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8770 	}
8771 	end_synchronized_op(sc, 0);
8772 	if (rc)
8773 		return (rc);
8774 
8775 	rc = sysctl_wire_old_buffer(req, 0);
8776 	if (rc != 0)
8777 		return (rc);
8778 
8779 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8780 	if (sb == NULL)
8781 		return (ENOMEM);
8782 
8783 	if (val == 0xffffffff) {
8784 		/* Only debug and custom firmwares report load averages. */
8785 		sbuf_printf(sb, "not available");
8786 	} else {
8787 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8788 		    (val >> 16) & 0xff);
8789 	}
8790 	rc = sbuf_finish(sb);
8791 	sbuf_delete(sb);
8792 
8793 	return (rc);
8794 }
8795 
8796 static int
8797 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8798 {
8799 	struct adapter *sc = arg1;
8800 	struct sbuf *sb;
8801 	int rc, i;
8802 	uint16_t incr[NMTUS][NCCTRL_WIN];
8803 	static const char *dec_fac[] = {
8804 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8805 		"0.9375"
8806 	};
8807 
8808 	rc = sysctl_wire_old_buffer(req, 0);
8809 	if (rc != 0)
8810 		return (rc);
8811 
8812 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8813 	if (sb == NULL)
8814 		return (ENOMEM);
8815 
8816 	mtx_lock(&sc->reg_lock);
8817 	if (hw_off_limits(sc))
8818 		rc = ENXIO;
8819 	else
8820 		t4_read_cong_tbl(sc, incr);
8821 	mtx_unlock(&sc->reg_lock);
8822 	if (rc)
8823 		goto done;
8824 
8825 	for (i = 0; i < NCCTRL_WIN; ++i) {
8826 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8827 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8828 		    incr[5][i], incr[6][i], incr[7][i]);
8829 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8830 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8831 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8832 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8833 	}
8834 
8835 	rc = sbuf_finish(sb);
8836 done:
8837 	sbuf_delete(sb);
8838 	return (rc);
8839 }
8840 
8841 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8842 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8843 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8844 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8845 };
8846 
8847 static int
8848 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8849 {
8850 	struct adapter *sc = arg1;
8851 	struct sbuf *sb;
8852 	int rc, i, n, qid = arg2;
8853 	uint32_t *buf, *p;
8854 	char *qtype;
8855 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8856 
8857 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8858 	    ("%s: bad qid %d\n", __func__, qid));
8859 
8860 	if (qid < CIM_NUM_IBQ) {
8861 		/* inbound queue */
8862 		qtype = "IBQ";
8863 		n = 4 * CIM_IBQ_SIZE;
8864 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8865 		mtx_lock(&sc->reg_lock);
8866 		if (hw_off_limits(sc))
8867 			rc = -ENXIO;
8868 		else
8869 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8870 		mtx_unlock(&sc->reg_lock);
8871 	} else {
8872 		/* outbound queue */
8873 		qtype = "OBQ";
8874 		qid -= CIM_NUM_IBQ;
8875 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8876 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8877 		mtx_lock(&sc->reg_lock);
8878 		if (hw_off_limits(sc))
8879 			rc = -ENXIO;
8880 		else
8881 			rc = t4_read_cim_obq(sc, qid, buf, n);
8882 		mtx_unlock(&sc->reg_lock);
8883 	}
8884 
8885 	if (rc < 0) {
8886 		rc = -rc;
8887 		goto done;
8888 	}
8889 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
8890 
8891 	rc = sysctl_wire_old_buffer(req, 0);
8892 	if (rc != 0)
8893 		goto done;
8894 
8895 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8896 	if (sb == NULL) {
8897 		rc = ENOMEM;
8898 		goto done;
8899 	}
8900 
8901 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8902 	for (i = 0, p = buf; i < n; i += 16, p += 4)
8903 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
8904 		    p[2], p[3]);
8905 
8906 	rc = sbuf_finish(sb);
8907 	sbuf_delete(sb);
8908 done:
8909 	free(buf, M_CXGBE);
8910 	return (rc);
8911 }
8912 
8913 static void
8914 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8915 {
8916 	uint32_t *p;
8917 
8918 	sbuf_printf(sb, "Status   Data      PC%s",
8919 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8920 	    "     LS0Stat  LS0Addr             LS0Data");
8921 
8922 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
8923 		if (cfg & F_UPDBGLACAPTPCONLY) {
8924 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
8925 			    p[6], p[7]);
8926 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
8927 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
8928 			    p[4] & 0xff, p[5] >> 8);
8929 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
8930 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8931 			    p[1] & 0xf, p[2] >> 4);
8932 		} else {
8933 			sbuf_printf(sb,
8934 			    "\n  %02x   %x%07x %x%07x %08x %08x "
8935 			    "%08x%08x%08x%08x",
8936 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8937 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
8938 			    p[6], p[7]);
8939 		}
8940 	}
8941 }
8942 
8943 static void
8944 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8945 {
8946 	uint32_t *p;
8947 
8948 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
8949 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8950 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
8951 
8952 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
8953 		if (cfg & F_UPDBGLACAPTPCONLY) {
8954 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
8955 			    p[3] & 0xff, p[2], p[1], p[0]);
8956 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
8957 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
8958 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
8959 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
8960 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
8961 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
8962 			    p[6] >> 16);
8963 		} else {
8964 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
8965 			    "%08x %08x %08x %08x %08x %08x",
8966 			    (p[9] >> 16) & 0xff,
8967 			    p[9] & 0xffff, p[8] >> 16,
8968 			    p[8] & 0xffff, p[7] >> 16,
8969 			    p[7] & 0xffff, p[6] >> 16,
8970 			    p[2], p[1], p[0], p[5], p[4], p[3]);
8971 		}
8972 	}
8973 }
8974 
8975 static int
8976 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
8977 {
8978 	uint32_t cfg, *buf;
8979 	int rc;
8980 
8981 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
8982 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
8983 	    M_ZERO | flags);
8984 	if (buf == NULL)
8985 		return (ENOMEM);
8986 
8987 	mtx_lock(&sc->reg_lock);
8988 	if (hw_off_limits(sc))
8989 		rc = ENXIO;
8990 	else {
8991 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
8992 		if (rc == 0)
8993 			rc = -t4_cim_read_la(sc, buf, NULL);
8994 	}
8995 	mtx_unlock(&sc->reg_lock);
8996 	if (rc == 0) {
8997 		if (chip_id(sc) < CHELSIO_T6)
8998 			sbuf_cim_la4(sc, sb, buf, cfg);
8999 		else
9000 			sbuf_cim_la6(sc, sb, buf, cfg);
9001 	}
9002 	free(buf, M_CXGBE);
9003 	return (rc);
9004 }
9005 
9006 static int
9007 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
9008 {
9009 	struct adapter *sc = arg1;
9010 	struct sbuf *sb;
9011 	int rc;
9012 
9013 	rc = sysctl_wire_old_buffer(req, 0);
9014 	if (rc != 0)
9015 		return (rc);
9016 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9017 	if (sb == NULL)
9018 		return (ENOMEM);
9019 
9020 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
9021 	if (rc == 0)
9022 		rc = sbuf_finish(sb);
9023 	sbuf_delete(sb);
9024 	return (rc);
9025 }
9026 
9027 static void
9028 dump_cim_regs(struct adapter *sc)
9029 {
9030 	log(LOG_DEBUG, "%s: CIM debug regs1 %08x %08x %08x %08x %08x\n",
9031 	    device_get_nameunit(sc->dev),
9032 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9033 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9034 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA2),
9035 	    t4_read_reg(sc, A_EDC_H_BIST_DATA_PATTERN),
9036 	    t4_read_reg(sc, A_EDC_H_BIST_STATUS_RDATA));
9037 	log(LOG_DEBUG, "%s: CIM debug regs2 %08x %08x %08x %08x %08x\n",
9038 	    device_get_nameunit(sc->dev),
9039 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9040 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9041 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0 + 0x800),
9042 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1 + 0x800),
9043 	    t4_read_reg(sc, A_EDC_H_BIST_CMD_LEN));
9044 }
9045 
9046 static void
9047 dump_cimla(struct adapter *sc)
9048 {
9049 	struct sbuf sb;
9050 	int rc;
9051 
9052 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9053 		log(LOG_DEBUG, "%s: failed to generate CIM LA dump.\n",
9054 		    device_get_nameunit(sc->dev));
9055 		return;
9056 	}
9057 	rc = sbuf_cim_la(sc, &sb, M_WAITOK);
9058 	if (rc == 0) {
9059 		rc = sbuf_finish(&sb);
9060 		if (rc == 0) {
9061 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s\n",
9062 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
9063 		}
9064 	}
9065 	sbuf_delete(&sb);
9066 }
9067 
9068 void
9069 t4_os_cim_err(struct adapter *sc)
9070 {
9071 	atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
9072 }
9073 
9074 static int
9075 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
9076 {
9077 	struct adapter *sc = arg1;
9078 	u_int i;
9079 	struct sbuf *sb;
9080 	uint32_t *buf, *p;
9081 	int rc;
9082 
9083 	rc = sysctl_wire_old_buffer(req, 0);
9084 	if (rc != 0)
9085 		return (rc);
9086 
9087 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9088 	if (sb == NULL)
9089 		return (ENOMEM);
9090 
9091 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
9092 	    M_ZERO | M_WAITOK);
9093 
9094 	mtx_lock(&sc->reg_lock);
9095 	if (hw_off_limits(sc))
9096 		rc = ENXIO;
9097 	else
9098 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
9099 	mtx_unlock(&sc->reg_lock);
9100 	if (rc)
9101 		goto done;
9102 
9103 	p = buf;
9104 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9105 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
9106 		    p[1], p[0]);
9107 	}
9108 
9109 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9110 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9111 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9112 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9113 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9114 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9115 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9116 		    p[0] & 1);
9117 	}
9118 	rc = sbuf_finish(sb);
9119 done:
9120 	sbuf_delete(sb);
9121 	free(buf, M_CXGBE);
9122 	return (rc);
9123 }
9124 
9125 static int
9126 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9127 {
9128 	struct adapter *sc = arg1;
9129 	u_int i;
9130 	struct sbuf *sb;
9131 	uint32_t *buf, *p;
9132 	int rc;
9133 
9134 	rc = sysctl_wire_old_buffer(req, 0);
9135 	if (rc != 0)
9136 		return (rc);
9137 
9138 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9139 	if (sb == NULL)
9140 		return (ENOMEM);
9141 
9142 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9143 	    M_ZERO | M_WAITOK);
9144 
9145 	mtx_lock(&sc->reg_lock);
9146 	if (hw_off_limits(sc))
9147 		rc = ENXIO;
9148 	else
9149 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9150 	mtx_unlock(&sc->reg_lock);
9151 	if (rc)
9152 		goto done;
9153 
9154 	p = buf;
9155 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9156 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9157 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9158 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9159 		    p[4], p[3], p[2], p[1], p[0]);
9160 	}
9161 
9162 	sbuf_printf(sb, "\n\nCntl ID               Data");
9163 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9164 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9165 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9166 	}
9167 
9168 	rc = sbuf_finish(sb);
9169 done:
9170 	sbuf_delete(sb);
9171 	free(buf, M_CXGBE);
9172 	return (rc);
9173 }
9174 
9175 static int
9176 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9177 {
9178 	struct adapter *sc = arg1;
9179 	struct sbuf *sb;
9180 	int rc, i;
9181 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9182 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9183 	uint16_t thres[CIM_NUM_IBQ];
9184 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9185 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9186 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9187 
9188 	cim_num_obq = sc->chip_params->cim_num_obq;
9189 	if (is_t4(sc)) {
9190 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9191 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9192 	} else {
9193 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9194 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9195 	}
9196 	nq = CIM_NUM_IBQ + cim_num_obq;
9197 
9198 	mtx_lock(&sc->reg_lock);
9199 	if (hw_off_limits(sc))
9200 		rc = ENXIO;
9201 	else {
9202 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9203 		if (rc == 0) {
9204 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9205 			    obq_wr);
9206 			if (rc == 0)
9207 				t4_read_cimq_cfg(sc, base, size, thres);
9208 		}
9209 	}
9210 	mtx_unlock(&sc->reg_lock);
9211 	if (rc)
9212 		return (rc);
9213 
9214 	rc = sysctl_wire_old_buffer(req, 0);
9215 	if (rc != 0)
9216 		return (rc);
9217 
9218 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9219 	if (sb == NULL)
9220 		return (ENOMEM);
9221 
9222 	sbuf_printf(sb,
9223 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9224 
9225 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9226 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9227 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9228 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9229 		    G_QUEREMFLITS(p[2]) * 16);
9230 	for ( ; i < nq; i++, p += 4, wr += 2)
9231 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9232 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9233 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9234 		    G_QUEREMFLITS(p[2]) * 16);
9235 
9236 	rc = sbuf_finish(sb);
9237 	sbuf_delete(sb);
9238 
9239 	return (rc);
9240 }
9241 
9242 static int
9243 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9244 {
9245 	struct adapter *sc = arg1;
9246 	struct sbuf *sb;
9247 	int rc;
9248 	struct tp_cpl_stats stats;
9249 
9250 	rc = sysctl_wire_old_buffer(req, 0);
9251 	if (rc != 0)
9252 		return (rc);
9253 
9254 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9255 	if (sb == NULL)
9256 		return (ENOMEM);
9257 
9258 	mtx_lock(&sc->reg_lock);
9259 	if (hw_off_limits(sc))
9260 		rc = ENXIO;
9261 	else
9262 		t4_tp_get_cpl_stats(sc, &stats, 0);
9263 	mtx_unlock(&sc->reg_lock);
9264 	if (rc)
9265 		goto done;
9266 
9267 	if (sc->chip_params->nchan > 2) {
9268 		sbuf_printf(sb, "                 channel 0  channel 1"
9269 		    "  channel 2  channel 3");
9270 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9271 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9272 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9273 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9274 	} else {
9275 		sbuf_printf(sb, "                 channel 0  channel 1");
9276 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9277 		    stats.req[0], stats.req[1]);
9278 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9279 		    stats.rsp[0], stats.rsp[1]);
9280 	}
9281 
9282 	rc = sbuf_finish(sb);
9283 done:
9284 	sbuf_delete(sb);
9285 	return (rc);
9286 }
9287 
9288 static int
9289 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9290 {
9291 	struct adapter *sc = arg1;
9292 	struct sbuf *sb;
9293 	int rc;
9294 	struct tp_usm_stats stats;
9295 
9296 	rc = sysctl_wire_old_buffer(req, 0);
9297 	if (rc != 0)
9298 		return(rc);
9299 
9300 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9301 	if (sb == NULL)
9302 		return (ENOMEM);
9303 
9304 	mtx_lock(&sc->reg_lock);
9305 	if (hw_off_limits(sc))
9306 		rc = ENXIO;
9307 	else
9308 		t4_get_usm_stats(sc, &stats, 1);
9309 	mtx_unlock(&sc->reg_lock);
9310 	if (rc == 0) {
9311 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9312 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9313 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9314 		rc = sbuf_finish(sb);
9315 	}
9316 	sbuf_delete(sb);
9317 
9318 	return (rc);
9319 }
9320 
9321 static int
9322 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9323 {
9324 	struct adapter *sc = arg1;
9325 	struct sbuf *sb;
9326 	int rc;
9327 	struct tp_tid_stats stats;
9328 
9329 	rc = sysctl_wire_old_buffer(req, 0);
9330 	if (rc != 0)
9331 		return(rc);
9332 
9333 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9334 	if (sb == NULL)
9335 		return (ENOMEM);
9336 
9337 	mtx_lock(&sc->reg_lock);
9338 	if (hw_off_limits(sc))
9339 		rc = ENXIO;
9340 	else
9341 		t4_tp_get_tid_stats(sc, &stats, 1);
9342 	mtx_unlock(&sc->reg_lock);
9343 	if (rc == 0) {
9344 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9345 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9346 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9347 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9348 		rc = sbuf_finish(sb);
9349 	}
9350 	sbuf_delete(sb);
9351 
9352 	return (rc);
9353 }
9354 
9355 static const char * const devlog_level_strings[] = {
9356 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9357 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9358 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9359 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9360 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9361 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9362 };
9363 
9364 static const char * const devlog_facility_strings[] = {
9365 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9366 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9367 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9368 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9369 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9370 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9371 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9372 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9373 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9374 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9375 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9376 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9377 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9378 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9379 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9380 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9381 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9382 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9383 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9384 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9385 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9386 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9387 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9388 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9389 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9390 };
9391 
9392 static int
9393 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9394 {
9395 	int i, j, rc, nentries, first = 0;
9396 	struct devlog_params *dparams = &sc->params.devlog;
9397 	struct fw_devlog_e *buf, *e;
9398 	uint64_t ftstamp = UINT64_MAX;
9399 
9400 	if (dparams->addr == 0)
9401 		return (ENXIO);
9402 
9403 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9404 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9405 	if (buf == NULL)
9406 		return (ENOMEM);
9407 
9408 	mtx_lock(&sc->reg_lock);
9409 	if (hw_off_limits(sc))
9410 		rc = ENXIO;
9411 	else
9412 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9413 		    dparams->size);
9414 	mtx_unlock(&sc->reg_lock);
9415 	if (rc != 0)
9416 		goto done;
9417 
9418 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9419 	for (i = 0; i < nentries; i++) {
9420 		e = &buf[i];
9421 
9422 		if (e->timestamp == 0)
9423 			break;	/* end */
9424 
9425 		e->timestamp = be64toh(e->timestamp);
9426 		e->seqno = be32toh(e->seqno);
9427 		for (j = 0; j < 8; j++)
9428 			e->params[j] = be32toh(e->params[j]);
9429 
9430 		if (e->timestamp < ftstamp) {
9431 			ftstamp = e->timestamp;
9432 			first = i;
9433 		}
9434 	}
9435 
9436 	if (buf[first].timestamp == 0)
9437 		goto done;	/* nothing in the log */
9438 
9439 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9440 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9441 
9442 	i = first;
9443 	do {
9444 		e = &buf[i];
9445 		if (e->timestamp == 0)
9446 			break;	/* end */
9447 
9448 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9449 		    e->seqno, e->timestamp,
9450 		    (e->level < nitems(devlog_level_strings) ?
9451 			devlog_level_strings[e->level] : "UNKNOWN"),
9452 		    (e->facility < nitems(devlog_facility_strings) ?
9453 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9454 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9455 		    e->params[2], e->params[3], e->params[4],
9456 		    e->params[5], e->params[6], e->params[7]);
9457 
9458 		if (++i == nentries)
9459 			i = 0;
9460 	} while (i != first);
9461 done:
9462 	free(buf, M_CXGBE);
9463 	return (rc);
9464 }
9465 
9466 static int
9467 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9468 {
9469 	struct adapter *sc = arg1;
9470 	int rc;
9471 	struct sbuf *sb;
9472 
9473 	rc = sysctl_wire_old_buffer(req, 0);
9474 	if (rc != 0)
9475 		return (rc);
9476 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9477 	if (sb == NULL)
9478 		return (ENOMEM);
9479 
9480 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9481 	if (rc == 0)
9482 		rc = sbuf_finish(sb);
9483 	sbuf_delete(sb);
9484 	return (rc);
9485 }
9486 
9487 static void
9488 dump_devlog(struct adapter *sc)
9489 {
9490 	int rc;
9491 	struct sbuf sb;
9492 
9493 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9494 		log(LOG_DEBUG, "%s: failed to generate devlog dump.\n",
9495 		    device_get_nameunit(sc->dev));
9496 		return;
9497 	}
9498 	rc = sbuf_devlog(sc, &sb, M_WAITOK);
9499 	if (rc == 0) {
9500 		rc = sbuf_finish(&sb);
9501 		if (rc == 0) {
9502 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9503 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
9504 		}
9505 	}
9506 	sbuf_delete(&sb);
9507 }
9508 
9509 static int
9510 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9511 {
9512 	struct adapter *sc = arg1;
9513 	struct sbuf *sb;
9514 	int rc;
9515 	struct tp_fcoe_stats stats[MAX_NCHAN];
9516 	int i, nchan = sc->chip_params->nchan;
9517 
9518 	rc = sysctl_wire_old_buffer(req, 0);
9519 	if (rc != 0)
9520 		return (rc);
9521 
9522 	mtx_lock(&sc->reg_lock);
9523 	if (hw_off_limits(sc))
9524 		rc = ENXIO;
9525 	else {
9526 		for (i = 0; i < nchan; i++)
9527 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9528 	}
9529 	mtx_unlock(&sc->reg_lock);
9530 	if (rc != 0)
9531 		return (rc);
9532 
9533 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9534 	if (sb == NULL)
9535 		return (ENOMEM);
9536 
9537 	if (nchan > 2) {
9538 		sbuf_printf(sb, "                   channel 0        channel 1"
9539 		    "        channel 2        channel 3");
9540 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9541 		    stats[0].octets_ddp, stats[1].octets_ddp,
9542 		    stats[2].octets_ddp, stats[3].octets_ddp);
9543 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9544 		    stats[0].frames_ddp, stats[1].frames_ddp,
9545 		    stats[2].frames_ddp, stats[3].frames_ddp);
9546 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9547 		    stats[0].frames_drop, stats[1].frames_drop,
9548 		    stats[2].frames_drop, stats[3].frames_drop);
9549 	} else {
9550 		sbuf_printf(sb, "                   channel 0        channel 1");
9551 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9552 		    stats[0].octets_ddp, stats[1].octets_ddp);
9553 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9554 		    stats[0].frames_ddp, stats[1].frames_ddp);
9555 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9556 		    stats[0].frames_drop, stats[1].frames_drop);
9557 	}
9558 
9559 	rc = sbuf_finish(sb);
9560 	sbuf_delete(sb);
9561 
9562 	return (rc);
9563 }
9564 
9565 static int
9566 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9567 {
9568 	struct adapter *sc = arg1;
9569 	struct sbuf *sb;
9570 	int rc, i;
9571 	unsigned int map, kbps, ipg, mode;
9572 	unsigned int pace_tab[NTX_SCHED];
9573 
9574 	rc = sysctl_wire_old_buffer(req, 0);
9575 	if (rc != 0)
9576 		return (rc);
9577 
9578 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9579 	if (sb == NULL)
9580 		return (ENOMEM);
9581 
9582 	mtx_lock(&sc->reg_lock);
9583 	if (hw_off_limits(sc)) {
9584 		rc = ENXIO;
9585 		goto done;
9586 	}
9587 
9588 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9589 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9590 	t4_read_pace_tbl(sc, pace_tab);
9591 
9592 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9593 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9594 
9595 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9596 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9597 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9598 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9599 		if (kbps)
9600 			sbuf_printf(sb, "%9u     ", kbps);
9601 		else
9602 			sbuf_printf(sb, " disabled     ");
9603 
9604 		if (ipg)
9605 			sbuf_printf(sb, "%13u        ", ipg);
9606 		else
9607 			sbuf_printf(sb, "     disabled        ");
9608 
9609 		if (pace_tab[i])
9610 			sbuf_printf(sb, "%10u", pace_tab[i]);
9611 		else
9612 			sbuf_printf(sb, "  disabled");
9613 	}
9614 	rc = sbuf_finish(sb);
9615 done:
9616 	mtx_unlock(&sc->reg_lock);
9617 	sbuf_delete(sb);
9618 	return (rc);
9619 }
9620 
9621 static int
9622 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9623 {
9624 	struct adapter *sc = arg1;
9625 	struct sbuf *sb;
9626 	int rc, i, j;
9627 	uint64_t *p0, *p1;
9628 	struct lb_port_stats s[2];
9629 	static const char *stat_name[] = {
9630 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9631 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9632 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9633 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9634 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9635 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9636 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9637 	};
9638 
9639 	rc = sysctl_wire_old_buffer(req, 0);
9640 	if (rc != 0)
9641 		return (rc);
9642 
9643 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9644 	if (sb == NULL)
9645 		return (ENOMEM);
9646 
9647 	memset(s, 0, sizeof(s));
9648 
9649 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9650 		mtx_lock(&sc->reg_lock);
9651 		if (hw_off_limits(sc))
9652 			rc = ENXIO;
9653 		else {
9654 			t4_get_lb_stats(sc, i, &s[0]);
9655 			t4_get_lb_stats(sc, i + 1, &s[1]);
9656 		}
9657 		mtx_unlock(&sc->reg_lock);
9658 		if (rc != 0)
9659 			break;
9660 
9661 		p0 = &s[0].octets;
9662 		p1 = &s[1].octets;
9663 		sbuf_printf(sb, "%s                       Loopback %u"
9664 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9665 
9666 		for (j = 0; j < nitems(stat_name); j++)
9667 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9668 				   *p0++, *p1++);
9669 	}
9670 
9671 	rc = sbuf_finish(sb);
9672 	sbuf_delete(sb);
9673 
9674 	return (rc);
9675 }
9676 
9677 static int
9678 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9679 {
9680 	int rc = 0;
9681 	struct port_info *pi = arg1;
9682 	struct link_config *lc = &pi->link_cfg;
9683 	struct sbuf *sb;
9684 
9685 	rc = sysctl_wire_old_buffer(req, 0);
9686 	if (rc != 0)
9687 		return(rc);
9688 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9689 	if (sb == NULL)
9690 		return (ENOMEM);
9691 
9692 	if (lc->link_ok || lc->link_down_rc == 255)
9693 		sbuf_printf(sb, "n/a");
9694 	else
9695 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9696 
9697 	rc = sbuf_finish(sb);
9698 	sbuf_delete(sb);
9699 
9700 	return (rc);
9701 }
9702 
9703 struct mem_desc {
9704 	u_int base;
9705 	u_int limit;
9706 	u_int idx;
9707 };
9708 
9709 static int
9710 mem_desc_cmp(const void *a, const void *b)
9711 {
9712 	const u_int v1 = ((const struct mem_desc *)a)->base;
9713 	const u_int v2 = ((const struct mem_desc *)b)->base;
9714 
9715 	if (v1 < v2)
9716 		return (-1);
9717 	else if (v1 > v2)
9718 		return (1);
9719 
9720 	return (0);
9721 }
9722 
9723 static void
9724 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9725     unsigned int to)
9726 {
9727 	unsigned int size;
9728 
9729 	if (from == to)
9730 		return;
9731 
9732 	size = to - from + 1;
9733 	if (size == 0)
9734 		return;
9735 
9736 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9737 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9738 }
9739 
9740 static int
9741 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9742 {
9743 	struct adapter *sc = arg1;
9744 	struct sbuf *sb;
9745 	int rc, i, n;
9746 	uint32_t lo, hi, used, free, alloc;
9747 	static const char *memory[] = {
9748 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9749 	};
9750 	static const char *region[] = {
9751 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9752 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9753 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9754 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9755 		"RQUDP region:", "PBL region:", "TXPBL region:",
9756 		"TLSKey region:", "DBVFIFO region:", "ULPRX state:",
9757 		"ULPTX state:", "On-chip queues:",
9758 	};
9759 	struct mem_desc avail[4];
9760 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9761 	struct mem_desc *md = mem;
9762 
9763 	rc = sysctl_wire_old_buffer(req, 0);
9764 	if (rc != 0)
9765 		return (rc);
9766 
9767 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9768 	if (sb == NULL)
9769 		return (ENOMEM);
9770 
9771 	for (i = 0; i < nitems(mem); i++) {
9772 		mem[i].limit = 0;
9773 		mem[i].idx = i;
9774 	}
9775 
9776 	mtx_lock(&sc->reg_lock);
9777 	if (hw_off_limits(sc)) {
9778 		rc = ENXIO;
9779 		goto done;
9780 	}
9781 
9782 	/* Find and sort the populated memory ranges */
9783 	i = 0;
9784 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9785 	if (lo & F_EDRAM0_ENABLE) {
9786 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9787 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9788 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9789 		avail[i].idx = 0;
9790 		i++;
9791 	}
9792 	if (lo & F_EDRAM1_ENABLE) {
9793 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9794 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9795 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9796 		avail[i].idx = 1;
9797 		i++;
9798 	}
9799 	if (lo & F_EXT_MEM_ENABLE) {
9800 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9801 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9802 		avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9803 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9804 		i++;
9805 	}
9806 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9807 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9808 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9809 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9810 		avail[i].idx = 4;
9811 		i++;
9812 	}
9813 	if (is_t6(sc) && lo & F_HMA_MUX) {
9814 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9815 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9816 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9817 		avail[i].idx = 5;
9818 		i++;
9819 	}
9820 	MPASS(i <= nitems(avail));
9821 	if (!i)                                    /* no memory available */
9822 		goto done;
9823 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9824 
9825 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9826 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9827 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9828 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9829 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9830 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9831 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9832 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9833 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9834 
9835 	/* the next few have explicit upper bounds */
9836 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9837 	md->limit = md->base - 1 +
9838 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9839 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9840 	md++;
9841 
9842 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9843 	md->limit = md->base - 1 +
9844 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9845 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9846 	md++;
9847 
9848 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9849 		if (chip_id(sc) <= CHELSIO_T5)
9850 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9851 		else
9852 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9853 		md->limit = 0;
9854 	} else {
9855 		md->base = 0;
9856 		md->idx = nitems(region);  /* hide it */
9857 	}
9858 	md++;
9859 
9860 #define ulp_region(reg) \
9861 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9862 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9863 
9864 	ulp_region(RX_ISCSI);
9865 	ulp_region(RX_TDDP);
9866 	ulp_region(TX_TPT);
9867 	ulp_region(RX_STAG);
9868 	ulp_region(RX_RQ);
9869 	ulp_region(RX_RQUDP);
9870 	ulp_region(RX_PBL);
9871 	ulp_region(TX_PBL);
9872 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
9873 		ulp_region(RX_TLS_KEY);
9874 	}
9875 #undef ulp_region
9876 
9877 	md->base = 0;
9878 	if (is_t4(sc))
9879 		md->idx = nitems(region);
9880 	else {
9881 		uint32_t size = 0;
9882 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9883 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9884 
9885 		if (is_t5(sc)) {
9886 			if (sge_ctrl & F_VFIFO_ENABLE)
9887 				size = fifo_size << 2;
9888 		} else
9889 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9890 
9891 		if (size) {
9892 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
9893 			md->limit = md->base + size - 1;
9894 		} else
9895 			md->idx = nitems(region);
9896 	}
9897 	md++;
9898 
9899 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9900 	md->limit = 0;
9901 	md++;
9902 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9903 	md->limit = 0;
9904 	md++;
9905 
9906 	md->base = sc->vres.ocq.start;
9907 	if (sc->vres.ocq.size)
9908 		md->limit = md->base + sc->vres.ocq.size - 1;
9909 	else
9910 		md->idx = nitems(region);  /* hide it */
9911 	md++;
9912 
9913 	/* add any address-space holes, there can be up to 3 */
9914 	for (n = 0; n < i - 1; n++)
9915 		if (avail[n].limit < avail[n + 1].base)
9916 			(md++)->base = avail[n].limit;
9917 	if (avail[n].limit)
9918 		(md++)->base = avail[n].limit;
9919 
9920 	n = md - mem;
9921 	MPASS(n <= nitems(mem));
9922 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
9923 
9924 	for (lo = 0; lo < i; lo++)
9925 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
9926 				avail[lo].limit - 1);
9927 
9928 	sbuf_printf(sb, "\n");
9929 	for (i = 0; i < n; i++) {
9930 		if (mem[i].idx >= nitems(region))
9931 			continue;                        /* skip holes */
9932 		if (!mem[i].limit)
9933 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
9934 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
9935 				mem[i].limit);
9936 	}
9937 
9938 	sbuf_printf(sb, "\n");
9939 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
9940 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
9941 	mem_region_show(sb, "uP RAM:", lo, hi);
9942 
9943 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
9944 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
9945 	mem_region_show(sb, "uP Extmem2:", lo, hi);
9946 
9947 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
9948 	for (i = 0, free = 0; i < 2; i++)
9949 		free += G_FREERXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_RX_CNT));
9950 	sbuf_printf(sb, "\n%u Rx pages (%u free) of size %uKiB for %u channels\n",
9951 		   G_PMRXMAXPAGE(lo), free,
9952 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
9953 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
9954 
9955 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
9956 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
9957 	for (i = 0, free = 0; i < 4; i++)
9958 		free += G_FREETXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_TX_CNT));
9959 	sbuf_printf(sb, "%u Tx pages (%u free) of size %u%ciB for %u channels\n",
9960 		   G_PMTXMAXPAGE(lo), free,
9961 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
9962 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
9963 	sbuf_printf(sb, "%u p-structs (%u free)\n",
9964 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT),
9965 		   G_FREEPSTRUCTCOUNT(t4_read_reg(sc, A_TP_FLM_FREE_PS_CNT)));
9966 
9967 	for (i = 0; i < 4; i++) {
9968 		if (chip_id(sc) > CHELSIO_T5)
9969 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
9970 		else
9971 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
9972 		if (is_t5(sc)) {
9973 			used = G_T5_USED(lo);
9974 			alloc = G_T5_ALLOC(lo);
9975 		} else {
9976 			used = G_USED(lo);
9977 			alloc = G_ALLOC(lo);
9978 		}
9979 		/* For T6 these are MAC buffer groups */
9980 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
9981 		    i, used, alloc);
9982 	}
9983 	for (i = 0; i < sc->chip_params->nchan; i++) {
9984 		if (chip_id(sc) > CHELSIO_T5)
9985 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
9986 		else
9987 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
9988 		if (is_t5(sc)) {
9989 			used = G_T5_USED(lo);
9990 			alloc = G_T5_ALLOC(lo);
9991 		} else {
9992 			used = G_USED(lo);
9993 			alloc = G_ALLOC(lo);
9994 		}
9995 		/* For T6 these are MAC buffer groups */
9996 		sbuf_printf(sb,
9997 		    "\nLoopback %d using %u pages out of %u allocated",
9998 		    i, used, alloc);
9999 	}
10000 done:
10001 	mtx_unlock(&sc->reg_lock);
10002 	if (rc == 0)
10003 		rc = sbuf_finish(sb);
10004 	sbuf_delete(sb);
10005 	return (rc);
10006 }
10007 
10008 static inline void
10009 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
10010 {
10011 	*mask = x | y;
10012 	y = htobe64(y);
10013 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
10014 }
10015 
10016 static int
10017 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
10018 {
10019 	struct adapter *sc = arg1;
10020 	struct sbuf *sb;
10021 	int rc, i;
10022 
10023 	MPASS(chip_id(sc) <= CHELSIO_T5);
10024 
10025 	rc = sysctl_wire_old_buffer(req, 0);
10026 	if (rc != 0)
10027 		return (rc);
10028 
10029 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10030 	if (sb == NULL)
10031 		return (ENOMEM);
10032 
10033 	sbuf_printf(sb,
10034 	    "Idx  Ethernet address     Mask     Vld Ports PF"
10035 	    "  VF              Replication             P0 P1 P2 P3  ML");
10036 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10037 		uint64_t tcamx, tcamy, mask;
10038 		uint32_t cls_lo, cls_hi;
10039 		uint8_t addr[ETHER_ADDR_LEN];
10040 
10041 		mtx_lock(&sc->reg_lock);
10042 		if (hw_off_limits(sc))
10043 			rc = ENXIO;
10044 		else {
10045 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
10046 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
10047 		}
10048 		mtx_unlock(&sc->reg_lock);
10049 		if (rc != 0)
10050 			break;
10051 		if (tcamx & tcamy)
10052 			continue;
10053 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10054 		mtx_lock(&sc->reg_lock);
10055 		if (hw_off_limits(sc))
10056 			rc = ENXIO;
10057 		else {
10058 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10059 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10060 		}
10061 		mtx_unlock(&sc->reg_lock);
10062 		if (rc != 0)
10063 			break;
10064 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
10065 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
10066 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
10067 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
10068 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
10069 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
10070 
10071 		if (cls_lo & F_REPLICATE) {
10072 			struct fw_ldst_cmd ldst_cmd;
10073 
10074 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10075 			ldst_cmd.op_to_addrspace =
10076 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10077 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10078 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10079 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10080 			ldst_cmd.u.mps.rplc.fid_idx =
10081 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10082 				V_FW_LDST_CMD_IDX(i));
10083 
10084 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10085 			    "t4mps");
10086 			if (rc)
10087 				break;
10088 			if (hw_off_limits(sc))
10089 				rc = ENXIO;
10090 			else
10091 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10092 				    sizeof(ldst_cmd), &ldst_cmd);
10093 			end_synchronized_op(sc, 0);
10094 			if (rc != 0)
10095 				break;
10096 			else {
10097 				sbuf_printf(sb, " %08x %08x %08x %08x",
10098 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10099 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10100 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10101 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10102 			}
10103 		} else
10104 			sbuf_printf(sb, "%36s", "");
10105 
10106 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
10107 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
10108 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
10109 	}
10110 
10111 	if (rc)
10112 		(void) sbuf_finish(sb);
10113 	else
10114 		rc = sbuf_finish(sb);
10115 	sbuf_delete(sb);
10116 
10117 	return (rc);
10118 }
10119 
10120 static int
10121 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
10122 {
10123 	struct adapter *sc = arg1;
10124 	struct sbuf *sb;
10125 	int rc, i;
10126 
10127 	MPASS(chip_id(sc) > CHELSIO_T5);
10128 
10129 	rc = sysctl_wire_old_buffer(req, 0);
10130 	if (rc != 0)
10131 		return (rc);
10132 
10133 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10134 	if (sb == NULL)
10135 		return (ENOMEM);
10136 
10137 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
10138 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
10139 	    "                           Replication"
10140 	    "                                    P0 P1 P2 P3  ML\n");
10141 
10142 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10143 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
10144 		uint16_t ivlan;
10145 		uint64_t tcamx, tcamy, val, mask;
10146 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10147 		uint8_t addr[ETHER_ADDR_LEN];
10148 
10149 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10150 		if (i < 256)
10151 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10152 		else
10153 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10154 		mtx_lock(&sc->reg_lock);
10155 		if (hw_off_limits(sc))
10156 			rc = ENXIO;
10157 		else {
10158 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10159 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10160 			tcamy = G_DMACH(val) << 32;
10161 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10162 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10163 		}
10164 		mtx_unlock(&sc->reg_lock);
10165 		if (rc != 0)
10166 			break;
10167 
10168 		lookup_type = G_DATALKPTYPE(data2);
10169 		port_num = G_DATAPORTNUM(data2);
10170 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10171 			/* Inner header VNI */
10172 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10173 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10174 			dip_hit = data2 & F_DATADIPHIT;
10175 			vlan_vld = 0;
10176 		} else {
10177 			vniy = 0;
10178 			dip_hit = 0;
10179 			vlan_vld = data2 & F_DATAVIDH2;
10180 			ivlan = G_VIDL(val);
10181 		}
10182 
10183 		ctl |= V_CTLXYBITSEL(1);
10184 		mtx_lock(&sc->reg_lock);
10185 		if (hw_off_limits(sc))
10186 			rc = ENXIO;
10187 		else {
10188 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10189 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10190 			tcamx = G_DMACH(val) << 32;
10191 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10192 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10193 		}
10194 		mtx_unlock(&sc->reg_lock);
10195 		if (rc != 0)
10196 			break;
10197 
10198 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10199 			/* Inner header VNI mask */
10200 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10201 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10202 		} else
10203 			vnix = 0;
10204 
10205 		if (tcamx & tcamy)
10206 			continue;
10207 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10208 
10209 		mtx_lock(&sc->reg_lock);
10210 		if (hw_off_limits(sc))
10211 			rc = ENXIO;
10212 		else {
10213 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10214 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10215 		}
10216 		mtx_unlock(&sc->reg_lock);
10217 		if (rc != 0)
10218 			break;
10219 
10220 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10221 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10222 			    "%012jx %06x %06x    -    -   %3c"
10223 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10224 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10225 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10226 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10227 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10228 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10229 		} else {
10230 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10231 			    "%012jx    -       -   ", i, addr[0], addr[1],
10232 			    addr[2], addr[3], addr[4], addr[5],
10233 			    (uintmax_t)mask);
10234 
10235 			if (vlan_vld)
10236 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10237 			else
10238 				sbuf_printf(sb, "  -    N     ");
10239 
10240 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10241 			    lookup_type ? 'I' : 'O', port_num,
10242 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10243 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10244 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10245 		}
10246 
10247 
10248 		if (cls_lo & F_T6_REPLICATE) {
10249 			struct fw_ldst_cmd ldst_cmd;
10250 
10251 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10252 			ldst_cmd.op_to_addrspace =
10253 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10254 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10255 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10256 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10257 			ldst_cmd.u.mps.rplc.fid_idx =
10258 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10259 				V_FW_LDST_CMD_IDX(i));
10260 
10261 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10262 			    "t6mps");
10263 			if (rc)
10264 				break;
10265 			if (hw_off_limits(sc))
10266 				rc = ENXIO;
10267 			else
10268 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10269 				    sizeof(ldst_cmd), &ldst_cmd);
10270 			end_synchronized_op(sc, 0);
10271 			if (rc != 0)
10272 				break;
10273 			else {
10274 				sbuf_printf(sb, " %08x %08x %08x %08x"
10275 				    " %08x %08x %08x %08x",
10276 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10277 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10278 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10279 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10280 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10281 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10282 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10283 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10284 			}
10285 		} else
10286 			sbuf_printf(sb, "%72s", "");
10287 
10288 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10289 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10290 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10291 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10292 	}
10293 
10294 	if (rc)
10295 		(void) sbuf_finish(sb);
10296 	else
10297 		rc = sbuf_finish(sb);
10298 	sbuf_delete(sb);
10299 
10300 	return (rc);
10301 }
10302 
10303 static int
10304 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10305 {
10306 	struct adapter *sc = arg1;
10307 	struct sbuf *sb;
10308 	int rc;
10309 	uint16_t mtus[NMTUS];
10310 
10311 	rc = sysctl_wire_old_buffer(req, 0);
10312 	if (rc != 0)
10313 		return (rc);
10314 
10315 	mtx_lock(&sc->reg_lock);
10316 	if (hw_off_limits(sc))
10317 		rc = ENXIO;
10318 	else
10319 		t4_read_mtu_tbl(sc, mtus, NULL);
10320 	mtx_unlock(&sc->reg_lock);
10321 	if (rc != 0)
10322 		return (rc);
10323 
10324 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10325 	if (sb == NULL)
10326 		return (ENOMEM);
10327 
10328 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10329 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10330 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10331 	    mtus[14], mtus[15]);
10332 
10333 	rc = sbuf_finish(sb);
10334 	sbuf_delete(sb);
10335 
10336 	return (rc);
10337 }
10338 
10339 static int
10340 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10341 {
10342 	struct adapter *sc = arg1;
10343 	struct sbuf *sb;
10344 	int rc, i;
10345 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10346 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10347 	static const char *tx_stats[MAX_PM_NSTATS] = {
10348 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10349 		"Tx FIFO wait", NULL, "Tx latency"
10350 	};
10351 	static const char *rx_stats[MAX_PM_NSTATS] = {
10352 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10353 		"Rx FIFO wait", NULL, "Rx latency"
10354 	};
10355 
10356 	rc = sysctl_wire_old_buffer(req, 0);
10357 	if (rc != 0)
10358 		return (rc);
10359 
10360 	mtx_lock(&sc->reg_lock);
10361 	if (hw_off_limits(sc))
10362 		rc = ENXIO;
10363 	else {
10364 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10365 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10366 	}
10367 	mtx_unlock(&sc->reg_lock);
10368 	if (rc != 0)
10369 		return (rc);
10370 
10371 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10372 	if (sb == NULL)
10373 		return (ENOMEM);
10374 
10375 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10376 	for (i = 0; i < 4; i++) {
10377 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10378 		    tx_cyc[i]);
10379 	}
10380 
10381 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10382 	for (i = 0; i < 4; i++) {
10383 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10384 		    rx_cyc[i]);
10385 	}
10386 
10387 	if (chip_id(sc) > CHELSIO_T5) {
10388 		sbuf_printf(sb,
10389 		    "\n              Total wait      Total occupancy");
10390 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10391 		    tx_cyc[i]);
10392 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10393 		    rx_cyc[i]);
10394 
10395 		i += 2;
10396 		MPASS(i < nitems(tx_stats));
10397 
10398 		sbuf_printf(sb,
10399 		    "\n                   Reads           Total wait");
10400 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10401 		    tx_cyc[i]);
10402 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10403 		    rx_cyc[i]);
10404 	}
10405 
10406 	rc = sbuf_finish(sb);
10407 	sbuf_delete(sb);
10408 
10409 	return (rc);
10410 }
10411 
10412 static int
10413 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10414 {
10415 	struct adapter *sc = arg1;
10416 	struct sbuf *sb;
10417 	int rc;
10418 	struct tp_rdma_stats stats;
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_rdma_stats(sc, &stats, 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, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10438 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10439 
10440 	rc = sbuf_finish(sb);
10441 	sbuf_delete(sb);
10442 
10443 	return (rc);
10444 }
10445 
10446 static int
10447 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10448 {
10449 	struct adapter *sc = arg1;
10450 	struct sbuf *sb;
10451 	int rc;
10452 	struct tp_tcp_stats v4, v6;
10453 
10454 	rc = sysctl_wire_old_buffer(req, 0);
10455 	if (rc != 0)
10456 		return (rc);
10457 
10458 	mtx_lock(&sc->reg_lock);
10459 	if (hw_off_limits(sc))
10460 		rc = ENXIO;
10461 	else
10462 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10463 	mtx_unlock(&sc->reg_lock);
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 	sbuf_printf(sb,
10472 	    "                                IP                 IPv6\n");
10473 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10474 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10475 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10476 	    v4.tcp_in_segs, v6.tcp_in_segs);
10477 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10478 	    v4.tcp_out_segs, v6.tcp_out_segs);
10479 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10480 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10481 
10482 	rc = sbuf_finish(sb);
10483 	sbuf_delete(sb);
10484 
10485 	return (rc);
10486 }
10487 
10488 static int
10489 sysctl_tids(SYSCTL_HANDLER_ARGS)
10490 {
10491 	struct adapter *sc = arg1;
10492 	struct sbuf *sb;
10493 	int rc;
10494 	uint32_t x, y;
10495 	struct tid_info *t = &sc->tids;
10496 
10497 	rc = sysctl_wire_old_buffer(req, 0);
10498 	if (rc != 0)
10499 		return (rc);
10500 
10501 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10502 	if (sb == NULL)
10503 		return (ENOMEM);
10504 
10505 	if (t->natids) {
10506 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10507 		    t->atids_in_use);
10508 	}
10509 
10510 	if (t->nhpftids) {
10511 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10512 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10513 	}
10514 
10515 	if (t->ntids) {
10516 		bool hashen = false;
10517 
10518 		mtx_lock(&sc->reg_lock);
10519 		if (hw_off_limits(sc))
10520 			rc = ENXIO;
10521 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10522 			hashen = true;
10523 			if (chip_id(sc) <= CHELSIO_T5) {
10524 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10525 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10526 			} else {
10527 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10528 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10529 			}
10530 		}
10531 		mtx_unlock(&sc->reg_lock);
10532 		if (rc != 0)
10533 			goto done;
10534 
10535 		sbuf_printf(sb, "TID range: ");
10536 		if (hashen) {
10537 			if (x)
10538 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10539 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10540 		} else {
10541 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10542 			    t->ntids - 1);
10543 		}
10544 		sbuf_printf(sb, ", in use: %u\n",
10545 		    atomic_load_acq_int(&t->tids_in_use));
10546 	}
10547 
10548 	if (t->nstids) {
10549 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10550 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10551 	}
10552 
10553 	if (t->nftids) {
10554 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10555 		    t->ftid_end, t->ftids_in_use);
10556 	}
10557 
10558 	if (t->netids) {
10559 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10560 		    t->etid_base + t->netids - 1, t->etids_in_use);
10561 	}
10562 
10563 	mtx_lock(&sc->reg_lock);
10564 	if (hw_off_limits(sc))
10565 		rc = ENXIO;
10566 	else {
10567 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10568 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10569 	}
10570 	mtx_unlock(&sc->reg_lock);
10571 	if (rc != 0)
10572 		goto done;
10573 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10574 done:
10575 	if (rc == 0)
10576 		rc = sbuf_finish(sb);
10577 	else
10578 		(void)sbuf_finish(sb);
10579 	sbuf_delete(sb);
10580 
10581 	return (rc);
10582 }
10583 
10584 static int
10585 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10586 {
10587 	struct adapter *sc = arg1;
10588 	struct sbuf *sb;
10589 	int rc;
10590 	struct tp_err_stats stats;
10591 
10592 	rc = sysctl_wire_old_buffer(req, 0);
10593 	if (rc != 0)
10594 		return (rc);
10595 
10596 	mtx_lock(&sc->reg_lock);
10597 	if (hw_off_limits(sc))
10598 		rc = ENXIO;
10599 	else
10600 		t4_tp_get_err_stats(sc, &stats, 0);
10601 	mtx_unlock(&sc->reg_lock);
10602 	if (rc != 0)
10603 		return (rc);
10604 
10605 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10606 	if (sb == NULL)
10607 		return (ENOMEM);
10608 
10609 	if (sc->chip_params->nchan > 2) {
10610 		sbuf_printf(sb, "                 channel 0  channel 1"
10611 		    "  channel 2  channel 3\n");
10612 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10613 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10614 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10615 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10616 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10617 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10618 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10619 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10620 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10621 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10622 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10623 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10624 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10625 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10626 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10627 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10628 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10629 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10630 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10631 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10632 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10633 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10634 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10635 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10636 	} else {
10637 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10638 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10639 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10640 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10641 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10642 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10643 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10644 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10645 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10646 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10647 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10648 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10649 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10650 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10651 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10652 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10653 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10654 	}
10655 
10656 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10657 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10658 
10659 	rc = sbuf_finish(sb);
10660 	sbuf_delete(sb);
10661 
10662 	return (rc);
10663 }
10664 
10665 static int
10666 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10667 {
10668 	struct adapter *sc = arg1;
10669 	struct sbuf *sb;
10670 	int rc;
10671 	struct tp_tnl_stats stats;
10672 
10673 	rc = sysctl_wire_old_buffer(req, 0);
10674 	if (rc != 0)
10675 		return(rc);
10676 
10677 	mtx_lock(&sc->reg_lock);
10678 	if (hw_off_limits(sc))
10679 		rc = ENXIO;
10680 	else
10681 		t4_tp_get_tnl_stats(sc, &stats, 1);
10682 	mtx_unlock(&sc->reg_lock);
10683 	if (rc != 0)
10684 		return (rc);
10685 
10686 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10687 	if (sb == NULL)
10688 		return (ENOMEM);
10689 
10690 	if (sc->chip_params->nchan > 2) {
10691 		sbuf_printf(sb, "           channel 0  channel 1"
10692 		    "  channel 2  channel 3\n");
10693 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10694 		    stats.out_pkt[0], stats.out_pkt[1],
10695 		    stats.out_pkt[2], stats.out_pkt[3]);
10696 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10697 		    stats.in_pkt[0], stats.in_pkt[1],
10698 		    stats.in_pkt[2], stats.in_pkt[3]);
10699 	} else {
10700 		sbuf_printf(sb, "           channel 0  channel 1\n");
10701 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10702 		    stats.out_pkt[0], stats.out_pkt[1]);
10703 		sbuf_printf(sb, "InPkts:   %10u %10u",
10704 		    stats.in_pkt[0], stats.in_pkt[1]);
10705 	}
10706 
10707 	rc = sbuf_finish(sb);
10708 	sbuf_delete(sb);
10709 
10710 	return (rc);
10711 }
10712 
10713 static int
10714 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10715 {
10716 	struct adapter *sc = arg1;
10717 	struct tp_params *tpp = &sc->params.tp;
10718 	u_int mask;
10719 	int rc;
10720 
10721 	mask = tpp->la_mask >> 16;
10722 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10723 	if (rc != 0 || req->newptr == NULL)
10724 		return (rc);
10725 	if (mask > 0xffff)
10726 		return (EINVAL);
10727 	mtx_lock(&sc->reg_lock);
10728 	if (hw_off_limits(sc))
10729 		rc = ENXIO;
10730 	else {
10731 		tpp->la_mask = mask << 16;
10732 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10733 		    tpp->la_mask);
10734 	}
10735 	mtx_unlock(&sc->reg_lock);
10736 
10737 	return (rc);
10738 }
10739 
10740 struct field_desc {
10741 	const char *name;
10742 	u_int start;
10743 	u_int width;
10744 };
10745 
10746 static void
10747 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10748 {
10749 	char buf[32];
10750 	int line_size = 0;
10751 
10752 	while (f->name) {
10753 		uint64_t mask = (1ULL << f->width) - 1;
10754 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10755 		    ((uintmax_t)v >> f->start) & mask);
10756 
10757 		if (line_size + len >= 79) {
10758 			line_size = 8;
10759 			sbuf_printf(sb, "\n        ");
10760 		}
10761 		sbuf_printf(sb, "%s ", buf);
10762 		line_size += len + 1;
10763 		f++;
10764 	}
10765 	sbuf_printf(sb, "\n");
10766 }
10767 
10768 static const struct field_desc tp_la0[] = {
10769 	{ "RcfOpCodeOut", 60, 4 },
10770 	{ "State", 56, 4 },
10771 	{ "WcfState", 52, 4 },
10772 	{ "RcfOpcSrcOut", 50, 2 },
10773 	{ "CRxError", 49, 1 },
10774 	{ "ERxError", 48, 1 },
10775 	{ "SanityFailed", 47, 1 },
10776 	{ "SpuriousMsg", 46, 1 },
10777 	{ "FlushInputMsg", 45, 1 },
10778 	{ "FlushInputCpl", 44, 1 },
10779 	{ "RssUpBit", 43, 1 },
10780 	{ "RssFilterHit", 42, 1 },
10781 	{ "Tid", 32, 10 },
10782 	{ "InitTcb", 31, 1 },
10783 	{ "LineNumber", 24, 7 },
10784 	{ "Emsg", 23, 1 },
10785 	{ "EdataOut", 22, 1 },
10786 	{ "Cmsg", 21, 1 },
10787 	{ "CdataOut", 20, 1 },
10788 	{ "EreadPdu", 19, 1 },
10789 	{ "CreadPdu", 18, 1 },
10790 	{ "TunnelPkt", 17, 1 },
10791 	{ "RcfPeerFin", 16, 1 },
10792 	{ "RcfReasonOut", 12, 4 },
10793 	{ "TxCchannel", 10, 2 },
10794 	{ "RcfTxChannel", 8, 2 },
10795 	{ "RxEchannel", 6, 2 },
10796 	{ "RcfRxChannel", 5, 1 },
10797 	{ "RcfDataOutSrdy", 4, 1 },
10798 	{ "RxDvld", 3, 1 },
10799 	{ "RxOoDvld", 2, 1 },
10800 	{ "RxCongestion", 1, 1 },
10801 	{ "TxCongestion", 0, 1 },
10802 	{ NULL }
10803 };
10804 
10805 static const struct field_desc tp_la1[] = {
10806 	{ "CplCmdIn", 56, 8 },
10807 	{ "CplCmdOut", 48, 8 },
10808 	{ "ESynOut", 47, 1 },
10809 	{ "EAckOut", 46, 1 },
10810 	{ "EFinOut", 45, 1 },
10811 	{ "ERstOut", 44, 1 },
10812 	{ "SynIn", 43, 1 },
10813 	{ "AckIn", 42, 1 },
10814 	{ "FinIn", 41, 1 },
10815 	{ "RstIn", 40, 1 },
10816 	{ "DataIn", 39, 1 },
10817 	{ "DataInVld", 38, 1 },
10818 	{ "PadIn", 37, 1 },
10819 	{ "RxBufEmpty", 36, 1 },
10820 	{ "RxDdp", 35, 1 },
10821 	{ "RxFbCongestion", 34, 1 },
10822 	{ "TxFbCongestion", 33, 1 },
10823 	{ "TxPktSumSrdy", 32, 1 },
10824 	{ "RcfUlpType", 28, 4 },
10825 	{ "Eread", 27, 1 },
10826 	{ "Ebypass", 26, 1 },
10827 	{ "Esave", 25, 1 },
10828 	{ "Static0", 24, 1 },
10829 	{ "Cread", 23, 1 },
10830 	{ "Cbypass", 22, 1 },
10831 	{ "Csave", 21, 1 },
10832 	{ "CPktOut", 20, 1 },
10833 	{ "RxPagePoolFull", 18, 2 },
10834 	{ "RxLpbkPkt", 17, 1 },
10835 	{ "TxLpbkPkt", 16, 1 },
10836 	{ "RxVfValid", 15, 1 },
10837 	{ "SynLearned", 14, 1 },
10838 	{ "SetDelEntry", 13, 1 },
10839 	{ "SetInvEntry", 12, 1 },
10840 	{ "CpcmdDvld", 11, 1 },
10841 	{ "CpcmdSave", 10, 1 },
10842 	{ "RxPstructsFull", 8, 2 },
10843 	{ "EpcmdDvld", 7, 1 },
10844 	{ "EpcmdFlush", 6, 1 },
10845 	{ "EpcmdTrimPrefix", 5, 1 },
10846 	{ "EpcmdTrimPostfix", 4, 1 },
10847 	{ "ERssIp4Pkt", 3, 1 },
10848 	{ "ERssIp6Pkt", 2, 1 },
10849 	{ "ERssTcpUdpPkt", 1, 1 },
10850 	{ "ERssFceFipPkt", 0, 1 },
10851 	{ NULL }
10852 };
10853 
10854 static const struct field_desc tp_la2[] = {
10855 	{ "CplCmdIn", 56, 8 },
10856 	{ "MpsVfVld", 55, 1 },
10857 	{ "MpsPf", 52, 3 },
10858 	{ "MpsVf", 44, 8 },
10859 	{ "SynIn", 43, 1 },
10860 	{ "AckIn", 42, 1 },
10861 	{ "FinIn", 41, 1 },
10862 	{ "RstIn", 40, 1 },
10863 	{ "DataIn", 39, 1 },
10864 	{ "DataInVld", 38, 1 },
10865 	{ "PadIn", 37, 1 },
10866 	{ "RxBufEmpty", 36, 1 },
10867 	{ "RxDdp", 35, 1 },
10868 	{ "RxFbCongestion", 34, 1 },
10869 	{ "TxFbCongestion", 33, 1 },
10870 	{ "TxPktSumSrdy", 32, 1 },
10871 	{ "RcfUlpType", 28, 4 },
10872 	{ "Eread", 27, 1 },
10873 	{ "Ebypass", 26, 1 },
10874 	{ "Esave", 25, 1 },
10875 	{ "Static0", 24, 1 },
10876 	{ "Cread", 23, 1 },
10877 	{ "Cbypass", 22, 1 },
10878 	{ "Csave", 21, 1 },
10879 	{ "CPktOut", 20, 1 },
10880 	{ "RxPagePoolFull", 18, 2 },
10881 	{ "RxLpbkPkt", 17, 1 },
10882 	{ "TxLpbkPkt", 16, 1 },
10883 	{ "RxVfValid", 15, 1 },
10884 	{ "SynLearned", 14, 1 },
10885 	{ "SetDelEntry", 13, 1 },
10886 	{ "SetInvEntry", 12, 1 },
10887 	{ "CpcmdDvld", 11, 1 },
10888 	{ "CpcmdSave", 10, 1 },
10889 	{ "RxPstructsFull", 8, 2 },
10890 	{ "EpcmdDvld", 7, 1 },
10891 	{ "EpcmdFlush", 6, 1 },
10892 	{ "EpcmdTrimPrefix", 5, 1 },
10893 	{ "EpcmdTrimPostfix", 4, 1 },
10894 	{ "ERssIp4Pkt", 3, 1 },
10895 	{ "ERssIp6Pkt", 2, 1 },
10896 	{ "ERssTcpUdpPkt", 1, 1 },
10897 	{ "ERssFceFipPkt", 0, 1 },
10898 	{ NULL }
10899 };
10900 
10901 static void
10902 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10903 {
10904 
10905 	field_desc_show(sb, *p, tp_la0);
10906 }
10907 
10908 static void
10909 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10910 {
10911 
10912 	if (idx)
10913 		sbuf_printf(sb, "\n");
10914 	field_desc_show(sb, p[0], tp_la0);
10915 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10916 		field_desc_show(sb, p[1], tp_la0);
10917 }
10918 
10919 static void
10920 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
10921 {
10922 
10923 	if (idx)
10924 		sbuf_printf(sb, "\n");
10925 	field_desc_show(sb, p[0], tp_la0);
10926 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10927 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
10928 }
10929 
10930 static int
10931 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
10932 {
10933 	struct adapter *sc = arg1;
10934 	struct sbuf *sb;
10935 	uint64_t *buf, *p;
10936 	int rc;
10937 	u_int i, inc;
10938 	void (*show_func)(struct sbuf *, uint64_t *, int);
10939 
10940 	rc = sysctl_wire_old_buffer(req, 0);
10941 	if (rc != 0)
10942 		return (rc);
10943 
10944 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10945 	if (sb == NULL)
10946 		return (ENOMEM);
10947 
10948 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
10949 
10950 	mtx_lock(&sc->reg_lock);
10951 	if (hw_off_limits(sc))
10952 		rc = ENXIO;
10953 	else {
10954 		t4_tp_read_la(sc, buf, NULL);
10955 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
10956 		case 2:
10957 			inc = 2;
10958 			show_func = tp_la_show2;
10959 			break;
10960 		case 3:
10961 			inc = 2;
10962 			show_func = tp_la_show3;
10963 			break;
10964 		default:
10965 			inc = 1;
10966 			show_func = tp_la_show;
10967 		}
10968 	}
10969 	mtx_unlock(&sc->reg_lock);
10970 	if (rc != 0)
10971 		goto done;
10972 
10973 	p = buf;
10974 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
10975 		(*show_func)(sb, p, i);
10976 	rc = sbuf_finish(sb);
10977 done:
10978 	sbuf_delete(sb);
10979 	free(buf, M_CXGBE);
10980 	return (rc);
10981 }
10982 
10983 static int
10984 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
10985 {
10986 	struct adapter *sc = arg1;
10987 	struct sbuf *sb;
10988 	int rc;
10989 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
10990 
10991 	rc = sysctl_wire_old_buffer(req, 0);
10992 	if (rc != 0)
10993 		return (rc);
10994 
10995 	mtx_lock(&sc->reg_lock);
10996 	if (hw_off_limits(sc))
10997 		rc = ENXIO;
10998 	else
10999 		t4_get_chan_txrate(sc, nrate, orate);
11000 	mtx_unlock(&sc->reg_lock);
11001 	if (rc != 0)
11002 		return (rc);
11003 
11004 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11005 	if (sb == NULL)
11006 		return (ENOMEM);
11007 
11008 	if (sc->chip_params->nchan > 2) {
11009 		sbuf_printf(sb, "              channel 0   channel 1"
11010 		    "   channel 2   channel 3\n");
11011 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
11012 		    nrate[0], nrate[1], nrate[2], nrate[3]);
11013 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
11014 		    orate[0], orate[1], orate[2], orate[3]);
11015 	} else {
11016 		sbuf_printf(sb, "              channel 0   channel 1\n");
11017 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
11018 		    nrate[0], nrate[1]);
11019 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
11020 		    orate[0], orate[1]);
11021 	}
11022 
11023 	rc = sbuf_finish(sb);
11024 	sbuf_delete(sb);
11025 
11026 	return (rc);
11027 }
11028 
11029 static int
11030 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
11031 {
11032 	struct adapter *sc = arg1;
11033 	struct sbuf *sb;
11034 	uint32_t *buf, *p;
11035 	int rc, i;
11036 
11037 	rc = sysctl_wire_old_buffer(req, 0);
11038 	if (rc != 0)
11039 		return (rc);
11040 
11041 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11042 	if (sb == NULL)
11043 		return (ENOMEM);
11044 
11045 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
11046 	    M_ZERO | M_WAITOK);
11047 
11048 	mtx_lock(&sc->reg_lock);
11049 	if (hw_off_limits(sc))
11050 		rc = ENXIO;
11051 	else
11052 		t4_ulprx_read_la(sc, buf);
11053 	mtx_unlock(&sc->reg_lock);
11054 	if (rc != 0)
11055 		goto done;
11056 
11057 	p = buf;
11058 	sbuf_printf(sb, "      Pcmd        Type   Message"
11059 	    "                Data");
11060 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
11061 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
11062 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
11063 	}
11064 	rc = sbuf_finish(sb);
11065 done:
11066 	sbuf_delete(sb);
11067 	free(buf, M_CXGBE);
11068 	return (rc);
11069 }
11070 
11071 static int
11072 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
11073 {
11074 	struct adapter *sc = arg1;
11075 	struct sbuf *sb;
11076 	int rc;
11077 	uint32_t cfg, s1, s2;
11078 
11079 	MPASS(chip_id(sc) >= CHELSIO_T5);
11080 
11081 	rc = sysctl_wire_old_buffer(req, 0);
11082 	if (rc != 0)
11083 		return (rc);
11084 
11085 	mtx_lock(&sc->reg_lock);
11086 	if (hw_off_limits(sc))
11087 		rc = ENXIO;
11088 	else {
11089 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
11090 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
11091 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
11092 	}
11093 	mtx_unlock(&sc->reg_lock);
11094 	if (rc != 0)
11095 		return (rc);
11096 
11097 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11098 	if (sb == NULL)
11099 		return (ENOMEM);
11100 
11101 	if (G_STATSOURCE_T5(cfg) == 7) {
11102 		int mode;
11103 
11104 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
11105 		if (mode == 0)
11106 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
11107 		else if (mode == 1)
11108 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
11109 		else
11110 			sbuf_printf(sb, "unknown mode %d", mode);
11111 	}
11112 	rc = sbuf_finish(sb);
11113 	sbuf_delete(sb);
11114 
11115 	return (rc);
11116 }
11117 
11118 static int
11119 sysctl_cpus(SYSCTL_HANDLER_ARGS)
11120 {
11121 	struct adapter *sc = arg1;
11122 	enum cpu_sets op = arg2;
11123 	cpuset_t cpuset;
11124 	struct sbuf *sb;
11125 	int i, rc;
11126 
11127 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
11128 
11129 	CPU_ZERO(&cpuset);
11130 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
11131 	if (rc != 0)
11132 		return (rc);
11133 
11134 	rc = sysctl_wire_old_buffer(req, 0);
11135 	if (rc != 0)
11136 		return (rc);
11137 
11138 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11139 	if (sb == NULL)
11140 		return (ENOMEM);
11141 
11142 	CPU_FOREACH(i)
11143 		sbuf_printf(sb, "%d ", i);
11144 	rc = sbuf_finish(sb);
11145 	sbuf_delete(sb);
11146 
11147 	return (rc);
11148 }
11149 
11150 static int
11151 sysctl_reset(SYSCTL_HANDLER_ARGS)
11152 {
11153 	struct adapter *sc = arg1;
11154 	u_int val;
11155 	int rc;
11156 
11157 	val = atomic_load_int(&sc->num_resets);
11158 	rc = sysctl_handle_int(oidp, &val, 0, req);
11159 	if (rc != 0 || req->newptr == NULL)
11160 		return (rc);
11161 
11162 	if (val == 0) {
11163 		/* Zero out the counter that tracks reset. */
11164 		atomic_store_int(&sc->num_resets, 0);
11165 		return (0);
11166 	}
11167 
11168 	if (val != 1)
11169 		return (EINVAL);	/* 0 or 1 are the only legal values */
11170 
11171 	if (hw_off_limits(sc))		/* harmless race */
11172 		return (EALREADY);
11173 
11174 	taskqueue_enqueue(reset_tq, &sc->reset_task);
11175 	return (0);
11176 }
11177 
11178 #ifdef TCP_OFFLOAD
11179 static int
11180 sysctl_tls(SYSCTL_HANDLER_ARGS)
11181 {
11182 	struct adapter *sc = arg1;
11183 	int i, j, v, rc;
11184 	struct vi_info *vi;
11185 
11186 	v = sc->tt.tls;
11187 	rc = sysctl_handle_int(oidp, &v, 0, req);
11188 	if (rc != 0 || req->newptr == NULL)
11189 		return (rc);
11190 
11191 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11192 		return (ENOTSUP);
11193 
11194 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11195 	if (rc)
11196 		return (rc);
11197 	if (hw_off_limits(sc))
11198 		rc = ENXIO;
11199 	else {
11200 		sc->tt.tls = !!v;
11201 		for_each_port(sc, i) {
11202 			for_each_vi(sc->port[i], j, vi) {
11203 				if (vi->flags & VI_INIT_DONE)
11204 					t4_update_fl_bufsize(vi->ifp);
11205 			}
11206 		}
11207 	}
11208 	end_synchronized_op(sc, 0);
11209 
11210 	return (rc);
11211 
11212 }
11213 
11214 static int
11215 sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS)
11216 {
11217 	struct adapter *sc = arg1;
11218 	int *old_ports, *new_ports;
11219 	int i, new_count, rc;
11220 
11221 	if (req->newptr == NULL && req->oldptr == NULL)
11222 		return (SYSCTL_OUT(req, NULL, imax(sc->tt.num_tls_rx_ports, 1) *
11223 		    sizeof(sc->tt.tls_rx_ports[0])));
11224 
11225 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tlsrx");
11226 	if (rc)
11227 		return (rc);
11228 
11229 	if (hw_off_limits(sc)) {
11230 		rc = ENXIO;
11231 		goto done;
11232 	}
11233 
11234 	if (sc->tt.num_tls_rx_ports == 0) {
11235 		i = -1;
11236 		rc = SYSCTL_OUT(req, &i, sizeof(i));
11237 	} else
11238 		rc = SYSCTL_OUT(req, sc->tt.tls_rx_ports,
11239 		    sc->tt.num_tls_rx_ports * sizeof(sc->tt.tls_rx_ports[0]));
11240 	if (rc == 0 && req->newptr != NULL) {
11241 		new_count = req->newlen / sizeof(new_ports[0]);
11242 		new_ports = malloc(new_count * sizeof(new_ports[0]), M_CXGBE,
11243 		    M_WAITOK);
11244 		rc = SYSCTL_IN(req, new_ports, new_count *
11245 		    sizeof(new_ports[0]));
11246 		if (rc)
11247 			goto err;
11248 
11249 		/* Allow setting to a single '-1' to clear the list. */
11250 		if (new_count == 1 && new_ports[0] == -1) {
11251 			ADAPTER_LOCK(sc);
11252 			old_ports = sc->tt.tls_rx_ports;
11253 			sc->tt.tls_rx_ports = NULL;
11254 			sc->tt.num_tls_rx_ports = 0;
11255 			ADAPTER_UNLOCK(sc);
11256 			free(old_ports, M_CXGBE);
11257 		} else {
11258 			for (i = 0; i < new_count; i++) {
11259 				if (new_ports[i] < 1 ||
11260 				    new_ports[i] > IPPORT_MAX) {
11261 					rc = EINVAL;
11262 					goto err;
11263 				}
11264 			}
11265 
11266 			ADAPTER_LOCK(sc);
11267 			old_ports = sc->tt.tls_rx_ports;
11268 			sc->tt.tls_rx_ports = new_ports;
11269 			sc->tt.num_tls_rx_ports = new_count;
11270 			ADAPTER_UNLOCK(sc);
11271 			free(old_ports, M_CXGBE);
11272 			new_ports = NULL;
11273 		}
11274 	err:
11275 		free(new_ports, M_CXGBE);
11276 	}
11277 done:
11278 	end_synchronized_op(sc, 0);
11279 	return (rc);
11280 }
11281 
11282 static int
11283 sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS)
11284 {
11285 	struct adapter *sc = arg1;
11286 	int v, rc;
11287 
11288 	v = sc->tt.tls_rx_timeout;
11289 	rc = sysctl_handle_int(oidp, &v, 0, req);
11290 	if (rc != 0 || req->newptr == NULL)
11291 		return (rc);
11292 
11293 	if (v < 0)
11294 		return (EINVAL);
11295 
11296 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11297 		return (ENOTSUP);
11298 
11299 	sc->tt.tls_rx_timeout = v;
11300 
11301 	return (0);
11302 
11303 }
11304 
11305 static void
11306 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11307 {
11308 	u_int rem = val % factor;
11309 
11310 	if (rem == 0)
11311 		snprintf(buf, len, "%u", val / factor);
11312 	else {
11313 		while (rem % 10 == 0)
11314 			rem /= 10;
11315 		snprintf(buf, len, "%u.%u", val / factor, rem);
11316 	}
11317 }
11318 
11319 static int
11320 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11321 {
11322 	struct adapter *sc = arg1;
11323 	char buf[16];
11324 	u_int res, re;
11325 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11326 
11327 	mtx_lock(&sc->reg_lock);
11328 	if (hw_off_limits(sc))
11329 		res = (u_int)-1;
11330 	else
11331 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11332 	mtx_unlock(&sc->reg_lock);
11333 	if (res == (u_int)-1)
11334 		return (ENXIO);
11335 
11336 	switch (arg2) {
11337 	case 0:
11338 		/* timer_tick */
11339 		re = G_TIMERRESOLUTION(res);
11340 		break;
11341 	case 1:
11342 		/* TCP timestamp tick */
11343 		re = G_TIMESTAMPRESOLUTION(res);
11344 		break;
11345 	case 2:
11346 		/* DACK tick */
11347 		re = G_DELAYEDACKRESOLUTION(res);
11348 		break;
11349 	default:
11350 		return (EDOOFUS);
11351 	}
11352 
11353 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11354 
11355 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11356 }
11357 
11358 static int
11359 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11360 {
11361 	struct adapter *sc = arg1;
11362 	int rc;
11363 	u_int dack_tmr, dack_re, v;
11364 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11365 
11366 	mtx_lock(&sc->reg_lock);
11367 	if (hw_off_limits(sc))
11368 		rc = ENXIO;
11369 	else {
11370 		rc = 0;
11371 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11372 		    A_TP_TIMER_RESOLUTION));
11373 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11374 	}
11375 	mtx_unlock(&sc->reg_lock);
11376 	if (rc != 0)
11377 		return (rc);
11378 
11379 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11380 
11381 	return (sysctl_handle_int(oidp, &v, 0, req));
11382 }
11383 
11384 static int
11385 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11386 {
11387 	struct adapter *sc = arg1;
11388 	int rc, reg = arg2;
11389 	u_int tre;
11390 	u_long tp_tick_us, v;
11391 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11392 
11393 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11394 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11395 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11396 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11397 
11398 	mtx_lock(&sc->reg_lock);
11399 	if (hw_off_limits(sc))
11400 		rc = ENXIO;
11401 	else {
11402 		rc = 0;
11403 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11404 		tp_tick_us = (cclk_ps << tre) / 1000000;
11405 		if (reg == A_TP_INIT_SRTT)
11406 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11407 		else
11408 			v = tp_tick_us * t4_read_reg(sc, reg);
11409 	}
11410 	mtx_unlock(&sc->reg_lock);
11411 	if (rc != 0)
11412 		return (rc);
11413 	else
11414 		return (sysctl_handle_long(oidp, &v, 0, req));
11415 }
11416 
11417 /*
11418  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11419  * passed to this function.
11420  */
11421 static int
11422 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11423 {
11424 	struct adapter *sc = arg1;
11425 	int rc, idx = arg2;
11426 	u_int v;
11427 
11428 	MPASS(idx >= 0 && idx <= 24);
11429 
11430 	mtx_lock(&sc->reg_lock);
11431 	if (hw_off_limits(sc))
11432 		rc = ENXIO;
11433 	else {
11434 		rc = 0;
11435 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11436 	}
11437 	mtx_unlock(&sc->reg_lock);
11438 	if (rc != 0)
11439 		return (rc);
11440 	else
11441 		return (sysctl_handle_int(oidp, &v, 0, req));
11442 }
11443 
11444 static int
11445 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11446 {
11447 	struct adapter *sc = arg1;
11448 	int rc, idx = arg2;
11449 	u_int shift, v, r;
11450 
11451 	MPASS(idx >= 0 && idx < 16);
11452 
11453 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11454 	shift = (idx & 3) << 3;
11455 	mtx_lock(&sc->reg_lock);
11456 	if (hw_off_limits(sc))
11457 		rc = ENXIO;
11458 	else {
11459 		rc = 0;
11460 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11461 	}
11462 	mtx_unlock(&sc->reg_lock);
11463 	if (rc != 0)
11464 		return (rc);
11465 	else
11466 		return (sysctl_handle_int(oidp, &v, 0, req));
11467 }
11468 
11469 static int
11470 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11471 {
11472 	struct vi_info *vi = arg1;
11473 	struct adapter *sc = vi->adapter;
11474 	int idx, rc, i;
11475 	struct sge_ofld_rxq *ofld_rxq;
11476 	uint8_t v;
11477 
11478 	idx = vi->ofld_tmr_idx;
11479 
11480 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11481 	if (rc != 0 || req->newptr == NULL)
11482 		return (rc);
11483 
11484 	if (idx < 0 || idx >= SGE_NTIMERS)
11485 		return (EINVAL);
11486 
11487 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11488 	    "t4otmr");
11489 	if (rc)
11490 		return (rc);
11491 
11492 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11493 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11494 #ifdef atomic_store_rel_8
11495 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11496 #else
11497 		ofld_rxq->iq.intr_params = v;
11498 #endif
11499 	}
11500 	vi->ofld_tmr_idx = idx;
11501 
11502 	end_synchronized_op(sc, LOCK_HELD);
11503 	return (0);
11504 }
11505 
11506 static int
11507 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11508 {
11509 	struct vi_info *vi = arg1;
11510 	struct adapter *sc = vi->adapter;
11511 	int idx, rc;
11512 
11513 	idx = vi->ofld_pktc_idx;
11514 
11515 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11516 	if (rc != 0 || req->newptr == NULL)
11517 		return (rc);
11518 
11519 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11520 		return (EINVAL);
11521 
11522 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11523 	    "t4opktc");
11524 	if (rc)
11525 		return (rc);
11526 
11527 	if (vi->flags & VI_INIT_DONE)
11528 		rc = EBUSY; /* cannot be changed once the queues are created */
11529 	else
11530 		vi->ofld_pktc_idx = idx;
11531 
11532 	end_synchronized_op(sc, LOCK_HELD);
11533 	return (rc);
11534 }
11535 #endif
11536 
11537 static int
11538 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11539 {
11540 	int rc;
11541 
11542 	if (cntxt->cid > M_CTXTQID)
11543 		return (EINVAL);
11544 
11545 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11546 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11547 		return (EINVAL);
11548 
11549 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11550 	if (rc)
11551 		return (rc);
11552 
11553 	if (hw_off_limits(sc)) {
11554 		rc = ENXIO;
11555 		goto done;
11556 	}
11557 
11558 	if (sc->flags & FW_OK) {
11559 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11560 		    &cntxt->data[0]);
11561 		if (rc == 0)
11562 			goto done;
11563 	}
11564 
11565 	/*
11566 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11567 	 * the backdoor.
11568 	 */
11569 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11570 done:
11571 	end_synchronized_op(sc, 0);
11572 	return (rc);
11573 }
11574 
11575 static int
11576 load_fw(struct adapter *sc, struct t4_data *fw)
11577 {
11578 	int rc;
11579 	uint8_t *fw_data;
11580 
11581 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11582 	if (rc)
11583 		return (rc);
11584 
11585 	if (hw_off_limits(sc)) {
11586 		rc = ENXIO;
11587 		goto done;
11588 	}
11589 
11590 	/*
11591 	 * The firmware, with the sole exception of the memory parity error
11592 	 * handler, runs from memory and not flash.  It is almost always safe to
11593 	 * install a new firmware on a running system.  Just set bit 1 in
11594 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11595 	 */
11596 	if (sc->flags & FULL_INIT_DONE &&
11597 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11598 		rc = EBUSY;
11599 		goto done;
11600 	}
11601 
11602 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11603 
11604 	rc = copyin(fw->data, fw_data, fw->len);
11605 	if (rc == 0)
11606 		rc = -t4_load_fw(sc, fw_data, fw->len);
11607 
11608 	free(fw_data, M_CXGBE);
11609 done:
11610 	end_synchronized_op(sc, 0);
11611 	return (rc);
11612 }
11613 
11614 static int
11615 load_cfg(struct adapter *sc, struct t4_data *cfg)
11616 {
11617 	int rc;
11618 	uint8_t *cfg_data = NULL;
11619 
11620 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11621 	if (rc)
11622 		return (rc);
11623 
11624 	if (hw_off_limits(sc)) {
11625 		rc = ENXIO;
11626 		goto done;
11627 	}
11628 
11629 	if (cfg->len == 0) {
11630 		/* clear */
11631 		rc = -t4_load_cfg(sc, NULL, 0);
11632 		goto done;
11633 	}
11634 
11635 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11636 
11637 	rc = copyin(cfg->data, cfg_data, cfg->len);
11638 	if (rc == 0)
11639 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11640 
11641 	free(cfg_data, M_CXGBE);
11642 done:
11643 	end_synchronized_op(sc, 0);
11644 	return (rc);
11645 }
11646 
11647 static int
11648 load_boot(struct adapter *sc, struct t4_bootrom *br)
11649 {
11650 	int rc;
11651 	uint8_t *br_data = NULL;
11652 	u_int offset;
11653 
11654 	if (br->len > 1024 * 1024)
11655 		return (EFBIG);
11656 
11657 	if (br->pf_offset == 0) {
11658 		/* pfidx */
11659 		if (br->pfidx_addr > 7)
11660 			return (EINVAL);
11661 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11662 		    A_PCIE_PF_EXPROM_OFST)));
11663 	} else if (br->pf_offset == 1) {
11664 		/* offset */
11665 		offset = G_OFFSET(br->pfidx_addr);
11666 	} else {
11667 		return (EINVAL);
11668 	}
11669 
11670 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11671 	if (rc)
11672 		return (rc);
11673 
11674 	if (hw_off_limits(sc)) {
11675 		rc = ENXIO;
11676 		goto done;
11677 	}
11678 
11679 	if (br->len == 0) {
11680 		/* clear */
11681 		rc = -t4_load_boot(sc, NULL, offset, 0);
11682 		goto done;
11683 	}
11684 
11685 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11686 
11687 	rc = copyin(br->data, br_data, br->len);
11688 	if (rc == 0)
11689 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11690 
11691 	free(br_data, M_CXGBE);
11692 done:
11693 	end_synchronized_op(sc, 0);
11694 	return (rc);
11695 }
11696 
11697 static int
11698 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11699 {
11700 	int rc;
11701 	uint8_t *bc_data = NULL;
11702 
11703 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11704 	if (rc)
11705 		return (rc);
11706 
11707 	if (hw_off_limits(sc)) {
11708 		rc = ENXIO;
11709 		goto done;
11710 	}
11711 
11712 	if (bc->len == 0) {
11713 		/* clear */
11714 		rc = -t4_load_bootcfg(sc, NULL, 0);
11715 		goto done;
11716 	}
11717 
11718 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11719 
11720 	rc = copyin(bc->data, bc_data, bc->len);
11721 	if (rc == 0)
11722 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11723 
11724 	free(bc_data, M_CXGBE);
11725 done:
11726 	end_synchronized_op(sc, 0);
11727 	return (rc);
11728 }
11729 
11730 static int
11731 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11732 {
11733 	int rc;
11734 	struct cudbg_init *cudbg;
11735 	void *handle, *buf;
11736 
11737 	/* buf is large, don't block if no memory is available */
11738 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11739 	if (buf == NULL)
11740 		return (ENOMEM);
11741 
11742 	handle = cudbg_alloc_handle();
11743 	if (handle == NULL) {
11744 		rc = ENOMEM;
11745 		goto done;
11746 	}
11747 
11748 	cudbg = cudbg_get_init(handle);
11749 	cudbg->adap = sc;
11750 	cudbg->print = (cudbg_print_cb)printf;
11751 
11752 #ifndef notyet
11753 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11754 	    __func__, dump->wr_flash, dump->len, dump->data);
11755 #endif
11756 
11757 	if (dump->wr_flash)
11758 		cudbg->use_flash = 1;
11759 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11760 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11761 
11762 	rc = cudbg_collect(handle, buf, &dump->len);
11763 	if (rc != 0)
11764 		goto done;
11765 
11766 	rc = copyout(buf, dump->data, dump->len);
11767 done:
11768 	cudbg_free_handle(handle);
11769 	free(buf, M_CXGBE);
11770 	return (rc);
11771 }
11772 
11773 static void
11774 free_offload_policy(struct t4_offload_policy *op)
11775 {
11776 	struct offload_rule *r;
11777 	int i;
11778 
11779 	if (op == NULL)
11780 		return;
11781 
11782 	r = &op->rule[0];
11783 	for (i = 0; i < op->nrules; i++, r++) {
11784 		free(r->bpf_prog.bf_insns, M_CXGBE);
11785 	}
11786 	free(op->rule, M_CXGBE);
11787 	free(op, M_CXGBE);
11788 }
11789 
11790 static int
11791 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11792 {
11793 	int i, rc, len;
11794 	struct t4_offload_policy *op, *old;
11795 	struct bpf_program *bf;
11796 	const struct offload_settings *s;
11797 	struct offload_rule *r;
11798 	void *u;
11799 
11800 	if (!is_offload(sc))
11801 		return (ENODEV);
11802 
11803 	if (uop->nrules == 0) {
11804 		/* Delete installed policies. */
11805 		op = NULL;
11806 		goto set_policy;
11807 	} else if (uop->nrules > 256) { /* arbitrary */
11808 		return (E2BIG);
11809 	}
11810 
11811 	/* Copy userspace offload policy to kernel */
11812 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11813 	op->nrules = uop->nrules;
11814 	len = op->nrules * sizeof(struct offload_rule);
11815 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11816 	rc = copyin(uop->rule, op->rule, len);
11817 	if (rc) {
11818 		free(op->rule, M_CXGBE);
11819 		free(op, M_CXGBE);
11820 		return (rc);
11821 	}
11822 
11823 	r = &op->rule[0];
11824 	for (i = 0; i < op->nrules; i++, r++) {
11825 
11826 		/* Validate open_type */
11827 		if (r->open_type != OPEN_TYPE_LISTEN &&
11828 		    r->open_type != OPEN_TYPE_ACTIVE &&
11829 		    r->open_type != OPEN_TYPE_PASSIVE &&
11830 		    r->open_type != OPEN_TYPE_DONTCARE) {
11831 error:
11832 			/*
11833 			 * Rules 0 to i have malloc'd filters that need to be
11834 			 * freed.  Rules i+1 to nrules have userspace pointers
11835 			 * and should be left alone.
11836 			 */
11837 			op->nrules = i;
11838 			free_offload_policy(op);
11839 			return (rc);
11840 		}
11841 
11842 		/* Validate settings */
11843 		s = &r->settings;
11844 		if ((s->offload != 0 && s->offload != 1) ||
11845 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11846 		    s->sched_class < -1 ||
11847 		    s->sched_class >= sc->params.nsched_cls) {
11848 			rc = EINVAL;
11849 			goto error;
11850 		}
11851 
11852 		bf = &r->bpf_prog;
11853 		u = bf->bf_insns;	/* userspace ptr */
11854 		bf->bf_insns = NULL;
11855 		if (bf->bf_len == 0) {
11856 			/* legal, matches everything */
11857 			continue;
11858 		}
11859 		len = bf->bf_len * sizeof(*bf->bf_insns);
11860 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11861 		rc = copyin(u, bf->bf_insns, len);
11862 		if (rc != 0)
11863 			goto error;
11864 
11865 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11866 			rc = EINVAL;
11867 			goto error;
11868 		}
11869 	}
11870 set_policy:
11871 	rw_wlock(&sc->policy_lock);
11872 	old = sc->policy;
11873 	sc->policy = op;
11874 	rw_wunlock(&sc->policy_lock);
11875 	free_offload_policy(old);
11876 
11877 	return (0);
11878 }
11879 
11880 #define MAX_READ_BUF_SIZE (128 * 1024)
11881 static int
11882 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11883 {
11884 	uint32_t addr, remaining, n;
11885 	uint32_t *buf;
11886 	int rc;
11887 	uint8_t *dst;
11888 
11889 	mtx_lock(&sc->reg_lock);
11890 	if (hw_off_limits(sc))
11891 		rc = ENXIO;
11892 	else
11893 		rc = validate_mem_range(sc, mr->addr, mr->len);
11894 	mtx_unlock(&sc->reg_lock);
11895 	if (rc != 0)
11896 		return (rc);
11897 
11898 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11899 	addr = mr->addr;
11900 	remaining = mr->len;
11901 	dst = (void *)mr->data;
11902 
11903 	while (remaining) {
11904 		n = min(remaining, MAX_READ_BUF_SIZE);
11905 		mtx_lock(&sc->reg_lock);
11906 		if (hw_off_limits(sc))
11907 			rc = ENXIO;
11908 		else
11909 			read_via_memwin(sc, 2, addr, buf, n);
11910 		mtx_unlock(&sc->reg_lock);
11911 		if (rc != 0)
11912 			break;
11913 
11914 		rc = copyout(buf, dst, n);
11915 		if (rc != 0)
11916 			break;
11917 
11918 		dst += n;
11919 		remaining -= n;
11920 		addr += n;
11921 	}
11922 
11923 	free(buf, M_CXGBE);
11924 	return (rc);
11925 }
11926 #undef MAX_READ_BUF_SIZE
11927 
11928 static int
11929 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11930 {
11931 	int rc;
11932 
11933 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11934 		return (EINVAL);
11935 
11936 	if (i2cd->len > sizeof(i2cd->data))
11937 		return (EFBIG);
11938 
11939 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11940 	if (rc)
11941 		return (rc);
11942 	if (hw_off_limits(sc))
11943 		rc = ENXIO;
11944 	else
11945 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11946 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11947 	end_synchronized_op(sc, 0);
11948 
11949 	return (rc);
11950 }
11951 
11952 static int
11953 clear_stats(struct adapter *sc, u_int port_id)
11954 {
11955 	int i, v, chan_map;
11956 	struct port_info *pi;
11957 	struct vi_info *vi;
11958 	struct sge_rxq *rxq;
11959 	struct sge_txq *txq;
11960 	struct sge_wrq *wrq;
11961 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11962 	struct sge_ofld_txq *ofld_txq;
11963 #endif
11964 #ifdef TCP_OFFLOAD
11965 	struct sge_ofld_rxq *ofld_rxq;
11966 #endif
11967 
11968 	if (port_id >= sc->params.nports)
11969 		return (EINVAL);
11970 	pi = sc->port[port_id];
11971 	if (pi == NULL)
11972 		return (EIO);
11973 
11974 	mtx_lock(&sc->reg_lock);
11975 	if (!hw_off_limits(sc)) {
11976 		/* MAC stats */
11977 		t4_clr_port_stats(sc, pi->tx_chan);
11978 		if (is_t6(sc)) {
11979 			if (pi->fcs_reg != -1)
11980 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11981 			else
11982 				pi->stats.rx_fcs_err = 0;
11983 		}
11984 		for_each_vi(pi, v, vi) {
11985 			if (vi->flags & VI_INIT_DONE)
11986 				t4_clr_vi_stats(sc, vi->vin);
11987 		}
11988 		chan_map = pi->rx_e_chan_map;
11989 		v = 0;	/* reuse */
11990 		while (chan_map) {
11991 			i = ffs(chan_map) - 1;
11992 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11993 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11994 			chan_map &= ~(1 << i);
11995 		}
11996 	}
11997 	mtx_unlock(&sc->reg_lock);
11998 	pi->tx_parse_error = 0;
11999 	pi->tnl_cong_drops = 0;
12000 
12001 	/*
12002 	 * Since this command accepts a port, clear stats for
12003 	 * all VIs on this port.
12004 	 */
12005 	for_each_vi(pi, v, vi) {
12006 		if (vi->flags & VI_INIT_DONE) {
12007 
12008 			for_each_rxq(vi, i, rxq) {
12009 #if defined(INET) || defined(INET6)
12010 				rxq->lro.lro_queued = 0;
12011 				rxq->lro.lro_flushed = 0;
12012 #endif
12013 				rxq->rxcsum = 0;
12014 				rxq->vlan_extraction = 0;
12015 				rxq->vxlan_rxcsum = 0;
12016 
12017 				rxq->fl.cl_allocated = 0;
12018 				rxq->fl.cl_recycled = 0;
12019 				rxq->fl.cl_fast_recycled = 0;
12020 			}
12021 
12022 			for_each_txq(vi, i, txq) {
12023 				txq->txcsum = 0;
12024 				txq->tso_wrs = 0;
12025 				txq->vlan_insertion = 0;
12026 				txq->imm_wrs = 0;
12027 				txq->sgl_wrs = 0;
12028 				txq->txpkt_wrs = 0;
12029 				txq->txpkts0_wrs = 0;
12030 				txq->txpkts1_wrs = 0;
12031 				txq->txpkts0_pkts = 0;
12032 				txq->txpkts1_pkts = 0;
12033 				txq->txpkts_flush = 0;
12034 				txq->raw_wrs = 0;
12035 				txq->vxlan_tso_wrs = 0;
12036 				txq->vxlan_txcsum = 0;
12037 				txq->kern_tls_records = 0;
12038 				txq->kern_tls_short = 0;
12039 				txq->kern_tls_partial = 0;
12040 				txq->kern_tls_full = 0;
12041 				txq->kern_tls_octets = 0;
12042 				txq->kern_tls_waste = 0;
12043 				txq->kern_tls_options = 0;
12044 				txq->kern_tls_header = 0;
12045 				txq->kern_tls_fin = 0;
12046 				txq->kern_tls_fin_short = 0;
12047 				txq->kern_tls_cbc = 0;
12048 				txq->kern_tls_gcm = 0;
12049 				mp_ring_reset_stats(txq->r);
12050 			}
12051 
12052 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12053 			for_each_ofld_txq(vi, i, ofld_txq) {
12054 				ofld_txq->wrq.tx_wrs_direct = 0;
12055 				ofld_txq->wrq.tx_wrs_copied = 0;
12056 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
12057 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
12058 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
12059 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
12060 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
12061 			}
12062 #endif
12063 #ifdef TCP_OFFLOAD
12064 			for_each_ofld_rxq(vi, i, ofld_rxq) {
12065 				ofld_rxq->fl.cl_allocated = 0;
12066 				ofld_rxq->fl.cl_recycled = 0;
12067 				ofld_rxq->fl.cl_fast_recycled = 0;
12068 				counter_u64_zero(
12069 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
12070 				counter_u64_zero(
12071 				    ofld_rxq->rx_iscsi_ddp_setup_error);
12072 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
12073 				ofld_rxq->rx_iscsi_ddp_octets = 0;
12074 				ofld_rxq->rx_iscsi_fl_pdus = 0;
12075 				ofld_rxq->rx_iscsi_fl_octets = 0;
12076 				ofld_rxq->rx_toe_tls_records = 0;
12077 				ofld_rxq->rx_toe_tls_octets = 0;
12078 			}
12079 #endif
12080 
12081 			if (IS_MAIN_VI(vi)) {
12082 				wrq = &sc->sge.ctrlq[pi->port_id];
12083 				wrq->tx_wrs_direct = 0;
12084 				wrq->tx_wrs_copied = 0;
12085 			}
12086 		}
12087 	}
12088 
12089 	return (0);
12090 }
12091 
12092 static int
12093 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12094 {
12095 #ifdef INET6
12096 	struct in6_addr in6;
12097 
12098 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12099 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
12100 		return (0);
12101 	else
12102 		return (EIO);
12103 #else
12104 	return (ENOTSUP);
12105 #endif
12106 }
12107 
12108 static int
12109 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12110 {
12111 #ifdef INET6
12112 	struct in6_addr in6;
12113 
12114 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12115 	return (t4_release_clip_addr(sc, &in6));
12116 #else
12117 	return (ENOTSUP);
12118 #endif
12119 }
12120 
12121 int
12122 t4_os_find_pci_capability(struct adapter *sc, int cap)
12123 {
12124 	int i;
12125 
12126 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
12127 }
12128 
12129 int
12130 t4_os_pci_save_state(struct adapter *sc)
12131 {
12132 	device_t dev;
12133 	struct pci_devinfo *dinfo;
12134 
12135 	dev = sc->dev;
12136 	dinfo = device_get_ivars(dev);
12137 
12138 	pci_cfg_save(dev, dinfo, 0);
12139 	return (0);
12140 }
12141 
12142 int
12143 t4_os_pci_restore_state(struct adapter *sc)
12144 {
12145 	device_t dev;
12146 	struct pci_devinfo *dinfo;
12147 
12148 	dev = sc->dev;
12149 	dinfo = device_get_ivars(dev);
12150 
12151 	pci_cfg_restore(dev, dinfo);
12152 	return (0);
12153 }
12154 
12155 void
12156 t4_os_portmod_changed(struct port_info *pi)
12157 {
12158 	struct adapter *sc = pi->adapter;
12159 	struct vi_info *vi;
12160 	struct ifnet *ifp;
12161 	static const char *mod_str[] = {
12162 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
12163 	};
12164 
12165 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
12166 	    ("%s: port_type %u", __func__, pi->port_type));
12167 
12168 	vi = &pi->vi[0];
12169 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12170 		PORT_LOCK(pi);
12171 		build_medialist(pi);
12172 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12173 			fixup_link_config(pi);
12174 			apply_link_config(pi);
12175 		}
12176 		PORT_UNLOCK(pi);
12177 		end_synchronized_op(sc, LOCK_HELD);
12178 	}
12179 
12180 	ifp = vi->ifp;
12181 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12182 		if_printf(ifp, "transceiver unplugged.\n");
12183 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12184 		if_printf(ifp, "unknown transceiver inserted.\n");
12185 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12186 		if_printf(ifp, "unsupported transceiver inserted.\n");
12187 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12188 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12189 		    port_top_speed(pi), mod_str[pi->mod_type]);
12190 	} else {
12191 		if_printf(ifp, "transceiver (type %d) inserted.\n",
12192 		    pi->mod_type);
12193 	}
12194 }
12195 
12196 void
12197 t4_os_link_changed(struct port_info *pi)
12198 {
12199 	struct vi_info *vi;
12200 	struct ifnet *ifp;
12201 	struct link_config *lc = &pi->link_cfg;
12202 	struct adapter *sc = pi->adapter;
12203 	int v;
12204 
12205 	PORT_LOCK_ASSERT_OWNED(pi);
12206 
12207 	if (is_t6(sc)) {
12208 		if (lc->link_ok) {
12209 			if (lc->speed > 25000 ||
12210 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12211 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12212 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12213 			} else {
12214 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12215 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12216 			}
12217 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12218 			pi->stats.rx_fcs_err = 0;
12219 		} else {
12220 			pi->fcs_reg = -1;
12221 		}
12222 	} else {
12223 		MPASS(pi->fcs_reg != -1);
12224 		MPASS(pi->fcs_base == 0);
12225 	}
12226 
12227 	for_each_vi(pi, v, vi) {
12228 		ifp = vi->ifp;
12229 		if (ifp == NULL)
12230 			continue;
12231 
12232 		if (lc->link_ok) {
12233 			ifp->if_baudrate = IF_Mbps(lc->speed);
12234 			if_link_state_change(ifp, LINK_STATE_UP);
12235 		} else {
12236 			if_link_state_change(ifp, LINK_STATE_DOWN);
12237 		}
12238 	}
12239 }
12240 
12241 void
12242 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12243 {
12244 	struct adapter *sc;
12245 
12246 	sx_slock(&t4_list_lock);
12247 	SLIST_FOREACH(sc, &t4_list, link) {
12248 		/*
12249 		 * func should not make any assumptions about what state sc is
12250 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12251 		 */
12252 		func(sc, arg);
12253 	}
12254 	sx_sunlock(&t4_list_lock);
12255 }
12256 
12257 static int
12258 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12259     struct thread *td)
12260 {
12261 	int rc;
12262 	struct adapter *sc = dev->si_drv1;
12263 
12264 	rc = priv_check(td, PRIV_DRIVER);
12265 	if (rc != 0)
12266 		return (rc);
12267 
12268 	switch (cmd) {
12269 	case CHELSIO_T4_GETREG: {
12270 		struct t4_reg *edata = (struct t4_reg *)data;
12271 
12272 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12273 			return (EFAULT);
12274 
12275 		mtx_lock(&sc->reg_lock);
12276 		if (hw_off_limits(sc))
12277 			rc = ENXIO;
12278 		else if (edata->size == 4)
12279 			edata->val = t4_read_reg(sc, edata->addr);
12280 		else if (edata->size == 8)
12281 			edata->val = t4_read_reg64(sc, edata->addr);
12282 		else
12283 			rc = EINVAL;
12284 		mtx_unlock(&sc->reg_lock);
12285 
12286 		break;
12287 	}
12288 	case CHELSIO_T4_SETREG: {
12289 		struct t4_reg *edata = (struct t4_reg *)data;
12290 
12291 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12292 			return (EFAULT);
12293 
12294 		mtx_lock(&sc->reg_lock);
12295 		if (hw_off_limits(sc))
12296 			rc = ENXIO;
12297 		else if (edata->size == 4) {
12298 			if (edata->val & 0xffffffff00000000)
12299 				rc = EINVAL;
12300 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12301 		} else if (edata->size == 8)
12302 			t4_write_reg64(sc, edata->addr, edata->val);
12303 		else
12304 			rc = EINVAL;
12305 		mtx_unlock(&sc->reg_lock);
12306 
12307 		break;
12308 	}
12309 	case CHELSIO_T4_REGDUMP: {
12310 		struct t4_regdump *regs = (struct t4_regdump *)data;
12311 		int reglen = t4_get_regs_len(sc);
12312 		uint8_t *buf;
12313 
12314 		if (regs->len < reglen) {
12315 			regs->len = reglen; /* hint to the caller */
12316 			return (ENOBUFS);
12317 		}
12318 
12319 		regs->len = reglen;
12320 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12321 		mtx_lock(&sc->reg_lock);
12322 		if (hw_off_limits(sc))
12323 			rc = ENXIO;
12324 		else
12325 			get_regs(sc, regs, buf);
12326 		mtx_unlock(&sc->reg_lock);
12327 		if (rc == 0)
12328 			rc = copyout(buf, regs->data, reglen);
12329 		free(buf, M_CXGBE);
12330 		break;
12331 	}
12332 	case CHELSIO_T4_GET_FILTER_MODE:
12333 		rc = get_filter_mode(sc, (uint32_t *)data);
12334 		break;
12335 	case CHELSIO_T4_SET_FILTER_MODE:
12336 		rc = set_filter_mode(sc, *(uint32_t *)data);
12337 		break;
12338 	case CHELSIO_T4_SET_FILTER_MASK:
12339 		rc = set_filter_mask(sc, *(uint32_t *)data);
12340 		break;
12341 	case CHELSIO_T4_GET_FILTER:
12342 		rc = get_filter(sc, (struct t4_filter *)data);
12343 		break;
12344 	case CHELSIO_T4_SET_FILTER:
12345 		rc = set_filter(sc, (struct t4_filter *)data);
12346 		break;
12347 	case CHELSIO_T4_DEL_FILTER:
12348 		rc = del_filter(sc, (struct t4_filter *)data);
12349 		break;
12350 	case CHELSIO_T4_GET_SGE_CONTEXT:
12351 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12352 		break;
12353 	case CHELSIO_T4_LOAD_FW:
12354 		rc = load_fw(sc, (struct t4_data *)data);
12355 		break;
12356 	case CHELSIO_T4_GET_MEM:
12357 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12358 		break;
12359 	case CHELSIO_T4_GET_I2C:
12360 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12361 		break;
12362 	case CHELSIO_T4_CLEAR_STATS:
12363 		rc = clear_stats(sc, *(uint32_t *)data);
12364 		break;
12365 	case CHELSIO_T4_SCHED_CLASS:
12366 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12367 		break;
12368 	case CHELSIO_T4_SCHED_QUEUE:
12369 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12370 		break;
12371 	case CHELSIO_T4_GET_TRACER:
12372 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12373 		break;
12374 	case CHELSIO_T4_SET_TRACER:
12375 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12376 		break;
12377 	case CHELSIO_T4_LOAD_CFG:
12378 		rc = load_cfg(sc, (struct t4_data *)data);
12379 		break;
12380 	case CHELSIO_T4_LOAD_BOOT:
12381 		rc = load_boot(sc, (struct t4_bootrom *)data);
12382 		break;
12383 	case CHELSIO_T4_LOAD_BOOTCFG:
12384 		rc = load_bootcfg(sc, (struct t4_data *)data);
12385 		break;
12386 	case CHELSIO_T4_CUDBG_DUMP:
12387 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12388 		break;
12389 	case CHELSIO_T4_SET_OFLD_POLICY:
12390 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12391 		break;
12392 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12393 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12394 		break;
12395 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12396 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12397 		break;
12398 	default:
12399 		rc = ENOTTY;
12400 	}
12401 
12402 	return (rc);
12403 }
12404 
12405 #ifdef TCP_OFFLOAD
12406 static int
12407 toe_capability(struct vi_info *vi, bool enable)
12408 {
12409 	int rc;
12410 	struct port_info *pi = vi->pi;
12411 	struct adapter *sc = pi->adapter;
12412 
12413 	ASSERT_SYNCHRONIZED_OP(sc);
12414 
12415 	if (!is_offload(sc))
12416 		return (ENODEV);
12417 	if (hw_off_limits(sc))
12418 		return (ENXIO);
12419 
12420 	if (enable) {
12421 #ifdef KERN_TLS
12422 		if (sc->flags & KERN_TLS_ON && is_t6(sc)) {
12423 			int i, j, n;
12424 			struct port_info *p;
12425 			struct vi_info *v;
12426 
12427 			/*
12428 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12429 			 * on any ifnet.
12430 			 */
12431 			n = 0;
12432 			for_each_port(sc, i) {
12433 				p = sc->port[i];
12434 				for_each_vi(p, j, v) {
12435 					if (v->ifp->if_capenable & IFCAP_TXTLS) {
12436 						CH_WARN(sc,
12437 						    "%s has NIC TLS enabled.\n",
12438 						    device_get_nameunit(v->dev));
12439 						n++;
12440 					}
12441 				}
12442 			}
12443 			if (n > 0) {
12444 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12445 				    "associated with this adapter before "
12446 				    "trying to enable TOE.\n");
12447 				return (EAGAIN);
12448 			}
12449 			rc = t6_config_kern_tls(sc, false);
12450 			if (rc)
12451 				return (rc);
12452 		}
12453 #endif
12454 		if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
12455 			/* TOE is already enabled. */
12456 			return (0);
12457 		}
12458 
12459 		/*
12460 		 * We need the port's queues around so that we're able to send
12461 		 * and receive CPLs to/from the TOE even if the ifnet for this
12462 		 * port has never been UP'd administratively.
12463 		 */
12464 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12465 			return (rc);
12466 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12467 		    ((rc = vi_init(&pi->vi[0])) != 0))
12468 			return (rc);
12469 
12470 		if (isset(&sc->offload_map, pi->port_id)) {
12471 			/* TOE is enabled on another VI of this port. */
12472 			pi->uld_vis++;
12473 			return (0);
12474 		}
12475 
12476 		if (!uld_active(sc, ULD_TOM)) {
12477 			rc = t4_activate_uld(sc, ULD_TOM);
12478 			if (rc == EAGAIN) {
12479 				log(LOG_WARNING,
12480 				    "You must kldload t4_tom.ko before trying "
12481 				    "to enable TOE on a cxgbe interface.\n");
12482 			}
12483 			if (rc != 0)
12484 				return (rc);
12485 			KASSERT(sc->tom_softc != NULL,
12486 			    ("%s: TOM activated but softc NULL", __func__));
12487 			KASSERT(uld_active(sc, ULD_TOM),
12488 			    ("%s: TOM activated but flag not set", __func__));
12489 		}
12490 
12491 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12492 		if (!uld_active(sc, ULD_IWARP))
12493 			(void) t4_activate_uld(sc, ULD_IWARP);
12494 		if (!uld_active(sc, ULD_ISCSI))
12495 			(void) t4_activate_uld(sc, ULD_ISCSI);
12496 
12497 		pi->uld_vis++;
12498 		setbit(&sc->offload_map, pi->port_id);
12499 	} else {
12500 		pi->uld_vis--;
12501 
12502 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12503 			return (0);
12504 
12505 		KASSERT(uld_active(sc, ULD_TOM),
12506 		    ("%s: TOM never initialized?", __func__));
12507 		clrbit(&sc->offload_map, pi->port_id);
12508 	}
12509 
12510 	return (0);
12511 }
12512 
12513 /*
12514  * Add an upper layer driver to the global list.
12515  */
12516 int
12517 t4_register_uld(struct uld_info *ui)
12518 {
12519 	int rc = 0;
12520 	struct uld_info *u;
12521 
12522 	sx_xlock(&t4_uld_list_lock);
12523 	SLIST_FOREACH(u, &t4_uld_list, link) {
12524 	    if (u->uld_id == ui->uld_id) {
12525 		    rc = EEXIST;
12526 		    goto done;
12527 	    }
12528 	}
12529 
12530 	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
12531 	ui->refcount = 0;
12532 done:
12533 	sx_xunlock(&t4_uld_list_lock);
12534 	return (rc);
12535 }
12536 
12537 int
12538 t4_unregister_uld(struct uld_info *ui)
12539 {
12540 	int rc = EINVAL;
12541 	struct uld_info *u;
12542 
12543 	sx_xlock(&t4_uld_list_lock);
12544 
12545 	SLIST_FOREACH(u, &t4_uld_list, link) {
12546 	    if (u == ui) {
12547 		    if (ui->refcount > 0) {
12548 			    rc = EBUSY;
12549 			    goto done;
12550 		    }
12551 
12552 		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
12553 		    rc = 0;
12554 		    goto done;
12555 	    }
12556 	}
12557 done:
12558 	sx_xunlock(&t4_uld_list_lock);
12559 	return (rc);
12560 }
12561 
12562 int
12563 t4_activate_uld(struct adapter *sc, int id)
12564 {
12565 	int rc;
12566 	struct uld_info *ui;
12567 
12568 	ASSERT_SYNCHRONIZED_OP(sc);
12569 
12570 	if (id < 0 || id > ULD_MAX)
12571 		return (EINVAL);
12572 	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
12573 
12574 	sx_slock(&t4_uld_list_lock);
12575 
12576 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12577 		if (ui->uld_id == id) {
12578 			if (!(sc->flags & FULL_INIT_DONE)) {
12579 				rc = adapter_init(sc);
12580 				if (rc != 0)
12581 					break;
12582 			}
12583 
12584 			rc = ui->activate(sc);
12585 			if (rc == 0) {
12586 				setbit(&sc->active_ulds, id);
12587 				ui->refcount++;
12588 			}
12589 			break;
12590 		}
12591 	}
12592 
12593 	sx_sunlock(&t4_uld_list_lock);
12594 
12595 	return (rc);
12596 }
12597 
12598 int
12599 t4_deactivate_uld(struct adapter *sc, int id)
12600 {
12601 	int rc;
12602 	struct uld_info *ui;
12603 
12604 	ASSERT_SYNCHRONIZED_OP(sc);
12605 
12606 	if (id < 0 || id > ULD_MAX)
12607 		return (EINVAL);
12608 	rc = ENXIO;
12609 
12610 	sx_slock(&t4_uld_list_lock);
12611 
12612 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12613 		if (ui->uld_id == id) {
12614 			rc = ui->deactivate(sc);
12615 			if (rc == 0) {
12616 				clrbit(&sc->active_ulds, id);
12617 				ui->refcount--;
12618 			}
12619 			break;
12620 		}
12621 	}
12622 
12623 	sx_sunlock(&t4_uld_list_lock);
12624 
12625 	return (rc);
12626 }
12627 
12628 static int
12629 t4_deactivate_all_uld(struct adapter *sc)
12630 {
12631 	int rc;
12632 	struct uld_info *ui;
12633 
12634 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4detuld");
12635 	if (rc != 0)
12636 		return (ENXIO);
12637 
12638 	sx_slock(&t4_uld_list_lock);
12639 
12640 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12641 		if (isset(&sc->active_ulds, ui->uld_id)) {
12642 			rc = ui->deactivate(sc);
12643 			if (rc != 0)
12644 				break;
12645 			clrbit(&sc->active_ulds, ui->uld_id);
12646 			ui->refcount--;
12647 		}
12648 	}
12649 
12650 	sx_sunlock(&t4_uld_list_lock);
12651 	end_synchronized_op(sc, 0);
12652 
12653 	return (rc);
12654 }
12655 
12656 static void
12657 t4_async_event(struct adapter *sc)
12658 {
12659 	struct uld_info *ui;
12660 
12661 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
12662 		return;
12663 	sx_slock(&t4_uld_list_lock);
12664 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12665 		if (ui->uld_id == ULD_IWARP) {
12666 			ui->async_event(sc);
12667 			break;
12668 		}
12669 	}
12670 	sx_sunlock(&t4_uld_list_lock);
12671 	end_synchronized_op(sc, 0);
12672 }
12673 
12674 int
12675 uld_active(struct adapter *sc, int uld_id)
12676 {
12677 
12678 	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
12679 
12680 	return (isset(&sc->active_ulds, uld_id));
12681 }
12682 #endif
12683 
12684 #ifdef KERN_TLS
12685 static int
12686 ktls_capability(struct adapter *sc, bool enable)
12687 {
12688 	ASSERT_SYNCHRONIZED_OP(sc);
12689 
12690 	if (!is_ktls(sc))
12691 		return (ENODEV);
12692 	if (!is_t6(sc))
12693 		return (0);
12694 	if (hw_off_limits(sc))
12695 		return (ENXIO);
12696 
12697 	if (enable) {
12698 		if (sc->flags & KERN_TLS_ON)
12699 			return (0);	/* already on */
12700 		if (sc->offload_map != 0) {
12701 			CH_WARN(sc,
12702 			    "Disable TOE on all interfaces associated with "
12703 			    "this adapter before trying to enable NIC TLS.\n");
12704 			return (EAGAIN);
12705 		}
12706 		return (t6_config_kern_tls(sc, true));
12707 	} else {
12708 		/*
12709 		 * Nothing to do for disable.  If TOE is enabled sometime later
12710 		 * then toe_capability will reconfigure the hardware.
12711 		 */
12712 		return (0);
12713 	}
12714 }
12715 #endif
12716 
12717 /*
12718  * t  = ptr to tunable.
12719  * nc = number of CPUs.
12720  * c  = compiled in default for that tunable.
12721  */
12722 static void
12723 calculate_nqueues(int *t, int nc, const int c)
12724 {
12725 	int nq;
12726 
12727 	if (*t > 0)
12728 		return;
12729 	nq = *t < 0 ? -*t : c;
12730 	*t = min(nc, nq);
12731 }
12732 
12733 /*
12734  * Come up with reasonable defaults for some of the tunables, provided they're
12735  * not set by the user (in which case we'll use the values as is).
12736  */
12737 static void
12738 tweak_tunables(void)
12739 {
12740 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12741 
12742 	if (t4_ntxq < 1) {
12743 #ifdef RSS
12744 		t4_ntxq = rss_getnumbuckets();
12745 #else
12746 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12747 #endif
12748 	}
12749 
12750 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12751 
12752 	if (t4_nrxq < 1) {
12753 #ifdef RSS
12754 		t4_nrxq = rss_getnumbuckets();
12755 #else
12756 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12757 #endif
12758 	}
12759 
12760 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12761 
12762 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12763 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12764 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12765 #endif
12766 #ifdef TCP_OFFLOAD
12767 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12768 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12769 #endif
12770 
12771 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12772 	if (t4_toecaps_allowed == -1)
12773 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12774 #else
12775 	if (t4_toecaps_allowed == -1)
12776 		t4_toecaps_allowed = 0;
12777 #endif
12778 
12779 #ifdef TCP_OFFLOAD
12780 	if (t4_rdmacaps_allowed == -1) {
12781 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12782 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12783 	}
12784 
12785 	if (t4_iscsicaps_allowed == -1) {
12786 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12787 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12788 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12789 	}
12790 
12791 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12792 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12793 
12794 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12795 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12796 
12797 	if (t4_toe_tls_rx_timeout < 0)
12798 		t4_toe_tls_rx_timeout = 0;
12799 #else
12800 	if (t4_rdmacaps_allowed == -1)
12801 		t4_rdmacaps_allowed = 0;
12802 
12803 	if (t4_iscsicaps_allowed == -1)
12804 		t4_iscsicaps_allowed = 0;
12805 #endif
12806 
12807 #ifdef DEV_NETMAP
12808 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12809 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12810 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12811 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12812 #endif
12813 
12814 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12815 		t4_tmr_idx = TMR_IDX;
12816 
12817 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12818 		t4_pktc_idx = PKTC_IDX;
12819 
12820 	if (t4_qsize_txq < 128)
12821 		t4_qsize_txq = 128;
12822 
12823 	if (t4_qsize_rxq < 128)
12824 		t4_qsize_rxq = 128;
12825 	while (t4_qsize_rxq & 7)
12826 		t4_qsize_rxq++;
12827 
12828 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12829 
12830 	/*
12831 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12832 	 * VI for the port.  The rest are additional virtual interfaces on the
12833 	 * same physical port.  Note that the main VI does not have native
12834 	 * netmap support but the extra VIs do.
12835 	 *
12836 	 * Limit the number of VIs per port to the number of available
12837 	 * MAC addresses per port.
12838 	 */
12839 	if (t4_num_vis < 1)
12840 		t4_num_vis = 1;
12841 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12842 		t4_num_vis = nitems(vi_mac_funcs);
12843 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12844 	}
12845 
12846 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12847 		pcie_relaxed_ordering = 1;
12848 #if defined(__i386__) || defined(__amd64__)
12849 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12850 			pcie_relaxed_ordering = 0;
12851 #endif
12852 	}
12853 }
12854 
12855 #ifdef DDB
12856 static void
12857 t4_dump_tcb(struct adapter *sc, int tid)
12858 {
12859 	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
12860 
12861 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12862 	save = t4_read_reg(sc, reg);
12863 	base = sc->memwin[2].mw_base;
12864 
12865 	/* Dump TCB for the tid */
12866 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12867 	tcb_addr += tid * TCB_SIZE;
12868 
12869 	if (is_t4(sc)) {
12870 		pf = 0;
12871 		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
12872 	} else {
12873 		pf = V_PFNUM(sc->pf);
12874 		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
12875 	}
12876 	t4_write_reg(sc, reg, win_pos | pf);
12877 	t4_read_reg(sc, reg);
12878 
12879 	off = tcb_addr - win_pos;
12880 	for (i = 0; i < 4; i++) {
12881 		uint32_t buf[8];
12882 		for (j = 0; j < 8; j++, off += 4)
12883 			buf[j] = htonl(t4_read_reg(sc, base + off));
12884 
12885 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12886 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12887 		    buf[7]);
12888 	}
12889 
12890 	t4_write_reg(sc, reg, save);
12891 	t4_read_reg(sc, reg);
12892 }
12893 
12894 static void
12895 t4_dump_devlog(struct adapter *sc)
12896 {
12897 	struct devlog_params *dparams = &sc->params.devlog;
12898 	struct fw_devlog_e e;
12899 	int i, first, j, m, nentries, rc;
12900 	uint64_t ftstamp = UINT64_MAX;
12901 
12902 	if (dparams->start == 0) {
12903 		db_printf("devlog params not valid\n");
12904 		return;
12905 	}
12906 
12907 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12908 	m = fwmtype_to_hwmtype(dparams->memtype);
12909 
12910 	/* Find the first entry. */
12911 	first = -1;
12912 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12913 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12914 		    sizeof(e), (void *)&e);
12915 		if (rc != 0)
12916 			break;
12917 
12918 		if (e.timestamp == 0)
12919 			break;
12920 
12921 		e.timestamp = be64toh(e.timestamp);
12922 		if (e.timestamp < ftstamp) {
12923 			ftstamp = e.timestamp;
12924 			first = i;
12925 		}
12926 	}
12927 
12928 	if (first == -1)
12929 		return;
12930 
12931 	i = first;
12932 	do {
12933 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12934 		    sizeof(e), (void *)&e);
12935 		if (rc != 0)
12936 			return;
12937 
12938 		if (e.timestamp == 0)
12939 			return;
12940 
12941 		e.timestamp = be64toh(e.timestamp);
12942 		e.seqno = be32toh(e.seqno);
12943 		for (j = 0; j < 8; j++)
12944 			e.params[j] = be32toh(e.params[j]);
12945 
12946 		db_printf("%10d  %15ju  %8s  %8s  ",
12947 		    e.seqno, e.timestamp,
12948 		    (e.level < nitems(devlog_level_strings) ?
12949 			devlog_level_strings[e.level] : "UNKNOWN"),
12950 		    (e.facility < nitems(devlog_facility_strings) ?
12951 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12952 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12953 		    e.params[3], e.params[4], e.params[5], e.params[6],
12954 		    e.params[7]);
12955 
12956 		if (++i == nentries)
12957 			i = 0;
12958 	} while (i != first && !db_pager_quit);
12959 }
12960 
12961 static struct db_command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
12962 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
12963 
12964 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
12965 {
12966 	device_t dev;
12967 	int t;
12968 	bool valid;
12969 
12970 	valid = false;
12971 	t = db_read_token();
12972 	if (t == tIDENT) {
12973 		dev = device_lookup_by_name(db_tok_string);
12974 		valid = true;
12975 	}
12976 	db_skip_to_eol();
12977 	if (!valid) {
12978 		db_printf("usage: show t4 devlog <nexus>\n");
12979 		return;
12980 	}
12981 
12982 	if (dev == NULL) {
12983 		db_printf("device not found\n");
12984 		return;
12985 	}
12986 
12987 	t4_dump_devlog(device_get_softc(dev));
12988 }
12989 
12990 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
12991 {
12992 	device_t dev;
12993 	int radix, tid, t;
12994 	bool valid;
12995 
12996 	valid = false;
12997 	radix = db_radix;
12998 	db_radix = 10;
12999 	t = db_read_token();
13000 	if (t == tIDENT) {
13001 		dev = device_lookup_by_name(db_tok_string);
13002 		t = db_read_token();
13003 		if (t == tNUMBER) {
13004 			tid = db_tok_number;
13005 			valid = true;
13006 		}
13007 	}
13008 	db_radix = radix;
13009 	db_skip_to_eol();
13010 	if (!valid) {
13011 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
13012 		return;
13013 	}
13014 
13015 	if (dev == NULL) {
13016 		db_printf("device not found\n");
13017 		return;
13018 	}
13019 	if (tid < 0) {
13020 		db_printf("invalid tid\n");
13021 		return;
13022 	}
13023 
13024 	t4_dump_tcb(device_get_softc(dev), tid);
13025 }
13026 #endif
13027 
13028 static eventhandler_tag vxlan_start_evtag;
13029 static eventhandler_tag vxlan_stop_evtag;
13030 
13031 struct vxlan_evargs {
13032 	struct ifnet *ifp;
13033 	uint16_t port;
13034 };
13035 
13036 static void
13037 enable_vxlan_rx(struct adapter *sc)
13038 {
13039 	int i, rc;
13040 	struct port_info *pi;
13041 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
13042 
13043 	ASSERT_SYNCHRONIZED_OP(sc);
13044 
13045 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
13046 	    F_VXLAN_EN);
13047 	for_each_port(sc, i) {
13048 		pi = sc->port[i];
13049 		if (pi->vxlan_tcam_entry == true)
13050 			continue;
13051 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
13052 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
13053 		    true);
13054 		if (rc < 0) {
13055 			rc = -rc;
13056 			CH_ERR(&pi->vi[0],
13057 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
13058 		} else {
13059 			MPASS(rc == sc->rawf_base + pi->port_id);
13060 			pi->vxlan_tcam_entry = true;
13061 		}
13062 	}
13063 }
13064 
13065 static void
13066 t4_vxlan_start(struct adapter *sc, void *arg)
13067 {
13068 	struct vxlan_evargs *v = arg;
13069 
13070 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13071 		return;
13072 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
13073 		return;
13074 
13075 	if (sc->vxlan_refcount == 0) {
13076 		sc->vxlan_port = v->port;
13077 		sc->vxlan_refcount = 1;
13078 		if (!hw_off_limits(sc))
13079 			enable_vxlan_rx(sc);
13080 	} else if (sc->vxlan_port == v->port) {
13081 		sc->vxlan_refcount++;
13082 	} else {
13083 		CH_ERR(sc, "VXLAN already configured on port  %d; "
13084 		    "ignoring attempt to configure it on port %d\n",
13085 		    sc->vxlan_port, v->port);
13086 	}
13087 	end_synchronized_op(sc, 0);
13088 }
13089 
13090 static void
13091 t4_vxlan_stop(struct adapter *sc, void *arg)
13092 {
13093 	struct vxlan_evargs *v = arg;
13094 
13095 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13096 		return;
13097 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
13098 		return;
13099 
13100 	/*
13101 	 * VXLANs may have been configured before the driver was loaded so we
13102 	 * may see more stops than starts.  This is not handled cleanly but at
13103 	 * least we keep the refcount sane.
13104 	 */
13105 	if (sc->vxlan_port != v->port)
13106 		goto done;
13107 	if (sc->vxlan_refcount == 0) {
13108 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
13109 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
13110 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
13111 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
13112 done:
13113 	end_synchronized_op(sc, 0);
13114 }
13115 
13116 static void
13117 t4_vxlan_start_handler(void *arg __unused, struct ifnet *ifp,
13118     sa_family_t family, u_int port)
13119 {
13120 	struct vxlan_evargs v;
13121 
13122 	MPASS(family == AF_INET || family == AF_INET6);
13123 	v.ifp = ifp;
13124 	v.port = port;
13125 
13126 	t4_iterate(t4_vxlan_start, &v);
13127 }
13128 
13129 static void
13130 t4_vxlan_stop_handler(void *arg __unused, struct ifnet *ifp, sa_family_t family,
13131     u_int port)
13132 {
13133 	struct vxlan_evargs v;
13134 
13135 	MPASS(family == AF_INET || family == AF_INET6);
13136 	v.ifp = ifp;
13137 	v.port = port;
13138 
13139 	t4_iterate(t4_vxlan_stop, &v);
13140 }
13141 
13142 
13143 static struct sx mlu;	/* mod load unload */
13144 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
13145 
13146 static int
13147 mod_event(module_t mod, int cmd, void *arg)
13148 {
13149 	int rc = 0;
13150 	static int loaded = 0;
13151 
13152 	switch (cmd) {
13153 	case MOD_LOAD:
13154 		sx_xlock(&mlu);
13155 		if (loaded++ == 0) {
13156 			t4_sge_modload();
13157 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13158 			    t4_filter_rpl, CPL_COOKIE_FILTER);
13159 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
13160 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
13161 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
13162 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
13163 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13164 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
13165 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
13166 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
13167 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
13168 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
13169 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
13170 			    do_smt_write_rpl);
13171 			sx_init(&t4_list_lock, "T4/T5 adapters");
13172 			SLIST_INIT(&t4_list);
13173 			callout_init(&fatal_callout, 1);
13174 #ifdef TCP_OFFLOAD
13175 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
13176 			SLIST_INIT(&t4_uld_list);
13177 #endif
13178 #ifdef INET6
13179 			t4_clip_modload();
13180 #endif
13181 #ifdef KERN_TLS
13182 			t6_ktls_modload();
13183 #endif
13184 			t4_tracer_modload();
13185 			tweak_tunables();
13186 			vxlan_start_evtag =
13187 			    EVENTHANDLER_REGISTER(vxlan_start,
13188 				t4_vxlan_start_handler, NULL,
13189 				EVENTHANDLER_PRI_ANY);
13190 			vxlan_stop_evtag =
13191 			    EVENTHANDLER_REGISTER(vxlan_stop,
13192 				t4_vxlan_stop_handler, NULL,
13193 				EVENTHANDLER_PRI_ANY);
13194 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
13195 			    taskqueue_thread_enqueue, &reset_tq);
13196 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
13197 			    "t4_rst_thr");
13198 		}
13199 		sx_xunlock(&mlu);
13200 		break;
13201 
13202 	case MOD_UNLOAD:
13203 		sx_xlock(&mlu);
13204 		if (--loaded == 0) {
13205 			int tries;
13206 
13207 			taskqueue_free(reset_tq);
13208 			sx_slock(&t4_list_lock);
13209 			if (!SLIST_EMPTY(&t4_list)) {
13210 				rc = EBUSY;
13211 				sx_sunlock(&t4_list_lock);
13212 				goto done_unload;
13213 			}
13214 #ifdef TCP_OFFLOAD
13215 			sx_slock(&t4_uld_list_lock);
13216 			if (!SLIST_EMPTY(&t4_uld_list)) {
13217 				rc = EBUSY;
13218 				sx_sunlock(&t4_uld_list_lock);
13219 				sx_sunlock(&t4_list_lock);
13220 				goto done_unload;
13221 			}
13222 #endif
13223 			tries = 0;
13224 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13225 				uprintf("%ju clusters with custom free routine "
13226 				    "still is use.\n", t4_sge_extfree_refs());
13227 				pause("t4unload", 2 * hz);
13228 			}
13229 #ifdef TCP_OFFLOAD
13230 			sx_sunlock(&t4_uld_list_lock);
13231 #endif
13232 			sx_sunlock(&t4_list_lock);
13233 
13234 			if (t4_sge_extfree_refs() == 0) {
13235 				EVENTHANDLER_DEREGISTER(vxlan_start,
13236 				    vxlan_start_evtag);
13237 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13238 				    vxlan_stop_evtag);
13239 				t4_tracer_modunload();
13240 #ifdef KERN_TLS
13241 				t6_ktls_modunload();
13242 #endif
13243 #ifdef INET6
13244 				t4_clip_modunload();
13245 #endif
13246 #ifdef TCP_OFFLOAD
13247 				sx_destroy(&t4_uld_list_lock);
13248 #endif
13249 				sx_destroy(&t4_list_lock);
13250 				t4_sge_modunload();
13251 				loaded = 0;
13252 			} else {
13253 				rc = EBUSY;
13254 				loaded++;	/* undo earlier decrement */
13255 			}
13256 		}
13257 done_unload:
13258 		sx_xunlock(&mlu);
13259 		break;
13260 	}
13261 
13262 	return (rc);
13263 }
13264 
13265 DRIVER_MODULE(t4nex, pci, t4_driver, mod_event, 0);
13266 MODULE_VERSION(t4nex, 1);
13267 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13268 #ifdef DEV_NETMAP
13269 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13270 #endif /* DEV_NETMAP */
13271 
13272 DRIVER_MODULE(t5nex, pci, t5_driver, mod_event, 0);
13273 MODULE_VERSION(t5nex, 1);
13274 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13275 #ifdef DEV_NETMAP
13276 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13277 #endif /* DEV_NETMAP */
13278 
13279 DRIVER_MODULE(t6nex, pci, t6_driver, mod_event, 0);
13280 MODULE_VERSION(t6nex, 1);
13281 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13282 #ifdef DEV_NETMAP
13283 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13284 #endif /* DEV_NETMAP */
13285 
13286 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, 0, 0);
13287 MODULE_VERSION(cxgbe, 1);
13288 
13289 DRIVER_MODULE(cxl, t5nex, cxl_driver, 0, 0);
13290 MODULE_VERSION(cxl, 1);
13291 
13292 DRIVER_MODULE(cc, t6nex, cc_driver, 0, 0);
13293 MODULE_VERSION(cc, 1);
13294 
13295 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, 0, 0);
13296 MODULE_VERSION(vcxgbe, 1);
13297 
13298 DRIVER_MODULE(vcxl, cxl, vcxl_driver, 0, 0);
13299 MODULE_VERSION(vcxl, 1);
13300 
13301 DRIVER_MODULE(vcc, cc, vcc_driver, 0, 0);
13302 MODULE_VERSION(vcc, 1);
13303