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