xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision ac099daf6742ead81ea7ea86351a8ef4e783041b)
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_str(device_t, device_t, char *, size_t);
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_str, t4_child_location_str),
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_str, t4_child_location_str),
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_str, t4_child_location_str),
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 static int cxgbe_snd_tag_modify(struct m_snd_tag *,
257     union if_snd_tag_modify_params *);
258 static int cxgbe_snd_tag_query(struct m_snd_tag *,
259     union if_snd_tag_query_params *);
260 static void cxgbe_snd_tag_free(struct m_snd_tag *);
261 #endif
262 
263 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
264 
265 /*
266  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
267  * then ADAPTER_LOCK, then t4_uld_list_lock.
268  */
269 static struct sx t4_list_lock;
270 SLIST_HEAD(, adapter) t4_list;
271 #ifdef TCP_OFFLOAD
272 static struct sx t4_uld_list_lock;
273 SLIST_HEAD(, uld_info) t4_uld_list;
274 #endif
275 
276 /*
277  * Tunables.  See tweak_tunables() too.
278  *
279  * Each tunable is set to a default value here if it's known at compile-time.
280  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
281  * provide a reasonable default (upto n) when the driver is loaded.
282  *
283  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
284  * T5 are under hw.cxl.
285  */
286 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
287     "cxgbe(4) parameters");
288 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
289     "cxgbe(4) T5+ parameters");
290 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
291     "cxgbe(4) TOE parameters");
292 
293 /*
294  * Number of queues for tx and rx, NIC and offload.
295  */
296 #define NTXQ 16
297 int t4_ntxq = -NTXQ;
298 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
299     "Number of TX queues per port");
300 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);	/* Old name, undocumented */
301 
302 #define NRXQ 8
303 int t4_nrxq = -NRXQ;
304 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
305     "Number of RX queues per port");
306 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);	/* Old name, undocumented */
307 
308 #define NTXQ_VI 1
309 static int t4_ntxq_vi = -NTXQ_VI;
310 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
311     "Number of TX queues per VI");
312 
313 #define NRXQ_VI 1
314 static int t4_nrxq_vi = -NRXQ_VI;
315 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
316     "Number of RX queues per VI");
317 
318 static int t4_rsrv_noflowq = 0;
319 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
320     0, "Reserve TX queue 0 of each VI for non-flowid packets");
321 
322 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
323 #define NOFLDTXQ 8
324 static int t4_nofldtxq = -NOFLDTXQ;
325 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
326     "Number of offload TX queues per port");
327 
328 #define NOFLDRXQ 2
329 static int t4_nofldrxq = -NOFLDRXQ;
330 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
331     "Number of offload RX queues per port");
332 
333 #define NOFLDTXQ_VI 1
334 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
335 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
336     "Number of offload TX queues per VI");
337 
338 #define NOFLDRXQ_VI 1
339 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
340 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
341     "Number of offload RX queues per VI");
342 
343 #define TMR_IDX_OFLD 1
344 int t4_tmr_idx_ofld = TMR_IDX_OFLD;
345 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
346     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
347 
348 #define PKTC_IDX_OFLD (-1)
349 int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
350 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
351     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
352 
353 /* 0 means chip/fw default, non-zero number is value in microseconds */
354 static u_long t4_toe_keepalive_idle = 0;
355 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
356     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
357 
358 /* 0 means chip/fw default, non-zero number is value in microseconds */
359 static u_long t4_toe_keepalive_interval = 0;
360 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
361     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
362 
363 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
364 static int t4_toe_keepalive_count = 0;
365 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
366     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
367 
368 /* 0 means chip/fw default, non-zero number is value in microseconds */
369 static u_long t4_toe_rexmt_min = 0;
370 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
371     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
372 
373 /* 0 means chip/fw default, non-zero number is value in microseconds */
374 static u_long t4_toe_rexmt_max = 0;
375 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
376     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
377 
378 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
379 static int t4_toe_rexmt_count = 0;
380 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
381     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
382 
383 /* -1 means chip/fw default, other values are raw backoff values to use */
384 static int t4_toe_rexmt_backoff[16] = {
385 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
386 };
387 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
388     CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
389     "cxgbe(4) TOE retransmit backoff values");
390 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
391     &t4_toe_rexmt_backoff[0], 0, "");
392 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
393     &t4_toe_rexmt_backoff[1], 0, "");
394 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
395     &t4_toe_rexmt_backoff[2], 0, "");
396 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
397     &t4_toe_rexmt_backoff[3], 0, "");
398 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
399     &t4_toe_rexmt_backoff[4], 0, "");
400 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
401     &t4_toe_rexmt_backoff[5], 0, "");
402 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
403     &t4_toe_rexmt_backoff[6], 0, "");
404 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
405     &t4_toe_rexmt_backoff[7], 0, "");
406 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
407     &t4_toe_rexmt_backoff[8], 0, "");
408 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
409     &t4_toe_rexmt_backoff[9], 0, "");
410 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
411     &t4_toe_rexmt_backoff[10], 0, "");
412 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
413     &t4_toe_rexmt_backoff[11], 0, "");
414 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
415     &t4_toe_rexmt_backoff[12], 0, "");
416 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
417     &t4_toe_rexmt_backoff[13], 0, "");
418 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
419     &t4_toe_rexmt_backoff[14], 0, "");
420 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
421     &t4_toe_rexmt_backoff[15], 0, "");
422 
423 static int t4_toe_tls_rx_timeout = 5;
424 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, tls_rx_timeout, CTLFLAG_RDTUN,
425     &t4_toe_tls_rx_timeout, 0,
426     "Timeout in seconds to downgrade TLS sockets to plain TOE");
427 #endif
428 
429 #ifdef DEV_NETMAP
430 #define NN_MAIN_VI	(1 << 0)	/* Native netmap on the main VI */
431 #define NN_EXTRA_VI	(1 << 1)	/* Native netmap on the extra VI(s) */
432 static int t4_native_netmap = NN_EXTRA_VI;
433 SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
434     0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
435 
436 #define NNMTXQ 8
437 static int t4_nnmtxq = -NNMTXQ;
438 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
439     "Number of netmap TX queues");
440 
441 #define NNMRXQ 8
442 static int t4_nnmrxq = -NNMRXQ;
443 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
444     "Number of netmap RX queues");
445 
446 #define NNMTXQ_VI 2
447 static int t4_nnmtxq_vi = -NNMTXQ_VI;
448 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
449     "Number of netmap TX queues per VI");
450 
451 #define NNMRXQ_VI 2
452 static int t4_nnmrxq_vi = -NNMRXQ_VI;
453 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
454     "Number of netmap RX queues per VI");
455 #endif
456 
457 /*
458  * Holdoff parameters for ports.
459  */
460 #define TMR_IDX 1
461 int t4_tmr_idx = TMR_IDX;
462 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
463     0, "Holdoff timer index");
464 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);	/* Old name */
465 
466 #define PKTC_IDX (-1)
467 int t4_pktc_idx = PKTC_IDX;
468 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
469     0, "Holdoff packet counter index");
470 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);	/* Old name */
471 
472 /*
473  * Size (# of entries) of each tx and rx queue.
474  */
475 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
476 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
477     "Number of descriptors in each TX queue");
478 
479 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
480 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
481     "Number of descriptors in each RX queue");
482 
483 /*
484  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
485  */
486 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
487 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
488     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
489 
490 /*
491  * Configuration file.  All the _CF names here are special.
492  */
493 #define DEFAULT_CF	"default"
494 #define BUILTIN_CF	"built-in"
495 #define FLASH_CF	"flash"
496 #define UWIRE_CF	"uwire"
497 #define FPGA_CF		"fpga"
498 static char t4_cfg_file[32] = DEFAULT_CF;
499 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
500     sizeof(t4_cfg_file), "Firmware configuration file");
501 
502 /*
503  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
504  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
505  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
506  *            mark or when signalled to do so, 0 to never emit PAUSE.
507  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
508  *                 negotiated settings will override rx_pause/tx_pause.
509  *                 Otherwise rx_pause/tx_pause are applied forcibly.
510  */
511 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
512 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
513     &t4_pause_settings, 0,
514     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
515 
516 /*
517  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
518  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
519  *  0 to disable FEC.
520  */
521 static int t4_fec = -1;
522 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
523     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
524 
525 /*
526  * Link autonegotiation.
527  * -1 to run with the firmware default.
528  *  0 to disable.
529  *  1 to enable.
530  */
531 static int t4_autoneg = -1;
532 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
533     "Link autonegotiation");
534 
535 /*
536  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
537  * encouraged respectively).  '-n' is the same as 'n' except the firmware
538  * version used in the checks is read from the firmware bundled with the driver.
539  */
540 static int t4_fw_install = 1;
541 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
542     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
543 
544 /*
545  * ASIC features that will be used.  Disable the ones you don't want so that the
546  * chip resources aren't wasted on features that will not be used.
547  */
548 static int t4_nbmcaps_allowed = 0;
549 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
550     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
551 
552 static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
553 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
554     &t4_linkcaps_allowed, 0, "Default link capabilities");
555 
556 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
557     FW_CAPS_CONFIG_SWITCH_EGRESS;
558 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
559     &t4_switchcaps_allowed, 0, "Default switch capabilities");
560 
561 #ifdef RATELIMIT
562 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
563 	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
564 #else
565 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
566 	FW_CAPS_CONFIG_NIC_HASHFILTER;
567 #endif
568 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
569     &t4_niccaps_allowed, 0, "Default NIC capabilities");
570 
571 static int t4_toecaps_allowed = -1;
572 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
573     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
574 
575 static int t4_rdmacaps_allowed = -1;
576 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
577     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
578 
579 static int t4_cryptocaps_allowed = -1;
580 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
581     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
582 
583 static int t4_iscsicaps_allowed = -1;
584 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
585     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
586 
587 static int t4_fcoecaps_allowed = 0;
588 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
589     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
590 
591 static int t5_write_combine = 0;
592 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
593     0, "Use WC instead of UC for BAR2");
594 
595 static int t4_num_vis = 1;
596 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
597     "Number of VIs per port");
598 
599 /*
600  * PCIe Relaxed Ordering.
601  * -1: driver should figure out a good value.
602  * 0: disable RO.
603  * 1: enable RO.
604  * 2: leave RO alone.
605  */
606 static int pcie_relaxed_ordering = -1;
607 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
608     &pcie_relaxed_ordering, 0,
609     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
610 
611 static int t4_panic_on_fatal_err = 0;
612 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
613     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
614 
615 static int t4_reset_on_fatal_err = 0;
616 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
617     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
618 
619 static int t4_tx_vm_wr = 0;
620 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
621     "Use VM work requests to transmit packets.");
622 
623 /*
624  * Set to non-zero to enable the attack filter.  A packet that matches any of
625  * these conditions will get dropped on ingress:
626  * 1) IP && source address == destination address.
627  * 2) TCP/IP && source address is not a unicast address.
628  * 3) TCP/IP && destination address is not a unicast address.
629  * 4) IP && source address is loopback (127.x.y.z).
630  * 5) IP && destination address is loopback (127.x.y.z).
631  * 6) IPv6 && source address == destination address.
632  * 7) IPv6 && source address is not a unicast address.
633  * 8) IPv6 && source address is loopback (::1/128).
634  * 9) IPv6 && destination address is loopback (::1/128).
635  * 10) IPv6 && source address is unspecified (::/128).
636  * 11) IPv6 && destination address is unspecified (::/128).
637  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
638  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
639  */
640 static int t4_attack_filter = 0;
641 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
642     &t4_attack_filter, 0, "Drop suspicious traffic");
643 
644 static int t4_drop_ip_fragments = 0;
645 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
646     &t4_drop_ip_fragments, 0, "Drop IP fragments");
647 
648 static int t4_drop_pkts_with_l2_errors = 1;
649 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
650     &t4_drop_pkts_with_l2_errors, 0,
651     "Drop all frames with Layer 2 length or checksum errors");
652 
653 static int t4_drop_pkts_with_l3_errors = 0;
654 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
655     &t4_drop_pkts_with_l3_errors, 0,
656     "Drop all frames with IP version, length, or checksum errors");
657 
658 static int t4_drop_pkts_with_l4_errors = 0;
659 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
660     &t4_drop_pkts_with_l4_errors, 0,
661     "Drop all frames with Layer 4 length, checksum, or other errors");
662 
663 #ifdef TCP_OFFLOAD
664 /*
665  * TOE tunables.
666  */
667 static int t4_cop_managed_offloading = 0;
668 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
669     &t4_cop_managed_offloading, 0,
670     "COP (Connection Offload Policy) controls all TOE offload");
671 #endif
672 
673 #ifdef KERN_TLS
674 /*
675  * This enables KERN_TLS for all adapters if set.
676  */
677 static int t4_kern_tls = 0;
678 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
679     "Enable KERN_TLS mode for all supported adapters");
680 
681 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
682     "cxgbe(4) KERN_TLS parameters");
683 
684 static int t4_tls_inline_keys = 0;
685 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
686     &t4_tls_inline_keys, 0,
687     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
688     "in card memory.");
689 
690 static int t4_tls_combo_wrs = 0;
691 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
692     0, "Attempt to combine TCB field updates with TLS record work requests.");
693 #endif
694 
695 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
696 static int vi_mac_funcs[] = {
697 	FW_VI_FUNC_ETH,
698 	FW_VI_FUNC_OFLD,
699 	FW_VI_FUNC_IWARP,
700 	FW_VI_FUNC_OPENISCSI,
701 	FW_VI_FUNC_OPENFCOE,
702 	FW_VI_FUNC_FOISCSI,
703 	FW_VI_FUNC_FOFCOE,
704 };
705 
706 struct intrs_and_queues {
707 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
708 	uint16_t num_vis;	/* number of VIs for each port */
709 	uint16_t nirq;		/* Total # of vectors */
710 	uint16_t ntxq;		/* # of NIC txq's for each port */
711 	uint16_t nrxq;		/* # of NIC rxq's for each port */
712 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
713 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
714 	uint16_t nnmtxq;	/* # of netmap txq's */
715 	uint16_t nnmrxq;	/* # of netmap rxq's */
716 
717 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
718 	uint16_t ntxq_vi;	/* # of NIC txq's */
719 	uint16_t nrxq_vi;	/* # of NIC rxq's */
720 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
721 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
722 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
723 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
724 };
725 
726 static void setup_memwin(struct adapter *);
727 static void position_memwin(struct adapter *, int, uint32_t);
728 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
729 static int fwmtype_to_hwmtype(int);
730 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
731     uint32_t *);
732 static int fixup_devlog_params(struct adapter *);
733 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
734 static int contact_firmware(struct adapter *);
735 static int partition_resources(struct adapter *);
736 static int get_params__pre_init(struct adapter *);
737 static int set_params__pre_init(struct adapter *);
738 static int get_params__post_init(struct adapter *);
739 static int set_params__post_init(struct adapter *);
740 static void t4_set_desc(struct adapter *);
741 static bool fixed_ifmedia(struct port_info *);
742 static void build_medialist(struct port_info *);
743 static void init_link_config(struct port_info *);
744 static int fixup_link_config(struct port_info *);
745 static int apply_link_config(struct port_info *);
746 static int cxgbe_init_synchronized(struct vi_info *);
747 static int cxgbe_uninit_synchronized(struct vi_info *);
748 static int adapter_full_init(struct adapter *);
749 static void adapter_full_uninit(struct adapter *);
750 static int vi_full_init(struct vi_info *);
751 static void vi_full_uninit(struct vi_info *);
752 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
753 static void quiesce_txq(struct sge_txq *);
754 static void quiesce_wrq(struct sge_wrq *);
755 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
756 static void quiesce_vi(struct vi_info *);
757 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
758     driver_intr_t *, void *, char *);
759 static int t4_free_irq(struct adapter *, struct irq *);
760 static void t4_init_atid_table(struct adapter *);
761 static void t4_free_atid_table(struct adapter *);
762 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
763 static void vi_refresh_stats(struct vi_info *);
764 static void cxgbe_refresh_stats(struct vi_info *);
765 static void cxgbe_tick(void *);
766 static void vi_tick(void *);
767 static void cxgbe_sysctls(struct port_info *);
768 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
769 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
770 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
771 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
772 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
773 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
774 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
775 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
776 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
777 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
778 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
779 static int sysctl_fec(SYSCTL_HANDLER_ARGS);
780 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
781 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
782 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
783 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
784 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
785 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
786 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
787 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
788 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
789 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
790 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
791 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
792 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
793 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
794 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
795 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
796 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
797 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
798 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
799 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
800 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
801 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
802 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
803 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
804 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
805 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
806 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
807 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
808 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
809 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
810 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
811 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
812 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
813 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
814 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
815 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
816 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
817 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
818 #ifdef TCP_OFFLOAD
819 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
820 static int sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS);
821 static int sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS);
822 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
823 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
824 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
825 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
826 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
827 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
828 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
829 #endif
830 static int get_sge_context(struct adapter *, struct t4_sge_context *);
831 static int load_fw(struct adapter *, struct t4_data *);
832 static int load_cfg(struct adapter *, struct t4_data *);
833 static int load_boot(struct adapter *, struct t4_bootrom *);
834 static int load_bootcfg(struct adapter *, struct t4_data *);
835 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
836 static void free_offload_policy(struct t4_offload_policy *);
837 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
838 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
839 static int read_i2c(struct adapter *, struct t4_i2c_data *);
840 static int clear_stats(struct adapter *, u_int);
841 #ifdef TCP_OFFLOAD
842 static int toe_capability(struct vi_info *, bool);
843 static void t4_async_event(void *, int);
844 #endif
845 #ifdef KERN_TLS
846 static int ktls_capability(struct adapter *, bool);
847 #endif
848 static int mod_event(module_t, int, void *);
849 static int notify_siblings(device_t, int);
850 static uint64_t vi_get_counter(struct ifnet *, ift_counter);
851 static uint64_t cxgbe_get_counter(struct ifnet *, ift_counter);
852 static void enable_vxlan_rx(struct adapter *);
853 static void reset_adapter(void *, int);
854 
855 struct {
856 	uint16_t device;
857 	char *desc;
858 } t4_pciids[] = {
859 	{0xa000, "Chelsio Terminator 4 FPGA"},
860 	{0x4400, "Chelsio T440-dbg"},
861 	{0x4401, "Chelsio T420-CR"},
862 	{0x4402, "Chelsio T422-CR"},
863 	{0x4403, "Chelsio T440-CR"},
864 	{0x4404, "Chelsio T420-BCH"},
865 	{0x4405, "Chelsio T440-BCH"},
866 	{0x4406, "Chelsio T440-CH"},
867 	{0x4407, "Chelsio T420-SO"},
868 	{0x4408, "Chelsio T420-CX"},
869 	{0x4409, "Chelsio T420-BT"},
870 	{0x440a, "Chelsio T404-BT"},
871 	{0x440e, "Chelsio T440-LP-CR"},
872 }, t5_pciids[] = {
873 	{0xb000, "Chelsio Terminator 5 FPGA"},
874 	{0x5400, "Chelsio T580-dbg"},
875 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
876 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
877 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
878 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
879 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
880 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
881 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
882 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
883 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
884 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
885 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
886 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
887 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
888 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
889 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
890 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
891 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
892 
893 	/* Custom */
894 	{0x5483, "Custom T540-CR"},
895 	{0x5484, "Custom T540-BT"},
896 }, t6_pciids[] = {
897 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
898 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
899 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
900 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
901 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
902 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
903 	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
904 	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
905 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
906 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
907 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
908 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
909 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
910 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
911 	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
912 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
913 
914 	/* Custom */
915 	{0x6480, "Custom T6225-CR"},
916 	{0x6481, "Custom T62100-CR"},
917 	{0x6482, "Custom T6225-CR"},
918 	{0x6483, "Custom T62100-CR"},
919 	{0x6484, "Custom T64100-CR"},
920 	{0x6485, "Custom T6240-SO"},
921 	{0x6486, "Custom T6225-SO-CR"},
922 	{0x6487, "Custom T6225-CR"},
923 };
924 
925 #ifdef TCP_OFFLOAD
926 /*
927  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
928  * be exactly the same for both rxq and ofld_rxq.
929  */
930 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
931 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
932 #endif
933 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
934 
935 static int
936 t4_probe(device_t dev)
937 {
938 	int i;
939 	uint16_t v = pci_get_vendor(dev);
940 	uint16_t d = pci_get_device(dev);
941 	uint8_t f = pci_get_function(dev);
942 
943 	if (v != PCI_VENDOR_ID_CHELSIO)
944 		return (ENXIO);
945 
946 	/* Attach only to PF0 of the FPGA */
947 	if (d == 0xa000 && f != 0)
948 		return (ENXIO);
949 
950 	for (i = 0; i < nitems(t4_pciids); i++) {
951 		if (d == t4_pciids[i].device) {
952 			device_set_desc(dev, t4_pciids[i].desc);
953 			return (BUS_PROBE_DEFAULT);
954 		}
955 	}
956 
957 	return (ENXIO);
958 }
959 
960 static int
961 t5_probe(device_t dev)
962 {
963 	int i;
964 	uint16_t v = pci_get_vendor(dev);
965 	uint16_t d = pci_get_device(dev);
966 	uint8_t f = pci_get_function(dev);
967 
968 	if (v != PCI_VENDOR_ID_CHELSIO)
969 		return (ENXIO);
970 
971 	/* Attach only to PF0 of the FPGA */
972 	if (d == 0xb000 && f != 0)
973 		return (ENXIO);
974 
975 	for (i = 0; i < nitems(t5_pciids); i++) {
976 		if (d == t5_pciids[i].device) {
977 			device_set_desc(dev, t5_pciids[i].desc);
978 			return (BUS_PROBE_DEFAULT);
979 		}
980 	}
981 
982 	return (ENXIO);
983 }
984 
985 static int
986 t6_probe(device_t dev)
987 {
988 	int i;
989 	uint16_t v = pci_get_vendor(dev);
990 	uint16_t d = pci_get_device(dev);
991 
992 	if (v != PCI_VENDOR_ID_CHELSIO)
993 		return (ENXIO);
994 
995 	for (i = 0; i < nitems(t6_pciids); i++) {
996 		if (d == t6_pciids[i].device) {
997 			device_set_desc(dev, t6_pciids[i].desc);
998 			return (BUS_PROBE_DEFAULT);
999 		}
1000 	}
1001 
1002 	return (ENXIO);
1003 }
1004 
1005 static void
1006 t5_attribute_workaround(device_t dev)
1007 {
1008 	device_t root_port;
1009 	uint32_t v;
1010 
1011 	/*
1012 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1013 	 * Ordering attributes when replying to a TLP from a Root
1014 	 * Port.  As a workaround, find the parent Root Port and
1015 	 * disable No Snoop and Relaxed Ordering.  Note that this
1016 	 * affects all devices under this root port.
1017 	 */
1018 	root_port = pci_find_pcie_root_port(dev);
1019 	if (root_port == NULL) {
1020 		device_printf(dev, "Unable to find parent root port\n");
1021 		return;
1022 	}
1023 
1024 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1025 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1026 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1027 	    0)
1028 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1029 		    device_get_nameunit(root_port));
1030 }
1031 
1032 static const struct devnames devnames[] = {
1033 	{
1034 		.nexus_name = "t4nex",
1035 		.ifnet_name = "cxgbe",
1036 		.vi_ifnet_name = "vcxgbe",
1037 		.pf03_drv_name = "t4iov",
1038 		.vf_nexus_name = "t4vf",
1039 		.vf_ifnet_name = "cxgbev"
1040 	}, {
1041 		.nexus_name = "t5nex",
1042 		.ifnet_name = "cxl",
1043 		.vi_ifnet_name = "vcxl",
1044 		.pf03_drv_name = "t5iov",
1045 		.vf_nexus_name = "t5vf",
1046 		.vf_ifnet_name = "cxlv"
1047 	}, {
1048 		.nexus_name = "t6nex",
1049 		.ifnet_name = "cc",
1050 		.vi_ifnet_name = "vcc",
1051 		.pf03_drv_name = "t6iov",
1052 		.vf_nexus_name = "t6vf",
1053 		.vf_ifnet_name = "ccv"
1054 	}
1055 };
1056 
1057 void
1058 t4_init_devnames(struct adapter *sc)
1059 {
1060 	int id;
1061 
1062 	id = chip_id(sc);
1063 	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1064 		sc->names = &devnames[id - CHELSIO_T4];
1065 	else {
1066 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1067 		sc->names = NULL;
1068 	}
1069 }
1070 
1071 static int
1072 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1073 {
1074 	const char *parent, *name;
1075 	long value;
1076 	int line, unit;
1077 
1078 	line = 0;
1079 	parent = device_get_nameunit(sc->dev);
1080 	name = sc->names->ifnet_name;
1081 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1082 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1083 		    value == pi->port_id)
1084 			return (unit);
1085 	}
1086 	return (-1);
1087 }
1088 
1089 static int
1090 t4_attach(device_t dev)
1091 {
1092 	struct adapter *sc;
1093 	int rc = 0, i, j, rqidx, tqidx, nports;
1094 	struct make_dev_args mda;
1095 	struct intrs_and_queues iaq;
1096 	struct sge *s;
1097 	uint32_t *buf;
1098 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1099 	int ofld_tqidx;
1100 #endif
1101 #ifdef TCP_OFFLOAD
1102 	int ofld_rqidx;
1103 #endif
1104 #ifdef DEV_NETMAP
1105 	int nm_rqidx, nm_tqidx;
1106 #endif
1107 	int num_vis;
1108 
1109 	sc = device_get_softc(dev);
1110 	sc->dev = dev;
1111 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1112 
1113 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1114 		t5_attribute_workaround(dev);
1115 	pci_enable_busmaster(dev);
1116 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1117 		uint32_t v;
1118 
1119 		pci_set_max_read_req(dev, 4096);
1120 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1121 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1122 		if (pcie_relaxed_ordering == 0 &&
1123 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1124 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1125 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1126 		} else if (pcie_relaxed_ordering == 1 &&
1127 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1128 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1129 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1130 		}
1131 	}
1132 
1133 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1134 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1135 	sc->traceq = -1;
1136 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1137 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1138 	    device_get_nameunit(dev));
1139 
1140 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1141 	    device_get_nameunit(dev));
1142 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1143 	t4_add_adapter(sc);
1144 
1145 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1146 	TAILQ_INIT(&sc->sfl);
1147 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1148 
1149 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1150 
1151 	sc->policy = NULL;
1152 	rw_init(&sc->policy_lock, "connection offload policy");
1153 
1154 	callout_init(&sc->ktls_tick, 1);
1155 
1156 #ifdef TCP_OFFLOAD
1157 	TASK_INIT(&sc->async_event_task, 0, t4_async_event, sc);
1158 #endif
1159 
1160 	refcount_init(&sc->vxlan_refcount, 0);
1161 
1162 	TASK_INIT(&sc->reset_task, 0, reset_adapter, sc);
1163 
1164 	sc->ctrlq_oid = SYSCTL_ADD_NODE(device_get_sysctl_ctx(sc->dev),
1165 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1166 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1167 	sc->fwq_oid = SYSCTL_ADD_NODE(device_get_sysctl_ctx(sc->dev),
1168 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1169 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1170 
1171 	rc = t4_map_bars_0_and_4(sc);
1172 	if (rc != 0)
1173 		goto done; /* error message displayed already */
1174 
1175 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1176 
1177 	/* Prepare the adapter for operation. */
1178 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1179 	rc = -t4_prep_adapter(sc, buf);
1180 	free(buf, M_CXGBE);
1181 	if (rc != 0) {
1182 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1183 		goto done;
1184 	}
1185 
1186 	/*
1187 	 * This is the real PF# to which we're attaching.  Works from within PCI
1188 	 * passthrough environments too, where pci_get_function() could return a
1189 	 * different PF# depending on the passthrough configuration.  We need to
1190 	 * use the real PF# in all our communication with the firmware.
1191 	 */
1192 	j = t4_read_reg(sc, A_PL_WHOAMI);
1193 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1194 	sc->mbox = sc->pf;
1195 
1196 	t4_init_devnames(sc);
1197 	if (sc->names == NULL) {
1198 		rc = ENOTSUP;
1199 		goto done; /* error message displayed already */
1200 	}
1201 
1202 	/*
1203 	 * Do this really early, with the memory windows set up even before the
1204 	 * character device.  The userland tool's register i/o and mem read
1205 	 * will work even in "recovery mode".
1206 	 */
1207 	setup_memwin(sc);
1208 	if (t4_init_devlog_params(sc, 0) == 0)
1209 		fixup_devlog_params(sc);
1210 	make_dev_args_init(&mda);
1211 	mda.mda_devsw = &t4_cdevsw;
1212 	mda.mda_uid = UID_ROOT;
1213 	mda.mda_gid = GID_WHEEL;
1214 	mda.mda_mode = 0600;
1215 	mda.mda_si_drv1 = sc;
1216 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1217 	if (rc != 0)
1218 		device_printf(dev, "failed to create nexus char device: %d.\n",
1219 		    rc);
1220 
1221 	/* Go no further if recovery mode has been requested. */
1222 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1223 		device_printf(dev, "recovery mode.\n");
1224 		goto done;
1225 	}
1226 
1227 #if defined(__i386__)
1228 	if ((cpu_feature & CPUID_CX8) == 0) {
1229 		device_printf(dev, "64 bit atomics not available.\n");
1230 		rc = ENOTSUP;
1231 		goto done;
1232 	}
1233 #endif
1234 
1235 	/* Contact the firmware and try to become the master driver. */
1236 	rc = contact_firmware(sc);
1237 	if (rc != 0)
1238 		goto done; /* error message displayed already */
1239 	MPASS(sc->flags & FW_OK);
1240 
1241 	rc = get_params__pre_init(sc);
1242 	if (rc != 0)
1243 		goto done; /* error message displayed already */
1244 
1245 	if (sc->flags & MASTER_PF) {
1246 		rc = partition_resources(sc);
1247 		if (rc != 0)
1248 			goto done; /* error message displayed already */
1249 		t4_intr_clear(sc);
1250 	}
1251 
1252 	rc = get_params__post_init(sc);
1253 	if (rc != 0)
1254 		goto done; /* error message displayed already */
1255 
1256 	rc = set_params__post_init(sc);
1257 	if (rc != 0)
1258 		goto done; /* error message displayed already */
1259 
1260 	rc = t4_map_bar_2(sc);
1261 	if (rc != 0)
1262 		goto done; /* error message displayed already */
1263 
1264 	rc = t4_create_dma_tag(sc);
1265 	if (rc != 0)
1266 		goto done; /* error message displayed already */
1267 
1268 	/*
1269 	 * First pass over all the ports - allocate VIs and initialize some
1270 	 * basic parameters like mac address, port type, etc.
1271 	 */
1272 	for_each_port(sc, i) {
1273 		struct port_info *pi;
1274 
1275 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1276 		sc->port[i] = pi;
1277 
1278 		/* These must be set before t4_port_init */
1279 		pi->adapter = sc;
1280 		pi->port_id = i;
1281 		/*
1282 		 * XXX: vi[0] is special so we can't delay this allocation until
1283 		 * pi->nvi's final value is known.
1284 		 */
1285 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1286 		    M_ZERO | M_WAITOK);
1287 
1288 		/*
1289 		 * Allocate the "main" VI and initialize parameters
1290 		 * like mac addr.
1291 		 */
1292 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1293 		if (rc != 0) {
1294 			device_printf(dev, "unable to initialize port %d: %d\n",
1295 			    i, rc);
1296 			free(pi->vi, M_CXGBE);
1297 			free(pi, M_CXGBE);
1298 			sc->port[i] = NULL;
1299 			goto done;
1300 		}
1301 
1302 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1303 		    device_get_nameunit(dev), i);
1304 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1305 		sc->chan_map[pi->tx_chan] = i;
1306 
1307 		/*
1308 		 * The MPS counter for FCS errors doesn't work correctly on the
1309 		 * T6 so we use the MAC counter here.  Which MAC is in use
1310 		 * depends on the link settings which will be known when the
1311 		 * link comes up.
1312 		 */
1313 		if (is_t6(sc)) {
1314 			pi->fcs_reg = -1;
1315 		} else if (is_t4(sc)) {
1316 			pi->fcs_reg = PORT_REG(pi->tx_chan,
1317 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1318 		} else {
1319 			pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
1320 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1321 		}
1322 		pi->fcs_base = 0;
1323 
1324 		/* All VIs on this port share this media. */
1325 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1326 		    cxgbe_media_status);
1327 
1328 		PORT_LOCK(pi);
1329 		init_link_config(pi);
1330 		fixup_link_config(pi);
1331 		build_medialist(pi);
1332 		if (fixed_ifmedia(pi))
1333 			pi->flags |= FIXED_IFMEDIA;
1334 		PORT_UNLOCK(pi);
1335 
1336 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1337 		    t4_ifnet_unit(sc, pi));
1338 		if (pi->dev == NULL) {
1339 			device_printf(dev,
1340 			    "failed to add device for port %d.\n", i);
1341 			rc = ENXIO;
1342 			goto done;
1343 		}
1344 		pi->vi[0].dev = pi->dev;
1345 		device_set_softc(pi->dev, pi);
1346 	}
1347 
1348 	/*
1349 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1350 	 */
1351 	nports = sc->params.nports;
1352 	rc = cfg_itype_and_nqueues(sc, &iaq);
1353 	if (rc != 0)
1354 		goto done; /* error message displayed already */
1355 
1356 	num_vis = iaq.num_vis;
1357 	sc->intr_type = iaq.intr_type;
1358 	sc->intr_count = iaq.nirq;
1359 
1360 	s = &sc->sge;
1361 	s->nrxq = nports * iaq.nrxq;
1362 	s->ntxq = nports * iaq.ntxq;
1363 	if (num_vis > 1) {
1364 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1365 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1366 	}
1367 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1368 	s->neq += nports;		/* ctrl queues: 1 per port */
1369 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1370 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1371 	if (is_offload(sc) || is_ethoffload(sc)) {
1372 		s->nofldtxq = nports * iaq.nofldtxq;
1373 		if (num_vis > 1)
1374 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1375 		s->neq += s->nofldtxq;
1376 
1377 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1378 		    M_CXGBE, M_ZERO | M_WAITOK);
1379 	}
1380 #endif
1381 #ifdef TCP_OFFLOAD
1382 	if (is_offload(sc)) {
1383 		s->nofldrxq = nports * iaq.nofldrxq;
1384 		if (num_vis > 1)
1385 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1386 		s->neq += s->nofldrxq;	/* free list */
1387 		s->niq += s->nofldrxq;
1388 
1389 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1390 		    M_CXGBE, M_ZERO | M_WAITOK);
1391 	}
1392 #endif
1393 #ifdef DEV_NETMAP
1394 	s->nnmrxq = 0;
1395 	s->nnmtxq = 0;
1396 	if (t4_native_netmap & NN_MAIN_VI) {
1397 		s->nnmrxq += nports * iaq.nnmrxq;
1398 		s->nnmtxq += nports * iaq.nnmtxq;
1399 	}
1400 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1401 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1402 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1403 	}
1404 	s->neq += s->nnmtxq + s->nnmrxq;
1405 	s->niq += s->nnmrxq;
1406 
1407 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1408 	    M_CXGBE, M_ZERO | M_WAITOK);
1409 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1410 	    M_CXGBE, M_ZERO | M_WAITOK);
1411 #endif
1412 	MPASS(s->niq <= s->iqmap_sz);
1413 	MPASS(s->neq <= s->eqmap_sz);
1414 
1415 	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1416 	    M_ZERO | M_WAITOK);
1417 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1418 	    M_ZERO | M_WAITOK);
1419 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1420 	    M_ZERO | M_WAITOK);
1421 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1422 	    M_ZERO | M_WAITOK);
1423 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1424 	    M_ZERO | M_WAITOK);
1425 
1426 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1427 	    M_ZERO | M_WAITOK);
1428 
1429 	t4_init_l2t(sc, M_WAITOK);
1430 	t4_init_smt(sc, M_WAITOK);
1431 	t4_init_tx_sched(sc);
1432 	t4_init_atid_table(sc);
1433 #ifdef RATELIMIT
1434 	t4_init_etid_table(sc);
1435 #endif
1436 #ifdef INET6
1437 	t4_init_clip_table(sc);
1438 #endif
1439 	if (sc->vres.key.size != 0)
1440 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1441 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1442 
1443 	/*
1444 	 * Second pass over the ports.  This time we know the number of rx and
1445 	 * tx queues that each port should get.
1446 	 */
1447 	rqidx = tqidx = 0;
1448 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1449 	ofld_tqidx = 0;
1450 #endif
1451 #ifdef TCP_OFFLOAD
1452 	ofld_rqidx = 0;
1453 #endif
1454 #ifdef DEV_NETMAP
1455 	nm_rqidx = nm_tqidx = 0;
1456 #endif
1457 	for_each_port(sc, i) {
1458 		struct port_info *pi = sc->port[i];
1459 		struct vi_info *vi;
1460 
1461 		if (pi == NULL)
1462 			continue;
1463 
1464 		pi->nvi = num_vis;
1465 		for_each_vi(pi, j, vi) {
1466 			vi->pi = pi;
1467 			vi->adapter = sc;
1468 			vi->first_intr = -1;
1469 			vi->qsize_rxq = t4_qsize_rxq;
1470 			vi->qsize_txq = t4_qsize_txq;
1471 
1472 			vi->first_rxq = rqidx;
1473 			vi->first_txq = tqidx;
1474 			vi->tmr_idx = t4_tmr_idx;
1475 			vi->pktc_idx = t4_pktc_idx;
1476 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1477 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1478 
1479 			rqidx += vi->nrxq;
1480 			tqidx += vi->ntxq;
1481 
1482 			if (j == 0 && vi->ntxq > 1)
1483 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1484 			else
1485 				vi->rsrv_noflowq = 0;
1486 
1487 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1488 			vi->first_ofld_txq = ofld_tqidx;
1489 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1490 			ofld_tqidx += vi->nofldtxq;
1491 #endif
1492 #ifdef TCP_OFFLOAD
1493 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1494 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1495 			vi->first_ofld_rxq = ofld_rqidx;
1496 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1497 
1498 			ofld_rqidx += vi->nofldrxq;
1499 #endif
1500 #ifdef DEV_NETMAP
1501 			vi->first_nm_rxq = nm_rqidx;
1502 			vi->first_nm_txq = nm_tqidx;
1503 			if (j == 0) {
1504 				vi->nnmrxq = iaq.nnmrxq;
1505 				vi->nnmtxq = iaq.nnmtxq;
1506 			} else {
1507 				vi->nnmrxq = iaq.nnmrxq_vi;
1508 				vi->nnmtxq = iaq.nnmtxq_vi;
1509 			}
1510 			nm_rqidx += vi->nnmrxq;
1511 			nm_tqidx += vi->nnmtxq;
1512 #endif
1513 		}
1514 	}
1515 
1516 	rc = t4_setup_intr_handlers(sc);
1517 	if (rc != 0) {
1518 		device_printf(dev,
1519 		    "failed to setup interrupt handlers: %d\n", rc);
1520 		goto done;
1521 	}
1522 
1523 	rc = bus_generic_probe(dev);
1524 	if (rc != 0) {
1525 		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1526 		goto done;
1527 	}
1528 
1529 	/*
1530 	 * Ensure thread-safe mailbox access (in debug builds).
1531 	 *
1532 	 * So far this was the only thread accessing the mailbox but various
1533 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1534 	 * will access the mailbox from different threads.
1535 	 */
1536 	sc->flags |= CHK_MBOX_ACCESS;
1537 
1538 	rc = bus_generic_attach(dev);
1539 	if (rc != 0) {
1540 		device_printf(dev,
1541 		    "failed to attach all child ports: %d\n", rc);
1542 		goto done;
1543 	}
1544 
1545 	device_printf(dev,
1546 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1547 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1548 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1549 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1550 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1551 
1552 	t4_set_desc(sc);
1553 
1554 	notify_siblings(dev, 0);
1555 
1556 done:
1557 	if (rc != 0 && sc->cdev) {
1558 		/* cdev was created and so cxgbetool works; recover that way. */
1559 		device_printf(dev,
1560 		    "error during attach, adapter is now in recovery mode.\n");
1561 		rc = 0;
1562 	}
1563 
1564 	if (rc != 0)
1565 		t4_detach_common(dev);
1566 	else
1567 		t4_sysctls(sc);
1568 
1569 	return (rc);
1570 }
1571 
1572 static int
1573 t4_child_location_str(device_t bus, device_t dev, char *buf, size_t buflen)
1574 {
1575 	struct adapter *sc;
1576 	struct port_info *pi;
1577 	int i;
1578 
1579 	sc = device_get_softc(bus);
1580 	buf[0] = '\0';
1581 	for_each_port(sc, i) {
1582 		pi = sc->port[i];
1583 		if (pi != NULL && pi->dev == dev) {
1584 			snprintf(buf, buflen, "port=%d", pi->port_id);
1585 			break;
1586 		}
1587 	}
1588 	return (0);
1589 }
1590 
1591 static int
1592 t4_ready(device_t dev)
1593 {
1594 	struct adapter *sc;
1595 
1596 	sc = device_get_softc(dev);
1597 	if (sc->flags & FW_OK)
1598 		return (0);
1599 	return (ENXIO);
1600 }
1601 
1602 static int
1603 t4_read_port_device(device_t dev, int port, device_t *child)
1604 {
1605 	struct adapter *sc;
1606 	struct port_info *pi;
1607 
1608 	sc = device_get_softc(dev);
1609 	if (port < 0 || port >= MAX_NPORTS)
1610 		return (EINVAL);
1611 	pi = sc->port[port];
1612 	if (pi == NULL || pi->dev == NULL)
1613 		return (ENXIO);
1614 	*child = pi->dev;
1615 	return (0);
1616 }
1617 
1618 static int
1619 notify_siblings(device_t dev, int detaching)
1620 {
1621 	device_t sibling;
1622 	int error, i;
1623 
1624 	error = 0;
1625 	for (i = 0; i < PCI_FUNCMAX; i++) {
1626 		if (i == pci_get_function(dev))
1627 			continue;
1628 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1629 		    pci_get_slot(dev), i);
1630 		if (sibling == NULL || !device_is_attached(sibling))
1631 			continue;
1632 		if (detaching)
1633 			error = T4_DETACH_CHILD(sibling);
1634 		else
1635 			(void)T4_ATTACH_CHILD(sibling);
1636 		if (error)
1637 			break;
1638 	}
1639 	return (error);
1640 }
1641 
1642 /*
1643  * Idempotent
1644  */
1645 static int
1646 t4_detach(device_t dev)
1647 {
1648 	struct adapter *sc;
1649 	int rc;
1650 
1651 	sc = device_get_softc(dev);
1652 
1653 	rc = notify_siblings(dev, 1);
1654 	if (rc) {
1655 		device_printf(dev,
1656 		    "failed to detach sibling devices: %d\n", rc);
1657 		return (rc);
1658 	}
1659 
1660 	return (t4_detach_common(dev));
1661 }
1662 
1663 int
1664 t4_detach_common(device_t dev)
1665 {
1666 	struct adapter *sc;
1667 	struct port_info *pi;
1668 	int i, rc;
1669 
1670 	sc = device_get_softc(dev);
1671 
1672 	if (sc->cdev) {
1673 		destroy_dev(sc->cdev);
1674 		sc->cdev = NULL;
1675 	}
1676 
1677 	sx_xlock(&t4_list_lock);
1678 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1679 	sx_xunlock(&t4_list_lock);
1680 
1681 	sc->flags &= ~CHK_MBOX_ACCESS;
1682 	if (sc->flags & FULL_INIT_DONE) {
1683 		if (!(sc->flags & IS_VF))
1684 			t4_intr_disable(sc);
1685 	}
1686 
1687 	if (device_is_attached(dev)) {
1688 		rc = bus_generic_detach(dev);
1689 		if (rc) {
1690 			device_printf(dev,
1691 			    "failed to detach child devices: %d\n", rc);
1692 			return (rc);
1693 		}
1694 	}
1695 
1696 #ifdef TCP_OFFLOAD
1697 	taskqueue_drain(taskqueue_thread, &sc->async_event_task);
1698 #endif
1699 
1700 	for (i = 0; i < sc->intr_count; i++)
1701 		t4_free_irq(sc, &sc->irq[i]);
1702 
1703 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1704 		t4_free_tx_sched(sc);
1705 
1706 	for (i = 0; i < MAX_NPORTS; i++) {
1707 		pi = sc->port[i];
1708 		if (pi) {
1709 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1710 			if (pi->dev)
1711 				device_delete_child(dev, pi->dev);
1712 
1713 			mtx_destroy(&pi->pi_lock);
1714 			free(pi->vi, M_CXGBE);
1715 			free(pi, M_CXGBE);
1716 		}
1717 	}
1718 
1719 	device_delete_children(dev);
1720 	adapter_full_uninit(sc);
1721 
1722 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1723 		t4_fw_bye(sc, sc->mbox);
1724 
1725 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1726 		pci_release_msi(dev);
1727 
1728 	if (sc->regs_res)
1729 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1730 		    sc->regs_res);
1731 
1732 	if (sc->udbs_res)
1733 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1734 		    sc->udbs_res);
1735 
1736 	if (sc->msix_res)
1737 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1738 		    sc->msix_res);
1739 
1740 	if (sc->l2t)
1741 		t4_free_l2t(sc->l2t);
1742 	if (sc->smt)
1743 		t4_free_smt(sc->smt);
1744 	t4_free_atid_table(sc);
1745 #ifdef RATELIMIT
1746 	t4_free_etid_table(sc);
1747 #endif
1748 	if (sc->key_map)
1749 		vmem_destroy(sc->key_map);
1750 #ifdef INET6
1751 	t4_destroy_clip_table(sc);
1752 #endif
1753 
1754 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1755 	free(sc->sge.ofld_txq, M_CXGBE);
1756 #endif
1757 #ifdef TCP_OFFLOAD
1758 	free(sc->sge.ofld_rxq, M_CXGBE);
1759 #endif
1760 #ifdef DEV_NETMAP
1761 	free(sc->sge.nm_rxq, M_CXGBE);
1762 	free(sc->sge.nm_txq, M_CXGBE);
1763 #endif
1764 	free(sc->irq, M_CXGBE);
1765 	free(sc->sge.rxq, M_CXGBE);
1766 	free(sc->sge.txq, M_CXGBE);
1767 	free(sc->sge.ctrlq, M_CXGBE);
1768 	free(sc->sge.iqmap, M_CXGBE);
1769 	free(sc->sge.eqmap, M_CXGBE);
1770 	free(sc->tids.ftid_tab, M_CXGBE);
1771 	free(sc->tids.hpftid_tab, M_CXGBE);
1772 	free_hftid_hash(&sc->tids);
1773 	free(sc->tids.tid_tab, M_CXGBE);
1774 	free(sc->tt.tls_rx_ports, M_CXGBE);
1775 	t4_destroy_dma_tag(sc);
1776 
1777 	callout_drain(&sc->ktls_tick);
1778 	callout_drain(&sc->sfl_callout);
1779 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1780 		mtx_destroy(&sc->tids.ftid_lock);
1781 		cv_destroy(&sc->tids.ftid_cv);
1782 	}
1783 	if (mtx_initialized(&sc->tids.atid_lock))
1784 		mtx_destroy(&sc->tids.atid_lock);
1785 	if (mtx_initialized(&sc->ifp_lock))
1786 		mtx_destroy(&sc->ifp_lock);
1787 
1788 	if (rw_initialized(&sc->policy_lock)) {
1789 		rw_destroy(&sc->policy_lock);
1790 #ifdef TCP_OFFLOAD
1791 		if (sc->policy != NULL)
1792 			free_offload_policy(sc->policy);
1793 #endif
1794 	}
1795 
1796 	for (i = 0; i < NUM_MEMWIN; i++) {
1797 		struct memwin *mw = &sc->memwin[i];
1798 
1799 		if (rw_initialized(&mw->mw_lock))
1800 			rw_destroy(&mw->mw_lock);
1801 	}
1802 
1803 	mtx_destroy(&sc->sfl_lock);
1804 	mtx_destroy(&sc->reg_lock);
1805 	mtx_destroy(&sc->sc_lock);
1806 
1807 	bzero(sc, sizeof(*sc));
1808 
1809 	return (0);
1810 }
1811 
1812 static inline bool
1813 ok_to_reset(struct adapter *sc)
1814 {
1815 	struct tid_info *t = &sc->tids;
1816 	struct port_info *pi;
1817 	struct vi_info *vi;
1818 	int i, j;
1819 	const int caps = IFCAP_TOE | IFCAP_TXTLS | IFCAP_NETMAP | IFCAP_TXRTLMT;
1820 
1821 	ASSERT_SYNCHRONIZED_OP(sc);
1822 	MPASS(!(sc->flags & IS_VF));
1823 
1824 	for_each_port(sc, i) {
1825 		pi = sc->port[i];
1826 		for_each_vi(pi, j, vi) {
1827 			if (vi->ifp->if_capenable & caps)
1828 				return (false);
1829 		}
1830 	}
1831 
1832 	if (atomic_load_int(&t->tids_in_use) > 0)
1833 		return (false);
1834 	if (atomic_load_int(&t->stids_in_use) > 0)
1835 		return (false);
1836 	if (atomic_load_int(&t->atids_in_use) > 0)
1837 		return (false);
1838 	if (atomic_load_int(&t->ftids_in_use) > 0)
1839 		return (false);
1840 	if (atomic_load_int(&t->hpftids_in_use) > 0)
1841 		return (false);
1842 	if (atomic_load_int(&t->etids_in_use) > 0)
1843 		return (false);
1844 
1845 	return (true);
1846 }
1847 
1848 static int
1849 t4_suspend(device_t dev)
1850 {
1851 	struct adapter *sc = device_get_softc(dev);
1852 	struct port_info *pi;
1853 	struct vi_info *vi;
1854 	struct ifnet *ifp;
1855 	struct sge_rxq *rxq;
1856 	struct sge_txq *txq;
1857 	struct sge_wrq *wrq;
1858 #ifdef TCP_OFFLOAD
1859 	struct sge_ofld_rxq *ofld_rxq;
1860 #endif
1861 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1862 	struct sge_ofld_txq *ofld_txq;
1863 #endif
1864 	int rc, i, j, k;
1865 
1866 	CH_ALERT(sc, "suspend requested\n");
1867 
1868 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4sus");
1869 	if (rc != 0)
1870 		return (ENXIO);
1871 
1872 	/* XXX: Can the kernel call suspend repeatedly without resume? */
1873 	MPASS(!hw_off_limits(sc));
1874 
1875 	if (!ok_to_reset(sc)) {
1876 		/* XXX: should list what resource is preventing suspend. */
1877 		CH_ERR(sc, "not safe to suspend.\n");
1878 		rc = EBUSY;
1879 		goto done;
1880 	}
1881 
1882 	/* No more DMA or interrupts. */
1883 	t4_shutdown_adapter(sc);
1884 
1885 	/* Quiesce all activity. */
1886 	for_each_port(sc, i) {
1887 		pi = sc->port[i];
1888 		pi->vxlan_tcam_entry = false;
1889 
1890 		PORT_LOCK(pi);
1891 		if (pi->up_vis > 0) {
1892 			/*
1893 			 * t4_shutdown_adapter has already shut down all the
1894 			 * PHYs but it also disables interrupts and DMA so there
1895 			 * won't be a link interrupt.  So we update the state
1896 			 * manually and inform the kernel.
1897 			 */
1898 			pi->link_cfg.link_ok = false;
1899 			t4_os_link_changed(pi);
1900 		}
1901 		PORT_UNLOCK(pi);
1902 
1903 		for_each_vi(pi, j, vi) {
1904 			vi->xact_addr_filt = -1;
1905 			if (!(vi->flags & VI_INIT_DONE))
1906 				continue;
1907 
1908 			ifp = vi->ifp;
1909 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1910 				mtx_lock(&vi->tick_mtx);
1911 				vi->flags |= VI_SKIP_STATS;
1912 				callout_stop(&vi->tick);
1913 				mtx_unlock(&vi->tick_mtx);
1914 				callout_drain(&vi->tick);
1915 			}
1916 
1917 			/*
1918 			 * Note that the HW is not available.
1919 			 */
1920 			for_each_txq(vi, k, txq) {
1921 				TXQ_LOCK(txq);
1922 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
1923 				TXQ_UNLOCK(txq);
1924 			}
1925 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1926 			for_each_ofld_txq(vi, k, ofld_txq) {
1927 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
1928 			}
1929 #endif
1930 			for_each_rxq(vi, k, rxq) {
1931 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1932 			}
1933 #if defined(TCP_OFFLOAD)
1934 			for_each_ofld_rxq(vi, k, ofld_rxq) {
1935 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1936 			}
1937 #endif
1938 
1939 			quiesce_vi(vi);
1940 		}
1941 
1942 		if (sc->flags & FULL_INIT_DONE) {
1943 			/* Control queue */
1944 			wrq = &sc->sge.ctrlq[i];
1945 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
1946 			quiesce_wrq(wrq);
1947 		}
1948 	}
1949 	if (sc->flags & FULL_INIT_DONE) {
1950 		/* Firmware event queue */
1951 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
1952 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
1953 	}
1954 
1955 	/* Mark the adapter totally off limits. */
1956 	mtx_lock(&sc->reg_lock);
1957 	sc->flags |= HW_OFF_LIMITS;
1958 	sc->flags &= ~(FW_OK | MASTER_PF);
1959 	sc->reset_thread = NULL;
1960 	mtx_unlock(&sc->reg_lock);
1961 
1962 	sc->num_resets++;
1963 	CH_ALERT(sc, "suspend completed.\n");
1964 done:
1965 	end_synchronized_op(sc, 0);
1966 	return (rc);
1967 }
1968 
1969 struct adapter_pre_reset_state {
1970 	u_int flags;
1971 	uint16_t nbmcaps;
1972 	uint16_t linkcaps;
1973 	uint16_t switchcaps;
1974 	uint16_t niccaps;
1975 	uint16_t toecaps;
1976 	uint16_t rdmacaps;
1977 	uint16_t cryptocaps;
1978 	uint16_t iscsicaps;
1979 	uint16_t fcoecaps;
1980 
1981 	u_int cfcsum;
1982 	char cfg_file[32];
1983 
1984 	struct adapter_params params;
1985 	struct t4_virt_res vres;
1986 	struct tid_info tids;
1987 	struct sge sge;
1988 
1989 	int rawf_base;
1990 	int nrawf;
1991 
1992 };
1993 
1994 static void
1995 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
1996 {
1997 
1998 	ASSERT_SYNCHRONIZED_OP(sc);
1999 
2000 	o->flags = sc->flags;
2001 
2002 	o->nbmcaps =  sc->nbmcaps;
2003 	o->linkcaps = sc->linkcaps;
2004 	o->switchcaps = sc->switchcaps;
2005 	o->niccaps = sc->niccaps;
2006 	o->toecaps = sc->toecaps;
2007 	o->rdmacaps = sc->rdmacaps;
2008 	o->cryptocaps = sc->cryptocaps;
2009 	o->iscsicaps = sc->iscsicaps;
2010 	o->fcoecaps = sc->fcoecaps;
2011 
2012 	o->cfcsum = sc->cfcsum;
2013 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2014 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2015 
2016 	o->params = sc->params;
2017 	o->vres = sc->vres;
2018 	o->tids = sc->tids;
2019 	o->sge = sc->sge;
2020 
2021 	o->rawf_base = sc->rawf_base;
2022 	o->nrawf = sc->nrawf;
2023 }
2024 
2025 static int
2026 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2027 {
2028 	int rc = 0;
2029 
2030 	ASSERT_SYNCHRONIZED_OP(sc);
2031 
2032 	/* Capabilities */
2033 #define COMPARE_CAPS(c) do { \
2034 	if (o->c##caps != sc->c##caps) { \
2035 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2036 		    sc->c##caps); \
2037 		rc = EINVAL; \
2038 	} \
2039 } while (0)
2040 	COMPARE_CAPS(nbm);
2041 	COMPARE_CAPS(link);
2042 	COMPARE_CAPS(switch);
2043 	COMPARE_CAPS(nic);
2044 	COMPARE_CAPS(toe);
2045 	COMPARE_CAPS(rdma);
2046 	COMPARE_CAPS(crypto);
2047 	COMPARE_CAPS(iscsi);
2048 	COMPARE_CAPS(fcoe);
2049 #undef COMPARE_CAPS
2050 
2051 	/* Firmware config file */
2052 	if (o->cfcsum != sc->cfcsum) {
2053 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2054 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2055 		rc = EINVAL;
2056 	}
2057 
2058 #define COMPARE_PARAM(p, name) do { \
2059 	if (o->p != sc->p) { \
2060 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2061 		rc = EINVAL; \
2062 	} \
2063 } while (0)
2064 	COMPARE_PARAM(sge.iq_start, iq_start);
2065 	COMPARE_PARAM(sge.eq_start, eq_start);
2066 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2067 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2068 	COMPARE_PARAM(tids.nftids, nftids);
2069 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2070 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2071 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2072 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2073 	COMPARE_PARAM(tids.tid_base, tid_base);
2074 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2075 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2076 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2077 	COMPARE_PARAM(rawf_base, rawf_base);
2078 	COMPARE_PARAM(nrawf, nrawf);
2079 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2080 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2081 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2082 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2083 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2084 	COMPARE_PARAM(tids.ntids, ntids);
2085 	COMPARE_PARAM(tids.etid_base, etid_base);
2086 	COMPARE_PARAM(tids.etid_end, etid_end);
2087 	COMPARE_PARAM(tids.netids, netids);
2088 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2089 	COMPARE_PARAM(params.ethoffload, ethoffload);
2090 	COMPARE_PARAM(tids.natids, natids);
2091 	COMPARE_PARAM(tids.stid_base, stid_base);
2092 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2093 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2094 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2095 	COMPARE_PARAM(vres.stag.start, stag_start);
2096 	COMPARE_PARAM(vres.stag.size, stag_size);
2097 	COMPARE_PARAM(vres.rq.start, rq_start);
2098 	COMPARE_PARAM(vres.rq.size, rq_size);
2099 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2100 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2101 	COMPARE_PARAM(vres.qp.start, qp_start);
2102 	COMPARE_PARAM(vres.qp.size, qp_size);
2103 	COMPARE_PARAM(vres.cq.start, cq_start);
2104 	COMPARE_PARAM(vres.cq.size, cq_size);
2105 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2106 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2107 	COMPARE_PARAM(vres.srq.start, srq_start);
2108 	COMPARE_PARAM(vres.srq.size, srq_size);
2109 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2110 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2111 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2112 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2113 	COMPARE_PARAM(vres.key.start, key_start);
2114 	COMPARE_PARAM(vres.key.size, key_size);
2115 #undef COMPARE_PARAM
2116 
2117 	return (rc);
2118 }
2119 
2120 static int
2121 t4_resume(device_t dev)
2122 {
2123 	struct adapter *sc = device_get_softc(dev);
2124 	struct adapter_pre_reset_state *old_state = NULL;
2125 	struct port_info *pi;
2126 	struct vi_info *vi;
2127 	struct ifnet *ifp;
2128 	struct sge_txq *txq;
2129 	int rc, i, j, k;
2130 
2131 	CH_ALERT(sc, "resume requested.\n");
2132 
2133 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4res");
2134 	if (rc != 0)
2135 		return (ENXIO);
2136 	MPASS(hw_off_limits(sc));
2137 	MPASS((sc->flags & FW_OK) == 0);
2138 	MPASS((sc->flags & MASTER_PF) == 0);
2139 	MPASS(sc->reset_thread == NULL);
2140 	sc->reset_thread = curthread;
2141 
2142 	/* Register access is expected to work by the time we're here. */
2143 	if (t4_read_reg(sc, A_PL_WHOAMI) == 0xffffffff) {
2144 		CH_ERR(sc, "%s: can't read device registers\n", __func__);
2145 		rc = ENXIO;
2146 		goto done;
2147 	}
2148 
2149 	/* Restore memory window. */
2150 	setup_memwin(sc);
2151 
2152 	/* Go no further if recovery mode has been requested. */
2153 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2154 		CH_ALERT(sc, "recovery mode on resume.\n");
2155 		rc = 0;
2156 		mtx_lock(&sc->reg_lock);
2157 		sc->flags &= ~HW_OFF_LIMITS;
2158 		mtx_unlock(&sc->reg_lock);
2159 		goto done;
2160 	}
2161 
2162 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2163 	save_caps_and_params(sc, old_state);
2164 
2165 	/* Reestablish contact with firmware and become the primary PF. */
2166 	rc = contact_firmware(sc);
2167 	if (rc != 0)
2168 		goto done; /* error message displayed already */
2169 	MPASS(sc->flags & FW_OK);
2170 
2171 	if (sc->flags & MASTER_PF) {
2172 		rc = partition_resources(sc);
2173 		if (rc != 0)
2174 			goto done; /* error message displayed already */
2175 		t4_intr_clear(sc);
2176 	}
2177 
2178 	rc = get_params__post_init(sc);
2179 	if (rc != 0)
2180 		goto done; /* error message displayed already */
2181 
2182 	rc = set_params__post_init(sc);
2183 	if (rc != 0)
2184 		goto done; /* error message displayed already */
2185 
2186 	rc = compare_caps_and_params(sc, old_state);
2187 	if (rc != 0)
2188 		goto done; /* error message displayed already */
2189 
2190 	for_each_port(sc, i) {
2191 		pi = sc->port[i];
2192 		MPASS(pi != NULL);
2193 		MPASS(pi->vi != NULL);
2194 		MPASS(pi->vi[0].dev == pi->dev);
2195 
2196 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2197 		if (rc != 0) {
2198 			CH_ERR(sc,
2199 			    "failed to re-initialize port %d: %d\n", i, rc);
2200 			goto done;
2201 		}
2202 		MPASS(sc->chan_map[pi->tx_chan] == i);
2203 
2204 		PORT_LOCK(pi);
2205 		fixup_link_config(pi);
2206 		build_medialist(pi);
2207 		PORT_UNLOCK(pi);
2208 		for_each_vi(pi, j, vi) {
2209 			if (IS_MAIN_VI(vi))
2210 				continue;
2211 			rc = alloc_extra_vi(sc, pi, vi);
2212 			if (rc != 0) {
2213 				CH_ERR(vi,
2214 				    "failed to re-allocate extra VI: %d\n", rc);
2215 				goto done;
2216 			}
2217 		}
2218 	}
2219 
2220 	/*
2221 	 * Interrupts and queues are about to be enabled and other threads will
2222 	 * want to access the hardware too.  It is safe to do so.  Note that
2223 	 * this thread is still in the middle of a synchronized_op.
2224 	 */
2225 	mtx_lock(&sc->reg_lock);
2226 	sc->flags &= ~HW_OFF_LIMITS;
2227 	mtx_unlock(&sc->reg_lock);
2228 
2229 	if (sc->flags & FULL_INIT_DONE) {
2230 		rc = adapter_full_init(sc);
2231 		if (rc != 0) {
2232 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2233 			goto done;
2234 		}
2235 
2236 		if (sc->vxlan_refcount > 0)
2237 			enable_vxlan_rx(sc);
2238 
2239 		for_each_port(sc, i) {
2240 			pi = sc->port[i];
2241 			for_each_vi(pi, j, vi) {
2242 				if (!(vi->flags & VI_INIT_DONE))
2243 					continue;
2244 				rc = vi_full_init(vi);
2245 				if (rc != 0) {
2246 					CH_ERR(vi, "failed to re-initialize "
2247 					    "interface: %d\n", rc);
2248 					goto done;
2249 				}
2250 
2251 				ifp = vi->ifp;
2252 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2253 					continue;
2254 				/*
2255 				 * Note that we do not setup multicast addresses
2256 				 * in the first pass.  This ensures that the
2257 				 * unicast DMACs for all VIs on all ports get an
2258 				 * MPS TCAM entry.
2259 				 */
2260 				rc = update_mac_settings(ifp, XGMAC_ALL &
2261 				    ~XGMAC_MCADDRS);
2262 				if (rc != 0) {
2263 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2264 					goto done;
2265 				}
2266 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2267 				    true);
2268 				if (rc != 0) {
2269 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2270 					goto done;
2271 				}
2272 				for_each_txq(vi, k, txq) {
2273 					TXQ_LOCK(txq);
2274 					txq->eq.flags |= EQ_ENABLED;
2275 					TXQ_UNLOCK(txq);
2276 				}
2277 				mtx_lock(&vi->tick_mtx);
2278 				vi->flags &= ~VI_SKIP_STATS;
2279 				callout_schedule(&vi->tick, hz);
2280 				mtx_unlock(&vi->tick_mtx);
2281 			}
2282 			PORT_LOCK(pi);
2283 			if (pi->up_vis > 0) {
2284 				t4_update_port_info(pi);
2285 				fixup_link_config(pi);
2286 				build_medialist(pi);
2287 				apply_link_config(pi);
2288 				if (pi->link_cfg.link_ok)
2289 					t4_os_link_changed(pi);
2290 			}
2291 			PORT_UNLOCK(pi);
2292 		}
2293 
2294 		/* Now reprogram the L2 multicast addresses. */
2295 		for_each_port(sc, i) {
2296 			pi = sc->port[i];
2297 			for_each_vi(pi, j, vi) {
2298 				if (!(vi->flags & VI_INIT_DONE))
2299 					continue;
2300 				ifp = vi->ifp;
2301 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2302 					continue;
2303 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2304 				if (rc != 0) {
2305 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2306 					rc = 0;	/* carry on */
2307 				}
2308 			}
2309 		}
2310 	}
2311 done:
2312 	if (rc == 0) {
2313 		sc->incarnation++;
2314 		CH_ALERT(sc, "resume completed.\n");
2315 	}
2316 	end_synchronized_op(sc, 0);
2317 	free(old_state, M_CXGBE);
2318 	return (rc);
2319 }
2320 
2321 static int
2322 t4_reset_prepare(device_t dev, device_t child)
2323 {
2324 	struct adapter *sc = device_get_softc(dev);
2325 
2326 	CH_ALERT(sc, "reset_prepare.\n");
2327 	return (0);
2328 }
2329 
2330 static int
2331 t4_reset_post(device_t dev, device_t child)
2332 {
2333 	struct adapter *sc = device_get_softc(dev);
2334 
2335 	CH_ALERT(sc, "reset_post.\n");
2336 	return (0);
2337 }
2338 
2339 static void
2340 reset_adapter(void *arg, int pending)
2341 {
2342 	struct adapter *sc = arg;
2343 	int rc;
2344 
2345 	CH_ALERT(sc, "reset requested.\n");
2346 
2347 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst1");
2348 	if (rc != 0)
2349 		return;
2350 
2351 	if (hw_off_limits(sc)) {
2352 		CH_ERR(sc, "adapter is suspended, use resume (not reset).\n");
2353 		rc = ENXIO;
2354 		goto done;
2355 	}
2356 
2357 	if (!ok_to_reset(sc)) {
2358 		/* XXX: should list what resource is preventing reset. */
2359 		CH_ERR(sc, "not safe to reset.\n");
2360 		rc = EBUSY;
2361 		goto done;
2362 	}
2363 
2364 done:
2365 	end_synchronized_op(sc, 0);
2366 	if (rc != 0)
2367 		return;	/* Error logged already. */
2368 
2369 	mtx_lock(&Giant);
2370 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2371 	mtx_unlock(&Giant);
2372 	if (rc != 0)
2373 		CH_ERR(sc, "bus_reset_child failed: %d.\n", rc);
2374 	else
2375 		CH_ALERT(sc, "bus_reset_child succeeded.\n");
2376 }
2377 
2378 static int
2379 cxgbe_probe(device_t dev)
2380 {
2381 	char buf[128];
2382 	struct port_info *pi = device_get_softc(dev);
2383 
2384 	snprintf(buf, sizeof(buf), "port %d", pi->port_id);
2385 	device_set_desc_copy(dev, buf);
2386 
2387 	return (BUS_PROBE_DEFAULT);
2388 }
2389 
2390 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2391     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2392     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2393     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2394 #define T4_CAP_ENABLE (T4_CAP)
2395 
2396 static int
2397 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2398 {
2399 	struct ifnet *ifp;
2400 	struct sbuf *sb;
2401 	struct sysctl_ctx_list *ctx;
2402 	struct sysctl_oid_list *children;
2403 	struct pfil_head_args pa;
2404 	struct adapter *sc = vi->adapter;
2405 
2406 	ctx = device_get_sysctl_ctx(vi->dev);
2407 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2408 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2409 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2410 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2411 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2412 #ifdef DEV_NETMAP
2413 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2414 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2415 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2416 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2417 #endif
2418 #ifdef TCP_OFFLOAD
2419 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2420 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2421 #endif
2422 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2423 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2424 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2425 #endif
2426 
2427 	vi->xact_addr_filt = -1;
2428 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2429 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2430 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2431 		vi->flags |= TX_USES_VM_WR;
2432 
2433 	/* Allocate an ifnet and set it up */
2434 	ifp = if_alloc_dev(IFT_ETHER, dev);
2435 	if (ifp == NULL) {
2436 		device_printf(dev, "Cannot allocate ifnet\n");
2437 		return (ENOMEM);
2438 	}
2439 	vi->ifp = ifp;
2440 	ifp->if_softc = vi;
2441 
2442 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2443 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
2444 
2445 	ifp->if_init = cxgbe_init;
2446 	ifp->if_ioctl = cxgbe_ioctl;
2447 	ifp->if_transmit = cxgbe_transmit;
2448 	ifp->if_qflush = cxgbe_qflush;
2449 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2450 		ifp->if_get_counter = vi_get_counter;
2451 	else
2452 		ifp->if_get_counter = cxgbe_get_counter;
2453 #if defined(KERN_TLS) || defined(RATELIMIT)
2454 	ifp->if_snd_tag_alloc = cxgbe_snd_tag_alloc;
2455 	ifp->if_snd_tag_modify = cxgbe_snd_tag_modify;
2456 	ifp->if_snd_tag_query = cxgbe_snd_tag_query;
2457 	ifp->if_snd_tag_free = cxgbe_snd_tag_free;
2458 #endif
2459 #ifdef RATELIMIT
2460 	ifp->if_ratelimit_query = cxgbe_ratelimit_query;
2461 #endif
2462 
2463 	ifp->if_capabilities = T4_CAP;
2464 	ifp->if_capenable = T4_CAP_ENABLE;
2465 	ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2466 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6;
2467 	if (chip_id(sc) >= CHELSIO_T6) {
2468 		ifp->if_capabilities |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2469 		ifp->if_capenable |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2470 		ifp->if_hwassist |= CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2471 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2472 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN;
2473 	}
2474 
2475 #ifdef TCP_OFFLOAD
2476 	if (vi->nofldrxq != 0)
2477 		ifp->if_capabilities |= IFCAP_TOE;
2478 #endif
2479 #ifdef RATELIMIT
2480 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2481 		ifp->if_capabilities |= IFCAP_TXRTLMT;
2482 		ifp->if_capenable |= IFCAP_TXRTLMT;
2483 	}
2484 #endif
2485 
2486 	ifp->if_hw_tsomax = IP_MAXPACKET;
2487 	if (vi->flags & TX_USES_VM_WR)
2488 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
2489 	else
2490 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
2491 #ifdef RATELIMIT
2492 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2493 		ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_EO_TSO;
2494 #endif
2495 	ifp->if_hw_tsomaxsegsize = 65536;
2496 #ifdef KERN_TLS
2497 	if (is_ktls(sc)) {
2498 		ifp->if_capabilities |= IFCAP_TXTLS;
2499 		if (sc->flags & KERN_TLS_ON)
2500 			ifp->if_capenable |= IFCAP_TXTLS;
2501 	}
2502 #endif
2503 
2504 	ether_ifattach(ifp, vi->hw_addr);
2505 #ifdef DEV_NETMAP
2506 	if (vi->nnmrxq != 0)
2507 		cxgbe_nm_attach(vi);
2508 #endif
2509 	sb = sbuf_new_auto();
2510 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2511 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2512 	switch (ifp->if_capabilities & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2513 	case IFCAP_TOE:
2514 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2515 		break;
2516 	case IFCAP_TOE | IFCAP_TXRTLMT:
2517 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2518 		break;
2519 	case IFCAP_TXRTLMT:
2520 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2521 		break;
2522 	}
2523 #endif
2524 #ifdef TCP_OFFLOAD
2525 	if (ifp->if_capabilities & IFCAP_TOE)
2526 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2527 #endif
2528 #ifdef DEV_NETMAP
2529 	if (ifp->if_capabilities & IFCAP_NETMAP)
2530 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2531 		    vi->nnmtxq, vi->nnmrxq);
2532 #endif
2533 	sbuf_finish(sb);
2534 	device_printf(dev, "%s\n", sbuf_data(sb));
2535 	sbuf_delete(sb);
2536 
2537 	vi_sysctls(vi);
2538 
2539 	pa.pa_version = PFIL_VERSION;
2540 	pa.pa_flags = PFIL_IN;
2541 	pa.pa_type = PFIL_TYPE_ETHERNET;
2542 	pa.pa_headname = ifp->if_xname;
2543 	vi->pfil = pfil_head_register(&pa);
2544 
2545 	return (0);
2546 }
2547 
2548 static int
2549 cxgbe_attach(device_t dev)
2550 {
2551 	struct port_info *pi = device_get_softc(dev);
2552 	struct adapter *sc = pi->adapter;
2553 	struct vi_info *vi;
2554 	int i, rc;
2555 
2556 	rc = cxgbe_vi_attach(dev, &pi->vi[0]);
2557 	if (rc)
2558 		return (rc);
2559 
2560 	for_each_vi(pi, i, vi) {
2561 		if (i == 0)
2562 			continue;
2563 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
2564 		if (vi->dev == NULL) {
2565 			device_printf(dev, "failed to add VI %d\n", i);
2566 			continue;
2567 		}
2568 		device_set_softc(vi->dev, vi);
2569 	}
2570 
2571 	cxgbe_sysctls(pi);
2572 
2573 	bus_generic_attach(dev);
2574 
2575 	return (0);
2576 }
2577 
2578 static void
2579 cxgbe_vi_detach(struct vi_info *vi)
2580 {
2581 	struct ifnet *ifp = vi->ifp;
2582 
2583 	if (vi->pfil != NULL) {
2584 		pfil_head_unregister(vi->pfil);
2585 		vi->pfil = NULL;
2586 	}
2587 
2588 	ether_ifdetach(ifp);
2589 
2590 	/* Let detach proceed even if these fail. */
2591 #ifdef DEV_NETMAP
2592 	if (ifp->if_capabilities & IFCAP_NETMAP)
2593 		cxgbe_nm_detach(vi);
2594 #endif
2595 	cxgbe_uninit_synchronized(vi);
2596 	callout_drain(&vi->tick);
2597 	vi_full_uninit(vi);
2598 
2599 	if_free(vi->ifp);
2600 	vi->ifp = NULL;
2601 }
2602 
2603 static int
2604 cxgbe_detach(device_t dev)
2605 {
2606 	struct port_info *pi = device_get_softc(dev);
2607 	struct adapter *sc = pi->adapter;
2608 	int rc;
2609 
2610 	/* Detach the extra VIs first. */
2611 	rc = bus_generic_detach(dev);
2612 	if (rc)
2613 		return (rc);
2614 	device_delete_children(dev);
2615 
2616 	doom_vi(sc, &pi->vi[0]);
2617 
2618 	if (pi->flags & HAS_TRACEQ) {
2619 		sc->traceq = -1;	/* cloner should not create ifnet */
2620 		t4_tracer_port_detach(sc);
2621 	}
2622 
2623 	cxgbe_vi_detach(&pi->vi[0]);
2624 	ifmedia_removeall(&pi->media);
2625 
2626 	end_synchronized_op(sc, 0);
2627 
2628 	return (0);
2629 }
2630 
2631 static void
2632 cxgbe_init(void *arg)
2633 {
2634 	struct vi_info *vi = arg;
2635 	struct adapter *sc = vi->adapter;
2636 
2637 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2638 		return;
2639 	cxgbe_init_synchronized(vi);
2640 	end_synchronized_op(sc, 0);
2641 }
2642 
2643 static int
2644 cxgbe_ioctl(struct ifnet *ifp, unsigned long cmd, caddr_t data)
2645 {
2646 	int rc = 0, mtu, flags;
2647 	struct vi_info *vi = ifp->if_softc;
2648 	struct port_info *pi = vi->pi;
2649 	struct adapter *sc = pi->adapter;
2650 	struct ifreq *ifr = (struct ifreq *)data;
2651 	uint32_t mask;
2652 
2653 	switch (cmd) {
2654 	case SIOCSIFMTU:
2655 		mtu = ifr->ifr_mtu;
2656 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2657 			return (EINVAL);
2658 
2659 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2660 		if (rc)
2661 			return (rc);
2662 		ifp->if_mtu = mtu;
2663 		if (vi->flags & VI_INIT_DONE) {
2664 			t4_update_fl_bufsize(ifp);
2665 			if (!hw_off_limits(sc) &&
2666 			    ifp->if_drv_flags & IFF_DRV_RUNNING)
2667 				rc = update_mac_settings(ifp, XGMAC_MTU);
2668 		}
2669 		end_synchronized_op(sc, 0);
2670 		break;
2671 
2672 	case SIOCSIFFLAGS:
2673 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2674 		if (rc)
2675 			return (rc);
2676 
2677 		if (hw_off_limits(sc)) {
2678 			rc = ENXIO;
2679 			goto fail;
2680 		}
2681 
2682 		if (ifp->if_flags & IFF_UP) {
2683 			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2684 				flags = vi->if_flags;
2685 				if ((ifp->if_flags ^ flags) &
2686 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2687 					rc = update_mac_settings(ifp,
2688 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2689 				}
2690 			} else {
2691 				rc = cxgbe_init_synchronized(vi);
2692 			}
2693 			vi->if_flags = ifp->if_flags;
2694 		} else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2695 			rc = cxgbe_uninit_synchronized(vi);
2696 		}
2697 		end_synchronized_op(sc, 0);
2698 		break;
2699 
2700 	case SIOCADDMULTI:
2701 	case SIOCDELMULTI:
2702 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2703 		if (rc)
2704 			return (rc);
2705 		if (!hw_off_limits(sc) && ifp->if_drv_flags & IFF_DRV_RUNNING)
2706 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2707 		end_synchronized_op(sc, 0);
2708 		break;
2709 
2710 	case SIOCSIFCAP:
2711 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2712 		if (rc)
2713 			return (rc);
2714 
2715 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
2716 		if (mask & IFCAP_TXCSUM) {
2717 			ifp->if_capenable ^= IFCAP_TXCSUM;
2718 			ifp->if_hwassist ^= (CSUM_TCP | CSUM_UDP | CSUM_IP);
2719 
2720 			if (IFCAP_TSO4 & ifp->if_capenable &&
2721 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2722 				mask &= ~IFCAP_TSO4;
2723 				ifp->if_capenable &= ~IFCAP_TSO4;
2724 				if_printf(ifp,
2725 				    "tso4 disabled due to -txcsum.\n");
2726 			}
2727 		}
2728 		if (mask & IFCAP_TXCSUM_IPV6) {
2729 			ifp->if_capenable ^= IFCAP_TXCSUM_IPV6;
2730 			ifp->if_hwassist ^= (CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2731 
2732 			if (IFCAP_TSO6 & ifp->if_capenable &&
2733 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2734 				mask &= ~IFCAP_TSO6;
2735 				ifp->if_capenable &= ~IFCAP_TSO6;
2736 				if_printf(ifp,
2737 				    "tso6 disabled due to -txcsum6.\n");
2738 			}
2739 		}
2740 		if (mask & IFCAP_RXCSUM)
2741 			ifp->if_capenable ^= IFCAP_RXCSUM;
2742 		if (mask & IFCAP_RXCSUM_IPV6)
2743 			ifp->if_capenable ^= IFCAP_RXCSUM_IPV6;
2744 
2745 		/*
2746 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2747 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2748 		 * sending a TSO request our way, so it's sufficient to toggle
2749 		 * IFCAP_TSOx only.
2750 		 */
2751 		if (mask & IFCAP_TSO4) {
2752 			if (!(IFCAP_TSO4 & ifp->if_capenable) &&
2753 			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
2754 				if_printf(ifp, "enable txcsum first.\n");
2755 				rc = EAGAIN;
2756 				goto fail;
2757 			}
2758 			ifp->if_capenable ^= IFCAP_TSO4;
2759 		}
2760 		if (mask & IFCAP_TSO6) {
2761 			if (!(IFCAP_TSO6 & ifp->if_capenable) &&
2762 			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2763 				if_printf(ifp, "enable txcsum6 first.\n");
2764 				rc = EAGAIN;
2765 				goto fail;
2766 			}
2767 			ifp->if_capenable ^= IFCAP_TSO6;
2768 		}
2769 		if (mask & IFCAP_LRO) {
2770 #if defined(INET) || defined(INET6)
2771 			int i;
2772 			struct sge_rxq *rxq;
2773 
2774 			ifp->if_capenable ^= IFCAP_LRO;
2775 			for_each_rxq(vi, i, rxq) {
2776 				if (ifp->if_capenable & IFCAP_LRO)
2777 					rxq->iq.flags |= IQ_LRO_ENABLED;
2778 				else
2779 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2780 			}
2781 #endif
2782 		}
2783 #ifdef TCP_OFFLOAD
2784 		if (mask & IFCAP_TOE) {
2785 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TOE;
2786 
2787 			rc = toe_capability(vi, enable);
2788 			if (rc != 0)
2789 				goto fail;
2790 
2791 			ifp->if_capenable ^= mask;
2792 		}
2793 #endif
2794 		if (mask & IFCAP_VLAN_HWTAGGING) {
2795 			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
2796 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2797 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2798 		}
2799 		if (mask & IFCAP_VLAN_MTU) {
2800 			ifp->if_capenable ^= IFCAP_VLAN_MTU;
2801 
2802 			/* Need to find out how to disable auto-mtu-inflation */
2803 		}
2804 		if (mask & IFCAP_VLAN_HWTSO)
2805 			ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
2806 		if (mask & IFCAP_VLAN_HWCSUM)
2807 			ifp->if_capenable ^= IFCAP_VLAN_HWCSUM;
2808 #ifdef RATELIMIT
2809 		if (mask & IFCAP_TXRTLMT)
2810 			ifp->if_capenable ^= IFCAP_TXRTLMT;
2811 #endif
2812 		if (mask & IFCAP_HWRXTSTMP) {
2813 			int i;
2814 			struct sge_rxq *rxq;
2815 
2816 			ifp->if_capenable ^= IFCAP_HWRXTSTMP;
2817 			for_each_rxq(vi, i, rxq) {
2818 				if (ifp->if_capenable & IFCAP_HWRXTSTMP)
2819 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2820 				else
2821 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2822 			}
2823 		}
2824 		if (mask & IFCAP_MEXTPG)
2825 			ifp->if_capenable ^= IFCAP_MEXTPG;
2826 
2827 #ifdef KERN_TLS
2828 		if (mask & IFCAP_TXTLS) {
2829 			int enable = (ifp->if_capenable ^ mask) & IFCAP_TXTLS;
2830 
2831 			rc = ktls_capability(sc, enable);
2832 			if (rc != 0)
2833 				goto fail;
2834 
2835 			ifp->if_capenable ^= (mask & IFCAP_TXTLS);
2836 		}
2837 #endif
2838 		if (mask & IFCAP_VXLAN_HWCSUM) {
2839 			ifp->if_capenable ^= IFCAP_VXLAN_HWCSUM;
2840 			ifp->if_hwassist ^= CSUM_INNER_IP6_UDP |
2841 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
2842 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP;
2843 		}
2844 		if (mask & IFCAP_VXLAN_HWTSO) {
2845 			ifp->if_capenable ^= IFCAP_VXLAN_HWTSO;
2846 			ifp->if_hwassist ^= CSUM_INNER_IP6_TSO |
2847 			    CSUM_INNER_IP_TSO;
2848 		}
2849 
2850 #ifdef VLAN_CAPABILITIES
2851 		VLAN_CAPABILITIES(ifp);
2852 #endif
2853 fail:
2854 		end_synchronized_op(sc, 0);
2855 		break;
2856 
2857 	case SIOCSIFMEDIA:
2858 	case SIOCGIFMEDIA:
2859 	case SIOCGIFXMEDIA:
2860 		ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
2861 		break;
2862 
2863 	case SIOCGI2C: {
2864 		struct ifi2creq i2c;
2865 
2866 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
2867 		if (rc != 0)
2868 			break;
2869 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
2870 			rc = EPERM;
2871 			break;
2872 		}
2873 		if (i2c.len > sizeof(i2c.data)) {
2874 			rc = EINVAL;
2875 			break;
2876 		}
2877 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
2878 		if (rc)
2879 			return (rc);
2880 		if (hw_off_limits(sc))
2881 			rc = ENXIO;
2882 		else
2883 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
2884 			    i2c.offset, i2c.len, &i2c.data[0]);
2885 		end_synchronized_op(sc, 0);
2886 		if (rc == 0)
2887 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
2888 		break;
2889 	}
2890 
2891 	default:
2892 		rc = ether_ioctl(ifp, cmd, data);
2893 	}
2894 
2895 	return (rc);
2896 }
2897 
2898 static int
2899 cxgbe_transmit(struct ifnet *ifp, struct mbuf *m)
2900 {
2901 	struct vi_info *vi = ifp->if_softc;
2902 	struct port_info *pi = vi->pi;
2903 	struct adapter *sc;
2904 	struct sge_txq *txq;
2905 	void *items[1];
2906 	int rc;
2907 
2908 	M_ASSERTPKTHDR(m);
2909 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
2910 #if defined(KERN_TLS) || defined(RATELIMIT)
2911 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
2912 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
2913 #endif
2914 
2915 	if (__predict_false(pi->link_cfg.link_ok == false)) {
2916 		m_freem(m);
2917 		return (ENETDOWN);
2918 	}
2919 
2920 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
2921 	if (__predict_false(rc != 0)) {
2922 		MPASS(m == NULL);			/* was freed already */
2923 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
2924 		return (rc);
2925 	}
2926 #ifdef RATELIMIT
2927 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG) {
2928 		if (m->m_pkthdr.snd_tag->type == IF_SND_TAG_TYPE_RATE_LIMIT)
2929 			return (ethofld_transmit(ifp, m));
2930 	}
2931 #endif
2932 
2933 	/* Select a txq. */
2934 	sc = vi->adapter;
2935 	txq = &sc->sge.txq[vi->first_txq];
2936 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
2937 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
2938 		    vi->rsrv_noflowq);
2939 
2940 	items[0] = m;
2941 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
2942 	if (__predict_false(rc != 0))
2943 		m_freem(m);
2944 
2945 	return (rc);
2946 }
2947 
2948 static void
2949 cxgbe_qflush(struct ifnet *ifp)
2950 {
2951 	struct vi_info *vi = ifp->if_softc;
2952 	struct sge_txq *txq;
2953 	int i;
2954 
2955 	/* queues do not exist if !VI_INIT_DONE. */
2956 	if (vi->flags & VI_INIT_DONE) {
2957 		for_each_txq(vi, i, txq) {
2958 			TXQ_LOCK(txq);
2959 			txq->eq.flags |= EQ_QFLUSH;
2960 			TXQ_UNLOCK(txq);
2961 			while (!mp_ring_is_idle(txq->r)) {
2962 				mp_ring_check_drainage(txq->r, 4096);
2963 				pause("qflush", 1);
2964 			}
2965 			TXQ_LOCK(txq);
2966 			txq->eq.flags &= ~EQ_QFLUSH;
2967 			TXQ_UNLOCK(txq);
2968 		}
2969 	}
2970 	if_qflush(ifp);
2971 }
2972 
2973 static uint64_t
2974 vi_get_counter(struct ifnet *ifp, ift_counter c)
2975 {
2976 	struct vi_info *vi = ifp->if_softc;
2977 	struct fw_vi_stats_vf *s = &vi->stats;
2978 
2979 	mtx_lock(&vi->tick_mtx);
2980 	vi_refresh_stats(vi);
2981 	mtx_unlock(&vi->tick_mtx);
2982 
2983 	switch (c) {
2984 	case IFCOUNTER_IPACKETS:
2985 		return (s->rx_bcast_frames + s->rx_mcast_frames +
2986 		    s->rx_ucast_frames);
2987 	case IFCOUNTER_IERRORS:
2988 		return (s->rx_err_frames);
2989 	case IFCOUNTER_OPACKETS:
2990 		return (s->tx_bcast_frames + s->tx_mcast_frames +
2991 		    s->tx_ucast_frames + s->tx_offload_frames);
2992 	case IFCOUNTER_OERRORS:
2993 		return (s->tx_drop_frames);
2994 	case IFCOUNTER_IBYTES:
2995 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
2996 		    s->rx_ucast_bytes);
2997 	case IFCOUNTER_OBYTES:
2998 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
2999 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3000 	case IFCOUNTER_IMCASTS:
3001 		return (s->rx_mcast_frames);
3002 	case IFCOUNTER_OMCASTS:
3003 		return (s->tx_mcast_frames);
3004 	case IFCOUNTER_OQDROPS: {
3005 		uint64_t drops;
3006 
3007 		drops = 0;
3008 		if (vi->flags & VI_INIT_DONE) {
3009 			int i;
3010 			struct sge_txq *txq;
3011 
3012 			for_each_txq(vi, i, txq)
3013 				drops += counter_u64_fetch(txq->r->dropped);
3014 		}
3015 
3016 		return (drops);
3017 
3018 	}
3019 
3020 	default:
3021 		return (if_get_counter_default(ifp, c));
3022 	}
3023 }
3024 
3025 static uint64_t
3026 cxgbe_get_counter(struct ifnet *ifp, ift_counter c)
3027 {
3028 	struct vi_info *vi = ifp->if_softc;
3029 	struct port_info *pi = vi->pi;
3030 	struct port_stats *s = &pi->stats;
3031 
3032 	mtx_lock(&vi->tick_mtx);
3033 	cxgbe_refresh_stats(vi);
3034 	mtx_unlock(&vi->tick_mtx);
3035 
3036 	switch (c) {
3037 	case IFCOUNTER_IPACKETS:
3038 		return (s->rx_frames);
3039 
3040 	case IFCOUNTER_IERRORS:
3041 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3042 		    s->rx_fcs_err + s->rx_len_err);
3043 
3044 	case IFCOUNTER_OPACKETS:
3045 		return (s->tx_frames);
3046 
3047 	case IFCOUNTER_OERRORS:
3048 		return (s->tx_error_frames);
3049 
3050 	case IFCOUNTER_IBYTES:
3051 		return (s->rx_octets);
3052 
3053 	case IFCOUNTER_OBYTES:
3054 		return (s->tx_octets);
3055 
3056 	case IFCOUNTER_IMCASTS:
3057 		return (s->rx_mcast_frames);
3058 
3059 	case IFCOUNTER_OMCASTS:
3060 		return (s->tx_mcast_frames);
3061 
3062 	case IFCOUNTER_IQDROPS:
3063 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3064 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3065 		    s->rx_trunc3 + pi->tnl_cong_drops);
3066 
3067 	case IFCOUNTER_OQDROPS: {
3068 		uint64_t drops;
3069 
3070 		drops = s->tx_drop;
3071 		if (vi->flags & VI_INIT_DONE) {
3072 			int i;
3073 			struct sge_txq *txq;
3074 
3075 			for_each_txq(vi, i, txq)
3076 				drops += counter_u64_fetch(txq->r->dropped);
3077 		}
3078 
3079 		return (drops);
3080 
3081 	}
3082 
3083 	default:
3084 		return (if_get_counter_default(ifp, c));
3085 	}
3086 }
3087 
3088 #if defined(KERN_TLS) || defined(RATELIMIT)
3089 static int
3090 cxgbe_snd_tag_alloc(struct ifnet *ifp, union if_snd_tag_alloc_params *params,
3091     struct m_snd_tag **pt)
3092 {
3093 	int error;
3094 
3095 	switch (params->hdr.type) {
3096 #ifdef RATELIMIT
3097 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3098 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3099 		break;
3100 #endif
3101 #ifdef KERN_TLS
3102 	case IF_SND_TAG_TYPE_TLS:
3103 		error = cxgbe_tls_tag_alloc(ifp, params, pt);
3104 		break;
3105 #endif
3106 	default:
3107 		error = EOPNOTSUPP;
3108 	}
3109 	return (error);
3110 }
3111 
3112 static int
3113 cxgbe_snd_tag_modify(struct m_snd_tag *mst,
3114     union if_snd_tag_modify_params *params)
3115 {
3116 
3117 	switch (mst->type) {
3118 #ifdef RATELIMIT
3119 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3120 		return (cxgbe_rate_tag_modify(mst, params));
3121 #endif
3122 	default:
3123 		return (EOPNOTSUPP);
3124 	}
3125 }
3126 
3127 static int
3128 cxgbe_snd_tag_query(struct m_snd_tag *mst,
3129     union if_snd_tag_query_params *params)
3130 {
3131 
3132 	switch (mst->type) {
3133 #ifdef RATELIMIT
3134 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3135 		return (cxgbe_rate_tag_query(mst, params));
3136 #endif
3137 	default:
3138 		return (EOPNOTSUPP);
3139 	}
3140 }
3141 
3142 static void
3143 cxgbe_snd_tag_free(struct m_snd_tag *mst)
3144 {
3145 
3146 	switch (mst->type) {
3147 #ifdef RATELIMIT
3148 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3149 		cxgbe_rate_tag_free(mst);
3150 		return;
3151 #endif
3152 #ifdef KERN_TLS
3153 	case IF_SND_TAG_TYPE_TLS:
3154 		cxgbe_tls_tag_free(mst);
3155 		return;
3156 #endif
3157 	default:
3158 		panic("shouldn't get here");
3159 	}
3160 }
3161 #endif
3162 
3163 /*
3164  * The kernel picks a media from the list we had provided but we still validate
3165  * the requeste.
3166  */
3167 int
3168 cxgbe_media_change(struct ifnet *ifp)
3169 {
3170 	struct vi_info *vi = ifp->if_softc;
3171 	struct port_info *pi = vi->pi;
3172 	struct ifmedia *ifm = &pi->media;
3173 	struct link_config *lc = &pi->link_cfg;
3174 	struct adapter *sc = pi->adapter;
3175 	int rc;
3176 
3177 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3178 	if (rc != 0)
3179 		return (rc);
3180 	PORT_LOCK(pi);
3181 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3182 		/* ifconfig .. media autoselect */
3183 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3184 			rc = ENOTSUP; /* AN not supported by transceiver */
3185 			goto done;
3186 		}
3187 		lc->requested_aneg = AUTONEG_ENABLE;
3188 		lc->requested_speed = 0;
3189 		lc->requested_fc |= PAUSE_AUTONEG;
3190 	} else {
3191 		lc->requested_aneg = AUTONEG_DISABLE;
3192 		lc->requested_speed =
3193 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3194 		lc->requested_fc = 0;
3195 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3196 			lc->requested_fc |= PAUSE_RX;
3197 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3198 			lc->requested_fc |= PAUSE_TX;
3199 	}
3200 	if (pi->up_vis > 0) {
3201 		fixup_link_config(pi);
3202 		rc = apply_link_config(pi);
3203 	}
3204 done:
3205 	PORT_UNLOCK(pi);
3206 	end_synchronized_op(sc, 0);
3207 	return (rc);
3208 }
3209 
3210 /*
3211  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3212  * given speed.
3213  */
3214 static int
3215 port_mword(struct port_info *pi, uint32_t speed)
3216 {
3217 
3218 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3219 	MPASS(powerof2(speed));
3220 
3221 	switch(pi->port_type) {
3222 	case FW_PORT_TYPE_BT_SGMII:
3223 	case FW_PORT_TYPE_BT_XFI:
3224 	case FW_PORT_TYPE_BT_XAUI:
3225 		/* BaseT */
3226 		switch (speed) {
3227 		case FW_PORT_CAP32_SPEED_100M:
3228 			return (IFM_100_T);
3229 		case FW_PORT_CAP32_SPEED_1G:
3230 			return (IFM_1000_T);
3231 		case FW_PORT_CAP32_SPEED_10G:
3232 			return (IFM_10G_T);
3233 		}
3234 		break;
3235 	case FW_PORT_TYPE_KX4:
3236 		if (speed == FW_PORT_CAP32_SPEED_10G)
3237 			return (IFM_10G_KX4);
3238 		break;
3239 	case FW_PORT_TYPE_CX4:
3240 		if (speed == FW_PORT_CAP32_SPEED_10G)
3241 			return (IFM_10G_CX4);
3242 		break;
3243 	case FW_PORT_TYPE_KX:
3244 		if (speed == FW_PORT_CAP32_SPEED_1G)
3245 			return (IFM_1000_KX);
3246 		break;
3247 	case FW_PORT_TYPE_KR:
3248 	case FW_PORT_TYPE_BP_AP:
3249 	case FW_PORT_TYPE_BP4_AP:
3250 	case FW_PORT_TYPE_BP40_BA:
3251 	case FW_PORT_TYPE_KR4_100G:
3252 	case FW_PORT_TYPE_KR_SFP28:
3253 	case FW_PORT_TYPE_KR_XLAUI:
3254 		switch (speed) {
3255 		case FW_PORT_CAP32_SPEED_1G:
3256 			return (IFM_1000_KX);
3257 		case FW_PORT_CAP32_SPEED_10G:
3258 			return (IFM_10G_KR);
3259 		case FW_PORT_CAP32_SPEED_25G:
3260 			return (IFM_25G_KR);
3261 		case FW_PORT_CAP32_SPEED_40G:
3262 			return (IFM_40G_KR4);
3263 		case FW_PORT_CAP32_SPEED_50G:
3264 			return (IFM_50G_KR2);
3265 		case FW_PORT_CAP32_SPEED_100G:
3266 			return (IFM_100G_KR4);
3267 		}
3268 		break;
3269 	case FW_PORT_TYPE_FIBER_XFI:
3270 	case FW_PORT_TYPE_FIBER_XAUI:
3271 	case FW_PORT_TYPE_SFP:
3272 	case FW_PORT_TYPE_QSFP_10G:
3273 	case FW_PORT_TYPE_QSA:
3274 	case FW_PORT_TYPE_QSFP:
3275 	case FW_PORT_TYPE_CR4_QSFP:
3276 	case FW_PORT_TYPE_CR_QSFP:
3277 	case FW_PORT_TYPE_CR2_QSFP:
3278 	case FW_PORT_TYPE_SFP28:
3279 		/* Pluggable transceiver */
3280 		switch (pi->mod_type) {
3281 		case FW_PORT_MOD_TYPE_LR:
3282 			switch (speed) {
3283 			case FW_PORT_CAP32_SPEED_1G:
3284 				return (IFM_1000_LX);
3285 			case FW_PORT_CAP32_SPEED_10G:
3286 				return (IFM_10G_LR);
3287 			case FW_PORT_CAP32_SPEED_25G:
3288 				return (IFM_25G_LR);
3289 			case FW_PORT_CAP32_SPEED_40G:
3290 				return (IFM_40G_LR4);
3291 			case FW_PORT_CAP32_SPEED_50G:
3292 				return (IFM_50G_LR2);
3293 			case FW_PORT_CAP32_SPEED_100G:
3294 				return (IFM_100G_LR4);
3295 			}
3296 			break;
3297 		case FW_PORT_MOD_TYPE_SR:
3298 			switch (speed) {
3299 			case FW_PORT_CAP32_SPEED_1G:
3300 				return (IFM_1000_SX);
3301 			case FW_PORT_CAP32_SPEED_10G:
3302 				return (IFM_10G_SR);
3303 			case FW_PORT_CAP32_SPEED_25G:
3304 				return (IFM_25G_SR);
3305 			case FW_PORT_CAP32_SPEED_40G:
3306 				return (IFM_40G_SR4);
3307 			case FW_PORT_CAP32_SPEED_50G:
3308 				return (IFM_50G_SR2);
3309 			case FW_PORT_CAP32_SPEED_100G:
3310 				return (IFM_100G_SR4);
3311 			}
3312 			break;
3313 		case FW_PORT_MOD_TYPE_ER:
3314 			if (speed == FW_PORT_CAP32_SPEED_10G)
3315 				return (IFM_10G_ER);
3316 			break;
3317 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3318 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3319 			switch (speed) {
3320 			case FW_PORT_CAP32_SPEED_1G:
3321 				return (IFM_1000_CX);
3322 			case FW_PORT_CAP32_SPEED_10G:
3323 				return (IFM_10G_TWINAX);
3324 			case FW_PORT_CAP32_SPEED_25G:
3325 				return (IFM_25G_CR);
3326 			case FW_PORT_CAP32_SPEED_40G:
3327 				return (IFM_40G_CR4);
3328 			case FW_PORT_CAP32_SPEED_50G:
3329 				return (IFM_50G_CR2);
3330 			case FW_PORT_CAP32_SPEED_100G:
3331 				return (IFM_100G_CR4);
3332 			}
3333 			break;
3334 		case FW_PORT_MOD_TYPE_LRM:
3335 			if (speed == FW_PORT_CAP32_SPEED_10G)
3336 				return (IFM_10G_LRM);
3337 			break;
3338 		case FW_PORT_MOD_TYPE_NA:
3339 			MPASS(0);	/* Not pluggable? */
3340 			/* fall throough */
3341 		case FW_PORT_MOD_TYPE_ERROR:
3342 		case FW_PORT_MOD_TYPE_UNKNOWN:
3343 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3344 			break;
3345 		case FW_PORT_MOD_TYPE_NONE:
3346 			return (IFM_NONE);
3347 		}
3348 		break;
3349 	case FW_PORT_TYPE_NONE:
3350 		return (IFM_NONE);
3351 	}
3352 
3353 	return (IFM_UNKNOWN);
3354 }
3355 
3356 void
3357 cxgbe_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
3358 {
3359 	struct vi_info *vi = ifp->if_softc;
3360 	struct port_info *pi = vi->pi;
3361 	struct adapter *sc = pi->adapter;
3362 	struct link_config *lc = &pi->link_cfg;
3363 
3364 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4med") != 0)
3365 		return;
3366 	PORT_LOCK(pi);
3367 
3368 	if (pi->up_vis == 0) {
3369 		/*
3370 		 * If all the interfaces are administratively down the firmware
3371 		 * does not report transceiver changes.  Refresh port info here
3372 		 * so that ifconfig displays accurate ifmedia at all times.
3373 		 * This is the only reason we have a synchronized op in this
3374 		 * function.  Just PORT_LOCK would have been enough otherwise.
3375 		 */
3376 		t4_update_port_info(pi);
3377 		build_medialist(pi);
3378 	}
3379 
3380 	/* ifm_status */
3381 	ifmr->ifm_status = IFM_AVALID;
3382 	if (lc->link_ok == false)
3383 		goto done;
3384 	ifmr->ifm_status |= IFM_ACTIVE;
3385 
3386 	/* ifm_active */
3387 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3388 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3389 	if (lc->fc & PAUSE_RX)
3390 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3391 	if (lc->fc & PAUSE_TX)
3392 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3393 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3394 done:
3395 	PORT_UNLOCK(pi);
3396 	end_synchronized_op(sc, 0);
3397 }
3398 
3399 static int
3400 vcxgbe_probe(device_t dev)
3401 {
3402 	char buf[128];
3403 	struct vi_info *vi = device_get_softc(dev);
3404 
3405 	snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
3406 	    vi - vi->pi->vi);
3407 	device_set_desc_copy(dev, buf);
3408 
3409 	return (BUS_PROBE_DEFAULT);
3410 }
3411 
3412 static int
3413 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3414 {
3415 	int func, index, rc;
3416 	uint32_t param, val;
3417 
3418 	ASSERT_SYNCHRONIZED_OP(sc);
3419 
3420 	index = vi - pi->vi;
3421 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3422 	KASSERT(index < nitems(vi_mac_funcs),
3423 	    ("%s: VI %s doesn't have a MAC func", __func__,
3424 	    device_get_nameunit(vi->dev)));
3425 	func = vi_mac_funcs[index];
3426 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3427 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3428 	if (rc < 0) {
3429 		CH_ERR(vi, "failed to allocate virtual interface %d"
3430 		    "for port %d: %d\n", index, pi->port_id, -rc);
3431 		return (-rc);
3432 	}
3433 	vi->viid = rc;
3434 
3435 	if (vi->rss_size == 1) {
3436 		/*
3437 		 * This VI didn't get a slice of the RSS table.  Reduce the
3438 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3439 		 * configuration file (nvi, rssnvi for this PF) if this is a
3440 		 * problem.
3441 		 */
3442 		device_printf(vi->dev, "RSS table not available.\n");
3443 		vi->rss_base = 0xffff;
3444 
3445 		return (0);
3446 	}
3447 
3448 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3449 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3450 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3451 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3452 	if (rc)
3453 		vi->rss_base = 0xffff;
3454 	else {
3455 		MPASS((val >> 16) == vi->rss_size);
3456 		vi->rss_base = val & 0xffff;
3457 	}
3458 
3459 	return (0);
3460 }
3461 
3462 static int
3463 vcxgbe_attach(device_t dev)
3464 {
3465 	struct vi_info *vi;
3466 	struct port_info *pi;
3467 	struct adapter *sc;
3468 	int rc;
3469 
3470 	vi = device_get_softc(dev);
3471 	pi = vi->pi;
3472 	sc = pi->adapter;
3473 
3474 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3475 	if (rc)
3476 		return (rc);
3477 	rc = alloc_extra_vi(sc, pi, vi);
3478 	end_synchronized_op(sc, 0);
3479 	if (rc)
3480 		return (rc);
3481 
3482 	rc = cxgbe_vi_attach(dev, vi);
3483 	if (rc) {
3484 		t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3485 		return (rc);
3486 	}
3487 	return (0);
3488 }
3489 
3490 static int
3491 vcxgbe_detach(device_t dev)
3492 {
3493 	struct vi_info *vi;
3494 	struct adapter *sc;
3495 
3496 	vi = device_get_softc(dev);
3497 	sc = vi->adapter;
3498 
3499 	doom_vi(sc, vi);
3500 
3501 	cxgbe_vi_detach(vi);
3502 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3503 
3504 	end_synchronized_op(sc, 0);
3505 
3506 	return (0);
3507 }
3508 
3509 static struct callout fatal_callout;
3510 static struct taskqueue *reset_tq;
3511 
3512 static void
3513 delayed_panic(void *arg)
3514 {
3515 	struct adapter *sc = arg;
3516 
3517 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3518 }
3519 
3520 void
3521 t4_fatal_err(struct adapter *sc, bool fw_error)
3522 {
3523 
3524 	t4_shutdown_adapter(sc);
3525 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped.\n",
3526 	    device_get_nameunit(sc->dev));
3527 	if (fw_error) {
3528 		if (sc->flags & CHK_MBOX_ACCESS)
3529 			ASSERT_SYNCHRONIZED_OP(sc);
3530 		sc->flags |= ADAP_ERR;
3531 	} else {
3532 		ADAPTER_LOCK(sc);
3533 		sc->flags |= ADAP_ERR;
3534 		ADAPTER_UNLOCK(sc);
3535 	}
3536 #ifdef TCP_OFFLOAD
3537 	taskqueue_enqueue(taskqueue_thread, &sc->async_event_task);
3538 #endif
3539 
3540 	if (t4_panic_on_fatal_err) {
3541 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3542 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3543 	} else if (t4_reset_on_fatal_err) {
3544 		CH_ALERT(sc, "resetting on fatal error.\n");
3545 		taskqueue_enqueue(reset_tq, &sc->reset_task);
3546 	}
3547 }
3548 
3549 void
3550 t4_add_adapter(struct adapter *sc)
3551 {
3552 	sx_xlock(&t4_list_lock);
3553 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3554 	sx_xunlock(&t4_list_lock);
3555 }
3556 
3557 int
3558 t4_map_bars_0_and_4(struct adapter *sc)
3559 {
3560 	sc->regs_rid = PCIR_BAR(0);
3561 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3562 	    &sc->regs_rid, RF_ACTIVE);
3563 	if (sc->regs_res == NULL) {
3564 		device_printf(sc->dev, "cannot map registers.\n");
3565 		return (ENXIO);
3566 	}
3567 	sc->bt = rman_get_bustag(sc->regs_res);
3568 	sc->bh = rman_get_bushandle(sc->regs_res);
3569 	sc->mmio_len = rman_get_size(sc->regs_res);
3570 	setbit(&sc->doorbells, DOORBELL_KDB);
3571 
3572 	sc->msix_rid = PCIR_BAR(4);
3573 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3574 	    &sc->msix_rid, RF_ACTIVE);
3575 	if (sc->msix_res == NULL) {
3576 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3577 		return (ENXIO);
3578 	}
3579 
3580 	return (0);
3581 }
3582 
3583 int
3584 t4_map_bar_2(struct adapter *sc)
3585 {
3586 
3587 	/*
3588 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3589 	 * to map it if RDMA is disabled.
3590 	 */
3591 	if (is_t4(sc) && sc->rdmacaps == 0)
3592 		return (0);
3593 
3594 	sc->udbs_rid = PCIR_BAR(2);
3595 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3596 	    &sc->udbs_rid, RF_ACTIVE);
3597 	if (sc->udbs_res == NULL) {
3598 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3599 		return (ENXIO);
3600 	}
3601 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3602 
3603 	if (chip_id(sc) >= CHELSIO_T5) {
3604 		setbit(&sc->doorbells, DOORBELL_UDB);
3605 #if defined(__i386__) || defined(__amd64__)
3606 		if (t5_write_combine) {
3607 			int rc, mode;
3608 
3609 			/*
3610 			 * Enable write combining on BAR2.  This is the
3611 			 * userspace doorbell BAR and is split into 128B
3612 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3613 			 * with an egress queue.  The first 64B has the doorbell
3614 			 * and the second 64B can be used to submit a tx work
3615 			 * request with an implicit doorbell.
3616 			 */
3617 
3618 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3619 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3620 			if (rc == 0) {
3621 				clrbit(&sc->doorbells, DOORBELL_UDB);
3622 				setbit(&sc->doorbells, DOORBELL_WCWR);
3623 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3624 			} else {
3625 				device_printf(sc->dev,
3626 				    "couldn't enable write combining: %d\n",
3627 				    rc);
3628 			}
3629 
3630 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3631 			t4_write_reg(sc, A_SGE_STAT_CFG,
3632 			    V_STATSOURCE_T5(7) | mode);
3633 		}
3634 #endif
3635 	}
3636 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3637 
3638 	return (0);
3639 }
3640 
3641 struct memwin_init {
3642 	uint32_t base;
3643 	uint32_t aperture;
3644 };
3645 
3646 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3647 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3648 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3649 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3650 };
3651 
3652 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3653 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3654 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3655 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3656 };
3657 
3658 static void
3659 setup_memwin(struct adapter *sc)
3660 {
3661 	const struct memwin_init *mw_init;
3662 	struct memwin *mw;
3663 	int i;
3664 	uint32_t bar0;
3665 
3666 	if (is_t4(sc)) {
3667 		/*
3668 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3669 		 * mechanism.  Works from within PCI passthrough environments
3670 		 * too, where rman_get_start() can return a different value.  We
3671 		 * need to program the T4 memory window decoders with the actual
3672 		 * addresses that will be coming across the PCIe link.
3673 		 */
3674 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3675 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3676 
3677 		mw_init = &t4_memwin[0];
3678 	} else {
3679 		/* T5+ use the relative offset inside the PCIe BAR */
3680 		bar0 = 0;
3681 
3682 		mw_init = &t5_memwin[0];
3683 	}
3684 
3685 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3686 		if (!rw_initialized(&mw->mw_lock)) {
3687 			rw_init(&mw->mw_lock, "memory window access");
3688 			mw->mw_base = mw_init->base;
3689 			mw->mw_aperture = mw_init->aperture;
3690 			mw->mw_curpos = 0;
3691 		}
3692 		t4_write_reg(sc,
3693 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3694 		    (mw->mw_base + bar0) | V_BIR(0) |
3695 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3696 		rw_wlock(&mw->mw_lock);
3697 		position_memwin(sc, i, mw->mw_curpos);
3698 		rw_wunlock(&mw->mw_lock);
3699 	}
3700 
3701 	/* flush */
3702 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3703 }
3704 
3705 /*
3706  * Positions the memory window at the given address in the card's address space.
3707  * There are some alignment requirements and the actual position may be at an
3708  * address prior to the requested address.  mw->mw_curpos always has the actual
3709  * position of the window.
3710  */
3711 static void
3712 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3713 {
3714 	struct memwin *mw;
3715 	uint32_t pf;
3716 	uint32_t reg;
3717 
3718 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3719 	mw = &sc->memwin[idx];
3720 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3721 
3722 	if (is_t4(sc)) {
3723 		pf = 0;
3724 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3725 	} else {
3726 		pf = V_PFNUM(sc->pf);
3727 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3728 	}
3729 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3730 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3731 	t4_read_reg(sc, reg);	/* flush */
3732 }
3733 
3734 int
3735 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3736     int len, int rw)
3737 {
3738 	struct memwin *mw;
3739 	uint32_t mw_end, v;
3740 
3741 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3742 
3743 	/* Memory can only be accessed in naturally aligned 4 byte units */
3744 	if (addr & 3 || len & 3 || len <= 0)
3745 		return (EINVAL);
3746 
3747 	mw = &sc->memwin[idx];
3748 	while (len > 0) {
3749 		rw_rlock(&mw->mw_lock);
3750 		mw_end = mw->mw_curpos + mw->mw_aperture;
3751 		if (addr >= mw_end || addr < mw->mw_curpos) {
3752 			/* Will need to reposition the window */
3753 			if (!rw_try_upgrade(&mw->mw_lock)) {
3754 				rw_runlock(&mw->mw_lock);
3755 				rw_wlock(&mw->mw_lock);
3756 			}
3757 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3758 			position_memwin(sc, idx, addr);
3759 			rw_downgrade(&mw->mw_lock);
3760 			mw_end = mw->mw_curpos + mw->mw_aperture;
3761 		}
3762 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3763 		while (addr < mw_end && len > 0) {
3764 			if (rw == 0) {
3765 				v = t4_read_reg(sc, mw->mw_base + addr -
3766 				    mw->mw_curpos);
3767 				*val++ = le32toh(v);
3768 			} else {
3769 				v = *val++;
3770 				t4_write_reg(sc, mw->mw_base + addr -
3771 				    mw->mw_curpos, htole32(v));
3772 			}
3773 			addr += 4;
3774 			len -= 4;
3775 		}
3776 		rw_runlock(&mw->mw_lock);
3777 	}
3778 
3779 	return (0);
3780 }
3781 
3782 static void
3783 t4_init_atid_table(struct adapter *sc)
3784 {
3785 	struct tid_info *t;
3786 	int i;
3787 
3788 	t = &sc->tids;
3789 	if (t->natids == 0)
3790 		return;
3791 
3792 	MPASS(t->atid_tab == NULL);
3793 
3794 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3795 	    M_ZERO | M_WAITOK);
3796 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3797 	t->afree = t->atid_tab;
3798 	t->atids_in_use = 0;
3799 	for (i = 1; i < t->natids; i++)
3800 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3801 	t->atid_tab[t->natids - 1].next = NULL;
3802 }
3803 
3804 static void
3805 t4_free_atid_table(struct adapter *sc)
3806 {
3807 	struct tid_info *t;
3808 
3809 	t = &sc->tids;
3810 
3811 	KASSERT(t->atids_in_use == 0,
3812 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3813 
3814 	if (mtx_initialized(&t->atid_lock))
3815 		mtx_destroy(&t->atid_lock);
3816 	free(t->atid_tab, M_CXGBE);
3817 	t->atid_tab = NULL;
3818 }
3819 
3820 int
3821 alloc_atid(struct adapter *sc, void *ctx)
3822 {
3823 	struct tid_info *t = &sc->tids;
3824 	int atid = -1;
3825 
3826 	mtx_lock(&t->atid_lock);
3827 	if (t->afree) {
3828 		union aopen_entry *p = t->afree;
3829 
3830 		atid = p - t->atid_tab;
3831 		MPASS(atid <= M_TID_TID);
3832 		t->afree = p->next;
3833 		p->data = ctx;
3834 		t->atids_in_use++;
3835 	}
3836 	mtx_unlock(&t->atid_lock);
3837 	return (atid);
3838 }
3839 
3840 void *
3841 lookup_atid(struct adapter *sc, int atid)
3842 {
3843 	struct tid_info *t = &sc->tids;
3844 
3845 	return (t->atid_tab[atid].data);
3846 }
3847 
3848 void
3849 free_atid(struct adapter *sc, int atid)
3850 {
3851 	struct tid_info *t = &sc->tids;
3852 	union aopen_entry *p = &t->atid_tab[atid];
3853 
3854 	mtx_lock(&t->atid_lock);
3855 	p->next = t->afree;
3856 	t->afree = p;
3857 	t->atids_in_use--;
3858 	mtx_unlock(&t->atid_lock);
3859 }
3860 
3861 static void
3862 queue_tid_release(struct adapter *sc, int tid)
3863 {
3864 
3865 	CXGBE_UNIMPLEMENTED("deferred tid release");
3866 }
3867 
3868 void
3869 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
3870 {
3871 	struct wrqe *wr;
3872 	struct cpl_tid_release *req;
3873 
3874 	wr = alloc_wrqe(sizeof(*req), ctrlq);
3875 	if (wr == NULL) {
3876 		queue_tid_release(sc, tid);	/* defer */
3877 		return;
3878 	}
3879 	req = wrtod(wr);
3880 
3881 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
3882 
3883 	t4_wrq_tx(sc, wr);
3884 }
3885 
3886 static int
3887 t4_range_cmp(const void *a, const void *b)
3888 {
3889 	return ((const struct t4_range *)a)->start -
3890 	       ((const struct t4_range *)b)->start;
3891 }
3892 
3893 /*
3894  * Verify that the memory range specified by the addr/len pair is valid within
3895  * the card's address space.
3896  */
3897 static int
3898 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
3899 {
3900 	struct t4_range mem_ranges[4], *r, *next;
3901 	uint32_t em, addr_len;
3902 	int i, n, remaining;
3903 
3904 	/* Memory can only be accessed in naturally aligned 4 byte units */
3905 	if (addr & 3 || len & 3 || len == 0)
3906 		return (EINVAL);
3907 
3908 	/* Enabled memories */
3909 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
3910 
3911 	r = &mem_ranges[0];
3912 	n = 0;
3913 	bzero(r, sizeof(mem_ranges));
3914 	if (em & F_EDRAM0_ENABLE) {
3915 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
3916 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
3917 		if (r->size > 0) {
3918 			r->start = G_EDRAM0_BASE(addr_len) << 20;
3919 			if (addr >= r->start &&
3920 			    addr + len <= r->start + r->size)
3921 				return (0);
3922 			r++;
3923 			n++;
3924 		}
3925 	}
3926 	if (em & F_EDRAM1_ENABLE) {
3927 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
3928 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
3929 		if (r->size > 0) {
3930 			r->start = G_EDRAM1_BASE(addr_len) << 20;
3931 			if (addr >= r->start &&
3932 			    addr + len <= r->start + r->size)
3933 				return (0);
3934 			r++;
3935 			n++;
3936 		}
3937 	}
3938 	if (em & F_EXT_MEM_ENABLE) {
3939 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
3940 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
3941 		if (r->size > 0) {
3942 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
3943 			if (addr >= r->start &&
3944 			    addr + len <= r->start + r->size)
3945 				return (0);
3946 			r++;
3947 			n++;
3948 		}
3949 	}
3950 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
3951 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
3952 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
3953 		if (r->size > 0) {
3954 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
3955 			if (addr >= r->start &&
3956 			    addr + len <= r->start + r->size)
3957 				return (0);
3958 			r++;
3959 			n++;
3960 		}
3961 	}
3962 	MPASS(n <= nitems(mem_ranges));
3963 
3964 	if (n > 1) {
3965 		/* Sort and merge the ranges. */
3966 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
3967 
3968 		/* Start from index 0 and examine the next n - 1 entries. */
3969 		r = &mem_ranges[0];
3970 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
3971 
3972 			MPASS(r->size > 0);	/* r is a valid entry. */
3973 			next = r + 1;
3974 			MPASS(next->size > 0);	/* and so is the next one. */
3975 
3976 			while (r->start + r->size >= next->start) {
3977 				/* Merge the next one into the current entry. */
3978 				r->size = max(r->start + r->size,
3979 				    next->start + next->size) - r->start;
3980 				n--;	/* One fewer entry in total. */
3981 				if (--remaining == 0)
3982 					goto done;	/* short circuit */
3983 				next++;
3984 			}
3985 			if (next != r + 1) {
3986 				/*
3987 				 * Some entries were merged into r and next
3988 				 * points to the first valid entry that couldn't
3989 				 * be merged.
3990 				 */
3991 				MPASS(next->size > 0);	/* must be valid */
3992 				memcpy(r + 1, next, remaining * sizeof(*r));
3993 #ifdef INVARIANTS
3994 				/*
3995 				 * This so that the foo->size assertion in the
3996 				 * next iteration of the loop do the right
3997 				 * thing for entries that were pulled up and are
3998 				 * no longer valid.
3999 				 */
4000 				MPASS(n < nitems(mem_ranges));
4001 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4002 				    sizeof(struct t4_range));
4003 #endif
4004 			}
4005 		}
4006 done:
4007 		/* Done merging the ranges. */
4008 		MPASS(n > 0);
4009 		r = &mem_ranges[0];
4010 		for (i = 0; i < n; i++, r++) {
4011 			if (addr >= r->start &&
4012 			    addr + len <= r->start + r->size)
4013 				return (0);
4014 		}
4015 	}
4016 
4017 	return (EFAULT);
4018 }
4019 
4020 static int
4021 fwmtype_to_hwmtype(int mtype)
4022 {
4023 
4024 	switch (mtype) {
4025 	case FW_MEMTYPE_EDC0:
4026 		return (MEM_EDC0);
4027 	case FW_MEMTYPE_EDC1:
4028 		return (MEM_EDC1);
4029 	case FW_MEMTYPE_EXTMEM:
4030 		return (MEM_MC0);
4031 	case FW_MEMTYPE_EXTMEM1:
4032 		return (MEM_MC1);
4033 	default:
4034 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4035 	}
4036 }
4037 
4038 /*
4039  * Verify that the memory range specified by the memtype/offset/len pair is
4040  * valid and lies entirely within the memtype specified.  The global address of
4041  * the start of the range is returned in addr.
4042  */
4043 static int
4044 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4045     uint32_t *addr)
4046 {
4047 	uint32_t em, addr_len, maddr;
4048 
4049 	/* Memory can only be accessed in naturally aligned 4 byte units */
4050 	if (off & 3 || len & 3 || len == 0)
4051 		return (EINVAL);
4052 
4053 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4054 	switch (fwmtype_to_hwmtype(mtype)) {
4055 	case MEM_EDC0:
4056 		if (!(em & F_EDRAM0_ENABLE))
4057 			return (EINVAL);
4058 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4059 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4060 		break;
4061 	case MEM_EDC1:
4062 		if (!(em & F_EDRAM1_ENABLE))
4063 			return (EINVAL);
4064 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4065 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4066 		break;
4067 	case MEM_MC:
4068 		if (!(em & F_EXT_MEM_ENABLE))
4069 			return (EINVAL);
4070 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4071 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4072 		break;
4073 	case MEM_MC1:
4074 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4075 			return (EINVAL);
4076 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4077 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4078 		break;
4079 	default:
4080 		return (EINVAL);
4081 	}
4082 
4083 	*addr = maddr + off;	/* global address */
4084 	return (validate_mem_range(sc, *addr, len));
4085 }
4086 
4087 static int
4088 fixup_devlog_params(struct adapter *sc)
4089 {
4090 	struct devlog_params *dparams = &sc->params.devlog;
4091 	int rc;
4092 
4093 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4094 	    dparams->size, &dparams->addr);
4095 
4096 	return (rc);
4097 }
4098 
4099 static void
4100 update_nirq(struct intrs_and_queues *iaq, int nports)
4101 {
4102 
4103 	iaq->nirq = T4_EXTRA_INTR;
4104 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4105 	iaq->nirq += nports * iaq->nofldrxq;
4106 	iaq->nirq += nports * (iaq->num_vis - 1) *
4107 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4108 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4109 }
4110 
4111 /*
4112  * Adjust requirements to fit the number of interrupts available.
4113  */
4114 static void
4115 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4116     int navail)
4117 {
4118 	int old_nirq;
4119 	const int nports = sc->params.nports;
4120 
4121 	MPASS(nports > 0);
4122 	MPASS(navail > 0);
4123 
4124 	bzero(iaq, sizeof(*iaq));
4125 	iaq->intr_type = itype;
4126 	iaq->num_vis = t4_num_vis;
4127 	iaq->ntxq = t4_ntxq;
4128 	iaq->ntxq_vi = t4_ntxq_vi;
4129 	iaq->nrxq = t4_nrxq;
4130 	iaq->nrxq_vi = t4_nrxq_vi;
4131 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4132 	if (is_offload(sc) || is_ethoffload(sc)) {
4133 		iaq->nofldtxq = t4_nofldtxq;
4134 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4135 	}
4136 #endif
4137 #ifdef TCP_OFFLOAD
4138 	if (is_offload(sc)) {
4139 		iaq->nofldrxq = t4_nofldrxq;
4140 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4141 	}
4142 #endif
4143 #ifdef DEV_NETMAP
4144 	if (t4_native_netmap & NN_MAIN_VI) {
4145 		iaq->nnmtxq = t4_nnmtxq;
4146 		iaq->nnmrxq = t4_nnmrxq;
4147 	}
4148 	if (t4_native_netmap & NN_EXTRA_VI) {
4149 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4150 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4151 	}
4152 #endif
4153 
4154 	update_nirq(iaq, nports);
4155 	if (iaq->nirq <= navail &&
4156 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4157 		/*
4158 		 * This is the normal case -- there are enough interrupts for
4159 		 * everything.
4160 		 */
4161 		goto done;
4162 	}
4163 
4164 	/*
4165 	 * If extra VIs have been configured try reducing their count and see if
4166 	 * that works.
4167 	 */
4168 	while (iaq->num_vis > 1) {
4169 		iaq->num_vis--;
4170 		update_nirq(iaq, nports);
4171 		if (iaq->nirq <= navail &&
4172 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4173 			device_printf(sc->dev, "virtual interfaces per port "
4174 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4175 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4176 			    "itype %d, navail %u, nirq %d.\n",
4177 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4178 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4179 			    itype, navail, iaq->nirq);
4180 			goto done;
4181 		}
4182 	}
4183 
4184 	/*
4185 	 * Extra VIs will not be created.  Log a message if they were requested.
4186 	 */
4187 	MPASS(iaq->num_vis == 1);
4188 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4189 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4190 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4191 	if (iaq->num_vis != t4_num_vis) {
4192 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4193 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4194 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4195 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4196 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4197 	}
4198 
4199 	/*
4200 	 * Keep reducing the number of NIC rx queues to the next lower power of
4201 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4202 	 * if that works.
4203 	 */
4204 	do {
4205 		if (iaq->nrxq > 1) {
4206 			do {
4207 				iaq->nrxq--;
4208 			} while (!powerof2(iaq->nrxq));
4209 			if (iaq->nnmrxq > iaq->nrxq)
4210 				iaq->nnmrxq = iaq->nrxq;
4211 		}
4212 		if (iaq->nofldrxq > 1)
4213 			iaq->nofldrxq >>= 1;
4214 
4215 		old_nirq = iaq->nirq;
4216 		update_nirq(iaq, nports);
4217 		if (iaq->nirq <= navail &&
4218 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4219 			device_printf(sc->dev, "running with reduced number of "
4220 			    "rx queues because of shortage of interrupts.  "
4221 			    "nrxq=%u, nofldrxq=%u.  "
4222 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4223 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4224 			goto done;
4225 		}
4226 	} while (old_nirq != iaq->nirq);
4227 
4228 	/* One interrupt for everything.  Ugh. */
4229 	device_printf(sc->dev, "running with minimal number of queues.  "
4230 	    "itype %d, navail %u.\n", itype, navail);
4231 	iaq->nirq = 1;
4232 	iaq->nrxq = 1;
4233 	iaq->ntxq = 1;
4234 	if (iaq->nofldrxq > 0) {
4235 		iaq->nofldrxq = 1;
4236 		iaq->nofldtxq = 1;
4237 	}
4238 	iaq->nnmtxq = 0;
4239 	iaq->nnmrxq = 0;
4240 done:
4241 	MPASS(iaq->num_vis > 0);
4242 	if (iaq->num_vis > 1) {
4243 		MPASS(iaq->nrxq_vi > 0);
4244 		MPASS(iaq->ntxq_vi > 0);
4245 	}
4246 	MPASS(iaq->nirq > 0);
4247 	MPASS(iaq->nrxq > 0);
4248 	MPASS(iaq->ntxq > 0);
4249 	if (itype == INTR_MSI) {
4250 		MPASS(powerof2(iaq->nirq));
4251 	}
4252 }
4253 
4254 static int
4255 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4256 {
4257 	int rc, itype, navail, nalloc;
4258 
4259 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4260 
4261 		if ((itype & t4_intr_types) == 0)
4262 			continue;	/* not allowed */
4263 
4264 		if (itype == INTR_MSIX)
4265 			navail = pci_msix_count(sc->dev);
4266 		else if (itype == INTR_MSI)
4267 			navail = pci_msi_count(sc->dev);
4268 		else
4269 			navail = 1;
4270 restart:
4271 		if (navail == 0)
4272 			continue;
4273 
4274 		calculate_iaq(sc, iaq, itype, navail);
4275 		nalloc = iaq->nirq;
4276 		rc = 0;
4277 		if (itype == INTR_MSIX)
4278 			rc = pci_alloc_msix(sc->dev, &nalloc);
4279 		else if (itype == INTR_MSI)
4280 			rc = pci_alloc_msi(sc->dev, &nalloc);
4281 
4282 		if (rc == 0 && nalloc > 0) {
4283 			if (nalloc == iaq->nirq)
4284 				return (0);
4285 
4286 			/*
4287 			 * Didn't get the number requested.  Use whatever number
4288 			 * the kernel is willing to allocate.
4289 			 */
4290 			device_printf(sc->dev, "fewer vectors than requested, "
4291 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4292 			    itype, iaq->nirq, nalloc);
4293 			pci_release_msi(sc->dev);
4294 			navail = nalloc;
4295 			goto restart;
4296 		}
4297 
4298 		device_printf(sc->dev,
4299 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4300 		    itype, rc, iaq->nirq, nalloc);
4301 	}
4302 
4303 	device_printf(sc->dev,
4304 	    "failed to find a usable interrupt type.  "
4305 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4306 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4307 
4308 	return (ENXIO);
4309 }
4310 
4311 #define FW_VERSION(chip) ( \
4312     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4313     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4314     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4315     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4316 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4317 
4318 /* Just enough of fw_hdr to cover all version info. */
4319 struct fw_h {
4320 	__u8	ver;
4321 	__u8	chip;
4322 	__be16	len512;
4323 	__be32	fw_ver;
4324 	__be32	tp_microcode_ver;
4325 	__u8	intfver_nic;
4326 	__u8	intfver_vnic;
4327 	__u8	intfver_ofld;
4328 	__u8	intfver_ri;
4329 	__u8	intfver_iscsipdu;
4330 	__u8	intfver_iscsi;
4331 	__u8	intfver_fcoepdu;
4332 	__u8	intfver_fcoe;
4333 };
4334 /* Spot check a couple of fields. */
4335 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4336 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4337 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4338 
4339 struct fw_info {
4340 	uint8_t chip;
4341 	char *kld_name;
4342 	char *fw_mod_name;
4343 	struct fw_h fw_h;
4344 } fw_info[] = {
4345 	{
4346 		.chip = CHELSIO_T4,
4347 		.kld_name = "t4fw_cfg",
4348 		.fw_mod_name = "t4fw",
4349 		.fw_h = {
4350 			.chip = FW_HDR_CHIP_T4,
4351 			.fw_ver = htobe32(FW_VERSION(T4)),
4352 			.intfver_nic = FW_INTFVER(T4, NIC),
4353 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4354 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4355 			.intfver_ri = FW_INTFVER(T4, RI),
4356 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4357 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4358 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4359 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4360 		},
4361 	}, {
4362 		.chip = CHELSIO_T5,
4363 		.kld_name = "t5fw_cfg",
4364 		.fw_mod_name = "t5fw",
4365 		.fw_h = {
4366 			.chip = FW_HDR_CHIP_T5,
4367 			.fw_ver = htobe32(FW_VERSION(T5)),
4368 			.intfver_nic = FW_INTFVER(T5, NIC),
4369 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4370 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4371 			.intfver_ri = FW_INTFVER(T5, RI),
4372 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4373 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4374 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4375 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4376 		},
4377 	}, {
4378 		.chip = CHELSIO_T6,
4379 		.kld_name = "t6fw_cfg",
4380 		.fw_mod_name = "t6fw",
4381 		.fw_h = {
4382 			.chip = FW_HDR_CHIP_T6,
4383 			.fw_ver = htobe32(FW_VERSION(T6)),
4384 			.intfver_nic = FW_INTFVER(T6, NIC),
4385 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4386 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4387 			.intfver_ri = FW_INTFVER(T6, RI),
4388 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4389 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4390 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4391 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4392 		},
4393 	}
4394 };
4395 
4396 static struct fw_info *
4397 find_fw_info(int chip)
4398 {
4399 	int i;
4400 
4401 	for (i = 0; i < nitems(fw_info); i++) {
4402 		if (fw_info[i].chip == chip)
4403 			return (&fw_info[i]);
4404 	}
4405 	return (NULL);
4406 }
4407 
4408 /*
4409  * Is the given firmware API compatible with the one the driver was compiled
4410  * with?
4411  */
4412 static int
4413 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4414 {
4415 
4416 	/* short circuit if it's the exact same firmware version */
4417 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4418 		return (1);
4419 
4420 	/*
4421 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4422 	 * features that are supported in the driver.
4423 	 */
4424 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4425 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4426 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4427 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4428 		return (1);
4429 #undef SAME_INTF
4430 
4431 	return (0);
4432 }
4433 
4434 static int
4435 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4436     const struct firmware **fw)
4437 {
4438 	struct fw_info *fw_info;
4439 
4440 	*dcfg = NULL;
4441 	if (fw != NULL)
4442 		*fw = NULL;
4443 
4444 	fw_info = find_fw_info(chip_id(sc));
4445 	if (fw_info == NULL) {
4446 		device_printf(sc->dev,
4447 		    "unable to look up firmware information for chip %d.\n",
4448 		    chip_id(sc));
4449 		return (EINVAL);
4450 	}
4451 
4452 	*dcfg = firmware_get(fw_info->kld_name);
4453 	if (*dcfg != NULL) {
4454 		if (fw != NULL)
4455 			*fw = firmware_get(fw_info->fw_mod_name);
4456 		return (0);
4457 	}
4458 
4459 	return (ENOENT);
4460 }
4461 
4462 static void
4463 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4464     const struct firmware *fw)
4465 {
4466 
4467 	if (fw != NULL)
4468 		firmware_put(fw, FIRMWARE_UNLOAD);
4469 	if (dcfg != NULL)
4470 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4471 }
4472 
4473 /*
4474  * Return values:
4475  * 0 means no firmware install attempted.
4476  * ERESTART means a firmware install was attempted and was successful.
4477  * +ve errno means a firmware install was attempted but failed.
4478  */
4479 static int
4480 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4481     const struct fw_h *drv_fw, const char *reason, int *already)
4482 {
4483 	const struct firmware *cfg, *fw;
4484 	const uint32_t c = be32toh(card_fw->fw_ver);
4485 	uint32_t d, k;
4486 	int rc, fw_install;
4487 	struct fw_h bundled_fw;
4488 	bool load_attempted;
4489 
4490 	cfg = fw = NULL;
4491 	load_attempted = false;
4492 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4493 
4494 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4495 	if (t4_fw_install < 0) {
4496 		rc = load_fw_module(sc, &cfg, &fw);
4497 		if (rc != 0 || fw == NULL) {
4498 			device_printf(sc->dev,
4499 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4500 			    " will use compiled-in firmware version for"
4501 			    "hw.cxgbe.fw_install checks.\n",
4502 			    rc, cfg, fw);
4503 		} else {
4504 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4505 		}
4506 		load_attempted = true;
4507 	}
4508 	d = be32toh(bundled_fw.fw_ver);
4509 
4510 	if (reason != NULL)
4511 		goto install;
4512 
4513 	if ((sc->flags & FW_OK) == 0) {
4514 
4515 		if (c == 0xffffffff) {
4516 			reason = "missing";
4517 			goto install;
4518 		}
4519 
4520 		rc = 0;
4521 		goto done;
4522 	}
4523 
4524 	if (!fw_compatible(card_fw, &bundled_fw)) {
4525 		reason = "incompatible or unusable";
4526 		goto install;
4527 	}
4528 
4529 	if (d > c) {
4530 		reason = "older than the version bundled with this driver";
4531 		goto install;
4532 	}
4533 
4534 	if (fw_install == 2 && d != c) {
4535 		reason = "different than the version bundled with this driver";
4536 		goto install;
4537 	}
4538 
4539 	/* No reason to do anything to the firmware already on the card. */
4540 	rc = 0;
4541 	goto done;
4542 
4543 install:
4544 	rc = 0;
4545 	if ((*already)++)
4546 		goto done;
4547 
4548 	if (fw_install == 0) {
4549 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4550 		    "but the driver is prohibited from installing a firmware "
4551 		    "on the card.\n",
4552 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4553 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4554 
4555 		goto done;
4556 	}
4557 
4558 	/*
4559 	 * We'll attempt to install a firmware.  Load the module first (if it
4560 	 * hasn't been loaded already).
4561 	 */
4562 	if (!load_attempted) {
4563 		rc = load_fw_module(sc, &cfg, &fw);
4564 		if (rc != 0 || fw == NULL) {
4565 			device_printf(sc->dev,
4566 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4567 			    rc, cfg, fw);
4568 			/* carry on */
4569 		}
4570 	}
4571 	if (fw == NULL) {
4572 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4573 		    "but the driver cannot take corrective action because it "
4574 		    "is unable to load the firmware module.\n",
4575 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4576 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4577 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4578 		goto done;
4579 	}
4580 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4581 	if (k != d) {
4582 		MPASS(t4_fw_install > 0);
4583 		device_printf(sc->dev,
4584 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4585 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4586 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4587 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4588 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4589 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4590 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4591 		goto done;
4592 	}
4593 
4594 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4595 	    "installing firmware %u.%u.%u.%u on card.\n",
4596 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4597 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4598 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4599 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4600 
4601 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4602 	if (rc != 0) {
4603 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4604 	} else {
4605 		/* Installed successfully, update the cached header too. */
4606 		rc = ERESTART;
4607 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4608 	}
4609 done:
4610 	unload_fw_module(sc, cfg, fw);
4611 
4612 	return (rc);
4613 }
4614 
4615 /*
4616  * Establish contact with the firmware and attempt to become the master driver.
4617  *
4618  * A firmware will be installed to the card if needed (if the driver is allowed
4619  * to do so).
4620  */
4621 static int
4622 contact_firmware(struct adapter *sc)
4623 {
4624 	int rc, already = 0;
4625 	enum dev_state state;
4626 	struct fw_info *fw_info;
4627 	struct fw_hdr *card_fw;		/* fw on the card */
4628 	const struct fw_h *drv_fw;
4629 
4630 	fw_info = find_fw_info(chip_id(sc));
4631 	if (fw_info == NULL) {
4632 		device_printf(sc->dev,
4633 		    "unable to look up firmware information for chip %d.\n",
4634 		    chip_id(sc));
4635 		return (EINVAL);
4636 	}
4637 	drv_fw = &fw_info->fw_h;
4638 
4639 	/* Read the header of the firmware on the card */
4640 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4641 restart:
4642 	rc = -t4_get_fw_hdr(sc, card_fw);
4643 	if (rc != 0) {
4644 		device_printf(sc->dev,
4645 		    "unable to read firmware header from card's flash: %d\n",
4646 		    rc);
4647 		goto done;
4648 	}
4649 
4650 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4651 	    &already);
4652 	if (rc == ERESTART)
4653 		goto restart;
4654 	if (rc != 0)
4655 		goto done;
4656 
4657 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4658 	if (rc < 0 || state == DEV_STATE_ERR) {
4659 		rc = -rc;
4660 		device_printf(sc->dev,
4661 		    "failed to connect to the firmware: %d, %d.  "
4662 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4663 #if 0
4664 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4665 		    "not responding properly to HELLO", &already) == ERESTART)
4666 			goto restart;
4667 #endif
4668 		goto done;
4669 	}
4670 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4671 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4672 
4673 	if (rc == sc->pf) {
4674 		sc->flags |= MASTER_PF;
4675 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4676 		    NULL, &already);
4677 		if (rc == ERESTART)
4678 			rc = 0;
4679 		else if (rc != 0)
4680 			goto done;
4681 	} else if (state == DEV_STATE_UNINIT) {
4682 		/*
4683 		 * We didn't get to be the master so we definitely won't be
4684 		 * configuring the chip.  It's a bug if someone else hasn't
4685 		 * configured it already.
4686 		 */
4687 		device_printf(sc->dev, "couldn't be master(%d), "
4688 		    "device not already initialized either(%d).  "
4689 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4690 		rc = EPROTO;
4691 		goto done;
4692 	} else {
4693 		/*
4694 		 * Some other PF is the master and has configured the chip.
4695 		 * This is allowed but untested.
4696 		 */
4697 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4698 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4699 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4700 		sc->cfcsum = 0;
4701 		rc = 0;
4702 	}
4703 done:
4704 	if (rc != 0 && sc->flags & FW_OK) {
4705 		t4_fw_bye(sc, sc->mbox);
4706 		sc->flags &= ~FW_OK;
4707 	}
4708 	free(card_fw, M_CXGBE);
4709 	return (rc);
4710 }
4711 
4712 static int
4713 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4714     uint32_t mtype, uint32_t moff)
4715 {
4716 	struct fw_info *fw_info;
4717 	const struct firmware *dcfg, *rcfg = NULL;
4718 	const uint32_t *cfdata;
4719 	uint32_t cflen, addr;
4720 	int rc;
4721 
4722 	load_fw_module(sc, &dcfg, NULL);
4723 
4724 	/* Card specific interpretation of "default". */
4725 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4726 		if (pci_get_device(sc->dev) == 0x440a)
4727 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4728 		if (is_fpga(sc))
4729 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4730 	}
4731 
4732 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4733 		if (dcfg == NULL) {
4734 			device_printf(sc->dev,
4735 			    "KLD with default config is not available.\n");
4736 			rc = ENOENT;
4737 			goto done;
4738 		}
4739 		cfdata = dcfg->data;
4740 		cflen = dcfg->datasize & ~3;
4741 	} else {
4742 		char s[32];
4743 
4744 		fw_info = find_fw_info(chip_id(sc));
4745 		if (fw_info == NULL) {
4746 			device_printf(sc->dev,
4747 			    "unable to look up firmware information for chip %d.\n",
4748 			    chip_id(sc));
4749 			rc = EINVAL;
4750 			goto done;
4751 		}
4752 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4753 
4754 		rcfg = firmware_get(s);
4755 		if (rcfg == NULL) {
4756 			device_printf(sc->dev,
4757 			    "unable to load module \"%s\" for configuration "
4758 			    "profile \"%s\".\n", s, cfg_file);
4759 			rc = ENOENT;
4760 			goto done;
4761 		}
4762 		cfdata = rcfg->data;
4763 		cflen = rcfg->datasize & ~3;
4764 	}
4765 
4766 	if (cflen > FLASH_CFG_MAX_SIZE) {
4767 		device_printf(sc->dev,
4768 		    "config file too long (%d, max allowed is %d).\n",
4769 		    cflen, FLASH_CFG_MAX_SIZE);
4770 		rc = EINVAL;
4771 		goto done;
4772 	}
4773 
4774 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4775 	if (rc != 0) {
4776 		device_printf(sc->dev,
4777 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4778 		    __func__, mtype, moff, cflen, rc);
4779 		rc = EINVAL;
4780 		goto done;
4781 	}
4782 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4783 done:
4784 	if (rcfg != NULL)
4785 		firmware_put(rcfg, FIRMWARE_UNLOAD);
4786 	unload_fw_module(sc, dcfg, NULL);
4787 	return (rc);
4788 }
4789 
4790 struct caps_allowed {
4791 	uint16_t nbmcaps;
4792 	uint16_t linkcaps;
4793 	uint16_t switchcaps;
4794 	uint16_t niccaps;
4795 	uint16_t toecaps;
4796 	uint16_t rdmacaps;
4797 	uint16_t cryptocaps;
4798 	uint16_t iscsicaps;
4799 	uint16_t fcoecaps;
4800 };
4801 
4802 #define FW_PARAM_DEV(param) \
4803 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4804 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4805 #define FW_PARAM_PFVF(param) \
4806 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4807 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4808 
4809 /*
4810  * Provide a configuration profile to the firmware and have it initialize the
4811  * chip accordingly.  This may involve uploading a configuration file to the
4812  * card.
4813  */
4814 static int
4815 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4816     const struct caps_allowed *caps_allowed)
4817 {
4818 	int rc;
4819 	struct fw_caps_config_cmd caps;
4820 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
4821 
4822 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4823 	if (rc != 0) {
4824 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
4825 		return (rc);
4826 	}
4827 
4828 	bzero(&caps, sizeof(caps));
4829 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4830 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
4831 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
4832 		mtype = 0;
4833 		moff = 0;
4834 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4835 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
4836 		mtype = FW_MEMTYPE_FLASH;
4837 		moff = t4_flash_cfg_addr(sc);
4838 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4839 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4840 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4841 		    FW_LEN16(caps));
4842 	} else {
4843 		/*
4844 		 * Ask the firmware where it wants us to upload the config file.
4845 		 */
4846 		param = FW_PARAM_DEV(CF);
4847 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4848 		if (rc != 0) {
4849 			/* No support for config file?  Shouldn't happen. */
4850 			device_printf(sc->dev,
4851 			    "failed to query config file location: %d.\n", rc);
4852 			goto done;
4853 		}
4854 		mtype = G_FW_PARAMS_PARAM_Y(val);
4855 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
4856 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4857 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4858 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4859 		    FW_LEN16(caps));
4860 
4861 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
4862 		if (rc != 0) {
4863 			device_printf(sc->dev,
4864 			    "failed to upload config file to card: %d.\n", rc);
4865 			goto done;
4866 		}
4867 	}
4868 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
4869 	if (rc != 0) {
4870 		device_printf(sc->dev, "failed to pre-process config file: %d "
4871 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
4872 		goto done;
4873 	}
4874 
4875 	finicsum = be32toh(caps.finicsum);
4876 	cfcsum = be32toh(caps.cfcsum);	/* actual */
4877 	if (finicsum != cfcsum) {
4878 		device_printf(sc->dev,
4879 		    "WARNING: config file checksum mismatch: %08x %08x\n",
4880 		    finicsum, cfcsum);
4881 	}
4882 	sc->cfcsum = cfcsum;
4883 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
4884 
4885 	/*
4886 	 * Let the firmware know what features will (not) be used so it can tune
4887 	 * things accordingly.
4888 	 */
4889 #define LIMIT_CAPS(x) do { \
4890 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
4891 } while (0)
4892 	LIMIT_CAPS(nbm);
4893 	LIMIT_CAPS(link);
4894 	LIMIT_CAPS(switch);
4895 	LIMIT_CAPS(nic);
4896 	LIMIT_CAPS(toe);
4897 	LIMIT_CAPS(rdma);
4898 	LIMIT_CAPS(crypto);
4899 	LIMIT_CAPS(iscsi);
4900 	LIMIT_CAPS(fcoe);
4901 #undef LIMIT_CAPS
4902 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
4903 		/*
4904 		 * TOE and hashfilters are mutually exclusive.  It is a config
4905 		 * file or firmware bug if both are reported as available.  Try
4906 		 * to cope with the situation in non-debug builds by disabling
4907 		 * TOE.
4908 		 */
4909 		MPASS(caps.toecaps == 0);
4910 
4911 		caps.toecaps = 0;
4912 		caps.rdmacaps = 0;
4913 		caps.iscsicaps = 0;
4914 	}
4915 
4916 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4917 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
4918 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4919 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
4920 	if (rc != 0) {
4921 		device_printf(sc->dev,
4922 		    "failed to process config file: %d.\n", rc);
4923 		goto done;
4924 	}
4925 
4926 	t4_tweak_chip_settings(sc);
4927 	set_params__pre_init(sc);
4928 
4929 	/* get basic stuff going */
4930 	rc = -t4_fw_initialize(sc, sc->mbox);
4931 	if (rc != 0) {
4932 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
4933 		goto done;
4934 	}
4935 done:
4936 	return (rc);
4937 }
4938 
4939 /*
4940  * Partition chip resources for use between various PFs, VFs, etc.
4941  */
4942 static int
4943 partition_resources(struct adapter *sc)
4944 {
4945 	char cfg_file[sizeof(t4_cfg_file)];
4946 	struct caps_allowed caps_allowed;
4947 	int rc;
4948 	bool fallback;
4949 
4950 	/* Only the master driver gets to configure the chip resources. */
4951 	MPASS(sc->flags & MASTER_PF);
4952 
4953 #define COPY_CAPS(x) do { \
4954 	caps_allowed.x##caps = t4_##x##caps_allowed; \
4955 } while (0)
4956 	bzero(&caps_allowed, sizeof(caps_allowed));
4957 	COPY_CAPS(nbm);
4958 	COPY_CAPS(link);
4959 	COPY_CAPS(switch);
4960 	COPY_CAPS(nic);
4961 	COPY_CAPS(toe);
4962 	COPY_CAPS(rdma);
4963 	COPY_CAPS(crypto);
4964 	COPY_CAPS(iscsi);
4965 	COPY_CAPS(fcoe);
4966 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
4967 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
4968 retry:
4969 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
4970 	if (rc != 0 && fallback) {
4971 		device_printf(sc->dev,
4972 		    "failed (%d) to configure card with \"%s\" profile, "
4973 		    "will fall back to a basic configuration and retry.\n",
4974 		    rc, cfg_file);
4975 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
4976 		bzero(&caps_allowed, sizeof(caps_allowed));
4977 		COPY_CAPS(switch);
4978 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
4979 		fallback = false;
4980 		goto retry;
4981 	}
4982 #undef COPY_CAPS
4983 	return (rc);
4984 }
4985 
4986 /*
4987  * Retrieve parameters that are needed (or nice to have) very early.
4988  */
4989 static int
4990 get_params__pre_init(struct adapter *sc)
4991 {
4992 	int rc;
4993 	uint32_t param[2], val[2];
4994 
4995 	t4_get_version_info(sc);
4996 
4997 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
4998 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
4999 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5000 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5001 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5002 
5003 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5004 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5005 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5006 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5007 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5008 
5009 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5010 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5011 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5012 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5013 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5014 
5015 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5016 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5017 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5018 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5019 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5020 
5021 	param[0] = FW_PARAM_DEV(PORTVEC);
5022 	param[1] = FW_PARAM_DEV(CCLK);
5023 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5024 	if (rc != 0) {
5025 		device_printf(sc->dev,
5026 		    "failed to query parameters (pre_init): %d.\n", rc);
5027 		return (rc);
5028 	}
5029 
5030 	sc->params.portvec = val[0];
5031 	sc->params.nports = bitcount32(val[0]);
5032 	sc->params.vpd.cclk = val[1];
5033 
5034 	/* Read device log parameters. */
5035 	rc = -t4_init_devlog_params(sc, 1);
5036 	if (rc == 0)
5037 		fixup_devlog_params(sc);
5038 	else {
5039 		device_printf(sc->dev,
5040 		    "failed to get devlog parameters: %d.\n", rc);
5041 		rc = 0;	/* devlog isn't critical for device operation */
5042 	}
5043 
5044 	return (rc);
5045 }
5046 
5047 /*
5048  * Any params that need to be set before FW_INITIALIZE.
5049  */
5050 static int
5051 set_params__pre_init(struct adapter *sc)
5052 {
5053 	int rc = 0;
5054 	uint32_t param, val;
5055 
5056 	if (chip_id(sc) >= CHELSIO_T6) {
5057 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5058 		val = 1;
5059 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5060 		/* firmwares < 1.20.1.0 do not have this param. */
5061 		if (rc == FW_EINVAL &&
5062 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5063 			rc = 0;
5064 		}
5065 		if (rc != 0) {
5066 			device_printf(sc->dev,
5067 			    "failed to enable high priority filters :%d.\n",
5068 			    rc);
5069 		}
5070 	}
5071 
5072 	/* Enable opaque VIIDs with firmwares that support it. */
5073 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5074 	val = 1;
5075 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5076 	if (rc == 0 && val == 1)
5077 		sc->params.viid_smt_extn_support = true;
5078 	else
5079 		sc->params.viid_smt_extn_support = false;
5080 
5081 	return (rc);
5082 }
5083 
5084 /*
5085  * Retrieve various parameters that are of interest to the driver.  The device
5086  * has been initialized by the firmware at this point.
5087  */
5088 static int
5089 get_params__post_init(struct adapter *sc)
5090 {
5091 	int rc;
5092 	uint32_t param[7], val[7];
5093 	struct fw_caps_config_cmd caps;
5094 
5095 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5096 	param[1] = FW_PARAM_PFVF(EQ_START);
5097 	param[2] = FW_PARAM_PFVF(FILTER_START);
5098 	param[3] = FW_PARAM_PFVF(FILTER_END);
5099 	param[4] = FW_PARAM_PFVF(L2T_START);
5100 	param[5] = FW_PARAM_PFVF(L2T_END);
5101 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5102 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5103 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5104 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5105 	if (rc != 0) {
5106 		device_printf(sc->dev,
5107 		    "failed to query parameters (post_init): %d.\n", rc);
5108 		return (rc);
5109 	}
5110 
5111 	sc->sge.iq_start = val[0];
5112 	sc->sge.eq_start = val[1];
5113 	if ((int)val[3] > (int)val[2]) {
5114 		sc->tids.ftid_base = val[2];
5115 		sc->tids.ftid_end = val[3];
5116 		sc->tids.nftids = val[3] - val[2] + 1;
5117 	}
5118 	sc->vres.l2t.start = val[4];
5119 	sc->vres.l2t.size = val[5] - val[4] + 1;
5120 	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
5121 	    ("%s: L2 table size (%u) larger than expected (%u)",
5122 	    __func__, sc->vres.l2t.size, L2T_SIZE));
5123 	sc->params.core_vdd = val[6];
5124 
5125 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5126 	param[1] = FW_PARAM_PFVF(EQ_END);
5127 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5128 	if (rc != 0) {
5129 		device_printf(sc->dev,
5130 		    "failed to query parameters (post_init2): %d.\n", rc);
5131 		return (rc);
5132 	}
5133 	MPASS((int)val[0] >= sc->sge.iq_start);
5134 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5135 	MPASS((int)val[1] >= sc->sge.eq_start);
5136 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5137 
5138 	if (chip_id(sc) >= CHELSIO_T6) {
5139 
5140 		sc->tids.tid_base = t4_read_reg(sc,
5141 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5142 
5143 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5144 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5145 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5146 		if (rc != 0) {
5147 			device_printf(sc->dev,
5148 			   "failed to query hpfilter parameters: %d.\n", rc);
5149 			return (rc);
5150 		}
5151 		if ((int)val[1] > (int)val[0]) {
5152 			sc->tids.hpftid_base = val[0];
5153 			sc->tids.hpftid_end = val[1];
5154 			sc->tids.nhpftids = val[1] - val[0] + 1;
5155 
5156 			/*
5157 			 * These should go off if the layout changes and the
5158 			 * driver needs to catch up.
5159 			 */
5160 			MPASS(sc->tids.hpftid_base == 0);
5161 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5162 		}
5163 
5164 		param[0] = FW_PARAM_PFVF(RAWF_START);
5165 		param[1] = FW_PARAM_PFVF(RAWF_END);
5166 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5167 		if (rc != 0) {
5168 			device_printf(sc->dev,
5169 			   "failed to query rawf parameters: %d.\n", rc);
5170 			return (rc);
5171 		}
5172 		if ((int)val[1] > (int)val[0]) {
5173 			sc->rawf_base = val[0];
5174 			sc->nrawf = val[1] - val[0] + 1;
5175 		}
5176 	}
5177 
5178 	/*
5179 	 * MPSBGMAP is queried separately because only recent firmwares support
5180 	 * it as a parameter and we don't want the compound query above to fail
5181 	 * on older firmwares.
5182 	 */
5183 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5184 	val[0] = 0;
5185 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5186 	if (rc == 0)
5187 		sc->params.mps_bg_map = val[0];
5188 	else
5189 		sc->params.mps_bg_map = 0;
5190 
5191 	/*
5192 	 * Determine whether the firmware supports the filter2 work request.
5193 	 * This is queried separately for the same reason as MPSBGMAP above.
5194 	 */
5195 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5196 	val[0] = 0;
5197 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5198 	if (rc == 0)
5199 		sc->params.filter2_wr_support = val[0] != 0;
5200 	else
5201 		sc->params.filter2_wr_support = 0;
5202 
5203 	/*
5204 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5205 	 * This is queried separately for the same reason as other params above.
5206 	 */
5207 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5208 	val[0] = 0;
5209 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5210 	if (rc == 0)
5211 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5212 	else
5213 		sc->params.ulptx_memwrite_dsgl = false;
5214 
5215 	/* FW_RI_FR_NSMR_TPTE_WR support */
5216 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5217 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5218 	if (rc == 0)
5219 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5220 	else
5221 		sc->params.fr_nsmr_tpte_wr_support = false;
5222 
5223 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5224 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5225 	if (rc == 0)
5226 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5227 	else
5228 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5229 
5230 	/* get capabilites */
5231 	bzero(&caps, sizeof(caps));
5232 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5233 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5234 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5235 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5236 	if (rc != 0) {
5237 		device_printf(sc->dev,
5238 		    "failed to get card capabilities: %d.\n", rc);
5239 		return (rc);
5240 	}
5241 
5242 #define READ_CAPS(x) do { \
5243 	sc->x = htobe16(caps.x); \
5244 } while (0)
5245 	READ_CAPS(nbmcaps);
5246 	READ_CAPS(linkcaps);
5247 	READ_CAPS(switchcaps);
5248 	READ_CAPS(niccaps);
5249 	READ_CAPS(toecaps);
5250 	READ_CAPS(rdmacaps);
5251 	READ_CAPS(cryptocaps);
5252 	READ_CAPS(iscsicaps);
5253 	READ_CAPS(fcoecaps);
5254 
5255 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5256 		MPASS(chip_id(sc) > CHELSIO_T4);
5257 		MPASS(sc->toecaps == 0);
5258 		sc->toecaps = 0;
5259 
5260 		param[0] = FW_PARAM_DEV(NTID);
5261 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5262 		if (rc != 0) {
5263 			device_printf(sc->dev,
5264 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5265 			return (rc);
5266 		}
5267 		sc->tids.ntids = val[0];
5268 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5269 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5270 			sc->tids.ntids -= sc->tids.nhpftids;
5271 		}
5272 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5273 		sc->params.hash_filter = 1;
5274 	}
5275 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5276 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5277 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5278 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5279 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5280 		if (rc != 0) {
5281 			device_printf(sc->dev,
5282 			    "failed to query NIC parameters: %d.\n", rc);
5283 			return (rc);
5284 		}
5285 		if ((int)val[1] > (int)val[0]) {
5286 			sc->tids.etid_base = val[0];
5287 			sc->tids.etid_end = val[1];
5288 			sc->tids.netids = val[1] - val[0] + 1;
5289 			sc->params.eo_wr_cred = val[2];
5290 			sc->params.ethoffload = 1;
5291 		}
5292 	}
5293 	if (sc->toecaps) {
5294 		/* query offload-related parameters */
5295 		param[0] = FW_PARAM_DEV(NTID);
5296 		param[1] = FW_PARAM_PFVF(SERVER_START);
5297 		param[2] = FW_PARAM_PFVF(SERVER_END);
5298 		param[3] = FW_PARAM_PFVF(TDDP_START);
5299 		param[4] = FW_PARAM_PFVF(TDDP_END);
5300 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5301 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5302 		if (rc != 0) {
5303 			device_printf(sc->dev,
5304 			    "failed to query TOE parameters: %d.\n", rc);
5305 			return (rc);
5306 		}
5307 		sc->tids.ntids = val[0];
5308 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5309 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5310 			sc->tids.ntids -= sc->tids.nhpftids;
5311 		}
5312 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5313 		if ((int)val[2] > (int)val[1]) {
5314 			sc->tids.stid_base = val[1];
5315 			sc->tids.nstids = val[2] - val[1] + 1;
5316 		}
5317 		sc->vres.ddp.start = val[3];
5318 		sc->vres.ddp.size = val[4] - val[3] + 1;
5319 		sc->params.ofldq_wr_cred = val[5];
5320 		sc->params.offload = 1;
5321 	} else {
5322 		/*
5323 		 * The firmware attempts memfree TOE configuration for -SO cards
5324 		 * and will report toecaps=0 if it runs out of resources (this
5325 		 * depends on the config file).  It may not report 0 for other
5326 		 * capabilities dependent on the TOE in this case.  Set them to
5327 		 * 0 here so that the driver doesn't bother tracking resources
5328 		 * that will never be used.
5329 		 */
5330 		sc->iscsicaps = 0;
5331 		sc->rdmacaps = 0;
5332 	}
5333 	if (sc->rdmacaps) {
5334 		param[0] = FW_PARAM_PFVF(STAG_START);
5335 		param[1] = FW_PARAM_PFVF(STAG_END);
5336 		param[2] = FW_PARAM_PFVF(RQ_START);
5337 		param[3] = FW_PARAM_PFVF(RQ_END);
5338 		param[4] = FW_PARAM_PFVF(PBL_START);
5339 		param[5] = FW_PARAM_PFVF(PBL_END);
5340 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5341 		if (rc != 0) {
5342 			device_printf(sc->dev,
5343 			    "failed to query RDMA parameters(1): %d.\n", rc);
5344 			return (rc);
5345 		}
5346 		sc->vres.stag.start = val[0];
5347 		sc->vres.stag.size = val[1] - val[0] + 1;
5348 		sc->vres.rq.start = val[2];
5349 		sc->vres.rq.size = val[3] - val[2] + 1;
5350 		sc->vres.pbl.start = val[4];
5351 		sc->vres.pbl.size = val[5] - val[4] + 1;
5352 
5353 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5354 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5355 		param[2] = FW_PARAM_PFVF(CQ_START);
5356 		param[3] = FW_PARAM_PFVF(CQ_END);
5357 		param[4] = FW_PARAM_PFVF(OCQ_START);
5358 		param[5] = FW_PARAM_PFVF(OCQ_END);
5359 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5360 		if (rc != 0) {
5361 			device_printf(sc->dev,
5362 			    "failed to query RDMA parameters(2): %d.\n", rc);
5363 			return (rc);
5364 		}
5365 		sc->vres.qp.start = val[0];
5366 		sc->vres.qp.size = val[1] - val[0] + 1;
5367 		sc->vres.cq.start = val[2];
5368 		sc->vres.cq.size = val[3] - val[2] + 1;
5369 		sc->vres.ocq.start = val[4];
5370 		sc->vres.ocq.size = val[5] - val[4] + 1;
5371 
5372 		param[0] = FW_PARAM_PFVF(SRQ_START);
5373 		param[1] = FW_PARAM_PFVF(SRQ_END);
5374 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5375 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5376 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5377 		if (rc != 0) {
5378 			device_printf(sc->dev,
5379 			    "failed to query RDMA parameters(3): %d.\n", rc);
5380 			return (rc);
5381 		}
5382 		sc->vres.srq.start = val[0];
5383 		sc->vres.srq.size = val[1] - val[0] + 1;
5384 		sc->params.max_ordird_qp = val[2];
5385 		sc->params.max_ird_adapter = val[3];
5386 	}
5387 	if (sc->iscsicaps) {
5388 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5389 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5390 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5391 		if (rc != 0) {
5392 			device_printf(sc->dev,
5393 			    "failed to query iSCSI parameters: %d.\n", rc);
5394 			return (rc);
5395 		}
5396 		sc->vres.iscsi.start = val[0];
5397 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5398 	}
5399 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5400 		param[0] = FW_PARAM_PFVF(TLS_START);
5401 		param[1] = FW_PARAM_PFVF(TLS_END);
5402 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5403 		if (rc != 0) {
5404 			device_printf(sc->dev,
5405 			    "failed to query TLS parameters: %d.\n", rc);
5406 			return (rc);
5407 		}
5408 		sc->vres.key.start = val[0];
5409 		sc->vres.key.size = val[1] - val[0] + 1;
5410 	}
5411 
5412 	/*
5413 	 * We've got the params we wanted to query directly from the firmware.
5414 	 * Grab some others via other means.
5415 	 */
5416 	t4_init_sge_params(sc);
5417 	t4_init_tp_params(sc);
5418 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5419 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5420 
5421 	rc = t4_verify_chip_settings(sc);
5422 	if (rc != 0)
5423 		return (rc);
5424 	t4_init_rx_buf_info(sc);
5425 
5426 	return (rc);
5427 }
5428 
5429 #ifdef KERN_TLS
5430 static void
5431 ktls_tick(void *arg)
5432 {
5433 	struct adapter *sc;
5434 	uint32_t tstamp;
5435 
5436 	sc = arg;
5437 	if (sc->flags & KERN_TLS_ON) {
5438 		tstamp = tcp_ts_getticks();
5439 		t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5440 		t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5441 	}
5442 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5443 }
5444 
5445 static int
5446 t4_config_kern_tls(struct adapter *sc, bool enable)
5447 {
5448 	int rc;
5449 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5450 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5451 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5452 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5453 
5454 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5455 	if (rc != 0) {
5456 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5457 		    enable ?  "enable" : "disable", rc);
5458 		return (rc);
5459 	}
5460 
5461 	if (enable)
5462 		sc->flags |= KERN_TLS_ON;
5463 	else
5464 		sc->flags &= ~KERN_TLS_ON;
5465 
5466 	return (rc);
5467 }
5468 #endif
5469 
5470 static int
5471 set_params__post_init(struct adapter *sc)
5472 {
5473 	uint32_t mask, param, val;
5474 #ifdef TCP_OFFLOAD
5475 	int i, v, shift;
5476 #endif
5477 
5478 	/* ask for encapsulated CPLs */
5479 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5480 	val = 1;
5481 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5482 
5483 	/* Enable 32b port caps if the firmware supports it. */
5484 	param = FW_PARAM_PFVF(PORT_CAPS32);
5485 	val = 1;
5486 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5487 		sc->params.port_caps32 = 1;
5488 
5489 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5490 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5491 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5492 	    V_MASKFILTER(val - 1));
5493 
5494 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5495 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5496 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5497 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5498 	val = 0;
5499 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5500 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5501 		    F_ATTACKFILTERENABLE);
5502 		val |= F_DROPERRORATTACK;
5503 	}
5504 	if (t4_drop_ip_fragments != 0) {
5505 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5506 		    F_FRAGMENTDROP);
5507 		val |= F_DROPERRORFRAG;
5508 	}
5509 	if (t4_drop_pkts_with_l2_errors != 0)
5510 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5511 	if (t4_drop_pkts_with_l3_errors != 0) {
5512 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5513 		    F_DROPERRORCSUMIP;
5514 	}
5515 	if (t4_drop_pkts_with_l4_errors != 0) {
5516 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5517 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5518 	}
5519 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5520 
5521 #ifdef TCP_OFFLOAD
5522 	/*
5523 	 * Override the TOE timers with user provided tunables.  This is not the
5524 	 * recommended way to change the timers (the firmware config file is) so
5525 	 * these tunables are not documented.
5526 	 *
5527 	 * All the timer tunables are in microseconds.
5528 	 */
5529 	if (t4_toe_keepalive_idle != 0) {
5530 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5531 		v &= M_KEEPALIVEIDLE;
5532 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5533 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5534 	}
5535 	if (t4_toe_keepalive_interval != 0) {
5536 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5537 		v &= M_KEEPALIVEINTVL;
5538 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5539 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5540 	}
5541 	if (t4_toe_keepalive_count != 0) {
5542 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5543 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5544 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5545 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5546 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5547 	}
5548 	if (t4_toe_rexmt_min != 0) {
5549 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5550 		v &= M_RXTMIN;
5551 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5552 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5553 	}
5554 	if (t4_toe_rexmt_max != 0) {
5555 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5556 		v &= M_RXTMAX;
5557 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5558 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5559 	}
5560 	if (t4_toe_rexmt_count != 0) {
5561 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5562 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5563 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5564 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5565 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5566 	}
5567 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5568 		if (t4_toe_rexmt_backoff[i] != -1) {
5569 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5570 			shift = (i & 3) << 3;
5571 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5572 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5573 		}
5574 	}
5575 #endif
5576 
5577 #ifdef KERN_TLS
5578 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS &&
5579 	    sc->toecaps & FW_CAPS_CONFIG_TOE) {
5580 		/*
5581 		 * Limit TOE connections to 2 reassembly "islands".  This is
5582 		 * required for TOE TLS connections to downgrade to plain TOE
5583 		 * connections if an unsupported TLS version or ciphersuite is
5584 		 * used.
5585 		 */
5586 		t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG,
5587 		    V_PASSMODE(M_PASSMODE), V_PASSMODE(2));
5588 		if (is_ktls(sc)) {
5589 			sc->tlst.inline_keys = t4_tls_inline_keys;
5590 			sc->tlst.combo_wrs = t4_tls_combo_wrs;
5591 			if (t4_kern_tls != 0)
5592 				t4_config_kern_tls(sc, true);
5593 		}
5594 	}
5595 #endif
5596 	return (0);
5597 }
5598 
5599 #undef FW_PARAM_PFVF
5600 #undef FW_PARAM_DEV
5601 
5602 static void
5603 t4_set_desc(struct adapter *sc)
5604 {
5605 	char buf[128];
5606 	struct adapter_params *p = &sc->params;
5607 
5608 	snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
5609 
5610 	device_set_desc_copy(sc->dev, buf);
5611 }
5612 
5613 static inline void
5614 ifmedia_add4(struct ifmedia *ifm, int m)
5615 {
5616 
5617 	ifmedia_add(ifm, m, 0, NULL);
5618 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5619 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5620 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5621 }
5622 
5623 /*
5624  * This is the selected media, which is not quite the same as the active media.
5625  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5626  * and active are not the same, and "media: Ethernet selected" otherwise.
5627  */
5628 static void
5629 set_current_media(struct port_info *pi)
5630 {
5631 	struct link_config *lc;
5632 	struct ifmedia *ifm;
5633 	int mword;
5634 	u_int speed;
5635 
5636 	PORT_LOCK_ASSERT_OWNED(pi);
5637 
5638 	/* Leave current media alone if it's already set to IFM_NONE. */
5639 	ifm = &pi->media;
5640 	if (ifm->ifm_cur != NULL &&
5641 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5642 		return;
5643 
5644 	lc = &pi->link_cfg;
5645 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5646 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5647 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5648 		return;
5649 	}
5650 	mword = IFM_ETHER | IFM_FDX;
5651 	if (lc->requested_fc & PAUSE_TX)
5652 		mword |= IFM_ETH_TXPAUSE;
5653 	if (lc->requested_fc & PAUSE_RX)
5654 		mword |= IFM_ETH_RXPAUSE;
5655 	if (lc->requested_speed == 0)
5656 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5657 	else
5658 		speed = lc->requested_speed;
5659 	mword |= port_mword(pi, speed_to_fwcap(speed));
5660 	ifmedia_set(ifm, mword);
5661 }
5662 
5663 /*
5664  * Returns true if the ifmedia list for the port cannot change.
5665  */
5666 static bool
5667 fixed_ifmedia(struct port_info *pi)
5668 {
5669 
5670 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5671 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5672 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5673 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5674 	    pi->port_type == FW_PORT_TYPE_KX ||
5675 	    pi->port_type == FW_PORT_TYPE_KR ||
5676 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5677 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5678 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5679 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5680 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5681 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5682 }
5683 
5684 static void
5685 build_medialist(struct port_info *pi)
5686 {
5687 	uint32_t ss, speed;
5688 	int unknown, mword, bit;
5689 	struct link_config *lc;
5690 	struct ifmedia *ifm;
5691 
5692 	PORT_LOCK_ASSERT_OWNED(pi);
5693 
5694 	if (pi->flags & FIXED_IFMEDIA)
5695 		return;
5696 
5697 	/*
5698 	 * Rebuild the ifmedia list.
5699 	 */
5700 	ifm = &pi->media;
5701 	ifmedia_removeall(ifm);
5702 	lc = &pi->link_cfg;
5703 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5704 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5705 		MPASS(ss != 0);
5706 no_media:
5707 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5708 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5709 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5710 		return;
5711 	}
5712 
5713 	unknown = 0;
5714 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5715 		speed = 1 << bit;
5716 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5717 		if (ss & speed) {
5718 			mword = port_mword(pi, speed);
5719 			if (mword == IFM_NONE) {
5720 				goto no_media;
5721 			} else if (mword == IFM_UNKNOWN)
5722 				unknown++;
5723 			else
5724 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5725 		}
5726 	}
5727 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5728 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5729 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5730 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5731 
5732 	set_current_media(pi);
5733 }
5734 
5735 /*
5736  * Initialize the requested fields in the link config based on driver tunables.
5737  */
5738 static void
5739 init_link_config(struct port_info *pi)
5740 {
5741 	struct link_config *lc = &pi->link_cfg;
5742 
5743 	PORT_LOCK_ASSERT_OWNED(pi);
5744 
5745 	lc->requested_speed = 0;
5746 
5747 	if (t4_autoneg == 0)
5748 		lc->requested_aneg = AUTONEG_DISABLE;
5749 	else if (t4_autoneg == 1)
5750 		lc->requested_aneg = AUTONEG_ENABLE;
5751 	else
5752 		lc->requested_aneg = AUTONEG_AUTO;
5753 
5754 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5755 	    PAUSE_AUTONEG);
5756 
5757 	if (t4_fec & FEC_AUTO)
5758 		lc->requested_fec = FEC_AUTO;
5759 	else if (t4_fec == 0)
5760 		lc->requested_fec = FEC_NONE;
5761 	else {
5762 		/* -1 is handled by the FEC_AUTO block above and not here. */
5763 		lc->requested_fec = t4_fec &
5764 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5765 		if (lc->requested_fec == 0)
5766 			lc->requested_fec = FEC_AUTO;
5767 	}
5768 }
5769 
5770 /*
5771  * Makes sure that all requested settings comply with what's supported by the
5772  * port.  Returns the number of settings that were invalid and had to be fixed.
5773  */
5774 static int
5775 fixup_link_config(struct port_info *pi)
5776 {
5777 	int n = 0;
5778 	struct link_config *lc = &pi->link_cfg;
5779 	uint32_t fwspeed;
5780 
5781 	PORT_LOCK_ASSERT_OWNED(pi);
5782 
5783 	/* Speed (when not autonegotiating) */
5784 	if (lc->requested_speed != 0) {
5785 		fwspeed = speed_to_fwcap(lc->requested_speed);
5786 		if ((fwspeed & lc->pcaps) == 0) {
5787 			n++;
5788 			lc->requested_speed = 0;
5789 		}
5790 	}
5791 
5792 	/* Link autonegotiation */
5793 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5794 	    lc->requested_aneg == AUTONEG_DISABLE ||
5795 	    lc->requested_aneg == AUTONEG_AUTO);
5796 	if (lc->requested_aneg == AUTONEG_ENABLE &&
5797 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5798 		n++;
5799 		lc->requested_aneg = AUTONEG_AUTO;
5800 	}
5801 
5802 	/* Flow control */
5803 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5804 	if (lc->requested_fc & PAUSE_TX &&
5805 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5806 		n++;
5807 		lc->requested_fc &= ~PAUSE_TX;
5808 	}
5809 	if (lc->requested_fc & PAUSE_RX &&
5810 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
5811 		n++;
5812 		lc->requested_fc &= ~PAUSE_RX;
5813 	}
5814 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
5815 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
5816 		n++;
5817 		lc->requested_fc |= PAUSE_AUTONEG;
5818 	}
5819 
5820 	/* FEC */
5821 	if ((lc->requested_fec & FEC_RS &&
5822 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
5823 	    (lc->requested_fec & FEC_BASER_RS &&
5824 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
5825 		n++;
5826 		lc->requested_fec = FEC_AUTO;
5827 	}
5828 
5829 	return (n);
5830 }
5831 
5832 /*
5833  * Apply the requested L1 settings, which are expected to be valid, to the
5834  * hardware.
5835  */
5836 static int
5837 apply_link_config(struct port_info *pi)
5838 {
5839 	struct adapter *sc = pi->adapter;
5840 	struct link_config *lc = &pi->link_cfg;
5841 	int rc;
5842 
5843 #ifdef INVARIANTS
5844 	ASSERT_SYNCHRONIZED_OP(sc);
5845 	PORT_LOCK_ASSERT_OWNED(pi);
5846 
5847 	if (lc->requested_aneg == AUTONEG_ENABLE)
5848 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
5849 	if (!(lc->requested_fc & PAUSE_AUTONEG))
5850 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
5851 	if (lc->requested_fc & PAUSE_TX)
5852 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
5853 	if (lc->requested_fc & PAUSE_RX)
5854 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
5855 	if (lc->requested_fec & FEC_RS)
5856 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
5857 	if (lc->requested_fec & FEC_BASER_RS)
5858 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
5859 #endif
5860 	rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
5861 	if (rc != 0) {
5862 		/* Don't complain if the VF driver gets back an EPERM. */
5863 		if (!(sc->flags & IS_VF) || rc != FW_EPERM)
5864 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
5865 	} else {
5866 		/*
5867 		 * An L1_CFG will almost always result in a link-change event if
5868 		 * the link is up, and the driver will refresh the actual
5869 		 * fec/fc/etc. when the notification is processed.  If the link
5870 		 * is down then the actual settings are meaningless.
5871 		 *
5872 		 * This takes care of the case where a change in the L1 settings
5873 		 * may not result in a notification.
5874 		 */
5875 		if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
5876 			lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
5877 	}
5878 	return (rc);
5879 }
5880 
5881 #define FW_MAC_EXACT_CHUNK	7
5882 struct mcaddr_ctx {
5883 	struct ifnet *ifp;
5884 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
5885 	uint64_t hash;
5886 	int i;
5887 	int del;
5888 	int rc;
5889 };
5890 
5891 static u_int
5892 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
5893 {
5894 	struct mcaddr_ctx *ctx = arg;
5895 	struct vi_info *vi = ctx->ifp->if_softc;
5896 	struct port_info *pi = vi->pi;
5897 	struct adapter *sc = pi->adapter;
5898 
5899 	if (ctx->rc < 0)
5900 		return (0);
5901 
5902 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
5903 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
5904 	ctx->i++;
5905 
5906 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
5907 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
5908 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
5909 		if (ctx->rc < 0) {
5910 			int j;
5911 
5912 			for (j = 0; j < ctx->i; j++) {
5913 				if_printf(ctx->ifp,
5914 				    "failed to add mc address"
5915 				    " %02x:%02x:%02x:"
5916 				    "%02x:%02x:%02x rc=%d\n",
5917 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
5918 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
5919 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
5920 				    -ctx->rc);
5921 			}
5922 			return (0);
5923 		}
5924 		ctx->del = 0;
5925 		ctx->i = 0;
5926 	}
5927 
5928 	return (1);
5929 }
5930 
5931 /*
5932  * Program the port's XGMAC based on parameters in ifnet.  The caller also
5933  * indicates which parameters should be programmed (the rest are left alone).
5934  */
5935 int
5936 update_mac_settings(struct ifnet *ifp, int flags)
5937 {
5938 	int rc = 0;
5939 	struct vi_info *vi = ifp->if_softc;
5940 	struct port_info *pi = vi->pi;
5941 	struct adapter *sc = pi->adapter;
5942 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
5943 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
5944 
5945 	ASSERT_SYNCHRONIZED_OP(sc);
5946 	KASSERT(flags, ("%s: not told what to update.", __func__));
5947 
5948 	if (flags & XGMAC_MTU)
5949 		mtu = ifp->if_mtu;
5950 
5951 	if (flags & XGMAC_PROMISC)
5952 		promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
5953 
5954 	if (flags & XGMAC_ALLMULTI)
5955 		allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
5956 
5957 	if (flags & XGMAC_VLANEX)
5958 		vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
5959 
5960 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
5961 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
5962 		    allmulti, 1, vlanex, false);
5963 		if (rc) {
5964 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
5965 			    rc);
5966 			return (rc);
5967 		}
5968 	}
5969 
5970 	if (flags & XGMAC_UCADDR) {
5971 		uint8_t ucaddr[ETHER_ADDR_LEN];
5972 
5973 		bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
5974 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
5975 		    ucaddr, true, &vi->smt_idx);
5976 		if (rc < 0) {
5977 			rc = -rc;
5978 			if_printf(ifp, "change_mac failed: %d\n", rc);
5979 			return (rc);
5980 		} else {
5981 			vi->xact_addr_filt = rc;
5982 			rc = 0;
5983 		}
5984 	}
5985 
5986 	if (flags & XGMAC_MCADDRS) {
5987 		struct epoch_tracker et;
5988 		struct mcaddr_ctx ctx;
5989 		int j;
5990 
5991 		ctx.ifp = ifp;
5992 		ctx.hash = 0;
5993 		ctx.i = 0;
5994 		ctx.del = 1;
5995 		ctx.rc = 0;
5996 		/*
5997 		 * Unlike other drivers, we accumulate list of pointers into
5998 		 * interface address lists and we need to keep it safe even
5999 		 * after if_foreach_llmaddr() returns, thus we must enter the
6000 		 * network epoch.
6001 		 */
6002 		NET_EPOCH_ENTER(et);
6003 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6004 		if (ctx.rc < 0) {
6005 			NET_EPOCH_EXIT(et);
6006 			rc = -ctx.rc;
6007 			return (rc);
6008 		}
6009 		if (ctx.i > 0) {
6010 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6011 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6012 			NET_EPOCH_EXIT(et);
6013 			if (rc < 0) {
6014 				rc = -rc;
6015 				for (j = 0; j < ctx.i; j++) {
6016 					if_printf(ifp,
6017 					    "failed to add mcast address"
6018 					    " %02x:%02x:%02x:"
6019 					    "%02x:%02x:%02x rc=%d\n",
6020 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6021 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6022 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6023 					    rc);
6024 				}
6025 				return (rc);
6026 			}
6027 			ctx.del = 0;
6028 		} else
6029 			NET_EPOCH_EXIT(et);
6030 
6031 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6032 		if (rc != 0)
6033 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6034 			    rc);
6035 		if (ctx.del == 0) {
6036 			/* We clobbered the VXLAN entry if there was one. */
6037 			pi->vxlan_tcam_entry = false;
6038 		}
6039 	}
6040 
6041 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6042 	    pi->vxlan_tcam_entry == false) {
6043 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6044 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6045 		    true);
6046 		if (rc < 0) {
6047 			rc = -rc;
6048 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6049 			    rc);
6050 		} else {
6051 			MPASS(rc == sc->rawf_base + pi->port_id);
6052 			rc = 0;
6053 			pi->vxlan_tcam_entry = true;
6054 		}
6055 	}
6056 
6057 	return (rc);
6058 }
6059 
6060 /*
6061  * {begin|end}_synchronized_op must be called from the same thread.
6062  */
6063 int
6064 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6065     char *wmesg)
6066 {
6067 	int rc, pri;
6068 
6069 #ifdef WITNESS
6070 	/* the caller thinks it's ok to sleep, but is it really? */
6071 	if (flags & SLEEP_OK)
6072 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6073 		    "begin_synchronized_op");
6074 #endif
6075 
6076 	if (INTR_OK)
6077 		pri = PCATCH;
6078 	else
6079 		pri = 0;
6080 
6081 	ADAPTER_LOCK(sc);
6082 	for (;;) {
6083 
6084 		if (vi && IS_DOOMED(vi)) {
6085 			rc = ENXIO;
6086 			goto done;
6087 		}
6088 
6089 		if (!IS_BUSY(sc)) {
6090 			rc = 0;
6091 			break;
6092 		}
6093 
6094 		if (!(flags & SLEEP_OK)) {
6095 			rc = EBUSY;
6096 			goto done;
6097 		}
6098 
6099 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6100 			rc = EINTR;
6101 			goto done;
6102 		}
6103 	}
6104 
6105 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6106 	SET_BUSY(sc);
6107 #ifdef INVARIANTS
6108 	sc->last_op = wmesg;
6109 	sc->last_op_thr = curthread;
6110 	sc->last_op_flags = flags;
6111 #endif
6112 
6113 done:
6114 	if (!(flags & HOLD_LOCK) || rc)
6115 		ADAPTER_UNLOCK(sc);
6116 
6117 	return (rc);
6118 }
6119 
6120 /*
6121  * Tell if_ioctl and if_init that the VI is going away.  This is
6122  * special variant of begin_synchronized_op and must be paired with a
6123  * call to end_synchronized_op.
6124  */
6125 void
6126 doom_vi(struct adapter *sc, struct vi_info *vi)
6127 {
6128 
6129 	ADAPTER_LOCK(sc);
6130 	SET_DOOMED(vi);
6131 	wakeup(&sc->flags);
6132 	while (IS_BUSY(sc))
6133 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6134 	SET_BUSY(sc);
6135 #ifdef INVARIANTS
6136 	sc->last_op = "t4detach";
6137 	sc->last_op_thr = curthread;
6138 	sc->last_op_flags = 0;
6139 #endif
6140 	ADAPTER_UNLOCK(sc);
6141 }
6142 
6143 /*
6144  * {begin|end}_synchronized_op must be called from the same thread.
6145  */
6146 void
6147 end_synchronized_op(struct adapter *sc, int flags)
6148 {
6149 
6150 	if (flags & LOCK_HELD)
6151 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6152 	else
6153 		ADAPTER_LOCK(sc);
6154 
6155 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6156 	CLR_BUSY(sc);
6157 	wakeup(&sc->flags);
6158 	ADAPTER_UNLOCK(sc);
6159 }
6160 
6161 static int
6162 cxgbe_init_synchronized(struct vi_info *vi)
6163 {
6164 	struct port_info *pi = vi->pi;
6165 	struct adapter *sc = pi->adapter;
6166 	struct ifnet *ifp = vi->ifp;
6167 	int rc = 0, i;
6168 	struct sge_txq *txq;
6169 
6170 	ASSERT_SYNCHRONIZED_OP(sc);
6171 
6172 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
6173 		return (0);	/* already running */
6174 
6175 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6176 		return (rc);	/* error message displayed already */
6177 
6178 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6179 		return (rc); /* error message displayed already */
6180 
6181 	rc = update_mac_settings(ifp, XGMAC_ALL);
6182 	if (rc)
6183 		goto done;	/* error message displayed already */
6184 
6185 	PORT_LOCK(pi);
6186 	if (pi->up_vis == 0) {
6187 		t4_update_port_info(pi);
6188 		fixup_link_config(pi);
6189 		build_medialist(pi);
6190 		apply_link_config(pi);
6191 	}
6192 
6193 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6194 	if (rc != 0) {
6195 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6196 		PORT_UNLOCK(pi);
6197 		goto done;
6198 	}
6199 
6200 	/*
6201 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6202 	 * if this changes.
6203 	 */
6204 
6205 	for_each_txq(vi, i, txq) {
6206 		TXQ_LOCK(txq);
6207 		txq->eq.flags |= EQ_ENABLED;
6208 		TXQ_UNLOCK(txq);
6209 	}
6210 
6211 	/*
6212 	 * The first iq of the first port to come up is used for tracing.
6213 	 */
6214 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6215 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6216 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6217 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6218 		    V_QUEUENUMBER(sc->traceq));
6219 		pi->flags |= HAS_TRACEQ;
6220 	}
6221 
6222 	/* all ok */
6223 	pi->up_vis++;
6224 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
6225 	if (pi->link_cfg.link_ok)
6226 		t4_os_link_changed(pi);
6227 	PORT_UNLOCK(pi);
6228 
6229 	mtx_lock(&vi->tick_mtx);
6230 	if (ifp->if_get_counter == vi_get_counter)
6231 		callout_reset(&vi->tick, hz, vi_tick, vi);
6232 	else
6233 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6234 	mtx_unlock(&vi->tick_mtx);
6235 done:
6236 	if (rc != 0)
6237 		cxgbe_uninit_synchronized(vi);
6238 
6239 	return (rc);
6240 }
6241 
6242 /*
6243  * Idempotent.
6244  */
6245 static int
6246 cxgbe_uninit_synchronized(struct vi_info *vi)
6247 {
6248 	struct port_info *pi = vi->pi;
6249 	struct adapter *sc = pi->adapter;
6250 	struct ifnet *ifp = vi->ifp;
6251 	int rc, i;
6252 	struct sge_txq *txq;
6253 
6254 	ASSERT_SYNCHRONIZED_OP(sc);
6255 
6256 	if (!(vi->flags & VI_INIT_DONE)) {
6257 		if (__predict_false(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6258 			KASSERT(0, ("uninited VI is running"));
6259 			if_printf(ifp, "uninited VI with running ifnet.  "
6260 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6261 			    "if_drv_flags 0x%08x\n", vi->flags, ifp->if_flags,
6262 			    ifp->if_drv_flags);
6263 		}
6264 		return (0);
6265 	}
6266 
6267 	/*
6268 	 * Disable the VI so that all its data in either direction is discarded
6269 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6270 	 * tick) intact as the TP can deliver negative advice or data that it's
6271 	 * holding in its RAM (for an offloaded connection) even after the VI is
6272 	 * disabled.
6273 	 */
6274 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6275 	if (rc) {
6276 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6277 		return (rc);
6278 	}
6279 
6280 	for_each_txq(vi, i, txq) {
6281 		TXQ_LOCK(txq);
6282 		txq->eq.flags &= ~EQ_ENABLED;
6283 		TXQ_UNLOCK(txq);
6284 	}
6285 
6286 	mtx_lock(&vi->tick_mtx);
6287 	callout_stop(&vi->tick);
6288 	mtx_unlock(&vi->tick_mtx);
6289 
6290 	PORT_LOCK(pi);
6291 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6292 		PORT_UNLOCK(pi);
6293 		return (0);
6294 	}
6295 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
6296 	pi->up_vis--;
6297 	if (pi->up_vis > 0) {
6298 		PORT_UNLOCK(pi);
6299 		return (0);
6300 	}
6301 
6302 	pi->link_cfg.link_ok = false;
6303 	pi->link_cfg.speed = 0;
6304 	pi->link_cfg.link_down_rc = 255;
6305 	t4_os_link_changed(pi);
6306 	PORT_UNLOCK(pi);
6307 
6308 	return (0);
6309 }
6310 
6311 /*
6312  * It is ok for this function to fail midway and return right away.  t4_detach
6313  * will walk the entire sc->irq list and clean up whatever is valid.
6314  */
6315 int
6316 t4_setup_intr_handlers(struct adapter *sc)
6317 {
6318 	int rc, rid, p, q, v;
6319 	char s[8];
6320 	struct irq *irq;
6321 	struct port_info *pi;
6322 	struct vi_info *vi;
6323 	struct sge *sge = &sc->sge;
6324 	struct sge_rxq *rxq;
6325 #ifdef TCP_OFFLOAD
6326 	struct sge_ofld_rxq *ofld_rxq;
6327 #endif
6328 #ifdef DEV_NETMAP
6329 	struct sge_nm_rxq *nm_rxq;
6330 #endif
6331 #ifdef RSS
6332 	int nbuckets = rss_getnumbuckets();
6333 #endif
6334 
6335 	/*
6336 	 * Setup interrupts.
6337 	 */
6338 	irq = &sc->irq[0];
6339 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6340 	if (forwarding_intr_to_fwq(sc))
6341 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6342 
6343 	/* Multiple interrupts. */
6344 	if (sc->flags & IS_VF)
6345 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6346 		    ("%s: too few intr.", __func__));
6347 	else
6348 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6349 		    ("%s: too few intr.", __func__));
6350 
6351 	/* The first one is always error intr on PFs */
6352 	if (!(sc->flags & IS_VF)) {
6353 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6354 		if (rc != 0)
6355 			return (rc);
6356 		irq++;
6357 		rid++;
6358 	}
6359 
6360 	/* The second one is always the firmware event queue (first on VFs) */
6361 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6362 	if (rc != 0)
6363 		return (rc);
6364 	irq++;
6365 	rid++;
6366 
6367 	for_each_port(sc, p) {
6368 		pi = sc->port[p];
6369 		for_each_vi(pi, v, vi) {
6370 			vi->first_intr = rid - 1;
6371 
6372 			if (vi->nnmrxq > 0) {
6373 				int n = max(vi->nrxq, vi->nnmrxq);
6374 
6375 				rxq = &sge->rxq[vi->first_rxq];
6376 #ifdef DEV_NETMAP
6377 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6378 #endif
6379 				for (q = 0; q < n; q++) {
6380 					snprintf(s, sizeof(s), "%x%c%x", p,
6381 					    'a' + v, q);
6382 					if (q < vi->nrxq)
6383 						irq->rxq = rxq++;
6384 #ifdef DEV_NETMAP
6385 					if (q < vi->nnmrxq)
6386 						irq->nm_rxq = nm_rxq++;
6387 
6388 					if (irq->nm_rxq != NULL &&
6389 					    irq->rxq == NULL) {
6390 						/* Netmap rx only */
6391 						rc = t4_alloc_irq(sc, irq, rid,
6392 						    t4_nm_intr, irq->nm_rxq, s);
6393 					}
6394 					if (irq->nm_rxq != NULL &&
6395 					    irq->rxq != NULL) {
6396 						/* NIC and Netmap rx */
6397 						rc = t4_alloc_irq(sc, irq, rid,
6398 						    t4_vi_intr, irq, s);
6399 					}
6400 #endif
6401 					if (irq->rxq != NULL &&
6402 					    irq->nm_rxq == NULL) {
6403 						/* NIC rx only */
6404 						rc = t4_alloc_irq(sc, irq, rid,
6405 						    t4_intr, irq->rxq, s);
6406 					}
6407 					if (rc != 0)
6408 						return (rc);
6409 #ifdef RSS
6410 					if (q < vi->nrxq) {
6411 						bus_bind_intr(sc->dev, irq->res,
6412 						    rss_getcpu(q % nbuckets));
6413 					}
6414 #endif
6415 					irq++;
6416 					rid++;
6417 					vi->nintr++;
6418 				}
6419 			} else {
6420 				for_each_rxq(vi, q, rxq) {
6421 					snprintf(s, sizeof(s), "%x%c%x", p,
6422 					    'a' + v, q);
6423 					rc = t4_alloc_irq(sc, irq, rid,
6424 					    t4_intr, rxq, s);
6425 					if (rc != 0)
6426 						return (rc);
6427 #ifdef RSS
6428 					bus_bind_intr(sc->dev, irq->res,
6429 					    rss_getcpu(q % nbuckets));
6430 #endif
6431 					irq++;
6432 					rid++;
6433 					vi->nintr++;
6434 				}
6435 			}
6436 #ifdef TCP_OFFLOAD
6437 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6438 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6439 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6440 				    ofld_rxq, s);
6441 				if (rc != 0)
6442 					return (rc);
6443 				irq++;
6444 				rid++;
6445 				vi->nintr++;
6446 			}
6447 #endif
6448 		}
6449 	}
6450 	MPASS(irq == &sc->irq[sc->intr_count]);
6451 
6452 	return (0);
6453 }
6454 
6455 static void
6456 write_global_rss_key(struct adapter *sc)
6457 {
6458 #ifdef RSS
6459 	int i;
6460 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6461 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6462 
6463 	CTASSERT(RSS_KEYSIZE == 40);
6464 
6465 	rss_getkey((void *)&raw_rss_key[0]);
6466 	for (i = 0; i < nitems(rss_key); i++) {
6467 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6468 	}
6469 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6470 #endif
6471 }
6472 
6473 /*
6474  * Idempotent.
6475  */
6476 static int
6477 adapter_full_init(struct adapter *sc)
6478 {
6479 	int rc, i;
6480 
6481 	ASSERT_SYNCHRONIZED_OP(sc);
6482 
6483 	if (!(sc->flags & ADAP_SYSCTL_CTX)) {
6484 		sysctl_ctx_init(&sc->ctx);
6485 		sc->flags |= ADAP_SYSCTL_CTX;
6486 	}
6487 
6488 	/*
6489 	 * queues that belong to the adapter (not any particular port).
6490 	 */
6491 	rc = t4_setup_adapter_queues(sc);
6492 	if (rc != 0)
6493 		return (rc);
6494 
6495 	for (i = 0; i < nitems(sc->tq); i++) {
6496 		if (sc->tq[i] != NULL)
6497 			continue;
6498 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6499 		    taskqueue_thread_enqueue, &sc->tq[i]);
6500 		if (sc->tq[i] == NULL) {
6501 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6502 			return (ENOMEM);
6503 		}
6504 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6505 		    device_get_nameunit(sc->dev), i);
6506 	}
6507 
6508 	if (!(sc->flags & IS_VF)) {
6509 		write_global_rss_key(sc);
6510 		t4_intr_enable(sc);
6511 	}
6512 #ifdef KERN_TLS
6513 	if (is_ktls(sc))
6514 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
6515 		    C_HARDCLOCK);
6516 #endif
6517 	return (0);
6518 }
6519 
6520 int
6521 adapter_init(struct adapter *sc)
6522 {
6523 	int rc;
6524 
6525 	ASSERT_SYNCHRONIZED_OP(sc);
6526 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6527 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6528 	    ("%s: FULL_INIT_DONE already", __func__));
6529 
6530 	rc = adapter_full_init(sc);
6531 	if (rc != 0)
6532 		adapter_full_uninit(sc);
6533 	else
6534 		sc->flags |= FULL_INIT_DONE;
6535 
6536 	return (rc);
6537 }
6538 
6539 /*
6540  * Idempotent.
6541  */
6542 static void
6543 adapter_full_uninit(struct adapter *sc)
6544 {
6545 	int i;
6546 
6547 	/* Do this before freeing the adapter queues. */
6548 	if (sc->flags & ADAP_SYSCTL_CTX) {
6549 		sysctl_ctx_free(&sc->ctx);
6550 		sc->flags &= ~ADAP_SYSCTL_CTX;
6551 	}
6552 
6553 	t4_teardown_adapter_queues(sc);
6554 
6555 	for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
6556 		taskqueue_free(sc->tq[i]);
6557 		sc->tq[i] = NULL;
6558 	}
6559 
6560 	sc->flags &= ~FULL_INIT_DONE;
6561 }
6562 
6563 #ifdef RSS
6564 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6565     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6566     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6567     RSS_HASHTYPE_RSS_UDP_IPV6)
6568 
6569 /* Translates kernel hash types to hardware. */
6570 static int
6571 hashconfig_to_hashen(int hashconfig)
6572 {
6573 	int hashen = 0;
6574 
6575 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6576 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6577 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6578 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6579 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6580 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6581 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6582 	}
6583 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6584 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6585 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6586 	}
6587 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6588 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6589 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6590 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6591 
6592 	return (hashen);
6593 }
6594 
6595 /* Translates hardware hash types to kernel. */
6596 static int
6597 hashen_to_hashconfig(int hashen)
6598 {
6599 	int hashconfig = 0;
6600 
6601 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6602 		/*
6603 		 * If UDP hashing was enabled it must have been enabled for
6604 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6605 		 * enabling any 4-tuple hash is nonsense configuration.
6606 		 */
6607 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6608 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6609 
6610 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6611 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6612 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6613 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6614 	}
6615 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6616 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6617 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6618 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6619 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6620 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6621 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6622 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6623 
6624 	return (hashconfig);
6625 }
6626 #endif
6627 
6628 /*
6629  * Idempotent.
6630  */
6631 static int
6632 vi_full_init(struct vi_info *vi)
6633 {
6634 	struct adapter *sc = vi->adapter;
6635 	struct sge_rxq *rxq;
6636 	int rc, i, j;
6637 #ifdef RSS
6638 	int nbuckets = rss_getnumbuckets();
6639 	int hashconfig = rss_gethashconfig();
6640 	int extra;
6641 #endif
6642 
6643 	ASSERT_SYNCHRONIZED_OP(sc);
6644 
6645 	if (!(vi->flags & VI_SYSCTL_CTX)) {
6646 		sysctl_ctx_init(&vi->ctx);
6647 		vi->flags |= VI_SYSCTL_CTX;
6648 	}
6649 
6650 	/*
6651 	 * Allocate tx/rx/fl queues for this VI.
6652 	 */
6653 	rc = t4_setup_vi_queues(vi);
6654 	if (rc != 0)
6655 		return (rc);
6656 
6657 	/*
6658 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6659 	 */
6660 	if (vi->nrxq > vi->rss_size) {
6661 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6662 		    "some queues will never receive traffic.\n", vi->nrxq,
6663 		    vi->rss_size);
6664 	} else if (vi->rss_size % vi->nrxq) {
6665 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6666 		    "expect uneven traffic distribution.\n", vi->nrxq,
6667 		    vi->rss_size);
6668 	}
6669 #ifdef RSS
6670 	if (vi->nrxq != nbuckets) {
6671 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6672 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6673 	}
6674 #endif
6675 	if (vi->rss == NULL)
6676 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6677 		    M_ZERO | M_WAITOK);
6678 	for (i = 0; i < vi->rss_size;) {
6679 #ifdef RSS
6680 		j = rss_get_indirection_to_bucket(i);
6681 		j %= vi->nrxq;
6682 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6683 		vi->rss[i++] = rxq->iq.abs_id;
6684 #else
6685 		for_each_rxq(vi, j, rxq) {
6686 			vi->rss[i++] = rxq->iq.abs_id;
6687 			if (i == vi->rss_size)
6688 				break;
6689 		}
6690 #endif
6691 	}
6692 
6693 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6694 	    vi->rss, vi->rss_size);
6695 	if (rc != 0) {
6696 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6697 		return (rc);
6698 	}
6699 
6700 #ifdef RSS
6701 	vi->hashen = hashconfig_to_hashen(hashconfig);
6702 
6703 	/*
6704 	 * We may have had to enable some hashes even though the global config
6705 	 * wants them disabled.  This is a potential problem that must be
6706 	 * reported to the user.
6707 	 */
6708 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6709 
6710 	/*
6711 	 * If we consider only the supported hash types, then the enabled hashes
6712 	 * are a superset of the requested hashes.  In other words, there cannot
6713 	 * be any supported hash that was requested but not enabled, but there
6714 	 * can be hashes that were not requested but had to be enabled.
6715 	 */
6716 	extra &= SUPPORTED_RSS_HASHTYPES;
6717 	MPASS((extra & hashconfig) == 0);
6718 
6719 	if (extra) {
6720 		CH_ALERT(vi,
6721 		    "global RSS config (0x%x) cannot be accommodated.\n",
6722 		    hashconfig);
6723 	}
6724 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6725 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6726 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6727 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6728 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6729 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6730 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6731 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6732 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6733 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6734 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6735 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6736 #else
6737 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6738 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6739 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6740 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6741 #endif
6742 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6743 	    0, 0);
6744 	if (rc != 0) {
6745 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6746 		return (rc);
6747 	}
6748 
6749 	return (0);
6750 }
6751 
6752 int
6753 vi_init(struct vi_info *vi)
6754 {
6755 	int rc;
6756 
6757 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6758 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6759 	    ("%s: VI_INIT_DONE already", __func__));
6760 
6761 	rc = vi_full_init(vi);
6762 	if (rc != 0)
6763 		vi_full_uninit(vi);
6764 	else
6765 		vi->flags |= VI_INIT_DONE;
6766 
6767 	return (rc);
6768 }
6769 
6770 /*
6771  * Idempotent.
6772  */
6773 static void
6774 vi_full_uninit(struct vi_info *vi)
6775 {
6776 
6777 	if (vi->flags & VI_INIT_DONE) {
6778 		quiesce_vi(vi);
6779 		free(vi->rss, M_CXGBE);
6780 		free(vi->nm_rss, M_CXGBE);
6781 	}
6782 
6783 	/* Do this before freeing the VI queues. */
6784 	if (vi->flags & VI_SYSCTL_CTX) {
6785 		sysctl_ctx_free(&vi->ctx);
6786 		vi->flags &= ~VI_SYSCTL_CTX;
6787 	}
6788 
6789 	t4_teardown_vi_queues(vi);
6790 	vi->flags &= ~VI_INIT_DONE;
6791 }
6792 
6793 static void
6794 quiesce_txq(struct sge_txq *txq)
6795 {
6796 	struct sge_eq *eq = &txq->eq;
6797 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6798 
6799 	MPASS(eq->flags & EQ_SW_ALLOCATED);
6800 	MPASS(!(eq->flags & EQ_ENABLED));
6801 
6802 	/* Wait for the mp_ring to empty. */
6803 	while (!mp_ring_is_idle(txq->r)) {
6804 		mp_ring_check_drainage(txq->r, 4096);
6805 		pause("rquiesce", 1);
6806 	}
6807 	MPASS(txq->txp.npkt == 0);
6808 
6809 	if (eq->flags & EQ_HW_ALLOCATED) {
6810 		/*
6811 		 * Hardware is alive and working normally.  Wait for it to
6812 		 * finish and then wait for the driver to catch up and reclaim
6813 		 * all descriptors.
6814 		 */
6815 		while (spg->cidx != htobe16(eq->pidx))
6816 			pause("equiesce", 1);
6817 		while (eq->cidx != eq->pidx)
6818 			pause("dquiesce", 1);
6819 	} else {
6820 		/*
6821 		 * Hardware is unavailable.  Discard all pending tx and reclaim
6822 		 * descriptors directly.
6823 		 */
6824 		TXQ_LOCK(txq);
6825 		while (eq->cidx != eq->pidx) {
6826 			struct mbuf *m, *nextpkt;
6827 			struct tx_sdesc *txsd;
6828 
6829 			txsd = &txq->sdesc[eq->cidx];
6830 			for (m = txsd->m; m != NULL; m = nextpkt) {
6831 				nextpkt = m->m_nextpkt;
6832 				m->m_nextpkt = NULL;
6833 				m_freem(m);
6834 			}
6835 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
6836 		}
6837 		spg->pidx = spg->cidx = htobe16(eq->cidx);
6838 		TXQ_UNLOCK(txq);
6839 	}
6840 }
6841 
6842 static void
6843 quiesce_wrq(struct sge_wrq *wrq)
6844 {
6845 
6846 	/* XXXTX */
6847 }
6848 
6849 static void
6850 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
6851 {
6852 	/* Synchronize with the interrupt handler */
6853 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
6854 		pause("iqfree", 1);
6855 
6856 	if (fl != NULL) {
6857 		MPASS(iq->flags & IQ_HAS_FL);
6858 
6859 		mtx_lock(&sc->sfl_lock);
6860 		FL_LOCK(fl);
6861 		fl->flags |= FL_DOOMED;
6862 		FL_UNLOCK(fl);
6863 		callout_stop(&sc->sfl_callout);
6864 		mtx_unlock(&sc->sfl_lock);
6865 
6866 		KASSERT((fl->flags & FL_STARVING) == 0,
6867 		    ("%s: still starving", __func__));
6868 
6869 		/* Release all buffers if hardware is no longer available. */
6870 		if (!(iq->flags & IQ_HW_ALLOCATED))
6871 			free_fl_buffers(sc, fl);
6872 	}
6873 }
6874 
6875 /*
6876  * Wait for all activity on all the queues of the VI to complete.  It is assumed
6877  * that no new work is being enqueued by the hardware or the driver.  That part
6878  * should be arranged before calling this function.
6879  */
6880 static void
6881 quiesce_vi(struct vi_info *vi)
6882 {
6883 	int i;
6884 	struct adapter *sc = vi->adapter;
6885 	struct sge_rxq *rxq;
6886 	struct sge_txq *txq;
6887 #ifdef TCP_OFFLOAD
6888 	struct sge_ofld_rxq *ofld_rxq;
6889 #endif
6890 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6891 	struct sge_ofld_txq *ofld_txq;
6892 #endif
6893 
6894 	if (!(vi->flags & VI_INIT_DONE))
6895 		return;
6896 
6897 	for_each_txq(vi, i, txq) {
6898 		quiesce_txq(txq);
6899 	}
6900 
6901 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6902 	for_each_ofld_txq(vi, i, ofld_txq) {
6903 		quiesce_wrq(&ofld_txq->wrq);
6904 	}
6905 #endif
6906 
6907 	for_each_rxq(vi, i, rxq) {
6908 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
6909 	}
6910 
6911 #ifdef TCP_OFFLOAD
6912 	for_each_ofld_rxq(vi, i, ofld_rxq) {
6913 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
6914 	}
6915 #endif
6916 }
6917 
6918 static int
6919 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
6920     driver_intr_t *handler, void *arg, char *name)
6921 {
6922 	int rc;
6923 
6924 	irq->rid = rid;
6925 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
6926 	    RF_SHAREABLE | RF_ACTIVE);
6927 	if (irq->res == NULL) {
6928 		device_printf(sc->dev,
6929 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
6930 		return (ENOMEM);
6931 	}
6932 
6933 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
6934 	    NULL, handler, arg, &irq->tag);
6935 	if (rc != 0) {
6936 		device_printf(sc->dev,
6937 		    "failed to setup interrupt for rid %d, name %s: %d\n",
6938 		    rid, name, rc);
6939 	} else if (name)
6940 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
6941 
6942 	return (rc);
6943 }
6944 
6945 static int
6946 t4_free_irq(struct adapter *sc, struct irq *irq)
6947 {
6948 	if (irq->tag)
6949 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
6950 	if (irq->res)
6951 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
6952 
6953 	bzero(irq, sizeof(*irq));
6954 
6955 	return (0);
6956 }
6957 
6958 static void
6959 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
6960 {
6961 
6962 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
6963 	t4_get_regs(sc, buf, regs->len);
6964 }
6965 
6966 #define	A_PL_INDIR_CMD	0x1f8
6967 
6968 #define	S_PL_AUTOINC	31
6969 #define	M_PL_AUTOINC	0x1U
6970 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
6971 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
6972 
6973 #define	S_PL_VFID	20
6974 #define	M_PL_VFID	0xffU
6975 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
6976 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
6977 
6978 #define	S_PL_ADDR	0
6979 #define	M_PL_ADDR	0xfffffU
6980 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
6981 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
6982 
6983 #define	A_PL_INDIR_DATA	0x1fc
6984 
6985 static uint64_t
6986 read_vf_stat(struct adapter *sc, u_int vin, int reg)
6987 {
6988 	u32 stats[2];
6989 
6990 	if (sc->flags & IS_VF) {
6991 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
6992 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
6993 	} else {
6994 		mtx_assert(&sc->reg_lock, MA_OWNED);
6995 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
6996 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
6997 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
6998 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
6999 	}
7000 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7001 }
7002 
7003 static void
7004 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7005 {
7006 
7007 #define GET_STAT(name) \
7008 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7009 
7010 	if (!(sc->flags & IS_VF))
7011 		mtx_lock(&sc->reg_lock);
7012 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7013 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7014 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7015 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7016 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7017 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7018 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7019 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7020 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7021 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7022 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7023 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7024 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7025 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7026 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7027 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7028 	if (!(sc->flags & IS_VF))
7029 		mtx_unlock(&sc->reg_lock);
7030 
7031 #undef GET_STAT
7032 }
7033 
7034 static void
7035 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7036 {
7037 	int reg;
7038 
7039 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7040 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7041 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7042 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7043 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7044 }
7045 
7046 static void
7047 vi_refresh_stats(struct vi_info *vi)
7048 {
7049 	struct timeval tv;
7050 	const struct timeval interval = {0, 250000};	/* 250ms */
7051 
7052 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7053 
7054 	if (!(vi->flags & VI_INIT_DONE) || vi->flags & VI_SKIP_STATS)
7055 		return;
7056 
7057 	getmicrotime(&tv);
7058 	timevalsub(&tv, &interval);
7059 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7060 		return;
7061 
7062 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7063 	getmicrotime(&vi->last_refreshed);
7064 }
7065 
7066 static void
7067 cxgbe_refresh_stats(struct vi_info *vi)
7068 {
7069 	u_int i, v, tnl_cong_drops, chan_map;
7070 	struct timeval tv;
7071 	const struct timeval interval = {0, 250000};	/* 250ms */
7072 	struct port_info *pi;
7073 	struct adapter *sc;
7074 
7075 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7076 
7077 	if (vi->flags & VI_SKIP_STATS)
7078 		return;
7079 
7080 	getmicrotime(&tv);
7081 	timevalsub(&tv, &interval);
7082 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7083 		return;
7084 
7085 	pi = vi->pi;
7086 	sc = vi->adapter;
7087 	tnl_cong_drops = 0;
7088 	t4_get_port_stats(sc, pi->tx_chan, &pi->stats);
7089 	chan_map = pi->rx_e_chan_map;
7090 	while (chan_map) {
7091 		i = ffs(chan_map) - 1;
7092 		mtx_lock(&sc->reg_lock);
7093 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7094 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7095 		mtx_unlock(&sc->reg_lock);
7096 		tnl_cong_drops += v;
7097 		chan_map &= ~(1 << i);
7098 	}
7099 	pi->tnl_cong_drops = tnl_cong_drops;
7100 	getmicrotime(&vi->last_refreshed);
7101 }
7102 
7103 static void
7104 cxgbe_tick(void *arg)
7105 {
7106 	struct vi_info *vi = arg;
7107 
7108 	MPASS(IS_MAIN_VI(vi));
7109 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7110 
7111 	cxgbe_refresh_stats(vi);
7112 	callout_schedule(&vi->tick, hz);
7113 }
7114 
7115 static void
7116 vi_tick(void *arg)
7117 {
7118 	struct vi_info *vi = arg;
7119 
7120 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7121 
7122 	vi_refresh_stats(vi);
7123 	callout_schedule(&vi->tick, hz);
7124 }
7125 
7126 /*
7127  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7128  */
7129 static char *caps_decoder[] = {
7130 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7131 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7132 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7133 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7134 	    "\006HASHFILTER\007ETHOFLD",
7135 	"\20\001TOE",					/* 4: TOE */
7136 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7137 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7138 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7139 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7140 	    "\007T10DIF"
7141 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7142 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7143 	    "\004TLS_HW",
7144 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7145 		    "\004PO_INITIATOR\005PO_TARGET",
7146 };
7147 
7148 void
7149 t4_sysctls(struct adapter *sc)
7150 {
7151 	struct sysctl_ctx_list *ctx;
7152 	struct sysctl_oid *oid;
7153 	struct sysctl_oid_list *children, *c0;
7154 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7155 
7156 	ctx = device_get_sysctl_ctx(sc->dev);
7157 
7158 	/*
7159 	 * dev.t4nex.X.
7160 	 */
7161 	oid = device_get_sysctl_tree(sc->dev);
7162 	c0 = children = SYSCTL_CHILDREN(oid);
7163 
7164 	sc->sc_do_rxcopy = 1;
7165 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7166 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7167 
7168 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7169 	    sc->params.nports, "# of ports");
7170 
7171 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7172 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7173 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7174 	    "available doorbells");
7175 
7176 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7177 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7178 
7179 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7180 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7181 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7182 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7183 
7184 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7185 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7186 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7187 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7188 
7189 	t4_sge_sysctls(sc, ctx, children);
7190 
7191 	sc->lro_timeout = 100;
7192 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7193 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7194 
7195 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7196 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7197 
7198 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7199 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7200 
7201 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7202 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7203 
7204 	if (sc->flags & IS_VF)
7205 		return;
7206 
7207 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7208 	    NULL, chip_rev(sc), "chip hardware revision");
7209 
7210 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7211 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7212 
7213 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7214 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7215 
7216 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7217 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7218 
7219 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7220 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7221 
7222 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7223 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7224 
7225 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7226 	    sc->er_version, 0, "expansion ROM version");
7227 
7228 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7229 	    sc->bs_version, 0, "bootstrap firmware version");
7230 
7231 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7232 	    NULL, sc->params.scfg_vers, "serial config version");
7233 
7234 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7235 	    NULL, sc->params.vpd_vers, "VPD version");
7236 
7237 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7238 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7239 
7240 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7241 	    sc->cfcsum, "config file checksum");
7242 
7243 #define SYSCTL_CAP(name, n, text) \
7244 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7245 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7246 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7247 	    "available " text " capabilities")
7248 
7249 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7250 	SYSCTL_CAP(linkcaps, 1, "link");
7251 	SYSCTL_CAP(switchcaps, 2, "switch");
7252 	SYSCTL_CAP(niccaps, 3, "NIC");
7253 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7254 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7255 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7256 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7257 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7258 #undef SYSCTL_CAP
7259 
7260 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7261 	    NULL, sc->tids.nftids, "number of filters");
7262 
7263 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7264 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7265 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7266 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7267 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7268 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7269 
7270 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7271 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7272 	    sysctl_loadavg, "A",
7273 	    "microprocessor load averages (debug firmwares only)");
7274 
7275 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7276 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7277 	    "I", "core Vdd (in mV)");
7278 
7279 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7280 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7281 	    sysctl_cpus, "A", "local CPUs");
7282 
7283 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7284 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7285 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7286 
7287 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7288 	    &sc->swintr, 0, "software triggered interrupts");
7289 
7290 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7291 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7292 	    "1 = reset adapter, 0 = zero reset counter");
7293 
7294 	/*
7295 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7296 	 */
7297 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7298 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7299 	    "logs and miscellaneous information");
7300 	children = SYSCTL_CHILDREN(oid);
7301 
7302 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7303 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7304 	    sysctl_cctrl, "A", "congestion control");
7305 
7306 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7307 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7308 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7309 
7310 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7311 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7312 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7313 
7314 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7315 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7316 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7317 
7318 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7319 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7320 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7321 
7322 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7323 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7324 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7325 
7326 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7327 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7328 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7329 
7330 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7331 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7332 	    sysctl_cim_la, "A", "CIM logic analyzer");
7333 
7334 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7335 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7336 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7337 
7338 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7339 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7340 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7341 
7342 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7343 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7344 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7345 
7346 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7347 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7348 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7349 
7350 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7351 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7352 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7353 
7354 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7355 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7356 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7357 
7358 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7359 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7360 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7361 
7362 	if (chip_id(sc) > CHELSIO_T4) {
7363 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7364 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7365 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7366 		    "CIM OBQ 6 (SGE0-RX)");
7367 
7368 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7369 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7370 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7371 		    "CIM OBQ 7 (SGE1-RX)");
7372 	}
7373 
7374 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7375 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7376 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7377 
7378 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7379 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7380 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7381 
7382 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7383 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7384 	    sysctl_cpl_stats, "A", "CPL statistics");
7385 
7386 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7387 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7388 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7389 
7390 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7391 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7392 	    sysctl_tid_stats, "A", "tid stats");
7393 
7394 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7395 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7396 	    sysctl_devlog, "A", "firmware's device log");
7397 
7398 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7399 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7400 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7401 
7402 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7403 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7404 	    sysctl_hw_sched, "A", "hardware scheduler ");
7405 
7406 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7407 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7408 	    sysctl_l2t, "A", "hardware L2 table");
7409 
7410 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7411 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7412 	    sysctl_smt, "A", "hardware source MAC table");
7413 
7414 #ifdef INET6
7415 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7416 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7417 	    sysctl_clip, "A", "active CLIP table entries");
7418 #endif
7419 
7420 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7421 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7422 	    sysctl_lb_stats, "A", "loopback statistics");
7423 
7424 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7425 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7426 	    sysctl_meminfo, "A", "memory regions");
7427 
7428 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7429 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7430 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7431 	    "A", "MPS TCAM entries");
7432 
7433 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7434 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7435 	    sysctl_path_mtus, "A", "path MTUs");
7436 
7437 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7438 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7439 	    sysctl_pm_stats, "A", "PM statistics");
7440 
7441 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7442 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7443 	    sysctl_rdma_stats, "A", "RDMA statistics");
7444 
7445 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7446 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7447 	    sysctl_tcp_stats, "A", "TCP statistics");
7448 
7449 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7450 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7451 	    sysctl_tids, "A", "TID information");
7452 
7453 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7454 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7455 	    sysctl_tp_err_stats, "A", "TP error statistics");
7456 
7457 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7458 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7459 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7460 
7461 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7462 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7463 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7464 
7465 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7466 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7467 	    sysctl_tp_la, "A", "TP logic analyzer");
7468 
7469 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7470 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7471 	    sysctl_tx_rate, "A", "Tx rate");
7472 
7473 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7474 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7475 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7476 
7477 	if (chip_id(sc) >= CHELSIO_T5) {
7478 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7479 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7480 		    sysctl_wcwr_stats, "A", "write combined work requests");
7481 	}
7482 
7483 #ifdef KERN_TLS
7484 	if (is_ktls(sc)) {
7485 		/*
7486 		 * dev.t4nex.0.tls.
7487 		 */
7488 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7489 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7490 		children = SYSCTL_CHILDREN(oid);
7491 
7492 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7493 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7494 		    "keys in work requests (1) or attempt to store TLS keys "
7495 		    "in card memory.");
7496 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7497 		    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to combine "
7498 		    "TCB field updates with TLS record work requests.");
7499 	}
7500 #endif
7501 
7502 #ifdef TCP_OFFLOAD
7503 	if (is_offload(sc)) {
7504 		int i;
7505 		char s[4];
7506 
7507 		/*
7508 		 * dev.t4nex.X.toe.
7509 		 */
7510 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7511 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7512 		children = SYSCTL_CHILDREN(oid);
7513 
7514 		sc->tt.cong_algorithm = -1;
7515 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7516 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7517 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7518 		    "3 = highspeed)");
7519 
7520 		sc->tt.sndbuf = -1;
7521 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7522 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7523 
7524 		sc->tt.ddp = 0;
7525 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7526 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7527 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7528 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7529 
7530 		sc->tt.rx_coalesce = -1;
7531 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7532 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7533 
7534 		sc->tt.tls = 0;
7535 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7536 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7537 		    "Inline TLS allowed");
7538 
7539 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_ports",
7540 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7541 		    sysctl_tls_rx_ports, "I",
7542 		    "TCP ports that use inline TLS+TOE RX");
7543 
7544 		sc->tt.tls_rx_timeout = t4_toe_tls_rx_timeout;
7545 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_timeout",
7546 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7547 		    sysctl_tls_rx_timeout, "I",
7548 		    "Timeout in seconds to downgrade TLS sockets to plain TOE");
7549 
7550 		sc->tt.tx_align = -1;
7551 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7552 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7553 
7554 		sc->tt.tx_zcopy = 0;
7555 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7556 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7557 		    "Enable zero-copy aio_write(2)");
7558 
7559 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7560 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7561 		    "cop_managed_offloading", CTLFLAG_RW,
7562 		    &sc->tt.cop_managed_offloading, 0,
7563 		    "COP (Connection Offload Policy) controls all TOE offload");
7564 
7565 		sc->tt.autorcvbuf_inc = 16 * 1024;
7566 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7567 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7568 		    "autorcvbuf increment");
7569 
7570 		sc->tt.update_hc_on_pmtu_change = 1;
7571 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7572 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7573 		    &sc->tt.update_hc_on_pmtu_change, 0,
7574 		    "Update hostcache entry if the PMTU changes");
7575 
7576 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7577 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7578 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7579 
7580 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7581 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7582 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7583 
7584 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7585 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7586 		    sysctl_tp_tick, "A", "DACK tick (us)");
7587 
7588 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7589 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7590 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7591 
7592 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7593 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7594 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7595 		    "Minimum retransmit interval (us)");
7596 
7597 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7598 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7599 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7600 		    "Maximum retransmit interval (us)");
7601 
7602 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7603 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7604 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7605 		    "Persist timer min (us)");
7606 
7607 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7608 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7609 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7610 		    "Persist timer max (us)");
7611 
7612 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7613 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7614 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7615 		    "Keepalive idle timer (us)");
7616 
7617 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7618 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7619 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7620 		    "Keepalive interval timer (us)");
7621 
7622 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7623 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7624 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7625 
7626 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7627 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7628 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7629 		    "FINWAIT2 timer (us)");
7630 
7631 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7632 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7633 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7634 		    "Number of SYN retransmissions before abort");
7635 
7636 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7637 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7638 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7639 		    "Number of retransmissions before abort");
7640 
7641 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7642 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7643 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7644 		    "Number of keepalive probes before abort");
7645 
7646 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7647 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7648 		    "TOE retransmit backoffs");
7649 		children = SYSCTL_CHILDREN(oid);
7650 		for (i = 0; i < 16; i++) {
7651 			snprintf(s, sizeof(s), "%u", i);
7652 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7653 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7654 			    i, sysctl_tp_backoff, "IU",
7655 			    "TOE retransmit backoff");
7656 		}
7657 	}
7658 #endif
7659 }
7660 
7661 void
7662 vi_sysctls(struct vi_info *vi)
7663 {
7664 	struct sysctl_ctx_list *ctx;
7665 	struct sysctl_oid *oid;
7666 	struct sysctl_oid_list *children;
7667 
7668 	ctx = device_get_sysctl_ctx(vi->dev);
7669 
7670 	/*
7671 	 * dev.v?(cxgbe|cxl).X.
7672 	 */
7673 	oid = device_get_sysctl_tree(vi->dev);
7674 	children = SYSCTL_CHILDREN(oid);
7675 
7676 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7677 	    vi->viid, "VI identifer");
7678 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7679 	    &vi->nrxq, 0, "# of rx queues");
7680 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7681 	    &vi->ntxq, 0, "# of tx queues");
7682 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7683 	    &vi->first_rxq, 0, "index of first rx queue");
7684 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7685 	    &vi->first_txq, 0, "index of first tx queue");
7686 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7687 	    vi->rss_base, "start of RSS indirection table");
7688 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7689 	    vi->rss_size, "size of RSS indirection table");
7690 
7691 	if (IS_MAIN_VI(vi)) {
7692 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7693 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7694 		    sysctl_noflowq, "IU",
7695 		    "Reserve queue 0 for non-flowid packets");
7696 	}
7697 
7698 	if (vi->adapter->flags & IS_VF) {
7699 		MPASS(vi->flags & TX_USES_VM_WR);
7700 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7701 		    NULL, 1, "use VM work requests for transmit");
7702 	} else {
7703 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7704 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7705 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7706 	}
7707 
7708 #ifdef TCP_OFFLOAD
7709 	if (vi->nofldrxq != 0) {
7710 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7711 		    &vi->nofldrxq, 0,
7712 		    "# of rx queues for offloaded TCP connections");
7713 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7714 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7715 		    "index of first TOE rx queue");
7716 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7717 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7718 		    sysctl_holdoff_tmr_idx_ofld, "I",
7719 		    "holdoff timer index for TOE queues");
7720 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7721 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7722 		    sysctl_holdoff_pktc_idx_ofld, "I",
7723 		    "holdoff packet counter index for TOE queues");
7724 	}
7725 #endif
7726 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7727 	if (vi->nofldtxq != 0) {
7728 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7729 		    &vi->nofldtxq, 0,
7730 		    "# of tx queues for TOE/ETHOFLD");
7731 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7732 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7733 		    "index of first TOE/ETHOFLD tx queue");
7734 	}
7735 #endif
7736 #ifdef DEV_NETMAP
7737 	if (vi->nnmrxq != 0) {
7738 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7739 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7740 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7741 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7742 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7743 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7744 		    "index of first netmap rx queue");
7745 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7746 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7747 		    "index of first netmap tx queue");
7748 	}
7749 #endif
7750 
7751 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7752 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7753 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7754 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7755 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7756 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7757 
7758 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7759 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7760 	    sysctl_qsize_rxq, "I", "rx queue size");
7761 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7762 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7763 	    sysctl_qsize_txq, "I", "tx queue size");
7764 }
7765 
7766 static void
7767 cxgbe_sysctls(struct port_info *pi)
7768 {
7769 	struct sysctl_ctx_list *ctx;
7770 	struct sysctl_oid *oid;
7771 	struct sysctl_oid_list *children, *children2;
7772 	struct adapter *sc = pi->adapter;
7773 	int i;
7774 	char name[16];
7775 	static char *tc_flags = {"\20\1USER\2SYNC\3ASYNC\4ERR"};
7776 
7777 	ctx = device_get_sysctl_ctx(pi->dev);
7778 
7779 	/*
7780 	 * dev.cxgbe.X.
7781 	 */
7782 	oid = device_get_sysctl_tree(pi->dev);
7783 	children = SYSCTL_CHILDREN(oid);
7784 
7785 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7786 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7787 	    sysctl_linkdnrc, "A", "reason why link is down");
7788 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7789 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7790 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7791 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
7792 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7793 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7794 		    sysctl_btphy, "I", "PHY firmware version");
7795 	}
7796 
7797 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7798 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7799 	    sysctl_pause_settings, "A",
7800 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7801 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fec",
7802 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7803 	    sysctl_fec, "A",
7804 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7805 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7806 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7807 	    "FEC recommended by the cable/transceiver");
7808 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7809 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7810 	    sysctl_autoneg, "I",
7811 	    "autonegotiation (-1 = not supported)");
7812 
7813 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7814 	    &pi->link_cfg.pcaps, 0, "port capabilities");
7815 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7816 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
7817 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7818 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7819 
7820 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7821 	    port_top_speed(pi), "max speed (in Gbps)");
7822 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7823 	    pi->mps_bg_map, "MPS buffer group map");
7824 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
7825 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
7826 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_c_chan", CTLFLAG_RD, NULL,
7827 	    pi->rx_c_chan, "TP rx c-channel");
7828 
7829 	if (sc->flags & IS_VF)
7830 		return;
7831 
7832 	/*
7833 	 * dev.(cxgbe|cxl).X.tc.
7834 	 */
7835 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
7836 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7837 	    "Tx scheduler traffic classes (cl_rl)");
7838 	children2 = SYSCTL_CHILDREN(oid);
7839 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
7840 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
7841 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
7842 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
7843 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
7844 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
7845 	for (i = 0; i < sc->chip_params->nsched_cls; i++) {
7846 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
7847 
7848 		snprintf(name, sizeof(name), "%d", i);
7849 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
7850 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
7851 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
7852 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
7853 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
7854 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
7855 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
7856 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
7857 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
7858 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7859 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
7860 		    "traffic class parameters");
7861 	}
7862 
7863 	/*
7864 	 * dev.cxgbe.X.stats.
7865 	 */
7866 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
7867 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
7868 	children = SYSCTL_CHILDREN(oid);
7869 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
7870 	    &pi->tx_parse_error, 0,
7871 	    "# of tx packets with invalid length or # of segments");
7872 
7873 #define T4_REGSTAT(name, stat, desc) \
7874     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
7875         CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
7876 	(is_t4(sc) ? PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L) : \
7877 	T5_PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L)), \
7878         sysctl_handle_t4_reg64, "QU", desc)
7879 
7880 /* We get these from port_stats and they may be stale by up to 1s */
7881 #define T4_PORTSTAT(name, desc) \
7882 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
7883 	    &pi->stats.name, desc)
7884 
7885 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
7886 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
7887 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
7888 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
7889 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
7890 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
7891 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
7892 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
7893 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
7894 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
7895 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
7896 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
7897 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
7898 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
7899 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
7900 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
7901 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
7902 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
7903 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
7904 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
7905 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
7906 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
7907 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
7908 
7909 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
7910 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
7911 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
7912 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
7913 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
7914 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
7915 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
7916 	if (is_t6(sc)) {
7917 		T4_PORTSTAT(rx_fcs_err,
7918 		    "# of frames received with bad FCS since last link up");
7919 	} else {
7920 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
7921 		    "# of frames received with bad FCS");
7922 	}
7923 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
7924 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
7925 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
7926 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
7927 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
7928 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
7929 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
7930 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
7931 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
7932 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
7933 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
7934 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
7935 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
7936 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
7937 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
7938 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
7939 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
7940 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
7941 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
7942 
7943 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
7944 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
7945 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
7946 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
7947 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
7948 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
7949 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
7950 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
7951 
7952 #undef T4_REGSTAT
7953 #undef T4_PORTSTAT
7954 }
7955 
7956 static int
7957 sysctl_int_array(SYSCTL_HANDLER_ARGS)
7958 {
7959 	int rc, *i, space = 0;
7960 	struct sbuf sb;
7961 
7962 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
7963 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
7964 		if (space)
7965 			sbuf_printf(&sb, " ");
7966 		sbuf_printf(&sb, "%d", *i);
7967 		space = 1;
7968 	}
7969 	rc = sbuf_finish(&sb);
7970 	sbuf_delete(&sb);
7971 	return (rc);
7972 }
7973 
7974 static int
7975 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
7976 {
7977 	int rc;
7978 	struct sbuf *sb;
7979 
7980 	rc = sysctl_wire_old_buffer(req, 0);
7981 	if (rc != 0)
7982 		return(rc);
7983 
7984 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7985 	if (sb == NULL)
7986 		return (ENOMEM);
7987 
7988 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
7989 	rc = sbuf_finish(sb);
7990 	sbuf_delete(sb);
7991 
7992 	return (rc);
7993 }
7994 
7995 static int
7996 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
7997 {
7998 	int rc;
7999 	struct sbuf *sb;
8000 
8001 	rc = sysctl_wire_old_buffer(req, 0);
8002 	if (rc != 0)
8003 		return(rc);
8004 
8005 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8006 	if (sb == NULL)
8007 		return (ENOMEM);
8008 
8009 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8010 	rc = sbuf_finish(sb);
8011 	sbuf_delete(sb);
8012 
8013 	return (rc);
8014 }
8015 
8016 static int
8017 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8018 {
8019 	struct port_info *pi = arg1;
8020 	int op = arg2;
8021 	struct adapter *sc = pi->adapter;
8022 	u_int v;
8023 	int rc;
8024 
8025 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8026 	if (rc)
8027 		return (rc);
8028 	if (hw_off_limits(sc))
8029 		rc = ENXIO;
8030 	else {
8031 		/* XXX: magic numbers */
8032 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8033 		    op ? 0x20 : 0xc820, &v);
8034 	}
8035 	end_synchronized_op(sc, 0);
8036 	if (rc)
8037 		return (rc);
8038 	if (op == 0)
8039 		v /= 256;
8040 
8041 	rc = sysctl_handle_int(oidp, &v, 0, req);
8042 	return (rc);
8043 }
8044 
8045 static int
8046 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8047 {
8048 	struct vi_info *vi = arg1;
8049 	int rc, val;
8050 
8051 	val = vi->rsrv_noflowq;
8052 	rc = sysctl_handle_int(oidp, &val, 0, req);
8053 	if (rc != 0 || req->newptr == NULL)
8054 		return (rc);
8055 
8056 	if ((val >= 1) && (vi->ntxq > 1))
8057 		vi->rsrv_noflowq = 1;
8058 	else
8059 		vi->rsrv_noflowq = 0;
8060 
8061 	return (rc);
8062 }
8063 
8064 static int
8065 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8066 {
8067 	struct vi_info *vi = arg1;
8068 	struct adapter *sc = vi->adapter;
8069 	int rc, val, i;
8070 
8071 	MPASS(!(sc->flags & IS_VF));
8072 
8073 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8074 	rc = sysctl_handle_int(oidp, &val, 0, req);
8075 	if (rc != 0 || req->newptr == NULL)
8076 		return (rc);
8077 
8078 	if (val != 0 && val != 1)
8079 		return (EINVAL);
8080 
8081 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8082 	    "t4txvm");
8083 	if (rc)
8084 		return (rc);
8085 	if (hw_off_limits(sc))
8086 		rc = ENXIO;
8087 	else if (vi->ifp->if_drv_flags & IFF_DRV_RUNNING) {
8088 		/*
8089 		 * We don't want parse_pkt to run with one setting (VF or PF)
8090 		 * and then eth_tx to see a different setting but still use
8091 		 * stale information calculated by parse_pkt.
8092 		 */
8093 		rc = EBUSY;
8094 	} else {
8095 		struct port_info *pi = vi->pi;
8096 		struct sge_txq *txq;
8097 		uint32_t ctrl0;
8098 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8099 
8100 		if (val) {
8101 			vi->flags |= TX_USES_VM_WR;
8102 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
8103 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8104 			    V_TXPKT_INTF(pi->tx_chan));
8105 			if (!(sc->flags & IS_VF))
8106 				npkt--;
8107 		} else {
8108 			vi->flags &= ~TX_USES_VM_WR;
8109 			vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
8110 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8111 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8112 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8113 		}
8114 		for_each_txq(vi, i, txq) {
8115 			txq->cpl_ctrl0 = ctrl0;
8116 			txq->txp.max_npkt = npkt;
8117 		}
8118 	}
8119 	end_synchronized_op(sc, LOCK_HELD);
8120 	return (rc);
8121 }
8122 
8123 static int
8124 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8125 {
8126 	struct vi_info *vi = arg1;
8127 	struct adapter *sc = vi->adapter;
8128 	int idx, rc, i;
8129 	struct sge_rxq *rxq;
8130 	uint8_t v;
8131 
8132 	idx = vi->tmr_idx;
8133 
8134 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8135 	if (rc != 0 || req->newptr == NULL)
8136 		return (rc);
8137 
8138 	if (idx < 0 || idx >= SGE_NTIMERS)
8139 		return (EINVAL);
8140 
8141 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8142 	    "t4tmr");
8143 	if (rc)
8144 		return (rc);
8145 
8146 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8147 	for_each_rxq(vi, i, rxq) {
8148 #ifdef atomic_store_rel_8
8149 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8150 #else
8151 		rxq->iq.intr_params = v;
8152 #endif
8153 	}
8154 	vi->tmr_idx = idx;
8155 
8156 	end_synchronized_op(sc, LOCK_HELD);
8157 	return (0);
8158 }
8159 
8160 static int
8161 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8162 {
8163 	struct vi_info *vi = arg1;
8164 	struct adapter *sc = vi->adapter;
8165 	int idx, rc;
8166 
8167 	idx = vi->pktc_idx;
8168 
8169 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8170 	if (rc != 0 || req->newptr == NULL)
8171 		return (rc);
8172 
8173 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8174 		return (EINVAL);
8175 
8176 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8177 	    "t4pktc");
8178 	if (rc)
8179 		return (rc);
8180 
8181 	if (vi->flags & VI_INIT_DONE)
8182 		rc = EBUSY; /* cannot be changed once the queues are created */
8183 	else
8184 		vi->pktc_idx = idx;
8185 
8186 	end_synchronized_op(sc, LOCK_HELD);
8187 	return (rc);
8188 }
8189 
8190 static int
8191 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8192 {
8193 	struct vi_info *vi = arg1;
8194 	struct adapter *sc = vi->adapter;
8195 	int qsize, rc;
8196 
8197 	qsize = vi->qsize_rxq;
8198 
8199 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8200 	if (rc != 0 || req->newptr == NULL)
8201 		return (rc);
8202 
8203 	if (qsize < 128 || (qsize & 7))
8204 		return (EINVAL);
8205 
8206 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8207 	    "t4rxqs");
8208 	if (rc)
8209 		return (rc);
8210 
8211 	if (vi->flags & VI_INIT_DONE)
8212 		rc = EBUSY; /* cannot be changed once the queues are created */
8213 	else
8214 		vi->qsize_rxq = qsize;
8215 
8216 	end_synchronized_op(sc, LOCK_HELD);
8217 	return (rc);
8218 }
8219 
8220 static int
8221 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8222 {
8223 	struct vi_info *vi = arg1;
8224 	struct adapter *sc = vi->adapter;
8225 	int qsize, rc;
8226 
8227 	qsize = vi->qsize_txq;
8228 
8229 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8230 	if (rc != 0 || req->newptr == NULL)
8231 		return (rc);
8232 
8233 	if (qsize < 128 || qsize > 65536)
8234 		return (EINVAL);
8235 
8236 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8237 	    "t4txqs");
8238 	if (rc)
8239 		return (rc);
8240 
8241 	if (vi->flags & VI_INIT_DONE)
8242 		rc = EBUSY; /* cannot be changed once the queues are created */
8243 	else
8244 		vi->qsize_txq = qsize;
8245 
8246 	end_synchronized_op(sc, LOCK_HELD);
8247 	return (rc);
8248 }
8249 
8250 static int
8251 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8252 {
8253 	struct port_info *pi = arg1;
8254 	struct adapter *sc = pi->adapter;
8255 	struct link_config *lc = &pi->link_cfg;
8256 	int rc;
8257 
8258 	if (req->newptr == NULL) {
8259 		struct sbuf *sb;
8260 		static char *bits = "\20\1RX\2TX\3AUTO";
8261 
8262 		rc = sysctl_wire_old_buffer(req, 0);
8263 		if (rc != 0)
8264 			return(rc);
8265 
8266 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8267 		if (sb == NULL)
8268 			return (ENOMEM);
8269 
8270 		if (lc->link_ok) {
8271 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8272 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8273 		} else {
8274 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8275 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8276 		}
8277 		rc = sbuf_finish(sb);
8278 		sbuf_delete(sb);
8279 	} else {
8280 		char s[2];
8281 		int n;
8282 
8283 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8284 		    PAUSE_AUTONEG));
8285 		s[1] = 0;
8286 
8287 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8288 		if (rc != 0)
8289 			return(rc);
8290 
8291 		if (s[1] != 0)
8292 			return (EINVAL);
8293 		if (s[0] < '0' || s[0] > '9')
8294 			return (EINVAL);	/* not a number */
8295 		n = s[0] - '0';
8296 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8297 			return (EINVAL);	/* some other bit is set too */
8298 
8299 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8300 		    "t4PAUSE");
8301 		if (rc)
8302 			return (rc);
8303 		if (!hw_off_limits(sc)) {
8304 			PORT_LOCK(pi);
8305 			lc->requested_fc = n;
8306 			fixup_link_config(pi);
8307 			if (pi->up_vis > 0)
8308 				rc = apply_link_config(pi);
8309 			set_current_media(pi);
8310 			PORT_UNLOCK(pi);
8311 		}
8312 		end_synchronized_op(sc, 0);
8313 	}
8314 
8315 	return (rc);
8316 }
8317 
8318 static int
8319 sysctl_fec(SYSCTL_HANDLER_ARGS)
8320 {
8321 	struct port_info *pi = arg1;
8322 	struct adapter *sc = pi->adapter;
8323 	struct link_config *lc = &pi->link_cfg;
8324 	int rc;
8325 	int8_t old;
8326 
8327 	if (req->newptr == NULL) {
8328 		struct sbuf *sb;
8329 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8330 		    "\5RSVD3\6auto\7module";
8331 
8332 		rc = sysctl_wire_old_buffer(req, 0);
8333 		if (rc != 0)
8334 			return(rc);
8335 
8336 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8337 		if (sb == NULL)
8338 			return (ENOMEM);
8339 
8340 		/*
8341 		 * Display the requested_fec when the link is down -- the actual
8342 		 * FEC makes sense only when the link is up.
8343 		 */
8344 		if (lc->link_ok) {
8345 			sbuf_printf(sb, "%b", (lc->fec & M_FW_PORT_CAP32_FEC) |
8346 			    (lc->requested_fec & (FEC_AUTO | FEC_MODULE)),
8347 			    bits);
8348 		} else {
8349 			sbuf_printf(sb, "%b", lc->requested_fec, bits);
8350 		}
8351 		rc = sbuf_finish(sb);
8352 		sbuf_delete(sb);
8353 	} else {
8354 		char s[8];
8355 		int n;
8356 
8357 		snprintf(s, sizeof(s), "%d",
8358 		    lc->requested_fec == FEC_AUTO ? -1 :
8359 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8360 
8361 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8362 		if (rc != 0)
8363 			return(rc);
8364 
8365 		n = strtol(&s[0], NULL, 0);
8366 		if (n < 0 || n & FEC_AUTO)
8367 			n = FEC_AUTO;
8368 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8369 			return (EINVAL);/* some other bit is set too */
8370 
8371 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8372 		    "t4fec");
8373 		if (rc)
8374 			return (rc);
8375 		PORT_LOCK(pi);
8376 		old = lc->requested_fec;
8377 		if (n == FEC_AUTO)
8378 			lc->requested_fec = FEC_AUTO;
8379 		else if (n == 0 || n == FEC_NONE)
8380 			lc->requested_fec = FEC_NONE;
8381 		else {
8382 			if ((lc->pcaps |
8383 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8384 			    lc->pcaps) {
8385 				rc = ENOTSUP;
8386 				goto done;
8387 			}
8388 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8389 			    FEC_MODULE);
8390 		}
8391 		if (!hw_off_limits(sc)) {
8392 			fixup_link_config(pi);
8393 			if (pi->up_vis > 0) {
8394 				rc = apply_link_config(pi);
8395 				if (rc != 0) {
8396 					lc->requested_fec = old;
8397 					if (rc == FW_EPROTO)
8398 						rc = ENOTSUP;
8399 				}
8400 			}
8401 		}
8402 done:
8403 		PORT_UNLOCK(pi);
8404 		end_synchronized_op(sc, 0);
8405 	}
8406 
8407 	return (rc);
8408 }
8409 
8410 static int
8411 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8412 {
8413 	struct port_info *pi = arg1;
8414 	struct adapter *sc = pi->adapter;
8415 	struct link_config *lc = &pi->link_cfg;
8416 	int rc;
8417 	int8_t fec;
8418 	struct sbuf *sb;
8419 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8420 
8421 	rc = sysctl_wire_old_buffer(req, 0);
8422 	if (rc != 0)
8423 		return (rc);
8424 
8425 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8426 	if (sb == NULL)
8427 		return (ENOMEM);
8428 
8429 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8430 		rc = EBUSY;
8431 		goto done;
8432 	}
8433 	if (hw_off_limits(sc)) {
8434 		rc = ENXIO;
8435 		goto done;
8436 	}
8437 	PORT_LOCK(pi);
8438 	if (pi->up_vis == 0) {
8439 		/*
8440 		 * If all the interfaces are administratively down the firmware
8441 		 * does not report transceiver changes.  Refresh port info here.
8442 		 * This is the only reason we have a synchronized op in this
8443 		 * function.  Just PORT_LOCK would have been enough otherwise.
8444 		 */
8445 		t4_update_port_info(pi);
8446 	}
8447 
8448 	fec = lc->fec_hint;
8449 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8450 	    !fec_supported(lc->pcaps)) {
8451 		sbuf_printf(sb, "n/a");
8452 	} else {
8453 		if (fec == 0)
8454 			fec = FEC_NONE;
8455 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8456 	}
8457 	rc = sbuf_finish(sb);
8458 	PORT_UNLOCK(pi);
8459 done:
8460 	sbuf_delete(sb);
8461 	end_synchronized_op(sc, 0);
8462 
8463 	return (rc);
8464 }
8465 
8466 static int
8467 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8468 {
8469 	struct port_info *pi = arg1;
8470 	struct adapter *sc = pi->adapter;
8471 	struct link_config *lc = &pi->link_cfg;
8472 	int rc, val;
8473 
8474 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8475 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8476 	else
8477 		val = -1;
8478 	rc = sysctl_handle_int(oidp, &val, 0, req);
8479 	if (rc != 0 || req->newptr == NULL)
8480 		return (rc);
8481 	if (val == 0)
8482 		val = AUTONEG_DISABLE;
8483 	else if (val == 1)
8484 		val = AUTONEG_ENABLE;
8485 	else
8486 		val = AUTONEG_AUTO;
8487 
8488 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8489 	    "t4aneg");
8490 	if (rc)
8491 		return (rc);
8492 	PORT_LOCK(pi);
8493 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8494 		rc = ENOTSUP;
8495 		goto done;
8496 	}
8497 	lc->requested_aneg = val;
8498 	if (!hw_off_limits(sc)) {
8499 		fixup_link_config(pi);
8500 		if (pi->up_vis > 0)
8501 			rc = apply_link_config(pi);
8502 		set_current_media(pi);
8503 	}
8504 done:
8505 	PORT_UNLOCK(pi);
8506 	end_synchronized_op(sc, 0);
8507 	return (rc);
8508 }
8509 
8510 static int
8511 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8512 {
8513 	struct adapter *sc = arg1;
8514 	int rc, reg = arg2;
8515 	uint64_t val;
8516 
8517 	mtx_lock(&sc->reg_lock);
8518 	if (hw_off_limits(sc))
8519 		rc = ENXIO;
8520 	else {
8521 		rc = 0;
8522 		val = t4_read_reg64(sc, reg);
8523 	}
8524 	mtx_unlock(&sc->reg_lock);
8525 	if (rc == 0)
8526 		rc = sysctl_handle_64(oidp, &val, 0, req);
8527 	return (rc);
8528 }
8529 
8530 static int
8531 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8532 {
8533 	struct adapter *sc = arg1;
8534 	int rc, t;
8535 	uint32_t param, val;
8536 
8537 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8538 	if (rc)
8539 		return (rc);
8540 	if (hw_off_limits(sc))
8541 		rc = ENXIO;
8542 	else {
8543 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8544 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8545 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8546 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8547 	}
8548 	end_synchronized_op(sc, 0);
8549 	if (rc)
8550 		return (rc);
8551 
8552 	/* unknown is returned as 0 but we display -1 in that case */
8553 	t = val == 0 ? -1 : val;
8554 
8555 	rc = sysctl_handle_int(oidp, &t, 0, req);
8556 	return (rc);
8557 }
8558 
8559 static int
8560 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8561 {
8562 	struct adapter *sc = arg1;
8563 	int rc;
8564 	uint32_t param, val;
8565 
8566 	if (sc->params.core_vdd == 0) {
8567 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8568 		    "t4vdd");
8569 		if (rc)
8570 			return (rc);
8571 		if (hw_off_limits(sc))
8572 			rc = ENXIO;
8573 		else {
8574 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8575 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8576 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8577 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8578 			    &param, &val);
8579 		}
8580 		end_synchronized_op(sc, 0);
8581 		if (rc)
8582 			return (rc);
8583 		sc->params.core_vdd = val;
8584 	}
8585 
8586 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8587 }
8588 
8589 static int
8590 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8591 {
8592 	struct adapter *sc = arg1;
8593 	int rc, v;
8594 	uint32_t param, val;
8595 
8596 	v = sc->sensor_resets;
8597 	rc = sysctl_handle_int(oidp, &v, 0, req);
8598 	if (rc != 0 || req->newptr == NULL || v <= 0)
8599 		return (rc);
8600 
8601 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8602 	    chip_id(sc) < CHELSIO_T5)
8603 		return (ENOTSUP);
8604 
8605 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8606 	if (rc)
8607 		return (rc);
8608 	if (hw_off_limits(sc))
8609 		rc = ENXIO;
8610 	else {
8611 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8612 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8613 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8614 		val = 1;
8615 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8616 	}
8617 	end_synchronized_op(sc, 0);
8618 	if (rc == 0)
8619 		sc->sensor_resets++;
8620 	return (rc);
8621 }
8622 
8623 static int
8624 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8625 {
8626 	struct adapter *sc = arg1;
8627 	struct sbuf *sb;
8628 	int rc;
8629 	uint32_t param, val;
8630 
8631 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8632 	if (rc)
8633 		return (rc);
8634 	if (hw_off_limits(sc))
8635 		rc = ENXIO;
8636 	else {
8637 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8638 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8639 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8640 	}
8641 	end_synchronized_op(sc, 0);
8642 	if (rc)
8643 		return (rc);
8644 
8645 	rc = sysctl_wire_old_buffer(req, 0);
8646 	if (rc != 0)
8647 		return (rc);
8648 
8649 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8650 	if (sb == NULL)
8651 		return (ENOMEM);
8652 
8653 	if (val == 0xffffffff) {
8654 		/* Only debug and custom firmwares report load averages. */
8655 		sbuf_printf(sb, "not available");
8656 	} else {
8657 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8658 		    (val >> 16) & 0xff);
8659 	}
8660 	rc = sbuf_finish(sb);
8661 	sbuf_delete(sb);
8662 
8663 	return (rc);
8664 }
8665 
8666 static int
8667 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8668 {
8669 	struct adapter *sc = arg1;
8670 	struct sbuf *sb;
8671 	int rc, i;
8672 	uint16_t incr[NMTUS][NCCTRL_WIN];
8673 	static const char *dec_fac[] = {
8674 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8675 		"0.9375"
8676 	};
8677 
8678 	rc = sysctl_wire_old_buffer(req, 0);
8679 	if (rc != 0)
8680 		return (rc);
8681 
8682 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8683 	if (sb == NULL)
8684 		return (ENOMEM);
8685 
8686 	mtx_lock(&sc->reg_lock);
8687 	if (hw_off_limits(sc))
8688 		rc = ENXIO;
8689 	else
8690 		t4_read_cong_tbl(sc, incr);
8691 	mtx_unlock(&sc->reg_lock);
8692 	if (rc)
8693 		goto done;
8694 
8695 	for (i = 0; i < NCCTRL_WIN; ++i) {
8696 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8697 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8698 		    incr[5][i], incr[6][i], incr[7][i]);
8699 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8700 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8701 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8702 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8703 	}
8704 
8705 	rc = sbuf_finish(sb);
8706 done:
8707 	sbuf_delete(sb);
8708 	return (rc);
8709 }
8710 
8711 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8712 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8713 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8714 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8715 };
8716 
8717 static int
8718 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8719 {
8720 	struct adapter *sc = arg1;
8721 	struct sbuf *sb;
8722 	int rc, i, n, qid = arg2;
8723 	uint32_t *buf, *p;
8724 	char *qtype;
8725 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8726 
8727 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8728 	    ("%s: bad qid %d\n", __func__, qid));
8729 
8730 	if (qid < CIM_NUM_IBQ) {
8731 		/* inbound queue */
8732 		qtype = "IBQ";
8733 		n = 4 * CIM_IBQ_SIZE;
8734 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8735 		mtx_lock(&sc->reg_lock);
8736 		if (hw_off_limits(sc))
8737 			rc = -ENXIO;
8738 		else
8739 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8740 		mtx_unlock(&sc->reg_lock);
8741 	} else {
8742 		/* outbound queue */
8743 		qtype = "OBQ";
8744 		qid -= CIM_NUM_IBQ;
8745 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8746 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8747 		mtx_lock(&sc->reg_lock);
8748 		if (hw_off_limits(sc))
8749 			rc = -ENXIO;
8750 		else
8751 			rc = t4_read_cim_obq(sc, qid, buf, n);
8752 		mtx_unlock(&sc->reg_lock);
8753 	}
8754 
8755 	if (rc < 0) {
8756 		rc = -rc;
8757 		goto done;
8758 	}
8759 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
8760 
8761 	rc = sysctl_wire_old_buffer(req, 0);
8762 	if (rc != 0)
8763 		goto done;
8764 
8765 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8766 	if (sb == NULL) {
8767 		rc = ENOMEM;
8768 		goto done;
8769 	}
8770 
8771 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8772 	for (i = 0, p = buf; i < n; i += 16, p += 4)
8773 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
8774 		    p[2], p[3]);
8775 
8776 	rc = sbuf_finish(sb);
8777 	sbuf_delete(sb);
8778 done:
8779 	free(buf, M_CXGBE);
8780 	return (rc);
8781 }
8782 
8783 static void
8784 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8785 {
8786 	uint32_t *p;
8787 
8788 	sbuf_printf(sb, "Status   Data      PC%s",
8789 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8790 	    "     LS0Stat  LS0Addr             LS0Data");
8791 
8792 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
8793 		if (cfg & F_UPDBGLACAPTPCONLY) {
8794 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
8795 			    p[6], p[7]);
8796 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
8797 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
8798 			    p[4] & 0xff, p[5] >> 8);
8799 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
8800 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8801 			    p[1] & 0xf, p[2] >> 4);
8802 		} else {
8803 			sbuf_printf(sb,
8804 			    "\n  %02x   %x%07x %x%07x %08x %08x "
8805 			    "%08x%08x%08x%08x",
8806 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8807 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
8808 			    p[6], p[7]);
8809 		}
8810 	}
8811 }
8812 
8813 static void
8814 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8815 {
8816 	uint32_t *p;
8817 
8818 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
8819 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8820 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
8821 
8822 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
8823 		if (cfg & F_UPDBGLACAPTPCONLY) {
8824 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
8825 			    p[3] & 0xff, p[2], p[1], p[0]);
8826 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
8827 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
8828 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
8829 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
8830 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
8831 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
8832 			    p[6] >> 16);
8833 		} else {
8834 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
8835 			    "%08x %08x %08x %08x %08x %08x",
8836 			    (p[9] >> 16) & 0xff,
8837 			    p[9] & 0xffff, p[8] >> 16,
8838 			    p[8] & 0xffff, p[7] >> 16,
8839 			    p[7] & 0xffff, p[6] >> 16,
8840 			    p[2], p[1], p[0], p[5], p[4], p[3]);
8841 		}
8842 	}
8843 }
8844 
8845 static int
8846 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
8847 {
8848 	uint32_t cfg, *buf;
8849 	int rc;
8850 
8851 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
8852 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
8853 	    M_ZERO | flags);
8854 	if (buf == NULL)
8855 		return (ENOMEM);
8856 
8857 	mtx_lock(&sc->reg_lock);
8858 	if (hw_off_limits(sc))
8859 		rc = ENXIO;
8860 	else {
8861 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
8862 		if (rc == 0)
8863 			rc = -t4_cim_read_la(sc, buf, NULL);
8864 	}
8865 	mtx_unlock(&sc->reg_lock);
8866 	if (rc == 0) {
8867 		if (chip_id(sc) < CHELSIO_T6)
8868 			sbuf_cim_la4(sc, sb, buf, cfg);
8869 		else
8870 			sbuf_cim_la6(sc, sb, buf, cfg);
8871 	}
8872 	free(buf, M_CXGBE);
8873 	return (rc);
8874 }
8875 
8876 static int
8877 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
8878 {
8879 	struct adapter *sc = arg1;
8880 	struct sbuf *sb;
8881 	int rc;
8882 
8883 	rc = sysctl_wire_old_buffer(req, 0);
8884 	if (rc != 0)
8885 		return (rc);
8886 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8887 	if (sb == NULL)
8888 		return (ENOMEM);
8889 
8890 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
8891 	if (rc == 0)
8892 		rc = sbuf_finish(sb);
8893 	sbuf_delete(sb);
8894 	return (rc);
8895 }
8896 
8897 bool
8898 t4_os_dump_cimla(struct adapter *sc, int arg, bool verbose)
8899 {
8900 	struct sbuf sb;
8901 	int rc;
8902 
8903 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
8904 		return (false);
8905 	rc = sbuf_cim_la(sc, &sb, M_NOWAIT);
8906 	if (rc == 0) {
8907 		rc = sbuf_finish(&sb);
8908 		if (rc == 0) {
8909 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s",
8910 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
8911 		}
8912 	}
8913 	sbuf_delete(&sb);
8914 	return (false);
8915 }
8916 
8917 static int
8918 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
8919 {
8920 	struct adapter *sc = arg1;
8921 	u_int i;
8922 	struct sbuf *sb;
8923 	uint32_t *buf, *p;
8924 	int rc;
8925 
8926 	rc = sysctl_wire_old_buffer(req, 0);
8927 	if (rc != 0)
8928 		return (rc);
8929 
8930 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8931 	if (sb == NULL)
8932 		return (ENOMEM);
8933 
8934 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
8935 	    M_ZERO | M_WAITOK);
8936 
8937 	mtx_lock(&sc->reg_lock);
8938 	if (hw_off_limits(sc))
8939 		rc = ENXIO;
8940 	else
8941 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
8942 	mtx_unlock(&sc->reg_lock);
8943 	if (rc)
8944 		goto done;
8945 
8946 	p = buf;
8947 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
8948 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
8949 		    p[1], p[0]);
8950 	}
8951 
8952 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
8953 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
8954 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
8955 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
8956 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
8957 		    (p[1] >> 2) | ((p[2] & 3) << 30),
8958 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
8959 		    p[0] & 1);
8960 	}
8961 	rc = sbuf_finish(sb);
8962 done:
8963 	sbuf_delete(sb);
8964 	free(buf, M_CXGBE);
8965 	return (rc);
8966 }
8967 
8968 static int
8969 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
8970 {
8971 	struct adapter *sc = arg1;
8972 	u_int i;
8973 	struct sbuf *sb;
8974 	uint32_t *buf, *p;
8975 	int rc;
8976 
8977 	rc = sysctl_wire_old_buffer(req, 0);
8978 	if (rc != 0)
8979 		return (rc);
8980 
8981 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8982 	if (sb == NULL)
8983 		return (ENOMEM);
8984 
8985 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
8986 	    M_ZERO | M_WAITOK);
8987 
8988 	mtx_lock(&sc->reg_lock);
8989 	if (hw_off_limits(sc))
8990 		rc = ENXIO;
8991 	else
8992 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
8993 	mtx_unlock(&sc->reg_lock);
8994 	if (rc)
8995 		goto done;
8996 
8997 	p = buf;
8998 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
8999 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9000 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9001 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9002 		    p[4], p[3], p[2], p[1], p[0]);
9003 	}
9004 
9005 	sbuf_printf(sb, "\n\nCntl ID               Data");
9006 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9007 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9008 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9009 	}
9010 
9011 	rc = sbuf_finish(sb);
9012 done:
9013 	sbuf_delete(sb);
9014 	free(buf, M_CXGBE);
9015 	return (rc);
9016 }
9017 
9018 static int
9019 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9020 {
9021 	struct adapter *sc = arg1;
9022 	struct sbuf *sb;
9023 	int rc, i;
9024 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9025 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9026 	uint16_t thres[CIM_NUM_IBQ];
9027 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9028 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9029 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9030 
9031 	cim_num_obq = sc->chip_params->cim_num_obq;
9032 	if (is_t4(sc)) {
9033 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9034 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9035 	} else {
9036 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9037 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9038 	}
9039 	nq = CIM_NUM_IBQ + cim_num_obq;
9040 
9041 	mtx_lock(&sc->reg_lock);
9042 	if (hw_off_limits(sc))
9043 		rc = ENXIO;
9044 	else {
9045 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9046 		if (rc == 0) {
9047 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9048 			    obq_wr);
9049 			if (rc == 0)
9050 				t4_read_cimq_cfg(sc, base, size, thres);
9051 		}
9052 	}
9053 	mtx_unlock(&sc->reg_lock);
9054 	if (rc)
9055 		return (rc);
9056 
9057 	rc = sysctl_wire_old_buffer(req, 0);
9058 	if (rc != 0)
9059 		return (rc);
9060 
9061 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9062 	if (sb == NULL)
9063 		return (ENOMEM);
9064 
9065 	sbuf_printf(sb,
9066 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9067 
9068 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9069 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9070 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9071 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9072 		    G_QUEREMFLITS(p[2]) * 16);
9073 	for ( ; i < nq; i++, p += 4, wr += 2)
9074 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9075 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9076 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9077 		    G_QUEREMFLITS(p[2]) * 16);
9078 
9079 	rc = sbuf_finish(sb);
9080 	sbuf_delete(sb);
9081 
9082 	return (rc);
9083 }
9084 
9085 static int
9086 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9087 {
9088 	struct adapter *sc = arg1;
9089 	struct sbuf *sb;
9090 	int rc;
9091 	struct tp_cpl_stats stats;
9092 
9093 	rc = sysctl_wire_old_buffer(req, 0);
9094 	if (rc != 0)
9095 		return (rc);
9096 
9097 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9098 	if (sb == NULL)
9099 		return (ENOMEM);
9100 
9101 	mtx_lock(&sc->reg_lock);
9102 	if (hw_off_limits(sc))
9103 		rc = ENXIO;
9104 	else
9105 		t4_tp_get_cpl_stats(sc, &stats, 0);
9106 	mtx_unlock(&sc->reg_lock);
9107 	if (rc)
9108 		goto done;
9109 
9110 	if (sc->chip_params->nchan > 2) {
9111 		sbuf_printf(sb, "                 channel 0  channel 1"
9112 		    "  channel 2  channel 3");
9113 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9114 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9115 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9116 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9117 	} else {
9118 		sbuf_printf(sb, "                 channel 0  channel 1");
9119 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9120 		    stats.req[0], stats.req[1]);
9121 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9122 		    stats.rsp[0], stats.rsp[1]);
9123 	}
9124 
9125 	rc = sbuf_finish(sb);
9126 done:
9127 	sbuf_delete(sb);
9128 	return (rc);
9129 }
9130 
9131 static int
9132 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9133 {
9134 	struct adapter *sc = arg1;
9135 	struct sbuf *sb;
9136 	int rc;
9137 	struct tp_usm_stats stats;
9138 
9139 	rc = sysctl_wire_old_buffer(req, 0);
9140 	if (rc != 0)
9141 		return(rc);
9142 
9143 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9144 	if (sb == NULL)
9145 		return (ENOMEM);
9146 
9147 	mtx_lock(&sc->reg_lock);
9148 	if (hw_off_limits(sc))
9149 		rc = ENXIO;
9150 	else
9151 		t4_get_usm_stats(sc, &stats, 1);
9152 	mtx_unlock(&sc->reg_lock);
9153 	if (rc == 0) {
9154 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9155 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9156 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9157 		rc = sbuf_finish(sb);
9158 	}
9159 	sbuf_delete(sb);
9160 
9161 	return (rc);
9162 }
9163 
9164 static int
9165 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9166 {
9167 	struct adapter *sc = arg1;
9168 	struct sbuf *sb;
9169 	int rc;
9170 	struct tp_tid_stats stats;
9171 
9172 	rc = sysctl_wire_old_buffer(req, 0);
9173 	if (rc != 0)
9174 		return(rc);
9175 
9176 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9177 	if (sb == NULL)
9178 		return (ENOMEM);
9179 
9180 	mtx_lock(&sc->reg_lock);
9181 	if (hw_off_limits(sc))
9182 		rc = ENXIO;
9183 	else
9184 		t4_tp_get_tid_stats(sc, &stats, 1);
9185 	mtx_unlock(&sc->reg_lock);
9186 	if (rc == 0) {
9187 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9188 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9189 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9190 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9191 		rc = sbuf_finish(sb);
9192 	}
9193 	sbuf_delete(sb);
9194 
9195 	return (rc);
9196 }
9197 
9198 static const char * const devlog_level_strings[] = {
9199 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9200 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9201 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9202 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9203 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9204 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9205 };
9206 
9207 static const char * const devlog_facility_strings[] = {
9208 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9209 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9210 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9211 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9212 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9213 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9214 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9215 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9216 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9217 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9218 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9219 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9220 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9221 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9222 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9223 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9224 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9225 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9226 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9227 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9228 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9229 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9230 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9231 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9232 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9233 };
9234 
9235 static int
9236 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9237 {
9238 	int i, j, rc, nentries, first = 0;
9239 	struct devlog_params *dparams = &sc->params.devlog;
9240 	struct fw_devlog_e *buf, *e;
9241 	uint64_t ftstamp = UINT64_MAX;
9242 
9243 	if (dparams->addr == 0)
9244 		return (ENXIO);
9245 
9246 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9247 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9248 	if (buf == NULL)
9249 		return (ENOMEM);
9250 
9251 	mtx_lock(&sc->reg_lock);
9252 	if (hw_off_limits(sc))
9253 		rc = ENXIO;
9254 	else
9255 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9256 		    dparams->size);
9257 	mtx_unlock(&sc->reg_lock);
9258 	if (rc != 0)
9259 		goto done;
9260 
9261 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9262 	for (i = 0; i < nentries; i++) {
9263 		e = &buf[i];
9264 
9265 		if (e->timestamp == 0)
9266 			break;	/* end */
9267 
9268 		e->timestamp = be64toh(e->timestamp);
9269 		e->seqno = be32toh(e->seqno);
9270 		for (j = 0; j < 8; j++)
9271 			e->params[j] = be32toh(e->params[j]);
9272 
9273 		if (e->timestamp < ftstamp) {
9274 			ftstamp = e->timestamp;
9275 			first = i;
9276 		}
9277 	}
9278 
9279 	if (buf[first].timestamp == 0)
9280 		goto done;	/* nothing in the log */
9281 
9282 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9283 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9284 
9285 	i = first;
9286 	do {
9287 		e = &buf[i];
9288 		if (e->timestamp == 0)
9289 			break;	/* end */
9290 
9291 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9292 		    e->seqno, e->timestamp,
9293 		    (e->level < nitems(devlog_level_strings) ?
9294 			devlog_level_strings[e->level] : "UNKNOWN"),
9295 		    (e->facility < nitems(devlog_facility_strings) ?
9296 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9297 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9298 		    e->params[2], e->params[3], e->params[4],
9299 		    e->params[5], e->params[6], e->params[7]);
9300 
9301 		if (++i == nentries)
9302 			i = 0;
9303 	} while (i != first);
9304 done:
9305 	free(buf, M_CXGBE);
9306 	return (rc);
9307 }
9308 
9309 static int
9310 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9311 {
9312 	struct adapter *sc = arg1;
9313 	int rc;
9314 	struct sbuf *sb;
9315 
9316 	rc = sysctl_wire_old_buffer(req, 0);
9317 	if (rc != 0)
9318 		return (rc);
9319 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9320 	if (sb == NULL)
9321 		return (ENOMEM);
9322 
9323 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9324 	if (rc == 0)
9325 		rc = sbuf_finish(sb);
9326 	sbuf_delete(sb);
9327 	return (rc);
9328 }
9329 
9330 void
9331 t4_os_dump_devlog(struct adapter *sc)
9332 {
9333 	int rc;
9334 	struct sbuf sb;
9335 
9336 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
9337 		return;
9338 	rc = sbuf_devlog(sc, &sb, M_NOWAIT);
9339 	if (rc == 0) {
9340 		rc = sbuf_finish(&sb);
9341 		if (rc == 0) {
9342 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9343 		    		device_get_nameunit(sc->dev), sbuf_data(&sb));
9344 		}
9345 	}
9346 	sbuf_delete(&sb);
9347 }
9348 
9349 static int
9350 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9351 {
9352 	struct adapter *sc = arg1;
9353 	struct sbuf *sb;
9354 	int rc;
9355 	struct tp_fcoe_stats stats[MAX_NCHAN];
9356 	int i, nchan = sc->chip_params->nchan;
9357 
9358 	rc = sysctl_wire_old_buffer(req, 0);
9359 	if (rc != 0)
9360 		return (rc);
9361 
9362 	mtx_lock(&sc->reg_lock);
9363 	if (hw_off_limits(sc))
9364 		rc = ENXIO;
9365 	else {
9366 		for (i = 0; i < nchan; i++)
9367 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9368 	}
9369 	mtx_unlock(&sc->reg_lock);
9370 	if (rc != 0)
9371 		return (rc);
9372 
9373 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9374 	if (sb == NULL)
9375 		return (ENOMEM);
9376 
9377 	if (nchan > 2) {
9378 		sbuf_printf(sb, "                   channel 0        channel 1"
9379 		    "        channel 2        channel 3");
9380 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9381 		    stats[0].octets_ddp, stats[1].octets_ddp,
9382 		    stats[2].octets_ddp, stats[3].octets_ddp);
9383 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9384 		    stats[0].frames_ddp, stats[1].frames_ddp,
9385 		    stats[2].frames_ddp, stats[3].frames_ddp);
9386 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9387 		    stats[0].frames_drop, stats[1].frames_drop,
9388 		    stats[2].frames_drop, stats[3].frames_drop);
9389 	} else {
9390 		sbuf_printf(sb, "                   channel 0        channel 1");
9391 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9392 		    stats[0].octets_ddp, stats[1].octets_ddp);
9393 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9394 		    stats[0].frames_ddp, stats[1].frames_ddp);
9395 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9396 		    stats[0].frames_drop, stats[1].frames_drop);
9397 	}
9398 
9399 	rc = sbuf_finish(sb);
9400 	sbuf_delete(sb);
9401 
9402 	return (rc);
9403 }
9404 
9405 static int
9406 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9407 {
9408 	struct adapter *sc = arg1;
9409 	struct sbuf *sb;
9410 	int rc, i;
9411 	unsigned int map, kbps, ipg, mode;
9412 	unsigned int pace_tab[NTX_SCHED];
9413 
9414 	rc = sysctl_wire_old_buffer(req, 0);
9415 	if (rc != 0)
9416 		return (rc);
9417 
9418 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9419 	if (sb == NULL)
9420 		return (ENOMEM);
9421 
9422 	mtx_lock(&sc->reg_lock);
9423 	if (hw_off_limits(sc)) {
9424 		rc = ENXIO;
9425 		goto done;
9426 	}
9427 
9428 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9429 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9430 	t4_read_pace_tbl(sc, pace_tab);
9431 
9432 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9433 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9434 
9435 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9436 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9437 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9438 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9439 		if (kbps)
9440 			sbuf_printf(sb, "%9u     ", kbps);
9441 		else
9442 			sbuf_printf(sb, " disabled     ");
9443 
9444 		if (ipg)
9445 			sbuf_printf(sb, "%13u        ", ipg);
9446 		else
9447 			sbuf_printf(sb, "     disabled        ");
9448 
9449 		if (pace_tab[i])
9450 			sbuf_printf(sb, "%10u", pace_tab[i]);
9451 		else
9452 			sbuf_printf(sb, "  disabled");
9453 	}
9454 	rc = sbuf_finish(sb);
9455 done:
9456 	mtx_unlock(&sc->reg_lock);
9457 	sbuf_delete(sb);
9458 	return (rc);
9459 }
9460 
9461 static int
9462 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9463 {
9464 	struct adapter *sc = arg1;
9465 	struct sbuf *sb;
9466 	int rc, i, j;
9467 	uint64_t *p0, *p1;
9468 	struct lb_port_stats s[2];
9469 	static const char *stat_name[] = {
9470 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9471 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9472 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9473 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9474 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9475 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9476 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9477 	};
9478 
9479 	rc = sysctl_wire_old_buffer(req, 0);
9480 	if (rc != 0)
9481 		return (rc);
9482 
9483 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9484 	if (sb == NULL)
9485 		return (ENOMEM);
9486 
9487 	memset(s, 0, sizeof(s));
9488 
9489 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9490 		mtx_lock(&sc->reg_lock);
9491 		if (hw_off_limits(sc))
9492 			rc = ENXIO;
9493 		else {
9494 			t4_get_lb_stats(sc, i, &s[0]);
9495 			t4_get_lb_stats(sc, i + 1, &s[1]);
9496 		}
9497 		mtx_unlock(&sc->reg_lock);
9498 		if (rc != 0)
9499 			break;
9500 
9501 		p0 = &s[0].octets;
9502 		p1 = &s[1].octets;
9503 		sbuf_printf(sb, "%s                       Loopback %u"
9504 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9505 
9506 		for (j = 0; j < nitems(stat_name); j++)
9507 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9508 				   *p0++, *p1++);
9509 	}
9510 
9511 	rc = sbuf_finish(sb);
9512 	sbuf_delete(sb);
9513 
9514 	return (rc);
9515 }
9516 
9517 static int
9518 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9519 {
9520 	int rc = 0;
9521 	struct port_info *pi = arg1;
9522 	struct link_config *lc = &pi->link_cfg;
9523 	struct sbuf *sb;
9524 
9525 	rc = sysctl_wire_old_buffer(req, 0);
9526 	if (rc != 0)
9527 		return(rc);
9528 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9529 	if (sb == NULL)
9530 		return (ENOMEM);
9531 
9532 	if (lc->link_ok || lc->link_down_rc == 255)
9533 		sbuf_printf(sb, "n/a");
9534 	else
9535 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9536 
9537 	rc = sbuf_finish(sb);
9538 	sbuf_delete(sb);
9539 
9540 	return (rc);
9541 }
9542 
9543 struct mem_desc {
9544 	unsigned int base;
9545 	unsigned int limit;
9546 	unsigned int idx;
9547 };
9548 
9549 static int
9550 mem_desc_cmp(const void *a, const void *b)
9551 {
9552 	return ((const struct mem_desc *)a)->base -
9553 	       ((const struct mem_desc *)b)->base;
9554 }
9555 
9556 static void
9557 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9558     unsigned int to)
9559 {
9560 	unsigned int size;
9561 
9562 	if (from == to)
9563 		return;
9564 
9565 	size = to - from + 1;
9566 	if (size == 0)
9567 		return;
9568 
9569 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9570 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9571 }
9572 
9573 static int
9574 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9575 {
9576 	struct adapter *sc = arg1;
9577 	struct sbuf *sb;
9578 	int rc, i, n;
9579 	uint32_t lo, hi, used, alloc;
9580 	static const char *memory[] = {"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:"};
9581 	static const char *region[] = {
9582 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9583 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9584 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9585 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9586 		"RQUDP region:", "PBL region:", "TXPBL region:",
9587 		"DBVFIFO region:", "ULPRX state:", "ULPTX state:",
9588 		"On-chip queues:", "TLS keys:",
9589 	};
9590 	struct mem_desc avail[4];
9591 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9592 	struct mem_desc *md = mem;
9593 
9594 	rc = sysctl_wire_old_buffer(req, 0);
9595 	if (rc != 0)
9596 		return (rc);
9597 
9598 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9599 	if (sb == NULL)
9600 		return (ENOMEM);
9601 
9602 	for (i = 0; i < nitems(mem); i++) {
9603 		mem[i].limit = 0;
9604 		mem[i].idx = i;
9605 	}
9606 
9607 	mtx_lock(&sc->reg_lock);
9608 	if (hw_off_limits(sc)) {
9609 		rc = ENXIO;
9610 		goto done;
9611 	}
9612 
9613 	/* Find and sort the populated memory ranges */
9614 	i = 0;
9615 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9616 	if (lo & F_EDRAM0_ENABLE) {
9617 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9618 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9619 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9620 		avail[i].idx = 0;
9621 		i++;
9622 	}
9623 	if (lo & F_EDRAM1_ENABLE) {
9624 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9625 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9626 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9627 		avail[i].idx = 1;
9628 		i++;
9629 	}
9630 	if (lo & F_EXT_MEM_ENABLE) {
9631 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9632 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9633 		avail[i].limit = avail[i].base +
9634 		    (G_EXT_MEM_SIZE(hi) << 20);
9635 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9636 		i++;
9637 	}
9638 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9639 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9640 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9641 		avail[i].limit = avail[i].base +
9642 		    (G_EXT_MEM1_SIZE(hi) << 20);
9643 		avail[i].idx = 4;
9644 		i++;
9645 	}
9646 	if (!i)                                    /* no memory available */
9647 		goto done;
9648 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9649 
9650 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9651 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9652 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9653 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9654 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9655 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9656 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9657 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9658 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9659 
9660 	/* the next few have explicit upper bounds */
9661 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9662 	md->limit = md->base - 1 +
9663 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9664 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9665 	md++;
9666 
9667 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9668 	md->limit = md->base - 1 +
9669 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9670 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9671 	md++;
9672 
9673 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9674 		if (chip_id(sc) <= CHELSIO_T5)
9675 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9676 		else
9677 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9678 		md->limit = 0;
9679 	} else {
9680 		md->base = 0;
9681 		md->idx = nitems(region);  /* hide it */
9682 	}
9683 	md++;
9684 
9685 #define ulp_region(reg) \
9686 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9687 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9688 
9689 	ulp_region(RX_ISCSI);
9690 	ulp_region(RX_TDDP);
9691 	ulp_region(TX_TPT);
9692 	ulp_region(RX_STAG);
9693 	ulp_region(RX_RQ);
9694 	ulp_region(RX_RQUDP);
9695 	ulp_region(RX_PBL);
9696 	ulp_region(TX_PBL);
9697 #undef ulp_region
9698 
9699 	md->base = 0;
9700 	md->idx = nitems(region);
9701 	if (!is_t4(sc)) {
9702 		uint32_t size = 0;
9703 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9704 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9705 
9706 		if (is_t5(sc)) {
9707 			if (sge_ctrl & F_VFIFO_ENABLE)
9708 				size = G_DBVFIFO_SIZE(fifo_size);
9709 		} else
9710 			size = G_T6_DBVFIFO_SIZE(fifo_size);
9711 
9712 		if (size) {
9713 			md->base = G_BASEADDR(t4_read_reg(sc,
9714 			    A_SGE_DBVFIFO_BADDR));
9715 			md->limit = md->base + (size << 2) - 1;
9716 		}
9717 	}
9718 	md++;
9719 
9720 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9721 	md->limit = 0;
9722 	md++;
9723 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9724 	md->limit = 0;
9725 	md++;
9726 
9727 	md->base = sc->vres.ocq.start;
9728 	if (sc->vres.ocq.size)
9729 		md->limit = md->base + sc->vres.ocq.size - 1;
9730 	else
9731 		md->idx = nitems(region);  /* hide it */
9732 	md++;
9733 
9734 	md->base = sc->vres.key.start;
9735 	if (sc->vres.key.size)
9736 		md->limit = md->base + sc->vres.key.size - 1;
9737 	else
9738 		md->idx = nitems(region);  /* hide it */
9739 	md++;
9740 
9741 	/* add any address-space holes, there can be up to 3 */
9742 	for (n = 0; n < i - 1; n++)
9743 		if (avail[n].limit < avail[n + 1].base)
9744 			(md++)->base = avail[n].limit;
9745 	if (avail[n].limit)
9746 		(md++)->base = avail[n].limit;
9747 
9748 	n = md - mem;
9749 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
9750 
9751 	for (lo = 0; lo < i; lo++)
9752 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
9753 				avail[lo].limit - 1);
9754 
9755 	sbuf_printf(sb, "\n");
9756 	for (i = 0; i < n; i++) {
9757 		if (mem[i].idx >= nitems(region))
9758 			continue;                        /* skip holes */
9759 		if (!mem[i].limit)
9760 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
9761 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
9762 				mem[i].limit);
9763 	}
9764 
9765 	sbuf_printf(sb, "\n");
9766 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
9767 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
9768 	mem_region_show(sb, "uP RAM:", lo, hi);
9769 
9770 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
9771 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
9772 	mem_region_show(sb, "uP Extmem2:", lo, hi);
9773 
9774 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
9775 	sbuf_printf(sb, "\n%u Rx pages of size %uKiB for %u channels\n",
9776 		   G_PMRXMAXPAGE(lo),
9777 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
9778 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
9779 
9780 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
9781 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
9782 	sbuf_printf(sb, "%u Tx pages of size %u%ciB for %u channels\n",
9783 		   G_PMTXMAXPAGE(lo),
9784 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
9785 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
9786 	sbuf_printf(sb, "%u p-structs\n",
9787 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT));
9788 
9789 	for (i = 0; i < 4; i++) {
9790 		if (chip_id(sc) > CHELSIO_T5)
9791 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
9792 		else
9793 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
9794 		if (is_t5(sc)) {
9795 			used = G_T5_USED(lo);
9796 			alloc = G_T5_ALLOC(lo);
9797 		} else {
9798 			used = G_USED(lo);
9799 			alloc = G_ALLOC(lo);
9800 		}
9801 		/* For T6 these are MAC buffer groups */
9802 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
9803 		    i, used, alloc);
9804 	}
9805 	for (i = 0; i < sc->chip_params->nchan; i++) {
9806 		if (chip_id(sc) > CHELSIO_T5)
9807 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
9808 		else
9809 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
9810 		if (is_t5(sc)) {
9811 			used = G_T5_USED(lo);
9812 			alloc = G_T5_ALLOC(lo);
9813 		} else {
9814 			used = G_USED(lo);
9815 			alloc = G_ALLOC(lo);
9816 		}
9817 		/* For T6 these are MAC buffer groups */
9818 		sbuf_printf(sb,
9819 		    "\nLoopback %d using %u pages out of %u allocated",
9820 		    i, used, alloc);
9821 	}
9822 done:
9823 	mtx_unlock(&sc->reg_lock);
9824 	if (rc == 0)
9825 		rc = sbuf_finish(sb);
9826 	sbuf_delete(sb);
9827 	return (rc);
9828 }
9829 
9830 static inline void
9831 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
9832 {
9833 	*mask = x | y;
9834 	y = htobe64(y);
9835 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
9836 }
9837 
9838 static int
9839 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
9840 {
9841 	struct adapter *sc = arg1;
9842 	struct sbuf *sb;
9843 	int rc, i;
9844 
9845 	MPASS(chip_id(sc) <= CHELSIO_T5);
9846 
9847 	rc = sysctl_wire_old_buffer(req, 0);
9848 	if (rc != 0)
9849 		return (rc);
9850 
9851 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9852 	if (sb == NULL)
9853 		return (ENOMEM);
9854 
9855 	sbuf_printf(sb,
9856 	    "Idx  Ethernet address     Mask     Vld Ports PF"
9857 	    "  VF              Replication             P0 P1 P2 P3  ML");
9858 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
9859 		uint64_t tcamx, tcamy, mask;
9860 		uint32_t cls_lo, cls_hi;
9861 		uint8_t addr[ETHER_ADDR_LEN];
9862 
9863 		mtx_lock(&sc->reg_lock);
9864 		if (hw_off_limits(sc))
9865 			rc = ENXIO;
9866 		else {
9867 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
9868 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
9869 		}
9870 		mtx_unlock(&sc->reg_lock);
9871 		if (rc != 0)
9872 			break;
9873 		if (tcamx & tcamy)
9874 			continue;
9875 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
9876 		mtx_lock(&sc->reg_lock);
9877 		if (hw_off_limits(sc))
9878 			rc = ENXIO;
9879 		else {
9880 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
9881 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
9882 		}
9883 		mtx_unlock(&sc->reg_lock);
9884 		if (rc != 0)
9885 			break;
9886 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
9887 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
9888 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
9889 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
9890 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
9891 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
9892 
9893 		if (cls_lo & F_REPLICATE) {
9894 			struct fw_ldst_cmd ldst_cmd;
9895 
9896 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
9897 			ldst_cmd.op_to_addrspace =
9898 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
9899 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
9900 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
9901 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
9902 			ldst_cmd.u.mps.rplc.fid_idx =
9903 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
9904 				V_FW_LDST_CMD_IDX(i));
9905 
9906 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
9907 			    "t4mps");
9908 			if (rc)
9909 				break;
9910 			if (hw_off_limits(sc))
9911 				rc = ENXIO;
9912 			else
9913 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
9914 				    sizeof(ldst_cmd), &ldst_cmd);
9915 			end_synchronized_op(sc, 0);
9916 			if (rc != 0)
9917 				break;
9918 			else {
9919 				sbuf_printf(sb, " %08x %08x %08x %08x",
9920 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
9921 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
9922 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
9923 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
9924 			}
9925 		} else
9926 			sbuf_printf(sb, "%36s", "");
9927 
9928 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
9929 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
9930 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
9931 	}
9932 
9933 	if (rc)
9934 		(void) sbuf_finish(sb);
9935 	else
9936 		rc = sbuf_finish(sb);
9937 	sbuf_delete(sb);
9938 
9939 	return (rc);
9940 }
9941 
9942 static int
9943 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
9944 {
9945 	struct adapter *sc = arg1;
9946 	struct sbuf *sb;
9947 	int rc, i;
9948 
9949 	MPASS(chip_id(sc) > CHELSIO_T5);
9950 
9951 	rc = sysctl_wire_old_buffer(req, 0);
9952 	if (rc != 0)
9953 		return (rc);
9954 
9955 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9956 	if (sb == NULL)
9957 		return (ENOMEM);
9958 
9959 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
9960 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
9961 	    "                           Replication"
9962 	    "                                    P0 P1 P2 P3  ML\n");
9963 
9964 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
9965 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
9966 		uint16_t ivlan;
9967 		uint64_t tcamx, tcamy, val, mask;
9968 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
9969 		uint8_t addr[ETHER_ADDR_LEN];
9970 
9971 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
9972 		if (i < 256)
9973 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
9974 		else
9975 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
9976 		mtx_lock(&sc->reg_lock);
9977 		if (hw_off_limits(sc))
9978 			rc = ENXIO;
9979 		else {
9980 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
9981 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
9982 			tcamy = G_DMACH(val) << 32;
9983 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
9984 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
9985 		}
9986 		mtx_unlock(&sc->reg_lock);
9987 		if (rc != 0)
9988 			break;
9989 
9990 		lookup_type = G_DATALKPTYPE(data2);
9991 		port_num = G_DATAPORTNUM(data2);
9992 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
9993 			/* Inner header VNI */
9994 			vniy = ((data2 & F_DATAVIDH2) << 23) |
9995 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
9996 			dip_hit = data2 & F_DATADIPHIT;
9997 			vlan_vld = 0;
9998 		} else {
9999 			vniy = 0;
10000 			dip_hit = 0;
10001 			vlan_vld = data2 & F_DATAVIDH2;
10002 			ivlan = G_VIDL(val);
10003 		}
10004 
10005 		ctl |= V_CTLXYBITSEL(1);
10006 		mtx_lock(&sc->reg_lock);
10007 		if (hw_off_limits(sc))
10008 			rc = ENXIO;
10009 		else {
10010 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10011 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10012 			tcamx = G_DMACH(val) << 32;
10013 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10014 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10015 		}
10016 		mtx_unlock(&sc->reg_lock);
10017 		if (rc != 0)
10018 			break;
10019 
10020 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10021 			/* Inner header VNI mask */
10022 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10023 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10024 		} else
10025 			vnix = 0;
10026 
10027 		if (tcamx & tcamy)
10028 			continue;
10029 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10030 
10031 		mtx_lock(&sc->reg_lock);
10032 		if (hw_off_limits(sc))
10033 			rc = ENXIO;
10034 		else {
10035 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10036 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10037 		}
10038 		mtx_unlock(&sc->reg_lock);
10039 		if (rc != 0)
10040 			break;
10041 
10042 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10043 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10044 			    "%012jx %06x %06x    -    -   %3c"
10045 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10046 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10047 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10048 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10049 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10050 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10051 		} else {
10052 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10053 			    "%012jx    -       -   ", i, addr[0], addr[1],
10054 			    addr[2], addr[3], addr[4], addr[5],
10055 			    (uintmax_t)mask);
10056 
10057 			if (vlan_vld)
10058 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10059 			else
10060 				sbuf_printf(sb, "  -    N     ");
10061 
10062 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10063 			    lookup_type ? 'I' : 'O', port_num,
10064 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10065 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10066 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10067 		}
10068 
10069 
10070 		if (cls_lo & F_T6_REPLICATE) {
10071 			struct fw_ldst_cmd ldst_cmd;
10072 
10073 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10074 			ldst_cmd.op_to_addrspace =
10075 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10076 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10077 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10078 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10079 			ldst_cmd.u.mps.rplc.fid_idx =
10080 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10081 				V_FW_LDST_CMD_IDX(i));
10082 
10083 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10084 			    "t6mps");
10085 			if (rc)
10086 				break;
10087 			if (hw_off_limits(sc))
10088 				rc = ENXIO;
10089 			else
10090 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10091 				    sizeof(ldst_cmd), &ldst_cmd);
10092 			end_synchronized_op(sc, 0);
10093 			if (rc != 0)
10094 				break;
10095 			else {
10096 				sbuf_printf(sb, " %08x %08x %08x %08x"
10097 				    " %08x %08x %08x %08x",
10098 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10099 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10100 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10101 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10102 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10103 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10104 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10105 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10106 			}
10107 		} else
10108 			sbuf_printf(sb, "%72s", "");
10109 
10110 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10111 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10112 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10113 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10114 	}
10115 
10116 	if (rc)
10117 		(void) sbuf_finish(sb);
10118 	else
10119 		rc = sbuf_finish(sb);
10120 	sbuf_delete(sb);
10121 
10122 	return (rc);
10123 }
10124 
10125 static int
10126 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10127 {
10128 	struct adapter *sc = arg1;
10129 	struct sbuf *sb;
10130 	int rc;
10131 	uint16_t mtus[NMTUS];
10132 
10133 	rc = sysctl_wire_old_buffer(req, 0);
10134 	if (rc != 0)
10135 		return (rc);
10136 
10137 	mtx_lock(&sc->reg_lock);
10138 	if (hw_off_limits(sc))
10139 		rc = ENXIO;
10140 	else
10141 		t4_read_mtu_tbl(sc, mtus, NULL);
10142 	mtx_unlock(&sc->reg_lock);
10143 	if (rc != 0)
10144 		return (rc);
10145 
10146 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10147 	if (sb == NULL)
10148 		return (ENOMEM);
10149 
10150 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10151 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10152 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10153 	    mtus[14], mtus[15]);
10154 
10155 	rc = sbuf_finish(sb);
10156 	sbuf_delete(sb);
10157 
10158 	return (rc);
10159 }
10160 
10161 static int
10162 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10163 {
10164 	struct adapter *sc = arg1;
10165 	struct sbuf *sb;
10166 	int rc, i;
10167 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10168 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10169 	static const char *tx_stats[MAX_PM_NSTATS] = {
10170 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10171 		"Tx FIFO wait", NULL, "Tx latency"
10172 	};
10173 	static const char *rx_stats[MAX_PM_NSTATS] = {
10174 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10175 		"Rx FIFO wait", NULL, "Rx latency"
10176 	};
10177 
10178 	rc = sysctl_wire_old_buffer(req, 0);
10179 	if (rc != 0)
10180 		return (rc);
10181 
10182 	mtx_lock(&sc->reg_lock);
10183 	if (hw_off_limits(sc))
10184 		rc = ENXIO;
10185 	else {
10186 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10187 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10188 	}
10189 	mtx_unlock(&sc->reg_lock);
10190 	if (rc != 0)
10191 		return (rc);
10192 
10193 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10194 	if (sb == NULL)
10195 		return (ENOMEM);
10196 
10197 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10198 	for (i = 0; i < 4; i++) {
10199 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10200 		    tx_cyc[i]);
10201 	}
10202 
10203 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10204 	for (i = 0; i < 4; i++) {
10205 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10206 		    rx_cyc[i]);
10207 	}
10208 
10209 	if (chip_id(sc) > CHELSIO_T5) {
10210 		sbuf_printf(sb,
10211 		    "\n              Total wait      Total occupancy");
10212 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10213 		    tx_cyc[i]);
10214 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10215 		    rx_cyc[i]);
10216 
10217 		i += 2;
10218 		MPASS(i < nitems(tx_stats));
10219 
10220 		sbuf_printf(sb,
10221 		    "\n                   Reads           Total wait");
10222 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10223 		    tx_cyc[i]);
10224 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10225 		    rx_cyc[i]);
10226 	}
10227 
10228 	rc = sbuf_finish(sb);
10229 	sbuf_delete(sb);
10230 
10231 	return (rc);
10232 }
10233 
10234 static int
10235 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10236 {
10237 	struct adapter *sc = arg1;
10238 	struct sbuf *sb;
10239 	int rc;
10240 	struct tp_rdma_stats stats;
10241 
10242 	rc = sysctl_wire_old_buffer(req, 0);
10243 	if (rc != 0)
10244 		return (rc);
10245 
10246 	mtx_lock(&sc->reg_lock);
10247 	if (hw_off_limits(sc))
10248 		rc = ENXIO;
10249 	else
10250 		t4_tp_get_rdma_stats(sc, &stats, 0);
10251 	mtx_unlock(&sc->reg_lock);
10252 	if (rc != 0)
10253 		return (rc);
10254 
10255 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10256 	if (sb == NULL)
10257 		return (ENOMEM);
10258 
10259 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10260 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10261 
10262 	rc = sbuf_finish(sb);
10263 	sbuf_delete(sb);
10264 
10265 	return (rc);
10266 }
10267 
10268 static int
10269 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10270 {
10271 	struct adapter *sc = arg1;
10272 	struct sbuf *sb;
10273 	int rc;
10274 	struct tp_tcp_stats v4, v6;
10275 
10276 	rc = sysctl_wire_old_buffer(req, 0);
10277 	if (rc != 0)
10278 		return (rc);
10279 
10280 	mtx_lock(&sc->reg_lock);
10281 	if (hw_off_limits(sc))
10282 		rc = ENXIO;
10283 	else
10284 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10285 	mtx_unlock(&sc->reg_lock);
10286 	if (rc != 0)
10287 		return (rc);
10288 
10289 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10290 	if (sb == NULL)
10291 		return (ENOMEM);
10292 
10293 	sbuf_printf(sb,
10294 	    "                                IP                 IPv6\n");
10295 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10296 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10297 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10298 	    v4.tcp_in_segs, v6.tcp_in_segs);
10299 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10300 	    v4.tcp_out_segs, v6.tcp_out_segs);
10301 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10302 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10303 
10304 	rc = sbuf_finish(sb);
10305 	sbuf_delete(sb);
10306 
10307 	return (rc);
10308 }
10309 
10310 static int
10311 sysctl_tids(SYSCTL_HANDLER_ARGS)
10312 {
10313 	struct adapter *sc = arg1;
10314 	struct sbuf *sb;
10315 	int rc;
10316 	uint32_t x, y;
10317 	struct tid_info *t = &sc->tids;
10318 
10319 	rc = sysctl_wire_old_buffer(req, 0);
10320 	if (rc != 0)
10321 		return (rc);
10322 
10323 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10324 	if (sb == NULL)
10325 		return (ENOMEM);
10326 
10327 	if (t->natids) {
10328 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10329 		    t->atids_in_use);
10330 	}
10331 
10332 	if (t->nhpftids) {
10333 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10334 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10335 	}
10336 
10337 	if (t->ntids) {
10338 		bool hashen = false;
10339 
10340 		mtx_lock(&sc->reg_lock);
10341 		if (hw_off_limits(sc))
10342 			rc = ENXIO;
10343 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10344 			hashen = true;
10345 			if (chip_id(sc) <= CHELSIO_T5) {
10346 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10347 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10348 			} else {
10349 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10350 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10351 			}
10352 		}
10353 		mtx_unlock(&sc->reg_lock);
10354 		if (rc != 0)
10355 			goto done;
10356 
10357 		sbuf_printf(sb, "TID range: ");
10358 		if (hashen) {
10359 			if (x)
10360 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10361 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10362 		} else {
10363 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10364 			    t->ntids - 1);
10365 		}
10366 		sbuf_printf(sb, ", in use: %u\n",
10367 		    atomic_load_acq_int(&t->tids_in_use));
10368 	}
10369 
10370 	if (t->nstids) {
10371 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10372 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10373 	}
10374 
10375 	if (t->nftids) {
10376 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10377 		    t->ftid_end, t->ftids_in_use);
10378 	}
10379 
10380 	if (t->netids) {
10381 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10382 		    t->etid_base + t->netids - 1, t->etids_in_use);
10383 	}
10384 
10385 	mtx_lock(&sc->reg_lock);
10386 	if (hw_off_limits(sc))
10387 		rc = ENXIO;
10388 	else {
10389 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10390 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10391 	}
10392 	mtx_unlock(&sc->reg_lock);
10393 	if (rc != 0)
10394 		goto done;
10395 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10396 done:
10397 	if (rc == 0)
10398 		rc = sbuf_finish(sb);
10399 	else
10400 		(void)sbuf_finish(sb);
10401 	sbuf_delete(sb);
10402 
10403 	return (rc);
10404 }
10405 
10406 static int
10407 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10408 {
10409 	struct adapter *sc = arg1;
10410 	struct sbuf *sb;
10411 	int rc;
10412 	struct tp_err_stats stats;
10413 
10414 	rc = sysctl_wire_old_buffer(req, 0);
10415 	if (rc != 0)
10416 		return (rc);
10417 
10418 	mtx_lock(&sc->reg_lock);
10419 	if (hw_off_limits(sc))
10420 		rc = ENXIO;
10421 	else
10422 		t4_tp_get_err_stats(sc, &stats, 0);
10423 	mtx_unlock(&sc->reg_lock);
10424 	if (rc != 0)
10425 		return (rc);
10426 
10427 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10428 	if (sb == NULL)
10429 		return (ENOMEM);
10430 
10431 	if (sc->chip_params->nchan > 2) {
10432 		sbuf_printf(sb, "                 channel 0  channel 1"
10433 		    "  channel 2  channel 3\n");
10434 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10435 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10436 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10437 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10438 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10439 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10440 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10441 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10442 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10443 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10444 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10445 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10446 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10447 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10448 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10449 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10450 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10451 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10452 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10453 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10454 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10455 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10456 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10457 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10458 	} else {
10459 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10460 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10461 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10462 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10463 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10464 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10465 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10466 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10467 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10468 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10469 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10470 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10471 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10472 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10473 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10474 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10475 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10476 	}
10477 
10478 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10479 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10480 
10481 	rc = sbuf_finish(sb);
10482 	sbuf_delete(sb);
10483 
10484 	return (rc);
10485 }
10486 
10487 static int
10488 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10489 {
10490 	struct adapter *sc = arg1;
10491 	struct sbuf *sb;
10492 	int rc;
10493 	struct tp_tnl_stats stats;
10494 
10495 	rc = sysctl_wire_old_buffer(req, 0);
10496 	if (rc != 0)
10497 		return(rc);
10498 
10499 	mtx_lock(&sc->reg_lock);
10500 	if (hw_off_limits(sc))
10501 		rc = ENXIO;
10502 	else
10503 		t4_tp_get_tnl_stats(sc, &stats, 1);
10504 	mtx_unlock(&sc->reg_lock);
10505 	if (rc != 0)
10506 		return (rc);
10507 
10508 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10509 	if (sb == NULL)
10510 		return (ENOMEM);
10511 
10512 	if (sc->chip_params->nchan > 2) {
10513 		sbuf_printf(sb, "           channel 0  channel 1"
10514 		    "  channel 2  channel 3\n");
10515 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10516 		    stats.out_pkt[0], stats.out_pkt[1],
10517 		    stats.out_pkt[2], stats.out_pkt[3]);
10518 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10519 		    stats.in_pkt[0], stats.in_pkt[1],
10520 		    stats.in_pkt[2], stats.in_pkt[3]);
10521 	} else {
10522 		sbuf_printf(sb, "           channel 0  channel 1\n");
10523 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10524 		    stats.out_pkt[0], stats.out_pkt[1]);
10525 		sbuf_printf(sb, "InPkts:   %10u %10u",
10526 		    stats.in_pkt[0], stats.in_pkt[1]);
10527 	}
10528 
10529 	rc = sbuf_finish(sb);
10530 	sbuf_delete(sb);
10531 
10532 	return (rc);
10533 }
10534 
10535 static int
10536 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10537 {
10538 	struct adapter *sc = arg1;
10539 	struct tp_params *tpp = &sc->params.tp;
10540 	u_int mask;
10541 	int rc;
10542 
10543 	mask = tpp->la_mask >> 16;
10544 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10545 	if (rc != 0 || req->newptr == NULL)
10546 		return (rc);
10547 	if (mask > 0xffff)
10548 		return (EINVAL);
10549 	mtx_lock(&sc->reg_lock);
10550 	if (hw_off_limits(sc))
10551 		rc = ENXIO;
10552 	else {
10553 		tpp->la_mask = mask << 16;
10554 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10555 		    tpp->la_mask);
10556 	}
10557 	mtx_unlock(&sc->reg_lock);
10558 
10559 	return (rc);
10560 }
10561 
10562 struct field_desc {
10563 	const char *name;
10564 	u_int start;
10565 	u_int width;
10566 };
10567 
10568 static void
10569 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10570 {
10571 	char buf[32];
10572 	int line_size = 0;
10573 
10574 	while (f->name) {
10575 		uint64_t mask = (1ULL << f->width) - 1;
10576 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10577 		    ((uintmax_t)v >> f->start) & mask);
10578 
10579 		if (line_size + len >= 79) {
10580 			line_size = 8;
10581 			sbuf_printf(sb, "\n        ");
10582 		}
10583 		sbuf_printf(sb, "%s ", buf);
10584 		line_size += len + 1;
10585 		f++;
10586 	}
10587 	sbuf_printf(sb, "\n");
10588 }
10589 
10590 static const struct field_desc tp_la0[] = {
10591 	{ "RcfOpCodeOut", 60, 4 },
10592 	{ "State", 56, 4 },
10593 	{ "WcfState", 52, 4 },
10594 	{ "RcfOpcSrcOut", 50, 2 },
10595 	{ "CRxError", 49, 1 },
10596 	{ "ERxError", 48, 1 },
10597 	{ "SanityFailed", 47, 1 },
10598 	{ "SpuriousMsg", 46, 1 },
10599 	{ "FlushInputMsg", 45, 1 },
10600 	{ "FlushInputCpl", 44, 1 },
10601 	{ "RssUpBit", 43, 1 },
10602 	{ "RssFilterHit", 42, 1 },
10603 	{ "Tid", 32, 10 },
10604 	{ "InitTcb", 31, 1 },
10605 	{ "LineNumber", 24, 7 },
10606 	{ "Emsg", 23, 1 },
10607 	{ "EdataOut", 22, 1 },
10608 	{ "Cmsg", 21, 1 },
10609 	{ "CdataOut", 20, 1 },
10610 	{ "EreadPdu", 19, 1 },
10611 	{ "CreadPdu", 18, 1 },
10612 	{ "TunnelPkt", 17, 1 },
10613 	{ "RcfPeerFin", 16, 1 },
10614 	{ "RcfReasonOut", 12, 4 },
10615 	{ "TxCchannel", 10, 2 },
10616 	{ "RcfTxChannel", 8, 2 },
10617 	{ "RxEchannel", 6, 2 },
10618 	{ "RcfRxChannel", 5, 1 },
10619 	{ "RcfDataOutSrdy", 4, 1 },
10620 	{ "RxDvld", 3, 1 },
10621 	{ "RxOoDvld", 2, 1 },
10622 	{ "RxCongestion", 1, 1 },
10623 	{ "TxCongestion", 0, 1 },
10624 	{ NULL }
10625 };
10626 
10627 static const struct field_desc tp_la1[] = {
10628 	{ "CplCmdIn", 56, 8 },
10629 	{ "CplCmdOut", 48, 8 },
10630 	{ "ESynOut", 47, 1 },
10631 	{ "EAckOut", 46, 1 },
10632 	{ "EFinOut", 45, 1 },
10633 	{ "ERstOut", 44, 1 },
10634 	{ "SynIn", 43, 1 },
10635 	{ "AckIn", 42, 1 },
10636 	{ "FinIn", 41, 1 },
10637 	{ "RstIn", 40, 1 },
10638 	{ "DataIn", 39, 1 },
10639 	{ "DataInVld", 38, 1 },
10640 	{ "PadIn", 37, 1 },
10641 	{ "RxBufEmpty", 36, 1 },
10642 	{ "RxDdp", 35, 1 },
10643 	{ "RxFbCongestion", 34, 1 },
10644 	{ "TxFbCongestion", 33, 1 },
10645 	{ "TxPktSumSrdy", 32, 1 },
10646 	{ "RcfUlpType", 28, 4 },
10647 	{ "Eread", 27, 1 },
10648 	{ "Ebypass", 26, 1 },
10649 	{ "Esave", 25, 1 },
10650 	{ "Static0", 24, 1 },
10651 	{ "Cread", 23, 1 },
10652 	{ "Cbypass", 22, 1 },
10653 	{ "Csave", 21, 1 },
10654 	{ "CPktOut", 20, 1 },
10655 	{ "RxPagePoolFull", 18, 2 },
10656 	{ "RxLpbkPkt", 17, 1 },
10657 	{ "TxLpbkPkt", 16, 1 },
10658 	{ "RxVfValid", 15, 1 },
10659 	{ "SynLearned", 14, 1 },
10660 	{ "SetDelEntry", 13, 1 },
10661 	{ "SetInvEntry", 12, 1 },
10662 	{ "CpcmdDvld", 11, 1 },
10663 	{ "CpcmdSave", 10, 1 },
10664 	{ "RxPstructsFull", 8, 2 },
10665 	{ "EpcmdDvld", 7, 1 },
10666 	{ "EpcmdFlush", 6, 1 },
10667 	{ "EpcmdTrimPrefix", 5, 1 },
10668 	{ "EpcmdTrimPostfix", 4, 1 },
10669 	{ "ERssIp4Pkt", 3, 1 },
10670 	{ "ERssIp6Pkt", 2, 1 },
10671 	{ "ERssTcpUdpPkt", 1, 1 },
10672 	{ "ERssFceFipPkt", 0, 1 },
10673 	{ NULL }
10674 };
10675 
10676 static const struct field_desc tp_la2[] = {
10677 	{ "CplCmdIn", 56, 8 },
10678 	{ "MpsVfVld", 55, 1 },
10679 	{ "MpsPf", 52, 3 },
10680 	{ "MpsVf", 44, 8 },
10681 	{ "SynIn", 43, 1 },
10682 	{ "AckIn", 42, 1 },
10683 	{ "FinIn", 41, 1 },
10684 	{ "RstIn", 40, 1 },
10685 	{ "DataIn", 39, 1 },
10686 	{ "DataInVld", 38, 1 },
10687 	{ "PadIn", 37, 1 },
10688 	{ "RxBufEmpty", 36, 1 },
10689 	{ "RxDdp", 35, 1 },
10690 	{ "RxFbCongestion", 34, 1 },
10691 	{ "TxFbCongestion", 33, 1 },
10692 	{ "TxPktSumSrdy", 32, 1 },
10693 	{ "RcfUlpType", 28, 4 },
10694 	{ "Eread", 27, 1 },
10695 	{ "Ebypass", 26, 1 },
10696 	{ "Esave", 25, 1 },
10697 	{ "Static0", 24, 1 },
10698 	{ "Cread", 23, 1 },
10699 	{ "Cbypass", 22, 1 },
10700 	{ "Csave", 21, 1 },
10701 	{ "CPktOut", 20, 1 },
10702 	{ "RxPagePoolFull", 18, 2 },
10703 	{ "RxLpbkPkt", 17, 1 },
10704 	{ "TxLpbkPkt", 16, 1 },
10705 	{ "RxVfValid", 15, 1 },
10706 	{ "SynLearned", 14, 1 },
10707 	{ "SetDelEntry", 13, 1 },
10708 	{ "SetInvEntry", 12, 1 },
10709 	{ "CpcmdDvld", 11, 1 },
10710 	{ "CpcmdSave", 10, 1 },
10711 	{ "RxPstructsFull", 8, 2 },
10712 	{ "EpcmdDvld", 7, 1 },
10713 	{ "EpcmdFlush", 6, 1 },
10714 	{ "EpcmdTrimPrefix", 5, 1 },
10715 	{ "EpcmdTrimPostfix", 4, 1 },
10716 	{ "ERssIp4Pkt", 3, 1 },
10717 	{ "ERssIp6Pkt", 2, 1 },
10718 	{ "ERssTcpUdpPkt", 1, 1 },
10719 	{ "ERssFceFipPkt", 0, 1 },
10720 	{ NULL }
10721 };
10722 
10723 static void
10724 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10725 {
10726 
10727 	field_desc_show(sb, *p, tp_la0);
10728 }
10729 
10730 static void
10731 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10732 {
10733 
10734 	if (idx)
10735 		sbuf_printf(sb, "\n");
10736 	field_desc_show(sb, p[0], tp_la0);
10737 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10738 		field_desc_show(sb, p[1], tp_la0);
10739 }
10740 
10741 static void
10742 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
10743 {
10744 
10745 	if (idx)
10746 		sbuf_printf(sb, "\n");
10747 	field_desc_show(sb, p[0], tp_la0);
10748 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10749 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
10750 }
10751 
10752 static int
10753 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
10754 {
10755 	struct adapter *sc = arg1;
10756 	struct sbuf *sb;
10757 	uint64_t *buf, *p;
10758 	int rc;
10759 	u_int i, inc;
10760 	void (*show_func)(struct sbuf *, uint64_t *, int);
10761 
10762 	rc = sysctl_wire_old_buffer(req, 0);
10763 	if (rc != 0)
10764 		return (rc);
10765 
10766 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10767 	if (sb == NULL)
10768 		return (ENOMEM);
10769 
10770 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
10771 
10772 	mtx_lock(&sc->reg_lock);
10773 	if (hw_off_limits(sc))
10774 		rc = ENXIO;
10775 	else {
10776 		t4_tp_read_la(sc, buf, NULL);
10777 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
10778 		case 2:
10779 			inc = 2;
10780 			show_func = tp_la_show2;
10781 			break;
10782 		case 3:
10783 			inc = 2;
10784 			show_func = tp_la_show3;
10785 			break;
10786 		default:
10787 			inc = 1;
10788 			show_func = tp_la_show;
10789 		}
10790 	}
10791 	mtx_unlock(&sc->reg_lock);
10792 	if (rc != 0)
10793 		goto done;
10794 
10795 	p = buf;
10796 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
10797 		(*show_func)(sb, p, i);
10798 	rc = sbuf_finish(sb);
10799 done:
10800 	sbuf_delete(sb);
10801 	free(buf, M_CXGBE);
10802 	return (rc);
10803 }
10804 
10805 static int
10806 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
10807 {
10808 	struct adapter *sc = arg1;
10809 	struct sbuf *sb;
10810 	int rc;
10811 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
10812 
10813 	rc = sysctl_wire_old_buffer(req, 0);
10814 	if (rc != 0)
10815 		return (rc);
10816 
10817 	mtx_lock(&sc->reg_lock);
10818 	if (hw_off_limits(sc))
10819 		rc = ENXIO;
10820 	else
10821 		t4_get_chan_txrate(sc, nrate, orate);
10822 	mtx_unlock(&sc->reg_lock);
10823 	if (rc != 0)
10824 		return (rc);
10825 
10826 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10827 	if (sb == NULL)
10828 		return (ENOMEM);
10829 
10830 	if (sc->chip_params->nchan > 2) {
10831 		sbuf_printf(sb, "              channel 0   channel 1"
10832 		    "   channel 2   channel 3\n");
10833 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
10834 		    nrate[0], nrate[1], nrate[2], nrate[3]);
10835 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
10836 		    orate[0], orate[1], orate[2], orate[3]);
10837 	} else {
10838 		sbuf_printf(sb, "              channel 0   channel 1\n");
10839 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
10840 		    nrate[0], nrate[1]);
10841 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
10842 		    orate[0], orate[1]);
10843 	}
10844 
10845 	rc = sbuf_finish(sb);
10846 	sbuf_delete(sb);
10847 
10848 	return (rc);
10849 }
10850 
10851 static int
10852 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
10853 {
10854 	struct adapter *sc = arg1;
10855 	struct sbuf *sb;
10856 	uint32_t *buf, *p;
10857 	int rc, i;
10858 
10859 	rc = sysctl_wire_old_buffer(req, 0);
10860 	if (rc != 0)
10861 		return (rc);
10862 
10863 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10864 	if (sb == NULL)
10865 		return (ENOMEM);
10866 
10867 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
10868 	    M_ZERO | M_WAITOK);
10869 
10870 	mtx_lock(&sc->reg_lock);
10871 	if (hw_off_limits(sc))
10872 		rc = ENXIO;
10873 	else
10874 		t4_ulprx_read_la(sc, buf);
10875 	mtx_unlock(&sc->reg_lock);
10876 	if (rc != 0)
10877 		goto done;
10878 
10879 	p = buf;
10880 	sbuf_printf(sb, "      Pcmd        Type   Message"
10881 	    "                Data");
10882 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
10883 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
10884 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
10885 	}
10886 	rc = sbuf_finish(sb);
10887 done:
10888 	sbuf_delete(sb);
10889 	free(buf, M_CXGBE);
10890 	return (rc);
10891 }
10892 
10893 static int
10894 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
10895 {
10896 	struct adapter *sc = arg1;
10897 	struct sbuf *sb;
10898 	int rc;
10899 	uint32_t cfg, s1, s2;
10900 
10901 	MPASS(chip_id(sc) >= CHELSIO_T5);
10902 
10903 	rc = sysctl_wire_old_buffer(req, 0);
10904 	if (rc != 0)
10905 		return (rc);
10906 
10907 	mtx_lock(&sc->reg_lock);
10908 	if (hw_off_limits(sc))
10909 		rc = ENXIO;
10910 	else {
10911 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
10912 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
10913 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
10914 	}
10915 	mtx_unlock(&sc->reg_lock);
10916 	if (rc != 0)
10917 		return (rc);
10918 
10919 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10920 	if (sb == NULL)
10921 		return (ENOMEM);
10922 
10923 	if (G_STATSOURCE_T5(cfg) == 7) {
10924 		int mode;
10925 
10926 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
10927 		if (mode == 0)
10928 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
10929 		else if (mode == 1)
10930 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
10931 		else
10932 			sbuf_printf(sb, "unknown mode %d", mode);
10933 	}
10934 	rc = sbuf_finish(sb);
10935 	sbuf_delete(sb);
10936 
10937 	return (rc);
10938 }
10939 
10940 static int
10941 sysctl_cpus(SYSCTL_HANDLER_ARGS)
10942 {
10943 	struct adapter *sc = arg1;
10944 	enum cpu_sets op = arg2;
10945 	cpuset_t cpuset;
10946 	struct sbuf *sb;
10947 	int i, rc;
10948 
10949 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
10950 
10951 	CPU_ZERO(&cpuset);
10952 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
10953 	if (rc != 0)
10954 		return (rc);
10955 
10956 	rc = sysctl_wire_old_buffer(req, 0);
10957 	if (rc != 0)
10958 		return (rc);
10959 
10960 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10961 	if (sb == NULL)
10962 		return (ENOMEM);
10963 
10964 	CPU_FOREACH(i)
10965 		sbuf_printf(sb, "%d ", i);
10966 	rc = sbuf_finish(sb);
10967 	sbuf_delete(sb);
10968 
10969 	return (rc);
10970 }
10971 
10972 static int
10973 sysctl_reset(SYSCTL_HANDLER_ARGS)
10974 {
10975 	struct adapter *sc = arg1;
10976 	u_int val;
10977 	int rc;
10978 
10979 	val = sc->num_resets;
10980 	rc = sysctl_handle_int(oidp, &val, 0, req);
10981 	if (rc != 0 || req->newptr == NULL)
10982 		return (rc);
10983 
10984 	if (val == 0) {
10985 		/* Zero out the counter that tracks reset. */
10986 		sc->num_resets = 0;
10987 		return (0);
10988 	}
10989 
10990 	if (val != 1)
10991 		return (EINVAL);	/* 0 or 1 are the only legal values */
10992 
10993 	if (hw_off_limits(sc))		/* harmless race */
10994 		return (EALREADY);
10995 
10996 	taskqueue_enqueue(reset_tq, &sc->reset_task);
10997 	return (0);
10998 }
10999 
11000 #ifdef TCP_OFFLOAD
11001 static int
11002 sysctl_tls(SYSCTL_HANDLER_ARGS)
11003 {
11004 	struct adapter *sc = arg1;
11005 	int i, j, v, rc;
11006 	struct vi_info *vi;
11007 
11008 	v = sc->tt.tls;
11009 	rc = sysctl_handle_int(oidp, &v, 0, req);
11010 	if (rc != 0 || req->newptr == NULL)
11011 		return (rc);
11012 
11013 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11014 		return (ENOTSUP);
11015 
11016 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11017 	if (rc)
11018 		return (rc);
11019 	if (hw_off_limits(sc))
11020 		rc = ENXIO;
11021 	else {
11022 		sc->tt.tls = !!v;
11023 		for_each_port(sc, i) {
11024 			for_each_vi(sc->port[i], j, vi) {
11025 				if (vi->flags & VI_INIT_DONE)
11026 					t4_update_fl_bufsize(vi->ifp);
11027 			}
11028 		}
11029 	}
11030 	end_synchronized_op(sc, 0);
11031 
11032 	return (rc);
11033 
11034 }
11035 
11036 static int
11037 sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS)
11038 {
11039 	struct adapter *sc = arg1;
11040 	int *old_ports, *new_ports;
11041 	int i, new_count, rc;
11042 
11043 	if (req->newptr == NULL && req->oldptr == NULL)
11044 		return (SYSCTL_OUT(req, NULL, imax(sc->tt.num_tls_rx_ports, 1) *
11045 		    sizeof(sc->tt.tls_rx_ports[0])));
11046 
11047 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tlsrx");
11048 	if (rc)
11049 		return (rc);
11050 
11051 	if (hw_off_limits(sc)) {
11052 		rc = ENXIO;
11053 		goto done;
11054 	}
11055 
11056 	if (sc->tt.num_tls_rx_ports == 0) {
11057 		i = -1;
11058 		rc = SYSCTL_OUT(req, &i, sizeof(i));
11059 	} else
11060 		rc = SYSCTL_OUT(req, sc->tt.tls_rx_ports,
11061 		    sc->tt.num_tls_rx_ports * sizeof(sc->tt.tls_rx_ports[0]));
11062 	if (rc == 0 && req->newptr != NULL) {
11063 		new_count = req->newlen / sizeof(new_ports[0]);
11064 		new_ports = malloc(new_count * sizeof(new_ports[0]), M_CXGBE,
11065 		    M_WAITOK);
11066 		rc = SYSCTL_IN(req, new_ports, new_count *
11067 		    sizeof(new_ports[0]));
11068 		if (rc)
11069 			goto err;
11070 
11071 		/* Allow setting to a single '-1' to clear the list. */
11072 		if (new_count == 1 && new_ports[0] == -1) {
11073 			ADAPTER_LOCK(sc);
11074 			old_ports = sc->tt.tls_rx_ports;
11075 			sc->tt.tls_rx_ports = NULL;
11076 			sc->tt.num_tls_rx_ports = 0;
11077 			ADAPTER_UNLOCK(sc);
11078 			free(old_ports, M_CXGBE);
11079 		} else {
11080 			for (i = 0; i < new_count; i++) {
11081 				if (new_ports[i] < 1 ||
11082 				    new_ports[i] > IPPORT_MAX) {
11083 					rc = EINVAL;
11084 					goto err;
11085 				}
11086 			}
11087 
11088 			ADAPTER_LOCK(sc);
11089 			old_ports = sc->tt.tls_rx_ports;
11090 			sc->tt.tls_rx_ports = new_ports;
11091 			sc->tt.num_tls_rx_ports = new_count;
11092 			ADAPTER_UNLOCK(sc);
11093 			free(old_ports, M_CXGBE);
11094 			new_ports = NULL;
11095 		}
11096 	err:
11097 		free(new_ports, M_CXGBE);
11098 	}
11099 done:
11100 	end_synchronized_op(sc, 0);
11101 	return (rc);
11102 }
11103 
11104 static int
11105 sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS)
11106 {
11107 	struct adapter *sc = arg1;
11108 	int v, rc;
11109 
11110 	v = sc->tt.tls_rx_timeout;
11111 	rc = sysctl_handle_int(oidp, &v, 0, req);
11112 	if (rc != 0 || req->newptr == NULL)
11113 		return (rc);
11114 
11115 	if (v < 0)
11116 		return (EINVAL);
11117 
11118 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11119 		return (ENOTSUP);
11120 
11121 	sc->tt.tls_rx_timeout = v;
11122 
11123 	return (0);
11124 
11125 }
11126 
11127 static void
11128 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11129 {
11130 	u_int rem = val % factor;
11131 
11132 	if (rem == 0)
11133 		snprintf(buf, len, "%u", val / factor);
11134 	else {
11135 		while (rem % 10 == 0)
11136 			rem /= 10;
11137 		snprintf(buf, len, "%u.%u", val / factor, rem);
11138 	}
11139 }
11140 
11141 static int
11142 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11143 {
11144 	struct adapter *sc = arg1;
11145 	char buf[16];
11146 	u_int res, re;
11147 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11148 
11149 	mtx_lock(&sc->reg_lock);
11150 	if (hw_off_limits(sc))
11151 		res = (u_int)-1;
11152 	else
11153 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11154 	mtx_unlock(&sc->reg_lock);
11155 	if (res == (u_int)-1)
11156 		return (ENXIO);
11157 
11158 	switch (arg2) {
11159 	case 0:
11160 		/* timer_tick */
11161 		re = G_TIMERRESOLUTION(res);
11162 		break;
11163 	case 1:
11164 		/* TCP timestamp tick */
11165 		re = G_TIMESTAMPRESOLUTION(res);
11166 		break;
11167 	case 2:
11168 		/* DACK tick */
11169 		re = G_DELAYEDACKRESOLUTION(res);
11170 		break;
11171 	default:
11172 		return (EDOOFUS);
11173 	}
11174 
11175 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11176 
11177 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11178 }
11179 
11180 static int
11181 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11182 {
11183 	struct adapter *sc = arg1;
11184 	int rc;
11185 	u_int dack_tmr, dack_re, v;
11186 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11187 
11188 	mtx_lock(&sc->reg_lock);
11189 	if (hw_off_limits(sc))
11190 		rc = ENXIO;
11191 	else {
11192 		rc = 0;
11193 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11194 		    A_TP_TIMER_RESOLUTION));
11195 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11196 	}
11197 	mtx_unlock(&sc->reg_lock);
11198 	if (rc != 0)
11199 		return (rc);
11200 
11201 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11202 
11203 	return (sysctl_handle_int(oidp, &v, 0, req));
11204 }
11205 
11206 static int
11207 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11208 {
11209 	struct adapter *sc = arg1;
11210 	int rc, reg = arg2;
11211 	u_int tre;
11212 	u_long tp_tick_us, v;
11213 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11214 
11215 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11216 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11217 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11218 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11219 
11220 	mtx_lock(&sc->reg_lock);
11221 	if (hw_off_limits(sc))
11222 		rc = ENXIO;
11223 	else {
11224 		rc = 0;
11225 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11226 		tp_tick_us = (cclk_ps << tre) / 1000000;
11227 		if (reg == A_TP_INIT_SRTT)
11228 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11229 		else
11230 			v = tp_tick_us * t4_read_reg(sc, reg);
11231 	}
11232 	mtx_unlock(&sc->reg_lock);
11233 	if (rc != 0)
11234 		return (rc);
11235 	else
11236 		return (sysctl_handle_long(oidp, &v, 0, req));
11237 }
11238 
11239 /*
11240  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11241  * passed to this function.
11242  */
11243 static int
11244 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11245 {
11246 	struct adapter *sc = arg1;
11247 	int rc, idx = arg2;
11248 	u_int v;
11249 
11250 	MPASS(idx >= 0 && idx <= 24);
11251 
11252 	mtx_lock(&sc->reg_lock);
11253 	if (hw_off_limits(sc))
11254 		rc = ENXIO;
11255 	else {
11256 		rc = 0;
11257 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11258 	}
11259 	mtx_unlock(&sc->reg_lock);
11260 	if (rc != 0)
11261 		return (rc);
11262 	else
11263 		return (sysctl_handle_int(oidp, &v, 0, req));
11264 }
11265 
11266 static int
11267 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11268 {
11269 	struct adapter *sc = arg1;
11270 	int rc, idx = arg2;
11271 	u_int shift, v, r;
11272 
11273 	MPASS(idx >= 0 && idx < 16);
11274 
11275 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11276 	shift = (idx & 3) << 3;
11277 	mtx_lock(&sc->reg_lock);
11278 	if (hw_off_limits(sc))
11279 		rc = ENXIO;
11280 	else {
11281 		rc = 0;
11282 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11283 	}
11284 	mtx_unlock(&sc->reg_lock);
11285 	if (rc != 0)
11286 		return (rc);
11287 	else
11288 		return (sysctl_handle_int(oidp, &v, 0, req));
11289 }
11290 
11291 static int
11292 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11293 {
11294 	struct vi_info *vi = arg1;
11295 	struct adapter *sc = vi->adapter;
11296 	int idx, rc, i;
11297 	struct sge_ofld_rxq *ofld_rxq;
11298 	uint8_t v;
11299 
11300 	idx = vi->ofld_tmr_idx;
11301 
11302 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11303 	if (rc != 0 || req->newptr == NULL)
11304 		return (rc);
11305 
11306 	if (idx < 0 || idx >= SGE_NTIMERS)
11307 		return (EINVAL);
11308 
11309 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11310 	    "t4otmr");
11311 	if (rc)
11312 		return (rc);
11313 
11314 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11315 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11316 #ifdef atomic_store_rel_8
11317 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11318 #else
11319 		ofld_rxq->iq.intr_params = v;
11320 #endif
11321 	}
11322 	vi->ofld_tmr_idx = idx;
11323 
11324 	end_synchronized_op(sc, LOCK_HELD);
11325 	return (0);
11326 }
11327 
11328 static int
11329 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11330 {
11331 	struct vi_info *vi = arg1;
11332 	struct adapter *sc = vi->adapter;
11333 	int idx, rc;
11334 
11335 	idx = vi->ofld_pktc_idx;
11336 
11337 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11338 	if (rc != 0 || req->newptr == NULL)
11339 		return (rc);
11340 
11341 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11342 		return (EINVAL);
11343 
11344 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11345 	    "t4opktc");
11346 	if (rc)
11347 		return (rc);
11348 
11349 	if (vi->flags & VI_INIT_DONE)
11350 		rc = EBUSY; /* cannot be changed once the queues are created */
11351 	else
11352 		vi->ofld_pktc_idx = idx;
11353 
11354 	end_synchronized_op(sc, LOCK_HELD);
11355 	return (rc);
11356 }
11357 #endif
11358 
11359 static int
11360 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11361 {
11362 	int rc;
11363 
11364 	if (cntxt->cid > M_CTXTQID)
11365 		return (EINVAL);
11366 
11367 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11368 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11369 		return (EINVAL);
11370 
11371 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11372 	if (rc)
11373 		return (rc);
11374 
11375 	if (hw_off_limits(sc)) {
11376 		rc = ENXIO;
11377 		goto done;
11378 	}
11379 
11380 	if (sc->flags & FW_OK) {
11381 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11382 		    &cntxt->data[0]);
11383 		if (rc == 0)
11384 			goto done;
11385 	}
11386 
11387 	/*
11388 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11389 	 * the backdoor.
11390 	 */
11391 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11392 done:
11393 	end_synchronized_op(sc, 0);
11394 	return (rc);
11395 }
11396 
11397 static int
11398 load_fw(struct adapter *sc, struct t4_data *fw)
11399 {
11400 	int rc;
11401 	uint8_t *fw_data;
11402 
11403 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11404 	if (rc)
11405 		return (rc);
11406 
11407 	if (hw_off_limits(sc)) {
11408 		rc = ENXIO;
11409 		goto done;
11410 	}
11411 
11412 	/*
11413 	 * The firmware, with the sole exception of the memory parity error
11414 	 * handler, runs from memory and not flash.  It is almost always safe to
11415 	 * install a new firmware on a running system.  Just set bit 1 in
11416 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11417 	 */
11418 	if (sc->flags & FULL_INIT_DONE &&
11419 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11420 		rc = EBUSY;
11421 		goto done;
11422 	}
11423 
11424 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11425 
11426 	rc = copyin(fw->data, fw_data, fw->len);
11427 	if (rc == 0)
11428 		rc = -t4_load_fw(sc, fw_data, fw->len);
11429 
11430 	free(fw_data, M_CXGBE);
11431 done:
11432 	end_synchronized_op(sc, 0);
11433 	return (rc);
11434 }
11435 
11436 static int
11437 load_cfg(struct adapter *sc, struct t4_data *cfg)
11438 {
11439 	int rc;
11440 	uint8_t *cfg_data = NULL;
11441 
11442 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11443 	if (rc)
11444 		return (rc);
11445 
11446 	if (hw_off_limits(sc)) {
11447 		rc = ENXIO;
11448 		goto done;
11449 	}
11450 
11451 	if (cfg->len == 0) {
11452 		/* clear */
11453 		rc = -t4_load_cfg(sc, NULL, 0);
11454 		goto done;
11455 	}
11456 
11457 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11458 
11459 	rc = copyin(cfg->data, cfg_data, cfg->len);
11460 	if (rc == 0)
11461 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11462 
11463 	free(cfg_data, M_CXGBE);
11464 done:
11465 	end_synchronized_op(sc, 0);
11466 	return (rc);
11467 }
11468 
11469 static int
11470 load_boot(struct adapter *sc, struct t4_bootrom *br)
11471 {
11472 	int rc;
11473 	uint8_t *br_data = NULL;
11474 	u_int offset;
11475 
11476 	if (br->len > 1024 * 1024)
11477 		return (EFBIG);
11478 
11479 	if (br->pf_offset == 0) {
11480 		/* pfidx */
11481 		if (br->pfidx_addr > 7)
11482 			return (EINVAL);
11483 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11484 		    A_PCIE_PF_EXPROM_OFST)));
11485 	} else if (br->pf_offset == 1) {
11486 		/* offset */
11487 		offset = G_OFFSET(br->pfidx_addr);
11488 	} else {
11489 		return (EINVAL);
11490 	}
11491 
11492 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11493 	if (rc)
11494 		return (rc);
11495 
11496 	if (hw_off_limits(sc)) {
11497 		rc = ENXIO;
11498 		goto done;
11499 	}
11500 
11501 	if (br->len == 0) {
11502 		/* clear */
11503 		rc = -t4_load_boot(sc, NULL, offset, 0);
11504 		goto done;
11505 	}
11506 
11507 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11508 
11509 	rc = copyin(br->data, br_data, br->len);
11510 	if (rc == 0)
11511 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11512 
11513 	free(br_data, M_CXGBE);
11514 done:
11515 	end_synchronized_op(sc, 0);
11516 	return (rc);
11517 }
11518 
11519 static int
11520 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11521 {
11522 	int rc;
11523 	uint8_t *bc_data = NULL;
11524 
11525 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11526 	if (rc)
11527 		return (rc);
11528 
11529 	if (hw_off_limits(sc)) {
11530 		rc = ENXIO;
11531 		goto done;
11532 	}
11533 
11534 	if (bc->len == 0) {
11535 		/* clear */
11536 		rc = -t4_load_bootcfg(sc, NULL, 0);
11537 		goto done;
11538 	}
11539 
11540 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11541 
11542 	rc = copyin(bc->data, bc_data, bc->len);
11543 	if (rc == 0)
11544 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11545 
11546 	free(bc_data, M_CXGBE);
11547 done:
11548 	end_synchronized_op(sc, 0);
11549 	return (rc);
11550 }
11551 
11552 static int
11553 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11554 {
11555 	int rc;
11556 	struct cudbg_init *cudbg;
11557 	void *handle, *buf;
11558 
11559 	/* buf is large, don't block if no memory is available */
11560 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11561 	if (buf == NULL)
11562 		return (ENOMEM);
11563 
11564 	handle = cudbg_alloc_handle();
11565 	if (handle == NULL) {
11566 		rc = ENOMEM;
11567 		goto done;
11568 	}
11569 
11570 	cudbg = cudbg_get_init(handle);
11571 	cudbg->adap = sc;
11572 	cudbg->print = (cudbg_print_cb)printf;
11573 
11574 #ifndef notyet
11575 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11576 	    __func__, dump->wr_flash, dump->len, dump->data);
11577 #endif
11578 
11579 	if (dump->wr_flash)
11580 		cudbg->use_flash = 1;
11581 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11582 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11583 
11584 	rc = cudbg_collect(handle, buf, &dump->len);
11585 	if (rc != 0)
11586 		goto done;
11587 
11588 	rc = copyout(buf, dump->data, dump->len);
11589 done:
11590 	cudbg_free_handle(handle);
11591 	free(buf, M_CXGBE);
11592 	return (rc);
11593 }
11594 
11595 static void
11596 free_offload_policy(struct t4_offload_policy *op)
11597 {
11598 	struct offload_rule *r;
11599 	int i;
11600 
11601 	if (op == NULL)
11602 		return;
11603 
11604 	r = &op->rule[0];
11605 	for (i = 0; i < op->nrules; i++, r++) {
11606 		free(r->bpf_prog.bf_insns, M_CXGBE);
11607 	}
11608 	free(op->rule, M_CXGBE);
11609 	free(op, M_CXGBE);
11610 }
11611 
11612 static int
11613 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11614 {
11615 	int i, rc, len;
11616 	struct t4_offload_policy *op, *old;
11617 	struct bpf_program *bf;
11618 	const struct offload_settings *s;
11619 	struct offload_rule *r;
11620 	void *u;
11621 
11622 	if (!is_offload(sc))
11623 		return (ENODEV);
11624 
11625 	if (uop->nrules == 0) {
11626 		/* Delete installed policies. */
11627 		op = NULL;
11628 		goto set_policy;
11629 	} else if (uop->nrules > 256) { /* arbitrary */
11630 		return (E2BIG);
11631 	}
11632 
11633 	/* Copy userspace offload policy to kernel */
11634 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11635 	op->nrules = uop->nrules;
11636 	len = op->nrules * sizeof(struct offload_rule);
11637 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11638 	rc = copyin(uop->rule, op->rule, len);
11639 	if (rc) {
11640 		free(op->rule, M_CXGBE);
11641 		free(op, M_CXGBE);
11642 		return (rc);
11643 	}
11644 
11645 	r = &op->rule[0];
11646 	for (i = 0; i < op->nrules; i++, r++) {
11647 
11648 		/* Validate open_type */
11649 		if (r->open_type != OPEN_TYPE_LISTEN &&
11650 		    r->open_type != OPEN_TYPE_ACTIVE &&
11651 		    r->open_type != OPEN_TYPE_PASSIVE &&
11652 		    r->open_type != OPEN_TYPE_DONTCARE) {
11653 error:
11654 			/*
11655 			 * Rules 0 to i have malloc'd filters that need to be
11656 			 * freed.  Rules i+1 to nrules have userspace pointers
11657 			 * and should be left alone.
11658 			 */
11659 			op->nrules = i;
11660 			free_offload_policy(op);
11661 			return (rc);
11662 		}
11663 
11664 		/* Validate settings */
11665 		s = &r->settings;
11666 		if ((s->offload != 0 && s->offload != 1) ||
11667 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11668 		    s->sched_class < -1 ||
11669 		    s->sched_class >= sc->chip_params->nsched_cls) {
11670 			rc = EINVAL;
11671 			goto error;
11672 		}
11673 
11674 		bf = &r->bpf_prog;
11675 		u = bf->bf_insns;	/* userspace ptr */
11676 		bf->bf_insns = NULL;
11677 		if (bf->bf_len == 0) {
11678 			/* legal, matches everything */
11679 			continue;
11680 		}
11681 		len = bf->bf_len * sizeof(*bf->bf_insns);
11682 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11683 		rc = copyin(u, bf->bf_insns, len);
11684 		if (rc != 0)
11685 			goto error;
11686 
11687 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11688 			rc = EINVAL;
11689 			goto error;
11690 		}
11691 	}
11692 set_policy:
11693 	rw_wlock(&sc->policy_lock);
11694 	old = sc->policy;
11695 	sc->policy = op;
11696 	rw_wunlock(&sc->policy_lock);
11697 	free_offload_policy(old);
11698 
11699 	return (0);
11700 }
11701 
11702 #define MAX_READ_BUF_SIZE (128 * 1024)
11703 static int
11704 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11705 {
11706 	uint32_t addr, remaining, n;
11707 	uint32_t *buf;
11708 	int rc;
11709 	uint8_t *dst;
11710 
11711 	mtx_lock(&sc->reg_lock);
11712 	if (hw_off_limits(sc))
11713 		rc = ENXIO;
11714 	else
11715 		rc = validate_mem_range(sc, mr->addr, mr->len);
11716 	mtx_unlock(&sc->reg_lock);
11717 	if (rc != 0)
11718 		return (rc);
11719 
11720 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11721 	addr = mr->addr;
11722 	remaining = mr->len;
11723 	dst = (void *)mr->data;
11724 
11725 	while (remaining) {
11726 		n = min(remaining, MAX_READ_BUF_SIZE);
11727 		mtx_lock(&sc->reg_lock);
11728 		if (hw_off_limits(sc))
11729 			rc = ENXIO;
11730 		else
11731 			read_via_memwin(sc, 2, addr, buf, n);
11732 		mtx_unlock(&sc->reg_lock);
11733 		if (rc != 0)
11734 			break;
11735 
11736 		rc = copyout(buf, dst, n);
11737 		if (rc != 0)
11738 			break;
11739 
11740 		dst += n;
11741 		remaining -= n;
11742 		addr += n;
11743 	}
11744 
11745 	free(buf, M_CXGBE);
11746 	return (rc);
11747 }
11748 #undef MAX_READ_BUF_SIZE
11749 
11750 static int
11751 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11752 {
11753 	int rc;
11754 
11755 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11756 		return (EINVAL);
11757 
11758 	if (i2cd->len > sizeof(i2cd->data))
11759 		return (EFBIG);
11760 
11761 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11762 	if (rc)
11763 		return (rc);
11764 	if (hw_off_limits(sc))
11765 		rc = ENXIO;
11766 	else
11767 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11768 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11769 	end_synchronized_op(sc, 0);
11770 
11771 	return (rc);
11772 }
11773 
11774 static int
11775 clear_stats(struct adapter *sc, u_int port_id)
11776 {
11777 	int i, v, chan_map;
11778 	struct port_info *pi;
11779 	struct vi_info *vi;
11780 	struct sge_rxq *rxq;
11781 	struct sge_txq *txq;
11782 	struct sge_wrq *wrq;
11783 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11784 	struct sge_ofld_txq *ofld_txq;
11785 #endif
11786 #ifdef TCP_OFFLOAD
11787 	struct sge_ofld_rxq *ofld_rxq;
11788 #endif
11789 
11790 	if (port_id >= sc->params.nports)
11791 		return (EINVAL);
11792 	pi = sc->port[port_id];
11793 	if (pi == NULL)
11794 		return (EIO);
11795 
11796 	mtx_lock(&sc->reg_lock);
11797 	if (!hw_off_limits(sc)) {
11798 		/* MAC stats */
11799 		t4_clr_port_stats(sc, pi->tx_chan);
11800 		if (is_t6(sc)) {
11801 			if (pi->fcs_reg != -1)
11802 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11803 			else
11804 				pi->stats.rx_fcs_err = 0;
11805 		}
11806 		for_each_vi(pi, v, vi) {
11807 			if (vi->flags & VI_INIT_DONE)
11808 				t4_clr_vi_stats(sc, vi->vin);
11809 		}
11810 		chan_map = pi->rx_e_chan_map;
11811 		v = 0;	/* reuse */
11812 		while (chan_map) {
11813 			i = ffs(chan_map) - 1;
11814 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11815 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11816 			chan_map &= ~(1 << i);
11817 		}
11818 	}
11819 	mtx_unlock(&sc->reg_lock);
11820 	pi->tx_parse_error = 0;
11821 	pi->tnl_cong_drops = 0;
11822 
11823 	/*
11824 	 * Since this command accepts a port, clear stats for
11825 	 * all VIs on this port.
11826 	 */
11827 	for_each_vi(pi, v, vi) {
11828 		if (vi->flags & VI_INIT_DONE) {
11829 
11830 			for_each_rxq(vi, i, rxq) {
11831 #if defined(INET) || defined(INET6)
11832 				rxq->lro.lro_queued = 0;
11833 				rxq->lro.lro_flushed = 0;
11834 #endif
11835 				rxq->rxcsum = 0;
11836 				rxq->vlan_extraction = 0;
11837 				rxq->vxlan_rxcsum = 0;
11838 
11839 				rxq->fl.cl_allocated = 0;
11840 				rxq->fl.cl_recycled = 0;
11841 				rxq->fl.cl_fast_recycled = 0;
11842 			}
11843 
11844 			for_each_txq(vi, i, txq) {
11845 				txq->txcsum = 0;
11846 				txq->tso_wrs = 0;
11847 				txq->vlan_insertion = 0;
11848 				txq->imm_wrs = 0;
11849 				txq->sgl_wrs = 0;
11850 				txq->txpkt_wrs = 0;
11851 				txq->txpkts0_wrs = 0;
11852 				txq->txpkts1_wrs = 0;
11853 				txq->txpkts0_pkts = 0;
11854 				txq->txpkts1_pkts = 0;
11855 				txq->txpkts_flush = 0;
11856 				txq->raw_wrs = 0;
11857 				txq->vxlan_tso_wrs = 0;
11858 				txq->vxlan_txcsum = 0;
11859 				txq->kern_tls_records = 0;
11860 				txq->kern_tls_short = 0;
11861 				txq->kern_tls_partial = 0;
11862 				txq->kern_tls_full = 0;
11863 				txq->kern_tls_octets = 0;
11864 				txq->kern_tls_waste = 0;
11865 				txq->kern_tls_options = 0;
11866 				txq->kern_tls_header = 0;
11867 				txq->kern_tls_fin = 0;
11868 				txq->kern_tls_fin_short = 0;
11869 				txq->kern_tls_cbc = 0;
11870 				txq->kern_tls_gcm = 0;
11871 				mp_ring_reset_stats(txq->r);
11872 			}
11873 
11874 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11875 			for_each_ofld_txq(vi, i, ofld_txq) {
11876 				ofld_txq->wrq.tx_wrs_direct = 0;
11877 				ofld_txq->wrq.tx_wrs_copied = 0;
11878 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
11879 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
11880 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
11881 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
11882 			}
11883 #endif
11884 #ifdef TCP_OFFLOAD
11885 			for_each_ofld_rxq(vi, i, ofld_rxq) {
11886 				ofld_rxq->fl.cl_allocated = 0;
11887 				ofld_rxq->fl.cl_recycled = 0;
11888 				ofld_rxq->fl.cl_fast_recycled = 0;
11889 				ofld_rxq->rx_toe_tls_records = 0;
11890 				ofld_rxq->rx_toe_tls_octets = 0;
11891 			}
11892 #endif
11893 
11894 			if (IS_MAIN_VI(vi)) {
11895 				wrq = &sc->sge.ctrlq[pi->port_id];
11896 				wrq->tx_wrs_direct = 0;
11897 				wrq->tx_wrs_copied = 0;
11898 			}
11899 		}
11900 	}
11901 
11902 	return (0);
11903 }
11904 
11905 int
11906 t4_os_find_pci_capability(struct adapter *sc, int cap)
11907 {
11908 	int i;
11909 
11910 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
11911 }
11912 
11913 int
11914 t4_os_pci_save_state(struct adapter *sc)
11915 {
11916 	device_t dev;
11917 	struct pci_devinfo *dinfo;
11918 
11919 	dev = sc->dev;
11920 	dinfo = device_get_ivars(dev);
11921 
11922 	pci_cfg_save(dev, dinfo, 0);
11923 	return (0);
11924 }
11925 
11926 int
11927 t4_os_pci_restore_state(struct adapter *sc)
11928 {
11929 	device_t dev;
11930 	struct pci_devinfo *dinfo;
11931 
11932 	dev = sc->dev;
11933 	dinfo = device_get_ivars(dev);
11934 
11935 	pci_cfg_restore(dev, dinfo);
11936 	return (0);
11937 }
11938 
11939 void
11940 t4_os_portmod_changed(struct port_info *pi)
11941 {
11942 	struct adapter *sc = pi->adapter;
11943 	struct vi_info *vi;
11944 	struct ifnet *ifp;
11945 	static const char *mod_str[] = {
11946 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
11947 	};
11948 
11949 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
11950 	    ("%s: port_type %u", __func__, pi->port_type));
11951 
11952 	vi = &pi->vi[0];
11953 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
11954 		PORT_LOCK(pi);
11955 		build_medialist(pi);
11956 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
11957 			fixup_link_config(pi);
11958 			apply_link_config(pi);
11959 		}
11960 		PORT_UNLOCK(pi);
11961 		end_synchronized_op(sc, LOCK_HELD);
11962 	}
11963 
11964 	ifp = vi->ifp;
11965 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
11966 		if_printf(ifp, "transceiver unplugged.\n");
11967 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
11968 		if_printf(ifp, "unknown transceiver inserted.\n");
11969 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
11970 		if_printf(ifp, "unsupported transceiver inserted.\n");
11971 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
11972 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
11973 		    port_top_speed(pi), mod_str[pi->mod_type]);
11974 	} else {
11975 		if_printf(ifp, "transceiver (type %d) inserted.\n",
11976 		    pi->mod_type);
11977 	}
11978 }
11979 
11980 void
11981 t4_os_link_changed(struct port_info *pi)
11982 {
11983 	struct vi_info *vi;
11984 	struct ifnet *ifp;
11985 	struct link_config *lc = &pi->link_cfg;
11986 	struct adapter *sc = pi->adapter;
11987 	int v;
11988 
11989 	PORT_LOCK_ASSERT_OWNED(pi);
11990 
11991 	if (is_t6(sc)) {
11992 		if (lc->link_ok) {
11993 			if (lc->speed > 25000 ||
11994 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
11995 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
11996 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
11997 			} else {
11998 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
11999 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12000 			}
12001 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12002 			pi->stats.rx_fcs_err = 0;
12003 		} else {
12004 			pi->fcs_reg = -1;
12005 		}
12006 	} else {
12007 		MPASS(pi->fcs_reg != -1);
12008 		MPASS(pi->fcs_base == 0);
12009 	}
12010 
12011 	for_each_vi(pi, v, vi) {
12012 		ifp = vi->ifp;
12013 		if (ifp == NULL)
12014 			continue;
12015 
12016 		if (lc->link_ok) {
12017 			ifp->if_baudrate = IF_Mbps(lc->speed);
12018 			if_link_state_change(ifp, LINK_STATE_UP);
12019 		} else {
12020 			if_link_state_change(ifp, LINK_STATE_DOWN);
12021 		}
12022 	}
12023 }
12024 
12025 void
12026 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12027 {
12028 	struct adapter *sc;
12029 
12030 	sx_slock(&t4_list_lock);
12031 	SLIST_FOREACH(sc, &t4_list, link) {
12032 		/*
12033 		 * func should not make any assumptions about what state sc is
12034 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12035 		 */
12036 		func(sc, arg);
12037 	}
12038 	sx_sunlock(&t4_list_lock);
12039 }
12040 
12041 static int
12042 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12043     struct thread *td)
12044 {
12045 	int rc;
12046 	struct adapter *sc = dev->si_drv1;
12047 
12048 	rc = priv_check(td, PRIV_DRIVER);
12049 	if (rc != 0)
12050 		return (rc);
12051 
12052 	switch (cmd) {
12053 	case CHELSIO_T4_GETREG: {
12054 		struct t4_reg *edata = (struct t4_reg *)data;
12055 
12056 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12057 			return (EFAULT);
12058 
12059 		mtx_lock(&sc->reg_lock);
12060 		if (hw_off_limits(sc))
12061 			rc = ENXIO;
12062 		else if (edata->size == 4)
12063 			edata->val = t4_read_reg(sc, edata->addr);
12064 		else if (edata->size == 8)
12065 			edata->val = t4_read_reg64(sc, edata->addr);
12066 		else
12067 			rc = EINVAL;
12068 		mtx_unlock(&sc->reg_lock);
12069 
12070 		break;
12071 	}
12072 	case CHELSIO_T4_SETREG: {
12073 		struct t4_reg *edata = (struct t4_reg *)data;
12074 
12075 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12076 			return (EFAULT);
12077 
12078 		mtx_lock(&sc->reg_lock);
12079 		if (hw_off_limits(sc))
12080 			rc = ENXIO;
12081 		else if (edata->size == 4) {
12082 			if (edata->val & 0xffffffff00000000)
12083 				rc = EINVAL;
12084 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12085 		} else if (edata->size == 8)
12086 			t4_write_reg64(sc, edata->addr, edata->val);
12087 		else
12088 			rc = EINVAL;
12089 		mtx_unlock(&sc->reg_lock);
12090 
12091 		break;
12092 	}
12093 	case CHELSIO_T4_REGDUMP: {
12094 		struct t4_regdump *regs = (struct t4_regdump *)data;
12095 		int reglen = t4_get_regs_len(sc);
12096 		uint8_t *buf;
12097 
12098 		if (regs->len < reglen) {
12099 			regs->len = reglen; /* hint to the caller */
12100 			return (ENOBUFS);
12101 		}
12102 
12103 		regs->len = reglen;
12104 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12105 		mtx_lock(&sc->reg_lock);
12106 		if (hw_off_limits(sc))
12107 			rc = ENXIO;
12108 		else
12109 			get_regs(sc, regs, buf);
12110 		mtx_unlock(&sc->reg_lock);
12111 		if (rc == 0)
12112 			rc = copyout(buf, regs->data, reglen);
12113 		free(buf, M_CXGBE);
12114 		break;
12115 	}
12116 	case CHELSIO_T4_GET_FILTER_MODE:
12117 		rc = get_filter_mode(sc, (uint32_t *)data);
12118 		break;
12119 	case CHELSIO_T4_SET_FILTER_MODE:
12120 		rc = set_filter_mode(sc, *(uint32_t *)data);
12121 		break;
12122 	case CHELSIO_T4_SET_FILTER_MASK:
12123 		rc = set_filter_mask(sc, *(uint32_t *)data);
12124 		break;
12125 	case CHELSIO_T4_GET_FILTER:
12126 		rc = get_filter(sc, (struct t4_filter *)data);
12127 		break;
12128 	case CHELSIO_T4_SET_FILTER:
12129 		rc = set_filter(sc, (struct t4_filter *)data);
12130 		break;
12131 	case CHELSIO_T4_DEL_FILTER:
12132 		rc = del_filter(sc, (struct t4_filter *)data);
12133 		break;
12134 	case CHELSIO_T4_GET_SGE_CONTEXT:
12135 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12136 		break;
12137 	case CHELSIO_T4_LOAD_FW:
12138 		rc = load_fw(sc, (struct t4_data *)data);
12139 		break;
12140 	case CHELSIO_T4_GET_MEM:
12141 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12142 		break;
12143 	case CHELSIO_T4_GET_I2C:
12144 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12145 		break;
12146 	case CHELSIO_T4_CLEAR_STATS:
12147 		rc = clear_stats(sc, *(uint32_t *)data);
12148 		break;
12149 	case CHELSIO_T4_SCHED_CLASS:
12150 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12151 		break;
12152 	case CHELSIO_T4_SCHED_QUEUE:
12153 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12154 		break;
12155 	case CHELSIO_T4_GET_TRACER:
12156 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12157 		break;
12158 	case CHELSIO_T4_SET_TRACER:
12159 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12160 		break;
12161 	case CHELSIO_T4_LOAD_CFG:
12162 		rc = load_cfg(sc, (struct t4_data *)data);
12163 		break;
12164 	case CHELSIO_T4_LOAD_BOOT:
12165 		rc = load_boot(sc, (struct t4_bootrom *)data);
12166 		break;
12167 	case CHELSIO_T4_LOAD_BOOTCFG:
12168 		rc = load_bootcfg(sc, (struct t4_data *)data);
12169 		break;
12170 	case CHELSIO_T4_CUDBG_DUMP:
12171 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12172 		break;
12173 	case CHELSIO_T4_SET_OFLD_POLICY:
12174 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12175 		break;
12176 	default:
12177 		rc = ENOTTY;
12178 	}
12179 
12180 	return (rc);
12181 }
12182 
12183 #ifdef TCP_OFFLOAD
12184 static int
12185 toe_capability(struct vi_info *vi, bool enable)
12186 {
12187 	int rc;
12188 	struct port_info *pi = vi->pi;
12189 	struct adapter *sc = pi->adapter;
12190 
12191 	ASSERT_SYNCHRONIZED_OP(sc);
12192 
12193 	if (!is_offload(sc))
12194 		return (ENODEV);
12195 	if (hw_off_limits(sc))
12196 		return (ENXIO);
12197 
12198 	if (enable) {
12199 #ifdef KERN_TLS
12200 		if (sc->flags & KERN_TLS_ON) {
12201 			int i, j, n;
12202 			struct port_info *p;
12203 			struct vi_info *v;
12204 
12205 			/*
12206 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12207 			 * on any ifnet.
12208 			 */
12209 			n = 0;
12210 			for_each_port(sc, i) {
12211 				p = sc->port[i];
12212 				for_each_vi(p, j, v) {
12213 					if (v->ifp->if_capenable & IFCAP_TXTLS) {
12214 						CH_WARN(sc,
12215 						    "%s has NIC TLS enabled.\n",
12216 						    device_get_nameunit(v->dev));
12217 						n++;
12218 					}
12219 				}
12220 			}
12221 			if (n > 0) {
12222 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12223 				    "associated with this adapter before "
12224 				    "trying to enable TOE.\n");
12225 				return (EAGAIN);
12226 			}
12227 			rc = t4_config_kern_tls(sc, false);
12228 			if (rc)
12229 				return (rc);
12230 		}
12231 #endif
12232 		if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
12233 			/* TOE is already enabled. */
12234 			return (0);
12235 		}
12236 
12237 		/*
12238 		 * We need the port's queues around so that we're able to send
12239 		 * and receive CPLs to/from the TOE even if the ifnet for this
12240 		 * port has never been UP'd administratively.
12241 		 */
12242 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12243 			return (rc);
12244 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12245 		    ((rc = vi_init(&pi->vi[0])) != 0))
12246 			return (rc);
12247 
12248 		if (isset(&sc->offload_map, pi->port_id)) {
12249 			/* TOE is enabled on another VI of this port. */
12250 			pi->uld_vis++;
12251 			return (0);
12252 		}
12253 
12254 		if (!uld_active(sc, ULD_TOM)) {
12255 			rc = t4_activate_uld(sc, ULD_TOM);
12256 			if (rc == EAGAIN) {
12257 				log(LOG_WARNING,
12258 				    "You must kldload t4_tom.ko before trying "
12259 				    "to enable TOE on a cxgbe interface.\n");
12260 			}
12261 			if (rc != 0)
12262 				return (rc);
12263 			KASSERT(sc->tom_softc != NULL,
12264 			    ("%s: TOM activated but softc NULL", __func__));
12265 			KASSERT(uld_active(sc, ULD_TOM),
12266 			    ("%s: TOM activated but flag not set", __func__));
12267 		}
12268 
12269 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12270 		if (!uld_active(sc, ULD_IWARP))
12271 			(void) t4_activate_uld(sc, ULD_IWARP);
12272 		if (!uld_active(sc, ULD_ISCSI))
12273 			(void) t4_activate_uld(sc, ULD_ISCSI);
12274 
12275 		pi->uld_vis++;
12276 		setbit(&sc->offload_map, pi->port_id);
12277 	} else {
12278 		pi->uld_vis--;
12279 
12280 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12281 			return (0);
12282 
12283 		KASSERT(uld_active(sc, ULD_TOM),
12284 		    ("%s: TOM never initialized?", __func__));
12285 		clrbit(&sc->offload_map, pi->port_id);
12286 	}
12287 
12288 	return (0);
12289 }
12290 
12291 /*
12292  * Add an upper layer driver to the global list.
12293  */
12294 int
12295 t4_register_uld(struct uld_info *ui)
12296 {
12297 	int rc = 0;
12298 	struct uld_info *u;
12299 
12300 	sx_xlock(&t4_uld_list_lock);
12301 	SLIST_FOREACH(u, &t4_uld_list, link) {
12302 	    if (u->uld_id == ui->uld_id) {
12303 		    rc = EEXIST;
12304 		    goto done;
12305 	    }
12306 	}
12307 
12308 	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
12309 	ui->refcount = 0;
12310 done:
12311 	sx_xunlock(&t4_uld_list_lock);
12312 	return (rc);
12313 }
12314 
12315 int
12316 t4_unregister_uld(struct uld_info *ui)
12317 {
12318 	int rc = EINVAL;
12319 	struct uld_info *u;
12320 
12321 	sx_xlock(&t4_uld_list_lock);
12322 
12323 	SLIST_FOREACH(u, &t4_uld_list, link) {
12324 	    if (u == ui) {
12325 		    if (ui->refcount > 0) {
12326 			    rc = EBUSY;
12327 			    goto done;
12328 		    }
12329 
12330 		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
12331 		    rc = 0;
12332 		    goto done;
12333 	    }
12334 	}
12335 done:
12336 	sx_xunlock(&t4_uld_list_lock);
12337 	return (rc);
12338 }
12339 
12340 int
12341 t4_activate_uld(struct adapter *sc, int id)
12342 {
12343 	int rc;
12344 	struct uld_info *ui;
12345 
12346 	ASSERT_SYNCHRONIZED_OP(sc);
12347 
12348 	if (id < 0 || id > ULD_MAX)
12349 		return (EINVAL);
12350 	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
12351 
12352 	sx_slock(&t4_uld_list_lock);
12353 
12354 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12355 		if (ui->uld_id == id) {
12356 			if (!(sc->flags & FULL_INIT_DONE)) {
12357 				rc = adapter_init(sc);
12358 				if (rc != 0)
12359 					break;
12360 			}
12361 
12362 			rc = ui->activate(sc);
12363 			if (rc == 0) {
12364 				setbit(&sc->active_ulds, id);
12365 				ui->refcount++;
12366 			}
12367 			break;
12368 		}
12369 	}
12370 
12371 	sx_sunlock(&t4_uld_list_lock);
12372 
12373 	return (rc);
12374 }
12375 
12376 int
12377 t4_deactivate_uld(struct adapter *sc, int id)
12378 {
12379 	int rc;
12380 	struct uld_info *ui;
12381 
12382 	ASSERT_SYNCHRONIZED_OP(sc);
12383 
12384 	if (id < 0 || id > ULD_MAX)
12385 		return (EINVAL);
12386 	rc = ENXIO;
12387 
12388 	sx_slock(&t4_uld_list_lock);
12389 
12390 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12391 		if (ui->uld_id == id) {
12392 			rc = ui->deactivate(sc);
12393 			if (rc == 0) {
12394 				clrbit(&sc->active_ulds, id);
12395 				ui->refcount--;
12396 			}
12397 			break;
12398 		}
12399 	}
12400 
12401 	sx_sunlock(&t4_uld_list_lock);
12402 
12403 	return (rc);
12404 }
12405 
12406 static void
12407 t4_async_event(void *arg, int n)
12408 {
12409 	struct uld_info *ui;
12410 	struct adapter *sc = (struct adapter *)arg;
12411 
12412 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
12413 		return;
12414 	sx_slock(&t4_uld_list_lock);
12415 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12416 		if (ui->uld_id == ULD_IWARP) {
12417 			ui->async_event(sc);
12418 			break;
12419 		}
12420 	}
12421 	sx_sunlock(&t4_uld_list_lock);
12422 	end_synchronized_op(sc, 0);
12423 }
12424 
12425 int
12426 uld_active(struct adapter *sc, int uld_id)
12427 {
12428 
12429 	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
12430 
12431 	return (isset(&sc->active_ulds, uld_id));
12432 }
12433 #endif
12434 
12435 #ifdef KERN_TLS
12436 static int
12437 ktls_capability(struct adapter *sc, bool enable)
12438 {
12439 	ASSERT_SYNCHRONIZED_OP(sc);
12440 
12441 	if (!is_ktls(sc))
12442 		return (ENODEV);
12443 	if (hw_off_limits(sc))
12444 		return (ENXIO);
12445 
12446 	if (enable) {
12447 		if (sc->flags & KERN_TLS_ON)
12448 			return (0);	/* already on */
12449 		if (sc->offload_map != 0) {
12450 			CH_WARN(sc,
12451 			    "Disable TOE on all interfaces associated with "
12452 			    "this adapter before trying to enable NIC TLS.\n");
12453 			return (EAGAIN);
12454 		}
12455 		return (t4_config_kern_tls(sc, true));
12456 	} else {
12457 		/*
12458 		 * Nothing to do for disable.  If TOE is enabled sometime later
12459 		 * then toe_capability will reconfigure the hardware.
12460 		 */
12461 		return (0);
12462 	}
12463 }
12464 #endif
12465 
12466 /*
12467  * t  = ptr to tunable.
12468  * nc = number of CPUs.
12469  * c  = compiled in default for that tunable.
12470  */
12471 static void
12472 calculate_nqueues(int *t, int nc, const int c)
12473 {
12474 	int nq;
12475 
12476 	if (*t > 0)
12477 		return;
12478 	nq = *t < 0 ? -*t : c;
12479 	*t = min(nc, nq);
12480 }
12481 
12482 /*
12483  * Come up with reasonable defaults for some of the tunables, provided they're
12484  * not set by the user (in which case we'll use the values as is).
12485  */
12486 static void
12487 tweak_tunables(void)
12488 {
12489 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12490 
12491 	if (t4_ntxq < 1) {
12492 #ifdef RSS
12493 		t4_ntxq = rss_getnumbuckets();
12494 #else
12495 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12496 #endif
12497 	}
12498 
12499 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12500 
12501 	if (t4_nrxq < 1) {
12502 #ifdef RSS
12503 		t4_nrxq = rss_getnumbuckets();
12504 #else
12505 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12506 #endif
12507 	}
12508 
12509 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12510 
12511 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12512 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12513 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12514 #endif
12515 #ifdef TCP_OFFLOAD
12516 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12517 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12518 #endif
12519 
12520 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12521 	if (t4_toecaps_allowed == -1)
12522 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12523 #else
12524 	if (t4_toecaps_allowed == -1)
12525 		t4_toecaps_allowed = 0;
12526 #endif
12527 
12528 #ifdef TCP_OFFLOAD
12529 	if (t4_rdmacaps_allowed == -1) {
12530 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12531 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12532 	}
12533 
12534 	if (t4_iscsicaps_allowed == -1) {
12535 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12536 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12537 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12538 	}
12539 
12540 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12541 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12542 
12543 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12544 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12545 
12546 	if (t4_toe_tls_rx_timeout < 0)
12547 		t4_toe_tls_rx_timeout = 0;
12548 #else
12549 	if (t4_rdmacaps_allowed == -1)
12550 		t4_rdmacaps_allowed = 0;
12551 
12552 	if (t4_iscsicaps_allowed == -1)
12553 		t4_iscsicaps_allowed = 0;
12554 #endif
12555 
12556 #ifdef DEV_NETMAP
12557 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12558 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12559 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12560 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12561 #endif
12562 
12563 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12564 		t4_tmr_idx = TMR_IDX;
12565 
12566 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12567 		t4_pktc_idx = PKTC_IDX;
12568 
12569 	if (t4_qsize_txq < 128)
12570 		t4_qsize_txq = 128;
12571 
12572 	if (t4_qsize_rxq < 128)
12573 		t4_qsize_rxq = 128;
12574 	while (t4_qsize_rxq & 7)
12575 		t4_qsize_rxq++;
12576 
12577 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12578 
12579 	/*
12580 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12581 	 * VI for the port.  The rest are additional virtual interfaces on the
12582 	 * same physical port.  Note that the main VI does not have native
12583 	 * netmap support but the extra VIs do.
12584 	 *
12585 	 * Limit the number of VIs per port to the number of available
12586 	 * MAC addresses per port.
12587 	 */
12588 	if (t4_num_vis < 1)
12589 		t4_num_vis = 1;
12590 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12591 		t4_num_vis = nitems(vi_mac_funcs);
12592 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12593 	}
12594 
12595 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12596 		pcie_relaxed_ordering = 1;
12597 #if defined(__i386__) || defined(__amd64__)
12598 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12599 			pcie_relaxed_ordering = 0;
12600 #endif
12601 	}
12602 }
12603 
12604 #ifdef DDB
12605 static void
12606 t4_dump_tcb(struct adapter *sc, int tid)
12607 {
12608 	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
12609 
12610 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12611 	save = t4_read_reg(sc, reg);
12612 	base = sc->memwin[2].mw_base;
12613 
12614 	/* Dump TCB for the tid */
12615 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12616 	tcb_addr += tid * TCB_SIZE;
12617 
12618 	if (is_t4(sc)) {
12619 		pf = 0;
12620 		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
12621 	} else {
12622 		pf = V_PFNUM(sc->pf);
12623 		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
12624 	}
12625 	t4_write_reg(sc, reg, win_pos | pf);
12626 	t4_read_reg(sc, reg);
12627 
12628 	off = tcb_addr - win_pos;
12629 	for (i = 0; i < 4; i++) {
12630 		uint32_t buf[8];
12631 		for (j = 0; j < 8; j++, off += 4)
12632 			buf[j] = htonl(t4_read_reg(sc, base + off));
12633 
12634 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12635 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12636 		    buf[7]);
12637 	}
12638 
12639 	t4_write_reg(sc, reg, save);
12640 	t4_read_reg(sc, reg);
12641 }
12642 
12643 static void
12644 t4_dump_devlog(struct adapter *sc)
12645 {
12646 	struct devlog_params *dparams = &sc->params.devlog;
12647 	struct fw_devlog_e e;
12648 	int i, first, j, m, nentries, rc;
12649 	uint64_t ftstamp = UINT64_MAX;
12650 
12651 	if (dparams->start == 0) {
12652 		db_printf("devlog params not valid\n");
12653 		return;
12654 	}
12655 
12656 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12657 	m = fwmtype_to_hwmtype(dparams->memtype);
12658 
12659 	/* Find the first entry. */
12660 	first = -1;
12661 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12662 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12663 		    sizeof(e), (void *)&e);
12664 		if (rc != 0)
12665 			break;
12666 
12667 		if (e.timestamp == 0)
12668 			break;
12669 
12670 		e.timestamp = be64toh(e.timestamp);
12671 		if (e.timestamp < ftstamp) {
12672 			ftstamp = e.timestamp;
12673 			first = i;
12674 		}
12675 	}
12676 
12677 	if (first == -1)
12678 		return;
12679 
12680 	i = first;
12681 	do {
12682 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12683 		    sizeof(e), (void *)&e);
12684 		if (rc != 0)
12685 			return;
12686 
12687 		if (e.timestamp == 0)
12688 			return;
12689 
12690 		e.timestamp = be64toh(e.timestamp);
12691 		e.seqno = be32toh(e.seqno);
12692 		for (j = 0; j < 8; j++)
12693 			e.params[j] = be32toh(e.params[j]);
12694 
12695 		db_printf("%10d  %15ju  %8s  %8s  ",
12696 		    e.seqno, e.timestamp,
12697 		    (e.level < nitems(devlog_level_strings) ?
12698 			devlog_level_strings[e.level] : "UNKNOWN"),
12699 		    (e.facility < nitems(devlog_facility_strings) ?
12700 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12701 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12702 		    e.params[3], e.params[4], e.params[5], e.params[6],
12703 		    e.params[7]);
12704 
12705 		if (++i == nentries)
12706 			i = 0;
12707 	} while (i != first && !db_pager_quit);
12708 }
12709 
12710 static struct command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
12711 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
12712 
12713 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
12714 {
12715 	device_t dev;
12716 	int t;
12717 	bool valid;
12718 
12719 	valid = false;
12720 	t = db_read_token();
12721 	if (t == tIDENT) {
12722 		dev = device_lookup_by_name(db_tok_string);
12723 		valid = true;
12724 	}
12725 	db_skip_to_eol();
12726 	if (!valid) {
12727 		db_printf("usage: show t4 devlog <nexus>\n");
12728 		return;
12729 	}
12730 
12731 	if (dev == NULL) {
12732 		db_printf("device not found\n");
12733 		return;
12734 	}
12735 
12736 	t4_dump_devlog(device_get_softc(dev));
12737 }
12738 
12739 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
12740 {
12741 	device_t dev;
12742 	int radix, tid, t;
12743 	bool valid;
12744 
12745 	valid = false;
12746 	radix = db_radix;
12747 	db_radix = 10;
12748 	t = db_read_token();
12749 	if (t == tIDENT) {
12750 		dev = device_lookup_by_name(db_tok_string);
12751 		t = db_read_token();
12752 		if (t == tNUMBER) {
12753 			tid = db_tok_number;
12754 			valid = true;
12755 		}
12756 	}
12757 	db_radix = radix;
12758 	db_skip_to_eol();
12759 	if (!valid) {
12760 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
12761 		return;
12762 	}
12763 
12764 	if (dev == NULL) {
12765 		db_printf("device not found\n");
12766 		return;
12767 	}
12768 	if (tid < 0) {
12769 		db_printf("invalid tid\n");
12770 		return;
12771 	}
12772 
12773 	t4_dump_tcb(device_get_softc(dev), tid);
12774 }
12775 #endif
12776 
12777 static eventhandler_tag vxlan_start_evtag;
12778 static eventhandler_tag vxlan_stop_evtag;
12779 
12780 struct vxlan_evargs {
12781 	struct ifnet *ifp;
12782 	uint16_t port;
12783 };
12784 
12785 static void
12786 enable_vxlan_rx(struct adapter *sc)
12787 {
12788 	int i, rc;
12789 	struct port_info *pi;
12790 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
12791 
12792 	ASSERT_SYNCHRONIZED_OP(sc);
12793 
12794 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
12795 	    F_VXLAN_EN);
12796 	for_each_port(sc, i) {
12797 		pi = sc->port[i];
12798 		if (pi->vxlan_tcam_entry == true)
12799 			continue;
12800 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
12801 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
12802 		    true);
12803 		if (rc < 0) {
12804 			rc = -rc;
12805 			CH_ERR(&pi->vi[0],
12806 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
12807 		} else {
12808 			MPASS(rc == sc->rawf_base + pi->port_id);
12809 			pi->vxlan_tcam_entry = true;
12810 		}
12811 	}
12812 }
12813 
12814 static void
12815 t4_vxlan_start(struct adapter *sc, void *arg)
12816 {
12817 	struct vxlan_evargs *v = arg;
12818 
12819 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
12820 		return;
12821 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
12822 		return;
12823 
12824 	if (sc->vxlan_refcount == 0) {
12825 		sc->vxlan_port = v->port;
12826 		sc->vxlan_refcount = 1;
12827 		if (!hw_off_limits(sc))
12828 			enable_vxlan_rx(sc);
12829 	} else if (sc->vxlan_port == v->port) {
12830 		sc->vxlan_refcount++;
12831 	} else {
12832 		CH_ERR(sc, "VXLAN already configured on port  %d; "
12833 		    "ignoring attempt to configure it on port %d\n",
12834 		    sc->vxlan_port, v->port);
12835 	}
12836 	end_synchronized_op(sc, 0);
12837 }
12838 
12839 static void
12840 t4_vxlan_stop(struct adapter *sc, void *arg)
12841 {
12842 	struct vxlan_evargs *v = arg;
12843 
12844 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
12845 		return;
12846 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
12847 		return;
12848 
12849 	/*
12850 	 * VXLANs may have been configured before the driver was loaded so we
12851 	 * may see more stops than starts.  This is not handled cleanly but at
12852 	 * least we keep the refcount sane.
12853 	 */
12854 	if (sc->vxlan_port != v->port)
12855 		goto done;
12856 	if (sc->vxlan_refcount == 0) {
12857 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
12858 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
12859 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
12860 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
12861 done:
12862 	end_synchronized_op(sc, 0);
12863 }
12864 
12865 static void
12866 t4_vxlan_start_handler(void *arg __unused, struct ifnet *ifp,
12867     sa_family_t family, u_int port)
12868 {
12869 	struct vxlan_evargs v;
12870 
12871 	MPASS(family == AF_INET || family == AF_INET6);
12872 	v.ifp = ifp;
12873 	v.port = port;
12874 
12875 	t4_iterate(t4_vxlan_start, &v);
12876 }
12877 
12878 static void
12879 t4_vxlan_stop_handler(void *arg __unused, struct ifnet *ifp, sa_family_t family,
12880     u_int port)
12881 {
12882 	struct vxlan_evargs v;
12883 
12884 	MPASS(family == AF_INET || family == AF_INET6);
12885 	v.ifp = ifp;
12886 	v.port = port;
12887 
12888 	t4_iterate(t4_vxlan_stop, &v);
12889 }
12890 
12891 
12892 static struct sx mlu;	/* mod load unload */
12893 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
12894 
12895 static int
12896 mod_event(module_t mod, int cmd, void *arg)
12897 {
12898 	int rc = 0;
12899 	static int loaded = 0;
12900 
12901 	switch (cmd) {
12902 	case MOD_LOAD:
12903 		sx_xlock(&mlu);
12904 		if (loaded++ == 0) {
12905 			t4_sge_modload();
12906 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
12907 			    t4_filter_rpl, CPL_COOKIE_FILTER);
12908 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
12909 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
12910 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
12911 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
12912 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
12913 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
12914 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
12915 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
12916 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
12917 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
12918 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
12919 			    do_smt_write_rpl);
12920 			sx_init(&t4_list_lock, "T4/T5 adapters");
12921 			SLIST_INIT(&t4_list);
12922 			callout_init(&fatal_callout, 1);
12923 #ifdef TCP_OFFLOAD
12924 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
12925 			SLIST_INIT(&t4_uld_list);
12926 #endif
12927 #ifdef INET6
12928 			t4_clip_modload();
12929 #endif
12930 #ifdef KERN_TLS
12931 			t6_ktls_modload();
12932 #endif
12933 			t4_tracer_modload();
12934 			tweak_tunables();
12935 			vxlan_start_evtag =
12936 			    EVENTHANDLER_REGISTER(vxlan_start,
12937 				t4_vxlan_start_handler, NULL,
12938 				EVENTHANDLER_PRI_ANY);
12939 			vxlan_stop_evtag =
12940 			    EVENTHANDLER_REGISTER(vxlan_stop,
12941 				t4_vxlan_stop_handler, NULL,
12942 				EVENTHANDLER_PRI_ANY);
12943 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
12944 			    taskqueue_thread_enqueue, &reset_tq);
12945 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
12946 			    "t4_rst_thr");
12947 		}
12948 		sx_xunlock(&mlu);
12949 		break;
12950 
12951 	case MOD_UNLOAD:
12952 		sx_xlock(&mlu);
12953 		if (--loaded == 0) {
12954 			int tries;
12955 
12956 			taskqueue_free(reset_tq);
12957 			sx_slock(&t4_list_lock);
12958 			if (!SLIST_EMPTY(&t4_list)) {
12959 				rc = EBUSY;
12960 				sx_sunlock(&t4_list_lock);
12961 				goto done_unload;
12962 			}
12963 #ifdef TCP_OFFLOAD
12964 			sx_slock(&t4_uld_list_lock);
12965 			if (!SLIST_EMPTY(&t4_uld_list)) {
12966 				rc = EBUSY;
12967 				sx_sunlock(&t4_uld_list_lock);
12968 				sx_sunlock(&t4_list_lock);
12969 				goto done_unload;
12970 			}
12971 #endif
12972 			tries = 0;
12973 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
12974 				uprintf("%ju clusters with custom free routine "
12975 				    "still is use.\n", t4_sge_extfree_refs());
12976 				pause("t4unload", 2 * hz);
12977 			}
12978 #ifdef TCP_OFFLOAD
12979 			sx_sunlock(&t4_uld_list_lock);
12980 #endif
12981 			sx_sunlock(&t4_list_lock);
12982 
12983 			if (t4_sge_extfree_refs() == 0) {
12984 				EVENTHANDLER_DEREGISTER(vxlan_start,
12985 				    vxlan_start_evtag);
12986 				EVENTHANDLER_DEREGISTER(vxlan_stop,
12987 				    vxlan_stop_evtag);
12988 				t4_tracer_modunload();
12989 #ifdef KERN_TLS
12990 				t6_ktls_modunload();
12991 #endif
12992 #ifdef INET6
12993 				t4_clip_modunload();
12994 #endif
12995 #ifdef TCP_OFFLOAD
12996 				sx_destroy(&t4_uld_list_lock);
12997 #endif
12998 				sx_destroy(&t4_list_lock);
12999 				t4_sge_modunload();
13000 				loaded = 0;
13001 			} else {
13002 				rc = EBUSY;
13003 				loaded++;	/* undo earlier decrement */
13004 			}
13005 		}
13006 done_unload:
13007 		sx_xunlock(&mlu);
13008 		break;
13009 	}
13010 
13011 	return (rc);
13012 }
13013 
13014 static devclass_t t4_devclass, t5_devclass, t6_devclass;
13015 static devclass_t cxgbe_devclass, cxl_devclass, cc_devclass;
13016 static devclass_t vcxgbe_devclass, vcxl_devclass, vcc_devclass;
13017 
13018 DRIVER_MODULE(t4nex, pci, t4_driver, t4_devclass, mod_event, 0);
13019 MODULE_VERSION(t4nex, 1);
13020 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13021 #ifdef DEV_NETMAP
13022 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13023 #endif /* DEV_NETMAP */
13024 
13025 DRIVER_MODULE(t5nex, pci, t5_driver, t5_devclass, mod_event, 0);
13026 MODULE_VERSION(t5nex, 1);
13027 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13028 #ifdef DEV_NETMAP
13029 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13030 #endif /* DEV_NETMAP */
13031 
13032 DRIVER_MODULE(t6nex, pci, t6_driver, t6_devclass, mod_event, 0);
13033 MODULE_VERSION(t6nex, 1);
13034 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13035 #ifdef DEV_NETMAP
13036 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13037 #endif /* DEV_NETMAP */
13038 
13039 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, cxgbe_devclass, 0, 0);
13040 MODULE_VERSION(cxgbe, 1);
13041 
13042 DRIVER_MODULE(cxl, t5nex, cxl_driver, cxl_devclass, 0, 0);
13043 MODULE_VERSION(cxl, 1);
13044 
13045 DRIVER_MODULE(cc, t6nex, cc_driver, cc_devclass, 0, 0);
13046 MODULE_VERSION(cc, 1);
13047 
13048 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, vcxgbe_devclass, 0, 0);
13049 MODULE_VERSION(vcxgbe, 1);
13050 
13051 DRIVER_MODULE(vcxl, cxl, vcxl_driver, vcxl_devclass, 0, 0);
13052 MODULE_VERSION(vcxl, 1);
13053 
13054 DRIVER_MODULE(vcc, cc, vcc_driver, vcc_devclass, 0, 0);
13055 MODULE_VERSION(vcc, 1);
13056