xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision bc7512cc58af2e8bbe5bbf5ca0059b1daa1da897)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 Chelsio Communications, Inc.
5  * All rights reserved.
6  * Written by: Navdeep Parhar <np@FreeBSD.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include "opt_ddb.h"
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_kern_tls.h"
37 #include "opt_ratelimit.h"
38 #include "opt_rss.h"
39 
40 #include <sys/param.h>
41 #include <sys/conf.h>
42 #include <sys/priv.h>
43 #include <sys/kernel.h>
44 #include <sys/bus.h>
45 #include <sys/eventhandler.h>
46 #include <sys/module.h>
47 #include <sys/malloc.h>
48 #include <sys/queue.h>
49 #include <sys/taskqueue.h>
50 #include <sys/pciio.h>
51 #include <dev/pci/pcireg.h>
52 #include <dev/pci/pcivar.h>
53 #include <dev/pci/pci_private.h>
54 #include <sys/firmware.h>
55 #include <sys/sbuf.h>
56 #include <sys/smp.h>
57 #include <sys/socket.h>
58 #include <sys/sockio.h>
59 #include <sys/sysctl.h>
60 #include <net/ethernet.h>
61 #include <net/if.h>
62 #include <net/if_types.h>
63 #include <net/if_dl.h>
64 #include <net/if_vlan_var.h>
65 #ifdef RSS
66 #include <net/rss_config.h>
67 #endif
68 #include <netinet/in.h>
69 #include <netinet/ip.h>
70 #ifdef KERN_TLS
71 #include <netinet/tcp_seq.h>
72 #endif
73 #if defined(__i386__) || defined(__amd64__)
74 #include <machine/md_var.h>
75 #include <machine/cputypes.h>
76 #include <vm/vm.h>
77 #include <vm/pmap.h>
78 #endif
79 #ifdef DDB
80 #include <ddb/ddb.h>
81 #include <ddb/db_lex.h>
82 #endif
83 
84 #include "common/common.h"
85 #include "common/t4_msg.h"
86 #include "common/t4_regs.h"
87 #include "common/t4_regs_values.h"
88 #include "cudbg/cudbg.h"
89 #include "t4_clip.h"
90 #include "t4_ioctl.h"
91 #include "t4_l2t.h"
92 #include "t4_mp_ring.h"
93 #include "t4_if.h"
94 #include "t4_smt.h"
95 
96 /* T4 bus driver interface */
97 static int t4_probe(device_t);
98 static int t4_attach(device_t);
99 static int t4_detach(device_t);
100 static int t4_child_location(device_t, device_t, struct sbuf *);
101 static int t4_ready(device_t);
102 static int t4_read_port_device(device_t, int, device_t *);
103 static int t4_suspend(device_t);
104 static int t4_resume(device_t);
105 static int t4_reset_prepare(device_t, device_t);
106 static int t4_reset_post(device_t, device_t);
107 static device_method_t t4_methods[] = {
108 	DEVMETHOD(device_probe,		t4_probe),
109 	DEVMETHOD(device_attach,	t4_attach),
110 	DEVMETHOD(device_detach,	t4_detach),
111 	DEVMETHOD(device_suspend,	t4_suspend),
112 	DEVMETHOD(device_resume,	t4_resume),
113 
114 	DEVMETHOD(bus_child_location,	t4_child_location),
115 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
116 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
117 
118 	DEVMETHOD(t4_is_main_ready,	t4_ready),
119 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
120 
121 	DEVMETHOD_END
122 };
123 static driver_t t4_driver = {
124 	"t4nex",
125 	t4_methods,
126 	sizeof(struct adapter)
127 };
128 
129 
130 /* T4 port (cxgbe) interface */
131 static int cxgbe_probe(device_t);
132 static int cxgbe_attach(device_t);
133 static int cxgbe_detach(device_t);
134 device_method_t cxgbe_methods[] = {
135 	DEVMETHOD(device_probe,		cxgbe_probe),
136 	DEVMETHOD(device_attach,	cxgbe_attach),
137 	DEVMETHOD(device_detach,	cxgbe_detach),
138 	{ 0, 0 }
139 };
140 static driver_t cxgbe_driver = {
141 	"cxgbe",
142 	cxgbe_methods,
143 	sizeof(struct port_info)
144 };
145 
146 /* T4 VI (vcxgbe) interface */
147 static int vcxgbe_probe(device_t);
148 static int vcxgbe_attach(device_t);
149 static int vcxgbe_detach(device_t);
150 static device_method_t vcxgbe_methods[] = {
151 	DEVMETHOD(device_probe,		vcxgbe_probe),
152 	DEVMETHOD(device_attach,	vcxgbe_attach),
153 	DEVMETHOD(device_detach,	vcxgbe_detach),
154 	{ 0, 0 }
155 };
156 static driver_t vcxgbe_driver = {
157 	"vcxgbe",
158 	vcxgbe_methods,
159 	sizeof(struct vi_info)
160 };
161 
162 static d_ioctl_t t4_ioctl;
163 
164 static struct cdevsw t4_cdevsw = {
165        .d_version = D_VERSION,
166        .d_ioctl = t4_ioctl,
167        .d_name = "t4nex",
168 };
169 
170 /* T5 bus driver interface */
171 static int t5_probe(device_t);
172 static device_method_t t5_methods[] = {
173 	DEVMETHOD(device_probe,		t5_probe),
174 	DEVMETHOD(device_attach,	t4_attach),
175 	DEVMETHOD(device_detach,	t4_detach),
176 	DEVMETHOD(device_suspend,	t4_suspend),
177 	DEVMETHOD(device_resume,	t4_resume),
178 
179 	DEVMETHOD(bus_child_location,	t4_child_location),
180 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
181 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
182 
183 	DEVMETHOD(t4_is_main_ready,	t4_ready),
184 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
185 
186 	DEVMETHOD_END
187 };
188 static driver_t t5_driver = {
189 	"t5nex",
190 	t5_methods,
191 	sizeof(struct adapter)
192 };
193 
194 
195 /* T5 port (cxl) interface */
196 static driver_t cxl_driver = {
197 	"cxl",
198 	cxgbe_methods,
199 	sizeof(struct port_info)
200 };
201 
202 /* T5 VI (vcxl) interface */
203 static driver_t vcxl_driver = {
204 	"vcxl",
205 	vcxgbe_methods,
206 	sizeof(struct vi_info)
207 };
208 
209 /* T6 bus driver interface */
210 static int t6_probe(device_t);
211 static device_method_t t6_methods[] = {
212 	DEVMETHOD(device_probe,		t6_probe),
213 	DEVMETHOD(device_attach,	t4_attach),
214 	DEVMETHOD(device_detach,	t4_detach),
215 	DEVMETHOD(device_suspend,	t4_suspend),
216 	DEVMETHOD(device_resume,	t4_resume),
217 
218 	DEVMETHOD(bus_child_location,	t4_child_location),
219 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
220 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
221 
222 	DEVMETHOD(t4_is_main_ready,	t4_ready),
223 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
224 
225 	DEVMETHOD_END
226 };
227 static driver_t t6_driver = {
228 	"t6nex",
229 	t6_methods,
230 	sizeof(struct adapter)
231 };
232 
233 
234 /* T6 port (cc) interface */
235 static driver_t cc_driver = {
236 	"cc",
237 	cxgbe_methods,
238 	sizeof(struct port_info)
239 };
240 
241 /* T6 VI (vcc) interface */
242 static driver_t vcc_driver = {
243 	"vcc",
244 	vcxgbe_methods,
245 	sizeof(struct vi_info)
246 };
247 
248 /* ifnet interface */
249 static void cxgbe_init(void *);
250 static int cxgbe_ioctl(struct ifnet *, unsigned long, caddr_t);
251 static int cxgbe_transmit(struct ifnet *, struct mbuf *);
252 static void cxgbe_qflush(struct ifnet *);
253 #if defined(KERN_TLS) || defined(RATELIMIT)
254 static int cxgbe_snd_tag_alloc(struct ifnet *, union if_snd_tag_alloc_params *,
255     struct m_snd_tag **);
256 #endif
257 
258 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
259 
260 /*
261  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
262  * then ADAPTER_LOCK, then t4_uld_list_lock.
263  */
264 static struct sx t4_list_lock;
265 SLIST_HEAD(, adapter) t4_list;
266 #ifdef TCP_OFFLOAD
267 static struct sx t4_uld_list_lock;
268 SLIST_HEAD(, uld_info) t4_uld_list;
269 #endif
270 
271 /*
272  * Tunables.  See tweak_tunables() too.
273  *
274  * Each tunable is set to a default value here if it's known at compile-time.
275  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
276  * provide a reasonable default (upto n) when the driver is loaded.
277  *
278  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
279  * T5 are under hw.cxl.
280  */
281 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
282     "cxgbe(4) parameters");
283 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
284     "cxgbe(4) T5+ parameters");
285 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
286     "cxgbe(4) TOE parameters");
287 
288 /*
289  * Number of queues for tx and rx, NIC and offload.
290  */
291 #define NTXQ 16
292 int t4_ntxq = -NTXQ;
293 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
294     "Number of TX queues per port");
295 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);	/* Old name, undocumented */
296 
297 #define NRXQ 8
298 int t4_nrxq = -NRXQ;
299 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
300     "Number of RX queues per port");
301 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);	/* Old name, undocumented */
302 
303 #define NTXQ_VI 1
304 static int t4_ntxq_vi = -NTXQ_VI;
305 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
306     "Number of TX queues per VI");
307 
308 #define NRXQ_VI 1
309 static int t4_nrxq_vi = -NRXQ_VI;
310 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
311     "Number of RX queues per VI");
312 
313 static int t4_rsrv_noflowq = 0;
314 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
315     0, "Reserve TX queue 0 of each VI for non-flowid packets");
316 
317 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
318 #define NOFLDTXQ 8
319 static int t4_nofldtxq = -NOFLDTXQ;
320 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
321     "Number of offload TX queues per port");
322 
323 #define NOFLDRXQ 2
324 static int t4_nofldrxq = -NOFLDRXQ;
325 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
326     "Number of offload RX queues per port");
327 
328 #define NOFLDTXQ_VI 1
329 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
330 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
331     "Number of offload TX queues per VI");
332 
333 #define NOFLDRXQ_VI 1
334 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
335 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
336     "Number of offload RX queues per VI");
337 
338 #define TMR_IDX_OFLD 1
339 int t4_tmr_idx_ofld = TMR_IDX_OFLD;
340 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
341     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
342 
343 #define PKTC_IDX_OFLD (-1)
344 int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
345 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
346     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
347 
348 /* 0 means chip/fw default, non-zero number is value in microseconds */
349 static u_long t4_toe_keepalive_idle = 0;
350 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
351     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
352 
353 /* 0 means chip/fw default, non-zero number is value in microseconds */
354 static u_long t4_toe_keepalive_interval = 0;
355 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
356     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
357 
358 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
359 static int t4_toe_keepalive_count = 0;
360 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
361     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
362 
363 /* 0 means chip/fw default, non-zero number is value in microseconds */
364 static u_long t4_toe_rexmt_min = 0;
365 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
366     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
367 
368 /* 0 means chip/fw default, non-zero number is value in microseconds */
369 static u_long t4_toe_rexmt_max = 0;
370 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
371     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
372 
373 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
374 static int t4_toe_rexmt_count = 0;
375 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
376     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
377 
378 /* -1 means chip/fw default, other values are raw backoff values to use */
379 static int t4_toe_rexmt_backoff[16] = {
380 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
381 };
382 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
383     CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
384     "cxgbe(4) TOE retransmit backoff values");
385 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
386     &t4_toe_rexmt_backoff[0], 0, "");
387 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
388     &t4_toe_rexmt_backoff[1], 0, "");
389 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
390     &t4_toe_rexmt_backoff[2], 0, "");
391 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
392     &t4_toe_rexmt_backoff[3], 0, "");
393 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
394     &t4_toe_rexmt_backoff[4], 0, "");
395 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
396     &t4_toe_rexmt_backoff[5], 0, "");
397 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
398     &t4_toe_rexmt_backoff[6], 0, "");
399 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
400     &t4_toe_rexmt_backoff[7], 0, "");
401 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
402     &t4_toe_rexmt_backoff[8], 0, "");
403 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
404     &t4_toe_rexmt_backoff[9], 0, "");
405 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
406     &t4_toe_rexmt_backoff[10], 0, "");
407 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
408     &t4_toe_rexmt_backoff[11], 0, "");
409 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
410     &t4_toe_rexmt_backoff[12], 0, "");
411 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
412     &t4_toe_rexmt_backoff[13], 0, "");
413 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
414     &t4_toe_rexmt_backoff[14], 0, "");
415 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
416     &t4_toe_rexmt_backoff[15], 0, "");
417 
418 static int t4_toe_tls_rx_timeout = 5;
419 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, tls_rx_timeout, CTLFLAG_RDTUN,
420     &t4_toe_tls_rx_timeout, 0,
421     "Timeout in seconds to downgrade TLS sockets to plain TOE");
422 #endif
423 
424 #ifdef DEV_NETMAP
425 #define NN_MAIN_VI	(1 << 0)	/* Native netmap on the main VI */
426 #define NN_EXTRA_VI	(1 << 1)	/* Native netmap on the extra VI(s) */
427 static int t4_native_netmap = NN_EXTRA_VI;
428 SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
429     0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
430 
431 #define NNMTXQ 8
432 static int t4_nnmtxq = -NNMTXQ;
433 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
434     "Number of netmap TX queues");
435 
436 #define NNMRXQ 8
437 static int t4_nnmrxq = -NNMRXQ;
438 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
439     "Number of netmap RX queues");
440 
441 #define NNMTXQ_VI 2
442 static int t4_nnmtxq_vi = -NNMTXQ_VI;
443 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
444     "Number of netmap TX queues per VI");
445 
446 #define NNMRXQ_VI 2
447 static int t4_nnmrxq_vi = -NNMRXQ_VI;
448 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
449     "Number of netmap RX queues per VI");
450 #endif
451 
452 /*
453  * Holdoff parameters for ports.
454  */
455 #define TMR_IDX 1
456 int t4_tmr_idx = TMR_IDX;
457 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
458     0, "Holdoff timer index");
459 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);	/* Old name */
460 
461 #define PKTC_IDX (-1)
462 int t4_pktc_idx = PKTC_IDX;
463 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
464     0, "Holdoff packet counter index");
465 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);	/* Old name */
466 
467 /*
468  * Size (# of entries) of each tx and rx queue.
469  */
470 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
471 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
472     "Number of descriptors in each TX queue");
473 
474 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
475 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
476     "Number of descriptors in each RX queue");
477 
478 /*
479  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
480  */
481 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
482 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
483     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
484 
485 /*
486  * Configuration file.  All the _CF names here are special.
487  */
488 #define DEFAULT_CF	"default"
489 #define BUILTIN_CF	"built-in"
490 #define FLASH_CF	"flash"
491 #define UWIRE_CF	"uwire"
492 #define FPGA_CF		"fpga"
493 static char t4_cfg_file[32] = DEFAULT_CF;
494 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
495     sizeof(t4_cfg_file), "Firmware configuration file");
496 
497 /*
498  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
499  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
500  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
501  *            mark or when signalled to do so, 0 to never emit PAUSE.
502  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
503  *                 negotiated settings will override rx_pause/tx_pause.
504  *                 Otherwise rx_pause/tx_pause are applied forcibly.
505  */
506 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
507 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
508     &t4_pause_settings, 0,
509     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
510 
511 /*
512  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
513  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
514  *  0 to disable FEC.
515  */
516 static int t4_fec = -1;
517 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
518     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
519 
520 /*
521  * Controls when the driver sets the FORCE_FEC bit in the L1_CFG32 that it
522  * issues to the firmware.  If the firmware doesn't support FORCE_FEC then the
523  * driver runs as if this is set to 0.
524  * -1 to set FORCE_FEC iff requested_fec != AUTO. Multiple FEC bits are okay.
525  *  0 to never set FORCE_FEC. requested_fec = AUTO means use the hint from the
526  *    transceiver. Multiple FEC bits may not be okay but will be passed on to
527  *    the firmware anyway (may result in l1cfg errors with old firmwares).
528  *  1 to always set FORCE_FEC. Multiple FEC bits are okay. requested_fec = AUTO
529  *    means set all FEC bits that are valid for the speed.
530  */
531 static int t4_force_fec = -1;
532 SYSCTL_INT(_hw_cxgbe, OID_AUTO, force_fec, CTLFLAG_RDTUN, &t4_force_fec, 0,
533     "Controls the use of FORCE_FEC bit in L1 configuration.");
534 
535 /*
536  * Link autonegotiation.
537  * -1 to run with the firmware default.
538  *  0 to disable.
539  *  1 to enable.
540  */
541 static int t4_autoneg = -1;
542 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
543     "Link autonegotiation");
544 
545 /*
546  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
547  * encouraged respectively).  '-n' is the same as 'n' except the firmware
548  * version used in the checks is read from the firmware bundled with the driver.
549  */
550 static int t4_fw_install = 1;
551 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
552     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
553 
554 /*
555  * ASIC features that will be used.  Disable the ones you don't want so that the
556  * chip resources aren't wasted on features that will not be used.
557  */
558 static int t4_nbmcaps_allowed = 0;
559 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
560     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
561 
562 static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
563 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
564     &t4_linkcaps_allowed, 0, "Default link capabilities");
565 
566 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
567     FW_CAPS_CONFIG_SWITCH_EGRESS;
568 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
569     &t4_switchcaps_allowed, 0, "Default switch capabilities");
570 
571 #ifdef RATELIMIT
572 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
573 	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
574 #else
575 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
576 	FW_CAPS_CONFIG_NIC_HASHFILTER;
577 #endif
578 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
579     &t4_niccaps_allowed, 0, "Default NIC capabilities");
580 
581 static int t4_toecaps_allowed = -1;
582 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
583     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
584 
585 static int t4_rdmacaps_allowed = -1;
586 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
587     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
588 
589 static int t4_cryptocaps_allowed = -1;
590 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
591     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
592 
593 static int t4_iscsicaps_allowed = -1;
594 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
595     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
596 
597 static int t4_fcoecaps_allowed = 0;
598 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
599     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
600 
601 static int t5_write_combine = 0;
602 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
603     0, "Use WC instead of UC for BAR2");
604 
605 static int t4_num_vis = 1;
606 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
607     "Number of VIs per port");
608 
609 /*
610  * PCIe Relaxed Ordering.
611  * -1: driver should figure out a good value.
612  * 0: disable RO.
613  * 1: enable RO.
614  * 2: leave RO alone.
615  */
616 static int pcie_relaxed_ordering = -1;
617 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
618     &pcie_relaxed_ordering, 0,
619     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
620 
621 static int t4_panic_on_fatal_err = 0;
622 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
623     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
624 
625 static int t4_reset_on_fatal_err = 0;
626 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
627     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
628 
629 static int t4_tx_vm_wr = 0;
630 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
631     "Use VM work requests to transmit packets.");
632 
633 /*
634  * Set to non-zero to enable the attack filter.  A packet that matches any of
635  * these conditions will get dropped on ingress:
636  * 1) IP && source address == destination address.
637  * 2) TCP/IP && source address is not a unicast address.
638  * 3) TCP/IP && destination address is not a unicast address.
639  * 4) IP && source address is loopback (127.x.y.z).
640  * 5) IP && destination address is loopback (127.x.y.z).
641  * 6) IPv6 && source address == destination address.
642  * 7) IPv6 && source address is not a unicast address.
643  * 8) IPv6 && source address is loopback (::1/128).
644  * 9) IPv6 && destination address is loopback (::1/128).
645  * 10) IPv6 && source address is unspecified (::/128).
646  * 11) IPv6 && destination address is unspecified (::/128).
647  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
648  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
649  */
650 static int t4_attack_filter = 0;
651 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
652     &t4_attack_filter, 0, "Drop suspicious traffic");
653 
654 static int t4_drop_ip_fragments = 0;
655 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
656     &t4_drop_ip_fragments, 0, "Drop IP fragments");
657 
658 static int t4_drop_pkts_with_l2_errors = 1;
659 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
660     &t4_drop_pkts_with_l2_errors, 0,
661     "Drop all frames with Layer 2 length or checksum errors");
662 
663 static int t4_drop_pkts_with_l3_errors = 0;
664 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
665     &t4_drop_pkts_with_l3_errors, 0,
666     "Drop all frames with IP version, length, or checksum errors");
667 
668 static int t4_drop_pkts_with_l4_errors = 0;
669 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
670     &t4_drop_pkts_with_l4_errors, 0,
671     "Drop all frames with Layer 4 length, checksum, or other errors");
672 
673 #ifdef TCP_OFFLOAD
674 /*
675  * TOE tunables.
676  */
677 static int t4_cop_managed_offloading = 0;
678 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
679     &t4_cop_managed_offloading, 0,
680     "COP (Connection Offload Policy) controls all TOE offload");
681 #endif
682 
683 #ifdef KERN_TLS
684 /*
685  * This enables KERN_TLS for all adapters if set.
686  */
687 static int t4_kern_tls = 0;
688 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
689     "Enable KERN_TLS mode for all supported adapters");
690 
691 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
692     "cxgbe(4) KERN_TLS parameters");
693 
694 static int t4_tls_inline_keys = 0;
695 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
696     &t4_tls_inline_keys, 0,
697     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
698     "in card memory.");
699 
700 static int t4_tls_combo_wrs = 0;
701 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
702     0, "Attempt to combine TCB field updates with TLS record work requests.");
703 #endif
704 
705 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
706 static int vi_mac_funcs[] = {
707 	FW_VI_FUNC_ETH,
708 	FW_VI_FUNC_OFLD,
709 	FW_VI_FUNC_IWARP,
710 	FW_VI_FUNC_OPENISCSI,
711 	FW_VI_FUNC_OPENFCOE,
712 	FW_VI_FUNC_FOISCSI,
713 	FW_VI_FUNC_FOFCOE,
714 };
715 
716 struct intrs_and_queues {
717 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
718 	uint16_t num_vis;	/* number of VIs for each port */
719 	uint16_t nirq;		/* Total # of vectors */
720 	uint16_t ntxq;		/* # of NIC txq's for each port */
721 	uint16_t nrxq;		/* # of NIC rxq's for each port */
722 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
723 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
724 	uint16_t nnmtxq;	/* # of netmap txq's */
725 	uint16_t nnmrxq;	/* # of netmap rxq's */
726 
727 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
728 	uint16_t ntxq_vi;	/* # of NIC txq's */
729 	uint16_t nrxq_vi;	/* # of NIC rxq's */
730 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
731 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
732 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
733 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
734 };
735 
736 static void setup_memwin(struct adapter *);
737 static void position_memwin(struct adapter *, int, uint32_t);
738 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
739 static int fwmtype_to_hwmtype(int);
740 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
741     uint32_t *);
742 static int fixup_devlog_params(struct adapter *);
743 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
744 static int contact_firmware(struct adapter *);
745 static int partition_resources(struct adapter *);
746 static int get_params__pre_init(struct adapter *);
747 static int set_params__pre_init(struct adapter *);
748 static int get_params__post_init(struct adapter *);
749 static int set_params__post_init(struct adapter *);
750 static void t4_set_desc(struct adapter *);
751 static bool fixed_ifmedia(struct port_info *);
752 static void build_medialist(struct port_info *);
753 static void init_link_config(struct port_info *);
754 static int fixup_link_config(struct port_info *);
755 static int apply_link_config(struct port_info *);
756 static int cxgbe_init_synchronized(struct vi_info *);
757 static int cxgbe_uninit_synchronized(struct vi_info *);
758 static int adapter_full_init(struct adapter *);
759 static void adapter_full_uninit(struct adapter *);
760 static int vi_full_init(struct vi_info *);
761 static void vi_full_uninit(struct vi_info *);
762 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
763 static void quiesce_txq(struct sge_txq *);
764 static void quiesce_wrq(struct sge_wrq *);
765 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
766 static void quiesce_vi(struct vi_info *);
767 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
768     driver_intr_t *, void *, char *);
769 static int t4_free_irq(struct adapter *, struct irq *);
770 static void t4_init_atid_table(struct adapter *);
771 static void t4_free_atid_table(struct adapter *);
772 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
773 static void vi_refresh_stats(struct vi_info *);
774 static void cxgbe_refresh_stats(struct vi_info *);
775 static void cxgbe_tick(void *);
776 static void vi_tick(void *);
777 static void cxgbe_sysctls(struct port_info *);
778 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
779 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
780 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
781 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
782 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
783 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
784 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
785 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
786 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
787 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
788 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
789 static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
790 static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
791 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
792 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
793 static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
794 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
795 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
796 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
797 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
798 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
799 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
800 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
801 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
802 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
803 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
804 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
805 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
806 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
807 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
808 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
809 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
810 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
811 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
812 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
813 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
814 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
815 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
816 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
817 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
818 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
819 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
820 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
821 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
822 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
823 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
824 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
825 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
826 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
827 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
828 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
829 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
830 #ifdef TCP_OFFLOAD
831 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
832 static int sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS);
833 static int sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS);
834 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
835 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
836 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
837 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
838 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
839 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
840 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
841 #endif
842 static int get_sge_context(struct adapter *, struct t4_sge_context *);
843 static int load_fw(struct adapter *, struct t4_data *);
844 static int load_cfg(struct adapter *, struct t4_data *);
845 static int load_boot(struct adapter *, struct t4_bootrom *);
846 static int load_bootcfg(struct adapter *, struct t4_data *);
847 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
848 static void free_offload_policy(struct t4_offload_policy *);
849 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
850 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
851 static int read_i2c(struct adapter *, struct t4_i2c_data *);
852 static int clear_stats(struct adapter *, u_int);
853 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
854 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
855 #ifdef TCP_OFFLOAD
856 static int toe_capability(struct vi_info *, bool);
857 static int t4_deactivate_all_uld(struct adapter *);
858 static void t4_async_event(struct adapter *);
859 #endif
860 #ifdef KERN_TLS
861 static int ktls_capability(struct adapter *, bool);
862 #endif
863 static int mod_event(module_t, int, void *);
864 static int notify_siblings(device_t, int);
865 static uint64_t vi_get_counter(struct ifnet *, ift_counter);
866 static uint64_t cxgbe_get_counter(struct ifnet *, ift_counter);
867 static void enable_vxlan_rx(struct adapter *);
868 static void reset_adapter_task(void *, int);
869 static void fatal_error_task(void *, int);
870 static void dump_devlog(struct adapter *);
871 static void dump_cim_regs(struct adapter *);
872 static void dump_cimla(struct adapter *);
873 
874 struct {
875 	uint16_t device;
876 	char *desc;
877 } t4_pciids[] = {
878 	{0xa000, "Chelsio Terminator 4 FPGA"},
879 	{0x4400, "Chelsio T440-dbg"},
880 	{0x4401, "Chelsio T420-CR"},
881 	{0x4402, "Chelsio T422-CR"},
882 	{0x4403, "Chelsio T440-CR"},
883 	{0x4404, "Chelsio T420-BCH"},
884 	{0x4405, "Chelsio T440-BCH"},
885 	{0x4406, "Chelsio T440-CH"},
886 	{0x4407, "Chelsio T420-SO"},
887 	{0x4408, "Chelsio T420-CX"},
888 	{0x4409, "Chelsio T420-BT"},
889 	{0x440a, "Chelsio T404-BT"},
890 	{0x440e, "Chelsio T440-LP-CR"},
891 }, t5_pciids[] = {
892 	{0xb000, "Chelsio Terminator 5 FPGA"},
893 	{0x5400, "Chelsio T580-dbg"},
894 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
895 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
896 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
897 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
898 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
899 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
900 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
901 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
902 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
903 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
904 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
905 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
906 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
907 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
908 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
909 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
910 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
911 
912 	/* Custom */
913 	{0x5483, "Custom T540-CR"},
914 	{0x5484, "Custom T540-BT"},
915 }, t6_pciids[] = {
916 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
917 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
918 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
919 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
920 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
921 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
922 	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
923 	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
924 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
925 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
926 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
927 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
928 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
929 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
930 	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
931 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
932 
933 	/* Custom */
934 	{0x6480, "Custom T6225-CR"},
935 	{0x6481, "Custom T62100-CR"},
936 	{0x6482, "Custom T6225-CR"},
937 	{0x6483, "Custom T62100-CR"},
938 	{0x6484, "Custom T64100-CR"},
939 	{0x6485, "Custom T6240-SO"},
940 	{0x6486, "Custom T6225-SO-CR"},
941 	{0x6487, "Custom T6225-CR"},
942 };
943 
944 #ifdef TCP_OFFLOAD
945 /*
946  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
947  * be exactly the same for both rxq and ofld_rxq.
948  */
949 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
950 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
951 #endif
952 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
953 
954 static int
955 t4_probe(device_t dev)
956 {
957 	int i;
958 	uint16_t v = pci_get_vendor(dev);
959 	uint16_t d = pci_get_device(dev);
960 	uint8_t f = pci_get_function(dev);
961 
962 	if (v != PCI_VENDOR_ID_CHELSIO)
963 		return (ENXIO);
964 
965 	/* Attach only to PF0 of the FPGA */
966 	if (d == 0xa000 && f != 0)
967 		return (ENXIO);
968 
969 	for (i = 0; i < nitems(t4_pciids); i++) {
970 		if (d == t4_pciids[i].device) {
971 			device_set_desc(dev, t4_pciids[i].desc);
972 			return (BUS_PROBE_DEFAULT);
973 		}
974 	}
975 
976 	return (ENXIO);
977 }
978 
979 static int
980 t5_probe(device_t dev)
981 {
982 	int i;
983 	uint16_t v = pci_get_vendor(dev);
984 	uint16_t d = pci_get_device(dev);
985 	uint8_t f = pci_get_function(dev);
986 
987 	if (v != PCI_VENDOR_ID_CHELSIO)
988 		return (ENXIO);
989 
990 	/* Attach only to PF0 of the FPGA */
991 	if (d == 0xb000 && f != 0)
992 		return (ENXIO);
993 
994 	for (i = 0; i < nitems(t5_pciids); i++) {
995 		if (d == t5_pciids[i].device) {
996 			device_set_desc(dev, t5_pciids[i].desc);
997 			return (BUS_PROBE_DEFAULT);
998 		}
999 	}
1000 
1001 	return (ENXIO);
1002 }
1003 
1004 static int
1005 t6_probe(device_t dev)
1006 {
1007 	int i;
1008 	uint16_t v = pci_get_vendor(dev);
1009 	uint16_t d = pci_get_device(dev);
1010 
1011 	if (v != PCI_VENDOR_ID_CHELSIO)
1012 		return (ENXIO);
1013 
1014 	for (i = 0; i < nitems(t6_pciids); i++) {
1015 		if (d == t6_pciids[i].device) {
1016 			device_set_desc(dev, t6_pciids[i].desc);
1017 			return (BUS_PROBE_DEFAULT);
1018 		}
1019 	}
1020 
1021 	return (ENXIO);
1022 }
1023 
1024 static void
1025 t5_attribute_workaround(device_t dev)
1026 {
1027 	device_t root_port;
1028 	uint32_t v;
1029 
1030 	/*
1031 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1032 	 * Ordering attributes when replying to a TLP from a Root
1033 	 * Port.  As a workaround, find the parent Root Port and
1034 	 * disable No Snoop and Relaxed Ordering.  Note that this
1035 	 * affects all devices under this root port.
1036 	 */
1037 	root_port = pci_find_pcie_root_port(dev);
1038 	if (root_port == NULL) {
1039 		device_printf(dev, "Unable to find parent root port\n");
1040 		return;
1041 	}
1042 
1043 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1044 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1045 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1046 	    0)
1047 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1048 		    device_get_nameunit(root_port));
1049 }
1050 
1051 static const struct devnames devnames[] = {
1052 	{
1053 		.nexus_name = "t4nex",
1054 		.ifnet_name = "cxgbe",
1055 		.vi_ifnet_name = "vcxgbe",
1056 		.pf03_drv_name = "t4iov",
1057 		.vf_nexus_name = "t4vf",
1058 		.vf_ifnet_name = "cxgbev"
1059 	}, {
1060 		.nexus_name = "t5nex",
1061 		.ifnet_name = "cxl",
1062 		.vi_ifnet_name = "vcxl",
1063 		.pf03_drv_name = "t5iov",
1064 		.vf_nexus_name = "t5vf",
1065 		.vf_ifnet_name = "cxlv"
1066 	}, {
1067 		.nexus_name = "t6nex",
1068 		.ifnet_name = "cc",
1069 		.vi_ifnet_name = "vcc",
1070 		.pf03_drv_name = "t6iov",
1071 		.vf_nexus_name = "t6vf",
1072 		.vf_ifnet_name = "ccv"
1073 	}
1074 };
1075 
1076 void
1077 t4_init_devnames(struct adapter *sc)
1078 {
1079 	int id;
1080 
1081 	id = chip_id(sc);
1082 	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1083 		sc->names = &devnames[id - CHELSIO_T4];
1084 	else {
1085 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1086 		sc->names = NULL;
1087 	}
1088 }
1089 
1090 static int
1091 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1092 {
1093 	const char *parent, *name;
1094 	long value;
1095 	int line, unit;
1096 
1097 	line = 0;
1098 	parent = device_get_nameunit(sc->dev);
1099 	name = sc->names->ifnet_name;
1100 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1101 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1102 		    value == pi->port_id)
1103 			return (unit);
1104 	}
1105 	return (-1);
1106 }
1107 
1108 static int
1109 t4_attach(device_t dev)
1110 {
1111 	struct adapter *sc;
1112 	int rc = 0, i, j, rqidx, tqidx, nports;
1113 	struct make_dev_args mda;
1114 	struct intrs_and_queues iaq;
1115 	struct sge *s;
1116 	uint32_t *buf;
1117 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1118 	int ofld_tqidx;
1119 #endif
1120 #ifdef TCP_OFFLOAD
1121 	int ofld_rqidx;
1122 #endif
1123 #ifdef DEV_NETMAP
1124 	int nm_rqidx, nm_tqidx;
1125 #endif
1126 	int num_vis;
1127 
1128 	sc = device_get_softc(dev);
1129 	sc->dev = dev;
1130 	sysctl_ctx_init(&sc->ctx);
1131 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1132 
1133 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1134 		t5_attribute_workaround(dev);
1135 	pci_enable_busmaster(dev);
1136 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1137 		uint32_t v;
1138 
1139 		pci_set_max_read_req(dev, 4096);
1140 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1141 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1142 		if (pcie_relaxed_ordering == 0 &&
1143 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1144 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1145 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1146 		} else if (pcie_relaxed_ordering == 1 &&
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 		}
1151 	}
1152 
1153 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1154 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1155 	sc->traceq = -1;
1156 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1157 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1158 	    device_get_nameunit(dev));
1159 
1160 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1161 	    device_get_nameunit(dev));
1162 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1163 	t4_add_adapter(sc);
1164 
1165 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1166 	TAILQ_INIT(&sc->sfl);
1167 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1168 
1169 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1170 
1171 	sc->policy = NULL;
1172 	rw_init(&sc->policy_lock, "connection offload policy");
1173 
1174 	callout_init(&sc->ktls_tick, 1);
1175 
1176 	refcount_init(&sc->vxlan_refcount, 0);
1177 
1178 	TASK_INIT(&sc->reset_task, 0, reset_adapter_task, sc);
1179 	TASK_INIT(&sc->fatal_error_task, 0, fatal_error_task, sc);
1180 
1181 	sc->ctrlq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1182 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1183 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1184 	sc->fwq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1185 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1186 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1187 
1188 	rc = t4_map_bars_0_and_4(sc);
1189 	if (rc != 0)
1190 		goto done; /* error message displayed already */
1191 
1192 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1193 
1194 	/* Prepare the adapter for operation. */
1195 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1196 	rc = -t4_prep_adapter(sc, buf);
1197 	free(buf, M_CXGBE);
1198 	if (rc != 0) {
1199 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1200 		goto done;
1201 	}
1202 
1203 	/*
1204 	 * This is the real PF# to which we're attaching.  Works from within PCI
1205 	 * passthrough environments too, where pci_get_function() could return a
1206 	 * different PF# depending on the passthrough configuration.  We need to
1207 	 * use the real PF# in all our communication with the firmware.
1208 	 */
1209 	j = t4_read_reg(sc, A_PL_WHOAMI);
1210 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1211 	sc->mbox = sc->pf;
1212 
1213 	t4_init_devnames(sc);
1214 	if (sc->names == NULL) {
1215 		rc = ENOTSUP;
1216 		goto done; /* error message displayed already */
1217 	}
1218 
1219 	/*
1220 	 * Do this really early, with the memory windows set up even before the
1221 	 * character device.  The userland tool's register i/o and mem read
1222 	 * will work even in "recovery mode".
1223 	 */
1224 	setup_memwin(sc);
1225 	if (t4_init_devlog_params(sc, 0) == 0)
1226 		fixup_devlog_params(sc);
1227 	make_dev_args_init(&mda);
1228 	mda.mda_devsw = &t4_cdevsw;
1229 	mda.mda_uid = UID_ROOT;
1230 	mda.mda_gid = GID_WHEEL;
1231 	mda.mda_mode = 0600;
1232 	mda.mda_si_drv1 = sc;
1233 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1234 	if (rc != 0)
1235 		device_printf(dev, "failed to create nexus char device: %d.\n",
1236 		    rc);
1237 
1238 	/* Go no further if recovery mode has been requested. */
1239 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1240 		device_printf(dev, "recovery mode.\n");
1241 		goto done;
1242 	}
1243 
1244 #if defined(__i386__)
1245 	if ((cpu_feature & CPUID_CX8) == 0) {
1246 		device_printf(dev, "64 bit atomics not available.\n");
1247 		rc = ENOTSUP;
1248 		goto done;
1249 	}
1250 #endif
1251 
1252 	/* Contact the firmware and try to become the master driver. */
1253 	rc = contact_firmware(sc);
1254 	if (rc != 0)
1255 		goto done; /* error message displayed already */
1256 	MPASS(sc->flags & FW_OK);
1257 
1258 	rc = get_params__pre_init(sc);
1259 	if (rc != 0)
1260 		goto done; /* error message displayed already */
1261 
1262 	if (sc->flags & MASTER_PF) {
1263 		rc = partition_resources(sc);
1264 		if (rc != 0)
1265 			goto done; /* error message displayed already */
1266 		t4_intr_clear(sc);
1267 	}
1268 
1269 	rc = get_params__post_init(sc);
1270 	if (rc != 0)
1271 		goto done; /* error message displayed already */
1272 
1273 	rc = set_params__post_init(sc);
1274 	if (rc != 0)
1275 		goto done; /* error message displayed already */
1276 
1277 	rc = t4_map_bar_2(sc);
1278 	if (rc != 0)
1279 		goto done; /* error message displayed already */
1280 
1281 	rc = t4_create_dma_tag(sc);
1282 	if (rc != 0)
1283 		goto done; /* error message displayed already */
1284 
1285 	/*
1286 	 * First pass over all the ports - allocate VIs and initialize some
1287 	 * basic parameters like mac address, port type, etc.
1288 	 */
1289 	for_each_port(sc, i) {
1290 		struct port_info *pi;
1291 
1292 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1293 		sc->port[i] = pi;
1294 
1295 		/* These must be set before t4_port_init */
1296 		pi->adapter = sc;
1297 		pi->port_id = i;
1298 		/*
1299 		 * XXX: vi[0] is special so we can't delay this allocation until
1300 		 * pi->nvi's final value is known.
1301 		 */
1302 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1303 		    M_ZERO | M_WAITOK);
1304 
1305 		/*
1306 		 * Allocate the "main" VI and initialize parameters
1307 		 * like mac addr.
1308 		 */
1309 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1310 		if (rc != 0) {
1311 			device_printf(dev, "unable to initialize port %d: %d\n",
1312 			    i, rc);
1313 			free(pi->vi, M_CXGBE);
1314 			free(pi, M_CXGBE);
1315 			sc->port[i] = NULL;
1316 			goto done;
1317 		}
1318 
1319 		if (is_bt(pi->port_type))
1320 			setbit(&sc->bt_map, pi->tx_chan);
1321 		else
1322 			MPASS(!isset(&sc->bt_map, pi->tx_chan));
1323 
1324 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1325 		    device_get_nameunit(dev), i);
1326 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1327 		sc->chan_map[pi->tx_chan] = i;
1328 
1329 		/*
1330 		 * The MPS counter for FCS errors doesn't work correctly on the
1331 		 * T6 so we use the MAC counter here.  Which MAC is in use
1332 		 * depends on the link settings which will be known when the
1333 		 * link comes up.
1334 		 */
1335 		if (is_t6(sc)) {
1336 			pi->fcs_reg = -1;
1337 		} else if (is_t4(sc)) {
1338 			pi->fcs_reg = PORT_REG(pi->tx_chan,
1339 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1340 		} else {
1341 			pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
1342 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1343 		}
1344 		pi->fcs_base = 0;
1345 
1346 		/* All VIs on this port share this media. */
1347 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1348 		    cxgbe_media_status);
1349 
1350 		PORT_LOCK(pi);
1351 		init_link_config(pi);
1352 		fixup_link_config(pi);
1353 		build_medialist(pi);
1354 		if (fixed_ifmedia(pi))
1355 			pi->flags |= FIXED_IFMEDIA;
1356 		PORT_UNLOCK(pi);
1357 
1358 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1359 		    t4_ifnet_unit(sc, pi));
1360 		if (pi->dev == NULL) {
1361 			device_printf(dev,
1362 			    "failed to add device for port %d.\n", i);
1363 			rc = ENXIO;
1364 			goto done;
1365 		}
1366 		pi->vi[0].dev = pi->dev;
1367 		device_set_softc(pi->dev, pi);
1368 	}
1369 
1370 	/*
1371 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1372 	 */
1373 	nports = sc->params.nports;
1374 	rc = cfg_itype_and_nqueues(sc, &iaq);
1375 	if (rc != 0)
1376 		goto done; /* error message displayed already */
1377 
1378 	num_vis = iaq.num_vis;
1379 	sc->intr_type = iaq.intr_type;
1380 	sc->intr_count = iaq.nirq;
1381 
1382 	s = &sc->sge;
1383 	s->nrxq = nports * iaq.nrxq;
1384 	s->ntxq = nports * iaq.ntxq;
1385 	if (num_vis > 1) {
1386 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1387 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1388 	}
1389 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1390 	s->neq += nports;		/* ctrl queues: 1 per port */
1391 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1392 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1393 	if (is_offload(sc) || is_ethoffload(sc)) {
1394 		s->nofldtxq = nports * iaq.nofldtxq;
1395 		if (num_vis > 1)
1396 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1397 		s->neq += s->nofldtxq;
1398 
1399 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1400 		    M_CXGBE, M_ZERO | M_WAITOK);
1401 	}
1402 #endif
1403 #ifdef TCP_OFFLOAD
1404 	if (is_offload(sc)) {
1405 		s->nofldrxq = nports * iaq.nofldrxq;
1406 		if (num_vis > 1)
1407 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1408 		s->neq += s->nofldrxq;	/* free list */
1409 		s->niq += s->nofldrxq;
1410 
1411 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1412 		    M_CXGBE, M_ZERO | M_WAITOK);
1413 	}
1414 #endif
1415 #ifdef DEV_NETMAP
1416 	s->nnmrxq = 0;
1417 	s->nnmtxq = 0;
1418 	if (t4_native_netmap & NN_MAIN_VI) {
1419 		s->nnmrxq += nports * iaq.nnmrxq;
1420 		s->nnmtxq += nports * iaq.nnmtxq;
1421 	}
1422 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1423 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1424 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1425 	}
1426 	s->neq += s->nnmtxq + s->nnmrxq;
1427 	s->niq += s->nnmrxq;
1428 
1429 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1430 	    M_CXGBE, M_ZERO | M_WAITOK);
1431 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1432 	    M_CXGBE, M_ZERO | M_WAITOK);
1433 #endif
1434 	MPASS(s->niq <= s->iqmap_sz);
1435 	MPASS(s->neq <= s->eqmap_sz);
1436 
1437 	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1438 	    M_ZERO | M_WAITOK);
1439 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1440 	    M_ZERO | M_WAITOK);
1441 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1442 	    M_ZERO | M_WAITOK);
1443 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1444 	    M_ZERO | M_WAITOK);
1445 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1446 	    M_ZERO | M_WAITOK);
1447 
1448 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1449 	    M_ZERO | M_WAITOK);
1450 
1451 	t4_init_l2t(sc, M_WAITOK);
1452 	t4_init_smt(sc, M_WAITOK);
1453 	t4_init_tx_sched(sc);
1454 	t4_init_atid_table(sc);
1455 #ifdef RATELIMIT
1456 	t4_init_etid_table(sc);
1457 #endif
1458 #ifdef INET6
1459 	t4_init_clip_table(sc);
1460 #endif
1461 	if (sc->vres.key.size != 0)
1462 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1463 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1464 
1465 	/*
1466 	 * Second pass over the ports.  This time we know the number of rx and
1467 	 * tx queues that each port should get.
1468 	 */
1469 	rqidx = tqidx = 0;
1470 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1471 	ofld_tqidx = 0;
1472 #endif
1473 #ifdef TCP_OFFLOAD
1474 	ofld_rqidx = 0;
1475 #endif
1476 #ifdef DEV_NETMAP
1477 	nm_rqidx = nm_tqidx = 0;
1478 #endif
1479 	for_each_port(sc, i) {
1480 		struct port_info *pi = sc->port[i];
1481 		struct vi_info *vi;
1482 
1483 		if (pi == NULL)
1484 			continue;
1485 
1486 		pi->nvi = num_vis;
1487 		for_each_vi(pi, j, vi) {
1488 			vi->pi = pi;
1489 			vi->adapter = sc;
1490 			vi->first_intr = -1;
1491 			vi->qsize_rxq = t4_qsize_rxq;
1492 			vi->qsize_txq = t4_qsize_txq;
1493 
1494 			vi->first_rxq = rqidx;
1495 			vi->first_txq = tqidx;
1496 			vi->tmr_idx = t4_tmr_idx;
1497 			vi->pktc_idx = t4_pktc_idx;
1498 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1499 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1500 
1501 			rqidx += vi->nrxq;
1502 			tqidx += vi->ntxq;
1503 
1504 			if (j == 0 && vi->ntxq > 1)
1505 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1506 			else
1507 				vi->rsrv_noflowq = 0;
1508 
1509 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1510 			vi->first_ofld_txq = ofld_tqidx;
1511 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1512 			ofld_tqidx += vi->nofldtxq;
1513 #endif
1514 #ifdef TCP_OFFLOAD
1515 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1516 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1517 			vi->first_ofld_rxq = ofld_rqidx;
1518 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1519 
1520 			ofld_rqidx += vi->nofldrxq;
1521 #endif
1522 #ifdef DEV_NETMAP
1523 			vi->first_nm_rxq = nm_rqidx;
1524 			vi->first_nm_txq = nm_tqidx;
1525 			if (j == 0) {
1526 				vi->nnmrxq = iaq.nnmrxq;
1527 				vi->nnmtxq = iaq.nnmtxq;
1528 			} else {
1529 				vi->nnmrxq = iaq.nnmrxq_vi;
1530 				vi->nnmtxq = iaq.nnmtxq_vi;
1531 			}
1532 			nm_rqidx += vi->nnmrxq;
1533 			nm_tqidx += vi->nnmtxq;
1534 #endif
1535 		}
1536 	}
1537 
1538 	rc = t4_setup_intr_handlers(sc);
1539 	if (rc != 0) {
1540 		device_printf(dev,
1541 		    "failed to setup interrupt handlers: %d\n", rc);
1542 		goto done;
1543 	}
1544 
1545 	rc = bus_generic_probe(dev);
1546 	if (rc != 0) {
1547 		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1548 		goto done;
1549 	}
1550 
1551 	/*
1552 	 * Ensure thread-safe mailbox access (in debug builds).
1553 	 *
1554 	 * So far this was the only thread accessing the mailbox but various
1555 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1556 	 * will access the mailbox from different threads.
1557 	 */
1558 	sc->flags |= CHK_MBOX_ACCESS;
1559 
1560 	rc = bus_generic_attach(dev);
1561 	if (rc != 0) {
1562 		device_printf(dev,
1563 		    "failed to attach all child ports: %d\n", rc);
1564 		goto done;
1565 	}
1566 
1567 	device_printf(dev,
1568 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1569 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1570 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1571 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1572 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1573 
1574 	t4_set_desc(sc);
1575 
1576 	notify_siblings(dev, 0);
1577 
1578 done:
1579 	if (rc != 0 && sc->cdev) {
1580 		/* cdev was created and so cxgbetool works; recover that way. */
1581 		device_printf(dev,
1582 		    "error during attach, adapter is now in recovery mode.\n");
1583 		rc = 0;
1584 	}
1585 
1586 	if (rc != 0)
1587 		t4_detach_common(dev);
1588 	else
1589 		t4_sysctls(sc);
1590 
1591 	return (rc);
1592 }
1593 
1594 static int
1595 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1596 {
1597 	struct adapter *sc;
1598 	struct port_info *pi;
1599 	int i;
1600 
1601 	sc = device_get_softc(bus);
1602 	for_each_port(sc, i) {
1603 		pi = sc->port[i];
1604 		if (pi != NULL && pi->dev == dev) {
1605 			sbuf_printf(sb, "port=%d", pi->port_id);
1606 			break;
1607 		}
1608 	}
1609 	return (0);
1610 }
1611 
1612 static int
1613 t4_ready(device_t dev)
1614 {
1615 	struct adapter *sc;
1616 
1617 	sc = device_get_softc(dev);
1618 	if (sc->flags & FW_OK)
1619 		return (0);
1620 	return (ENXIO);
1621 }
1622 
1623 static int
1624 t4_read_port_device(device_t dev, int port, device_t *child)
1625 {
1626 	struct adapter *sc;
1627 	struct port_info *pi;
1628 
1629 	sc = device_get_softc(dev);
1630 	if (port < 0 || port >= MAX_NPORTS)
1631 		return (EINVAL);
1632 	pi = sc->port[port];
1633 	if (pi == NULL || pi->dev == NULL)
1634 		return (ENXIO);
1635 	*child = pi->dev;
1636 	return (0);
1637 }
1638 
1639 static int
1640 notify_siblings(device_t dev, int detaching)
1641 {
1642 	device_t sibling;
1643 	int error, i;
1644 
1645 	error = 0;
1646 	for (i = 0; i < PCI_FUNCMAX; i++) {
1647 		if (i == pci_get_function(dev))
1648 			continue;
1649 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1650 		    pci_get_slot(dev), i);
1651 		if (sibling == NULL || !device_is_attached(sibling))
1652 			continue;
1653 		if (detaching)
1654 			error = T4_DETACH_CHILD(sibling);
1655 		else
1656 			(void)T4_ATTACH_CHILD(sibling);
1657 		if (error)
1658 			break;
1659 	}
1660 	return (error);
1661 }
1662 
1663 /*
1664  * Idempotent
1665  */
1666 static int
1667 t4_detach(device_t dev)
1668 {
1669 	int rc;
1670 
1671 	rc = notify_siblings(dev, 1);
1672 	if (rc) {
1673 		device_printf(dev,
1674 		    "failed to detach sibling devices: %d\n", rc);
1675 		return (rc);
1676 	}
1677 
1678 	return (t4_detach_common(dev));
1679 }
1680 
1681 int
1682 t4_detach_common(device_t dev)
1683 {
1684 	struct adapter *sc;
1685 	struct port_info *pi;
1686 	int i, rc;
1687 
1688 	sc = device_get_softc(dev);
1689 
1690 #ifdef TCP_OFFLOAD
1691 	rc = t4_deactivate_all_uld(sc);
1692 	if (rc) {
1693 		device_printf(dev,
1694 		    "failed to detach upper layer drivers: %d\n", rc);
1695 		return (rc);
1696 	}
1697 #endif
1698 
1699 	if (sc->cdev) {
1700 		destroy_dev(sc->cdev);
1701 		sc->cdev = NULL;
1702 	}
1703 
1704 	sx_xlock(&t4_list_lock);
1705 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1706 	sx_xunlock(&t4_list_lock);
1707 
1708 	sc->flags &= ~CHK_MBOX_ACCESS;
1709 	if (sc->flags & FULL_INIT_DONE) {
1710 		if (!(sc->flags & IS_VF))
1711 			t4_intr_disable(sc);
1712 	}
1713 
1714 	if (device_is_attached(dev)) {
1715 		rc = bus_generic_detach(dev);
1716 		if (rc) {
1717 			device_printf(dev,
1718 			    "failed to detach child devices: %d\n", rc);
1719 			return (rc);
1720 		}
1721 	}
1722 
1723 	for (i = 0; i < sc->intr_count; i++)
1724 		t4_free_irq(sc, &sc->irq[i]);
1725 
1726 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1727 		t4_free_tx_sched(sc);
1728 
1729 	for (i = 0; i < MAX_NPORTS; i++) {
1730 		pi = sc->port[i];
1731 		if (pi) {
1732 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1733 			if (pi->dev)
1734 				device_delete_child(dev, pi->dev);
1735 
1736 			mtx_destroy(&pi->pi_lock);
1737 			free(pi->vi, M_CXGBE);
1738 			free(pi, M_CXGBE);
1739 		}
1740 	}
1741 
1742 	device_delete_children(dev);
1743 	sysctl_ctx_free(&sc->ctx);
1744 	adapter_full_uninit(sc);
1745 
1746 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1747 		t4_fw_bye(sc, sc->mbox);
1748 
1749 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1750 		pci_release_msi(dev);
1751 
1752 	if (sc->regs_res)
1753 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1754 		    sc->regs_res);
1755 
1756 	if (sc->udbs_res)
1757 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1758 		    sc->udbs_res);
1759 
1760 	if (sc->msix_res)
1761 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1762 		    sc->msix_res);
1763 
1764 	if (sc->l2t)
1765 		t4_free_l2t(sc->l2t);
1766 	if (sc->smt)
1767 		t4_free_smt(sc->smt);
1768 	t4_free_atid_table(sc);
1769 #ifdef RATELIMIT
1770 	t4_free_etid_table(sc);
1771 #endif
1772 	if (sc->key_map)
1773 		vmem_destroy(sc->key_map);
1774 #ifdef INET6
1775 	t4_destroy_clip_table(sc);
1776 #endif
1777 
1778 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1779 	free(sc->sge.ofld_txq, M_CXGBE);
1780 #endif
1781 #ifdef TCP_OFFLOAD
1782 	free(sc->sge.ofld_rxq, M_CXGBE);
1783 #endif
1784 #ifdef DEV_NETMAP
1785 	free(sc->sge.nm_rxq, M_CXGBE);
1786 	free(sc->sge.nm_txq, M_CXGBE);
1787 #endif
1788 	free(sc->irq, M_CXGBE);
1789 	free(sc->sge.rxq, M_CXGBE);
1790 	free(sc->sge.txq, M_CXGBE);
1791 	free(sc->sge.ctrlq, M_CXGBE);
1792 	free(sc->sge.iqmap, M_CXGBE);
1793 	free(sc->sge.eqmap, M_CXGBE);
1794 	free(sc->tids.ftid_tab, M_CXGBE);
1795 	free(sc->tids.hpftid_tab, M_CXGBE);
1796 	free_hftid_hash(&sc->tids);
1797 	free(sc->tids.tid_tab, M_CXGBE);
1798 	free(sc->tt.tls_rx_ports, M_CXGBE);
1799 	t4_destroy_dma_tag(sc);
1800 
1801 	callout_drain(&sc->ktls_tick);
1802 	callout_drain(&sc->sfl_callout);
1803 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1804 		mtx_destroy(&sc->tids.ftid_lock);
1805 		cv_destroy(&sc->tids.ftid_cv);
1806 	}
1807 	if (mtx_initialized(&sc->tids.atid_lock))
1808 		mtx_destroy(&sc->tids.atid_lock);
1809 	if (mtx_initialized(&sc->ifp_lock))
1810 		mtx_destroy(&sc->ifp_lock);
1811 
1812 	if (rw_initialized(&sc->policy_lock)) {
1813 		rw_destroy(&sc->policy_lock);
1814 #ifdef TCP_OFFLOAD
1815 		if (sc->policy != NULL)
1816 			free_offload_policy(sc->policy);
1817 #endif
1818 	}
1819 
1820 	for (i = 0; i < NUM_MEMWIN; i++) {
1821 		struct memwin *mw = &sc->memwin[i];
1822 
1823 		if (rw_initialized(&mw->mw_lock))
1824 			rw_destroy(&mw->mw_lock);
1825 	}
1826 
1827 	mtx_destroy(&sc->sfl_lock);
1828 	mtx_destroy(&sc->reg_lock);
1829 	mtx_destroy(&sc->sc_lock);
1830 
1831 	bzero(sc, sizeof(*sc));
1832 
1833 	return (0);
1834 }
1835 
1836 static inline bool
1837 ok_to_reset(struct adapter *sc)
1838 {
1839 	struct tid_info *t = &sc->tids;
1840 	struct port_info *pi;
1841 	struct vi_info *vi;
1842 	int i, j;
1843 	const int caps = IFCAP_TOE | IFCAP_TXTLS | IFCAP_NETMAP | IFCAP_TXRTLMT;
1844 
1845 	ASSERT_SYNCHRONIZED_OP(sc);
1846 	MPASS(!(sc->flags & IS_VF));
1847 
1848 	for_each_port(sc, i) {
1849 		pi = sc->port[i];
1850 		for_each_vi(pi, j, vi) {
1851 			if (vi->ifp->if_capenable & caps)
1852 				return (false);
1853 		}
1854 	}
1855 
1856 	if (atomic_load_int(&t->tids_in_use) > 0)
1857 		return (false);
1858 	if (atomic_load_int(&t->stids_in_use) > 0)
1859 		return (false);
1860 	if (atomic_load_int(&t->atids_in_use) > 0)
1861 		return (false);
1862 	if (atomic_load_int(&t->ftids_in_use) > 0)
1863 		return (false);
1864 	if (atomic_load_int(&t->hpftids_in_use) > 0)
1865 		return (false);
1866 	if (atomic_load_int(&t->etids_in_use) > 0)
1867 		return (false);
1868 
1869 	return (true);
1870 }
1871 
1872 static inline int
1873 stop_adapter(struct adapter *sc)
1874 {
1875 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_STOPPED)))
1876 		return (1);		/* Already stopped. */
1877 	return (t4_shutdown_adapter(sc));
1878 }
1879 
1880 static int
1881 t4_suspend(device_t dev)
1882 {
1883 	struct adapter *sc = device_get_softc(dev);
1884 	struct port_info *pi;
1885 	struct vi_info *vi;
1886 	struct ifnet *ifp;
1887 	struct sge_rxq *rxq;
1888 	struct sge_txq *txq;
1889 	struct sge_wrq *wrq;
1890 #ifdef TCP_OFFLOAD
1891 	struct sge_ofld_rxq *ofld_rxq;
1892 #endif
1893 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1894 	struct sge_ofld_txq *ofld_txq;
1895 #endif
1896 	int rc, i, j, k;
1897 
1898 	CH_ALERT(sc, "suspend requested\n");
1899 
1900 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4sus");
1901 	if (rc != 0)
1902 		return (ENXIO);
1903 
1904 	/* XXX: Can the kernel call suspend repeatedly without resume? */
1905 	MPASS(!hw_off_limits(sc));
1906 
1907 	if (!ok_to_reset(sc)) {
1908 		/* XXX: should list what resource is preventing suspend. */
1909 		CH_ERR(sc, "not safe to suspend.\n");
1910 		rc = EBUSY;
1911 		goto done;
1912 	}
1913 
1914 	/* No more DMA or interrupts. */
1915 	stop_adapter(sc);
1916 
1917 	/* Quiesce all activity. */
1918 	for_each_port(sc, i) {
1919 		pi = sc->port[i];
1920 		pi->vxlan_tcam_entry = false;
1921 
1922 		PORT_LOCK(pi);
1923 		if (pi->up_vis > 0) {
1924 			/*
1925 			 * t4_shutdown_adapter has already shut down all the
1926 			 * PHYs but it also disables interrupts and DMA so there
1927 			 * won't be a link interrupt.  So we update the state
1928 			 * manually and inform the kernel.
1929 			 */
1930 			pi->link_cfg.link_ok = false;
1931 			t4_os_link_changed(pi);
1932 		}
1933 		PORT_UNLOCK(pi);
1934 
1935 		for_each_vi(pi, j, vi) {
1936 			vi->xact_addr_filt = -1;
1937 			mtx_lock(&vi->tick_mtx);
1938 			vi->flags |= VI_SKIP_STATS;
1939 			mtx_unlock(&vi->tick_mtx);
1940 			if (!(vi->flags & VI_INIT_DONE))
1941 				continue;
1942 
1943 			ifp = vi->ifp;
1944 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1945 				mtx_lock(&vi->tick_mtx);
1946 				callout_stop(&vi->tick);
1947 				mtx_unlock(&vi->tick_mtx);
1948 				callout_drain(&vi->tick);
1949 			}
1950 
1951 			/*
1952 			 * Note that the HW is not available.
1953 			 */
1954 			for_each_txq(vi, k, txq) {
1955 				TXQ_LOCK(txq);
1956 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
1957 				TXQ_UNLOCK(txq);
1958 			}
1959 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1960 			for_each_ofld_txq(vi, k, ofld_txq) {
1961 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
1962 			}
1963 #endif
1964 			for_each_rxq(vi, k, rxq) {
1965 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1966 			}
1967 #if defined(TCP_OFFLOAD)
1968 			for_each_ofld_rxq(vi, k, ofld_rxq) {
1969 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1970 			}
1971 #endif
1972 
1973 			quiesce_vi(vi);
1974 		}
1975 
1976 		if (sc->flags & FULL_INIT_DONE) {
1977 			/* Control queue */
1978 			wrq = &sc->sge.ctrlq[i];
1979 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
1980 			quiesce_wrq(wrq);
1981 		}
1982 	}
1983 	if (sc->flags & FULL_INIT_DONE) {
1984 		/* Firmware event queue */
1985 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
1986 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
1987 	}
1988 
1989 	/* Mark the adapter totally off limits. */
1990 	mtx_lock(&sc->reg_lock);
1991 	atomic_set_int(&sc->error_flags, HW_OFF_LIMITS);
1992 	sc->flags &= ~(FW_OK | MASTER_PF);
1993 	sc->reset_thread = NULL;
1994 	mtx_unlock(&sc->reg_lock);
1995 
1996 	CH_ALERT(sc, "suspend completed.\n");
1997 done:
1998 	end_synchronized_op(sc, 0);
1999 	return (rc);
2000 }
2001 
2002 struct adapter_pre_reset_state {
2003 	u_int flags;
2004 	uint16_t nbmcaps;
2005 	uint16_t linkcaps;
2006 	uint16_t switchcaps;
2007 	uint16_t niccaps;
2008 	uint16_t toecaps;
2009 	uint16_t rdmacaps;
2010 	uint16_t cryptocaps;
2011 	uint16_t iscsicaps;
2012 	uint16_t fcoecaps;
2013 
2014 	u_int cfcsum;
2015 	char cfg_file[32];
2016 
2017 	struct adapter_params params;
2018 	struct t4_virt_res vres;
2019 	struct tid_info tids;
2020 	struct sge sge;
2021 
2022 	int rawf_base;
2023 	int nrawf;
2024 
2025 };
2026 
2027 static void
2028 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2029 {
2030 
2031 	ASSERT_SYNCHRONIZED_OP(sc);
2032 
2033 	o->flags = sc->flags;
2034 
2035 	o->nbmcaps =  sc->nbmcaps;
2036 	o->linkcaps = sc->linkcaps;
2037 	o->switchcaps = sc->switchcaps;
2038 	o->niccaps = sc->niccaps;
2039 	o->toecaps = sc->toecaps;
2040 	o->rdmacaps = sc->rdmacaps;
2041 	o->cryptocaps = sc->cryptocaps;
2042 	o->iscsicaps = sc->iscsicaps;
2043 	o->fcoecaps = sc->fcoecaps;
2044 
2045 	o->cfcsum = sc->cfcsum;
2046 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2047 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2048 
2049 	o->params = sc->params;
2050 	o->vres = sc->vres;
2051 	o->tids = sc->tids;
2052 	o->sge = sc->sge;
2053 
2054 	o->rawf_base = sc->rawf_base;
2055 	o->nrawf = sc->nrawf;
2056 }
2057 
2058 static int
2059 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2060 {
2061 	int rc = 0;
2062 
2063 	ASSERT_SYNCHRONIZED_OP(sc);
2064 
2065 	/* Capabilities */
2066 #define COMPARE_CAPS(c) do { \
2067 	if (o->c##caps != sc->c##caps) { \
2068 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2069 		    sc->c##caps); \
2070 		rc = EINVAL; \
2071 	} \
2072 } while (0)
2073 	COMPARE_CAPS(nbm);
2074 	COMPARE_CAPS(link);
2075 	COMPARE_CAPS(switch);
2076 	COMPARE_CAPS(nic);
2077 	COMPARE_CAPS(toe);
2078 	COMPARE_CAPS(rdma);
2079 	COMPARE_CAPS(crypto);
2080 	COMPARE_CAPS(iscsi);
2081 	COMPARE_CAPS(fcoe);
2082 #undef COMPARE_CAPS
2083 
2084 	/* Firmware config file */
2085 	if (o->cfcsum != sc->cfcsum) {
2086 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2087 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2088 		rc = EINVAL;
2089 	}
2090 
2091 #define COMPARE_PARAM(p, name) do { \
2092 	if (o->p != sc->p) { \
2093 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2094 		rc = EINVAL; \
2095 	} \
2096 } while (0)
2097 	COMPARE_PARAM(sge.iq_start, iq_start);
2098 	COMPARE_PARAM(sge.eq_start, eq_start);
2099 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2100 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2101 	COMPARE_PARAM(tids.nftids, nftids);
2102 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2103 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2104 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2105 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2106 	COMPARE_PARAM(tids.tid_base, tid_base);
2107 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2108 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2109 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2110 	COMPARE_PARAM(rawf_base, rawf_base);
2111 	COMPARE_PARAM(nrawf, nrawf);
2112 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2113 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2114 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2115 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2116 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2117 	COMPARE_PARAM(tids.ntids, ntids);
2118 	COMPARE_PARAM(tids.etid_base, etid_base);
2119 	COMPARE_PARAM(tids.etid_end, etid_end);
2120 	COMPARE_PARAM(tids.netids, netids);
2121 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2122 	COMPARE_PARAM(params.ethoffload, ethoffload);
2123 	COMPARE_PARAM(tids.natids, natids);
2124 	COMPARE_PARAM(tids.stid_base, stid_base);
2125 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2126 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2127 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2128 	COMPARE_PARAM(vres.stag.start, stag_start);
2129 	COMPARE_PARAM(vres.stag.size, stag_size);
2130 	COMPARE_PARAM(vres.rq.start, rq_start);
2131 	COMPARE_PARAM(vres.rq.size, rq_size);
2132 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2133 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2134 	COMPARE_PARAM(vres.qp.start, qp_start);
2135 	COMPARE_PARAM(vres.qp.size, qp_size);
2136 	COMPARE_PARAM(vres.cq.start, cq_start);
2137 	COMPARE_PARAM(vres.cq.size, cq_size);
2138 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2139 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2140 	COMPARE_PARAM(vres.srq.start, srq_start);
2141 	COMPARE_PARAM(vres.srq.size, srq_size);
2142 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2143 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2144 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2145 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2146 	COMPARE_PARAM(vres.key.start, key_start);
2147 	COMPARE_PARAM(vres.key.size, key_size);
2148 #undef COMPARE_PARAM
2149 
2150 	return (rc);
2151 }
2152 
2153 static int
2154 t4_resume(device_t dev)
2155 {
2156 	struct adapter *sc = device_get_softc(dev);
2157 	struct adapter_pre_reset_state *old_state = NULL;
2158 	struct port_info *pi;
2159 	struct vi_info *vi;
2160 	struct ifnet *ifp;
2161 	struct sge_txq *txq;
2162 	int rc, i, j, k;
2163 
2164 	CH_ALERT(sc, "resume requested.\n");
2165 
2166 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4res");
2167 	if (rc != 0)
2168 		return (ENXIO);
2169 	MPASS(hw_off_limits(sc));
2170 	MPASS((sc->flags & FW_OK) == 0);
2171 	MPASS((sc->flags & MASTER_PF) == 0);
2172 	MPASS(sc->reset_thread == NULL);
2173 	sc->reset_thread = curthread;
2174 
2175 	/* Register access is expected to work by the time we're here. */
2176 	if (t4_read_reg(sc, A_PL_WHOAMI) == 0xffffffff) {
2177 		CH_ERR(sc, "%s: can't read device registers\n", __func__);
2178 		rc = ENXIO;
2179 		goto done;
2180 	}
2181 
2182 	/* Note that HW_OFF_LIMITS is cleared a bit later. */
2183 	atomic_clear_int(&sc->error_flags, ADAP_FATAL_ERR | ADAP_STOPPED);
2184 
2185 	/* Restore memory window. */
2186 	setup_memwin(sc);
2187 
2188 	/* Go no further if recovery mode has been requested. */
2189 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2190 		CH_ALERT(sc, "recovery mode on resume.\n");
2191 		rc = 0;
2192 		mtx_lock(&sc->reg_lock);
2193 		atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2194 		mtx_unlock(&sc->reg_lock);
2195 		goto done;
2196 	}
2197 
2198 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2199 	save_caps_and_params(sc, old_state);
2200 
2201 	/* Reestablish contact with firmware and become the primary PF. */
2202 	rc = contact_firmware(sc);
2203 	if (rc != 0)
2204 		goto done; /* error message displayed already */
2205 	MPASS(sc->flags & FW_OK);
2206 
2207 	if (sc->flags & MASTER_PF) {
2208 		rc = partition_resources(sc);
2209 		if (rc != 0)
2210 			goto done; /* error message displayed already */
2211 		t4_intr_clear(sc);
2212 	}
2213 
2214 	rc = get_params__post_init(sc);
2215 	if (rc != 0)
2216 		goto done; /* error message displayed already */
2217 
2218 	rc = set_params__post_init(sc);
2219 	if (rc != 0)
2220 		goto done; /* error message displayed already */
2221 
2222 	rc = compare_caps_and_params(sc, old_state);
2223 	if (rc != 0)
2224 		goto done; /* error message displayed already */
2225 
2226 	for_each_port(sc, i) {
2227 		pi = sc->port[i];
2228 		MPASS(pi != NULL);
2229 		MPASS(pi->vi != NULL);
2230 		MPASS(pi->vi[0].dev == pi->dev);
2231 
2232 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2233 		if (rc != 0) {
2234 			CH_ERR(sc,
2235 			    "failed to re-initialize port %d: %d\n", i, rc);
2236 			goto done;
2237 		}
2238 		MPASS(sc->chan_map[pi->tx_chan] == i);
2239 
2240 		PORT_LOCK(pi);
2241 		fixup_link_config(pi);
2242 		build_medialist(pi);
2243 		PORT_UNLOCK(pi);
2244 		for_each_vi(pi, j, vi) {
2245 			if (IS_MAIN_VI(vi))
2246 				continue;
2247 			rc = alloc_extra_vi(sc, pi, vi);
2248 			if (rc != 0) {
2249 				CH_ERR(vi,
2250 				    "failed to re-allocate extra VI: %d\n", rc);
2251 				goto done;
2252 			}
2253 		}
2254 	}
2255 
2256 	/*
2257 	 * Interrupts and queues are about to be enabled and other threads will
2258 	 * want to access the hardware too.  It is safe to do so.  Note that
2259 	 * this thread is still in the middle of a synchronized_op.
2260 	 */
2261 	mtx_lock(&sc->reg_lock);
2262 	atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2263 	mtx_unlock(&sc->reg_lock);
2264 
2265 	if (sc->flags & FULL_INIT_DONE) {
2266 		rc = adapter_full_init(sc);
2267 		if (rc != 0) {
2268 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2269 			goto done;
2270 		}
2271 
2272 		if (sc->vxlan_refcount > 0)
2273 			enable_vxlan_rx(sc);
2274 
2275 		for_each_port(sc, i) {
2276 			pi = sc->port[i];
2277 			for_each_vi(pi, j, vi) {
2278 				mtx_lock(&vi->tick_mtx);
2279 				vi->flags &= ~VI_SKIP_STATS;
2280 				mtx_unlock(&vi->tick_mtx);
2281 				if (!(vi->flags & VI_INIT_DONE))
2282 					continue;
2283 				rc = vi_full_init(vi);
2284 				if (rc != 0) {
2285 					CH_ERR(vi, "failed to re-initialize "
2286 					    "interface: %d\n", rc);
2287 					goto done;
2288 				}
2289 
2290 				ifp = vi->ifp;
2291 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2292 					continue;
2293 				/*
2294 				 * Note that we do not setup multicast addresses
2295 				 * in the first pass.  This ensures that the
2296 				 * unicast DMACs for all VIs on all ports get an
2297 				 * MPS TCAM entry.
2298 				 */
2299 				rc = update_mac_settings(ifp, XGMAC_ALL &
2300 				    ~XGMAC_MCADDRS);
2301 				if (rc != 0) {
2302 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2303 					goto done;
2304 				}
2305 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2306 				    true);
2307 				if (rc != 0) {
2308 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2309 					goto done;
2310 				}
2311 				for_each_txq(vi, k, txq) {
2312 					TXQ_LOCK(txq);
2313 					txq->eq.flags |= EQ_ENABLED;
2314 					TXQ_UNLOCK(txq);
2315 				}
2316 				mtx_lock(&vi->tick_mtx);
2317 				callout_schedule(&vi->tick, hz);
2318 				mtx_unlock(&vi->tick_mtx);
2319 			}
2320 			PORT_LOCK(pi);
2321 			if (pi->up_vis > 0) {
2322 				t4_update_port_info(pi);
2323 				fixup_link_config(pi);
2324 				build_medialist(pi);
2325 				apply_link_config(pi);
2326 				if (pi->link_cfg.link_ok)
2327 					t4_os_link_changed(pi);
2328 			}
2329 			PORT_UNLOCK(pi);
2330 		}
2331 
2332 		/* Now reprogram the L2 multicast addresses. */
2333 		for_each_port(sc, i) {
2334 			pi = sc->port[i];
2335 			for_each_vi(pi, j, vi) {
2336 				if (!(vi->flags & VI_INIT_DONE))
2337 					continue;
2338 				ifp = vi->ifp;
2339 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2340 					continue;
2341 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2342 				if (rc != 0) {
2343 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2344 					rc = 0;	/* carry on */
2345 				}
2346 			}
2347 		}
2348 	}
2349 done:
2350 	if (rc == 0) {
2351 		sc->incarnation++;
2352 		CH_ALERT(sc, "resume completed.\n");
2353 	}
2354 	end_synchronized_op(sc, 0);
2355 	free(old_state, M_CXGBE);
2356 	return (rc);
2357 }
2358 
2359 static int
2360 t4_reset_prepare(device_t dev, device_t child)
2361 {
2362 	struct adapter *sc = device_get_softc(dev);
2363 
2364 	CH_ALERT(sc, "reset_prepare.\n");
2365 	return (0);
2366 }
2367 
2368 static int
2369 t4_reset_post(device_t dev, device_t child)
2370 {
2371 	struct adapter *sc = device_get_softc(dev);
2372 
2373 	CH_ALERT(sc, "reset_post.\n");
2374 	return (0);
2375 }
2376 
2377 static int
2378 reset_adapter(struct adapter *sc)
2379 {
2380 	int rc, oldinc, error_flags;
2381 
2382 	CH_ALERT(sc, "reset requested.\n");
2383 
2384 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst1");
2385 	if (rc != 0)
2386 		return (EBUSY);
2387 
2388 	if (hw_off_limits(sc)) {
2389 		CH_ERR(sc, "adapter is suspended, use resume (not reset).\n");
2390 		rc = ENXIO;
2391 		goto done;
2392 	}
2393 
2394 	if (!ok_to_reset(sc)) {
2395 		/* XXX: should list what resource is preventing reset. */
2396 		CH_ERR(sc, "not safe to reset.\n");
2397 		rc = EBUSY;
2398 		goto done;
2399 	}
2400 
2401 done:
2402 	oldinc = sc->incarnation;
2403 	end_synchronized_op(sc, 0);
2404 	if (rc != 0)
2405 		return (rc);	/* Error logged already. */
2406 
2407 	atomic_add_int(&sc->num_resets, 1);
2408 	mtx_lock(&Giant);
2409 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2410 	mtx_unlock(&Giant);
2411 	if (rc != 0)
2412 		CH_ERR(sc, "bus_reset_child failed: %d.\n", rc);
2413 	else {
2414 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst2");
2415 		if (rc != 0)
2416 			return (EBUSY);
2417 		error_flags = atomic_load_int(&sc->error_flags);
2418 		if (sc->incarnation > oldinc && error_flags == 0) {
2419 			CH_ALERT(sc, "bus_reset_child succeeded.\n");
2420 		} else {
2421 			CH_ERR(sc, "adapter did not reset properly, flags "
2422 			    "0x%08x, error_flags 0x%08x.\n", sc->flags,
2423 			    error_flags);
2424 			rc = ENXIO;
2425 		}
2426 		end_synchronized_op(sc, 0);
2427 	}
2428 
2429 	return (rc);
2430 }
2431 
2432 static void
2433 reset_adapter_task(void *arg, int pending)
2434 {
2435 	/* XXX: t4_async_event here? */
2436 	reset_adapter(arg);
2437 }
2438 
2439 static int
2440 cxgbe_probe(device_t dev)
2441 {
2442 	char buf[128];
2443 	struct port_info *pi = device_get_softc(dev);
2444 
2445 	snprintf(buf, sizeof(buf), "port %d", pi->port_id);
2446 	device_set_desc_copy(dev, buf);
2447 
2448 	return (BUS_PROBE_DEFAULT);
2449 }
2450 
2451 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2452     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2453     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2454     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2455 #define T4_CAP_ENABLE (T4_CAP)
2456 
2457 static int
2458 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2459 {
2460 	struct ifnet *ifp;
2461 	struct sbuf *sb;
2462 	struct sysctl_ctx_list *ctx = &vi->ctx;
2463 	struct sysctl_oid_list *children;
2464 	struct pfil_head_args pa;
2465 	struct adapter *sc = vi->adapter;
2466 
2467 	sysctl_ctx_init(ctx);
2468 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2469 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2470 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2471 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2472 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2473 #ifdef DEV_NETMAP
2474 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2475 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2476 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2477 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2478 #endif
2479 #ifdef TCP_OFFLOAD
2480 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2481 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2482 #endif
2483 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2484 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2485 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2486 #endif
2487 
2488 	vi->xact_addr_filt = -1;
2489 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2490 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2491 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2492 		vi->flags |= TX_USES_VM_WR;
2493 
2494 	/* Allocate an ifnet and set it up */
2495 	ifp = if_alloc_dev(IFT_ETHER, dev);
2496 	if (ifp == NULL) {
2497 		device_printf(dev, "Cannot allocate ifnet\n");
2498 		return (ENOMEM);
2499 	}
2500 	vi->ifp = ifp;
2501 	ifp->if_softc = vi;
2502 
2503 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2504 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
2505 
2506 	ifp->if_init = cxgbe_init;
2507 	ifp->if_ioctl = cxgbe_ioctl;
2508 	ifp->if_transmit = cxgbe_transmit;
2509 	ifp->if_qflush = cxgbe_qflush;
2510 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2511 		ifp->if_get_counter = vi_get_counter;
2512 	else
2513 		ifp->if_get_counter = cxgbe_get_counter;
2514 #if defined(KERN_TLS) || defined(RATELIMIT)
2515 	ifp->if_snd_tag_alloc = cxgbe_snd_tag_alloc;
2516 #endif
2517 #ifdef RATELIMIT
2518 	ifp->if_ratelimit_query = cxgbe_ratelimit_query;
2519 #endif
2520 
2521 	ifp->if_capabilities = T4_CAP;
2522 	ifp->if_capenable = T4_CAP_ENABLE;
2523 	ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2524 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6;
2525 	if (chip_id(sc) >= CHELSIO_T6) {
2526 		ifp->if_capabilities |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2527 		ifp->if_capenable |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2528 		ifp->if_hwassist |= CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2529 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2530 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN;
2531 	}
2532 
2533 #ifdef TCP_OFFLOAD
2534 	if (vi->nofldrxq != 0)
2535 		ifp->if_capabilities |= IFCAP_TOE;
2536 #endif
2537 #ifdef RATELIMIT
2538 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2539 		ifp->if_capabilities |= IFCAP_TXRTLMT;
2540 		ifp->if_capenable |= IFCAP_TXRTLMT;
2541 	}
2542 #endif
2543 
2544 	ifp->if_hw_tsomax = IP_MAXPACKET;
2545 	if (vi->flags & TX_USES_VM_WR)
2546 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
2547 	else
2548 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
2549 #ifdef RATELIMIT
2550 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2551 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_EO_TSO;
2552 #endif
2553 	ifp->if_hw_tsomaxsegsize = 65536;
2554 #ifdef KERN_TLS
2555 	if (is_ktls(sc)) {
2556 		ifp->if_capabilities |= IFCAP_TXTLS;
2557 		if (sc->flags & KERN_TLS_ON)
2558 			ifp->if_capenable |= IFCAP_TXTLS;
2559 	}
2560 #endif
2561 
2562 	ether_ifattach(ifp, vi->hw_addr);
2563 #ifdef DEV_NETMAP
2564 	if (vi->nnmrxq != 0)
2565 		cxgbe_nm_attach(vi);
2566 #endif
2567 	sb = sbuf_new_auto();
2568 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2569 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2570 	switch (ifp->if_capabilities & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2571 	case IFCAP_TOE:
2572 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2573 		break;
2574 	case IFCAP_TOE | IFCAP_TXRTLMT:
2575 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2576 		break;
2577 	case IFCAP_TXRTLMT:
2578 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2579 		break;
2580 	}
2581 #endif
2582 #ifdef TCP_OFFLOAD
2583 	if (ifp->if_capabilities & IFCAP_TOE)
2584 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2585 #endif
2586 #ifdef DEV_NETMAP
2587 	if (ifp->if_capabilities & IFCAP_NETMAP)
2588 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2589 		    vi->nnmtxq, vi->nnmrxq);
2590 #endif
2591 	sbuf_finish(sb);
2592 	device_printf(dev, "%s\n", sbuf_data(sb));
2593 	sbuf_delete(sb);
2594 
2595 	vi_sysctls(vi);
2596 
2597 	pa.pa_version = PFIL_VERSION;
2598 	pa.pa_flags = PFIL_IN;
2599 	pa.pa_type = PFIL_TYPE_ETHERNET;
2600 	pa.pa_headname = ifp->if_xname;
2601 	vi->pfil = pfil_head_register(&pa);
2602 
2603 	return (0);
2604 }
2605 
2606 static int
2607 cxgbe_attach(device_t dev)
2608 {
2609 	struct port_info *pi = device_get_softc(dev);
2610 	struct adapter *sc = pi->adapter;
2611 	struct vi_info *vi;
2612 	int i, rc;
2613 
2614 	sysctl_ctx_init(&pi->ctx);
2615 
2616 	rc = cxgbe_vi_attach(dev, &pi->vi[0]);
2617 	if (rc)
2618 		return (rc);
2619 
2620 	for_each_vi(pi, i, vi) {
2621 		if (i == 0)
2622 			continue;
2623 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
2624 		if (vi->dev == NULL) {
2625 			device_printf(dev, "failed to add VI %d\n", i);
2626 			continue;
2627 		}
2628 		device_set_softc(vi->dev, vi);
2629 	}
2630 
2631 	cxgbe_sysctls(pi);
2632 
2633 	bus_generic_attach(dev);
2634 
2635 	return (0);
2636 }
2637 
2638 static void
2639 cxgbe_vi_detach(struct vi_info *vi)
2640 {
2641 	struct ifnet *ifp = vi->ifp;
2642 
2643 	if (vi->pfil != NULL) {
2644 		pfil_head_unregister(vi->pfil);
2645 		vi->pfil = NULL;
2646 	}
2647 
2648 	ether_ifdetach(ifp);
2649 
2650 	/* Let detach proceed even if these fail. */
2651 #ifdef DEV_NETMAP
2652 	if (ifp->if_capabilities & IFCAP_NETMAP)
2653 		cxgbe_nm_detach(vi);
2654 #endif
2655 	cxgbe_uninit_synchronized(vi);
2656 	callout_drain(&vi->tick);
2657 	sysctl_ctx_free(&vi->ctx);
2658 	vi_full_uninit(vi);
2659 
2660 	if_free(vi->ifp);
2661 	vi->ifp = NULL;
2662 }
2663 
2664 static int
2665 cxgbe_detach(device_t dev)
2666 {
2667 	struct port_info *pi = device_get_softc(dev);
2668 	struct adapter *sc = pi->adapter;
2669 	int rc;
2670 
2671 	/* Detach the extra VIs first. */
2672 	rc = bus_generic_detach(dev);
2673 	if (rc)
2674 		return (rc);
2675 	device_delete_children(dev);
2676 
2677 	sysctl_ctx_free(&pi->ctx);
2678 	doom_vi(sc, &pi->vi[0]);
2679 
2680 	if (pi->flags & HAS_TRACEQ) {
2681 		sc->traceq = -1;	/* cloner should not create ifnet */
2682 		t4_tracer_port_detach(sc);
2683 	}
2684 
2685 	cxgbe_vi_detach(&pi->vi[0]);
2686 	ifmedia_removeall(&pi->media);
2687 
2688 	end_synchronized_op(sc, 0);
2689 
2690 	return (0);
2691 }
2692 
2693 static void
2694 cxgbe_init(void *arg)
2695 {
2696 	struct vi_info *vi = arg;
2697 	struct adapter *sc = vi->adapter;
2698 
2699 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2700 		return;
2701 	cxgbe_init_synchronized(vi);
2702 	end_synchronized_op(sc, 0);
2703 }
2704 
2705 static int
2706 cxgbe_ioctl(struct ifnet *ifp, unsigned long cmd, caddr_t data)
2707 {
2708 	int rc = 0, mtu, flags;
2709 	struct vi_info *vi = ifp->if_softc;
2710 	struct port_info *pi = vi->pi;
2711 	struct adapter *sc = pi->adapter;
2712 	struct ifreq *ifr = (struct ifreq *)data;
2713 	uint32_t mask;
2714 
2715 	switch (cmd) {
2716 	case SIOCSIFMTU:
2717 		mtu = ifr->ifr_mtu;
2718 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2719 			return (EINVAL);
2720 
2721 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2722 		if (rc)
2723 			return (rc);
2724 		ifp->if_mtu = mtu;
2725 		if (vi->flags & VI_INIT_DONE) {
2726 			t4_update_fl_bufsize(ifp);
2727 			if (!hw_off_limits(sc) &&
2728 			    ifp->if_drv_flags & IFF_DRV_RUNNING)
2729 				rc = update_mac_settings(ifp, XGMAC_MTU);
2730 		}
2731 		end_synchronized_op(sc, 0);
2732 		break;
2733 
2734 	case SIOCSIFFLAGS:
2735 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2736 		if (rc)
2737 			return (rc);
2738 
2739 		if (hw_off_limits(sc)) {
2740 			rc = ENXIO;
2741 			goto fail;
2742 		}
2743 
2744 		if (ifp->if_flags & IFF_UP) {
2745 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2746 				flags = vi->if_flags;
2747 				if ((ifp->if_flags ^ flags) &
2748 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2749 					rc = update_mac_settings(ifp,
2750 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2751 				}
2752 			} else {
2753 				rc = cxgbe_init_synchronized(vi);
2754 			}
2755 			vi->if_flags = ifp->if_flags;
2756 		} else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2757 			rc = cxgbe_uninit_synchronized(vi);
2758 		}
2759 		end_synchronized_op(sc, 0);
2760 		break;
2761 
2762 	case SIOCADDMULTI:
2763 	case SIOCDELMULTI:
2764 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2765 		if (rc)
2766 			return (rc);
2767 		if (!hw_off_limits(sc) && ifp->if_drv_flags & IFF_DRV_RUNNING)
2768 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2769 		end_synchronized_op(sc, 0);
2770 		break;
2771 
2772 	case SIOCSIFCAP:
2773 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2774 		if (rc)
2775 			return (rc);
2776 
2777 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
2778 		if (mask & IFCAP_TXCSUM) {
2779 			ifp->if_capenable ^= IFCAP_TXCSUM;
2780 			ifp->if_hwassist ^= (CSUM_TCP | CSUM_UDP | CSUM_IP);
2781 
2782 			if (IFCAP_TSO4 & ifp->if_capenable &&
2783 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2784 				mask &= ~IFCAP_TSO4;
2785 				ifp->if_capenable &= ~IFCAP_TSO4;
2786 				if_printf(ifp,
2787 				    "tso4 disabled due to -txcsum.\n");
2788 			}
2789 		}
2790 		if (mask & IFCAP_TXCSUM_IPV6) {
2791 			ifp->if_capenable ^= IFCAP_TXCSUM_IPV6;
2792 			ifp->if_hwassist ^= (CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2793 
2794 			if (IFCAP_TSO6 & ifp->if_capenable &&
2795 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2796 				mask &= ~IFCAP_TSO6;
2797 				ifp->if_capenable &= ~IFCAP_TSO6;
2798 				if_printf(ifp,
2799 				    "tso6 disabled due to -txcsum6.\n");
2800 			}
2801 		}
2802 		if (mask & IFCAP_RXCSUM)
2803 			ifp->if_capenable ^= IFCAP_RXCSUM;
2804 		if (mask & IFCAP_RXCSUM_IPV6)
2805 			ifp->if_capenable ^= IFCAP_RXCSUM_IPV6;
2806 
2807 		/*
2808 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2809 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2810 		 * sending a TSO request our way, so it's sufficient to toggle
2811 		 * IFCAP_TSOx only.
2812 		 */
2813 		if (mask & IFCAP_TSO4) {
2814 			if (!(IFCAP_TSO4 & ifp->if_capenable) &&
2815 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2816 				if_printf(ifp, "enable txcsum first.\n");
2817 				rc = EAGAIN;
2818 				goto fail;
2819 			}
2820 			ifp->if_capenable ^= IFCAP_TSO4;
2821 		}
2822 		if (mask & IFCAP_TSO6) {
2823 			if (!(IFCAP_TSO6 & ifp->if_capenable) &&
2824 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2825 				if_printf(ifp, "enable txcsum6 first.\n");
2826 				rc = EAGAIN;
2827 				goto fail;
2828 			}
2829 			ifp->if_capenable ^= IFCAP_TSO6;
2830 		}
2831 		if (mask & IFCAP_LRO) {
2832 #if defined(INET) || defined(INET6)
2833 			int i;
2834 			struct sge_rxq *rxq;
2835 
2836 			ifp->if_capenable ^= IFCAP_LRO;
2837 			for_each_rxq(vi, i, rxq) {
2838 				if (ifp->if_capenable & IFCAP_LRO)
2839 					rxq->iq.flags |= IQ_LRO_ENABLED;
2840 				else
2841 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2842 			}
2843 #endif
2844 		}
2845 #ifdef TCP_OFFLOAD
2846 		if (mask & IFCAP_TOE) {
2847 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TOE;
2848 
2849 			rc = toe_capability(vi, enable);
2850 			if (rc != 0)
2851 				goto fail;
2852 
2853 			ifp->if_capenable ^= mask;
2854 		}
2855 #endif
2856 		if (mask & IFCAP_VLAN_HWTAGGING) {
2857 			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
2858 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2859 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2860 		}
2861 		if (mask & IFCAP_VLAN_MTU) {
2862 			ifp->if_capenable ^= IFCAP_VLAN_MTU;
2863 
2864 			/* Need to find out how to disable auto-mtu-inflation */
2865 		}
2866 		if (mask & IFCAP_VLAN_HWTSO)
2867 			ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
2868 		if (mask & IFCAP_VLAN_HWCSUM)
2869 			ifp->if_capenable ^= IFCAP_VLAN_HWCSUM;
2870 #ifdef RATELIMIT
2871 		if (mask & IFCAP_TXRTLMT)
2872 			ifp->if_capenable ^= IFCAP_TXRTLMT;
2873 #endif
2874 		if (mask & IFCAP_HWRXTSTMP) {
2875 			int i;
2876 			struct sge_rxq *rxq;
2877 
2878 			ifp->if_capenable ^= IFCAP_HWRXTSTMP;
2879 			for_each_rxq(vi, i, rxq) {
2880 				if (ifp->if_capenable & IFCAP_HWRXTSTMP)
2881 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2882 				else
2883 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2884 			}
2885 		}
2886 		if (mask & IFCAP_MEXTPG)
2887 			ifp->if_capenable ^= IFCAP_MEXTPG;
2888 
2889 #ifdef KERN_TLS
2890 		if (mask & IFCAP_TXTLS) {
2891 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TXTLS;
2892 
2893 			rc = ktls_capability(sc, enable);
2894 			if (rc != 0)
2895 				goto fail;
2896 
2897 			ifp->if_capenable ^= (mask & IFCAP_TXTLS);
2898 		}
2899 #endif
2900 		if (mask & IFCAP_VXLAN_HWCSUM) {
2901 			ifp->if_capenable ^= IFCAP_VXLAN_HWCSUM;
2902 			ifp->if_hwassist ^= CSUM_INNER_IP6_UDP |
2903 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
2904 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP;
2905 		}
2906 		if (mask & IFCAP_VXLAN_HWTSO) {
2907 			ifp->if_capenable ^= IFCAP_VXLAN_HWTSO;
2908 			ifp->if_hwassist ^= CSUM_INNER_IP6_TSO |
2909 			    CSUM_INNER_IP_TSO;
2910 		}
2911 
2912 #ifdef VLAN_CAPABILITIES
2913 		VLAN_CAPABILITIES(ifp);
2914 #endif
2915 fail:
2916 		end_synchronized_op(sc, 0);
2917 		break;
2918 
2919 	case SIOCSIFMEDIA:
2920 	case SIOCGIFMEDIA:
2921 	case SIOCGIFXMEDIA:
2922 		rc = ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
2923 		break;
2924 
2925 	case SIOCGI2C: {
2926 		struct ifi2creq i2c;
2927 
2928 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
2929 		if (rc != 0)
2930 			break;
2931 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
2932 			rc = EPERM;
2933 			break;
2934 		}
2935 		if (i2c.len > sizeof(i2c.data)) {
2936 			rc = EINVAL;
2937 			break;
2938 		}
2939 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
2940 		if (rc)
2941 			return (rc);
2942 		if (hw_off_limits(sc))
2943 			rc = ENXIO;
2944 		else
2945 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
2946 			    i2c.offset, i2c.len, &i2c.data[0]);
2947 		end_synchronized_op(sc, 0);
2948 		if (rc == 0)
2949 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
2950 		break;
2951 	}
2952 
2953 	default:
2954 		rc = ether_ioctl(ifp, cmd, data);
2955 	}
2956 
2957 	return (rc);
2958 }
2959 
2960 static int
2961 cxgbe_transmit(struct ifnet *ifp, struct mbuf *m)
2962 {
2963 	struct vi_info *vi = ifp->if_softc;
2964 	struct port_info *pi = vi->pi;
2965 	struct adapter *sc;
2966 	struct sge_txq *txq;
2967 	void *items[1];
2968 	int rc;
2969 
2970 	M_ASSERTPKTHDR(m);
2971 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
2972 #if defined(KERN_TLS) || defined(RATELIMIT)
2973 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
2974 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
2975 #endif
2976 
2977 	if (__predict_false(pi->link_cfg.link_ok == false)) {
2978 		m_freem(m);
2979 		return (ENETDOWN);
2980 	}
2981 
2982 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
2983 	if (__predict_false(rc != 0)) {
2984 		MPASS(m == NULL);			/* was freed already */
2985 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
2986 		return (rc);
2987 	}
2988 #ifdef RATELIMIT
2989 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG) {
2990 		if (m->m_pkthdr.snd_tag->sw->type == IF_SND_TAG_TYPE_RATE_LIMIT)
2991 			return (ethofld_transmit(ifp, m));
2992 	}
2993 #endif
2994 
2995 	/* Select a txq. */
2996 	sc = vi->adapter;
2997 	txq = &sc->sge.txq[vi->first_txq];
2998 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
2999 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
3000 		    vi->rsrv_noflowq);
3001 
3002 	items[0] = m;
3003 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
3004 	if (__predict_false(rc != 0))
3005 		m_freem(m);
3006 
3007 	return (rc);
3008 }
3009 
3010 static void
3011 cxgbe_qflush(struct ifnet *ifp)
3012 {
3013 	struct vi_info *vi = ifp->if_softc;
3014 	struct sge_txq *txq;
3015 	int i;
3016 
3017 	/* queues do not exist if !VI_INIT_DONE. */
3018 	if (vi->flags & VI_INIT_DONE) {
3019 		for_each_txq(vi, i, txq) {
3020 			TXQ_LOCK(txq);
3021 			txq->eq.flags |= EQ_QFLUSH;
3022 			TXQ_UNLOCK(txq);
3023 			while (!mp_ring_is_idle(txq->r)) {
3024 				mp_ring_check_drainage(txq->r, 4096);
3025 				pause("qflush", 1);
3026 			}
3027 			TXQ_LOCK(txq);
3028 			txq->eq.flags &= ~EQ_QFLUSH;
3029 			TXQ_UNLOCK(txq);
3030 		}
3031 	}
3032 	if_qflush(ifp);
3033 }
3034 
3035 static uint64_t
3036 vi_get_counter(struct ifnet *ifp, ift_counter c)
3037 {
3038 	struct vi_info *vi = ifp->if_softc;
3039 	struct fw_vi_stats_vf *s = &vi->stats;
3040 
3041 	mtx_lock(&vi->tick_mtx);
3042 	vi_refresh_stats(vi);
3043 	mtx_unlock(&vi->tick_mtx);
3044 
3045 	switch (c) {
3046 	case IFCOUNTER_IPACKETS:
3047 		return (s->rx_bcast_frames + s->rx_mcast_frames +
3048 		    s->rx_ucast_frames);
3049 	case IFCOUNTER_IERRORS:
3050 		return (s->rx_err_frames);
3051 	case IFCOUNTER_OPACKETS:
3052 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3053 		    s->tx_ucast_frames + s->tx_offload_frames);
3054 	case IFCOUNTER_OERRORS:
3055 		return (s->tx_drop_frames);
3056 	case IFCOUNTER_IBYTES:
3057 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3058 		    s->rx_ucast_bytes);
3059 	case IFCOUNTER_OBYTES:
3060 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3061 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3062 	case IFCOUNTER_IMCASTS:
3063 		return (s->rx_mcast_frames);
3064 	case IFCOUNTER_OMCASTS:
3065 		return (s->tx_mcast_frames);
3066 	case IFCOUNTER_OQDROPS: {
3067 		uint64_t drops;
3068 
3069 		drops = 0;
3070 		if (vi->flags & VI_INIT_DONE) {
3071 			int i;
3072 			struct sge_txq *txq;
3073 
3074 			for_each_txq(vi, i, txq)
3075 				drops += counter_u64_fetch(txq->r->dropped);
3076 		}
3077 
3078 		return (drops);
3079 
3080 	}
3081 
3082 	default:
3083 		return (if_get_counter_default(ifp, c));
3084 	}
3085 }
3086 
3087 static uint64_t
3088 cxgbe_get_counter(struct ifnet *ifp, ift_counter c)
3089 {
3090 	struct vi_info *vi = ifp->if_softc;
3091 	struct port_info *pi = vi->pi;
3092 	struct port_stats *s = &pi->stats;
3093 
3094 	mtx_lock(&vi->tick_mtx);
3095 	cxgbe_refresh_stats(vi);
3096 	mtx_unlock(&vi->tick_mtx);
3097 
3098 	switch (c) {
3099 	case IFCOUNTER_IPACKETS:
3100 		return (s->rx_frames);
3101 
3102 	case IFCOUNTER_IERRORS:
3103 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3104 		    s->rx_fcs_err + s->rx_len_err);
3105 
3106 	case IFCOUNTER_OPACKETS:
3107 		return (s->tx_frames);
3108 
3109 	case IFCOUNTER_OERRORS:
3110 		return (s->tx_error_frames);
3111 
3112 	case IFCOUNTER_IBYTES:
3113 		return (s->rx_octets);
3114 
3115 	case IFCOUNTER_OBYTES:
3116 		return (s->tx_octets);
3117 
3118 	case IFCOUNTER_IMCASTS:
3119 		return (s->rx_mcast_frames);
3120 
3121 	case IFCOUNTER_OMCASTS:
3122 		return (s->tx_mcast_frames);
3123 
3124 	case IFCOUNTER_IQDROPS:
3125 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3126 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3127 		    s->rx_trunc3 + pi->tnl_cong_drops);
3128 
3129 	case IFCOUNTER_OQDROPS: {
3130 		uint64_t drops;
3131 
3132 		drops = s->tx_drop;
3133 		if (vi->flags & VI_INIT_DONE) {
3134 			int i;
3135 			struct sge_txq *txq;
3136 
3137 			for_each_txq(vi, i, txq)
3138 				drops += counter_u64_fetch(txq->r->dropped);
3139 		}
3140 
3141 		return (drops);
3142 
3143 	}
3144 
3145 	default:
3146 		return (if_get_counter_default(ifp, c));
3147 	}
3148 }
3149 
3150 #if defined(KERN_TLS) || defined(RATELIMIT)
3151 static int
3152 cxgbe_snd_tag_alloc(struct ifnet *ifp, union if_snd_tag_alloc_params *params,
3153     struct m_snd_tag **pt)
3154 {
3155 	int error;
3156 
3157 	switch (params->hdr.type) {
3158 #ifdef RATELIMIT
3159 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3160 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3161 		break;
3162 #endif
3163 #ifdef KERN_TLS
3164 	case IF_SND_TAG_TYPE_TLS:
3165 		error = cxgbe_tls_tag_alloc(ifp, params, pt);
3166 		break;
3167 #endif
3168 	default:
3169 		error = EOPNOTSUPP;
3170 	}
3171 	return (error);
3172 }
3173 #endif
3174 
3175 /*
3176  * The kernel picks a media from the list we had provided but we still validate
3177  * the requeste.
3178  */
3179 int
3180 cxgbe_media_change(struct ifnet *ifp)
3181 {
3182 	struct vi_info *vi = ifp->if_softc;
3183 	struct port_info *pi = vi->pi;
3184 	struct ifmedia *ifm = &pi->media;
3185 	struct link_config *lc = &pi->link_cfg;
3186 	struct adapter *sc = pi->adapter;
3187 	int rc;
3188 
3189 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3190 	if (rc != 0)
3191 		return (rc);
3192 	PORT_LOCK(pi);
3193 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3194 		/* ifconfig .. media autoselect */
3195 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3196 			rc = ENOTSUP; /* AN not supported by transceiver */
3197 			goto done;
3198 		}
3199 		lc->requested_aneg = AUTONEG_ENABLE;
3200 		lc->requested_speed = 0;
3201 		lc->requested_fc |= PAUSE_AUTONEG;
3202 	} else {
3203 		lc->requested_aneg = AUTONEG_DISABLE;
3204 		lc->requested_speed =
3205 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3206 		lc->requested_fc = 0;
3207 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3208 			lc->requested_fc |= PAUSE_RX;
3209 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3210 			lc->requested_fc |= PAUSE_TX;
3211 	}
3212 	if (pi->up_vis > 0 && !hw_off_limits(sc)) {
3213 		fixup_link_config(pi);
3214 		rc = apply_link_config(pi);
3215 	}
3216 done:
3217 	PORT_UNLOCK(pi);
3218 	end_synchronized_op(sc, 0);
3219 	return (rc);
3220 }
3221 
3222 /*
3223  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3224  * given speed.
3225  */
3226 static int
3227 port_mword(struct port_info *pi, uint32_t speed)
3228 {
3229 
3230 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3231 	MPASS(powerof2(speed));
3232 
3233 	switch(pi->port_type) {
3234 	case FW_PORT_TYPE_BT_SGMII:
3235 	case FW_PORT_TYPE_BT_XFI:
3236 	case FW_PORT_TYPE_BT_XAUI:
3237 		/* BaseT */
3238 		switch (speed) {
3239 		case FW_PORT_CAP32_SPEED_100M:
3240 			return (IFM_100_T);
3241 		case FW_PORT_CAP32_SPEED_1G:
3242 			return (IFM_1000_T);
3243 		case FW_PORT_CAP32_SPEED_10G:
3244 			return (IFM_10G_T);
3245 		}
3246 		break;
3247 	case FW_PORT_TYPE_KX4:
3248 		if (speed == FW_PORT_CAP32_SPEED_10G)
3249 			return (IFM_10G_KX4);
3250 		break;
3251 	case FW_PORT_TYPE_CX4:
3252 		if (speed == FW_PORT_CAP32_SPEED_10G)
3253 			return (IFM_10G_CX4);
3254 		break;
3255 	case FW_PORT_TYPE_KX:
3256 		if (speed == FW_PORT_CAP32_SPEED_1G)
3257 			return (IFM_1000_KX);
3258 		break;
3259 	case FW_PORT_TYPE_KR:
3260 	case FW_PORT_TYPE_BP_AP:
3261 	case FW_PORT_TYPE_BP4_AP:
3262 	case FW_PORT_TYPE_BP40_BA:
3263 	case FW_PORT_TYPE_KR4_100G:
3264 	case FW_PORT_TYPE_KR_SFP28:
3265 	case FW_PORT_TYPE_KR_XLAUI:
3266 		switch (speed) {
3267 		case FW_PORT_CAP32_SPEED_1G:
3268 			return (IFM_1000_KX);
3269 		case FW_PORT_CAP32_SPEED_10G:
3270 			return (IFM_10G_KR);
3271 		case FW_PORT_CAP32_SPEED_25G:
3272 			return (IFM_25G_KR);
3273 		case FW_PORT_CAP32_SPEED_40G:
3274 			return (IFM_40G_KR4);
3275 		case FW_PORT_CAP32_SPEED_50G:
3276 			return (IFM_50G_KR2);
3277 		case FW_PORT_CAP32_SPEED_100G:
3278 			return (IFM_100G_KR4);
3279 		}
3280 		break;
3281 	case FW_PORT_TYPE_FIBER_XFI:
3282 	case FW_PORT_TYPE_FIBER_XAUI:
3283 	case FW_PORT_TYPE_SFP:
3284 	case FW_PORT_TYPE_QSFP_10G:
3285 	case FW_PORT_TYPE_QSA:
3286 	case FW_PORT_TYPE_QSFP:
3287 	case FW_PORT_TYPE_CR4_QSFP:
3288 	case FW_PORT_TYPE_CR_QSFP:
3289 	case FW_PORT_TYPE_CR2_QSFP:
3290 	case FW_PORT_TYPE_SFP28:
3291 		/* Pluggable transceiver */
3292 		switch (pi->mod_type) {
3293 		case FW_PORT_MOD_TYPE_LR:
3294 			switch (speed) {
3295 			case FW_PORT_CAP32_SPEED_1G:
3296 				return (IFM_1000_LX);
3297 			case FW_PORT_CAP32_SPEED_10G:
3298 				return (IFM_10G_LR);
3299 			case FW_PORT_CAP32_SPEED_25G:
3300 				return (IFM_25G_LR);
3301 			case FW_PORT_CAP32_SPEED_40G:
3302 				return (IFM_40G_LR4);
3303 			case FW_PORT_CAP32_SPEED_50G:
3304 				return (IFM_50G_LR2);
3305 			case FW_PORT_CAP32_SPEED_100G:
3306 				return (IFM_100G_LR4);
3307 			}
3308 			break;
3309 		case FW_PORT_MOD_TYPE_SR:
3310 			switch (speed) {
3311 			case FW_PORT_CAP32_SPEED_1G:
3312 				return (IFM_1000_SX);
3313 			case FW_PORT_CAP32_SPEED_10G:
3314 				return (IFM_10G_SR);
3315 			case FW_PORT_CAP32_SPEED_25G:
3316 				return (IFM_25G_SR);
3317 			case FW_PORT_CAP32_SPEED_40G:
3318 				return (IFM_40G_SR4);
3319 			case FW_PORT_CAP32_SPEED_50G:
3320 				return (IFM_50G_SR2);
3321 			case FW_PORT_CAP32_SPEED_100G:
3322 				return (IFM_100G_SR4);
3323 			}
3324 			break;
3325 		case FW_PORT_MOD_TYPE_ER:
3326 			if (speed == FW_PORT_CAP32_SPEED_10G)
3327 				return (IFM_10G_ER);
3328 			break;
3329 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3330 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3331 			switch (speed) {
3332 			case FW_PORT_CAP32_SPEED_1G:
3333 				return (IFM_1000_CX);
3334 			case FW_PORT_CAP32_SPEED_10G:
3335 				return (IFM_10G_TWINAX);
3336 			case FW_PORT_CAP32_SPEED_25G:
3337 				return (IFM_25G_CR);
3338 			case FW_PORT_CAP32_SPEED_40G:
3339 				return (IFM_40G_CR4);
3340 			case FW_PORT_CAP32_SPEED_50G:
3341 				return (IFM_50G_CR2);
3342 			case FW_PORT_CAP32_SPEED_100G:
3343 				return (IFM_100G_CR4);
3344 			}
3345 			break;
3346 		case FW_PORT_MOD_TYPE_LRM:
3347 			if (speed == FW_PORT_CAP32_SPEED_10G)
3348 				return (IFM_10G_LRM);
3349 			break;
3350 		case FW_PORT_MOD_TYPE_NA:
3351 			MPASS(0);	/* Not pluggable? */
3352 			/* fall throough */
3353 		case FW_PORT_MOD_TYPE_ERROR:
3354 		case FW_PORT_MOD_TYPE_UNKNOWN:
3355 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3356 			break;
3357 		case FW_PORT_MOD_TYPE_NONE:
3358 			return (IFM_NONE);
3359 		}
3360 		break;
3361 	case FW_PORT_TYPE_NONE:
3362 		return (IFM_NONE);
3363 	}
3364 
3365 	return (IFM_UNKNOWN);
3366 }
3367 
3368 void
3369 cxgbe_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
3370 {
3371 	struct vi_info *vi = ifp->if_softc;
3372 	struct port_info *pi = vi->pi;
3373 	struct adapter *sc = pi->adapter;
3374 	struct link_config *lc = &pi->link_cfg;
3375 
3376 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4med") != 0)
3377 		return;
3378 	PORT_LOCK(pi);
3379 
3380 	if (pi->up_vis == 0 && !hw_off_limits(sc)) {
3381 		/*
3382 		 * If all the interfaces are administratively down the firmware
3383 		 * does not report transceiver changes.  Refresh port info here
3384 		 * so that ifconfig displays accurate ifmedia at all times.
3385 		 * This is the only reason we have a synchronized op in this
3386 		 * function.  Just PORT_LOCK would have been enough otherwise.
3387 		 */
3388 		t4_update_port_info(pi);
3389 		build_medialist(pi);
3390 	}
3391 
3392 	/* ifm_status */
3393 	ifmr->ifm_status = IFM_AVALID;
3394 	if (lc->link_ok == false)
3395 		goto done;
3396 	ifmr->ifm_status |= IFM_ACTIVE;
3397 
3398 	/* ifm_active */
3399 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3400 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3401 	if (lc->fc & PAUSE_RX)
3402 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3403 	if (lc->fc & PAUSE_TX)
3404 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3405 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3406 done:
3407 	PORT_UNLOCK(pi);
3408 	end_synchronized_op(sc, 0);
3409 }
3410 
3411 static int
3412 vcxgbe_probe(device_t dev)
3413 {
3414 	char buf[128];
3415 	struct vi_info *vi = device_get_softc(dev);
3416 
3417 	snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
3418 	    vi - vi->pi->vi);
3419 	device_set_desc_copy(dev, buf);
3420 
3421 	return (BUS_PROBE_DEFAULT);
3422 }
3423 
3424 static int
3425 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3426 {
3427 	int func, index, rc;
3428 	uint32_t param, val;
3429 
3430 	ASSERT_SYNCHRONIZED_OP(sc);
3431 
3432 	index = vi - pi->vi;
3433 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3434 	KASSERT(index < nitems(vi_mac_funcs),
3435 	    ("%s: VI %s doesn't have a MAC func", __func__,
3436 	    device_get_nameunit(vi->dev)));
3437 	func = vi_mac_funcs[index];
3438 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3439 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3440 	if (rc < 0) {
3441 		CH_ERR(vi, "failed to allocate virtual interface %d"
3442 		    "for port %d: %d\n", index, pi->port_id, -rc);
3443 		return (-rc);
3444 	}
3445 	vi->viid = rc;
3446 
3447 	if (vi->rss_size == 1) {
3448 		/*
3449 		 * This VI didn't get a slice of the RSS table.  Reduce the
3450 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3451 		 * configuration file (nvi, rssnvi for this PF) if this is a
3452 		 * problem.
3453 		 */
3454 		device_printf(vi->dev, "RSS table not available.\n");
3455 		vi->rss_base = 0xffff;
3456 
3457 		return (0);
3458 	}
3459 
3460 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3461 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3462 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3463 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3464 	if (rc)
3465 		vi->rss_base = 0xffff;
3466 	else {
3467 		MPASS((val >> 16) == vi->rss_size);
3468 		vi->rss_base = val & 0xffff;
3469 	}
3470 
3471 	return (0);
3472 }
3473 
3474 static int
3475 vcxgbe_attach(device_t dev)
3476 {
3477 	struct vi_info *vi;
3478 	struct port_info *pi;
3479 	struct adapter *sc;
3480 	int rc;
3481 
3482 	vi = device_get_softc(dev);
3483 	pi = vi->pi;
3484 	sc = pi->adapter;
3485 
3486 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3487 	if (rc)
3488 		return (rc);
3489 	rc = alloc_extra_vi(sc, pi, vi);
3490 	end_synchronized_op(sc, 0);
3491 	if (rc)
3492 		return (rc);
3493 
3494 	rc = cxgbe_vi_attach(dev, vi);
3495 	if (rc) {
3496 		t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3497 		return (rc);
3498 	}
3499 	return (0);
3500 }
3501 
3502 static int
3503 vcxgbe_detach(device_t dev)
3504 {
3505 	struct vi_info *vi;
3506 	struct adapter *sc;
3507 
3508 	vi = device_get_softc(dev);
3509 	sc = vi->adapter;
3510 
3511 	doom_vi(sc, vi);
3512 
3513 	cxgbe_vi_detach(vi);
3514 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3515 
3516 	end_synchronized_op(sc, 0);
3517 
3518 	return (0);
3519 }
3520 
3521 static struct callout fatal_callout;
3522 static struct taskqueue *reset_tq;
3523 
3524 static void
3525 delayed_panic(void *arg)
3526 {
3527 	struct adapter *sc = arg;
3528 
3529 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3530 }
3531 
3532 static void
3533 fatal_error_task(void *arg, int pending)
3534 {
3535 	struct adapter *sc = arg;
3536 	int rc;
3537 
3538 #ifdef TCP_OFFLOAD
3539 	t4_async_event(sc);
3540 #endif
3541 	if (atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_CIM_ERR))) {
3542 		dump_cim_regs(sc);
3543 		dump_cimla(sc);
3544 		dump_devlog(sc);
3545 	}
3546 
3547 	if (t4_reset_on_fatal_err) {
3548 		CH_ALERT(sc, "resetting on fatal error.\n");
3549 		rc = reset_adapter(sc);
3550 		if (rc == 0 && t4_panic_on_fatal_err) {
3551 			CH_ALERT(sc, "reset was successful, "
3552 			    "system will NOT panic.\n");
3553 			return;
3554 		}
3555 	}
3556 
3557 	if (t4_panic_on_fatal_err) {
3558 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3559 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3560 	}
3561 }
3562 
3563 void
3564 t4_fatal_err(struct adapter *sc, bool fw_error)
3565 {
3566 	const bool verbose = (sc->debug_flags & DF_VERBOSE_SLOWINTR) != 0;
3567 
3568 	stop_adapter(sc);
3569 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_FATAL_ERR)))
3570 		return;
3571 	if (fw_error) {
3572 		/*
3573 		 * We are here because of a firmware error/timeout and not
3574 		 * because of a hardware interrupt.  It is possible (although
3575 		 * not very likely) that an error interrupt was also raised but
3576 		 * this thread ran first and inhibited t4_intr_err.  We walk the
3577 		 * main INT_CAUSE registers here to make sure we haven't missed
3578 		 * anything interesting.
3579 		 */
3580 		t4_slow_intr_handler(sc, verbose);
3581 		atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
3582 	}
3583 	t4_report_fw_error(sc);
3584 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped (%d).\n",
3585 	    device_get_nameunit(sc->dev), fw_error);
3586 	taskqueue_enqueue(reset_tq, &sc->fatal_error_task);
3587 }
3588 
3589 void
3590 t4_add_adapter(struct adapter *sc)
3591 {
3592 	sx_xlock(&t4_list_lock);
3593 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3594 	sx_xunlock(&t4_list_lock);
3595 }
3596 
3597 int
3598 t4_map_bars_0_and_4(struct adapter *sc)
3599 {
3600 	sc->regs_rid = PCIR_BAR(0);
3601 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3602 	    &sc->regs_rid, RF_ACTIVE);
3603 	if (sc->regs_res == NULL) {
3604 		device_printf(sc->dev, "cannot map registers.\n");
3605 		return (ENXIO);
3606 	}
3607 	sc->bt = rman_get_bustag(sc->regs_res);
3608 	sc->bh = rman_get_bushandle(sc->regs_res);
3609 	sc->mmio_len = rman_get_size(sc->regs_res);
3610 	setbit(&sc->doorbells, DOORBELL_KDB);
3611 
3612 	sc->msix_rid = PCIR_BAR(4);
3613 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3614 	    &sc->msix_rid, RF_ACTIVE);
3615 	if (sc->msix_res == NULL) {
3616 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3617 		return (ENXIO);
3618 	}
3619 
3620 	return (0);
3621 }
3622 
3623 int
3624 t4_map_bar_2(struct adapter *sc)
3625 {
3626 
3627 	/*
3628 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3629 	 * to map it if RDMA is disabled.
3630 	 */
3631 	if (is_t4(sc) && sc->rdmacaps == 0)
3632 		return (0);
3633 
3634 	sc->udbs_rid = PCIR_BAR(2);
3635 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3636 	    &sc->udbs_rid, RF_ACTIVE);
3637 	if (sc->udbs_res == NULL) {
3638 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3639 		return (ENXIO);
3640 	}
3641 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3642 
3643 	if (chip_id(sc) >= CHELSIO_T5) {
3644 		setbit(&sc->doorbells, DOORBELL_UDB);
3645 #if defined(__i386__) || defined(__amd64__)
3646 		if (t5_write_combine) {
3647 			int rc, mode;
3648 
3649 			/*
3650 			 * Enable write combining on BAR2.  This is the
3651 			 * userspace doorbell BAR and is split into 128B
3652 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3653 			 * with an egress queue.  The first 64B has the doorbell
3654 			 * and the second 64B can be used to submit a tx work
3655 			 * request with an implicit doorbell.
3656 			 */
3657 
3658 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3659 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3660 			if (rc == 0) {
3661 				clrbit(&sc->doorbells, DOORBELL_UDB);
3662 				setbit(&sc->doorbells, DOORBELL_WCWR);
3663 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3664 			} else {
3665 				device_printf(sc->dev,
3666 				    "couldn't enable write combining: %d\n",
3667 				    rc);
3668 			}
3669 
3670 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3671 			t4_write_reg(sc, A_SGE_STAT_CFG,
3672 			    V_STATSOURCE_T5(7) | mode);
3673 		}
3674 #endif
3675 	}
3676 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3677 
3678 	return (0);
3679 }
3680 
3681 struct memwin_init {
3682 	uint32_t base;
3683 	uint32_t aperture;
3684 };
3685 
3686 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3687 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3688 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3689 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3690 };
3691 
3692 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3693 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3694 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3695 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3696 };
3697 
3698 static void
3699 setup_memwin(struct adapter *sc)
3700 {
3701 	const struct memwin_init *mw_init;
3702 	struct memwin *mw;
3703 	int i;
3704 	uint32_t bar0;
3705 
3706 	if (is_t4(sc)) {
3707 		/*
3708 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3709 		 * mechanism.  Works from within PCI passthrough environments
3710 		 * too, where rman_get_start() can return a different value.  We
3711 		 * need to program the T4 memory window decoders with the actual
3712 		 * addresses that will be coming across the PCIe link.
3713 		 */
3714 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3715 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3716 
3717 		mw_init = &t4_memwin[0];
3718 	} else {
3719 		/* T5+ use the relative offset inside the PCIe BAR */
3720 		bar0 = 0;
3721 
3722 		mw_init = &t5_memwin[0];
3723 	}
3724 
3725 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3726 		if (!rw_initialized(&mw->mw_lock)) {
3727 			rw_init(&mw->mw_lock, "memory window access");
3728 			mw->mw_base = mw_init->base;
3729 			mw->mw_aperture = mw_init->aperture;
3730 			mw->mw_curpos = 0;
3731 		}
3732 		t4_write_reg(sc,
3733 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3734 		    (mw->mw_base + bar0) | V_BIR(0) |
3735 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3736 		rw_wlock(&mw->mw_lock);
3737 		position_memwin(sc, i, mw->mw_curpos);
3738 		rw_wunlock(&mw->mw_lock);
3739 	}
3740 
3741 	/* flush */
3742 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3743 }
3744 
3745 /*
3746  * Positions the memory window at the given address in the card's address space.
3747  * There are some alignment requirements and the actual position may be at an
3748  * address prior to the requested address.  mw->mw_curpos always has the actual
3749  * position of the window.
3750  */
3751 static void
3752 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3753 {
3754 	struct memwin *mw;
3755 	uint32_t pf;
3756 	uint32_t reg;
3757 
3758 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3759 	mw = &sc->memwin[idx];
3760 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3761 
3762 	if (is_t4(sc)) {
3763 		pf = 0;
3764 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3765 	} else {
3766 		pf = V_PFNUM(sc->pf);
3767 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3768 	}
3769 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3770 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3771 	t4_read_reg(sc, reg);	/* flush */
3772 }
3773 
3774 int
3775 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3776     int len, int rw)
3777 {
3778 	struct memwin *mw;
3779 	uint32_t mw_end, v;
3780 
3781 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3782 
3783 	/* Memory can only be accessed in naturally aligned 4 byte units */
3784 	if (addr & 3 || len & 3 || len <= 0)
3785 		return (EINVAL);
3786 
3787 	mw = &sc->memwin[idx];
3788 	while (len > 0) {
3789 		rw_rlock(&mw->mw_lock);
3790 		mw_end = mw->mw_curpos + mw->mw_aperture;
3791 		if (addr >= mw_end || addr < mw->mw_curpos) {
3792 			/* Will need to reposition the window */
3793 			if (!rw_try_upgrade(&mw->mw_lock)) {
3794 				rw_runlock(&mw->mw_lock);
3795 				rw_wlock(&mw->mw_lock);
3796 			}
3797 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3798 			position_memwin(sc, idx, addr);
3799 			rw_downgrade(&mw->mw_lock);
3800 			mw_end = mw->mw_curpos + mw->mw_aperture;
3801 		}
3802 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3803 		while (addr < mw_end && len > 0) {
3804 			if (rw == 0) {
3805 				v = t4_read_reg(sc, mw->mw_base + addr -
3806 				    mw->mw_curpos);
3807 				*val++ = le32toh(v);
3808 			} else {
3809 				v = *val++;
3810 				t4_write_reg(sc, mw->mw_base + addr -
3811 				    mw->mw_curpos, htole32(v));
3812 			}
3813 			addr += 4;
3814 			len -= 4;
3815 		}
3816 		rw_runlock(&mw->mw_lock);
3817 	}
3818 
3819 	return (0);
3820 }
3821 
3822 static void
3823 t4_init_atid_table(struct adapter *sc)
3824 {
3825 	struct tid_info *t;
3826 	int i;
3827 
3828 	t = &sc->tids;
3829 	if (t->natids == 0)
3830 		return;
3831 
3832 	MPASS(t->atid_tab == NULL);
3833 
3834 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3835 	    M_ZERO | M_WAITOK);
3836 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3837 	t->afree = t->atid_tab;
3838 	t->atids_in_use = 0;
3839 	for (i = 1; i < t->natids; i++)
3840 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3841 	t->atid_tab[t->natids - 1].next = NULL;
3842 }
3843 
3844 static void
3845 t4_free_atid_table(struct adapter *sc)
3846 {
3847 	struct tid_info *t;
3848 
3849 	t = &sc->tids;
3850 
3851 	KASSERT(t->atids_in_use == 0,
3852 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3853 
3854 	if (mtx_initialized(&t->atid_lock))
3855 		mtx_destroy(&t->atid_lock);
3856 	free(t->atid_tab, M_CXGBE);
3857 	t->atid_tab = NULL;
3858 }
3859 
3860 int
3861 alloc_atid(struct adapter *sc, void *ctx)
3862 {
3863 	struct tid_info *t = &sc->tids;
3864 	int atid = -1;
3865 
3866 	mtx_lock(&t->atid_lock);
3867 	if (t->afree) {
3868 		union aopen_entry *p = t->afree;
3869 
3870 		atid = p - t->atid_tab;
3871 		MPASS(atid <= M_TID_TID);
3872 		t->afree = p->next;
3873 		p->data = ctx;
3874 		t->atids_in_use++;
3875 	}
3876 	mtx_unlock(&t->atid_lock);
3877 	return (atid);
3878 }
3879 
3880 void *
3881 lookup_atid(struct adapter *sc, int atid)
3882 {
3883 	struct tid_info *t = &sc->tids;
3884 
3885 	return (t->atid_tab[atid].data);
3886 }
3887 
3888 void
3889 free_atid(struct adapter *sc, int atid)
3890 {
3891 	struct tid_info *t = &sc->tids;
3892 	union aopen_entry *p = &t->atid_tab[atid];
3893 
3894 	mtx_lock(&t->atid_lock);
3895 	p->next = t->afree;
3896 	t->afree = p;
3897 	t->atids_in_use--;
3898 	mtx_unlock(&t->atid_lock);
3899 }
3900 
3901 static void
3902 queue_tid_release(struct adapter *sc, int tid)
3903 {
3904 
3905 	CXGBE_UNIMPLEMENTED("deferred tid release");
3906 }
3907 
3908 void
3909 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
3910 {
3911 	struct wrqe *wr;
3912 	struct cpl_tid_release *req;
3913 
3914 	wr = alloc_wrqe(sizeof(*req), ctrlq);
3915 	if (wr == NULL) {
3916 		queue_tid_release(sc, tid);	/* defer */
3917 		return;
3918 	}
3919 	req = wrtod(wr);
3920 
3921 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
3922 
3923 	t4_wrq_tx(sc, wr);
3924 }
3925 
3926 static int
3927 t4_range_cmp(const void *a, const void *b)
3928 {
3929 	return ((const struct t4_range *)a)->start -
3930 	       ((const struct t4_range *)b)->start;
3931 }
3932 
3933 /*
3934  * Verify that the memory range specified by the addr/len pair is valid within
3935  * the card's address space.
3936  */
3937 static int
3938 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
3939 {
3940 	struct t4_range mem_ranges[4], *r, *next;
3941 	uint32_t em, addr_len;
3942 	int i, n, remaining;
3943 
3944 	/* Memory can only be accessed in naturally aligned 4 byte units */
3945 	if (addr & 3 || len & 3 || len == 0)
3946 		return (EINVAL);
3947 
3948 	/* Enabled memories */
3949 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
3950 
3951 	r = &mem_ranges[0];
3952 	n = 0;
3953 	bzero(r, sizeof(mem_ranges));
3954 	if (em & F_EDRAM0_ENABLE) {
3955 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
3956 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
3957 		if (r->size > 0) {
3958 			r->start = G_EDRAM0_BASE(addr_len) << 20;
3959 			if (addr >= r->start &&
3960 			    addr + len <= r->start + r->size)
3961 				return (0);
3962 			r++;
3963 			n++;
3964 		}
3965 	}
3966 	if (em & F_EDRAM1_ENABLE) {
3967 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
3968 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
3969 		if (r->size > 0) {
3970 			r->start = G_EDRAM1_BASE(addr_len) << 20;
3971 			if (addr >= r->start &&
3972 			    addr + len <= r->start + r->size)
3973 				return (0);
3974 			r++;
3975 			n++;
3976 		}
3977 	}
3978 	if (em & F_EXT_MEM_ENABLE) {
3979 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
3980 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
3981 		if (r->size > 0) {
3982 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
3983 			if (addr >= r->start &&
3984 			    addr + len <= r->start + r->size)
3985 				return (0);
3986 			r++;
3987 			n++;
3988 		}
3989 	}
3990 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
3991 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
3992 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
3993 		if (r->size > 0) {
3994 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
3995 			if (addr >= r->start &&
3996 			    addr + len <= r->start + r->size)
3997 				return (0);
3998 			r++;
3999 			n++;
4000 		}
4001 	}
4002 	MPASS(n <= nitems(mem_ranges));
4003 
4004 	if (n > 1) {
4005 		/* Sort and merge the ranges. */
4006 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
4007 
4008 		/* Start from index 0 and examine the next n - 1 entries. */
4009 		r = &mem_ranges[0];
4010 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
4011 
4012 			MPASS(r->size > 0);	/* r is a valid entry. */
4013 			next = r + 1;
4014 			MPASS(next->size > 0);	/* and so is the next one. */
4015 
4016 			while (r->start + r->size >= next->start) {
4017 				/* Merge the next one into the current entry. */
4018 				r->size = max(r->start + r->size,
4019 				    next->start + next->size) - r->start;
4020 				n--;	/* One fewer entry in total. */
4021 				if (--remaining == 0)
4022 					goto done;	/* short circuit */
4023 				next++;
4024 			}
4025 			if (next != r + 1) {
4026 				/*
4027 				 * Some entries were merged into r and next
4028 				 * points to the first valid entry that couldn't
4029 				 * be merged.
4030 				 */
4031 				MPASS(next->size > 0);	/* must be valid */
4032 				memcpy(r + 1, next, remaining * sizeof(*r));
4033 #ifdef INVARIANTS
4034 				/*
4035 				 * This so that the foo->size assertion in the
4036 				 * next iteration of the loop do the right
4037 				 * thing for entries that were pulled up and are
4038 				 * no longer valid.
4039 				 */
4040 				MPASS(n < nitems(mem_ranges));
4041 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4042 				    sizeof(struct t4_range));
4043 #endif
4044 			}
4045 		}
4046 done:
4047 		/* Done merging the ranges. */
4048 		MPASS(n > 0);
4049 		r = &mem_ranges[0];
4050 		for (i = 0; i < n; i++, r++) {
4051 			if (addr >= r->start &&
4052 			    addr + len <= r->start + r->size)
4053 				return (0);
4054 		}
4055 	}
4056 
4057 	return (EFAULT);
4058 }
4059 
4060 static int
4061 fwmtype_to_hwmtype(int mtype)
4062 {
4063 
4064 	switch (mtype) {
4065 	case FW_MEMTYPE_EDC0:
4066 		return (MEM_EDC0);
4067 	case FW_MEMTYPE_EDC1:
4068 		return (MEM_EDC1);
4069 	case FW_MEMTYPE_EXTMEM:
4070 		return (MEM_MC0);
4071 	case FW_MEMTYPE_EXTMEM1:
4072 		return (MEM_MC1);
4073 	default:
4074 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4075 	}
4076 }
4077 
4078 /*
4079  * Verify that the memory range specified by the memtype/offset/len pair is
4080  * valid and lies entirely within the memtype specified.  The global address of
4081  * the start of the range is returned in addr.
4082  */
4083 static int
4084 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4085     uint32_t *addr)
4086 {
4087 	uint32_t em, addr_len, maddr;
4088 
4089 	/* Memory can only be accessed in naturally aligned 4 byte units */
4090 	if (off & 3 || len & 3 || len == 0)
4091 		return (EINVAL);
4092 
4093 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4094 	switch (fwmtype_to_hwmtype(mtype)) {
4095 	case MEM_EDC0:
4096 		if (!(em & F_EDRAM0_ENABLE))
4097 			return (EINVAL);
4098 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4099 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4100 		break;
4101 	case MEM_EDC1:
4102 		if (!(em & F_EDRAM1_ENABLE))
4103 			return (EINVAL);
4104 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4105 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4106 		break;
4107 	case MEM_MC:
4108 		if (!(em & F_EXT_MEM_ENABLE))
4109 			return (EINVAL);
4110 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4111 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4112 		break;
4113 	case MEM_MC1:
4114 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4115 			return (EINVAL);
4116 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4117 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4118 		break;
4119 	default:
4120 		return (EINVAL);
4121 	}
4122 
4123 	*addr = maddr + off;	/* global address */
4124 	return (validate_mem_range(sc, *addr, len));
4125 }
4126 
4127 static int
4128 fixup_devlog_params(struct adapter *sc)
4129 {
4130 	struct devlog_params *dparams = &sc->params.devlog;
4131 	int rc;
4132 
4133 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4134 	    dparams->size, &dparams->addr);
4135 
4136 	return (rc);
4137 }
4138 
4139 static void
4140 update_nirq(struct intrs_and_queues *iaq, int nports)
4141 {
4142 
4143 	iaq->nirq = T4_EXTRA_INTR;
4144 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4145 	iaq->nirq += nports * iaq->nofldrxq;
4146 	iaq->nirq += nports * (iaq->num_vis - 1) *
4147 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4148 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4149 }
4150 
4151 /*
4152  * Adjust requirements to fit the number of interrupts available.
4153  */
4154 static void
4155 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4156     int navail)
4157 {
4158 	int old_nirq;
4159 	const int nports = sc->params.nports;
4160 
4161 	MPASS(nports > 0);
4162 	MPASS(navail > 0);
4163 
4164 	bzero(iaq, sizeof(*iaq));
4165 	iaq->intr_type = itype;
4166 	iaq->num_vis = t4_num_vis;
4167 	iaq->ntxq = t4_ntxq;
4168 	iaq->ntxq_vi = t4_ntxq_vi;
4169 	iaq->nrxq = t4_nrxq;
4170 	iaq->nrxq_vi = t4_nrxq_vi;
4171 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4172 	if (is_offload(sc) || is_ethoffload(sc)) {
4173 		iaq->nofldtxq = t4_nofldtxq;
4174 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4175 	}
4176 #endif
4177 #ifdef TCP_OFFLOAD
4178 	if (is_offload(sc)) {
4179 		iaq->nofldrxq = t4_nofldrxq;
4180 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4181 	}
4182 #endif
4183 #ifdef DEV_NETMAP
4184 	if (t4_native_netmap & NN_MAIN_VI) {
4185 		iaq->nnmtxq = t4_nnmtxq;
4186 		iaq->nnmrxq = t4_nnmrxq;
4187 	}
4188 	if (t4_native_netmap & NN_EXTRA_VI) {
4189 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4190 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4191 	}
4192 #endif
4193 
4194 	update_nirq(iaq, nports);
4195 	if (iaq->nirq <= navail &&
4196 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4197 		/*
4198 		 * This is the normal case -- there are enough interrupts for
4199 		 * everything.
4200 		 */
4201 		goto done;
4202 	}
4203 
4204 	/*
4205 	 * If extra VIs have been configured try reducing their count and see if
4206 	 * that works.
4207 	 */
4208 	while (iaq->num_vis > 1) {
4209 		iaq->num_vis--;
4210 		update_nirq(iaq, nports);
4211 		if (iaq->nirq <= navail &&
4212 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4213 			device_printf(sc->dev, "virtual interfaces per port "
4214 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4215 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4216 			    "itype %d, navail %u, nirq %d.\n",
4217 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4218 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4219 			    itype, navail, iaq->nirq);
4220 			goto done;
4221 		}
4222 	}
4223 
4224 	/*
4225 	 * Extra VIs will not be created.  Log a message if they were requested.
4226 	 */
4227 	MPASS(iaq->num_vis == 1);
4228 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4229 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4230 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4231 	if (iaq->num_vis != t4_num_vis) {
4232 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4233 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4234 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4235 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4236 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4237 	}
4238 
4239 	/*
4240 	 * Keep reducing the number of NIC rx queues to the next lower power of
4241 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4242 	 * if that works.
4243 	 */
4244 	do {
4245 		if (iaq->nrxq > 1) {
4246 			do {
4247 				iaq->nrxq--;
4248 			} while (!powerof2(iaq->nrxq));
4249 			if (iaq->nnmrxq > iaq->nrxq)
4250 				iaq->nnmrxq = iaq->nrxq;
4251 		}
4252 		if (iaq->nofldrxq > 1)
4253 			iaq->nofldrxq >>= 1;
4254 
4255 		old_nirq = iaq->nirq;
4256 		update_nirq(iaq, nports);
4257 		if (iaq->nirq <= navail &&
4258 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4259 			device_printf(sc->dev, "running with reduced number of "
4260 			    "rx queues because of shortage of interrupts.  "
4261 			    "nrxq=%u, nofldrxq=%u.  "
4262 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4263 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4264 			goto done;
4265 		}
4266 	} while (old_nirq != iaq->nirq);
4267 
4268 	/* One interrupt for everything.  Ugh. */
4269 	device_printf(sc->dev, "running with minimal number of queues.  "
4270 	    "itype %d, navail %u.\n", itype, navail);
4271 	iaq->nirq = 1;
4272 	iaq->nrxq = 1;
4273 	iaq->ntxq = 1;
4274 	if (iaq->nofldrxq > 0) {
4275 		iaq->nofldrxq = 1;
4276 		iaq->nofldtxq = 1;
4277 	}
4278 	iaq->nnmtxq = 0;
4279 	iaq->nnmrxq = 0;
4280 done:
4281 	MPASS(iaq->num_vis > 0);
4282 	if (iaq->num_vis > 1) {
4283 		MPASS(iaq->nrxq_vi > 0);
4284 		MPASS(iaq->ntxq_vi > 0);
4285 	}
4286 	MPASS(iaq->nirq > 0);
4287 	MPASS(iaq->nrxq > 0);
4288 	MPASS(iaq->ntxq > 0);
4289 	if (itype == INTR_MSI) {
4290 		MPASS(powerof2(iaq->nirq));
4291 	}
4292 }
4293 
4294 static int
4295 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4296 {
4297 	int rc, itype, navail, nalloc;
4298 
4299 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4300 
4301 		if ((itype & t4_intr_types) == 0)
4302 			continue;	/* not allowed */
4303 
4304 		if (itype == INTR_MSIX)
4305 			navail = pci_msix_count(sc->dev);
4306 		else if (itype == INTR_MSI)
4307 			navail = pci_msi_count(sc->dev);
4308 		else
4309 			navail = 1;
4310 restart:
4311 		if (navail == 0)
4312 			continue;
4313 
4314 		calculate_iaq(sc, iaq, itype, navail);
4315 		nalloc = iaq->nirq;
4316 		rc = 0;
4317 		if (itype == INTR_MSIX)
4318 			rc = pci_alloc_msix(sc->dev, &nalloc);
4319 		else if (itype == INTR_MSI)
4320 			rc = pci_alloc_msi(sc->dev, &nalloc);
4321 
4322 		if (rc == 0 && nalloc > 0) {
4323 			if (nalloc == iaq->nirq)
4324 				return (0);
4325 
4326 			/*
4327 			 * Didn't get the number requested.  Use whatever number
4328 			 * the kernel is willing to allocate.
4329 			 */
4330 			device_printf(sc->dev, "fewer vectors than requested, "
4331 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4332 			    itype, iaq->nirq, nalloc);
4333 			pci_release_msi(sc->dev);
4334 			navail = nalloc;
4335 			goto restart;
4336 		}
4337 
4338 		device_printf(sc->dev,
4339 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4340 		    itype, rc, iaq->nirq, nalloc);
4341 	}
4342 
4343 	device_printf(sc->dev,
4344 	    "failed to find a usable interrupt type.  "
4345 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4346 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4347 
4348 	return (ENXIO);
4349 }
4350 
4351 #define FW_VERSION(chip) ( \
4352     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4353     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4354     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4355     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4356 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4357 
4358 /* Just enough of fw_hdr to cover all version info. */
4359 struct fw_h {
4360 	__u8	ver;
4361 	__u8	chip;
4362 	__be16	len512;
4363 	__be32	fw_ver;
4364 	__be32	tp_microcode_ver;
4365 	__u8	intfver_nic;
4366 	__u8	intfver_vnic;
4367 	__u8	intfver_ofld;
4368 	__u8	intfver_ri;
4369 	__u8	intfver_iscsipdu;
4370 	__u8	intfver_iscsi;
4371 	__u8	intfver_fcoepdu;
4372 	__u8	intfver_fcoe;
4373 };
4374 /* Spot check a couple of fields. */
4375 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4376 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4377 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4378 
4379 struct fw_info {
4380 	uint8_t chip;
4381 	char *kld_name;
4382 	char *fw_mod_name;
4383 	struct fw_h fw_h;
4384 } fw_info[] = {
4385 	{
4386 		.chip = CHELSIO_T4,
4387 		.kld_name = "t4fw_cfg",
4388 		.fw_mod_name = "t4fw",
4389 		.fw_h = {
4390 			.chip = FW_HDR_CHIP_T4,
4391 			.fw_ver = htobe32(FW_VERSION(T4)),
4392 			.intfver_nic = FW_INTFVER(T4, NIC),
4393 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4394 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4395 			.intfver_ri = FW_INTFVER(T4, RI),
4396 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4397 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4398 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4399 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4400 		},
4401 	}, {
4402 		.chip = CHELSIO_T5,
4403 		.kld_name = "t5fw_cfg",
4404 		.fw_mod_name = "t5fw",
4405 		.fw_h = {
4406 			.chip = FW_HDR_CHIP_T5,
4407 			.fw_ver = htobe32(FW_VERSION(T5)),
4408 			.intfver_nic = FW_INTFVER(T5, NIC),
4409 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4410 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4411 			.intfver_ri = FW_INTFVER(T5, RI),
4412 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4413 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4414 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4415 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4416 		},
4417 	}, {
4418 		.chip = CHELSIO_T6,
4419 		.kld_name = "t6fw_cfg",
4420 		.fw_mod_name = "t6fw",
4421 		.fw_h = {
4422 			.chip = FW_HDR_CHIP_T6,
4423 			.fw_ver = htobe32(FW_VERSION(T6)),
4424 			.intfver_nic = FW_INTFVER(T6, NIC),
4425 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4426 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4427 			.intfver_ri = FW_INTFVER(T6, RI),
4428 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4429 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4430 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4431 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4432 		},
4433 	}
4434 };
4435 
4436 static struct fw_info *
4437 find_fw_info(int chip)
4438 {
4439 	int i;
4440 
4441 	for (i = 0; i < nitems(fw_info); i++) {
4442 		if (fw_info[i].chip == chip)
4443 			return (&fw_info[i]);
4444 	}
4445 	return (NULL);
4446 }
4447 
4448 /*
4449  * Is the given firmware API compatible with the one the driver was compiled
4450  * with?
4451  */
4452 static int
4453 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4454 {
4455 
4456 	/* short circuit if it's the exact same firmware version */
4457 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4458 		return (1);
4459 
4460 	/*
4461 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4462 	 * features that are supported in the driver.
4463 	 */
4464 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4465 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4466 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4467 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4468 		return (1);
4469 #undef SAME_INTF
4470 
4471 	return (0);
4472 }
4473 
4474 static int
4475 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4476     const struct firmware **fw)
4477 {
4478 	struct fw_info *fw_info;
4479 
4480 	*dcfg = NULL;
4481 	if (fw != NULL)
4482 		*fw = NULL;
4483 
4484 	fw_info = find_fw_info(chip_id(sc));
4485 	if (fw_info == NULL) {
4486 		device_printf(sc->dev,
4487 		    "unable to look up firmware information for chip %d.\n",
4488 		    chip_id(sc));
4489 		return (EINVAL);
4490 	}
4491 
4492 	*dcfg = firmware_get(fw_info->kld_name);
4493 	if (*dcfg != NULL) {
4494 		if (fw != NULL)
4495 			*fw = firmware_get(fw_info->fw_mod_name);
4496 		return (0);
4497 	}
4498 
4499 	return (ENOENT);
4500 }
4501 
4502 static void
4503 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4504     const struct firmware *fw)
4505 {
4506 
4507 	if (fw != NULL)
4508 		firmware_put(fw, FIRMWARE_UNLOAD);
4509 	if (dcfg != NULL)
4510 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4511 }
4512 
4513 /*
4514  * Return values:
4515  * 0 means no firmware install attempted.
4516  * ERESTART means a firmware install was attempted and was successful.
4517  * +ve errno means a firmware install was attempted but failed.
4518  */
4519 static int
4520 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4521     const struct fw_h *drv_fw, const char *reason, int *already)
4522 {
4523 	const struct firmware *cfg, *fw;
4524 	const uint32_t c = be32toh(card_fw->fw_ver);
4525 	uint32_t d, k;
4526 	int rc, fw_install;
4527 	struct fw_h bundled_fw;
4528 	bool load_attempted;
4529 
4530 	cfg = fw = NULL;
4531 	load_attempted = false;
4532 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4533 
4534 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4535 	if (t4_fw_install < 0) {
4536 		rc = load_fw_module(sc, &cfg, &fw);
4537 		if (rc != 0 || fw == NULL) {
4538 			device_printf(sc->dev,
4539 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4540 			    " will use compiled-in firmware version for"
4541 			    "hw.cxgbe.fw_install checks.\n",
4542 			    rc, cfg, fw);
4543 		} else {
4544 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4545 		}
4546 		load_attempted = true;
4547 	}
4548 	d = be32toh(bundled_fw.fw_ver);
4549 
4550 	if (reason != NULL)
4551 		goto install;
4552 
4553 	if ((sc->flags & FW_OK) == 0) {
4554 
4555 		if (c == 0xffffffff) {
4556 			reason = "missing";
4557 			goto install;
4558 		}
4559 
4560 		rc = 0;
4561 		goto done;
4562 	}
4563 
4564 	if (!fw_compatible(card_fw, &bundled_fw)) {
4565 		reason = "incompatible or unusable";
4566 		goto install;
4567 	}
4568 
4569 	if (d > c) {
4570 		reason = "older than the version bundled with this driver";
4571 		goto install;
4572 	}
4573 
4574 	if (fw_install == 2 && d != c) {
4575 		reason = "different than the version bundled with this driver";
4576 		goto install;
4577 	}
4578 
4579 	/* No reason to do anything to the firmware already on the card. */
4580 	rc = 0;
4581 	goto done;
4582 
4583 install:
4584 	rc = 0;
4585 	if ((*already)++)
4586 		goto done;
4587 
4588 	if (fw_install == 0) {
4589 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4590 		    "but the driver is prohibited from installing a firmware "
4591 		    "on the card.\n",
4592 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4593 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4594 
4595 		goto done;
4596 	}
4597 
4598 	/*
4599 	 * We'll attempt to install a firmware.  Load the module first (if it
4600 	 * hasn't been loaded already).
4601 	 */
4602 	if (!load_attempted) {
4603 		rc = load_fw_module(sc, &cfg, &fw);
4604 		if (rc != 0 || fw == NULL) {
4605 			device_printf(sc->dev,
4606 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4607 			    rc, cfg, fw);
4608 			/* carry on */
4609 		}
4610 	}
4611 	if (fw == NULL) {
4612 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4613 		    "but the driver cannot take corrective action because it "
4614 		    "is unable to load the firmware module.\n",
4615 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4616 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4617 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4618 		goto done;
4619 	}
4620 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4621 	if (k != d) {
4622 		MPASS(t4_fw_install > 0);
4623 		device_printf(sc->dev,
4624 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4625 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4626 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4627 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4628 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4629 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4630 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4631 		goto done;
4632 	}
4633 
4634 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4635 	    "installing firmware %u.%u.%u.%u on card.\n",
4636 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4637 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4638 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4639 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4640 
4641 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4642 	if (rc != 0) {
4643 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4644 	} else {
4645 		/* Installed successfully, update the cached header too. */
4646 		rc = ERESTART;
4647 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4648 	}
4649 done:
4650 	unload_fw_module(sc, cfg, fw);
4651 
4652 	return (rc);
4653 }
4654 
4655 /*
4656  * Establish contact with the firmware and attempt to become the master driver.
4657  *
4658  * A firmware will be installed to the card if needed (if the driver is allowed
4659  * to do so).
4660  */
4661 static int
4662 contact_firmware(struct adapter *sc)
4663 {
4664 	int rc, already = 0;
4665 	enum dev_state state;
4666 	struct fw_info *fw_info;
4667 	struct fw_hdr *card_fw;		/* fw on the card */
4668 	const struct fw_h *drv_fw;
4669 
4670 	fw_info = find_fw_info(chip_id(sc));
4671 	if (fw_info == NULL) {
4672 		device_printf(sc->dev,
4673 		    "unable to look up firmware information for chip %d.\n",
4674 		    chip_id(sc));
4675 		return (EINVAL);
4676 	}
4677 	drv_fw = &fw_info->fw_h;
4678 
4679 	/* Read the header of the firmware on the card */
4680 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4681 restart:
4682 	rc = -t4_get_fw_hdr(sc, card_fw);
4683 	if (rc != 0) {
4684 		device_printf(sc->dev,
4685 		    "unable to read firmware header from card's flash: %d\n",
4686 		    rc);
4687 		goto done;
4688 	}
4689 
4690 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4691 	    &already);
4692 	if (rc == ERESTART)
4693 		goto restart;
4694 	if (rc != 0)
4695 		goto done;
4696 
4697 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4698 	if (rc < 0 || state == DEV_STATE_ERR) {
4699 		rc = -rc;
4700 		device_printf(sc->dev,
4701 		    "failed to connect to the firmware: %d, %d.  "
4702 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4703 #if 0
4704 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4705 		    "not responding properly to HELLO", &already) == ERESTART)
4706 			goto restart;
4707 #endif
4708 		goto done;
4709 	}
4710 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4711 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4712 
4713 	if (rc == sc->pf) {
4714 		sc->flags |= MASTER_PF;
4715 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4716 		    NULL, &already);
4717 		if (rc == ERESTART)
4718 			rc = 0;
4719 		else if (rc != 0)
4720 			goto done;
4721 	} else if (state == DEV_STATE_UNINIT) {
4722 		/*
4723 		 * We didn't get to be the master so we definitely won't be
4724 		 * configuring the chip.  It's a bug if someone else hasn't
4725 		 * configured it already.
4726 		 */
4727 		device_printf(sc->dev, "couldn't be master(%d), "
4728 		    "device not already initialized either(%d).  "
4729 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4730 		rc = EPROTO;
4731 		goto done;
4732 	} else {
4733 		/*
4734 		 * Some other PF is the master and has configured the chip.
4735 		 * This is allowed but untested.
4736 		 */
4737 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4738 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4739 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4740 		sc->cfcsum = 0;
4741 		rc = 0;
4742 	}
4743 done:
4744 	if (rc != 0 && sc->flags & FW_OK) {
4745 		t4_fw_bye(sc, sc->mbox);
4746 		sc->flags &= ~FW_OK;
4747 	}
4748 	free(card_fw, M_CXGBE);
4749 	return (rc);
4750 }
4751 
4752 static int
4753 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4754     uint32_t mtype, uint32_t moff)
4755 {
4756 	struct fw_info *fw_info;
4757 	const struct firmware *dcfg, *rcfg = NULL;
4758 	const uint32_t *cfdata;
4759 	uint32_t cflen, addr;
4760 	int rc;
4761 
4762 	load_fw_module(sc, &dcfg, NULL);
4763 
4764 	/* Card specific interpretation of "default". */
4765 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4766 		if (pci_get_device(sc->dev) == 0x440a)
4767 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4768 		if (is_fpga(sc))
4769 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4770 	}
4771 
4772 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4773 		if (dcfg == NULL) {
4774 			device_printf(sc->dev,
4775 			    "KLD with default config is not available.\n");
4776 			rc = ENOENT;
4777 			goto done;
4778 		}
4779 		cfdata = dcfg->data;
4780 		cflen = dcfg->datasize & ~3;
4781 	} else {
4782 		char s[32];
4783 
4784 		fw_info = find_fw_info(chip_id(sc));
4785 		if (fw_info == NULL) {
4786 			device_printf(sc->dev,
4787 			    "unable to look up firmware information for chip %d.\n",
4788 			    chip_id(sc));
4789 			rc = EINVAL;
4790 			goto done;
4791 		}
4792 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4793 
4794 		rcfg = firmware_get(s);
4795 		if (rcfg == NULL) {
4796 			device_printf(sc->dev,
4797 			    "unable to load module \"%s\" for configuration "
4798 			    "profile \"%s\".\n", s, cfg_file);
4799 			rc = ENOENT;
4800 			goto done;
4801 		}
4802 		cfdata = rcfg->data;
4803 		cflen = rcfg->datasize & ~3;
4804 	}
4805 
4806 	if (cflen > FLASH_CFG_MAX_SIZE) {
4807 		device_printf(sc->dev,
4808 		    "config file too long (%d, max allowed is %d).\n",
4809 		    cflen, FLASH_CFG_MAX_SIZE);
4810 		rc = EINVAL;
4811 		goto done;
4812 	}
4813 
4814 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4815 	if (rc != 0) {
4816 		device_printf(sc->dev,
4817 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4818 		    __func__, mtype, moff, cflen, rc);
4819 		rc = EINVAL;
4820 		goto done;
4821 	}
4822 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4823 done:
4824 	if (rcfg != NULL)
4825 		firmware_put(rcfg, FIRMWARE_UNLOAD);
4826 	unload_fw_module(sc, dcfg, NULL);
4827 	return (rc);
4828 }
4829 
4830 struct caps_allowed {
4831 	uint16_t nbmcaps;
4832 	uint16_t linkcaps;
4833 	uint16_t switchcaps;
4834 	uint16_t niccaps;
4835 	uint16_t toecaps;
4836 	uint16_t rdmacaps;
4837 	uint16_t cryptocaps;
4838 	uint16_t iscsicaps;
4839 	uint16_t fcoecaps;
4840 };
4841 
4842 #define FW_PARAM_DEV(param) \
4843 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4844 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4845 #define FW_PARAM_PFVF(param) \
4846 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4847 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4848 
4849 /*
4850  * Provide a configuration profile to the firmware and have it initialize the
4851  * chip accordingly.  This may involve uploading a configuration file to the
4852  * card.
4853  */
4854 static int
4855 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4856     const struct caps_allowed *caps_allowed)
4857 {
4858 	int rc;
4859 	struct fw_caps_config_cmd caps;
4860 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
4861 
4862 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4863 	if (rc != 0) {
4864 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
4865 		return (rc);
4866 	}
4867 
4868 	bzero(&caps, sizeof(caps));
4869 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4870 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
4871 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
4872 		mtype = 0;
4873 		moff = 0;
4874 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4875 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
4876 		mtype = FW_MEMTYPE_FLASH;
4877 		moff = t4_flash_cfg_addr(sc);
4878 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4879 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4880 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4881 		    FW_LEN16(caps));
4882 	} else {
4883 		/*
4884 		 * Ask the firmware where it wants us to upload the config file.
4885 		 */
4886 		param = FW_PARAM_DEV(CF);
4887 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4888 		if (rc != 0) {
4889 			/* No support for config file?  Shouldn't happen. */
4890 			device_printf(sc->dev,
4891 			    "failed to query config file location: %d.\n", rc);
4892 			goto done;
4893 		}
4894 		mtype = G_FW_PARAMS_PARAM_Y(val);
4895 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
4896 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4897 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4898 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4899 		    FW_LEN16(caps));
4900 
4901 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
4902 		if (rc != 0) {
4903 			device_printf(sc->dev,
4904 			    "failed to upload config file to card: %d.\n", rc);
4905 			goto done;
4906 		}
4907 	}
4908 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
4909 	if (rc != 0) {
4910 		device_printf(sc->dev, "failed to pre-process config file: %d "
4911 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
4912 		goto done;
4913 	}
4914 
4915 	finicsum = be32toh(caps.finicsum);
4916 	cfcsum = be32toh(caps.cfcsum);	/* actual */
4917 	if (finicsum != cfcsum) {
4918 		device_printf(sc->dev,
4919 		    "WARNING: config file checksum mismatch: %08x %08x\n",
4920 		    finicsum, cfcsum);
4921 	}
4922 	sc->cfcsum = cfcsum;
4923 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
4924 
4925 	/*
4926 	 * Let the firmware know what features will (not) be used so it can tune
4927 	 * things accordingly.
4928 	 */
4929 #define LIMIT_CAPS(x) do { \
4930 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
4931 } while (0)
4932 	LIMIT_CAPS(nbm);
4933 	LIMIT_CAPS(link);
4934 	LIMIT_CAPS(switch);
4935 	LIMIT_CAPS(nic);
4936 	LIMIT_CAPS(toe);
4937 	LIMIT_CAPS(rdma);
4938 	LIMIT_CAPS(crypto);
4939 	LIMIT_CAPS(iscsi);
4940 	LIMIT_CAPS(fcoe);
4941 #undef LIMIT_CAPS
4942 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
4943 		/*
4944 		 * TOE and hashfilters are mutually exclusive.  It is a config
4945 		 * file or firmware bug if both are reported as available.  Try
4946 		 * to cope with the situation in non-debug builds by disabling
4947 		 * TOE.
4948 		 */
4949 		MPASS(caps.toecaps == 0);
4950 
4951 		caps.toecaps = 0;
4952 		caps.rdmacaps = 0;
4953 		caps.iscsicaps = 0;
4954 	}
4955 
4956 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4957 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
4958 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4959 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
4960 	if (rc != 0) {
4961 		device_printf(sc->dev,
4962 		    "failed to process config file: %d.\n", rc);
4963 		goto done;
4964 	}
4965 
4966 	t4_tweak_chip_settings(sc);
4967 	set_params__pre_init(sc);
4968 
4969 	/* get basic stuff going */
4970 	rc = -t4_fw_initialize(sc, sc->mbox);
4971 	if (rc != 0) {
4972 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
4973 		goto done;
4974 	}
4975 done:
4976 	return (rc);
4977 }
4978 
4979 /*
4980  * Partition chip resources for use between various PFs, VFs, etc.
4981  */
4982 static int
4983 partition_resources(struct adapter *sc)
4984 {
4985 	char cfg_file[sizeof(t4_cfg_file)];
4986 	struct caps_allowed caps_allowed;
4987 	int rc;
4988 	bool fallback;
4989 
4990 	/* Only the master driver gets to configure the chip resources. */
4991 	MPASS(sc->flags & MASTER_PF);
4992 
4993 #define COPY_CAPS(x) do { \
4994 	caps_allowed.x##caps = t4_##x##caps_allowed; \
4995 } while (0)
4996 	bzero(&caps_allowed, sizeof(caps_allowed));
4997 	COPY_CAPS(nbm);
4998 	COPY_CAPS(link);
4999 	COPY_CAPS(switch);
5000 	COPY_CAPS(nic);
5001 	COPY_CAPS(toe);
5002 	COPY_CAPS(rdma);
5003 	COPY_CAPS(crypto);
5004 	COPY_CAPS(iscsi);
5005 	COPY_CAPS(fcoe);
5006 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
5007 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
5008 retry:
5009 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
5010 	if (rc != 0 && fallback) {
5011 		device_printf(sc->dev,
5012 		    "failed (%d) to configure card with \"%s\" profile, "
5013 		    "will fall back to a basic configuration and retry.\n",
5014 		    rc, cfg_file);
5015 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
5016 		bzero(&caps_allowed, sizeof(caps_allowed));
5017 		COPY_CAPS(switch);
5018 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
5019 		fallback = false;
5020 		goto retry;
5021 	}
5022 #undef COPY_CAPS
5023 	return (rc);
5024 }
5025 
5026 /*
5027  * Retrieve parameters that are needed (or nice to have) very early.
5028  */
5029 static int
5030 get_params__pre_init(struct adapter *sc)
5031 {
5032 	int rc;
5033 	uint32_t param[2], val[2];
5034 
5035 	t4_get_version_info(sc);
5036 
5037 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5038 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5039 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5040 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5041 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5042 
5043 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5044 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5045 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5046 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5047 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5048 
5049 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5050 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5051 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5052 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5053 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5054 
5055 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5056 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5057 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5058 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5059 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5060 
5061 	param[0] = FW_PARAM_DEV(PORTVEC);
5062 	param[1] = FW_PARAM_DEV(CCLK);
5063 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5064 	if (rc != 0) {
5065 		device_printf(sc->dev,
5066 		    "failed to query parameters (pre_init): %d.\n", rc);
5067 		return (rc);
5068 	}
5069 
5070 	sc->params.portvec = val[0];
5071 	sc->params.nports = bitcount32(val[0]);
5072 	sc->params.vpd.cclk = val[1];
5073 
5074 	/* Read device log parameters. */
5075 	rc = -t4_init_devlog_params(sc, 1);
5076 	if (rc == 0)
5077 		fixup_devlog_params(sc);
5078 	else {
5079 		device_printf(sc->dev,
5080 		    "failed to get devlog parameters: %d.\n", rc);
5081 		rc = 0;	/* devlog isn't critical for device operation */
5082 	}
5083 
5084 	return (rc);
5085 }
5086 
5087 /*
5088  * Any params that need to be set before FW_INITIALIZE.
5089  */
5090 static int
5091 set_params__pre_init(struct adapter *sc)
5092 {
5093 	int rc = 0;
5094 	uint32_t param, val;
5095 
5096 	if (chip_id(sc) >= CHELSIO_T6) {
5097 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5098 		val = 1;
5099 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5100 		/* firmwares < 1.20.1.0 do not have this param. */
5101 		if (rc == FW_EINVAL &&
5102 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5103 			rc = 0;
5104 		}
5105 		if (rc != 0) {
5106 			device_printf(sc->dev,
5107 			    "failed to enable high priority filters :%d.\n",
5108 			    rc);
5109 		}
5110 
5111 		param = FW_PARAM_DEV(PPOD_EDRAM);
5112 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5113 		if (rc == 0 && val == 1) {
5114 			rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param,
5115 			    &val);
5116 			if (rc != 0) {
5117 				device_printf(sc->dev,
5118 				    "failed to set PPOD_EDRAM: %d.\n", rc);
5119 			}
5120 		}
5121 	}
5122 
5123 	/* Enable opaque VIIDs with firmwares that support it. */
5124 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5125 	val = 1;
5126 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5127 	if (rc == 0 && val == 1)
5128 		sc->params.viid_smt_extn_support = true;
5129 	else
5130 		sc->params.viid_smt_extn_support = false;
5131 
5132 	return (rc);
5133 }
5134 
5135 /*
5136  * Retrieve various parameters that are of interest to the driver.  The device
5137  * has been initialized by the firmware at this point.
5138  */
5139 static int
5140 get_params__post_init(struct adapter *sc)
5141 {
5142 	int rc;
5143 	uint32_t param[7], val[7];
5144 	struct fw_caps_config_cmd caps;
5145 
5146 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5147 	param[1] = FW_PARAM_PFVF(EQ_START);
5148 	param[2] = FW_PARAM_PFVF(FILTER_START);
5149 	param[3] = FW_PARAM_PFVF(FILTER_END);
5150 	param[4] = FW_PARAM_PFVF(L2T_START);
5151 	param[5] = FW_PARAM_PFVF(L2T_END);
5152 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5153 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5154 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5155 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5156 	if (rc != 0) {
5157 		device_printf(sc->dev,
5158 		    "failed to query parameters (post_init): %d.\n", rc);
5159 		return (rc);
5160 	}
5161 
5162 	sc->sge.iq_start = val[0];
5163 	sc->sge.eq_start = val[1];
5164 	if ((int)val[3] > (int)val[2]) {
5165 		sc->tids.ftid_base = val[2];
5166 		sc->tids.ftid_end = val[3];
5167 		sc->tids.nftids = val[3] - val[2] + 1;
5168 	}
5169 	sc->vres.l2t.start = val[4];
5170 	sc->vres.l2t.size = val[5] - val[4] + 1;
5171 	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
5172 	    ("%s: L2 table size (%u) larger than expected (%u)",
5173 	    __func__, sc->vres.l2t.size, L2T_SIZE));
5174 	sc->params.core_vdd = val[6];
5175 
5176 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5177 	param[1] = FW_PARAM_PFVF(EQ_END);
5178 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5179 	if (rc != 0) {
5180 		device_printf(sc->dev,
5181 		    "failed to query parameters (post_init2): %d.\n", rc);
5182 		return (rc);
5183 	}
5184 	MPASS((int)val[0] >= sc->sge.iq_start);
5185 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5186 	MPASS((int)val[1] >= sc->sge.eq_start);
5187 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5188 
5189 	if (chip_id(sc) >= CHELSIO_T6) {
5190 
5191 		sc->tids.tid_base = t4_read_reg(sc,
5192 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5193 
5194 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5195 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5196 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5197 		if (rc != 0) {
5198 			device_printf(sc->dev,
5199 			   "failed to query hpfilter parameters: %d.\n", rc);
5200 			return (rc);
5201 		}
5202 		if ((int)val[1] > (int)val[0]) {
5203 			sc->tids.hpftid_base = val[0];
5204 			sc->tids.hpftid_end = val[1];
5205 			sc->tids.nhpftids = val[1] - val[0] + 1;
5206 
5207 			/*
5208 			 * These should go off if the layout changes and the
5209 			 * driver needs to catch up.
5210 			 */
5211 			MPASS(sc->tids.hpftid_base == 0);
5212 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5213 		}
5214 
5215 		param[0] = FW_PARAM_PFVF(RAWF_START);
5216 		param[1] = FW_PARAM_PFVF(RAWF_END);
5217 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5218 		if (rc != 0) {
5219 			device_printf(sc->dev,
5220 			   "failed to query rawf parameters: %d.\n", rc);
5221 			return (rc);
5222 		}
5223 		if ((int)val[1] > (int)val[0]) {
5224 			sc->rawf_base = val[0];
5225 			sc->nrawf = val[1] - val[0] + 1;
5226 		}
5227 	}
5228 
5229 	/*
5230 	 * MPSBGMAP is queried separately because only recent firmwares support
5231 	 * it as a parameter and we don't want the compound query above to fail
5232 	 * on older firmwares.
5233 	 */
5234 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5235 	val[0] = 0;
5236 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5237 	if (rc == 0)
5238 		sc->params.mps_bg_map = val[0];
5239 	else
5240 		sc->params.mps_bg_map = 0;
5241 
5242 	/*
5243 	 * Determine whether the firmware supports the filter2 work request.
5244 	 * This is queried separately for the same reason as MPSBGMAP above.
5245 	 */
5246 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5247 	val[0] = 0;
5248 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5249 	if (rc == 0)
5250 		sc->params.filter2_wr_support = val[0] != 0;
5251 	else
5252 		sc->params.filter2_wr_support = 0;
5253 
5254 	/*
5255 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5256 	 * This is queried separately for the same reason as other params above.
5257 	 */
5258 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5259 	val[0] = 0;
5260 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5261 	if (rc == 0)
5262 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5263 	else
5264 		sc->params.ulptx_memwrite_dsgl = false;
5265 
5266 	/* FW_RI_FR_NSMR_TPTE_WR support */
5267 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5268 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5269 	if (rc == 0)
5270 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5271 	else
5272 		sc->params.fr_nsmr_tpte_wr_support = false;
5273 
5274 	/* Support for 512 SGL entries per FR MR. */
5275 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5276 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5277 	if (rc == 0)
5278 		sc->params.dev_512sgl_mr = val[0] != 0;
5279 	else
5280 		sc->params.dev_512sgl_mr = false;
5281 
5282 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5283 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5284 	if (rc == 0)
5285 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5286 	else
5287 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5288 
5289 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5290 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5291 	if (rc == 0) {
5292 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5293 		sc->params.nsched_cls = val[0];
5294 	} else
5295 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5296 
5297 	/* get capabilites */
5298 	bzero(&caps, sizeof(caps));
5299 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5300 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5301 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5302 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5303 	if (rc != 0) {
5304 		device_printf(sc->dev,
5305 		    "failed to get card capabilities: %d.\n", rc);
5306 		return (rc);
5307 	}
5308 
5309 #define READ_CAPS(x) do { \
5310 	sc->x = htobe16(caps.x); \
5311 } while (0)
5312 	READ_CAPS(nbmcaps);
5313 	READ_CAPS(linkcaps);
5314 	READ_CAPS(switchcaps);
5315 	READ_CAPS(niccaps);
5316 	READ_CAPS(toecaps);
5317 	READ_CAPS(rdmacaps);
5318 	READ_CAPS(cryptocaps);
5319 	READ_CAPS(iscsicaps);
5320 	READ_CAPS(fcoecaps);
5321 
5322 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5323 		MPASS(chip_id(sc) > CHELSIO_T4);
5324 		MPASS(sc->toecaps == 0);
5325 		sc->toecaps = 0;
5326 
5327 		param[0] = FW_PARAM_DEV(NTID);
5328 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5329 		if (rc != 0) {
5330 			device_printf(sc->dev,
5331 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5332 			return (rc);
5333 		}
5334 		sc->tids.ntids = val[0];
5335 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5336 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5337 			sc->tids.ntids -= sc->tids.nhpftids;
5338 		}
5339 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5340 		sc->params.hash_filter = 1;
5341 	}
5342 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5343 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5344 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5345 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5346 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5347 		if (rc != 0) {
5348 			device_printf(sc->dev,
5349 			    "failed to query NIC parameters: %d.\n", rc);
5350 			return (rc);
5351 		}
5352 		if ((int)val[1] > (int)val[0]) {
5353 			sc->tids.etid_base = val[0];
5354 			sc->tids.etid_end = val[1];
5355 			sc->tids.netids = val[1] - val[0] + 1;
5356 			sc->params.eo_wr_cred = val[2];
5357 			sc->params.ethoffload = 1;
5358 		}
5359 	}
5360 	if (sc->toecaps) {
5361 		/* query offload-related parameters */
5362 		param[0] = FW_PARAM_DEV(NTID);
5363 		param[1] = FW_PARAM_PFVF(SERVER_START);
5364 		param[2] = FW_PARAM_PFVF(SERVER_END);
5365 		param[3] = FW_PARAM_PFVF(TDDP_START);
5366 		param[4] = FW_PARAM_PFVF(TDDP_END);
5367 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5368 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5369 		if (rc != 0) {
5370 			device_printf(sc->dev,
5371 			    "failed to query TOE parameters: %d.\n", rc);
5372 			return (rc);
5373 		}
5374 		sc->tids.ntids = val[0];
5375 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5376 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5377 			sc->tids.ntids -= sc->tids.nhpftids;
5378 		}
5379 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5380 		if ((int)val[2] > (int)val[1]) {
5381 			sc->tids.stid_base = val[1];
5382 			sc->tids.nstids = val[2] - val[1] + 1;
5383 		}
5384 		sc->vres.ddp.start = val[3];
5385 		sc->vres.ddp.size = val[4] - val[3] + 1;
5386 		sc->params.ofldq_wr_cred = val[5];
5387 		sc->params.offload = 1;
5388 	} else {
5389 		/*
5390 		 * The firmware attempts memfree TOE configuration for -SO cards
5391 		 * and will report toecaps=0 if it runs out of resources (this
5392 		 * depends on the config file).  It may not report 0 for other
5393 		 * capabilities dependent on the TOE in this case.  Set them to
5394 		 * 0 here so that the driver doesn't bother tracking resources
5395 		 * that will never be used.
5396 		 */
5397 		sc->iscsicaps = 0;
5398 		sc->rdmacaps = 0;
5399 	}
5400 	if (sc->rdmacaps) {
5401 		param[0] = FW_PARAM_PFVF(STAG_START);
5402 		param[1] = FW_PARAM_PFVF(STAG_END);
5403 		param[2] = FW_PARAM_PFVF(RQ_START);
5404 		param[3] = FW_PARAM_PFVF(RQ_END);
5405 		param[4] = FW_PARAM_PFVF(PBL_START);
5406 		param[5] = FW_PARAM_PFVF(PBL_END);
5407 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5408 		if (rc != 0) {
5409 			device_printf(sc->dev,
5410 			    "failed to query RDMA parameters(1): %d.\n", rc);
5411 			return (rc);
5412 		}
5413 		sc->vres.stag.start = val[0];
5414 		sc->vres.stag.size = val[1] - val[0] + 1;
5415 		sc->vres.rq.start = val[2];
5416 		sc->vres.rq.size = val[3] - val[2] + 1;
5417 		sc->vres.pbl.start = val[4];
5418 		sc->vres.pbl.size = val[5] - val[4] + 1;
5419 
5420 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5421 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5422 		param[2] = FW_PARAM_PFVF(CQ_START);
5423 		param[3] = FW_PARAM_PFVF(CQ_END);
5424 		param[4] = FW_PARAM_PFVF(OCQ_START);
5425 		param[5] = FW_PARAM_PFVF(OCQ_END);
5426 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5427 		if (rc != 0) {
5428 			device_printf(sc->dev,
5429 			    "failed to query RDMA parameters(2): %d.\n", rc);
5430 			return (rc);
5431 		}
5432 		sc->vres.qp.start = val[0];
5433 		sc->vres.qp.size = val[1] - val[0] + 1;
5434 		sc->vres.cq.start = val[2];
5435 		sc->vres.cq.size = val[3] - val[2] + 1;
5436 		sc->vres.ocq.start = val[4];
5437 		sc->vres.ocq.size = val[5] - val[4] + 1;
5438 
5439 		param[0] = FW_PARAM_PFVF(SRQ_START);
5440 		param[1] = FW_PARAM_PFVF(SRQ_END);
5441 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5442 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5443 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5444 		if (rc != 0) {
5445 			device_printf(sc->dev,
5446 			    "failed to query RDMA parameters(3): %d.\n", rc);
5447 			return (rc);
5448 		}
5449 		sc->vres.srq.start = val[0];
5450 		sc->vres.srq.size = val[1] - val[0] + 1;
5451 		sc->params.max_ordird_qp = val[2];
5452 		sc->params.max_ird_adapter = val[3];
5453 	}
5454 	if (sc->iscsicaps) {
5455 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5456 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5457 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5458 		if (rc != 0) {
5459 			device_printf(sc->dev,
5460 			    "failed to query iSCSI parameters: %d.\n", rc);
5461 			return (rc);
5462 		}
5463 		sc->vres.iscsi.start = val[0];
5464 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5465 	}
5466 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5467 		param[0] = FW_PARAM_PFVF(TLS_START);
5468 		param[1] = FW_PARAM_PFVF(TLS_END);
5469 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5470 		if (rc != 0) {
5471 			device_printf(sc->dev,
5472 			    "failed to query TLS parameters: %d.\n", rc);
5473 			return (rc);
5474 		}
5475 		sc->vres.key.start = val[0];
5476 		sc->vres.key.size = val[1] - val[0] + 1;
5477 	}
5478 
5479 	/*
5480 	 * We've got the params we wanted to query directly from the firmware.
5481 	 * Grab some others via other means.
5482 	 */
5483 	t4_init_sge_params(sc);
5484 	t4_init_tp_params(sc);
5485 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5486 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5487 
5488 	rc = t4_verify_chip_settings(sc);
5489 	if (rc != 0)
5490 		return (rc);
5491 	t4_init_rx_buf_info(sc);
5492 
5493 	return (rc);
5494 }
5495 
5496 #ifdef KERN_TLS
5497 static void
5498 ktls_tick(void *arg)
5499 {
5500 	struct adapter *sc;
5501 	uint32_t tstamp;
5502 
5503 	sc = arg;
5504 	tstamp = tcp_ts_getticks();
5505 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5506 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5507 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5508 }
5509 
5510 static int
5511 t4_config_kern_tls(struct adapter *sc, bool enable)
5512 {
5513 	int rc;
5514 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5515 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5516 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5517 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5518 
5519 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5520 	if (rc != 0) {
5521 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5522 		    enable ?  "enable" : "disable", rc);
5523 		return (rc);
5524 	}
5525 
5526 	if (enable) {
5527 		sc->flags |= KERN_TLS_ON;
5528 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5529 		    C_HARDCLOCK);
5530 	} else {
5531 		sc->flags &= ~KERN_TLS_ON;
5532 		callout_stop(&sc->ktls_tick);
5533 	}
5534 
5535 	return (rc);
5536 }
5537 #endif
5538 
5539 static int
5540 set_params__post_init(struct adapter *sc)
5541 {
5542 	uint32_t mask, param, val;
5543 #ifdef TCP_OFFLOAD
5544 	int i, v, shift;
5545 #endif
5546 
5547 	/* ask for encapsulated CPLs */
5548 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5549 	val = 1;
5550 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5551 
5552 	/* Enable 32b port caps if the firmware supports it. */
5553 	param = FW_PARAM_PFVF(PORT_CAPS32);
5554 	val = 1;
5555 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5556 		sc->params.port_caps32 = 1;
5557 
5558 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5559 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5560 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5561 	    V_MASKFILTER(val - 1));
5562 
5563 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5564 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5565 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5566 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5567 	val = 0;
5568 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5569 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5570 		    F_ATTACKFILTERENABLE);
5571 		val |= F_DROPERRORATTACK;
5572 	}
5573 	if (t4_drop_ip_fragments != 0) {
5574 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5575 		    F_FRAGMENTDROP);
5576 		val |= F_DROPERRORFRAG;
5577 	}
5578 	if (t4_drop_pkts_with_l2_errors != 0)
5579 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5580 	if (t4_drop_pkts_with_l3_errors != 0) {
5581 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5582 		    F_DROPERRORCSUMIP;
5583 	}
5584 	if (t4_drop_pkts_with_l4_errors != 0) {
5585 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5586 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5587 	}
5588 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5589 
5590 #ifdef TCP_OFFLOAD
5591 	/*
5592 	 * Override the TOE timers with user provided tunables.  This is not the
5593 	 * recommended way to change the timers (the firmware config file is) so
5594 	 * these tunables are not documented.
5595 	 *
5596 	 * All the timer tunables are in microseconds.
5597 	 */
5598 	if (t4_toe_keepalive_idle != 0) {
5599 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5600 		v &= M_KEEPALIVEIDLE;
5601 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5602 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5603 	}
5604 	if (t4_toe_keepalive_interval != 0) {
5605 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5606 		v &= M_KEEPALIVEINTVL;
5607 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5608 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5609 	}
5610 	if (t4_toe_keepalive_count != 0) {
5611 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5612 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5613 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5614 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5615 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5616 	}
5617 	if (t4_toe_rexmt_min != 0) {
5618 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5619 		v &= M_RXTMIN;
5620 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5621 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5622 	}
5623 	if (t4_toe_rexmt_max != 0) {
5624 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5625 		v &= M_RXTMAX;
5626 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5627 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5628 	}
5629 	if (t4_toe_rexmt_count != 0) {
5630 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5631 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5632 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5633 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5634 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5635 	}
5636 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5637 		if (t4_toe_rexmt_backoff[i] != -1) {
5638 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5639 			shift = (i & 3) << 3;
5640 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5641 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5642 		}
5643 	}
5644 #endif
5645 
5646 #ifdef KERN_TLS
5647 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS &&
5648 	    sc->toecaps & FW_CAPS_CONFIG_TOE) {
5649 		/*
5650 		 * Limit TOE connections to 2 reassembly "islands".  This is
5651 		 * required for TOE TLS connections to downgrade to plain TOE
5652 		 * connections if an unsupported TLS version or ciphersuite is
5653 		 * used.
5654 		 */
5655 		t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG,
5656 		    V_PASSMODE(M_PASSMODE), V_PASSMODE(2));
5657 		if (is_ktls(sc)) {
5658 			sc->tlst.inline_keys = t4_tls_inline_keys;
5659 			sc->tlst.combo_wrs = t4_tls_combo_wrs;
5660 			if (t4_kern_tls != 0)
5661 				t4_config_kern_tls(sc, true);
5662 		}
5663 	}
5664 #endif
5665 	return (0);
5666 }
5667 
5668 #undef FW_PARAM_PFVF
5669 #undef FW_PARAM_DEV
5670 
5671 static void
5672 t4_set_desc(struct adapter *sc)
5673 {
5674 	char buf[128];
5675 	struct adapter_params *p = &sc->params;
5676 
5677 	snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
5678 
5679 	device_set_desc_copy(sc->dev, buf);
5680 }
5681 
5682 static inline void
5683 ifmedia_add4(struct ifmedia *ifm, int m)
5684 {
5685 
5686 	ifmedia_add(ifm, m, 0, NULL);
5687 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5688 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5689 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5690 }
5691 
5692 /*
5693  * This is the selected media, which is not quite the same as the active media.
5694  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5695  * and active are not the same, and "media: Ethernet selected" otherwise.
5696  */
5697 static void
5698 set_current_media(struct port_info *pi)
5699 {
5700 	struct link_config *lc;
5701 	struct ifmedia *ifm;
5702 	int mword;
5703 	u_int speed;
5704 
5705 	PORT_LOCK_ASSERT_OWNED(pi);
5706 
5707 	/* Leave current media alone if it's already set to IFM_NONE. */
5708 	ifm = &pi->media;
5709 	if (ifm->ifm_cur != NULL &&
5710 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5711 		return;
5712 
5713 	lc = &pi->link_cfg;
5714 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5715 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5716 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5717 		return;
5718 	}
5719 	mword = IFM_ETHER | IFM_FDX;
5720 	if (lc->requested_fc & PAUSE_TX)
5721 		mword |= IFM_ETH_TXPAUSE;
5722 	if (lc->requested_fc & PAUSE_RX)
5723 		mword |= IFM_ETH_RXPAUSE;
5724 	if (lc->requested_speed == 0)
5725 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5726 	else
5727 		speed = lc->requested_speed;
5728 	mword |= port_mword(pi, speed_to_fwcap(speed));
5729 	ifmedia_set(ifm, mword);
5730 }
5731 
5732 /*
5733  * Returns true if the ifmedia list for the port cannot change.
5734  */
5735 static bool
5736 fixed_ifmedia(struct port_info *pi)
5737 {
5738 
5739 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5740 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5741 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5742 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5743 	    pi->port_type == FW_PORT_TYPE_KX ||
5744 	    pi->port_type == FW_PORT_TYPE_KR ||
5745 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5746 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5747 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5748 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5749 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5750 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5751 }
5752 
5753 static void
5754 build_medialist(struct port_info *pi)
5755 {
5756 	uint32_t ss, speed;
5757 	int unknown, mword, bit;
5758 	struct link_config *lc;
5759 	struct ifmedia *ifm;
5760 
5761 	PORT_LOCK_ASSERT_OWNED(pi);
5762 
5763 	if (pi->flags & FIXED_IFMEDIA)
5764 		return;
5765 
5766 	/*
5767 	 * Rebuild the ifmedia list.
5768 	 */
5769 	ifm = &pi->media;
5770 	ifmedia_removeall(ifm);
5771 	lc = &pi->link_cfg;
5772 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5773 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5774 		MPASS(ss != 0);
5775 no_media:
5776 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5777 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5778 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5779 		return;
5780 	}
5781 
5782 	unknown = 0;
5783 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5784 		speed = 1 << bit;
5785 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5786 		if (ss & speed) {
5787 			mword = port_mword(pi, speed);
5788 			if (mword == IFM_NONE) {
5789 				goto no_media;
5790 			} else if (mword == IFM_UNKNOWN)
5791 				unknown++;
5792 			else
5793 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5794 		}
5795 	}
5796 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5797 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5798 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5799 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5800 
5801 	set_current_media(pi);
5802 }
5803 
5804 /*
5805  * Initialize the requested fields in the link config based on driver tunables.
5806  */
5807 static void
5808 init_link_config(struct port_info *pi)
5809 {
5810 	struct link_config *lc = &pi->link_cfg;
5811 
5812 	PORT_LOCK_ASSERT_OWNED(pi);
5813 
5814 	lc->requested_caps = 0;
5815 	lc->requested_speed = 0;
5816 
5817 	if (t4_autoneg == 0)
5818 		lc->requested_aneg = AUTONEG_DISABLE;
5819 	else if (t4_autoneg == 1)
5820 		lc->requested_aneg = AUTONEG_ENABLE;
5821 	else
5822 		lc->requested_aneg = AUTONEG_AUTO;
5823 
5824 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5825 	    PAUSE_AUTONEG);
5826 
5827 	if (t4_fec & FEC_AUTO)
5828 		lc->requested_fec = FEC_AUTO;
5829 	else if (t4_fec == 0)
5830 		lc->requested_fec = FEC_NONE;
5831 	else {
5832 		/* -1 is handled by the FEC_AUTO block above and not here. */
5833 		lc->requested_fec = t4_fec &
5834 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5835 		if (lc->requested_fec == 0)
5836 			lc->requested_fec = FEC_AUTO;
5837 	}
5838 	if (t4_force_fec < 0)
5839 		lc->force_fec = -1;
5840 	else if (t4_force_fec > 0)
5841 		lc->force_fec = 1;
5842 	else
5843 		lc->force_fec = 0;
5844 }
5845 
5846 /*
5847  * Makes sure that all requested settings comply with what's supported by the
5848  * port.  Returns the number of settings that were invalid and had to be fixed.
5849  */
5850 static int
5851 fixup_link_config(struct port_info *pi)
5852 {
5853 	int n = 0;
5854 	struct link_config *lc = &pi->link_cfg;
5855 	uint32_t fwspeed;
5856 
5857 	PORT_LOCK_ASSERT_OWNED(pi);
5858 
5859 	/* Speed (when not autonegotiating) */
5860 	if (lc->requested_speed != 0) {
5861 		fwspeed = speed_to_fwcap(lc->requested_speed);
5862 		if ((fwspeed & lc->pcaps) == 0) {
5863 			n++;
5864 			lc->requested_speed = 0;
5865 		}
5866 	}
5867 
5868 	/* Link autonegotiation */
5869 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5870 	    lc->requested_aneg == AUTONEG_DISABLE ||
5871 	    lc->requested_aneg == AUTONEG_AUTO);
5872 	if (lc->requested_aneg == AUTONEG_ENABLE &&
5873 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5874 		n++;
5875 		lc->requested_aneg = AUTONEG_AUTO;
5876 	}
5877 
5878 	/* Flow control */
5879 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5880 	if (lc->requested_fc & PAUSE_TX &&
5881 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5882 		n++;
5883 		lc->requested_fc &= ~PAUSE_TX;
5884 	}
5885 	if (lc->requested_fc & PAUSE_RX &&
5886 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
5887 		n++;
5888 		lc->requested_fc &= ~PAUSE_RX;
5889 	}
5890 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
5891 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
5892 		n++;
5893 		lc->requested_fc |= PAUSE_AUTONEG;
5894 	}
5895 
5896 	/* FEC */
5897 	if ((lc->requested_fec & FEC_RS &&
5898 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
5899 	    (lc->requested_fec & FEC_BASER_RS &&
5900 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
5901 		n++;
5902 		lc->requested_fec = FEC_AUTO;
5903 	}
5904 
5905 	return (n);
5906 }
5907 
5908 /*
5909  * Apply the requested L1 settings, which are expected to be valid, to the
5910  * hardware.
5911  */
5912 static int
5913 apply_link_config(struct port_info *pi)
5914 {
5915 	struct adapter *sc = pi->adapter;
5916 	struct link_config *lc = &pi->link_cfg;
5917 	int rc;
5918 
5919 #ifdef INVARIANTS
5920 	ASSERT_SYNCHRONIZED_OP(sc);
5921 	PORT_LOCK_ASSERT_OWNED(pi);
5922 
5923 	if (lc->requested_aneg == AUTONEG_ENABLE)
5924 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
5925 	if (!(lc->requested_fc & PAUSE_AUTONEG))
5926 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
5927 	if (lc->requested_fc & PAUSE_TX)
5928 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
5929 	if (lc->requested_fc & PAUSE_RX)
5930 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
5931 	if (lc->requested_fec & FEC_RS)
5932 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
5933 	if (lc->requested_fec & FEC_BASER_RS)
5934 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
5935 #endif
5936 	rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
5937 	if (rc != 0) {
5938 		/* Don't complain if the VF driver gets back an EPERM. */
5939 		if (!(sc->flags & IS_VF) || rc != FW_EPERM)
5940 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
5941 	} else {
5942 		/*
5943 		 * An L1_CFG will almost always result in a link-change event if
5944 		 * the link is up, and the driver will refresh the actual
5945 		 * fec/fc/etc. when the notification is processed.  If the link
5946 		 * is down then the actual settings are meaningless.
5947 		 *
5948 		 * This takes care of the case where a change in the L1 settings
5949 		 * may not result in a notification.
5950 		 */
5951 		if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
5952 			lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
5953 	}
5954 	return (rc);
5955 }
5956 
5957 #define FW_MAC_EXACT_CHUNK	7
5958 struct mcaddr_ctx {
5959 	struct ifnet *ifp;
5960 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
5961 	uint64_t hash;
5962 	int i;
5963 	int del;
5964 	int rc;
5965 };
5966 
5967 static u_int
5968 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
5969 {
5970 	struct mcaddr_ctx *ctx = arg;
5971 	struct vi_info *vi = ctx->ifp->if_softc;
5972 	struct port_info *pi = vi->pi;
5973 	struct adapter *sc = pi->adapter;
5974 
5975 	if (ctx->rc < 0)
5976 		return (0);
5977 
5978 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
5979 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
5980 	ctx->i++;
5981 
5982 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
5983 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
5984 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
5985 		if (ctx->rc < 0) {
5986 			int j;
5987 
5988 			for (j = 0; j < ctx->i; j++) {
5989 				if_printf(ctx->ifp,
5990 				    "failed to add mc address"
5991 				    " %02x:%02x:%02x:"
5992 				    "%02x:%02x:%02x rc=%d\n",
5993 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
5994 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
5995 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
5996 				    -ctx->rc);
5997 			}
5998 			return (0);
5999 		}
6000 		ctx->del = 0;
6001 		ctx->i = 0;
6002 	}
6003 
6004 	return (1);
6005 }
6006 
6007 /*
6008  * Program the port's XGMAC based on parameters in ifnet.  The caller also
6009  * indicates which parameters should be programmed (the rest are left alone).
6010  */
6011 int
6012 update_mac_settings(struct ifnet *ifp, int flags)
6013 {
6014 	int rc = 0;
6015 	struct vi_info *vi = ifp->if_softc;
6016 	struct port_info *pi = vi->pi;
6017 	struct adapter *sc = pi->adapter;
6018 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
6019 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
6020 
6021 	ASSERT_SYNCHRONIZED_OP(sc);
6022 	KASSERT(flags, ("%s: not told what to update.", __func__));
6023 
6024 	if (flags & XGMAC_MTU)
6025 		mtu = ifp->if_mtu;
6026 
6027 	if (flags & XGMAC_PROMISC)
6028 		promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
6029 
6030 	if (flags & XGMAC_ALLMULTI)
6031 		allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
6032 
6033 	if (flags & XGMAC_VLANEX)
6034 		vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
6035 
6036 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
6037 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
6038 		    allmulti, 1, vlanex, false);
6039 		if (rc) {
6040 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
6041 			    rc);
6042 			return (rc);
6043 		}
6044 	}
6045 
6046 	if (flags & XGMAC_UCADDR) {
6047 		uint8_t ucaddr[ETHER_ADDR_LEN];
6048 
6049 		bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
6050 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
6051 		    ucaddr, true, &vi->smt_idx);
6052 		if (rc < 0) {
6053 			rc = -rc;
6054 			if_printf(ifp, "change_mac failed: %d\n", rc);
6055 			return (rc);
6056 		} else {
6057 			vi->xact_addr_filt = rc;
6058 			rc = 0;
6059 		}
6060 	}
6061 
6062 	if (flags & XGMAC_MCADDRS) {
6063 		struct epoch_tracker et;
6064 		struct mcaddr_ctx ctx;
6065 		int j;
6066 
6067 		ctx.ifp = ifp;
6068 		ctx.hash = 0;
6069 		ctx.i = 0;
6070 		ctx.del = 1;
6071 		ctx.rc = 0;
6072 		/*
6073 		 * Unlike other drivers, we accumulate list of pointers into
6074 		 * interface address lists and we need to keep it safe even
6075 		 * after if_foreach_llmaddr() returns, thus we must enter the
6076 		 * network epoch.
6077 		 */
6078 		NET_EPOCH_ENTER(et);
6079 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6080 		if (ctx.rc < 0) {
6081 			NET_EPOCH_EXIT(et);
6082 			rc = -ctx.rc;
6083 			return (rc);
6084 		}
6085 		if (ctx.i > 0) {
6086 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6087 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6088 			NET_EPOCH_EXIT(et);
6089 			if (rc < 0) {
6090 				rc = -rc;
6091 				for (j = 0; j < ctx.i; j++) {
6092 					if_printf(ifp,
6093 					    "failed to add mcast address"
6094 					    " %02x:%02x:%02x:"
6095 					    "%02x:%02x:%02x rc=%d\n",
6096 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6097 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6098 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6099 					    rc);
6100 				}
6101 				return (rc);
6102 			}
6103 			ctx.del = 0;
6104 		} else
6105 			NET_EPOCH_EXIT(et);
6106 
6107 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6108 		if (rc != 0)
6109 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6110 			    rc);
6111 		if (ctx.del == 0) {
6112 			/* We clobbered the VXLAN entry if there was one. */
6113 			pi->vxlan_tcam_entry = false;
6114 		}
6115 	}
6116 
6117 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6118 	    pi->vxlan_tcam_entry == false) {
6119 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6120 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6121 		    true);
6122 		if (rc < 0) {
6123 			rc = -rc;
6124 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6125 			    rc);
6126 		} else {
6127 			MPASS(rc == sc->rawf_base + pi->port_id);
6128 			rc = 0;
6129 			pi->vxlan_tcam_entry = true;
6130 		}
6131 	}
6132 
6133 	return (rc);
6134 }
6135 
6136 /*
6137  * {begin|end}_synchronized_op must be called from the same thread.
6138  */
6139 int
6140 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6141     char *wmesg)
6142 {
6143 	int rc, pri;
6144 
6145 #ifdef WITNESS
6146 	/* the caller thinks it's ok to sleep, but is it really? */
6147 	if (flags & SLEEP_OK)
6148 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6149 		    "begin_synchronized_op");
6150 #endif
6151 
6152 	if (INTR_OK)
6153 		pri = PCATCH;
6154 	else
6155 		pri = 0;
6156 
6157 	ADAPTER_LOCK(sc);
6158 	for (;;) {
6159 
6160 		if (vi && IS_DOOMED(vi)) {
6161 			rc = ENXIO;
6162 			goto done;
6163 		}
6164 
6165 		if (!IS_BUSY(sc)) {
6166 			rc = 0;
6167 			break;
6168 		}
6169 
6170 		if (!(flags & SLEEP_OK)) {
6171 			rc = EBUSY;
6172 			goto done;
6173 		}
6174 
6175 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6176 			rc = EINTR;
6177 			goto done;
6178 		}
6179 	}
6180 
6181 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6182 	SET_BUSY(sc);
6183 #ifdef INVARIANTS
6184 	sc->last_op = wmesg;
6185 	sc->last_op_thr = curthread;
6186 	sc->last_op_flags = flags;
6187 #endif
6188 
6189 done:
6190 	if (!(flags & HOLD_LOCK) || rc)
6191 		ADAPTER_UNLOCK(sc);
6192 
6193 	return (rc);
6194 }
6195 
6196 /*
6197  * Tell if_ioctl and if_init that the VI is going away.  This is
6198  * special variant of begin_synchronized_op and must be paired with a
6199  * call to end_synchronized_op.
6200  */
6201 void
6202 doom_vi(struct adapter *sc, struct vi_info *vi)
6203 {
6204 
6205 	ADAPTER_LOCK(sc);
6206 	SET_DOOMED(vi);
6207 	wakeup(&sc->flags);
6208 	while (IS_BUSY(sc))
6209 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6210 	SET_BUSY(sc);
6211 #ifdef INVARIANTS
6212 	sc->last_op = "t4detach";
6213 	sc->last_op_thr = curthread;
6214 	sc->last_op_flags = 0;
6215 #endif
6216 	ADAPTER_UNLOCK(sc);
6217 }
6218 
6219 /*
6220  * {begin|end}_synchronized_op must be called from the same thread.
6221  */
6222 void
6223 end_synchronized_op(struct adapter *sc, int flags)
6224 {
6225 
6226 	if (flags & LOCK_HELD)
6227 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6228 	else
6229 		ADAPTER_LOCK(sc);
6230 
6231 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6232 	CLR_BUSY(sc);
6233 	wakeup(&sc->flags);
6234 	ADAPTER_UNLOCK(sc);
6235 }
6236 
6237 static int
6238 cxgbe_init_synchronized(struct vi_info *vi)
6239 {
6240 	struct port_info *pi = vi->pi;
6241 	struct adapter *sc = pi->adapter;
6242 	struct ifnet *ifp = vi->ifp;
6243 	int rc = 0, i;
6244 	struct sge_txq *txq;
6245 
6246 	ASSERT_SYNCHRONIZED_OP(sc);
6247 
6248 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
6249 		return (0);	/* already running */
6250 
6251 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6252 		return (rc);	/* error message displayed already */
6253 
6254 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6255 		return (rc); /* error message displayed already */
6256 
6257 	rc = update_mac_settings(ifp, XGMAC_ALL);
6258 	if (rc)
6259 		goto done;	/* error message displayed already */
6260 
6261 	PORT_LOCK(pi);
6262 	if (pi->up_vis == 0) {
6263 		t4_update_port_info(pi);
6264 		fixup_link_config(pi);
6265 		build_medialist(pi);
6266 		apply_link_config(pi);
6267 	}
6268 
6269 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6270 	if (rc != 0) {
6271 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6272 		PORT_UNLOCK(pi);
6273 		goto done;
6274 	}
6275 
6276 	/*
6277 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6278 	 * if this changes.
6279 	 */
6280 
6281 	for_each_txq(vi, i, txq) {
6282 		TXQ_LOCK(txq);
6283 		txq->eq.flags |= EQ_ENABLED;
6284 		TXQ_UNLOCK(txq);
6285 	}
6286 
6287 	/*
6288 	 * The first iq of the first port to come up is used for tracing.
6289 	 */
6290 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6291 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6292 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6293 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6294 		    V_QUEUENUMBER(sc->traceq));
6295 		pi->flags |= HAS_TRACEQ;
6296 	}
6297 
6298 	/* all ok */
6299 	pi->up_vis++;
6300 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
6301 	if (pi->link_cfg.link_ok)
6302 		t4_os_link_changed(pi);
6303 	PORT_UNLOCK(pi);
6304 
6305 	mtx_lock(&vi->tick_mtx);
6306 	if (ifp->if_get_counter == vi_get_counter)
6307 		callout_reset(&vi->tick, hz, vi_tick, vi);
6308 	else
6309 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6310 	mtx_unlock(&vi->tick_mtx);
6311 done:
6312 	if (rc != 0)
6313 		cxgbe_uninit_synchronized(vi);
6314 
6315 	return (rc);
6316 }
6317 
6318 /*
6319  * Idempotent.
6320  */
6321 static int
6322 cxgbe_uninit_synchronized(struct vi_info *vi)
6323 {
6324 	struct port_info *pi = vi->pi;
6325 	struct adapter *sc = pi->adapter;
6326 	struct ifnet *ifp = vi->ifp;
6327 	int rc, i;
6328 	struct sge_txq *txq;
6329 
6330 	ASSERT_SYNCHRONIZED_OP(sc);
6331 
6332 	if (!(vi->flags & VI_INIT_DONE)) {
6333 		if (__predict_false(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6334 			KASSERT(0, ("uninited VI is running"));
6335 			if_printf(ifp, "uninited VI with running ifnet.  "
6336 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6337 			    "if_drv_flags 0x%08x\n", vi->flags, ifp->if_flags,
6338 			    ifp->if_drv_flags);
6339 		}
6340 		return (0);
6341 	}
6342 
6343 	/*
6344 	 * Disable the VI so that all its data in either direction is discarded
6345 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6346 	 * tick) intact as the TP can deliver negative advice or data that it's
6347 	 * holding in its RAM (for an offloaded connection) even after the VI is
6348 	 * disabled.
6349 	 */
6350 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6351 	if (rc) {
6352 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6353 		return (rc);
6354 	}
6355 
6356 	for_each_txq(vi, i, txq) {
6357 		TXQ_LOCK(txq);
6358 		txq->eq.flags &= ~EQ_ENABLED;
6359 		TXQ_UNLOCK(txq);
6360 	}
6361 
6362 	mtx_lock(&vi->tick_mtx);
6363 	callout_stop(&vi->tick);
6364 	mtx_unlock(&vi->tick_mtx);
6365 
6366 	PORT_LOCK(pi);
6367 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6368 		PORT_UNLOCK(pi);
6369 		return (0);
6370 	}
6371 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
6372 	pi->up_vis--;
6373 	if (pi->up_vis > 0) {
6374 		PORT_UNLOCK(pi);
6375 		return (0);
6376 	}
6377 
6378 	pi->link_cfg.link_ok = false;
6379 	pi->link_cfg.speed = 0;
6380 	pi->link_cfg.link_down_rc = 255;
6381 	t4_os_link_changed(pi);
6382 	PORT_UNLOCK(pi);
6383 
6384 	return (0);
6385 }
6386 
6387 /*
6388  * It is ok for this function to fail midway and return right away.  t4_detach
6389  * will walk the entire sc->irq list and clean up whatever is valid.
6390  */
6391 int
6392 t4_setup_intr_handlers(struct adapter *sc)
6393 {
6394 	int rc, rid, p, q, v;
6395 	char s[8];
6396 	struct irq *irq;
6397 	struct port_info *pi;
6398 	struct vi_info *vi;
6399 	struct sge *sge = &sc->sge;
6400 	struct sge_rxq *rxq;
6401 #ifdef TCP_OFFLOAD
6402 	struct sge_ofld_rxq *ofld_rxq;
6403 #endif
6404 #ifdef DEV_NETMAP
6405 	struct sge_nm_rxq *nm_rxq;
6406 #endif
6407 #ifdef RSS
6408 	int nbuckets = rss_getnumbuckets();
6409 #endif
6410 
6411 	/*
6412 	 * Setup interrupts.
6413 	 */
6414 	irq = &sc->irq[0];
6415 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6416 	if (forwarding_intr_to_fwq(sc))
6417 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6418 
6419 	/* Multiple interrupts. */
6420 	if (sc->flags & IS_VF)
6421 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6422 		    ("%s: too few intr.", __func__));
6423 	else
6424 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6425 		    ("%s: too few intr.", __func__));
6426 
6427 	/* The first one is always error intr on PFs */
6428 	if (!(sc->flags & IS_VF)) {
6429 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6430 		if (rc != 0)
6431 			return (rc);
6432 		irq++;
6433 		rid++;
6434 	}
6435 
6436 	/* The second one is always the firmware event queue (first on VFs) */
6437 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6438 	if (rc != 0)
6439 		return (rc);
6440 	irq++;
6441 	rid++;
6442 
6443 	for_each_port(sc, p) {
6444 		pi = sc->port[p];
6445 		for_each_vi(pi, v, vi) {
6446 			vi->first_intr = rid - 1;
6447 
6448 			if (vi->nnmrxq > 0) {
6449 				int n = max(vi->nrxq, vi->nnmrxq);
6450 
6451 				rxq = &sge->rxq[vi->first_rxq];
6452 #ifdef DEV_NETMAP
6453 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6454 #endif
6455 				for (q = 0; q < n; q++) {
6456 					snprintf(s, sizeof(s), "%x%c%x", p,
6457 					    'a' + v, q);
6458 					if (q < vi->nrxq)
6459 						irq->rxq = rxq++;
6460 #ifdef DEV_NETMAP
6461 					if (q < vi->nnmrxq)
6462 						irq->nm_rxq = nm_rxq++;
6463 
6464 					if (irq->nm_rxq != NULL &&
6465 					    irq->rxq == NULL) {
6466 						/* Netmap rx only */
6467 						rc = t4_alloc_irq(sc, irq, rid,
6468 						    t4_nm_intr, irq->nm_rxq, s);
6469 					}
6470 					if (irq->nm_rxq != NULL &&
6471 					    irq->rxq != NULL) {
6472 						/* NIC and Netmap rx */
6473 						rc = t4_alloc_irq(sc, irq, rid,
6474 						    t4_vi_intr, irq, s);
6475 					}
6476 #endif
6477 					if (irq->rxq != NULL &&
6478 					    irq->nm_rxq == NULL) {
6479 						/* NIC rx only */
6480 						rc = t4_alloc_irq(sc, irq, rid,
6481 						    t4_intr, irq->rxq, s);
6482 					}
6483 					if (rc != 0)
6484 						return (rc);
6485 #ifdef RSS
6486 					if (q < vi->nrxq) {
6487 						bus_bind_intr(sc->dev, irq->res,
6488 						    rss_getcpu(q % nbuckets));
6489 					}
6490 #endif
6491 					irq++;
6492 					rid++;
6493 					vi->nintr++;
6494 				}
6495 			} else {
6496 				for_each_rxq(vi, q, rxq) {
6497 					snprintf(s, sizeof(s), "%x%c%x", p,
6498 					    'a' + v, q);
6499 					rc = t4_alloc_irq(sc, irq, rid,
6500 					    t4_intr, rxq, s);
6501 					if (rc != 0)
6502 						return (rc);
6503 #ifdef RSS
6504 					bus_bind_intr(sc->dev, irq->res,
6505 					    rss_getcpu(q % nbuckets));
6506 #endif
6507 					irq++;
6508 					rid++;
6509 					vi->nintr++;
6510 				}
6511 			}
6512 #ifdef TCP_OFFLOAD
6513 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6514 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6515 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6516 				    ofld_rxq, s);
6517 				if (rc != 0)
6518 					return (rc);
6519 				irq++;
6520 				rid++;
6521 				vi->nintr++;
6522 			}
6523 #endif
6524 		}
6525 	}
6526 	MPASS(irq == &sc->irq[sc->intr_count]);
6527 
6528 	return (0);
6529 }
6530 
6531 static void
6532 write_global_rss_key(struct adapter *sc)
6533 {
6534 #ifdef RSS
6535 	int i;
6536 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6537 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6538 
6539 	CTASSERT(RSS_KEYSIZE == 40);
6540 
6541 	rss_getkey((void *)&raw_rss_key[0]);
6542 	for (i = 0; i < nitems(rss_key); i++) {
6543 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6544 	}
6545 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6546 #endif
6547 }
6548 
6549 /*
6550  * Idempotent.
6551  */
6552 static int
6553 adapter_full_init(struct adapter *sc)
6554 {
6555 	int rc, i;
6556 
6557 	ASSERT_SYNCHRONIZED_OP(sc);
6558 
6559 	/*
6560 	 * queues that belong to the adapter (not any particular port).
6561 	 */
6562 	rc = t4_setup_adapter_queues(sc);
6563 	if (rc != 0)
6564 		return (rc);
6565 
6566 	for (i = 0; i < nitems(sc->tq); i++) {
6567 		if (sc->tq[i] != NULL)
6568 			continue;
6569 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6570 		    taskqueue_thread_enqueue, &sc->tq[i]);
6571 		if (sc->tq[i] == NULL) {
6572 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6573 			return (ENOMEM);
6574 		}
6575 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6576 		    device_get_nameunit(sc->dev), i);
6577 	}
6578 
6579 	if (!(sc->flags & IS_VF)) {
6580 		write_global_rss_key(sc);
6581 		t4_intr_enable(sc);
6582 	}
6583 	return (0);
6584 }
6585 
6586 int
6587 adapter_init(struct adapter *sc)
6588 {
6589 	int rc;
6590 
6591 	ASSERT_SYNCHRONIZED_OP(sc);
6592 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6593 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6594 	    ("%s: FULL_INIT_DONE already", __func__));
6595 
6596 	rc = adapter_full_init(sc);
6597 	if (rc != 0)
6598 		adapter_full_uninit(sc);
6599 	else
6600 		sc->flags |= FULL_INIT_DONE;
6601 
6602 	return (rc);
6603 }
6604 
6605 /*
6606  * Idempotent.
6607  */
6608 static void
6609 adapter_full_uninit(struct adapter *sc)
6610 {
6611 	int i;
6612 
6613 	t4_teardown_adapter_queues(sc);
6614 
6615 	for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
6616 		taskqueue_free(sc->tq[i]);
6617 		sc->tq[i] = NULL;
6618 	}
6619 
6620 	sc->flags &= ~FULL_INIT_DONE;
6621 }
6622 
6623 #ifdef RSS
6624 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6625     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6626     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6627     RSS_HASHTYPE_RSS_UDP_IPV6)
6628 
6629 /* Translates kernel hash types to hardware. */
6630 static int
6631 hashconfig_to_hashen(int hashconfig)
6632 {
6633 	int hashen = 0;
6634 
6635 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6636 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6637 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6638 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6639 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6640 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6641 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6642 	}
6643 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6644 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6645 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6646 	}
6647 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6648 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6649 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6650 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6651 
6652 	return (hashen);
6653 }
6654 
6655 /* Translates hardware hash types to kernel. */
6656 static int
6657 hashen_to_hashconfig(int hashen)
6658 {
6659 	int hashconfig = 0;
6660 
6661 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6662 		/*
6663 		 * If UDP hashing was enabled it must have been enabled for
6664 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6665 		 * enabling any 4-tuple hash is nonsense configuration.
6666 		 */
6667 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6668 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6669 
6670 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6671 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6672 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6673 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6674 	}
6675 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6676 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6677 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6678 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6679 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6680 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6681 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6682 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6683 
6684 	return (hashconfig);
6685 }
6686 #endif
6687 
6688 /*
6689  * Idempotent.
6690  */
6691 static int
6692 vi_full_init(struct vi_info *vi)
6693 {
6694 	struct adapter *sc = vi->adapter;
6695 	struct sge_rxq *rxq;
6696 	int rc, i, j;
6697 #ifdef RSS
6698 	int nbuckets = rss_getnumbuckets();
6699 	int hashconfig = rss_gethashconfig();
6700 	int extra;
6701 #endif
6702 
6703 	ASSERT_SYNCHRONIZED_OP(sc);
6704 
6705 	/*
6706 	 * Allocate tx/rx/fl queues for this VI.
6707 	 */
6708 	rc = t4_setup_vi_queues(vi);
6709 	if (rc != 0)
6710 		return (rc);
6711 
6712 	/*
6713 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6714 	 */
6715 	if (vi->nrxq > vi->rss_size) {
6716 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6717 		    "some queues will never receive traffic.\n", vi->nrxq,
6718 		    vi->rss_size);
6719 	} else if (vi->rss_size % vi->nrxq) {
6720 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6721 		    "expect uneven traffic distribution.\n", vi->nrxq,
6722 		    vi->rss_size);
6723 	}
6724 #ifdef RSS
6725 	if (vi->nrxq != nbuckets) {
6726 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6727 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6728 	}
6729 #endif
6730 	if (vi->rss == NULL)
6731 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6732 		    M_ZERO | M_WAITOK);
6733 	for (i = 0; i < vi->rss_size;) {
6734 #ifdef RSS
6735 		j = rss_get_indirection_to_bucket(i);
6736 		j %= vi->nrxq;
6737 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6738 		vi->rss[i++] = rxq->iq.abs_id;
6739 #else
6740 		for_each_rxq(vi, j, rxq) {
6741 			vi->rss[i++] = rxq->iq.abs_id;
6742 			if (i == vi->rss_size)
6743 				break;
6744 		}
6745 #endif
6746 	}
6747 
6748 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6749 	    vi->rss, vi->rss_size);
6750 	if (rc != 0) {
6751 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6752 		return (rc);
6753 	}
6754 
6755 #ifdef RSS
6756 	vi->hashen = hashconfig_to_hashen(hashconfig);
6757 
6758 	/*
6759 	 * We may have had to enable some hashes even though the global config
6760 	 * wants them disabled.  This is a potential problem that must be
6761 	 * reported to the user.
6762 	 */
6763 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6764 
6765 	/*
6766 	 * If we consider only the supported hash types, then the enabled hashes
6767 	 * are a superset of the requested hashes.  In other words, there cannot
6768 	 * be any supported hash that was requested but not enabled, but there
6769 	 * can be hashes that were not requested but had to be enabled.
6770 	 */
6771 	extra &= SUPPORTED_RSS_HASHTYPES;
6772 	MPASS((extra & hashconfig) == 0);
6773 
6774 	if (extra) {
6775 		CH_ALERT(vi,
6776 		    "global RSS config (0x%x) cannot be accommodated.\n",
6777 		    hashconfig);
6778 	}
6779 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6780 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6781 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6782 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6783 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6784 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6785 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6786 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6787 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6788 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6789 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6790 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6791 #else
6792 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6793 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6794 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6795 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6796 #endif
6797 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6798 	    0, 0);
6799 	if (rc != 0) {
6800 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6801 		return (rc);
6802 	}
6803 
6804 	return (0);
6805 }
6806 
6807 int
6808 vi_init(struct vi_info *vi)
6809 {
6810 	int rc;
6811 
6812 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6813 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6814 	    ("%s: VI_INIT_DONE already", __func__));
6815 
6816 	rc = vi_full_init(vi);
6817 	if (rc != 0)
6818 		vi_full_uninit(vi);
6819 	else
6820 		vi->flags |= VI_INIT_DONE;
6821 
6822 	return (rc);
6823 }
6824 
6825 /*
6826  * Idempotent.
6827  */
6828 static void
6829 vi_full_uninit(struct vi_info *vi)
6830 {
6831 
6832 	if (vi->flags & VI_INIT_DONE) {
6833 		quiesce_vi(vi);
6834 		free(vi->rss, M_CXGBE);
6835 		free(vi->nm_rss, M_CXGBE);
6836 	}
6837 
6838 	t4_teardown_vi_queues(vi);
6839 	vi->flags &= ~VI_INIT_DONE;
6840 }
6841 
6842 static void
6843 quiesce_txq(struct sge_txq *txq)
6844 {
6845 	struct sge_eq *eq = &txq->eq;
6846 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6847 
6848 	MPASS(eq->flags & EQ_SW_ALLOCATED);
6849 	MPASS(!(eq->flags & EQ_ENABLED));
6850 
6851 	/* Wait for the mp_ring to empty. */
6852 	while (!mp_ring_is_idle(txq->r)) {
6853 		mp_ring_check_drainage(txq->r, 4096);
6854 		pause("rquiesce", 1);
6855 	}
6856 	MPASS(txq->txp.npkt == 0);
6857 
6858 	if (eq->flags & EQ_HW_ALLOCATED) {
6859 		/*
6860 		 * Hardware is alive and working normally.  Wait for it to
6861 		 * finish and then wait for the driver to catch up and reclaim
6862 		 * all descriptors.
6863 		 */
6864 		while (spg->cidx != htobe16(eq->pidx))
6865 			pause("equiesce", 1);
6866 		while (eq->cidx != eq->pidx)
6867 			pause("dquiesce", 1);
6868 	} else {
6869 		/*
6870 		 * Hardware is unavailable.  Discard all pending tx and reclaim
6871 		 * descriptors directly.
6872 		 */
6873 		TXQ_LOCK(txq);
6874 		while (eq->cidx != eq->pidx) {
6875 			struct mbuf *m, *nextpkt;
6876 			struct tx_sdesc *txsd;
6877 
6878 			txsd = &txq->sdesc[eq->cidx];
6879 			for (m = txsd->m; m != NULL; m = nextpkt) {
6880 				nextpkt = m->m_nextpkt;
6881 				m->m_nextpkt = NULL;
6882 				m_freem(m);
6883 			}
6884 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
6885 		}
6886 		spg->pidx = spg->cidx = htobe16(eq->cidx);
6887 		TXQ_UNLOCK(txq);
6888 	}
6889 }
6890 
6891 static void
6892 quiesce_wrq(struct sge_wrq *wrq)
6893 {
6894 
6895 	/* XXXTX */
6896 }
6897 
6898 static void
6899 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
6900 {
6901 	/* Synchronize with the interrupt handler */
6902 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
6903 		pause("iqfree", 1);
6904 
6905 	if (fl != NULL) {
6906 		MPASS(iq->flags & IQ_HAS_FL);
6907 
6908 		mtx_lock(&sc->sfl_lock);
6909 		FL_LOCK(fl);
6910 		fl->flags |= FL_DOOMED;
6911 		FL_UNLOCK(fl);
6912 		callout_stop(&sc->sfl_callout);
6913 		mtx_unlock(&sc->sfl_lock);
6914 
6915 		KASSERT((fl->flags & FL_STARVING) == 0,
6916 		    ("%s: still starving", __func__));
6917 
6918 		/* Release all buffers if hardware is no longer available. */
6919 		if (!(iq->flags & IQ_HW_ALLOCATED))
6920 			free_fl_buffers(sc, fl);
6921 	}
6922 }
6923 
6924 /*
6925  * Wait for all activity on all the queues of the VI to complete.  It is assumed
6926  * that no new work is being enqueued by the hardware or the driver.  That part
6927  * should be arranged before calling this function.
6928  */
6929 static void
6930 quiesce_vi(struct vi_info *vi)
6931 {
6932 	int i;
6933 	struct adapter *sc = vi->adapter;
6934 	struct sge_rxq *rxq;
6935 	struct sge_txq *txq;
6936 #ifdef TCP_OFFLOAD
6937 	struct sge_ofld_rxq *ofld_rxq;
6938 #endif
6939 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6940 	struct sge_ofld_txq *ofld_txq;
6941 #endif
6942 
6943 	if (!(vi->flags & VI_INIT_DONE))
6944 		return;
6945 
6946 	for_each_txq(vi, i, txq) {
6947 		quiesce_txq(txq);
6948 	}
6949 
6950 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6951 	for_each_ofld_txq(vi, i, ofld_txq) {
6952 		quiesce_wrq(&ofld_txq->wrq);
6953 	}
6954 #endif
6955 
6956 	for_each_rxq(vi, i, rxq) {
6957 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
6958 	}
6959 
6960 #ifdef TCP_OFFLOAD
6961 	for_each_ofld_rxq(vi, i, ofld_rxq) {
6962 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
6963 	}
6964 #endif
6965 }
6966 
6967 static int
6968 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
6969     driver_intr_t *handler, void *arg, char *name)
6970 {
6971 	int rc;
6972 
6973 	irq->rid = rid;
6974 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
6975 	    RF_SHAREABLE | RF_ACTIVE);
6976 	if (irq->res == NULL) {
6977 		device_printf(sc->dev,
6978 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
6979 		return (ENOMEM);
6980 	}
6981 
6982 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
6983 	    NULL, handler, arg, &irq->tag);
6984 	if (rc != 0) {
6985 		device_printf(sc->dev,
6986 		    "failed to setup interrupt for rid %d, name %s: %d\n",
6987 		    rid, name, rc);
6988 	} else if (name)
6989 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
6990 
6991 	return (rc);
6992 }
6993 
6994 static int
6995 t4_free_irq(struct adapter *sc, struct irq *irq)
6996 {
6997 	if (irq->tag)
6998 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
6999 	if (irq->res)
7000 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
7001 
7002 	bzero(irq, sizeof(*irq));
7003 
7004 	return (0);
7005 }
7006 
7007 static void
7008 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
7009 {
7010 
7011 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
7012 	t4_get_regs(sc, buf, regs->len);
7013 }
7014 
7015 #define	A_PL_INDIR_CMD	0x1f8
7016 
7017 #define	S_PL_AUTOINC	31
7018 #define	M_PL_AUTOINC	0x1U
7019 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
7020 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
7021 
7022 #define	S_PL_VFID	20
7023 #define	M_PL_VFID	0xffU
7024 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
7025 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
7026 
7027 #define	S_PL_ADDR	0
7028 #define	M_PL_ADDR	0xfffffU
7029 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
7030 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
7031 
7032 #define	A_PL_INDIR_DATA	0x1fc
7033 
7034 static uint64_t
7035 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7036 {
7037 	u32 stats[2];
7038 
7039 	if (sc->flags & IS_VF) {
7040 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7041 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7042 	} else {
7043 		mtx_assert(&sc->reg_lock, MA_OWNED);
7044 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7045 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7046 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7047 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7048 	}
7049 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7050 }
7051 
7052 static void
7053 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7054 {
7055 
7056 #define GET_STAT(name) \
7057 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7058 
7059 	if (!(sc->flags & IS_VF))
7060 		mtx_lock(&sc->reg_lock);
7061 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7062 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7063 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7064 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7065 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7066 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7067 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7068 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7069 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7070 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7071 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7072 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7073 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7074 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7075 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7076 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7077 	if (!(sc->flags & IS_VF))
7078 		mtx_unlock(&sc->reg_lock);
7079 
7080 #undef GET_STAT
7081 }
7082 
7083 static void
7084 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7085 {
7086 	int reg;
7087 
7088 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7089 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7090 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7091 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7092 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7093 }
7094 
7095 static void
7096 vi_refresh_stats(struct vi_info *vi)
7097 {
7098 	struct timeval tv;
7099 	const struct timeval interval = {0, 250000};	/* 250ms */
7100 
7101 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7102 
7103 	if (vi->flags & VI_SKIP_STATS)
7104 		return;
7105 
7106 	getmicrotime(&tv);
7107 	timevalsub(&tv, &interval);
7108 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7109 		return;
7110 
7111 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7112 	getmicrotime(&vi->last_refreshed);
7113 }
7114 
7115 static void
7116 cxgbe_refresh_stats(struct vi_info *vi)
7117 {
7118 	u_int i, v, tnl_cong_drops, chan_map;
7119 	struct timeval tv;
7120 	const struct timeval interval = {0, 250000};	/* 250ms */
7121 	struct port_info *pi;
7122 	struct adapter *sc;
7123 
7124 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7125 
7126 	if (vi->flags & VI_SKIP_STATS)
7127 		return;
7128 
7129 	getmicrotime(&tv);
7130 	timevalsub(&tv, &interval);
7131 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7132 		return;
7133 
7134 	pi = vi->pi;
7135 	sc = vi->adapter;
7136 	tnl_cong_drops = 0;
7137 	t4_get_port_stats(sc, pi->port_id, &pi->stats);
7138 	chan_map = pi->rx_e_chan_map;
7139 	while (chan_map) {
7140 		i = ffs(chan_map) - 1;
7141 		mtx_lock(&sc->reg_lock);
7142 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7143 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7144 		mtx_unlock(&sc->reg_lock);
7145 		tnl_cong_drops += v;
7146 		chan_map &= ~(1 << i);
7147 	}
7148 	pi->tnl_cong_drops = tnl_cong_drops;
7149 	getmicrotime(&vi->last_refreshed);
7150 }
7151 
7152 static void
7153 cxgbe_tick(void *arg)
7154 {
7155 	struct vi_info *vi = arg;
7156 
7157 	MPASS(IS_MAIN_VI(vi));
7158 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7159 
7160 	cxgbe_refresh_stats(vi);
7161 	callout_schedule(&vi->tick, hz);
7162 }
7163 
7164 static void
7165 vi_tick(void *arg)
7166 {
7167 	struct vi_info *vi = arg;
7168 
7169 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7170 
7171 	vi_refresh_stats(vi);
7172 	callout_schedule(&vi->tick, hz);
7173 }
7174 
7175 /*
7176  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7177  */
7178 static char *caps_decoder[] = {
7179 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7180 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7181 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7182 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7183 	    "\006HASHFILTER\007ETHOFLD",
7184 	"\20\001TOE",					/* 4: TOE */
7185 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7186 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7187 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7188 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7189 	    "\007T10DIF"
7190 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7191 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7192 	    "\004TLS_HW",
7193 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7194 		    "\004PO_INITIATOR\005PO_TARGET",
7195 };
7196 
7197 void
7198 t4_sysctls(struct adapter *sc)
7199 {
7200 	struct sysctl_ctx_list *ctx = &sc->ctx;
7201 	struct sysctl_oid *oid;
7202 	struct sysctl_oid_list *children, *c0;
7203 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7204 
7205 	/*
7206 	 * dev.t4nex.X.
7207 	 */
7208 	oid = device_get_sysctl_tree(sc->dev);
7209 	c0 = children = SYSCTL_CHILDREN(oid);
7210 
7211 	sc->sc_do_rxcopy = 1;
7212 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7213 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7214 
7215 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7216 	    sc->params.nports, "# of ports");
7217 
7218 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7219 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7220 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7221 	    "available doorbells");
7222 
7223 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7224 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7225 
7226 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7227 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7228 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7229 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7230 
7231 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7232 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7233 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7234 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7235 
7236 	t4_sge_sysctls(sc, ctx, children);
7237 
7238 	sc->lro_timeout = 100;
7239 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7240 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7241 
7242 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7243 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7244 
7245 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7246 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7247 
7248 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7249 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7250 
7251 	if (sc->flags & IS_VF)
7252 		return;
7253 
7254 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7255 	    NULL, chip_rev(sc), "chip hardware revision");
7256 
7257 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7258 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7259 
7260 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7261 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7262 
7263 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7264 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7265 
7266 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7267 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7268 
7269 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7270 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7271 
7272 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7273 	    sc->er_version, 0, "expansion ROM version");
7274 
7275 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7276 	    sc->bs_version, 0, "bootstrap firmware version");
7277 
7278 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7279 	    NULL, sc->params.scfg_vers, "serial config version");
7280 
7281 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7282 	    NULL, sc->params.vpd_vers, "VPD version");
7283 
7284 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7285 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7286 
7287 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7288 	    sc->cfcsum, "config file checksum");
7289 
7290 #define SYSCTL_CAP(name, n, text) \
7291 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7292 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7293 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7294 	    "available " text " capabilities")
7295 
7296 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7297 	SYSCTL_CAP(linkcaps, 1, "link");
7298 	SYSCTL_CAP(switchcaps, 2, "switch");
7299 	SYSCTL_CAP(niccaps, 3, "NIC");
7300 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7301 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7302 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7303 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7304 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7305 #undef SYSCTL_CAP
7306 
7307 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7308 	    NULL, sc->tids.nftids, "number of filters");
7309 
7310 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7311 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7312 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7313 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7314 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7315 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7316 
7317 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7318 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7319 	    sysctl_loadavg, "A",
7320 	    "microprocessor load averages (debug firmwares only)");
7321 
7322 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7323 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7324 	    "I", "core Vdd (in mV)");
7325 
7326 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7327 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7328 	    sysctl_cpus, "A", "local CPUs");
7329 
7330 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7331 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7332 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7333 
7334 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7335 	    &sc->swintr, 0, "software triggered interrupts");
7336 
7337 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7338 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7339 	    "1 = reset adapter, 0 = zero reset counter");
7340 
7341 	/*
7342 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7343 	 */
7344 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7345 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7346 	    "logs and miscellaneous information");
7347 	children = SYSCTL_CHILDREN(oid);
7348 
7349 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7350 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7351 	    sysctl_cctrl, "A", "congestion control");
7352 
7353 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7354 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7355 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7356 
7357 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7358 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7359 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7360 
7361 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7362 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7363 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7364 
7365 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7366 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7367 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7368 
7369 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7370 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7371 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7372 
7373 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7374 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7375 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7376 
7377 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7378 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7379 	    sysctl_cim_la, "A", "CIM logic analyzer");
7380 
7381 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7382 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7383 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7384 
7385 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7386 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7387 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7388 
7389 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7390 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7391 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7392 
7393 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7394 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7395 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7396 
7397 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7398 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7399 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7400 
7401 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7402 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7403 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7404 
7405 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7406 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7407 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7408 
7409 	if (chip_id(sc) > CHELSIO_T4) {
7410 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7411 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7412 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7413 		    "CIM OBQ 6 (SGE0-RX)");
7414 
7415 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7416 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7417 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7418 		    "CIM OBQ 7 (SGE1-RX)");
7419 	}
7420 
7421 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7422 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7423 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7424 
7425 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7426 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7427 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7428 
7429 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7430 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7431 	    sysctl_cpl_stats, "A", "CPL statistics");
7432 
7433 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7434 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7435 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7436 
7437 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7438 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7439 	    sysctl_tid_stats, "A", "tid stats");
7440 
7441 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7442 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7443 	    sysctl_devlog, "A", "firmware's device log");
7444 
7445 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7446 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7447 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7448 
7449 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7450 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7451 	    sysctl_hw_sched, "A", "hardware scheduler ");
7452 
7453 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7454 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7455 	    sysctl_l2t, "A", "hardware L2 table");
7456 
7457 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7458 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7459 	    sysctl_smt, "A", "hardware source MAC table");
7460 
7461 #ifdef INET6
7462 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7463 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7464 	    sysctl_clip, "A", "active CLIP table entries");
7465 #endif
7466 
7467 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7468 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7469 	    sysctl_lb_stats, "A", "loopback statistics");
7470 
7471 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7472 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7473 	    sysctl_meminfo, "A", "memory regions");
7474 
7475 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7476 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7477 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7478 	    "A", "MPS TCAM entries");
7479 
7480 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7481 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7482 	    sysctl_path_mtus, "A", "path MTUs");
7483 
7484 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7485 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7486 	    sysctl_pm_stats, "A", "PM statistics");
7487 
7488 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7489 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7490 	    sysctl_rdma_stats, "A", "RDMA statistics");
7491 
7492 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7493 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7494 	    sysctl_tcp_stats, "A", "TCP statistics");
7495 
7496 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7497 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7498 	    sysctl_tids, "A", "TID information");
7499 
7500 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7501 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7502 	    sysctl_tp_err_stats, "A", "TP error statistics");
7503 
7504 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7505 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7506 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7507 
7508 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7509 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7510 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7511 
7512 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7513 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7514 	    sysctl_tp_la, "A", "TP logic analyzer");
7515 
7516 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7517 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7518 	    sysctl_tx_rate, "A", "Tx rate");
7519 
7520 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7521 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7522 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7523 
7524 	if (chip_id(sc) >= CHELSIO_T5) {
7525 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7526 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7527 		    sysctl_wcwr_stats, "A", "write combined work requests");
7528 	}
7529 
7530 #ifdef KERN_TLS
7531 	if (is_ktls(sc)) {
7532 		/*
7533 		 * dev.t4nex.0.tls.
7534 		 */
7535 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7536 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7537 		children = SYSCTL_CHILDREN(oid);
7538 
7539 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7540 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7541 		    "keys in work requests (1) or attempt to store TLS keys "
7542 		    "in card memory.");
7543 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7544 		    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to combine "
7545 		    "TCB field updates with TLS record work requests.");
7546 	}
7547 #endif
7548 
7549 #ifdef TCP_OFFLOAD
7550 	if (is_offload(sc)) {
7551 		int i;
7552 		char s[4];
7553 
7554 		/*
7555 		 * dev.t4nex.X.toe.
7556 		 */
7557 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7558 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7559 		children = SYSCTL_CHILDREN(oid);
7560 
7561 		sc->tt.cong_algorithm = -1;
7562 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7563 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7564 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7565 		    "3 = highspeed)");
7566 
7567 		sc->tt.sndbuf = -1;
7568 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7569 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7570 
7571 		sc->tt.ddp = 0;
7572 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7573 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7574 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7575 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7576 
7577 		sc->tt.rx_coalesce = -1;
7578 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7579 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7580 
7581 		sc->tt.tls = 0;
7582 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7583 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7584 		    "Inline TLS allowed");
7585 
7586 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_ports",
7587 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7588 		    sysctl_tls_rx_ports, "I",
7589 		    "TCP ports that use inline TLS+TOE RX");
7590 
7591 		sc->tt.tls_rx_timeout = t4_toe_tls_rx_timeout;
7592 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_timeout",
7593 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7594 		    sysctl_tls_rx_timeout, "I",
7595 		    "Timeout in seconds to downgrade TLS sockets to plain TOE");
7596 
7597 		sc->tt.tx_align = -1;
7598 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7599 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7600 
7601 		sc->tt.tx_zcopy = 0;
7602 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7603 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7604 		    "Enable zero-copy aio_write(2)");
7605 
7606 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7607 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7608 		    "cop_managed_offloading", CTLFLAG_RW,
7609 		    &sc->tt.cop_managed_offloading, 0,
7610 		    "COP (Connection Offload Policy) controls all TOE offload");
7611 
7612 		sc->tt.autorcvbuf_inc = 16 * 1024;
7613 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7614 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7615 		    "autorcvbuf increment");
7616 
7617 		sc->tt.update_hc_on_pmtu_change = 1;
7618 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7619 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7620 		    &sc->tt.update_hc_on_pmtu_change, 0,
7621 		    "Update hostcache entry if the PMTU changes");
7622 
7623 		sc->tt.iso = 1;
7624 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7625 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7626 
7627 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7628 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7629 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7630 
7631 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7632 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7633 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7634 
7635 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7636 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7637 		    sysctl_tp_tick, "A", "DACK tick (us)");
7638 
7639 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7640 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7641 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7642 
7643 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7644 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7645 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7646 		    "Minimum retransmit interval (us)");
7647 
7648 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7649 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7650 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7651 		    "Maximum retransmit interval (us)");
7652 
7653 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7654 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7655 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7656 		    "Persist timer min (us)");
7657 
7658 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7659 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7660 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7661 		    "Persist timer max (us)");
7662 
7663 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7664 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7665 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7666 		    "Keepalive idle timer (us)");
7667 
7668 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7669 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7670 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7671 		    "Keepalive interval timer (us)");
7672 
7673 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7674 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7675 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7676 
7677 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7678 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7679 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7680 		    "FINWAIT2 timer (us)");
7681 
7682 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7683 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7684 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7685 		    "Number of SYN retransmissions before abort");
7686 
7687 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7688 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7689 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7690 		    "Number of retransmissions before abort");
7691 
7692 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7693 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7694 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7695 		    "Number of keepalive probes before abort");
7696 
7697 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7698 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7699 		    "TOE retransmit backoffs");
7700 		children = SYSCTL_CHILDREN(oid);
7701 		for (i = 0; i < 16; i++) {
7702 			snprintf(s, sizeof(s), "%u", i);
7703 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7704 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7705 			    i, sysctl_tp_backoff, "IU",
7706 			    "TOE retransmit backoff");
7707 		}
7708 	}
7709 #endif
7710 }
7711 
7712 void
7713 vi_sysctls(struct vi_info *vi)
7714 {
7715 	struct sysctl_ctx_list *ctx = &vi->ctx;
7716 	struct sysctl_oid *oid;
7717 	struct sysctl_oid_list *children;
7718 
7719 	/*
7720 	 * dev.v?(cxgbe|cxl).X.
7721 	 */
7722 	oid = device_get_sysctl_tree(vi->dev);
7723 	children = SYSCTL_CHILDREN(oid);
7724 
7725 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7726 	    vi->viid, "VI identifer");
7727 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7728 	    &vi->nrxq, 0, "# of rx queues");
7729 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7730 	    &vi->ntxq, 0, "# of tx queues");
7731 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7732 	    &vi->first_rxq, 0, "index of first rx queue");
7733 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7734 	    &vi->first_txq, 0, "index of first tx queue");
7735 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7736 	    vi->rss_base, "start of RSS indirection table");
7737 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7738 	    vi->rss_size, "size of RSS indirection table");
7739 
7740 	if (IS_MAIN_VI(vi)) {
7741 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7742 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7743 		    sysctl_noflowq, "IU",
7744 		    "Reserve queue 0 for non-flowid packets");
7745 	}
7746 
7747 	if (vi->adapter->flags & IS_VF) {
7748 		MPASS(vi->flags & TX_USES_VM_WR);
7749 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7750 		    NULL, 1, "use VM work requests for transmit");
7751 	} else {
7752 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7753 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7754 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7755 	}
7756 
7757 #ifdef TCP_OFFLOAD
7758 	if (vi->nofldrxq != 0) {
7759 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7760 		    &vi->nofldrxq, 0,
7761 		    "# of rx queues for offloaded TCP connections");
7762 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7763 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7764 		    "index of first TOE rx queue");
7765 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7766 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7767 		    sysctl_holdoff_tmr_idx_ofld, "I",
7768 		    "holdoff timer index for TOE queues");
7769 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7770 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7771 		    sysctl_holdoff_pktc_idx_ofld, "I",
7772 		    "holdoff packet counter index for TOE queues");
7773 	}
7774 #endif
7775 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7776 	if (vi->nofldtxq != 0) {
7777 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7778 		    &vi->nofldtxq, 0,
7779 		    "# of tx queues for TOE/ETHOFLD");
7780 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7781 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7782 		    "index of first TOE/ETHOFLD tx queue");
7783 	}
7784 #endif
7785 #ifdef DEV_NETMAP
7786 	if (vi->nnmrxq != 0) {
7787 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7788 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7789 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7790 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7791 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7792 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7793 		    "index of first netmap rx queue");
7794 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7795 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7796 		    "index of first netmap tx queue");
7797 	}
7798 #endif
7799 
7800 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7801 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7802 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7803 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7804 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7805 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7806 
7807 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7808 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7809 	    sysctl_qsize_rxq, "I", "rx queue size");
7810 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7811 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7812 	    sysctl_qsize_txq, "I", "tx queue size");
7813 }
7814 
7815 static void
7816 cxgbe_sysctls(struct port_info *pi)
7817 {
7818 	struct sysctl_ctx_list *ctx = &pi->ctx;
7819 	struct sysctl_oid *oid;
7820 	struct sysctl_oid_list *children, *children2;
7821 	struct adapter *sc = pi->adapter;
7822 	int i;
7823 	char name[16];
7824 	static char *tc_flags = {"\20\1USER"};
7825 
7826 	/*
7827 	 * dev.cxgbe.X.
7828 	 */
7829 	oid = device_get_sysctl_tree(pi->dev);
7830 	children = SYSCTL_CHILDREN(oid);
7831 
7832 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7833 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7834 	    sysctl_linkdnrc, "A", "reason why link is down");
7835 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7836 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7837 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7838 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
7839 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7840 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7841 		    sysctl_btphy, "I", "PHY firmware version");
7842 	}
7843 
7844 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7845 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7846 	    sysctl_pause_settings, "A",
7847 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7848 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
7849 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
7850 	    "FEC in use on the link");
7851 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
7852 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7853 	    sysctl_requested_fec, "A",
7854 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7855 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7856 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7857 	    "FEC recommended by the cable/transceiver");
7858 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7859 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7860 	    sysctl_autoneg, "I",
7861 	    "autonegotiation (-1 = not supported)");
7862 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
7863 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7864 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
7865 
7866 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
7867 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
7868 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7869 	    &pi->link_cfg.pcaps, 0, "port capabilities");
7870 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7871 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
7872 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7873 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7874 
7875 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7876 	    port_top_speed(pi), "max speed (in Gbps)");
7877 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7878 	    pi->mps_bg_map, "MPS buffer group map");
7879 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
7880 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
7881 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_c_chan", CTLFLAG_RD, NULL,
7882 	    pi->rx_c_chan, "TP rx c-channel");
7883 
7884 	if (sc->flags & IS_VF)
7885 		return;
7886 
7887 	/*
7888 	 * dev.(cxgbe|cxl).X.tc.
7889 	 */
7890 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
7891 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7892 	    "Tx scheduler traffic classes (cl_rl)");
7893 	children2 = SYSCTL_CHILDREN(oid);
7894 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
7895 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
7896 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
7897 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
7898 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
7899 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
7900 	for (i = 0; i < sc->params.nsched_cls; i++) {
7901 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
7902 
7903 		snprintf(name, sizeof(name), "%d", i);
7904 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
7905 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
7906 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
7907 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
7908 		    CTLFLAG_RD, &tc->state, 0, "current state");
7909 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
7910 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
7911 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
7912 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
7913 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
7914 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
7915 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7916 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
7917 		    "traffic class parameters");
7918 	}
7919 
7920 	/*
7921 	 * dev.cxgbe.X.stats.
7922 	 */
7923 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
7924 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
7925 	children = SYSCTL_CHILDREN(oid);
7926 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
7927 	    &pi->tx_parse_error, 0,
7928 	    "# of tx packets with invalid length or # of segments");
7929 
7930 #define T4_REGSTAT(name, stat, desc) \
7931     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
7932         CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
7933 	(is_t4(sc) ? PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L) : \
7934 	T5_PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L)), \
7935         sysctl_handle_t4_reg64, "QU", desc)
7936 
7937 /* We get these from port_stats and they may be stale by up to 1s */
7938 #define T4_PORTSTAT(name, desc) \
7939 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
7940 	    &pi->stats.name, desc)
7941 
7942 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
7943 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
7944 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
7945 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
7946 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
7947 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
7948 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
7949 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
7950 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
7951 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
7952 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
7953 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
7954 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
7955 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
7956 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
7957 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
7958 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
7959 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
7960 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
7961 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
7962 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
7963 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
7964 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
7965 
7966 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
7967 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
7968 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
7969 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
7970 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
7971 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
7972 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
7973 	if (is_t6(sc)) {
7974 		T4_PORTSTAT(rx_fcs_err,
7975 		    "# of frames received with bad FCS since last link up");
7976 	} else {
7977 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
7978 		    "# of frames received with bad FCS");
7979 	}
7980 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
7981 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
7982 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
7983 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
7984 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
7985 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
7986 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
7987 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
7988 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
7989 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
7990 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
7991 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
7992 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
7993 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
7994 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
7995 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
7996 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
7997 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
7998 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
7999 
8000 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
8001 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
8002 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
8003 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
8004 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
8005 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
8006 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
8007 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
8008 
8009 #undef T4_REGSTAT
8010 #undef T4_PORTSTAT
8011 }
8012 
8013 static int
8014 sysctl_int_array(SYSCTL_HANDLER_ARGS)
8015 {
8016 	int rc, *i, space = 0;
8017 	struct sbuf sb;
8018 
8019 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
8020 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
8021 		if (space)
8022 			sbuf_printf(&sb, " ");
8023 		sbuf_printf(&sb, "%d", *i);
8024 		space = 1;
8025 	}
8026 	rc = sbuf_finish(&sb);
8027 	sbuf_delete(&sb);
8028 	return (rc);
8029 }
8030 
8031 static int
8032 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
8033 {
8034 	int rc;
8035 	struct sbuf *sb;
8036 
8037 	rc = sysctl_wire_old_buffer(req, 0);
8038 	if (rc != 0)
8039 		return(rc);
8040 
8041 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8042 	if (sb == NULL)
8043 		return (ENOMEM);
8044 
8045 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8046 	rc = sbuf_finish(sb);
8047 	sbuf_delete(sb);
8048 
8049 	return (rc);
8050 }
8051 
8052 static int
8053 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8054 {
8055 	int rc;
8056 	struct sbuf *sb;
8057 
8058 	rc = sysctl_wire_old_buffer(req, 0);
8059 	if (rc != 0)
8060 		return(rc);
8061 
8062 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8063 	if (sb == NULL)
8064 		return (ENOMEM);
8065 
8066 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8067 	rc = sbuf_finish(sb);
8068 	sbuf_delete(sb);
8069 
8070 	return (rc);
8071 }
8072 
8073 static int
8074 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8075 {
8076 	struct port_info *pi = arg1;
8077 	int op = arg2;
8078 	struct adapter *sc = pi->adapter;
8079 	u_int v;
8080 	int rc;
8081 
8082 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8083 	if (rc)
8084 		return (rc);
8085 	if (hw_off_limits(sc))
8086 		rc = ENXIO;
8087 	else {
8088 		/* XXX: magic numbers */
8089 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8090 		    op ? 0x20 : 0xc820, &v);
8091 	}
8092 	end_synchronized_op(sc, 0);
8093 	if (rc)
8094 		return (rc);
8095 	if (op == 0)
8096 		v /= 256;
8097 
8098 	rc = sysctl_handle_int(oidp, &v, 0, req);
8099 	return (rc);
8100 }
8101 
8102 static int
8103 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8104 {
8105 	struct vi_info *vi = arg1;
8106 	int rc, val;
8107 
8108 	val = vi->rsrv_noflowq;
8109 	rc = sysctl_handle_int(oidp, &val, 0, req);
8110 	if (rc != 0 || req->newptr == NULL)
8111 		return (rc);
8112 
8113 	if ((val >= 1) && (vi->ntxq > 1))
8114 		vi->rsrv_noflowq = 1;
8115 	else
8116 		vi->rsrv_noflowq = 0;
8117 
8118 	return (rc);
8119 }
8120 
8121 static int
8122 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8123 {
8124 	struct vi_info *vi = arg1;
8125 	struct adapter *sc = vi->adapter;
8126 	int rc, val, i;
8127 
8128 	MPASS(!(sc->flags & IS_VF));
8129 
8130 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8131 	rc = sysctl_handle_int(oidp, &val, 0, req);
8132 	if (rc != 0 || req->newptr == NULL)
8133 		return (rc);
8134 
8135 	if (val != 0 && val != 1)
8136 		return (EINVAL);
8137 
8138 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8139 	    "t4txvm");
8140 	if (rc)
8141 		return (rc);
8142 	if (hw_off_limits(sc))
8143 		rc = ENXIO;
8144 	else if (vi->ifp->if_drv_flags & IFF_DRV_RUNNING) {
8145 		/*
8146 		 * We don't want parse_pkt to run with one setting (VF or PF)
8147 		 * and then eth_tx to see a different setting but still use
8148 		 * stale information calculated by parse_pkt.
8149 		 */
8150 		rc = EBUSY;
8151 	} else {
8152 		struct port_info *pi = vi->pi;
8153 		struct sge_txq *txq;
8154 		uint32_t ctrl0;
8155 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8156 
8157 		if (val) {
8158 			vi->flags |= TX_USES_VM_WR;
8159 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
8160 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8161 			    V_TXPKT_INTF(pi->tx_chan));
8162 			if (!(sc->flags & IS_VF))
8163 				npkt--;
8164 		} else {
8165 			vi->flags &= ~TX_USES_VM_WR;
8166 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
8167 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8168 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8169 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8170 		}
8171 		for_each_txq(vi, i, txq) {
8172 			txq->cpl_ctrl0 = ctrl0;
8173 			txq->txp.max_npkt = npkt;
8174 		}
8175 	}
8176 	end_synchronized_op(sc, LOCK_HELD);
8177 	return (rc);
8178 }
8179 
8180 static int
8181 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8182 {
8183 	struct vi_info *vi = arg1;
8184 	struct adapter *sc = vi->adapter;
8185 	int idx, rc, i;
8186 	struct sge_rxq *rxq;
8187 	uint8_t v;
8188 
8189 	idx = vi->tmr_idx;
8190 
8191 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8192 	if (rc != 0 || req->newptr == NULL)
8193 		return (rc);
8194 
8195 	if (idx < 0 || idx >= SGE_NTIMERS)
8196 		return (EINVAL);
8197 
8198 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8199 	    "t4tmr");
8200 	if (rc)
8201 		return (rc);
8202 
8203 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8204 	for_each_rxq(vi, i, rxq) {
8205 #ifdef atomic_store_rel_8
8206 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8207 #else
8208 		rxq->iq.intr_params = v;
8209 #endif
8210 	}
8211 	vi->tmr_idx = idx;
8212 
8213 	end_synchronized_op(sc, LOCK_HELD);
8214 	return (0);
8215 }
8216 
8217 static int
8218 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8219 {
8220 	struct vi_info *vi = arg1;
8221 	struct adapter *sc = vi->adapter;
8222 	int idx, rc;
8223 
8224 	idx = vi->pktc_idx;
8225 
8226 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8227 	if (rc != 0 || req->newptr == NULL)
8228 		return (rc);
8229 
8230 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8231 		return (EINVAL);
8232 
8233 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8234 	    "t4pktc");
8235 	if (rc)
8236 		return (rc);
8237 
8238 	if (vi->flags & VI_INIT_DONE)
8239 		rc = EBUSY; /* cannot be changed once the queues are created */
8240 	else
8241 		vi->pktc_idx = idx;
8242 
8243 	end_synchronized_op(sc, LOCK_HELD);
8244 	return (rc);
8245 }
8246 
8247 static int
8248 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8249 {
8250 	struct vi_info *vi = arg1;
8251 	struct adapter *sc = vi->adapter;
8252 	int qsize, rc;
8253 
8254 	qsize = vi->qsize_rxq;
8255 
8256 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8257 	if (rc != 0 || req->newptr == NULL)
8258 		return (rc);
8259 
8260 	if (qsize < 128 || (qsize & 7))
8261 		return (EINVAL);
8262 
8263 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8264 	    "t4rxqs");
8265 	if (rc)
8266 		return (rc);
8267 
8268 	if (vi->flags & VI_INIT_DONE)
8269 		rc = EBUSY; /* cannot be changed once the queues are created */
8270 	else
8271 		vi->qsize_rxq = qsize;
8272 
8273 	end_synchronized_op(sc, LOCK_HELD);
8274 	return (rc);
8275 }
8276 
8277 static int
8278 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8279 {
8280 	struct vi_info *vi = arg1;
8281 	struct adapter *sc = vi->adapter;
8282 	int qsize, rc;
8283 
8284 	qsize = vi->qsize_txq;
8285 
8286 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8287 	if (rc != 0 || req->newptr == NULL)
8288 		return (rc);
8289 
8290 	if (qsize < 128 || qsize > 65536)
8291 		return (EINVAL);
8292 
8293 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8294 	    "t4txqs");
8295 	if (rc)
8296 		return (rc);
8297 
8298 	if (vi->flags & VI_INIT_DONE)
8299 		rc = EBUSY; /* cannot be changed once the queues are created */
8300 	else
8301 		vi->qsize_txq = qsize;
8302 
8303 	end_synchronized_op(sc, LOCK_HELD);
8304 	return (rc);
8305 }
8306 
8307 static int
8308 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8309 {
8310 	struct port_info *pi = arg1;
8311 	struct adapter *sc = pi->adapter;
8312 	struct link_config *lc = &pi->link_cfg;
8313 	int rc;
8314 
8315 	if (req->newptr == NULL) {
8316 		struct sbuf *sb;
8317 		static char *bits = "\20\1RX\2TX\3AUTO";
8318 
8319 		rc = sysctl_wire_old_buffer(req, 0);
8320 		if (rc != 0)
8321 			return(rc);
8322 
8323 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8324 		if (sb == NULL)
8325 			return (ENOMEM);
8326 
8327 		if (lc->link_ok) {
8328 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8329 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8330 		} else {
8331 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8332 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8333 		}
8334 		rc = sbuf_finish(sb);
8335 		sbuf_delete(sb);
8336 	} else {
8337 		char s[2];
8338 		int n;
8339 
8340 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8341 		    PAUSE_AUTONEG));
8342 		s[1] = 0;
8343 
8344 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8345 		if (rc != 0)
8346 			return(rc);
8347 
8348 		if (s[1] != 0)
8349 			return (EINVAL);
8350 		if (s[0] < '0' || s[0] > '9')
8351 			return (EINVAL);	/* not a number */
8352 		n = s[0] - '0';
8353 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8354 			return (EINVAL);	/* some other bit is set too */
8355 
8356 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8357 		    "t4PAUSE");
8358 		if (rc)
8359 			return (rc);
8360 		if (!hw_off_limits(sc)) {
8361 			PORT_LOCK(pi);
8362 			lc->requested_fc = n;
8363 			fixup_link_config(pi);
8364 			if (pi->up_vis > 0)
8365 				rc = apply_link_config(pi);
8366 			set_current_media(pi);
8367 			PORT_UNLOCK(pi);
8368 		}
8369 		end_synchronized_op(sc, 0);
8370 	}
8371 
8372 	return (rc);
8373 }
8374 
8375 static int
8376 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
8377 {
8378 	struct port_info *pi = arg1;
8379 	struct link_config *lc = &pi->link_cfg;
8380 	int rc;
8381 	struct sbuf *sb;
8382 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2";
8383 
8384 	rc = sysctl_wire_old_buffer(req, 0);
8385 	if (rc != 0)
8386 		return(rc);
8387 
8388 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8389 	if (sb == NULL)
8390 		return (ENOMEM);
8391 	if (lc->link_ok)
8392 		sbuf_printf(sb, "%b", lc->fec, bits);
8393 	else
8394 		sbuf_printf(sb, "no link");
8395 	rc = sbuf_finish(sb);
8396 	sbuf_delete(sb);
8397 
8398 	return (rc);
8399 }
8400 
8401 static int
8402 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
8403 {
8404 	struct port_info *pi = arg1;
8405 	struct adapter *sc = pi->adapter;
8406 	struct link_config *lc = &pi->link_cfg;
8407 	int rc;
8408 	int8_t old;
8409 
8410 	if (req->newptr == NULL) {
8411 		struct sbuf *sb;
8412 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8413 		    "\5RSVD3\6auto\7module";
8414 
8415 		rc = sysctl_wire_old_buffer(req, 0);
8416 		if (rc != 0)
8417 			return(rc);
8418 
8419 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8420 		if (sb == NULL)
8421 			return (ENOMEM);
8422 
8423 		sbuf_printf(sb, "%b", lc->requested_fec, bits);
8424 		rc = sbuf_finish(sb);
8425 		sbuf_delete(sb);
8426 	} else {
8427 		char s[8];
8428 		int n;
8429 
8430 		snprintf(s, sizeof(s), "%d",
8431 		    lc->requested_fec == FEC_AUTO ? -1 :
8432 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8433 
8434 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8435 		if (rc != 0)
8436 			return(rc);
8437 
8438 		n = strtol(&s[0], NULL, 0);
8439 		if (n < 0 || n & FEC_AUTO)
8440 			n = FEC_AUTO;
8441 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8442 			return (EINVAL);/* some other bit is set too */
8443 
8444 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8445 		    "t4reqf");
8446 		if (rc)
8447 			return (rc);
8448 		PORT_LOCK(pi);
8449 		old = lc->requested_fec;
8450 		if (n == FEC_AUTO)
8451 			lc->requested_fec = FEC_AUTO;
8452 		else if (n == 0 || n == FEC_NONE)
8453 			lc->requested_fec = FEC_NONE;
8454 		else {
8455 			if ((lc->pcaps |
8456 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8457 			    lc->pcaps) {
8458 				rc = ENOTSUP;
8459 				goto done;
8460 			}
8461 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8462 			    FEC_MODULE);
8463 		}
8464 		if (!hw_off_limits(sc)) {
8465 			fixup_link_config(pi);
8466 			if (pi->up_vis > 0) {
8467 				rc = apply_link_config(pi);
8468 				if (rc != 0) {
8469 					lc->requested_fec = old;
8470 					if (rc == FW_EPROTO)
8471 						rc = ENOTSUP;
8472 				}
8473 			}
8474 		}
8475 done:
8476 		PORT_UNLOCK(pi);
8477 		end_synchronized_op(sc, 0);
8478 	}
8479 
8480 	return (rc);
8481 }
8482 
8483 static int
8484 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8485 {
8486 	struct port_info *pi = arg1;
8487 	struct adapter *sc = pi->adapter;
8488 	struct link_config *lc = &pi->link_cfg;
8489 	int rc;
8490 	int8_t fec;
8491 	struct sbuf *sb;
8492 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8493 
8494 	rc = sysctl_wire_old_buffer(req, 0);
8495 	if (rc != 0)
8496 		return (rc);
8497 
8498 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8499 	if (sb == NULL)
8500 		return (ENOMEM);
8501 
8502 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8503 		rc = EBUSY;
8504 		goto done;
8505 	}
8506 	if (hw_off_limits(sc)) {
8507 		rc = ENXIO;
8508 		goto done;
8509 	}
8510 	PORT_LOCK(pi);
8511 	if (pi->up_vis == 0) {
8512 		/*
8513 		 * If all the interfaces are administratively down the firmware
8514 		 * does not report transceiver changes.  Refresh port info here.
8515 		 * This is the only reason we have a synchronized op in this
8516 		 * function.  Just PORT_LOCK would have been enough otherwise.
8517 		 */
8518 		t4_update_port_info(pi);
8519 	}
8520 
8521 	fec = lc->fec_hint;
8522 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8523 	    !fec_supported(lc->pcaps)) {
8524 		sbuf_printf(sb, "n/a");
8525 	} else {
8526 		if (fec == 0)
8527 			fec = FEC_NONE;
8528 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8529 	}
8530 	rc = sbuf_finish(sb);
8531 	PORT_UNLOCK(pi);
8532 done:
8533 	sbuf_delete(sb);
8534 	end_synchronized_op(sc, 0);
8535 
8536 	return (rc);
8537 }
8538 
8539 static int
8540 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8541 {
8542 	struct port_info *pi = arg1;
8543 	struct adapter *sc = pi->adapter;
8544 	struct link_config *lc = &pi->link_cfg;
8545 	int rc, val;
8546 
8547 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8548 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8549 	else
8550 		val = -1;
8551 	rc = sysctl_handle_int(oidp, &val, 0, req);
8552 	if (rc != 0 || req->newptr == NULL)
8553 		return (rc);
8554 	if (val == 0)
8555 		val = AUTONEG_DISABLE;
8556 	else if (val == 1)
8557 		val = AUTONEG_ENABLE;
8558 	else
8559 		val = AUTONEG_AUTO;
8560 
8561 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8562 	    "t4aneg");
8563 	if (rc)
8564 		return (rc);
8565 	PORT_LOCK(pi);
8566 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8567 		rc = ENOTSUP;
8568 		goto done;
8569 	}
8570 	lc->requested_aneg = val;
8571 	if (!hw_off_limits(sc)) {
8572 		fixup_link_config(pi);
8573 		if (pi->up_vis > 0)
8574 			rc = apply_link_config(pi);
8575 		set_current_media(pi);
8576 	}
8577 done:
8578 	PORT_UNLOCK(pi);
8579 	end_synchronized_op(sc, 0);
8580 	return (rc);
8581 }
8582 
8583 static int
8584 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
8585 {
8586 	struct port_info *pi = arg1;
8587 	struct adapter *sc = pi->adapter;
8588 	struct link_config *lc = &pi->link_cfg;
8589 	int rc, val;
8590 
8591 	val = lc->force_fec;
8592 	MPASS(val >= -1 && val <= 1);
8593 	rc = sysctl_handle_int(oidp, &val, 0, req);
8594 	if (rc != 0 || req->newptr == NULL)
8595 		return (rc);
8596 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
8597 		return (ENOTSUP);
8598 	if (val < -1 || val > 1)
8599 		return (EINVAL);
8600 
8601 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
8602 	if (rc)
8603 		return (rc);
8604 	PORT_LOCK(pi);
8605 	lc->force_fec = val;
8606 	if (!hw_off_limits(sc)) {
8607 		fixup_link_config(pi);
8608 		if (pi->up_vis > 0)
8609 			rc = apply_link_config(pi);
8610 	}
8611 	PORT_UNLOCK(pi);
8612 	end_synchronized_op(sc, 0);
8613 	return (rc);
8614 }
8615 
8616 static int
8617 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8618 {
8619 	struct adapter *sc = arg1;
8620 	int rc, reg = arg2;
8621 	uint64_t val;
8622 
8623 	mtx_lock(&sc->reg_lock);
8624 	if (hw_off_limits(sc))
8625 		rc = ENXIO;
8626 	else {
8627 		rc = 0;
8628 		val = t4_read_reg64(sc, reg);
8629 	}
8630 	mtx_unlock(&sc->reg_lock);
8631 	if (rc == 0)
8632 		rc = sysctl_handle_64(oidp, &val, 0, req);
8633 	return (rc);
8634 }
8635 
8636 static int
8637 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8638 {
8639 	struct adapter *sc = arg1;
8640 	int rc, t;
8641 	uint32_t param, val;
8642 
8643 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8644 	if (rc)
8645 		return (rc);
8646 	if (hw_off_limits(sc))
8647 		rc = ENXIO;
8648 	else {
8649 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8650 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8651 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8652 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8653 	}
8654 	end_synchronized_op(sc, 0);
8655 	if (rc)
8656 		return (rc);
8657 
8658 	/* unknown is returned as 0 but we display -1 in that case */
8659 	t = val == 0 ? -1 : val;
8660 
8661 	rc = sysctl_handle_int(oidp, &t, 0, req);
8662 	return (rc);
8663 }
8664 
8665 static int
8666 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8667 {
8668 	struct adapter *sc = arg1;
8669 	int rc;
8670 	uint32_t param, val;
8671 
8672 	if (sc->params.core_vdd == 0) {
8673 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8674 		    "t4vdd");
8675 		if (rc)
8676 			return (rc);
8677 		if (hw_off_limits(sc))
8678 			rc = ENXIO;
8679 		else {
8680 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8681 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8682 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8683 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8684 			    &param, &val);
8685 		}
8686 		end_synchronized_op(sc, 0);
8687 		if (rc)
8688 			return (rc);
8689 		sc->params.core_vdd = val;
8690 	}
8691 
8692 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8693 }
8694 
8695 static int
8696 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8697 {
8698 	struct adapter *sc = arg1;
8699 	int rc, v;
8700 	uint32_t param, val;
8701 
8702 	v = sc->sensor_resets;
8703 	rc = sysctl_handle_int(oidp, &v, 0, req);
8704 	if (rc != 0 || req->newptr == NULL || v <= 0)
8705 		return (rc);
8706 
8707 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8708 	    chip_id(sc) < CHELSIO_T5)
8709 		return (ENOTSUP);
8710 
8711 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8712 	if (rc)
8713 		return (rc);
8714 	if (hw_off_limits(sc))
8715 		rc = ENXIO;
8716 	else {
8717 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8718 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8719 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8720 		val = 1;
8721 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8722 	}
8723 	end_synchronized_op(sc, 0);
8724 	if (rc == 0)
8725 		sc->sensor_resets++;
8726 	return (rc);
8727 }
8728 
8729 static int
8730 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8731 {
8732 	struct adapter *sc = arg1;
8733 	struct sbuf *sb;
8734 	int rc;
8735 	uint32_t param, val;
8736 
8737 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8738 	if (rc)
8739 		return (rc);
8740 	if (hw_off_limits(sc))
8741 		rc = ENXIO;
8742 	else {
8743 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8744 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8745 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8746 	}
8747 	end_synchronized_op(sc, 0);
8748 	if (rc)
8749 		return (rc);
8750 
8751 	rc = sysctl_wire_old_buffer(req, 0);
8752 	if (rc != 0)
8753 		return (rc);
8754 
8755 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8756 	if (sb == NULL)
8757 		return (ENOMEM);
8758 
8759 	if (val == 0xffffffff) {
8760 		/* Only debug and custom firmwares report load averages. */
8761 		sbuf_printf(sb, "not available");
8762 	} else {
8763 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8764 		    (val >> 16) & 0xff);
8765 	}
8766 	rc = sbuf_finish(sb);
8767 	sbuf_delete(sb);
8768 
8769 	return (rc);
8770 }
8771 
8772 static int
8773 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8774 {
8775 	struct adapter *sc = arg1;
8776 	struct sbuf *sb;
8777 	int rc, i;
8778 	uint16_t incr[NMTUS][NCCTRL_WIN];
8779 	static const char *dec_fac[] = {
8780 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8781 		"0.9375"
8782 	};
8783 
8784 	rc = sysctl_wire_old_buffer(req, 0);
8785 	if (rc != 0)
8786 		return (rc);
8787 
8788 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8789 	if (sb == NULL)
8790 		return (ENOMEM);
8791 
8792 	mtx_lock(&sc->reg_lock);
8793 	if (hw_off_limits(sc))
8794 		rc = ENXIO;
8795 	else
8796 		t4_read_cong_tbl(sc, incr);
8797 	mtx_unlock(&sc->reg_lock);
8798 	if (rc)
8799 		goto done;
8800 
8801 	for (i = 0; i < NCCTRL_WIN; ++i) {
8802 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8803 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8804 		    incr[5][i], incr[6][i], incr[7][i]);
8805 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8806 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8807 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8808 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8809 	}
8810 
8811 	rc = sbuf_finish(sb);
8812 done:
8813 	sbuf_delete(sb);
8814 	return (rc);
8815 }
8816 
8817 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8818 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8819 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8820 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8821 };
8822 
8823 static int
8824 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8825 {
8826 	struct adapter *sc = arg1;
8827 	struct sbuf *sb;
8828 	int rc, i, n, qid = arg2;
8829 	uint32_t *buf, *p;
8830 	char *qtype;
8831 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8832 
8833 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8834 	    ("%s: bad qid %d\n", __func__, qid));
8835 
8836 	if (qid < CIM_NUM_IBQ) {
8837 		/* inbound queue */
8838 		qtype = "IBQ";
8839 		n = 4 * CIM_IBQ_SIZE;
8840 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8841 		mtx_lock(&sc->reg_lock);
8842 		if (hw_off_limits(sc))
8843 			rc = -ENXIO;
8844 		else
8845 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8846 		mtx_unlock(&sc->reg_lock);
8847 	} else {
8848 		/* outbound queue */
8849 		qtype = "OBQ";
8850 		qid -= CIM_NUM_IBQ;
8851 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8852 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8853 		mtx_lock(&sc->reg_lock);
8854 		if (hw_off_limits(sc))
8855 			rc = -ENXIO;
8856 		else
8857 			rc = t4_read_cim_obq(sc, qid, buf, n);
8858 		mtx_unlock(&sc->reg_lock);
8859 	}
8860 
8861 	if (rc < 0) {
8862 		rc = -rc;
8863 		goto done;
8864 	}
8865 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
8866 
8867 	rc = sysctl_wire_old_buffer(req, 0);
8868 	if (rc != 0)
8869 		goto done;
8870 
8871 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8872 	if (sb == NULL) {
8873 		rc = ENOMEM;
8874 		goto done;
8875 	}
8876 
8877 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8878 	for (i = 0, p = buf; i < n; i += 16, p += 4)
8879 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
8880 		    p[2], p[3]);
8881 
8882 	rc = sbuf_finish(sb);
8883 	sbuf_delete(sb);
8884 done:
8885 	free(buf, M_CXGBE);
8886 	return (rc);
8887 }
8888 
8889 static void
8890 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8891 {
8892 	uint32_t *p;
8893 
8894 	sbuf_printf(sb, "Status   Data      PC%s",
8895 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8896 	    "     LS0Stat  LS0Addr             LS0Data");
8897 
8898 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
8899 		if (cfg & F_UPDBGLACAPTPCONLY) {
8900 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
8901 			    p[6], p[7]);
8902 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
8903 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
8904 			    p[4] & 0xff, p[5] >> 8);
8905 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
8906 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8907 			    p[1] & 0xf, p[2] >> 4);
8908 		} else {
8909 			sbuf_printf(sb,
8910 			    "\n  %02x   %x%07x %x%07x %08x %08x "
8911 			    "%08x%08x%08x%08x",
8912 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8913 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
8914 			    p[6], p[7]);
8915 		}
8916 	}
8917 }
8918 
8919 static void
8920 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8921 {
8922 	uint32_t *p;
8923 
8924 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
8925 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8926 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
8927 
8928 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
8929 		if (cfg & F_UPDBGLACAPTPCONLY) {
8930 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
8931 			    p[3] & 0xff, p[2], p[1], p[0]);
8932 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
8933 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
8934 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
8935 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
8936 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
8937 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
8938 			    p[6] >> 16);
8939 		} else {
8940 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
8941 			    "%08x %08x %08x %08x %08x %08x",
8942 			    (p[9] >> 16) & 0xff,
8943 			    p[9] & 0xffff, p[8] >> 16,
8944 			    p[8] & 0xffff, p[7] >> 16,
8945 			    p[7] & 0xffff, p[6] >> 16,
8946 			    p[2], p[1], p[0], p[5], p[4], p[3]);
8947 		}
8948 	}
8949 }
8950 
8951 static int
8952 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
8953 {
8954 	uint32_t cfg, *buf;
8955 	int rc;
8956 
8957 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
8958 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
8959 	    M_ZERO | flags);
8960 	if (buf == NULL)
8961 		return (ENOMEM);
8962 
8963 	mtx_lock(&sc->reg_lock);
8964 	if (hw_off_limits(sc))
8965 		rc = ENXIO;
8966 	else {
8967 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
8968 		if (rc == 0)
8969 			rc = -t4_cim_read_la(sc, buf, NULL);
8970 	}
8971 	mtx_unlock(&sc->reg_lock);
8972 	if (rc == 0) {
8973 		if (chip_id(sc) < CHELSIO_T6)
8974 			sbuf_cim_la4(sc, sb, buf, cfg);
8975 		else
8976 			sbuf_cim_la6(sc, sb, buf, cfg);
8977 	}
8978 	free(buf, M_CXGBE);
8979 	return (rc);
8980 }
8981 
8982 static int
8983 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
8984 {
8985 	struct adapter *sc = arg1;
8986 	struct sbuf *sb;
8987 	int rc;
8988 
8989 	rc = sysctl_wire_old_buffer(req, 0);
8990 	if (rc != 0)
8991 		return (rc);
8992 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8993 	if (sb == NULL)
8994 		return (ENOMEM);
8995 
8996 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
8997 	if (rc == 0)
8998 		rc = sbuf_finish(sb);
8999 	sbuf_delete(sb);
9000 	return (rc);
9001 }
9002 
9003 static void
9004 dump_cim_regs(struct adapter *sc)
9005 {
9006 	log(LOG_DEBUG, "%s: CIM debug regs1 %08x %08x %08x %08x %08x\n",
9007 	    device_get_nameunit(sc->dev),
9008 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9009 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9010 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA2),
9011 	    t4_read_reg(sc, A_EDC_H_BIST_DATA_PATTERN),
9012 	    t4_read_reg(sc, A_EDC_H_BIST_STATUS_RDATA));
9013 	log(LOG_DEBUG, "%s: CIM debug regs2 %08x %08x %08x %08x %08x\n",
9014 	    device_get_nameunit(sc->dev),
9015 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9016 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9017 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0 + 0x800),
9018 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1 + 0x800),
9019 	    t4_read_reg(sc, A_EDC_H_BIST_CMD_LEN));
9020 }
9021 
9022 static void
9023 dump_cimla(struct adapter *sc)
9024 {
9025 	struct sbuf sb;
9026 	int rc;
9027 
9028 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9029 		log(LOG_DEBUG, "%s: failed to generate CIM LA dump.\n",
9030 		    device_get_nameunit(sc->dev));
9031 		return;
9032 	}
9033 	rc = sbuf_cim_la(sc, &sb, M_WAITOK);
9034 	if (rc == 0) {
9035 		rc = sbuf_finish(&sb);
9036 		if (rc == 0) {
9037 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s\n",
9038 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
9039 		}
9040 	}
9041 	sbuf_delete(&sb);
9042 }
9043 
9044 void
9045 t4_os_cim_err(struct adapter *sc)
9046 {
9047 	atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
9048 }
9049 
9050 static int
9051 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
9052 {
9053 	struct adapter *sc = arg1;
9054 	u_int i;
9055 	struct sbuf *sb;
9056 	uint32_t *buf, *p;
9057 	int rc;
9058 
9059 	rc = sysctl_wire_old_buffer(req, 0);
9060 	if (rc != 0)
9061 		return (rc);
9062 
9063 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9064 	if (sb == NULL)
9065 		return (ENOMEM);
9066 
9067 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
9068 	    M_ZERO | M_WAITOK);
9069 
9070 	mtx_lock(&sc->reg_lock);
9071 	if (hw_off_limits(sc))
9072 		rc = ENXIO;
9073 	else
9074 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
9075 	mtx_unlock(&sc->reg_lock);
9076 	if (rc)
9077 		goto done;
9078 
9079 	p = buf;
9080 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9081 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
9082 		    p[1], p[0]);
9083 	}
9084 
9085 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9086 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9087 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9088 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9089 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9090 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9091 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9092 		    p[0] & 1);
9093 	}
9094 	rc = sbuf_finish(sb);
9095 done:
9096 	sbuf_delete(sb);
9097 	free(buf, M_CXGBE);
9098 	return (rc);
9099 }
9100 
9101 static int
9102 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9103 {
9104 	struct adapter *sc = arg1;
9105 	u_int i;
9106 	struct sbuf *sb;
9107 	uint32_t *buf, *p;
9108 	int rc;
9109 
9110 	rc = sysctl_wire_old_buffer(req, 0);
9111 	if (rc != 0)
9112 		return (rc);
9113 
9114 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9115 	if (sb == NULL)
9116 		return (ENOMEM);
9117 
9118 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9119 	    M_ZERO | M_WAITOK);
9120 
9121 	mtx_lock(&sc->reg_lock);
9122 	if (hw_off_limits(sc))
9123 		rc = ENXIO;
9124 	else
9125 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9126 	mtx_unlock(&sc->reg_lock);
9127 	if (rc)
9128 		goto done;
9129 
9130 	p = buf;
9131 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9132 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9133 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9134 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9135 		    p[4], p[3], p[2], p[1], p[0]);
9136 	}
9137 
9138 	sbuf_printf(sb, "\n\nCntl ID               Data");
9139 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9140 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9141 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9142 	}
9143 
9144 	rc = sbuf_finish(sb);
9145 done:
9146 	sbuf_delete(sb);
9147 	free(buf, M_CXGBE);
9148 	return (rc);
9149 }
9150 
9151 static int
9152 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9153 {
9154 	struct adapter *sc = arg1;
9155 	struct sbuf *sb;
9156 	int rc, i;
9157 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9158 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9159 	uint16_t thres[CIM_NUM_IBQ];
9160 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9161 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9162 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9163 
9164 	cim_num_obq = sc->chip_params->cim_num_obq;
9165 	if (is_t4(sc)) {
9166 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9167 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9168 	} else {
9169 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9170 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9171 	}
9172 	nq = CIM_NUM_IBQ + cim_num_obq;
9173 
9174 	mtx_lock(&sc->reg_lock);
9175 	if (hw_off_limits(sc))
9176 		rc = ENXIO;
9177 	else {
9178 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9179 		if (rc == 0) {
9180 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9181 			    obq_wr);
9182 			if (rc == 0)
9183 				t4_read_cimq_cfg(sc, base, size, thres);
9184 		}
9185 	}
9186 	mtx_unlock(&sc->reg_lock);
9187 	if (rc)
9188 		return (rc);
9189 
9190 	rc = sysctl_wire_old_buffer(req, 0);
9191 	if (rc != 0)
9192 		return (rc);
9193 
9194 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9195 	if (sb == NULL)
9196 		return (ENOMEM);
9197 
9198 	sbuf_printf(sb,
9199 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9200 
9201 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9202 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9203 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9204 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9205 		    G_QUEREMFLITS(p[2]) * 16);
9206 	for ( ; i < nq; i++, p += 4, wr += 2)
9207 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9208 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9209 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9210 		    G_QUEREMFLITS(p[2]) * 16);
9211 
9212 	rc = sbuf_finish(sb);
9213 	sbuf_delete(sb);
9214 
9215 	return (rc);
9216 }
9217 
9218 static int
9219 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9220 {
9221 	struct adapter *sc = arg1;
9222 	struct sbuf *sb;
9223 	int rc;
9224 	struct tp_cpl_stats stats;
9225 
9226 	rc = sysctl_wire_old_buffer(req, 0);
9227 	if (rc != 0)
9228 		return (rc);
9229 
9230 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9231 	if (sb == NULL)
9232 		return (ENOMEM);
9233 
9234 	mtx_lock(&sc->reg_lock);
9235 	if (hw_off_limits(sc))
9236 		rc = ENXIO;
9237 	else
9238 		t4_tp_get_cpl_stats(sc, &stats, 0);
9239 	mtx_unlock(&sc->reg_lock);
9240 	if (rc)
9241 		goto done;
9242 
9243 	if (sc->chip_params->nchan > 2) {
9244 		sbuf_printf(sb, "                 channel 0  channel 1"
9245 		    "  channel 2  channel 3");
9246 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9247 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9248 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9249 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9250 	} else {
9251 		sbuf_printf(sb, "                 channel 0  channel 1");
9252 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9253 		    stats.req[0], stats.req[1]);
9254 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9255 		    stats.rsp[0], stats.rsp[1]);
9256 	}
9257 
9258 	rc = sbuf_finish(sb);
9259 done:
9260 	sbuf_delete(sb);
9261 	return (rc);
9262 }
9263 
9264 static int
9265 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9266 {
9267 	struct adapter *sc = arg1;
9268 	struct sbuf *sb;
9269 	int rc;
9270 	struct tp_usm_stats stats;
9271 
9272 	rc = sysctl_wire_old_buffer(req, 0);
9273 	if (rc != 0)
9274 		return(rc);
9275 
9276 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9277 	if (sb == NULL)
9278 		return (ENOMEM);
9279 
9280 	mtx_lock(&sc->reg_lock);
9281 	if (hw_off_limits(sc))
9282 		rc = ENXIO;
9283 	else
9284 		t4_get_usm_stats(sc, &stats, 1);
9285 	mtx_unlock(&sc->reg_lock);
9286 	if (rc == 0) {
9287 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9288 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9289 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9290 		rc = sbuf_finish(sb);
9291 	}
9292 	sbuf_delete(sb);
9293 
9294 	return (rc);
9295 }
9296 
9297 static int
9298 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9299 {
9300 	struct adapter *sc = arg1;
9301 	struct sbuf *sb;
9302 	int rc;
9303 	struct tp_tid_stats stats;
9304 
9305 	rc = sysctl_wire_old_buffer(req, 0);
9306 	if (rc != 0)
9307 		return(rc);
9308 
9309 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9310 	if (sb == NULL)
9311 		return (ENOMEM);
9312 
9313 	mtx_lock(&sc->reg_lock);
9314 	if (hw_off_limits(sc))
9315 		rc = ENXIO;
9316 	else
9317 		t4_tp_get_tid_stats(sc, &stats, 1);
9318 	mtx_unlock(&sc->reg_lock);
9319 	if (rc == 0) {
9320 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9321 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9322 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9323 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9324 		rc = sbuf_finish(sb);
9325 	}
9326 	sbuf_delete(sb);
9327 
9328 	return (rc);
9329 }
9330 
9331 static const char * const devlog_level_strings[] = {
9332 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9333 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9334 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9335 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9336 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9337 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9338 };
9339 
9340 static const char * const devlog_facility_strings[] = {
9341 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9342 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9343 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9344 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9345 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9346 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9347 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9348 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9349 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9350 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9351 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9352 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9353 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9354 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9355 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9356 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9357 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9358 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9359 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9360 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9361 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9362 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9363 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9364 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9365 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9366 };
9367 
9368 static int
9369 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9370 {
9371 	int i, j, rc, nentries, first = 0;
9372 	struct devlog_params *dparams = &sc->params.devlog;
9373 	struct fw_devlog_e *buf, *e;
9374 	uint64_t ftstamp = UINT64_MAX;
9375 
9376 	if (dparams->addr == 0)
9377 		return (ENXIO);
9378 
9379 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9380 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9381 	if (buf == NULL)
9382 		return (ENOMEM);
9383 
9384 	mtx_lock(&sc->reg_lock);
9385 	if (hw_off_limits(sc))
9386 		rc = ENXIO;
9387 	else
9388 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9389 		    dparams->size);
9390 	mtx_unlock(&sc->reg_lock);
9391 	if (rc != 0)
9392 		goto done;
9393 
9394 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9395 	for (i = 0; i < nentries; i++) {
9396 		e = &buf[i];
9397 
9398 		if (e->timestamp == 0)
9399 			break;	/* end */
9400 
9401 		e->timestamp = be64toh(e->timestamp);
9402 		e->seqno = be32toh(e->seqno);
9403 		for (j = 0; j < 8; j++)
9404 			e->params[j] = be32toh(e->params[j]);
9405 
9406 		if (e->timestamp < ftstamp) {
9407 			ftstamp = e->timestamp;
9408 			first = i;
9409 		}
9410 	}
9411 
9412 	if (buf[first].timestamp == 0)
9413 		goto done;	/* nothing in the log */
9414 
9415 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9416 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9417 
9418 	i = first;
9419 	do {
9420 		e = &buf[i];
9421 		if (e->timestamp == 0)
9422 			break;	/* end */
9423 
9424 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9425 		    e->seqno, e->timestamp,
9426 		    (e->level < nitems(devlog_level_strings) ?
9427 			devlog_level_strings[e->level] : "UNKNOWN"),
9428 		    (e->facility < nitems(devlog_facility_strings) ?
9429 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9430 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9431 		    e->params[2], e->params[3], e->params[4],
9432 		    e->params[5], e->params[6], e->params[7]);
9433 
9434 		if (++i == nentries)
9435 			i = 0;
9436 	} while (i != first);
9437 done:
9438 	free(buf, M_CXGBE);
9439 	return (rc);
9440 }
9441 
9442 static int
9443 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9444 {
9445 	struct adapter *sc = arg1;
9446 	int rc;
9447 	struct sbuf *sb;
9448 
9449 	rc = sysctl_wire_old_buffer(req, 0);
9450 	if (rc != 0)
9451 		return (rc);
9452 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9453 	if (sb == NULL)
9454 		return (ENOMEM);
9455 
9456 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9457 	if (rc == 0)
9458 		rc = sbuf_finish(sb);
9459 	sbuf_delete(sb);
9460 	return (rc);
9461 }
9462 
9463 static void
9464 dump_devlog(struct adapter *sc)
9465 {
9466 	int rc;
9467 	struct sbuf sb;
9468 
9469 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9470 		log(LOG_DEBUG, "%s: failed to generate devlog dump.\n",
9471 		    device_get_nameunit(sc->dev));
9472 		return;
9473 	}
9474 	rc = sbuf_devlog(sc, &sb, M_WAITOK);
9475 	if (rc == 0) {
9476 		rc = sbuf_finish(&sb);
9477 		if (rc == 0) {
9478 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9479 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
9480 		}
9481 	}
9482 	sbuf_delete(&sb);
9483 }
9484 
9485 static int
9486 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9487 {
9488 	struct adapter *sc = arg1;
9489 	struct sbuf *sb;
9490 	int rc;
9491 	struct tp_fcoe_stats stats[MAX_NCHAN];
9492 	int i, nchan = sc->chip_params->nchan;
9493 
9494 	rc = sysctl_wire_old_buffer(req, 0);
9495 	if (rc != 0)
9496 		return (rc);
9497 
9498 	mtx_lock(&sc->reg_lock);
9499 	if (hw_off_limits(sc))
9500 		rc = ENXIO;
9501 	else {
9502 		for (i = 0; i < nchan; i++)
9503 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9504 	}
9505 	mtx_unlock(&sc->reg_lock);
9506 	if (rc != 0)
9507 		return (rc);
9508 
9509 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9510 	if (sb == NULL)
9511 		return (ENOMEM);
9512 
9513 	if (nchan > 2) {
9514 		sbuf_printf(sb, "                   channel 0        channel 1"
9515 		    "        channel 2        channel 3");
9516 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9517 		    stats[0].octets_ddp, stats[1].octets_ddp,
9518 		    stats[2].octets_ddp, stats[3].octets_ddp);
9519 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9520 		    stats[0].frames_ddp, stats[1].frames_ddp,
9521 		    stats[2].frames_ddp, stats[3].frames_ddp);
9522 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9523 		    stats[0].frames_drop, stats[1].frames_drop,
9524 		    stats[2].frames_drop, stats[3].frames_drop);
9525 	} else {
9526 		sbuf_printf(sb, "                   channel 0        channel 1");
9527 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9528 		    stats[0].octets_ddp, stats[1].octets_ddp);
9529 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9530 		    stats[0].frames_ddp, stats[1].frames_ddp);
9531 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9532 		    stats[0].frames_drop, stats[1].frames_drop);
9533 	}
9534 
9535 	rc = sbuf_finish(sb);
9536 	sbuf_delete(sb);
9537 
9538 	return (rc);
9539 }
9540 
9541 static int
9542 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9543 {
9544 	struct adapter *sc = arg1;
9545 	struct sbuf *sb;
9546 	int rc, i;
9547 	unsigned int map, kbps, ipg, mode;
9548 	unsigned int pace_tab[NTX_SCHED];
9549 
9550 	rc = sysctl_wire_old_buffer(req, 0);
9551 	if (rc != 0)
9552 		return (rc);
9553 
9554 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9555 	if (sb == NULL)
9556 		return (ENOMEM);
9557 
9558 	mtx_lock(&sc->reg_lock);
9559 	if (hw_off_limits(sc)) {
9560 		rc = ENXIO;
9561 		goto done;
9562 	}
9563 
9564 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9565 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9566 	t4_read_pace_tbl(sc, pace_tab);
9567 
9568 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9569 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9570 
9571 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9572 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9573 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9574 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9575 		if (kbps)
9576 			sbuf_printf(sb, "%9u     ", kbps);
9577 		else
9578 			sbuf_printf(sb, " disabled     ");
9579 
9580 		if (ipg)
9581 			sbuf_printf(sb, "%13u        ", ipg);
9582 		else
9583 			sbuf_printf(sb, "     disabled        ");
9584 
9585 		if (pace_tab[i])
9586 			sbuf_printf(sb, "%10u", pace_tab[i]);
9587 		else
9588 			sbuf_printf(sb, "  disabled");
9589 	}
9590 	rc = sbuf_finish(sb);
9591 done:
9592 	mtx_unlock(&sc->reg_lock);
9593 	sbuf_delete(sb);
9594 	return (rc);
9595 }
9596 
9597 static int
9598 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9599 {
9600 	struct adapter *sc = arg1;
9601 	struct sbuf *sb;
9602 	int rc, i, j;
9603 	uint64_t *p0, *p1;
9604 	struct lb_port_stats s[2];
9605 	static const char *stat_name[] = {
9606 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9607 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9608 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9609 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9610 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9611 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9612 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9613 	};
9614 
9615 	rc = sysctl_wire_old_buffer(req, 0);
9616 	if (rc != 0)
9617 		return (rc);
9618 
9619 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9620 	if (sb == NULL)
9621 		return (ENOMEM);
9622 
9623 	memset(s, 0, sizeof(s));
9624 
9625 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9626 		mtx_lock(&sc->reg_lock);
9627 		if (hw_off_limits(sc))
9628 			rc = ENXIO;
9629 		else {
9630 			t4_get_lb_stats(sc, i, &s[0]);
9631 			t4_get_lb_stats(sc, i + 1, &s[1]);
9632 		}
9633 		mtx_unlock(&sc->reg_lock);
9634 		if (rc != 0)
9635 			break;
9636 
9637 		p0 = &s[0].octets;
9638 		p1 = &s[1].octets;
9639 		sbuf_printf(sb, "%s                       Loopback %u"
9640 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9641 
9642 		for (j = 0; j < nitems(stat_name); j++)
9643 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9644 				   *p0++, *p1++);
9645 	}
9646 
9647 	rc = sbuf_finish(sb);
9648 	sbuf_delete(sb);
9649 
9650 	return (rc);
9651 }
9652 
9653 static int
9654 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9655 {
9656 	int rc = 0;
9657 	struct port_info *pi = arg1;
9658 	struct link_config *lc = &pi->link_cfg;
9659 	struct sbuf *sb;
9660 
9661 	rc = sysctl_wire_old_buffer(req, 0);
9662 	if (rc != 0)
9663 		return(rc);
9664 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9665 	if (sb == NULL)
9666 		return (ENOMEM);
9667 
9668 	if (lc->link_ok || lc->link_down_rc == 255)
9669 		sbuf_printf(sb, "n/a");
9670 	else
9671 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9672 
9673 	rc = sbuf_finish(sb);
9674 	sbuf_delete(sb);
9675 
9676 	return (rc);
9677 }
9678 
9679 struct mem_desc {
9680 	u_int base;
9681 	u_int limit;
9682 	u_int idx;
9683 };
9684 
9685 static int
9686 mem_desc_cmp(const void *a, const void *b)
9687 {
9688 	const u_int v1 = ((const struct mem_desc *)a)->base;
9689 	const u_int v2 = ((const struct mem_desc *)b)->base;
9690 
9691 	if (v1 < v2)
9692 		return (-1);
9693 	else if (v1 > v2)
9694 		return (1);
9695 
9696 	return (0);
9697 }
9698 
9699 static void
9700 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9701     unsigned int to)
9702 {
9703 	unsigned int size;
9704 
9705 	if (from == to)
9706 		return;
9707 
9708 	size = to - from + 1;
9709 	if (size == 0)
9710 		return;
9711 
9712 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9713 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9714 }
9715 
9716 static int
9717 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9718 {
9719 	struct adapter *sc = arg1;
9720 	struct sbuf *sb;
9721 	int rc, i, n;
9722 	uint32_t lo, hi, used, free, alloc;
9723 	static const char *memory[] = {
9724 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9725 	};
9726 	static const char *region[] = {
9727 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9728 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9729 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9730 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9731 		"RQUDP region:", "PBL region:", "TXPBL region:",
9732 		"TLSKey region:", "DBVFIFO region:", "ULPRX state:",
9733 		"ULPTX state:", "On-chip queues:",
9734 	};
9735 	struct mem_desc avail[4];
9736 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9737 	struct mem_desc *md = mem;
9738 
9739 	rc = sysctl_wire_old_buffer(req, 0);
9740 	if (rc != 0)
9741 		return (rc);
9742 
9743 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9744 	if (sb == NULL)
9745 		return (ENOMEM);
9746 
9747 	for (i = 0; i < nitems(mem); i++) {
9748 		mem[i].limit = 0;
9749 		mem[i].idx = i;
9750 	}
9751 
9752 	mtx_lock(&sc->reg_lock);
9753 	if (hw_off_limits(sc)) {
9754 		rc = ENXIO;
9755 		goto done;
9756 	}
9757 
9758 	/* Find and sort the populated memory ranges */
9759 	i = 0;
9760 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9761 	if (lo & F_EDRAM0_ENABLE) {
9762 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9763 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9764 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9765 		avail[i].idx = 0;
9766 		i++;
9767 	}
9768 	if (lo & F_EDRAM1_ENABLE) {
9769 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9770 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9771 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9772 		avail[i].idx = 1;
9773 		i++;
9774 	}
9775 	if (lo & F_EXT_MEM_ENABLE) {
9776 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9777 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9778 		avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9779 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9780 		i++;
9781 	}
9782 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9783 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9784 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9785 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9786 		avail[i].idx = 4;
9787 		i++;
9788 	}
9789 	if (is_t6(sc) && lo & F_HMA_MUX) {
9790 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9791 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9792 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9793 		avail[i].idx = 5;
9794 		i++;
9795 	}
9796 	MPASS(i <= nitems(avail));
9797 	if (!i)                                    /* no memory available */
9798 		goto done;
9799 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9800 
9801 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9802 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9803 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9804 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9805 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9806 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9807 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9808 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9809 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9810 
9811 	/* the next few have explicit upper bounds */
9812 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9813 	md->limit = md->base - 1 +
9814 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9815 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9816 	md++;
9817 
9818 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9819 	md->limit = md->base - 1 +
9820 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9821 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9822 	md++;
9823 
9824 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9825 		if (chip_id(sc) <= CHELSIO_T5)
9826 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9827 		else
9828 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9829 		md->limit = 0;
9830 	} else {
9831 		md->base = 0;
9832 		md->idx = nitems(region);  /* hide it */
9833 	}
9834 	md++;
9835 
9836 #define ulp_region(reg) \
9837 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9838 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9839 
9840 	ulp_region(RX_ISCSI);
9841 	ulp_region(RX_TDDP);
9842 	ulp_region(TX_TPT);
9843 	ulp_region(RX_STAG);
9844 	ulp_region(RX_RQ);
9845 	ulp_region(RX_RQUDP);
9846 	ulp_region(RX_PBL);
9847 	ulp_region(TX_PBL);
9848 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
9849 		ulp_region(RX_TLS_KEY);
9850 	}
9851 #undef ulp_region
9852 
9853 	md->base = 0;
9854 	if (is_t4(sc))
9855 		md->idx = nitems(region);
9856 	else {
9857 		uint32_t size = 0;
9858 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9859 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9860 
9861 		if (is_t5(sc)) {
9862 			if (sge_ctrl & F_VFIFO_ENABLE)
9863 				size = fifo_size << 2;
9864 		} else
9865 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9866 
9867 		if (size) {
9868 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
9869 			md->limit = md->base + size - 1;
9870 		} else
9871 			md->idx = nitems(region);
9872 	}
9873 	md++;
9874 
9875 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9876 	md->limit = 0;
9877 	md++;
9878 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9879 	md->limit = 0;
9880 	md++;
9881 
9882 	md->base = sc->vres.ocq.start;
9883 	if (sc->vres.ocq.size)
9884 		md->limit = md->base + sc->vres.ocq.size - 1;
9885 	else
9886 		md->idx = nitems(region);  /* hide it */
9887 	md++;
9888 
9889 	/* add any address-space holes, there can be up to 3 */
9890 	for (n = 0; n < i - 1; n++)
9891 		if (avail[n].limit < avail[n + 1].base)
9892 			(md++)->base = avail[n].limit;
9893 	if (avail[n].limit)
9894 		(md++)->base = avail[n].limit;
9895 
9896 	n = md - mem;
9897 	MPASS(n <= nitems(mem));
9898 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
9899 
9900 	for (lo = 0; lo < i; lo++)
9901 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
9902 				avail[lo].limit - 1);
9903 
9904 	sbuf_printf(sb, "\n");
9905 	for (i = 0; i < n; i++) {
9906 		if (mem[i].idx >= nitems(region))
9907 			continue;                        /* skip holes */
9908 		if (!mem[i].limit)
9909 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
9910 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
9911 				mem[i].limit);
9912 	}
9913 
9914 	sbuf_printf(sb, "\n");
9915 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
9916 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
9917 	mem_region_show(sb, "uP RAM:", lo, hi);
9918 
9919 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
9920 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
9921 	mem_region_show(sb, "uP Extmem2:", lo, hi);
9922 
9923 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
9924 	for (i = 0, free = 0; i < 2; i++)
9925 		free += G_FREERXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_RX_CNT));
9926 	sbuf_printf(sb, "\n%u Rx pages (%u free) of size %uKiB for %u channels\n",
9927 		   G_PMRXMAXPAGE(lo), free,
9928 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
9929 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
9930 
9931 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
9932 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
9933 	for (i = 0, free = 0; i < 4; i++)
9934 		free += G_FREETXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_TX_CNT));
9935 	sbuf_printf(sb, "%u Tx pages (%u free) of size %u%ciB for %u channels\n",
9936 		   G_PMTXMAXPAGE(lo), free,
9937 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
9938 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
9939 	sbuf_printf(sb, "%u p-structs (%u free)\n",
9940 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT),
9941 		   G_FREEPSTRUCTCOUNT(t4_read_reg(sc, A_TP_FLM_FREE_PS_CNT)));
9942 
9943 	for (i = 0; i < 4; i++) {
9944 		if (chip_id(sc) > CHELSIO_T5)
9945 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
9946 		else
9947 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
9948 		if (is_t5(sc)) {
9949 			used = G_T5_USED(lo);
9950 			alloc = G_T5_ALLOC(lo);
9951 		} else {
9952 			used = G_USED(lo);
9953 			alloc = G_ALLOC(lo);
9954 		}
9955 		/* For T6 these are MAC buffer groups */
9956 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
9957 		    i, used, alloc);
9958 	}
9959 	for (i = 0; i < sc->chip_params->nchan; i++) {
9960 		if (chip_id(sc) > CHELSIO_T5)
9961 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
9962 		else
9963 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
9964 		if (is_t5(sc)) {
9965 			used = G_T5_USED(lo);
9966 			alloc = G_T5_ALLOC(lo);
9967 		} else {
9968 			used = G_USED(lo);
9969 			alloc = G_ALLOC(lo);
9970 		}
9971 		/* For T6 these are MAC buffer groups */
9972 		sbuf_printf(sb,
9973 		    "\nLoopback %d using %u pages out of %u allocated",
9974 		    i, used, alloc);
9975 	}
9976 done:
9977 	mtx_unlock(&sc->reg_lock);
9978 	if (rc == 0)
9979 		rc = sbuf_finish(sb);
9980 	sbuf_delete(sb);
9981 	return (rc);
9982 }
9983 
9984 static inline void
9985 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
9986 {
9987 	*mask = x | y;
9988 	y = htobe64(y);
9989 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
9990 }
9991 
9992 static int
9993 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
9994 {
9995 	struct adapter *sc = arg1;
9996 	struct sbuf *sb;
9997 	int rc, i;
9998 
9999 	MPASS(chip_id(sc) <= CHELSIO_T5);
10000 
10001 	rc = sysctl_wire_old_buffer(req, 0);
10002 	if (rc != 0)
10003 		return (rc);
10004 
10005 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10006 	if (sb == NULL)
10007 		return (ENOMEM);
10008 
10009 	sbuf_printf(sb,
10010 	    "Idx  Ethernet address     Mask     Vld Ports PF"
10011 	    "  VF              Replication             P0 P1 P2 P3  ML");
10012 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10013 		uint64_t tcamx, tcamy, mask;
10014 		uint32_t cls_lo, cls_hi;
10015 		uint8_t addr[ETHER_ADDR_LEN];
10016 
10017 		mtx_lock(&sc->reg_lock);
10018 		if (hw_off_limits(sc))
10019 			rc = ENXIO;
10020 		else {
10021 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
10022 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
10023 		}
10024 		mtx_unlock(&sc->reg_lock);
10025 		if (rc != 0)
10026 			break;
10027 		if (tcamx & tcamy)
10028 			continue;
10029 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10030 		mtx_lock(&sc->reg_lock);
10031 		if (hw_off_limits(sc))
10032 			rc = ENXIO;
10033 		else {
10034 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10035 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10036 		}
10037 		mtx_unlock(&sc->reg_lock);
10038 		if (rc != 0)
10039 			break;
10040 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
10041 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
10042 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
10043 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
10044 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
10045 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
10046 
10047 		if (cls_lo & F_REPLICATE) {
10048 			struct fw_ldst_cmd ldst_cmd;
10049 
10050 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10051 			ldst_cmd.op_to_addrspace =
10052 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10053 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10054 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10055 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10056 			ldst_cmd.u.mps.rplc.fid_idx =
10057 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10058 				V_FW_LDST_CMD_IDX(i));
10059 
10060 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10061 			    "t4mps");
10062 			if (rc)
10063 				break;
10064 			if (hw_off_limits(sc))
10065 				rc = ENXIO;
10066 			else
10067 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10068 				    sizeof(ldst_cmd), &ldst_cmd);
10069 			end_synchronized_op(sc, 0);
10070 			if (rc != 0)
10071 				break;
10072 			else {
10073 				sbuf_printf(sb, " %08x %08x %08x %08x",
10074 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10075 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10076 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10077 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10078 			}
10079 		} else
10080 			sbuf_printf(sb, "%36s", "");
10081 
10082 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
10083 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
10084 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
10085 	}
10086 
10087 	if (rc)
10088 		(void) sbuf_finish(sb);
10089 	else
10090 		rc = sbuf_finish(sb);
10091 	sbuf_delete(sb);
10092 
10093 	return (rc);
10094 }
10095 
10096 static int
10097 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
10098 {
10099 	struct adapter *sc = arg1;
10100 	struct sbuf *sb;
10101 	int rc, i;
10102 
10103 	MPASS(chip_id(sc) > CHELSIO_T5);
10104 
10105 	rc = sysctl_wire_old_buffer(req, 0);
10106 	if (rc != 0)
10107 		return (rc);
10108 
10109 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10110 	if (sb == NULL)
10111 		return (ENOMEM);
10112 
10113 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
10114 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
10115 	    "                           Replication"
10116 	    "                                    P0 P1 P2 P3  ML\n");
10117 
10118 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10119 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
10120 		uint16_t ivlan;
10121 		uint64_t tcamx, tcamy, val, mask;
10122 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10123 		uint8_t addr[ETHER_ADDR_LEN];
10124 
10125 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10126 		if (i < 256)
10127 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10128 		else
10129 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10130 		mtx_lock(&sc->reg_lock);
10131 		if (hw_off_limits(sc))
10132 			rc = ENXIO;
10133 		else {
10134 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10135 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10136 			tcamy = G_DMACH(val) << 32;
10137 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10138 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10139 		}
10140 		mtx_unlock(&sc->reg_lock);
10141 		if (rc != 0)
10142 			break;
10143 
10144 		lookup_type = G_DATALKPTYPE(data2);
10145 		port_num = G_DATAPORTNUM(data2);
10146 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10147 			/* Inner header VNI */
10148 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10149 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10150 			dip_hit = data2 & F_DATADIPHIT;
10151 			vlan_vld = 0;
10152 		} else {
10153 			vniy = 0;
10154 			dip_hit = 0;
10155 			vlan_vld = data2 & F_DATAVIDH2;
10156 			ivlan = G_VIDL(val);
10157 		}
10158 
10159 		ctl |= V_CTLXYBITSEL(1);
10160 		mtx_lock(&sc->reg_lock);
10161 		if (hw_off_limits(sc))
10162 			rc = ENXIO;
10163 		else {
10164 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10165 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10166 			tcamx = G_DMACH(val) << 32;
10167 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10168 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10169 		}
10170 		mtx_unlock(&sc->reg_lock);
10171 		if (rc != 0)
10172 			break;
10173 
10174 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10175 			/* Inner header VNI mask */
10176 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10177 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10178 		} else
10179 			vnix = 0;
10180 
10181 		if (tcamx & tcamy)
10182 			continue;
10183 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10184 
10185 		mtx_lock(&sc->reg_lock);
10186 		if (hw_off_limits(sc))
10187 			rc = ENXIO;
10188 		else {
10189 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10190 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10191 		}
10192 		mtx_unlock(&sc->reg_lock);
10193 		if (rc != 0)
10194 			break;
10195 
10196 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10197 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10198 			    "%012jx %06x %06x    -    -   %3c"
10199 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10200 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10201 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10202 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10203 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10204 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10205 		} else {
10206 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10207 			    "%012jx    -       -   ", i, addr[0], addr[1],
10208 			    addr[2], addr[3], addr[4], addr[5],
10209 			    (uintmax_t)mask);
10210 
10211 			if (vlan_vld)
10212 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10213 			else
10214 				sbuf_printf(sb, "  -    N     ");
10215 
10216 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10217 			    lookup_type ? 'I' : 'O', port_num,
10218 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10219 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10220 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10221 		}
10222 
10223 
10224 		if (cls_lo & F_T6_REPLICATE) {
10225 			struct fw_ldst_cmd ldst_cmd;
10226 
10227 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10228 			ldst_cmd.op_to_addrspace =
10229 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10230 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10231 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10232 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10233 			ldst_cmd.u.mps.rplc.fid_idx =
10234 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10235 				V_FW_LDST_CMD_IDX(i));
10236 
10237 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10238 			    "t6mps");
10239 			if (rc)
10240 				break;
10241 			if (hw_off_limits(sc))
10242 				rc = ENXIO;
10243 			else
10244 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10245 				    sizeof(ldst_cmd), &ldst_cmd);
10246 			end_synchronized_op(sc, 0);
10247 			if (rc != 0)
10248 				break;
10249 			else {
10250 				sbuf_printf(sb, " %08x %08x %08x %08x"
10251 				    " %08x %08x %08x %08x",
10252 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10253 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10254 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10255 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10256 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10257 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10258 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10259 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10260 			}
10261 		} else
10262 			sbuf_printf(sb, "%72s", "");
10263 
10264 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10265 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10266 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10267 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10268 	}
10269 
10270 	if (rc)
10271 		(void) sbuf_finish(sb);
10272 	else
10273 		rc = sbuf_finish(sb);
10274 	sbuf_delete(sb);
10275 
10276 	return (rc);
10277 }
10278 
10279 static int
10280 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10281 {
10282 	struct adapter *sc = arg1;
10283 	struct sbuf *sb;
10284 	int rc;
10285 	uint16_t mtus[NMTUS];
10286 
10287 	rc = sysctl_wire_old_buffer(req, 0);
10288 	if (rc != 0)
10289 		return (rc);
10290 
10291 	mtx_lock(&sc->reg_lock);
10292 	if (hw_off_limits(sc))
10293 		rc = ENXIO;
10294 	else
10295 		t4_read_mtu_tbl(sc, mtus, NULL);
10296 	mtx_unlock(&sc->reg_lock);
10297 	if (rc != 0)
10298 		return (rc);
10299 
10300 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10301 	if (sb == NULL)
10302 		return (ENOMEM);
10303 
10304 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10305 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10306 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10307 	    mtus[14], mtus[15]);
10308 
10309 	rc = sbuf_finish(sb);
10310 	sbuf_delete(sb);
10311 
10312 	return (rc);
10313 }
10314 
10315 static int
10316 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10317 {
10318 	struct adapter *sc = arg1;
10319 	struct sbuf *sb;
10320 	int rc, i;
10321 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10322 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10323 	static const char *tx_stats[MAX_PM_NSTATS] = {
10324 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10325 		"Tx FIFO wait", NULL, "Tx latency"
10326 	};
10327 	static const char *rx_stats[MAX_PM_NSTATS] = {
10328 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10329 		"Rx FIFO wait", NULL, "Rx latency"
10330 	};
10331 
10332 	rc = sysctl_wire_old_buffer(req, 0);
10333 	if (rc != 0)
10334 		return (rc);
10335 
10336 	mtx_lock(&sc->reg_lock);
10337 	if (hw_off_limits(sc))
10338 		rc = ENXIO;
10339 	else {
10340 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10341 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10342 	}
10343 	mtx_unlock(&sc->reg_lock);
10344 	if (rc != 0)
10345 		return (rc);
10346 
10347 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10348 	if (sb == NULL)
10349 		return (ENOMEM);
10350 
10351 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10352 	for (i = 0; i < 4; i++) {
10353 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10354 		    tx_cyc[i]);
10355 	}
10356 
10357 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10358 	for (i = 0; i < 4; i++) {
10359 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10360 		    rx_cyc[i]);
10361 	}
10362 
10363 	if (chip_id(sc) > CHELSIO_T5) {
10364 		sbuf_printf(sb,
10365 		    "\n              Total wait      Total occupancy");
10366 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10367 		    tx_cyc[i]);
10368 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10369 		    rx_cyc[i]);
10370 
10371 		i += 2;
10372 		MPASS(i < nitems(tx_stats));
10373 
10374 		sbuf_printf(sb,
10375 		    "\n                   Reads           Total wait");
10376 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10377 		    tx_cyc[i]);
10378 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10379 		    rx_cyc[i]);
10380 	}
10381 
10382 	rc = sbuf_finish(sb);
10383 	sbuf_delete(sb);
10384 
10385 	return (rc);
10386 }
10387 
10388 static int
10389 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10390 {
10391 	struct adapter *sc = arg1;
10392 	struct sbuf *sb;
10393 	int rc;
10394 	struct tp_rdma_stats stats;
10395 
10396 	rc = sysctl_wire_old_buffer(req, 0);
10397 	if (rc != 0)
10398 		return (rc);
10399 
10400 	mtx_lock(&sc->reg_lock);
10401 	if (hw_off_limits(sc))
10402 		rc = ENXIO;
10403 	else
10404 		t4_tp_get_rdma_stats(sc, &stats, 0);
10405 	mtx_unlock(&sc->reg_lock);
10406 	if (rc != 0)
10407 		return (rc);
10408 
10409 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10410 	if (sb == NULL)
10411 		return (ENOMEM);
10412 
10413 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10414 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10415 
10416 	rc = sbuf_finish(sb);
10417 	sbuf_delete(sb);
10418 
10419 	return (rc);
10420 }
10421 
10422 static int
10423 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10424 {
10425 	struct adapter *sc = arg1;
10426 	struct sbuf *sb;
10427 	int rc;
10428 	struct tp_tcp_stats v4, v6;
10429 
10430 	rc = sysctl_wire_old_buffer(req, 0);
10431 	if (rc != 0)
10432 		return (rc);
10433 
10434 	mtx_lock(&sc->reg_lock);
10435 	if (hw_off_limits(sc))
10436 		rc = ENXIO;
10437 	else
10438 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10439 	mtx_unlock(&sc->reg_lock);
10440 	if (rc != 0)
10441 		return (rc);
10442 
10443 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10444 	if (sb == NULL)
10445 		return (ENOMEM);
10446 
10447 	sbuf_printf(sb,
10448 	    "                                IP                 IPv6\n");
10449 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10450 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10451 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10452 	    v4.tcp_in_segs, v6.tcp_in_segs);
10453 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10454 	    v4.tcp_out_segs, v6.tcp_out_segs);
10455 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10456 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10457 
10458 	rc = sbuf_finish(sb);
10459 	sbuf_delete(sb);
10460 
10461 	return (rc);
10462 }
10463 
10464 static int
10465 sysctl_tids(SYSCTL_HANDLER_ARGS)
10466 {
10467 	struct adapter *sc = arg1;
10468 	struct sbuf *sb;
10469 	int rc;
10470 	uint32_t x, y;
10471 	struct tid_info *t = &sc->tids;
10472 
10473 	rc = sysctl_wire_old_buffer(req, 0);
10474 	if (rc != 0)
10475 		return (rc);
10476 
10477 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10478 	if (sb == NULL)
10479 		return (ENOMEM);
10480 
10481 	if (t->natids) {
10482 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10483 		    t->atids_in_use);
10484 	}
10485 
10486 	if (t->nhpftids) {
10487 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10488 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10489 	}
10490 
10491 	if (t->ntids) {
10492 		bool hashen = false;
10493 
10494 		mtx_lock(&sc->reg_lock);
10495 		if (hw_off_limits(sc))
10496 			rc = ENXIO;
10497 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10498 			hashen = true;
10499 			if (chip_id(sc) <= CHELSIO_T5) {
10500 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10501 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10502 			} else {
10503 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10504 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10505 			}
10506 		}
10507 		mtx_unlock(&sc->reg_lock);
10508 		if (rc != 0)
10509 			goto done;
10510 
10511 		sbuf_printf(sb, "TID range: ");
10512 		if (hashen) {
10513 			if (x)
10514 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10515 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10516 		} else {
10517 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10518 			    t->ntids - 1);
10519 		}
10520 		sbuf_printf(sb, ", in use: %u\n",
10521 		    atomic_load_acq_int(&t->tids_in_use));
10522 	}
10523 
10524 	if (t->nstids) {
10525 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10526 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10527 	}
10528 
10529 	if (t->nftids) {
10530 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10531 		    t->ftid_end, t->ftids_in_use);
10532 	}
10533 
10534 	if (t->netids) {
10535 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10536 		    t->etid_base + t->netids - 1, t->etids_in_use);
10537 	}
10538 
10539 	mtx_lock(&sc->reg_lock);
10540 	if (hw_off_limits(sc))
10541 		rc = ENXIO;
10542 	else {
10543 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10544 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10545 	}
10546 	mtx_unlock(&sc->reg_lock);
10547 	if (rc != 0)
10548 		goto done;
10549 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10550 done:
10551 	if (rc == 0)
10552 		rc = sbuf_finish(sb);
10553 	else
10554 		(void)sbuf_finish(sb);
10555 	sbuf_delete(sb);
10556 
10557 	return (rc);
10558 }
10559 
10560 static int
10561 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10562 {
10563 	struct adapter *sc = arg1;
10564 	struct sbuf *sb;
10565 	int rc;
10566 	struct tp_err_stats stats;
10567 
10568 	rc = sysctl_wire_old_buffer(req, 0);
10569 	if (rc != 0)
10570 		return (rc);
10571 
10572 	mtx_lock(&sc->reg_lock);
10573 	if (hw_off_limits(sc))
10574 		rc = ENXIO;
10575 	else
10576 		t4_tp_get_err_stats(sc, &stats, 0);
10577 	mtx_unlock(&sc->reg_lock);
10578 	if (rc != 0)
10579 		return (rc);
10580 
10581 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10582 	if (sb == NULL)
10583 		return (ENOMEM);
10584 
10585 	if (sc->chip_params->nchan > 2) {
10586 		sbuf_printf(sb, "                 channel 0  channel 1"
10587 		    "  channel 2  channel 3\n");
10588 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10589 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10590 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10591 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10592 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10593 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10594 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10595 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10596 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10597 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10598 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10599 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10600 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10601 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10602 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10603 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10604 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10605 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10606 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10607 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10608 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10609 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10610 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10611 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10612 	} else {
10613 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10614 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10615 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10616 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10617 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10618 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10619 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10620 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10621 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10622 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10623 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10624 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10625 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10626 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10627 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10628 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10629 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10630 	}
10631 
10632 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10633 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10634 
10635 	rc = sbuf_finish(sb);
10636 	sbuf_delete(sb);
10637 
10638 	return (rc);
10639 }
10640 
10641 static int
10642 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10643 {
10644 	struct adapter *sc = arg1;
10645 	struct sbuf *sb;
10646 	int rc;
10647 	struct tp_tnl_stats stats;
10648 
10649 	rc = sysctl_wire_old_buffer(req, 0);
10650 	if (rc != 0)
10651 		return(rc);
10652 
10653 	mtx_lock(&sc->reg_lock);
10654 	if (hw_off_limits(sc))
10655 		rc = ENXIO;
10656 	else
10657 		t4_tp_get_tnl_stats(sc, &stats, 1);
10658 	mtx_unlock(&sc->reg_lock);
10659 	if (rc != 0)
10660 		return (rc);
10661 
10662 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10663 	if (sb == NULL)
10664 		return (ENOMEM);
10665 
10666 	if (sc->chip_params->nchan > 2) {
10667 		sbuf_printf(sb, "           channel 0  channel 1"
10668 		    "  channel 2  channel 3\n");
10669 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10670 		    stats.out_pkt[0], stats.out_pkt[1],
10671 		    stats.out_pkt[2], stats.out_pkt[3]);
10672 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10673 		    stats.in_pkt[0], stats.in_pkt[1],
10674 		    stats.in_pkt[2], stats.in_pkt[3]);
10675 	} else {
10676 		sbuf_printf(sb, "           channel 0  channel 1\n");
10677 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10678 		    stats.out_pkt[0], stats.out_pkt[1]);
10679 		sbuf_printf(sb, "InPkts:   %10u %10u",
10680 		    stats.in_pkt[0], stats.in_pkt[1]);
10681 	}
10682 
10683 	rc = sbuf_finish(sb);
10684 	sbuf_delete(sb);
10685 
10686 	return (rc);
10687 }
10688 
10689 static int
10690 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10691 {
10692 	struct adapter *sc = arg1;
10693 	struct tp_params *tpp = &sc->params.tp;
10694 	u_int mask;
10695 	int rc;
10696 
10697 	mask = tpp->la_mask >> 16;
10698 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10699 	if (rc != 0 || req->newptr == NULL)
10700 		return (rc);
10701 	if (mask > 0xffff)
10702 		return (EINVAL);
10703 	mtx_lock(&sc->reg_lock);
10704 	if (hw_off_limits(sc))
10705 		rc = ENXIO;
10706 	else {
10707 		tpp->la_mask = mask << 16;
10708 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10709 		    tpp->la_mask);
10710 	}
10711 	mtx_unlock(&sc->reg_lock);
10712 
10713 	return (rc);
10714 }
10715 
10716 struct field_desc {
10717 	const char *name;
10718 	u_int start;
10719 	u_int width;
10720 };
10721 
10722 static void
10723 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10724 {
10725 	char buf[32];
10726 	int line_size = 0;
10727 
10728 	while (f->name) {
10729 		uint64_t mask = (1ULL << f->width) - 1;
10730 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10731 		    ((uintmax_t)v >> f->start) & mask);
10732 
10733 		if (line_size + len >= 79) {
10734 			line_size = 8;
10735 			sbuf_printf(sb, "\n        ");
10736 		}
10737 		sbuf_printf(sb, "%s ", buf);
10738 		line_size += len + 1;
10739 		f++;
10740 	}
10741 	sbuf_printf(sb, "\n");
10742 }
10743 
10744 static const struct field_desc tp_la0[] = {
10745 	{ "RcfOpCodeOut", 60, 4 },
10746 	{ "State", 56, 4 },
10747 	{ "WcfState", 52, 4 },
10748 	{ "RcfOpcSrcOut", 50, 2 },
10749 	{ "CRxError", 49, 1 },
10750 	{ "ERxError", 48, 1 },
10751 	{ "SanityFailed", 47, 1 },
10752 	{ "SpuriousMsg", 46, 1 },
10753 	{ "FlushInputMsg", 45, 1 },
10754 	{ "FlushInputCpl", 44, 1 },
10755 	{ "RssUpBit", 43, 1 },
10756 	{ "RssFilterHit", 42, 1 },
10757 	{ "Tid", 32, 10 },
10758 	{ "InitTcb", 31, 1 },
10759 	{ "LineNumber", 24, 7 },
10760 	{ "Emsg", 23, 1 },
10761 	{ "EdataOut", 22, 1 },
10762 	{ "Cmsg", 21, 1 },
10763 	{ "CdataOut", 20, 1 },
10764 	{ "EreadPdu", 19, 1 },
10765 	{ "CreadPdu", 18, 1 },
10766 	{ "TunnelPkt", 17, 1 },
10767 	{ "RcfPeerFin", 16, 1 },
10768 	{ "RcfReasonOut", 12, 4 },
10769 	{ "TxCchannel", 10, 2 },
10770 	{ "RcfTxChannel", 8, 2 },
10771 	{ "RxEchannel", 6, 2 },
10772 	{ "RcfRxChannel", 5, 1 },
10773 	{ "RcfDataOutSrdy", 4, 1 },
10774 	{ "RxDvld", 3, 1 },
10775 	{ "RxOoDvld", 2, 1 },
10776 	{ "RxCongestion", 1, 1 },
10777 	{ "TxCongestion", 0, 1 },
10778 	{ NULL }
10779 };
10780 
10781 static const struct field_desc tp_la1[] = {
10782 	{ "CplCmdIn", 56, 8 },
10783 	{ "CplCmdOut", 48, 8 },
10784 	{ "ESynOut", 47, 1 },
10785 	{ "EAckOut", 46, 1 },
10786 	{ "EFinOut", 45, 1 },
10787 	{ "ERstOut", 44, 1 },
10788 	{ "SynIn", 43, 1 },
10789 	{ "AckIn", 42, 1 },
10790 	{ "FinIn", 41, 1 },
10791 	{ "RstIn", 40, 1 },
10792 	{ "DataIn", 39, 1 },
10793 	{ "DataInVld", 38, 1 },
10794 	{ "PadIn", 37, 1 },
10795 	{ "RxBufEmpty", 36, 1 },
10796 	{ "RxDdp", 35, 1 },
10797 	{ "RxFbCongestion", 34, 1 },
10798 	{ "TxFbCongestion", 33, 1 },
10799 	{ "TxPktSumSrdy", 32, 1 },
10800 	{ "RcfUlpType", 28, 4 },
10801 	{ "Eread", 27, 1 },
10802 	{ "Ebypass", 26, 1 },
10803 	{ "Esave", 25, 1 },
10804 	{ "Static0", 24, 1 },
10805 	{ "Cread", 23, 1 },
10806 	{ "Cbypass", 22, 1 },
10807 	{ "Csave", 21, 1 },
10808 	{ "CPktOut", 20, 1 },
10809 	{ "RxPagePoolFull", 18, 2 },
10810 	{ "RxLpbkPkt", 17, 1 },
10811 	{ "TxLpbkPkt", 16, 1 },
10812 	{ "RxVfValid", 15, 1 },
10813 	{ "SynLearned", 14, 1 },
10814 	{ "SetDelEntry", 13, 1 },
10815 	{ "SetInvEntry", 12, 1 },
10816 	{ "CpcmdDvld", 11, 1 },
10817 	{ "CpcmdSave", 10, 1 },
10818 	{ "RxPstructsFull", 8, 2 },
10819 	{ "EpcmdDvld", 7, 1 },
10820 	{ "EpcmdFlush", 6, 1 },
10821 	{ "EpcmdTrimPrefix", 5, 1 },
10822 	{ "EpcmdTrimPostfix", 4, 1 },
10823 	{ "ERssIp4Pkt", 3, 1 },
10824 	{ "ERssIp6Pkt", 2, 1 },
10825 	{ "ERssTcpUdpPkt", 1, 1 },
10826 	{ "ERssFceFipPkt", 0, 1 },
10827 	{ NULL }
10828 };
10829 
10830 static const struct field_desc tp_la2[] = {
10831 	{ "CplCmdIn", 56, 8 },
10832 	{ "MpsVfVld", 55, 1 },
10833 	{ "MpsPf", 52, 3 },
10834 	{ "MpsVf", 44, 8 },
10835 	{ "SynIn", 43, 1 },
10836 	{ "AckIn", 42, 1 },
10837 	{ "FinIn", 41, 1 },
10838 	{ "RstIn", 40, 1 },
10839 	{ "DataIn", 39, 1 },
10840 	{ "DataInVld", 38, 1 },
10841 	{ "PadIn", 37, 1 },
10842 	{ "RxBufEmpty", 36, 1 },
10843 	{ "RxDdp", 35, 1 },
10844 	{ "RxFbCongestion", 34, 1 },
10845 	{ "TxFbCongestion", 33, 1 },
10846 	{ "TxPktSumSrdy", 32, 1 },
10847 	{ "RcfUlpType", 28, 4 },
10848 	{ "Eread", 27, 1 },
10849 	{ "Ebypass", 26, 1 },
10850 	{ "Esave", 25, 1 },
10851 	{ "Static0", 24, 1 },
10852 	{ "Cread", 23, 1 },
10853 	{ "Cbypass", 22, 1 },
10854 	{ "Csave", 21, 1 },
10855 	{ "CPktOut", 20, 1 },
10856 	{ "RxPagePoolFull", 18, 2 },
10857 	{ "RxLpbkPkt", 17, 1 },
10858 	{ "TxLpbkPkt", 16, 1 },
10859 	{ "RxVfValid", 15, 1 },
10860 	{ "SynLearned", 14, 1 },
10861 	{ "SetDelEntry", 13, 1 },
10862 	{ "SetInvEntry", 12, 1 },
10863 	{ "CpcmdDvld", 11, 1 },
10864 	{ "CpcmdSave", 10, 1 },
10865 	{ "RxPstructsFull", 8, 2 },
10866 	{ "EpcmdDvld", 7, 1 },
10867 	{ "EpcmdFlush", 6, 1 },
10868 	{ "EpcmdTrimPrefix", 5, 1 },
10869 	{ "EpcmdTrimPostfix", 4, 1 },
10870 	{ "ERssIp4Pkt", 3, 1 },
10871 	{ "ERssIp6Pkt", 2, 1 },
10872 	{ "ERssTcpUdpPkt", 1, 1 },
10873 	{ "ERssFceFipPkt", 0, 1 },
10874 	{ NULL }
10875 };
10876 
10877 static void
10878 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10879 {
10880 
10881 	field_desc_show(sb, *p, tp_la0);
10882 }
10883 
10884 static void
10885 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10886 {
10887 
10888 	if (idx)
10889 		sbuf_printf(sb, "\n");
10890 	field_desc_show(sb, p[0], tp_la0);
10891 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10892 		field_desc_show(sb, p[1], tp_la0);
10893 }
10894 
10895 static void
10896 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
10897 {
10898 
10899 	if (idx)
10900 		sbuf_printf(sb, "\n");
10901 	field_desc_show(sb, p[0], tp_la0);
10902 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10903 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
10904 }
10905 
10906 static int
10907 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
10908 {
10909 	struct adapter *sc = arg1;
10910 	struct sbuf *sb;
10911 	uint64_t *buf, *p;
10912 	int rc;
10913 	u_int i, inc;
10914 	void (*show_func)(struct sbuf *, uint64_t *, int);
10915 
10916 	rc = sysctl_wire_old_buffer(req, 0);
10917 	if (rc != 0)
10918 		return (rc);
10919 
10920 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10921 	if (sb == NULL)
10922 		return (ENOMEM);
10923 
10924 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
10925 
10926 	mtx_lock(&sc->reg_lock);
10927 	if (hw_off_limits(sc))
10928 		rc = ENXIO;
10929 	else {
10930 		t4_tp_read_la(sc, buf, NULL);
10931 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
10932 		case 2:
10933 			inc = 2;
10934 			show_func = tp_la_show2;
10935 			break;
10936 		case 3:
10937 			inc = 2;
10938 			show_func = tp_la_show3;
10939 			break;
10940 		default:
10941 			inc = 1;
10942 			show_func = tp_la_show;
10943 		}
10944 	}
10945 	mtx_unlock(&sc->reg_lock);
10946 	if (rc != 0)
10947 		goto done;
10948 
10949 	p = buf;
10950 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
10951 		(*show_func)(sb, p, i);
10952 	rc = sbuf_finish(sb);
10953 done:
10954 	sbuf_delete(sb);
10955 	free(buf, M_CXGBE);
10956 	return (rc);
10957 }
10958 
10959 static int
10960 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
10961 {
10962 	struct adapter *sc = arg1;
10963 	struct sbuf *sb;
10964 	int rc;
10965 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
10966 
10967 	rc = sysctl_wire_old_buffer(req, 0);
10968 	if (rc != 0)
10969 		return (rc);
10970 
10971 	mtx_lock(&sc->reg_lock);
10972 	if (hw_off_limits(sc))
10973 		rc = ENXIO;
10974 	else
10975 		t4_get_chan_txrate(sc, nrate, orate);
10976 	mtx_unlock(&sc->reg_lock);
10977 	if (rc != 0)
10978 		return (rc);
10979 
10980 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10981 	if (sb == NULL)
10982 		return (ENOMEM);
10983 
10984 	if (sc->chip_params->nchan > 2) {
10985 		sbuf_printf(sb, "              channel 0   channel 1"
10986 		    "   channel 2   channel 3\n");
10987 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
10988 		    nrate[0], nrate[1], nrate[2], nrate[3]);
10989 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
10990 		    orate[0], orate[1], orate[2], orate[3]);
10991 	} else {
10992 		sbuf_printf(sb, "              channel 0   channel 1\n");
10993 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
10994 		    nrate[0], nrate[1]);
10995 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
10996 		    orate[0], orate[1]);
10997 	}
10998 
10999 	rc = sbuf_finish(sb);
11000 	sbuf_delete(sb);
11001 
11002 	return (rc);
11003 }
11004 
11005 static int
11006 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
11007 {
11008 	struct adapter *sc = arg1;
11009 	struct sbuf *sb;
11010 	uint32_t *buf, *p;
11011 	int rc, i;
11012 
11013 	rc = sysctl_wire_old_buffer(req, 0);
11014 	if (rc != 0)
11015 		return (rc);
11016 
11017 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11018 	if (sb == NULL)
11019 		return (ENOMEM);
11020 
11021 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
11022 	    M_ZERO | M_WAITOK);
11023 
11024 	mtx_lock(&sc->reg_lock);
11025 	if (hw_off_limits(sc))
11026 		rc = ENXIO;
11027 	else
11028 		t4_ulprx_read_la(sc, buf);
11029 	mtx_unlock(&sc->reg_lock);
11030 	if (rc != 0)
11031 		goto done;
11032 
11033 	p = buf;
11034 	sbuf_printf(sb, "      Pcmd        Type   Message"
11035 	    "                Data");
11036 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
11037 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
11038 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
11039 	}
11040 	rc = sbuf_finish(sb);
11041 done:
11042 	sbuf_delete(sb);
11043 	free(buf, M_CXGBE);
11044 	return (rc);
11045 }
11046 
11047 static int
11048 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
11049 {
11050 	struct adapter *sc = arg1;
11051 	struct sbuf *sb;
11052 	int rc;
11053 	uint32_t cfg, s1, s2;
11054 
11055 	MPASS(chip_id(sc) >= CHELSIO_T5);
11056 
11057 	rc = sysctl_wire_old_buffer(req, 0);
11058 	if (rc != 0)
11059 		return (rc);
11060 
11061 	mtx_lock(&sc->reg_lock);
11062 	if (hw_off_limits(sc))
11063 		rc = ENXIO;
11064 	else {
11065 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
11066 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
11067 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
11068 	}
11069 	mtx_unlock(&sc->reg_lock);
11070 	if (rc != 0)
11071 		return (rc);
11072 
11073 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11074 	if (sb == NULL)
11075 		return (ENOMEM);
11076 
11077 	if (G_STATSOURCE_T5(cfg) == 7) {
11078 		int mode;
11079 
11080 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
11081 		if (mode == 0)
11082 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
11083 		else if (mode == 1)
11084 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
11085 		else
11086 			sbuf_printf(sb, "unknown mode %d", mode);
11087 	}
11088 	rc = sbuf_finish(sb);
11089 	sbuf_delete(sb);
11090 
11091 	return (rc);
11092 }
11093 
11094 static int
11095 sysctl_cpus(SYSCTL_HANDLER_ARGS)
11096 {
11097 	struct adapter *sc = arg1;
11098 	enum cpu_sets op = arg2;
11099 	cpuset_t cpuset;
11100 	struct sbuf *sb;
11101 	int i, rc;
11102 
11103 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
11104 
11105 	CPU_ZERO(&cpuset);
11106 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
11107 	if (rc != 0)
11108 		return (rc);
11109 
11110 	rc = sysctl_wire_old_buffer(req, 0);
11111 	if (rc != 0)
11112 		return (rc);
11113 
11114 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11115 	if (sb == NULL)
11116 		return (ENOMEM);
11117 
11118 	CPU_FOREACH(i)
11119 		sbuf_printf(sb, "%d ", i);
11120 	rc = sbuf_finish(sb);
11121 	sbuf_delete(sb);
11122 
11123 	return (rc);
11124 }
11125 
11126 static int
11127 sysctl_reset(SYSCTL_HANDLER_ARGS)
11128 {
11129 	struct adapter *sc = arg1;
11130 	u_int val;
11131 	int rc;
11132 
11133 	val = atomic_load_int(&sc->num_resets);
11134 	rc = sysctl_handle_int(oidp, &val, 0, req);
11135 	if (rc != 0 || req->newptr == NULL)
11136 		return (rc);
11137 
11138 	if (val == 0) {
11139 		/* Zero out the counter that tracks reset. */
11140 		atomic_store_int(&sc->num_resets, 0);
11141 		return (0);
11142 	}
11143 
11144 	if (val != 1)
11145 		return (EINVAL);	/* 0 or 1 are the only legal values */
11146 
11147 	if (hw_off_limits(sc))		/* harmless race */
11148 		return (EALREADY);
11149 
11150 	taskqueue_enqueue(reset_tq, &sc->reset_task);
11151 	return (0);
11152 }
11153 
11154 #ifdef TCP_OFFLOAD
11155 static int
11156 sysctl_tls(SYSCTL_HANDLER_ARGS)
11157 {
11158 	struct adapter *sc = arg1;
11159 	int i, j, v, rc;
11160 	struct vi_info *vi;
11161 
11162 	v = sc->tt.tls;
11163 	rc = sysctl_handle_int(oidp, &v, 0, req);
11164 	if (rc != 0 || req->newptr == NULL)
11165 		return (rc);
11166 
11167 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11168 		return (ENOTSUP);
11169 
11170 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11171 	if (rc)
11172 		return (rc);
11173 	if (hw_off_limits(sc))
11174 		rc = ENXIO;
11175 	else {
11176 		sc->tt.tls = !!v;
11177 		for_each_port(sc, i) {
11178 			for_each_vi(sc->port[i], j, vi) {
11179 				if (vi->flags & VI_INIT_DONE)
11180 					t4_update_fl_bufsize(vi->ifp);
11181 			}
11182 		}
11183 	}
11184 	end_synchronized_op(sc, 0);
11185 
11186 	return (rc);
11187 
11188 }
11189 
11190 static int
11191 sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS)
11192 {
11193 	struct adapter *sc = arg1;
11194 	int *old_ports, *new_ports;
11195 	int i, new_count, rc;
11196 
11197 	if (req->newptr == NULL && req->oldptr == NULL)
11198 		return (SYSCTL_OUT(req, NULL, imax(sc->tt.num_tls_rx_ports, 1) *
11199 		    sizeof(sc->tt.tls_rx_ports[0])));
11200 
11201 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tlsrx");
11202 	if (rc)
11203 		return (rc);
11204 
11205 	if (hw_off_limits(sc)) {
11206 		rc = ENXIO;
11207 		goto done;
11208 	}
11209 
11210 	if (sc->tt.num_tls_rx_ports == 0) {
11211 		i = -1;
11212 		rc = SYSCTL_OUT(req, &i, sizeof(i));
11213 	} else
11214 		rc = SYSCTL_OUT(req, sc->tt.tls_rx_ports,
11215 		    sc->tt.num_tls_rx_ports * sizeof(sc->tt.tls_rx_ports[0]));
11216 	if (rc == 0 && req->newptr != NULL) {
11217 		new_count = req->newlen / sizeof(new_ports[0]);
11218 		new_ports = malloc(new_count * sizeof(new_ports[0]), M_CXGBE,
11219 		    M_WAITOK);
11220 		rc = SYSCTL_IN(req, new_ports, new_count *
11221 		    sizeof(new_ports[0]));
11222 		if (rc)
11223 			goto err;
11224 
11225 		/* Allow setting to a single '-1' to clear the list. */
11226 		if (new_count == 1 && new_ports[0] == -1) {
11227 			ADAPTER_LOCK(sc);
11228 			old_ports = sc->tt.tls_rx_ports;
11229 			sc->tt.tls_rx_ports = NULL;
11230 			sc->tt.num_tls_rx_ports = 0;
11231 			ADAPTER_UNLOCK(sc);
11232 			free(old_ports, M_CXGBE);
11233 		} else {
11234 			for (i = 0; i < new_count; i++) {
11235 				if (new_ports[i] < 1 ||
11236 				    new_ports[i] > IPPORT_MAX) {
11237 					rc = EINVAL;
11238 					goto err;
11239 				}
11240 			}
11241 
11242 			ADAPTER_LOCK(sc);
11243 			old_ports = sc->tt.tls_rx_ports;
11244 			sc->tt.tls_rx_ports = new_ports;
11245 			sc->tt.num_tls_rx_ports = new_count;
11246 			ADAPTER_UNLOCK(sc);
11247 			free(old_ports, M_CXGBE);
11248 			new_ports = NULL;
11249 		}
11250 	err:
11251 		free(new_ports, M_CXGBE);
11252 	}
11253 done:
11254 	end_synchronized_op(sc, 0);
11255 	return (rc);
11256 }
11257 
11258 static int
11259 sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS)
11260 {
11261 	struct adapter *sc = arg1;
11262 	int v, rc;
11263 
11264 	v = sc->tt.tls_rx_timeout;
11265 	rc = sysctl_handle_int(oidp, &v, 0, req);
11266 	if (rc != 0 || req->newptr == NULL)
11267 		return (rc);
11268 
11269 	if (v < 0)
11270 		return (EINVAL);
11271 
11272 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11273 		return (ENOTSUP);
11274 
11275 	sc->tt.tls_rx_timeout = v;
11276 
11277 	return (0);
11278 
11279 }
11280 
11281 static void
11282 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11283 {
11284 	u_int rem = val % factor;
11285 
11286 	if (rem == 0)
11287 		snprintf(buf, len, "%u", val / factor);
11288 	else {
11289 		while (rem % 10 == 0)
11290 			rem /= 10;
11291 		snprintf(buf, len, "%u.%u", val / factor, rem);
11292 	}
11293 }
11294 
11295 static int
11296 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11297 {
11298 	struct adapter *sc = arg1;
11299 	char buf[16];
11300 	u_int res, re;
11301 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11302 
11303 	mtx_lock(&sc->reg_lock);
11304 	if (hw_off_limits(sc))
11305 		res = (u_int)-1;
11306 	else
11307 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11308 	mtx_unlock(&sc->reg_lock);
11309 	if (res == (u_int)-1)
11310 		return (ENXIO);
11311 
11312 	switch (arg2) {
11313 	case 0:
11314 		/* timer_tick */
11315 		re = G_TIMERRESOLUTION(res);
11316 		break;
11317 	case 1:
11318 		/* TCP timestamp tick */
11319 		re = G_TIMESTAMPRESOLUTION(res);
11320 		break;
11321 	case 2:
11322 		/* DACK tick */
11323 		re = G_DELAYEDACKRESOLUTION(res);
11324 		break;
11325 	default:
11326 		return (EDOOFUS);
11327 	}
11328 
11329 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11330 
11331 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11332 }
11333 
11334 static int
11335 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11336 {
11337 	struct adapter *sc = arg1;
11338 	int rc;
11339 	u_int dack_tmr, dack_re, v;
11340 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11341 
11342 	mtx_lock(&sc->reg_lock);
11343 	if (hw_off_limits(sc))
11344 		rc = ENXIO;
11345 	else {
11346 		rc = 0;
11347 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11348 		    A_TP_TIMER_RESOLUTION));
11349 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11350 	}
11351 	mtx_unlock(&sc->reg_lock);
11352 	if (rc != 0)
11353 		return (rc);
11354 
11355 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11356 
11357 	return (sysctl_handle_int(oidp, &v, 0, req));
11358 }
11359 
11360 static int
11361 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11362 {
11363 	struct adapter *sc = arg1;
11364 	int rc, reg = arg2;
11365 	u_int tre;
11366 	u_long tp_tick_us, v;
11367 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11368 
11369 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11370 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11371 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11372 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11373 
11374 	mtx_lock(&sc->reg_lock);
11375 	if (hw_off_limits(sc))
11376 		rc = ENXIO;
11377 	else {
11378 		rc = 0;
11379 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11380 		tp_tick_us = (cclk_ps << tre) / 1000000;
11381 		if (reg == A_TP_INIT_SRTT)
11382 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11383 		else
11384 			v = tp_tick_us * t4_read_reg(sc, reg);
11385 	}
11386 	mtx_unlock(&sc->reg_lock);
11387 	if (rc != 0)
11388 		return (rc);
11389 	else
11390 		return (sysctl_handle_long(oidp, &v, 0, req));
11391 }
11392 
11393 /*
11394  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11395  * passed to this function.
11396  */
11397 static int
11398 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11399 {
11400 	struct adapter *sc = arg1;
11401 	int rc, idx = arg2;
11402 	u_int v;
11403 
11404 	MPASS(idx >= 0 && idx <= 24);
11405 
11406 	mtx_lock(&sc->reg_lock);
11407 	if (hw_off_limits(sc))
11408 		rc = ENXIO;
11409 	else {
11410 		rc = 0;
11411 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11412 	}
11413 	mtx_unlock(&sc->reg_lock);
11414 	if (rc != 0)
11415 		return (rc);
11416 	else
11417 		return (sysctl_handle_int(oidp, &v, 0, req));
11418 }
11419 
11420 static int
11421 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11422 {
11423 	struct adapter *sc = arg1;
11424 	int rc, idx = arg2;
11425 	u_int shift, v, r;
11426 
11427 	MPASS(idx >= 0 && idx < 16);
11428 
11429 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11430 	shift = (idx & 3) << 3;
11431 	mtx_lock(&sc->reg_lock);
11432 	if (hw_off_limits(sc))
11433 		rc = ENXIO;
11434 	else {
11435 		rc = 0;
11436 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11437 	}
11438 	mtx_unlock(&sc->reg_lock);
11439 	if (rc != 0)
11440 		return (rc);
11441 	else
11442 		return (sysctl_handle_int(oidp, &v, 0, req));
11443 }
11444 
11445 static int
11446 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11447 {
11448 	struct vi_info *vi = arg1;
11449 	struct adapter *sc = vi->adapter;
11450 	int idx, rc, i;
11451 	struct sge_ofld_rxq *ofld_rxq;
11452 	uint8_t v;
11453 
11454 	idx = vi->ofld_tmr_idx;
11455 
11456 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11457 	if (rc != 0 || req->newptr == NULL)
11458 		return (rc);
11459 
11460 	if (idx < 0 || idx >= SGE_NTIMERS)
11461 		return (EINVAL);
11462 
11463 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11464 	    "t4otmr");
11465 	if (rc)
11466 		return (rc);
11467 
11468 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11469 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11470 #ifdef atomic_store_rel_8
11471 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11472 #else
11473 		ofld_rxq->iq.intr_params = v;
11474 #endif
11475 	}
11476 	vi->ofld_tmr_idx = idx;
11477 
11478 	end_synchronized_op(sc, LOCK_HELD);
11479 	return (0);
11480 }
11481 
11482 static int
11483 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11484 {
11485 	struct vi_info *vi = arg1;
11486 	struct adapter *sc = vi->adapter;
11487 	int idx, rc;
11488 
11489 	idx = vi->ofld_pktc_idx;
11490 
11491 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11492 	if (rc != 0 || req->newptr == NULL)
11493 		return (rc);
11494 
11495 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11496 		return (EINVAL);
11497 
11498 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11499 	    "t4opktc");
11500 	if (rc)
11501 		return (rc);
11502 
11503 	if (vi->flags & VI_INIT_DONE)
11504 		rc = EBUSY; /* cannot be changed once the queues are created */
11505 	else
11506 		vi->ofld_pktc_idx = idx;
11507 
11508 	end_synchronized_op(sc, LOCK_HELD);
11509 	return (rc);
11510 }
11511 #endif
11512 
11513 static int
11514 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11515 {
11516 	int rc;
11517 
11518 	if (cntxt->cid > M_CTXTQID)
11519 		return (EINVAL);
11520 
11521 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11522 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11523 		return (EINVAL);
11524 
11525 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11526 	if (rc)
11527 		return (rc);
11528 
11529 	if (hw_off_limits(sc)) {
11530 		rc = ENXIO;
11531 		goto done;
11532 	}
11533 
11534 	if (sc->flags & FW_OK) {
11535 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11536 		    &cntxt->data[0]);
11537 		if (rc == 0)
11538 			goto done;
11539 	}
11540 
11541 	/*
11542 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11543 	 * the backdoor.
11544 	 */
11545 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11546 done:
11547 	end_synchronized_op(sc, 0);
11548 	return (rc);
11549 }
11550 
11551 static int
11552 load_fw(struct adapter *sc, struct t4_data *fw)
11553 {
11554 	int rc;
11555 	uint8_t *fw_data;
11556 
11557 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11558 	if (rc)
11559 		return (rc);
11560 
11561 	if (hw_off_limits(sc)) {
11562 		rc = ENXIO;
11563 		goto done;
11564 	}
11565 
11566 	/*
11567 	 * The firmware, with the sole exception of the memory parity error
11568 	 * handler, runs from memory and not flash.  It is almost always safe to
11569 	 * install a new firmware on a running system.  Just set bit 1 in
11570 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11571 	 */
11572 	if (sc->flags & FULL_INIT_DONE &&
11573 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11574 		rc = EBUSY;
11575 		goto done;
11576 	}
11577 
11578 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11579 
11580 	rc = copyin(fw->data, fw_data, fw->len);
11581 	if (rc == 0)
11582 		rc = -t4_load_fw(sc, fw_data, fw->len);
11583 
11584 	free(fw_data, M_CXGBE);
11585 done:
11586 	end_synchronized_op(sc, 0);
11587 	return (rc);
11588 }
11589 
11590 static int
11591 load_cfg(struct adapter *sc, struct t4_data *cfg)
11592 {
11593 	int rc;
11594 	uint8_t *cfg_data = NULL;
11595 
11596 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11597 	if (rc)
11598 		return (rc);
11599 
11600 	if (hw_off_limits(sc)) {
11601 		rc = ENXIO;
11602 		goto done;
11603 	}
11604 
11605 	if (cfg->len == 0) {
11606 		/* clear */
11607 		rc = -t4_load_cfg(sc, NULL, 0);
11608 		goto done;
11609 	}
11610 
11611 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11612 
11613 	rc = copyin(cfg->data, cfg_data, cfg->len);
11614 	if (rc == 0)
11615 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11616 
11617 	free(cfg_data, M_CXGBE);
11618 done:
11619 	end_synchronized_op(sc, 0);
11620 	return (rc);
11621 }
11622 
11623 static int
11624 load_boot(struct adapter *sc, struct t4_bootrom *br)
11625 {
11626 	int rc;
11627 	uint8_t *br_data = NULL;
11628 	u_int offset;
11629 
11630 	if (br->len > 1024 * 1024)
11631 		return (EFBIG);
11632 
11633 	if (br->pf_offset == 0) {
11634 		/* pfidx */
11635 		if (br->pfidx_addr > 7)
11636 			return (EINVAL);
11637 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11638 		    A_PCIE_PF_EXPROM_OFST)));
11639 	} else if (br->pf_offset == 1) {
11640 		/* offset */
11641 		offset = G_OFFSET(br->pfidx_addr);
11642 	} else {
11643 		return (EINVAL);
11644 	}
11645 
11646 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11647 	if (rc)
11648 		return (rc);
11649 
11650 	if (hw_off_limits(sc)) {
11651 		rc = ENXIO;
11652 		goto done;
11653 	}
11654 
11655 	if (br->len == 0) {
11656 		/* clear */
11657 		rc = -t4_load_boot(sc, NULL, offset, 0);
11658 		goto done;
11659 	}
11660 
11661 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11662 
11663 	rc = copyin(br->data, br_data, br->len);
11664 	if (rc == 0)
11665 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11666 
11667 	free(br_data, M_CXGBE);
11668 done:
11669 	end_synchronized_op(sc, 0);
11670 	return (rc);
11671 }
11672 
11673 static int
11674 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11675 {
11676 	int rc;
11677 	uint8_t *bc_data = NULL;
11678 
11679 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11680 	if (rc)
11681 		return (rc);
11682 
11683 	if (hw_off_limits(sc)) {
11684 		rc = ENXIO;
11685 		goto done;
11686 	}
11687 
11688 	if (bc->len == 0) {
11689 		/* clear */
11690 		rc = -t4_load_bootcfg(sc, NULL, 0);
11691 		goto done;
11692 	}
11693 
11694 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11695 
11696 	rc = copyin(bc->data, bc_data, bc->len);
11697 	if (rc == 0)
11698 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11699 
11700 	free(bc_data, M_CXGBE);
11701 done:
11702 	end_synchronized_op(sc, 0);
11703 	return (rc);
11704 }
11705 
11706 static int
11707 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11708 {
11709 	int rc;
11710 	struct cudbg_init *cudbg;
11711 	void *handle, *buf;
11712 
11713 	/* buf is large, don't block if no memory is available */
11714 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11715 	if (buf == NULL)
11716 		return (ENOMEM);
11717 
11718 	handle = cudbg_alloc_handle();
11719 	if (handle == NULL) {
11720 		rc = ENOMEM;
11721 		goto done;
11722 	}
11723 
11724 	cudbg = cudbg_get_init(handle);
11725 	cudbg->adap = sc;
11726 	cudbg->print = (cudbg_print_cb)printf;
11727 
11728 #ifndef notyet
11729 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11730 	    __func__, dump->wr_flash, dump->len, dump->data);
11731 #endif
11732 
11733 	if (dump->wr_flash)
11734 		cudbg->use_flash = 1;
11735 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11736 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11737 
11738 	rc = cudbg_collect(handle, buf, &dump->len);
11739 	if (rc != 0)
11740 		goto done;
11741 
11742 	rc = copyout(buf, dump->data, dump->len);
11743 done:
11744 	cudbg_free_handle(handle);
11745 	free(buf, M_CXGBE);
11746 	return (rc);
11747 }
11748 
11749 static void
11750 free_offload_policy(struct t4_offload_policy *op)
11751 {
11752 	struct offload_rule *r;
11753 	int i;
11754 
11755 	if (op == NULL)
11756 		return;
11757 
11758 	r = &op->rule[0];
11759 	for (i = 0; i < op->nrules; i++, r++) {
11760 		free(r->bpf_prog.bf_insns, M_CXGBE);
11761 	}
11762 	free(op->rule, M_CXGBE);
11763 	free(op, M_CXGBE);
11764 }
11765 
11766 static int
11767 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11768 {
11769 	int i, rc, len;
11770 	struct t4_offload_policy *op, *old;
11771 	struct bpf_program *bf;
11772 	const struct offload_settings *s;
11773 	struct offload_rule *r;
11774 	void *u;
11775 
11776 	if (!is_offload(sc))
11777 		return (ENODEV);
11778 
11779 	if (uop->nrules == 0) {
11780 		/* Delete installed policies. */
11781 		op = NULL;
11782 		goto set_policy;
11783 	} else if (uop->nrules > 256) { /* arbitrary */
11784 		return (E2BIG);
11785 	}
11786 
11787 	/* Copy userspace offload policy to kernel */
11788 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11789 	op->nrules = uop->nrules;
11790 	len = op->nrules * sizeof(struct offload_rule);
11791 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11792 	rc = copyin(uop->rule, op->rule, len);
11793 	if (rc) {
11794 		free(op->rule, M_CXGBE);
11795 		free(op, M_CXGBE);
11796 		return (rc);
11797 	}
11798 
11799 	r = &op->rule[0];
11800 	for (i = 0; i < op->nrules; i++, r++) {
11801 
11802 		/* Validate open_type */
11803 		if (r->open_type != OPEN_TYPE_LISTEN &&
11804 		    r->open_type != OPEN_TYPE_ACTIVE &&
11805 		    r->open_type != OPEN_TYPE_PASSIVE &&
11806 		    r->open_type != OPEN_TYPE_DONTCARE) {
11807 error:
11808 			/*
11809 			 * Rules 0 to i have malloc'd filters that need to be
11810 			 * freed.  Rules i+1 to nrules have userspace pointers
11811 			 * and should be left alone.
11812 			 */
11813 			op->nrules = i;
11814 			free_offload_policy(op);
11815 			return (rc);
11816 		}
11817 
11818 		/* Validate settings */
11819 		s = &r->settings;
11820 		if ((s->offload != 0 && s->offload != 1) ||
11821 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11822 		    s->sched_class < -1 ||
11823 		    s->sched_class >= sc->params.nsched_cls) {
11824 			rc = EINVAL;
11825 			goto error;
11826 		}
11827 
11828 		bf = &r->bpf_prog;
11829 		u = bf->bf_insns;	/* userspace ptr */
11830 		bf->bf_insns = NULL;
11831 		if (bf->bf_len == 0) {
11832 			/* legal, matches everything */
11833 			continue;
11834 		}
11835 		len = bf->bf_len * sizeof(*bf->bf_insns);
11836 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11837 		rc = copyin(u, bf->bf_insns, len);
11838 		if (rc != 0)
11839 			goto error;
11840 
11841 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11842 			rc = EINVAL;
11843 			goto error;
11844 		}
11845 	}
11846 set_policy:
11847 	rw_wlock(&sc->policy_lock);
11848 	old = sc->policy;
11849 	sc->policy = op;
11850 	rw_wunlock(&sc->policy_lock);
11851 	free_offload_policy(old);
11852 
11853 	return (0);
11854 }
11855 
11856 #define MAX_READ_BUF_SIZE (128 * 1024)
11857 static int
11858 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11859 {
11860 	uint32_t addr, remaining, n;
11861 	uint32_t *buf;
11862 	int rc;
11863 	uint8_t *dst;
11864 
11865 	mtx_lock(&sc->reg_lock);
11866 	if (hw_off_limits(sc))
11867 		rc = ENXIO;
11868 	else
11869 		rc = validate_mem_range(sc, mr->addr, mr->len);
11870 	mtx_unlock(&sc->reg_lock);
11871 	if (rc != 0)
11872 		return (rc);
11873 
11874 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11875 	addr = mr->addr;
11876 	remaining = mr->len;
11877 	dst = (void *)mr->data;
11878 
11879 	while (remaining) {
11880 		n = min(remaining, MAX_READ_BUF_SIZE);
11881 		mtx_lock(&sc->reg_lock);
11882 		if (hw_off_limits(sc))
11883 			rc = ENXIO;
11884 		else
11885 			read_via_memwin(sc, 2, addr, buf, n);
11886 		mtx_unlock(&sc->reg_lock);
11887 		if (rc != 0)
11888 			break;
11889 
11890 		rc = copyout(buf, dst, n);
11891 		if (rc != 0)
11892 			break;
11893 
11894 		dst += n;
11895 		remaining -= n;
11896 		addr += n;
11897 	}
11898 
11899 	free(buf, M_CXGBE);
11900 	return (rc);
11901 }
11902 #undef MAX_READ_BUF_SIZE
11903 
11904 static int
11905 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11906 {
11907 	int rc;
11908 
11909 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11910 		return (EINVAL);
11911 
11912 	if (i2cd->len > sizeof(i2cd->data))
11913 		return (EFBIG);
11914 
11915 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11916 	if (rc)
11917 		return (rc);
11918 	if (hw_off_limits(sc))
11919 		rc = ENXIO;
11920 	else
11921 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11922 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11923 	end_synchronized_op(sc, 0);
11924 
11925 	return (rc);
11926 }
11927 
11928 static int
11929 clear_stats(struct adapter *sc, u_int port_id)
11930 {
11931 	int i, v, chan_map;
11932 	struct port_info *pi;
11933 	struct vi_info *vi;
11934 	struct sge_rxq *rxq;
11935 	struct sge_txq *txq;
11936 	struct sge_wrq *wrq;
11937 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11938 	struct sge_ofld_txq *ofld_txq;
11939 #endif
11940 #ifdef TCP_OFFLOAD
11941 	struct sge_ofld_rxq *ofld_rxq;
11942 #endif
11943 
11944 	if (port_id >= sc->params.nports)
11945 		return (EINVAL);
11946 	pi = sc->port[port_id];
11947 	if (pi == NULL)
11948 		return (EIO);
11949 
11950 	mtx_lock(&sc->reg_lock);
11951 	if (!hw_off_limits(sc)) {
11952 		/* MAC stats */
11953 		t4_clr_port_stats(sc, pi->tx_chan);
11954 		if (is_t6(sc)) {
11955 			if (pi->fcs_reg != -1)
11956 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11957 			else
11958 				pi->stats.rx_fcs_err = 0;
11959 		}
11960 		for_each_vi(pi, v, vi) {
11961 			if (vi->flags & VI_INIT_DONE)
11962 				t4_clr_vi_stats(sc, vi->vin);
11963 		}
11964 		chan_map = pi->rx_e_chan_map;
11965 		v = 0;	/* reuse */
11966 		while (chan_map) {
11967 			i = ffs(chan_map) - 1;
11968 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11969 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11970 			chan_map &= ~(1 << i);
11971 		}
11972 	}
11973 	mtx_unlock(&sc->reg_lock);
11974 	pi->tx_parse_error = 0;
11975 	pi->tnl_cong_drops = 0;
11976 
11977 	/*
11978 	 * Since this command accepts a port, clear stats for
11979 	 * all VIs on this port.
11980 	 */
11981 	for_each_vi(pi, v, vi) {
11982 		if (vi->flags & VI_INIT_DONE) {
11983 
11984 			for_each_rxq(vi, i, rxq) {
11985 #if defined(INET) || defined(INET6)
11986 				rxq->lro.lro_queued = 0;
11987 				rxq->lro.lro_flushed = 0;
11988 #endif
11989 				rxq->rxcsum = 0;
11990 				rxq->vlan_extraction = 0;
11991 				rxq->vxlan_rxcsum = 0;
11992 
11993 				rxq->fl.cl_allocated = 0;
11994 				rxq->fl.cl_recycled = 0;
11995 				rxq->fl.cl_fast_recycled = 0;
11996 			}
11997 
11998 			for_each_txq(vi, i, txq) {
11999 				txq->txcsum = 0;
12000 				txq->tso_wrs = 0;
12001 				txq->vlan_insertion = 0;
12002 				txq->imm_wrs = 0;
12003 				txq->sgl_wrs = 0;
12004 				txq->txpkt_wrs = 0;
12005 				txq->txpkts0_wrs = 0;
12006 				txq->txpkts1_wrs = 0;
12007 				txq->txpkts0_pkts = 0;
12008 				txq->txpkts1_pkts = 0;
12009 				txq->txpkts_flush = 0;
12010 				txq->raw_wrs = 0;
12011 				txq->vxlan_tso_wrs = 0;
12012 				txq->vxlan_txcsum = 0;
12013 				txq->kern_tls_records = 0;
12014 				txq->kern_tls_short = 0;
12015 				txq->kern_tls_partial = 0;
12016 				txq->kern_tls_full = 0;
12017 				txq->kern_tls_octets = 0;
12018 				txq->kern_tls_waste = 0;
12019 				txq->kern_tls_options = 0;
12020 				txq->kern_tls_header = 0;
12021 				txq->kern_tls_fin = 0;
12022 				txq->kern_tls_fin_short = 0;
12023 				txq->kern_tls_cbc = 0;
12024 				txq->kern_tls_gcm = 0;
12025 				mp_ring_reset_stats(txq->r);
12026 			}
12027 
12028 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12029 			for_each_ofld_txq(vi, i, ofld_txq) {
12030 				ofld_txq->wrq.tx_wrs_direct = 0;
12031 				ofld_txq->wrq.tx_wrs_copied = 0;
12032 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
12033 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
12034 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
12035 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
12036 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
12037 			}
12038 #endif
12039 #ifdef TCP_OFFLOAD
12040 			for_each_ofld_rxq(vi, i, ofld_rxq) {
12041 				ofld_rxq->fl.cl_allocated = 0;
12042 				ofld_rxq->fl.cl_recycled = 0;
12043 				ofld_rxq->fl.cl_fast_recycled = 0;
12044 				counter_u64_zero(
12045 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
12046 				counter_u64_zero(
12047 				    ofld_rxq->rx_iscsi_ddp_setup_error);
12048 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
12049 				ofld_rxq->rx_iscsi_ddp_octets = 0;
12050 				ofld_rxq->rx_iscsi_fl_pdus = 0;
12051 				ofld_rxq->rx_iscsi_fl_octets = 0;
12052 				ofld_rxq->rx_toe_tls_records = 0;
12053 				ofld_rxq->rx_toe_tls_octets = 0;
12054 			}
12055 #endif
12056 
12057 			if (IS_MAIN_VI(vi)) {
12058 				wrq = &sc->sge.ctrlq[pi->port_id];
12059 				wrq->tx_wrs_direct = 0;
12060 				wrq->tx_wrs_copied = 0;
12061 			}
12062 		}
12063 	}
12064 
12065 	return (0);
12066 }
12067 
12068 static int
12069 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12070 {
12071 #ifdef INET6
12072 	struct in6_addr in6;
12073 
12074 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12075 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
12076 		return (0);
12077 	else
12078 		return (EIO);
12079 #else
12080 	return (ENOTSUP);
12081 #endif
12082 }
12083 
12084 static int
12085 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12086 {
12087 #ifdef INET6
12088 	struct in6_addr in6;
12089 
12090 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12091 	return (t4_release_clip_addr(sc, &in6));
12092 #else
12093 	return (ENOTSUP);
12094 #endif
12095 }
12096 
12097 int
12098 t4_os_find_pci_capability(struct adapter *sc, int cap)
12099 {
12100 	int i;
12101 
12102 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
12103 }
12104 
12105 int
12106 t4_os_pci_save_state(struct adapter *sc)
12107 {
12108 	device_t dev;
12109 	struct pci_devinfo *dinfo;
12110 
12111 	dev = sc->dev;
12112 	dinfo = device_get_ivars(dev);
12113 
12114 	pci_cfg_save(dev, dinfo, 0);
12115 	return (0);
12116 }
12117 
12118 int
12119 t4_os_pci_restore_state(struct adapter *sc)
12120 {
12121 	device_t dev;
12122 	struct pci_devinfo *dinfo;
12123 
12124 	dev = sc->dev;
12125 	dinfo = device_get_ivars(dev);
12126 
12127 	pci_cfg_restore(dev, dinfo);
12128 	return (0);
12129 }
12130 
12131 void
12132 t4_os_portmod_changed(struct port_info *pi)
12133 {
12134 	struct adapter *sc = pi->adapter;
12135 	struct vi_info *vi;
12136 	struct ifnet *ifp;
12137 	static const char *mod_str[] = {
12138 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
12139 	};
12140 
12141 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
12142 	    ("%s: port_type %u", __func__, pi->port_type));
12143 
12144 	vi = &pi->vi[0];
12145 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12146 		PORT_LOCK(pi);
12147 		build_medialist(pi);
12148 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12149 			fixup_link_config(pi);
12150 			apply_link_config(pi);
12151 		}
12152 		PORT_UNLOCK(pi);
12153 		end_synchronized_op(sc, LOCK_HELD);
12154 	}
12155 
12156 	ifp = vi->ifp;
12157 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12158 		if_printf(ifp, "transceiver unplugged.\n");
12159 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12160 		if_printf(ifp, "unknown transceiver inserted.\n");
12161 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12162 		if_printf(ifp, "unsupported transceiver inserted.\n");
12163 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12164 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12165 		    port_top_speed(pi), mod_str[pi->mod_type]);
12166 	} else {
12167 		if_printf(ifp, "transceiver (type %d) inserted.\n",
12168 		    pi->mod_type);
12169 	}
12170 }
12171 
12172 void
12173 t4_os_link_changed(struct port_info *pi)
12174 {
12175 	struct vi_info *vi;
12176 	struct ifnet *ifp;
12177 	struct link_config *lc = &pi->link_cfg;
12178 	struct adapter *sc = pi->adapter;
12179 	int v;
12180 
12181 	PORT_LOCK_ASSERT_OWNED(pi);
12182 
12183 	if (is_t6(sc)) {
12184 		if (lc->link_ok) {
12185 			if (lc->speed > 25000 ||
12186 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12187 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12188 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12189 			} else {
12190 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12191 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12192 			}
12193 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12194 			pi->stats.rx_fcs_err = 0;
12195 		} else {
12196 			pi->fcs_reg = -1;
12197 		}
12198 	} else {
12199 		MPASS(pi->fcs_reg != -1);
12200 		MPASS(pi->fcs_base == 0);
12201 	}
12202 
12203 	for_each_vi(pi, v, vi) {
12204 		ifp = vi->ifp;
12205 		if (ifp == NULL)
12206 			continue;
12207 
12208 		if (lc->link_ok) {
12209 			ifp->if_baudrate = IF_Mbps(lc->speed);
12210 			if_link_state_change(ifp, LINK_STATE_UP);
12211 		} else {
12212 			if_link_state_change(ifp, LINK_STATE_DOWN);
12213 		}
12214 	}
12215 }
12216 
12217 void
12218 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12219 {
12220 	struct adapter *sc;
12221 
12222 	sx_slock(&t4_list_lock);
12223 	SLIST_FOREACH(sc, &t4_list, link) {
12224 		/*
12225 		 * func should not make any assumptions about what state sc is
12226 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12227 		 */
12228 		func(sc, arg);
12229 	}
12230 	sx_sunlock(&t4_list_lock);
12231 }
12232 
12233 static int
12234 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12235     struct thread *td)
12236 {
12237 	int rc;
12238 	struct adapter *sc = dev->si_drv1;
12239 
12240 	rc = priv_check(td, PRIV_DRIVER);
12241 	if (rc != 0)
12242 		return (rc);
12243 
12244 	switch (cmd) {
12245 	case CHELSIO_T4_GETREG: {
12246 		struct t4_reg *edata = (struct t4_reg *)data;
12247 
12248 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12249 			return (EFAULT);
12250 
12251 		mtx_lock(&sc->reg_lock);
12252 		if (hw_off_limits(sc))
12253 			rc = ENXIO;
12254 		else if (edata->size == 4)
12255 			edata->val = t4_read_reg(sc, edata->addr);
12256 		else if (edata->size == 8)
12257 			edata->val = t4_read_reg64(sc, edata->addr);
12258 		else
12259 			rc = EINVAL;
12260 		mtx_unlock(&sc->reg_lock);
12261 
12262 		break;
12263 	}
12264 	case CHELSIO_T4_SETREG: {
12265 		struct t4_reg *edata = (struct t4_reg *)data;
12266 
12267 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12268 			return (EFAULT);
12269 
12270 		mtx_lock(&sc->reg_lock);
12271 		if (hw_off_limits(sc))
12272 			rc = ENXIO;
12273 		else if (edata->size == 4) {
12274 			if (edata->val & 0xffffffff00000000)
12275 				rc = EINVAL;
12276 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12277 		} else if (edata->size == 8)
12278 			t4_write_reg64(sc, edata->addr, edata->val);
12279 		else
12280 			rc = EINVAL;
12281 		mtx_unlock(&sc->reg_lock);
12282 
12283 		break;
12284 	}
12285 	case CHELSIO_T4_REGDUMP: {
12286 		struct t4_regdump *regs = (struct t4_regdump *)data;
12287 		int reglen = t4_get_regs_len(sc);
12288 		uint8_t *buf;
12289 
12290 		if (regs->len < reglen) {
12291 			regs->len = reglen; /* hint to the caller */
12292 			return (ENOBUFS);
12293 		}
12294 
12295 		regs->len = reglen;
12296 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12297 		mtx_lock(&sc->reg_lock);
12298 		if (hw_off_limits(sc))
12299 			rc = ENXIO;
12300 		else
12301 			get_regs(sc, regs, buf);
12302 		mtx_unlock(&sc->reg_lock);
12303 		if (rc == 0)
12304 			rc = copyout(buf, regs->data, reglen);
12305 		free(buf, M_CXGBE);
12306 		break;
12307 	}
12308 	case CHELSIO_T4_GET_FILTER_MODE:
12309 		rc = get_filter_mode(sc, (uint32_t *)data);
12310 		break;
12311 	case CHELSIO_T4_SET_FILTER_MODE:
12312 		rc = set_filter_mode(sc, *(uint32_t *)data);
12313 		break;
12314 	case CHELSIO_T4_SET_FILTER_MASK:
12315 		rc = set_filter_mask(sc, *(uint32_t *)data);
12316 		break;
12317 	case CHELSIO_T4_GET_FILTER:
12318 		rc = get_filter(sc, (struct t4_filter *)data);
12319 		break;
12320 	case CHELSIO_T4_SET_FILTER:
12321 		rc = set_filter(sc, (struct t4_filter *)data);
12322 		break;
12323 	case CHELSIO_T4_DEL_FILTER:
12324 		rc = del_filter(sc, (struct t4_filter *)data);
12325 		break;
12326 	case CHELSIO_T4_GET_SGE_CONTEXT:
12327 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12328 		break;
12329 	case CHELSIO_T4_LOAD_FW:
12330 		rc = load_fw(sc, (struct t4_data *)data);
12331 		break;
12332 	case CHELSIO_T4_GET_MEM:
12333 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12334 		break;
12335 	case CHELSIO_T4_GET_I2C:
12336 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12337 		break;
12338 	case CHELSIO_T4_CLEAR_STATS:
12339 		rc = clear_stats(sc, *(uint32_t *)data);
12340 		break;
12341 	case CHELSIO_T4_SCHED_CLASS:
12342 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12343 		break;
12344 	case CHELSIO_T4_SCHED_QUEUE:
12345 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12346 		break;
12347 	case CHELSIO_T4_GET_TRACER:
12348 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12349 		break;
12350 	case CHELSIO_T4_SET_TRACER:
12351 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12352 		break;
12353 	case CHELSIO_T4_LOAD_CFG:
12354 		rc = load_cfg(sc, (struct t4_data *)data);
12355 		break;
12356 	case CHELSIO_T4_LOAD_BOOT:
12357 		rc = load_boot(sc, (struct t4_bootrom *)data);
12358 		break;
12359 	case CHELSIO_T4_LOAD_BOOTCFG:
12360 		rc = load_bootcfg(sc, (struct t4_data *)data);
12361 		break;
12362 	case CHELSIO_T4_CUDBG_DUMP:
12363 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12364 		break;
12365 	case CHELSIO_T4_SET_OFLD_POLICY:
12366 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12367 		break;
12368 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12369 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12370 		break;
12371 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12372 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12373 		break;
12374 	default:
12375 		rc = ENOTTY;
12376 	}
12377 
12378 	return (rc);
12379 }
12380 
12381 #ifdef TCP_OFFLOAD
12382 static int
12383 toe_capability(struct vi_info *vi, bool enable)
12384 {
12385 	int rc;
12386 	struct port_info *pi = vi->pi;
12387 	struct adapter *sc = pi->adapter;
12388 
12389 	ASSERT_SYNCHRONIZED_OP(sc);
12390 
12391 	if (!is_offload(sc))
12392 		return (ENODEV);
12393 	if (hw_off_limits(sc))
12394 		return (ENXIO);
12395 
12396 	if (enable) {
12397 #ifdef KERN_TLS
12398 		if (sc->flags & KERN_TLS_ON) {
12399 			int i, j, n;
12400 			struct port_info *p;
12401 			struct vi_info *v;
12402 
12403 			/*
12404 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12405 			 * on any ifnet.
12406 			 */
12407 			n = 0;
12408 			for_each_port(sc, i) {
12409 				p = sc->port[i];
12410 				for_each_vi(p, j, v) {
12411 					if (v->ifp->if_capenable & IFCAP_TXTLS) {
12412 						CH_WARN(sc,
12413 						    "%s has NIC TLS enabled.\n",
12414 						    device_get_nameunit(v->dev));
12415 						n++;
12416 					}
12417 				}
12418 			}
12419 			if (n > 0) {
12420 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12421 				    "associated with this adapter before "
12422 				    "trying to enable TOE.\n");
12423 				return (EAGAIN);
12424 			}
12425 			rc = t4_config_kern_tls(sc, false);
12426 			if (rc)
12427 				return (rc);
12428 		}
12429 #endif
12430 		if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
12431 			/* TOE is already enabled. */
12432 			return (0);
12433 		}
12434 
12435 		/*
12436 		 * We need the port's queues around so that we're able to send
12437 		 * and receive CPLs to/from the TOE even if the ifnet for this
12438 		 * port has never been UP'd administratively.
12439 		 */
12440 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12441 			return (rc);
12442 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12443 		    ((rc = vi_init(&pi->vi[0])) != 0))
12444 			return (rc);
12445 
12446 		if (isset(&sc->offload_map, pi->port_id)) {
12447 			/* TOE is enabled on another VI of this port. */
12448 			pi->uld_vis++;
12449 			return (0);
12450 		}
12451 
12452 		if (!uld_active(sc, ULD_TOM)) {
12453 			rc = t4_activate_uld(sc, ULD_TOM);
12454 			if (rc == EAGAIN) {
12455 				log(LOG_WARNING,
12456 				    "You must kldload t4_tom.ko before trying "
12457 				    "to enable TOE on a cxgbe interface.\n");
12458 			}
12459 			if (rc != 0)
12460 				return (rc);
12461 			KASSERT(sc->tom_softc != NULL,
12462 			    ("%s: TOM activated but softc NULL", __func__));
12463 			KASSERT(uld_active(sc, ULD_TOM),
12464 			    ("%s: TOM activated but flag not set", __func__));
12465 		}
12466 
12467 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12468 		if (!uld_active(sc, ULD_IWARP))
12469 			(void) t4_activate_uld(sc, ULD_IWARP);
12470 		if (!uld_active(sc, ULD_ISCSI))
12471 			(void) t4_activate_uld(sc, ULD_ISCSI);
12472 
12473 		pi->uld_vis++;
12474 		setbit(&sc->offload_map, pi->port_id);
12475 	} else {
12476 		pi->uld_vis--;
12477 
12478 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12479 			return (0);
12480 
12481 		KASSERT(uld_active(sc, ULD_TOM),
12482 		    ("%s: TOM never initialized?", __func__));
12483 		clrbit(&sc->offload_map, pi->port_id);
12484 	}
12485 
12486 	return (0);
12487 }
12488 
12489 /*
12490  * Add an upper layer driver to the global list.
12491  */
12492 int
12493 t4_register_uld(struct uld_info *ui)
12494 {
12495 	int rc = 0;
12496 	struct uld_info *u;
12497 
12498 	sx_xlock(&t4_uld_list_lock);
12499 	SLIST_FOREACH(u, &t4_uld_list, link) {
12500 	    if (u->uld_id == ui->uld_id) {
12501 		    rc = EEXIST;
12502 		    goto done;
12503 	    }
12504 	}
12505 
12506 	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
12507 	ui->refcount = 0;
12508 done:
12509 	sx_xunlock(&t4_uld_list_lock);
12510 	return (rc);
12511 }
12512 
12513 int
12514 t4_unregister_uld(struct uld_info *ui)
12515 {
12516 	int rc = EINVAL;
12517 	struct uld_info *u;
12518 
12519 	sx_xlock(&t4_uld_list_lock);
12520 
12521 	SLIST_FOREACH(u, &t4_uld_list, link) {
12522 	    if (u == ui) {
12523 		    if (ui->refcount > 0) {
12524 			    rc = EBUSY;
12525 			    goto done;
12526 		    }
12527 
12528 		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
12529 		    rc = 0;
12530 		    goto done;
12531 	    }
12532 	}
12533 done:
12534 	sx_xunlock(&t4_uld_list_lock);
12535 	return (rc);
12536 }
12537 
12538 int
12539 t4_activate_uld(struct adapter *sc, int id)
12540 {
12541 	int rc;
12542 	struct uld_info *ui;
12543 
12544 	ASSERT_SYNCHRONIZED_OP(sc);
12545 
12546 	if (id < 0 || id > ULD_MAX)
12547 		return (EINVAL);
12548 	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
12549 
12550 	sx_slock(&t4_uld_list_lock);
12551 
12552 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12553 		if (ui->uld_id == id) {
12554 			if (!(sc->flags & FULL_INIT_DONE)) {
12555 				rc = adapter_init(sc);
12556 				if (rc != 0)
12557 					break;
12558 			}
12559 
12560 			rc = ui->activate(sc);
12561 			if (rc == 0) {
12562 				setbit(&sc->active_ulds, id);
12563 				ui->refcount++;
12564 			}
12565 			break;
12566 		}
12567 	}
12568 
12569 	sx_sunlock(&t4_uld_list_lock);
12570 
12571 	return (rc);
12572 }
12573 
12574 int
12575 t4_deactivate_uld(struct adapter *sc, int id)
12576 {
12577 	int rc;
12578 	struct uld_info *ui;
12579 
12580 	ASSERT_SYNCHRONIZED_OP(sc);
12581 
12582 	if (id < 0 || id > ULD_MAX)
12583 		return (EINVAL);
12584 	rc = ENXIO;
12585 
12586 	sx_slock(&t4_uld_list_lock);
12587 
12588 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12589 		if (ui->uld_id == id) {
12590 			rc = ui->deactivate(sc);
12591 			if (rc == 0) {
12592 				clrbit(&sc->active_ulds, id);
12593 				ui->refcount--;
12594 			}
12595 			break;
12596 		}
12597 	}
12598 
12599 	sx_sunlock(&t4_uld_list_lock);
12600 
12601 	return (rc);
12602 }
12603 
12604 static int
12605 t4_deactivate_all_uld(struct adapter *sc)
12606 {
12607 	int rc;
12608 	struct uld_info *ui;
12609 
12610 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4detuld");
12611 	if (rc != 0)
12612 		return (ENXIO);
12613 
12614 	sx_slock(&t4_uld_list_lock);
12615 
12616 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12617 		if (isset(&sc->active_ulds, ui->uld_id)) {
12618 			rc = ui->deactivate(sc);
12619 			if (rc != 0)
12620 				break;
12621 			clrbit(&sc->active_ulds, ui->uld_id);
12622 			ui->refcount--;
12623 		}
12624 	}
12625 
12626 	sx_sunlock(&t4_uld_list_lock);
12627 	end_synchronized_op(sc, 0);
12628 
12629 	return (rc);
12630 }
12631 
12632 static void
12633 t4_async_event(struct adapter *sc)
12634 {
12635 	struct uld_info *ui;
12636 
12637 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
12638 		return;
12639 	sx_slock(&t4_uld_list_lock);
12640 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12641 		if (ui->uld_id == ULD_IWARP) {
12642 			ui->async_event(sc);
12643 			break;
12644 		}
12645 	}
12646 	sx_sunlock(&t4_uld_list_lock);
12647 	end_synchronized_op(sc, 0);
12648 }
12649 
12650 int
12651 uld_active(struct adapter *sc, int uld_id)
12652 {
12653 
12654 	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
12655 
12656 	return (isset(&sc->active_ulds, uld_id));
12657 }
12658 #endif
12659 
12660 #ifdef KERN_TLS
12661 static int
12662 ktls_capability(struct adapter *sc, bool enable)
12663 {
12664 	ASSERT_SYNCHRONIZED_OP(sc);
12665 
12666 	if (!is_ktls(sc))
12667 		return (ENODEV);
12668 	if (hw_off_limits(sc))
12669 		return (ENXIO);
12670 
12671 	if (enable) {
12672 		if (sc->flags & KERN_TLS_ON)
12673 			return (0);	/* already on */
12674 		if (sc->offload_map != 0) {
12675 			CH_WARN(sc,
12676 			    "Disable TOE on all interfaces associated with "
12677 			    "this adapter before trying to enable NIC TLS.\n");
12678 			return (EAGAIN);
12679 		}
12680 		return (t4_config_kern_tls(sc, true));
12681 	} else {
12682 		/*
12683 		 * Nothing to do for disable.  If TOE is enabled sometime later
12684 		 * then toe_capability will reconfigure the hardware.
12685 		 */
12686 		return (0);
12687 	}
12688 }
12689 #endif
12690 
12691 /*
12692  * t  = ptr to tunable.
12693  * nc = number of CPUs.
12694  * c  = compiled in default for that tunable.
12695  */
12696 static void
12697 calculate_nqueues(int *t, int nc, const int c)
12698 {
12699 	int nq;
12700 
12701 	if (*t > 0)
12702 		return;
12703 	nq = *t < 0 ? -*t : c;
12704 	*t = min(nc, nq);
12705 }
12706 
12707 /*
12708  * Come up with reasonable defaults for some of the tunables, provided they're
12709  * not set by the user (in which case we'll use the values as is).
12710  */
12711 static void
12712 tweak_tunables(void)
12713 {
12714 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12715 
12716 	if (t4_ntxq < 1) {
12717 #ifdef RSS
12718 		t4_ntxq = rss_getnumbuckets();
12719 #else
12720 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12721 #endif
12722 	}
12723 
12724 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12725 
12726 	if (t4_nrxq < 1) {
12727 #ifdef RSS
12728 		t4_nrxq = rss_getnumbuckets();
12729 #else
12730 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12731 #endif
12732 	}
12733 
12734 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12735 
12736 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12737 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12738 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12739 #endif
12740 #ifdef TCP_OFFLOAD
12741 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12742 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12743 #endif
12744 
12745 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12746 	if (t4_toecaps_allowed == -1)
12747 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12748 #else
12749 	if (t4_toecaps_allowed == -1)
12750 		t4_toecaps_allowed = 0;
12751 #endif
12752 
12753 #ifdef TCP_OFFLOAD
12754 	if (t4_rdmacaps_allowed == -1) {
12755 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12756 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12757 	}
12758 
12759 	if (t4_iscsicaps_allowed == -1) {
12760 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12761 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12762 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12763 	}
12764 
12765 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12766 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12767 
12768 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12769 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12770 
12771 	if (t4_toe_tls_rx_timeout < 0)
12772 		t4_toe_tls_rx_timeout = 0;
12773 #else
12774 	if (t4_rdmacaps_allowed == -1)
12775 		t4_rdmacaps_allowed = 0;
12776 
12777 	if (t4_iscsicaps_allowed == -1)
12778 		t4_iscsicaps_allowed = 0;
12779 #endif
12780 
12781 #ifdef DEV_NETMAP
12782 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12783 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12784 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12785 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12786 #endif
12787 
12788 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12789 		t4_tmr_idx = TMR_IDX;
12790 
12791 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12792 		t4_pktc_idx = PKTC_IDX;
12793 
12794 	if (t4_qsize_txq < 128)
12795 		t4_qsize_txq = 128;
12796 
12797 	if (t4_qsize_rxq < 128)
12798 		t4_qsize_rxq = 128;
12799 	while (t4_qsize_rxq & 7)
12800 		t4_qsize_rxq++;
12801 
12802 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12803 
12804 	/*
12805 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12806 	 * VI for the port.  The rest are additional virtual interfaces on the
12807 	 * same physical port.  Note that the main VI does not have native
12808 	 * netmap support but the extra VIs do.
12809 	 *
12810 	 * Limit the number of VIs per port to the number of available
12811 	 * MAC addresses per port.
12812 	 */
12813 	if (t4_num_vis < 1)
12814 		t4_num_vis = 1;
12815 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12816 		t4_num_vis = nitems(vi_mac_funcs);
12817 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12818 	}
12819 
12820 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12821 		pcie_relaxed_ordering = 1;
12822 #if defined(__i386__) || defined(__amd64__)
12823 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12824 			pcie_relaxed_ordering = 0;
12825 #endif
12826 	}
12827 }
12828 
12829 #ifdef DDB
12830 static void
12831 t4_dump_tcb(struct adapter *sc, int tid)
12832 {
12833 	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
12834 
12835 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12836 	save = t4_read_reg(sc, reg);
12837 	base = sc->memwin[2].mw_base;
12838 
12839 	/* Dump TCB for the tid */
12840 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12841 	tcb_addr += tid * TCB_SIZE;
12842 
12843 	if (is_t4(sc)) {
12844 		pf = 0;
12845 		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
12846 	} else {
12847 		pf = V_PFNUM(sc->pf);
12848 		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
12849 	}
12850 	t4_write_reg(sc, reg, win_pos | pf);
12851 	t4_read_reg(sc, reg);
12852 
12853 	off = tcb_addr - win_pos;
12854 	for (i = 0; i < 4; i++) {
12855 		uint32_t buf[8];
12856 		for (j = 0; j < 8; j++, off += 4)
12857 			buf[j] = htonl(t4_read_reg(sc, base + off));
12858 
12859 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12860 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12861 		    buf[7]);
12862 	}
12863 
12864 	t4_write_reg(sc, reg, save);
12865 	t4_read_reg(sc, reg);
12866 }
12867 
12868 static void
12869 t4_dump_devlog(struct adapter *sc)
12870 {
12871 	struct devlog_params *dparams = &sc->params.devlog;
12872 	struct fw_devlog_e e;
12873 	int i, first, j, m, nentries, rc;
12874 	uint64_t ftstamp = UINT64_MAX;
12875 
12876 	if (dparams->start == 0) {
12877 		db_printf("devlog params not valid\n");
12878 		return;
12879 	}
12880 
12881 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12882 	m = fwmtype_to_hwmtype(dparams->memtype);
12883 
12884 	/* Find the first entry. */
12885 	first = -1;
12886 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12887 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12888 		    sizeof(e), (void *)&e);
12889 		if (rc != 0)
12890 			break;
12891 
12892 		if (e.timestamp == 0)
12893 			break;
12894 
12895 		e.timestamp = be64toh(e.timestamp);
12896 		if (e.timestamp < ftstamp) {
12897 			ftstamp = e.timestamp;
12898 			first = i;
12899 		}
12900 	}
12901 
12902 	if (first == -1)
12903 		return;
12904 
12905 	i = first;
12906 	do {
12907 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12908 		    sizeof(e), (void *)&e);
12909 		if (rc != 0)
12910 			return;
12911 
12912 		if (e.timestamp == 0)
12913 			return;
12914 
12915 		e.timestamp = be64toh(e.timestamp);
12916 		e.seqno = be32toh(e.seqno);
12917 		for (j = 0; j < 8; j++)
12918 			e.params[j] = be32toh(e.params[j]);
12919 
12920 		db_printf("%10d  %15ju  %8s  %8s  ",
12921 		    e.seqno, e.timestamp,
12922 		    (e.level < nitems(devlog_level_strings) ?
12923 			devlog_level_strings[e.level] : "UNKNOWN"),
12924 		    (e.facility < nitems(devlog_facility_strings) ?
12925 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12926 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12927 		    e.params[3], e.params[4], e.params[5], e.params[6],
12928 		    e.params[7]);
12929 
12930 		if (++i == nentries)
12931 			i = 0;
12932 	} while (i != first && !db_pager_quit);
12933 }
12934 
12935 static struct command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
12936 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
12937 
12938 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
12939 {
12940 	device_t dev;
12941 	int t;
12942 	bool valid;
12943 
12944 	valid = false;
12945 	t = db_read_token();
12946 	if (t == tIDENT) {
12947 		dev = device_lookup_by_name(db_tok_string);
12948 		valid = true;
12949 	}
12950 	db_skip_to_eol();
12951 	if (!valid) {
12952 		db_printf("usage: show t4 devlog <nexus>\n");
12953 		return;
12954 	}
12955 
12956 	if (dev == NULL) {
12957 		db_printf("device not found\n");
12958 		return;
12959 	}
12960 
12961 	t4_dump_devlog(device_get_softc(dev));
12962 }
12963 
12964 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
12965 {
12966 	device_t dev;
12967 	int radix, tid, t;
12968 	bool valid;
12969 
12970 	valid = false;
12971 	radix = db_radix;
12972 	db_radix = 10;
12973 	t = db_read_token();
12974 	if (t == tIDENT) {
12975 		dev = device_lookup_by_name(db_tok_string);
12976 		t = db_read_token();
12977 		if (t == tNUMBER) {
12978 			tid = db_tok_number;
12979 			valid = true;
12980 		}
12981 	}
12982 	db_radix = radix;
12983 	db_skip_to_eol();
12984 	if (!valid) {
12985 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
12986 		return;
12987 	}
12988 
12989 	if (dev == NULL) {
12990 		db_printf("device not found\n");
12991 		return;
12992 	}
12993 	if (tid < 0) {
12994 		db_printf("invalid tid\n");
12995 		return;
12996 	}
12997 
12998 	t4_dump_tcb(device_get_softc(dev), tid);
12999 }
13000 #endif
13001 
13002 static eventhandler_tag vxlan_start_evtag;
13003 static eventhandler_tag vxlan_stop_evtag;
13004 
13005 struct vxlan_evargs {
13006 	struct ifnet *ifp;
13007 	uint16_t port;
13008 };
13009 
13010 static void
13011 enable_vxlan_rx(struct adapter *sc)
13012 {
13013 	int i, rc;
13014 	struct port_info *pi;
13015 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
13016 
13017 	ASSERT_SYNCHRONIZED_OP(sc);
13018 
13019 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
13020 	    F_VXLAN_EN);
13021 	for_each_port(sc, i) {
13022 		pi = sc->port[i];
13023 		if (pi->vxlan_tcam_entry == true)
13024 			continue;
13025 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
13026 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
13027 		    true);
13028 		if (rc < 0) {
13029 			rc = -rc;
13030 			CH_ERR(&pi->vi[0],
13031 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
13032 		} else {
13033 			MPASS(rc == sc->rawf_base + pi->port_id);
13034 			pi->vxlan_tcam_entry = true;
13035 		}
13036 	}
13037 }
13038 
13039 static void
13040 t4_vxlan_start(struct adapter *sc, void *arg)
13041 {
13042 	struct vxlan_evargs *v = arg;
13043 
13044 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13045 		return;
13046 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
13047 		return;
13048 
13049 	if (sc->vxlan_refcount == 0) {
13050 		sc->vxlan_port = v->port;
13051 		sc->vxlan_refcount = 1;
13052 		if (!hw_off_limits(sc))
13053 			enable_vxlan_rx(sc);
13054 	} else if (sc->vxlan_port == v->port) {
13055 		sc->vxlan_refcount++;
13056 	} else {
13057 		CH_ERR(sc, "VXLAN already configured on port  %d; "
13058 		    "ignoring attempt to configure it on port %d\n",
13059 		    sc->vxlan_port, v->port);
13060 	}
13061 	end_synchronized_op(sc, 0);
13062 }
13063 
13064 static void
13065 t4_vxlan_stop(struct adapter *sc, void *arg)
13066 {
13067 	struct vxlan_evargs *v = arg;
13068 
13069 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13070 		return;
13071 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
13072 		return;
13073 
13074 	/*
13075 	 * VXLANs may have been configured before the driver was loaded so we
13076 	 * may see more stops than starts.  This is not handled cleanly but at
13077 	 * least we keep the refcount sane.
13078 	 */
13079 	if (sc->vxlan_port != v->port)
13080 		goto done;
13081 	if (sc->vxlan_refcount == 0) {
13082 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
13083 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
13084 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
13085 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
13086 done:
13087 	end_synchronized_op(sc, 0);
13088 }
13089 
13090 static void
13091 t4_vxlan_start_handler(void *arg __unused, struct ifnet *ifp,
13092     sa_family_t family, u_int port)
13093 {
13094 	struct vxlan_evargs v;
13095 
13096 	MPASS(family == AF_INET || family == AF_INET6);
13097 	v.ifp = ifp;
13098 	v.port = port;
13099 
13100 	t4_iterate(t4_vxlan_start, &v);
13101 }
13102 
13103 static void
13104 t4_vxlan_stop_handler(void *arg __unused, struct ifnet *ifp, sa_family_t family,
13105     u_int port)
13106 {
13107 	struct vxlan_evargs v;
13108 
13109 	MPASS(family == AF_INET || family == AF_INET6);
13110 	v.ifp = ifp;
13111 	v.port = port;
13112 
13113 	t4_iterate(t4_vxlan_stop, &v);
13114 }
13115 
13116 
13117 static struct sx mlu;	/* mod load unload */
13118 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
13119 
13120 static int
13121 mod_event(module_t mod, int cmd, void *arg)
13122 {
13123 	int rc = 0;
13124 	static int loaded = 0;
13125 
13126 	switch (cmd) {
13127 	case MOD_LOAD:
13128 		sx_xlock(&mlu);
13129 		if (loaded++ == 0) {
13130 			t4_sge_modload();
13131 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13132 			    t4_filter_rpl, CPL_COOKIE_FILTER);
13133 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
13134 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
13135 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
13136 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
13137 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13138 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
13139 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
13140 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
13141 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
13142 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
13143 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
13144 			    do_smt_write_rpl);
13145 			sx_init(&t4_list_lock, "T4/T5 adapters");
13146 			SLIST_INIT(&t4_list);
13147 			callout_init(&fatal_callout, 1);
13148 #ifdef TCP_OFFLOAD
13149 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
13150 			SLIST_INIT(&t4_uld_list);
13151 #endif
13152 #ifdef INET6
13153 			t4_clip_modload();
13154 #endif
13155 #ifdef KERN_TLS
13156 			t6_ktls_modload();
13157 #endif
13158 			t4_tracer_modload();
13159 			tweak_tunables();
13160 			vxlan_start_evtag =
13161 			    EVENTHANDLER_REGISTER(vxlan_start,
13162 				t4_vxlan_start_handler, NULL,
13163 				EVENTHANDLER_PRI_ANY);
13164 			vxlan_stop_evtag =
13165 			    EVENTHANDLER_REGISTER(vxlan_stop,
13166 				t4_vxlan_stop_handler, NULL,
13167 				EVENTHANDLER_PRI_ANY);
13168 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
13169 			    taskqueue_thread_enqueue, &reset_tq);
13170 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
13171 			    "t4_rst_thr");
13172 		}
13173 		sx_xunlock(&mlu);
13174 		break;
13175 
13176 	case MOD_UNLOAD:
13177 		sx_xlock(&mlu);
13178 		if (--loaded == 0) {
13179 			int tries;
13180 
13181 			taskqueue_free(reset_tq);
13182 			sx_slock(&t4_list_lock);
13183 			if (!SLIST_EMPTY(&t4_list)) {
13184 				rc = EBUSY;
13185 				sx_sunlock(&t4_list_lock);
13186 				goto done_unload;
13187 			}
13188 #ifdef TCP_OFFLOAD
13189 			sx_slock(&t4_uld_list_lock);
13190 			if (!SLIST_EMPTY(&t4_uld_list)) {
13191 				rc = EBUSY;
13192 				sx_sunlock(&t4_uld_list_lock);
13193 				sx_sunlock(&t4_list_lock);
13194 				goto done_unload;
13195 			}
13196 #endif
13197 			tries = 0;
13198 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13199 				uprintf("%ju clusters with custom free routine "
13200 				    "still is use.\n", t4_sge_extfree_refs());
13201 				pause("t4unload", 2 * hz);
13202 			}
13203 #ifdef TCP_OFFLOAD
13204 			sx_sunlock(&t4_uld_list_lock);
13205 #endif
13206 			sx_sunlock(&t4_list_lock);
13207 
13208 			if (t4_sge_extfree_refs() == 0) {
13209 				EVENTHANDLER_DEREGISTER(vxlan_start,
13210 				    vxlan_start_evtag);
13211 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13212 				    vxlan_stop_evtag);
13213 				t4_tracer_modunload();
13214 #ifdef KERN_TLS
13215 				t6_ktls_modunload();
13216 #endif
13217 #ifdef INET6
13218 				t4_clip_modunload();
13219 #endif
13220 #ifdef TCP_OFFLOAD
13221 				sx_destroy(&t4_uld_list_lock);
13222 #endif
13223 				sx_destroy(&t4_list_lock);
13224 				t4_sge_modunload();
13225 				loaded = 0;
13226 			} else {
13227 				rc = EBUSY;
13228 				loaded++;	/* undo earlier decrement */
13229 			}
13230 		}
13231 done_unload:
13232 		sx_xunlock(&mlu);
13233 		break;
13234 	}
13235 
13236 	return (rc);
13237 }
13238 
13239 DRIVER_MODULE(t4nex, pci, t4_driver, mod_event, 0);
13240 MODULE_VERSION(t4nex, 1);
13241 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13242 #ifdef DEV_NETMAP
13243 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13244 #endif /* DEV_NETMAP */
13245 
13246 DRIVER_MODULE(t5nex, pci, t5_driver, mod_event, 0);
13247 MODULE_VERSION(t5nex, 1);
13248 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13249 #ifdef DEV_NETMAP
13250 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13251 #endif /* DEV_NETMAP */
13252 
13253 DRIVER_MODULE(t6nex, pci, t6_driver, mod_event, 0);
13254 MODULE_VERSION(t6nex, 1);
13255 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13256 #ifdef DEV_NETMAP
13257 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13258 #endif /* DEV_NETMAP */
13259 
13260 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, 0, 0);
13261 MODULE_VERSION(cxgbe, 1);
13262 
13263 DRIVER_MODULE(cxl, t5nex, cxl_driver, 0, 0);
13264 MODULE_VERSION(cxl, 1);
13265 
13266 DRIVER_MODULE(cc, t6nex, cc_driver, 0, 0);
13267 MODULE_VERSION(cc, 1);
13268 
13269 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, 0, 0);
13270 MODULE_VERSION(vcxgbe, 1);
13271 
13272 DRIVER_MODULE(vcxl, cxl, vcxl_driver, 0, 0);
13273 MODULE_VERSION(vcxl, 1);
13274 
13275 DRIVER_MODULE(vcc, cc, vcc_driver, 0, 0);
13276 MODULE_VERSION(vcc, 1);
13277